@@ -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