From d4ea2e749b42761839e8b4b0c2fa1c14e17be7f4 Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Wed, 29 Jul 2026 03:48:05 +0200 Subject: [PATCH] fix(orchestrator): harden provider edge cases Co-authored-by: codex --- apps/server/scripts/acp-replay-agent.test.ts | 7 +- .../codexReplayRecordingRecords.test.ts | 35 +++++++ .../scripts/codexReplayRecordingRecords.ts | 9 ++ .../record-codex-app-server-replay-fixture.ts | 96 +------------------ apps/server/src/mcp/OrchestratorMcpService.ts | 2 +- ...OrchestratorMcpToolkit.integration.test.ts | 32 +++++++ .../Adapters/AcpAdapterV2.test.ts | 65 +++++++++++++ .../Adapters/AcpAdapterV2.testkit.ts | 6 +- .../orchestration-v2/Adapters/AcpAdapterV2.ts | 40 +++++--- 9 files changed, 180 insertions(+), 112 deletions(-) create mode 100644 apps/server/scripts/codexReplayRecordingRecords.test.ts create mode 100644 apps/server/scripts/codexReplayRecordingRecords.ts diff --git a/apps/server/scripts/acp-replay-agent.test.ts b/apps/server/scripts/acp-replay-agent.test.ts index c2e14a6b2f..2a662a0ff8 100644 --- a/apps/server/scripts/acp-replay-agent.test.ts +++ b/apps/server/scripts/acp-replay-agent.test.ts @@ -7,6 +7,8 @@ import * as NodeURL from "node:url"; import { expect, it } from "vite-plus/test"; +import { acpReplayAgentArgs } from "../src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts"; + const replayAgentPath = NodeURL.fileURLToPath(new URL("./acp-replay-agent.ts", import.meta.url)); async function runRuntimeExit(status: "success" | "error" | "cancelled") { @@ -16,7 +18,8 @@ async function runRuntimeExit(status: "success" | "error" | "cancelled") { scenario: `${status}-runtime-exit`, entries: [{ type: "runtime_exit", status }], }; - const child = NodeChildProcess.spawn(process.execPath, [replayAgentPath], { + const args = acpReplayAgentArgs(replayAgentPath); + const child = NodeChildProcess.spawn(process.execPath, args, { env: { ...process.env, T3_ACP_REPLAY_STATUS_PATH: statusPath, @@ -42,6 +45,7 @@ async function runRuntimeExit(status: "success" | "error" | "cancelled") { status: JSON.parse(NodeFS.readFileSync(statusPath, "utf8")) as unknown, stderr, transcript, + args, }; } finally { NodeFS.rmSync(scratch, { recursive: true, force: true }); @@ -51,6 +55,7 @@ async function runRuntimeExit(status: "success" | "error" | "cancelled") { it("accepts a recorded cancelled runtime exit", async () => { const result = await runRuntimeExit("cancelled"); expect(result.code, result.stderr).toBe(0); + expect(result.args).toEqual(["--experimental-strip-types", replayAgentPath]); expect(result.status).toEqual({ scenario: result.transcript.scenario, cursor: 1, diff --git a/apps/server/scripts/codexReplayRecordingRecords.test.ts b/apps/server/scripts/codexReplayRecordingRecords.test.ts new file mode 100644 index 0000000000..476781214f --- /dev/null +++ b/apps/server/scripts/codexReplayRecordingRecords.test.ts @@ -0,0 +1,35 @@ +import { assert, it } from "@effect/vitest"; + +import { codexReplayRecordingOutputRecords } from "./codexReplayRecordingRecords.ts"; + +it("preserves monotonic request ids across native Codex forks", () => { + const records = [ + { + type: "expect_outbound", + label: "initialize", + frame: { id: 1, method: "initialize" }, + }, + { + type: "expect_outbound", + label: "thread/fork", + frame: { id: 4, method: "thread/fork" }, + }, + { + type: "expect_outbound", + label: "turn/start", + frame: { id: 5, method: "turn/start" }, + }, + ]; + + const output = codexReplayRecordingOutputRecords(records); + + assert.deepEqual(output, records); + assert.deepEqual( + output.map((record) => record.label), + ["initialize", "thread/fork", "turn/start"], + ); + assert.deepEqual( + output.map((record) => (record.frame as { readonly id: number }).id), + [1, 4, 5], + ); +}); diff --git a/apps/server/scripts/codexReplayRecordingRecords.ts b/apps/server/scripts/codexReplayRecordingRecords.ts new file mode 100644 index 0000000000..4147543719 --- /dev/null +++ b/apps/server/scripts/codexReplayRecordingRecords.ts @@ -0,0 +1,9 @@ +/** + * Codex supports multiple provider threads in one app-server session, so native + * fork recording keeps the request ids emitted by that single client. + */ +export function codexReplayRecordingOutputRecords( + records: ReadonlyArray>, +): ReadonlyArray> { + return [...records]; +} diff --git a/apps/server/scripts/record-codex-app-server-replay-fixture.ts b/apps/server/scripts/record-codex-app-server-replay-fixture.ts index e0f4105ab4..6468e230a8 100644 --- a/apps/server/scripts/record-codex-app-server-replay-fixture.ts +++ b/apps/server/scripts/record-codex-app-server-replay-fixture.ts @@ -51,6 +51,7 @@ import { TURN_INTERRUPT_MID_TOOL_PROMPT, TURN_INTERRUPT_PROMPT, } from "../src/orchestration-v2/testkit/fixtures/shared.ts"; +import { codexReplayRecordingOutputRecords } from "./codexReplayRecordingRecords.ts"; import { makeReplayRecorderDeferredRegistry } from "./replayRecorderDeferredRegistry.ts"; const CODEX_REPLAY_PLAN_MODE_DEVELOPER_INSTRUCTIONS = @@ -859,10 +860,7 @@ function makeRecorder({ records.push(record); }); const flush = () => { - const outputRecords = sessionizeForkReplayRecords({ - scenario: scenario.name, - records, - }); + const outputRecords = codexReplayRecordingOutputRecords(records); return fs.writeFileString( outPath, `${[ @@ -889,96 +887,6 @@ function makeRecorder({ }); } -function sessionizeForkReplayRecords(input: { - readonly scenario: ScenarioName; - readonly records: ReadonlyArray>; -}): ReadonlyArray> { - if ( - input.scenario !== "thread_merge_back_continue" && - input.scenario !== "thread_merge_back_siblings" - ) { - return input.records; - } - const initializeRequest = input.records.find( - (record) => record.type === "expect_outbound" && record.label === "initialize", - ); - const initializeResponse = input.records.find( - (record) => record.type === "emit_inbound" && record.label === "initialize", - ); - const initializedNotification = input.records.find( - (record) => record.type === "expect_outbound" && record.label === "initialized", - ); - if ( - initializeRequest === undefined || - initializeResponse === undefined || - initializedNotification === undefined - ) { - throw new Error(`Scenario ${input.scenario} is missing initialization records.`); - } - - let nextRequestId = 1; - let forkSessionOrdinal = 0; - const requestIdMap = new Map(); - const output: Array> = []; - const appendRequest = (record: Record, id: number) => { - const frame = record.frame as Record; - output.push({ ...record, frame: { ...frame, id } }); - }; - const appendResponse = (record: Record, id: number) => { - const frame = record.frame as Record; - output.push({ ...record, frame: { ...frame, id } }); - }; - - for (const record of input.records) { - const frame = record.frame; - if (record.type === "expect_outbound" && isRecord(frame) && frame.method === "thread/fork") { - forkSessionOrdinal += 1; - const initializeId = nextRequestId++; - appendRequest( - { ...initializeRequest, label: `initialize/fork:${forkSessionOrdinal}` }, - initializeId, - ); - appendResponse( - { ...initializeResponse, label: `initialize/fork:${forkSessionOrdinal}` }, - initializeId, - ); - output.push({ - ...initializedNotification, - label: `initialized/fork:${forkSessionOrdinal}`, - }); - } - - if ( - record.type === "expect_outbound" && - isRecord(frame) && - typeof frame.id === "number" && - typeof frame.method === "string" - ) { - const requestId = nextRequestId++; - requestIdMap.set(frame.id, requestId); - appendRequest(record, requestId); - continue; - } - if ( - record.type === "emit_inbound" && - isRecord(frame) && - typeof frame.id === "number" && - !("method" in frame) - ) { - const responseId = requestIdMap.get(frame.id); - if (responseId === undefined) { - throw new Error( - `Scenario ${input.scenario} has an unmatched response id ${String(frame.id)}.`, - ); - } - appendResponse(record, responseId); - continue; - } - output.push(record); - } - return output; -} - function makeCodexLayer({ recorder }: { readonly recorder: Recorder }) { const clientRequestMethodById = new Map(); const serverRequestMethodById = new Map(); diff --git a/apps/server/src/mcp/OrchestratorMcpService.ts b/apps/server/src/mcp/OrchestratorMcpService.ts index 6f3a6cdd5e..0672d6df6b 100644 --- a/apps/server/src/mcp/OrchestratorMcpService.ts +++ b/apps/server/src/mcp/OrchestratorMcpService.ts @@ -773,7 +773,7 @@ const make = Effect.gen(function* () { ); } const childProjection = yield* loadProjection(task.childThreadId); - const childRun = childProjection.runs[0]; + const childRun = latestRun(childProjection); const status = taskStatusForRun(childRun); const derivedResult = task.result !== null diff --git a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts index 78b4d86edb..fd747e13a9 100644 --- a/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts +++ b/apps/server/src/mcp/OrchestratorMcpToolkit.integration.test.ts @@ -817,6 +817,38 @@ describe("orchestrator MCP toolkit", () => { expect(delegatedStatus.status).toBe("completed"); expect(delegatedStatus.resultContextTransferId).not.toBeNull(); + const childFollowupCall = yield* invoke("t3_thread_send", { + threadId: delegated.childThreadId, + message: "Confirm the delegated API boundary remains inspected.", + clientRequestId: "delegated-child-followup-1", + }); + const childFollowup = yield* decodeThreadSendResult( + childFollowupCall.structuredContent, + ).pipe(Effect.orDie); + const childFollowupWaitCall = yield* invoke("t3_thread_wait", { + threadId: delegated.childThreadId, + runId: childFollowup.runId, + timeoutMs: 10_000, + }); + const childFollowupWait = yield* decodeThreadWaitResult( + childFollowupWaitCall.structuredContent, + ).pipe(Effect.orDie); + expect(childFollowupWait).toMatchObject({ + runId: childFollowup.runId, + status: "completed", + timedOut: false, + }); + const delegatedStatusAfterFollowupCall = yield* invoke("task_status", { + taskId: delegated.taskId, + }); + const delegatedStatusAfterFollowup = yield* decodeDelegateTaskResult( + delegatedStatusAfterFollowupCall.structuredContent, + ).pipe(Effect.orDie); + expect(delegatedStatusAfterFollowup).toMatchObject({ + childRunId: childFollowup.runId, + status: "completed", + }); + // A wait-mode child (completionWake settled_only) that completes // while the parent run is live does not offer a wake: the // blocking delegate_task call above already returned the result. diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 01fe8a089d..e501cc4b22 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -59,6 +59,7 @@ import { } from "../../provider/acp/XAiAcpExtension.ts"; import { layer as idAllocatorLayer, IdAllocatorV2 } from "../IdAllocator.ts"; import { + ProviderAdapterProtocolError, ProviderAdapterV2RuntimePolicy, type ProviderAdapterV2Event, type ProviderAdapterV2TurnInput, @@ -998,6 +999,10 @@ describe("AcpAdapterV2", () => { assert.isTrue(runtime.providerSession.capabilities.threads.canForkThread); assert.isTrue(runtime.providerSession.capabilities.threads.canReadThreadSnapshot); + assert.isTrue(runtime.providerSession.capabilities.sessions.supportsModelSwitchInSession); + assert.isFalse( + runtime.providerSession.capabilities.sessions.supportsRuntimeModeSwitchInSession, + ); const sourceProviderThread = yield* runtime.ensureThread({ threadId: sourceThreadId, @@ -1040,6 +1045,66 @@ describe("AcpAdapterV2", () => { }).pipe(Effect.provide(testLayer), Effect.scoped), ); + it.effect("fails missing native ACP session ids through the typed start-turn error channel", () => + Effect.gen(function* () { + const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const fileSystem = yield* FileSystem.FileSystem; + const idAllocator = yield* IdAllocatorV2; + const path = yield* Path.Path; + const serverConfig = yield* ServerConfig; + const mockAgentPath = yield* path.fromFileUrl( + new URL("../../../scripts/acp-mock-agent.ts", import.meta.url), + ); + const instanceId = ProviderInstanceId.make("acp-test-missing-native-thread"); + const adapter = makeAcpAdapterV2({ + crypto: yield* Crypto.Crypto, + instanceId, + flavor: { + driver: ACP_TEST_DRIVER, + capabilities: AcpProviderCapabilitiesV2, + makeRuntime: makeMockRuntime({ childProcessSpawner, mockAgentPath }), + }, + fileSystem, + idAllocator, + serverConfig, + }); + const threadId = ThreadId.make("thread-acp-missing-native-thread"); + const runtimePolicy = ProviderAdapterV2RuntimePolicy.make({ + runtimeMode: "full-access", + interactionMode: "default", + cwd: process.cwd(), + }); + const modelSelection = { instanceId, model: "default" } as const; + const runtime = yield* adapter.openSession({ + threadId, + providerSessionId: ProviderSessionId.make("provider-session-acp-missing-native-thread"), + modelSelection, + runtimePolicy, + }); + const providerThread = yield* runtime.ensureThread({ + threadId, + modelSelection, + runtimePolicy, + }); + const now = yield* DateTime.now; + const error = yield* runtime + .startTurn( + makeTurnInput({ + threadId, + providerThread: { ...providerThread, nativeThreadRef: null }, + instanceId, + runtimePolicy, + now, + }), + ) + .pipe(Effect.flip); + + assert.equal(error._tag, "ProviderAdapterTurnStartError"); + assert.instanceOf(error.cause, ProviderAdapterProtocolError); + assert.include(String(error.cause), "missing its ACP session id"); + }).pipe(Effect.provide(testLayer), Effect.scoped), + ); + it.effect("closes an idle ACP session exactly once through the transition permit", () => Effect.gen(function* () { const childProcessSpawner = yield* ChildProcessSpawner.ChildProcessSpawner; diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts index 5b3c51f787..1a8971eb24 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts @@ -145,6 +145,10 @@ export function makeAcpReplayCompletenessAssertion( ); } +export function acpReplayAgentArgs(scriptPath: string): ReadonlyArray { + return ["--experimental-strip-types", scriptPath]; +} + export function makeAcpReplayRuntime(input: { readonly transcript: AcpReplayTranscript; readonly statusPath: string; @@ -167,7 +171,7 @@ export function makeAcpReplayRuntime(input: { ...runtimeInput, spawn: { command: process.execPath, - args: [input.scriptPath], + args: acpReplayAgentArgs(input.scriptPath), cwd: runtimeInput.cwd, env: { ...process.env, diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts index 69e983e667..8cccbb332f 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts @@ -474,7 +474,6 @@ function negotiatedCapabilities( const setup = started.sessionSetupResult; const hasModelConfig = setup.configOptions?.some((option) => option.category === "model") === true; - const hasModeConfig = setup.configOptions?.some((option) => option.category === "mode") === true; const supportsMcp = agent.mcpCapabilities?.http === true || agent.mcpCapabilities?.sse === true; const canLoad = agent.loadSession === true; const canFork = session?.fork != null; @@ -483,7 +482,6 @@ function negotiatedCapabilities( sessions: { ...base.sessions, supportsModelSwitchInSession: setup.models != null || hasModelConfig, - supportsRuntimeModeSwitchInSession: setup.modes != null || hasModeConfig, }, threads: { ...base.threads, @@ -523,15 +521,20 @@ function acpMcpServers(threadId: ThreadId | null): ReadonlyArray { const id = thread.nativeThreadRef?.nativeId; if (id === null || id === undefined || id.trim().length === 0) { - throw new ProviderAdapterProtocolError({ - driver, - detail: `Provider thread ${thread.id} is missing its ACP session id`, - }); + return Effect.fail( + new ProviderAdapterProtocolError({ + driver, + detail: `Provider thread ${thread.id} is missing its ACP session id`, + }), + ); } - return id; + return Effect.succeed(id); } function makeProviderThread(input: { @@ -960,6 +963,7 @@ interface ActiveTextStream { interface ActiveAcpTurn { readonly input: ProviderAdapterV2TurnInput; readonly providerTurnId: OrchestrationV2ProviderTurn["id"]; + readonly nativeThreadId: string; readonly nativeTurnId: string; readonly startedAt: DateTime.Utc; readonly completed: Deferred.Deferred; @@ -1990,7 +1994,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV existing?.childThreadId ?? idAllocator.derive.threadFromProviderThread({ driver, - nativeThreadId: `${nativeThreadId(driver, context.input.providerThread)}:task:${nativeTaskId}`, + nativeThreadId: `${context.nativeThreadId}:task:${nativeTaskId}`, }); const childRootNodeId = existing?.childRootNodeId ?? @@ -2478,7 +2482,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV } const status = projectedStatus ?? toolStatus(toolCall.status); const now = yield* DateTime.now; - const nativeItemId = `${nativeThreadId(driver, context.input.providerThread)}:tool:${toolCall.toolCallId}`; + const nativeItemId = `${context.nativeThreadId}:tool:${toolCall.toolCallId}`; const ordinal = yield* resolveItemOrdinal(context, nativeItemId); const nodeId = idAllocator.derive.nodeFromProviderItem({ driver, nativeItemId }); const turnItemId = idAllocator.derive.turnItemFromProviderItem({ @@ -4522,7 +4526,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV detail: `ACP provider turn ${existing.providerTurnId} is still active`, }); } - const requestedSessionId = nativeThreadId(driver, turnInput.providerThread); + const requestedSessionId = yield* nativeThreadId(driver, turnInput.providerThread); const restartAfterInterrupt = yield* restartRuntimeAfterTeardownIfRequired(); const needsSessionActivation = (yield* Ref.get(activeSessionId)) !== requestedSessionId || restartAfterInterrupt; @@ -4603,6 +4607,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV const context: ActiveAcpTurn = { input: turnInput, providerTurnId, + nativeThreadId: requestedSessionId, nativeTurnId, startedAt, completed, @@ -4922,7 +4927,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV Effect.gen(function* () { yield* awaitRuntimeTeardown(); const restartAfterInterrupt = yield* restartRuntimeAfterTeardownIfRequired(); - const sessionId = nativeThreadId(driver, threadInput.providerThread); + const sessionId = yield* nativeThreadId(driver, threadInput.providerThread); if ((yield* Ref.get(activeSessionId)) !== sessionId || restartAfterInterrupt) { yield* Ref.set(snapshot, { order: [], @@ -5327,7 +5332,7 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV Effect.gen(function* () { yield* awaitRuntimeTeardown(); yield* restartRuntimeAfterTeardownIfRequired(); - const sessionId = nativeThreadId(driver, snapshotInput.providerThread); + const sessionId = yield* nativeThreadId(driver, snapshotInput.providerThread); if ((yield* Ref.get(activeSessionId)) !== sessionId) { if (!capabilities.threads.canReadThreadSnapshot) { return yield* new ProviderAdapterProtocolError({ @@ -5405,8 +5410,13 @@ export function makeAcpAdapterV2(options: AcpAdapterV2Options): ProviderAdapterV detail: "ACP session/fork can only fork the current session head", }); } - const sourceSessionId = nativeThreadId(driver, forkInput.sourceProviderThread); - const forked = yield* runtime.forkSession(sourceSessionId); + const sourceSessionId = yield* nativeThreadId( + driver, + forkInput.sourceProviderThread, + ); + const forked = yield* runtime.forkSession(sourceSessionId, { + mcpServers: acpMcpServers(forkInput.targetThreadId), + }); yield* Ref.set(activeSessionId, forked.sessionId); yield* Ref.set(activeSessionSetup, forked); yield* Ref.set(activeSelection, null);