Skip to main content

Module pairing

Module pairing 

Source
Expand description

Invariant-repair pass: ensure every tool_call has its tool_result and vice versa.

Provider APIs (OpenAI Responses, Anthropic Messages, Gemini) all enforce one of two invariants on conversation history:

  1. Every assistant tool_call must be followed by a matching tool_result with the same tool_call_id.
  2. Every tool_result must reference a tool_call_id that exists earlier in the buffer.

If a prior strategy in the super pipeline drops a message that broke one of these invariants — for example, a middle-drop that crosses a tool_call↔tool_result boundary — the provider rejects the request outright (OpenAI: “No tool output found for function call call_XXX”).

This module runs last in super::apply_all and repairs orphans in the safest way available:

  • Orphan tool_call (call with no matching result): inject a synthetic Role::Tool message immediately after it carrying a [tool result unavailable: elided by context management] payload. The call id is preserved so the model can correlate.
  • Orphan tool_result (result whose call_id is nowhere earlier): drop the result. Providers that see an unreferenced result treat it as a malformed payload.

§Always-on

No config. This is a correctness pass — it can only make the buffer more-valid, never less.

Functions§

repair_orphans
Repair orphaned tool_call/tool_result pairings.