Skip to content

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.

fix(review-3): address third-pass PR #210 feedback

chopratejas504f20a1f785
diff --git a/headroom/cli/proxy.py b/headroom/cli/proxy.py
index 303c9d6ea..2dafc9a7b 100644
--- a/headroom/cli/proxy.py
+++ b/headroom/cli/proxy.py
@@ -1,6 +1,7 @@
"""Proxy server CLI commands."""
import os
+import sys
import click
@@ -288,13 +289,17 @@ def proxy(
critical_tools = ["ast-grep"]
missing = [t for t in critical_tools if not resolved_tools.get(t)]
if missing:
+ # User explicitly opted in — fail fast rather than silently starting
+ # with non-functional interceptors. They can retry with the tool
+ # installed, or drop the flag if they want pass-through behavior.
click.secho(
- f"warning: --intercept-tool-results set but tool(s) unavailable: {missing}. "
- "Interceptors depending on them will silently pass through. "
- "Run `headroom tools doctor` to diagnose.",
- fg="yellow",
+ f"error: --intercept-tool-results requires tool(s) that could not "
+ f"be installed: {missing}. Run `headroom tools doctor` to diagnose, "
+ "or omit the flag to start the proxy without interceptors.",
+ fg="red",
err=True,
)
+ sys.exit(1)
os.environ["HEADROOM_INTERCEPT_ENABLED"] = "1"
# Resolve API URL overrides: CLI flag > env var > None
diff --git a/headroom/config.py b/headroom/config.py
index 4eaf3197b..c18a130e5 100644
--- a/headroom/config.py
+++ b/headroom/config.py
@@ -629,6 +629,10 @@ class HeadroomConfig:
default_factory=lambda: IntelligentContextConfig(enabled=False)
)
+ # Tool-result interceptors (ast-grep Read outline, etc.). Opt-in for now.
+ # Env var HEADROOM_INTERCEPT_ENABLED=1 also enables (for CLI `--intercept-tool-results`).
+ intercept_tool_results: bool = False
+
# Debugging - opt-in diff artifact generation
generate_diff_artifact: bool = False # Enable to get detailed transform diffs
diff --git a/headroom/proxy/interceptors/astgrep.py b/headroom/proxy/interceptors/astgrep.py
index ed0874bb6..8fcb3f89e 100644
--- a/headroom/proxy/interceptors/astgrep.py
+++ b/headroom/proxy/interceptors/astgrep.py
@@ -111,7 +111,11 @@ class AstGrepReadOutline:
return None
try:
exe = binaries.resolve("ast-grep")
- except binaries.PlatformNotSupported:
+ except (binaries.BinaryError, KeyError, OSError) as e:
+ # Covers PlatformNotSupported, OfflineError, BinaryFetchError,
+ # Sha256Mismatch, unknown-tool KeyError, and FS permission errors.
+ # Any of these means the interceptor simply passes through.
+ logger.debug("ast-grep unavailable: %s", e)
return None
matches = _run_ast_grep(exe, lang, tool_output)
@@ -177,8 +181,11 @@ def _run_ast_grep(
tmp_dir = Path(tempfile.mkdtemp(prefix="headroom-sg-"))
try:
os.chmod(tmp_dir, 0o700)
- except OSError:
- pass # best-effort on Windows / restricted FS
+ except OSError as e:
+ # On Windows / restricted FS chmod has no effect, but silently
+ # swallowing means a shared-tmp system may leave untrusted content
+ # world-readable without any indication. Log so the miss is visible.
+ logger.debug("chmod 0700 failed for %s: %s (hardening skipped)", tmp_dir, e)
tmp_path = tmp_dir / f"src{ext}"
tmp_path.write_text(source, encoding="utf-8")
diff --git a/headroom/proxy/interceptors/base.py b/headroom/proxy/interceptors/base.py
index 996d8c938..6f9b689a9 100644
--- a/headroom/proxy/interceptors/base.py
+++ b/headroom/proxy/interceptors/base.py
@@ -154,7 +154,16 @@ def _build_tool_use_index(
if isinstance(raw_args, str):
try:
args = json.loads(raw_args)
- except json.JSONDecodeError:
+ except json.JSONDecodeError as e:
+ # Empty dict means range-key checks fail for this call
+ # (interceptor may outline despite an explicit line range).
+ # Log so the miss is diagnosable.
+ logger.debug(
+ "tool_call %s arguments failed to JSON-decode: %s; "
+ "proceeding with empty args (range-key checks disabled)",
+ cid,
+ e,
+ )
args = {}
elif isinstance(raw_args, dict):
args = raw_args
@@ -183,27 +192,63 @@ def _tool_use_id_for_message(msg: dict[str, Any]) -> str | None:
def apply_to_messages(
messages: list[dict[str, Any]],
tokenizer: Tokenizer,
+ *,
+ frozen_count: int = 0,
) -> InterceptionResult:
"""Run every registered interceptor against every tool_result in `messages`.
+ `frozen_count`: leading messages in the provider's prefix cache that
+ MUST be passed through verbatim. Their tool_uses are still scanned so
+ that progressive disclosure works across the prefix / tail boundary —
+ e.g., a file first Read in the frozen prefix won't be re-outlined when
+ the model Reads it again in the mutable tail.
+
Returns the (possibly) rewritten message list and a list of spans that
actually saved tokens.
"""
if not INTERCEPTORS:
return InterceptionResult(messages=messages, spans=[])
- new_messages: list[dict[str, Any]] = []
spans: list[TransformSpan] = []
# Progressive disclosure: per-interceptor set of keys already rewritten
# earlier in this message list. Prevents the second Read of the same
# file from being outlined again — the model evidently came back for
# more, so give it the raw content.
fired: dict[str, set[str]] = {}
- # Build O(1) tool_use lookup index once per request — prior implementation
- # was O(n²) on long conversations.
+ # Build O(1) tool_use lookup index once per request (over ALL messages,
+ # including the frozen prefix, so keys resolve correctly even when the
+ # tool_use lives in the frozen part).
tool_use_index = _build_tool_use_index(messages)
- for msg in messages:
+ # Pre-seed `fired` from the frozen prefix so that any file already Read
+ # in the cached prefix counts as "already disclosed" for subsequent reads.
+ for msg in messages[:frozen_count]:
+ if not _is_tool_result_message(msg):
+ continue
+ frozen_tuid = _tool_use_id_for_message(msg)
+ if not frozen_tuid:
+ continue
+ f_tool_name, f_tool_input = tool_use_index.get(frozen_tuid, (None, {}))
+ for interceptor in INTERCEPTORS:
+ key_fn = getattr(interceptor, "progressive_disclosure_key", None)
+ if not callable(key_fn):
+ continue
+ try:
+ k = key_fn(f_tool_name, f_tool_input)
+ except Exception as e: # noqa: BLE001
+ logger.debug(
+ "interceptor %s key() failed on frozen prefix: %s",
+ interceptor.name,
+ e,
+ )
+ continue
+ if k:
+ fired.setdefault(interceptor.name, set()).add(k)
+
+ # Pass frozen messages through verbatim; only the mutable tail is
+ # considered for rewriting.
+ new_messages: list[dict[str, Any]] = list(messages[:frozen_count])
+ for msg in messages[frozen_count:]:
if not _is_tool_result_message(msg):
new_messages.append(msg)
continue
@@ -231,7 +276,12 @@ def apply_to_messages(
try:
key = key_fn(tool_name, tool_input)
except Exception as e: # noqa: BLE001
- logger.warning("interceptor %s key() failed: %s", interceptor.name, e)
+ logger.warning(
+ "interceptor %s key() failed: %s",
+ interceptor.name,
+ e,
+ exc_info=True,
+ )
_record_failure(interceptor.name)
# Skip this interceptor entirely rather than firing
# without progressive-disclosure protection — a broken
@@ -245,7 +295,12 @@ def apply_to_messages(
continue
rewritten = interceptor.transform(tool_name, tool_input, current)
except Exception as e: # noqa: BLE001 — never crash a request
- logger.warning("interceptor %s failed: %s", interceptor.name, e)
+ logger.warning(
+ "interceptor %s failed: %s",
+ interceptor.name,
+ e,
+ exc_info=True,
+ )
_record_failure(interceptor.name)
continue
if not rewritten or rewritten == current:
@@ -296,19 +351,15 @@ class ToolResultInterceptorTransform(Transform):
# overhead that spans don't track.
tokens_before = tokenizer.count_messages(messages)
- # Honor the frozen prefix: never touch cached messages.
+ # `apply_to_messages` handles the frozen/mutable split internally
+ # and pre-seeds progressive-disclosure state from the frozen prefix
+ # so a file already Read there isn't re-outlined in the tail.
frozen = int(kwargs.get("frozen_message_count") or 0)
- if frozen > 0:
- frozen_msgs, mutable_msgs = messages[:frozen], messages[frozen:]
- else:
- frozen_msgs, mutable_msgs = [], messages
-
- result = apply_to_messages(mutable_msgs, tokenizer)
- out_messages = frozen_msgs + result.messages
- tokens_after = tokenizer.count_messages(out_messages)
+ result = apply_to_messages(messages, tokenizer, frozen_count=frozen)
+ tokens_after = tokenizer.count_messages(result.messages)
transforms_applied = [f"interceptor:{s.tool}" for s in result.spans] if result.spans else []
return TransformResult(
- messages=out_messages,
+ messages=result.messages,
tokens_before=tokens_before,
tokens_after=tokens_after,
transforms_applied=transforms_applied,
diff --git a/headroom/transforms/pipeline.py b/headroom/transforms/pipeline.py
index 6d6cecc26..9140f4e10 100644
--- a/headroom/transforms/pipeline.py
+++ b/headroom/transforms/pipeline.py
@@ -77,12 +77,15 @@ class TransformPipeline:
# 0. Tool-result interceptors (ast-grep Read outline, etc.) run first
# so downstream compressors operate on the already-shrunk content.
- # OPT-IN: enable with HEADROOM_INTERCEPT_ENABLED=1 or `headroom proxy
- # --intercept-tool-results`. Off by default while this ships — lets
+ # OPT-IN: enable via HeadroomConfig.intercept_tool_results, or for
+ # non-config callers (CLI / SDK / tests) the env var
+ # HEADROOM_INTERCEPT_ENABLED=1. Off by default while this ships — lets
# users try it and compare before we make it the default.
import os as _os
- if _os.environ.get("HEADROOM_INTERCEPT_ENABLED"):
+ if getattr(self.config, "intercept_tool_results", False) or _os.environ.get(
+ "HEADROOM_INTERCEPT_ENABLED"
+ ):
from headroom.proxy.interceptors import ToolResultInterceptorTransform
transforms.append(ToolResultInterceptorTransform())
diff --git a/tests/test_tool_result_interceptors.py b/tests/test_tool_result_interceptors.py
index f5d9d6f98..b6b139a86 100644
--- a/tests/test_tool_result_interceptors.py
+++ b/tests/test_tool_result_interceptors.py
@@ -628,6 +628,69 @@ def test_transform_adapter_respects_frozen_message_count(tokenizer):
assert "outlined by ast-grep" in result.messages[3]["content"][0]["content"]
+def test_progressive_disclosure_respects_frozen_prefix_history(tokenizer):
+ """If a file was Read in the frozen prefix, re-reading it in the mutable
+ tail passes through — even though apply_to_messages only sees the tail
+ for rewriting, it pre-scans the frozen prefix to seed `fired` keys.
+ """
+ transform = ToolResultInterceptorTransform()
+ messages = [
+ # Frozen prefix: first Read of payments.py. This is cached, so we
+ # don't outline it; but it counts as "already disclosed."
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "tool_use",
+ "id": "frozen-read",
+ "name": "Read",
+ "input": {"file_path": "/repo/payments.py"},
+ }
+ ],
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": "frozen-read",
+ "content": _PY_FIXTURE,
+ }
+ ],
+ },
+ # Mutable tail: model reads payments.py again — should pass through
+ # because the frozen prefix already served it.
+ {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "tool_use",
+ "id": "tail-read",
+ "name": "Read",
+ "input": {"file_path": "/repo/payments.py"},
+ }
+ ],
+ },
+ {
+ "role": "user",
+ "content": [
+ {
+ "type": "tool_result",
+ "tool_use_id": "tail-read",
+ "content": _PY_FIXTURE,
+ }
+ ],
+ },
+ ]
+ result = transform.apply(messages, tokenizer, frozen_message_count=2)
+ # Tail re-read preserved (not outlined) because the frozen prefix
+ # already exposed the file.
+ tail_content = result.messages[3]["content"][0]["content"]
+ assert "outlined by ast-grep" not in tail_content
+ assert "def process_payment" in tail_content
+ assert "subtotal = compute_subtotal(items)" in tail_content
+
+
def test_transform_adapter_tokens_before_is_baseline_not_reconstruction(tokenizer):
"""tokens_before must reflect the real original messages, not back-calc."""
transform = ToolResultInterceptorTransform()