Skip to content

The agent that grows with you

fix(compression): tail walk prices native preserved thinking like preflight

kshitijk4poore8cc8c31c4fe
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index 6da13625b39..ddb2e2fab6d 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -3091,10 +3091,14 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngin
n = len(messages)
newest_asst_idx = _last_assistant_index(messages)
charge_all_thinking = self._stale_thinking_on_wire()
+ native_budget = self._native_anthropic_budget()
accumulated = 0
cut = n # start from beyond the end
for i in range(n - 1, head_end - 1, -1):
- msg_tokens = _estimate_msg_budget_tokens(messages[i], charge_all_thinking or i == newest_asst_idx)
+ msg_tokens = (
+ native_budget(messages[i]) if native_budget
+ else _estimate_msg_budget_tokens(messages[i], charge_all_thinking or i == newest_asst_idx)
+ )
if accumulated + msg_tokens > ceiling and (n - i) >= min_tail:
return (i if cut_at_break else cut), accumulated
accumulated += msg_tokens
@@ -4969,6 +4973,30 @@ Write only the summary body. Do not include any preamble or prefix."""
except Exception:
return False
+ def _native_anthropic_budget(self):
+ """Per-message tail budget on a preserved-thinking native Anthropic route, else None. That route
+ replays exactly the projected carriers minus this session's rejected signatures — what the
+ preflight estimate prices — never the canonical ``reasoning`` keys."""
+ from agent.anthropic_thinking_policy import native_anthropic_preserves_prior_thinking
+
+ if (self.api_mode or "") != "anthropic_messages" or not native_anthropic_preserves_prior_thinking(
+ self.base_url, self.model
+ ):
+ return None
+ from agent.anthropic_thinking_replay import rejected_thinking_fingerprints, strip_rejected_thinking
+ from agent.message_sanitization import native_anthropic_accounting_projection
+
+ rejected = rejected_thinking_fingerprints(getattr(self, "_session_db", None), getattr(self, "_session_id", ""))
+
+ def budget(msg: Dict[str, Any]) -> int:
+ request_copy = dict(msg)
+ if rejected:
+ strip_rejected_thinking(request_copy, rejected)
+ (projected,), readable = native_anthropic_accounting_projection([request_copy])
+ return _estimate_msg_budget_tokens(projected) + sum(estimate_tokens_rough(text) for text in readable)
+
+ return budget
+
def _find_tail_cut_by_tokens(
self, messages: List[Dict[str, Any]], head_end: int, token_budget: int | None = None,
*, allow_split_turn: bool = True,