AI Tools
Headroom: Open-Source AI Context Compression — 60–95% Fewer Tokens, Same Answers
By DevShelfHub
A comprehensive technical deep-dive into Headroom — the open-source context compression layer for AI agents. Covers all six compression engines (CacheAligner, ContentRouter, SmartCrusher, CodeCompressor, Kompress-base, CCR), reversible compression architecture, output token reduction, cross-agent memory, MCP integration, real benchmarks, and an honest comparison against OpenAI Compaction, RTK, lean-ctx, and hosted services.
Introduction
There is a number that has quietly become one of the most important line items in every serious AI engineering budget: the token count. Every call to GPT-4o, Claude Opus, or Gemini Ultra is billed by the token. A single token is roughly four characters of English text. That sounds benign until you run your first agentic workflow at scale and discover that a single SRE incident investigation can consume 65,000 input tokens in one session — the equivalent of the first 50 pages of a novel — just in log data, stack traces, and tool outputs.
The dominant response has been to wait for providers to offer longer, cheaper context windows. That strategy has worked partially. But bigger context windows have not reduced costs — they have enabled more tokens to be consumed at the same per-token price. A different approach is now emerging: compress what you send before it reaches the model. Process raw, verbose tool outputs locally, strip out redundancy, and ship only the signal to the LLM.
This is the philosophy behind Headroom — an open-source context compression layer with 37K+ GitHub stars, built for AI engineers who are serious about cost control without sacrificing answer quality.
Key takeaways
- 60–95% token reduction on real agent workloads — validated on code search, SRE debugging, issue triage, and codebase exploration.
- Local-first architecture — all compression runs on your infrastructure. Your source code, logs, and internal data never leave your environment.
- Reversible by design — the CCR architecture caches originals locally so the LLM can retrieve full content on demand.
-
Zero-code deployment —
headroom wrap claudeorheadroom proxy --port 8787requires no application code changes. - Cross-agent memory — shared context store across Claude, Codex, Cursor, and Aider sessions with automatic deduplication.
What is Headroom?
Headroom ( github.com/chopratejas/headroom, Apache 2.0) is an open-source context compression layer for AI agents and LLM-powered applications. Its core promise: 60–95% fewer tokens, same answers.
It compresses everything an AI agent reads — tool outputs, log files, RAG retrieval chunks, source code, conversation history, and structured JSON — before that content reaches the LLM provider. The LLM receives a semantically equivalent but dramatically smaller representation, processes it correctly, and answers as accurately as it would have with the full payload.
Headroom is not a model. It is not a provider. It is a middleware layer — a local, privacy-preserving processing pipeline that sits between your application and the cloud LLM. It ships in four deployment modes:
| Mode | How You Use It | Requires Code Changes? |
|---|---|---|
| Library | compress(messages) in Python or TypeScript |
Yes (minimal) |
| Proxy | headroom proxy --port 8787 |
No |
| Agent Wrap | headroom wrap claude|codex|cursor |
No |
| MCP Server | headroom mcp install |
No |
Why AI agents generate massive context
A traditional chatbot sends a question and gets an answer. The context is small. AI agents operate on an entirely different paradigm. A coding agent in a single session might:
- List all files in a repository (returns 500 filenames)
- Read five relevant files in full (returns 2,000–10,000 lines each)
- Run a search across the codebase (returns 100 matched snippets with context)
- Execute tests (returns thousands of lines of output, stack traces, and timing data)
- Query a GitHub issue tracker (returns 50 issue descriptions, comments, and metadata)
Each step appends a tool output to the conversation context, which is sent in full with the next step. By step 6, the agent may be carrying 150,000 tokens of accumulated context — most of it raw, unprocessed noise.
The structural waste problem
- JSON tool outputs contain enormous amounts of repeated field names, null fields, and metadata the LLM rarely needs
- Log files are 95% routine operational noise; only the FATAL and ERROR lines matter
- RAG chunks frequently contain the same boilerplate (documentation headers, license notices) across dozens of retrieved documents
- Code search results return full files when the LLM needs only function signatures and the five lines around a match
How Headroom works internally
At the highest level, Headroom applies a pipeline of transforms to the messages array before it leaves your system. The pipeline lifecycle has well-defined stages:
Your Agent / App
(Claude Code, Cursor, Codex, LangChain, Agno, your own code…)
│ prompts · tool outputs · logs · RAG results · files
▼
┌────────────────────────────────────────────────────┐
│ Headroom (runs locally — your data stays here) │
│ ──────────────────────────────────────────────── │
│ CacheAligner → ContentRouter → CCR │
│ ├─ SmartCrusher (JSON) │
│ ├─ CodeCompressor (AST) │
│ └─ Kompress-base (text, HF) │
│ │
│ Cross-agent memory · headroom learn · MCP │
└────────────────────────────────────────────────────┘
│ compressed prompt + retrieval tool
▼
LLM provider (Anthropic · OpenAI · Bedrock · …)
Each stage is extensible. You can attach pipeline extensions that observe or mutate content at any lifecycle event — a design that keeps core orchestration clean while supporting advanced customization.
Architecture deep dive
Headroom's architecture reflects three core design decisions that distinguish it from simpler approaches.
1 · Local-First
All compression runs on your machine. No content is uploaded to a third-party service. Compression adds sub-10ms overhead on most transforms — negligible compared to LLM latency.
2 · Polyglot Engines
Different content types have different redundancy profiles. A router-and-engine model dispatches each block to the best specialist: SmartCrusher for JSON, CodeCompressor for ASTs, Kompress-base for prose.
3 · Reversibility
Originals are cached locally. The LLM can call headroom_retrieve to fetch full context on demand — making compression safe for multi-step agentic workflows.
Implementation languages reflect the performance requirements: Python (78.7%) for orchestration, CLi, proxy and ML inference; Rust (16.8%) for performance-critical components (AST parser, CCR storage backend) exposed via PyO3 bindings; TypeScript (2.4%) for the Node.js SDK.
The six compression engines
CacheAligner
CacheAligner runs first, and its job is not to reduce tokens — it is to stabilize token usage through provider KV cache hits. Modern LLM providers cache shared prefixes across requests. If your prompt starts with an identical system prompt every time, the provider can skip re-processing it. But agentic systems often have dynamic preambles — timestamps, session IDs — that break prefix stability and cause cache misses. CacheAligner detects and pins these elements. On Anthropic with prompt caching enabled, this alone can produce 80–90% latency reductions on repeated calls.
ContentRouter
ContentRouter is the dispatch layer. When a block of content arrives, it classifies it by type —
JSON, source code (with language detection), log output, prose, image, or git diff — and routes
it to the appropriate specialist engine. ContentRouter uses a combination of heuristic rules (file
extensions, MIME types, structural signatures like {,
def,
func) and a lightweight ML classifier trained on agentic traces.
SmartCrusher
SmartCrusher handles JSON — the lingua franca of tool outputs, API responses, and structured data. It goes far beyond whitespace removal:
- Array normalization — emits the schema once, represents each row as a positional value array
- Null field elimination — drops empty fields with schema notation
- Anomaly preservation — statistical analysis identifies values deviating from the distribution; these are always kept
- Deep nesting collapse — flattens single-leaf nested objects to
parent.child: value
Result: 70–90% token reduction on typical API response payloads.
CodeCompressor
CodeCompressor is AST-aware and supports Python, JavaScript/TypeScript, Go, Rust, Java, and C++. Rather than treating source code as text, it parses the AST and re-serializes a compressed form:
- For context queries: emits function/method signatures, docstrings, class hierarchies, imports — omits implementation bodies
- For diffs: preserves all changed hunks at full fidelity; compresses unchanged context to a one-line summary
- For search results: emits only the matched function with ±5 lines; suppresses the rest of the file
For the code search (100 results) benchmark, CodeCompressor achieves 92% reduction — 17,765 tokens to 1,408.
Kompress-base
Kompress-base is a machine learning model hosted on HuggingFace (chopratejas/kompress-v2-base),
trained on agentic traces — real agent sessions with real
tool outputs and real LLM conversations. It handles unstructured prose, markdown documentation, ticket
descriptions, and mixed-format content using a ModernBERT-based token classifier that assigns importance
scores to each sentence or paragraph.
Training on agentic traces rather than general corpora is what makes it effective: it has learned that error messages are high importance, repeated disclaimers are low importance, and actionable recommendations are high importance. Typical savings: 30–50% on prose.
CCR — Context Compression Retrieval
CCR is the architectural pattern that makes Headroom safe for production. When Headroom compresses a block, it: (1) stores the original in a local TTL-aware store (Rust-backed); (2) generates a unique retrieval key; (3) injects a retrieval hint into the compressed version. The LLM sees something like:
[COMPRESSED — 94% reduction. Full original retrievable via headroom_retrieve("key:abc123") if needed]
Error spike detected in auth-service logs: 47 FATAL events, 12 unique error signatures.
Top error: NullPointerException in UserAuthHandler:127 (39 occurrences, 14:32–14:41 UTC)
If the LLM needs the raw logs, it calls headroom_retrieve and gets them. Compression
is reversible on demand, never permanently lossy.
Output token reduction
Everything above shrinks the tokens you send. But you also pay for every token the model writes back — and on Opus-class models, output costs 5× the input rate. A significant fraction of that output is waste: preambles, re-printed code, and deep "thinking" on routine steps.
Headroom trims this through two mechanisms:
Verbosity Steering
Appends a short “be terse, don’t restate context” note at the end of the system prompt — after your prompt, so the prefix remains stable and provider KV cache still hits.
Effort Routing
Dials down the model’s thinking budget when the agent is simply resuming after a tool result (file read, passing test). New questions and errors retain full thinking effort.
export HEADROOM_OUTPUT_SHAPER=1
headroom proxy --port 8787
# See estimated savings
headroom output-savings
# Reduction: 31.7% (95% CI 27.7% … 35.7%) [estimated]
Savings are reported as estimates with confidence intervals since you cannot know what the model would
have written without steering. For a measured number, use
HEADROOM_OUTPUT_HOLDOUT=0.1
to leave 10% of conversations unshaped as a control group.
Headroom Learn
headroom learn
mines your past agent sessions to automatically improve future ones. It scans local session history for
failed or corrected steps, identifies the pattern (missing information, wrong assumption, misread tool
output), and writes a correction to your agent’s instruction file:
CLAUDE.md,
AGENTS.md, or
GEMINI.md.
headroom learn # Preview what it found (dry run)
headroom learn --apply # Write corrections to instruction files
headroom learn --verbosity # Learn preferred output length from session history
headroom learn --verbosity --apply # Save verbosity preference; proxy uses it immediately
The --verbosity flag
reads your past sessions and infers how verbose you prefer answers by looking at how quickly you
interrupted long replies or moved on before reading them. It configures verbosity steering accordingly
— personalizing terseness without requiring you to articulate a preference.
Cross-agent memory
Modern development workflows often span multiple AI agents. Claude Code for architecture, Cursor for inline edits, Codex for automation. Each agent currently runs in isolation, unable to benefit from what the others learned. Headroom’s cross-agent memory changes this with a shared context store that persists facts and decisions across agent sessions, with automatic deduplication.
from headroom import SharedContext
ctx = SharedContext()
# In a Claude Code session
ctx.put("db_connection_format", "postgres://user:pass@host:5432/db?sslmode=require")
# Automatically available in any Cursor or Codex session (same project)
conn_format = ctx.get("db_connection_format")
The shared store includes agent provenance metadata — knowing that a fact came from Claude Code vs. Codex allows downstream agents to weight it appropriately.
MCP integration
The Model Context Protocol (MCP) is becoming the standard integration interface for AI agent ecosystems. Headroom ships a first-class MCP server that exposes its capabilities as native MCP tools.
headroom mcp install
This registers three tools for any MCP-compatible client (Claude Desktop, Cursor, custom MCP hosts):
| Tool | Description |
|---|---|
| headroom_compress | Compress a content block with the full pipeline |
| headroom_retrieve | Retrieve a cached original via CCR key |
| headroom_stats | Get compression statistics for the current session |
Supported AI tools and frameworks
Agent compatibility
| Agent | Wrap Support | Notes |
|---|---|---|
| Claude Code | ✓ Yes | --memory and --code-graph flags |
| OpenAI Codex | ✓ Yes | Shares memory with Claude sessions |
| Cursor | ✓ Yes | Prints config to paste into Cursor settings |
| Aider | ✓ Yes | Starts proxy + launches Aider |
| GitHub Copilot CLI | ✓ Yes | OAuth token exchange via headroom copilot-auth login |
| OpenClaw | ✓ Yes | Installs as ContextEngine plugin |
Framework SDK integrations
| Framework | Integration |
|---|---|
| Anthropic SDK | withHeadroom(new Anthropic()) |
| OpenAI SDK | withHeadroom(new OpenAI()) |
| Vercel AI SDK | wrapLanguageModel({ model, middleware: headroomMiddleware() }) |
| LiteLLM | litellm.callbacks = [HeadroomCallback()] |
| LangChain | HeadroomChatModel(your_llm) |
| Agno | HeadroomAgnoModel(your_model) |
| ASGI / FastAPI | app.add_middleware(CompressionMiddleware) |
Installation and setup
Requires Python 3.10+. Optional: Apple Silicon GPU acceleration via [pytorch-mps].
# Full installation with all features
pip install "headroom-ai[all]"
# Granular extras
pip install "headroom-ai[proxy]" # Proxy server
pip install "headroom-ai[mcp]" # MCP server
pip install "headroom-ai[ml]" # Kompress-base ML model
pip install "headroom-ai[code]" # CodeCompressor (Rust AST parser)
pip install "headroom-ai[memory]" # Cross-agent memory
pip install "headroom-ai[langchain]" # LangChain integration
pip install "headroom-ai[pytorch-mps]" # Apple GPU acceleration
# TypeScript / Node.js
npm install headroom-ai
Quick start tutorial
Option A: Zero-code proxy (any agent, any language)
headroom proxy --port 8787
# Point your agent at the proxy
export ANTHROPIC_BASE_URL=http://localhost:8787
claude # or any other AI agent
headroom perf # View real-time savings
Option B: Agent wrap (one command)
headroom wrap claude # Wraps Claude Code with compression + memory
headroom wrap codex # Wraps OpenAI Codex
headroom wrap cursor # Prints Cursor proxy config
headroom wrap aider # Wraps Aider with compression
Option C: Python library
from headroom import compress
import anthropic
client = anthropic.Anthropic()
messages = [{"role": "user", "content": "Analyze these logs: " + very_long_log_string}]
result = compress(messages, model="claude-opus-4-8")
print(f"Tokens saved: {result.tokens_saved}") # e.g. 55,200
print(f"Compression ratio: {result.compression_ratio}") # e.g. 0.08
response = client.messages.create(
model="claude-opus-4-8",
max_tokens=2048,
messages=result.messages
)
Option D: LangChain
from langchain_anthropic import ChatAnthropic
from headroom.integrations.langchain import HeadroomChatModel
base_llm = ChatAnthropic(model="claude-opus-4-8")
llm = HeadroomChatModel(base_llm)
response = llm.invoke("Summarize these 100 search results...")
Real benchmark analysis
Headroom publishes benchmarks from real agent workloads — not synthetic datasets. These four workloads are representative of what engineering teams run daily.
| Workload | Before | After | Savings | Primary Engine |
|---|---|---|---|---|
| Code Search (100 results) | 17,765 | 1,408 | 92% | CodeCompressor |
| SRE Incident Debugging | 65,694 | 5,118 | 92% | SmartCrusher + Kompress-base |
| GitHub Issue Triage | 54,174 | 14,761 | 73% | Kompress-base + SmartCrusher |
| Codebase Exploration | 78,502 | 41,254 | 47% | CodeCompressor |
Reproduce with: python -m headroom.evals suite --tier 1
The 47% ceiling on codebase exploration illustrates an honest limit: Headroom cannot compress genuinely novel, high-entropy content aggressively. When an agent is exploring a new codebase, it needs broad structural understanding — there is less redundancy to eliminate.
Accuracy preservation benchmarks
Token reduction is meaningless if it degrades answer quality. Headroom’s accuracy benchmarks use 100-sample runs on standard evaluation datasets:
| Benchmark | Category | Baseline | Headroom | Delta |
|---|---|---|---|---|
| GSM8K | Math reasoning | 0.870 | 0.870 | ±0.000 |
| TruthfulQA | Factual accuracy | 0.530 | 0.560 | +0.030 |
| SQuAD v2 | Question answering | — | 97% | 19% compression |
| BFCL Tools | Tool calling | — | 97% | 32% compression |
The TruthfulQA improvement (+0.030) is counterintuitive: compression improves factual accuracy. The likely explanation: Headroom removes verbose but misleading context that was pushing the model toward plausible-sounding but incorrect answers. The BFCL result (97% tool-calling accuracy at 32% compression) is critical for agent builders — tool-calling accuracy is the most operationally important metric in agentic workloads.
Headroom vs. the competition
| Feature | Headroom | OpenAI Compaction | RTK | lean-ctx | Hosted Services |
|---|---|---|---|---|---|
| Open source | ✓ | ✗ | ✓ | ✓ | ✗ |
| Local-first / Privacy | ✓ | ✗ | ✓ | ✓ | ✗ |
| Reversible (CCR) | ✓ | ✗ | ✗ | ✗ | ✗ |
| Multi-provider | ✓ | ✗ | ✓ | ✓ | Varies |
| Cross-agent memory | ✓ | ✗ | ✗ | ✗ | Some |
| MCP server | ✓ | ✗ | ✗ | ✗ | ✗ |
| Zero-code proxy | ✓ | ✗ | ✗ | Limited | Varies |
| Output token reduction | ✓ | ✗ | ✗ | ✗ | ✗ |
| AST-aware code compression | ✓ | ✗ | ✗ | ✗ | ✗ |
| ML model (trained) | ✓ | ✗ | ✗ | ✗ | Varies |
| headroom learn | ✓ | ✗ | ✗ | ✗ | ✗ |
| Max reported savings | 92% | ~35% | ~50% | ~40% | ~60% |
| Pricing | Free (OSS) | Included | Free | Free | Paid |
OpenAI Compaction is automatic and convenient but provider-locked, one-directional, and covers only conversation history — not tool outputs. RTK is effective for pure RAG pipelines but does not handle code, logs, or JSON tool outputs. lean-ctx is a truncation tool — it cannot distinguish a FATAL log line from an INFO line. Hosted services introduce data egress, per-call fees on top of LLM costs, and additional network latency.
Pros and cons
Advantages
- 92% reduction on SRE debugging and code search workloads
- Local-first — no data egress, strong compliance posture
- Reversible via CCR — originals are never permanently lost
- Zero-code proxy deployment for any existing agent or framework
- Output token reduction addresses the 5× output cost premium
- Cross-agent memory across Claude, Codex, Cursor, Aider
- 10+ framework SDK integrations (LangChain, Vercel AI, LiteLLM, Agno…)
- Honest benchmarks with reproducibility instructions
Disadvantages
- Requires local Python runtime — not compatible with restricted sandbox environments
- Kompress-base ML model adds RAM overhead on memory-constrained machines
- More moving parts than simple truncation — pipeline understanding required for advanced customization
- 47% ceiling on genuinely novel, high-entropy content (codebase exploration)
- Output savings are estimated (counterfactual by nature) — confidence intervals, not exact numbers
- Cross-agent memory full stack requires Docker (Qdrant + Neo4j)
- Some integration paths (GitHub Enterprise Copilot) still being validated across platforms
Cost-saving calculations
Concrete monthly cost model for a 10-person engineering team on Claude Opus 4.8-class models:
Without Headroom
- Input: 10 × 150K tokens × 20 days = 30M tokens/mo
- Input cost: 30M × $15/M = $450/mo
- Output: 10 × 30K tokens × 20 days = 6M tokens/mo
- Output cost: 6M × $75/M = $450/mo
- Total: $900/mo
With Headroom (conservative: 65% input, 30% output reduction)
- Input: 30M × 0.35 = 10.5M tokens/mo
- Input cost: 10.5M × $15/M = $157.50/mo
- Output: 6M × 0.70 = 4.2M tokens/mo
- Output cost: 4.2M × $75/M = $315/mo
- Total: $472.50/mo — saves $427.50
- Annual savings: $5,130
For teams where log analysis and code search dominate (90%+ compression achievable), savings can reach 70–80% of total LLM spend. Output token reduction alone on a $1,000/mo output bill saves ~$300/mo from a single configuration flag.
Frequently asked questions
Does Headroom change the answers I get from the LLM?
Is my code safe? Does Headroom send it anywhere?
How much latency does Headroom add?
[pytorch-mps] extra. This is negligible compared to LLM round-trip latency of 200ms–3s.Can I use Headroom with Gemini or other non-OpenAI/Anthropic providers?
HeadroomCallback).What happens if the CCR cache expires before the LLM retrieves an original?
headroom_retrieve returns a cache-miss response. The LLM can still work with the compressed information — it simply cannot expand it further. Configure TTL based on your typical session length.Does Headroom work in serverless environments?
pip install headroom-ai and call compress() inline before each LLM call.Can I use Headroom with self-hosted LLMs (Ollama, vLLM)?
OPENAI_BASE_URL to your local inference server and point your LLM client at Headroom’s proxy endpoint.How does headroom learn know which sessions to mine?
headroom learn reads session logs from your local agent history (Claude Code’s ~/.claude/sessions, Codex session store, etc.) using a plugin-based reader per agent type. Only sessions within the configured lookback window (default: 7 days) are analyzed.How does Headroom handle multilingual content?
Is Headroom production-ready?
headroom learn are newer and warrant more careful evaluation before production use.What license is Headroom under?
ENTERPRISE.md in the repository.Final verdict
Key takeaways
- Benchmark-validated 47–92% token reductions on the workloads that dominate AI engineering costs.
- Local-first architecture makes it the only open-source solution that preserves data privacy by design.
- CCR reversible compression solves the accuracy risk that makes compression dangerous in production agentic workloads.
- Output token reduction addresses the 5× premium on Opus-class output — a differentiated capability no other OSS tool currently offers.
Use Headroom if you…
- ✓Run AI coding agents daily and want savings without changing your code
- ✓Work across multiple agents and need shared memory
- ✓Build RAG pipelines or LLM APIs where context budget is a constraint
- ✓Are in a compliance-sensitive org that cannot send raw data to cloud services
- ✓Spend more than $200/mo on LLM input tokens
Skip it if you…
- ✗Use only one provider’s native compaction and are satisfied with it
- ✗Run in a restricted sandbox where local processes cannot execute
- ✗Have genuinely small context (under 10K tokens per call)
- ✗Need guaranteed lossless compression — CCR is reversible, but the compressed representation is lossy
Final recommendation
Headroom is the most technically sophisticated open-source solution to the AI token cost problem
available today. Its polyglot compression engines, reversible CCR architecture, zero-code deployment,
cross-agent memory, and output token reduction put it in a category of its own among local-first
compression tools. The evaluation barrier is low: install in an afternoon, run
headroom perf, and let the numbers make the case. For
any team spending meaningfully on LLM input tokens — which describes virtually every serious
AI application team today — this is a strongly recommended tool.