xonecas.io
64875
Mc

mini-coder / commit 7dd4a2d

fix(stream): stabilize tool-call id mapping across providers

xonecas2026-03-14 7dd4a2d6fdd05c111ab52821f5874e6e51489305 parent 5cf366a

2 files changed

src/llm-api/turn-execution.test.ts+56−0
@@ -0,0 +1,56 @@
1+import { describe, expect, test } from "bun:test";
2+import { mapFullStreamToTurnEvents } from "./turn-execution.ts";
3+import type { TurnEvent } from "./types.ts";
4+
5+function chunksFrom(
6+ chunks: Array<{ type?: string; [key: string]: unknown }>,
7+): AsyncIterable<{ type?: string; [key: string]: unknown }> {
8+ return (async function* () {
9+ for (const chunk of chunks) {
10+ yield chunk;
11+ }
12+ })();
13+}
14+
15+async function collectEvents(
16+ chunks: Array<{ type?: string; [key: string]: unknown }>,
17+): Promise<TurnEvent[]> {
18+ const events: TurnEvent[] = [];
19+ for await (const event of mapFullStreamToTurnEvents(chunksFrom(chunks), {})) {
20+ events.push(event);
21+ }
22+ return events;
23+}
24+
25+describe("mapFullStreamToTurnEvents", () => {
26+ test("synthesizes missing toolCallId and reuses it for matching result", async () => {
27+ const events = await collectEvents([
28+ { type: "tool-call", toolName: "read", input: { path: "a.ts" } },
29+ { type: "tool-result", toolName: "read", output: { ok: true } },
30+ ]);
31+
32+ expect(events).toHaveLength(2);
33+ expect(events[0]).toMatchObject({
34+ type: "tool-call-start",
35+ toolName: "read",
36+ });
37+ expect(events[1]).toMatchObject({ type: "tool-result", toolName: "read" });
38+
39+ const start = events[0] as Extract<TurnEvent, { type: "tool-call-start" }>;
40+ const result = events[1] as Extract<TurnEvent, { type: "tool-result" }>;
41+
42+ expect(start.toolCallId).toMatch(/^synthetic-tool-call-\d+$/);
43+ expect(result.toolCallId).toBe(start.toolCallId);
44+ });
45+
46+ test("uses explicit tool call id when result id is missing", async () => {
47+ const events = await collectEvents([
48+ { type: "tool-call", toolCallId: "call-1", toolName: "shell", input: {} },
49+ { type: "tool-result", toolName: "shell", output: "done" },
50+ ]);
51+
52+ expect(events).toHaveLength(2);
53+ const result = events[1] as Extract<TurnEvent, { type: "tool-result" }>;
54+ expect(result.toolCallId).toBe("call-1");
55+ });
56+});
src/llm-api/turn-execution.ts+86−1
@@ -99,13 +99,98 @@ export function createTurnStepTracker(opts: {
9999 };
100100 }
101101
102+interface StreamToolChunk {
103+ type?: string;
104+ toolName?: unknown;
105+ toolCallId?: unknown;
106+ [key: string]: unknown;
107+}
108+
109+const TOOL_START_CHUNK_TYPES = new Set(["tool-input-start", "tool-call"]);
110+const TOOL_RESULT_CHUNK_TYPES = new Set(["tool-result", "tool-error"]);
111+
112+function normalizeToolCallId(raw: unknown): string | null {
113+ if (typeof raw !== "string") return null;
114+ const trimmed = raw.trim();
115+ return trimmed ? trimmed : null;
116+}
117+
118+function normalizeToolName(raw: unknown): string {
119+ if (typeof raw !== "string") return "tool";
120+ const trimmed = raw.trim();
121+ return trimmed || "tool";
122+}
123+
124+class StreamToolCallTracker {
125+ private syntheticCount = 0;
126+ private pendingByTool = new Map<string, string[]>();
127+
128+ assign(chunk: StreamToolChunk): StreamToolChunk {
129+ const type = chunk.type;
130+ if (!type) return chunk;
131+
132+ if (TOOL_START_CHUNK_TYPES.has(type)) {
133+ const toolName = normalizeToolName(chunk.toolName);
134+ const toolCallId =
135+ normalizeToolCallId(chunk.toolCallId) ?? this.nextSyntheticToolCallId();
136+ this.trackStart(toolName, toolCallId);
137+ if (toolCallId === chunk.toolCallId) return chunk;
138+ return { ...chunk, toolCallId };
139+ }
140+
141+ if (TOOL_RESULT_CHUNK_TYPES.has(type)) {
142+ const toolName = normalizeToolName(chunk.toolName);
143+ const existingToolCallId = normalizeToolCallId(chunk.toolCallId);
144+ if (existingToolCallId) {
145+ this.consumeTracked(toolName, existingToolCallId);
146+ return chunk;
147+ }
148+ const toolCallId =
149+ this.consumeNextTracked(toolName) ?? this.nextSyntheticToolCallId();
150+ return { ...chunk, toolCallId };
151+ }
152+
153+ return chunk;
154+ }
155+
156+ private nextSyntheticToolCallId(): string {
157+ this.syntheticCount += 1;
158+ return `synthetic-tool-call-${this.syntheticCount}`;
159+ }
160+
161+ private trackStart(toolName: string, toolCallId: string): void {
162+ const pending = this.pendingByTool.get(toolName) ?? [];
163+ pending.push(toolCallId);
164+ this.pendingByTool.set(toolName, pending);
165+ }
166+
167+ private consumeTracked(toolName: string, toolCallId: string): void {
168+ const pending = this.pendingByTool.get(toolName);
169+ if (!pending || pending.length === 0) return;
170+ const idx = pending.indexOf(toolCallId);
171+ if (idx === -1) return;
172+ pending.splice(idx, 1);
173+ if (pending.length === 0) this.pendingByTool.delete(toolName);
174+ }
175+
176+ private consumeNextTracked(toolName: string): string | null {
177+ const pending = this.pendingByTool.get(toolName);
178+ if (!pending || pending.length === 0) return null;
179+ const toolCallId = pending.shift() ?? null;
180+ if (pending.length === 0) this.pendingByTool.delete(toolName);
181+ return toolCallId;
182+ }
183+}
184+
102185 export async function* mapFullStreamToTurnEvents(
103186 stream: AsyncIterable<{ type?: string; [key: string]: unknown }>,
104187 opts: {
105188 onChunk?: (chunk: { type?: string; [key: string]: unknown }) => void;
106189 },
107190 ): AsyncGenerator<TurnEvent> {
108- for await (const chunk of stream) {
191+ const toolCallTracker = new StreamToolCallTracker();
192+ for await (const originalChunk of stream) {
193+ const chunk = toolCallTracker.assign(originalChunk);
109194 if (shouldLogStreamChunk(chunk)) {
110195 opts.onChunk?.(chunk);
111196 }