Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
fix(openai-codex): load a sandbox module before replaying after a retire
Jack Rudenko1cbc109a0fa3
diff --git a/ai-docs/architecture/code-mode.md b/ai-docs/architecture/code-mode.mdindex a53bf876..ec31b087 100644--- a/ai-docs/architecture/code-mode.md+++ b/ai-docs/architecture/code-mode.md@@ -197,7 +197,7 @@ for the same script.| consumed batch, same `batchHash` (a duplicate request) | the memoised step: the same synthetic reply, or the stored completion. The reply goes to the OWNER only: a fork asking while the owner's next batch is pending gets the forked-script `Script failed` below, never that batch (its tools would run twice) || consumed batch, different `batchHash` (a rewind that re-ran tools) | lost path, tombstone under the new completion key || suspended, owned by ANOTHER session (a fork) | untouched; the fork gets `Script failed` "this script belongs to the session this one was forked from; claudish cannot run it twice"; the owner's later run output wins every lookup |-| record lost, source kept, owned by this session, the request answers its LAST round | **replay** (`replay.ts`): the source re-runs in a fresh runtime and each batch is answered from history, provided batch k is exactly the k-th round (same ids, names and canonical inputs — or, for a call Layer 4 repaired when it was relayed, the script's input and history's input equal the hashes recorded then); then as the first row. The emitter writes a repaired input back onto the record's block (the script's own kept as `scriptInput`), so a duplicate reply re-sends exactly what was relayed, repaired once. `Math.random` is seeded by the call id; a script that branches on `Date` diverges |+| record lost, source kept, owned by this session, the request answers its LAST round | **replay** (`replay.ts`): the source re-runs in a fresh runtime (when no module is loaded — the first answer after a retire, a poison or a recycle — 5r answers `needs-module` without touching anything, the handler awaits `loadQuickJSModule()`, about 3 ms, and runs 5r once more; 5r itself never awaits) and each batch is answered from history, provided batch k is exactly the k-th round (same ids, names and canonical inputs — or, for a call Layer 4 repaired when it was relayed, the script's input and history's input equal the hashes recorded then); then as the first row. The emitter writes a repaired input back onto the record's block (the script's own kept as `scriptInput`), so a duplicate reply re-sends exactly what was relayed, repaired once. `Math.random` is seeded by the call id; a script that branches on `Date` diverges || record lost (eviction, poisoned module, or a replay that diverged) or none (restart, another account) | `Script failed` "claudish lost this script's state (proxy restart or eviction); the nested tool results it was waiting for follow" + the results, stored as a TOMBSTONE (a minimal record when none) || late results for a settled record | nothing; history renders its output |diff --git a/packages/cli/src/code-mode/replay.ts b/packages/cli/src/code-mode/replay.tsindex cc62e6cb..3c959331 100644--- a/packages/cli/src/code-mode/replay.ts+++ b/packages/cli/src/code-mode/replay.ts@@ -10,7 +10,7 @@* canonical input. Only then are that round's tool_results fed in. A script is* deterministic enough for this: `Math.random` is seeded by its exec call id;* `Date` is not, and a script that branches on it mismatches. Any mismatch, or- * no loaded sandbox module (this step is synchronous and never loads one),+ * no loaded sandbox module (synchronous, never loads one; 5r asks its caller to load one first: `needs-module`),* leaves the record lost and the caller takes the lost path.** The record is only ever replayed by its OWNER session (the caller checks).diff --git a/packages/cli/src/code-mode/resume.ts b/packages/cli/src/code-mode/resume.tsindex 0f2361fe..819ecace 100644--- a/packages/cli/src/code-mode/resume.ts+++ b/packages/cli/src/code-mode/resume.ts@@ -55,6 +55,7 @@ import type { ExecOutput, OutputPart } from "./output.js";import type { CodeModeSetting } from "./policy.js";import { nestedBlocksFor, settleDone, suspendBlocked } from "./relay.js";import { replayLostScript } from "./replay.js";+import { currentQuickJSModule } from "./sandbox/quickjs-loader.js";import type { NestedResult } from "./sandbox/script-runtime.js";import type { ExecRecord, ScriptStore } from "./script-store.js";import type { CodeModeStores } from "./stores.js";@@ -75,7 +76,14 @@ export type ResumeOutcome =/** A script resolved or ended: the request continues to the upstream turn. */| { kind: "continue" }/** A script blocked again: answer with these tool_use blocks, no upstream call. */- | { kind: "reply"; blocks: [NestedToolUse, ...NestedToolUse[]] };+ | { kind: "reply"; blocks: [NestedToolUse, ...NestedToolUse[]] }+ /**+ * Only with `mayRequestModule`: a lost script this request could replay, and+ * no sandbox module is loaded (a retired, poisoned or recycled one was+ * dropped). Nothing was touched; the caller awaits `loadQuickJSModule()` and+ * calls 5r again without `mayRequestModule`, so 5r itself never awaits.+ */+ | { kind: "needs-module" };export interface ResumeOptions {/** The resolved code-mode setting; `off` turns matching suspended records lost. */@@ -86,6 +94,8 @@ export interface ResumeOptions {* tombstone is stored before 5d builds the input. Default: never create.*/createStores?: () => CodeModeStores;+ /** May answer `needs-module` (see ResumeOutcome). Default false: replay without a module tombstones. */+ mayRequestModule?: boolean;}/** True when the last message is a user message carrying a tool_result for a nested id. */@@ -575,6 +585,26 @@ class Resume {}}+ /**+ * True when the last message answers a script this session owns whose+ * runtime is gone but whose source is kept — the case `run()` replays.+ * Read-only (`peek`, no transition), so a `needs-module` answer touches+ * nothing.+ */+ wouldReplay(): boolean {+ const { groups } = this.lastMessageResults();+ for (const execKey of groups.keys()) {+ const record = this.scripts.peek(this.view.accountKey, execKey);+ if (!record || record.sessionKey !== this.view.sessionKey) continue;+ if (!record.source || record.batches.length === 0) continue;+ const runtimeGone =+ record.state === "lost" ||+ (record.state === "suspended" && (!record.runtime || !record.runtime.alive));+ if (runtimeGone) return true;+ }+ return false;+ }+/** Setting `off`: every suspended record the last message answers is lost (runtime disposed). */loseAnswered(): void {const { groups } = this.lastMessageResults();@@ -639,6 +669,10 @@ export function resumeFromToolResults(resume.loseAnswered();return { kind: "none" };}+ if (opts.mayRequestModule && !currentQuickJSModule() && resume.wouldReplay()) {+ log("[CodeMode] a lost script can replay but no sandbox module is loaded; loading one first");+ return { kind: "needs-module" };+ }return resume.run();} catch (err) {log(`[CodeMode] resume step failed; continuing without it: ${err}`);diff --git a/packages/cli/src/handlers/composed-handler.ts b/packages/cli/src/handlers/composed-handler.tsindex 4742b148..3a570576 100644--- a/packages/cli/src/handlers/composed-handler.ts+++ b/packages/cli/src/handlers/composed-handler.ts@@ -49,6 +49,7 @@ import {withoutLiteHeader,} from "../code-mode/request.js";import { resumeFromToolResults } from "../code-mode/resume.js";+import { loadQuickJSModule } from "../code-mode/sandbox/quickjs-loader.js";import { getCodeModeStores, peekCodeModeStores } from "../code-mode/stores.js";import {getLogLevel,@@ -1449,16 +1450,26 @@ export class ComposedHandler implements ModelHandler {// last message answers nested ids — the first request after a restart —// so the lost script's tombstone exists before 5d builds the input.if (this.provider.name === "openai-codex") {- const resumed = resumeFromToolResults(- claudeRequest,- binding,- peekCodeModeStores(),- claudeRequest?.tool_choice,- {- setting: this.options.codeMode ?? DEFAULT_CODE_MODE_SETTING,- createStores: getCodeModeStores,- }- );+ const resume = (mayRequestModule: boolean) =>+ resumeFromToolResults(+ claudeRequest,+ binding,+ peekCodeModeStores(),+ claudeRequest?.tool_choice,+ {+ setting: this.options.codeMode ?? DEFAULT_CODE_MODE_SETTING,+ createStores: getCodeModeStores,+ mayRequestModule,+ }+ );+ let resumed = resume(true);+ if (resumed.kind === "needs-module") {+ // A lost script can replay, but its module was dropped (retired,+ // poisoned, recycled). 5r never awaits: load here, then run 5r once+ // more — never a third time, so a failed load ends in the tombstone.+ await loadQuickJSModule();+ resumed = resume(false);+ }if (resumed.kind === "reply") {const sse = createSyntheticToolUseReply(resumed.blocks, {modelName: this.bareModelName,