The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(compression): keep the unanswered tool round verbatim through mid-turn compaction
MongLong021418eb09f5db38
diff --git a/agent/context_compressor.py b/agent/context_compressor.pyindex 7806a72c838..2f3abf6dab6 100644--- a/agent/context_compressor.py+++ b/agent/context_compressor.py@@ -1377,6 +1377,19 @@ def _last_assistant_index(messages: "List[Dict[str, Any]]") -> int:return _last_index_with_role(messages, "assistant")+def _pending_tool_round(messages: "List[Dict[str, Any]]") -> range:+ """Indices of the tool results the transcript ends with — a round the model has not answered yet; empty when+ the transcript ends in any other row. One /steer row after the round does not answer it: the steer is+ delivered after the newest tool result before the next API call, so preflight compaction sees it last."""+ end = len(messages)+ if end and messages[end - 1].get("display_kind") == STEER_DISPLAY_KIND:+ end -= 1+ start = end+ while start > 0 and messages[start - 1].get("role") == "tool":+ start -= 1+ return range(start, end)++def _part_text(item: Any) -> Optional[str]:"""Text of a content part: the string itself, a dict's ``text``, else None."""return item if isinstance(item, str) else item.get("text") if isinstance(item, dict) else None@@ -2685,6 +2698,13 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEnginreturn max(threshold_percent, _SMALL_CTX_THRESHOLD_PERCENT)return threshold_percent+ @staticmethod+ def _effective_input_window(context_length: int, max_tokens: int | None) -> int:+ """Usable input budget: the window minus the output reservation, or the whole window when the reservation+ is unset or leaves nothing."""+ effective_window = context_length - (max_tokens or 0)+ return effective_window if effective_window > 0 else context_length+@staticmethoddef _compute_threshold_tokens(context_length: int, threshold_percent: float, max_tokens: int | None = None,@@ -2706,9 +2726,7 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEnginthe degenerate-window check below both operate on the effective input budget. ``max_tokens=None``(provider default) conservatively assumes no reservation (full window)."""- effective_window = context_length - (max_tokens or 0)- if effective_window <= 0:- effective_window = context_length+ effective_window = ContextCompressor._effective_input_window(context_length, max_tokens)pct_value = int(effective_window * threshold_percent)floored = max(pct_value, MINIMUM_CONTEXT_LENGTH)# The floor must not consume output headroom: cap at 85% when it is the binding term. Near-minimum windows@@ -3144,11 +3162,12 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngindef _pressure_demote_tail(self, result: List[Dict[str, Any]], prune_boundary: int, protect_tail_tokens: int,- call_id_to_tool: Dict[str, tuple[str, str]], min_prune_chars: int,+ call_id_to_tool: Dict[str, tuple[str, str]], min_prune_chars: int, spared: range,) -> int:"""Pass 4: demote inside the protected tail when it alone exceeds the soft budget (#61932).- Keeps a short recent floor verbatim; overrides the skill guard (else the dead-end recurs).- Returns the number of tool results demoted (arg truncations are logged but not counted)."""+ Keeps a short recent floor and the ``spared`` pending tool round verbatim; overrides the skill guard+ (else the dead-end recurs). Returns the number of tool results demoted (arg truncations are logged+ but not counted)."""soft_ceiling = self._tail_soft_ceiling(protect_tail_tokens)demote_end = len(result) - min(_PRESSURE_KEEP_RECENT_MESSAGES, len(result))start = max(0, prune_boundary)@@ -3161,6 +3180,8 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngindef _shrink_at(i: int) -> None:# Each helper no-ops on the other role, so both may run unconditionally.nonlocal demoted, pressure_hits+ if i in spared:+ returnif self._demote_tool_result_at(result, i, call_id_to_tool, min_prune_chars):demoted += 1pressure_hits += 1@@ -3178,9 +3199,11 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEnginlast_tool_idx = next((i for i in range(len(result) - 1, -1, -1) if result[i].get("role") == "tool"), None)for i in (i for i in range(start, len(result)) if i != last_tool_idx):_shrink_at(i)- # Last resort: the newest body alone may exceed the soft budget; summarize it.+ # Last resort, unless it is the spared pending round: the newest body may exceed the soft budget+ # alone (one 200KB read); summarize it.if (- last_tool_idx is not None and last_tool_idx >= prune_boundary and _protected_region_tokens() > soft_ceiling+ last_tool_idx is not None and last_tool_idx not in spared and last_tool_idx >= prune_boundary+ and _protected_region_tokens() > soft_ceiling) and self._demote_tool_result_at(result, last_tool_idx, call_id_to_tool, min_prune_chars):demoted += 1pressure_hits += 1@@ -3203,6 +3226,17 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEnginresult = [m.copy() for m in messages]call_id_to_tool = _tool_calls_by_id(result)prune_boundary = self._prune_boundary(result, protect_tail_count, protect_tail_tokens)+ # The pending tool round is output the model asked for and has not read yet: a stub makes it re-run the+ # call (side effects included) or answer blind. Passes 2 and 4 spare it unless it alone exceeds the tail's+ # hard share of the input budget the threshold is computed from (the output reservation is not room the+ # round can keep) — the #61932 single-200KB-read case, which must still give way.+ pending = _pending_tool_round(result)+ input_window = self._effective_input_window(+ getattr(self, "context_length", 0) or 0, getattr(self, "max_tokens", None))+ hard_share = int(input_window * TAIL_MAX_CONTEXT_FRACTION)+ fits = sum(_estimate_msg_budget_tokens(result[i]) for i in pending) <= hard_share+ spared = pending if fits else range(0)+ prune_boundary = min(prune_boundary, spared.start) if spared else prune_boundarypruned = self._dedupe_tool_results(result)# Just-loaded / tail-referenced skills keep full skill_view bodies through the ordinary passes.# Without this, a skill loaded moments before a compaction can be demoted to metadata while the@@ -3222,7 +3256,7 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEnginpruned += _retire_stale_tool_result_images(result)if protect_tail_tokens is not None and protect_tail_tokens > 0 and result:pruned += self._pressure_demote_tail(- result, prune_boundary, protect_tail_tokens, call_id_to_tool, min_prune_chars,+ result, prune_boundary, protect_tail_tokens, call_id_to_tool, min_prune_chars, spared,)return result, pruned@@ -4930,7 +4964,10 @@ Write only the summary body. Do not include any preamble or prefix."""cut_idx, _ = self._walk_tail_budget(messages, head_end, token_budget, min_tail, cut_at_break=True)fallback_cut = n - min_tail- cut_idx = min(cut_idx, n - walk_floor)+ # The newest row never leaves the tail. When it alone exceeds the ceiling the walk accepts nothing, and a cut+ # at ``n`` summarised the pending tool round the model had not read (the split below then took the whole+ # turn); aligning from ``n - 1`` keeps that group whole, as atomic groups may exceed the ceiling.+ cut_idx = min(cut_idx, n - max(walk_floor, 1))# Small conversations: force a cut after the head so compression still removes something.if cut_idx <= head_end:cut_idx = max(fallback_cut, head_end + 1)diff --git a/tests/agent/test_protected_tail_pressure.py b/tests/agent/test_protected_tail_pressure.pyindex 7515849e7af..79b45fb0b0d 100644--- a/tests/agent/test_protected_tail_pressure.py+++ b/tests/agent/test_protected_tail_pressure.py@@ -13,6 +13,7 @@ This is the core compressor contract — not Desktop/Windows-specific.from __future__ import annotations+import jsonfrom unittest.mock import patchimport pytest@@ -23,6 +24,7 @@ from agent.context_compressor import (_PRESSURE_KEEP_RECENT_MESSAGES,)from agent.model_metadata import estimate_messages_tokens_rough+from agent.prompt_builder import steer_user_rowfrom agent.turn_context import compression_made_progress@@ -204,3 +206,70 @@ class TestProtectedTailPressure61932:for cid in call_ids:assert cid in tool_result_ids, f"orphaned tool call {cid!r}"++def _terminal_call(call_id: str, command: str) -> dict:+ return {+ "id": call_id,+ "type": "function",+ "function": {"name": "terminal", "arguments": json.dumps({"command": command})},+ }+++def _terminal_result(call_id: str, tag: str, lines: int) -> dict:+ """A multi-line terminal result in the tool's own JSON shape (newlines escaped)."""+ output = "\n".join(+ f"node-{tag}-{i:03d} cpu={i % 97} lease={tag.upper()}{i:06X} zone=eu-west-2a status=HEALTHY "+ f"mem=41% disk=73% uptime=31d kernel=6.8.0-45 owner=okafor rack=R-{i % 40:02d} note=nominal"+ for i in range(lines)+ )+ return {"role": "tool", "tool_call_id": call_id, "content": json.dumps({"output": output, "exit_code": 0})}++[email protected]("steered", [False, True], ids=["round_last", "steer_after_round"])+def test_mid_turn_compaction_keeps_the_pending_tool_round_verbatim(steered):+ """Regression: compaction after a tool round stubbed the output the model had just asked for.++ Lean mode's 10K tail budget puts pass 4's soft ceiling at 15K tokens. Long user messages (no pass+ may shrink them) filled it, so the last resort stubbed the pending round. The model has not read+ that round and would re-run the command or answer blind, so it must survive verbatim while older+ rounds still give way to the budget. A /steer sent during the tools lands as a user row after the+ round before preflight compaction runs; the round is still unread then.+ """+ ctx = 272_000+ with patch("agent.context_compressor.get_model_context_length", return_value=ctx):+ c = ContextCompressor(+ model="test/model", threshold_percent=0.50, protect_first_n=3, protect_last_n=8,+ quiet_mode=True, config_context_length=ctx,+ )+ c._generate_summary = lambda *a, **k: "compact summary of earlier turns"+ prose = ("the quarterly fleet review keeps drifting between regions and owners " * 360)[:24_000]+ msgs: list[dict] = [{"role": "system", "content": "You are Hermes."}]+ for t in range(13):+ msgs += [+ {"role": "user", "content": f"{prose}\nRun probe {t} and name the hottest node."},+ {"role": "assistant", "content": None, "tool_calls": [_terminal_call(f"old_{t}", f"python3 probe.py c{t} 3")]},+ _terminal_result(f"old_{t}", f"o{t}", 70),+ {"role": "assistant", "content": f"node-o{t}-000 is the hottest."},+ ]+ msgs += [+ {"role": "user", "content": "Run both probes and compare them."},+ {"role": "assistant", "content": None, "tool_calls": [+ _terminal_call("new_a", "python3 probe.py indus 3"), _terminal_call("new_b", "python3 probe.py lyra 1"),+ ]},+ _terminal_result("new_a", "na", 70),+ # Last and bigger than the soft ceiling on its own, still well inside the hard window share.+ _terminal_result("new_b", "nb", 420),+ ]+ pending = {m["tool_call_id"]: m["content"] for m in msgs[-2:]}+ previous = msgs[-6]+ if steered:+ msgs.append(steer_user_row("Also flag any node above 90% cpu."))+ assert previous["tool_call_id"] == "old_12"++ out = c.compress(list(msgs), current_tokens=estimate_messages_tokens_rough(msgs))++ by_id = {m.get("tool_call_id"): m.get("content") for m in out if m.get("role") == "tool"}+ for call_id, content in pending.items():+ assert by_id.get(call_id) == content, f"pending result {call_id} was not kept verbatim: {by_id.get(call_id)!r:.120}"+ # The budget still binds older rounds: the previous turn's result does not survive verbatim.+ assert by_id.get("old_12") != previous["content"]diff --git a/website/docs/developer-guide/context-compression-and-caching.md b/website/docs/developer-guide/context-compression-and-caching.mdindex e1f70109fc5..6bf5ecb0bb5 100644--- a/website/docs/developer-guide/context-compression-and-caching.md+++ b/website/docs/developer-guide/context-compression-and-caching.md@@ -503,6 +503,12 @@ Old tool results (>200 chars) outside the protected tail are replaced with:This is a cheap pre-pass that saves significant tokens from verbose tooloutputs (file contents, terminal output, search results).+A tool round the model has not answered yet (compaction fired right after it ran, with or+without a `/steer` delivered after it) keeps its text results verbatim in the tail, so the model+does not re-run the call or answer without its output. The one exception is a round that alone+exceeds 20% of the input budget (the context window minus the output reservation): it is+summarized so compaction can still make room.+### Phase 2: Determine Boundaries```