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): collapse 3 stream finalizers onto RequestOutcome.from_stream
chopratejas694589fec499
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex d22330cb7..9ac7d0c7f 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -5,14 +5,14 @@},"metadata": {"description": "Headroom marketplace for Claude Code and GitHub Copilot CLI plugins.",- "version": "0.21.37"+ "version": "0.21.38"},"plugins": [{"name": "headroom","source": "./plugins/headroom-agent-hooks","description": "Headroom startup hooks for Claude Code and GitHub Copilot CLI.",- "version": "0.21.37",+ "version": "0.21.38","author": {"name": "Headroom Contributors","url": "https://github.com/chopratejas/headroom"diff --git a/.github/plugin/marketplace.json b/.github/plugin/marketplace.jsonindex d22330cb7..9ac7d0c7f 100644--- a/.github/plugin/marketplace.json+++ b/.github/plugin/marketplace.json@@ -5,14 +5,14 @@},"metadata": {"description": "Headroom marketplace for Claude Code and GitHub Copilot CLI plugins.",- "version": "0.21.37"+ "version": "0.21.38"},"plugins": [{"name": "headroom","source": "./plugins/headroom-agent-hooks","description": "Headroom startup hooks for Claude Code and GitHub Copilot CLI.",- "version": "0.21.37",+ "version": "0.21.38","author": {"name": "Headroom Contributors","url": "https://github.com/chopratejas/headroom"diff --git a/headroom/proxy/handlers/streaming.py b/headroom/proxy/handlers/streaming.pyindex b79af5d85..3e76ac53e 100644--- a/headroom/proxy/handlers/streaming.py+++ b/headroom/proxy/handlers/streaming.py@@ -13,7 +13,7 @@ import timefrom typing import TYPE_CHECKING, Anyfrom headroom.proxy.auth_mode import classify_client-from headroom.proxy.helpers import compute_turn_id, jitter_delay_ms+from headroom.proxy.helpers import jitter_delay_msif TYPE_CHECKING:from fastapi.responses import Response, StreamingResponse@@ -677,39 +677,35 @@ class StreamingMixin:original_messages=next_original,)- # Active-compression denominator. No frozen_message_count is- # propagated to the streaming finalizer yet, so we fall back to- # the pre-comp request size (effective_optimized + tokens_saved).- # Per-message live-zone tracking is a follow-up; without this- # fallback the dashboard headline collapses to 0% for streaming- # traffic even though compression is happening (issue #455).- attempted_input_tokens = effective_optimized_tokens + tokens_saved-- outcome = RequestOutcome(- request_id=request_id,+ # Active-compression denominator (``attempted_input_tokens``) is+ # derived inside ``RequestOutcome.from_stream`` as+ # ``optimized_tokens + tokens_saved``. No frozen_message_count+ # propagates to the streaming finalizer yet — per-message+ # live-zone tracking is a follow-up. Without this fallback the+ # dashboard headline collapses to 0% even when compression is+ # happening (issue #455).+ outcome = RequestOutcome.from_stream(+ body=body,provider=provider,model=model,+ request_id=request_id,original_tokens=effective_original_tokens,optimized_tokens=effective_optimized_tokens,output_tokens=output_tokens,tokens_saved=tokens_saved,- attempted_input_tokens=attempted_input_tokens,+ transforms_applied=transforms_applied,+ total_latency_ms=total_latency,+ overhead_ms=optimization_latency,+ tags=tags,+ client=client,+ log_full_messages=getattr(self.config, "log_full_messages", False),cache_read_tokens=cache_read_tokens,cache_write_tokens=cache_write_tokens,cache_write_5m_tokens=cache_write_5m_tokens,cache_write_1h_tokens=cache_write_1h_tokens,uncached_input_tokens=uncached_input_tokens,- total_latency_ms=total_latency,- overhead_ms=optimization_latency,ttfb_ms=stream_state["ttfb_ms"] or total_latency,pipeline_timing=pipeline_timing,- transforms_applied=tuple(transforms_applied),- num_messages=len(body.get("messages", [])),- tags=tags or {},- client=client,- request_messages=body.get("messages")- if getattr(self.config, "log_full_messages", False)- else None,)await self._record_request_outcome(outcome)@@ -1330,35 +1326,31 @@ class StreamingMixin:_backend_name = (self.anthropic_backend.name if self.anthropic_backend else "anthropic")- # Active-compression denominator: pre-comp request size.- # Bedrock streaming doesn't propagate frozen_message_count- # here either; without this, attempted_input_tokens_total- # stays 0 and the dashboard headline reads 0% (#455).- outcome = RequestOutcome(- request_id=request_id,+ # Active-compression denominator derived inside+ # ``from_stream`` as ``optimized + saved``. Bedrock+ # doesn't propagate frozen_message_count either — same+ # fallback as the SSE finalizer (#455).+ outcome = RequestOutcome.from_stream(+ body=body,provider=_backend_name,model=model,+ request_id=request_id,original_tokens=original_tokens,optimized_tokens=optimized_tokens,output_tokens=stream_state["output_tokens"],tokens_saved=tokens_saved,- attempted_input_tokens=optimized_tokens + tokens_saved,+ transforms_applied=transforms_applied,+ total_latency_ms=total_latency,+ overhead_ms=optimization_latency,+ tags=tags,+ client=client,+ log_full_messages=getattr(self.config, "log_full_messages", False),cache_read_tokens=stream_state["cache_read_input_tokens"],cache_write_tokens=stream_state["cache_creation_input_tokens"],cache_write_5m_tokens=stream_state["cache_creation_ephemeral_5m_input_tokens"],cache_write_1h_tokens=stream_state["cache_creation_ephemeral_1h_input_tokens"],- total_latency_ms=total_latency,- overhead_ms=optimization_latency,ttfb_ms=stream_state["ttfb_ms"] or 0,pipeline_timing=pipeline_timing,- transforms_applied=tuple(transforms_applied),- num_messages=len(body.get("messages", [])),- tags=tags or {},- client=client,- turn_id=compute_turn_id(model, body.get("system"), body.get("messages")),- request_messages=body.get("messages")- if getattr(self.config, "log_full_messages", False)- else None,)await self._record_request_outcome(outcome)@@ -1481,30 +1473,27 @@ class StreamingMixin:# comp request size. This keeps active_savings_percent# in sync with proxy_savings_percent for this provider# instead of collapsing the dashboard headline to 0%.- outcome = RequestOutcome(- request_id=request_id,+ outcome = RequestOutcome.from_stream(+ body=body,provider=self.anthropic_backend.name,model=model,+ request_id=request_id,original_tokens=original_tokens,optimized_tokens=optimized_tokens,output_tokens=output_tokens,tokens_saved=tokens_saved,- attempted_input_tokens=optimized_tokens + tokens_saved,+ transforms_applied=transforms_applied,+ total_latency_ms=total_latency,+ overhead_ms=optimization_latency,+ tags=tags,+ client=client,+ log_full_messages=getattr(self.config, "log_full_messages", False),cache_read_tokens=cache_read_tokens,cache_write_tokens=cache_write_tokens,uncached_input_tokens=uncached_input_tokens,cache_inferred=cache_inferred,- total_latency_ms=total_latency,- overhead_ms=optimization_latency,pipeline_timing=pipeline_timing,waste_signals=waste_signals,- transforms_applied=tuple(transforms_applied),- num_messages=len(body.get("messages", [])),- tags=tags or {},- client=client,- request_messages=body.get("messages")- if getattr(self.config, "log_full_messages", False)- else None,)await self._record_request_outcome(outcome)diff --git a/headroom/proxy/outcome.py b/headroom/proxy/outcome.pyindex 104a92393..74dbe1676 100644--- a/headroom/proxy/outcome.py+++ b/headroom/proxy/outcome.py@@ -173,6 +173,83 @@ class RequestOutcome:return 0.0return self.tokens_saved / self.original_tokens * 100.0+ @classmethod+ def from_stream(+ cls,+ *,+ body: dict[str, Any],+ provider: str,+ model: str,+ request_id: str,+ original_tokens: int,+ optimized_tokens: int,+ output_tokens: int,+ tokens_saved: int,+ transforms_applied: list[str] | tuple[str, ...],+ total_latency_ms: float,+ overhead_ms: float,+ tags: dict[str, str] | None,+ client: str | None,+ log_full_messages: bool = False,+ cache_read_tokens: int = 0,+ cache_write_tokens: int = 0,+ cache_write_5m_tokens: int = 0,+ cache_write_1h_tokens: int = 0,+ uncached_input_tokens: int = 0,+ cache_inferred: bool = False,+ ttfb_ms: float = 0.0,+ pipeline_timing: dict[str, float] | None = None,+ waste_signals: dict[str, int] | None = None,+ ) -> RequestOutcome:+ """Construct an outcome from the locals available at streaming+ finalize. Three streaming finalizers+ (``_finalize_stream_response``, ``_stream_response_bedrock``,+ ``_stream_openai_via_backend``) each duplicated the same body- and+ config-derived fields inline. This classmethod is the single+ construction point so derivation logic can't drift apart again.++ Centralises six derivations:++ * ``attempted_input_tokens = optimized_tokens + tokens_saved``+ * ``num_messages = len(body["messages"])``+ * ``request_messages`` conditional on ``log_full_messages``+ * ``turn_id`` via ``compute_turn_id`` — pre-refactor only the+ Bedrock site computed this; sites 1 and 3 silently dropped it,+ breaking multi-turn-session grouping on Anthropic-SSE and+ OpenAI-via-backend traffic+ * ``transforms_applied`` list → tuple (frozen-dataclass contract)+ * ``tags or {}`` normalization+ """+ from headroom.proxy.helpers import compute_turn_id++ return cls(+ request_id=request_id,+ provider=provider,+ model=model,+ original_tokens=original_tokens,+ optimized_tokens=optimized_tokens,+ output_tokens=output_tokens,+ tokens_saved=tokens_saved,+ attempted_input_tokens=optimized_tokens + tokens_saved,+ cache_read_tokens=cache_read_tokens,+ cache_write_tokens=cache_write_tokens,+ cache_write_5m_tokens=cache_write_5m_tokens,+ cache_write_1h_tokens=cache_write_1h_tokens,+ uncached_input_tokens=uncached_input_tokens,+ cache_inferred=cache_inferred,+ total_latency_ms=total_latency_ms,+ overhead_ms=overhead_ms,+ ttfb_ms=ttfb_ms,+ pipeline_timing=pipeline_timing,+ transforms_applied=tuple(transforms_applied),+ waste_signals=waste_signals,+ num_messages=len(body.get("messages", [])),+ turn_id=compute_turn_id(model, body.get("system"), body.get("messages")),+ tags=tags or {},+ client=client,+ request_messages=body.get("messages") if log_full_messages else None,+ )+# ── The funnel ───────────────────────────────────────────────────────diff --git a/plugins/headroom-agent-hooks/.claude-plugin/plugin.json b/plugins/headroom-agent-hooks/.claude-plugin/plugin.jsonindex c7c5241d2..ab49bb9a8 100644--- a/plugins/headroom-agent-hooks/.claude-plugin/plugin.json+++ b/plugins/headroom-agent-hooks/.claude-plugin/plugin.json@@ -1,6 +1,6 @@{"name": "headroom",- "version": "0.21.37",+ "version": "0.21.38","description": "Headroom startup hooks for Claude Code and GitHub Copilot CLI.","author": {"name": "Headroom Contributors",diff --git a/plugins/headroom-agent-hooks/.github/plugin/plugin.json b/plugins/headroom-agent-hooks/.github/plugin/plugin.jsonindex 5f0fbb8fc..34c3be518 100644--- a/plugins/headroom-agent-hooks/.github/plugin/plugin.json+++ b/plugins/headroom-agent-hooks/.github/plugin/plugin.json@@ -1,6 +1,6 @@{"name": "headroom",- "version": "0.21.37",+ "version": "0.21.38","description": "Headroom startup hooks for Claude Code and GitHub Copilot CLI.","author": {"name": "Headroom Contributors",diff --git a/tests/test_request_outcome.py b/tests/test_request_outcome.pyindex 53e50e026..182d479d4 100644--- a/tests/test_request_outcome.py+++ b/tests/test_request_outcome.py@@ -421,3 +421,150 @@ async def test_funnel_stamps_client_into_request_log_tags() -> None:await h._record_request_outcome(_outcome(client="aider"))assert len(h.logger.logs) == 1assert h.logger.logs[0].tags.get("client") == "aider"+++# ── from_stream classmethod (streaming-finalizer construction shape) ──+#+# Three streaming finalizers (``_finalize_stream_response``,+# ``_stream_response_bedrock``, ``_stream_openai_via_backend``) each used+# to construct ``RequestOutcome(...)`` inline with the same body- and+# config-derived fields — ``attempted_input_tokens``, ``num_messages``,+# ``request_messages``, ``turn_id``, tuple-conversion of+# ``transforms_applied``, ``tags`` normalization. One site (Bedrock)+# computed ``turn_id``; the other two silently dropped it — a real bug+# the helper fixes by computing it uniformly. ``from_stream`` is the+# canonical construction point so the three finalizers cannot drift+# apart on derivation logic again.+++def _stream_kwargs(**overrides: Any) -> dict[str, Any]:+ """Minimal kwargs for ``RequestOutcome.from_stream``; override per test."""+ base: dict[str, Any] = {+ "body": {"messages": [{"role": "user", "content": "hi"}]},+ "provider": "anthropic",+ "model": "claude-sonnet-4",+ "request_id": "req-1",+ "original_tokens": 1000,+ "optimized_tokens": 300,+ "output_tokens": 50,+ "tokens_saved": 700,+ "transforms_applied": ["smart_crusher"],+ "total_latency_ms": 1234.5,+ "overhead_ms": 12.3,+ "tags": {"a": "b"},+ "client": "codex",+ "log_full_messages": False,+ }+ base.update(overrides)+ return base+++def test_from_stream_returns_request_outcome() -> None:+ o = RequestOutcome.from_stream(**_stream_kwargs())+ assert isinstance(o, RequestOutcome)+++def test_from_stream_derives_attempted_input_tokens_from_optimized_plus_saved() -> None:+ """One of the six derivations the three finalizers each computed+ inline. Centralising it makes the dashboard's active-savings+ denominator structurally consistent across providers (#454/#455)."""+ o = RequestOutcome.from_stream(**_stream_kwargs(optimized_tokens=300, tokens_saved=700))+ assert o.attempted_input_tokens == 1000+++def test_from_stream_counts_messages_from_body() -> None:+ """``num_messages`` powers PERF ``msgs=N``. Computing it from the+ body in one place prevents the historical drift where some sites+ used ``original_messages`` and others used ``body["messages"]``."""+ body = {"messages": [{"role": "user", "content": "1"}, {"role": "user", "content": "2"}]}+ assert RequestOutcome.from_stream(**_stream_kwargs(body=body)).num_messages == 2+++def test_from_stream_handles_missing_messages_key() -> None:+ """Empty body — e.g. a probe request — must yield num_messages=0,+ not raise KeyError. All three pre-refactor sites used+ ``len(body.get("messages", []))`` so the contract is already+ "default to 0"."""+ assert RequestOutcome.from_stream(**_stream_kwargs(body={})).num_messages == 0+++def test_from_stream_always_computes_turn_id() -> None:+ """The bug the helper is fixing: pre-refactor, only the Bedrock+ finalizer called ``compute_turn_id``. Sites 1 and 3 silently dropped+ it, breaking the dashboard's multi-turn-session grouping for every+ Anthropic-SSE and OpenAI-via-backend request. The helper computes+ it uniformly."""+ body = {+ "messages": [{"role": "user", "content": "hi"}],+ "system": "you are helpful",+ }+ o = RequestOutcome.from_stream(**_stream_kwargs(body=body, model="claude-sonnet-4"))+ assert o.turn_id is not None+ assert isinstance(o.turn_id, str)+ # Stable: same body+model produces the same turn_id.+ o2 = RequestOutcome.from_stream(**_stream_kwargs(body=body, model="claude-sonnet-4"))+ assert o.turn_id == o2.turn_id+++def test_from_stream_converts_transforms_to_tuple() -> None:+ """``transforms_applied`` is typed as ``tuple[str, ...]`` on the+ dataclass (frozen → must be hashable/immutable). Callers pass lists.+ The helper does the conversion so no caller has to remember."""+ o = RequestOutcome.from_stream(**_stream_kwargs(transforms_applied=["a", "b"]))+ assert o.transforms_applied == ("a", "b")+ assert isinstance(o.transforms_applied, tuple)+++def test_from_stream_normalises_none_tags_to_empty_dict() -> None:+ """``tags=None`` is the common case (no routing tags); the dataclass+ contract is ``dict[str, str]``. Pre-refactor each site wrote+ ``tags or {}``; the helper does it once."""+ assert RequestOutcome.from_stream(**_stream_kwargs(tags=None)).tags == {}+++def test_from_stream_omits_request_messages_when_log_full_messages_disabled() -> None:+ """``log_full_messages=False`` is the default; message bodies are+ sensitive (tool outputs, secrets) and must not land in the request+ log unless explicitly enabled."""+ body = {"messages": [{"role": "user", "content": "secret"}]}+ o = RequestOutcome.from_stream(**_stream_kwargs(body=body, log_full_messages=False))+ assert o.request_messages is None+++def test_from_stream_includes_request_messages_when_log_full_messages_enabled() -> None:+ """Same path, opt-in for full-message logging — used by+ /transformations/feed when the operator enables it."""+ body = {"messages": [{"role": "user", "content": "hi"}]}+ o = RequestOutcome.from_stream(**_stream_kwargs(body=body, log_full_messages=True))+ assert o.request_messages == body["messages"]+++def test_from_stream_threads_provider_specific_cache_fields() -> None:+ """Anthropic populates all five cache fields; OpenAI-via-backend+ sets ``cache_inferred=True``; Gemini populates read only. The+ helper must pass each through without forcing every caller to+ pass every field."""+ o = RequestOutcome.from_stream(+ **_stream_kwargs(),+ cache_read_tokens=100,+ cache_write_tokens=200,+ cache_write_5m_tokens=150,+ cache_write_1h_tokens=50,+ uncached_input_tokens=10,+ )+ assert o.cache_read_tokens == 100+ assert o.cache_write_tokens == 200+ assert o.cache_write_5m_tokens == 150+ assert o.cache_write_1h_tokens == 50+ assert o.uncached_input_tokens == 10+ assert o.cache_inferred is False # default — only set True by OpenAI sites+++def test_from_stream_threads_waste_signals_for_openai_via_backend_site() -> None:+ """Only the OpenAI-via-backend finalizer populates ``waste_signals``;+ the helper threads it through as an optional kwarg."""+ o = RequestOutcome.from_stream(+ **_stream_kwargs(),+ waste_signals={"skipped_units": 3, "applied_units": 7},+ )+ assert o.waste_signals == {"skipped_units": 3, "applied_units": 7}