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
feat(savings): per-agent attribution in history checkpoints and rollups (#2627)
gglucass489de4682585
diff --git a/headroom/proxy/prometheus_metrics.py b/headroom/proxy/prometheus_metrics.pyindex e22b8308b..4dd74b2d1 100644--- a/headroom/proxy/prometheus_metrics.py+++ b/headroom/proxy/prometheus_metrics.py@@ -1065,6 +1065,7 @@ class PrometheusMetrics:# saved next to "0 tokens saved".tool_search_saved=tool_search_saved,provider=provider,+ agent=client,project=project,cache_read_tokens=cache_read_tokens,cache_write_tokens=cache_write_tokens,diff --git a/headroom/proxy/savings_tracker.py b/headroom/proxy/savings_tracker.pyindex 101474ab0..d07622ce0 100644--- a/headroom/proxy/savings_tracker.py+++ b/headroom/proxy/savings_tracker.py@@ -265,6 +265,23 @@ def _normalize_provider(value: Any) -> str:return cleaned or PROVIDER_UNKNOWN+AGENT_UNKNOWN = "unknown"+++def _normalize_agent(value: Any) -> str:+ """Normalize a client/agent label, falling back to a stable sentinel.++ The agent is the harness classified from User-Agent / X-Client+ (claude-code, codex, opencode, grok_build, ...). Checkpoints persisted+ before per-agent attribution existed have no agent field and collapse+ into ``AGENT_UNKNOWN``.+ """+ if not isinstance(value, str):+ return AGENT_UNKNOWN+ cleaned = value.strip()+ return cleaned or AGENT_UNKNOWN++MODEL_UNKNOWN = "unknown"@@ -649,6 +666,7 @@ def _normalize_history_entry(entry: Any) -> dict[str, Any] | None:total_output_cost_usd = 0.0provider = PROVIDER_UNKNOWNmodel = MODEL_UNKNOWN+ agent = AGENT_UNKNOWNif isinstance(entry, dict):timestamp = _parse_timestamp(entry.get("timestamp"))@@ -668,6 +686,7 @@ def _normalize_history_entry(entry: Any) -> dict[str, Any] | None:total_output_cost_usd = _coerce_float(entry.get("total_output_cost_usd"))provider = _normalize_provider(entry.get("provider"))model = _normalize_model(entry.get("model"))+ agent = _normalize_agent(entry.get("agent"))elif isinstance(entry, list | tuple) and len(entry) >= 2:timestamp = _parse_timestamp(entry[0])total_tokens_saved = _coerce_int(entry[1])@@ -687,6 +706,7 @@ def _normalize_history_entry(entry: Any) -> dict[str, Any] | None:"timestamp": _to_utc_iso(timestamp),"provider": provider,"model": model,+ "agent": agent,"total_tokens_saved": total_tokens_saved,"compression_savings_usd": round(compression_savings_usd, 6),"cache_read_tokens": cache_read_tokens,@@ -971,6 +991,7 @@ class SavingsTracker:model: str,tokens_saved: int,provider: str | None = None,+ agent: str | None = None,total_input_tokens: int | None = None,total_input_cost_usd: float | None = None,timestamp: datetime | str | None = None,@@ -1023,6 +1044,7 @@ class SavingsTracker:{"timestamp": _to_utc_iso(timestamp_dt),"provider": _normalize_provider(provider),+ "agent": _normalize_agent(agent),"model": _normalize_model(model),"total_tokens_saved": lifetime["tokens_saved"],"compression_savings_usd": lifetime["compression_savings_usd"],@@ -1052,6 +1074,7 @@ class SavingsTracker:# into ``lifetime["total_output_cost_usd"]``; see the delta below.output_tokens: int = 0,provider: str | None = None,+ agent: str | None = None,project: str | None = None,cache_read_tokens: int = 0,cache_write_tokens: int = 0,@@ -1325,6 +1348,7 @@ class SavingsTracker:{"timestamp": _to_utc_iso(timestamp_dt),"provider": _normalize_provider(provider),+ "agent": _normalize_agent(agent),"model": _normalize_model(model),"total_tokens_saved": lifetime["tokens_saved"],"compression_savings_usd": lifetime["compression_savings_usd"],@@ -2294,6 +2318,7 @@ class SavingsTracker:"total_output_cost_usd": total_output_cost_usd,**_empty_cache_delta(),"by_provider": {},+ "by_agent": {},"by_model": {},},)@@ -2371,6 +2396,39 @@ class SavingsTracker:6,)+ # Same single-owner attribution by agent. Providers cannot+ # separate clients that share an upstream (Claude Code vs+ # OpenCode both hit anthropic; Codex vs OpenCode both hit+ # openai), so dashboards need this dimension for honest+ # per-connector rows.+ agent = _normalize_agent(point.get("agent"))+ agent_entry = entry["by_agent"].setdefault(+ agent,+ {+ "tokens_saved": 0,+ "compression_savings_usd_delta": 0.0,+ "total_input_tokens_delta": 0,+ "total_input_cost_usd_delta": 0.0,+ **_empty_cache_delta(),+ },+ )+ _add_cache(+ agent_entry,+ delta_cache_read_tokens,+ delta_cache_savings_usd,+ delta_cache_read_cost_usd,+ )+ agent_entry["tokens_saved"] += delta_tokens+ agent_entry["compression_savings_usd_delta"] = round(+ agent_entry["compression_savings_usd_delta"] + delta_usd,+ 6,+ )+ agent_entry["total_input_tokens_delta"] += delta_input_tokens+ agent_entry["total_input_cost_usd_delta"] = round(+ agent_entry["total_input_cost_usd_delta"] + delta_input_cost_usd,+ 6,+ )+mod = entry["by_model"].setdefault(model,{diff --git a/tests/test_proxy_savings_history.py b/tests/test_proxy_savings_history.pyindex 6bc09a99a..c2e01a58e 100644--- a/tests/test_proxy_savings_history.py+++ b/tests/test_proxy_savings_history.py@@ -76,6 +76,7 @@ def test_savings_tracker_helpers_normalize_inputs_and_paths(tmp_path, monkeypatc"timestamp": "2026-03-27T09:00:00Z","provider": "unknown","model": "unknown",+ "agent": "unknown","total_tokens_saved": 12,"compression_savings_usd": 0.5,"cache_read_tokens": 0,@@ -157,6 +158,7 @@ def test_savings_tracker_sanitizes_legacy_state_and_applies_retention(tmp_path):"timestamp": "2026-03-27T09:00:00Z","provider": "unknown","model": "unknown",+ "agent": "unknown","total_tokens_saved": 30,"compression_savings_usd": 0.03,"cache_read_tokens": 0,@@ -244,6 +246,7 @@ def test_record_compression_savings_skips_empty_updates_and_normalizes_timestamp{"timestamp": "2026-03-27T08:00:00Z","provider": "unknown",+ "agent": "unknown","model": "gpt-4o","total_tokens_saved": 10,"compression_savings_usd": 0.01,@@ -253,6 +256,7 @@ def test_record_compression_savings_skips_empty_updates_and_normalizes_timestamp{"timestamp": "2026-03-27T12:34:00Z","provider": "unknown",+ "agent": "unknown","model": "gpt-4o","total_tokens_saved": 15,"compression_savings_usd": 0.015,@@ -937,6 +941,111 @@ def test_savings_tracker_rollup_attributes_savings_per_provider(tmp_path, monkeyassert third["by_provider"]["unknown"]["tokens_saved"] == 15+def test_savings_tracker_rollup_attributes_savings_per_agent(tmp_path, monkeypatch):+ path = tmp_path / "proxy_savings.json"+ tracker = SavingsTracker(+ path=str(path),+ max_history_points=100,+ max_history_age_days=30,+ )+ monkeypatch.setattr(+ "headroom.proxy.savings_tracker._estimate_compression_savings_usd",+ lambda model, tokens_saved: tokens_saved / 1000.0,+ )++ # Two agents sharing the SAME upstream provider in one hour bucket - the+ # case by_provider fundamentally cannot separate (Claude Code and+ # OpenCode both talk to anthropic).+ tracker.record_compression_savings(+ model="claude-3-5-sonnet",+ tokens_saved=100,+ provider="anthropic",+ agent="claude-code",+ total_input_tokens=120,+ total_input_cost_usd=0.24,+ timestamp="2026-03-27T09:10:00Z",+ )+ tracker.record_compression_savings(+ model="claude-3-5-sonnet",+ tokens_saved=40,+ provider="anthropic",+ agent="opencode",+ total_input_tokens=200,+ total_input_cost_usd=0.40,+ timestamp="2026-03-27T09:40:00Z",+ )+ # A legacy-style record with no agent collapses into "unknown".+ tracker.record_compression_savings(+ model="gpt-4o",+ tokens_saved=15,+ provider="openai",+ total_input_tokens=260,+ total_input_cost_usd=0.52,+ timestamp="2026-03-27T10:05:00Z",+ )++ hourly = tracker.history_response()["series"]["hourly"]++ first = hourly[0]+ # by_provider blends the two agents...+ assert set(first["by_provider"]) == {"anthropic"}+ assert first["by_provider"]["anthropic"]["tokens_saved"] == 140+ # ...by_agent separates them.+ assert set(first["by_agent"]) == {"claude-code", "opencode"}+ assert first["by_agent"]["claude-code"]["tokens_saved"] == 100+ assert first["by_agent"]["claude-code"]["total_input_tokens_delta"] == 120+ assert first["by_agent"]["claude-code"]["compression_savings_usd_delta"] == pytest.approx(0.1)+ assert first["by_agent"]["opencode"]["tokens_saved"] == 40+ assert first["by_agent"]["opencode"]["total_input_tokens_delta"] == 80+ assert (+ first["by_agent"]["claude-code"]["tokens_saved"]+ + first["by_agent"]["opencode"]["tokens_saved"]+ == first["tokens_saved"]+ )++ second = hourly[1]+ assert set(second["by_agent"]) == {"unknown"}+ assert second["by_agent"]["unknown"]["tokens_saved"] == 15+++def test_savings_tracker_rollup_reloads_persisted_agent_field(tmp_path):+ """Persisted checkpoints keep their agent across a reload.++ ``_normalize_history_entry`` runs on every load; if it drops the ``agent``+ key, a real ``agent: "claude-code"`` checkpoint collapses into "unknown"+ on the next restart even though in-memory attribution was correct.+ """+ path = tmp_path / "proxy_savings.json"+ path.write_text(+ json.dumps(+ {+ "history": [+ {+ "timestamp": "2026-03-27T09:10:00Z",+ "provider": "anthropic",+ "agent": "claude-code",+ "model": "claude-3-5-sonnet",+ "total_tokens_saved": 100,+ "compression_savings_usd": 0.1,+ "total_input_tokens": 120,+ "total_input_cost_usd": 0.24,+ }+ ]+ }+ )+ )++ tracker = SavingsTracker(+ path=str(path),+ max_history_points=100,+ max_history_age_days=30,+ )++ by_agent = tracker.history_response()["series"]["hourly"][0]["by_agent"]+ assert set(by_agent) == {"claude-code"}+ assert by_agent["claude-code"]["tokens_saved"] == 100++def test_savings_tracker_rollup_carries_exact_cache_read_cost_per_provider(tmp_path, monkeypatch):# Reads on "steep-model" bill at 0.025x list (Fable-5.1-shaped pricing),# on "flat-model" at the usual 0.1x. A consumer that backs the read cost