Skip to content

fix: reorder tool_result blocks to match tool_use order (#11804)#11806

Draft
roomote[bot] wants to merge 1 commit intomainfrom
fix/reorder-tool-results-11804
Draft

fix: reorder tool_result blocks to match tool_use order (#11804)#11806
roomote[bot] wants to merge 1 commit intomainfrom
fix/reorder-tool-results-11804

Conversation

@roomote
Copy link
Contributor

@roomote roomote bot commented Mar 1, 2026

This PR attempts to address Issue #11804 -- Claude requests failing with HTTP 400 when multiple tool calls run concurrently due to tool_result order mismatch.

Changes

Root cause: When the Anthropic API returns multiple tool_use blocks in a single assistant turn, tool_result blocks could be pushed into userMessageContent in completion order rather than the original tool_use order. The Anthropic Messages API requires them to match, so out-of-order results trigger HTTP 400.

Fix: Added a reorderToolResults() helper at the end of validateAndFixToolResultIds() in src/core/task/validateToolResultIds.ts. After all existing validation (deduplication, ID correction, missing result injection), tool_result blocks are sorted to match the tool_use order from the preceding assistant message, matched by tool_use_id.

Key design decisions per the approved plan and reviewer feedback:

  • Non-tool-result blocks (text, image) stay in their original positions
  • Only tool_result blocks are reordered relative to each other (stable)
  • Reordering runs on both the early-return path (valid IDs) and the fix-up path
  • Returns null (no-op) when already in correct order

Tests

Added 4 new test cases covering:

  • Out-of-order tool_results (reversed order)
  • Non-tool-result blocks preserving position during reorder
  • Already-ordered tool_results (no-op)
  • Reordering combined with missing result injection

Updated 2 existing tests whose expected order changed due to the new reordering behavior.

Feedback and guidance are welcome.

Interactively review PR in Roo Code Cloud

When the Anthropic API returns multiple tool_use blocks, tool_result blocks
must appear in the same order. The existing validateAndFixToolResultIds()
already handled missing/duplicate results but did not reorder them.

This adds a reorderToolResults() helper that sorts tool_result blocks by
their corresponding tool_use index while keeping non-tool-result blocks
(text, image) in their original positions.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant