Listed from the MCP registry; nobody on Odel publishes it.

MCP server: One MCP server.

Distil

@dshakesRun by its publisher: served from their own domain, namespace checked by the registry.MCP server · External

Reversibly compress tool outputs to recoverable handles; expand to exact original bytes on demand.

Freeno charge per call

Runs on your machine from its package; the steps are below.

What it does

  1. Reads
  2. Writes
  3. High impact

At most: moves money, runs code or commands, deletes data, or sends messages for you.

What it costs

Free

Odel charges nothing per call. The publisher may charge for its own service.

Runs locally over stdio

This server isn't hosted — your MCP client launches it from a package registry. Use one of the commands below, or drop the config into your client (e.g. Claude Desktop).

PyPIdistil-llmv1.30.0

Run

uvx distil-llm

MCP client config

{
  "mcpServers": {
    "distil": {
      "command": "uvx",
      "args": [
        "distil-llm"
      ]
    }
  }
}
README43 min read

Distil — cuts what your coding agent costs you, and shows you the real bill, cache included

CI PyPI version npm version Python versions license zero runtime deps typed PyPI installs/month, bot-filtered

Distil measures what your coding agent's context tooling actually costs you —
in dollars per solved task and in changed decisions: any compressor, your provider's own compaction, and its own.

bash
uv tool install distil-llm && distil setup

Other installs (curl, Homebrew, pipx, Windows): Install your way

bash
distil wrap -- claude      # run your agent through distil (or let `distil setup` make it always-on)
distil savings             # what it saved you, from your own traffic
distil doctor              # if something looks off
bash
distil audit --compressor anthropic-context-editing --cap-usd 1 # did it change what your agent does, and what it cost? (opt-in, capped)
distil audit report # helped, hurt, or can't tell yet, per compressor

Distil also compresses (lossless by default, every byte recoverable), and holds that compressor to the same measurements.

What the measurements say today (2026-10-06; every figure links to its artifact)

  • On short coding tasks no compressor is shown to save money. SWE-bench Lite, 298 tasks, same model and grader: distil is at parity with no compression ($0.0393 vs $0.0387 per solved task). RTK looked 20.7% cheaper per task until we found that its arm read other arms' prompt cache; re-priced as a cold run it is −6.5% [−13.1%, +0.1%], not significant. Selective Context and Anthropic context editing are not cheaper. Headroom has not run there yet. Scoreboard →
  • Long sessions: inconclusive. A 7-task long-horizon pilot (median 63–69 steps) shows no cost difference for distil or RTK; on the 6 tasks without one crashed attempt, distil cost 9.7% more than plain. Run →
  • Why. An offline simulator that reproduces the provider's bill within 2.5% on runs it never saw finds that lossless policies change cost by less than 0.2%, and that lossy compression saves money only if the agent does not take extra steps to make up for what was removed. Measuring that is the next live A/B. Simulator → · Why RTK looked cheaper →
  • On the maintainer's own metered Claude Code traffic (13,191 requests, September 2026) distil removed an estimated 8.3–9.2% of the bill, cache priced in, its own spend netted out (source, method). That is a same-trajectory estimate: it assumes the agent behaved the same, which is exactly what the A/B above has to check.

Why trust the measurements

  • It doesn't break your prompt cache. Distil never rewrites bytes the provider still has cached; older context changes only once that cache has already expired. We shipped that bug once, measured what it cost, and made the rule an enforced invariant. The cache contract →
  • Every compressed byte is recoverable. What distil folds away it keeps in a local store, and the agent gets a distil_expand tool to pull the exact original back mid-task. How the digest works →
  • It's measured on a real bill, receipts included. Savings are counted per request and calibrated against the usage your provider actually bills; every request writes a hash-chained receipt you can verify. The same harness runs every other compressor, and when it found a flaw in its own head-to-head it published the correction. How it's measured →

And it tells you when it is hurting you. Shadow mode replays a sample of requests on the original and the compressed context and reports the difference per compression mode; when the digest's harm bound goes over budget, the proxy holds itself at lossless-only. Pointed at the providers instead, the same check found Anthropic's context clearing changed the agent's next action in 37 of 40 cases with every old tool result cleared (keep=0, synthetic corpus) (study).

Going deeper: what distil checks, and what it found when it pointed those checks at the providers' own compaction ↓

What it does

  • Referee your context tooling — distil audit replays a capped sample of your own requests as a named compressor (distil, Anthropic context editing, OpenAI compaction, Headroom) would shape them and reports helped / hurt / can't tell yet, in billed dollars and in the agent's next action (ADR 0024). Offline, the SWE-bench outcome harness scores any arm on dollars per solved task, with each arm's prompt cache isolated; results are on the scoreboard.
  • Wrap your agent — 19 presets: distil wrap -- <agent> for aider · claude · gemini · copilot · goose · grok · kilo · kimi · vibe · openclaude · opencode · openhands · qwen · cline · codex · cn · crush · droid · omp. Zero config, no code change. distil wrap --list prints every target, its mechanism and the provider shape it speaks.
  • Run a proxy — point any base_url client at it. Python, TypeScript, any language, any framework. Sync proxy, async proxy, and a standalone gateway, with the same provider coverage in each: Anthropic Messages, OpenAI Chat Completions and the Responses API, Azure OpenAI, Gemini generateContent, AWS Bedrock InvokeModel and Google Vertex AI (Anthropic and Gemini). Which routes compress →
  • Call it as a library — from distil import compress_messages in your own agent loop.
  • Give your agent a recall tool — MCP server: it compresses its own output and gets the exact bytes back on demand.
  • Framework hooks — LangChain · LangGraph · LiteLLM · Agno · Strands · AutoGen · LlamaIndex, in-process, no network hop — plus an ASGI middleware for any Starlette/FastAPI app that hosts its own LLM endpoint, and the npm package for the Vercel AI SDK. A strict-typed TypeScript SDK (sdk/typescript, ADR 0029) adds compress(messages, { provider }) for Anthropic and OpenAI shapes; like every in-process library it is lossless-only, byte-identical to the Python engine.
  • Where a proxy can't reach — distil setup --hooks: Claude Code, Cursor (MCP output), Gemini CLI and Codex CLI compress tool output through their documented post-tool hooks. Lossless-only on a subscription unless you add --digest; every digest recoverable with distil expand <handle>. No proxy, no credentials touched. distil quota shows the rate-limit window it buys back. Hooks →
  • Shape shell output at the source — distil sh -- <command> (opt-in, ADR 0026) keeps every failure, error and summary line of a test run or git status verbatim and folds the passing-test noise behind a distil expand handle; distil hook install --shell makes Claude Code use it. On SWE-bench Lite transcripts test runs are rare, so it removes 0.06% of bash output there and stays opt-in. Shell →
  • Same mechanisms on every provider — re-fetch verbatim, cold-point eviction, the edit-quote guard and census run on Anthropic Messages, OpenAI Chat and Responses, and Gemini; OpenAI and Gemini are priced, so savings and distil audit stop booking $0 there; the distil savings what-if replays Codex CLI and Gemini CLI sessions as well as Claude Code's. Parity matrix →
  • VS Code Copilot Chat — its BYOK Custom Endpoint can point at a distil proxy: distil setup --vscode.
  • Keep a span verbatim — <distil:keep>…</distil:keep> in a prompt or tool output is never compressed.
  • Keeps MCP tool search on — distil wrap -- claude keeps Claude Code's MCP tool search switched on, which Claude Code otherwise turns off behind a proxy, so unused connectors stay deferred instead of riding along on every turn. Verified live on 1.54.0 (2026-09-25): tools_deferred of 4–5 on every request, tool payload 9,733 tokens, prompt-cache reads intact. (ADR 0013)
  • Real code skeletons — pip install 'distil-llm[code]' adds tree-sitter parses for Go, Rust, Java, C/C++, Ruby and TS/JS. Code skeletons →
  • See what it did — live status line, session dissect, per-request headers, OTel spans, Prometheus metrics.
bash
uv tool install distil-llm && distil setup    # detects your agent + billing, wires everything

Not sure which of those you want? Two questions pick your mode → — plain language, honest savings ranges, no jargon.

Four ways to run distil — agent wrap, proxy/gateway, MCP server, and the in-process library. Wrap, proxy and MCP reach the reversible digest tier, covered by the decision-equivalence certificate; the in-process library is lossless-only and byte-identical to the Python engine, enforced by a conformance suite.

Will it save you money? On metered billing (an API key) it cuts the tokens you send — an estimated 8.3–9.2% of the bill on the maintainer's traffic, if the agent behaves the same. Whether that shows up as a lower bill depends on the workload: on short SWE-bench tasks the net cost effect measured cost-neutral, and the long-session pilot (7 tasks) is inconclusive. On a flat-rate Pro/Max subscription there is no per-token bill to cut, but there is a rate-limit window, and spending fewer tokens per turn leaves more of it for the next task. distil quota shows that window live. Savings come from large, repetitive tool output: verbose JSON and duplicated log runs compress 25–99%, while prose and unique-line output compress ~0% — a short session that never reads a big file showing near 0% is the tool working correctly, not failing. Why → Shell output (grep, git, ad-hoc scripts) goes through that same generic, reversible digest (ADR 0015); search, listing and reads stay verbatim. The one exception is opt-in: distil sh shapes test-runner and git status output at the source (ADR 0026).

◉  LIVE · measured from the opt-in census on a public git branch, never estimated

community tokens saved decision-equivalence active installs, 30d

▶  Watch the counter tick live & audit every number →

⚡ Get the savings
2 min, no config

uv tool install distil-llm
distil setup
🔬 See the proof
real harness

benchmark ↓ · paper
vs the others

Use it · Library · Integrations · Install · Why trust it · Full Docs → · llms.txt

AI agents: read /docs/llms.txt for a compact, machine-oriented summary of what distil is and how to call it.


🧩 Use it as a library

Building the agent yourself? Compress the message list where it lives — no proxy, no network hop:

python
from distil import compress_messages, expand_handle

result = compress_messages(messages)          # OpenAI/Anthropic-style dicts
print(f"{result.saved_pct:.1f}% smaller")
response = client.messages.create(model=..., messages=result.messages)

original = expand_handle(result.handles[0])   # byte-exact, any time, any process

Tool results get the reversible digest; user and system text get lossless transforms only; the model's own turns are never rewritten. Handles resolve across processes and restarts, so a digest made by the proxy expands here and vice versa. verbatim=True disables digests entirely.

Named compress_messages/expand_handle rather than compress/expand because distil.compress and distil.expand are modules — a top-level export sharing those names would resolve to the function or the module depending on unrelated import order.

TypeScript too — compress(messages) from the npm package, byte-identical to the Python engine. Full reference: Library API → · runnable examples: python_library.py · js_library.ts.

Maintain a framework? docs/INTEGRATING.md is the ~20 lines and the four rules — we would rather the integration live in your repo than ours.


🔬 What distil checks — and what it found

Something is rewriting your agent's context.
Distil measures what it cost you.

Your provider now edits the context window for you — clearing old tool results, summarizing history — by default, server-side, with no report of what changed.
Distil is the instrument that answers the only question that matters: did the agent still do the same thing?

We pointed it at the providers. Anthropic's default context-editing retention rule (keep=3, fired at a 3k-token trigger rather than the default 100k, on a corpus ordered so the decision-bearing facts are older than the three kept tool uses) changed the agent's next action in 95–100% of cases, against a 2.5% A/A noise floor. Keeping the 3 most recent tool uses didn't lower the change rate at all — it turned stalling into acting on missing facts. OpenAI's compaction changed 12.5–20%. Pre-registered, replicated, n=40 per run.

Read the study → · rerun it on your own config

Distil also compresses — the tool output, logs, and history your agent re-sends every turn, reversibly.
It's the one context operation that ships with its own certificate, its own adversarial gate, and a number it is willing to refuse to print.

The 60-second version

Compression that cannot be checked is a guess about your agent's behaviour.
Distil is built so every part of it is checkable, and so the checks are allowed to come back no.

  • It measures decision-equivalence per request — and can say no. Shadow mode replays a sampled request three times: twice on the original context and once on the compressed one, then reports 1{A=B} − 1{A=A'} — a paired difference against the model's own self-agreement, with a bootstrap 95% CI, unclipped, so it is allowed to be negative, and per compression mode. One reporting floor (50 A/B + 30 A/A) gates every surface; below it, every surface says below reporting floor instead of a number. On the maintainer's 2026-09-15 sample the digest agreed 102/206 times against a self-agreement of 113/206 — −5.3 pp, over the 5% budget — while lossless-only read 109/192 against 109/193 (≈0). The pooled figure, which averaged the two, read inside the budget; that is why every report now shows each mode, and why the drift guard holds digest at lossless-only when its recent harm bound is over budget (ADR 0022).
  • What it folds, it can give back byte-exact. A digest is a marker plus a handle into a local content-addressed store, and the agent gets a distil_expand tool to recover the original mid-task. The multi-tenant gateway runs Tier-0 only by default; an operator can opt a gateway into the digest with --digest, which is unguarded there (no per-mode certification on the gateway yet), and a tenant can only expand its own handles.
  • It will not digest a line your agent has to quote back. An Edit(old_string=…) is a literal match. Reading exact-quote provenance from the shell command, not just the tool name, took byte-exact quote loss from 39.3% → 16.2% on real coding traffic — and it costs real savings, which we price rather than hide.
  • It does not break your prompt cache. Compression is suffix-only and cache-monotonic by construction: a later turn may never rewrite bytes the provider has already cached. We shipped that bug once, measured it at 2× the cost of compressing nothing, and made the invariant enforced. The cache contract →
  • It has been pointed at a hostile input, not just a hard one. distil validate --adversarial runs a COMA-class battery through the same path the proxy uses, and we publish the two cases that do not come back clean. Threat model →
  • Every rung of the dial is measured, not just the default. distil bench --curve traces savings against fact recall across the whole ladder, offline and free. The curve →

Proof and provenance

Every claim above is checkable, and so is the supply chain that shipped it. Releases carry PEP 740 attestations so you can verify a build came from this repo's CI, not a compromised laptop; a CycloneDX SBOM ships with every release so you know what's inside; OpenSSF Scorecard runs weekly against the repo itself. The adversarial path is documented rather than assumed: see the threat model and the security whitepaper for what's in scope and what isn't, and run distil validate yourself to gate a deployment against hostile input before you trust it with one.


Why trust it 📊

On SWE-bench Lite the shipped path is cost-neutral and within about 2 points on task success — not statistically distinguishable at n=300.

Two runs after the shell-search fix, distil-served vs plain Claude: 204/299 vs 210/299 (−2.0 pts, 95% CI −5.5..+1.5; cost $7.18 vs $7.18) and 213/298 vs 218/298 (−1.7 pts, 95% CI −5.1..+1.7; cost $8.44 vs $8.52). Non-inferiority at the pre-registered 5-point margin is not shown; the long-session pilot (7 tasks) is inconclusive. Every other compressor is scored the same way on the scoreboard. Reports: low effort · medium effort.

Distil vs LLMLingua-2 vs Headroom — token savings, decision-change rate, latency

Research configurations (E8–E14, SWE-bench Verified) are on the research page. They are not the shipped path, and none of them is quoted here as a result for it.

Why Distil — the properties, not the adjectives

Headroom column read directly against the public headroom-ai 0.37.0 source, as of v0.37.0, 2026-09-04; every line there cites a file:line in that release. Facts, not adjectives — and where it is genuinely strong, we say so.

PropertyDistilHeadroom 0.37.0 (2026-09-04)
Per-request behavioural checkPaired A/A′/B replay, unclipped difference, bootstrap CI, one reporting floorNo shadow or dual-send path in the codebase; accuracy_guard="strict" is echoed on /healthz and /stats but nothing branches on it
Recovery of what was foldedContent-addressed store + agent-facing distil_expand, byte-exact, verified by a gateA TTL cache (SQLite, 1800s, 1000-entry FIFO), no integrity or round-trip check
Lossy paths with no recoveryNone — every server that emits a stub (proxy and gateway) injects and answers distil_expandFour: OpenAI chat streaming, Responses under ChatGPT auth, Gemini streaming, Bedrock
Savings numberCounted, then calibrated against the provider's billed usageFalls back to chars/3.5
Exact-quote guarantee for coding agentsProvenance read from the shell command, not just the tool name; quote loss 39.3% → 16.2%Not a property the tool has
Cache contractSuffix-only, cache-monotonic, enforced as an invariantGenuinely strong prompt-cache replay (overlay_cached_prefix) — real engineering
Adversarial gateCOMA-class battery in CI; the two cases that don't come back clean are publishedNone shipped
Degradation curveEvery ladder rung measured, offline and freePoint configuration only
Shipped defaultCompressesMode cache — a full bypass on Bedrock, freeze-only on OpenAI

Headroom 0.42.0, offline (2026-10-29): on 360 real tool outputs Headroom kept more facts in view than distil 1.58.0, and still wins on prose. The identifier-line keep moved distil's held-out visible recall from 86.1% to 98.4% (Headroom default 92.4%). 1.59.0 then stopped digesting output under 2,000 tokens: re-run on fresh samples, distil's default removes 2.3% of tokens at 99.6% visible recall against Headroom coding's 5.5% at 94.7%, with a modelled session bill of −5.7% against −4.3% (not significantly different). Tokens and fact recall only; expand rate and task success are unmeasured. Both sides →

Offline token savings, not a cost or task-success result: on the same corpus, re-run 2026-09-04 with Headroom's model preloaded: distil 52.9% tokens / 58.7% $ / 100% decision-equivalent / PASS vs Headroom 1.7% / 2.0% / 81% / FAIL. On a read→edit→re-read coding workload Headroom reaches 35.6% tokens where distil's digest is 0.0% by design — that is the exact-quote guarantee being paid for, and both numbers are on one page with the raw output committed.


🚀 Use it now

Four commands. distil --help shows only these; distil --help-all shows the rest.

bash
uvx --from distil-llm distil savings   # what your agent costs you now — no install, read-only
uv tool install distil-llm
distil setup                           # detects your agent + billing, wires the status line, tells you what's next
distil wrap -- claude                  # run your agent through distil
distil savings                         # spent, saved, daily graph, what to fix next
distil doctor                          # if anything looks wrong

distil setup detects your environment (Claude Code · Codex · Gemini CLI; metered vs subscription). Or wrap your agent directly — no config, no code change:

bash
# Claude Code on a metered API key — saves real $$:
distil wrap --expand -- claude

# Claude Code on a Pro/Max subscription — flat-rate, ToS-safe (trims context, not $):
distil wrap --lossless-only -- claude

# Codex, Gemini CLI, aider — same pattern; env var auto-selected per agent:
distil wrap --expand -- codex     # → session-only -c model_provider override, HTTP forced (API-key login only)
distil wrap --expand -- gemini    # → GOOGLE_GEMINI_BASE_URL
distil wrap --expand -- aider     # → OPENAI_API_BASE
distil wrap --list                # every target, its mechanism, and the agents it can't reach

# Headless too — print mode, CI, and Agent SDK scripts route the same way:
distil wrap -- claude -p "summarise this diff"
distil wrap -- python my_agent_sdk_script.py

Using Cursor, the Cline editor extension, Windsurf, Zed, Warp or Amp? (The Cline CLI is different — distil wrap -- cline reaches it.) None of them publishes a base-URL contract distil wrap can set — some have no such knob at all, some have one that structurally cannot point at localhost (Warp runs the agent on its own servers and rejects private addresses). Run a proxy and point the tool's own setting at it: docs/IDE-AGENTS.md, where every one of them is listed with the page and date the claim was checked against. The VS Code Copilot extension is not redirectable at all and that page says so rather than wasting your afternoon — the GitHub Copilot CLI is a different tool and wrap does reach it.

Each recognized agent auto-selects the right env var and upstream — no --env-var or --upstream flag needed. 13 route through an environment variable (aider / claude / gemini / copilot / goose / grok / kilo / kimi / vibe / openclaude / opencode / openhands / qwen); 6 have no env-var contract at all and route through a config file wrap manages for the session and restores on exit (cline / codex / cn / crush / droid / omp). Prints preset: <agent> detected → <VAR> on start. Explicit flags always win.

Make it the default — never type distil wrap again

Tired of typing distil wrap every time? Make it the default — once:

bash
distil default            # adds a managed shell alias so `claude` always routes through distil
distil default --undo     # remove it anytime (backed up before any change)

It detects your shell (zsh / bash / fish / PowerShell) and billing mode, writes the right line to the rc file your shell actually reads, and tells you what it detected. Want every SDK covered (not just the agent you type)? distil default --always-on runs a persistent proxy service — powerful, but it pins ANTHROPIC_BASE_URL, so every client on the machine goes through one local process.

That pin used to be a single point of failure: a proxy that was down for one second meant sessions failing with ConnectionRefused, an error that names the provider rather than distil. It no longer is. The service supervisor (launchd/systemd) owns the listening socket, so a crash or a restart leaves connections queued in the kernel backlog instead of refused — the client waits about a second rather than dying. distil default --always-on also verifies the service is genuinely registered and serving before it wires anything, and refuses to wire at all if it isn't.

If you ever need out and distil is already uninstalled, sh ~/.distil/uninstall.sh removes the pin, the service, and the shell block using nothing but sh.

Then watch genuine savings from your traffic — measured, not estimated:

bash
distil savings              # billed spend vs saved, daily graph, top fixes (--since 7d / --all / --json)
distil leaderboard          # cumulative tokens + $ saved, from the local ledger
distil dashboard            # live terminal TUI — token-trim + decision-equiv bars, Ctrl-C to exit
distil dissect             # per-session deep-dive: savings, digest inventory, anomalies (--html/--serve)

Validate it on your traffic. --shadow runs a fraction of requests twice (compressed and full) and compares the agent's chosen next action:

bash
distil wrap --shadow 0.1 -- claude   # wrap + shadow 10% of requests
distil shadow-stats                  # live decision-equivalence rate

Honest scope: that's next-action equivalence — a proxy, not task success (E7 shows it doesn't fully transfer under aggressive lossy compression). Distil fails safe to full context.

Will it save money? On metered billing (API key) — fewer tokens: about 9% of the bill on the maintainer's traffic. On short SWE-bench tasks the net cost effect measured cost-neutral; the long-session pilot (7 tasks) is inconclusive, and whether lossy compression pays depends on whether the agent takes extra steps, which the next live A/B measures. On a flat-rate subscription there is no per-token bill, so the saving is rate-limit headroom: fewer tokens per turn means more turns before you hit the window (distil quota shows it live).


💡 Why Distil is different

You don't need byte-equivalence — you need decision-equivalence: your agent taking the same actions with compressed context. That's measurable and certifiable.

  • Gated, not assumed — a lossy mode is served only while its per-request decision-change check is inside budget; can't show that → full context. Task-level non-inferiority is not shown yet (SWE-bench Lite: −1.7 pts, 95% CI −5.1..+1.7).
  • An estimator that can report harm — the live check is a paired statistic, 1{A=B} − 1{A=A'}, with a bootstrap 95% CI and no clamp at zero. The old ratio estimator printed exactly 100% whenever chance favoured it and could not express harm at all. One reporting floor now gates the status line, the proof ledger, shadow-stats, the census feed and the public dashboard alike — and prints below reporting floor rather than a flattering number.
  • Byte-exact quotes survive, so Edit still applies — an Edit(old_string=…) is a literal match against bytes the agent read earlier; digest that read and the edit silently does nothing while the agent reports success. Provenance is read from the shell command (cat, head, sed -n), not just the tool name — that is 33.6% of tool-result mass the name rule never covered. It costs savings, and the changelog prices it instead of hiding it.
  • Adversarially gated, and honest about the two hits — distil validate --adversarial runs seven COMA-class cases through the same public path the proxy uses. Trusted/untrusted budget isolation is structural: there is no keep budget shared between blocks anywhere, asserted as an equality in CI. Two results we publish rather than smooth over: dedup-baiting does fold the genuine error line (reversibility is what saves it), and decoy-verdict flooding is a real, unmitigated denial of savings — 0.0% on that block.
  • The whole dial is measured, not just the default — distil bench --curve reports savings, fact recall, visible recall, facts lost and reversibility at every rung, offline and free.
  • A task-level bound you can run — distil certify-trajectories bounds how many solvable tasks compression can cost on your matched eval outcomes. On our own SWE-bench runs that bound does not yet clear the 5-point margin.
  • Reversible, not lossy — digests behind a handle, keeps the original, hands the agent a distil_expand tool. Compress fearlessly.
  • Keeps the answer, folds the noise — a per-content-type keep policy pins each kind's load-bearing lines (a log's pass/fail verdict, a traceback's frames, a diff's hunk headers); repeated near-identical error spam is deduped, and on a green run dedup tightens further since that noise didn't fail anything.
  • Query-aware — keeps the line you're actually asking about — distil is a proxy, so it sees the agent's intent (its tool_use args + latest ask) in the same request as the output. The line matching what you searched for (a grep hit, a config value, a SHA) is pinned even in arbitrary output — additively, so reversibility and the certificate are untouched. No post-hoc compressor has that query/output pairing. It also goes semantic, and always-on: a zero-dependency bridge — morphology, a curated technical synonym map, and char-trigram fuzz — pins lines that answer the query without sharing a word with it. Ask "the retry limit?" and it keeps max_attempts = 5; ask "the connection timeout?" and it keeps deadline_ms. Two more layers grow from your own traffic, never from a shipped blob: associations distil learns from its content-free expand flywheel (hashed pairs, --expand sessions), and a learned relevance model that is promoted only after its held-out recall beats the lexical baseline on your labels — until promotion, the lexical + bridge layers are exactly what runs. An optional distributional-vector table can be supplied too (pure-Python cosine; none ships). Every layer is additive — it can only widen keeps, so reversibility and the certificate are untouched — and it needs no embeddings or model to work.
  • Lossless even on a flat-rate plan — subscription/lossless mode isn't just verbatim: it minifies JSON, collapses duplicate runs, and folds tabular tool output into a compact self-describing table (ToS-safe, no lossy digest). Recent tool outputs stay byte-exact. Be clear about the size of it: lossless savings are shape-dependent, and on distil's own eval corpus — no JSON, no repeated lines — it saves 0.00% (E15b).
  • See exactly what happened — distil dissect turns a wrap session into a report: savings by model/mechanism, the digest inventory, billed-usage calibration, latency by path, and a worth-your-attention anomaly list that catches silent failures automatically.
  • Compounds on outcomes — expansions and matched failures teach the policy what to protect (signatures only, never content) — always more conservative.
  • Re-reads cost what changed, not what it re-read — a coding agent re-reads the same file constantly (51.4% of reads on 2,489 measured sessions) and almost never at the same offset, so block-level dedup misses it. Distil matches on lines: the run a new read shares with an earlier one still in context becomes a reversible reference, everything else stays byte-exact, and the freshest read is never touched. It runs inside the exact-quote guarantee — the only transform that recovers savings on content distil has promised to keep verbatim — and stays safe because an Edit's old_string only has to exist byte-exact somewhere in the forwarded payload. → ADR 0010
  • Streams like it isn't there — SSE relays chunk-by-chunk; TTFT preserved — including recoverable digest, which speculatively streams and only intercepts an actual distil_expand call mid-stream, splicing the recovery in without buffering the turn (no TTFT tax on the reversible tier).

Fidelity tiers: lossless (--verbatim) · reversible (byte-recoverable on demand — default) · lossy (every other tool). Distil's reversible tier is gated by its per-request decision-change check, and its recovery is agent-facing — the model expands mid-task (Headroom ships a retrieve with no such gate). Neither is shown to save money on task outcomes.


⚡ Prove the numbers yourself — no API key

Don't take the table above on faith. distil bench re-certifies savings and decision-equivalence on a bundled 8-domain corpus, offline, in seconds — the same gate that runs in CI. How we evaluate — and why a compression ratio without a task-success delta is meaningless — is written up in docs/EVALUATION.md, including our own negative result:

bash
uvx --from distil-llm distil bench      # certify savings + quality across 9 domains, in seconds
distil verify                           # byte-fidelity: every compression is exactly reversible
distil validate                         # adversarial real-path gate: invariants on hostile inputs
distil retention                        # fact recall: what stays visible vs expand-recoverable
distil retention --dataset hotpotqa     # graded against a PUBLIC benchmark's ground truth
distil fidelity                         # state probes: artifact state, overclaim, continuation

Five gates, all in CI: bench (non-inferiority on the corpus), verify (byte-fidelity), retention (fact-level recall), fidelity (state probes, below), and validate — which drives the compressor against adversarial inputs (huge/unicode/nested/malformed/marker-injection/secret-looking) and asserts reversibility, reject-if-bigger, recency-exactness, fail-open, and content-free telemetry hold on every one. That last gate exists because a green unit suite kept coexisting with real-traffic bugs; validate is the adversarial layer that catches them.

Recall is not enough, and here's the case that proves it. A trajectory creates net/scratch_bench.py at turn 2 and deletes it at turn 4. Compress away turn 4 and every path token is still present — string recall reads 100% — while the agent now believes a file exists that doesn't, and will plan around it. distil fidelity folds tool calls into a file-state ledger and grades the final state, separating lost (path gone — the agent can see the gap) from stale (path present, state wrong — the agent acts confidently on a falsehood). On that case: string recall 100%, state fidelity 0%.

It reports three more things recall can't see: overclaim ("approximately 4200 ms" → "4200 ms" — the value survives, its uncertainty doesn't), continuation (does the agent still know what's left to do?), and error propagation (does a loss at turn k show up as a behaviour change at turn k+n?). The gate is on silent failures only — CI runs --max-silent 15 — because loud loss is already retention --max-lost's job, and gating one regression twice hides which property broke. The bound is the measured one, not zero: Tier-1 digests hedged spans behind restore handles and drops the qualifier on 9 of 171 claims, so gating at zero would assert a property the compressor does not have. On top of that, distil suite grades twelve public benchmarks whose answer keys were written by someone else — including BFCL, which compresses the tool schema and checks that every name the gold call needs — the function and each argument — survives. At 91.4% savings distil keeps every name the gold calls need (raw) — though none of them visibly: the schema sits behind a restore handle, one distil_expand away. The suite prints that gap (visible → true support: bfcl 0%→100%) rather than the flattering number alone, because a reader who assumes the model can see a schema it must actually expand first has been misled by figures that are individually correct. Names are matched as identifiers — a quoted JSON token, escaping tolerated — not as prose: the generic matcher was crediting 11 of 85 golds by accident ('a' matching inside "tool-schemas"). Fifteen golds BFCL genuinely names a, b, c are excluded and counted, since a one-letter token can be neither credited nor failed honestly. Every row is labelled rich or thin payload, because a benchmark with nothing to compress is a control, not evidence — and a run that grades only controls exits 1. It needs no API key and no spend, so it is wired into make gate and the CI gate job rather than run before a launch. Full methodology, including what these probes found wrong with our own corpus, in docs/EVALUATION.md §6; how to run everything, in docs/RUNNING-EVALS.md.

Recall, and a number you can check yourself. The three gates above are graded on our corpus against our oracle — rigorous, but not checkable by you. distil retention --dataset hotpotqa grades against ground truth written by someone else (HotpotQA's gold supporting sentences, amid 8 distractor paragraphs), next to a truncation baseline tuned to distil's own savings on the same case:

HotpotQA, n=100 (raw)savingsanswer recallgold-sentence recall
distil (reversible)14.3%100.0%100.0%
truncation @ matched savings14.1%91.6%82.7%

distil retention also splits recall into visible (in front of the model) and recoverable (one distil_expand away, verified against the handle's restore bytes). On the corpus that's 100% true recall with 0 lost, and being reversible instead of lossy is worth 17.5% recall — the mean across all 9 domains, each counted once (raw). That's deliberately the macro average: the fact-weighted one reads 60.2%, but it's set by whichever domain carries the most probes, and one HTML fixture once moved it by more than fifty points without the compressor changing at all — the moat, as a measurement rather than an argument. (It was 23.1% before the digest started keeping identifier lines in view: more of the corpus is now visible, so less of it needs the expand.) distil retention --live reports the same on your own traffic; the meter stores counts only, never content.

And it found a real hole. The first thing the recall harness caught was not a regression but a missing capability: distil was compressing 0.0% of HTML tool results — minified markup is one long line, so line-folding had nothing to fold. Agents with a fetch or browser tool were paying full price for <script>, <style>, and nav chrome. Now a Wikipedia article and a Python docs page now lose most of their size with 0 facts lost. (Measured on two pages; that run's output was not committed, so no percentage is quoted here.)

Reversible, which is the part a lossy extractor can't offer: the exact original stays behind the handle, so a bad heuristic call costs one distil_expand instead of the content.

To be precise about what each layer proves: the per-commit gates grade decision-equivalence with an offline deterministic oracle over the committed corpus (fast, free, runs on every push — but synthetic). A nightly live-cert job re-certifies the same trajectories against a real model (distil certify --runner anthropic), budget-capped with a hard --max-live-calls ceiling so an unattended run can never spend silently. The empirical results above (SWE-bench n=500, live head-to-head n=200) were graded by real models; the per-commit badge alone doesn't claim that.

Who grades the live runs. Since 1.56.0 the default live certifier is claude-sonnet-5-5 at effort=low (--effort is a flag on certify, eval, benchmark, frontier and conformal). It was chosen by a pre-registered, paired model-migration eval on real τ-bench traffic: it cleared every gate, including a quality lower bound of at least −5 points against claude-opus-4-8, at 57.5% lower cost per case. The earlier live results above were graded by claude-opus-4-8 and are still labelled so.

Choosing or migrating the live certifier. The grader is itself a variable, so changing it is a measured decision, not a flag flip. Pick it per run with --model (on certify, overrides the trajectory's model for --runner anthropic) and --effort low|medium|high|xhigh|max; the default is claude-sonnet-5-5 at low. To qualify a new model against the incumbent, run the same cases and compare paired on held-out turns:

bash
python benchmarks/model_migration_eval.py --fetch-tau-bench      # pinned, sha256-verified real traces
python benchmarks/model_migration_eval.py --cases real --flow .claude/hillclimb/decision-equivalence-real \
    --variant baseline --model claude-opus-4-8 --reps 4          # incumbent
python benchmarks/model_migration_eval.py --cases real --flow .claude/hillclimb/decision-equivalence-real \
    --variant v5 --model <new-model> --effort low --reps 4       # candidate
python benchmarks/model_migration_eval.py --status               # cross-variant table
python benchmarks/model_migration_summary.py                     # paired CIs -> benchmarks/results/model-migration/summary.json

Live runs spend money; add --fake oracle to check the wiring offline first. Gates, tables and the rest of the commands: Model Migration (docs/ab.html#model-migration). Decision records: ADR 0020 (default certifier) and ADR 0021 (served-path certification).

An open risk on coding traffic. The certified distil strategy digests only the latest tool output and saves 2.6% of tokens on real SWE-agent trajectories; the serving adapter digests every earlier tool output and saves 52.6%, so most served bytes were never certified. distil certify --strategy served now grades the real adapter, and its first result is not a pass: with recovery it keeps the next action in 78.0% of held-out coding decisions, against 94.1% for two identical uncompressed calls. Whether that costs solved tasks is what the SWE-bench outcome eval (spec, benchmarks/swebench_outcome/) is for; on all 300 SWE-bench Lite tasks (report), with both agents using prompt caching, the distil-served agent resolved 201 of 299 paired tasks against 210 for the plain agent: −3.0 pts (95% CI −6.4 to +0.4, McNemar p = 0.12). That does not show non-inferiority at the pre-registered 5-point margin, and it supersedes an earlier 100-task run that had passed narrowly. Serving also cost 12.4% more and took 29.9% more steps. Replaying the compression offline shows why: distil digested most of the agent's shell grep output, its map of where things are, and the agent searched and re-read again instead of calling distil_expand. distil already kept a Grep tool's output verbatim, but not the same search run through bash; it now keeps both. Re-running the distil arm with that fix (report) removes the penalty: steps over plain fall from +29.9% to +3.1% and cost from +12.4% to parity. Task success is still not shown: 204 of 299 against 210 (−2.0 pts, 95% CI −5.5 to +1.5), just outside the margin. A second run at higher effort (report) points the same way. Treat the served path on coding agents as cost-neutral and not yet proven for task success; on long sessions a 7-task pilot is inconclusive (run). Method, tables and rerun commands: Model Migration; every dataset used, with sources and pins: EVALUATION.md §6.9.

domain            trajectory                $ saved   distil   aggr  pruned
---------------------------------------------------------------------------
ops/sre           sre-disk-incident           32.8%     PASS   FAIL     615
coding            coding-bugfix               25.5%     PASS   FAIL     736
support           support-refund              32.6%     PASS   FAIL     765
research          research-synthesis          25.7%     PASS   FAIL     809
data-analysis     data-analysis-sql           18.1%     PASS   FAIL     965
devops            devops-rollback             22.8%     PASS   FAIL     857
finance           finance-reconcile           24.9%     PASS   FAIL    1014
web-research      web-research                89.8%     PASS   FAIL     428
agent-worklog     agent-worklog               35.3%     PASS   FAIL     891
---------------------------------------------------------------------------
aggregate: distil cuts $0.24052 -> $0.12400 (48.4% cheaper) reversibly; 7080 tokens causally prunable.
GATE: PASS — every trajectory certified non-inferior; aggressive rejected on all.

measured across 9 domains

Why trust the number? Token-savings numbers are easy to fake — measure quality at low compression, advertise savings at high compression. Distil refuses that: accuracy and compression are measured on the same trajectories, and a strategy that can't pass non-inferiority doesn't ship.

distil certify --strategy distil       # VERDICT: PASS  (100% decision-equivalence)
distil certify --strategy aggressive   # VERDICT: FAIL  (mean diff −1.0, blocked)

distil eval plots the certified compression frontier — a savings-vs-quality curve where every point carries its certification verdict, locating the cliff past which lossy compression drops decisions. The artifact no competitor publishes: benchmark.html.


📊 The proof

Three results, all reproducible, all published with caveats:

  • Head-to-head on a synthetic corpus vs real llmlingua / headroom-ai (a seeded 120-turn corpus from benchmarks/gen_realworld.py, graded by claude-opus-4-8; 2026-07-05, distil 1.10.1 vs llmlingua 0.2.2 and headroom-ai 0.27.0): 83.2% savings at 0% decision-change, ~1,000× faster (no ML model loaded vs. competitors' local transformer inference). The live proxy behavior is pinned to the certified strategy by tests/test_live_certified_equivalence.py; the one reviewed delta is a recency carve-out that keeps the freshest tool-result turns verbatim (an agent needs its freshest output byte-exact). Since 1.45 that carve-out applies only to content the provider has not cached — anchored to the client's cache_control breakpoint, and dropped entirely for providers that cache implicitly. A carve-out counted back from the end of the conversation slid forward as it grew, rewriting already-cached content one turn later and costing more in re-billed prefix than the digest saved. → benchmark

  • E7 (SWE-bench Verified): aggressive lossy compression craters task success (52% → 16%) — a per-step certificate doesn't transfer to multi-turn. The reversible tier survives (56% vs 52%). We publish it because it's true. → E7

  • SWE-bench Lite, the shipped path (n=300, twice): cost-neutral and within about 2 points on task success (−2.0 pts, 95% CI −5.5..+1.5; −1.7 pts, 95% CI −5.1..+1.7) — not statistically distinguishable, and non-inferiority at the 5-point margin not shown. → reports. Research configurations (E8–E14, SWE-bench Verified) are on the research page and are not the shipped path.

  • Head-to-head against other compressors (SWE-bench Lite, 298 tasks; long-horizon pilot, 7 tasks): success rates on the scoreboard; RTK is the only arm shown non-inferior on success, and no arm is shown cheaper once a shared-prompt-cache confound in that run is removed (RTK −6.5% per task [−13.1%, +0.1%], not significant). The long-horizon pilot shows no cost difference. → cost confound · why

Full methodology, McNemar tests, per-instance data: docs/PAPER.md · PDF.


📡 See it working

Measured on your traffic, never estimated, nothing leaves your machine:

  • Per request: x-distil-* response headers (tokens-saved, mode, compressible-tokens, expanded).
  • Per machine: distil leaderboard (--html for a page).
  • Shadow mode: distil proxy --shadow 0.05 reports the live decision-change rate — streaming-aware.
  • What you're still leaving behind: distil discover aggregates your recent sessions and ranks what is still costing you — tool/MCP definitions resent on every request, MCP servers whose definitions rode along on every turn and were never called, sessions that never reached the digest tier, a cache prefix that drifts and re-bills itself, re-fold churn the provider is not already discounting, a system prompt that grew. Each action carries the tokens and dollars per week it would recover, how that number was derived, and the one command or setting to act on it. It prints the median and the p10/p90 of your per-session savings beside the best session, so a best case is never read as a typical one, and it uses the rate your own ledger measured — falling back to a published benchmark ratio only when this machine has never run that mode, and saying so on the line. A detector that cannot measure stays silent, so "nothing to recommend" is a result rather than a failure to look.
  • Org-wide: distil proxy sidecar + set ANTHROPIC_BASE_URL once; every client routes through it.
  • Community: an opt-in census (distil census on) shares your numbers-only totals — preview the exact payload with distil census show before consenting; TELEMETRY.md has the frozen schema. Default remains: nothing is sent.

Dashboard, status-line plugin, federated leaderboard: Deploy & observability.

🔌 Works with every SDK

One proxy. Point any base_url-honoring client at it — Python, TypeScript, any language — and get cache-aware reversible compression with no code change.

one proxy, every SDK

bash
distil proxy --upstream https://api.anthropic.com   # localhost:8788
ts
// JS/TS: npm i distil-llm  → helper so you don't hardcode the URL
import Anthropic from "@anthropic-ai/sdk";
import { distilBaseURL } from "distil-llm";
const client = new Anthropic({ baseURL: distilBaseURL() });
SDK / frameworkChangeExample
Anthropic SDK (Py/TS)base_url="http://127.0.0.1:8788"examples/python_anthropic.py · examples/js_anthropic.ts
Claude Agent SDK / claude -p (headless)distil wrap -- <cmd> or ANTHROPIC_BASE_URLexamples/python_claude_agent_sdk.py
OpenAI SDK (Chat + Responses)base_url="http://127.0.0.1:8788/v1"examples/python_openai.py
Vercel AI SDKcreateAnthropic({ baseURL: '…:8788' }) — or in-process: wrapLanguageModel({ model, middleware: distilMiddleware() })examples/js_vercel_ai_sdk.ts
LangChain (py/js) · LangGraphanthropicApiUrl / base URL · pre_model_hookexamples/js_langchain.ts
LiteLLMapi_base="http://127.0.0.1:8788"examples/python_litellm.py
Google Gemini--upstream https://generativelanguage.googleapis.comexamples/python_gemini.py
AWS Bedrock (InvokeModel)--upstream https://bedrock-runtime.<region>.amazonaws.com with a Bedrock API key (AWS_BEARER_TOKEN_BEDROCK); SigV4-signed requests are refused, Converse passes through untouched—
Google Vertex AI (Anthropic rawPredict, Gemini generateContent)--upstream https://<region>-aiplatform.googleapis.com—
Codex · aider · OpenCode · Qwen Code · any base_url clientdistil wrap -- <agent> (picks the right var per agent) or OPENAI_BASE_URL—

Anything that speaks the Anthropic / OpenAI / Gemini wire format works — the proxy is framework-agnostic, so CrewAI, AutoGen, LlamaIndex, Agno, Strands, etc. route through it by pointing their client's base URL at distil. Bedrock streams (binary eventstream) get the lossless tier only; Bedrock Converse is forwarded untouched. Codex over a ChatGPT login (chatgpt.com/backend-api/codex) cannot be routed at all.

Prefer in-process? Wrap the client directly — still no call-site change:

python
from distil.adapters.anthropic import wrap
client = wrap(anthropic.Anthropic())   # compresses the request, keeps the cache warm

(OpenAI — Chat Completions and Responses API — and Gemini route through the proxy: distil wrap -- codex, or point OPENAI_BASE_URL at it; the proxy answers a WebSocket upgrade with 426, so a client has to speak HTTP. An in-process client wrap exists for the Anthropic SDK only.)

Framework hooks (no proxy, no network hop) — for agent frameworks that own the message list, compress it where it lives:

FrameworkHookExample
LiteLLMdistil.integrations.litellm.compress(kwargs)examples/python_litellm.py
LangChaindistil.integrations.langchain.compress_messages(msgs)—
LangGraphpre_model_hook=pre_model_hook() (compresses graph state before the model node)examples/python_langgraph.py
Agnodistil.integrations.agno.compressed_model(model)—
Strandsdistil.integrations.strands.compressing_hook()—
LlamaIndexDistilNodePostprocessor() (node postprocessor) · DistilLLM(llm) · compressing_tool(fn)integrations.html#llamaindex-page

LangChain / LangGraph — langchain-distil

Listed in LangChain's own community middleware integrations. If you came from there, this is the package:

bash
pip install langchain-distil
python
from langchain_distil import compress_messages, pre_model_hook, as_runnable

msgs = compress_messages(msgs)                 # compress a message list in place of the call
graph = create_react_agent(..., pre_model_hook=pre_model_hook())   # LangGraph: before the model node
chain = as_runnable() | llm                    # or drop it into a chain (lazy langchain-core import)

Tool and function messages get the reversible Tier-1 digest, human and system messages are Tier-0 lossless, and assistant messages are never rewritten — a model's own words are not distil's to edit. Every digest is byte-exact recoverable. Pass verbatim=True for Tier-0-only when no recovery tool is available.

It is a thin wrapper over the hooks in the table above, so it inherits the same certified compression path — nothing is re-implemented. distil-llm is a dependency; you do not install both by hand.


🎟️ Subscription — save the window, not the bill

On a flat-rate Pro/Max plan there is no per-token bill to cut, so distil's dollar figures are notional. The rate-limit window is not notional: tokens spent on a 40 KB test log are quota unavailable for the next task.

The proxy can't help much here. Anthropic's consumer terms (§3, item 7) restrict automated access on subscription credentials, so distil deliberately runs --lossless-only there, which on most traffic saves close to nothing (0.00% on distil's own corpus, E15b). Your account isn't worth a few percent.

A PostToolUse hook is a different mechanism — a documented, first-party extension point. Claude Code compresses its own tool output, in its own process, before the model reads it:

bash
distil hook --install     # writes ~/.claude/settings.json (idempotent, preserves your other hooks)
distil hook --selftest    # verify the schema adapters — a live mismatch is SILENT
distil quota              # the window it buys back
$ distil quota
Subscription quota (the currency a flat-rate plan actually spends):
  five_hour          [########............]  43.0% used  resets 2026-08-16 15:49Z
  seven_day          [....................]   4.0% used  resets 2026-08-23 07:59Z

A single-session observation, not a benchmark: one paired live A/B on one task, both arms answering correctly, read tool_result −38.6%, cache_creation −67.4%, cost-weighted −68.3% (raw); five more verifiable tasks agreed 5/5 (raw) — enough to catch a gross regression, not to certify a rate. Critically cache_read did not collapse — a hook sees each result once and cannot rewrite history, so compression is append-only by construction and the prompt cache survives.

Where it saves nothing. Tier-0 is JSON minification plus consecutive-run collapse, so savings are shape-dependent: verbose JSON (npm/pip/kubectl/terraform) 28–33%, duplicated log runs up to 99%, and unique-line logs, prose, git log and git diff 0%. On distil's own eval corpus it saves 0.00% — that corpus has no JSON and no consecutive duplicates. Published because quoting only the favourable fixtures would be the overclaim we criticise in others.

Other agents: Gemini CLI's AfterTool can influence output indirectly (under evaluation); Codex CLI hooks are observe-only and reject output rewriting, so it's blocked upstream there.

Full page, with the method and the caveats →


🧠 MCP server — give your agent a recall tool

Distil ships a Model Context Protocol server so

Similar modules

Browse LLM access & routing