Skip to content

Use Claude Code with your ChatGPT, Kimi, Cursor or Grok subscription via a local Anthropic-compatible proxy

Rust

repair stalled codex read calls

Raine Virta467549f0eac8
diff --git a/src/providers/codex/translate/reducer.test.ts b/src/providers/codex/translate/reducer.test.ts
index a529431..894e451 100644
--- a/src/providers/codex/translate/reducer.test.ts
+++ b/src/providers/codex/translate/reducer.test.ts
@@ -86,6 +86,47 @@ describe("reduceUpstream finish metadata", () => {
});
});
+ it("repairs whitespace-stalled Read function call arguments", async () => {
+ const out = await events([
+ sse("response.output_item.added", {
+ output_index: 0,
+ item: { type: "function_call", call_id: "call_1", name: "Read" },
+ }),
+ sse("response.function_call_arguments.delta", {
+ output_index: 0,
+ delta: '{"file_path":"/tmp/a","limit":2200',
+ }),
+ sse("response.function_call_arguments.delta", {
+ output_index: 0,
+ delta: " ".repeat(1024),
+ }),
+ ]);
+
+ expect(out).toContainEqual({
+ kind: "tool-delta",
+ index: 0,
+ partialJson: '{"file_path":"/tmp/a","limit":2200}',
+ });
+ expect(out).toContainEqual({ kind: "tool-stop", index: 0 });
+ expect(out.at(-1)).toEqual({
+ kind: "finish",
+ stopReason: "tool_use",
+ terminalType: "response.incomplete",
+ continuationEligible: false,
+ usage: undefined,
+ webSearchRequests: 0,
+ responseId: undefined,
+ outputItems: [
+ {
+ type: "function_call",
+ call_id: "call_1",
+ name: "Read",
+ arguments: '{"file_path":"/tmp/a","limit":2200}',
+ },
+ ],
+ });
+ });
+
it("treats hosted web search response events as progress", async () => {
const out = await events([
sse("response.output_item.added", {
diff --git a/src/providers/codex/translate/reducer.ts b/src/providers/codex/translate/reducer.ts
index 73e125d..62f86c8 100644
--- a/src/providers/codex/translate/reducer.ts
+++ b/src/providers/codex/translate/reducer.ts
@@ -76,6 +76,7 @@ const BUFFERED_TOOL_PROGRESS_LOG_INTERVAL_MS = 30_000;
const BUFFERED_TOOL_LARGE_ARGS_BYTES = 1_000_000;
const BUFFERED_TOOL_MAX_ARGS_BYTES = 5_000_000;
const BUFFERED_TOOL_MAX_DURATION_MS = 120_000;
+const BUFFERED_READ_REPAIR_TRAILING_WHITESPACE_BYTES = 1_024;
function shouldBufferToolArgs(name: string): boolean {
return name === "Read";
@@ -129,6 +130,61 @@ function toolArgJsonState(args: string): Record<string, unknown> {
}
}
+function parseReadArgsCandidate(args: string): string | undefined {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(args);
+ } catch {
+ return undefined;
+ }
+ if (!isValidReadArgs(parsed)) return undefined;
+ return sanitizeToolArgs("Read", JSON.stringify(parsed));
+}
+
+function isValidReadArgs(value: unknown): value is Record<string, unknown> {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
+ const allowed = new Set(["file_path", "offset", "limit", "pages"]);
+ for (const key of Object.keys(value)) {
+ if (!allowed.has(key)) return false;
+ }
+ const args = value as Record<string, unknown>;
+ if (typeof args.file_path !== "string" || !args.file_path) return false;
+ if (
+ args.offset !== undefined &&
+ (!Number.isSafeInteger(args.offset) || (args.offset as number) < 0)
+ )
+ return false;
+ if (
+ args.limit !== undefined &&
+ (!Number.isSafeInteger(args.limit) || (args.limit as number) <= 0)
+ )
+ return false;
+ if (args.pages !== undefined && typeof args.pages !== "string") return false;
+ return true;
+}
+
+function repairWhitespaceStalledReadArgs(log: Logger, state: ToolState): string | undefined {
+ if (!state.bufferUntilDone || state.name !== "Read") return undefined;
+ const trimmed = state.argsAccum.trimEnd();
+ const trailingWhitespace = state.argsAccum.length - trimmed.length;
+ if (trailingWhitespace < BUFFERED_READ_REPAIR_TRAILING_WHITESPACE_BYTES) return undefined;
+
+ const repaired = parseReadArgsCandidate(trimmed) ?? parseReadArgsCandidate(`${trimmed}}`);
+ if (!repaired) return undefined;
+
+ log.warn("repairing whitespace-stalled Read tool arguments", {
+ outputIndex: state.outputIndex,
+ index: state.index,
+ callId: state.callId,
+ name: state.name,
+ deltaCount: state.deltaCount,
+ elapsedMs: Date.now() - state.startedAt,
+ args: toolArgSummary(state.argsAccum),
+ repaired: toolArgJsonState(repaired),
+ });
+ return repaired;
+}
+
function logBufferedToolProgress(log: Logger, state: ToolState, force = false): void {
if (!state.bufferUntilDone) return;
const now = Date.now();
@@ -411,6 +467,30 @@ export async function* reduceUpstream(
state.deltaCount += 1;
state.hadDelta = true;
logBufferedToolProgress(log, state);
+ const repairedArgs = repairWhitespaceStalledReadArgs(log, state);
+ if (repairedArgs) {
+ state.argsAccum = repairedArgs;
+ state.emittedArgs = true;
+ captureOutputItem(p.output_index, state);
+ yield { kind: "tool-delta", index: state.index, partialJson: state.argsAccum };
+ yield { kind: "tool-stop", index: state.index };
+ blocksByOutputIndex.delete(p.output_index);
+ const outputItems = Array.from(outputItemsByIndex.entries())
+ .sort(([a], [b]) => a - b)
+ .map(([, item]) => item);
+ yield {
+ kind: "finish",
+ stopReason: "tool_use",
+ terminalType: "response.incomplete",
+ continuationEligible: false,
+ usage: undefined,
+ webSearchRequests,
+ responseId: undefined,
+ outputItems,
+ };
+ await events.return?.(undefined);
+ return;
+ }
throwIfBufferedToolExceeded(log, state);
if (!state.bufferUntilDone) {
state.emittedArgs = true;
diff --git a/src/providers/codex/translate/stream.test.ts b/src/providers/codex/translate/stream.test.ts
index d4b29fc..8ca65de 100644
--- a/src/providers/codex/translate/stream.test.ts
+++ b/src/providers/codex/translate/stream.test.ts
@@ -132,6 +132,31 @@ describe("translateStream", () => {
expect(output).toContain("event: message_stop");
});
+ it("short-circuits whitespace-stalled Read arguments as a tool use", async () => {
+ const chunks = [
+ sse("response.output_item.added", {
+ output_index: 0,
+ item: { type: "function_call", call_id: "call_read", name: "Read" },
+ }),
+ sse("response.function_call_arguments.delta", {
+ output_index: 0,
+ delta: '{"file_path":"/tmp/a","limit":2200',
+ }),
+ sse("response.function_call_arguments.delta", {
+ output_index: 0,
+ delta: " ".repeat(1024),
+ }),
+ ];
+
+ const output = await collectFromChunks(chunks);
+
+ expect(output).toContain("event: content_block_start");
+ expect(output).toContain('"partial_json":"{\\"file_path\\":\\"/tmp/a\\",\\"limit\\":2200}"');
+ expect(output).toContain('"stop_reason":"tool_use"');
+ expect(output).toContain("event: message_stop");
+ expect(output).not.toContain("event: error");
+ });
+
it("emits keepalive pings for upstream keepalive events", async () => {
const chunks = [
sse("response.output_item.added", {
diff --git a/src/sse.ts b/src/sse.ts
index d054ff4..92c4cb6 100644
--- a/src/sse.ts
+++ b/src/sse.ts
@@ -34,10 +34,14 @@ export async function* parseSseStream(
const reader = body.getReader();
const decoder = new TextDecoder();
let buf = "";
+ let completed = false;
try {
while (true) {
const { value, done } = await reader.read();
- if (done) break;
+ if (done) {
+ completed = true;
+ break;
+ }
stats.bytesRead += value.byteLength;
stats.chunkCount += 1;
stats.lastChunkAt = Date.now();
@@ -62,7 +66,9 @@ export async function* parseSseStream(
yield evt;
}
}
+ completed = true;
} finally {
+ if (!completed) await reader.cancel("SSE parser closed before stream end").catch(() => {});
reader.releaseLock();
}
}