diff --git a/packages/agent-runtime/src/util/__tests__/stream-xml-parser.test.ts b/packages/agent-runtime/src/util/__tests__/stream-xml-parser.test.ts index 6365720299..2f70c8a141 100644 --- a/packages/agent-runtime/src/util/__tests__/stream-xml-parser.test.ts +++ b/packages/agent-runtime/src/util/__tests__/stream-xml-parser.test.ts @@ -249,14 +249,16 @@ Thinking about the task... } }) - it('keeps start tags and partial end tags that appear inside a tool call body', () => { - const body = 'see and ${JSON.stringify({ cb_tool_name: 'x', body })}` + it('keeps tool tags inside JSON strings across chunk boundaries', () => { + const body = + 'see and " at C:\\tmp\\' + const fullText = `before${JSON.stringify({ cb_tool_name: 'x', body })}after` for (let size = 1; size <= 24; size++) { - expect(streamInChunks(fullText, size).toolCalls).toEqual([ - { toolName: 'x', input: { body } }, - ]) + expect(streamInChunks(fullText, size)).toEqual({ + text: 'beforeafter', + toolCalls: [{ toolName: 'x', input: { body } }], + }) } }) diff --git a/packages/agent-runtime/src/util/stream-xml-parser.ts b/packages/agent-runtime/src/util/stream-xml-parser.ts index f3095d2ad5..39cca5bd56 100644 --- a/packages/agent-runtime/src/util/stream-xml-parser.ts +++ b/packages/agent-runtime/src/util/stream-xml-parser.ts @@ -26,6 +26,9 @@ export type StreamParserState = { insideToolCall: boolean /** Body of the open tool call, joined once its end tag arrives */ toolCallBody: string[] + /** JSON lexical state carried between body chunks */ + inJsonString: boolean + jsonEscapeNext: boolean } export type ParseResult = { @@ -43,6 +46,8 @@ export function createStreamParserState(): StreamParserState { buffer: '', insideToolCall: false, toolCallBody: [], + inJsonString: false, + jsonEscapeNext: false, } } @@ -70,8 +75,8 @@ export function parseStreamChunk( while (text.length > 0) { if (state.insideToolCall) { - // We're inside a tool call, look for the end tag - const endIndex = text.indexOf(endToolTag) + // A tag inside a JSON string is tool input, not the end of the call. + const endIndex = findToolCallEnd(text, state) if (endIndex !== -1) { // Found end tag - extract the content and parse it @@ -120,6 +125,26 @@ export function parseStreamChunk( return { filteredText, toolCalls } } +function findToolCallEnd(text: string, state: StreamParserState): number { + for (let i = 0; i < text.length; i++) { + const char = text[i] + if (state.inJsonString) { + if (state.jsonEscapeNext) { + state.jsonEscapeNext = false + } else if (char === '\\') { + state.jsonEscapeNext = true + } else if (char === '"') { + state.inJsonString = false + } + } else if (char === '"') { + state.inJsonString = true + } else if (text.startsWith(endToolTag, i)) { + return i + } + } + return -1 +} + /** * Parse the JSON content inside a tool call tag. */