diff --git a/src/backend/controllers/puterai/sse.test.ts b/src/backend/controllers/puterai/sse.test.ts index 78afff1d8..a0f86cd8f 100644 --- a/src/backend/controllers/puterai/sse.test.ts +++ b/src/backend/controllers/puterai/sse.test.ts @@ -271,6 +271,174 @@ describe('AnthropicSseWriter', () => { expect(stops.map((e) => (e.data as { index: number }).index)).toEqual([0, 1]); }); + /** Each tool_use block's id and joined input, checking blocks never overlap. */ + const toolBlocks = (written: string[]) => { + const blocks: { id: string; json: string }[] = []; + let open: number | null = null; + for (const { event, data } of events(written)) { + const d = data as { + index: number; + content_block?: { type: string; id: string }; + delta?: { partial_json?: string }; + }; + if (event === 'content_block_start') { + expect(open).toBeNull(); + open = d.index; + if (d.content_block?.type === 'tool_use') { + blocks[d.index] = { id: d.content_block.id, json: '' }; + } + } else if (event === 'content_block_delta') { + expect(d.index).toBe(open); + if (blocks[d.index]) { + blocks[d.index]!.json += d.delta?.partial_json ?? ''; + } + } else if (event === 'content_block_stop') { + expect(d.index).toBe(open); + open = null; + } + } + return blocks.filter(Boolean); + }; + + it('keeps the pieces of a call that arrive after the next call starts', () => { + const { writer, written } = newWriter(); + writer.start(); + writer.onChunk({ type: 'tool_use_start', id: 'tu_a', name: 'Read' }); + writer.onChunk({ type: 'tool_input_delta', id: 'tu_a', partialJson: '{"x":' }); + writer.onChunk({ type: 'tool_use_start', id: 'tu_b', name: 'Grep' }); + writer.onChunk({ type: 'tool_input_delta', id: 'tu_b', partialJson: '{"y":' }); + writer.onChunk({ type: 'tool_input_delta', id: 'tu_a', partialJson: '1}' }); + writer.onChunk({ type: 'tool_input_delta', id: 'tu_b', partialJson: '2}' }); + writer.onChunk({ type: 'tool_use', id: 'tu_a', name: 'Read', input: { x: 1 } }); + writer.onChunk({ type: 'tool_use', id: 'tu_b', name: 'Grep', input: { y: 2 } }); + writer.onChunk({ type: 'usage', usageDetails: {} }); + + expect(toolBlocks(written)).toEqual([ + { id: 'tu_a', json: '{"x":1}' }, + { id: 'tu_b', json: '{"y":2}' }, + ]); + expect( + events(written).find((e) => e.event === 'message_delta')!.data, + ).toMatchObject({ delta: { stop_reason: 'tool_use' } }); + }); + + it('writes a call that ends while another call is still open', () => { + const { writer, written } = newWriter(); + writer.start(); + writer.onChunk({ type: 'tool_use_start', id: 'tu_a', name: 'Read' }); + writer.onChunk({ type: 'tool_input_delta', id: 'tu_a', partialJson: '{"x":' }); + writer.onChunk({ type: 'tool_use_start', id: 'tu_b', name: 'Grep' }); + writer.onChunk({ type: 'tool_input_delta', id: 'tu_b', partialJson: '{"y":2}' }); + writer.onChunk({ type: 'tool_use', id: 'tu_b', name: 'Grep', input: { y: 2 } }); + writer.onChunk({ type: 'tool_input_delta', id: 'tu_a', partialJson: '1}' }); + writer.onChunk({ type: 'tool_use', id: 'tu_a', name: 'Read', input: { x: 1 } }); + writer.onChunk({ type: 'usage', usageDetails: {} }); + + expect(toolBlocks(written)).toEqual([ + { id: 'tu_a', json: '{"x":1}' }, + { id: 'tu_b', json: '{"y":2}' }, + ]); + }); + + it('writes a waiting call before the message ends, even without its tool_use', () => { + const { writer, written } = newWriter(); + writer.start(); + writer.onChunk({ type: 'tool_use_start', id: 'tu_a', name: 'Read' }); + writer.onChunk({ type: 'tool_use_start', id: 'tu_b', name: 'Grep' }); + writer.onChunk({ type: 'tool_input_delta', id: 'tu_b', partialJson: '{"y":2}' }); + writer.onChunk({ type: 'tool_input_delta', id: 'tu_a', partialJson: '{}' }); + writer.onChunk({ type: 'usage', usageDetails: {} }); + + expect(toolBlocks(written)).toEqual([ + { id: 'tu_a', json: '{}' }, + { id: 'tu_b', json: '{"y":2}' }, + ]); + }); + + it('streams the next call live once the open call has its whole input', () => { + const { writer, written } = newWriter(); + writer.start(); + writer.onChunk({ type: 'tool_use_start', id: 'tu_a', name: 'Read' }); + writer.onChunk({ type: 'tool_input_delta', id: 'tu_a', partialJson: '{"x":1}' }); + writer.onChunk({ type: 'tool_use_start', id: 'tu_b', name: 'Grep' }); + writer.onChunk({ type: 'tool_input_delta', id: 'tu_b', partialJson: '{"y":2}' }); + + // The driver holds every tool_use until the upstream ends; B is live before that. + expect(toolBlocks(written)).toEqual([ + { id: 'tu_a', json: '{"x":1}' }, + { id: 'tu_b', json: '{"y":2}' }, + ]); + }); + + it('streams a waiting call live after its pieces so far are written', () => { + const { writer, written } = newWriter(); + writer.start(); + writer.onChunk({ type: 'tool_use_start', id: 'tu_a', name: 'Read' }); + writer.onChunk({ type: 'tool_input_delta', id: 'tu_a', partialJson: '{"x":' }); + writer.onChunk({ type: 'tool_use_start', id: 'tu_b', name: 'Grep' }); + writer.onChunk({ type: 'tool_input_delta', id: 'tu_b', partialJson: '{"y":' }); + writer.onChunk({ type: 'tool_input_delta', id: 'tu_a', partialJson: '1}' }); + writer.onChunk({ type: 'tool_use', id: 'tu_a', name: 'Read', input: { x: 1 } }); + writer.onChunk({ type: 'tool_input_delta', id: 'tu_b', partialJson: '2}' }); + writer.onChunk({ type: 'tool_use', id: 'tu_b', name: 'Grep', input: { y: 2 } }); + writer.onChunk({ type: 'usage', usageDetails: {} }); + + expect(toolBlocks(written)).toEqual([ + { id: 'tu_a', json: '{"x":1}' }, + { id: 'tu_b', json: '{"y":2}' }, + ]); + }); + + it.each([undefined, ''])('keeps calls apart when their ids are %j', (id) => { + const { writer, written } = newWriter(); + writer.start(); + writer.onChunk({ type: 'tool_use_start', id, name: 'Read' }); + writer.onChunk({ type: 'tool_input_delta', id, partialJson: '{"a":' }); + writer.onChunk({ type: 'tool_input_delta', id, partialJson: '1}' }); + writer.onChunk({ type: 'tool_use_start', id, name: 'Grep' }); + writer.onChunk({ type: 'tool_input_delta', id, partialJson: '{"b":2}' }); + writer.onChunk({ type: 'tool_use', id, name: 'Read', input: { a: 1 } }); + writer.onChunk({ type: 'tool_use', id, name: 'Grep', input: { b: 2 } }); + writer.onChunk({ type: 'usage', usageDetails: {} }); + + expect(toolBlocks(written).map((block) => block.json)).toEqual([ + '{"a":1}', + '{"b":2}', + ]); + }); + + it('queues a whole tool_use behind an open call instead of cutting it short', () => { + const { writer, written } = newWriter(); + writer.start(); + writer.onChunk({ type: 'tool_use_start', id: 'tu_a', name: 'Read' }); + writer.onChunk({ type: 'tool_input_delta', id: 'tu_a', partialJson: '{"x":' }); + writer.onChunk({ type: 'tool_use', id: 'tu_d', name: 'Grep', input: { d: 4 } }); + writer.onChunk({ type: 'tool_input_delta', id: 'tu_a', partialJson: '1}' }); + writer.onChunk({ type: 'tool_use', id: 'tu_a', name: 'Read', input: { x: 1 } }); + writer.onChunk({ type: 'usage', usageDetails: {} }); + + expect(toolBlocks(written)).toEqual([ + { id: 'tu_a', json: '{"x":1}' }, + { id: 'tu_d', json: '{"d":4}' }, + ]); + }); + + it('writes waiting calls when the open call ends after another block closed it', () => { + const { writer, written } = newWriter(); + writer.start(); + writer.onChunk({ type: 'tool_use_start', id: 'tu_a', name: 'Read' }); + writer.onChunk({ type: 'tool_input_delta', id: 'tu_a', partialJson: '{"x":' }); + writer.onChunk({ type: 'tool_use_start', id: 'tu_b', name: 'Grep' }); + writer.onChunk({ type: 'tool_input_delta', id: 'tu_b', partialJson: '{"y":2}' }); + writer.onChunk({ type: 'text', text: 'checking' }); + writer.onChunk({ type: 'tool_use', id: 'tu_a', name: 'Read', input: { x: 1 } }); + + expect(toolBlocks(written).map((block) => block.id)).toEqual([ + 'tu_a', + 'tu_b', + ]); + }); + it('tool_use single-shot (no prior start): one content_block_start/delta/stop', () => { const { writer, written } = newWriter(); writer.start(); diff --git a/src/backend/controllers/puterai/sse.ts b/src/backend/controllers/puterai/sse.ts index f0a9251d9..d9a887c93 100644 --- a/src/backend/controllers/puterai/sse.ts +++ b/src/backend/controllers/puterai/sse.ts @@ -110,6 +110,15 @@ const STREAM_ERROR_TYPES: Record = { const jsonOf = (value: unknown): string => typeof value === 'string' ? value : JSON.stringify(value ?? {}); +const isCompleteJson = (text: string): boolean => { + try { + JSON.parse(text); + return true; + } catch { + return false; + } +}; + type OpenBlockKind = | 'text' | 'thinking' @@ -123,6 +132,14 @@ interface OpenBlock { id?: string; } +/** A tool call waiting for the open tool block to end, with its pieces so far. */ +interface WaitingToolCall { + id: unknown; + name: unknown; + pieces: string[]; + ended: boolean; +} + /** * Anthropic `/v1/messages` SSE writer: one instance per streaming request. * Consumes the driver's NDJSON chunks (`onChunk`) and writes the matching @@ -141,6 +158,10 @@ export class AnthropicSseWriter { #sawToolUse = false; /** Tool calls already opened by `tool_use_start`. */ #startedToolIds = new Set(); + /** Calls that started while another tool block was open, in start order. */ + #waitingTools: WaitingToolCall[] = []; + /** The open tool block's input so far. */ + #openToolInput = ''; #ended = false; constructor( @@ -204,6 +225,52 @@ export class AnthropicSseWriter { this.#open = null; } + #openToolBlock(id: unknown, name: unknown): void { + this.#openBlock( + 'tool_use', + { type: 'tool_use', id, name, input: {} }, + id as string | undefined, + ); + this.#openToolInput = ''; + } + + #toolDelta(partialJson: string): void { + this.#openToolInput += partialJson; + this.#delta({ type: 'input_json_delta', partial_json: partialJson }); + } + + /** + * Whether a new call should wait rather than close the open one: only while + * the open call's input is still incomplete JSON, or others already wait. A + * call without a distinct id can't be told apart, so it never waits. + */ + #canWait(id: unknown): boolean { + if (typeof id !== 'string' || !id || id === this.#open?.id) { + return false; + } + if (this.#waitingTools.some((call) => call.id === id)) return false; + if (this.#waitingTools.length) return true; + return ( + this.#open?.kind === 'tool_use' && + !isCompleteJson(this.#openToolInput) + ); + } + + /** + * Opens each waiting call in turn and writes its pieces so far. A call that + * hasn't ended stays open to stream the rest, unless `all` closes it too. + */ + #writeWaitingTools({ all }: { all: boolean }): void { + while (this.#waitingTools.length) { + const call = this.#waitingTools.shift()!; + this.#close(); + this.#openToolBlock(call.id, call.name); + for (const piece of call.pieces) this.#toolDelta(piece); + if (!call.ended && !all) return; + this.#close(); + } + } + #ensureText(): void { if (this.#open?.kind === 'text') return; this.#close(); @@ -299,35 +366,59 @@ export class AnthropicSseWriter { break; case 'tool_use_start': this.#startedToolIds.add(ev.id); + // Blocks can't overlap, so a call that starts while another is + // open waits for it instead of closing it under its pieces. + if (this.#canWait(ev.id)) { + this.#waitingTools.push({ + id: ev.id, + name: ev.name, + pieces: [], + ended: false, + }); + break; + } this.#close(); - this.#openBlock( - 'tool_use', - { type: 'tool_use', id: ev.id, name: ev.name, input: {} }, - ev.id as string | undefined, - ); + this.#openToolBlock(ev.id, ev.name); break; case 'tool_input_delta': + if (typeof ev.partialJson !== 'string') break; if ( this.#open?.kind === 'tool_use' && - this.#open.id === ev.id && - typeof ev.partialJson === 'string' + this.#open.id === ev.id ) { - this.#delta({ - type: 'input_json_delta', - partial_json: ev.partialJson, - }); + this.#toolDelta(ev.partialJson); + } else { + this.#waitingTools + .find((call) => call.id === ev.id) + ?.pieces.push(ev.partialJson); } break; - case 'tool_use': + case 'tool_use': { this.#sawToolUse = true; + const waiting = this.#waitingTools.find( + (call) => call.id === ev.id, + ); if ( this.#open?.kind === 'tool_use' && this.#open.id === ev.id ) { this.#close(); // already streamed incrementally + this.#writeWaitingTools({ all: false }); + } else if (waiting) { + waiting.ended = true; } else if (this.#startedToolIds.has(ev.id)) { - // Streamed and closed already (a parallel call that ended - // after the next one opened) — never emit it twice. + // Another block closed it already; never emit it twice, but + // let the calls waiting behind it go. + if (this.#open?.kind !== 'tool_use') { + this.#writeWaitingTools({ all: false }); + } + } else if (this.#canWait(ev.id)) { + this.#waitingTools.push({ + id: ev.id, + name: ev.name, + pieces: [jsonOf(ev.input)], + ended: true, + }); } else { this.#close(); this.#openBlock( @@ -347,6 +438,7 @@ export class AnthropicSseWriter { this.#close(); } break; + } case 'server_tool': this.#serverBlock(ev.block as Record); break; @@ -396,6 +488,7 @@ export class AnthropicSseWriter { #finish(ev: Record): void { this.#close(); + this.#writeWaitingTools({ all: true }); const stopReason = promoteStopForToolCalls( (ev.stopReason as string | undefined) ?? (this.#sawToolUse ? 'tool_use' : 'end_turn'), @@ -403,16 +496,13 @@ export class AnthropicSseWriter { 'tool_use', ); const stopDetails = ev.stopDetails as - | Record - | null - | undefined; + Record | null | undefined; const usageDetails = (ev.usageDetails as UsageDetails | undefined) ?? { inputTokens: 0, outputTokens: 0, }; const contextManagement = ev.contextManagement as - | Record - | undefined; + Record | undefined; this.#sse.write('message_delta', { type: 'message_delta', delta: {