From 8ea9af80531135e586e766cb17b43bcb53f5ae79 Mon Sep 17 00:00:00 2001 From: Bazyli Brzoska Date: Thu, 26 Nov 2026 19:32:36 -0800 Subject: [PATCH 1/5] fix(server): Codex threads stay Working while the agent waits on a background command Codex reports background terminals only as command turn items, and its adapter had no `t3_background_wait` support, so a Codex thread waiting on its tests read as done in the sidebar, attention and auto-settle. Codex now answers `t3_background_wait`: it matches a running root command by its terminal session id (what the agent sees) or item id, and marks the command turn item `awaited`. Pending background work carries that mark, so the command holds the thread like a Claude, Cursor or OpenCode wait. Codex gets a short instruction on when to use the tool. Every background command still wakes Codex, so `completionWake` alone holds nothing, as Vault-Task: Report Codex background commands as awaited in T3's pending background work Co-Authored-By: Claude Opus 5.5 --- .../Adapters/CodexAdapterV2.test.ts | 98 +++++++++++++++++++ .../Adapters/CodexAdapterV2.ts | 74 ++++++++++++-- .../ProviderSessionManager.test.ts | 11 ++- .../provider/CodexDeveloperInstructions.ts | 5 + .../mcp-tool-use/cases/background-wait.ndjson | 2 + packages/contracts/src/orchestrationV2.ts | 4 + ...chestrationV2PendingBackgroundWork.test.ts | 34 +++++++ .../orchestrationV2PendingBackgroundWork.ts | 7 +- 8 files changed, 224 insertions(+), 11 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 58214ab95b380..814c0e667e550 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -8088,6 +8088,104 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect("marks a running command awaited by its session id or item id until it ends", () => + Effect.gen(function* () { + const released = yield* Deferred.make(); + const harness = yield* makeCodexReplayHarness( + { + ...backgroundExecTranscript, + entries: backgroundExecTranscript.entries.map((entry) => + entry.type === "emit_inbound" && entry.label === "item/completed/command-late" + ? { ...entry, afterMs: 0 } + : entry, + ), + }, + undefined, + undefined, + undefined, + (entry) => + entry.label === "item/completed/command-late" ? Deferred.await(released) : Effect.void, + ); + yield* harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-command-background-wait"), + text: BG_PROMPT, + }), + ); + yield* harness.firstTerminal; + const awaitBackgroundTasks = harness.runtime.awaitBackgroundTasks; + if (awaitBackgroundTasks === undefined) { + return yield* Effect.die("Codex adapter runtime must expose awaitBackgroundTasks."); + } + const commands = () => + harness.events.flatMap((event) => + event.type === "turn_item.updated" && event.turnItem.type === "command_execution" + ? [[event.turnItem.status, event.turnItem.awaited]] + : [], + ); + + // Codex shows the agent the terminal's session id; T3 knows the item id. + assert.deepEqual( + yield* awaitBackgroundTasks({ + providerThread: harness.providerThread, + taskIds: ["4242", "9999"], + awaited: true, + }), + { matched: ["4242"] }, + ); + yield* harness.until(() => commands().length === 2); + assert.deepEqual(commands(), [ + ["running", undefined], + ["running", true], + ]); + assert.deepEqual( + yield* awaitBackgroundTasks({ + providerThread: harness.providerThread, + taskIds: [BG_COMMAND_ITEM], + awaited: false, + }), + { matched: [BG_COMMAND_ITEM] }, + ); + yield* awaitBackgroundTasks({ + providerThread: harness.providerThread, + taskIds: [BG_COMMAND_ITEM], + awaited: true, + }); + yield* harness.until(() => commands().length === 4); + + yield* Deferred.succeed(released, undefined); + yield* harness.until(() => commands().some(([status]) => status === "completed")); + assert.deepEqual(commands(), [ + ["running", undefined], + ["running", true], + ["running", undefined], + ["running", true], + ["completed", undefined], + ]); + assert.deepEqual( + yield* awaitBackgroundTasks({ + providerThread: harness.providerThread, + taskIds: ["4242"], + awaited: true, + }), + { matched: [] }, + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + it.effect("settles a command Codex never completed once its terminal is gone", () => Effect.gen(function* () { const settled = yield* Deferred.make(); diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 28c4312b499a6..a7a1ec3ec972b 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -398,6 +398,7 @@ export const CodexProviderCapabilitiesV2 = { emitsToolOutput: true, supportsMcpTools: true, supportsDynamicToolCallbacks: true, + supportsBackgroundWait: true, }, approvals: { supportsCommandApproval: true, @@ -1545,11 +1546,21 @@ function codexRetryTurnItem( }); } +type CodexCommandExecutionItem = Extract< + | CodexSchema.V2ItemStartedNotification__ThreadItem + | CodexSchema.V2ItemCompletedNotification__ThreadItem, + { type: "commandExecution" } +>; + interface TrackedRunningCommandItem { readonly id: string; readonly command: string; readonly aggregatedOutput?: string; readonly processId?: string; + /** The started item, to project the command again when only its wait mark changes. */ + readonly item: CodexCommandExecutionItem; + /** The agent waits on this command (`t3_background_wait`). */ + readonly awaited?: true; } function isPersistentCodexDynamicTool(item: CodexDynamicToolItem): boolean { @@ -4515,16 +4526,13 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( const buildCommandExecutionArtifacts = Effect.fn( "CodexAdapterV2.buildCommandExecutionArtifacts", - )(function* ( - context: ActiveCodexTurnContext, - item: Extract< - | CodexSchema.V2ItemStartedNotification__ThreadItem - | CodexSchema.V2ItemCompletedNotification__ThreadItem, - { type: "commandExecution" } - >, - ) { + )(function* (context: ActiveCodexTurnContext, item: CodexCommandExecutionItem) { const updatedAt = yield* DateTime.now; const status = codexItemStatus(item.status); + const awaited = + !status.completed && + (yield* Ref.get(runningCommandItemsByTurn)).get(context.nativeTurnId)?.get(item.id) + ?.awaited === true; const completedAt = status.completed ? updatedAt : null; const nodeId = idAllocator.derive.nodeFromProviderItem({ driver: CODEX_PROVIDER, @@ -4585,6 +4593,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ...(context.subagent === null && continuationRequests !== undefined ? { completionWake: "always" as const } : {}), + ...(awaited ? { awaited: true as const } : {}), }; return { node, turnItem }; }); @@ -5999,6 +6008,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( yield* trackRunningCommandItem(payload.turnId, { id: payload.item.id, command: payload.item.command, + item: payload.item, ...(payload.item.aggregatedOutput === null || payload.item.aggregatedOutput === undefined ? {} @@ -8660,6 +8670,54 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( } return false; }), + awaitBackgroundTasks: Effect.fn("CodexAdapterV2.awaitBackgroundTasks")( + function* ({ providerThread, taskIds, awaited }) { + const contexts = new Map([ + ...(yield* Ref.get(settledTurns)), + ...(yield* Ref.get(activeTurns)), + ]); + const matched = new Set(); + const marked: Array<{ + readonly context: ActiveCodexTurnContext; + readonly item: CodexCommandExecutionItem; + }> = []; + yield* Ref.update(runningCommandItemsByTurn, (current) => { + const updated = new Map(current); + for (const [nativeTurnId, items] of current) { + const context = contexts.get(nativeTurnId); + // Only a root command wakes the agent when it ends. + if (context?.providerThread.id !== providerThread.id || context.subagent !== null) + continue; + for (const tracked of items.values()) { + // Codex shows the agent a terminal's session id, which is its processId. + const named = taskIds.filter( + (taskId) => taskId === tracked.id || taskId === tracked.processId, + ); + if (named.length === 0) continue; + for (const taskId of named) matched.add(taskId); + if ((tracked.awaited === true) === awaited) continue; + const { awaited: _previous, ...rest } = tracked; + const nextItems = new Map(updated.get(nativeTurnId)); + nextItems.set(tracked.id, awaited ? { ...rest, awaited: true } : rest); + updated.set(nativeTurnId, nextItems); + marked.push({ context, item: tracked.item }); + } + } + return updated; + }); + for (const { context, item } of marked) { + const artifacts = yield* buildCommandExecutionArtifacts(context, item); + yield* emitProviderEvent({ + type: "turn_item.updated", + driver: CODEX_PROVIDER, + turnItem: artifacts.turnItem, + }); + } + return { matched: [...matched] }; + }, + // Item events hold this permit, so a mark never projects a command after its result. + turnTerminalizationPermit.withPermits(1), + ), ensureThread: (threadInput) => rejectIfRetired.pipe( Effect.andThen(ensureInitialized), diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index b447e171a675b..156c21d015dc7 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -2772,7 +2772,14 @@ it.effect( assert.equal(resolved?.thread.threadId, threadId); assert.deepEqual( resolved?.capabilities, - new Set(["preview", "orchestration", "worktree", "pull-requests", "issues"]), + new Set([ + "preview", + "orchestration", + "worktree", + "pull-requests", + "issues", + "background-wait", + ]), ); assert.isFalse(yield* captured!.hasPendingWake!); @@ -2884,7 +2891,7 @@ it.effect( const resolved = yield* registry.resolve(token!); assert.deepEqual( resolved?.capabilities, - new Set(["orchestration", "worktree", "pull-requests", "issues"]), + new Set(["orchestration", "worktree", "pull-requests", "issues", "background-wait"]), ); yield* manager.close(providerSessionId); diff --git a/apps/server/src/provider/CodexDeveloperInstructions.ts b/apps/server/src/provider/CodexDeveloperInstructions.ts index 12b35b3c0aaf8..3babc92588308 100644 --- a/apps/server/src/provider/CodexDeveloperInstructions.ts +++ b/apps/server/src/provider/CodexDeveloperInstructions.ts @@ -31,6 +31,10 @@ const toolInstructions = (tools: T3CodeToolAvailability): string => .filter(Boolean) .join("\n\n"); +// Codex wakes the agent when any background command ends, so T3 can't tell a wait from a dev server. +const CODEX_BACKGROUND_WAIT_INSTRUCTIONS = + "To wait for a background command you started (tests, a build), pass its session ID to `t3_background_wait` before you end your turn. Do not mark work you leave running, or PRs."; + export interface CodexRuntimeInfo { readonly agentFeedback?: AgentFeedbackMode; readonly model: string; @@ -58,5 +62,6 @@ export function buildCodexAdditionalContext( value: buildRuntimeInstructions({ harness: "Codex", ...runtime }), }, ...(tools ? { t3_code_tools: { kind: "application", value: tools } } : {}), + t3_code_background_wait: { kind: "application", value: CODEX_BACKGROUND_WAIT_INSTRUCTIONS }, }; } diff --git a/evals/mcp-tool-use/cases/background-wait.ndjson b/evals/mcp-tool-use/cases/background-wait.ndjson index f6fcebc9325bb..8b21e00f896b6 100644 --- a/evals/mcp-tool-use/cases/background-wait.ndjson +++ b/evals/mcp-tool-use/cases/background-wait.ndjson @@ -1,2 +1,4 @@ {"id":"background-wait-opencode-tests","area":"background-wait","kind":"bad","pattern":"OpenCode awaits a background validation result -> mark only that shell awaited","experience":"OpenCode background shells outlived successful turns without a supported explicit wait marker, so T3 presented validation as finished.","privacy":"commit-safe","setup":{"role":"top","context":"You are running through the OpenCode provider in T3. Two native background shells have already launched: sh_tests runs the requested validation; sh_dev serves the development app and should stay running after the work is done. Their completion notifications will wake you automatically. There is no other work to do until validation ends.","mocks":{"t3_background_wait":{"matched":["sh_tests"],"unmatched":[]}}},"prompt":"Wait for the validation shell sh_tests, then inspect its result when it finishes. Leave sh_dev running. Do not poll or stop either shell.","expect":{"calls":[{"tool":"t3_background_wait","args":{"taskIds":["sh_tests"]}}],"callsMustNot":[{"tool":"t3_background_wait","args":{"taskIds":["sh_dev"]}},{"tool":"t3_background_wait","args":{"waiting":false}}]},"maxSteps":5,"source":{"issue":"https://github.com/pingdotgg/t3code/issues/35214"},"notes":"API replay exercises the provider-neutral tool description with OpenCode context, not an OpenCode harness capture or the adapter's injected instructions."} {"id":"background-wait-opencode-dev-server","area":"background-wait","kind":"guard","pattern":"intentionally detached OpenCode dev server -> no wait mark","experience":"The old customization kept finished threads in Working merely because their dev servers were still running.","privacy":"commit-safe","setup":{"role":"top","context":"You are running through the OpenCode provider in T3. Validation passed. The only background work is sh_dev, the development server, which is ready at http://localhost:3000. No further agent work depends on its exit."},"prompt":"We're done. Leave the dev server running and give me a short summary. Don't inspect the browser.","expect":{"callsMustNot":[{"tool":"t3_background_wait"}]},"maxSteps":3,"source":{"decision":"https://github.com/pingdotgg/t3code/pull/24610"}} +{"id":"background-wait-codex-tests","area":"background-wait","kind":"bad","pattern":"Codex leaves a test run in a background terminal and ends its turn -> mark only that session awaited","experience":"Codex background terminals never held a thread: T3 listed a Codex thread waiting on its tests as done, and the sidebar and attention showed nothing to wait for until the wake arrived.","privacy":"commit-safe","setup":{"role":"top","harness":"codex","context":"Earlier in this turn you started two commands with exec_command and they are still running in background terminals: session 41 runs `vp test run`, the full suite the user asked for, which takes about 15 minutes; session 42 runs `vp run dev`, the development server, ready at http://localhost:3000, which should stay running afterwards. When a background command exits, T3 starts a new turn for you with its result.","world":{"backgroundTasks":["41","42"],"tests":"The suite started a minute ago. 38 test files have passed and none have failed yet."}},"prompt":"I'm heading out for a bit. Tell me what failed when the tests are done.","expect":{"calls":[{"tool":"t3_background_wait","args":{"taskIds":["41"]}}],"callsMustNot":[{"tool":"t3_background_wait","args":{"taskIds":["42"]}},{"tool":"t3_background_wait","args":{"waiting":false}}]},"maxSteps":6,"source":{"decision":"https://github.com/pingdotgg/t3code/pull/24610"},"notes":"T3 answers the wait from its own handler over sessions 41 and 42. The context stands in for the exec_command calls, as the OpenCode cases do."} +{"id":"background-wait-codex-dev-server","area":"background-wait","kind":"guard","pattern":"Codex leaves a dev server running on purpose -> no wait mark","experience":"Before #24610, finished threads stayed in Working only because their dev servers were still running.","privacy":"commit-safe","setup":{"role":"top","harness":"codex","context":"Validation passed. The only command still running is in background terminal session 42: `vp run dev`, the development server, ready at http://localhost:3000. Nothing else depends on it exiting.","world":{"backgroundTasks":["42"]}},"prompt":"We're done. Leave the dev server running and give me a short summary. Don't inspect the browser.","expect":{"callsMustNot":[{"tool":"t3_background_wait"}]},"maxSteps":3,"source":{"decision":"https://github.com/pingdotgg/t3code/pull/24610"}} diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 04ea9df12bbd2..796120b612910 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -2010,6 +2010,8 @@ export const OrchestrationV2TurnItem = Schema.Union([ monitor: Schema.optional(Schema.Boolean), /** The provider wakes the agent when this command finishes after its turn. */ completionWake: Schema.optional(Schema.Literal("always")), + /** The agent marked this running command as work it waits on, so it holds the thread. */ + awaited: Schema.optional(Schema.Literal(true)), }), Schema.Struct({ ...OrchestrationV2TurnItemBaseFields, @@ -2920,6 +2922,8 @@ export const OrchestrationV2TurnItemJson = Schema.Union([ monitor: Schema.optional(Schema.Boolean), /** The provider wakes the agent when this command finishes after its turn. */ completionWake: Schema.optional(Schema.Literal("always")), + /** The agent marked this running command as work it waits on, so it holds the thread. */ + awaited: Schema.optional(Schema.Literal(true)), }), Schema.Struct({ ...OrchestrationV2TurnItemJsonBaseFields, diff --git a/packages/shared/src/orchestrationV2PendingBackgroundWork.test.ts b/packages/shared/src/orchestrationV2PendingBackgroundWork.test.ts index 5b8f67e1fae1a..88ef5e471a77b 100644 --- a/packages/shared/src/orchestrationV2PendingBackgroundWork.test.ts +++ b/packages/shared/src/orchestrationV2PendingBackgroundWork.test.ts @@ -387,6 +387,40 @@ describe("derivePendingBackgroundWork kinds", () => { ]); }); + it("holds only for a background command item the agent marked awaited", () => { + const tasks = derivePendingBackgroundWork({ + latestRun: { id: "run-1" as never, ordinal: 1, status: "completed" }, + providerThreads: [], + turnItems: [ + { + id: "item-tests" as never, + type: "command_execution", + status: "running", + title: null, + nativeItemRef: { nativeId: "tests" }, + input: "npm test", + awaited: true, + }, + { + id: "item-dev" as never, + type: "command_execution", + status: "running", + title: null, + nativeItemRef: { nativeId: "dev" }, + input: "npm run dev", + }, + ], + }); + expect(tasks).toEqual([ + { taskId: "tests", description: "npm test", kind: "command", awaited: true }, + { taskId: "dev", description: "npm run dev", kind: "command" }, + ]); + expect(backgroundWorkHoldsCompletion(tasks)).toBe(true); + expect(backgroundWorkHoldsCompletion(tasks.filter((task) => task.taskId === "dev"))).toBe( + false, + ); + }); + describe("pull request watches", () => { const watch = { startedAt: "2026-10-05T00:00:00.000Z", diff --git a/packages/shared/src/orchestrationV2PendingBackgroundWork.ts b/packages/shared/src/orchestrationV2PendingBackgroundWork.ts index cc8513fb64e60..dfd39e0f7ede5 100644 --- a/packages/shared/src/orchestrationV2PendingBackgroundWork.ts +++ b/packages/shared/src/orchestrationV2PendingBackgroundWork.ts @@ -167,6 +167,7 @@ type PendingBackgroundWorkTurnItem = { } | null; readonly input?: unknown; readonly monitor?: boolean | undefined; + readonly awaited?: true | undefined; readonly prompt?: string | undefined; readonly childThreadId?: ThreadId | null; }; @@ -225,7 +226,11 @@ function pendingTaskFromTurnItem( ...(item.childThreadId == null ? {} : { childThreadId: item.childThreadId }), }; case "command_execution": - return { ...named, kind: item.monitor === true ? "monitor" : "command" }; + return { + ...named, + kind: item.monitor === true ? "monitor" : "command", + ...(item.awaited === true ? { awaited: true as const } : {}), + }; default: return { ...named, kind: "background_task" }; } From 5257c33a50f4cf9b1b736030690bff6979ffcc1b Mon Sep 17 00:00:00 2001 From: Bazyli Brzoska Date: Thu, 26 Nov 2026 23:20:11 -0800 Subject: [PATCH 2/5] fix(server): Codex lists awaited commands on its roster and resolves approved session ids A command that waited on approval starts with no processId, so a mark by its session id never matched. The adapter now asks Codex's background terminal list, which maps each session id to its item, for ids it has not seen. An awaited command marked only on its turn item stayed invisible to delegated-task completion, which reads the provider thread's roster. Awaited commands now go on that roster, as Cursor and OpenCode list theirs, and leave it when the command ends, stops or settles. The turn-item awaited field is gone. Vault-Task: Report Codex background commands as awaited in T3's pending background work Co-Authored-By: Claude Opus 5.5 --- .../Adapters/CodexAdapterV2.test.ts | 245 ++++++++++++++---- .../Adapters/CodexAdapterV2.ts | 240 ++++++++++++----- packages/contracts/src/orchestrationV2.ts | 4 - ...chestrationV2PendingBackgroundWork.test.ts | 12 +- .../orchestrationV2PendingBackgroundWork.ts | 7 +- 5 files changed, 373 insertions(+), 135 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 814c0e667e550..fc6a56bff6d21 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -8088,18 +8088,188 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); - it.effect("marks a running command awaited by its session id or item id until it ends", () => + const awaitedRosters = ( + events: ReadonlyArray, + providerThreadId: OrchestrationV2ProviderThread["id"], + ) => + events.flatMap((event) => + event.type === "provider_thread.updated" && + event.providerThread.id === providerThreadId && + event.providerThread.pendingBackgroundTasks !== undefined + ? [event.providerThread.pendingBackgroundTasks.map((task) => task.taskId)] + : [], + ); + + it.effect( + "lists a command the agent marks awaited, by session id or item id, until it ends", + () => + Effect.gen(function* () { + const released = yield* Deferred.make(); + const harness = yield* makeCodexReplayHarness( + { + ...backgroundExecTranscript, + entries: backgroundExecTranscript.entries.map((entry) => + entry.type === "emit_inbound" && entry.label === "item/completed/command-late" + ? { ...entry, afterMs: 0 } + : entry, + ), + }, + undefined, + undefined, + undefined, + (entry) => + entry.label === "item/completed/command-late" ? Deferred.await(released) : Effect.void, + ); + const turnInput = makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now: yield* DateTime.now, + attemptId: RunAttemptId.make("attempt-command-background-wait"), + text: BG_PROMPT, + }); + yield* harness.runtime.startTurn(turnInput); + yield* harness.firstTerminal; + const awaitBackgroundTasks = harness.runtime.awaitBackgroundTasks; + if (awaitBackgroundTasks === undefined) { + return yield* Effect.die("Codex adapter runtime must expose awaitBackgroundTasks."); + } + const rosters = () => awaitedRosters(harness.events, harness.providerThread.id); + + // Codex shows the agent the terminal's session id; T3 knows the item id. + assert.deepEqual( + yield* awaitBackgroundTasks({ + providerThread: harness.providerThread, + taskIds: ["4242", "9999"], + awaited: true, + }), + { matched: ["4242"] }, + ); + yield* harness.until(() => rosters().length === 1); + const listed = harness.events.findLast((event) => event.type === "provider_thread.updated"); + assert.deepEqual( + listed?.type === "provider_thread.updated" + ? listed.providerThread.pendingBackgroundTasks + : undefined, + [ + { + taskId: BG_COMMAND_ITEM, + kind: "command", + command: BG_COMMAND, + description: BG_COMMAND, + runId: turnInput.runId, + awaited: true, + }, + ], + ); + assert.deepEqual( + yield* awaitBackgroundTasks({ + providerThread: harness.providerThread, + taskIds: [BG_COMMAND_ITEM], + awaited: false, + }), + { matched: [BG_COMMAND_ITEM] }, + ); + yield* awaitBackgroundTasks({ + providerThread: harness.providerThread, + taskIds: [BG_COMMAND_ITEM], + awaited: true, + }); + yield* harness.until(() => rosters().length === 3); + + yield* Deferred.succeed(released, undefined); + yield* harness.until(() => rosters().length === 4); + assert.deepEqual(rosters(), [[BG_COMMAND_ITEM], [], [BG_COMMAND_ITEM], []]); + assert.deepEqual( + yield* awaitBackgroundTasks({ + providerThread: harness.providerThread, + taskIds: ["4242"], + awaited: true, + }), + { matched: [] }, + ); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + + // A command that waited on approval starts without a process id; Codex sends it on completion. + it.effect("resolves the session id of an approved command Codex started without one", () => Effect.gen(function* () { const released = yield* Deferred.make(); - const harness = yield* makeCodexReplayHarness( + const [started, answer, turnCompleted, late] = backgroundExecTranscript.entries.slice(-4); + const liveTerminal = (id: number) => [ { - ...backgroundExecTranscript, - entries: backgroundExecTranscript.entries.map((entry) => - entry.type === "emit_inbound" && entry.label === "item/completed/command-late" - ? { ...entry, afterMs: 0 } - : entry, - ), + type: "expect_outbound" as const, + label: `list-background-terminals-${id}`, + frame: { + id, + method: "thread/backgroundTerminals/list", + params: { threadId: BG_NATIVE_THREAD }, + }, }, + { + type: "emit_inbound" as const, + label: `list-background-terminals-${id}`, + frame: { + id, + result: { + data: [ + { + processId: "4242", + itemId: BG_COMMAND_ITEM, + command: BG_COMMAND, + cwd: "/workspace", + }, + ], + nextCursor: null, + }, + }, + }, + ]; + if ( + started?.type !== "emit_inbound" || + late?.type !== "emit_inbound" || + answer === undefined || + turnCompleted === undefined + ) { + return yield* Effect.die("The background exec transcript changed shape."); + } + const harness = yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ + scenario: "codex-bg-approved-command", + entries: [ + ...backgroundExecTranscript.entries.slice(0, -4), + { + ...started, + frame: { + method: "item/started", + params: { + item: { + ...backgroundCommandItem("inProgress"), + processId: null, + source: "agent", + }, + threadId: BG_NATIVE_THREAD, + turnId: BG_NATIVE_TURN, + startedAtMs: 1782622440500, + }, + }, + }, + ...liveTerminal(4), + answer, + turnCompleted, + ...liveTerminal(5), + { ...late, afterMs: 0 }, + ], + }), undefined, undefined, undefined, @@ -8111,68 +8281,33 @@ describe("CodexAdapterV2 post-settle continuation", () => { threadId: harness.threadId, providerThread: harness.providerThread, now: yield* DateTime.now, - attemptId: RunAttemptId.make("attempt-command-background-wait"), + attemptId: RunAttemptId.make("attempt-approved-command-wait"), text: BG_PROMPT, }), ); - yield* harness.firstTerminal; + yield* harness.until(() => + harness.events.some( + (event) => + event.type === "turn_item.updated" && event.turnItem.type === "command_execution", + ), + ); const awaitBackgroundTasks = harness.runtime.awaitBackgroundTasks; if (awaitBackgroundTasks === undefined) { return yield* Effect.die("Codex adapter runtime must expose awaitBackgroundTasks."); } - const commands = () => - harness.events.flatMap((event) => - event.type === "turn_item.updated" && event.turnItem.type === "command_execution" - ? [[event.turnItem.status, event.turnItem.awaited]] - : [], - ); - - // Codex shows the agent the terminal's session id; T3 knows the item id. assert.deepEqual( yield* awaitBackgroundTasks({ providerThread: harness.providerThread, - taskIds: ["4242", "9999"], + taskIds: ["4242"], awaited: true, }), { matched: ["4242"] }, ); - yield* harness.until(() => commands().length === 2); - assert.deepEqual(commands(), [ - ["running", undefined], - ["running", true], - ]); - assert.deepEqual( - yield* awaitBackgroundTasks({ - providerThread: harness.providerThread, - taskIds: [BG_COMMAND_ITEM], - awaited: false, - }), - { matched: [BG_COMMAND_ITEM] }, - ); - yield* awaitBackgroundTasks({ - providerThread: harness.providerThread, - taskIds: [BG_COMMAND_ITEM], - awaited: true, - }); - yield* harness.until(() => commands().length === 4); - + yield* harness.firstTerminal; yield* Deferred.succeed(released, undefined); - yield* harness.until(() => commands().some(([status]) => status === "completed")); - assert.deepEqual(commands(), [ - ["running", undefined], - ["running", true], - ["running", undefined], - ["running", true], - ["completed", undefined], - ]); - assert.deepEqual( - yield* awaitBackgroundTasks({ - providerThread: harness.providerThread, - taskIds: ["4242"], - awaited: true, - }), - { matched: [] }, - ); + const rosters = () => awaitedRosters(harness.events, harness.providerThread.id); + yield* harness.until(() => rosters().length === 2); + assert.deepEqual(rosters(), [[BG_COMMAND_ITEM], []]); }).pipe( Effect.scoped, Effect.provide( diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index a7a1ec3ec972b..a8ea3be52394d 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -75,6 +75,7 @@ import type { OrchestrationV2ConversationMessage, OrchestrationV2ExecutionNode, ModelSelection, + OrchestrationV2PendingBackgroundTask, OrchestrationV2PlanArtifact, OrchestrationV2ProviderCapabilities, OrchestrationV2ProviderFailure, @@ -331,6 +332,7 @@ const CodexBackgroundTerminalsListResponse = Schema.Struct({ data: Schema.Array( Schema.Struct({ processId: Schema.String, + itemId: Schema.optionalKey(Schema.String), }), ), nextCursor: Schema.NullOr(Schema.String), @@ -1546,19 +1548,11 @@ function codexRetryTurnItem( }); } -type CodexCommandExecutionItem = Extract< - | CodexSchema.V2ItemStartedNotification__ThreadItem - | CodexSchema.V2ItemCompletedNotification__ThreadItem, - { type: "commandExecution" } ->; - interface TrackedRunningCommandItem { readonly id: string; readonly command: string; readonly aggregatedOutput?: string; readonly processId?: string; - /** The started item, to project the command again when only its wait mark changes. */ - readonly item: CodexCommandExecutionItem; /** The agent waits on this command (`t3_background_wait`). */ readonly awaited?: true; } @@ -3017,6 +3011,66 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( return updated; }); + /** + * Commands the agent waits on go on their root provider thread's roster, as other + * adapters list awaited work, so delegated tasks, Settle and restart recovery see them. + */ + const publishAwaitedCommandRosters = Effect.fnUntraced(function* () { + const contexts = new Map([ + ...(yield* Ref.get(settledTurns)), + ...(yield* Ref.get(activeTurns)), + ]); + const rosters = new Map>(); + for (const [nativeTurnId, items] of yield* Ref.get(runningCommandItemsByTurn)) { + const context = contexts.get(nativeTurnId); + const nativeThreadId = context?.providerThread.nativeThreadRef?.nativeId; + if (context === undefined || context.subagent !== null || nativeThreadId == null) + continue; + for (const tracked of items.values()) { + if (tracked.awaited !== true) continue; + const description = tracked.command.trim(); + rosters.set(nativeThreadId, [ + ...(rosters.get(nativeThreadId) ?? []), + { + taskId: tracked.id, + kind: "command", + command: tracked.command, + ...(description.length === 0 ? {} : { description }), + ...(context.projectionRunId === null ? {} : { runId: context.projectionRunId }), + awaited: true, + }, + ]); + } + } + const activeNativeThreadIds = new Set( + [...(yield* Ref.get(activeTurns)).values()].flatMap((context) => + context.subagent === null ? [context.providerThread.nativeThreadRef?.nativeId] : [], + ), + ); + for (const [nativeThreadId, providerThread] of rootProviderThreads) { + const tasks = rosters.get(nativeThreadId) ?? []; + const previous = providerThread.pendingBackgroundTasks ?? []; + if ( + previous.length === tasks.length && + previous.every((task, index) => task.taskId === tasks[index]?.taskId) + ) + continue; + const updated = { + ...providerThread, + pendingBackgroundTasks: tasks, + updatedAt: yield* DateTime.now, + }; + rootProviderThreads.set(nativeThreadId, updated); + yield* emitProviderEvent({ + type: "provider_thread.updated", + driver: CODEX_PROVIDER, + providerThread: updated, + // No run reads this stream between turns, so the session stores the roster itself. + ...(activeNativeThreadIds.has(nativeThreadId) ? {} : { sessionScoped: true }), + }); + } + }); + const clearRunningCommandItem = (nativeTurnId: string, nativeItemId: string) => Ref.modify(runningCommandItemsByTurn, (current) => { const items = current.get(nativeTurnId); @@ -3032,7 +3086,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( updated.set(nativeTurnId, remaining); } return [remaining.size === 0, updated] as const; - }); + }).pipe(Effect.tap(publishAwaitedCommandRosters)); interface PendingMcpAppCapture { readonly item: Extract; @@ -3273,14 +3327,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( Effect.timeout("10 seconds"), ); - /** - * Codex can end a turn without item/completed for a command whose shell already - * exited (openai/codex#53488). Only a live background terminal keeps a command - * running past its turn; the rest settle as cancelled since their result is unknown. - */ - const settleExitedCommandItems = Effect.fn("CodexAdapterV2.settleExitedCommandItems")( - function* (nativeThreadId: string, nativeTurnId: string) { - const liveProcessIds = new Set(); + const listBackgroundTerminals = Effect.fn("CodexAdapterV2.listBackgroundTerminals")( + function* (nativeThreadId: string) { + const terminals: Array = []; let cursor: string | null = null; while (true) { const response: unknown = yield* client.raw.request( @@ -3292,10 +3341,25 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ); const page: CodexBackgroundTerminalsListPage = yield* decodeCodexBackgroundTerminalsListResponse(response); - for (const terminal of page.data) liveProcessIds.add(terminal.processId); - if (page.nextCursor === null) break; + terminals.push(...page.data); + if (page.nextCursor === null) return terminals; cursor = page.nextCursor; } + }, + ); + + /** + * Codex can end a turn without item/completed for a command whose shell already + * exited (openai/codex#53488). Only a live background terminal keeps a command + * running past its turn; the rest settle as cancelled since their result is unknown. + */ + const settleExitedCommandItems = Effect.fn("CodexAdapterV2.settleExitedCommandItems")( + function* (nativeThreadId: string, nativeTurnId: string) { + const liveProcessIds = new Set( + (yield* listBackgroundTerminals(nativeThreadId)).map( + (terminal) => terminal.processId, + ), + ); yield* turnTerminalizationPermit.withPermits(1)( Effect.gen(function* () { const context = (yield* Ref.get(settledTurns)).get(nativeTurnId); @@ -4526,13 +4590,16 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( const buildCommandExecutionArtifacts = Effect.fn( "CodexAdapterV2.buildCommandExecutionArtifacts", - )(function* (context: ActiveCodexTurnContext, item: CodexCommandExecutionItem) { + )(function* ( + context: ActiveCodexTurnContext, + item: Extract< + | CodexSchema.V2ItemStartedNotification__ThreadItem + | CodexSchema.V2ItemCompletedNotification__ThreadItem, + { type: "commandExecution" } + >, + ) { const updatedAt = yield* DateTime.now; const status = codexItemStatus(item.status); - const awaited = - !status.completed && - (yield* Ref.get(runningCommandItemsByTurn)).get(context.nativeTurnId)?.get(item.id) - ?.awaited === true; const completedAt = status.completed ? updatedAt : null; const nodeId = idAllocator.derive.nodeFromProviderItem({ driver: CODEX_PROVIDER, @@ -4593,7 +4660,6 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ...(context.subagent === null && continuationRequests !== undefined ? { completionWake: "always" as const } : {}), - ...(awaited ? { awaited: true as const } : {}), }; return { node, turnItem }; }); @@ -5902,6 +5968,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( updated.delete(context.nativeTurnId); return updated; }); + yield* publishAwaitedCommandRosters(); yield* releaseSettledTurnIfIdle(context.nativeTurnId); } }).pipe(Effect.orDie, turnTerminalizationPermit.withPermits(1)), @@ -6008,7 +6075,6 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( yield* trackRunningCommandItem(payload.turnId, { id: payload.item.id, command: payload.item.command, - item: payload.item, ...(payload.item.aggregatedOutput === null || payload.item.aggregatedOutput === undefined ? {} @@ -7732,6 +7798,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( updated.delete(input.nativeTurnId); return updated; }); + yield* publishAwaitedCommandRosters(); yield* Ref.update(runningDynamicToolsByTurn, (current) => { if (!current.has(input.nativeTurnId)) { return current; @@ -8670,54 +8737,91 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( } return false; }), - awaitBackgroundTasks: Effect.fn("CodexAdapterV2.awaitBackgroundTasks")( - function* ({ providerThread, taskIds, awaited }) { + awaitBackgroundTasks: Effect.fn("CodexAdapterV2.awaitBackgroundTasks")(function* ({ + providerThread, + taskIds, + awaited, + }) { + // Only a root command wakes the agent when it ends. + const rootCommandTurnIds = Effect.gen(function* () { const contexts = new Map([ ...(yield* Ref.get(settledTurns)), ...(yield* Ref.get(activeTurns)), ]); - const matched = new Set(); - const marked: Array<{ - readonly context: ActiveCodexTurnContext; - readonly item: CodexCommandExecutionItem; - }> = []; - yield* Ref.update(runningCommandItemsByTurn, (current) => { - const updated = new Map(current); - for (const [nativeTurnId, items] of current) { + return new Set( + [...(yield* Ref.get(runningCommandItemsByTurn)).keys()].filter((nativeTurnId) => { const context = contexts.get(nativeTurnId); - // Only a root command wakes the agent when it ends. - if (context?.providerThread.id !== providerThread.id || context.subagent !== null) - continue; - for (const tracked of items.values()) { - // Codex shows the agent a terminal's session id, which is its processId. - const named = taskIds.filter( - (taskId) => taskId === tracked.id || taskId === tracked.processId, - ); - if (named.length === 0) continue; - for (const taskId of named) matched.add(taskId); - if ((tracked.awaited === true) === awaited) continue; - const { awaited: _previous, ...rest } = tracked; - const nextItems = new Map(updated.get(nativeTurnId)); - nextItems.set(tracked.id, awaited ? { ...rest, awaited: true } : rest); - updated.set(nativeTurnId, nextItems); - marked.push({ context, item: tracked.item }); - } + return ( + context?.providerThread.id === providerThread.id && context.subagent === null + ); + }), + ); + }); + // Codex shows the agent a terminal's session id, its processId. A command that waited + // on approval starts without one, so Codex's terminal list maps unseen ids to items. + const turnIds = yield* rootCommandTurnIds; + const running = yield* Ref.get(runningCommandItemsByTurn); + const commands = [...turnIds].flatMap((id) => [...(running.get(id)?.values() ?? [])]); + const unseen = taskIds.filter( + (taskId) => + !commands.some((tracked) => taskId === tracked.id || taskId === tracked.processId), + ); + const nativeThreadId = providerThread.nativeThreadRef?.nativeId; + const learnedProcessIds = new Map(); + if ( + unseen.length > 0 && + nativeThreadId != null && + commands.some((tracked) => tracked.processId === undefined) + ) { + const terminals = yield* listBackgroundTerminals(nativeThreadId).pipe( + Effect.mapError( + (cause) => + new ProviderAdapter.ProviderAdapterProtocolError({ + driver: CODEX_PROVIDER, + detail: "Could not list Codex background terminals.", + cause, + }), + ), + ); + for (const terminal of terminals) { + if (terminal.itemId !== undefined && unseen.includes(terminal.processId)) { + learnedProcessIds.set(terminal.itemId, terminal.processId); } - return updated; - }); - for (const { context, item } of marked) { - const artifacts = yield* buildCommandExecutionArtifacts(context, item); - yield* emitProviderEvent({ - type: "turn_item.updated", - driver: CODEX_PROVIDER, - turnItem: artifacts.turnItem, - }); } - return { matched: [...matched] }; - }, - // Item events hold this permit, so a mark never projects a command after its result. - turnTerminalizationPermit.withPermits(1), - ), + } + // Item events hold this permit, so a mark never lists a command after its result. + return yield* turnTerminalizationPermit.withPermits(1)( + Effect.gen(function* () { + const eligible = yield* rootCommandTurnIds; + const matched = new Set(); + yield* Ref.update(runningCommandItemsByTurn, (current) => { + const updated = new Map(current); + for (const nativeTurnId of eligible) { + for (const tracked of current.get(nativeTurnId)?.values() ?? []) { + const processId = tracked.processId ?? learnedProcessIds.get(tracked.id); + const named = taskIds.filter( + (taskId) => taskId === tracked.id || taskId === processId, + ); + if (named.length === 0) continue; + for (const taskId of named) matched.add(taskId); + const { awaited: _previous, ...rest } = tracked; + updated.set( + nativeTurnId, + new Map(updated.get(nativeTurnId)).set(tracked.id, { + ...rest, + ...(processId === undefined ? {} : { processId }), + ...(awaited ? { awaited: true as const } : {}), + }), + ); + } + } + return updated; + }); + yield* publishAwaitedCommandRosters(); + return { matched: [...matched] }; + }), + ); + }), ensureThread: (threadInput) => rejectIfRetired.pipe( Effect.andThen(ensureInitialized), @@ -9202,6 +9306,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( } return updated; }); + yield* publishAwaitedCommandRosters(); }); const finalizeRemainingInterruptLineage = Effect.gen(function* () { @@ -9390,6 +9495,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( updated.delete(context.nativeTurnId); return updated; }); + yield* publishAwaitedCommandRosters(); yield* clearImageWork(context); yield* releaseSettledTurnIfIdle(context.nativeTurnId); } diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 796120b612910..04ea9df12bbd2 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -2010,8 +2010,6 @@ export const OrchestrationV2TurnItem = Schema.Union([ monitor: Schema.optional(Schema.Boolean), /** The provider wakes the agent when this command finishes after its turn. */ completionWake: Schema.optional(Schema.Literal("always")), - /** The agent marked this running command as work it waits on, so it holds the thread. */ - awaited: Schema.optional(Schema.Literal(true)), }), Schema.Struct({ ...OrchestrationV2TurnItemBaseFields, @@ -2922,8 +2920,6 @@ export const OrchestrationV2TurnItemJson = Schema.Union([ monitor: Schema.optional(Schema.Boolean), /** The provider wakes the agent when this command finishes after its turn. */ completionWake: Schema.optional(Schema.Literal("always")), - /** The agent marked this running command as work it waits on, so it holds the thread. */ - awaited: Schema.optional(Schema.Literal(true)), }), Schema.Struct({ ...OrchestrationV2TurnItemJsonBaseFields, diff --git a/packages/shared/src/orchestrationV2PendingBackgroundWork.test.ts b/packages/shared/src/orchestrationV2PendingBackgroundWork.test.ts index 88ef5e471a77b..faaf9aea24a6e 100644 --- a/packages/shared/src/orchestrationV2PendingBackgroundWork.test.ts +++ b/packages/shared/src/orchestrationV2PendingBackgroundWork.test.ts @@ -387,10 +387,17 @@ describe("derivePendingBackgroundWork kinds", () => { ]); }); - it("holds only for a background command item the agent marked awaited", () => { + it("holds for a command the provider lists awaited, over its running turn item", () => { const tasks = derivePendingBackgroundWork({ latestRun: { id: "run-1" as never, ordinal: 1, status: "completed" }, - providerThreads: [], + providerThreads: [ + { + id: "provider-thread-1" as never, + pendingBackgroundTasks: [ + { taskId: "tests", kind: "command", description: "npm test", awaited: true }, + ], + }, + ], turnItems: [ { id: "item-tests" as never, @@ -399,7 +406,6 @@ describe("derivePendingBackgroundWork kinds", () => { title: null, nativeItemRef: { nativeId: "tests" }, input: "npm test", - awaited: true, }, { id: "item-dev" as never, diff --git a/packages/shared/src/orchestrationV2PendingBackgroundWork.ts b/packages/shared/src/orchestrationV2PendingBackgroundWork.ts index dfd39e0f7ede5..cc8513fb64e60 100644 --- a/packages/shared/src/orchestrationV2PendingBackgroundWork.ts +++ b/packages/shared/src/orchestrationV2PendingBackgroundWork.ts @@ -167,7 +167,6 @@ type PendingBackgroundWorkTurnItem = { } | null; readonly input?: unknown; readonly monitor?: boolean | undefined; - readonly awaited?: true | undefined; readonly prompt?: string | undefined; readonly childThreadId?: ThreadId | null; }; @@ -226,11 +225,7 @@ function pendingTaskFromTurnItem( ...(item.childThreadId == null ? {} : { childThreadId: item.childThreadId }), }; case "command_execution": - return { - ...named, - kind: item.monitor === true ? "monitor" : "command", - ...(item.awaited === true ? { awaited: true as const } : {}), - }; + return { ...named, kind: item.monitor === true ? "monitor" : "command" }; default: return { ...named, kind: "background_task" }; } From 067c8a48e6a869d84e67427fd16c30b8824db3f2 Mon Sep 17 00:00:00 2001 From: Bazyli Brzoska Date: Fri, 27 Nov 2026 12:03:12 -0800 Subject: [PATCH 3/5] fix(server): Codex relies on the t3_background_wait tool description alone Drop the separate Codex developer instruction so the agent context stays within main's budget; the tool description already says when to call it. Vault-Task: Report Codex background commands as awaited in T3's pending background work Co-Authored-By: Claude Opus 5.5 --- apps/server/src/provider/CodexDeveloperInstructions.ts | 5 ----- 1 file changed, 5 deletions(-) diff --git a/apps/server/src/provider/CodexDeveloperInstructions.ts b/apps/server/src/provider/CodexDeveloperInstructions.ts index 3babc92588308..12b35b3c0aaf8 100644 --- a/apps/server/src/provider/CodexDeveloperInstructions.ts +++ b/apps/server/src/provider/CodexDeveloperInstructions.ts @@ -31,10 +31,6 @@ const toolInstructions = (tools: T3CodeToolAvailability): string => .filter(Boolean) .join("\n\n"); -// Codex wakes the agent when any background command ends, so T3 can't tell a wait from a dev server. -const CODEX_BACKGROUND_WAIT_INSTRUCTIONS = - "To wait for a background command you started (tests, a build), pass its session ID to `t3_background_wait` before you end your turn. Do not mark work you leave running, or PRs."; - export interface CodexRuntimeInfo { readonly agentFeedback?: AgentFeedbackMode; readonly model: string; @@ -62,6 +58,5 @@ export function buildCodexAdditionalContext( value: buildRuntimeInstructions({ harness: "Codex", ...runtime }), }, ...(tools ? { t3_code_tools: { kind: "application", value: tools } } : {}), - t3_code_background_wait: { kind: "application", value: CODEX_BACKGROUND_WAIT_INSTRUCTIONS }, }; } From 99f531eec90e28c4fb93b7e6388901e737f190bb Mon Sep 17 00:00:00 2001 From: Julius Marminge Date: Fri, 27 Nov 2026 07:45:57 +0000 Subject: [PATCH 4/5] fix(server): a later Codex turn no longer rolls back the awaited-command roster Turn and resume inputs carry provider-thread snapshots older than the roster the adapter published since. Storing one replaced the cached roster, so a marked command's end compared empty against empty and its removal was never published, leaving the thread Working. The adapter now keeps the roster it published and lays it over every snapshot it stores. Co-Authored-By: Claude Opus 5.5 --- .../Adapters/CodexAdapterV2.test.ts | 101 ++++++++++++++++++ .../Adapters/CodexAdapterV2.ts | 37 +++++-- 2 files changed, 130 insertions(+), 8 deletions(-) diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index fc6a56bff6d21..57d5e1928c8d4 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -8200,6 +8200,107 @@ describe("CodexAdapterV2 post-settle continuation", () => { ), ); + it.effect("lists an awaited command's end after a later turn starts from an older snapshot", () => + Effect.gen(function* () { + const released = yield* Deferred.make(); + const entries = backgroundExecTranscript.entries; + const late = entries.at(-1); + const turnStart = entries.filter( + (entry) => entry.type !== "runtime_exit" && entry.label === "turn/start", + ); + const turnStarted = entries.find( + (entry) => entry.type !== "runtime_exit" && entry.label === "turn/started", + ); + if (late === undefined || turnStart.length !== 2 || turnStarted === undefined) { + return yield* Effect.die("The background exec transcript changed shape."); + } + const NEXT_TURN = "native-codex-bg-turn-2"; + const nextTurn = JSON.parse( + JSON.stringify([...turnStart, turnStarted]) + .replaceAll('"id":3', '"id":5') + .replaceAll(`"${BG_NATIVE_TURN}"`, `"${NEXT_TURN}"`), + ) as Array; + const harness = yield* makeCodexReplayHarness( + makeCodexReplayTranscript({ + scenario: "codex-bg-roster-after-next-turn", + entries: [ + ...entries.slice(0, -1), + { + type: "expect_outbound", + label: "list-background-terminals", + frame: { + id: 4, + method: "thread/backgroundTerminals/list", + params: { threadId: BG_NATIVE_THREAD }, + }, + }, + { + type: "emit_inbound", + label: "list-background-terminals", + frame: { id: 4, result: { data: [{ processId: "4242" }], nextCursor: null } }, + }, + ...nextTurn, + { + type: "emit_inbound", + label: "turn/completed/next", + frame: { + method: "turn/completed", + params: { + threadId: BG_NATIVE_THREAD, + turn: makeCodexReplayTurn({ id: NEXT_TURN, status: "completed" }), + }, + }, + }, + { ...late, afterMs: 0 } as CodexReplay.CodexAppServerReplayEntry, + ], + }), + undefined, + undefined, + undefined, + (entry) => + entry.label === "item/completed/command-late" ? Deferred.await(released) : Effect.void, + ); + const startTurn = (attempt: string) => + Effect.flatMap(DateTime.now, (now) => + harness.runtime.startTurn( + makeCodexTestTurnInput({ + threadId: harness.threadId, + providerThread: harness.providerThread, + now, + attemptId: RunAttemptId.make(attempt), + text: BG_PROMPT, + }), + ), + ); + const rosters = () => awaitedRosters(harness.events, harness.providerThread.id); + yield* startTurn("attempt-roster-first"); + yield* harness.firstTerminal; + yield* harness.runtime.awaitBackgroundTasks!({ + providerThread: harness.providerThread, + taskIds: ["4242"], + awaited: true, + }); + yield* harness.until(() => rosters().length === 1); + // The next turn's input predates the roster published above. + yield* startTurn("attempt-roster-next"); + yield* harness.until(() => harness.terminalEvents().length === 2); + + yield* Deferred.succeed(released, undefined); + yield* harness.until(() => rosters().length === 2); + assert.deepEqual(rosters(), [[BG_COMMAND_ITEM], []]); + }).pipe( + Effect.scoped, + Effect.provide( + Layer.mergeAll( + IdAllocator.layer, + McpProviderSessions.layer, + NodeServices.layer, + NodeCrypto.layer, + ), + ), + ), + ); + // A command that waited on approval starts without a process id; Codex sends it on completion. it.effect("resolves the session id of an approved command Codex started without one", () => Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index a8ea3be52394d..8e921541ce4ca 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -2604,6 +2604,23 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( const turnTerminalizationPermit = yield* Semaphore.make(1); const goalsByNativeThread = new Map(); const rootProviderThreads = new Map(); + // Turn and resume inputs carry snapshots older than the roster published since. + const publishedAwaitedRosters = new Map< + string, + ReadonlyArray + >(); + const setRootProviderThread = ( + nativeThreadId: string, + providerThread: OrchestrationV2ProviderThread, + ) => { + const roster = publishedAwaitedRosters.get(nativeThreadId); + rootProviderThreads.set( + nativeThreadId, + roster === undefined + ? providerThread + : { ...providerThread, pendingBackgroundTasks: roster }, + ); + }; const goalHolds = new Map(); const continuedRuns = new Map>(); const capacityContinuations = new Map< @@ -2769,7 +2786,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( const goal = goalsByNativeThread.get(nativeThreadId) ?? null; if (providerGoalsEqual(providerThread.goal ?? null, goal)) return; const updated = { ...providerThread, goal, updatedAt: yield* DateTime.now }; - rootProviderThreads.set(nativeThreadId, updated); + setRootProviderThread(nativeThreadId, updated); yield* emitProviderEvent({ type: "provider_thread.updated", driver: CODEX_PROVIDER, @@ -2782,7 +2799,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ) { const nativeThreadId = providerThread.nativeThreadRef?.nativeId; if (nativeThreadId == null) return; - rootProviderThreads.set(nativeThreadId, providerThread); + setRootProviderThread(nativeThreadId, providerThread); yield* emitGoalUpdate(nativeThreadId); }); @@ -3049,7 +3066,10 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( ); for (const [nativeThreadId, providerThread] of rootProviderThreads) { const tasks = rosters.get(nativeThreadId) ?? []; - const previous = providerThread.pendingBackgroundTasks ?? []; + const previous = + publishedAwaitedRosters.get(nativeThreadId) ?? + providerThread.pendingBackgroundTasks ?? + []; if ( previous.length === tasks.length && previous.every((task, index) => task.taskId === tasks[index]?.taskId) @@ -3060,6 +3080,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( pendingBackgroundTasks: tasks, updatedAt: yield* DateTime.now, }; + publishedAwaitedRosters.set(nativeThreadId, tasks); rootProviderThreads.set(nativeThreadId, updated); yield* emitProviderEvent({ type: "provider_thread.updated", @@ -7215,7 +7236,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( const rootProviderThread = nativeThreadId == null ? undefined : rootProviderThreads.get(nativeThreadId); if (nativeThreadId != null && rootProviderThread !== undefined) { - rootProviderThreads.set(nativeThreadId, { ...rootProviderThread, status: "idle" }); + setRootProviderThread(nativeThreadId, { ...rootProviderThread, status: "idle" }); } // Notification handlers block response routing, so the read and terminal get a fiber. if (awaitsReset) { @@ -8460,7 +8481,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( yield* rejectIfRetired; if (command.type === "set") yield* validateCodexGoalObjective(command.objective); const threadId = yield* getNativeThreadId(turnInput.providerThread); - rootProviderThreads.set(threadId, turnInput.providerThread); + setRootProviderThread(threadId, turnInput.providerThread); const readGoal = client .request("thread/goal/get", { threadId }) .pipe( @@ -8899,7 +8920,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( }); // Codex resumes an active goal's turns right after the response; own them before it. const previousRoot = rootProviderThreads.get(nativeThreadId); - rootProviderThreads.set(nativeThreadId, threadInput.providerThread); + setRootProviderThread(nativeThreadId, threadInput.providerThread); goalUpdatesHeld.add(nativeThreadId); const response = yield* ensureInitialized.pipe( Effect.andThen(appThreadId == null ? resume : reportingResume(appThreadId, resume)), @@ -8909,7 +8930,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( Effect.onError(() => Effect.suspend(() => { if (previousRoot !== undefined) { - rootProviderThreads.set(nativeThreadId, previousRoot); + setRootProviderThread(nativeThreadId, previousRoot); } return releaseGoalUpdates(nativeThreadId); }), @@ -8928,7 +8949,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* ( nativeConversationHeadRef: threadInput.providerThread.nativeConversationHeadRef, updatedAt: codexTimestamp(response.thread.updatedAt), } satisfies OrchestrationV2ProviderThread; - rootProviderThreads.set(nativeThreadId, resumed); + setRootProviderThread(nativeThreadId, resumed); yield* releaseGoalUpdates(nativeThreadId); return rootProviderThreads.get(nativeThreadId) ?? resumed; }, From 3ac535b547126897213692f629316e5b83271208 Mon Sep 17 00:00:00 2001 From: Bazyli Brzoska Date: Fri, 27 Nov 2026 12:09:20 -0800 Subject: [PATCH 5/5] fix(server): restore the Codex background-wait instruction Revert 415ea9b285. Without it Codex models skip t3_background_wait on a test suite they mean to report on, so the instruction stays and the budget carries its measured size. Vault-Task: Report Codex background commands as awaited in T3's pending background work Co-Authored-By: Claude Opus 5.5 --- apps/server/src/provider/CodexDeveloperInstructions.ts | 5 +++++ apps/server/src/provider/agentContextBudget.json | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/apps/server/src/provider/CodexDeveloperInstructions.ts b/apps/server/src/provider/CodexDeveloperInstructions.ts index 12b35b3c0aaf8..3babc92588308 100644 --- a/apps/server/src/provider/CodexDeveloperInstructions.ts +++ b/apps/server/src/provider/CodexDeveloperInstructions.ts @@ -31,6 +31,10 @@ const toolInstructions = (tools: T3CodeToolAvailability): string => .filter(Boolean) .join("\n\n"); +// Codex wakes the agent when any background command ends, so T3 can't tell a wait from a dev server. +const CODEX_BACKGROUND_WAIT_INSTRUCTIONS = + "To wait for a background command you started (tests, a build), pass its session ID to `t3_background_wait` before you end your turn. Do not mark work you leave running, or PRs."; + export interface CodexRuntimeInfo { readonly agentFeedback?: AgentFeedbackMode; readonly model: string; @@ -58,5 +62,6 @@ export function buildCodexAdditionalContext( value: buildRuntimeInstructions({ harness: "Codex", ...runtime }), }, ...(tools ? { t3_code_tools: { kind: "application", value: tools } } : {}), + t3_code_background_wait: { kind: "application", value: CODEX_BACKGROUND_WAIT_INSTRUCTIONS }, }; } diff --git a/apps/server/src/provider/agentContextBudget.json b/apps/server/src/provider/agentContextBudget.json index f962a7b44a4f9..92fe1b6c50565 100644 --- a/apps/server/src/provider/agentContextBudget.json +++ b/apps/server/src/provider/agentContextBudget.json @@ -1,5 +1,5 @@ { "claudeSystemAppendBytes": 6347, - "codexAdditionalContextBytes": 7916, + "codexAdditionalContextBytes": 8092, "mcpToolListJsonBytes": 63718 }