tokmeter

module
v0.0.0-...-52276c1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 9, 2026 License: MIT

README

tokmeter

Exact token and cost accounting for Claude Code. One Go binary (no cgo, SQLite inside) that reads every API request Claude Code made, prices it per token type and per model, and shows the result as a table, JSON, or a live web page.

Dashboard, dark theme

Screenshots in this README come from synthetic demo data, not from real usage (see Try it with demo data).

Why

Claude Code does not tell you what a month of work cost, and a plain tokens x price sum is wrong in ways that matter:

  • Cache writes have two prices. A 5-minute cache write and a 1-hour cache write are billed at different rates, and cache reads at a third. Together they are usually most of the bill.
  • Thinking tokens are part of the output tokens. They must be shown, but billed once.
  • One request appears as several transcript lines while it streams. Count lines and you overcount.
  • Subagents, other profiles and scratch directories all spend money, in places a per-project view does not show.
  • Some pricing rules are not published precisely (long-prompt tiers, fast mode, web search). Silent guesses make a total that looks exact and is not.

tokmeter prices every request with the rate card that was valid when it ran, keeps each token type separate, deduplicates by request id, and reconciles its result against the cost_usd Claude Code itself reports in its telemetry. Where the two agree to 1e-6 USD, the pricing is confirmed; where a rule cannot be checked, tokmeter says so instead of assuming. A model without a price is shown as unpriced, never as $0.

Requirements

  • Go 1.25 or newer, to build it.
  • Claude Code, with its transcripts in ~/.claude/projects/ (the default location).
  • Optional: Claude Code OpenTelemetry events as api_request JSON lines in a directory of *.jsonl files, in the format written by ccwatch. They carry Claude Code's own cost_usd, which is what makes reconciliation possible. Without them tokmeter still works; reconcile just has nothing to compare against.
  • git on PATH, to group projects by repository (see Projects).
  • Linux or macOS. Developed and tested on Linux.

Install

go install github.com/toniim/tokmeter/cmd/tokmeter@latest

Or from a checkout:

git clone https://github.com/toniim/tokmeter
cd tokmeter
go build -o tokmeter ./cmd/tokmeter

Either gives you a tokmeter binary (go install puts it in $(go env GOPATH)/bin).

Quick start

tokmeter ingest --backfill     # first run: read every transcript (and OTEL file), fetch prices
tokmeter report                # cost per day, as a table
tokmeter serve                 # web page on http://127.0.0.1:4320, updates live

ingest --backfill prints one line per source, then the number of rows stored:

claudecode-otel        files=112 changed=112 lines=5673 requests=5673 new_rows=112 bad_lines=0
claudecode-transcript  files=204 changed=204 lines=8839 requests=6649 new_rows=6649 bad_lines=0
orphan OTEL events merged: 0
rows in store: 6761
elapsed: 1.948s

Later tokmeter ingest runs read only the bytes added since the last run. tokmeter serve does the same on its own and keeps tailing, so you do not need to run ingest while it is up.

A report grouped by model, per week (--group also takes project, type, agent, profile, session):

$ tokmeter report --by week --group model --tz UTC
      bucket              model  reqs    input   output  thinking*  cache_read     cw_5m     cw_1h  web  cost USD
  ...
  2026-11-02  claude-sonnet-5-5  1081    99057   545216     123292   104268412   1383771   3671271    0   34.2216
  2026-11-02    claude-opus-5-5   454     2932   237123      46024    44469029    562315   1688646    0   29.9687
  2026-11-02   claude-haiku-5-5   112   110113    28408          0     2722079    376575         0    0    0.0995
       total                     6761  1140096  3246564     665759   602639503  10572624  21681518    0  266.5868
* thinking is part of output

Configuration

tokmeter has no required configuration. Precedence is: environment variable, then <state>/config.yaml, then the default.

What Default Override
State directory (database, config, price override) ${XDG_STATE_HOME:-~/.local/state}/tokmeter TOKMETER_STATE=dir
Profiles: Claude Code config directories, each holding projects/ default=~/.claude TOKMETER_PROFILES=name=path,name=path or profiles: in config.yaml
OTEL events directory (*.jsonl) ${XDG_STATE_HOME:-~/.local/state}/ccwatch/otel TOKMETER_OTEL=dir or otel_dir:
Local price override file <state>/prices.yaml TOKMETER_PRICES=file or prices_file:

