Docs Track cost
View as Markdown

Track cost and tokens

Tokens and cost per session, agent, model, repo and day, your most expensive sessions, and where each number comes from.

coding.sh reads the token counts that any AI agent records, turns them into cost, and keeps both with each session.

Before you start

  • coding.sh is installed and has sessions (Quickstart).
  • To count sessions from before you installed, run coding.sh ingest --backfill --since 30d once.

1. See totals

coding.sh usage --since 7d
output
AGENT             SESSIONS  TURNS  TOKENS  OUTPUT  TOK/TURN  CACHE READ  COST
claude-code       29        108    9.8M    86.9k   6899      93%         ~$6.92
codex             14        38     4.0M    52.4k   26.1k     76%         ~$2.08
opencode          5         5      1.1M    8542    26.5k     89%         ~$0.7937
coding-sh-triage  8         8      13.4k   221     1679      0%          ~$0.0095
  ~ = includes cost estimated from tokens × list price (no reported cost).
  Cache breaks: 32, 349.9k prompt tokens billed again (~$0.5240 extra). Causes per session: coding.sh show <id>.

coding-sh-triage is an SDK app; its rows sit next to the coding agents. --since defaults to 30d. -a codex keeps one agent, --repo keeps one repo, and --where takes any query.

2. Find the most expensive sessions

coding.sh sessions --where 'sort:-cost limit:5'
output
ID                                    AGENT        STARTED       DURATION  TURNS  TOOLS  TITLE
e2ac1139-922a-46bd-8350-bcce0f43da68  claude-code  Nov 5 02:36   3m41s     4      11     Stream large blobs instead of buffering them
842f85fe-a932-4e47-8ed2-de9b968eaa72  claude-code  Nov 8 18:53   4m01s     3      11     Fix the flaky hook test on Windows
c9adf6ea-3327-47ed-8b99-62f696ca7bc7  claude-code  Nov 7 21:33   4m25s     3      11     Handle an empty spool in ingest
ea916f85-7248-4f70-8159-52d28269c6c5  claude-code  Nov 6 21:22   3m24s     5      11     Fix the N+1 query for subagents
4b3edd8a-56c9-4cb5-83d4-213c0706f973  claude-code  Nov 10 02:08  2m35s     4      6      Add a --json flag to coding.sh show

The list has no cost column. To see the figures, ask for JSON:

coding.sh sessions --where 'sort:-cost limit:5' --json --fields id,title,stats.usage.costUsd

usage --json also carries the five biggest sessions of the window in topSessions, ranked by cost when any session has one, else by output tokens (topSessionsRankedBy says which).

Narrow the list with the same query: agent:codex, repo:coding-sh, since:24h or cost>$0.25. Subagents are left out unless you pass --subagents.

The session list in the viewer, newest first, with agent, tokens and cost per row
coding.sh ui: the session list

3. Open one

coding.sh show e2ac1139
output
Tokens       in 47 out 5.2k cache 547k $0.3823 (estimated)
Cost split   cache read 43% $0.1641  cache write 37% $0.1401  in 0% $0.0001  out 20% $0.0780
Cache breaks 1: 2.9k prompt tokens billed again, $0.0100 extra (other 1)

The Tokens line holds input, output, cache reads and cost. Cost split divides the estimate by token type (Cost by token type). Each model call below it shows its own cost, with est when it is an estimate. Long sessions usually spend their tokens re-reading context: look for a high cache-read share, a compaction flag and repeated tool calls. coding.sh ui opens the same session as a timeline.

4. Split by agent, model, repo or day

coding.sh usage --since 7d --by model
output
MODEL              SESSIONS  TURNS  TOKENS  OUTPUT  TOK/TURN  CACHE READ  COST
claude-sonnet-4-6  28        99     9.7M    84.9k   8009      93%         ~$6.51
gpt-5              14        38     4.0M    52.4k   26.1k     76%         ~$2.08
claude-opus-4-8    4         13     1.1M    9773    5796      94%         ~$1.17
claude-haiku-4-5   5         4      74.0k   932     4180      60%         ~$0.0404
gpt-5-mini         5         5      6079    109     1216      0%          ~$0.0017
--byOne row per
agentAgent or app (the default)
modelMain model
agent-modelAgent and model pair
repoRepo root
dayLocal day, newest first
mcpMCP server, by the calls the agent made to it
skillSkill tag (skill:<name>)
subagentSubagent type, over child sessions only

