Skip to content
Proyek

Tentang

Send less repeated context from Claude Code and OpenCode. In one hosted OpenCode test: 66.5% smaller failed log, 28.4% fewer prompt tokens. Opt-in live mode. No telemetry.

Alat pengembangan

Cara angka ini diukur

21 bintang1 Fork +12 dalam 24 jam

Pertumbuhan bintang terukur

dalam 24 jam
+12
dalam 7 hari
Mengumpulkan riwayat
dalam 15 hari
Mengumpulkan riwayat
dalam 1 bulan
Mengumpulkan riwayat

Perubahan bersih pada periode yang tumpang tindih, bukan total harian. Pengukuran yang belum tersedia dibiarkan kosong. Bintang menunjukkan perhatian, bukan kualitas.

README.md

Asli

TokenDefrag: less re-reading, more building

Send less repeated context from Claude Code and OpenCode.
TokenDefrag shortens noisy tool output, keeps diagnostics, and can summarize older turns in Claude Code.

Up to 26% estimated saving on long sessions (the author's own 30 days) · 28.4% fewer prompt tokens in a hosted OpenCode test · 42.8% on the synthetic benchmark. Results by source

CI Release License: MIT Claude Code live mode

Claude Code: summaries and tool-output rewrites · OpenCode: tool-output rewrites · opt-in live mode · no telemetry

Install · Save in Claude Code · Save in OpenCode · Benchmarks


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

Save tokens in Claude Code

Try live mode in one long debugging or refactoring session. Use v0.5.2 or later for Claude Code sessions with mid-conversation system messages:

tokendefrag claude --live         # run Claude Code with rewriting enabled for this session
tokendefrag stats --since 1d     # see how many requests were sent condensed

TokenDefrag can shrink bulky tool output before the model reads it and summarize older turns when the expected savings justify rebuilding the prompt cache. It keeps originals locally for recovery. If the API rejects a rewrite with a validation error, the proxy retries with the original request. Short sessions and requests Claude Code has already compacted may see little or no change.

In stats, Live counts requests sent condensed. For priced requests, the cost uses the provider's reported usage at list prices. The cost without TokenDefrag is estimated, so the difference is an estimate rather than a measured reduction in your bill.

Use tokendefrag live on to enable rewriting for future tokendefrag claude launches. tokendefrag live off restores the shadow default; tokendefrag off also bypasses live mode in running sessions. Claude Code running through Bedrock or Vertex bypasses the proxy.

Reduce token cost in OpenCode

Install or update the OpenCode V2 plugin to shorten large text results before the model reads them, including when you use a provider such as Bedrock.

tokendefrag opencode install
tokendefrag live on
# Use OpenCode normally after its plugin reloads.
tokendefrag stats --since 1d

Live mode shortens fresh plain-text results and failed shell logs, preserving the exit status, and replays those edits on later requests. Old-turn summaries, the larger part of the estimated saving in long sessions, are Claude Code only for now. It leaves conversation turns, reasoning, and attachments alone. stats counts applied rewrites and approximate tokens removed; the plugin does not see the provider's usage after dispatch.

Use tokendefrag estimate --agent opencode --since 7d to compare recorded input and cache costs across similar sessions. Use tokendefrag live off to restore the shadow default. If old context dominates in OpenCode, use its built-in compaction or start a new session with /new for unrelated work.

Estimate Codex CLI and Pi sessions

Codex CLI and Pi get the same offline estimate, with no setup. Use v0.8.0 or later for current OpenAI model prices:

tokendefrag doctor                                  # shows which agent histories it found
tokendefrag estimate --agent codex --since 30d      # ~/.codex (or $CODEX_HOME)
tokendefrag estimate --agent pi --since 30d         # ~/.pi/agent

Use --codex-home or --pi-dir if your sessions live elsewhere, or plain tokendefrag estimate to cover every agent it finds. The report is read-only and numeric. Models without a known price are counted as unpriced and left out of the dollar totals. Live rewriting and shadow mode are for Claude Code and OpenCode only; for Codex and Pi this is an estimate of where the spend goes.

Results

The numbers come from three different kinds of test. They answer different questions, so they are kept apart here.

Real sessions: one developer, 30 days

tokendefrag estimate on the author's own history: 1,212 sessions, 18,746 API calls, $1,134 at list prices, mostly OpenCode with some Claude Code. One developer's mix of work, not a sample of users. Dollar figures are API-equivalent estimates, not invoices.

Session length Share of spend Estimated saving
1-49 calls 43.8% 0.2%
50-199 calls 26.0% 7.3%
200+ calls 30.2% 26.3%
All sessions 100% 9.9% ($112.69)
  • Short sessions are left alone; the saving is in the 15 sessions of 200+ calls, which were 30% of spend.
  • Claude Code: 14.3% estimated overall. OpenCode: 9.4% estimated, but about a third of that comes from trimming tool output, which live mode does today. The rest is old-turn summaries, which OpenCode live mode does not do yet.
  • Summary recall in this history was 84.8% of 7,037 later references still in context.
  • Live Claude Code requests (80, five sessions) billed $1.33 against a modelled $1.99 without TokenDefrag. That baseline is estimated, and the sample is small.

Hosted tests: real models, small samples

In one hosted OpenCode noisy-build test, TokenDefrag cut the failed log from 38.0 KB to 12.7 KB, with 28.4% fewer prompt tokens and 27.0% less of the OpenCode Go plan allowance over the whole task. Both runs found the buried diagnostic and fixed the build; live mode ran one extra verification build. It is one task and one pair of runs. A hosted Claude Code long-session pair has not yet sent a condensed request, so it shows no saving either way.

Synthetic benchmark and mock eval: controlled, reproducible

On the offline synthetic benchmark, the estimate is 42.8% lower API-equivalent cost overall, from 0.9% on quick fixes to 62.3% on API-heavy workloads. In the Claude Code paired mock eval, live mode rewrote 120 requests and sent 37.3% fewer prompt tokens with every task still passing. These use generated workloads that are rich in long sessions and noisy output, plus simulated prices. They check the mechanism and compare designs; the real-session table above is the better guide to what you will see.

Claude Code and OpenCode live-mode setup and stats for condensed tool output
Actual stats from the Claude Code proxy's scripted noisy-build eval and an OpenCode session against a local mock model.

The problem

Every turn of an agent session sends the conversation again. With prompt caching that re-read is cheaper per token, but it happens on every call, and the conversation only grows.

The re-reading tax: each call re-sends the whole conversation; TokenDefrag condenses old turns once

On the reproducible benchmark corpus, re-reading and rewriting the context cache accounted for $108.73 of $118.57 in modeled cost across 20 synthetic Claude Code sessions. Run tokendefrag estimate to see the breakdown for your own history. It reads the last 30 days of Claude Code transcripts and OpenCode's local database without modifying them. It also reads Codex CLI rollouts and Pi sessions, offline and read-only, so you can see where those agents' spend goes. Live rewriting is available for Claude Code and OpenCode only.

Benchmarks

Estimated saving by workload

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 task bench.

Workload What it simulates Saving
quick-fix A few reads, one edit, one test run 0.9%
feature Read, edit, re-read, test, repeat 2.7%
debugging Long, noisy build and test logs 26.2%
api-research MCP and API tools returning pretty-printed JSON 62.3%
marathon An all-day refactor far past 200k tokens 49.5%
All 42.8%

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.

Full tables, per-rule breakdowns, and reproduction steps: docs/benchmarks.md.

Paired eval: with and without, same tasks

The paired eval runs the same tasks with and without request rewriting and compares token usage, cost at list prices, and task pass rates. Run these commands from a checkout of this repository so the eval can find eval/tasks. The mock model exercises the rewriting path for free; a hosted model tests how the agent behaves with condensed context.

tokendefrag eval run --mock                     # free: the whole pipeline against a mock model
TOKENDEFRAG_EVAL_API_KEY=sk-ant-... tokendefrag eval run --budget 5 --yes   # real Claude Code, hard-capped

Against the scripted mock, prompt tokens went from 50.6M to 31.7M, with 14.7% lower simulated cost and all 8 runs per variant passing. The smaller cost reduction reflects prompt-cache pricing: cached tokens are already cheaper, and rewriting old turns can require a cache rebuild. See the real-agent results for the hosted OpenCode pair and earlier Claude Code runs, including when the proxy sent requests unchanged.

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.

Defragmenting a conversation: old turns become one summary, bulky output shrinks, recent work is kept

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.

Rewrite once, replay forever: naive compression misses the cache every call; frozen rewrites hit it

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

One engine, two ways in: a loopback proxy for Claude Code, a plugin for OpenCode, a numbers-only ledger

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
Live mode Shortens tool results and older turns Shortens fresh plain-text results and failed shell logs; replays frozen edits
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:

  1. Rewrite once, replay forever. Every rewrite is stored and replayed byte for byte on later calls, so the prompt cache stays warm.
  2. 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.
  3. 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 offline baseline uses recorded usage. 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. A paired evaluation records the outcome, tool calls, and provider-reported usage for each run. The full method is in docs/estimate-method.md.

How it compares

TokenDefrag Shell-output hooks (RTK-style) Cost viewers (ccusage, CodeBurn)
Shows where your spend went Yes No Yes
Models cache-aware savings Yes No No
Measures live without changing requests Yes, shadow mode No No
Rewrites live requests to reduce tokens Opt-in in both clients Shrinks shell output before it reaches the agent No
Reproducible, free benchmark Synthetic corpus and mock eval No n/a

Private by design

  • No telemetry or extra model calls. The proxy uses the agent's configured upstream. Shadow mode forwards requests unchanged; live mode can condense them before forwarding.
  • 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. Sessions and projects get short SHA-256 pseudonyms. Live mode stores rewrites and recovery files locally with owner-only permissions.
  • Read-only. Transcripts and databases are never modified.
  • Explicit cleanup. tokendefrag purge --yes removes ~/.tokendefrag.

Details: docs/privacy.md.

Command reference

Release binaries cover macOS and Linux (arm64 and amd64). The install script verifies SHA256SUMS and installs tokendefrag and its tdf alias into ~/.local/bin. To build from source with Go 1.27.4 or newer, run go build -trimpath -o bin/tokendefrag ./cmd/tokendefrag or task build from the checkout.

Command Purpose
tokendefrag estimate Replay past sessions offline and estimate the saving
tokendefrag claude [--live|--shadow] [args...] Run Claude Code through the local proxy (shadow unless live is on); the exit code passes through
tokendefrag live on | off Enable rewriting for Claude Code and the OpenCode plugin, or return to shadow
tokendefrag opencode install | uninstall Add, update, or remove the OpenCode V2 plugin
tokendefrag stats [--since 7d] [--json] Shadow estimates and live rewrite counts, usage-based costs, and estimated savings
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 eval run | report Paired benchmark with and without TokenDefrag (docs/eval.md)
estimate flag Default Meaning
--agent NAME all claude, opencode, codex, pi, 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
2a eval: paired cost and pass-rate runs with Claude Code, live rewriting inside the eval sandbox, recovery files, fallback to the original Built; real-model results pending
2b Live rewriting for Claude Code (tokendefrag live on): saved state, fallback, measured stats Built; real-model validation pending
2c Live tool-output rewriting in the OpenCode plugin Built; OpenCode paired eval planned

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

Third-party license notices are 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 and performance
Paired eval With-and-without runs on real tasks: method, tasks, results
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 Implementation influences and RTK lessons
OpenCode plugin Install, options, and live rewriting
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

task check        # vet, gofmt, race-enabled tests, build
task test-plugin  # OpenCode plugin tests (needs bun)
task 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.

Jelajahi proyek terkait

Memuat…