项目 / headroomlabs-ai/headroom

headroomlabs-ai/headroom

暂无行业标签
语言 Python标签 agentaianthropiccompressioncontext-engineeringcontext-windowfastapilangchainllmmcpopenaiproxypythonragtoken-optimizationclaude-codecursorprompt-engineeringtokenstypescript数据更新 2026-11-25 06:49:28 · 仓库 2026-11-24

一段话介绍

给 AI 编程助手瘦身的中间件,把废话日志压掉再喂给模型。

本站整理,非 GitHub 官方 description。

官方 description(GitHub API 原样)
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.
77,240累计星
5,957Fork
+549峰值日增
4上榜次数

官方快照(gh_history.db,2026-11-25):总榜 未进 Top50 · 日榜 未进 Top50 · 周榜未满 7 天基线(官方不生成) · 月榜暂无官方口径;下方四卡为站内趋势聚合(周卡按上榜次数,非官方 7 日增量窗)。

行业与场景 — 暂未挂到行业场景库

更多信息

以下三段按该项目自己的 GitHub README 章节摘录(可合理截断并标明);README 没有对应章节的留空,不编造。

我的用法
安装或使用说明见 https://docs.headroomlabs.ai/docs/fastapi。
特点或设计要点
项目支持在 Python 或 TypeScript 应用内直接调用消息压缩。
星标走势近 18 天
本站点评(非项目 README 原文)
相当于给 AI 配了个会做笔记的秘书,只把关键上下文递上去,每月调用大模型的费用能砍一大截。
首次发现 2026-10-20 · 最近在榜 2026-10-22 · 语言 Python · 贡献者 chopratejas、JerrettDavis、claude、abhay-codes07、gglucass
agentllmmcpsdk

GitHub 项目主页介绍

来自 GitHub 仓库 README / 主页介绍正文,正文较长,已截断:保留前 20000 字符(原始 37,166 字节),完整内容见 GitHub 仓库。

<div align="center">

<img src="https://raw.githubusercontent.com/headroomlabs-ai/headroom/main/.github/assets/hero.svg" alt="Headroom — the context compression layer for AI agents. A 55,957 token agent prompt compresses to the 24,340 tokens actually sent to the model, and the FATAL line at item 67 survives byte for byte." width="880">

<a href="https://trendshift.io/repositories/20881" target="_blank"><img src="https://trendshift.io/api/badge/repositories/20881" alt="headroomlabs-ai/headroom | Trendshift — #1 Repository Of The Day" width="250" height="55"/></a>

<p>
  <a href="https://github.com/headroomlabs-ai/headroom"><img src="https://img.shields.io/github/stars/headroomlabs-ai/headroom?style=flat&color=00F0B5&labelColor=0C1118&label=stars" alt="GitHub stars"></a>
  <a href="https://github.com/headroomlabs-ai/headroom/actions/workflows/ci.yml"><img src="https://github.com/headroomlabs-ai/headroom/actions/workflows/ci.yml/badge.svg" alt="CI"></a>
  <a href="https://pypi.org/project/headroom-ai/"><img src="https://img.shields.io/pypi/v/headroom-ai.svg?color=00F0B5&labelColor=0C1118&label=pypi" alt="PyPI"></a>
  <a href="https://www.npmjs.com/package/headroom-ai"><img src="https://img.shields.io/npm/v/headroom-ai.svg?color=00F0B5&labelColor=0C1118&label=npm" alt="npm"></a>
  <a href="https://huggingface.co/chopratejas/kompress-v2-base"><img src="https://img.shields.io/badge/model-kompress--v2--base-65D8FF?labelColor=0C1118" alt="Model"></a>
  <a href="https://docs.headroomlabs.ai/docs"><img src="https://img.shields.io/badge/docs-online-00F0B5?labelColor=0C1118" alt="Docs"></a>
  <a href="https://github.com/headroomlabs-ai/headroom/blob/main/LICENSE"><img src="https://img.shields.io/badge/license-Apache%202.0-98A4B3?labelColor=0C1118" alt="License"></a>
</p>

<p>
  <b><a href="https://docs.headroomlabs.ai/docs/quickstart">Quickstart</a></b> ·
  <b><a href="#headroom-for-teams">Headroom for Teams</a></b> ·
  <a href="#get-started-60-seconds">Install</a> ·
  <a href="#proof-measured-token-savings">Proof</a> ·
  <a href="#agent-compatibility">Agents</a> ·
  <a href="https://docs.headroomlabs.ai/docs">Docs</a> ·
  <a href="https://discord.gg/yRmaUNpsPJ">Discord</a> ·
  <a href="https://github.com/headroomlabs-ai/headroom/blob/main/llms.txt">llms.txt</a>
