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
fix: propagate HEADROOM_MODE through wrap CLI and drop cache write premium penalty
Tejas Chopra30667833657e
diff --git a/headroom/cli/proxy.py b/headroom/cli/proxy.pyindex aae0c2d47..236cf5a7e 100644--- a/headroom/cli/proxy.py+++ b/headroom/cli/proxy.py@@ -10,6 +10,12 @@ from .main import main@main.command()@click.option("--host", default="127.0.0.1", help="Host to bind to (default: 127.0.0.1)")@click.option("--port", "-p", default=8787, type=int, help="Port to bind to (default: 8787)")+ "--mode",+ default=None,+ type=click.Choice(["cost_savings", "token_headroom"]),+ help="Optimization mode: cost_savings (preserve prefix cache) or token_headroom (compress for session extension). Default: cost_savings. Env: HEADROOM_MODE",+)@click.option("--no-optimize", is_flag=True, help="Disable optimization (passthrough mode)")@click.option("--no-cache", is_flag=True, help="Disable semantic caching")@click.option("--no-rate-limit", is_flag=True, help="Disable rate limiting")@@ -117,6 +123,7 @@ from .main import main@click.pass_contextdef proxy(ctx: click.Context,+ mode: str | None,host: str,port: int,no_optimize: bool,@@ -176,11 +183,15 @@ def proxy(# Resolve anyllm provider: env var takes precedence over CLI default (matches argparse path)effective_anyllm_provider = os.environ.get("HEADROOM_ANYLLM_PROVIDER") or anyllm_provider+ # Resolve mode: CLI flag > env var > default+ effective_mode = mode or os.environ.get("HEADROOM_MODE", "cost_savings")+config = ProxyConfig(host=host,port=port,openai_api_url=effective_openai_api_url,gemini_api_url=effective_gemini_api_url,+ mode=effective_mode,optimize=not no_optimize,cache_enabled=not no_cache,rate_limit_enabled=not no_rate_limit,@@ -280,6 +291,7 @@ Starting proxy server...URL: http://{config.host}:{config.port}Backend: {backend_status}+ Mode: {config.mode}Optimization: {"ENABLED" if config.optimize else "DISABLED"}Caching: {"ENABLED" if config.cache_enabled else "DISABLED"}Rate Limit: {"ENABLED" if config.rate_limit_enabled else "DISABLED"}diff --git a/headroom/cli/wrap.py b/headroom/cli/wrap.pyindex 8736a6d03..dfeda8083 100644--- a/headroom/cli/wrap.py+++ b/headroom/cli/wrap.py@@ -56,6 +56,11 @@ def _start_proxy(port: int) -> subprocess.Popen:"""cmd = [sys.executable, "-m", "headroom.cli", "proxy", "--port", str(port)]+ # Forward HEADROOM_MODE env var so the proxy respects the user's mode choice+ headroom_mode = os.environ.get("HEADROOM_MODE")+ if headroom_mode:+ cmd.extend(["--mode", headroom_mode])+log_path = _get_log_path()log_file = open(log_path, "a") # noqa: SIM115diff --git a/headroom/dashboard/templates/dashboard.html b/headroom/dashboard/templates/dashboard.htmlindex c4b419d1d..e087a9c38 100644--- a/headroom/dashboard/templates/dashboard.html+++ b/headroom/dashboard/templates/dashboard.html@@ -156,7 +156,7 @@<div><div class="text-xs text-gray-500 uppercase tracking-wide mb-1">Cache Writes</div><div class="text-2xl font-light tabular-nums text-amber-400" x-text="formatNumber(stats.prefix_cache?.totals?.cache_write_tokens || 0)"></div>- <div class="text-xs text-amber-400/70" x-text="'$' + formatCurrency(stats.prefix_cache?.totals?.bust_penalty_usd || 0) + ' penalty'"></div>+ <div class="text-xs text-amber-400/70" x-text="'$' + formatCurrency(stats.prefix_cache?.totals?.write_premium_usd || 0) + ' write premium'"></div></div><div><div class="text-xs text-gray-500 uppercase tracking-wide mb-1">Hit Rate</div>diff --git a/headroom/proxy/server.py b/headroom/proxy/server.pyindex 3373527a5..50d0f4a80 100644--- a/headroom/proxy/server.py+++ b/headroom/proxy/server.py@@ -272,7 +272,7 @@ def _build_prefix_cache_stats("bust_count": 0,"bust_write_tokens": 0,"savings_usd": 0.0,- "bust_penalty_usd": 0.0,+ "write_premium_usd": 0.0,}for provider, pc in metrics.cache_by_provider.items():@@ -302,19 +302,21 @@ def _build_prefix_cache_stats(break# Calculate savings:- # Without cache: all tokens at 1.0x input price- # With cache: read tokens at read_mult, write tokens at write_mult+ # Cache reads save (1.0 - read_mult) per token vs uncached input price.+ # Cache write premium is NOT deducted — it's baseline cost that the+ # client (e.g. Claude Code) pays regardless of Headroom. We track it+ # for observability but don't penalise our savings number.read_tokens: int = pc["cache_read_tokens"] # type: ignore[assignment]write_tokens: int = pc["cache_write_tokens"] # type: ignore[assignment]savings_usd = 0.0- bust_penalty_usd = 0.0+ write_premium_usd = 0.0if input_price_per_token:# Savings from reads: tokens * price * (1.0 - read_multiplier)savings_usd = read_tokens * input_price_per_token * (1.0 - read_mult)- # Penalty from writes: tokens * price * (write_multiplier - 1.0)+ # Write premium (observability only — not subtracted from savings)if write_mult > 1.0:- bust_penalty_usd = write_tokens * input_price_per_token * (write_mult - 1.0)+ write_premium_usd = write_tokens * input_price_per_token * (write_mult - 1.0)hit_rate = round(pc["hit_requests"] / pc["requests"] * 100, 1) if pc["requests"] > 0 else 0@@ -329,8 +331,8 @@ def _build_prefix_cache_stats("read_discount": f"{(1.0 - read_mult) * 100:.0f}%","write_premium": f"{(write_mult - 1.0) * 100:.0f}%" if write_mult > 1.0 else "none","savings_usd": round(savings_usd, 4),- "bust_penalty_usd": round(bust_penalty_usd, 4),- "net_savings_usd": round(savings_usd - bust_penalty_usd, 4),+ "write_premium_usd": round(write_premium_usd, 4),+ "net_savings_usd": round(savings_usd, 4),"label": str(econ["label"]),}by_provider[provider] = provider_stats@@ -343,11 +345,11 @@ def _build_prefix_cache_stats(totals["bust_count"] += pc["bust_count"]totals["bust_write_tokens"] += pc["bust_write_tokens"]totals["savings_usd"] += savings_usd- totals["bust_penalty_usd"] += bust_penalty_usd+ totals["write_premium_usd"] += write_premium_usd- totals["net_savings_usd"] = round(totals["savings_usd"] - totals["bust_penalty_usd"], 4)+ totals["net_savings_usd"] = round(totals["savings_usd"], 4)totals["savings_usd"] = round(totals["savings_usd"], 4)- totals["bust_penalty_usd"] = round(totals["bust_penalty_usd"], 4)+ totals["write_premium_usd"] = round(totals["write_premium_usd"], 4)totals["hit_rate"] = (round(totals["hit_requests"] / totals["requests"] * 100, 1) if totals["requests"] > 0 else 0)