Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(transforms): keep file-read protection in token mode under the coding profile (#3885)
gglucass1512c0623506
diff --git a/headroom/transforms/content_router.py b/headroom/transforms/content_router.pyindex 18514253f..d672688dc 100644--- a/headroom/transforms/content_router.py+++ b/headroom/transforms/content_router.py@@ -5509,6 +5509,7 @@ class ContentRouter(Transform):runtime_read_protection_window = kwargs.get("read_protection_window")if (runtime_read_protection_window is not None+ and int(runtime_read_protection_window) > 0and self.config.protect_recent_reads_fraction > 0):# A profile-derived window may only narrow protection when the@@ -5517,7 +5518,11 @@ class ContentRouter(Transform):# See #1374's documented contract: protected tool output must never# lossy-compress "regardless of conversation depth" -- a per-request# savings-profile kwarg must not silently weaken that.- read_protection_window = max(0, int(runtime_read_protection_window))+ # A window of 0 is "no override", not "protect nothing": it comes+ # from a profile's protect_recent=0 (coding, general), a positional+ # guard for cache mode, and would otherwise strip file reads of all+ # protection in token mode, down to the newest message.+ read_protection_window = int(runtime_read_protection_window)# Adaptive compression ratio: scale with context pressureif model_limit > 0:diff --git a/tests/test_content_router_exclude_tools.py b/tests/test_content_router_exclude_tools.pyindex e1fedc4ae..ad1d44497 100644--- a/tests/test_content_router_exclude_tools.py+++ b/tests/test_content_router_exclude_tools.py@@ -214,6 +214,97 @@ def test_protect_tool_results_survives_runtime_read_protection_window_kwarg() ->assert "router:excluded:tool" in result.transforms_applied+# ---------------------------------------------------------------------------+# Test 5: token mode + coding profile keeps recent file reads byte-exact+# ---------------------------------------------------------------------------+++ ("trailing_turns", "window", "protected"),+ [+ (0, None, True), # newest Read, the profile's window of 0+ (1, None, True), # 3 from the end, inside max(4, 0.3*n)+ (1, 2, False), # a positive profile window still narrows it+ (20, None, False), # past the 0.3 window: ages out+ ],+)+def test_token_mode_coding_profile_keeps_recent_read_byte_exact(+ trailing_turns: int, window: int | None, protected: bool, monkeypatch: pytest.MonkeyPatch+) -> None:+ """The coding profile's protect_recent=0 reaches the router as+ read_protection_window=0. In token mode (fraction 0.3) that used to replace+ the max(4, 0.3*n) window with 0, so a `Read` result lossy-compressed even+ as the newest message. Recent reads must stay byte-exact; reads past the+ fraction window still age out to compression, and a positive profile+ window still narrows the fraction window."""+ pytest.importorskip("tiktoken")++ from types import SimpleNamespace++ from headroom.agent_savings import proxy_pipeline_kwargs+ from headroom.providers import OpenAIProvider+ from headroom.tokenizer import Tokenizer++ tokenizer = Tokenizer(OpenAIProvider().get_token_counter("gpt-4o"), "gpt-4o")+ proxy = _build(mode="token", savings_profile="coding")+ router = _router(proxy)+ assert router.config.protect_recent_reads_fraction == 0.3++ class FakeKompress:+ def is_ready(self) -> bool:+ return True++ def ensure_background_load(self) -> None:+ pass++ def compress(self, content, **kwargs):+ compressed = " ".join(content.split()[:20]) + " Retrieve more: hash=deadbeef"+ return SimpleNamespace(compressed=compressed, compressed_tokens=len(compressed.split()))++ monkeypatch.setattr(router, "_get_kompress", lambda: FakeKompress())++ read_output = "\n".join(+ f"{i:>6}\tThe release notes describe change number {i} and its rollout plan."+ for i in range(1, 121)+ )+ messages: list[dict[str, object]] = [+ {"role": "user", "content": "read the notes"},+ {+ "role": "assistant",+ "content": [+ {+ "type": "tool_use",+ "id": "toolu_read_1",+ "name": "Read",+ "input": {"file_path": "/repo/NOTES.md"},+ }+ ],+ },+ {+ "role": "user",+ "content": [+ {"type": "tool_result", "tool_use_id": "toolu_read_1", "content": read_output}+ ],+ },+ ]+ for i in range(trailing_turns):+ messages.append({"role": "assistant", "content": f"reply {i}"})+ messages.append({"role": "user", "content": f"follow-up {i}"})++ kwargs = proxy_pipeline_kwargs(proxy.config)+ assert kwargs["read_protection_window"] == 0+ if window is not None:+ kwargs["read_protection_window"] = window+ result = router.apply(messages, tokenizer, **kwargs)++ content = result.messages[2]["content"][0]["content"]+ if protected:+ assert content == read_output, "a recent Read must stay byte-exact in token mode"+ assert "router:excluded:tool" in result.transforms_applied+ else:+ assert content != read_output, "a Read outside the window still ages out"++# ---------------------------------------------------------------------------# Baseline: Bash NOT in DEFAULT_EXCLUDE_TOOLS (unchanged by this PR)# ---------------------------------------------------------------------------