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(smart-crusher): preserve wrapped retrieval results in apply (#4149)
Mansurshakh Japarov9762a14a40bd
diff --git a/docs/content/docs/smart-crusher.mdx b/docs/content/docs/smart-crusher.mdxindex b2bf1c75d..cd7e335f4 100644--- a/docs/content/docs/smart-crusher.mdx+++ b/docs/content/docs/smart-crusher.mdx@@ -73,6 +73,22 @@ print(result.strategy) # e.g. "lossless:table(...)" or "smart_sample(1000->15)"</Tab></Tabs>+### Recovered tool output in the Python message transform++`SmartCrusher.apply(messages, tokenizer)` preserves recognized+`headroom_retrieve` results byte for byte when their call ID matches the+originating assistant call. The originating identity is resolved with the+shared wrapper parser for both OpenAI `tool_calls`/`arguments` and Anthropic+`tool_use`/`input`, including Hermes `tool_call` bridges and retrieval calls+inside `execute`, `exec`, or `functions.exec`.++Other wrapper output remains compressible; an unrecognized or ambiguous+wrapper does not gain a blanket recovery exemption. Keep the originating+assistant call in the message history so the result can be identified.+The context-free `crush(json_string)` API has no originating-call history and+does not provide this message-level exemption.++## Configuration<Tabs groupId="lang" items={['TypeScript', 'Python']}>diff --git a/headroom/transforms/smart_crusher.py b/headroom/transforms/smart_crusher.pyindex c7a0b0917..66bb85962 100644--- a/headroom/transforms/smart_crusher.py+++ b/headroom/transforms/smart_crusher.py@@ -52,7 +52,7 @@ from dataclasses import dataclassfrom typing import Anyfrom ..ccr.tool_injection import CCR_TOOL_NAME-from ..config import CCRConfig, TransformResult, is_tool_excluded+from ..config import CCRConfig, TransformResult, is_tool_excluded, unwrap_tool_call_namefrom ..tokenizer import Tokenizerfrom ..utils import compute_short_hash, create_tool_digest_marker, deep_copy_messagesfrom .base import Transform@@ -129,7 +129,7 @@ def strip_ccr_sentinels(items: Any) -> Any:def _build_tool_name_index(messages: list[dict[str, Any]]) -> dict[str, str]:- """Map tool_call_id/tool_use_id → tool name across OpenAI + Anthropic formats.+ """Map tool_call_id/tool_use_id → effective tool name in both wire formats.Skips entries where id or name is missing; those calls still crush, butwon't contribute a tool-name to the ``smart_crush`` tag.@@ -140,9 +140,10 @@ def _build_tool_name_index(messages: list[dict[str, Any]]) -> dict[str, str]:continuefor tc in msg.get("tool_calls") or []:tc_id = tc.get("id")- name = (tc.get("function") or {}).get("name")- if tc_id and name:- index[tc_id] = name+ function = tc.get("function") or {}+ name = function.get("name")+ if tc_id and isinstance(name, str) and name:+ index[tc_id] = unwrap_tool_call_name(name, function.get("arguments"))content = msg.get("content")if isinstance(content, list):for block in content:@@ -150,8 +151,8 @@ def _build_tool_name_index(messages: list[dict[str, Any]]) -> dict[str, str]:continuebid = block.get("id")name = block.get("name")- if bid and name:- index[bid] = name+ if bid and isinstance(name, str) and name:+ index[bid] = unwrap_tool_call_name(name, block.get("input"))return indexdiff --git a/tests/test_transforms/test_smart_crusher_ccr_retrieve_exemption.py b/tests/test_transforms/test_smart_crusher_ccr_retrieve_exemption.pyindex da76bb130..ecdbf2cd6 100644--- a/tests/test_transforms/test_smart_crusher_ccr_retrieve_exemption.py+++ b/tests/test_transforms/test_smart_crusher_ccr_retrieve_exemption.py@@ -9,6 +9,7 @@ that content again → new <<ccr:hash>> marker → infinite retrieval loop.from __future__ import annotationsimport json+from copy import deepcopyimport pytest@@ -80,29 +81,6 @@ class TestHeadroomRetrieveExemptionOpenAI:# No CCR transforms should have firedassert not any("smart_crush" in t for t in result.transforms_applied)- def test_non_retrieve_tool_still_compressed(self):- """Normal tool results are still compressed — exemption is narrow."""- content = _big_content()- messages = [- {- "role": "assistant",- "tool_calls": [- {- "id": "call_xyz",- "function": {"name": "Bash", "arguments": '{"cmd":"ls"}'},- }- ],- },- {"role": "tool", "tool_call_id": "call_xyz", "content": content},- ]- crusher = _make_crusher(min_tokens=0)- tokenizer = _get_tokenizer()- result = crusher.apply(messages, tokenizer)-- tool_msg = result.messages[1]- # Content should have been modified (compressed)- assert tool_msg["content"] != content or result.tokens_after <= result.tokens_before-class TestHeadroomRetrieveExemptionAnthropic:"""Anthropic-style tool_result content blocks from headroom_retrieve must not be crushed."""@@ -145,42 +123,6 @@ class TestHeadroomRetrieveExemptionAnthropic:)assert not any("smart_crush" in t for t in result.transforms_applied)- def test_non_retrieve_anthropic_tool_still_compressed(self):- """Normal Anthropic tool_result blocks are still compressed."""- content = _big_content()- messages = [- {- "role": "assistant",- "content": [- {- "type": "tool_use",- "id": "toolu_bash_1",- "name": "Bash",- "input": {"cmd": "ls"},- }- ],- },- {- "role": "user",- "content": [- {- "type": "tool_result",- "tool_use_id": "toolu_bash_1",- "content": content,- }- ],- },- ]- crusher = _make_crusher(min_tokens=0)- tokenizer = _get_tokenizer()- result = crusher.apply(messages, tokenizer)-- # Either the content changed (compressed) or tokens went down- tool_result_block = result.messages[1]["content"][0]- assert (- tool_result_block["content"] != content or result.tokens_after <= result.tokens_before- )-def test_mixed_retrieve_and_normal_only_normal_compressed(self):"""With two tool_results in one user turn, only the non-CCR one is compressed."""content = _big_content()@@ -224,11 +166,139 @@ class TestHeadroomRetrieveExemptionAnthropic:blocks = result.messages[1]["content"]ccr_block = blocks[0]- bash_block = blocks[1]# headroom_retrieve result must be untouchedassert ccr_block["content"] == content, ("headroom_retrieve result was compressed — infinite loop bug #1077")- # The bash result should differ (or at least the crush count > 0)- assert bash_block["content"] != content or result.tokens_after < result.tokens_before++[email protected]("wire", ["openai", "anthropic"])[email protected]("wrapper", ["tool_call", "functions.exec"])+def test_wrapped_retrieval_is_exact_and_unrelated_wrapper_remains_compressible(wire, wrapper):+ content = json.dumps([{"id": i, "value": "sample record " * 8} for i in range(200)])+ retrieval_args = (+ {"name": CCR_TOOL_NAME, "arguments": {"hash": "abc123def456"}}+ if wrapper == "tool_call"+ else {"code": 'text(await tools.mcp__headroom__headroom_retrieve({hash: "abc123def456"}))'}+ )+ ordinary_args = (+ {"name": "Bash", "arguments": {"command": "echo sample"}}+ if wrapper == "tool_call"+ else {"code": 'text(await tools.exec_command({cmd: "echo sample"}))'}+ )+ if wire == "openai":+ messages = [+ {+ "role": "assistant",+ "tool_calls": [+ {+ "id": "retrieved",+ "function": {"name": wrapper, "arguments": json.dumps(retrieval_args)},+ },+ {+ "id": "ordinary",+ "function": {"name": wrapper, "arguments": json.dumps(ordinary_args)},+ },+ ],+ },+ {"role": "tool", "tool_call_id": "retrieved", "content": content},+ {"role": "tool", "tool_call_id": "ordinary", "content": content},+ ]+ else:+ messages = [+ {+ "role": "assistant",+ "content": [+ {+ "type": "tool_use",+ "id": "retrieved",+ "name": wrapper,+ "input": retrieval_args,+ },+ {+ "type": "tool_use",+ "id": "ordinary",+ "name": wrapper,+ "input": ordinary_args,+ },+ ],+ },+ {+ "role": "user",+ "content": [+ {"type": "tool_result", "tool_use_id": "retrieved", "content": content},+ {"type": "tool_result", "tool_use_id": "ordinary", "content": content},+ ],+ },+ ]+ result = _make_crusher(min_tokens=0).apply(messages, _get_tokenizer())+ if wire == "openai":+ recovered = result.messages[1]["content"]+ ordinary = result.messages[2]["content"]+ else:+ recovered = result.messages[1]["content"][0]["content"]+ ordinary = result.messages[1]["content"][1]["content"]+ assert recovered == content+ assert ordinary != content+++def _messages_with_tool_name(wire, name):+ if wire == "openai":+ return [+ {+ "role": "assistant",+ "tool_calls": [+ {"id": "call_1", "function": {"name": name, "arguments": "{}"}},+ ],+ },+ {"role": "tool", "tool_call_id": "call_1", "content": "ok"},+ ]+ return [+ {+ "role": "assistant",+ "content": [+ {"type": "tool_use", "id": "call_1", "name": name, "input": {}},+ ],+ },+ {+ "role": "user",+ "content": [+ {"type": "tool_result", "tool_use_id": "call_1", "content": "ok"},+ ],+ },+ ]++[email protected]("wire", ["openai", "anthropic"])+ "name",+ [["Bash"], {"name": "Bash"}, 7, True, None, ""],+ ids=["list", "dict", "integer", "boolean", "null", "empty"],+)+def test_invalid_tool_names_are_unresolved(wire, name):+ """Both wire formats reject non-string names before shared wrapper parsing."""+ from headroom.transforms.smart_crusher import _build_tool_name_index++ messages = _messages_with_tool_name(wire, name)+ original = deepcopy(messages)+ assert _build_tool_name_index(messages) == {}+ assert messages == original+++ "name",+ [["Bash"], {"name": "Bash"}, 7, True, None, ""],+ ids=["list", "dict", "integer", "boolean", "null", "empty"],+)+def test_invalid_openai_tool_names_leave_small_results_unchanged(name):+ """The real OpenAI counter reaches indexing even for malformed function names."""+ messages = _messages_with_tool_name("openai", name)+ original = deepcopy(messages)+ result = _make_crusher(min_tokens=200).apply(messages, _get_tokenizer())++ assert result.messages == original+ assert messages == original+ assert result.transforms_applied == []+ assert result.markers_inserted == []+ assert result.tokens_before == result.tokens_after