Cost by MCP server, skill or subagent

--by mcp, --by skill and --by subagent attribute cost to what a session used. A line under the table says how each column is attributed, and each --json row has "basis": "attributed".

coding.sh usage --since 7d --by mcp
output
SERVER  CALLS  FAILED  RESULT  TOKENS  COST
docs    1      1       32 B    ~8      ~<$0.0001
GroupWhat a row shows
mcpThe calls to one server, the failed ones, and the bytes the calls returned. TOKENS is the token count the source stored, else the bytes / 4, marked ~. COST is those tokens at the input price of the session's model, so it is always an estimate. A ≥ on RESULT means some results were clipped in the index and their full size is not known.
skillThe sessions tagged with one skill, with their whole tokens and cost. A session with two skills counts in both rows; the line under the table gives the total, and --json has "rowsOverlap": true.
subagentChild sessions of one subagent type (unnamed when the agent recorded none), with their count, tokens, cost and median duration. The parents' own cost is left out, and so is a T3 Code thread's switch to another agent.

--cache and --baseline work with the other groups only; with these three they exit 2.

Where cost comes from

Transcripts and most OpenTelemetry spans carry tokens, not dollars. Each model call's cost comes from the first of these that exists:

  1. Billed. The bill from an LLM gateway, after coding.sh gateway enrich (LLM gateways).
  2. Provider-reported. A cost the agent or app records: Claude Code runs that coding.sh starts in evals and experiments (total_cost_usd), OpenCode, Pi, or a span with gen_ai.usage.cost or cost_usd.
  3. Estimate. Each kind of token times the model's list price, marked ~. Only whole token counts from 0 to 2^53 - 1 are priced.

A model with no price keeps no cost, never $0. usage names it under the table, with the fix: a [prices."<model>"] table in config.toml (Configuration). On a flat subscription, an estimate is what the same tokens cost at API list prices, not what you paid.

Which agents record tokens
AgentTokens
SDK and OpenTelemetry appsEvery model call the app traces
Claude Code, Codex, OpenCode, Pi, Factory Droid, Amp, T3 CodeEvery session
Antigravity CLI, Goose, GitHub Copilot CLIFrom their history files, imported by coding.sh ingest --backfill; their hooks carry none
Cursor CLINone, so no cost either
coding.sh run -- <cmd>None, except Aider's token and cost lines in eval runs

When prices change, estimates refresh on their own. To recompute them now:

coding.sh usage --since 7d --reprice

It prints Repriced N model calls in M sessions on stderr, then the table.

Rates, tiers and Claude Code's own tally

The price table covers current Claude, OpenAI, Gemini and common open models. A model with no row is priced like its nearest sibling in the same family and major version, shown in payload.pricedAs. Antigravity's -orchestrator models are priced as the Gemini 4 model they run. Each call is priced at the rate it ran at:

RatePrice
Long contextA prompt over OpenAI 272K, Gemini Pro 200K, Haiku 5.5 100K or Sonnet 4.5 and 4 (1M beta) 200K tokens
BatchHalf price at every provider
OpenAI FlexHalf price (GPT-6.2 has none)
OpenAI Fast (once called Priority)About 2x
Gemini Priority1.8x
Claude fast modeIts own rates
Anthropic Priority TierStandard rates: it is a commitment, not a per-token price
Claude cache writes1.25x input for the 5-minute cache, 2x for the 1-hour cache
US-only inference1.1x on every token type for Claude 4.6 and later, on top of any other rate

Long context is decided per call, so one long call does not reprice the session. Claude 4.6 and later have no long-context surcharge. Codex rollouts record no tier, so their calls get standard rates.

A call priced at another rate says so in payload.priceTier (batch, flex, long-context, or a mix such as batch+long-context). Totals by tier are in estimatedCostByTier.

Claude Code also keeps its own tally at the end of its transcript. A backfill stores it on session.end as payload.reportedUsage. It is never added to the session's cost; compare the two to check your prices.

Prompt cache health

coding.sh usage --since 7d --cache shows cache hit rate, reads, writes, breaks and the cost of each break per agent; coding.sh cache doctor grades it and lists the causes.

