opencode-tokenstats
See where your OpenCode tokens and cost actually go.
Local-first CLI for session analytics, model cost breakdowns, tool usage, and exportable reports.
opencode-tokenstats reads OpenCode session data and turns it into useful summaries:
- token composition: input, output, reasoning, cache read/write
- costs by model: API cost when present, estimates when needed
- tool usage: top tools, MCP servers, component families, OpenCode core usage
- period reports: daily, weekly, monthly, custom range, lifetime
- machine output: JSON or Markdown for downstream automation
It is built for one job: make OpenCode usage legible without Grafana, proxies, or extra infra.
Why this exists
OpenCode already has the raw data. This project makes it readable.
- No dashboard stack to deploy
- No data leaving your machine in local mode
- No wrapper around OpenCode
- Fast enough for daily use
- Useful for both humans and scripts
Install
From PyPI
pip install opencode-tokenstats
octoken --help
From source
git clone git@github.com:kecsap/opencode-tokenstats.git
cd opencode-tokenstats
pip install -e .[dev]
octoken --help
Run without installing
PYTHONPATH=src python -m opencode_tokenstats.cli --help
PYTHONPATH=src python -m opencode_tokenstats.cli --mode local health
PYTHONPATH=src python -m opencode_tokenstats.cli --mode api health
Quick start
# local mode is the default
octoken status
octoken daily
octoken weekly
# inspect one session
octoken session --session-id <session-id>
# export machine-readable output
octoken json --period daily --format json
# compare read-only local query strategies
octoken local-query-benchmark --period lifetime
# override local period-query workers for reports
octoken --local-query-workers 4 weekly
Common flows
# API-backed checks
octoken --mode api health
octoken --mode api weekly
# explicit time window
octoken range --from-date 2026-05-01 --to-date 2026-05-07
# warm tokenizer caches up front
octoken tokenizer-warmup --pair local:qwen3.6-27b --pair openai:gpt-5.3-codex
What you get
The report focuses on the stuff that matters when AI usage gets expensive or noisy:
- Period Summary for totals and high-level usage
- Token Composition to separate productive output from context overhead
- Model Costs to see where spend concentrates
Model Costs shows actual API charges separately from local estimates. Exact zero
currency values display as -; non-zero values below one cent display as
<0.01. The footer defines only markers present in displayed rows: * generic fallback estimate marks rows made entirely from generic fallback rates; † hosted-market estimation marks projected or cross-provider hosted-market
amounts. These estimates are counterfactual pricing, not money spent.
Mixed-basis rows have no * marker.
- Top Tools to spot tool-heavy sessions
- Component Contribution to understand MCP/skill/subagent families
- OpenCode Contribution to measure built-in tool overhead
- MCP Servers to isolate external tool usage
- By Activity / Top Sessions for period dashboards
- Period Trends for correlated token usage, lines changed, and tokens per changed LOC
Period Summary Sessions counts sessions matching the selected time window,
-sf session-root filter, and active -sm model filter. It does not require
Git mapping or timestamped telemetry. The Sessions chart is narrower: it only
uses sessions with Git history and timestamped telemetry, so its count may
differ from Period Summary.
If you know CodeBurn, the goal is similar: make AI usage visible. This project is narrower and lazier on purpose: OpenCode-first, simple CLI, no extra stack.
Commands
| Command |
What it does |
health |
Check data source health, tokenizer, and compatibility |
status |
Current mode, session count, latest session |
session |
Canonical summary for one session |
daily |
Aggregate last 24 hours |
weekly |
Aggregate last 7 days |
month [month] |
Aggregate last 30 days or a named month |
range --from-date --to-date |
Aggregate an explicit date window |
lifetime |
Aggregate all sessions |
| `json --period ... --format json |
md` |
local-query-benchmark --period ... |
Compare read-only 1/2/4/8 local query strategies |
tokenizer-warmup |
Preload tokenizer caches |
pricing status |
Inspect ledger records, Fast aliases, and coverage gaps |
pricing import <source> --target <path> |
Merge reviewed dated records into the ledger |
pricing refresh --target <path> |
Propose dated records from the official OpenAI pricing page |
pricing snapshot --target <path> |
Preview or write the current all-provider models.dev snapshot |
pricing backfill <manifest> --target <path> |
Propose dated records from pinned models.dev Git revisions |
Global options
--mode [local|api]
--timeout <seconds>
--retries <count>
--no-warmup
--model-alias-file <path>
-caf/--component-alias-file <path>
--session-filter <root1,root2,...>
--loc-scope code|all (default: code)
--loc-exclude <pattern1,pattern2,...>
--local-query-workers auto|1|N (default: auto)
Local period and lifetime reports keep one query for small collections. With the
fixed auto policy, collections of 1,800 or more session IDs use four concurrent
session-ID buckets. Every bucket contains at most 900 IDs, and workers never exceed
eight. Use --local-query-workers 1 to force sequential bounded buckets for large
collections (<=900 IDs still use one query), or
N to choose another bounded worker count. local-query-benchmark reads the local
database, compares 1/2/4/8 workers, prints a recommendation, and never writes
benchmark results, configuration, or database state.
Period reports show three fixed-width aggregate trend charts when selected sessions map
to Git repositories and have timestamped token telemetry. Trend points also include
active unique session counts per bucket. Git churn counts added plus deleted lines in
HEAD history; the report also shows signed net LOC. Sessions without both sources are
excluded from the charts, while the normal report totals are unchanged.
Local mode vs API mode
Local mode
- reads OpenCode SQLite data directly
- default mode
- fastest path for local analytics
API mode
- talks to the OpenCode API
- useful when API telemetry is the source of truth
- good for compatibility and remote checks
Default base URL: http://127.0.0.1:4096
Model aliases
Use models.conf to merge model variants under one label and mark local models as zero-cost:
gpt-unified = azure/gpt-5.4 openai/gpt-5.4
claude-pro = anthropic/claude-sonnet-4
@local myollama/* myllamacpp/*
@local *qwen36*
# Map local model IDs to hosted catalog IDs when pricing is available.
@market-model qwen3.8-27b* = openai/qwen3.8-27b
@cloud-equivalent qwen3.8-27b = openai/qwen3.8-27b
@market-model rules are authoritative for local-model pricing estimates.
Exact sources win; otherwise the most-specific wildcard wins, then the later
rule. Matching ignores case and separators in the final model-ID segment. If
an explicit market target is unavailable in the pricing ledger, its
@cloud-equivalent rule is tried, then the generic fallback is used; automatic
matching is not retried. These rules do not change aliases, @local
classification, actual costs, or report aggregation.
Load order:
--model-alias-file
OPTOKEN_MODEL_ALIAS_FILE
./models.conf
Component aliases
Use components.conf to merge configured skill, subagent, and tool names under one
canonical Component Contribution group in session and period reports:
# canonical = alias1,alias2
make-suite = make-plan, make-implement, make_test
lean-ctx = lean-ctx_ctx_read, lean-ctx_ctx_search
- Rules match exact original component names case-insensitively; wildcards are not supported.
- Explicit aliases override automatic grouping (skill/subagent prefix matching). Components
without an alias keep the current grouping behavior.
- Automatic subagent-to-skill matching in period and JSON reports works across all
selected sessions in the same root directory: a subagent matches a skill when its
name starts with the skill name (case-insensitive, no separator required), and the
longest matching skill wins. Candidates come only from available and invoked skill
rows of the report's selected sessions, so date and session filters apply. Single
session reports match within the session only, using the same case-insensitive
longest-prefix rule. Explicit aliases always take precedence over automatic matching.
- When a skill's own name carries an explicit alias, prefix-matched subagents inherit
the skill's canonical group, so the skill and its matched subagents aggregate
together as
mixed in session and period/JSON reports.
- Configured names merge across component types and across sessions in period reports.
Merged rows with different component types are shown as
mixed.
- Original component names and types stay intact in detail data and in the JSON
components[].component_group output. Top Tools and MCP Servers output is unchanged.
- Repeated rules for the same canonical label combine their aliases. Malformed rules
(missing
=, empty canonical label, empty alias list, wildcard) and aliases assigned to
two different canonical labels fail with a clear error.
Load order:
-caf/--component-alias-file
OPTOKEN_COMPONENT_ALIAS_FILE
./components.conf
Pricing ledger
Report costs come from a tracked historical ledger (src/opencode_tokenstats/data/pricing-history.json), not from live price lookups. Each record pins a rate to an effective period and the source where it was observed, so historical rates stay reviewable and reproducible. Ledger records can come from official provider pricing or models.dev catalog observations; official-provider records take precedence when both cover the same model and period.
Maintaining rates
# review what is active, retired, and missing
octoken pricing status
# import reviewed dated records from a ledger-format JSON file
octoken pricing import reviewed-rates.json --target my-ledger.json --yes
# fetch the official OpenAI pricing page and propose dated records
octoken pricing refresh --effective-from 2026-09-18 --target my-ledger.json --yes
# collect the current all-provider models.dev catalog (preview unless --yes)
octoken pricing snapshot --target my-ledger.json --yes
# reconstruct historical records from reviewed, pinned models.dev revisions
octoken pricing backfill models-dev-history.json --target my-ledger.json --yes
pricing status lists every record with its status (active/retired), effective period, source URL, retrieval time, and confidence, plus Fast aliases and coverage gaps. --ledger points it at any ledger file.
import, refresh, and backfill are preview-only unless you pass --yes; writes always go to the explicit --target path, never to the bundled ledger. snapshot also previews unless --yes is passed.
snapshot fetches the current models.dev catalog, records its URL, retrieval time, catalog revision, and source.kind: "models.dev", then validates the complete schema before writing. It describes current catalog observations, not historical prices.
- A failed fetch or validation leaves the ledger unchanged.
refresh only accepts official OpenAI https URLs (openai.com or *.openai.com); no third-party scrapers are supported. It parses Standard and Fast model-token tables, including input-only embedding token rates in Specialized tables. Batch, Flex, modality-specific, fine-tuning, and tool pricing are excluded. - cache cells are recorded as 0.0; embedding output - means no billable output tokens and is recorded as 0.0. Other missing output prices are rejected. --effective-from overrides the default retrieval timestamp; otherwise proposed records use exact retrieval time.
backfill requires a JSON list (or {"revisions": [...]}) of { "revision": "<40-char SHA>", "effective_from": "YYYY-MM-DD" } entries. It is preview-only without --yes, and each catalog is fetched at its pinned revision.
Merge rules
- A record's identity is
provider + model + service_profile; a model ID ending in -fast gets its own fast record, all others are standard.
- Updates are append-only: a new rate closes the open record for that identity at the new
effective_from and adds a new record. Existing history is never rewritten or deleted.
- A proposed record supersedes an open one only when their rates differ; identical rates are reported as
unchanged.
- Models missing from a proposal are never retired.
- A proposed
effective_from must start after the open record's start, or the command fails without writing.