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(wrap): warn when reused proxy ignores compression settings (#4019)

Mansurshakh Japarov278bbc877193
diff --git a/docs/content/docs/proxy.mdx b/docs/content/docs/proxy.mdx
index d1abf0ffc..02ddd60e8 100644
--- a/docs/content/docs/proxy.mdx
+++ b/docs/content/docs/proxy.mdx
@@ -886,6 +886,18 @@ headroom wrap cursor
headroom wrap grok-build
```
+Wrapping can reuse an existing proxy instead of starting a new process. Its
+startup-only settings do not change when you export different values in the
+calling shell. `wrap` warns when an explicit `HEADROOM_MODE`,
+`HEADROOM_MIN_TOKENS`, or `HEADROOM_EXCLUDE_TOOLS` disagrees with the settings
+reported by that proxy. It does not restart a shared proxy or interrupt other
+clients. Restart the proxy with the desired settings, or use `--port` to start
+a separate instance. Tool exclusions are compared case-insensitively using the
+effective router exclusions, including built-ins and tools protected by
+`HEADROOM_PROTECT_TOOL_RESULTS`. Older proxies that do not report a setting
+cannot be compared for that setting.
+
+
`headroom wrap codex` keeps routing scoped to the Codex process it launches: it
passes the proxy URL as a `--config` override and never writes it to
`~/.codex/config.toml`. Codex runs any session started with command-line
diff --git a/headroom/cli/wrap.py b/headroom/cli/wrap.py
index c9e977fc7..b5e22d9be 100644
--- a/headroom/cli/wrap.py
+++ b/headroom/cli/wrap.py
@@ -5131,7 +5131,13 @@ def _ensure_proxy_unlocked(
_warn_proxy_mode_mismatch(running_config)
elif not helpers._check_proxy(port):
click.echo(f" Warning: No proxy detected on port {port}")
- elif vertex_api_url or clear_vertex_api_url or os.environ.get("HEADROOM_MODE"):
+ elif (
+ vertex_api_url
+ or clear_vertex_api_url
+ or os.environ.get("HEADROOM_MODE")
+ or os.environ.get("HEADROOM_MIN_TOKENS") is not None
+ or os.environ.get("HEADROOM_EXCLUDE_TOOLS") is not None
+ ):
health_payload = helpers._query_proxy_health(port)
running_config = helpers._proxy_health_config(health_payload)
if running_config is None:
@@ -9041,12 +9047,49 @@ def unwrap_zcode(port: int, no_stop_proxy: bool) -> None:
def _warn_proxy_mode_mismatch(running_config: dict[str, Any] | None) -> None:
- """Warn when a reused proxy runs a different mode than this session asked for.
+ """Warn when reuse ignores this session's startup-only settings.
- Mode is fixed at proxy startup, so a requested HEADROOM_MODE (explicit, or
- a wrap target's default_mode) is silently ignored on reuse. Warning-only:
- other clients may be attached to the running proxy.
+ Do not restart a shared proxy: other clients may be attached to it.
"""
+ config = running_config or {}
+ mismatches: list[str] = []
+ requested_min = os.environ.get("HEADROOM_MIN_TOKENS")
+ running_min = config.get("min_tokens_to_crush")
+ if requested_min is not None and isinstance(running_min, int):
+ try:
+ requested_min_value = int(requested_min)
+ except ValueError:
+ requested_min_value = None
+ if requested_min_value is not None and requested_min_value != running_min:
+ mismatches.append(f"HEADROOM_MIN_TOKENS={requested_min_value} (running: {running_min})")
+
+ requested_excludes = os.environ.get("HEADROOM_EXCLUDE_TOOLS")
+ running_excludes = config.get("exclude_tools")
+ if (
+ requested_excludes is not None
+ and isinstance(running_excludes, list)
+ and all(isinstance(name, str) for name in running_excludes)
+ ):
+ from headroom.config import DEFAULT_EXCLUDE_TOOLS
+
+ defaults = {name.lower() for name in DEFAULT_EXCLUDE_TOOLS}
+ requested_names = {
+ name.strip().lower() for name in requested_excludes.split(",") if name.strip()
+ }
+ running_names = {name.lower() for name in running_excludes}
+ if requested_names | defaults != running_names | defaults:
+ mismatches.append(
+ f"HEADROOM_EXCLUDE_TOOLS={sorted(requested_names)!r} "
+ f"(running: {sorted(running_names)!r})"
+ )
+
+ if mismatches:
+ click.echo(
+ " Warning: this session requested "
+ + "; ".join(mismatches)
+ + ", but those settings are fixed at proxy startup. "
+ "Restart the proxy, or use --port for a separate one."
+ )
requested = os.environ.get("HEADROOM_MODE")
running = (running_config or {}).get("mode")
if not requested or not isinstance(running, str):
diff --git a/headroom/proxy/server.py b/headroom/proxy/server.py
index ccedd24a2..c3f68eb80 100644
--- a/headroom/proxy/server.py
+++ b/headroom/proxy/server.py
@@ -3847,6 +3847,13 @@ def create_app(config: ProxyConfig | None = None) -> FastAPI:
"min_tokens_to_compress",
config.min_tokens_to_crush,
),
+ "exclude_tools": sorted(
+ {
+ *DEFAULT_EXCLUDE_TOOLS,
+ *(config.exclude_tools or ()),
+ *(config.protect_tool_results or ()),
+ }
+ ),
"max_items_after_crush": profile_kwargs.get(
"max_items_after_crush",
config.max_items_after_crush,
diff --git a/tests/test_cli/test_wrap_bob.py b/tests/test_cli/test_wrap_bob.py
index 3e85fe113..0500047d0 100644
--- a/tests/test_cli/test_wrap_bob.py
+++ b/tests/test_cli/test_wrap_bob.py
@@ -291,6 +291,72 @@ class TestModeMismatchWarning:
assert self._warnings(monkeypatch, running_config, requested) == []
+class TestStartupCompressionMismatchWarning:
+ @pytest.fixture(autouse=True)
+ def _session_env(self, monkeypatch):
+ for name in ("HEADROOM_MODE", "HEADROOM_MIN_TOKENS", "HEADROOM_EXCLUDE_TOOLS"):
+ monkeypatch.delenv(name, raising=False)
+
+ @pytest.mark.parametrize(
+ ("name", "value", "config"),
+ [
+ ("HEADROOM_MIN_TOKENS", "2000", {"min_tokens_to_crush": 120}),
+ ("HEADROOM_MIN_TOKENS", "0", {"min_tokens_to_crush": 120}),
+ ("HEADROOM_EXCLUDE_TOOLS", "Bash,Read", {"exclude_tools": []}),
+ ("HEADROOM_EXCLUDE_TOOLS", "", {"exclude_tools": ["Bash"]}),
+ ],
+ )
+ def test_warns_when_reuse_ignores_explicit_compression_settings(
+ self, monkeypatch, capsys, name, value, config
+ ):
+ monkeypatch.setenv(name, value)
+ _warn_proxy_mode_mismatch(config)
+ output = capsys.readouterr().out
+ assert name in output
+ assert "Restart" in output and "--port" in output
+
+ @pytest.mark.parametrize(
+ ("env", "config"),
+ [
+ ({}, {"min_tokens_to_crush": 120, "exclude_tools": ["Bash"]}),
+ ({"HEADROOM_MIN_TOKENS": "120"}, {"min_tokens_to_crush": 120}),
+ ({"HEADROOM_MIN_TOKENS": "invalid"}, {"min_tokens_to_crush": 120}),
+ ({"HEADROOM_MIN_TOKENS": "2000"}, {}),
+ (
+ {"HEADROOM_EXCLUDE_TOOLS": " Read, BASH, bash "},
+ {"exclude_tools": ["Bash", "bash"]},
+ ),
+ ({"HEADROOM_EXCLUDE_TOOLS": "Read"}, {"exclude_tools": []}),
+ ({"HEADROOM_EXCLUDE_TOOLS": "Bash"}, {}),
+ ({"HEADROOM_EXCLUDE_TOOLS": "Bash"}, {"exclude_tools": None}),
+ ],
+ )
+ def test_does_not_warn_for_matching_unrequested_or_unknown_settings(
+ self, monkeypatch, capsys, env, config
+ ):
+ for name, value in env.items():
+ monkeypatch.setenv(name, value)
+ _warn_proxy_mode_mismatch(config)
+ assert capsys.readouterr().out == ""
+
+ @pytest.mark.parametrize(
+ ("name", "value"),
+ [("HEADROOM_MIN_TOKENS", "2000"), ("HEADROOM_EXCLUDE_TOOLS", "Bash")],
+ )
+ def test_no_start_reuse_warns_without_an_explicit_mode(self, monkeypatch, capsys, name, value):
+ monkeypatch.setenv(name, value)
+ monkeypatch.setattr(wrap_mod, "_check_proxy", lambda _port: True)
+ monkeypatch.setattr(
+ wrap_mod,
+ "_query_proxy_health",
+ lambda _port: {"config": {"min_tokens_to_crush": 120, "exclude_tools": []}},
+ )
+
+ wrap_mod._ensure_proxy_unlocked(18795, True)
+
+ assert name in capsys.readouterr().out
+
+
def test_passthrough_handler_roots_profile_at_origin_and_strips_region_domain():
import asyncio
from types import SimpleNamespace
diff --git a/tests/test_proxy_loopback_gating.py b/tests/test_proxy_loopback_gating.py
index 382baa449..dd1ce1e72 100644
--- a/tests/test_proxy_loopback_gating.py
+++ b/tests/test_proxy_loopback_gating.py
@@ -541,6 +541,47 @@ def test_health_config_block_is_loopback_only(monkeypatch: pytest.MonkeyPatch) -
assert "config" in local.json()
+ ("exclude_tools", "requested"),
+ [(None, "Bash"), ({"WebSearch"}, "Bash,WebSearch")],
+)
+def test_protected_tool_reuse_does_not_warn_about_missing_exclusions(
+ monkeypatch: pytest.MonkeyPatch,
+ capsys: pytest.CaptureFixture[str],
+ exclude_tools: set[str] | None,
+ requested: str,
+) -> None:
+ from headroom.cli.wrap import _warn_proxy_mode_mismatch
+
+ monkeypatch.setenv("HEADROOM_SKIP_UPSTREAM_CHECK", "1")
+ monkeypatch.delenv("HEADROOM_MODE", raising=False)
+ monkeypatch.delenv("HEADROOM_MIN_TOKENS", raising=False)
+ monkeypatch.setenv("HEADROOM_EXCLUDE_TOOLS", requested)
+ app = create_app(
+ ProxyConfig(
+ optimize=False,
+ cache_enabled=False,
+ rate_limit_enabled=False,
+ cost_tracking_enabled=False,
+ log_requests=False,
+ ccr_inject_tool=False,
+ ccr_handle_responses=False,
+ ccr_context_tracking=False,
+ image_optimize=False,
+ disable_kompress=True,
+ exclude_tools=exclude_tools,
+ protect_tool_results={"Bash"},
+ )
+ )
+ client = TestClient(app, base_url="http://127.0.0.1", client=("127.0.0.1", 12345))
+ response = client.get("/health")
+ assert response.status_code == 200
+
+ capsys.readouterr()
+ _warn_proxy_mode_mismatch(response.json()["config"])
+ assert capsys.readouterr().out == ""
+
+
def test_stats_per_request_metadata_is_loopback_only() -> None:
"""/stats keeps aggregate counters public but restricts per-request metadata
(recent_requests / request_logs) and `config` to loopback callers."""