output
AGENT        SESSIONS  CACHED  READ    WRITE   R:W      BREAKS  WASTE
claude-code  29        93%     9.0M    657.6k  13.71:1  13      ~$0.1808
codex        14        76%     3.0M    0       -        18      ~$0.3305
opencode     5         89%     979.4k  0       -        1       ~$0.0128

A break is a model call whose cached prompt prefix was gone, so the prompt was billed again. To find the worst sessions: coding.sh sessions --where 'cache.breaks>0 sort:-cache.cost'.

Cost by token type

usage --cache splits the estimate into cache reads, cache writes, uncached input and output, on a line under the table:

output
Estimated cost by token type: cache reads ~$4.21 (58%), cache writes ~$1.73 (24%), uncached input ~$0.2400 (3%), output ~$1.08 (15%); ~$7.26 in all. Not split by token type: $0.5000 reported or billed.

Each model call's estimate is split when it is priced, at the rates of the estimate: tiers, long context and 1-hour cache writes included. A call's parts add up to its estimate.

Reported and billed costs have no split, and neither has an estimate stored without one. The line names both apart, so the split never claims more than the estimate. In show, the row is Est. split when part of the session's cost was reported or billed.

usage --json and the MCP usage tool carry the split in each row and in the total (not with --by mcp, skill or subagent):

FieldMeaning
estimatedCostByTokenTypeUSD per part (cacheRead, cacheWrite, input, output), to 4 decimals, adding up to the estimate less its unsplit part
estimatedCostShareByTokenTypeEach part's share of the split, to 3 decimals, adding up to 1
estimatedCostUnsplitUsdThe part of the estimate stored without a split

A session keeps its split in stats.usage.estimatedCostByTokenType, and each model call in payload.costByTokenType (API reference). Estimates stored by an older coding.sh get their split when estimates refresh on their own, or now with coding.sh usage --reprice, on a Postgres or ClickHouse store too. A row with no estimate has no split, never $0.

Set a budget

coding.sh budget set day 20                  # every session, per local day
coding.sh budget set week 50 --agent codex   # one agent, per week from Monday
coding.sh budget set month 200 --repo .      # one repo (a path or a repo name), per calendar month
coding.sh budget status

Spend is the estimated cost of the sessions that started in the current period, subagents included: the same total as coding.sh usage over that window with the budget's --agent and --repo. A repo budget counts the sessions coding.sh sessions --repo lists.

budget status shows spend, limit, percent and next reset, or - and a warning for a budget it can't read (exit code 1). Setting the same period and scope again changes the limit. budget list and budget rm <id> manage budgets.json in the data folder.

A budget for one user, model or project

coding.sh budget set day 5 --where 'user:alice'

--where takes the query language. Spend counts the sessions it matches and their subagents. The status line counts only day budgets on session keys.

The status line adds budget 82% once the highest budget passes 80%.

coding.sh proxy --enforce-budget answers 429 to a call a budget over its limit applies to, and the call never goes upstream. It ignores --repo and --where budgets. Log every model call with the proxy says which budgets it can match and what the 429 holds.

Read the result

MarkMeans
~$6.92Part of the figure is an estimate at list price.
≥$1.20A lower bound: some sessions in the row have tokens but no price.
-No session in the row has a price.
estThis model call's cost is an estimate (show).
(estimated)The session's cost includes an estimate (show).
estimatedCostUsdThe estimated part, in --json and the API.
TURNSUser turns of top-level sessions.
TOK/TURNInput, output and cache-write tokens per turn, top-level sessions only.
CACHE READCache reads as a share of all prompt tokens.

If something goes wrong

SymptomCheck
No COST columnNo session in the window has a price. Look for model names under the table and add [prices."<model>"].
An agent shows tokens but - for costIts model has no price. Add one, then run coding.sh usage --reprice.
An agent shows no tokensSome agents record none in their hooks; see "Which agents record tokens" above. Run coding.sh ingest --backfill to read their history files.
Totals look lowSessions from before you installed are missing. Run coding.sh ingest --backfill --since 30d.
The cost differs from your invoiceIt is an estimate at list price. Route calls through a gateway and run coding.sh gateway enrich for billed cost.

Next steps