How to read Claude Code token usage from JSONL transcripts
To read Claude Code token usage from JSONL transcripts, you only need files already on your disk. Each assistant line can carry a usage block, but one response often spans several lines. On one of our machines, over the last 7 days of transcripts, summing every line overstated output tokens 2.4x. Read the assistant lines, count each message once and include subagent files. The jq recipe below does all three.
Last updated
Key points
- Session files live under
~/.claude/projects/, with subagent transcripts in nestedsubagentsfolders, so search recursively. - On one of our machines, over the last 7 days of transcripts, there were about 2.05 usage lines per message, so count each
message.idonce. - Thinking tokens are part of output tokens, and cache reads and writes are separate from input. Totals show what the files record, which may differ from a bill.
Where Claude Code stores its JSONL files
Sessions are written to ~/.claude/projects/<project>/<session-uuid>.jsonl. <project> is your working directory path with non-alphanumeric characters replaced by -, so /Users/you/src/app becomes -Users-you-src-app. Names over 200 characters are cut to 200, plus a hash of the full path.
If you set CLAUDE_CONFIG_DIR, use $CLAUDE_CONFIG_DIR/projects in the commands below.
Claude Code deletes transcripts older than cleanupPeriodDays (30 by default), so raise it before you need older history. The files are plaintext, protected only by OS file permissions.
Claude Code JSONL format: the usage fields
Token counts are on lines with type set to assistant, inside message, next to message.id and message.model. These are the fields to read.
| Field in message.usage | What it counts |
|---|---|
input_tokens | Input not read from or written to the cache |
cache_creation_input_tokens | Input written to the cache |
cache_creation.ephemeral_1h_input_tokens | The one-hour part of cache writes |
cache_read_input_tokens | Input served from the cache |
output_tokens | Output for the response |
output_tokens_details.thinking_tokens | Internal reasoning, already inside output: never add it |
Lines with model <synthetic> are local notices and involve no model call.
Anthropic's sessions documentation says "The entry format is internal to Claude Code and changes between versions," and that scripts parsing these files "can break on any release." After an upgrade, recheck the recipe against a session you know.
Count each message.id once
One API response is normally written as several lines, one per content block. Each repeats the same id and normally the same usage (some older subagent files differ, see below). Anthropic's Agent SDK documentation describes messages sharing an ID during parallel tool use and says to "skip duplicates to avoid inflated totals."
The line and overstatement figures above come from one machine and one week, so measure your own. In the recipe's output, lines minus messages is the number of repeated copies, and naive_output minus output is the output tokens a plain sum counts more than once.
A jq recipe for Claude Code token usage from JSONL
Install jq, then run this in bash or zsh:
find -L ~/.claude/projects -name '*.jsonl' -mtime -7 -exec cat {} + \
| jq -cR 'fromjson? | select(.type == "assistant" and .message.usage != null)
| select((.message.model // "<") | startswith("<") | not)
| {id: (.message.id // .requestId), model: .message.model, u: .message.usage}' \
| jq -s '{lines: length,
naive_output: (map(.u.output_tokens) | add),
messages: (unique_by(.id) | length),
output: (unique_by(.id) | map(.u.output_tokens) | add),
input: (unique_by(.id) | map(.u.input_tokens) | add),
cache_read: (unique_by(.id) | map(.u.cache_read_input_tokens) | add),
cache_write: (unique_by(.id) | map(.u.cache_creation_input_tokens) | add),
cache_write_1h: (unique_by(.id) | map(.u.cache_creation.ephemeral_1h_input_tokens // 0) | add)}'The pipeline works in four steps:
find -Lfollows symlinks, searches every depth and selects files by modification time (-mtime -7). A resumed older session brings its old lines into the window.fromjson?parses each line and silently drops any that fail.- The
selectcalls keep assistant lines with usage and drop lines with no model or a model starting with<. The ID falls back torequestId. jq -sreads everything into one array, andunique_by(.id)keeps one copy of each ID.
Turn the output into a token usage report
The recipe prints one JSON object. Its keys form a small report for the files you selected.
| Key | Meaning |
|---|---|
lines | Usage lines after filtering, with repeats |
naive_output | Output summed over every line |
messages | Distinct IDs |
output | Output, one copy per ID, thinking included |
input | Input, one copy per ID, cache excluded |
cache_read | Input served from the cache |
cache_write | Input written to the cache, one-hour part included |
cache_write_1h | One-hour part of cache_write: do not add |
The recipe doesn't group by model or session, or sum thinking tokens. For cost, apply the rates on Anthropic's pricing page. Any dollar figure you get this way is ESTIMATED, not an invoice. Claude Code's /usage is a useful cross-check, though its figures are also approximate and computed from local session history.
Include subagent and workflow files
Subagents write to <session-uuid>/subagents/agent-<id>.jsonl. Workflow agents write under subagents/workflows/<wf>/, a layout we observed but did not find in the official pages we read. Anthropic's documentation says every subagent "sends its own requests on top of the main conversation's," so their tokens count.
A non-recursive glob such as ~/.claude/projects/*/*.jsonl misses these files. To check that the recipe finds them, run its find command alone, with -exec cat {} + replaced by -print, and look for paths containing /subagents/.
GitHub issue reports describe subagent transcripts whose first copy of a message held a partial output_tokens, with the final count on a later copy. A maintainer closed them as fixed in Claude Code 2.1.307, which we have not verified. The recipe keeps one copy per ID without picking the largest, so it may undercount output in files from affected versions.
Handle malformed lines without losing data
A line can be unparseable. Over the last 7 days of transcripts on one of our machines, a plain jq run aborted on one malformed line. Piped in a shell, that truncates the result without an obvious failure in the totals. fromjson? skips the bad line and continues, but the skipped line isn't counted.
In your own scripts, run set -o pipefail so a failure at any stage shows in the pipeline's exit status, and check that status before you trust a total.
Read the cache fields separately
Total input is input_tokens plus cache read plus cache creation. Five-minute and one-hour writes are both inside cache creation, and Anthropic prices them differently, which is why the recipe reports cache_write_1h.
A large cache_read beside a small input is no error, since they are separate buckets. The glossary defines cache read tokens versus cache creation tokens.
How accurate is ccusage, or your own total?
Treat both as estimates. ccusage is a local reader for Claude Code logs, and its docs say costs are estimates that may not reflect actual billing. We have not tested its totals and don't claim they are wrong. Its issue tracker shows the dedupe logic changing during 2026.
We'd use jq to audit a single number, because every step is visible, and ccusage for ready daily or session reports. When two totals differ, check these in order:
- The tool version and its dedupe rule.
- The date window (
-mtime -7selects whole files). - Which copy of each
message.idis kept: first, last or largest. - Whether subagent files are included.
- The config directory. ccusage also checks
~/.config/claude/projects; the recipe does not.
Your own output total has a further limit. Anthropic's Agent SDK documentation calls per-step output_tokens a placeholder, reported before the response was generated. That page covers the SDK message stream, so we can't say whether transcript lines carry final counts. Don't treat the total as billing truth.
For dollar figures, check the basis first. A SUBSCRIPTION figure is an API-equivalent estimate and was never invoiced. The glossary's cost basis entry defines REPORTED, ESTIMATED and SUBSCRIPTION.
What AgentsTrack automates
AgentsTrack's open-source collector reads the session files Claude Code writes, and the dashboard shows usage and spend by cost basis. Install it with npm i -g @agentstrack/collector, then run agentstrack login and agentstrack start (Node 24 or newer). Of its three privacy modes, analytics (the default) uploads a title, usually the prompt's first line, and secret-redacted commands; metadata drops the title and reduces each command to its binary name. The documentation covers those and full. The organization setting is a ceiling, never a floor. To see your own sessions, start a 14-day Pro trial; onboarding gives you the key the collector asks for.
Read on
Check it against your own sessions
14 days of Pro, no card. The collector is open source, and a dry run prints exactly what it would upload.