Skip to content

The agent that grows with you

fix(context): keep compaction history lossless

JoaoMarcos44a7baa5f5eb3a
diff --git a/agent/context_compressor.py b/agent/context_compressor.py
index b7c62fcb16c..c8c2709c5a3 100644
--- a/agent/context_compressor.py
+++ b/agent/context_compressor.py
@@ -1568,53 +1568,6 @@ def evict_stale_outbound_tool_images(api_messages: List[Dict[str, Any]]) -> int:
return pruned
-def _truncate_tool_call_args_json(args: str, head_chars: int = 200) -> str:
- """Shrink long string leaves in a tool-call arguments JSON blob, keeping it valid (providers 400 on malformed args).
-
- Only leaves where the replacement is a net reduction are changed (``head_chars`` plus the
- marker, ~420 chars); the input string is returned unchanged when nothing was replaced.
- """
- try:
- parsed = json.loads(args)
- except (ValueError, TypeError):
- return args
-
- changed = False
-
- def _shrink(obj: Any) -> Any:
- nonlocal changed
- if isinstance(obj, str):
- # Already marked: the compressor writes the head and the marker as the whole tail, so
- # key on that shape. A substring/prefix test alone would exempt a leaf that merely
- # quotes the marker — including the imitation #83714 is about — from shrinking forever.
- marked = obj.startswith(_COMPRESSION_MARKER_PREFIX, head_chars) and obj.endswith("⟫")
- if len(obj) <= head_chars or marked:
- return obj
- marker = _COMPRESSION_MARKER_TEMPLATE.format(
- omitted=len(obj) - head_chars, total=len(obj)
- )
- # Only replace when it reclaims bytes: for a leaf just over the cap the marker is
- # longer than what it replaces.
- if head_chars + len(marker) >= len(obj):
- return obj
- changed = True
- return obj[:head_chars] + marker
- if isinstance(obj, dict):
- return {k: _shrink(v) for k, v in obj.items()}
- if isinstance(obj, list):
- return [_shrink(v) for v in obj]
- return obj
-
- shrunken = _shrink(parsed)
- # Re-serialising alone would rewrite the caller's bytes (compact wire JSON gains spaces),
- # which the callers read as "this message changed" and count as reclaimed pressure.
- if not changed:
- return args
- # ensure_ascii=False keeps CJK/emoji from bloating into \uXXXX
- out = json.dumps(shrunken, ensure_ascii=False)
- return out if len(out) < len(args) else args
-
-
_IMAGE_PART_TYPES = frozenset({"image_url", "input_image", "image"})
@@ -3134,22 +3087,6 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngin
content_hashes.add(h)
return pruned
- @staticmethod
- def _truncate_tool_call_args_at(result: List[Dict[str, Any]], idx: int) -> bool:
- """Shrink large tool_call argument payloads at ``idx`` (inside the parsed JSON, so it stays valid)."""
- msg = result[idx]
- if msg.get("role") != "assistant" or not msg.get("tool_calls"):
- return False
- new_tcs = []
- for tc in msg["tool_calls"]:
- args = tc.get("function", {}).get("arguments", "") if isinstance(tc, dict) else ""
- new_args = _truncate_tool_call_args_json(args) if len(args) > 500 else args
- new_tcs.append(tc if new_args == args else {**tc, "function": {**tc["function"], "arguments": new_args}})
- modified = any(new is not old for new, old in zip(new_tcs, msg["tool_calls"]))
- if modified:
- result[idx] = {**msg, "tool_calls": new_tcs}
- return modified
-
@staticmethod
def _demote_tool_result_at(
result: List[Dict[str, Any]], idx: int, call_id_to_tool: Dict[str, tuple[str, str]],
@@ -3195,10 +3132,10 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngin
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, spared: range,
) -> int:
- """Pass 4: demote inside the protected tail when it alone exceeds the soft budget (#61932).
- 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)."""
+ """Pass 4: demote tool-result bodies inside the protected tail when it alone exceeds the soft
+ budget (#61932). Keeps a short recent floor and the ``spared`` pending tool round verbatim; overrides
+ the skill guard (else the dead-end recurs). Tool-call arguments stay byte-exact. Returns the number of
+ tool results demoted."""
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)
@@ -3209,15 +3146,12 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngin
demoted = pressure_hits = 0
def _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:
return
if self._demote_tool_result_at(result, i, call_id_to_tool, min_prune_chars):
demoted += 1
pressure_hits += 1
- if self._truncate_tool_call_args_at(result, i):
- pressure_hits += 1
if demote_end <= prune_boundary or _protected_region_tokens() <= soft_ceiling:
return 0
@@ -3261,8 +3195,9 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngin
self, messages: List[Dict[str, Any]], protect_tail_count: int,
protect_tail_tokens: int | None = None, min_prune_chars: int = _PRUNE_MIN_CHARS,
) -> tuple[List[Dict[str, Any]], int]:
- """Old tool results -> 1-line summaries; dedup, arg truncation, pressure demotion. Returns ``(messages, count)``.
- Token budget (when given) takes priority over the message-count floor."""
+ """Project old tool-result bodies to bounded summaries without rewriting tool-call arguments.
+ Returns ``(messages, count)``; token budget (when given) takes priority over the
+ message-count floor."""
if not messages:
return messages, 0
result = [m.copy() for m in messages]
@@ -3279,15 +3214,14 @@ class ContextCompressor(SummaryDispatchMixin, MicroCompactionMixin, ContextEngin
# Without this, a skill loaded moments before a compaction can be demoted to metadata while the
# model still believes its instructions are in context. See #32106.
protected_skills = _collect_protected_skill_names(result, prune_boundary)
- # Pass 2: summarize old tool results. Pass 3: shrink large tool_call arguments INSIDE the parsed JSON so
- # the result stays valid; otherwise providers 400 on every turn until the call leaves the window.
+ # Pass 2: summarize old tool results. Tool-call arguments are canonical execution
+ # records and are never rewritten; summary input is bounded separately by
+ # _render_tool_call_for_summary().
pruned += sum(
self._demote_tool_result_at(result, i, call_id_to_tool, min_prune_chars, protected_skills)
for i in range(max(0, prune_boundary))
)
- for i in range(max(0, prune_boundary)):
- self._truncate_tool_call_args_at(result, i)
- # Pass 3.5: retire image payloads inside the protected tail; re-sent embeds otherwise make
+ # Pass 3: retire image payloads inside the protected tail; re-sent embeds otherwise make
# compression look ineffective and trip anti-thrash. Newest frames stay live.
# Newest frames stay live for follow-up QA; unread spared results stay live too. See #92699.
pruned += _retire_stale_tool_result_images(result, spared=spared)
@@ -5453,8 +5387,8 @@ Write only the summary body. Do not include any preamble or prefix."""
self, messages: List[Dict[str, Any]], current_tokens: Optional[int] = None, focus_topic: Optional[str] = None,
force: bool = False, memory_context: str = "", bypass_cooldown: bool = False,
) -> List[Dict[str, Any]]:
- """Summarize the middle turns: prune tool results and blank echoes (survives an abort), protect head and a
- token-budget tail, summarize, clean orphaned tool pairs. ``force`` clears the failure cooldown and bypasses
+ """Summarize the middle turns: use pruned tool results only as summary input, protect a canonical
+ head/tail, summarize, then clean orphaned tool pairs. ``force`` clears the failure cooldown and bypasses
the feasibility skip; ``bypass_cooldown`` runs the summary LLM without clearing the cooldown.
Args: focus_topic: Optional focus string for guided compression. When provided, the summariser will
@@ -5484,6 +5418,8 @@ Write only the summary body. Do not include any preamble or prefix."""
return messages
display_tokens = current_tokens if current_tokens else self.last_prompt_tokens or estimate_messages_tokens_rough(messages)
spare_pending_images = bool(self._spared_pending_tool_round(messages))
+ # Head rows are carried from canonical history; pruning only feeds the summary and the tail.
+ canonical_messages = self._drop_blank_echoes(messages)
# Phase 1: Prune old tool results (cheap, no LLM call)
messages, pruned_count = self._prune_old_tool_results(
messages, protect_tail_count=self.protect_last_n, protect_tail_tokens=self.tail_token_budget,
@@ -5492,17 +5428,19 @@ Write only the summary body. Do not include any preamble or prefix."""
logger.info("Pre-compression: pruned %d old tool result(s)", pruned_count)
messages = self._drop_blank_echoes(messages)
n_messages = len(messages)
- # Phase 2: Determine boundaries
+ # Phase 2: Determine boundaries (on the pruned copy so a pressure-demoted tail can compress, #61932)
compress_start, compress_end = self._compress_window(messages)
if compress_start >= compress_end:
self._record_compression_regions(
- head_messages=messages[:compress_start], middle_messages=[], tail_messages=messages[compress_end:],
+ head_messages=canonical_messages[:compress_start],
+ middle_messages=[],
+ tail_messages=canonical_messages[compress_end:],
)
self._structural_no_op_result(
telemetry, "no_compressible_window",
f"compress_start ({compress_start}) >= compress_end ({compress_end}) - transcript fits within tail budget",
)
- return messages
+ return canonical_messages
turns_to_summarize = messages[compress_start:compress_end]
# Lean mode demotes stale tail tool results before summary generation so stubs exist even if it aborts.
if getattr(self, "tail_mode", "lean") == "lean":
@@ -5510,7 +5448,9 @@ Write only the summary body. Do not include any preamble or prefix."""
scan = self._scan_window_handoffs(messages, compress_start, compress_end, turns_to_summarize)
turns_to_summarize = scan.turns_to_summarize
self._record_compression_regions(
- head_messages=messages[:compress_start], middle_messages=turns_to_summarize, tail_messages=messages[compress_end:],
+ head_messages=canonical_messages[:compress_start],
+ middle_messages=turns_to_summarize,
+ tail_messages=canonical_messages[compress_end:],
)
telemetry["chunk_count"] = 1 if turns_to_summarize else 0
if not turns_to_summarize:
@@ -5520,7 +5460,7 @@ Write only the summary body. Do not include any preamble or prefix."""
telemetry, "empty_post_handoff_window",
f"window {compress_start}-{compress_end} holds only already-summarized handoffs",
)
- return messages
+ return canonical_messages
if not self.quiet_mode:
self._log_compression_start(
display_tokens, compress_start, compress_end, len(turns_to_summarize), n_messages - scan.tail_start,
@@ -5542,21 +5482,25 @@ Write only the summary body. Do not include any preamble or prefix."""
if not summary and self._abort_on_summary_failure(
telemetry, compress_end - compress_start, scan.previous_summary_before,
):
- return messages
+ return canonical_messages
if not summary:
summary = self._fallback_summary_for_window(
telemetry, turns_to_summarize, compress_end - compress_start, feasibility_skip,
)
# Phase 4: Assemble compressed message list
- compressed = self._assemble_compressed(messages, compress_start, compress_end, scan, summary)
- return self._finalize_compressed(compressed, messages, n_messages, spare_pending_images)
+ compressed = self._assemble_compressed(
+ messages, compress_start, compress_end, scan, summary, source_messages=canonical_messages,
+ )
+ return self._finalize_compressed(compressed, canonical_messages, n_messages, spare_pending_images)
def _assemble_compressed(
- self, messages: List[Dict[str, Any]], compress_start: int, compress_end: int, scan: "_HandoffScan", summary: str,
+ self, messages: List[Dict[str, Any]], compress_start: int, compress_end: int,
+ scan: "_HandoffScan", summary: str, *, source_messages: List[Dict[str, Any]] | None = None,
) -> List[Dict[str, Any]]:
- """Head + summary row (or merged carrier) + tail, with alternation-safe summary placement."""
- compressed = self._assemble_head(messages, compress_start)
- tail_messages = self._assemble_tail(messages, compress_end, scan.tail_start, scan.summary_indices)
+ """Head + summary + tail; temporary prune copies never become durable rows."""
+ source = source_messages if source_messages is not None else messages
+ compressed = self._assemble_head(source, compress_start)
+ tail_messages = self._assemble_tail(source, compress_end, scan.tail_start, scan.summary_indices)
summary_role, merge_into_tail, force_user_leading, first_tail_visible_idx = (
self._summary_placement(compressed, tail_messages, compress_start)
)
diff --git a/tests/agent/test_context_compression_canonical_state.py b/tests/agent/test_context_compression_canonical_state.py
new file mode 100644
index 00000000000..65373e3b12d
--- /dev/null
+++ b/tests/agent/test_context_compression_canonical_state.py
@@ -0,0 +1,87 @@
+"""Regression coverage for #122559 canonical compression state."""
+
+from __future__ import annotations
+
+import json
+from unittest.mock import patch
+
+from agent.compression_marker import _COMPRESSION_MARKER_PREFIX
+from agent.context_compressor import ContextCompressor
+
+
+def _call(call_id: str, payload: str) -> dict:
+ return {
+ "role": "assistant",
+ "content": "",
+ "tool_calls": [{
+ "id": call_id,
+ "type": "function",
+ "function": {
+ "name": "write_file",
+ "arguments": json.dumps({"path": "/tmp/x.py", "content": payload}),
+ },
+ }],
+ }
+
+
+def _messages() -> list[dict]:
+ return [
+ {"role": "user", "content": "head request"},
+ _call("head_call", "A" * 4_000),
+ {"role": "tool", "tool_call_id": "head_call", "content": "R" * 10_000},
+ {"role": "user", "content": "middle 1"},
+ {"role": "assistant", "content": "middle answer 1"},
+ {"role": "user", "content": "middle 2"},
+ {"role": "assistant", "content": "middle answer 2"},
+ {"role": "user", "content": "tail request"},
+ {"role": "assistant", "content": "tail answer"},
+ ]
+
+
+def _compressor() -> ContextCompressor:
+ return ContextCompressor(
+ model="test/model",
+ config_context_length=200_000,
+ protect_first_n=3,
+ protect_last_n=2,
+ quiet_mode=True,
+ tail_mode="legacy",
+ )
+
+
+def test_structural_noop_returns_canonical_tool_arguments() -> None:
+ compressor = _compressor()
+ messages = _messages()
+ original_args = messages[1]["tool_calls"][0]["function"]["arguments"]
+
+ with patch.object(compressor, "_compress_window", return_value=(3, 3)):
+ result = compressor.compress(messages, current_tokens=100_000)
+
+ assert result[1]["tool_calls"][0]["function"]["arguments"] == original_args
+ assert _COMPRESSION_MARKER_PREFIX not in json.dumps(result, ensure_ascii=False)
+
+
+def test_successful_compaction_carries_canonical_head_not_pruned_working_copy() -> None:
+ compressor = _compressor()
+ messages = _messages()
+ original_args = messages[1]["tool_calls"][0]["function"]["arguments"]
+ original_result = messages[2]["content"]
+
+ with (
+ patch.object(compressor, "_compress_window", return_value=(3, 7)),
+ patch.object(compressor, "_generate_summary", return_value="Summary of middle turns."),
+ ):
+ result = compressor.compress(messages, current_tokens=100_000, force=True)
+
+ head_call = next(
+ message for message in result
+ if message.get("role") == "assistant"
+ and any(call.get("id") == "head_call" for call in message.get("tool_calls", []))
+ )
+ head_tool = next(
+ message for message in result
+ if message.get("role") == "tool" and message.get("tool_call_id") == "head_call"
+ )
+ assert head_call["tool_calls"][0]["function"]["arguments"] == original_args
+ assert head_tool["content"] == original_result
+ assert _COMPRESSION_MARKER_PREFIX not in head_call["tool_calls"][0]["function"]["arguments"]
diff --git a/tests/agent/test_context_compressor.py b/tests/agent/test_context_compressor.py
index c2624b6e1af..ace2fd9d3b8 100644
--- a/tests/agent/test_context_compressor.py
+++ b/tests/agent/test_context_compressor.py
@@ -1,4 +1,4 @@
-"""Tests for agent/context_compressor.py — compression logic, thresholds, truncation fallback."""
+"""Tests for agent/context_compressor.py — compression logic, thresholds, and fallbacks."""
import json
import re
@@ -14,12 +14,9 @@ from agent.context_compressor import (
HISTORICAL_TASK_HEADING,
SUMMARY_PREFIX,
COMPRESSED_SUMMARY_METADATA_KEY,
- _COMPRESSION_MARKER_PREFIX,
- _COMPRESSION_MARKER_TEMPLATE,
_PRUNE_MIN_CHARS,
_summarize_tool_result,
_is_summary_access_or_quota_error,
- _truncate_tool_call_args_json,
)
from hermes_state import SessionDB
from agent.auxiliary_client import CODEX_STREAM_STALL_MARKER
@@ -2293,130 +2290,80 @@ class TestThresholdTokensCap:
-class TestTruncateToolCallArgsJson:
- """Regression tests for #11762.
-
- The previous implementation produced invalid JSON by slicing
- ``function.arguments`` mid-string, which caused non-retryable 400s from
- strict providers (observed on MiniMax) and stuck long sessions in a
- re-send loop. The helper here must always emit parseable JSON whose
- shape matches the original — shrunken, not corrupted.
- """
-
- def _helper(self):
- from agent.context_compressor import _truncate_tool_call_args_json
- return _truncate_tool_call_args_json
-
-
-
-
-
- def test_non_string_leaves_preserved(self):
- import json as _json
- shrink = self._helper()
- payload = _json.dumps({
- "retries": 3,
- "enabled": True,
- "timeout": None,
- "items": [1, 2, 3],
- "note": "z" * 500,
- })
- parsed = _json.loads(shrink(payload))
- assert parsed["retries"] == 3
- assert parsed["enabled"] is True
- assert parsed["timeout"] is None
- assert parsed["items"] == [1, 2, 3]
- assert parsed["note"].startswith("z" * 200)
- assert parsed["note"][200:].startswith(_COMPRESSION_MARKER_PREFIX)
+class TestHistoricalToolCallArgumentsStayCanonical:
+ """Regression coverage for #122559: compression may summarize results, never executable args."""
+ @staticmethod
+ def _compressor():
+ return ContextCompressor(
+ model="test/model",
+ config_context_length=100_000,
+ threshold_percent=0.85,
+ protect_first_n=1,
+ protect_last_n=2,
+ quiet_mode=True,
+ )
+ @staticmethod
+ def _write_call(call_id: str, arguments: str) -> dict:
+ return {
+ "role": "assistant",
+ "content": None,
+ "tool_calls": [{
+ "id": call_id,
+ "type": "function",
+ "function": {"name": "write_file", "arguments": arguments},
+ }],
+ }
- def test_pass3_emits_valid_json_for_downstream_provider(self):
- """End-to-end: Pass 3 must never produce the exact failure payload
- that caused the 400 loop (unterminated string, missing brace)."""
- import json as _json
- with patch("agent.context_compressor.get_model_context_length", return_value=100000):
- c = ContextCompressor(
- model="test/model",
- threshold_percent=0.85,
- protect_first_n=1,
- protect_last_n=1,
- quiet_mode=True,
- )
- huge_content = "# Shopping Browser Setup Notes\n\n## Overview\n" + "x " * 400
- args_payload = _json.dumps({
- "path": "~/.hermes/skills/shopping/browser-setup-notes.md",
- "content": huge_content,
- })
- assert len(args_payload) > 500 # triggers the Pass-3 shrink
+ def test_ordinary_prune_keeps_effectful_arguments_byte_exact(self):
+ c = self._compressor()
+ arguments = json.dumps(
+ {"path": "/tmp/app.py", "content": "x" * 4_000},
+ separators=(",", ":"),
+ )
messages = [
- {"role": "user", "content": "please write two files"},
- {"role": "assistant", "content": None, "tool_calls": [
- {"id": "call_1", "type": "function",
- "function": {"name": "write_file", "arguments": args_payload}},
- ]},
- {"role": "tool", "tool_call_id": "call_1",
- "content": '{"bytes_written": 727}'},
- {"role": "user", "content": "ok"},
+ {"role": "user", "content": "write it"},
+ self._write_call("call_1", arguments),
+ {"role": "tool", "tool_call_id": "call_1", "content": "R" * 10_000},
+ {"role": "user", "content": "continue"},
{"role": "assistant", "content": "done"},
]
- result, _ = c._prune_old_tool_results(messages, protect_tail_count=2)
- shrunk = result[1]["tool_calls"][0]["function"]["arguments"]
- # Must parse — otherwise downstream provider returns 400
- parsed = _json.loads(shrunk)
- assert parsed["path"] == "~/.hermes/skills/shopping/browser-setup-notes.md"
- assert parsed["content"].startswith(huge_content[:200])
- assert parsed["content"][200:].startswith(_COMPRESSION_MARKER_PREFIX)
-
-
-class TestTruncationMarkerNotImitable:
- """Regression tests for #83714.
-
- A model replayed its own history containing the bare
- ``"...[truncated]"`` marker and, in a later turn, imitated it — writing
- the literal marker into a *new* tool call's ``new_string`` instead of
- real content. The compressor-side fix is to stop injecting a marker that
- looks like something the model itself would plausibly write.
- """
+ result, pruned = c._prune_old_tool_results(
+ messages, protect_tail_count=2, min_prune_chars=1_000,
+ )
- def test_args_without_a_net_gain_leaf_are_left_byte_identical(self):
- """Leaves the marker would not shrink, and leaves that merely quote the marker.
+ assert pruned >= 1
+ assert result[1]["tool_calls"][0]["function"]["arguments"] == arguments
+ assert "HERMES-CONTEXT-COMPRESSION" not in json.dumps(result, ensure_ascii=False)
- Below the break-even (``head_chars`` + marker) replacing a leaf would grow the payload, and
- re-serialising alone would rewrite compact wire JSON — both read as "this changed" upstream
- and are counted as reclaimed pressure.
- """
- tiny = json.dumps({"new_string": "y" * 201, "pad": "z" * 320})
- assert _truncate_tool_call_args_json(tiny) == tiny
- compact = json.dumps({"new_string": "y" * 201, "pad": "z" * 320}, separators=(",", ":"))
- assert _truncate_tool_call_args_json(compact) == compact
- # Separator whitespace added by the re-serialise can exceed a single leaf's saving.
- many_keys = json.dumps(
- {**{f"k{i}": i for i in range(300)}, "big": "y" * 426}, separators=(",", ":")
+ def test_pressure_demotion_keeps_protected_arguments_byte_exact(self):
+ c = self._compressor()
+ arguments = json.dumps(
+ {"path": "/tmp/app.py", "content": "y" * 8_000},
+ separators=(",", ":"),
)
- assert _truncate_tool_call_args_json(many_keys) == many_keys
-
- # The guard keys on the marker being the whole tail, so the imitation shape #83714
- # describes — replayed head+marker followed by new content — is still shrinkable.
- for leaf in (
- "x" * 1000 + _COMPRESSION_MARKER_PREFIX + " 5 of 9⟫" + "y" * 500,
- "x" * 200 + _COMPRESSION_MARKER_PREFIX + " 5 of 9 chars omitted⟫" + "y" * 5000,
- ):
- out = _truncate_tool_call_args_json(json.dumps({"new_string": leaf}))
- assert json.loads(out)["new_string"] == "x" * 200 + _COMPRESSION_MARKER_TEMPLATE.format(
- omitted=len(leaf) - 200, total=len(leaf)
- )
+ messages = [
+ {"role": "user", "content": "write it"},
+ self._write_call("call_1", arguments),
+ {"role": "tool", "tool_call_id": "call_1", "content": "R" * 12_000},
+ {"role": "user", "content": "follow up"},
+ {"role": "assistant", "content": "ok"},
+ {"role": "user", "content": "again"},
+ {"role": "assistant", "content": "done"},
+ ]
- def test_shrunken_leaf_is_head_plus_marker_and_a_fixed_point(self):
- """Re-shrinking must be a no-op: the marker's counts are its anti-imitation value."""
- payload = json.dumps({"content": "x" * 2000})
- once = _truncate_tool_call_args_json(payload)
- assert len(once) < len(payload)
- assert json.loads(once)["content"] == "x" * 200 + _COMPRESSION_MARKER_TEMPLATE.format(
- omitted=1800, total=2000
+ result, pruned = c._prune_old_tool_results(
+ messages,
+ protect_tail_count=6,
+ protect_tail_tokens=100,
+ min_prune_chars=1_000,
)
- assert _truncate_tool_call_args_json(once) == once
+
+ assert pruned >= 1
+ assert result[1]["tool_calls"][0]["function"]["arguments"] == arguments
+ assert "HERMES-CONTEXT-COMPRESSION" not in json.dumps(result, ensure_ascii=False)
class TestLazyContextResolution:
diff --git a/tests/agent/test_tool_call_guardrail_runtime.py b/tests/agent/test_tool_call_guardrail_runtime.py
index 70beca9cf74..0df8956a45c 100644
--- a/tests/agent/test_tool_call_guardrail_runtime.py
+++ b/tests/agent/test_tool_call_guardrail_runtime.py
@@ -371,11 +371,18 @@ def test_plugin_pre_tool_block_wins_without_counting_as_toolguard_block():
def _compressed_args(field: str) -> dict:
- """Generate the current model-visible prune marker through the real compressor."""
- from agent.context_compressor import _COMPRESSION_MARKER_PREFIX, _truncate_tool_call_args_json
+ """Generate a legacy compression marker for already-contaminated session coverage."""
+ from agent.compression_marker import (
+ _COMPRESSION_MARKER_PREFIX,
+ _COMPRESSION_MARKER_TEMPLATE,
+ )
- raw = json.dumps({field: "z" * 2000})
- parsed = json.loads(_truncate_tool_call_args_json(raw))
+ original = "z" * 2000
+ marker = _COMPRESSION_MARKER_TEMPLATE.format(
+ omitted=len(original) - 200,
+ total=len(original),
+ )
+ parsed = {field: original[:200] + marker}
assert _COMPRESSION_MARKER_PREFIX in parsed[field]
return parsed
diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.md
index 73efc481bfe..2f16c5cb607 100644
--- a/website/docs/user-guide/configuration.md
+++ b/website/docs/user-guide/configuration.md
@@ -1049,7 +1049,7 @@ The value is the **first rung** of an escalating ladder, not a fixed interval: c
`idle_compact_after_seconds` is an **opt-in, time-based** trigger that complements the size-based `threshold`. Default `0` (disabled). When set above 0, a session that resumes after at least that many seconds of inactivity compacts its accumulated history up front, before the first reply — so a long-lived thread (e.g. a Telegram conversation you come back to hours later) doesn't re-read its full stale context on every subsequent turn. It never fires when the context is already at or below the post-compression target (`threshold × target_ratio`), and it honors the same failure-cooldown, anti-thrash, and per-session lock guards as every automatic compaction. Example: `idle_compact_after_seconds: 1800` compacts after 30 minutes idle.
-`proactive_prune_tokens` enables a deterministic, no-LLM prune of old tool-result payloads that runs independently of `threshold`. On large-window models the `threshold` compaction (≈50% of the window) rarely fires, so bulky tool outputs (terminal dumps, file reads, web extracts) ride along in history and get re-sent on every subsequent turn. When re-sent history exceeds `proactive_prune_tokens` (default `0` = off; try `48000` to enable), the prune dedupes identical results, summarizes older oversized ones, and truncates large tool-call arguments — protecting the most recent `protect_last_n` messages and never calling the model. That protection is not absolute: every compaction also runs a *pressure* pass that demotes tool results and truncates tool-call arguments **inside** the protected tail when the tail alone exceeds 1.5× its token budget (it is not gated on `proactive_prune_tokens`). Both passes rewrite only the history copy the model re-reads — a tool call is executed from the provider's live response, never from history, so an already-dispatched call's arguments are never altered by either pass. Full outputs stay recoverable from the session store. `proactive_prune_min_result_chars` (default `8000`, clamped to ≥ 200) sets the size below which a tool result is left untouched. `proactive_prune_min_reclaim_tokens` (default `4096`) prevents a prune from committing unless it reclaims at least that many tokens — a committed prune rewrites already-sent history and invalidates the provider's prompt-cache prefix, so this gate keeps those cache breaks episodic and amortized (one meaningful break, like a compression boundary) instead of firing on every tool iteration. This runs only under the built-in `compressor` engine; other context engines inherit a no-op.
+`proactive_prune_tokens` enables a deterministic, no-LLM prune of old tool-result payloads that runs independently of `threshold`. On large-window models the `threshold` compaction (≈50% of the window) rarely fires, so bulky tool outputs (terminal dumps, file reads, web extracts) ride along in history and get re-sent on every subsequent turn. When re-sent history exceeds `proactive_prune_tokens` (default `0` = off; try `48000` to enable), the prune dedupes identical results and summarizes older oversized tool results, protecting the most recent `protect_last_n` messages and never calling the model. Tool-call arguments are execution records and are never rewritten by pruning; the summary model has a separate bounded serializer for copies included in its prompt. The pressure pass likewise demotes tool-result bodies only. During full semantic compaction those demotions live only in the summarizer working copy: carried head/tail rows come from canonical history. The opt-in proactive prune still commits eligible tool-result-body demotions, so `proactive_prune_min_reclaim_tokens` (default `4096`) keeps those cache-breaking commits episodic; `proactive_prune_min_result_chars` (default `8000`, clamped to ≥ 200) sets the size below which a tool result is left untouched. This runs only under the built-in `compressor` engine; other context engines inherit a no-op.
:::tip Gateway hot-reload of compression and context length
As of recent releases, editing `model.context_length` or any `compression.*` key in `config.yaml` on a running gateway takes effect on the next message — no gateway restart, no `/reset`, no session rotation required. The cached-agent signature includes these keys, so the gateway transparently rebuilds the agent when it sees a change. API keys and tool/skill config still require the usual reload paths.