Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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 <codebuff_tool_call> and </codebuff_tool_cal and </'
const fullText = `<codebuff_tool_call>${JSON.stringify({ cb_tool_name: 'x', body })}</codebuff_tool_call>`
it('keeps tool tags inside JSON strings across chunk boundaries', () => {
const body =
'see <codebuff_tool_call> and </codebuff_tool_cal and </ plus "</codebuff_tool_call>" at C:\\tmp\\'
const fullText = `before<codebuff_tool_call>${JSON.stringify({ cb_tool_name: 'x', body })}</codebuff_tool_call>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 } }],
})
}
})

Expand Down
29 changes: 27 additions & 2 deletions packages/agent-runtime/src/util/stream-xml-parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand All @@ -43,6 +46,8 @@ export function createStreamParserState(): StreamParserState {
buffer: '',
insideToolCall: false,
toolCallBody: [],
inJsonString: false,
jsonEscapeNext: false,
}
}

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
*/
Expand Down
Loading