TOKMETER_PROFILES replaces the profile list from config.yaml (it does not add to it). A leading ~/ in any path is expanded.

<state>/config.yaml:

profiles:
  default: ~/.claude
  work: ~/.config/claude-work
otel_dir: ~/.local/state/ccwatch/otel
prices_file: ~/.local/state/tokmeter/prices.yaml

Command flags are listed in the CLI reference. The only flags that matter day to day are serve --addr (listen address, default 127.0.0.1:4320) and --tz (time zone used for buckets: an IANA name such as Europe/Berlin, or an offset such as +02). Both serve --tz and report --tz default to the machine's local zone.

tokmeter only reads Claude Code and OTEL directories. It never writes to them. Everything it writes is in the state directory.

Data sources and how they are merged

Source Where What it gives
Transcripts <profile>/projects/**/*.jsonl (including <session>/subagents/agent-*.jsonl and their .meta.json) token counts per token type, 5m/1h cache-write split, thinking tokens, web search/fetch counts, model, session, working directory, subagent id and type
OTEL events <otel dir>/*.jsonl, api_request events the same tokens, plus Claude Code's own cost_usd, the request's query_source (main thread, a subagent, session-title generation, ...) and requests that never reach a transcript

How rows are keyed and merged:

  • One row per requestId (fallback: message.id). A request that Claude Code wrote as several transcript lines while streaming counts once, with the largest output count.
  • An OTEL event merges into the transcript row with the same request_id. A row records which sources saw it, so reconcile can tell "transcript only", "OTEL only" and "both".
  • An OTEL event without a request id (older Claude Code versions) is folded into the transcript row with the same session, model and token counts. One that matches nothing stays as its own row.
  • Re-reading is safe. Every file is tracked by inode, size and byte offset, so ingest reads only new bytes, --backfill re-reads from byte 0 and produces the same rows, and a rotated file is read again from the start.
  • A line that is not valid JSON is counted in bad_lines and skipped.

Pricing

Where prices come from
Priority Source Notes
1 Local override (<state>/prices.yaml) wins over everything, USD per 1M tokens
2 LiteLLM model_prices_and_context_window.json Anthropic models, includes the 1-hour cache-write rate, tiers and the fast/US multipliers
3 OpenRouter used when LiteLLM has no valid card; tokmeter prices list flags models where the two disagree

Both public lists are fetched at most once a day (serve checks hourly, ingest on each run, prices update forces it) and stored as versions. The price used for a request is the one effective at the request's timestamp, and its id (price_id) is stored with the row. If a source changes a price, that is a new version; old rows keep the price they were charged at until you run tokmeter reprice. A model that the public lists drop is tombstoned and falls back to the next source. A model with no card at all costs NULL and is listed by ingest and reconcile; it is never priced as zero. A dated id such as claude-haiku-4-5-20251001 also matches the card of the undated name.

Override file (USD per 1M tokens; web_search_per_request, fast_multiplier, us_multiplier and tiers are optional):

models:
  claude-opus-5-5:
    input: 4
    output: 20
    cache_read: 0.2
    cache_write_5m: 5
    cache_write_1h: 8
  claude-haiku-5-5:
    input: 0.1
    output: 0.5
    cache_read: 0.01
    cache_write_5m: 0.125
    cache_write_1h: 0.2
    tiers:
      - above_prompt_tokens: 100000
        input: 0.5
        output: 2.5
        cache_read: 0.05
        cache_write_5m: 0.625
        cache_write_1h: 1
aliases:
  my-proxy-model-id: claude-opus-5-5

After editing the override, or after prices update brought new versions, run tokmeter reprice to recompute stored costs.

The formula

For one request, with the rate card in effect:

cost = input        x input rate
     + output       x output rate          (thinking tokens are inside output: billed once, shown separately)
     + cache_read   x cache read rate
     + cache_write_5m  x 5-minute cache write rate
     + cache_write_1h  x 1-hour cache write rate
     + web_search_requests x price per search

then multiplied by the fast-mode factor when speed is fast and by the US factor when inference_geo is us. If the prompt is larger than a tier threshold, all five token rates are replaced by that tier's rates. The prompt size is input + cache read + cache write 5m + cache write 1h, and "larger" means strictly more than the threshold. Web fetch requests are free.

Which rules are verified
Rule Status Evidence
Per-type rates, with 5m and 1h cache writes priced separately confirmed matched Claude Code's cost_usd on every request that has one (see Accuracy)
Thinking tokens are part of output_tokens, billed once confirmed same
Opus and Sonnet 5.5 have no prompt-size tier confirmed requests with prompts up to several hundred thousand tokens match base rates
Prompt-size tier basis (Haiku 5.5, over 100k) not yet verified no request with both a prompt over 100k and a Claude Code cost was available. The reading above (all prompt tokens, strictly above) is the most likely one
speed: fast multiplier not yet verified no fast request seen
inference_geo: us multiplier not yet verified only global and not_available seen; only the literal us triggers the multiplier
Web search per request not yet verified no request with a search seen
Web fetch is free not yet verified no request with a fetch seen
iterations[] is not added on top of usage not yet verified always a single iteration equal to usage

This is the state when the project was written, from one machine's data. tokmeter reconcile recomputes it from yours: each rule shows how many of your requests exercised it, how many of those had a Claude Code cost to compare with, and how many matched, and moves from "not verified yet" to confirmed (or contradicted, with the likely cause) as evidence appears.

Accuracy

tokmeter reconcile

compares tokmeter's cost with cost_usd for every request that both sources saw:

requests: 6761 (transcript only 1088, OTEL only 112, both 5561)
matched (both sources, priced): 5561; within 1e-06 USD of cost_usd: 5561 (100.0000%)
ours 223.389425 USD vs reference 223.389425 USD; max |diff| 5.551e-17
rules:
  [unverified] prompt-size tier: tier applies when input + cache read + cache write > threshold, all token types at tier rates (exercised 0, ...)
  ...

Each mismatch is classified by re-pricing the request under alternative readings (token counts from OTEL instead of the transcript, tiers off, other tier bases, fast/US/web-search surcharges off) and reporting the first reading that reproduces Claude Code's cost. A mismatch no reading explains is listed as unexplained. reconcile --json has the same data, including up to five example request ids per mismatch class.

Reconciliation card

The output above is from the synthetic demo data, where OTEL costs are generated with the same prices, so 100% means "the plumbing works". On real data the number is the measurement.

CLI reference

tokmeter ingest [--backfill] [--watch] [--no-prices]
tokmeter report [--by hour|day|week|month] [--group model|project|type|agent|profile|session]
                [--since DATE] [--until DATE] [--session ID] [--tz ZONE] [--json]
tokmeter reconcile [--json]
tokmeter serve [--addr 127.0.0.1:4320] [--tz ZONE] [--no-prices]
tokmeter prices update | list [--all] [--json]
tokmeter reprice
Command What it does
ingest Scans all sources from the saved offsets and refreshes prices if the last fetch is over a day old. --backfill re-reads every file from byte 0 (idempotent). --watch keeps running and ingests new lines until Ctrl-C. --no-prices never touches the network. Prints unpriced models, if any.
report Table (or --json) of tokens and cost per bucket. --by sets the bucket (default day); --group splits each bucket (no grouping: one line per bucket); --since / --until take YYYY-MM-DD in --tz, or RFC 3339, and --until is exclusive; --session restricts to one session id; --tz is the zone for buckets (default: local).
reconcile Compares with Claude Code's cost_usd, explains mismatches and shows the status of each pricing rule (see Accuracy).
serve Scans from the saved offsets, tails every source, refreshes prices daily and serves the web page and JSON API. --addr is the listen address, --tz the page's time zone (default: local), --no-prices disables price fetching. Ctrl-C or SIGTERM stops it.
prices update Fetches LiteLLM and OpenRouter now and stores new versions; tells you to reprice if any changed.
prices list The cards in effect, per model and source, USD per 1M tokens, with tiers and a "sources disagree" flag. --all also shows superseded versions; --json for machines.
reprice Recomputes every stored cost with the current prices and override file.

tokmeter help prints the usage. Exit codes: 0 success, 1 error, 2 unknown command.

Web page and JSON API

tokmeter serve --addr 127.0.0.1:4320 --tz Europe/Berlin

The page shows: a range picker (today, 7 days, 30 days, this month, all, custom dates) and bucket size (hour, day, week, month); filters for profile, project, model and agent; tiles for cost, requests, tokens, cache hit ratio and average cost per request; a stacked chart by token type (tokens or cost); a stacked cost chart by model, project, agent or profile; token-type, latest-request, top-project and top-session tables; the price table with source, fetch time and a flag where LiteLLM and OpenRouter disagree; and the reconciliation card with the status of each pricing rule. It updates itself within seconds of a new request (server-sent events, with a 5-second poll as fallback) and follows the system light or dark theme (button to override). The chart library is vendored: the page works offline.

Dashboard, light theme

Project filter On a phone (390 px)
Project dropdown with search Mobile layout, dark theme

The JSON API behind it is plain GET. Common query parameters: range=today|7d|30d|month|all|custom, from and to (YYYY-MM-DD, inclusive, for custom), by=hour|day|week|month, tz, and the filters profile, project, model, agent.

Endpoint Returns
/api/meta filter values with cost, last request time, current time and state (backfilling while the first scan runs, then live)
/api/series?group=type|model|project|agent|profile stacked series per bucket
/api/breakdown?group=type|model|project|agent|profile|session&limit=N totals per group
/api/prices[?all=1] price cards
/api/reconcile the reconcile --json report
/api/recent?limit=N latest requests (up to 200)
/api/events server-sent events: a message whenever new data arrives
curl -s 'http://127.0.0.1:4320/api/breakdown?group=model&range=7d'

Projects

A project is the root of the git repository a request ran in. Each distinct working directory is resolved once with git rev-parse --git-common-dir, so subdirectories and linked worktrees (including those created by tools such as Orca under workspaces/<repo>/<name>) group under the main repository. The answer is cached in the database, so a deleted worktree keeps its group. A path that no longer exists and was never cached falls back to the longest known repository root that prefixes it, then to the workspaces/<repo>/ layout, then to the directory itself. Anything under /tmp, /var/tmp or /dev/shm is the single group (scratch). The raw working directory is kept in the database.

Run as a systemd user service

deploy/tokmeter-serve.service runs tokmeter serve --addr 127.0.0.1:4320 for the default profile. Comments in the file show how to add a second profile and how to open the page to the LAN.

go build -o ~/.local/bin/tokmeter ./cmd/tokmeter
mkdir -p ~/.config/systemd/user
cp deploy/tokmeter-serve.service ~/.config/systemd/user/
systemctl --user daemon-reload
systemctl --user enable --now tokmeter-serve.service
curl -s http://127.0.0.1:4320/api/meta     # "state":"live" once the first scan is done

There is no authentication. The page and API show your projects, session ids and spend. The default listens on loopback only. If you change it to 0.0.0.0 (LAN), everyone who can reach the port can read it; put it behind a firewall or a reverse proxy with authentication.

Keep your history: transcript retention

Claude Code deletes old transcripts (30 days by default, cleanupPeriodDays in ~/.claude/settings.json). tokmeter stores what it has read in its own database, so anything ingested before deletion stays in your reports. Run tokmeter serve (or ingest regularly) so nothing ages out unread, or raise cleanupPeriodDays if you want the raw transcripts for longer.

Try it with demo data

scripts/demo-data writes about 30 days of synthetic usage: two profiles (default, work), several fictional repositories and one worktree, Opus, Sonnet and Haiku 5.5, 5-minute and 1-hour cache writes, subagents, and OTEL events whose cost_usd is computed from the same price cards. Nothing in it is real. It creates tiny empty git repositories under --code-root (default ~/code) so project grouping has something to resolve; delete that directory when you are done.

go run ./scripts/demo-data --out /tmp/tokmeter-demo --code-root ~/demo-code

It prints the export lines to paste. With them set, every command in this README works on the demo data, for example:

export TOKMETER_STATE=/tmp/tokmeter-demo/state
export TOKMETER_PROFILES=default=/tmp/tokmeter-demo/default,work=/tmp/tokmeter-demo/work
export TOKMETER_OTEL=/tmp/tokmeter-demo/otel
export TOKMETER_PRICES=/tmp/tokmeter-demo/prices.yaml
tokmeter ingest --backfill --no-prices
tokmeter serve --addr 127.0.0.1:4322 --tz UTC --no-prices

Note: working directories under /tmp are grouped as (scratch), so keep --code-root outside /tmp (the screenshots here used ~/code). The matches reconcile reports on this data prove the plumbing only, and the rules that need real evidence (tiers, fast mode, web search) are deliberately not exercised, so they stay "not verified yet".

Privacy

tokmeter reads local files only: your Claude Code transcripts and OTEL event files. Nothing from them leaves the machine. The only network traffic is fetching the two public price lists (LiteLLM on raw.githubusercontent.com, OpenRouter on openrouter.ai), a plain GET with no data about you; --no-prices turns it off. The database, config and price versions live in the state directory. The web page loads no external resources.

Uninstall

systemctl --user disable --now tokmeter-serve.service      # if you installed the service
rm -f ~/.config/systemd/user/tokmeter-serve.service ~/.local/bin/tokmeter
systemctl --user daemon-reload
rm -rf ~/.local/state/tokmeter                             # drops the history; skip to keep it

Limitations

  • Prices are public list prices. Enterprise discounts, credits and any rate that differs from LiteLLM/OpenRouter are not seen; use the override file for those. Cost is an estimate of list price unless reconcile says it matches Claude Code's own figure for your usage.
  • Six pricing rules are not verified (see the table).
  • Only Claude Code is read. Other tools that call the API, and usage on claude.ai, are not included.
  • Transcripts Claude Code deleted before tokmeter first read them are gone.
  • The web page has no authentication.
  • OTEL events are read in ccwatch's file layout (*.jsonl of api_request events); other layouts are not supported.
  • Tested on Linux; macOS is expected to work but is untested.

Development

go vet ./...
go test ./...

The tests run on small fixtures in testdata/ and need no network or Claude Code install.

Credits

License

MIT, see LICENSE.

Directories

Path Synopsis
cmd
tokmeter command
Command tokmeter ingests Claude Code usage and prices it exactly.
Command tokmeter ingests Claude Code usage and prices it exactly.
internal
cli
Package cli implements the tokmeter command line.
Package cli implements the tokmeter command line.
config
Package config resolves state paths, profiles and the OTEL directory.
Package config resolves state paths, profiles and the OTEL directory.
ingest
Package ingest wires sources, prices and the store together.
Package ingest wires sources, prices and the store together.
model
Package model holds the source-neutral request record.
Package model holds the source-neutral request record.
prices
Package prices fetches and parses public price lists into pricing.Rates.
Package prices fetches and parses public price lists into pricing.Rates.
pricing
Package pricing turns token counts and a rate card into USD.
Package pricing turns token counts and a rate card into USD.
project
Package project maps the working directory of a request to a project: the root of the git repository it belongs to.
Package project maps the working directory of a request to a project: the root of the git repository it belongs to.
reconcile
Package reconcile compares tokmeter's cost with Claude Code's own cost_usd.
Package reconcile compares tokmeter's cost with Claude Code's own cost_usd.
report
Package report answers usage questions from the hourly aggregate.
Package report answers usage questions from the hourly aggregate.
source
Package source reads request records from log files on disk.
Package source reads request records from log files on disk.
store
Package store is the SQLite (WAL, pure Go) persistence layer.
Package store is the SQLite (WAL, pure Go) persistence layer.
web
Package web serves the JSON API and the embedded page.
Package web serves the JSON API and the embedded page.
scripts
demo-data command
Command demo-data writes synthetic Claude Code transcripts and OTEL events so tokmeter can be tried (and screenshotted) without any real usage data.
Command demo-data writes synthetic Claude Code transcripts and OTEL events so tokmeter can be tried (and screenshotted) without any real usage data.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL