Claude Code. Any Model. The most powerful AI coding agent now speaks every language.
fix(sse): the block writer refuses to re-open an index it already stopped
Jack Rudenko48f1f90d5108
diff --git a/packages/cli/src/handlers/shared/stream-parsers/block-writer.test.ts b/packages/cli/src/handlers/shared/stream-parsers/block-writer.test.tsnew file mode 100644index 00000000..1b5e41ad--- /dev/null+++ b/packages/cli/src/handlers/shared/stream-parsers/block-writer.test.ts@@ -0,0 +1,164 @@+/**+ * The block writer's own contract: an index is spent ONCE.+ *+ * Anthropic's wire identifies a content block by its index for the whole+ * message. Re-opening an index that already had its `content_block_stop` gives+ * the client two different blocks wearing one name — two `content_block_start`+ * frames, two full lifecycles — and makes the tool-observation hook in+ * `openai-sse.ts` count one call twice, against its own comment ("exactly one+ * `content_block_start` is emitted per tool call").+ *+ * THE PRODUCTION CALLER that reaches it: when a tool's argument fragments lose+ * the open block mid-stream (OpenAI's wire lets `tool_calls[0]` and+ * `tool_calls[1]` interleave; Anthropic's does not), `openai-sse.ts` degrades+ * that tool to the buffered path — `started = false; ref = null` — while KEEPING+ * its already-spent `blockIndex`. Finalization then asks for that index again.+ * The sequence below is that exact call order, taken from the two sites rather+ * than imagined.+ *+ * ## Provenance of the inputs+ *+ * These are calls on this tree's own function, not a provider's bytes. No `.sse`+ * fixture was invented to reach the degrade path: no capture in+ * `test-fixtures/sse-responses/` interleaves two unbuffered tool calls, and+ * writing one that did would be inventing the capture. The capture-driven gate+ * is `block-nesting.test.ts`, whose `nestingViolations` already reports+ * `index=N started twice` — so the day a real capture with interleaved calls+ * lands, it is covered there for free.+ *+ * §A.3: the writer must NEVER throw. Every case below asserts it corrected the+ * state and carried on.+ */++import { describe, expect, test } from "bun:test";+import { createBlockWriter } from "./block-writer.js";++interface Frame {+ event: string;+ data: any;+}++function recordingWriter() {+ const frames: Frame[] = [];+ const writer = createBlockWriter((event, data) => frames.push({ event, data }));+ return { writer, frames };+}++/** The same rules `block-nesting.test.ts` applies to a replayed capture. */+function nestingViolations(frames: Frame[]): string[] {+ const problems: string[] = [];+ let open: number | null = null;+ const started = new Set<number>();+ const stopped = new Set<number>();++ frames.forEach(({ event, data }, i) => {+ if (event === "content_block_start") {+ if (open !== null)+ problems.push(`frame ${i}: start index=${data.index} while ${open} is open`);+ if (started.has(data.index)) problems.push(`frame ${i}: index=${data.index} started twice`);+ started.add(data.index);+ open = data.index;+ } else if (event === "content_block_delta") {+ if (open !== data.index) {+ problems.push(`frame ${i}: delta index=${data.index} but open is ${open ?? "none"}`);+ }+ } else if (event === "content_block_stop") {+ if (open !== data.index) {+ problems.push(`frame ${i}: stop index=${data.index} but open is ${open ?? "none"}`);+ }+ if (stopped.has(data.index)) problems.push(`frame ${i}: index=${data.index} stopped twice`);+ stopped.add(data.index);+ open = null;+ }+ });+ if (open !== null) problems.push(`ended with index=${open} still open`);+ return problems;+}++const startIndices = (frames: Frame[]) =>+ frames.filter((f) => f.event === "content_block_start").map((f) => f.data.index);++describe("an index is spent once", () => {+ test("openTool refuses a stopped index and re-indexes instead", () => {+ const { writer, frames } = recordingWriter();++ // Tool 0 opens and streams a partial argument fragment.+ const t0 = writer.openTool({ id: "call_0", name: "Read" });+ expect(t0.index).toBe(0);+ expect(writer.append(t0, '{"file')).toBe(true);++ // Tool 1's fragments interleave. Opening it closes tool 0's block — index 0+ // is now spent.+ const t1 = writer.openTool({ id: "call_1", name: "Read" });+ expect(writer.append(t1, '{"file_path":"b"}')).toBe(true);++ // The rest of tool 0's arguments arrive. Its block is gone, so the append+ // is refused and the caller degrades it to the buffered path — keeping the+ // index it already spent.+ expect(writer.append(t0, '_path":"a"}')).toBe(false);++ // Finalization asks for that spent index back. It must NOT be honoured.+ const reopened = writer.openTool({ id: "call_0", name: "Read", index: t0.index });+ expect(reopened.index).not.toBe(t0.index);+ writer.append(reopened, '{"file_path":"a"}');+ writer.close(reopened);++ expect(nestingViolations(frames)).toEqual([]);+ expect(startIndices(frames)).toEqual([0, 1, 2]);+ });++ test("openText refuses a stopped index the same way", () => {+ // The validation-failure path spends a buffered tool's reserved index on a+ // `⚠️` text block. If that index has already carried a block, the warning+ // must not reuse it.+ const { writer, frames } = recordingWriter();++ const tool = writer.openTool({ id: "call_0", name: "Read" });+ writer.append(tool, "{}");+ writer.closeCurrent();++ const text = writer.openText({ index: tool.index });+ expect(text.index).not.toBe(tool.index);+ writer.append(text, "⚠️");+ writer.close(text);++ expect(nestingViolations(frames)).toEqual([]);+ expect(startIndices(frames)).toEqual([0, 1]);+ });++ test("the writer corrects and continues — it never throws", () => {+ const { writer } = recordingWriter();+ const tool = writer.openTool({ id: "call_0", name: "Read" });+ writer.closeCurrent();++ expect(() => writer.openTool({ id: "call_0", name: "Read", index: tool.index })).not.toThrow();+ expect(() => writer.openText({ index: tool.index })).not.toThrow();+ // …and the superseded ref is still safe to close, as it always was.+ expect(() => writer.close(tool)).not.toThrow();+ });+});++describe("a reserved index that was never opened is still honoured", () => {+ test("reserve() then openTool(index) spends exactly the reserved slot", () => {+ // The non-regression half: a buffered tool reserves its index when its name+ // arrives and emits at finish_reason time. Nothing was stopped there, so the+ // reservation must be kept — otherwise the fix above silently re-orders+ // every buffered tool call.+ const { writer, frames } = recordingWriter();++ const reserved = writer.reserve();+ expect(reserved).toBe(0);++ const text = writer.openText();+ expect(text.index).toBe(1);+ writer.append(text, "Let me read that file.");++ const tool = writer.openTool({ id: "call_0", name: "Read", index: reserved });+ expect(tool.index).toBe(reserved);+ writer.append(tool, '{"file_path":"a"}');+ writer.close(tool);++ expect(nestingViolations(frames)).toEqual([]);+ expect(startIndices(frames)).toEqual([1, 0]);+ });+});diff --git a/packages/cli/src/handlers/shared/stream-parsers/block-writer.ts b/packages/cli/src/handlers/shared/stream-parsers/block-writer.tsindex c76852d0..26bfbb96 100644--- a/packages/cli/src/handlers/shared/stream-parsers/block-writer.ts+++ b/packages/cli/src/handlers/shared/stream-parsers/block-writer.ts@@ -63,7 +63,8 @@ export interface BlockWriter {** `index` is honoured only when no text block is already open — the* validation-failure path reserves a buffered tool's index and then spends it- * on a `⚠️` text block instead.+ * on a `⚠️` text block instead — and only when that index has not already+ * been stopped (see `openTool`).*/openText(opts?: { index?: number }): BlockRef;@@ -75,7 +76,10 @@ export interface BlockWriter {* are two blocks, which is what the repair path needs.** `index` is supplied when the index was reserved earlier — a buffered tool- * reserves at the moment its name arrives and emits at finish_reason time.+ * reserves at the moment its name arrives and emits at finish_reason time. A+ * requested index that has ALREADY been stopped is refused and a fresh one is+ * allocated instead: an index names a block for the whole message, so+ * re-opening a spent one gives the client two blocks under one name.*/openTool(opts: { id: string; name: string; index?: number }): BlockRef;@@ -126,6 +130,37 @@ export function createBlockWriter(send: SendFn): BlockWriter {const describe = (ref: BlockRef | null) => (ref ? `${ref.kind}@${ref.index}` : "none");+ /**+ * A requested index, or a fresh one when that index has already been stopped.+ *+ * AN INDEX IS SPENT ONCE. Anthropic's wire identifies a content block by its+ * index for the whole message, so re-opening one that already had its+ * `content_block_stop` gives the client two different blocks wearing one name:+ * two `content_block_start`s, two lifecycles, and a renderer that has to guess+ * which deltas belong to which. The tool-observation hook counts the call+ * twice as well — its own comment rests on "exactly one+ * `content_block_start` is emitted per tool call".+ *+ * `openai-sse.ts` reaches this: when a tool's fragments lose the open block+ * mid-arguments it degrades that tool to the buffered path+ * (`started = false; ref = null`) while KEEPING `blockIndex`, and+ * finalization then re-opens that spent index. Reachable with no tool+ * schemas and two interleaved unbuffered calls.+ *+ * Correct, log, continue — never throw (see the header). A fresh index costs+ * a gap in the sequence, which is cosmetic; the alternatives are a corrupt+ * stream or a silently truncated HTTP 200.+ */+ const spendableIndex = (requested: number | undefined, kind: BlockKind): number => {+ if (requested === undefined) return nextIndex++;+ if (!stopped.has(requested)) return requested;+ const replacement = nextIndex++;+ log(+ `[BlockWriter] open error: index ${requested} was already stopped; ${kind} block re-indexed to ${replacement}`+ );+ return replacement;+ };+const closeCurrent = (): void => {if (!openRef) return;send("content_block_stop", { type: "content_block_stop", index: openRef.index });@@ -158,7 +193,7 @@ export function createBlockWriter(send: SendFn): BlockWriter {return openRef;}closeCurrent();- const index = opts?.index ?? nextIndex++;+ const index = spendableIndex(opts?.index, "text");return start({ index, kind: "text" }, { type: "text", text: "" });},@@ -170,7 +205,11 @@ export function createBlockWriter(send: SendFn): BlockWriter {openTool({ id, name, index }) {closeCurrent();- const ref: BlockRef = { index: index ?? nextIndex++, kind: "tool_use", toolId: id };+ const ref: BlockRef = {+ index: spendableIndex(index, "tool_use"),+ kind: "tool_use",+ toolId: id,+ };// `input: {}` is part of Anthropic's `content_block_start` for a tool_use:// the block opens with an EMPTY input object, which the `input_json_delta`// frames then fill in. Omitting it leaves the client with a tool_use block