// tokenleak v2.1.0 reference

documentation.

complete reference for the cli, subcommands, flags, providers, mcp server, config file, and env vars. nothing here leaves your machine — except, optionally, a single fetch to cursor's api when you opt into tokenleak cursor login.

# install

install globally with the package manager you already use:

$ bun install -g tokenleak
$ npm install -g tokenleak

or run without installing:

$ npx tokenleak --help

build from source

git clone https://github.com/ya-nsh/tokenleak.git
cd tokenleak
bun install
bun run build
bun run bundle
bun dist/tokenleak.js

# providers

tokenleak auto-detects all 13 providers from their local data. cursor is the only one that needs a one-time tokenleak cursor login to populate its cache — every other provider just reads files those tools already write to disk.

providerdata locationoverride envaliases
claude code~/.claude/projects/**/*.jsonlCLAUDE_CONFIG_DIRanthropic, claude, claudecode
codex~/.codex/sessions/**/*.jsonlCODEX_HOMEopenai
cursor~/.config/tokenleak/cursor-cache/usage*.csvTOKENLEAK_CURSOR_DIRcursor-ide, cursoride
gemini~/.gemini/tmp/**/*.{json,jsonl}TOKENLEAK_GEMINI_DIRgoogle
github copilot~/.copilot/otel/**/*.jsonlTOKENLEAK_COPILOT_OTEL_DIRcopilot, github-copilot, copilot-otel
amp${XDG_DATA_HOME:-~/.local/share}/amp/threads/T-*.jsonTOKENLEAK_AMP_DIRsourcegraph-amp
opencode~/.local/share/opencode/storage/message/<session>/*.jsonopen-code, open_code
qwen~/.qwen/projects/**/*.jsonlTOKENLEAK_QWEN_DIR
roo code~/.config/Code/User/globalStorage/rooveterinaryinc.roo-cline/tasks/**/ui_messages.jsonTOKENLEAK_ROO_CODE_DIRroo, roocode
kilo code~/.config/Code/User/globalStorage/kilocode.kilo-code/tasks/**/ui_messages.jsonTOKENLEAK_KILO_CODE_DIRkilo, kilocode
openclaw~/.openclaw/agents/**/*.jsonl*TOKENLEAK_OPENCLAW_DIRopen-claw
hermes${HERMES_HOME:-~/.hermes}/state.dbHERMES_HOME / TOKENLEAK_HERMES_DIR
pi~/.pi/agent/sessions/**/*.jsonlPI_CODING_AGENT_DIRpi-mono

# provider setup

twelve of the thirteen providers are fully automatic — tokenleak just reads the log files those tools already write to disk. cursor is the only one that needs a one-time manual step (a session token) because cursor doesn't write usage data locally.

the auto-detected list: claude code, codex, gemini, github copilot, amp, opencode, qwen, roo code, kilo code, openclaw, hermes, and pi. if a provider is installed but tokenleak doesn't see it, point the matching env var (see env vars) at the right directory. detailed instructions for the most common ones below.

claude code automatic

nothing to do. claude code writes a JSONL transcript per session into ~/.claude/projects/<project-hash>/*.jsonl. tokenleak walks every sub-directory and aggregates every assistant message that has a usage block.

if you've moved your claude config (e.g. to a synced drive), set CLAUDE_CONFIG_DIR=/path/to/.claude before running tokenleak.

$ ls ~/.claude/projects

if that listing is empty, you don't have any claude code session data yet — open claude code, run a session, then re-run tokenleak.

codex automatic

codex writes one JSONL per session into ~/.codex/sessions/<date>/*.jsonl. tokenleak parses each response event and uses cumulative-delta extraction so retries and tool calls don't double-count.

override location with CODEX_HOME=/path/to/.codex.

opencode automatic

opencode storage moved between releases — tokenleak checks all three locations in order:

  1. ~/.local/share/opencode/storage/message/<session>/*.json
  2. ~/.config/opencode/storage/message/<session>/*.json
  3. ~/.opencode/opencode.db (legacy SQLite) or ~/.opencode/sessions/*.json (legacy JSON)

no env override needed — first one with data wins.

pi automatic

pi (also called pi-mono) writes session JSONL files to ~/.pi/agent/sessions/**/*.jsonl. assistant messages with usage metadata are aggregated. override base directory with PI_CODING_AGENT_DIR=/path/to/.pi/agent.

