Skip to content

Claude Code. Any Model. The most powerful AI coding agent now speaks every language.

fix(openai-codex): replay a script whose relayed calls Layer 4 repaired

Jack Rudenko0cc643c37956
diff --git a/ai-docs/architecture/code-mode.md b/ai-docs/architecture/code-mode.md
index 6103f0f5..4733bbe2 100644
--- a/ai-docs/architecture/code-mode.md
+++ b/ai-docs/architecture/code-mode.md
@@ -189,7 +189,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); then as the first row. `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 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/hashes.ts b/packages/cli/src/code-mode/hashes.ts
index a10556a8..16c1ab76 100644
--- a/packages/cli/src/code-mode/hashes.ts
+++ b/packages/cli/src/code-mode/hashes.ts
@@ -40,6 +40,13 @@ export function canonicalJson(value: unknown): string {
return `{${body}}`;
}
+/** sha256 hex of a tool input's canonical JSON. */
+export function inputHash(input: unknown): string {
+ return createHash("sha256")
+ .update(canonicalJson(input ?? {}))
+ .digest("hex");
+}
+
/** Nested-call order: by decoded seq, then by id for anything that does not decode. */
function compareIds(a: string, b: string): number {
const da = decodeNestedId(a);
diff --git a/packages/cli/src/code-mode/replay.ts b/packages/cli/src/code-mode/replay.ts
index 3c515659..cc62e6cb 100644
--- a/packages/cli/src/code-mode/replay.ts
+++ b/packages/cli/src/code-mode/replay.ts
@@ -18,7 +18,13 @@
import { log } from "../logger.js";
import { type ClaudeToolLike, renderExecTool } from "./exec-tool.js";
-import { type BatchResultEntry, batchHash, canonicalJson, completionKey } from "./hashes.js";
+import {
+ type BatchResultEntry,
+ batchHash,
+ canonicalJson,
+ completionKey,
+ inputHash,
+} from "./hashes.js";
import { decodeNestedId, encodeNestedId } from "./ids.js";
import type { ExecOutput } from "./output.js";
import { nestedBlocksFor, settleDone, suspendBlocked } from "./relay.js";
@@ -30,7 +36,7 @@ import {
type ScriptStep,
createScriptRuntime,
} from "./sandbox/script-runtime.js";
-import type { ExecRecord, ExecState, ScriptStore } from "./script-store.js";
+import type { ExecBatch, ExecRecord, ExecState, ScriptStore } from "./script-store.js";
import { nestedResultFromToolResult } from "./tool-results.js";
import type { ClaudeContentBlock, NestedToolUse } from "./types.js";
@@ -87,16 +93,28 @@ function entriesOf(
});
}
-/** The batch the script blocked on is exactly this history round. */
-function matchesRound(execKey: string, calls: readonly NestedCall[], round: HistoryRound): boolean {
+/**
+ * The batch the script blocked on is exactly this history round: the same
+ * ids and names, and each input either equal to history's or the one Layer 4
+ * repaired into history's (`repairs`, recorded when the batch was relayed).
+ */
+function matchesRound(
+ execKey: string,
+ calls: readonly NestedCall[],
+ round: HistoryRound,
+ repairs: ExecBatch["repairs"]
+): boolean {
if (calls.length !== round.blocks.length) return false;
return calls.every((call) => {
const id = encodeNestedId(execKey, call.seq);
const block = round.blocks.find((b) => b.id === id);
+ if (block === undefined || block.name !== call.name) return false;
+ if (canonicalJson(block.input ?? {}) === canonicalJson(call.input)) return true;
+ const repair = repairs?.[id];
return (
- block !== undefined &&
- block.name === call.name &&
- canonicalJson(block.input ?? {}) === canonicalJson(call.input)
+ repair !== undefined &&
+ repair.script === inputHash(call.input) &&
+ repair.relayed === inputHash(block.input)
);
});
}
@@ -127,7 +145,8 @@ function runRounds(
let step = runtime.start(record.source);
const hashes: string[] = [];
for (const [k, round] of rounds.entries()) {
- if (step.kind !== "blocked" || !matchesRound(record.execCallId, step.calls, round)) {
+ const repairs = record.batches[k]?.repairs;
+ if (step.kind !== "blocked" || !matchesRound(record.execCallId, step.calls, round, repairs)) {
log(`[CodeMode] exec ${record.originalCallId}: replay diverged from history; script lost`);
runtime.dispose();
return { kind: "stopped", result: undefined };
@@ -172,7 +191,11 @@ export function replayLostScript(input: ReplayInput): ReplayResult {
const { step, hashes } = ran;
scripts.transition(record, "replay");
scripts.attachRuntime(record, runtime);
- record.batches = rounds.map((round, k) => ({ ids: round.ids, batchHash: hashes[k] }));
+ record.batches = rounds.map((round, k) => ({
+ ids: round.ids,
+ batchHash: hashes[k],
+ repairs: record.batches[k]?.repairs,
+ }));
if (step.kind === "blocked") {
const blocks = nestedBlocksFor(record.execCallId, step.calls);
suspendBlocked(scripts, record, blocks);
diff --git a/packages/cli/src/code-mode/script-store.ts b/packages/cli/src/code-mode/script-store.ts
index 1903d8a5..df1527ee 100644
--- a/packages/cli/src/code-mode/script-store.ts
+++ b/packages/cli/src/code-mode/script-store.ts
@@ -38,6 +38,7 @@
*/
import { log } from "../logger.js";
+import { inputHash } from "./hashes.js";
import type { ExecOutput } from "./output.js";
import type { ScriptRuntime } from "./sandbox/script-runtime.js";
import type { NestedToolUse, ResponsesItem } from "./types.js";
@@ -102,6 +103,25 @@ export interface ExecBatch {
* inputs are up to 8 MiB a batch and are not in the byte cap).
*/
blocks?: NestedToolUse[];
+ /**
+ * The Layer 4 repairs of this batch, by nested id: hashes of the script's
+ * own input and of the input relayed instead. Taken from `blocks` when they
+ * are dropped, so a replay can accept history's repaired input for a call.
+ */
+ repairs?: Record<string, { script: string; relayed: string }>;
+}
+
+/** Keep a batch's repairs as hashes, then drop its blocks. */
+function compactBatch(batch: ExecBatch): void {
+ for (const block of batch.blocks ?? []) {
+ if (block.scriptInput === undefined) continue;
+ batch.repairs ??= {};
+ batch.repairs[block.id] = {
+ script: inputHash(block.scriptInput),
+ relayed: inputHash(block.input),
+ };
+ }
+ batch.blocks = undefined;
}
export interface ExecRecord {
@@ -326,7 +346,7 @@ export class ScriptStore {
record.state = to;
record.lastTouched = this.now();
const nowLive = isLive(to);
- if (!nowLive) for (const batch of record.batches) batch.blocks = undefined;
+ if (!nowLive) for (const batch of record.batches) compactBatch(batch);
if (wasLive && !nowLive) this.settledBytes += record.bytes;
else if (!wasLive && nowLive) this.settledBytes -= record.bytes;
if (!nowLive) this.enforceCaps();
diff --git a/packages/cli/src/code-mode/types.ts b/packages/cli/src/code-mode/types.ts
index bf1c1d3e..7f061351 100644
--- a/packages/cli/src/code-mode/types.ts
+++ b/packages/cli/src/code-mode/types.ts
@@ -37,7 +37,38 @@ export interface NestedToolUse {
id: string;
/** Claude Code's own tool name. */
name: string;
+ /** The input as relayed to Claude Code (after a Layer 4 repair, when one applied). */
input: Record<string, unknown>;
+ /** The script's own input, set only when Layer 4 repaired what was relayed. */
+ scriptInput?: Record<string, unknown>;
+}
+
+/**
+ * The input JSON Claude Code gets for `block`: `repair` (Layer 4) applied ONCE
+ * to the script's input. A repaired input is written back onto the block — the
+ * exec record holds the same object — with the script's own kept as
+ * `scriptInput`, so a duplicate reply re-sends exactly what was relayed and a
+ * replay can tell a repair from a divergence. A pure function, safe for the
+ * turn driver to import (it loads no sandbox).
+ */
+export function relayNestedInput(
+ block: NestedToolUse,
+ repair: (name: string, argsJson: string) => string
+): string {
+ const args = JSON.stringify(block.input ?? {});
+ if (block.scriptInput !== undefined) return args;
+ const sent = repair(block.name, args);
+ if (sent === args) return args;
+ try {
+ const parsed: unknown = JSON.parse(sent);
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
+ block.scriptInput = block.input;
+ block.input = parsed as Record<string, unknown>;
+ }
+ } catch {
+ // An unparsable repair is sent as it is and not recorded.
+ }
+ return sent;
}
/**
diff --git a/packages/cli/src/handlers/shared/stream-parsers/openai-responses-sse.ts b/packages/cli/src/handlers/shared/stream-parsers/openai-responses-sse.ts
index fdaacb17..dd077b19 100644
--- a/packages/cli/src/handlers/shared/stream-parsers/openai-responses-sse.ts
+++ b/packages/cli/src/handlers/shared/stream-parsers/openai-responses-sse.ts
@@ -11,7 +11,11 @@
*/
import type { Context } from "hono";
-import type { CodeModeTurnHooks } from "../../../code-mode/types.js";
+import {
+ type CodeModeTurnHooks,
+ type NestedToolUse,
+ relayNestedInput,
+} from "../../../code-mode/types.js";
import { wrapAnthropicError } from "../anthropic-error.js";
import type { UsageCacheDetail } from "../token-tracker.js";
import { ClaudeSseSink } from "./responses/claude-sse-sink.js";
@@ -30,7 +34,7 @@ export { resolveStallPolicy, type StallPolicy } from "./responses/stall-guard.js
* request's input and 0 output; nothing was billed, so no usage callback fires.
*/
export function createSyntheticToolUseReply(
- blocks: ReadonlyArray<{ id: string; name: string; input: Record<string, unknown> }>,
+ blocks: ReadonlyArray<NestedToolUse>,
opts: {
modelName: string;
priorInputTokens?: number;
@@ -61,7 +65,7 @@ export function createSyntheticToolUseReply(
try {
sink.start();
for (const block of blocks) {
- sink.emitToolUse(block.id, block.name, repair(block.name, JSON.stringify(block.input)));
+ sink.emitToolUse(block.id, block.name, relayNestedInput(block, repair));
}
sink.endMessage("tool_use", { input_tokens: opts.priorInputTokens ?? 0, output_tokens: 0 });
if (opts.middlewareManager) {
diff --git a/packages/cli/src/handlers/shared/stream-parsers/responses/responses-turn.ts b/packages/cli/src/handlers/shared/stream-parsers/responses/responses-turn.ts
index 14be136c..a5e4d555 100644
--- a/packages/cli/src/handlers/shared/stream-parsers/responses/responses-turn.ts
+++ b/packages/cli/src/handlers/shared/stream-parsers/responses/responses-turn.ts
@@ -86,10 +86,11 @@ function sum(values: number[]): number {
return values.reduce((a, b) => a + b, 0);
}
-import type {
- CodeModeTurnHooks,
- ExecTurnStep,
- ResponsesItem,
+import {
+ type CodeModeTurnHooks,
+ type ExecTurnStep,
+ type ResponsesItem,
+ relayNestedInput,
} from "../../../../code-mode/types.js";
import { log } from "../../../../logger.js";
import type { LegResponse } from "../../responses-leg-issuer.js";
@@ -442,7 +443,7 @@ class ResponsesTurn {
this.sink.emitToolUse(
block.id,
block.name,
- this.repairNested(block.name, JSON.stringify(block.input ?? {}))
+ relayNestedInput(block, (name, args) => this.repairNested(name, args))
);
}
log(`[ResponsesTurn] exec ${outcome.callId} relayed as ${blocks.length} tool_use block(s)`);