Skip to content

Commit 55c683d

Browse files
committed
agent-runtime: Add case for aborted tools without tool results to be filetered out
1 parent 17de998 commit 55c683d

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

packages/agent-runtime/src/tools/stream-parser.ts

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -313,10 +313,27 @@ export async function processStream(
313313
// Build message history from the current agentState.messageHistory so that
314314
// inline agent modifications (e.g. set_messages) are preserved, while
315315
// tool_calls and tool_results are still appended in deterministic order.
316+
//
317+
// When the signal was aborted, tool calls are added synchronously but tool
318+
// results arrive asynchronously via .then(). Because we skip awaiting
319+
// previousToolCallFinished on abort, some tool calls may not have matching
320+
// tool results yet. Including orphaned tool calls in the message history
321+
// causes provider errors ("unexpected tool_use_id found in tool_result
322+
// blocks"). Filter them out so every tool_call has a corresponding
323+
// tool_result.
324+
const completedToolCallIds = new Set(
325+
toolResultsToAddToMessageHistory.map((r) => r.toolCallId),
326+
)
327+
const filteredToolCalls = signal.aborted
328+
? toolCallsToAddToMessageHistory.filter((tc) =>
329+
completedToolCallIds.has(tc.toolCallId),
330+
)
331+
: toolCallsToAddToMessageHistory
332+
316333
agentState.messageHistory = buildArray<Message>([
317334
...agentState.messageHistory,
318335
...assistantMessages,
319-
...toolCallsToAddToMessageHistory.map((toolCall) => assistantMessage({ ...toolCall, type: 'tool-call' })),
336+
...filteredToolCalls.map((toolCall) => assistantMessage({ ...toolCall, type: 'tool-call' })),
320337
...toolResultsToAddToMessageHistory,
321338
...errorMessages,
322339
])

0 commit comments

Comments
 (0)