@@ -469,11 +469,12 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
469469 * Push a tool_result block to userMessageContent, preventing duplicates.
470470 * Duplicate tool_use_ids cause API errors.
471471 *
472- * Keeps all tool_result blocks contiguous, as the Anthropic API requires:
473- * image blocks attached to earlier tool results must not sit between two
474- * tool_results ("tool_use ids were found without tool_result blocks
475- * immediately after"), so any images preceding the new result are moved
476- * after it.
472+ * Keeps all tool_result blocks first and contiguous, as the Anthropic API
473+ * requires: a user message responding to tool_use blocks must begin with
474+ * the tool_result blocks, and any other content (images, text) between or
475+ * ahead of them is rejected ("tool_use ids were found without tool_result
476+ * blocks immediately after"). All tool_result blocks are therefore kept
477+ * ahead of other content in this array.
477478 *
478479 * @param toolResult - The tool_result block to add
479480 * @returns true if added, false if duplicate was skipped
@@ -491,15 +492,15 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
491492 }
492493 this . userMessageContent . push ( toolResult )
493494
494- // The new result is always appended at the end, so every image block
495- // currently in the array precedes it and would split the tool_result
496- // run once another result arrives. Move them after the new result .
497- const images = this . userMessageContent . filter (
498- ( block ) : block is Anthropic . ImageBlockParam => block . type === "image " ,
495+ // Partition into [tool_results, other blocks], preserving order within
496+ // each group, so results stay first and contiguous regardless of what
497+ // other content (images, text) arrived between pushes .
498+ const results = this . userMessageContent . filter (
499+ ( block ) : block is Anthropic . ToolResultBlockParam => block . type === "tool_result " ,
499500 )
500- if ( images . length > 0 ) {
501- const withoutImages = this . userMessageContent . filter ( ( block ) => block . type !== "image " )
502- this . userMessageContent . splice ( 0 , this . userMessageContent . length , ...withoutImages , ...images )
501+ if ( results . length !== this . userMessageContent . length ) {
502+ const others = this . userMessageContent . filter ( ( block ) => block . type !== "tool_result " )
503+ this . userMessageContent . splice ( 0 , this . userMessageContent . length , ...results , ...others )
503504 }
504505
505506 return true
0 commit comments