Skip to content

fix(compaction): splitMessagesByTokenShare can orphan tool_use from toolResult #58836

Closed

Description

@aaron-he-zhu

Bug Description

splitMessagesByTokenShare() in src/agents/compaction.ts splits message arrays purely by token count. When a split point lands between an assistant message containing a tool_use block and its corresponding toolResult message, the resulting chunks contain orphaned messages that produce invalid API request sequences.

Reproduction

Given a conversation with interleaved tool calls:

[user] (1000 tokens)
[assistant + tool_use: tc1] (1000 tokens)
[toolResult: tc1] (200 tokens)
[user] (1000 tokens)

When splitMessagesByTokenShare(messages, 2) is called with a target of ~1600 tokens per chunk, the split can land between the assistant (index 1) and toolResult (index 2), producing:

  • Chunk 1: [user, assistant+tool_use:tc1] — orphaned tool_use with no result
  • Chunk 2: [toolResult:tc1, user] — orphaned toolResult with no matching tool_use

Impact

  • Downstream summarization receives invalid message sequences
  • Anthropic API rejects orphaned tool_use_id references
  • repairToolUseResultPairing() in pruneHistoryForContextShare already handles this for pruning, but splitMessagesByTokenShare lacks equivalent protection

Expected Behavior

Split points should respect tool call boundaries — never splitting between a tool_use and its matching toolResult. The split should snap to the nearest safe boundary (after a complete tool call/result pair).

Affected Code

  • src/agents/compaction.ts:116 — splitMessagesByTokenShare()
  • Called from summarizeInStages() (line 424) and pruneHistoryForContextShare() (line 487)

Activity

  1. locked as resolved and limited conversation to collaborators on Apr 7, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Fields

    Priority

    None yet

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions