token-defrag
Health Warn
- License — License: MIT
- Description — Repository has a description
- Active repo — Last push 0 days ago
- Low visibility — Only 6 GitHub stars
Code Warn
- process.env — Environment variable access in plugins/opencode/plugin.test.ts
Permissions Pass
- Permissions — No dangerous permissions requested
No AI report is available for this listing yet.
See and cut what Claude Code and OpenCode spend re-reading their own context. Offline estimate + shadow mode, one static Go binary, no telemetry.

Most of what a long coding-agent session costs goes to re-reading itself.
TokenDefrag shows how much of that you could cut, and measures it live without changing a thing.
Works with Claude Code and OpenCode (any provider, Bedrock included) · one static Go binary · no account · no telemetry
Quick start · Benchmarks · How it works · Why trust the number · Compared · Roadmap
Real CLI output on the synthetic benchmark corpus, not on private sessions.
[!IMPORTANT]
TokenDefrag measures; it does not rewrite yet.estimatereplays your past sessions offline,
and shadow mode (tokendefrag claude, the OpenCode plugin) measures real requests while forwarding
them unchanged. Live rewriting comes after shadow numbers and a paired eval back it up, so every
saving below is an estimate or a would-be measurement, not a reduced bill.
The problem
Every turn of an agent session sends the whole conversation again. With prompt caching that
re-read is cheaper per token, but it happens on every call, and the conversation only grows.

On the reproducible benchmark corpus (synthetic Claude Code sessions, no
real prompts or code):
| Sessions, API calls | 20 sessions, 1,392 calls |
| API-equivalent cost | $118.57 |
| Spent re-reading and re-writing the context cache | $108.73 (91.7%) |
| Spent on the model's actual output | $9.82 (8.3%) |
| Estimated saving with TokenDefrag | $52.67 (44.4%), 51.2% on sessions of 200+ calls |
Your own numbers will differ; tokendefrag estimate shows them in a few seconds, offline.
Short sessions barely change. The money is in the long ones, and that is where TokenDefrag works.
Quick start
brew install --cask yuseferi/tap/tokendefrag # macOS, Homebrew
# or: curl -fsSL https://raw.githubusercontent.com/yuseferi/token-defrag/main/scripts/install.sh | sh
# or: go install github.com/yuseferi/token-defrag/cmd/tokendefrag@latest
tokendefrag estimate # what it would have saved on your past sessions (offline)
tokendefrag claude # run Claude Code in shadow mode; every argument passes through
tokendefrag opencode install # add the shadow plugin to OpenCode
tokendefrag stats # what shadow mode measured
estimate reads the last 30 days of Claude Code transcripts (~/.claude/projects) and OpenCode's
local database (~/.local/share/opencode/opencode.db), read-only, and prints counts and costs
only. A month of history takes a few seconds.
tokendefrag estimate --agent opencode # one agent
tokendefrag estimate --since 7d --top 20 # a shorter window, more sessions listed
tokendefrag estimate --verbose # safety counters, inferred prices, every assumption
tokendefrag estimate --json > estimate.json # the full machine-readable report
tokendefrag off # bypass TokenDefrag at once (tokendefrag on resumes)
Releases are static binaries for macOS and Linux (arm64 and amd64) with a SHA256SUMS file;
the install script verifies the checksum and installs into ~/.local/bin (with a short tdf
alias). From source: git clone https://github.com/yuseferi/token-defrag && cd token-defrag && make build.
Benchmarks

The benchmark is a reproducible synthetic corpus: 20 Claude Code-style sessions, 1,392 API
calls, generated from a fixed seed with no real prompts or code. Anyone can regenerate it and get
the same numbers with make bench.
| Workload | What it simulates | Saving |
|---|---|---|
quick-fix |
A few reads, one edit, one test run | 1.0% |
feature |
Read, edit, re-read, test, repeat | 2.7% |
debugging |
Long, noisy build and test logs | 31.2% |
api-research |
MCP and API tools returning pretty-printed JSON | 62.3% |
marathon |
An all-day refactor far past 200k tokens | 51.2% |
| All | 44.4% |
The synthetic corpus is deliberately rich in long sessions and noisy output, so it likely saves
more than a typical month of real work; it exists to catch regressions and compare designs. Your own history is the test
that matters.
Speed. On the synthetic corpus the estimator runs about 9x faster than Lightfoot's Python
estimator (1.0 s against 9.1 s) for nearly the same saving (44.4% against 47.3%; the gap is
explained in docs/benchmarks.md). Shadow planning
takes about a millisecond per request and runs off the request path.
Full tables, per-rule breakdowns, and reproduction steps: docs/benchmarks.md.
How it works
TokenDefrag "defragments" the conversation: old turns collapse into one summary, bulky output
shrinks, and your recent work stays exactly as it was.

The catch is the prompt cache: it only hits on an identical prefix. Condensing differently on every
call would throw the cache away and cost more than it saves. TokenDefrag stores each rewrite and
replays it byte for byte, so the cache is rebuilt once and then stays warm on a shorter prefix.

One Go engine holds the rules, the frozen rewrites, and the cache accounting. Each agent gets a
thin adapter:

| Claude Code | OpenCode | |
|---|---|---|
| How TokenDefrag sees requests | A loopback proxy via ANTHROPIC_BASE_URL, started by tokendefrag claude |
A plugin on OpenCode's context hook |
| Providers | Anthropic API, Pro/Max logins, an existing gateway | Every OpenCode provider, including Bedrock, which a proxy cannot rewrite |
| Shadow mode | Byte-for-byte forwarding; usage read from the response | The plugin hands a copy to the engine and never waits |
| Offline estimate | ~/.claude/projects transcripts |
OpenCode's local database |
The rules:
| Rule | What it does | When |
|---|---|---|
| Old-turn summary | Replaces older turns with a bounded extractive summary. Your first request and your last 3 prompts with their work stay verbatim. | At your next prompt, past 200k tokens, only if it pays for its cache rebuild |
| Large-output trim | Keeps the head, the tail, and every error line of output over ~4k tokens. | Fresh output, before the model reads it |
| JSON minify | Removes whitespace from pretty-printed JSON. Key order, escapes, and numbers stay byte for byte. | Fresh output |
| Terminal noise | Strips ANSI codes, keeps the final frame of progress bars, collapses repeated lines with a count. | Fresh output |
| Stale reads, repeated searches | Superseded file reads and identical searches become one-line pointers to the newer result. | At a prompt, only if the history edit pays for itself |
Three ideas make it safe and cheap:
- Rewrite once, replay forever. Every rewrite is stored and replayed byte for byte on later
calls, so the prompt cache stays warm. - Lossless first. JSON minification and noise stripping run before trimming, so more output
reaches the model complete. Fresh output is rewritten before the model has seen it, which costs
nothing in cache terms. - History edits must pay for themselves. Editing anything the model has already seen rebuilds
the cache. Every such edit is checked against its break-even point first.
Why trust the number
The independent JetBrains study of RTK
found that a tool's self-reported savings are a claim about its counterfactual, not your bill: a
shell-output compressor reported large savings and measured none. TokenDefrag is built around that
lesson.
- The baseline is your actual bill. Each call is priced from its recorded input, output, cache
reads, and cache writes. Raw tool output is never substituted for what the agent really sent. - Cache rebuilds are charged. Every history edit pays to rewrite the cached conversation, and
that cost is in the total. The estimator does report sessions that would get more expensive. - The rule rows add up. Each call's net effect is split between the rules that shaped it, so
"where the saving comes from" sums exactly to the total. - Summary recall is measured. Every later reference to something a summary dropped counts as a
hit (still in context) or a miss, so "without making it worse" is a number, not a promise. - Prices come from evidence. Anthropic models use a pinned table. Other OpenCode models (GLM,
Kimi, GPT, DeepSeek) are priced by fitting OpenCode's own recorded per-call costs, accepted only
on an exact fit; anything else stays unpriced and is never treated as free. - Two account types. Results are computed for accounts that enforce the thinking-prefix check
and for accounts that allow history edits.
What an offline estimate cannot know: whether the agent does the same work as well with a
condensed context. Only a paired evaluation on real tasks can show savings at equal quality, and
that is on the roadmap. The full method is in
docs/estimate-method.md.
How it compares
| TokenDefrag | Lightfoot | Shell-output hooks (RTK-style) | Cost viewers (ccusage, CodeBurn) | |
|---|---|---|---|---|
| Shows where your spend went | Yes | Yes | No | Yes |
| Models cache-aware savings | Yes | Yes | No | No |
| Measures live without changing requests | Yes, shadow mode | Yes, shadow mode | No | No |
| Saves on live sessions | Not yet | Yes, via a local proxy | Claims to; not measurable | No |
| OpenCode | Estimate and shadow via a native plugin, any provider | Experimental, measure only | Varies | Varies |
| Summary recall | Yes | Yes | n/a | n/a |
| Prices non-Anthropic models | From the agent's recorded costs | Fallback table | n/a | Varies |
| Install | One static binary | Python 3.11+ | Varies | Node |
| Reports show project names | No, pseudonymous IDs | Yes | n/a | Varies |
| Reproducible, free benchmark | Yes, make bench |
Bench calls live model APIs | No | n/a |
Lightfoot is the most complete project in this space and TokenDefrag's estimator is adapted from
it (see credits). If you need live savings on Claude Code today, use Lightfoot.
TokenDefrag focuses on OpenCode and Claude Code, a dependency-free binary, a stricter and faster
estimate, and an evidence-first path to live mode.
Private by design
- Nothing leaves your machine. No account, analytics, update check, or model call. The proxy
forwards the agent's own requests to the agent's own upstream, byte for byte. - No credentials touched. They pass through the proxy unchanged and are never read, stored, or
logged. OpenCode's database is read only from its session and message tables. - No content in reports or the ledger. Project names, session IDs, prompts, code, tool output,
and paths are never printed or stored. Sessions and projects get short SHA-256 pseudonyms. - Read-only. Transcripts and databases are never modified.
- Explicit cleanup.
tokendefrag purge --yesremoves~/.tokendefrag.
Details: docs/privacy.md.
Command reference
| Command | Purpose |
|---|---|
tokendefrag estimate |
Replay past sessions offline and estimate the saving |
tokendefrag claude [args...] |
Run Claude Code through the shadow proxy; the exit code passes through |
tokendefrag opencode install | uninstall |
Add or remove the OpenCode shadow plugin |
tokendefrag stats [--since 7d] [--json] |
What shadow mode measured |
tokendefrag off / on |
Bypass TokenDefrag immediately, or resume shadow mode |
tokendefrag doctor |
Check transcript and database access and the price table |
tokendefrag purge --yes |
Remove ~/.tokendefrag |
tokendefrag shadow off, eval |
Not available yet (live rewriting, paired eval) |
estimate flag |
Default | Meaning |
|---|---|---|
--agent NAME |
all |
claude, opencode, or all that exist |
--since DATE |
30d |
YYYY-MM-DD, Nd, or Nh; 0d disables the filter |
--project TEXT |
all | Project-directory substring; never printed |
--threshold N |
200000 |
Context size that triggers the old-turn summary |
--top N |
8 |
Largest sessions to list; 0 hides them |
--verbose |
off | Safety counters, inferred prices, cache-rebuild detail, assumptions |
--json |
off | Full tokendefrag.estimate.v1 report |
--root PATH |
~/.claude/projects |
Claude Code transcript file or folder |
--opencode-db PATH |
~/.local/share/opencode/opencode.db |
OpenCode database |
--no-infer-prices |
off | Leave models outside the price table unpriced |
--prices PATH |
embedded | A local YAML price table |
All amounts are API-equivalent list prices in USD, not invoices or subscription bills.
Roadmap
| Phase | Scope | Status |
|---|---|---|
| 0 | Offline estimator for Claude Code and OpenCode, rules, summary recall, inferred prices, benchmark | Done |
| 1 | Shadow mode: Claude Code proxy, OpenCode plugin, stats |
Done |
| 1b | OpenCode compaction hook: supply the extractive summary and skip the summarization model call |
Next |
| 2 | Live rewriting per rule, after review: recovery files, validation, persistent frozen state | Planned |
| 2 | eval: paired billed-cost and pass-rate runs with claude -p and opencode run |
Planned, needs approval (it spends real tokens) |
estimate and the OpenCode plugin add no network hop; tokendefrag claude adds one local hop
on 127.0.0.1. The architecture is in docs/design.md.
Credits
TokenDefrag's estimator adapts the design and parts of the code of
Lightfoot (MIT), pinned to commit0763aa5cc0fa069205406fb3fdd64f2d53e26ebf; its copyright is preserved in NOTICE.
CodeBurn informed transcript parsing and pricing.
docs/prior-art.md lists what was adopted, what changed, and why shell-only hook
mode was rejected. TokenDefrag is independent and not affiliated with or endorsed by Anthropic or
OpenCode.
Documentation
| Document | What it covers |
|---|---|
| Benchmarks | Synthetic corpus results, Lightfoot comparison, performance |
| Estimate method | Formulas, cache accounting, OpenCode input, inferred prices, recall |
| Architecture | Engine and adapters, proxy versus plugin, shadow and live pipelines |
| Privacy | What is read, what is never printed or stored |
| Prior art | Lightfoot and CodeBurn commits, adaptations, RTK lessons |
| OpenCode plugin | Install, options, how it stays out of the request path |
| Contributing | Setup, checks, benchmarks, fixtures, price updates |
| Security | Private vulnerability reporting, what counts as a security issue |
| Code of conduct | Contributor Covenant 2.1 |
| Changelog | User-visible changes |
Contributing
make check # vet, gofmt, race-enabled tests, build
make test-plugin # OpenCode plugin tests (needs bun)
make bench # regenerate docs/benchmarks.md
Synthetic fixtures, honest measurements, and new benchmark workloads are especially welcome. Never
attach private transcripts to issues. See CONTRIBUTING.md.
License
MIT © Yusef Mohamadi. See NOTICE for adapted-work credits.
If TokenDefrag shows you something surprising about your own sessions, a star helps others find it.
Reviews (0)
Sign in to leave a review.
Leave a reviewNo results found