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
refactor(proxy): extract tool injection config (#2010)
JD Davis0f846e5a8fb5
diff --git a/headroom/proxy/helpers.py b/headroom/proxy/helpers.pyindex ef6f1e105..68d1ae7f4 100644--- a/headroom/proxy/helpers.py+++ b/headroom/proxy/helpers.py@@ -38,6 +38,15 @@ from headroom.proxy.body_forwarding import (prepare_outbound_body_bytes as prepare_outbound_body_bytes, # noqa: F401 - compatibility export)from headroom.proxy.body_forwarding import serialize_body_canonical+from headroom.proxy.tool_injection_config import (+ ToolInjectionStickyMode,+)+from headroom.proxy.tool_injection_config import (+ get_tool_injection_sticky_mode as _get_tool_injection_sticky_mode,+)+from headroom.proxy.tool_injection_config import (+ get_tool_tracker_max_sessions as _get_tool_tracker_max_sessions,+)if TYPE_CHECKING:import httpx@@ -1923,13 +1932,6 @@ def log_beta_header_merge(# silent fallback. It exists for diagnostic shadow tracing / emergency# rollback only.-_TOOL_INJECTION_STICKY_ENV = "HEADROOM_TOOL_INJECTION_STICKY"-ToolInjectionStickyMode = Literal["enabled", "disabled"]-_TOOL_INJECTION_STICKY_DEFAULT: ToolInjectionStickyMode = "enabled"--_TOOL_TRACKER_MAX_SESSIONS_ENV = "HEADROOM_TOOL_TRACKER_MAX_SESSIONS"-_TOOL_TRACKER_MAX_SESSIONS_DEFAULT = 1000-def get_tool_injection_sticky_mode() -> ToolInjectionStickyMode:"""Return the active memory-tool stickiness mode.@@ -1938,30 +1940,12 @@ def get_tool_injection_sticky_mode() -> ToolInjectionStickyMode:restart. Unknown values raise loudly per the no-silent-fallbackbuild constraint."""- raw = os.environ.get(_TOOL_INJECTION_STICKY_ENV, "").strip().lower()- if not raw:- return _TOOL_INJECTION_STICKY_DEFAULT- if raw in ("enabled", "disabled"):- return cast(ToolInjectionStickyMode, raw)- raise ValueError(- f"Invalid {_TOOL_INJECTION_STICKY_ENV}={raw!r}; expected 'enabled' or 'disabled'"- )+ return _get_tool_injection_sticky_mode()def get_tool_tracker_max_sessions() -> int:"""Return the LRU bound for `SessionToolTracker` (sessions cap)."""- raw = os.environ.get(_TOOL_TRACKER_MAX_SESSIONS_ENV, "").strip()- if not raw:- return _TOOL_TRACKER_MAX_SESSIONS_DEFAULT- try:- value = int(raw)- except ValueError as exc:- raise ValueError(- f"Invalid {_TOOL_TRACKER_MAX_SESSIONS_ENV}={raw!r}; expected positive int"- ) from exc- if value <= 0:- raise ValueError(f"Invalid {_TOOL_TRACKER_MAX_SESSIONS_ENV}={raw!r}; expected positive int")- return value+ return _get_tool_tracker_max_sessions()def serialize_tool_definition_canonical(tool_definition: dict[str, Any]) -> bytes:diff --git a/headroom/proxy/tool_injection_config.py b/headroom/proxy/tool_injection_config.pynew file mode 100644index 000000000..01ebdf0bf--- /dev/null+++ b/headroom/proxy/tool_injection_config.py@@ -0,0 +1,43 @@+"""Operator configuration policy for proxy tool injection."""++from __future__ import annotations++import os+from typing import Literal, cast++TOOL_INJECTION_STICKY_ENV = "HEADROOM_TOOL_INJECTION_STICKY"+ToolInjectionStickyMode = Literal["enabled", "disabled"]+TOOL_INJECTION_STICKY_DEFAULT: ToolInjectionStickyMode = "enabled"++TOOL_TRACKER_MAX_SESSIONS_ENV = "HEADROOM_TOOL_TRACKER_MAX_SESSIONS"+TOOL_TRACKER_MAX_SESSIONS_DEFAULT = 1000+++def get_tool_injection_sticky_mode() -> ToolInjectionStickyMode:+ """Return the active memory-tool stickiness mode."""++ raw = os.environ.get(TOOL_INJECTION_STICKY_ENV, "").strip().lower()+ if not raw:+ return TOOL_INJECTION_STICKY_DEFAULT+ if raw in ("enabled", "disabled"):+ return cast(ToolInjectionStickyMode, raw)+ raise ValueError(+ f"Invalid {TOOL_INJECTION_STICKY_ENV}={raw!r}; expected 'enabled' or 'disabled'"+ )+++def get_tool_tracker_max_sessions() -> int:+ """Return the LRU bound for memory tool session tracking."""++ raw = os.environ.get(TOOL_TRACKER_MAX_SESSIONS_ENV, "").strip()+ if not raw:+ return TOOL_TRACKER_MAX_SESSIONS_DEFAULT+ try:+ value = int(raw)+ except ValueError as exc:+ raise ValueError(+ f"Invalid {TOOL_TRACKER_MAX_SESSIONS_ENV}={raw!r}; expected positive int"+ ) from exc+ if value <= 0:+ raise ValueError(f"Invalid {TOOL_TRACKER_MAX_SESSIONS_ENV}={raw!r}; expected positive int")+ return valuediff --git a/tests/test_tool_injection_config.py b/tests/test_tool_injection_config.pynew file mode 100644index 000000000..73ecb98d6--- /dev/null+++ b/tests/test_tool_injection_config.py@@ -0,0 +1,66 @@+from __future__ import annotations++import pytest++from headroom.proxy.helpers import (+ get_tool_injection_sticky_mode as helper_get_tool_injection_sticky_mode,+)+from headroom.proxy.helpers import (+ get_tool_tracker_max_sessions as helper_get_tool_tracker_max_sessions,+)+from headroom.proxy.tool_injection_config import (+ get_tool_injection_sticky_mode,+ get_tool_tracker_max_sessions,+)+++def test_sticky_mode_defaults_enabled(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("HEADROOM_TOOL_INJECTION_STICKY", raising=False)++ assert get_tool_injection_sticky_mode() == "enabled"+++def test_sticky_mode_accepts_enabled_and_disabled(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("HEADROOM_TOOL_INJECTION_STICKY", "enabled")+ assert get_tool_injection_sticky_mode() == "enabled"++ monkeypatch.setenv("HEADROOM_TOOL_INJECTION_STICKY", " DISABLED ")+ assert get_tool_injection_sticky_mode() == "disabled"+++def test_sticky_mode_rejects_unknown_values(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("HEADROOM_TOOL_INJECTION_STICKY", "maybe")++ with pytest.raises(ValueError, match="HEADROOM_TOOL_INJECTION_STICKY"):+ get_tool_injection_sticky_mode()+++def test_tracker_max_sessions_defaults_to_1000(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("HEADROOM_TOOL_TRACKER_MAX_SESSIONS", raising=False)++ assert get_tool_tracker_max_sessions() == 1000+++def test_tracker_max_sessions_accepts_positive_int(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("HEADROOM_TOOL_TRACKER_MAX_SESSIONS", "42")++ assert get_tool_tracker_max_sessions() == 42++[email protected]("raw", ["0", "-1", "not-int"])+def test_tracker_max_sessions_rejects_invalid_values(+ monkeypatch: pytest.MonkeyPatch,+ raw: str,+) -> None:+ monkeypatch.setenv("HEADROOM_TOOL_TRACKER_MAX_SESSIONS", raw)++ with pytest.raises(ValueError, match="HEADROOM_TOOL_TRACKER_MAX_SESSIONS"):+ get_tool_tracker_max_sessions()+++def test_helpers_keep_existing_config_import_paths(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.setenv("HEADROOM_TOOL_INJECTION_STICKY", "disabled")+ monkeypatch.setenv("HEADROOM_TOOL_TRACKER_MAX_SESSIONS", "12")++ assert helper_get_tool_injection_sticky_mode() == get_tool_injection_sticky_mode()+ assert helper_get_tool_tracker_max_sessions() == get_tool_tracker_max_sessions()