Repository navigation
Token Tracking and Cost
How tokensave measures the tokens it saves, and the commands that report savings, cost, and resource use.
When enabled, the tokensave_metrics line reports estimated baseline (before) and MCP cost (after) for the call. The estimate uses the files associated with the result, caps the baseline according to the type of result, and accounts for request, response, and applicable schema overhead.
Turning the reporting off. The metrics line, together with a sentence in the MCP instructions, asks the agent to report savings to you — which means the model spends output tokens narrating a saving tokensave made on input tokens. Output tokens are the more expensive kind, so if your agent mentions tokensave on nearly every turn, that narration can offset the win (#356). Set report_savings to false in .tokensave/config.json, or the TOKENSAVE_REPORT_SAVINGS environment variable to override it per-run (any value enables it except 0, false, no, off, or empty). Both the metrics line and the instruction disappear; tokensave install likewise stops writing the reporting rule into agent prompt files. Measurement is untouched either way — every call still lands in the savings ledger, so tokensave gain, tokensave list, status and monitor keep reporting exactly as before. The default stays true.
MCP tool calls write an append-only row to ~/.tokensave/global.db (savings_ledger table): the time, the project, the tool name, and the token counts before and after. Inspect with tokensave gain:
tokensave gain # current project, last 30 days
tokensave gain --all # all projects
tokensave gain --history --range 7d
tokensave gain --by-tool # calls and tokens saved per tool
tokensave gain --json--by-tool prints one row per tool name for the selected range and project, most-called first. With --json each row is an object with tool, calls and saved_tokens. It reads the same ledger as the other views, so it counts the same calls; it cannot be combined with --history. The ledger has no session id, so there is no per-session breakdown.
A row is written for each tools/call on the served project that its tool handler answers, including calls with a redundant scalar graph_root. These calls write no row: tokensave_more; calls that select another graph or federate across graphs; calls a server with no default project answers from the client's roots; calls refused before dispatch (an invalid argument, no default project, a branch-drift or strict-mode refusal); and calls whose handler fails. The write is best-effort: if the global database cannot be opened, the row is skipped. The tokensave_metrics line and report_savings do not affect it.
A successful call can add to the call count while contributing zero savings. A status call has no source-read baseline. A lookup can also lack usable file attribution, or its estimated baseline can be equal to or smaller than the cost of the MCP call. The totals describe estimated input-token savings and can differ from provider usage or billing. Use gain --by-tool to identify which tools recorded calls in the selected scope.
Dollar estimates use the existing pricing module (Sonnet input pricing, refreshed daily via LiteLLM).
tokensave cost # 7-day cost summary (default)
tokensave cost today # today only
tokensave cost --by-agent # breakdown by supported agent
tokensave cost --by-model # breakdown by Claude model
tokensave cost --by-task # breakdown by task category (coding, debugging, exploration, ...)
tokensave cost --export json # JSON export to stdout
tokensave cost --export csv # CSV export to stdoutParses Claude Code session transcripts (~/.claude/projects/**/*.jsonl) and prices each API turn with model pricing, reads Pi sessions (~/.pi/agent/sessions/**/*.jsonl) using the cost Pi already reports per message, and ingests Factory Droid session settings in credits. It also reads local GitHub Copilot CLI checkpoints from ~/.copilot/session-state/**/events.jsonl; those checkpoints provide cumulative AIU, not token counts, a USD price, or turn-level data. In cost --by-agent, Copilot's human-readable credits are shown as whole AIU, while JSON and CSV keep the exact nano-AIU value. Copilot's date bucket uses the selected checkpoint timestamp, so a later cumulative checkpoint can move the usage into a later range. Malformed JSONL lines or checkpoint records make Copilot coverage partial; valid non-checkpoint events are ignored. Copilot token fields are currently zero; its USD value is n/a in the table, null in JSON, and blank in CSV. Usage is stored in ~/.tokensave/global.db for fast aggregate queries. Available turn-level session data is classified into one of 13 task categories. Pricing is refreshed from LiteLLM every 24 hours and falls back to an embedded table when offline.
Codex local rollouts (~/.codex/sessions/**/rollout-*.jsonl) provide cumulative
native token totals. Cached input is billed at the cache-read rate; native output
already includes reasoning, so reasoning is not added a second time. USD is an
API-equivalent estimate, not the Codex subscription bill.
AugmentCode sessions (~/.augment/sessions/<uuid>.json) provide cumulative
subAgentCostUsd. This is real USD for subagents only, not the full session
cost; main-agent usage is not sourceable, so Augment coverage is always partial.
Augment spend appears in cost --by-agent, JSON, the monitor, and status/default
cost summaries when in range, but is not assigned to a model or used to infer
token counts. Cached Augment rows are hidden from status and summaries when the
local session source is absent.
Legacy Codex snapshots may contain overcounts. A per-row usage revision allows validated source replay to correct them once, without guessing missing reasoning counts or deleting history. Older or inconsistent source checkpoints cannot replace a newer cached snapshot. Missing logs leave the old estimates intact and coverage partial; those estimates may be overstated, not a known minimum.
Before the first live repair, back up ~/.tokensave/global.db and quiesce old
cost, status and monitor writers. Ensure normal launchers select the updated
runtime. Do not resume an older accounting writer or roll back the runtime
against the repaired database: restore a matching database backup as part of any
old-runtime rollback. Unrelated graph-only MCP clients need not be terminated.
The tokensave status header includes a cost row showing today's spend, 7-day total, and efficiency ratio (tokens saved / total tokens). The tokensave monitor TUI shows a live cost panel alongside the savings feed. At the end of each Claude Code session, the hook_stop handler prints a one-line receipt to the terminal; in Pi, the installed extension does the same through its agent_settled handler.
Task classification categories: Coding, Debugging, Feature Dev, Refactoring, Testing, Exploration, Planning, Delegation, Git Ops, Build/Deploy, Brainstorming, Conversation, General. Classification is deterministic (pattern matching on tool names and Bash commands), requires no LLM calls, and is adapted from AgentSeal/codeburn.
tokensave discover # last 30 days (default)
tokensave discover --since today # today, 7d, 30d, month or all
tokensave discover --json # machine-readable reporttokensave discover reads the same Claude Code turns as tokensave cost and lists turns that a tokensave query could have answered more cheaply. A turn counts only when every tool it used is navigation: Read, Grep, Glob, or a Bash code search. Turns that also edit files or run other commands are left out, so the figures are a lower bound. The Addressable column is the measured size of those tools' results; Recoverable claims half of it.
A Bash command counts as a code search when it is a grep, rg, ag or git grep for one symbol in code: a bare identifier, \bname\b, a declaration such as fn name or class Name, or const/let/var NAME in a JavaScript or TypeScript file. It may be followed by read-only filters such as | head. tokensave classifies the command when it ingests the turn, using the same rules as the Claude Code search hook, and stores only the verdict, never the command text. Pipelines can count as code searches while running unchanged under the search hook.
Bash searches that do not count are listed under Bash searches not counted (excluded_bash_searches in JSON), one line per reason:
| Reason | Meaning |
|---|---|
explicit_opt_out |
The command set TOKENSAVE_DISABLE_GREP_HOOK inline |
compound_command |
The search was chained with other commands, or piped into one that does more than filter |
unsupported_shell_syntax |
Command substitution, redirects or other syntax the classifier does not model |
revision_search |
git grep with an argument that may name a revision |
pattern_too_long |
The pattern is too long for a symbol lookup |
non_symbol_pattern |
A regex or text pattern, not one symbol |
declaration_outside_js_ts |
const/let/var NAME searched outside a JavaScript or TypeScript file |
non_code_target |
The searched paths, globs or type filter are not indexed code |
mixed_with_other_tools |
The search qualified, but the same turn used non-navigation tools |
Bash turns ingested by an earlier version were stored without this classification and are not counted. find and cat navigation is not classified.
tokensave monitorA global TUI that shows MCP tool calls from all projects in real time, via a shared memory-mapped ring buffer at ~/.tokensave/monitor.mmap. Each entry shows the project name, tool name, and token delta. A cost panel at the top shows today's USD spend, savings, efficiency, and top model (refreshed every 30 seconds). When the panel is active, it also shows available local source coverage; Copilot AIU gets its own line when Droid usage is also shown, so the amount remains visible and is never combined with USD totals. Augment subagent spend is shown separately as partial USD because main-agent usage is not sourced.
tokensave memory [--clean]A machine-wide memory report for every tokensave process (MCP servers, syncs, index runs), via a shared memory-mapped table at ~/.tokensave/memory.mmap. Each instance self-samples its RSS best-effort at startup, per MCP tool call, and around the sync/resolution phases, so the report shows current and peak RSS with the phase that produced the peak — the data needed to attribute high memory use (see #253). Rows are flagged alive, dead (an OOM-killed process leaves its peak/phase behind as a forensic record), or orphan (still running but reparented to init). --clean purges dead slots.
PEAK PHASE names the highest sample, so it is only as precise as the sampling. Incremental sync records, in order: sync:extract, sync:resolve:load_nodes, sync:resolve:build_caches, sync:resolve:refs, sync:variants, sync:done. A full index records index:extract, index:resolve:build_caches, index:resolve:refs, index:resolve:done, index:insert, index:done.
Each is recorded after the work it names. They used to be recorded before it, so every sample reported the previous step's RSS under the next step's label — which attributed 73 MiB to the node load that in fact belonged to loading the unresolved references, a step with no sample at all, and pointed a memory investigation at the wrong subsystem for months (#409). If you add a phase, sample after the work, not before it, and add one for any step large enough to hold the peak.
tokensave current-counter # show per-project session counter
tokensave reset-counter # reset the session counter
tokensave status # shows project + global lifetime totals + costtokensave status renders the project index stats, language breakdown, cost row (today / 7d / efficiency), and project + worldwide lifetime totals:
All tokensave users contribute to an anonymous aggregate counter. tokensave status shows both your project total and the worldwide total. The upload sends only a single number (e.g. 4823) with no identifying information. Opt out with tokensave disable-upload-counter, or for one environment with TOKENSAVE_TELEMETRY=off or DO_NOT_TRACK=1 (see Turning telemetry off).
This wiki is generated from docs/guide at commit 87d5911ad29e. Edit the files there in a pull request; direct wiki edits are overwritten.