Skip to content

Commit 5a5bf4d

Browse files
authored
fix(codex): preserve native child continuation on yield (#124004)
1 parent af76f49 commit 5a5bf4d

10 files changed

Lines changed: 106 additions & 23 deletions

‎extensions/codex/src/app-server/native-subagent-monitor.ts‎

Lines changed: 21 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -56,18 +56,18 @@ type NativeSubagentMonitorClient = Pick<
5656
"request" | "addNotificationHandler" | "addCloseHandler"
5757
>;
5858

59+
type ParentOwner = {
60+
turnId?: string;
61+
claimDirectChild?: (threadId: string) => (() => void) | undefined;
62+
rejectPendingDirectChild?: (threadId: string, reason: string) => void;
63+
onDirectChildAccepted?: () => void;
64+
};
65+
5966
type ParentState = {
6067
parentThreadId: string;
6168
// Overlapping runs share this parent; the last owner releases it only after
6269
// detached children finish recovery and delivery.
63-
owners: Map<
64-
symbol,
65-
{
66-
turnId?: string;
67-
claimDirectChild?: (threadId: string) => (() => void) | undefined;
68-
rejectPendingDirectChild?: (threadId: string, reason: string) => void;
69-
}
70-
>;
70+
owners: Map<symbol, ParentOwner>;
7171
requesterSessionKey?: string;
7272
taskRuntimeScope?: AgentHarnessTaskRuntimeScope;
7373
agentId?: string;
@@ -196,6 +196,7 @@ function registerMonitor(params: {
196196
retainParentThread?: (threadId: string) => (() => void) | undefined;
197197
claimDirectChild?: (threadId: string) => (() => void) | undefined;
198198
rejectPendingDirectChild?: (threadId: string, reason: string) => void;
199+
onDirectChildAccepted?: () => void;
199200
}): { bindTurn: (turnId: string) => void; unregister: () => void } {
200201
let monitor = monitors.get(params.client);
201202
if (!monitor) {
@@ -261,6 +262,7 @@ function registerMonitor(params: {
261262
agentId: params.agentId,
262263
claimDirectChild: params.claimDirectChild,
263264
rejectPendingDirectChild: params.rejectPendingDirectChild,
265+
onDirectChildAccepted: params.onDirectChildAccepted,
264266
});
265267
}
266268

@@ -363,6 +365,7 @@ class Monitor {
363365
agentId?: string;
364366
claimDirectChild?: (threadId: string) => (() => void) | undefined;
365367
rejectPendingDirectChild?: (threadId: string, reason: string) => void;
368+
onDirectChildAccepted?: () => void;
366369
}): { bindTurn: (turnId: string) => void; unregister: () => void } {
367370
const parentThreadId = params.parentThreadId.trim();
368371
if (!parentThreadId) {
@@ -390,6 +393,7 @@ class Monitor {
390393
state.owners.set(owner, {
391394
claimDirectChild: params.claimDirectChild,
392395
rejectPendingDirectChild: params.rejectPendingDirectChild,
396+
onDirectChildAccepted: params.onDirectChildAccepted,
393397
});
394398
this.prepareParentTaskRuntime(state);
395399
for (const childState of this.childStates.values()) {
@@ -1387,9 +1391,7 @@ class Monitor {
13871391
private resolveParentOwner(
13881392
state: ParentState,
13891393
turnIdInput: string | undefined,
1390-
):
1391-
| { turnId?: string; claimDirectChild?: (threadId: string) => (() => void) | undefined }
1392-
| undefined {
1394+
): ParentOwner | undefined {
13931395
const turnId = turnIdInput?.trim();
13941396
if (!turnId) {
13951397
return undefined;
@@ -1402,14 +1404,16 @@ class Monitor {
14021404
state: ParentState,
14031405
turnIdInput: string | undefined,
14041406
evidence: DirectSpawnEvidence,
1405-
owner: { claimDirectChild?: (threadId: string) => (() => void) | undefined } | undefined,
1407+
owner: ParentOwner | undefined,
14061408
): ChildState | undefined {
14071409
const childState = this.registerChildThread(state.parentThreadId, evidence.childThreadId, {
14081410
...(evidence.agentPath === undefined ? {} : { agentPath: evidence.agentPath }),
14091411
...(owner?.claimDirectChild ? { claimDirectChild: owner.claimDirectChild } : {}),
14101412
});
14111413
if (!owner) {
14121414
this.bufferPendingDirectSpawnEvidence(turnIdInput, evidence);
1415+
} else if (childState) {
1416+
owner.onDirectChildAccepted?.();
14131417
}
14141418
return childState;
14151419
}
@@ -1443,7 +1447,7 @@ class Monitor {
14431447

14441448
private drainPendingDirectSpawnEvidence(
14451449
state: ParentState,
1446-
owner: { claimDirectChild?: (threadId: string) => (() => void) | undefined },
1450+
owner: ParentOwner,
14471451
turnId: string,
14481452
): void {
14491453
const pending = this.pendingDirectSpawnEvidence.get(turnId);
@@ -1453,10 +1457,13 @@ class Monitor {
14531457
}
14541458
for (const evidence of pending) {
14551459
if (evidence.parentThreadId === state.parentThreadId) {
1456-
this.registerChildThread(state.parentThreadId, evidence.childThreadId, {
1460+
const childState = this.registerChildThread(state.parentThreadId, evidence.childThreadId, {
14571461
...(evidence.agentPath === undefined ? {} : { agentPath: evidence.agentPath }),
14581462
claimDirectChild: owner.claimDirectChild,
14591463
});
1464+
if (childState) {
1465+
owner.onDirectChildAccepted?.();
1466+
}
14601467
}
14611468
}
14621469
}

‎extensions/codex/src/app-server/run-attempt-finalize.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -494,6 +494,7 @@ export async function finalizeCodexAttempt(
494494
...(terminalAnchor ? { contextEngineTerminalAnchor: terminalAnchor } : {}),
495495
...(settledTurnFinalizationContext ? { settledTurnFinalizationContext } : {}),
496496
...(resourceState.runtimeArtifact ? { runtimeArtifact: resourceState.runtimeArtifact } : {}),
497+
...(resourceState.runtimeContinuationStarted ? { runtimeContinuationStarted: true } : {}),
497498
...(!finalAborted && !effectiveTimedOut && !finalPromptError && preparedAuthBinding
498499
? { authBindingFingerprint: preparedAuthBinding.fingerprint }
499500
: {}),

‎extensions/codex/src/app-server/run-attempt-resources.ts‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,7 @@ export function prepareCodexAttemptResources(prompt: CodexAttemptPrompt) {
7272
nativeSubagentMonitor: undefined as
7373
| ReturnType<typeof codexNativeSubagentMonitorRuntime.register>
7474
| undefined,
75+
runtimeContinuationStarted: false,
7576
nativePreToolUseFailureFallbackActive: false,
7677
nativePreToolUseFailureFallbackTerminalReason: undefined as
7778
| CodexNativePreToolUseFailure["disposition"]
@@ -187,6 +188,13 @@ export function prepareCodexAttemptResources(prompt: CodexAttemptPrompt) {
187188
claimDirectChild: (childThreadId) => state.nativeHookRelay?.claimDirectChild(childThreadId),
188189
rejectPendingDirectChild: (childThreadId, reason) =>
189190
state.nativeHookRelay?.rejectPendingDirectChild(childThreadId, reason),
191+
...(params.sessionKey && params.agentHarnessTaskRuntimeScope
192+
? {
193+
onDirectChildAccepted: () => {
194+
state.runtimeContinuationStarted = true;
195+
},
196+
}
197+
: {}),
190198
});
191199
};
192200
const releaseCurrentRoute = () => {

‎extensions/codex/src/app-server/run-attempt.native-hook-relay-retention.test.ts‎

Lines changed: 32 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ describe("runCodexAppServerAttempt native hook relay retention", () => {
3030
it.each([
3131
{
3232
name: "Codex multi-agent V1",
33+
bindBeforeClaim: false,
34+
hasDeliveryScope: true,
3335
childThreadId: "child-v1",
3436
childClaim: {
3537
type: "collabAgentToolCall",
@@ -41,6 +43,8 @@ describe("runCodexAppServerAttempt native hook relay retention", () => {
4143
},
4244
{
4345
name: "Codex multi-agent V2",
46+
bindBeforeClaim: true,
47+
hasDeliveryScope: true,
4448
childThreadId: "child-v2",
4549
childClaim: {
4650
type: "subAgentActivity",
@@ -49,9 +53,21 @@ describe("runCodexAppServerAttempt native hook relay retention", () => {
4953
agentPath: "/root/child-v2",
5054
},
5155
},
56+
{
57+
name: "Codex multi-agent V2 without delivery scope",
58+
bindBeforeClaim: true,
59+
hasDeliveryScope: false,
60+
childThreadId: "child-v2-no-delivery",
61+
childClaim: {
62+
type: "subAgentActivity",
63+
kind: "started",
64+
agentThreadId: "child-v2-no-delivery",
65+
agentPath: "/root/child-v2-no-delivery",
66+
},
67+
},
5268
] as const)(
5369
"retains and fences a live child through sessions_yield ($name)",
54-
async ({ childThreadId, childClaim }) => {
70+
async ({ bindBeforeClaim, hasDeliveryScope, childThreadId, childClaim }) => {
5571
const sessionFile = path.join(tempDir, `${childThreadId}-yield-session.jsonl`);
5672
const workspaceDir = path.join(tempDir, `${childThreadId}-yield-workspace`);
5773
let resolveTurnStart: ((value: undefined) => void) | undefined;
@@ -71,6 +87,9 @@ describe("runCodexAppServerAttempt native hook relay retention", () => {
7187
setCodexTestModelSupportsTools(params, true);
7288
const fixture = await createAdmittedHostCapabilityTestFixture(params);
7389
params.hostCapabilities = fixture.hostCapabilities;
90+
if (hasDeliveryScope) {
91+
params.agentHarnessTaskRuntimeScope = fixture.agentHarnessTaskRuntimeScope;
92+
}
7493

7594
const beforeToolCall = vi.fn(async (event: unknown) =>
7695
(event as { params?: { command?: string } }).params?.command === "deny-child"
@@ -87,6 +106,12 @@ describe("runCodexAppServerAttempt native hook relay retention", () => {
87106
let relayId: string | undefined;
88107
try {
89108
await harness.waitForMethod("turn/start");
109+
if (bindBeforeClaim) {
110+
resolveTurnStart?.(undefined);
111+
await new Promise<void>((resolve) => {
112+
setImmediate(resolve);
113+
});
114+
}
90115
const startRequest = harness.requests.find((request) => request.method === "thread/start");
91116
relayId = extractRelayIdFromThreadRequest(startRequest?.params);
92117
const preDiscoveryPayload = {
@@ -200,10 +225,11 @@ describe("runCodexAppServerAttempt native hook relay retention", () => {
200225
item: childClaim,
201226
},
202227
} as unknown as CodexServerNotification);
203-
// The app-server can publish the direct-spawn item after starting its
204-
// turn but before turn/start responds. Binding must replay this exact
205-
// evidence rather than dropping the already-pending child hook.
206-
resolveTurnStart?.(undefined);
228+
// Cover both exact-turn admission paths: an already-bound owner and
229+
// evidence buffered before turn/start responds.
230+
if (!bindBeforeClaim) {
231+
resolveTurnStart?.(undefined);
232+
}
207233
await expect(Promise.all([firstPending, duplicatePending])).resolves.toEqual([
208234
{ stdout: "", stderr: "", exitCode: 0 },
209235
{ stdout: "", stderr: "", exitCode: 0 },
@@ -232,6 +258,7 @@ describe("runCodexAppServerAttempt native hook relay retention", () => {
232258
await harness.completeTurn({ threadId: "thread-1", turnId: "turn-1" });
233259
const result = await run;
234260
expect(readAttemptTerminal(result)).toMatchObject({ aborted: false, promptError: null });
261+
expect(result.runtimeContinuationStarted).toBe(hasDeliveryScope ? true : undefined);
235262
const terminalLifecycleEvents = (params.onAgentEvent as ReturnType<typeof vi.fn>).mock.calls
236263
.map(([event]) => event as { stream?: string; data?: Record<string, unknown> })
237264
.filter(

‎src/agents/embedded-agent-runner/result-fallback-classifier.test.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -393,7 +393,7 @@ describe("classifyEmbeddedAgentRunResultForModelFallback", () => {
393393
});
394394
});
395395

396-
it("does not fallback after structured replay state records potential side effects", () => {
396+
it("does not fallback after a yielded empty result records potential side effects", () => {
397397
const result = classifyEmbeddedAgentRunResultForModelFallback({
398398
provider: "openai",
399399
model: "gpt-5.5",
@@ -402,7 +402,8 @@ describe("classifyEmbeddedAgentRunResultForModelFallback", () => {
402402
meta: {
403403
durationMs: 42,
404404
replayInvalid: true,
405-
agentHarnessResultClassification: "reasoning-only",
405+
yielded: true,
406+
stopReason: "end_turn",
406407
},
407408
},
408409
});

‎src/agents/embedded-agent-runner/run/incomplete-turn-resolution.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,7 @@ interface YieldContinuationAttempt {
182182
didSendDeterministicApprovalPrompt?: boolean;
183183
successfulCronAdds?: number;
184184
acceptedSessionSpawns?: readonly { runId: string; childSessionKey: string }[];
185+
runtimeContinuationStarted?: boolean;
185186
messagingToolSentTexts?: readonly string[];
186187
messagingToolSentMediaUrls?: readonly string[];
187188
messagingToolSentTargets?: readonly MessagingToolSend[];
@@ -201,6 +202,7 @@ export function hasYieldContinuationEvidence(attempt: YieldContinuationAttempt):
201202
messagingToolSentTargets: attempt.messagingToolSentTargets ?? [],
202203
}) ||
203204
hasAcceptedSessionSpawn(attempt.acceptedSessionSpawns) ||
205+
attempt.runtimeContinuationStarted === true ||
204206
hasAsyncActivity(attempt.toolMetas) ||
205207
(attempt.successfulCronAdds ?? 0) > 0
206208
);

‎src/agents/embedded-agent-runner/run/run-attempt-result.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,10 @@ export function normalizeEmbeddedRunAttemptResult(
2525
| EmbeddedRunAttemptForRunner["currentAttemptReplayMetadata"]
2626
| null;
2727
};
28+
const runtimeContinuationReplayMetadata =
29+
raw.runtimeContinuationStarted === true
30+
? { hadPotentialSideEffects: true, replaySafe: false }
31+
: undefined;
2832
return {
2933
...attempt,
3034
assistantTexts: raw.assistantTexts ?? [],
@@ -41,8 +45,10 @@ export function normalizeEmbeddedRunAttemptResult(
4145
completedCount: 0,
4246
activeCount: 0,
4347
},
44-
replayMetadata: raw.replayMetadata ?? { hadPotentialSideEffects: true, replaySafe: false },
45-
currentAttemptReplayMetadata: raw.currentAttemptReplayMetadata ?? undefined,
48+
replayMetadata: runtimeContinuationReplayMetadata ??
49+
raw.replayMetadata ?? { hadPotentialSideEffects: true, replaySafe: false },
50+
currentAttemptReplayMetadata:
51+
runtimeContinuationReplayMetadata ?? raw.currentAttemptReplayMetadata ?? undefined,
4652
};
4753
}
4854

‎src/agents/embedded-agent-runner/run/types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -282,6 +282,8 @@ export type EmbeddedRunAttemptResult = {
282282
asyncTaskId?: string;
283283
}>;
284284
acceptedSessionSpawns?: AcceptedSessionSpawn[];
285+
/** This attempt accepted work whose future output has a runtime-owned delivery path. */
286+
runtimeContinuationStarted?: boolean;
285287
lastAssistant: AssistantMessage | undefined;
286288
/**
287289
* Omission preserves the legacy `lastAssistant` fallback; explicit `undefined`

‎src/agents/embedded-agent-runner/sessions-yield.orchestration.test-support.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -134,6 +134,26 @@ describe("sessions_yield orchestration", () => {
134134
expect(result.meta.stopReason).toBe("end_turn");
135135
expect(result.meta.yielded).toBe(true);
136136
});
137+
138+
it("yield with runtime continuation — diagnostic suppressed", async () => {
139+
mockedRunEmbeddedAttempt.mockResolvedValueOnce(
140+
makeAttemptResult({
141+
yieldDetected: true,
142+
assistantTexts: [],
143+
runtimeContinuationStarted: true,
144+
}),
145+
);
146+
147+
const result = await runEmbeddedAgent({
148+
...overflowBaseRunParams,
149+
runId: "run-yield-runtime-continuation-suppressed",
150+
});
151+
152+
expect(result.payloads).toBeUndefined();
153+
expect(result.meta.stopReason).toBe("end_turn");
154+
expect(result.meta.yielded).toBe(true);
155+
expect(result.meta.replayInvalid).toBe(true);
156+
});
137157
});
138158

139159
it("normal attempt without yield has no stopReason override", async () => {

‎src/agents/harness/host-capability.test-support.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { createAgentHarnessTaskRuntimeScope } from "../../tasks/agent-harness-task-runtime-scope.js";
12
import {
23
createOperationalRunInstanceRef,
34
prepareAgentRunAdmission,
@@ -10,6 +11,7 @@ type HostAttempt = Parameters<typeof createAgentHarnessHostCapabilities>[0]["att
1011
type AdmittedHostCapabilityTestFixture = Readonly<{
1112
admittedRunContext: AdmittedRunContext;
1213
hostCapabilities: ReturnType<typeof createAgentHarnessHostCapabilities>["capabilities"];
14+
agentHarnessTaskRuntimeScope?: ReturnType<typeof createAgentHarnessTaskRuntimeScope>;
1315
closeHost: () => void;
1416
closeAdmission: () => void;
1517
}>;
@@ -35,6 +37,13 @@ export async function createAdmittedHostCapabilityTestFixture(
3537
return {
3638
admittedRunContext,
3739
hostCapabilities: host.capabilities,
40+
...(attempt.sessionKey
41+
? {
42+
agentHarnessTaskRuntimeScope: createAgentHarnessTaskRuntimeScope({
43+
requesterSessionKey: attempt.sessionKey,
44+
}),
45+
}
46+
: {}),
3847
closeHost: host.close,
3948
closeAdmission: admission.close,
4049
};

0 commit comments

Comments
 (0)