Discover MCPs & agents
Loading MCPs and agents…
Loading MCPs and agents…
Private, local-first token analytics for Claude Code, Gemini CLI, and Codex.
Jump to setup instructionsFetched from the repository for this visit.
See where your AI coding tokens go — without sending your logs anywhere.
Turn local Claude Code, Gemini CLI, Codex, OpenCode, and Antigravity records into terminal summaries, a loopback-only live dashboard, or one self-contained offline HTML file.
Try the interactive demo · Clone and run · Docs · Dashboard guide · 中文说明
See it before using your own data: explore the synthetic dashboard in your browser. No install, account, or local logs needed. The hosted preview is interactive, not a live view of your machine. To run it locally without logs, use ./run demo --open after cloning.
Preview generated by the real dashboard from invented records. It contains no real local logs, private paths, session identifiers, or router configuration.
Open the interactive synthetic demo to explore the dashboard with invented records. It does not refresh from your machine. After cloning, ./run demo --open generates the same kind of local-only sample report.
AI coding tools already leave usage records on your machine, but each tool stores and counts them differently. tokens gives you one inspectable local view:
--source auto) while keeping each source's reported token semantics visible.tokens quota for official Codex rate-limit snapshots and explicit Claude capacity estimates with projected limit times, without sending logs anywhere.The local CLI and dashboard require no account, telemetry endpoint, hosted backend, or external runtime assets; your AI coding tools and this documentation site have their own network policies. Core parsing, aggregation, reporting, and loopback serving use the Python standard library. Windows additionally needs the data-only tzdata package for consistent IANA timezone support.
Requirements: Python 3.9 or newer on macOS, Linux, or Windows. To analyze your own usage, you also need existing local logs from a supported AI coding CLI; the synthetic demo needs no logs.
git clone https://github.com/LingXi-fur/tokens.git
cd tokens
./run doctor
./run serve --open
Without --source (--source auto), tokens checks paths and permissions for all five registered sources in sources.py (Claude Code, Gemini CLI, Codex, OpenCode, and Antigravity) and enables every readable source without opening logs. Pass explicit --source flags (e.g. --source gemini or --source antigravity, repeatable and combinable with auto) to limit the sources for a run.
./run doctor checks paths, candidate file counts, timezone, output, and cache permissions. It does not parse message contents or print project and session identifiers.
./run doctor --models explains how Claude usage was attributed to models. It reads records through the normal cached reader path, groups them by the logged request name and the resolved model, and labels each group's basis: logged (a backend name stored as-is), hex_alias (a CCR anthropic/claude-ccr-h… alias decoded to its backend), native_direct (a direct Anthropic request kept and normalized, for example claude-opus-5-5 → claude-opus-5.5), or router_rule (a tier alias rewritten by the current router). The report lists the router file path and its current rules, then shows record counts, token totals, and first/last dates only—never cwd, session ids, or project names. Add --since/--until (YYYY-MM-DD, interpreted in the report timezone) to narrow the window, for example to today, and --json for machine-readable output. Plain ./run doctor still checks the environment only and does not read logs.
./run quota answers “how much of this window is left, and when would I hit the limit?” It reads official Codex rate_limits snapshots and Claude rate-limit events. Codex windows are identified by window_minutes (for example 300 or 10080), never by the primary/secondary label, and limits with different limit_id/limit_name values stay separate. For each window it shows the latest used percentage, reset time in the report timezone, a velocity from snapshots in the last 60 minutes, and an extrapolated limit time; fewer than two snapshots or a span under five minutes reports insufficient data. An already reset window is marked instead of showing a stale percentage.
Claude has no official percentage, so its section is explicitly an estimate. For every rate-limit event with a reset time, the tokens in [reset − 5h, event] become one capacity sample, using only Anthropic-direct records (model starts with claude- and the request name normalizes to that model). CCR-routed GLM/DeepSeek records are excluded. Ended five-hour windows without a rate-limit hit also provide a safe lower bound: capacity is max(median hit sample, highest safe window), and if the safe window is higher than every hit sample the report says the hit samples are stale. The report shows the median, min/max, and sample count, then estimates the current window from the first direct record in the latest five-hour segment. That window boundary is an approximation, and different models are not weighted by cost. OpenCode has no quota signal and is reported as such.
--source codex (repeatable) limits the sections, --json prints machine-readable output, and --no-cache ignores the separate quota-v1.json scan cache under the local cache directory. Only timestamps, quota fields, model names, and token totals are used; message text, cwd, session ids, and project names are never printed. The first run scans all local logs and can be slow; later runs reuse the quota and reader caches.
The dashboard's Today HUD shows the same windows — official Codex snapshots and Claude estimates — with a used-percentage bar, reset time, and projected limit time in the report timezone; tokens serve refreshes it with every live snapshot, while a static dashboard carries a generation-time snapshot.
./run outcomes answers a different question than quota — not “how much is left?”, but “what did the spend produce?” It reports commits, added and deleted lines, lines still present after 7 days, a rework tax, retained lines per $1, and cost per commit, by day, project, model, and tool. --since/--until (YYYY-MM-DD, inclusive, in the reporting timezone) bound the range: with only --since the range runs through today, with only --until it starts at the records' earliest day, and with no explicit bound it covers the records' own day span. --json prints machine-readable output.
Each session's working directory is matched to its git repository — worktrees of one repository roll up into that repository — and your own commits (git config user.email/user.name, extended by TOKENS_OUTCOME_EMAILS) are attributed to the session they fall in, from the session's start until 30 minutes after its last activity; commits inside several windows go to the session whose activity ends closest, merge commits are not counted, and commits outside every session count as manual work. Surviving lines are lines still present at HEAD 7 days after the commit, measured with read-only git blame and cached per repository and commit under the local cache directory (outcomes-blame-v1.json, invalidated when HEAD moves). Commits younger than 7 days are pending: their added lines are counted, but survival is reported as unknown, not as zero. The rework tax is the share of a session's added lines removed within 7 days, times that session's spend. Costs use the same official USD reference prices as the Cost Ledger — records without an official price contribute tokens but no cost, and the report says amounts cover the priced part. Lock files, package-lock.json, dist/, node_modules/, and *.min.js never enter the measurements; TOKENS_OUTCOME_EXCLUDE adds patterns.
Sessions outside any git repository are listed separately with their spend (a missing working directory counts there too), and sessions in a repository that produced no commits are listed separately. The block reports a status: ok when everything was measured; partial when a repository could not be read, a file could not be blamed within 10 seconds, or the per-build blame budget of 400 commits ran out (reasons names the failed checks, such as repo_unavailable, blame_timeout, blame_skipped); or unavailable when git is missing — session spend is still reported then. Other reason counters include no_repo (sessions outside any git repository), bad_session_ts (records with unparseable timestamps are skipped), blame_cache_reset (the on-disk blame cache was corrupt or version-mismatched and was rebuilt), binary_commit (commits touching binary files, where numstat provides no line counts), and unestimated_cost (records without an official price).
Value by model and by tool reuses the same measured commits, but never assigns a whole session to its primary model. Spend is exact per (tool, model) bucket. Commits, added lines, settled surviving lines, pending lines and rework tax are allocated by that item's share of the session spend, so a session that used several models appears in each model's row with a proportional slice; only when every priced amount in a session is zero do token counts decide the weights. A row with fewer than 3 sessions or less than $1 of settled spend is marked low sample, and low-sample rows never enter the ranking (the terminal prints them after the ranked rows with a *). Commits outside every session stay unattributable and are excluded from both tables. Sessions whose working directory was deleted can still resolve through OpenCode's local project mapping (including removed worktrees).
Privacy is unchanged: the outcomes block holds only counts, ratios, and labels — never commit messages, file names, or author emails — and project names follow --anonymize. Git is only read, and every call is bounded by a timeout.
When agent-taskboard is installed, outcomes can join its export --json to the same session costs. It is discovered from repositories that already appear in outcomes with a .taskboard/ directory, plus absolute repositories in TOKENS_ATB_REPOS (separated by the OS path separator). The command is TOKENS_ATB_CMD (for example python3 -m agent_taskboard, parsed with shlex) or atb on PATH; no atb means the block is absent. The export runs as a subprocess with a 120-second timeout — it can take tens of seconds on a large store, so tokens serve refreshes it in a background thread (showing the previous cache or “reading atb”), while tokens dashboard and tokens outcomes wait. Results are cached per repository and .taskboard/ mtime for at most 10 minutes.
Each atb session segment (adapter, native id, from, to) is matched to records of the same tool and native session id, using [from, to) — a record exactly at a boundary belongs to the segment that starts there, and only the session's final segment includes its own to. Adapter names map to tokens sources (claude-code → claude, codex → codex, gemini-cli → gemini, opencode → opencode). Segment spend uses the same official reference prices; a segment's own usage is only a check (a >5% difference increments atb_usage_mismatch). The dashboard adds a collapsed task-cost section with a by-agent table, the five most expensive tasks, and worktree/command/time_window evidence counts (time_window is the fallback with the lowest confidence). Task titles are local-only and are removed by --anonymize; no session ids or paths enter the payload.
Example (project paths replaced with placeholders):
Outcomes (2026-10-20 ~ 2026-11-05)
Status: ok
Session spend: $1,833.10 · Commits: 6 · Commits outside any session: 0 · Sessions without commits: 3
Sessions outside any git repo: 30 · Session spend: $1,688.02
Added/deleted lines: 6,948 / 290 · Surviving lines: 6,804
Rework tax: $0.77 · Retained lines per $1: 3.7 · Retained lines per $1 (settled only): 155.1 · Cost per commit: $305.52
Project Repo Commits Surviving Spend Rework
/path/to/home no 0 0 $288.23 $0.00
/path/to/project-a no 0 0 $4.18 $0.00
/path/to/project-b no 0 0 $6.37 $0.00
/path/to/repo-a yes 3 2,196 $11.75 $0.62
/path/to/repo-b yes 0 0 $45.56 $0.00
/path/to/project-c no 0 0 $1,303.64 $0.00
/path/to/project-d no 0 0 $20.54 $0.00
/path/to/project-e no 0 0 $58.47 $0.00
/path/to/project-f no 0 0 $6.60 $0.00
/path/to/repo-c yes 3 4,608 $87.75 $0.15
The live dashboard binds only to 127.0.0.1. A background worker checks local logs every five minutes by default (--interval); page requests read the latest successful in-memory snapshot without waiting for a scan. The page checks for published updates at most every minute by default, with shorter checks while data is being prepared. Its 1, 5, 15, or 30 minute selector and pause control affect browser checks only, not background scans. Initial preparation is shown explicitly; later scan failures keep the last successful data visible with its last successful check time. Unchanged files are not reparsed.
Browser checks use the small /api/status response; the full /api/snapshot is fetched only when needed. Older servers without the status endpoint retain conditional snapshot polling. Scan details show discovery, collection, payload building, and encoding, plus elapsed time, successfully processed files, discovered candidates, cache hits, parses, and skips. Discovered candidates are a running count, not a known total: these numbers are not a completion percentage or an ETA. A single large file can take time without changing the counters. Paused, hidden, or disconnected pages retain the last received state rather than inventing a heartbeat. Timings diagnose work; they do not promise a speedup.
Integration status: the reader-level memo is implemented, but serve is not wired to it yet; the following describes the pending service integration, not an enabled runtime feature.
Non-anonymous serve with caching enabled also keeps a bounded, per-process memo of successfully processed Claude/Codex files. After a later file fails, a retry can reuse unchanged earlier files while still securely reopening them and rerunning cross-file conflicts and collection limits. Failed files are retried, not skipped; no partial report or partial disk cache is published. Cache-hit counts include disk and in-process reuse. The memo is limited to 4,096 files, 100,000 records, and 64 MiB of estimated retained data (not a process RSS cap), with at most 8 MiB / 20,000 records per file; oversized entries are not retained. Restarting clears it, changed files/configuration invalidate reuse, and unsupported parser/timezone contexts bypass it. Files whose output records contain timestamps without an explicit UTC offset are also excluded from in-process reuse; parsing still follows the existing rules. When a sequential scan exceeds the memo's capacity, LRU eviction can leave the next scan with no hits; the limits do not guarantee a speedup. --no-cache and anonymous mode disable the memo. This can reduce repeated parsing after failures, not the first cold scan or the underlying conflict.
With caching enabled, non-anonymous serve can keep one successful dashboard snapshot in live-snapshot/last.json under the local cache directory (~/Library/Caches/ai-cli-tokens on macOS). A compatible snapshot appears immediately after restart, marked as restored with its original timestamps, while a full scan revalidates it. Failed or partial scans never replace it. This is the dashboard's aggregate data, including project/session labels and titles already present in the report—not raw conversation logs, but still potentially private. Storage stays local, with a private POSIX directory (0700) and file (0600); no upload is added. Integrity hashes detect damage, not malicious changes by another process running as the same user; this is not a same-user security boundary. --no-cache disables both record and snapshot cache reads/writes. Anonymous mode, Windows without equivalent ACL validation, and environments without a stable timezone identity do not persist or restore snapshots. Invalid, unsafe, or incompatible files are ignored; a write failure leaves valid in-memory data visible with a storage warning. Recovery requires a previous complete success: it cannot turn an initial collection failure, including a Codex usage conflict, into valid data.
No local logs yet? Open a full synthetic dashboard generated through the same reporting pipeline:
./run demo --open
The demo writes out/dashboard-demo.html from generated sample data only. It does not read local Claude Code, Gemini CLI, Codex, OpenCode, or Antigravity logs.
Create an offline archive instead:
./run dashboard --open
Install the checkout in a local virtual environment first. This also installs the required tzdata package:
git clone https://github.com/LingXi-fur/tokens.git
cd tokens
python -m venv .venv
.\.venv\Scripts\Activate.ps1
python -m pip install -e .
tokens doctor
tokens serve --open
To narrow a run to specific tools, pass repeatable --source flags to tokens serve --open.
From the cloned checkout, install an editable command into a virtual environment:
python -m venv .venv
source .venv/bin/activate # Windows PowerShell: .venv\Scripts\Activate.ps1
python -m pip install -e .
tokens doctor
tokens serve --open
This installs from your local checkout. No package-registry release is required by these instructions.
Tagged releases on GitHub Releases attach a wheel, an sdist and SHA256SUMS. 0.3.0 is not published to PyPI; install the downloaded wheel into a virtual environment:
shasum -a 256 -c SHA256SUMS --ignore-missing # in the download folder
python3 -m venv ~/.venvs/tokens
~/.venvs/tokens/bin/python -m pip install ./ai_cli_tokens-0.3.0-py3-none-any.whl
~/.venvs/tokens/bin/tokens --version
~/.venvs/tokens/bin/tokens demo --output /tmp/tokens-demo --open
On Windows, use the venv's Scripts\python.exe / Scripts\tokens.exe. What changed in 0.3.0 is summarized in docs/release-notes-0.3.0.md. The monthly-budget specification (docs/monthly-budget-design.md) documents the local monthly budget in the Cost Ledger (stored in the browser under tk-budget-v1 only when you save a budget).
| Goal | Source-checkout command | Behavior |
|---|---|---|
| Quick terminal summary | ./run day | Last 14 days in the terminal |
| Try before installing | Open the hosted synthetic Demo | No clone, account, local logs, or upload |
| Explore locally without logs | ./run demo --open | Synthetic data only; writes dashboard-demo.html |
| Keep a dashboard open | ./run serve --open | Loopback-only service with in-page updates |
| Save an offline archive | ./run dashboard --open | Self-contained generation-time snapshot |
| Prepare a safer sharing copy | ./run dashboard --anonymize --open | Pseudonymizes selected identifiers |
Reports are written to ./out by default. Use --output DIR to choose another location.
The page is organized as Statistics scope → Usage overview → Trend and exact details → Daily model usage → Cost. Pick the date range and models first, then read the current statistics; the report-generation-day fallback rule and the coverage boundary expand under the header's "Snapshot details" disclosure.
The header distinguishes the configured local sources from the sources this snapshot actually read. Data Health lists each source's record count, tokens, record dates, and field capabilities; "No records in this snapshot" does not mean no usage, and "Not enabled" does not mean no local logs. Source counts and dates follow the report snapshot, not the front-end model filters, and the latest record day is not a sync time. A first failed scan never substitutes zero for usage; a later failed update keeps the last successful snapshot and says so. Error diagnostics contain only controlled stages and reason codes, never raw exceptions or paths.
Find your busiest days, compare two equal-length periods, and see which recorded models, projects, or sessions contributed to the difference. Up to eight top models keep distinct palette colors (at least one slot guaranteed per active source), while Other uses neutral gray and itemizes every folded model individually across legends, donut slices, tooltips, period-table expansion (Other (N)), exports, and a "More models" filter; Today HUD's top model always resolves to a real model name, and anonymized reports omit folded names. When source records provide the fields, you can:
The interactive Dashboard guide covers the A/B interval lens, peak profile, keyboard controls, achievements, and other views. A/B compares recorded token contributions; it does not establish why usage changed. A zero baseline reports absolute Token change only. Projects and sessions are parallel aggregates, not automatically paired. Selected A/B periods and an open peak profile may be restored from the URL; project/session IDs and exact token details are not written there.
Token change describes usage, not productivity or code quality. Cache Read is cached-token volume, not guaranteed monetary savings.
The Cost ledger estimates model costs from independently recorded billing components. It ships with built-in official reference prices checked on 2026-11-15 (including Google Gemini, OpenAI, Anthropic, DeepSeek, Z.ai, and Moonshot) and also accepts prices you enter under Set prices. Unpublished vendor components stay blank instead of being estimated, and retired or internal model names stay unpriced. With no local settings, it shows USD reference estimates by default and writes nothing to browser storage until you save.
gemini-4-neon, gemini-4-hydrogen, gemini-2.5-pro at the ≤200K tier, gemini-2.5-flash, gemini-3-flash-preview, with thinking tokens billed at the output rate and unpublished components like cache writes left blank; names the pricing page does not list, such as gemini-3-pro-preview, stay unpriced), OpenAI Standard short-context tiers (≤272K, plus gpt-5.3-codex), the Anthropic Claude lineup (plus claude-fable-5-1; cache writes at the 5-minute tier), DeepSeek peak-time baselines, Z.ai international USD rates rechecked on 2026-11-19 (GLM-5.3, GLM-5.3-Flash, GLM-5.3-FlashX, GLM-5.2, GLM-5.1, and GLM-5; not the domestic Zhipu equivalent, with limited-time-free cache storage recorded as zero, reasoning billed at the output rate, and bare provider-prefixed records like zhipu/glm-5.3-flash listed separately at the same backend's rates), and Moonshot Kimi. The page never requests them from a provider; published rates travel with the page assets, and vendor source links open only when you click them.tk-cost-v1 local-storage key, with no provider calls or API keys and no new storage key; readers and usage statistics are unchanged. Manually entered private prices are not embedded in the report. Browser storage for a live page and an offline file may be separate; if storage fails, settings remain available for the current page only.Older offline snapshots without billing data must be regenerated to use the ledger. The current record cache file is records-v8.json; its internal schema version (currently 22) covers Codex event identities, corrected output accounting, accepted zero-usage and bounded context-estimate updates, the mixed-format union accounting contract, cumulative recomputation treated as a new ledger baseline, unconditional first-sight evidence for repeated cumulative anchors (including across model changes, so consumption after a model-switch resume is attributed to the first-seen model), Claude records keeping the original request model name alongside the router-resolved backend name as an informational field that never changes counting, dedup, or cost attribution, and direct Anthropic requests keeping their logged model identity instead of being retroactively rewritten by current CCR router rules. Older cache files are retained.
| Source | Default local path | Project data | Session data | Accounting note |
|---|---|---|---|---|
| Claude Code | ~/.claude/projects/**/*.jsonl | Yes | Yes | Total is input + output + cache read + cache write. |
| Gemini CLI | ~/.gemini/tmp/*/chats/session-*.json | Usually no | Yes | Uses source tokens.total when available. |
| Codex | ~/.codex/{sessions,archived_sessions}/**/rollout-*.jsonl[.zst] | Usually no | Usually no | Cached input is included in input; reasoning is included in output. Neither is added twice. Compressed archives require an existing local zstd executable. |
| OpenCode | ~/.local/share/opencode/opencode.db (SQLite, honors XDG_DATA_HOME) | Yes | Yes | Total is input + output + reasoning + cache read + cache write; OpenCode input excludes cache and output excludes reasoning. Read-only; only token, model, and time fields are queried, never message text. |
| Antigravity | ~/.gemini/antigravity/conversations/*.db (SQLite, overridable via TOKENS_ANTIGRAVITY_DIR) | No | Yes | Total is input + output + cache read. Read-only; only token, model, and timestamp fields are queried, never conversation payloads or summaries. Uses an undocumented private format, so app upgrades may require updating the reader. |
Antigravity names claude-opus-5-5-low / -medium / -high are explicit aliases of the official claude-opus-5.5 reference rate (thinking tiers do not change the price); the dashboard and terminal keep showing the original name and label the estimate. Names Google does not list exactly (for example gemini-4-argon-trial, gemini-3.8-flash-n) stay pending rather than guessed. Antigravity records currently carry no working directory, so outcomes cannot attribute them to a repository; the conversation summaries' workspace_uris/FTS workspace columns and the annotation/state/brain metadata are empty or contain no reliable path.
All readable sources in sources.py are enabled automatically by --source auto; repeat --source to narrow or combine specific tools (for example, adding --source antigravity):
Codex .jsonl.zst archives require zstd to be discoverable on the collecting process's PATH; uncompressed logs do not. A background service can have a different environment from an interactive terminal. ./run doctor --source codex reports dependency discovery for the process running that command, not necessarily the background service. If collection reports collection · codex · decompressor_unavailable, check the service's environment rather than skipping archives; the existing service must reload its configured environment before that change takes effect. Enabling a source is not proof of collected usage: verify a successful snapshot and actual source records.
A collection · codex · usage_conflict error is an integrity failure, not a missing decompressor. It can mean inconsistent evidence for one response or cumulative anchor, or conflicting duplicate identities across active and archived files. This public code alone does not identify which check failed or prove a producer bug. New live Dashboard/API responses can additionally include the fixed error_details.conflict_kind codes below; older servers and failures without a subcode retain the generic diagnostic. These codes name the failed check, not which underlying field or copy is correct. CLI errors remain generic.
conflict_kind | Failed check |
|---|---|
modern_response_mismatch | Usage, model, or billing evidence differs for one modern response identity within a file. |
legacy_cumulative_rollback | Retained as an error code for compatibility, but no longer triggered: a legacy cumulative total_tokens decrease starts a new ledger baseline instead of failing. |
legacy_anchor_mismatch | Retained as an error code for compatibility, but no longer triggered within a file: repeated legacy cumulative anchors keep first-sight evidence, including across model changes. |
cross_file_identity_mismatch | Usage, model, or billing evidence differs for one duplicate usage identity across files; this is not limited to modern responses. |
For legacy_anchor_mismatch only, error_details.mismatch_kind can further identify the differing groups: usage, model, billing, usage_model, usage_billing, model_billing, or usage_model_billing. Usage means the existing six-field usage signature; billing also distinguishes missing fields from explicit zeroes. The dashboard displays fixed group labels, never the compared values, model names, paths, or session identifiers. Missing or invalid detail retains the generic anchor explanation. These groups do not establish the cause, select a correct copy, or mean statistics have recovered.
Two narrow state updates are accepted without adding another consumption record. Both require adjacent legacy events under the same session and model, complete unchanged cumulative counters, and an original trusted positive usage at that anchor. The new last usage must have explicit integer-zero components and either a trusted zero total, or a positive total strictly below the original last total and no greater than the cumulative total, with total_mismatch as its only billing uncertainty. Codex can replace last usage with a context estimate while leaving cumulative spending unchanged; the estimate is not new spending. The original record and billing remain untouched. This shape does not authenticate the producer or establish the cause of a local conflict. Standalone total-only records are not filtered; incomplete evidence, other billing uncertainty, model changes, broken adjacency, or subsequent differing consumption still follow the original checks.
Modern records never break the legacy adjacency evidence behind those updates. Legacy token_count events are the ledger baseline: real producer logs persist modern responses only partially and out of order, so neither side alone is a complete record. A mixed-format file therefore counts the union of both formats: every legacy consumption counts once, and a modern record whose exact (usage, model, complete billing) value matches an unused legacy entry is absorbed as its mirror rather than counted again. Modern records beyond that multiset intersection join the ledger as independent consumptions—real producers persist incomplete responses in the modern format only. Because legacy events have no response ID, this value matching cannot prove that a modern record mirrors a specific legacy entry: a distinct real consumption equal in value to a legacy entry is absorbed into it and undercounted. That direction is structural under this contract; arbitrary mixed logs are not guaranteed to merge losslessly, and passing these checks does not establish that local statistics have recovered.
Collection stops without publishing partial totals; any last successful snapshot remains visible. Keep original logs and caches intact—do not delete archives, pick an arbitrary copy, or relax checks to obtain a total. doctor does not parse usage events and cannot resolve this conflict; investigate with synthetic reproductions or explicitly authorized, de-identified evidence rather than uploading conversation logs.
./run serve \
--source claude \
--source gemini \
--source codex \
--source opencode \
--source antigravity \
--open
Different tools do not expose identical token semantics. tokens preserves each source's reported total instead of pretending the values are perfectly interchangeable.
Claude App Code sessions that reuse Claude Code's local logs are included once through the existing Claude source, not through a second App source. Ordinary Claude chat and Cowork token usage are not connected: their token totals are unknown, not zero. Subscription utilization samples are not converted into tokens. Local reports do not establish coverage of other devices, cloud sessions, or an entire account.
Codex collection supports legacy token_count and newer token_usage_record events. Stable response identities prevent duplicate active/archive copies from inflating totals; exact mirrors across the two formats are counted once. Ambiguous mixed formats, conflicting identities, unreadable files, unavailable archive decompression, and resource-limit failures report an incomplete collection instead of publishing a partial successful report.
./run [day|week|month|all|dashboard|demo|serve|doctor|quota] [options]
tokens [day|week|month|all|dashboard|demo|serve|doctor|quota] [options] # after local install
| Option | Purpose |
|---|---|
--source antigravity|claude|codex|gemini|opencode|auto | Select a source (default auto enables every readable source); repeat to combine sources. |
--since YYYY-MM-DD / --until YYYY-MM-DD | Limit the inclusive report range. |
--days N / --weeks N / --months N | Number of periods shown in day, week, or month terminal mode. |
--timezone AREA/CITY | Override the detected system timezone. |
--lang en|zh | Terminal and static HTML language; default follows system locale (TOKENS_LANG overrides it). |
--output DIR | Choose the report directory; default is ./out. |
--html | Add a static HTML report to terminal modes. |
--dashboard | Write the interactive offline dashboard regardless of positional range. |
--anonymize | Pseudonymize identifiers in dashboard or live mode. |
--models | With doctor, show model attribution groups (including OpenCode). |
--json | With doctor --models or quota, print machine-readable JSON. |
--interval SECONDS | Set the background log-scan interval; minimum 1, default 300. Browser checks are separate. |
--port PORT | Set loopback port; default 8765, or 0 for an available port. |
--open | Open generated file or local URL in the default browser. |
--no-cache | Re-read all selected log files. |
--version | Show the program version number and exit. |
See the complete CLI reference.
tokens reads local files and performs analysis locally. Offline snapshots make no network requests. Live mode talks only to its same-origin service on 127.0.0.1 and provides no LAN binding option. When present, ~/.claude-code-router/custom-router.js is read locally as text only; it is never executed or uploaded. Router rules are used only to interpret plain Claude request aliases and never rewrite Gemini or Codex model names. Claude records additionally keep the pre-resolution request model name as an informational field; request names can reveal local routing intent and are omitted from anonymized exports. Daily model usage includes a collapsed "Route map" panel: an SVG flow diagram from request names to resolved backends with line width proportional to tokens, hover highlighting, and click-to-filter on backend nodes; it hides entirely when no alias flows exist or in anonymized exports.
Record-cache writes use a temporary file in the cache directory and atomic replacement. Descriptor-based permission setup is applied when os.fchmod is available; POSIX uses mode 0600. On Windows, permission bits are not equivalent to POSIX access controls, and this does not promise a user-only Windows ACL. Keep the cache directory in a location with appropriate access permissions.
A normal dashboard may still contain:
--anonymize replaces project paths, session identifiers, and natural-language titles with report-scoped aliases. Exact dates, retained model names, token values, relationships, and replay sequences remain. Non-anonymized dashboards additionally show original names and exact usage for models folded into the chart’s Other color slot; anonymized exports omit these overflow names. Router-resolved backend names can reveal local routing configuration. This is pseudonymization, not guaranteed anonymity.
Before sharing a report:
./run dashboard --anonymize and confirm the file is dashboard-anonymized.html, not an older regular dashboard.htmlRead the full data and privacy guide.
--source (auto), every readable registered source across Claude Code, Gemini CLI, Codex, OpenCode, and Antigravity is enabled by path/permission checks without opening logs; explicit --source filters restrict discovery to the named sources.os.fchmod, cross-API safe-read checks compare creation timestamps (birth time) where supported while macOS and Linux keep full ctime checks, and Codex .zst archives stream through a writer thread on Windows. Cross-platform CI (Windows, macOS, Linux) and browser runtime suites (Chromium, Firefox, WebKit) pass.--lang en|zh, defaulting to your system locale; the interactive dashboard has its own in-page language switch../run serve --open for ongoing updates.No logs found? Run ./run doctor to inspect auto-discovered and skipped sources. To focus on a single tool, try ./run day --source gemini or ./run day --source antigravity. To explore without any local logs, run ./run demo --open; an installed checkout can use tokens demo --open.
Dashboard numbers do not change? ./run dashboard creates an offline snapshot. Use ./run serve --open for live updates.
Collection is incomplete, or totals seem too low? Check log readability and the collection limits before retrying. A failed refresh is not proof of zero usage: live mode can still show an older successful snapshot. --no-cache bypasses the record cache but does not remove safety limits. Do not delete logs or old caches to force a successful result, and never attach raw logs to a public issue. Synthetic regression tests verify parser behavior, not the amount missing from any real history; updating source code also does not restart a running service.
Browser did not open? Command still prints generated path or local URL. Open it manually.
More answers are in the FAQ.
Node.js 22 or newer is needed only for development checks, not to use the CLI or dashboard.
python -m pip install -e .
python -m unittest discover -s tests -v
python -m compileall -q src tests
node --check src/tokens_cli/dashboard_assets/dashboard.js
node --check docs/assets/site.js
Suite covers readers, cache invalidation, packaging, CLI validation, pseudonymization, dashboard contracts, documentation links, accessibility, privacy assertions, and loopback live updates.
Bug reports and focused pull requests are welcome. Start with CONTRIBUTING.md, and use synthetic records when reproducing a problem.
For vulnerabilities or privacy issues, follow SECURITY.md rather than opening a public issue. Never include raw logs or an unreviewed generated dashboard.
If tokens helps, a star makes it easier for other local-first AI tool users to find. Real platform feedback and bug reports matter even more.
GitHub checked 208h ago - refresh overdue. Recently viewed repositories target hourly refresh.
Find a documented setup for your client. No sign-in, installation, or tool execution.
If this MCP is also published on mcpchannel.ai, you can subscribe from Browse and use the gateway config there instead.