gemini automatic

the gemini CLI writes chat / session / usage records under ~/.gemini/tmp/. tokenleak walks every JSON and JSONL file with usage metadata. override with TOKENLEAK_GEMINI_DIR=/path/to/.gemini/tmp.

github copilot automatic

copilot writes OTEL spans to ~/.copilot/otel/**/*.jsonl. tokenleak counts chat spans whose gen_ai.usage.* attributes report token counts. override with TOKENLEAK_COPILOT_OTEL_DIR.

amp automatic

sourcegraph amp stores threads at ${XDG_DATA_HOME:-~/.local/share}/amp/threads/T-*.json. tokenleak combines the usage ledger with message-level usage and de-duplicates matching entries. override with TOKENLEAK_AMP_DIR.

qwen automatic

the qwen CLI writes per-project JSONL logs to ~/.qwen/projects/**/*.jsonl. assistant records with usageMetadata are parsed for prompt, candidate, thought, and cached-content tokens. override with TOKENLEAK_QWEN_DIR.

roo code & kilo code automatic

both vs code extensions write task logs into ~/.config/Code/User/globalStorage/<extension-id>/tasks/**/ui_messages.json. tokenleak uses the sibling api_conversation_history.json to recover the model used. override with TOKENLEAK_ROO_CODE_DIR or TOKENLEAK_KILO_CODE_DIR.

openclaw automatic

openclaw writes agent transcripts to ~/.openclaw/agents/**/*.jsonl* with optional sessions.json indexes. model-change and model-snapshot records anchor the model for assistant usage rows. override with TOKENLEAK_OPENCLAW_DIR.

hermes automatic

hermes ships a SQLite state database at ${HERMES_HOME:-~/.hermes}/state.db. tokenleak reads aggregated session rows directly. override with HERMES_HOME or TOKENLEAK_HERMES_DIR.

cursor manual one-time

cursor doesn't write usage data to disk, so tokenleak fetches it from cursor's API using your session cookie and caches the result locally as csv. you only need to do this once per machine; later runs auto-refresh the cache.