</p>

<sub><b>AI agents / LLMs:</b> read <a href="https://github.com/headroomlabs-ai/headroom/blob/main/llms.txt"><code>/llms.txt</code></a> here, or fetch
<a href="https://docs.headroomlabs.ai/llms.txt">the live index</a> ·
<a href="https://docs.headroomlabs.ai/llms-full.txt">full docs blob</a>.</sub>

</div>

<!-- mcp-name: io.github.headroomlabs-ai/headroom -->

**Headroom** (`headroom-ai` on PyPI and npm) compresses everything your AI agent
reads — tool outputs, logs, RAG chunks, files, and conversation history — before
it reaches the LLM. Same answers, fewer input tokens. Measured: 21–57% fewer
input tokens on four agent scenarios, 90%+ on repeated JSON arrays and log
lines, little on prose ([Proof](#proof-measured-token-savings)). Compression
runs on your machine; no prompt or file content is sent anywhere to be compressed.

## Start here

**My app calls an LLM** (Python, LangChain, LiteLLM, Agno, Strands):

```bash
pip install headroom-ai
```

```python
from headroom import compress

result = compress(messages, model="gpt-4o")  # OpenAI or Anthropic message dicts
client.chat.completions.create(model="gpt-4o", messages=result.messages)
```

No API key, no model download, in-process. Set `HEADROOM_OFFLINE=1` for a
zero-network run. Tool and assistant messages are compressed; user messages are
left alone unless you pass `compress_user_messages=True`.
[FastAPI example](https://docs.headroomlabs.ai/docs/fastapi) ·
[API reference](https://docs.headroomlabs.ai/docs/api-reference).
TypeScript apps: `npm install headroom-ai` plus the proxy
(`pip install "headroom-ai[proxy]"`, `headroom proxy --port 8787`); the npm SDK
sends messages to it. [TypeScript quickstart](https://docs.headroomlabs.ai/docs/quickstart)

**I run coding agents** (Claude Code, Codex, Cursor, Copilot, OpenCode, Aider):

```bash
uv tool install --python 3.13 "headroom-ai[all]"
headroom wrap claude
```

Zero code changes. [Agent compatibility](#agent-compatibility) ·
[Proxy](https://docs.headroomlabs.ai/docs/proxy)

<p align="center">
  <a href="https://headroomlabs.ai"><img src="https://raw.githubusercontent.com/headroomlabs-ai/headroom/main/.github/assets/enterprise-perk.svg" alt="Headroom Enterprise for teams. Talk to us: hello@headroomlabs.ai." width="880"></a>
</p>

<div align="center">
  <img src="https://raw.githubusercontent.com/headroomlabs-ai/headroom/main/HeadroomDemo-Fast.gif" alt="Headroom compressing a 10,144 token log dump to 1,260 tokens while preserving the FATAL line" width="820">
  <br><sub>10,144 → 1,260 tokens. The same <code>FATAL</code> found.</sub>
</div>

## What it does

- **Library** — `compress(messages)` in Python or TypeScript, inline in any app.
- **Proxy** — `headroom proxy --port 8787`, zero code changes, any language.
- **Agent wrap** — `headroom wrap claude|codex|grok|copilot|cursor|aider|opencode|cline|continue|goose|openhands|openclaw|vibe|omp|droid|zcode` in one command; undo with `headroom unwrap <tool>`.
- **MCP server** — `headroom_compress`, `headroom_retrieve`, `headroom_stats` for any MCP client.
- **Cross-agent memory** — one shared store across Claude, Codex, Gemini and Grok, with automatic dedup.
- **`headroom learn`** — mines failed sessions and writes corrections to `CLAUDE.local.md` (default, gitignored), `CLAUDE.md`, `AGENTS.md`, `GEMINI.md` or `GROK.md`.
- **Output token reduction** — trims what the model *writes back*, not only what you send. See [below](#output-token-reduction).
- **Reversible (CCR)** — originals are cached locally and retrieved on demand.

## How it works

```
 Your agent / app
   (Claude Code, Cursor, Codex, LangChain, Agno, Strands, 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-v2-base (text, HF)  │
    │                                                    │
    │  Cross-agent memory  ·  headroom learn  ·  MCP     │
    └────────────────────────────────────────────────────┘
        │   compressed prompt  +  retrieval tool
        ▼
 LLM provider  (Anthropic · OpenAI · Bedrock · …)
```

- **ContentRouter** detects the content type and selects a compressor for it.
- **SmartCrusher / CodeCompressor / Kompress-v2-base** handle JSON, source code and prose respectively.
- **CacheAligner** flags volatile content that would bust a provider KV-cache prefix. It never rewrites prompts.
- **CCR** stores originals locally so the model can call `headroom_retrieve` when it needs the full text.

→ [Architecture](https://docs.headroomlabs.ai/docs/architecture) ·
[CCR](https://docs.headroomlabs.ai/docs/ccr) ·
[Kompress-v2-base model card](https://huggingface.co/chopratejas/kompress-v2-base)

## Get started (60 seconds)

```bash
# 1 — Install
uv tool install --python 3.13 "headroom-ai[all]"  # CLI in a self-contained env
pip install "headroom-ai[all]"                    # Python — ships the `headroom` CLI
npm install headroom-ai                           # TypeScript SDK only — no CLI

# 2 — Pick a mode
headroom deploy                         # turnkey local deployment + agent config
headroom wrap claude                    # wrap a coding agent
headroom proxy --port 8787              # drop-in proxy, zero code changes
# or: from headroom import compress     # inline library

# 3 — Check it and watch the savings
headroom doctor                         # health check — confirms routing works
headroom perf
headroom dashboard                      # live savings (proxy must be running)
```

### Reduce input tokens in your own app

```python
from headroom import compress
from openai import OpenAI

messages = [{"role": "user", "content": "Analyze these results"}]
result = compress(messages, model="gpt-4o")

client = OpenAI()
response = client.chat.completions.create(model="gpt-4o", messages=result.messages)
print(f"Saved {result.tokens_saved} tokens ({result.compression_ratio:.0%})")
```

Launch a wrapped agent session each time, so the setup runs. `headroom wrap`
starts a local proxy and launches the agent configured to route through
Headroom. Add `--code-memory serena` to also install
**[Serena](https://github.com/oraios/serena)** for semantic code navigation (off
by default). For Claude Code, Serena is registered for the wrapped project only
(as a `local`-scope MCP server in `~/.claude.json`); use `--code-memory-scope user`
to make it available in every project. `headroom unwrap` removes either registration.

`headroom wrap ...` is session-scoped: its proxy exits with the wrapped agent.
For a proxy that survives reboots, use the turnkey `headroom deploy` command.
Use `headroom install apply` when you need to choose a specific persistent
service, scheduled task, Docker runtime, scope, or provider target; see the
[persistent installs guide](https://docs.headroomlabs.ai/docs/persistent-installs).

The `headroom` CLI ships only in the PyPI package. The npm `headroom-ai` package
is the TypeScript SDK — a library you import
(`import { compress } from 'headroom-ai'`) — and provides no `headroom` command.

## Proof: measured token savings

Four scenarios built from real MCP server output formats, measured with the
provider tokenizer and the shipped `compress()` at its default configuration.
Seeded and offline, so you get the same numbers we did:

```bash
uv run python benchmarks/index_proof_table.py --seed 20260902
```

| Scenario | Before | After | Saved |
|---|---:|---:|---:|
| Code search (100 results) | 17,199 | 13,597 | **21%** |
| SRE incident debugging | 55,957 | 24,340 | **57%** |
| Codebase exploration | 58,801 | 33,895 | **42%** |
| GitHub issue triage | 46,067 | 32,429 | **30%** |

Savings scale with how repetitive the payload is. Repeated JSON arrays and log
lines clear 90% in `benchmarks/bench_latency.py`; prose and already-dense output
compress very little. Run `headroom savings` against your own traffic for the
number that applies to you.

Compression costs **well under a millisecond** — 0.21 ms p50 on a 10K-token JSON
search result, 1.4 ms at 100K tokens — so it does not show up in agent latency.

**Accuracy.** `python -m headroom.evals suite --tier 1`:

| Benchmark | Category | N | Baseline | Headroom | Delta |
|---|---|---:|---:|---:|---|
| GSM8K | Math | 100 | 0.870 | 0.870 | ±0.000 |
| TruthfulQA | Factual | 100 | 0.530 | 0.560 | +0.030 |
| SQuAD v2 | QA | 100 | — | 97% | at 19% compression |
| BFCL | Tools | 100 | — | 97% | at 32% compression |

At N=100 a delta of ±0.03 falls inside the confidence interval, so TruthfulQA
shows no detectable difference rather than an improvement.
[Methodology →](https://docs.headroomlabs.ai/docs/benchmarks)

## Output token reduction

Everything above shrinks the prompt you **send**. You also pay for every token
the model **writes back**, and on Opus-class models output costs 5× input. Much
of that output is ceremony: "Great, let me…" preambles, code re-printed straight
back at you, and deep reasoning spent on routine steps like reading a file.

Headroom trims it from the proxy, with no change to your code:

- **Verbosity steering** appends a short "be terse, don't restate context" note to the *end* of the system prompt, so your prompt cache still hits.

It applies to Anthropic `/v1/messages` and to OpenAI-compatible
`/v1/chat/completions` and `/v1/responses`, with the same `output_shaper:*`
labels on all paths.

```bash
export HEADROOM_OUTPUT_SHAPER=1     # off by default
headroom proxy --port 8787
```

> **Already running a proxy?** These switches are read live on every request, so
> a proxy that `headroom wrap` *reused* rather than started would not see a value
> you export afterwards — its environment was snapshotted at launch. `headroom
> wrap` hot-syncs your current settings to the running proxy over a loopback
> `POST /admin/runtime-env`, so they take effect with no restart and no dropped
> requests. On a shared proxy these overrides are global; the last explicit
> setting wins.

**Terseness you didn't have to configure.** People rarely state how terse they
want answers — they show it, by interrupting long replies or moving on before
they could have read them. `headroom learn --verbosity` reads past sessions and
picks the level:

```bash
headroom learn --verbosity            # dry run — preview what it found
headroom learn --verbosity --apply    # save it and apply it to the running proxy
```

A proxy in cache mode (the default) never re-reads the learned level, because a
level that changes mid-conversation would bust the prompt cache. There `--apply`
pins it with `HEADROOM_VERBOSITY_LEVEL`; set that variable yourself to keep it
after a restart.

**Measuring it.** Output savings are counterfactual — we never see what the model
*would* have written — so Headroom reports an estimate with a confidence range
and labels it as one:

```bash
headroom output-savings
# Reduction: 31.7%  (95% CI 27.7% … 35.7%)   [estimated]
```

For a measured number instead, hold out 10% of conversations as an unshaped
control: `export HEADROOM_OUTPUT_HOLDOUT=0.1`. The dashboard's **Output Tokens
Saved** card then reads `measured` rather than `estimated`, with the band.

→ [Output token reduction](https://docs.headroomlabs.ai/docs/savings)

## Agent compatibility

| Agent | `headroom wrap` | Notes |
|---|:---:|---|
| Claude Code | ✅ | `--memory` · `--code-graph` · `--1m` · `--tool-search` |
| Codex | ✅ | shares memory with Claude |
| Grok CLI | ✅ | routes via `GROK_MODELS_BASE_URL` |
| Cursor | Manual setup | starts the proxy and prints base URLs for Cursor settings |
| Aider | ✅ | starts proxy + launches |
| Copilot CLI | ✅ | starts proxy + launches |
| VS Code Copilot | ✅ | transparent proxy; keeps the selected model |
| OpenClaw | ✅ | installs as a ContextEngine plugin |
| OpenCode | ✅ | injects config · starts proxy + launches [^third-party-upstream] |
| Cline | ✅ | starts proxy + injects config |
| Continue | ✅ | starts proxy + injects config |
| Goose | ✅ | starts proxy + launches |
| OpenHands | ✅ | starts proxy + launches |
| Mistral Vibe | ✅ | starts proxy + launches |
| Oh My Pi | ✅ | Anthropic + OpenAI/Codex · injects config · starts proxy + launches |
| Factory Droid | ✅ | routes via `FACTORY_API_BASE_URL`; Anthropic-model turns compressed, other Factory traffic passed through |
| Cortex Code | Library only | 60–65% savings in library mode; no `wrap` |
| Kimi CLI | ✅ | OAuth bearer forwarded — log in once |
| ZCode | ✅ | starts the proxy and prints base URLs for ZCode settings |

[^third-party-upstream]: `headroom wrap` routes OpenAI-compatible traffic to the default upstream (`https://api.openai.com/v1`). For a third-party OpenAI-compatible provider (DeepSeek, Together, OpenRouter, a self-hosted gateway), pass `--openai-api-url https://api.deepseek.com/v1` — or set `OPENAI_TARGET_API_URL` before wrapping — otherwise your provider key is sent to OpenAI and rejected with `401 Incorrect API key provided`. See [OpenCode + DeepSeek](https://docs.headroomlabs.ai/docs/opencode-deepseek).

Any OpenAI-compatible client works through `headroom proxy`. MCP-native clients:
`headroom mcp install`. Undo durable wrapping with `headroom unwrap <tool>`
(`claude`, `copilot`, `codex`, `grok`, `kimi`, `omp`, `opencode`, `openclaw`,
`zcode`). Registry authors should use the canonical [`server.json`](https://github.com/headroomlabs-ai/headroom/blob/main/server.json)
rather than reconstructing the `headroom mcp serve` contract from prose.

For Anthropic `/v1/messages`, `--mode cache` skips automatic `--memory` context injection so the provider prefix remains stable. OpenAI chat/responses and Gemini append memory to the live-zone tail. Use `--mode token` when you need automatic memory context on the Anthropic path.

<details>
<summary><b>GitHub Copilot CLI subscription mode</b></summary>

Headroom can route Copilot CLI subscription traffic through the local proxy:

```bash
headroom copilot-auth login
headroom wrap copilot --subscription -- --model gpt-4o
```

The wrapper exchanges Headroom's reusable GitHub OAuth token for Copilot's
short-lived API token and prints the upstream endpoint as
`COPILOT_PROVIDER_API_URL=...` at launch. `headroom copilot-auth login` stores a
Headroom-specific Copilot OAuth token, rather than relying on generic GitHub or
Copilot CLI tokens that can read account metadata but are still rejected by
Copilot's token-exchange endpoint.

For GitHub Enterprise Server or a custom-domain Copilot deployment, set one of
these before launching. If both are set, the URL wins:

```bash
export GITHUB_COPILOT_ENTERPRISE_DOMAIN=ghe.example.com
export GITHUB_COPILOT_ENTERPRISE_URL=https://ghe.example.com
```

For GitHub.com Enterprise Cloud URLs such as
`github.com/enterprises/your-enterprise`, set neither — Headroom uses GitHub's
normal token-exchange endpoint and the Copilot API endpoint advertised for the
signed-in account.

**Platform support.** macOS auth reuse through Copilot CLI Keychain storage and
Windows device authentication are live-tested. Copilot CLI 1.0.81 does not expose
its Windows login through the legacy Credential Manager schema Headroom reads, so
run `headroom copilot-auth login` on Windows. Linux Secret Service /
`secret-tool` reuse is implemented but not yet validated on a real desktop. In
Docker and CI, pass an explicit `GITHUB_COPILOT_TOKEN` or
`GITHUB_COPILOT_GITHUB_TOKEN` instead of relying on host keychain access.

</details>

<details>
<summary><b>GitHub Copilot in VS Code</b></summary>

Headroom overrides Copilot's API proxy endpoint, so the VS Code model picker
stays authoritative. GPT-5.5, GPT-5.6 Luna/Sol/Terra, Claude Sonnet/Opus and
other Copilot models keep their original model IDs while traffic passes through
the local compression proxy. Headroom does not patch VS Code or change Codex
settings.

```bash
headroom copilot-auth login
headroom wrap vscode
```

Keep the command running and use Copilot normally. The short-lived upstream
Copilot token is held only in the proxy process.
[Full guide →](https://docs.headroomlabs.ai/docs/vscode-copilot)

</details>

<details>
<summary><b>Claude Code in VS Code</b></summary>

The official Claude Code extension embeds Claude Code and reads the same user
settings as the CLI. Install the proxy extra, then run the wrapper from the
project you will open in VS Code:

```bash
pip install "headroom-ai[proxy]"
headroom wrap vscode-claude
# Optional: persist Claude Code's client-owned 1M model selector
headroom wrap vscode-claude --1m
```

Reload the VS Code window on first run. Keep the wrapper terminal running while
you use the Claude Code panel; the dashboard or proxy log printed at startup
shows requests and savings. Your Anthropic authentication and selected model are
preserved. `Ctrl+C` stops the proxy; `headroom unwrap vscode-claude` restores the
settings that existed before setup.

With `--1m`, Headroom writes the resolved `[1m]` model selector to Claude Code's
top-level user setting and restores the exact prior model on
`headroom unwrap vscode-claude` or when setup runs again without `--1m`. Use
`headroom wrap vscode-claude --no-configure --1m` to print the setting without
writing files.

Claude Code and Anthropic own 1M model support and account eligibility. Local
tests prove persisted settings and restoration, not a live entitled VS Code
session or the resulting context window.
[Full guide →](https://docs.headroomlabs.ai/docs/
↑