v1.4.5
Bug Fix
fix: prevent context compaction from corrupting tool_use/tool_result pairing
Fixed a critical bug where long-running agent workflows (15+ iterations) would fail with tool_use ids were found without tool_result blocks immediately after API errors.
Root Cause
Three interacting issues in the context compaction system:
-
Compaction fired between tool_use and tool_result addition —
AgentContext::addMessage()triggered auto-compaction after adding the assistant'stool_useresponse but before thetool_resultwas added, orphaning the tool_use block. -
Initial user message dropped during compaction — The compaction algorithm preserved
systemmessages but not the initialusertask message, causing compacted messages to start with anassistantrole and violating API requirements. -
Compaction algorithm misordered preserved messages — The
array_unshiftapproach inserted recent messages before preserved messages, breaking message ordering.
Changes
AgentContext::addMessage()now defers compaction when the last message is a danglingtool_use(no matchingtool_resultyet)ContextManager::compactMessages()preserves both the system message and initial user task message- Rewrote compaction to correctly build
preserved + recentmessage sets, keeping the maximum number of recent message units that fit - Added early return after
clearToolResultsif that alone brings context within limits - Added 7 regression tests covering multi-iteration compaction, tool_use pairing integrity, and message ordering
Impact
Fixes production failures for:
- Document analysis (PDFs, large files)
- Complex multi-step automation workflows
- Data extraction requiring 15+ agent iterations
- Any workflow using context management with
auto_compactenabled