get your cursor session token

  1. open cursor and sign in (if you haven't already).
  2. in any browser, navigate to https://www.cursor.com/settings.
  3. open browser developer tools (cmd+opt+i on mac, f12 on windows/linux).
  4. switch to the application tab (chrome) or storage tab (firefox).
  5. under cookies → https://www.cursor.com, find WorkosCursorSessionToken.
  6. copy the full value — it's a long base64-looking string.

save the token

two options. either run the cli prompt:

$ tokenleak cursor login --name work

you'll be prompted to paste the token. it gets stored at ~/.config/tokenleak/cursor-credentials.json with file permissions only you can read.

or, from inside the TUI dashboard, press c when the cursor banner appears and paste the token there.

verify and pull data

tokenleak cursor status                         # validates the saved token
tokenleak --provider cursor --format terminal   # first sync + render
tokenleak --list-providers                      # cursor should now show [available]

cursor only shows [available] in --list-providers after the first cache sync writes a cursor-cache/usage*.csv file. if status is valid but cursor still shows unavailable, run the second command above once.

multi-account / switching

tokenleak supports multiple cursor accounts side-by-side, named by label:

tokenleak cursor login --name personal
tokenleak cursor login --name work
tokenleak cursor accounts            # list all
tokenleak cursor switch work         # set active
tokenleak cursor logout --name work
tokenleak cursor logout --all --purge-cache
tokenleak cursor reset               # clean slate, useful for testing

change the credentials/cache root with TOKENLEAK_CURSOR_DIR=/path if you want them outside ~/.config/tokenleak.

privacy notes

  • the cursor fetch is the only network call tokenleak ever makes, and only when you've opted into it via login.
  • tokens are stored in plaintext locally with chmod 600 (only your user can read them).
  • everything else (claude code, codex, gemini, copilot, amp, opencode, qwen, roo, kilo, openclaw, hermes, pi) is read directly from your filesystem — no api keys, no requests.
  • nothing tokenleak does is uploaded anywhere. all rendering happens on your machine.

# tui dashboard

run bare tokenleak in a tty to launch the full-screen dashboard. eleven views, mouse + keyboard.

← →switch view
1–9, 0, -jump to view (1–11)
tab / >next time period (1d → 7d → 30d → 90d → all)
shift+tab / <previous period
j / kscroll in scrollable views
[ / ]matrix page navigation
h / lprevious/next day in explain
stoggle sort in overview
rrefresh data
copen cursor setup banner
?help overlay
qquit

views

  • overview — heatmap, stats, providers, top models
  • matrix — 4-page deep-dive (cache economics, sessions, attribution, model efficiency)
  • advisor — model-switch recs + waste-pattern findings
  • focus — deep-work session ranking
  • explain — narrative day breakdown
  • compare — period vs period with deltas
  • export — png / svg / json / wrapped / live server
  • wrapped — spotify-style story card
  • replay — session timeline with flow blocks + pulse chart (or --interactive for browser scrub)
  • nutrition — tokens vs git output by repo, $/commit, roi signal
  • receipts — itemized spend grouped by prompt behavior

prefer the old launcher? tokenleak --legacy

# commands

everything you can do, by example:

# launch the tui dashboard
tokenleak

# render directly with flags (skip tui)
tokenleak --format terminal
tokenleak --format json
tokenleak --format svg --output usage.svg
tokenleak --format png --output usage.png

# generate your AI Coding Wrapped story card
tokenleak --format wrapped
tokenleak --format wrapped --theme light --open

# launch the interactive AI Wrapped presentation in a browser
tokenleak --wrapped-live --days 365

# start the local live dashboard server
tokenleak --live-server

# get model efficiency recommendations
tokenleak --advisor --days 30 --claude

# explain one day's usage
tokenleak explain 2026-04-22

# replay a day's session timeline
tokenleak replay
tokenleak replay 2026-04-22 --format json
tokenleak replay 2026-04-22 --interactive

# rank deep-work sessions
tokenleak focus --provider codex --days 30

# estimate AI ROI from token usage and local git output
tokenleak nutrition --days 30

# export anonymized aggregate data or an llm-ready prompt
tokenleak commons export --days 90 --output commons.json
tokenleak commons prompt --days 90 --clipboard

# itemized receipt of spend by prompt behavior
tokenleak receipts --days 30

# show registered providers, aliases, and availability
tokenleak --list-providers

# subcommands

tokenleak explain <date>

builds a narrative day report with top providers, sessions, projects, models, and anomaly flags.

$ tokenleak explain 2026-04-22 --format json --output explain.json

tokenleak focus

ranks sessions by a deep-work score from duration, density, and project streak.

$ tokenleak focus --provider pi --days 30 --format json

tokenleak replay [date]

chronological session timeline with flow blocks, pulse chart, and flow/think ratio. defaults to today.

$ tokenleak replay 2026-04-22 --format json --output replay.json

add -i / --interactive to skip the static report and open a browser scrub UI on http://localhost:3567: drag the timeline, press space to play the day at 60–600× speed, watch the cumulative cost odometer tick up. add --open to auto-open your default browser, or --port <n> to override the starting port.

tokenleak replay --interactive
tokenleak replay 2026-04-22 --interactive --open
tokenleak replay 2026-04-22 --interactive --port 4567

tokenleak nutrition

estimates AI ROI by cross-referencing token usage with local git output. resolves each provider's project paths to git roots, runs read-only git log --numstat, and reports tokens/cost per commit and per changed line. emits a per-repo table and a global summary.

tokenleak nutrition --days 30
tokenleak nutrition --days 90 --format json --output nutrition.json

tokenleak commons export | prompt | inspect

share an anonymized cut of your usage for analysis. export writes aggregate JSON, prompt writes (or copies) a markdown analysis prompt ready to paste into any LLM, inspect validates a commons JSON file before sharing.

tokenleak commons export --days 90 --output commons.json
tokenleak commons prompt --days 90 --clipboard
tokenleak commons prompt --provider claude,codex --output tokenleak-llm-prompt.md
tokenleak commons inspect commons.json

tokenleak receipts

an itemized receipt of spend grouped by prompt behavior — sortable by cost, qty, or alpha. ships in terminal, json, svg, or png.

tokenleak receipts --days 30
tokenleak receipts --format json --output receipts.json

tokenleak cursor

cursor needs a session token. tokenleak stores it locally with file permissions only you can read.

tokenleak cursor login --name work
tokenleak cursor status
tokenleak cursor accounts --json
tokenleak cursor switch work
tokenleak cursor logout --name work
tokenleak cursor logout --all --purge-cache
tokenleak cursor reset

get the token by copying the WorkosCursorSessionToken cookie from https://www.cursor.com/settings in your browser devtools.

# flags

flagdescriptiondefault
--format / -fjson | svg | png | terminal | wrappedterminal
--theme / -tdark | lightdark
--since / -sYYYY-MM-DD start date
--until / -uYYYY-MM-DD end datetoday
--days / -dtrailing days to include90
--output / -ooutput path (format inferred from ext)stdout
--width / -wterminal render width80
--provider / -pfilter to provider(s), comma-separatedauto
--claude / --codex / --cursor / --pi / --open-codeshortcut provider flagsfalse
--all-providersignore filters, use everythingfalse
--list-providersshow registered providers + aliasesfalse
--compareauto or YYYY-MM-DD..YYYY-MM-DD
--moreexpanded stats and compare cardsfalse
--clipboardcopy rendered output to clipboardfalse
--openopen output file in default appfalse
--uploadupload to a service (gist)
--live-server / -Lstart local browser dashboardfalse
--wrapped-livestart interactive ai wrapped presentationfalse
--advisorrun model efficiency advisorfalse
--legacyopen the classic interactive launcherfalse
--no-colorstrip ansi escape codesfalse
--no-insightshide terminal insightsfalse

# compare mode

compare token usage across two periods. with auto, tokenleak splits your selected range in half (e.g. --days 60 compares last 30 vs prior 30).

tokenleak --compare auto
tokenleak --compare 2026-01-01..2026-03-31
tokenleak --compare auto --format json
tokenleak --compare auto --format png --output compare.png

json shape is { periodA, periodB, deltas }. png/svg auto-enable expanded compare cards.

# advisor

the advisor surfaces two kinds of findings: model-switch recommendations (concrete $/month savings from routing some sessions to a cheaper model) and waste patterns (deterministic inefficiencies with local recipes to fix them).

$ tokenleak --advisor --days 30 --claude

each rec includes current cost, projected cost, monthly savings, and a confidence rating (high/medium/low). also exposed as the get_efficiency_advice mcp tool.

waste taxonomy

six deterministic categories. each finding ships severity, evidence, an estimated monthly savings, and at least one recipe (sometimes a runnable command).

  • premium-short-outputpremium model used on responses too short to need it
  • low-cache-hit-rateprompts that should reuse cache but don't
  • wasted-cache-writescache writes that never get reused before expiry
  • context-dragconsistently large prompts that bloat every call
  • burst-spikeisolated days that spend disproportionately
  • model-switch-churnfrequent model swaps inside the same session

# wrapped

spotify-wrapped style story card as a tall png — 12 sections of stats and achievements.

tokenleak --format wrapped --open
tokenleak --format wrapped --theme light --output my-wrapped.png
tokenleak --format wrapped --since 2026-01-01 --until 2026-12-31

wrapped live (browser deck)

tokenleak --wrapped-live
tokenleak --wrapped-live --days 365 --claude

opens an interactive 12-slide presentation on http://localhost:3456 (auto-increments port if taken).

# mcp server

tokenleak ships a model context protocol server. drop it into claude code, cursor, or any mcp-compatible client and your AI gets full read access to your local usage.

config (.mcp.json)

{
  "mcpServers": {
    "tokenleak": {
      "command": "bun",
      "args": ["run", "/path/to/tokenleak/packages/mcp/dist/index.js"]
    }
  }
}

tools

  • list_providerslist registered providers and availability
  • get_usage_summarytokens, cost, streaks, rolling windows, per-provider breakdown
  • get_daily_usageday-by-day usage data for trend analysis
  • get_cost_breakdownmodels ranked by cost with token counts and shares
  • get_streaks_and_habitsstreaks, day-of-week, peak day, session metrics
  • compare_periodscompare two time periods with deltas
  • get_efficiency_advicemodel-switch recs and projected savings

resources

tokenleak://overview — 30-day summary as json. tokenleak://provider/{name} — per-provider data.

# config file

create ~/.tokenleakrc for persistent defaults. priority: cli flags > env vars > config > defaults.

{
  "format": "terminal",
  "theme": "dark",
  "days": 90,
  "width": 120,
  "noColor": false,
  "noInsights": false,
  "more": false
}

# env vars

variabledefaultdescription
TOKENLEAK_FORMATterminaldefault output format
TOKENLEAK_THEMEdarkdefault theme
TOKENLEAK_DAYS90default lookback period
TOKENLEAK_MAX_JSONL_RECORD_BYTES10485760max single record size before reject
CLAUDE_CONFIG_DIR~/.claudeclaude code config directory
CODEX_HOME~/.codexcodex home directory
TOKENLEAK_CURSOR_DIR~/.config/tokenleakcursor credentials/cache root
TOKENLEAK_GEMINI_DIR~/.gemini/tmpgemini cli temp/session directory
TOKENLEAK_COPILOT_OTEL_DIR~/.copilot/otelgithub copilot OTEL JSONL directory
TOKENLEAK_AMP_DIR$XDG_DATA_HOME/amp/threadsamp thread directory
TOKENLEAK_QWEN_DIR~/.qwen/projectsqwen project log directory
TOKENLEAK_ROO_CODE_DIRvs code roo code task storageroo code task-log directory
TOKENLEAK_KILO_CODE_DIRvs code kilo code task storagekilo code task-log directory
TOKENLEAK_OPENCLAW_DIR~/.openclaw/agentsopenclaw agent transcript directory
TOKENLEAK_HERMES_DIR~/.hermeshermes directory containing state.db
HERMES_HOME~/.hermeshermes home directory
PI_CODING_AGENT_DIR~/.pi/agentpi coding agent directory

# output formats

terminal

ansi heatmap with the ░▒▓█ blocks, stats panel, providers, top models, day-of-week breakdown, and insights. falls back to a one-liner under 40 cols.

json

structured payload with schemaVersion, dateRange, per-provider daily + models, and an aggregated block (streaks, rolling windows, peak day, dow, top models). with --more the more field carries cache roi, model efficiency, session/project drilldowns, and attribution clusters.

svg

self-contained heatmap (7×N weeks) with quantile-binned colour, month + dow labels, stats panel, insights panel. dark + light themes.

png

same layout as svg, rendered through sharp. great for embedding in docs or social posts.

wrapped

tall single-page editorial card with title, big numbers, streak story, top model donut, provider mix, dow + tod bars, cache gauge, peak day, achievements, monthly burn projection, and footer.