Skip to content

feat(usage): claude totals are modelUsage, with unattributed and withChildren (#282) - #292

Merged
xxchan merged 1 commit into
mainfrom
feat/claude-model-usage
Oct 9, 2026
Merged

xxchan merged 1 commit into
mainfrom
feat/claude-model-usage

Conversation

@TennyZhuang

@TennyZhuang TennyZhuang commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Closes #282.

Why

A claude Session's usage().total added up each turn's result.usage. claude's own schema (2.1.289) calls that field "MAIN AGENT LOOP ONLY — excludes Task subagent, sidechain, and auxiliary model calls … Prefer modelUsage for token/cost accounting". So a Session that ran subagents or compacted reported far less than it spent. result.modelUsage covers every model call (main loop, Task subagents, sidechains, compaction) and is a running total: each result carries the total so far.

Separately, a host that wanted "everything this session spent" had to sum graph() itself and know, per runtime, whether a parent's figure already includes its children's.

What

  • claude total = modelUsage.
    • usage().total is the latest result.modelUsage, summed over models. input is inputTokens + cacheReadInputTokens + cacheCreationInputTokens, with cacheRead and cacheWrite as before. It is read, never summed.
    • The root's byAgent entry stays the main loop (result.usage).
  • SessionUsage.unattributed?: TokenTotals
    • What total includes that no byAgent entry accounts for: the total less the breakdown, never split by estimate. byAgent plus unattributed sum to total.
    • Absent when the agents account for everything, so a plain claude session still reads { total }.
    • claude subagents get no entry of their own. Only a subagent's first assistant frame carries parent_tool_use_id, and its message.usage is the stream-start value (3 output tokens in the recording), not the final usage. So their spend stays in unattributed.
  • SessionUsage.withChildren?: TokenTotals
    • total plus the total of every session derived from this one in graph() (codex child threads, grok child sessions, OpenCode v2 children), nested ones too, each counted once (a diamond counts its shared child once).
    • Absent when no child session reported usage, and while total is null.
    • usage().seq now covers those child records.
  • Resume baseline.
    • A resumed claude process continues the previous process's modelUsage, and its total_cost_usd too.
    • On a resume only, right after open and before the first turn, the adapter sends get_usage (skip_behaviors: true). Its session.model_usage becomes a per-model baseline, subtracted from every later report the way codex subtracts its re-report.
    • The answer also carries the subscription type, rate-limit windows, credits and behaviors. It is consumed privately like initialize and get_settings, and late duplicates stay private too.
    • Don't know, don't report: on a timeout (the existing 30 s readback bound), an error answer, or an answer without session, the resumed Session's usage events carry context only and usage().total stays null. The answer never fails the open, and new sessions never send it.
  • Robustness.
    • A zeroed crash or startup-error modelUsage ({} on the recorded missing-resume result) never moves the total back.
    • A lower running total is claude resetting it. Its schema says "a mid-session /clear resets the running total". What was counted so far is kept, and counting restarts from zero.
  • Record surface: UsageReport.total?: TokenTotals carries a runtime's own session total on the usage event. The session view folds it the same way usage() does, through one shared helper.
  • Code: claude's token readings are in runtimes/claude/token-usage.ts (main loop plus modelUsage, named like codex's).
  • Recording: sea-trial/record/claude.ts now keeps modelUsage and parent_tool_use_id in scrubbed recordings.
  • Docs:
    • attribution.md: the claude line, the usage constraint (total, unattributed, withChildren, claude's resume baseline), example 7 and the cache table.
    • The claude runtime page: a new "Token totals" section, plus the mapping, resume and subagent paragraphs.
    • record-stream.md, runtime-matrix.md, and the usage() / SessionUsage / UsageReport contract comments.

Example from the recording (claude 2.1.292, haiku): a turn that ran one Task subagent.

{ "total":        { "input": 69147, "output": 1011, "cacheRead": 47627, "cacheWrite": 21484 },
  "byAgent":      [{ "agentPath": [], "tokens": { "input": 43876, "output": 834, "cacheRead": 35315, "cacheWrite": 8543 } }],
  "unattributed": { "input": 25271, "output": 177, "cacheRead": 12312, "cacheWrite": 12941 } }

Release notes

For the next release PR:

  • Added
    • SessionUsage.unattributed: the part of the total no agent entry accounts for (claude's subagents, sidechains, compaction).
    • SessionUsage.withChildren: the total plus every derived child session's, each once.
    • UsageReport.total.
  • Behavior changes
    • claude usage().total grows: it is now claude's modelUsage, which includes subagents and compaction. A host that compared it with summed result.usage will see the difference.
    • A resumed claude Session asks claude get_usage once at open. If that answer is missing, its usage().total is null rather than a figure.
    • usage().seq also covers derived child sessions' records.

Tests

  • tests/claude/claude-token-usage.test.ts, on frames Lookout recorded on claude 2.1.292 (tests/replay/fixtures/claude-usage-*.raw.jsonl):
    • the total is modelUsage and the root is the main loop;
    • the subagent's spend is unattributed;
    • the plain turn grows both totals equally (latest wins, nothing summed);
    • /compact grows only the total;
    • the session view agrees with usage();
    • the subagent gets no entry;
    • the resume total is that turn's own (22087 / 36, not 137784 / 2249);
    • without a baseline: context only, total null (no answer, error, timeout, no session);
    • an entry without counts makes the baseline unknown;
    • the real zeroed startup-error result moves nothing.
  • tests/claude/claude-usage-baseline.test.ts, with the adapter on a fake process:
    • a resume sends initialize, then get_usage, with both answers and a late duplicate kept private;
    • a new session sends nothing;
    • a refusal leaves the total null and the process alive;
    • an unanswered get_usage opens after the bound.
  • tests/observe-folds.test.ts:
    • withChildren with a diamond, a nested child, a stray node, and a child that has not reported;
    • absent while the own total is null;
    • a reported total with unattributed.
  • tests/replay/claude-projection.test.ts snapshots the new recording.
  • The claude-aimock vendor resume test (CI) now asserts that the resumed Session's total equals its own turn's main loop.
  • Existing resume tests answer the new get_usage.
  • Synthetic, marked as such: the get_usage answer (schema-shaped, its model_usage the previous process's last modelUsage, which a live read found identical) and the /clear reset (schema text only).
  • pnpm run check: typecheck, lint, 1442 tests, sea-trial 19/19. CI passed all 17 checks on 180696e. On all three OSes, the claude-aimock resume test ran the real claude binary (with a scripted provider) through the real get_usage read-back.

Open questions

  • The /clear reset handling and the get_usage answer come from the schema plus one live read, not from a recorded fixture. Recording a get_usage answer and a /clear would replace the synthetic frames.
  • get_usage may make claude fetch the subscription's rate-limit endpoint. This costs one extra request on every resume and can add up to 30 s to a resume when claude never answers.

🤖 Generated with Claude Code

…Children (#282)

claude's session total in OAR added up each turn's `result.usage`, which
claude's own schema calls "MAIN AGENT LOOP ONLY": it leaves out Task
subagents, sidechains and compaction, so a claude Session with subagents
reported far less than it spent. `result.modelUsage` covers every model
call and is a running total, so it is read, never summed.

- claude `usage().total` is the latest `modelUsage`, summed over models
  (input with cache reads and writes, output, cacheRead, cacheWrite). The
  root's `byAgent` entry stays the main loop (`result.usage`).
- `SessionUsage.unattributed`: what the total holds that no agent entry
  accounts for, the total less the breakdown, never split by estimate.
  claude subagents get no entry: only a subagent's first assistant frame
  carries `parent_tool_use_id`, and its usage is the stream-start value.
- `SessionUsage.withChildren`: the total plus every derived child
  session's total in `graph()` (codex child threads, grok child sessions,
  OpenCode v2 children), each once, nested ones too, so a host need not
  know per runtime whether a parent's figure includes its children.
- A resumed claude process continues the previous one's `modelUsage`, so
  a resume asks `get_usage` before the first turn and subtracts its
  `session.model_usage` per model, as codex subtracts its re-report. The
  answer carries account data and is consumed privately. Without it (a
  timeout, an error, no session totals) the resumed Session's total stays
  null: never the session's lifetime figure.
- A zeroed crash or startup-error `modelUsage` never moves the total back;
  a lower running total (claude resetting it on /clear) keeps what was
  counted.
- `UsageReport.total` carries a runtime's own session total on the record.

Tests fold claude 2.1.292 frames recorded by Lookout (a Task subagent,
a plain turn and /compact; then a resumed process); the get_usage answer
and the /clear reset are synthetic and marked so.

Behavior change: claude totals grow (subagents and compaction included);
`usage().seq` now covers derived child sessions' records.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@TennyZhuang
TennyZhuang marked this pull request as ready for review October 9, 2026 21:47
@xxchan
xxchan merged commit 03d5f0f into main Oct 9, 2026
17 checks passed
@xxchan
xxchan deleted the feat/claude-model-usage branch October 9, 2026 21:48
@xxchan xxchan mentioned this pull request Oct 9, 2026
xxchan added a commit that referenced this pull request Oct 9, 2026
Release OAR and CLI 0.50.0. This PR changes only the two package version
fields.

**Breaking: a failed turn is a union tagged by `failure`** (#280)
- `TurnOutcome` `failed` is now `FailedTurn`, exported: `credential`
exists only on `failure: "auth"`, `resetsAt` only on `failure: "quota"`,
`status` on every class. A host that reads `outcome.credential` must
check `failure === "auth"` first, or it no longer compiles.

**Added**
- **`resetsAt` on a quota failure** (#280): when the limit that refused
the turn resets, where the runtime reports it. Only claude does: a
`rate_limit` failure while claude's latest `rate_limit_event` says a
subscription limit is `rejected`, overage does not take the requests,
and a reset is named. It is the runtime's last report; a time already
past means unknown. Codex's reset time exists only in its prose and is
not parsed.
- **Claude token totals include subagents and compaction** (#282, #292):
`usage().total` is claude's own running total (`result.modelUsage`),
which counts the main loop, Task subagents, sidechains and compaction.
Before, it was the main loop only (`result.usage`).
- **`SessionUsage.unattributed`**: what the total includes that no
`byAgent` entry accounts for (claude's subagents and compaction, which
its stream does not attribute per agent). `byAgent` plus `unattributed`
sums to `total`.
- **`SessionUsage.withChildren`**: the total plus the total of every
session derived from this one in `graph()` (codex child threads, grok
child sessions, OpenCode v2 children), each counted once.
- **Open errors keep their native cause** (#284): a failed codex, ACP or
claude open carries `cause: { method, native }` (redacted), so a host
can diagnose a failure even when no Session was returned.

**Fixed**
- **Known session credentials are redacted from every record and error**
(#286), not only from error text: session env and MCP env values chosen
by name, MCP credential headers, password-bearing connection URLs, and
pi's resolved model key. Original runtime input is unchanged. Limit: a
key the model repeats back across several streamed text deltas is not
caught, so SessionView text and coalesced events can still show it.
- **ACP error `data` is redacted** (#284); it used to bypass MCP
credential redaction.
- **Claude resume of a missing session fails at open** (#285, #287) with
claude's own text ("No conversation found with session ID: …") and
`cause: { method: "initialize", native }`, instead of returning a
Session that exits before its first prompt. A normal resume now waits
for claude's `initialize` answer (about 1 s observed).
- **Claude's `initialize` answer is no longer recorded** (#287): it
carries the account's email, organization and subscription. This
affected every open with `serviceTier` since that option shipped.
- **pi provider auth and model catalog use the agent dir sessions use**
(#289, #290): with `OAR_PI_AGENT_DIR` set, `createPiProviderAuth()` and
`createPiModelCatalog()` read and write that dir's `auth.json` and
`models.json` instead of pi's own. An empty `OAR_PI_AGENT_DIR` now
counts as unset everywhere, instead of becoming a relative path.

**Behavior changes**
- Narrow on `failure` before reading `credential` or `resetsAt` (see
above).
- Some claude rate-limit failures are now `quota` (with `resetsAt`)
instead of `rate_limited`; `failureAdvice` says `retry: "later"` for
them.
- Claude totals grow: they now include subagent and compaction tokens. A
resumed claude Session asks `get_usage` once at open for its baseline
(consumed privately, never recorded); if that answer does not come,
`usage().total` stays null for the Session rather than reporting the
lifetime figure.
- After a claude open with `serviceTier`, `serviceTier()` is null until
the first turn reports it; no `service_tier` event is emitted at open.
- Redaction now applies to every record, so a host comparing raw records
with what it sent may see `[redacted]` where a known credential
appeared.

**Known issues**
- `createPiModelCatalog().providers()[].configured` is false for a
stored credential until `refresh()` (#291). Use
`createPiProviderAuth().status(id)`.
- A Windows CI flake in the credential-redaction vendor test (#288);
tests only.

Validation: every PR passed all 17 checks on its final head. #284, #286,
#287, #280 and #290 merged with trees equal to their CI trees. #292 was
checked on its base, so its combination with #290 (disjoint files) was
verified locally (typecheck, lint, full tests: 1446 passed), and the
merged tree equals that verified tree. Lookout verified #286, #287, #290
and #292 against real binaries. After this PR passes CI and merges, tag
its exact squash commit as `v0.50.0` to trigger npm trusted publishing.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: exe.dev user <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Token totals: claude counts only its main loop (use modelUsage); a total that includes derived child sessions

2 participants