Skip to content

Commit 7879adf

Browse files
committed
fix(inference): preserve cancellation, lifecycle, and Codex completion ownership
1 parent 86a95b4 commit 7879adf

27 files changed

Lines changed: 694 additions & 287 deletions

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ export async function cleanupCodexAttempt(
8989
terminalState.turnSucceeded &&
9090
!isIncognitoSessionKey(params.sessionKey) &&
9191
params.cleanupBundleMcpOnRunEnd !== true &&
92-
!params.contextEngine &&
92+
!connection.activeContextEngine &&
9393
resourceState.thread.liveThreadConfigFingerprint !== undefined &&
9494
resourceState.thread.clientId === resolveCodexAppServerClientInstanceId(resourceState.client) &&
9595
resourceState.thread.preserveNativeModel !== true &&

‎extensions/codex/src/app-server/run-attempt-thread-cleanup.test.ts‎

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,15 @@ describe("Codex app-server main thread cleanup", () => {
198198
await fs.rm(tempDir, { recursive: true, force: true });
199199
});
200200

201-
it("retains a subscribed persistent Codex thread after a completed turn", async () => {
201+
it.each([
202+
{ label: "without a context engine", contextEngine: undefined },
203+
{
204+
label: "with the default legacy context engine",
205+
contextEngine: {
206+
info: { id: "legacy", name: "Legacy", version: "1.0.0" },
207+
} as EmbeddedRunAttemptParams["contextEngine"],
208+
},
209+
])("retains a subscribed persistent Codex thread $label", async ({ contextEngine }) => {
202210
const sessionFile = path.join(tempDir, "session.jsonl");
203211
const workspaceDir = path.join(tempDir, "workspace");
204212
const requests: Array<{ method: string; params: unknown }> = [];
@@ -227,10 +235,10 @@ describe("Codex app-server main thread cleanup", () => {
227235
} as never;
228236
});
229237

230-
const run = runCodexAppServerAttempt(createParams(sessionFile, workspaceDir), {
231-
bindingStore: testCodexAppServerBindingStore,
232-
clientFactory,
233-
});
238+
const run = runCodexAppServerAttempt(
239+
{ ...createParams(sessionFile, workspaceDir), contextEngine },
240+
{ bindingStore: testCodexAppServerBindingStore, clientFactory },
241+
);
234242
await vi.waitFor(() => expect(requests.map((entry) => entry.method)).toContain("turn/start"), {
235243
interval: 1,
236244
timeout: 5_000,

‎extensions/codex/src/app-server/turn-router.test.ts‎

Lines changed: 38 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -935,46 +935,44 @@ describe("CodexAppServerTurnRouter", () => {
935935
expect(notificationHandler).not.toHaveBeenCalled();
936936
expect(requestHandler).not.toHaveBeenCalled();
937937

938-
let finishActiveRequest!: (result: { decision: string }) => void;
939-
const activeResult = new Promise<{ decision: string }>((resolve) => {
940-
finishActiveRequest = resolve;
941-
});
942-
let failActiveRequest!: (error: Error) => void;
943-
const rejectedActiveResult = new Promise<{ decision: string }>((_resolve, reject) => {
944-
failActiveRequest = reject;
945-
});
946-
const activeHandler = vi.fn((request: { id: number | string }) =>
947-
request.id === "request-active-reject" ? rejectedActiveResult : activeResult,
938+
const activeHandler = vi.fn(
939+
(request: { id: number | string }, _scope: unknown, signal: AbortSignal) =>
940+
new Promise<{ decision: string }>((resolve, reject) => {
941+
signal.addEventListener(
942+
"abort",
943+
() => {
944+
if (request.id === "request-active-reject") {
945+
reject(new Error("stale request failure"));
946+
return;
947+
}
948+
resolve({ decision: "accept" });
949+
},
950+
{ once: true },
951+
);
952+
}),
948953
);
949954
const activeRoute = router.reserveThread({
950955
threadId: "thread-active",
951956
onRequest: activeHandler,
952957
});
953958
activeRoute.armTurn();
954959
await activeRoute.bindTurn("turn-active");
955-
harness.send({
956-
id: "request-active",
957-
method: "item/commandExecution/requestApproval",
958-
params: {
959-
threadId: "thread-active",
960-
turnId: "turn-active",
961-
itemId: "item-2",
962-
},
963-
});
964-
harness.send({
965-
id: "request-active-reject",
966-
method: "item/commandExecution/requestApproval",
967-
params: {
968-
threadId: "thread-active",
969-
turnId: "turn-active",
970-
itemId: "item-3",
971-
},
972-
});
960+
for (const [id, itemId] of [
961+
["request-active", "item-2"],
962+
["request-active-reject", "item-3"],
963+
]) {
964+
harness.send({
965+
id,
966+
method: "item/commandExecution/requestApproval",
967+
params: { threadId: "thread-active", turnId: "turn-active", itemId },
968+
});
969+
}
973970
await vi.waitFor(() => expect(activeHandler).toHaveBeenCalledTimes(2));
971+
const activeSignals = () => activeHandler.mock.calls.map((call) => call[2].aborted);
972+
expect(activeSignals()).toEqual([false, false]);
974973

975974
activeRoute.release();
976-
finishActiveRequest({ decision: "accept" });
977-
failActiveRequest(new Error("stale request failure"));
975+
expect(activeSignals()).toEqual([true, true]);
978976

979977
expect(await waitForResponse(harness, "request-active")).toEqual({
980978
id: "request-active",
@@ -987,12 +985,21 @@ describe("CodexAppServerTurnRouter", () => {
987985

988986
const closingRoute = router.reserveThread({
989987
threadId: "thread-close",
990-
onRequest: requestHandler,
988+
onRequest: activeHandler,
989+
});
990+
closingRoute.armTurn();
991+
await closingRoute.bindTurn("turn-close");
992+
harness.send({
993+
id: "request-close",
994+
method: "item/commandExecution/requestApproval",
995+
params: { threadId: "thread-close", turnId: "turn-close", itemId: "item-4" },
991996
});
997+
await vi.waitFor(() => expect(activeHandler).toHaveBeenCalledTimes(3));
992998
harness.process.stderr.write("fatal transport detail\n");
993999
harness.process.emit("exit", 17, "SIGTERM");
9941000

9951001
await expect(closingRoute.bindTurn("turn-close")).rejects.toThrow("turn router closed");
1002+
expect(activeHandler.mock.calls[2]?.[2].aborted).toBe(true);
9961003
expect(closingRoute.signal.aborted).toBe(true);
9971004
expect(closingRoute.signal.reason).toEqual(
9981005
new Error("codex app-server turn router closed", {

‎extensions/codex/src/app-server/turn-router.ts‎

Lines changed: 15 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -389,13 +389,16 @@ class ClientTurnRouter implements CodexAppServerTurnRouter {
389389
return undefined;
390390
}
391391
const route = this.routes.get(scope.threadId);
392-
if (!route || route.released) {
392+
if (!route) {
393393
return undefined;
394394
}
395-
if (!route.handlers && !(await waitForPromiseOrAbort(route.activated.promise, signal))) {
395+
// A retired route owns its in-flight tools and approvals; upstream can
396+
// cancel their callbacks before sending the terminal turn notification.
397+
const requestSignal = AbortSignal.any([signal, route.controller.signal]);
398+
if (!route.handlers && !(await waitForPromiseOrAbort(route.activated.promise, requestSignal))) {
396399
return undefined;
397400
}
398-
if (signal.aborted || route.released || !route.handlers) {
401+
if (requestSignal.aborted || !route.handlers) {
399402
return undefined;
400403
}
401404
const handler = route.handlers.onRequest;
@@ -406,25 +409,20 @@ class ClientTurnRouter implements CodexAppServerTurnRouter {
406409
// new OpenClaw turn, whose requests must wait for its accepted turn id.
407410
while (route.gate === "armed") {
408411
const binding = route.binding?.promise;
409-
if (!binding || !(await waitForPromiseOrAbort(binding, signal))) {
412+
if (!binding || !(await waitForPromiseOrAbort(binding, requestSignal))) {
410413
return undefined;
411414
}
412-
if (signal.aborted || route.released) {
415+
if (requestSignal.aborted) {
413416
return undefined;
414417
}
415418
}
416-
if (route.gate === "bound") {
417-
if (scope.turnId && scope.turnId !== route.turnId) {
418-
return undefined;
419-
}
420-
if (route.released) {
421-
return undefined;
422-
}
419+
if (route.gate === "bound" && scope.turnId && scope.turnId !== route.turnId) {
420+
return undefined;
423421
}
424-
if (!(await waitForPromiseOrAbort(this.waitForNotifications(route), signal))) {
422+
if (!(await waitForPromiseOrAbort(this.waitForNotifications(route), requestSignal))) {
425423
return undefined;
426424
}
427-
if (signal.aborted || route.released) {
425+
if (requestSignal.aborted) {
428426
return undefined;
429427
}
430428
try {
@@ -434,11 +432,11 @@ class ClientTurnRouter implements CodexAppServerTurnRouter {
434432
threadId: scope.threadId,
435433
...(scope.turnId ? { turnId: scope.turnId } : {}),
436434
},
437-
signal,
435+
requestSignal,
438436
);
439-
return signal.aborted || route.released ? undefined : result;
437+
return requestSignal.aborted ? undefined : result;
440438
} catch (error) {
441-
if (signal.aborted || route.released) {
439+
if (requestSignal.aborted) {
442440
return undefined;
443441
}
444442
throw error;

‎extensions/qa-lab/src/providers/mock-openai/mock-anthropic-wire.ts‎

Lines changed: 6 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -102,15 +102,12 @@ export function convertAnthropicMessagesToResponsesInput(params: {
102102
continue;
103103
}
104104
if (block.type === "tool_result") {
105-
const output = stringifyToolResultContent(block.content);
106-
if (output.trim()) {
107-
toolResultItems.push({
108-
type: "function_call_output",
109-
call_id: block.tool_use_id,
110-
output,
111-
...(block.is_error === true ? { is_error: true } : {}),
112-
});
113-
}
105+
toolResultItems.push({
106+
type: "function_call_output",
107+
call_id: block.tool_use_id,
108+
output: stringifyToolResultContent(block.content),
109+
...(block.is_error === true ? { is_error: true } : {}),
110+
});
114111
continue;
115112
}
116113
if (block.type === "tool_use") {

‎extensions/qa-lab/src/providers/mock-openai/mock-openai-input.ts‎

Lines changed: 33 additions & 95 deletions
Original file line numberDiff line numberDiff line change
@@ -126,116 +126,56 @@ function extractFunctionCallOutputText(item: ResponsesInputItem) {
126126
return stringifyFunctionCallOutput(item.output);
127127
}
128128

129-
function extractFunctionCallOutputCallId(item: ResponsesInputItem) {
130-
if (!isResponsesToolCallOutput(item)) {
131-
return "";
132-
}
133-
const record = item as {
134-
call_id?: unknown;
135-
tool_call_id?: unknown;
136-
tool_use_id?: unknown;
137-
};
138-
return (
139-
[record.call_id, record.tool_call_id, record.tool_use_id].find(
140-
(value): value is string => typeof value === "string" && value.trim().length > 0,
141-
) ?? ""
142-
);
143-
}
144-
145-
function functionCallOutputIsStructuredError(item: ResponsesInputItem) {
146-
if (!isResponsesToolCallOutput(item)) {
147-
return false;
148-
}
149-
return item.is_error === true || item.isError === true;
150-
}
151-
152-
export function extractToolOutput(input: ResponsesInputItem[]) {
129+
function findCurrentToolOutput(input: ResponsesInputItem[]): ResponsesInputItem | undefined {
153130
const lastUserIndex = findLastUserIndex(input);
154131
for (const item of input.slice(lastUserIndex + 1).toReversed()) {
155-
const output = extractFunctionCallOutputText(item);
156-
if (output) {
157-
return output;
132+
if (isResponsesToolCallOutput(item)) {
133+
return item;
158134
}
159135
}
160136
for (const [candidateIndex, candidateItem] of Array.from(input.entries()).toReversed()) {
161-
const output = extractFunctionCallOutputText(candidateItem);
162-
if (output) {
163-
const laterUserTexts = input
164-
.slice(candidateIndex + 1)
165-
.filter((laterItem) => laterItem.role === "user" && Array.isArray(laterItem.content))
166-
.map((laterItem) => extractInputText(laterItem.content as unknown[]))
167-
.filter(Boolean);
168-
if (
169-
laterUserTexts.length > 0 &&
170-
laterUserTexts.every((text) => isContinuationUserText(text))
171-
) {
172-
return output;
173-
}
137+
if (!isResponsesToolCallOutput(candidateItem)) {
174138
continue;
175139
}
140+
const laterUserTexts = input
141+
.slice(candidateIndex + 1)
142+
.filter((laterItem) => laterItem.role === "user" && Array.isArray(laterItem.content))
143+
.map((laterItem) => extractInputText(laterItem.content as unknown[]))
144+
.filter(Boolean);
145+
if (laterUserTexts.length > 0 && laterUserTexts.every(isContinuationUserText)) {
146+
return candidateItem;
147+
}
176148
}
177-
return "";
149+
return undefined;
150+
}
151+
152+
export function hasToolOutput(input: ResponsesInputItem[]) {
153+
return findCurrentToolOutput(input) !== undefined;
154+
}
155+
156+
export function extractToolOutput(input: ResponsesInputItem[]) {
157+
const item = findCurrentToolOutput(input);
158+
return item ? stringifyFunctionCallOutput(item.output) : "";
178159
}
179160

180161
export function extractToolOutputStructuredError(input: ResponsesInputItem[]) {
181-
const lastUserIndex = findLastUserIndex(input);
182-
for (const item of input.slice(lastUserIndex + 1).toReversed()) {
183-
const output = extractFunctionCallOutputText(item);
184-
if (output) {
185-
return functionCallOutputIsStructuredError(item);
186-
}
187-
}
188-
for (const [candidateIndex, candidateItem] of Array.from(input.entries()).toReversed()) {
189-
const output = extractFunctionCallOutputText(candidateItem);
190-
if (output) {
191-
const laterUserTexts = input
192-
.slice(candidateIndex + 1)
193-
.filter((laterItem) => laterItem.role === "user" && Array.isArray(laterItem.content))
194-
.map((laterItem) => extractInputText(laterItem.content as unknown[]))
195-
.filter(Boolean);
196-
if (
197-
laterUserTexts.length > 0 &&
198-
laterUserTexts.every((text) => isContinuationUserText(text))
199-
) {
200-
return functionCallOutputIsStructuredError(candidateItem);
201-
}
202-
}
203-
}
204-
return false;
162+
const item = findCurrentToolOutput(input);
163+
return item?.is_error === true || item?.isError === true;
205164
}
206165

207166
export function extractToolOutputCallId(input: ResponsesInputItem[]) {
208-
const lastUserIndex = findLastUserIndex(input);
209-
for (const item of input.slice(lastUserIndex + 1).toReversed()) {
210-
const output = extractFunctionCallOutputText(item);
211-
if (output) {
212-
return extractFunctionCallOutputCallId(item);
213-
}
214-
}
215-
for (const [candidateIndex, candidateItem] of Array.from(input.entries()).toReversed()) {
216-
const output = extractFunctionCallOutputText(candidateItem);
217-
if (output) {
218-
const laterUserTexts = input
219-
.slice(candidateIndex + 1)
220-
.filter((laterItem) => laterItem.role === "user" && Array.isArray(laterItem.content))
221-
.map((laterItem) => extractInputText(laterItem.content as unknown[]))
222-
.filter(Boolean);
223-
if (
224-
laterUserTexts.length > 0 &&
225-
laterUserTexts.every((text) => isContinuationUserText(text))
226-
) {
227-
return extractFunctionCallOutputCallId(candidateItem);
228-
}
229-
}
230-
}
231-
return "";
167+
const item = findCurrentToolOutput(input);
168+
return (
169+
[item?.call_id, item?.tool_call_id, item?.tool_use_id].find(
170+
(value): value is string => typeof value === "string" && value.trim().length > 0,
171+
) ?? ""
172+
);
232173
}
233174

234175
export function extractLatestToolOutput(input: ResponsesInputItem[]) {
235176
for (const item of input.toReversed()) {
236-
const output = extractFunctionCallOutputText(item);
237-
if (output) {
238-
return output;
177+
if (isResponsesToolCallOutput(item)) {
178+
return stringifyFunctionCallOutput(item.output);
239179
}
240180
}
241181
return "";
@@ -249,9 +189,7 @@ export function extractAllToolOutputText(input: ResponsesInputItem[]) {
249189
}
250190

251191
export function extractUserTextAfterLatestToolOutput(input: ResponsesInputItem[]) {
252-
const latestToolOutputIndex = input.findLastIndex((item) =>
253-
Boolean(extractFunctionCallOutputText(item)),
254-
);
192+
const latestToolOutputIndex = input.findLastIndex(isResponsesToolCallOutput);
255193
if (latestToolOutputIndex < 0) {
256194
return "";
257195
}

0 commit comments

Comments
 (0)