Usage parser

Pure-Python helpers that decode the JSONL stdout agents.models.AgentResult carries into a UsageMetrics dataclass — backend, distinct model(s), turn count, input / output / cached / cache-read / cache-write token totals, cost_usd, a cost_source tag of reported / estimated / unknown-price / no-usage, the cost and token evidence that say what those amounts and counters mean, and why an unpriced cost has no amount (below). No external dependency: the parser is jq-free.

The pass runs once the audit agent_exit event has already fired, and record_agent_exit writes what it returns as the token / cost detail on the analytics agent_exit record and the run_usage summary on the trajectory record. Two siblings ride the same stream under the same resilience contract: the opt-in skill-trigger extractor and the trajectory classifier below. None of the three reads or writes a file — redaction, truncation, and the append itself belong to the writers downstream of them.

Where the parser sits in the package tree, and what it is responsible for beside the surfaces around it, is in architecture/observability-modules.md; the knobs are in configuration/observability.md.

Module layout. Callers import the parsers directly from metrics.py, skills.py, and trajectory.py. Each dispatches across Codex, Claude, and Antigravity. The six result types come from their defining modules: UsageMetrics and SkillTriggers from the first two, and AgentTrajectory / TrajectoryStep / SourceItem / TurnUsage from trajectory_models.py. Provider payload handling is split behind them: protocol.py holds the JSONL vocabulary and event_stream.py the resilient line decoder and the cost-precedence selection, cost_evidence.py the cost basis, completeness, and reduction, unpriced.py the reasons an estimate leaves usage unpriced, and token_evidence.py the token-counter semantics every surface shares, prices.py the first-party API price catalogue over the dated rows and bounded lookup on price_catalogue.py, and model_names.py the nested model-name lookup, claude_rows.py / claude_summary.py and codex_rows.py / codex_summary.py the per-provider frame decoding and run summary, with claude_settlement.py settling each Claude message's final output count between the two and claude_requests.py holding each Claude usage row's scope, the lifetime of each of its cache writes, and the estimate it is priced at, and codex_requests.py what one Codex usage record establishes about the requests it sums and the estimate it is priced at, shell_segments.py / skill_commands.py / skills_claude.py / skills_codex.py the skill-evidence classification, and trajectory_claude_blocks.py / trajectory_claude_stream.py / trajectory_claude_turns.py plus trajectory_codex.py and the per-item-type trajectory_codex_items.py under it the timeline reconstruction. Antigravity's envelopes, tool lifecycles, and completed-step usage live in agy_events.py / agy_summary.py, with agy_requests.py holding which Gemini API model a run's CLI slug is priced as and the estimate its steps are priced at, and its text and tool timeline in trajectory_agy.py. Per-request usage has owners of its own: request_models.py the observation, marker, and checkpoint records, request_normalization.py the common counters every provider's are read into, request_coverage.py the coverage a collection states and the field the observations ride in, request_scan.py the bounded pass a collector reads stdout in, request_agy.py with request_agy_steps.py and request_agy_branches.py the Antigravity collector, its step fold, and its conversation attribution, and request_claude.py with request_claude_stream.py, request_claude_messages.py, request_claude_counters.py, and request_claude_reports.py the Claude collector, its stream fold, its request fold, the counters a usage block is read for, and what the stream reports of its process, and request_codex.py with request_codex_scope.py, request_codex_turns.py, request_codex_fold.py, and request_codex_counters.py the Codex collector over the native session log lines the trajectory sink's reader hands it, the scope proving which of them an invocation wrote, the turns it follows, the fold reading what those lines report, and the counters a usage block is read for, as request usage observations describes. The trajectory classifier reuses the same event decoder, pricing path, and skill evidence owners, so the resilience and cost-precedence contracts are defined once. Tests intercept parsers on the module their caller imports. The package initializer re-exports the public parsers and result types; callers name the defining owner so patches reach it.

Provider parsing. parse_claude_usage(stdout) consumes claude --output-format stream-json events, reads one usage row per API message by grouping its assistant frames on message.id, and sums per-model. Every one of those frames repeats the usage the message's message_start event opened with, so the output count it carries is the one at the start of the message. The final count, thinking included, is only on the message_delta stream event that closes the message, whose stream_event wrapper names it through api_message_id; that event settles the message's output count. Input, cache-read, and cache-write counts are the same on every frame and stay the ones the assistant frames carry. A subagent prints no stream events. The message that closes it prints no frame at all: its usage rides on the lead thread's tool_result for the call that launched the subagent, as tool_use_result.usage, and that hand-back adds a row carrying the message's output count alone, since the run's input and cache counts are its frames'. A hand-back counts once per call it answers — the tool_use_id of its tool_result — since a resumed subagent returns under the agent id it had before. The final count of any earlier subagent message is printed nowhere: the result frame's modelUsage reports only the model's total, and what it holds beyond every output count the stream printed settles that message only when it is the model's sole message no message_delta closed, only when modelUsage reports the model's input, cache-read, cache-creation, and output totals — an absent one establishes nothing, never a zero — and only when those input and cache totals equal the counts the stream printed, hand-backs included. Two or more such messages share a total no frame divides, so each keeps its start count, as a subagent's message does whenever modelUsage also covers usage no frame of the stream printed; a message whose frames reported no output count and that nothing settles keeps no output count at all. A message_delta whose output is no count closes nothing. A stream with no message_delta at all — printed without --include-partial-messages, which the Claude backend always passes — settles nothing: every message keeps the count its last frame carries, and neither hand-backs nor modelUsage are read. On the captures the run's output equals the CLI's modelUsage total: 358 on the main run, and 450 on the subagent run, whose lead thread alone reports 314. A stream with no assistant usage falls back to the result frame's usage. The sanitized Claude Code 2.1.295 captures this accounting is pinned to, and the frame-by-frame evidence behind it, are in usage_claude_stream_capture.py. parse_codex_usage(stdout, fallback_model=None) consumes codex --json events and treats usage as cumulative across the session: the last non-zero usage record is the authoritative total. Codex prints usage on turn.completed alone, and its block sums every API request of the thread — each request the turn made, and on exec resume the requests of the invocations before it too, so a resumed run's counters include theirs. No frame names the model, so the configured -m model the caller passes as fallback_model is what an estimate is priced as. parse_agent_usage(backend, stdout, fallback_model=None, span=None) dispatches by backend string the same way agents.runner.run_agent does, handing an Antigravity parse the span its dated Gemini rows are resolved over, as the Antigravity usage span below describes.

Claude cache lifetimes. A Claude usage block reports its cache writes twice: cache_creation_input_tokens is their aggregate, and the cache_creation object splits it by lifetime into ephemeral_5m_input_tokens and ephemeral_1h_input_tokens, which the prompt-caching contract documents as summing to the aggregate. Claude Code prints both on every assistant, hand-back, and result usage block; on the captures the lead thread writes one-hour entries and the subagent five-minute ones. claude_requests.cache_writes counts each write once, under the lifetime the block reports for it, and the estimate prices it at that lifetime's rate. A write the block gives no lifetime is counted under an unknown one, which no rate prices, so the estimate states no amount instead of a five-minute or one-hour guess: the whole of a nonzero aggregate printed with no split or with a split that is no object, and the part of an aggregate a partial split leaves over. A lifetime field holding anything but a non-negative whole number — a fraction, an infinite or NaN value, a string, a bool — is unreported, read before any coercion could round it into a count; a float such as 600.0 is the whole number it spells. A split claiming more writes than its aggregate holds, beside a zero aggregate too, contradicts it: the block establishes neither its write count nor its prompt, so it keeps the aggregate as its cache-write count, all of it under the unknown lifetime, and the row records the conflict apart from any token count (conflicting_writes) and has no price on any model. With no aggregate, a split reporting both lifetimes is the whole write count, and one reporting a single lifetime counts those writes alone. cache_write_tokens is the aggregate wherever a block reports one and the lifetimes summed otherwise, and an explicit zero is a count like any other.

Claude request pricing. Each usage row carries a scope. A message row is one API message's usage block, so its input, cache reads, and cache writes are that request's prompt; a handback-output row holds only the output count of a subagent's closing message; a result-total row is the result frame's usage, a sum over the lead thread's requests. Every row is priced on its own (ClaudeUsageRow.price) and the run's estimate is those prices summed, one unpriced row leaving the whole estimate unknown-price; each turn is priced through the same call, and a CLI-reported cost still outranks the run's estimate, as the cost precedence below says. A request-tiered model is priced only on a row that establishes its prompt. Claude Haiku 5.5 charges its higher rates on every class, output included, to a request whose input, cache reads, and cache writes together exceed 100,000 tokens, cache hits counted, so each message is measured alone: a request at or under the threshold pays the base rates however far the run's requests add up past it. A handback-output or result-total row, or a message missing its input, cache-read, or whole cache-write count, establishes no prompt and leaves a Haiku 5.5 estimate unknown-price. A flat-rate model prices such rows at its one set of rates, since summing requests changes nothing it charges. With the CLI's reported cost cut from the captures, the main run's estimate equals that cost, and the subagent run's equals it less the prompt of the subagent's closing message, whose input and cache counts the run leaves out.

Claude output counts recorded before the correction. The parser kept the last assistant frame's output count, the one at the start of each message: 31 output tokens on the main capture, where the CLI reports 358, and 92 on the subagent capture against 450. The correction is included in v0.14.0; v0.13.0 and every earlier release record the start counts. Pull request #2199 identifies the source-checkout boundary: a checkout after the v0.13.0 tag can contain the correction while still reporting 0.13.0, so its history determines which accounting it uses. Records carry no orchestrator version: the boundary for recorded usage is when the host started running the corrected build. Records already written keep their values: output_tokens on agent_exit and agent_trajectory lines, the analytics database rows synced from them, and the pinned issue_total_tokens an issue accumulated, along with issue_total_cost_usd where a run's cost was estimated from the undercount. Nothing backfills them, and an issue in flight across the upgrade mixes both in its counters. The correction leaves input and cache counts, and a CLI-reported cost_usd, unchanged.

Claude estimates recorded before the lifetime correction. v0.14.0 and every earlier release price a block's aggregate cache_creation_input_tokens at the five-minute rate whenever the block carries one, as Claude Code's always do, so a one-hour write was priced at the five-minute rate, and they price each model's summed usage rather than each request. The correction ships in v0.15.0; pull request #2452 identifies the source boundary. A source checkout between the v0.14.0 and v0.15.0 tags can contain it while still reporting 0.14.0, so its history decides which pricing it records, and records carry no orchestrator version. Records already written keep their values: an estimated cost_usd on agent_exit lines, every trajectory turn's estimate, the analytics rows synced from them, and the pinned issue totals those runs fed, as does an unknown-price an earlier build recorded for a Claude model it did not price. Nothing reprices them. A CLI-reported cost_usd is unchanged.

Codex cache writes. What a Codex usage block establishes is pinned to codex-cli 0.166.0 captures, run with the backend's own flags against a local stand-in for the Responses API whose scripted usage sits beside each stream in usage_codex_usage_capture.py. The block carries five flat counts: input_tokens is the whole input, cached_input_tokens the billed cache reads inside it, cache_write_input_tokens the cache writes inside it, and output_tokens holds reasoning_output_tokens. The write count is the responses' input_tokens_details.cache_write_tokens, with its cache_write_tokens_details split into ttl_30m_tokens and ttl_12h_tokens dropped — the binary holds neither name — and printed as 0 where a response reported no write count at all, so a zero there, the 0.148.0 capture's included, is no evidence that nothing was written. codex_rows.codex_usage_record reads a positive count as that many writes of unknown lifetime and a zero or an absent field as no write count, and keeps a negative count, which then prices the run on no model. No nested lifetime field is parsed, since no CLI stream prints one. codex_requests.CodexUsageRow.price prices the authoritative record on its own, following OpenAI's cache accounting, revalidated on 2026-10-31. A model whose row publishes cache-write rates — GPT-5.6 and later, a 30-minute write at 1.25× ordinary input and a 12-hour one at 2.5× — bills as ordinary input the input less its reads and writes, and each write once, at its lifetime's rate, never the aggregate again. A write of unknown lifetime finds no rate there, and a record establishing no whole write count cannot separate its ordinary input, so either leaves the run unknown-price; on GPT-5.6 and later every run the CLI prints is one or the other. A model before GPT-5.6 charges no cache write of its own, so there a write is ordinary input and the run prices its input less its reads at the input rate. Reads and writes beyond the input, or a negative count, price nothing on any model.

Codex request tiers. A usage block sums the thread's requests, so it sizes none of them, and neither does a difference between two blocks: repeated and cumulative blocks are priced once, on the last. The tiered rows — GPT-5.4 and GPT-5.5 with their pro models, and every GPT-5.6 and GPT-6 row — charge their long-context rates to a request over 272,000 input tokens, so a run on one prices at the base rates only where its whole input is at or under 272,000, which keeps every request it sums there too (PriceRow.rates_for_requests_within); past it the run is unknown-price, however small each request was. The captured turn of two requests, at 200,000 and 201,000 input tokens, prints 401,000 and is unpriced on GPT-5.5. The long-context rates are never charged, since no stream sizes a request past the threshold, and a flat-rate model prices any run.

Codex estimates recorded before the request correction. v0.14.0 and every earlier release price a Codex run's whole cumulative input at the long-context rates, output included, once it passes 272,000 tokens, and price the input a cache-read count exceeds at nothing. The correction ships in v0.15.0; pull request #2455 identifies the source boundary. A source checkout between the v0.14.0 and v0.15.0 tags can contain it while still reporting 0.14.0, so its history decides which pricing it records, and records carry no orchestrator version. Records already written keep their values — an estimated cost_usd on agent_exit lines and trajectory run_usage, the analytics rows synced from them, and the pinned issue totals they fed — as does the unknown-price an earlier build recorded for a GPT-5.6 or GPT-6 row it held dormant. Nothing reprices them. A CLI-reported cost_usd is unchanged.

For agy, token totals come from the completed step_update events in this invocation, deduplicated by step index. The terminal result's usage and turn counts include earlier conversation turns on a resume, so they are not added to the per-run counters. user_input steps count this invocation's turns; init.model supplies the model, falling back to the configured --model. The CLI supplies no USD cost. No completed usage frames means no-usage.

Antigravity usage and its Gemini estimate. What a step's usage counts is pinned to agy 1.4.10: a fresh run and its --conversation resume, captured with the backend's own flags in usage_agy_stream_capture.py beside the stream examples the headless guide publishes, and the CLI's conversation store on the capture host. init.model echoes the --model slug, only when one was given, and no other frame names a model. A completed step carries one generation's usage, and every generation the store records, a response's and each helper generation beside it, names the model the conversation selected, so a checkpoint step's usage is priced as that model's like a response's. input_tokens is the ordinary input alone, apart from cache_read_tokens: a step's cache reads exceed its input on nearly every step the store holds that reads any, and the guide's second turn reads 30,214 cached tokens beside 278 of input. Output tokens already include thinking tokens: a step's total_tokens is its input plus its output, thinking_tokens inside the output. A resumed run's steps are its own, while its result usage counts the whole conversation, so the estimate prices the same deduplicated steps the counters sum, each once.

agy_requests.API_MODELS maps a slug to the Gemini API model it is priced as only where the headless guide or the CLI's model listing names it: gemini-4-argon-high and -medium to gemini-4-argon; gemini-3.8-flash-high, -medium, and -low (the last from the 1.4.10 listing) to gemini-3.8-flash; and gemini-3.6-flash-high and -medium to gemini-3.6-flash. A thinking level is a setting of the model, not another SKU. Nothing else maps. Gemini 3.7 Flash stays unpriced: the Developer API routes its deprecated ID to 3.8 Flash while Antigravity still serves a 3.7 deployment, and neither is the other's price. Gemini 3.1 Pro stays unpriced too, since nothing confirms that it is the gemini-3.1-pro-preview SKU or sizes the requests its 200,000-token tier is charged on. So do the Claude and GPT-OSS models Antigravity also serves, a bare API ID, an unlisted thinking level, and any other spelling. agy_requests.price prices a run attributed to exactly one mapped slug: ordinary input at the input rate, cache reads at the cached-input rate, and output, thinking included, at the output rate, on the active row in effect throughout the run's usage span (below). It states no amount for a run whose models are mixed or unnamed, a run any of whose steps spawned a subagent (subagent_info), since that conversation's model and usage are not on the stream, a step reporting a negative count or no count at all, and a run with no span or one a scheduled rate change falls inside.

Antigravity usage span. Gemini 4 Argon and the Flash models change rates on a scheduled date, and the pricing page names that date and no time zone. parse_agent_usage takes the run's span — a price_catalogue.UsageSpan of the instants it started and ended — and record_agent_exit hands it the duration_s seconds that end as the record is built, right after the run exits. A dated row prices the run only where the same row is in effect on every calendar date the span touches in any time zone, UTC-12 through UTC+14 (price_catalogue.active_row_throughout): a run ending by 09:59:59 UTC on 2026-11-30 pays Argon's first rates, one starting at or after 12:00 UTC on 2026-12-01 its second, and one touching both dates is unknown-price. A parse given no span prices no dated row, so every Gemini estimate needs one; the Claude and OpenAI rows carry no dates and ignore it.

Antigravity costs recorded before the estimate. v0.14.0 and every earlier release record every Antigravity run as unknown-price, and its cache reads with a cache overlap nothing establishes, so its token total is unknown wherever it read from cache. The estimate and declared cache overlap ship in v0.15.0; pull request #2456 identifies the source boundary. A source checkout between the v0.14.0 and v0.15.0 tags can contain them while still reporting 0.14.0, so its history decides which it records, and records carry no orchestrator version. Records already written keep their values: the agent_exit lines and trajectory run_usage, the analytics rows synced from them, and the pinned issue totals they fed. Nothing reprices them or reads their overlap again.

Antigravity trajectories join each response step's text deltas, retain tool parameters and outcomes, read offered tools from init, and take the final answer only from a successful terminal result. Interrupted response text is kept in the timeline without becoming a final answer. Skill evidence remains empty because this adapter does not infer skill loads from Antigravity's tools; no per-turn pricing or source-item accounting is emitted.

Tool lifecycles fold repeated and sparse step_update frames by step_index, retaining tool identity across partial updates and recording each step's latest state. The lifecycle reducer reports every indexed tool step whose latest state is not DONE, ensuring earlier background commands remain authoritative even when later status checks finish and emit terminal output.

Cost precedence. A total_cost_usd reported by the CLI itself always wins, an explicit 0 included (cost_source="reported", on the cli-reported basis); otherwise the parser prices the usage from an active row of the price catalogue below and produces an estimate ("estimated", on that provider's API basis). When usage is present but its model resolves to no active row — or, for Claude, a cache write carries no lifetime, a lifetime split contradicts its aggregate, or a request-tiered model's row establishes no prompt, as the Claude paragraphs above describe, and for Codex, a GPT-5.6 or later run's cache writes carry no lifetime or no count, its reads and writes exceed its input, or a request-tiered model's run passes 272,000 input tokens, as the Codex paragraphs describe, and for Antigravity, a run's models are mixed or unnamed, a step spawned a subagent or reports no count or a negative one, or the run has no span one dated row covers throughout, as the Antigravity paragraphs describe — the parser returns cost_source="unknown-price" and cost_usd=None — an incomplete cost — rather than guess at zero, bill cached tokens at the input rate, or choose a rate the usage does not establish. An empty stream — or one with no usage frames at all — yields "no-usage". One selection, event_stream.select_cost, builds the run's cost evidence, and UsageMetrics.apply_cost reads cost_usd and cost_source off it, so the three never disagree.

Why a run is unpriced. Each estimator answers an unpriced.Pricing: its estimate, or every reason no estimate is established, each an UnpricedReason naming the model the usage was priced as (unknown where the run named none). An estimator evaluates every check that applies rather than stopping at the first, so a run can give several reasons, and a Claude run gives each of its rows' reasons, a row on an unknown model stopping none of the others from being read. The vocabulary is closed:

  • missing-model-price — no active catalogue row answers to the model: an unknown, unnamed, or dormant one, or an Antigravity slug no Gemini API model is mapped for.
  • indeterminate-request-tier — a request-tiered row, and usage sizing no request: a Codex input past 272,000, or a Claude row that is not one message's whole prompt.
  • missing-cache-write-count — a row charging cache writes by lifetime, and no whole write count, such as the zero or missing count the Codex CLI prints.
  • missing-cache-write-lifetime — cache writes of no reported lifetime on a row charging each lifetime its own rate.
  • unrated-token-class — tokens of a class the row publishes no rate for, such as cached input on a model whose page lists no cached rate.
  • invalid-token-counts — a negative count, reads and writes past the input, or a lifetime split larger than its aggregate.
  • missing-token-count — an Antigravity step reporting no count.
  • indeterminate-rate-period — no one dated Gemini row in effect throughout the run's span: no span, or one crossing a scheduled change.
  • subagent-usage — an Antigravity run spawning a subagent, whose model and usage the stream does not establish.
  • several-models — an Antigravity run naming more than one model, given against each of them.

A Codex row with no active row gives missing-model-price alone, since nothing is left to read its counts at; past the tier, a record's counts are read at the row's base rates, which publish the classes its tier's rates do. The observed GPT-6 Astra runs give two at once: a cumulative input past 272,000 leaves the tier indeterminate, and the CLI's zero or missing write count leaves the cache-write count missing. UsageMetrics.apply_cost keeps the reasons only where the selected cost is incomplete: a CLI-reported amount, an explicit zero included, outranks the estimate and leaves none, as does a complete estimate, and a run with no usage has none to give. UsageMetrics.to_dict() serializes them, sorted and each pair once, as unpriced_reasons and only where it holds one, so the agent_exit record and the trajectory run_usage carry the field on exactly the unpriced runs:

{"unpriced_reasons": [
  {"model": "gpt-6-astra", "reason": "indeterminate-request-tier"},
  {"model": "gpt-6-astra", "reason": "missing-cache-write-count"}
]}

A Claude turn's cost states no reasons of its own. unpriced.recorded_reasons reads a record back for only the entries this vocabulary writes, a model a non-empty string; an unpriced record carrying none — every one an earlier build wrote — gives no reason, which the analytics dashboard shows as Reason unavailable, and nothing re-estimates it.

Cost basis and completeness. v0.15.0 introduces explicit cost and token evidence; records from v0.14.0 and earlier carry neither and retain the unknown readings described below. cost_evidence.py defines the cost every surface records and folds. A CostEvidence holds monetary contributions, at most one per basis and in basis order, beside a completeness, and serializes as cost_evidence on UsageMetrics.to_dict() and on each Claude TurnUsage:

{
  "completeness": "complete",
  "contributions": [
    {"basis": "anthropic-api-estimate", "amount_usd": 0.42, "rates_verified_on": ["2026-10-29"]}
  ]
}

A basis says what an amount is:

  • cli-reported — the USD figure the agent CLI printed for the run (Claude's total_cost_usd). Its origin is the CLI; nothing here verifies it against an invoice, a subscription, or a credit balance, so it is never presented as a bill.
  • anthropic-api-estimate, openai-api-estimate, gemini-api-estimate — a token-only list-price equivalent: the run's observable usage priced at that provider's Standard first-party API rates from active catalogue rows, with rates_verified_on naming each row's verification date. Claude estimates are on the Anthropic basis, Codex estimates on the OpenAI one, and Antigravity estimates on the Gemini one.
  • unknown — an amount recorded with no basis. No parser writes it; a reader files under it the cost_usd of a record that carries no cost_evidence.

Completeness is complete (the contributions cover all the observable usage), incomplete (some usage carries no amount, so the contributions are at most a subtotal — today an unpriced run states none), no-usage (the stream showed nothing to price), or unknown (nothing states it). complete_usd is the total only when it is complete, which is what cost_usd records, so an unknown-price cost never exposes a complete amount; basis is the sole contribution's basis, blended across several. A complete zero keeps its contribution: spend of zero, not an absence.

An estimate excludes everything its token rates do not price: subscriptions, included quotas, credits, negotiated or discounted prices, service-tier and regional adjustments outside the declared Standard basis (Batch, Flex, Priority, data residency, and Claude's fast mode, which a usage block names in its speed field), cache storage, grounding and search, and every other non-token charge. That matters most for Codex, which can run on a ChatGPT plan's subscription or credits as well as on an API key: Codex pricing states that Codex credit billing has no separate cache-write charge and that GPT-6.1 Sol usage drawn from a subscription has no long-context surcharge, while API-key usage follows API pricing. An openai-api-estimate therefore prices usage on the API's terms, which charge GPT-5.6 and later cache writes and long-context requests where the account's Codex billing may not; it is an API comparison basis, never the subscription or credit charge. The Gemini basis is the same kind of comparison: it prices Antigravity usage at the Gemini API's rates for the model a slug maps to, and establishes no Antigravity charge — no plan, quota, or credit Antigravity draws on, and no proof that Antigravity serves a request as the API would.

recorded_cost(record) reads the cost any serialized usage record states — an agent_exit line, a trajectory's run_usage, or one of its turns. An amount is read only as a non-negative finite number a float holds, zero included, so a negative amount or one too large for a float is no amount at all. A record without cost_evidence, or with evidence this format does not serialize — an invalid amount in it included — is read as unknown completeness holding its cost_usd, when that is a valid amount, under the unknown basis: nothing is inferred from its cost_source, its backend, or its models, and nothing backfills a provider breakdown for records written before the field existed. The parsers record a CLI-reported figure as the CLI printed it, so a run whose CLI printed a negative cost carries evidence this reader refuses and reads back as unknown with no amount. reduce_costs folds many costs into one: each basis's amounts are summed on their own, verification dates are unioned, and the result keeps the weakest completeness any input states — incomplete over unknown over complete over no-usage — so a total holding unpriced usage or an amount with no basis never reads as complete spend. An empty fold is no-usage; the reduced evidence serializes and reads back in the same shape.

Token-count semantics. The raw counters keep each provider's own meaning, and token_evidence.py states it beside them as token_evidence on UsageMetrics.to_dict() and each TurnUsage: observed, the counters the stream's usage payloads reported a count for, and cache_overlap, how the cache counters relate to the input counter. A reported zero is observed; a counter observed does not name is missing evidence rather than a zero, even though its raw field reads 0. The decoders keep the two apart by reading every field through token_evidence.reported_count / first_count, which answer None for a field no spelling of it reported — an infinite or NaN value, never a count, included, so one never stops a stream's parse — and keeping only the token classes a payload reported a count for. A missing class still sums as zero and costs nothing, so no counter or flat-rate estimate changes with it; only a request-tiered Claude model needs every input and cache class of a message to size its prompt.

Backend Counters a usage payload can report cache_overlap
claude input_tokens, output_tokens, cache_read_tokens, cache_write_tokens disjoint
codex input_tokens, output_tokens, cached_tokens within-input
agy input_tokens, output_tokens, cache_read_tokens disjoint

A Claude run observes a counter once any usage row it sums reported one, and a turn what its own row reported. Claude's usage blocks count ordinary input apart from cache reads and writes, and a block omitting a cache field observes none of it. A subagent hand-back turn observes output_tokens alone, since the stream prints only that count for the closing message, and its estimate prices that count alone where the model's rates are flat, while on Haiku 5.5, whose rate depends on a request the stream does not size, it states no amount; a run's own input and cache counters still leave that message out, as the provider parsing above describes. A Codex run observes what its authoritative record reported: the last one reporting any tokens, or, when every one reports only zeros, the last record reporting a count at all — those zeros were measured, so they are observed, while such a stream still has no-usage cost. Codex's cached_tokens is the part of its input served from cache, and it records no cache-read or cache-write counter: its cache_write_input_tokens, a part of its input too, is read by the estimate alone. An Antigravity run observes a counter once any completed step reported one, and its cache reads sit beside its input, as the Antigravity paragraphs above establish.

non_overlapping_total(record) is the shared way to add the counters up: every observed counter once, a cache counter left out only where it sits within-input of an input count that was itself observed — a cache count with no observed input to hold it is counted on its own. Beside an observed input, a nonzero cache counter of unknown overlap leaves the total None, never guessed either way, and so does an observed counter holding no count is_count accepts (a non-negative integer) — null, negative, a bool, or a number spelled as a string. recorded_tokens(record) is the evidence a record is read with: the token_evidence it states, or, for a record without it, the counters it holds and an unknown overlap, so such a record totals only when none of its cache counters is nonzero. The trajectory viewer reads each run_usage and turn through recorded_cost and recorded_tokens alike, and each counter through is_count, so the totals it shows are the ones this reader gives. The analytics sync reads each agent_exit record through the same two readers and stores what they answer — the amount per basis, the completeness, the estimate dates, and the non-overlapping total — as columns the database sums.

Price catalogue. prices.py holds one table of rows per provider — Anthropic, OpenAI, and Gemini — at Standard first-party API list rates in USD per million tokens, each row recording the date it was last checked against its provider's page (verified_on, 2026-10-29 for every row): Claude pricing, OpenAI pricing with each model's page for its aliases and snapshots, and Gemini pricing. A row answers to its canonical model ID, the documented aliases, and the published snapshot IDs listed on it, each compared whole and case-sensitively. No prefix, substring, or suffix resolves: an unknown version, an unpublished snapshot, a partner-platform ID such as Bedrock's anthropic. form or a Google Cloud @ snapshot, and an arbitrary suffix such as [1m] stay unknown-price rather than inheriting a neighbour's rates. The retired Claude Opus 4 and 4.1, Sonnet 4, and 3.5 Haiku keep their rows and their documented aliases (claude-opus-4-0, claude-opus-4-1, claude-sonnet-4-0, claude-3-5-haiku-latest), and the shut-down gpt-5-chat-latest through gpt-5.3-chat-latest IDs keep the rates their model pages publish: a shut-down model's -latest ID names that one model. Models the pages do not price (Claude 3 Opus and Haiku, the Claude 3.5 and 3.7 Sonnets, and a bare gpt-5.3) carry no row, nor does the bare chat-latest, which moves with OpenAI's current chat model.

A row publishes each token class its page prices: Claude's five-minute and one-hour cache writes beside input, cache reads, and output; OpenAI's input, cached input, and output, with 30-minute and 12-hour cache writes where the page lists them; Gemini's input, cached input, and output including thinking tokens. A class the page leaves blank, such as the pro models' cached input, has no rate, so tokens of that class leave the estimate unknown. A model-specific request tier carries the whole set of rates a request pays once its prompt exceeds the threshold: Claude Haiku 5.5 above 100,000 prompt tokens, the GPT-5.4, GPT-5.5, GPT-5.6, and GPT-6 families above 272,000 input tokens, and Gemini 3.1 Pro Preview above 200,000. The Claude estimate applies Haiku 5.5's tier to each API message's own prompt, as the request pricing above describes; the Codex estimate prices a tiered row's base rates only under a bound on every request, and its tier never, as the Codex request tiers above describe; and the Antigravity estimate prices no tiered row, since no slug it maps is one.

A provider-scheduled change is two rows over consecutive inclusive dates, and a dated row resolves only for a usage date inside its interval, and prices a run only for a usage span it covers on every date the span touches in any time zone, as the Antigravity usage span above describes: Gemini 4 Argon is $2 / $0.10 / $10 for input, cached input, and output through 2026-11-30 and $4 / $0.20 / $20 from 2026-12-01; Gemini 3.8 Flash and 3.6 Flash are $0.75 / $0.075 / $3.75 through 2026-12-31 and $1.50 / $0.15 / $7.50 from 2027-01-01, rates the Gemini page still listed when revalidated on 2026-10-31. GPT-5.6 Sol's promotional rates are guaranteed at least through 2026-11-21; the row records that date as a review trigger (review_after), which changes no rate by itself.

Only active rows price a run: every Claude row — Opus 4 through 5.5, Sonnet 4 through 5.5, Fable 5 and 5.1, and Haiku 3.5, 4.5, and 5.5, since the Claude accounting prices each message's cache writes and request tier as billed — and every OpenAI row: GPT-5 through GPT-5.5 with their Codex and chat models, GPT-5.6 Sol (also gpt-5.6), Terra, and Luna, GPT-6 Astra, Sol, and Luna, and GPT-6.1 Sol and Terra, since the Codex accounting prices a cache write only at a lifetime its record reports and a tier only under a bound on every request. The Gemini 4 Argon, 3.8 Flash, and 3.6 Flash rows are active too, since the Antigravity accounting prices a mapped slug's steps at them over a span one row covers. Gemini 3.1 Pro Preview is the one dormant row — resolvable for its identity and rates, but priced by nothing, since no Antigravity slug is established as that SKU — so nothing a parser reads is priced on it. No Gemini 3.7 row exists: the Developer API routes that deprecated ID to 3.8. The restricted Claude Mythos and OpenAI Daybreak (cyber) models carry no row, since no captured stream shows a harness emitting their IDs and gpt-5.6-cyber names whichever cyber model is current; nor does any gpt-5.6-pro, which OpenAI does not publish.

Resilience. Malformed JSON lines (banner text, truncated frames, partial flushes) are silently skipped so a single bad line never invalidates the rest of the stream. A line the decoder refuses although it parses -- a number past the interpreter's digit limit, nesting past its depth -- is not skipped: it raises out of the parser, so no total read before it is published as the run's. _run_agent_tracked (in workflow/engine/usage.py) calls parse_agent_usage after every tracked agent run and appends the parsed counts to the analytics sink under event="agent_exit"; a parser exception is caught and downgraded to a log.exception, and the run writes no agent_exit record and publishes no total. Its trajectory reconstructs nothing from the refused stream either; where the trajectory sink is on and the backend has a request collector, the trajectory record carries only the request usage the collector read past the refusal, marked stream_refused (see Request usage observations).

Terminal verdict surface. Beyond the analytics sink, every invoked run's parsed UsageMetrics is counted on per-issue totals on the pinned state (issue_agent_runs / issue_total_tokens / issue_total_tokens_unknown_runs / issue_total_cost_usd / issue_cost_sources / issue_cost_evidence / issue_unevidenced_runs; see state-machine/labels-and-state.md). Each run is read as its usage record serializes it: its non-overlapping token total is added where its token evidence settles one, and the run is counted among those whose total is unknown where it does not; its cost evidence is reduced into the issue's with reduce_costs, one summed amount per basis beside the weakest completeness any run states. When an issue reaches a terminal, _format_issue_usage_verdict renders those totals into one visible receipt line posted on the issue thread, :receipt: this issue: N agent runs · T tokens · <cost>, its cost worded by the same cost_text owner the trajectory viewer uses and the analytics dashboard's Cost details section names its sources by:

Totals state Receipt cost
A CLI-reported amount alone $0.87 (CLI-reported)
Antigravity usage priced on Gemini's API rates alone $0.42 (Gemini API token estimate)
Amounts on several bases $1.29 (blended: CLI-reported $0.87 + Gemini API token estimate $0.42)
A known amount beside unpriced usage $0.87 (CLI-reported, incomplete subtotal)
Unpriced usage alone unpriced
Runs that printed no usage no usage
An earlier build's totals, which keep no evidence $0.87 (basis unknown, completeness unknown)
Runs counted after those $1.37 (blended: CLI-reported $0.50 + basis unknown $0.87, completeness unknown)

The token figure says which runs it settles no total for — T tokens (subtotal: token total unknown for 1 run) for a run whose cache overlap nothing establishes, and (2 runs counted without usage evidence) for an earlier build's runs, which stay unknown in basis, completeness, and overlap however many runs follow them. Nothing is inferred from issue_cost_sources, and no receipt already posted is rewritten. The PR merged / rejected finalizers and the closed-question terminal post it as a standalone tracked comment; the umbrella close comment appends it. It is a read-only summary — nothing gates on the figure — and it is skipped when no run was ever counted.

Accounting checkpoint. The counters have one writer: the accounting checkpoint (workflow/engine/usage_checkpoint.py), which _run_agent_tracked asks of every result a process returns, right after the usage is parsed and before any pause, interruption, timeout, wrapper, or stage disposition can discard the result. It lands one invoked run's increment on the usage totals exactly once, keyed by the identity _run_agent_tracked stamps on each process's result (AgentResult.invocation) rather than by a request fingerprint or a CLI session id, together with a bounded issue_usage_receipts ledger in one guarded commit, and refuses parsed usage no total can take — a negative count, a negative cost or one no float holds, or cost evidence no usage record carries. Every role is counted there — developer, reviewer, the initial and late decomposer, question, discussion, documentation, and conflict runs — and so is each attempt of a wrapper that hands its caller only the last: a poisoned session's fresh retry and an Antigravity command-recovery continuation are two exits, each counted. An exit whose decision is withheld is counted all the same: a live pause, a shutdown kill, a timeout, a failure, an incomplete run, a reviewer subject that moved, a refused report, or a verdict with no room. The count buys none of those decisions a replay. The parser's meanings are unchanged by it: a None usage adds nothing, a no-usage run counts one exit with no cost, and an unpriced run leaves the cost total as it stands and the cost evidence an incomplete subtotal.

What the checkpoint landed is laid back onto the caller's state as the comment's, so the stage's own write behind it neither counts the run again nor puts the totals back as the handler read them, and no other field the handler staged is persisted by it. A held return writes that accounting and nothing else of the run. A checkpoint that neither landed nor read back covered — refused, or sent and never confirmed — leaves the result unaccounted and the caller's state withheld from every whole-state write, and holds the run's disposition and any further invocation its wrapper would make, as a live pause does; the next tick reads the comment afresh, and a lost response is settled there by its receipt rather than counted twice. So an observed exit is retained only where a usable checkpoint lands: a process lost before its checkpoint, or one whose checkpoint is refused, is an exit this meter never counts, and nothing reconstructs it from the analytics or audit sinks, which stay observational. See state-machine/labels-and-state.md for its fields and refusals.

issue_agent_runs has one reader outside that receipt: the lifetime agent-run ledger on workflow/engine/run_ledger.py never reads agent_runs_used below it, so a ledger count that is missing or unreadable refunds nothing this meter counted. The two count the same unit but not the same set — the ledger charges the launch and so also holds the runs whose usage never parsed, while this meter counts the parsed exits — which is why the ledger's total is the larger of the pair. Nothing turns a run away against THIS meter — the ledger is the one that is judged, at the tracked spawn boundary (workflow/engine/run_circuit.py), and where an issue that has spent it all STOPS is the durable agent_run_limit park on workflow/engine/run_limit.py and the dispatcher hold over it. What that ledger DOES, as opposed to what it currently holds, is its own record: workflow/engine/run_budget.py writes one agent_run_budget event to both sinks per durable transition — a run charged, the spawn it paid for, the ceiling that refused one, and the ceiling an operator widened — each carrying the configured limit, the allowance in force, the spend, and what is left. That is the stream to count charges on; agent_exit records, and this meter behind them, count the runs whose usage parsed. See configuration.md for MAX_AGENT_RUNS_PER_ISSUE and state-machine/labels-and-state.md for the ledger's and the park's own keys.

Skill-trigger extractor (opt-in). A sibling trio mirrors the usage parsers' two-parsers-one-dispatcher shape and resilience contract to record which agent skills a run loaded, gated behind TRACK_SKILL_TRIGGERS (default off; see agent_exit records). The result is a names-only evidence model on SkillTriggers: triggered / trigger_counts are the loaded skills, evidence maps each to its tier (confirmed / inferred), and incidental / incidental_counts are path-only references that never become loads. The two buckets are independent — a skill both read and inspected is recorded in both — the only exclusion is structural: an incidental reference never enters triggered / trigger_counts or the skill_triggered audit events. parse_claude_skills(stdout) reads the firm confirmed signal — tool_use content blocks named Skill in the assistant stream — and returns input.skill in first-seen order, de-duplicating per invocation by the block id. (A captured real stream showed that under --include-partial-messages each completed content block lands in its own assistant frame — the content array is partitioned across frames, not a cumulative snapshot that repeats earlier blocks the way the usage sub-object does — so the parser walks every frame and de-dups by id rather than keeping the last frame per message id.) Claude has no dedicated file mechanism, so it produces no incidental references. parse_codex_skills(stdout) recognizes the codex shape: codex has no dedicated Skill tool, so its file-based skill mechanism surfaces only as a command_execution item whose shell command opens a skill's skills/<name>/SKILL.md file (codex's own "open its SKILL.md" instruction). A captured reviewer run pinned this — codex both registered-under-$CODEX_HOME/skills/ and project-local .agents/skills/ reads match. The command is first unwrapped (peeling the bash -lc "…" shell) and split into sub-commands on unquoted, unescaped operators — quote- and backslash-aware, so a metacharacter inside a quoted argument (rg 'foo|bar' path) or a backslash-escaped one (rg foo\|cat path) does not fabricate a spurious segment — then each SKILL.md match is routed by its sub-command's leading verb (skipping any NAME=value env prefix). Only a verb established as a direct reader (cat / sed / head / …) makes the reference an inferred load; every other verb — an inspection / search (git diff / git status / rg), an env-prefixed inspection (GIT_PAGER=cat git diff …), or a generic path-only command (echo …) — makes it an incidental reference. Even a reader verb is demoted to incidental when the SKILL.md is written rather than read: an output-redirect target (cat t > .agents/skills/x/SKILL.md) or a non-reading mode (sed -i / --in-place) is an incidental reference, so a skill file a run only writes is never miscounted as a load. So a read chained after an inspection still counts, and a bystander git diff over a changed SKILL.md does not fabricate a load. Started/completed echo the same command, so the parser dedups by the shared item.id (last-frame-wins, as for usage) — for inferred loads and incidental references alike. It reads only the <name> path segment and the routing verb — never the command text or its aggregated_output (the file's contents), both of which can echo user content (names-only Privacy). The inferred signal stays heuristic within the reader allowlist: a reader that opens a SKILL.md for an unrelated reason would still register as an inferred load, while defaulting non-readers to incidental keeps an unrecognized command from fabricating a trigger. parse_agent_skills(backend, stdout) dispatches by backend exactly as parse_agent_usage does. The offered-skills set (SkillTriggers.available) is confirmed on claude — read from the dedicated skills array in the system/init frame, captured against a real stream — and stays empty on codex at the parser layer: a captured codex exec --json stream (v0.142.5) carries no offered-skills frame at all, so record_agent_exit backfills the codex offered set out-of-band from the filesystem via skills.discovery.discover_local_skill_sources(cwd) instead — a scan that also reports the source level each name was defined at, which the agent_exit record keeps beside the names as skill_levels. The triggered set does not depend on it either way. As with the usage parsers, malformed JSONL lines are skipped and a missing / renamed field yields an empty result rather than an exception. Only the skill name is ever read — never the Skill tool's args (Privacy).

Trajectory classifier. A third sibling trio mirrors the same two-parsers-one-dispatcher shape and resilience contract to reconstruct a run's trajectory — the ordered timeline of tool calls / results interleaved with the assistant / user text turns — into an AgentTrajectory dataclass: backend, a best-effort system_prompt / tools, the names-only skills (SkillTriggers), an ordered steps tuple of TrajectoryStep (kind is "tool_call" / "tool_result" / "assistant_message" / "user_message", with name / tool_id / raw content — name / tool_id empty on the text turns — plus a turn index tying each billed step back to the assistant turn that produced it), a source_items tuple of SourceItem accounting for every item the provider stream identified (codex-only today), final_output, a best-effort turns tuple of per-turn token usage (TurnUsage, parallel to tools / skills and claude-only today), and a request_usage field every parser leaves None for the trajectory writer to collect, as request usage observations describes. parse_claude_trajectory(stdout) reads the offered tools from the system/init frame's tools array, then the ordered timeline: assistant text blocks become assistant_message turns and tool_use blocks tool_call steps; user text blocks become user_message turns and tool_result blocks tool_result steps — calls / results joined by tool_use_id and de-duplicated per id the same way parse_claude_skills is, while id-less text blocks ride claude's per-completed-block framing — and the final answer from the result frame's result string. It also groups those assistant frames by message.id in first-seen order to assign each a 0-based turn index — stamped onto the assistant_message / tool_call steps that frame produced (a tool_result / user_message step is a turn input, not billed output, so its turn stays None) — and emits one TurnUsage per turn: model, input_tokens / output_tokens, cache_read_tokens / cache_write_tokens (every cache write, whatever its lifetime), and an always-estimated cost_usd / cost_source ("estimated", or "unknown-price" with cost_usd=None for an unpriced SKU, a cache write of no lifetime, a lifetime split contradicting its aggregate, or a request-tiered model's turn whose prompt is unknown — a reported total_cost_usd is a run-level figure and never reaches a turn). A turn's output_tokens is settled exactly as in the run parser above — its message's final count where the stream shows one, the start count its frames carry where it does not — while its input and cache counts are the frames'. Where hand-backs are read, a subagent's closing message, which printed no frame and so stamped no step, becomes a turn of its own numbered after every turn the steps carry, holding the hand-back's output count alone; the turns the frames gave keep their indices. Both builders settle their rows through claude_settlement.ClaudeSettlement, and each turn is priced on the same claude_requests.ClaudeUsageRow.price call the run estimate sums its rows through, each turn carrying its own Anthropic-basis cost evidence and the token evidence above. Unless the run totals fall back to the result frame, the per-turn token counts therefore sum to parse_claude_usage's run totals, and the per-turn estimates to its estimate wherever every turn is priced; a turn that is not leaves the run's estimate unknown-price too. parse_codex_trajectory(stdout) normalizes each operational item codex reports into one tool_call and, when the stream actually carried an outcome, one tool_result beneath it, and each agent_message item into one assistant_message turn (its text). Codex emits several frames per item — item.started, any item.updated, then item.completed — so every item is correlated by its item.id and a frame contributes only the fields it carried, which is what collapses a started/completed pair into a single pair of steps and lets the completing frame name what the started one had not resolved yet — except where the item type says otherwise: an item codex republishes whole on every frame is invoked once, by the frame that opened it, so a revision moves its result rather than its call. Every item also keeps the position its first frame took, so folding a later frame into it fills that pair in place rather than moving it behind the operations that started after it, and the timeline reads in the order the run started its operations. A frame the stream left without an item.id correlates with nothing, so each one stands on its own and its steps trail the ordered items rather than claiming a position between two of them. The supported item types and the fields each pair is built from are: command_execution (its command, then the aggregated_output of the frame that completed it — a running command already reports that field, empty, so presence alone would credit a command still running with a result it never produced), mcp_tool_call (its arguments, then its result — or its error when the server filled that instead — under a <server>.<tool> step name), web_search (its query, then the action it resolved to — a search announces itself with an empty query and names itself only on the frame that completes it, so that frame is both what the query is read from and the only one that reports an outcome, and that action is the whole of the outcome the stream carries: the pages a search read and the answers it got are absent from the stream and are never reconstructed for the record), file_change (its changes, kept as the structured one-entry-per-path list codex reports them as, then the status once it is terminal — completed or failed, on whichever frame carries it, since a patch reports in_progress until it has ended, so a patch that failed stays distinguishable from one the run left half applied, and a patch still in_progress when the stream stopped keeps its call with no result under it), and todo_list (the plan items of the frame that opened it, then the plan items of the frame that completed it — codex republishes the whole plan on every revision, so one plan is one pair however often it is rewritten: every item.updated between the two folds into that same pair instead of adding a step of its own, and a plan the stream never completed keeps its call with no result under it, since where a plan stood when the stream stopped is not where it ended). file_change is codex's custom (freeform) tool surface: the model calls apply_patch, and the stream reports the call and its outcome as a file_change item, so a custom tool call normalizes to a pair like any other. codex exec --json publishes no separate custom / dynamic tool item type — its whole item vocabulary is agent_message, reasoning, command_execution, file_change, mcp_tool_call, collab_tool_call, web_search, todo_list, and error (verified against codex-cli 0.148.0), and custom_tool_call is a raw model-response / rollout spelling that never reaches this stream. A web_search item serializes id twice, the provider's own exec-… call id last, so that call id is what the decoder hands the parser and what a search is correlated and recorded under; every other item is correlated under the synthetic item_N the exec stream numbers its items with. The id is also what keeps one operation one item: a wrapper frame reporting the id of the call nested inside it merges into that call rather than doubling it, and a wrapper of a type nothing normalizes neither replaces the normalized pair with a placeholder nor adds one beside it — nor survives inside one: a placeholder is named after the wrapper's own item type and payloaded with the wrapper's own status, so the normalized frame replaces it whole rather than merging into it, and an item that frame reported no invocation for is left with none instead of reading back as the wrapper's in_progress. The final answer is read from the last agent_message text; turns stays empty with every step.turn None, since codex usage frames are cumulative across the session rather than per-turn. Both reuse the matching skill extractor for the skills field. parse_agent_trajectory(backend, stdout) dispatches by backend exactly as the usage / skill dispatchers do. system_prompt stays None and tools stays empty in the classifier whenever a backend's stream does not expose them (codex exposes neither); the analytics writer backfills codex tools out-of-band from skills.discovery.discover_codex_tools(). Malformed JSONL lines are skipped and a missing / renamed field yields an empty section rather than an exception. Unlike the skill extractor, this classifier records the raw stream payload — tool inputs, tool outputs, and the final text — verbatim: it deliberately does not redact, truncate, or write any file. Those concerns belong to its downstream writer, observability/analytics/trajectories/'s persistence.maybe_record_trajectory (called from record_agent_exit), which redacts every free-text field, applies the head/tail and total-record truncation caps, and appends the agent_trajectory record to the trajectory sink — only when TRAJECTORY_LOG_PATH is enabled and always behind its own fail-open guard.

Codex item types beyond those five. Nothing is dropped silently. An item type the classifier does not normalize — codex's non-fatal error items and its collab_tool_call today, whatever a later release adds tomorrow — becomes one bounded unsupported_item placeholder step naming the item type, its id, and the status it reported (null for a type that reports none, error among them), deduplicated by item.id the same way a tool pair is and carrying no payload of its own. reasoning is the one deliberate exclusion: its text is hidden model content that never enters a record, and a placeholder per reasoning item would be noise rather than a diagnostic — but the exclusion is named rather than silent, in the per-item accounting below. Nothing fabricates an outcome either — a call that failed, or one the stream never completed, keeps its tool_call with no tool_result under it unless a frame actually reported one.

Every identified codex item is accounted for. Beside the steps, parse_codex_trajectory returns one SourceItem per item.id the stream carried, in first-seen order across every identified frame — the ones that contribute no step at all included — and deduplicated across the started / updated / completed frames the same way a tool pair is. Each names the item_id, the item_type the classification settled on, and a disposition: stored (the item's own steps are in steps), unsupported (nothing normalized its type, so the placeholder step above is what names it), excluded (the reasoning the classifier keeps out whole — the accounting records the id and the type and nothing else, never the hidden text or any other field of the item), or empty (its frames carried no payload to store — an agent_message with no text, a call whose fields never arrived, or an item too malformed to name a type at all, whose item_type is then the empty string). A normalized frame outranks an unsupported wrapper sharing its id whichever of the two arrives first — and renames it in place, since an id holds the position its first frame took either way — so the wrapper that adds no step renames nothing either and leaves no payload of its own behind. The accounting is also what carries an agent_message item's id: a text turn is not a tool call, so its step's tool_id stays empty and the provider id lands here rather than in the field a downstream reader joins a result to its invocation by. A frame the stream left without an id is the one thing not accounted — there is no name to account it under, and every such frame would otherwise share one — so it contributes its steps and nothing else. AgentTrajectory.to_dict() carries the tuple as source_items, and the agent_trajectory sink record serializes it under that same key — bounded, counted, and flagged when truncated, as trajectories.md describes.

Request usage observations

parse_agent_request_usage(backend, stdout, fallback_model=None, native_session=None) on trajectory.py collects one run's usage request by request: a RequestUsage (request_coverage.py) holding one observation per request the source settled usage for, the explicit boundary markers it printed, its aggregate checkpoints, and the coverage of the collection. It is AgentTrajectory's request_usage field, kept apart from Claude's per-turn turns: the trajectory parsers leave it None, and the trajectory writer collects it on every tracked exit behind a failure boundary of its own, as the trajectory sink describes. Every backend has a collector: an Antigravity and a Claude run's read its stdout, and a Codex run's reads the native session log the trajectory writer hands it as native_session, since its stdout prints no request (Codex requests, below). A record an earlier build wrote leaves the field out, which means its run's requests were not collected, never that it made none. The contract is observation alone: pricing, the run's UsageMetrics, the accounting checkpoint and pinned totals, the cost and token evidence, Claude's turns, and the viewer's timeline are computed exactly as they would be without it, and never read a sample, marker, or checkpoint.

What an observation carries. request_models.py defines the record; each sample serializes these keys, and a key the stream gave nothing for is absent rather than null:

  • identity: id, a key that stays the same however often the stream repeats the request, with id_kind saying what kind of key it is -- conversation-step (<conversation>:<step>) or process-step (process:<step>, for a step naming no conversation, known only within the process that printed it), api-message (a message id), api-request (the id of the API request that produced the message), handback-call (handback:<call>, the output of a subagent's closing message under the call its hand-back answers), source-position (position:<line>, for a request the stream named no identity for), or native-position (rollout-line:<line>, a Codex request known by the line of its native session log that reported it) -- and every identity the stream gave: conversation_id, session_id, turn_id, message_id, request_id, step_index, parent_conversation_id, parent_step_index, parent_tool_use_id, parent_turn_id, agent_id, and subagent_type, beside trajectory_turn, the index of the record's turns entry and steps the request is numbered under, by the key it settles under, where the trajectory numbers it;
  • order: position, the 0-based stdout line its collector places it at -- the one that completed an Antigravity step, the first one printing a Claude request -- or, on Codex, the 0-based line of the native session log reporting it, and branch_order, its place among its own branch's samples -- a conversation, on Claude the lead thread or one subagent call, on Codex the thread or one child turn; neither orders it against another branch's;
  • source: source_kind (the provider's own kind of request), source_timestamp, source_duration_s, source_version, and source_flags, the allowlisted flags the source reported beside the counters as it reported them -- Codex's last_usage_includes_reasoning. A source timestamp is the source's own; when a collection ran is the record's ts, never a sample field;
  • attribution: model with its model_source -- stream where the stream named it, configured-fallback where it named none and the configured model stands in, unestablished where the stream leaves it unknown, and unavailable where neither exists -- and context_capacity where the stream reports one;
  • settlement: scope -- request, or request-output for an observation of a request's output alone -- status (final or provisional), and settlement, the report the status rests on;
  • counters: raw, the counters its collector allowlists, as whole counts -- a negative whole number included, and a value that is no whole count left out, its field invalid -- the normalized counters below, the overlap profile they were read under, and evidence, one state for each normalized field.

Nothing is inferred into a sample: no timestamp, order across conversations, context capacity, or model is taken from unrelated data. A marker (markers) is an explicit boundary the stream printed -- model-change, with the model and previous_model, or a compaction or reset of the context -- with the conversation_id or parent_tool_use_id of the branch it bounds, or a Codex child turn's turn_id and parent_turn_id, and none is inferred where the stream prints no such boundary. A checkpoint (checkpoints) is aggregate usage over a wider scope than one request -- a terminal total over its whole conversation, every lead-thread request of one process, or every request one model served in it, that model named beside it -- with its raw counters, turns, source_status, and an evidence map naming each counter it reported no usable count for or its own arithmetic contradicts. Neither is a request: neither is counted as one, and a reader reconciles a checkpoint only against samples of its own scope. Only allowlisted counters and correlation metadata enter any of the three: no prompt, response or tool text, reasoning text, credential, or source dictionary.

Normalization. request_normalization.py reads each request's raw counters into the same fields under its provider's profile:

Profile overlap context_input_tokens Cache writes
Codex input-includes-cache the input, which already holds its cache reads and writes inside the input
Claude input-excludes-cache input plus cache reads plus cache writes, each write once aggregate or split
Antigravity input-excludes-cache-reads input plus cache reads unsupported

output_tokens is the output, reasoning_tokens a subset of it on every profile, and total_tokens the context input plus the output. cache_read_tokens and cache_write_tokens keep the cache breakdown, and cache_write_lifetimes a Claude write's cache_write_5m / cache_write_1h split. A Claude write is its aggregate where the block reports one and its lifetime split only where the aggregate is missing; a split summing to anything but its aggregate, or one lifetime exceeding it, leaves both, and so the context input and total, conflicting. On Codex, cache reads and writes -- the writes held at least at what is known of them: their settled count, or the lifetimes reported so far where it is unknown -- that together exceed the input holding them are conflicting, the lifetimes with them, while the input stays the context input and a write nothing establishes stays unknown. The provider's own total is kept apart as source_total_tokens and never derives the common total: an Antigravity request of 278 input tokens beside 30,214 cache reads and 4 output tokens has 30,492 context-input tokens and a total_tokens of 30,496, while the 282 its source reports stays its source_total_tokens. Where the profile states what the source total sums -- input plus output, on Codex and Antigravity -- one disagreeing with those counters is conflicting, and so is one smaller than the ones that are known where another is missing, since those already bound it from below.

Each field's evidence is observed (a usable count), missing (nothing reported, never a zero), invalid (a negative number, a fraction, an infinite or NaN value, a boolean, a word, or a number of more than 30 digits, reported or spelled, which no token count reaches -- judged before anything is truncated to a count, and a string, or a number literal the scan kept exact, read exactly, never through a float that could round a fraction whole or move a large count), conflicting (two reports of the request disagree, a part exceeds its whole, or a total contradicts its parts), or unsupported (the profile has no such counter -- a limitation of the source on an optional field such as Antigravity's cache writes, but an unsupported-counters gap on the context input or the output a request is unusable without). A derived field is established only where every part is observed and otherwise takes the weakest part's evidence, so a request reporting no cache reads has no context input, while one reporting zero has its input as its context.

Coverage. Each collection states its coverage: status, reasons (each gap's code and how often it occurred, from a vocabulary fixed in request_coverage.py), limitations (what the source never reports), and scan_scope, beside scanned_lines and skipped_lines and the observed and retained counts of samples, markers, and checkpoints. The status is read off the reasons, most severe first: unavailable where nothing attributable to the invocation could be read (no-stream-events, collector-error, and the native-log reasons a Codex collection states: no-session-identity, no-launch-observation, native-log-missing, native-log-unreadable, discovery-limit, native-identity-unproven, and invocation-unattributed), source-limit-truncated where a bound cut the scan short or the source stopped answering partway (scan-limit, oversize-lines, correlation-limit, native-read-interrupted), storage-truncated where the record kept fewer samples or markers than were observed (storage-budget, counting the dropped entries), incomplete for any other gap, and complete-empty or complete where there is none, with no sample or with some. A scan a bound cut short is partial in scan_scope, so its observed count is never read as the invocation's; one that read nothing is none, and so is one whose lines established nothing of the invocation -- a native log not proven the session's own, or one nothing in which places the invocation -- however many it read, while a stream read through without an event covers it. The native-log reasons name why no line of a native session log could be attributed: the run named no session, its launch was not observed, the lookup found no log, could not read it, or ran out of bounds, or the log is not proven the session's own or proves no line the invocation's (Codex requests, below). A request leaves its own gaps where a core counter -- its context input or output -- establishes no count (missing-counters, unsupported-counters), any of its fields is invalid or conflicting (invalid-counters, conflicting-counters), its usage is provisional (provisional-usage), or it has no model (model-unattributed, or subagent-model-unestablished for a subagent's). An observation of a request's output alone (request-output scope) has its output as its one core counter, and only its output and the thinking inside it are judged, since its scope establishes no context input; the part of the request it never observed is an output-only-observations gap instead, so a collection holding one is never complete. The scan records malformed-lines itself, as below; the rest of the vocabulary is for a collector to record about its stream: no-terminal-result, unsettled-steps, unreported-usage, unindexed-frames, conversation-ambiguous, subagent-usage-unavailable, subagent-unidentified, subagent-attribution-conflicting, oversize-metadata, malformed-metadata, malformed-envelopes, malformed-usage, aggregate-only-usage -- a stream reporting usage only in aggregate, with no request to observe it on -- identity-conflicting, a frame tying together identities the stream already gave different requests, unreconciled-usage, a Codex report not proven a new request of the invocation beside the running sum it reports, or requests not adding up to that sum, and unsupported-usage-source, Codex usage reported only where no request is read from, such as a usage record no report answers.

Bounded scan. A collector reads stdout a second time, so request_scan.py bounds everything it adds, as module defaults read when a collection starts. The scan itself holds to at most 64 Mi characters of stdout (MAX_SCAN_CHARS; whitespace past them is no gap, and is looked through for as many characters again at most, any output beyond taken as unread), 4 Mi characters per line (MAX_LINE_CHARS), and 200,000 decoded events (MAX_EVENTS), each a gap where it stops or skips the scan. The correlation bounds a collector enforces are defined beside them: 20,000 correlated steps (MAX_TRACKED_STEPS), 64 subagent branches (MAX_BRANCHES), 256 markers (MAX_MARKERS), 4 checkpoints (MAX_CHECKPOINTS, the last ones a stream printed), and 128 characters of any one piece of correlation metadata (MAX_METADATA_CHARS). Metadata drops a longer id or model name whole and counts it, never cutting it -- the configured fallback model included -- and drops and counts a value that is no string apart, so a malformed field costs its own reading and nothing beside it. Each line goes through the standard JSON decoder the run parsers use, except that a number literal with a fraction or an exponent is kept as the exact Decimal it spells -- NaN where its exponent is past any Decimal -- so a counter such as 1e-400 or 2.0000000000000000001 is invalid rather than the whole number its float would round to; the run parsers still decode floats. A line shaped like a JSON object that decodes to none -- cut short, or refused by the decoder -- is a malformed-lines gap, while banner text and a value that is no object, which could never have been an event, are skipped without being one. The decoder's refusal is caught by the scan alone, for the line it was decoding: the run parsers still refuse such a stream, as Resilience above describes, so a tracked run carrying one publishes no total and reconstructs no timeline, while its trajectory record still carries the collection, marked stream_refused. A Codex collection decodes its native session log through the same decoder and gap accounting, one line at a time as a reader hands it over (EventScan.counted), keeping none: a line past MAX_LINE_CHARS -- whitespace included, short of the one line ending it: a newline, a carriage return, or the two as a pair -- is an oversize-lines gap however it arrived, and any line holding no object -- whitespace alone included -- a malformed-lines one, each scanned where it stands. The bounds a reader of that log is held to are defined beside these, so a collection reads them all from current_limits: 4,096 session directories (MAX_SESSION_DIRECTORIES) and 262,144 directory entries (MAX_SESSION_ENTRIES) a lookup examines, and 64 MiB of the log (MAX_LOG_BYTES) beside MAX_EVENTS lines a read takes; the trajectory sink's lookup and read of that log hold them, at a Codex launch and at its exit (Codex requests, below).

Antigravity requests. request_agy.py produces one observation per completed usage-bearing step of the process's own stream, on the same agy 1.4.10 captures the run accounting is pinned to. A step is keyed by its conversation and step_index and folded from every frame of it (request_agy_steps.py): a completed frame adds the counters it carries and never takes back ones an earlier frame supplied, so a repeated or sparse frame keeps the step's usage; two completed frames reporting different counts leave that counter conflicting; a frame arriving after completion and naming no state adds the counters it carries to the completed report under the same rule; and a counter only a frame not marked completed reported -- before completion, or after it under another state such as ACTIVE -- is unconfirmed, keeping that frame's count. A sample every counter of which a completed report holds is final (completed-frame, or completed-and-later-frames where a frame after completion added one); one resting on unconfirmed counters alone or in part is provisional (unconfirmed-frame, or completed-and-unconfirmed-frames). Two steps reporting equal counts stay two samples, and checkpoint steps -- helper generations -- are requests in their own right, in the order the stream completed them. raw reads input_tokens, output_tokens, thinking_tokens, cache_read_tokens, and total_tokens and nothing else of the block: the context input is the input plus the cache reads, the thinking a part of the output, and total_tokens the source total. The guide's cached step normalizes 278 input tokens beside 30,214 cache reads to 30,492 context-input tokens, keeps its total_tokens of 282 as source_total_tokens, keeps its 0 thinking tokens inside its 4 output tokens, and leaves cache writes and their lifetimes unsupported.

Only this process's steps are samples, a resumed run's included: the terminal result usage counts the whole conversation, every earlier process of it too, so it is a result-total checkpoint of conversation scope and never a request, held to the same arithmetic as a request -- a total that is not its input plus its output, or thinking beyond its output, is conflicting -- and its unusable counters named in its evidence. On the fresh captures, whose conversation is their own process, it equals the samples' sum; a resumed run's also counts the earlier processes, so its samples are never reconciled against it.

request_agy_branches.py reads which conversations a stream names -- in its init, step_update, and result events, up to one more than the branch bound -- before folding any step. An init names its conversation beside its envelope, so that name is read even where the envelope is no object; a step_update or result names it inside, so one whose envelope is no object could have named any conversation, like a line the scan left unread, and so could an event whose discriminator is no string. A frame naming no conversation, in a stream naming exactly one and spawning no subagent, is that conversation's, folded into the same step as the frames naming it; in a stream naming none it is still this process's stdout and is kept under a process-step identity; and in any other stream it is kept the same way with no model and a conversation-ambiguous gap, since it could be more than one conversation's. A later init naming no conversation is placed the same way: in a stream naming one conversation or none it is that conversation's, its model a change like any other, and elsewhere it changes no model and is a conversation-ambiguous gap. A conversation name this collection refused -- too long to keep, or no string -- is not an absent one: a stream carrying one never names only one conversation, and a process init naming one leaves the process's conversation unknown, so no other conversation the steps name is taken for it. A line the scan left unread -- past the scan bound, too long to read, or one the decoder refused -- could have named any conversation or spawned any subagent, so a stream missing one never names only one conversation either.

Each step runs on the model its own conversation's init named as it began -- a subagent's own init included. A step of the process's own conversation -- the one its first init names, or, where that names none, the one conversation the stream names besides the subagents any subagent_info names, a stream naming more than one leaving it unknown and a conversation-ambiguous gap -- falls back to the process's init model and then the configured --model (configured-fallback); an unnamed first init's model is that conversation's, so a later init naming it with another model is a change of it. A step of a subagent conversation a subagent_info named keeps its parent conversation, parent step, and subagent type, and without an init of its own no model at all, never its parent's, as does a step of any other conversation: unestablished, and a subagent-model-unestablished or model-unattributed gap. Models are kept for one more conversation than the branch bound, beside the process's own, which always has room: its steps alone fall back to the configured --model, so a model the stream named for them is never dropped for that, while another conversation's past the bound is a correlation-limit gap and leaves its steps unestablished. An init naming a different model than its conversation's previous one is a model-change marker. An init naming a model this collection refused -- too long to keep, or no string -- or one whose envelope is no object, so that any model it named went unread, leaves its conversation's model unknown from there on: a step begun before it keeps the model it began under, while a later one is unestablished, never an earlier init's model or the configured --model, and no marker is kept, since the model it changed to is unknown. A frame naming a subagent is read whether or not it carries a step index, and a later one completes the attribution earlier frames left out -- the parent conversation, the parent step, or the subagent type -- while one naming any of them differently keeps the first and is a subagent-attribution-conflicting gap. A subagent gap counts the steps that spawned it once, however often their frames repeat it, keeping no more spawning steps than MAX_TRACKED_STEPS for each of subagent-unidentified and the subagents past the branch bound: a spawning step past that has no room to be told apart from one already counted, so every frame naming it is a correlation-limit gap instead.

The other gaps an Antigravity collection records are a response or checkpoint step, or one that carried usage, the stream never completed (unsettled-steps; a tool step still running that carried no usage is none), a completed one with no usage (unreported-usage), a frame with no step index -- or one outside 0 through 2,147,483,647, which no step counter reaches -- that carries usage or a generation's step type (unindexed-frames), a subagent whose conversation exposed no usage (subagent-usage-unavailable), one subagent_info does not name (subagent-unidentified), an event naming an init, step_update, or result envelope but carrying no object under it, or naming its envelope by a discriminator that is no string (malformed-envelopes), a usage block on any step or result that is no object or names no counter (malformed-usage), a duration no float holds or that is negative, its sign judged on the exact number (malformed-metadata), and a stream with no terminal result of the process's own conversation (no-terminal-result) -- a subagent's result ends its own conversation, never the process. Once the process's first init has settled its conversation, another conversation's result takes no room, so no number of them crowds out the process's own; one printed before then could be the process's, so it is held within the branch bound, and one with no room left is a correlation-limit gap. The stream reports no timestamp, context capacity, CLI version, cache write, or compaction or reset boundary, so every collection lists those as limitations and records none of them. The run accounting is unchanged: agy_summary.py still counts each completed step's last completed frame, so where completed frames disagree the run counters keep that frame while the sample states the counter conflicting.

Claude requests. request_claude.py produces one observation per API message the process's stream printed, and one per subagent hand-back, on the same Claude Code 2.1.295 captures the run accounting is pinned to; request_claude_stream.py folds the stream, request_claude_messages.py folds one request, request_claude_counters.py reads a usage block, and request_claude_reports.py reads what the stream says of the process. A message prints a message_start stream event and one assistant frame per content block, each repeating the usage it started with, so its frames are one sample however many blocks it has -- an assistant frame keyed by the message it names (message.id, else its wrapper's api_message_id), then by its request_id, then by its place in the stream, as the trajectory keys its turn except that the trajectory reads no wrapper id, a stream event through its wrapper's api_message_id, or where it names no message by its request_id as an assistant frame is, a content event among them witnessing the message even where no frame of it reports usage, and naming its session and timestamp as any frame of it does -- while two messages reporting equal counts stay two samples. A message_start or assistant frame naming one message on itself (message.id) and another on its wrapper (api_message_id) names no one message, so it folds into neither and is an identity-conflicting gap. A frame naming a message by both its id and its request_id joins the two keys, so a start naming the request alone and a block naming both are one sample, at the line first printing it and settled under its message id, as the trajectory's turns key it; two requests held apart until a frame bridges them are folded into the one printed first, which links the turn either was numbered under by its message id. A frame joining keys the stream already named apart -- a request id another message already gave, or a message another request already produced -- joins nothing and is an identity-conflicting gap, both requests kept; a request id named for two messages names neither from then on, so a frame naming it alone settles nothing and is an unindexed-frames gap. Only ids within the metadata bound join keys -- a longer one, dropped from the sample as oversize-metadata, could never be caught contradicting another -- and a key is kept only for a request held within the bound on tracked requests, each request found by at most one key besides its own: a frame that would give it a second is an identity-conflicting gap whatever ids its frames kept, so the keys a stream names never outnumber the requests held. Its input, cache-read, and cache-write counters are the same on every frame that reports them, two disagreeing leaving that counter conflicting. Its output and thinking are settled by the message_delta naming it, which replaces the start count rather than adding to it (final, message-delta): two closing reports disagreeing leave the output conflicting, and one whose output is no count leaves it invalid. A closing report that breaks out the thinking but reports no output settles the thinking alone (final, message-delta-partial): the output is missing, never the start count beside a final thinking count. A message no closing report reached keeps its start counts as provisional (message-start), its thinking unknown, and a message_delta naming no message settles nothing and is an unindexed-frames gap where it carries usage.

raw reads input_tokens, output_tokens, cache_read_input_tokens, cache_creation_input_tokens, the cache_creation object's ephemeral_5m_input_tokens and ephemeral_1h_input_tokens, and output_tokens_details.thinking_tokens -- a lifetime or the thinking spelled beside its object standing in where the object leaves it out -- and nothing else of a block; the alternate spellings the run accounting also accepts (prompt_tokens, completion_tokens, cached_input_tokens) are not read. The context input is ordinary input plus cache reads plus cache writes, each write once: the aggregate where it is reported, its five-minute and one-hour split kept in cache_write_lifetimes, and an aggregate with no split leaving its lifetimes missing. A split contradicting its aggregate leaves the writes, the context input, and the total conflicting, and a cache_creation or output_tokens_details that is no object at all leaves its counters invalid. The thinking sits inside the output, and a message whose final report breaks out none has no thinking count. The main capture's three messages normalize to 21,517, 21,798, and 21,910 context-input tokens, the last one's 107 output tokens holding its 60 thinking tokens.

A subagent prints its messages under the parent_tool_use_id of the call that launched it and its agent_id, but no stream events, so each keeps its start output as provisional -- except where modelUsage settles it. Any frame of a message naming the agent but no call -- a block, a start or close, or a content event -- makes it the subagent's: its call is unknown, a subagent-unidentified gap, and it never takes the lead thread's model. Every frame of a message places it, so a later frame naming the call or the agent an earlier one left out makes it the subagent's, and one naming another call than an earlier frame is a subagent-attribution-conflicting gap, the first call kept. The stream fold feeds every event to the trajectory's own ClaudeTurnUsageBuilder, whose settlement is the run accounting's, and where that settles a model's sole open message -- a subagent's, in a stream whose modelUsage reports every input and cache total for the model, each equal to what the stream printed -- the sample takes that output as final (model-usage), its raw still the start count the frame reported and its thinking only what a closing report broke out. It takes it only where this collection's own counts reproduce that settlement -- the model's totals equal, class by class, the prompts of the messages and hand-backs it sums, and what its output total leaves beyond their outputs is that output -- since the accounting reads some counters otherwise than this collection does, a fraction truncated and a lifetime spelled as a string left out, and only where that settlement sums every request this collection holds: a message no assistant frame reported usage for, a start naming no message, and a hand-back naming no agent are usage it never sums, so any of them could hold the remainder it found, and each leaves every open message provisional. The builder reads the same exact numbers this scan decodes, a Decimal as the float the run parsers decode its literal as, so a whole count spelled 2.0 or 1.4561e4 -- a lifetime split's included -- settles exactly as its integer spelling does. Wherever the evidence is ambiguous -- two open messages, a total covering usage the stream did not print, or one missing a total -- every open message keeps its start count; no result.usage or modelUsage total is ever divided among requests or made into one. The message that closes a subagent prints no frame: the lead thread's hand-back for its call -- a user frame whose tool_use_result carries a usage and either names an agentId or answers a call the stream already named a subagent for -- is an observation of that message's output and thinking alone, of request-output scope, final (handback), keyed handback:<call> by the call it answers and carrying the agentId, where it names one, and its resolvedModel. Its input and cache counters are never recorded -- they are read only to check such a settlement -- so it leaves an output-only-observations gap; a hand-back answering no named call is known by its line and is a subagent-unidentified gap. One call answered twice is one sample, and a resumed subagent answering a new call under the same agent another. A subagent call the stream named -- by a system task_started frame, which also gives the subagent_type its samples carry, or by any frame on its branch, its own user frames included -- that no hand-back with usage answered is a subagent-usage-unavailable gap. On the subagent capture the subagent's message settles at 97 output tokens through modelUsage and the hand-back holds 39, 36 of them thinking.

Each message links the trajectory turn its assistant frames were numbered under by the key it is settled under (trajectory_turn) -- its message id once a frame names one, as the trajectory settles the turn -- and a hand-back the turn numbered after every message turn wherever the turns number it, where some message_delta closed a message at all. A message whose only turn is numbered under another key -- a block naming the request alone, or naming the message on its wrapper alone, which the trajectory numbers by its request id or its line, or the message named first by a stream event -- links none, since that turn holds the count it started with rather than its output. A linked turn holds the sample's output, wherever it is a count, except where the closing report named the request alone: the sample is settled by it, while the trajectory settles a turn only through its api_message_id. A scan a bound cut short, or one that skipped a line too long to read, may have missed a frame the trajectory counted, so it links no turn and settles nothing through modelUsage. The builder is held to MAX_TRACKED_STEPS like the requests: the first event taking any of its correlation maps past the bound drops it, a correlation-limit gap, and from there the turns already linked stay -- the trajectory's numbering of the events before -- while no hand-back turn is numbered and nothing is settled through modelUsage, both of which need every message. A record whose stream the run parsers refused has no turns, so the requests it keeps name none. A sample is placed at the line first printing it, and its branch_order is its place on its own branch -- the lead thread, or one subagent call (parent_tool_use_id) -- never across branches. Its id is its message id -- a stream event's api_message_id included -- (api-message), else its request_id (api-request), else position:<line> (source-position); its session_id is its frames' own, else the process's (init, then result). Its model is the one its own frames name (stream), read where the run parsers read a Claude frame's -- its message, a stream event's message, then the frame itself: a lead-thread message naming none falls back to the init model and then the configured --model (configured-fallback), while a subagent's message or hand-back naming none is unestablished, never the lead thread's. A model a frame named that this collection refused is a malformed-metadata gap where it is no string, passed over for the next place as the run parsers pass it over, and an oversize-metadata gap where it is too long to keep, the one the run parsers read; a message whose frames name no model kept but one refused is unestablished too, never the init or configured model, since the model it ran on is unknown rather than unnamed. The init frame's claude_code_version is every sample's source_version, the contextWindow the last modelUsage reports for a sample's model its context_capacity, and a frame's timestamp its source_timestamp, each only where the stream supplied it. A message naming another model than the previous one on its branch is a model-change marker with its branch's call, and a system compact_boundary frame a compaction marker.

The result frame's usage -- on the captures the sum of this process's lead-thread final message counts -- is a result-total checkpoint of lead-thread scope, with its num_turns and its subtype as source_status, and its modelUsage, which adds every subagent message, a model-usage checkpoint of model scope per model; each is held to a request's arithmetic, a lifetime split contradicting its aggregate or thinking beyond its output being conflicting in its evidence. A complete collection reconciles with the totals of its own scope -- the main capture's samples sum to its result.usage and its modelUsage alike, and the subagent capture's lead-thread samples to its result.usage -- while partial subagent coverage is never forced to match a wider total: the subagent capture's sample prompts fall short of its modelUsage by exactly the closing message's prompt, so its collection is incomplete. No capture establishes whether a resumed process's totals stop at the process. A stream reporting usage only in aggregate has no sample and an aggregate-only-usage gap.

Only this process's stream is read, so a resumed run's samples are its own, and so are an ID-less run's. The other gaps a Claude collection records are a request none of whose frames carried a counter -- a message witnessed only by its content included -- (unreported-usage), a frame whose discriminator is no string or whose message is no object (malformed-envelopes), a usage block that is no object or names no counter this collection reads (malformed-usage), a stream with no result (no-terminal-result), requests past MAX_TRACKED_STEPS, subagent calls past MAX_BRANCHES, and markers past MAX_MARKERS (correlation-limit), and refused metadata. Every collection lists no-reset-markers among its limitations, the stream printing no reset of the context, and adds no-session-id, no-message-id (a sample known by no message id, every hand-back included), no-agent-id (a subagent's sample naming no agent), no-source-version, no-source-timestamps, and no-context-capacity where this stream left them out. The run accounting is unchanged: its settled rows also name the report each output rests on (message-start, message-delta, model-usage, or handback), which only this collection reads.

Codex requests. codex exec --json prints usage only on turn.completed, a running sum of the whole thread -- every request of the turn, and on exec resume every earlier invocation's too -- so its stdout holds no request, and that block is never a sample nor a source a request's size is inferred from. The requests are in the native session log the CLI writes beside it, <CODEX_HOME>/sessions/YYYY/MM/DD/rollout-<local time>-<session id>.jsonl, one JSON object per line carrying a timestamp, a type, and a payload. request_codex.py produces one observation per request the invocation's own lines of that log settled, on a sanitized codex-cli 0.167.1 capture of one session written by a fresh run and five resumes: request_codex_scope.py proves which lines one invocation wrote, request_codex_turns.py follows the turns they open and the turn each usage line settles in, request_codex_fold.py folds what the lines report, and request_codex_counters.py reads a usage block. It reads session_meta, turn_context, and compacted lines, and event_msg lines naming task_started, task_complete, turn_aborted, token_count, thread_rolled_back, an item_completed subagent activity, or a legacy sub_agent_activity, and counts token_usage_record lines (below); a response item, the world state, and the settings lines are never read.

parse_agent_request_usage calls request_codex.collect(stdout, session, fallback_model) for every Codex run, with the session the trajectory sink's native reader hands over (below); the collector itself does no I/O. Its session, a NativeSession, carries the invocation's facts -- the session id the run returned, whether it resumed one, a UTC moment read just before its launch off the clock the CLI stamps by, and, for a resume, how many whole lines the log held at that moment -- and the log's lines as (line, text) pairs it reads one at a time, never holding the log whole. A caller with no line to hand over states why instead (no-session-identity, native-log-missing, native-log-unreadable, discovery-limit, native-identity-unproven, or invocation-unattributed), and no session at all is no-launch-observation; each attributes nothing. A caller that reads the log under its own bounds shares the EventScan it records them in -- a byte or line bound reached is a scan-limit gap, a read failing partway a native-read-interrupted one -- and the collection is then partial; one handing over no scan has the collection decode into its own, held to the bounds in force. Each line is placed by the scope, NativeScope.of(invocation, scan): its read(position, line) says whether the line is the invocation's, its stamp, the envelope it is read as, whether turn knowledge was lost at it, and the turn a usage line settles in, and its refusal(stdout) names why nothing in the log can be attributed to the invocation -- which is then the collection's one reason, keeping nothing the fold read beside the lines its scan counted. A native log holds JSON objects alone, so a line holding none -- cut short, a value that is no object, plain text, or nothing but whitespace -- is a malformed-lines gap, a last line the process never finished writing among them.

The native reader, trajectories/codex_sessions.py, runs only while the trajectory sink is on, inside the request collection's failure boundary: a lookup or read that raises leaves a collector-error collection, and the trajectory, the baseline agent_exit record, and the run's accounting are written as they would have been. It looks the session up by the id the run returned and nothing else. A run that returned none, or an empty one, is no-session-identity and is looked up nowhere; its stdout holds only cumulative turn.completed sums, aggregate evidence the run accounting already reads, so nothing of it is kept as a request. The home it looks under is the one the launch observed (trajectories/codex_launch.py): just before the tracked spawn starts a Codex process with the trajectory sink on, it records the CODEX_HOME the process's effective environment names -- built by the backend's own environment owner from the run's options, an override included, taken against the directory the process runs in where relative -- or Codex's ~/.codex where it names none or an empty one; for a resume, the log the session already has, looked up as the exit looks it up -- its device, inode, and bytes, and the whole lines it holds within the read bound, one more where it runs past the bound, and no count where its last line is unfinished; and then the launch moment, as precisely as the clock gives it, so every line counted precedes it. The observation rides the tracked spawn's own launch record to the exit's launch_observation, nothing the CLI is launched with changes, and an observation that fails is logged and leaves none. An exit with no observation -- the sink off at the launch, another backend's, or one that failed -- is no-launch-observation, and a resume whose launch counted no line is invocation-unattributed; neither is looked up.

A resumed session's log stays under the date the session began, so every date directory is walked, newest first, for a regular file named rollout- and ending in -<session id>.jsonl, and a log is adopted only where the whole walk finds exactly one: it goes on past the first it finds and stops at a second, under the same date or another, which leaves no one log. A link, a directory, or a name only near the session's is never adopted, and no worktree, branch, or other session is searched. None found is native-log-missing, two native-identity-unproven, a directory or file that cannot be listed or opened native-log-unreadable, and past MAX_SESSION_DIRECTORIES directories or MAX_SESSION_ENTRIES entries examined -- which also bound what the walk holds of any listing -- discovery-limit, each attributing nothing; a launch whose lookup ends in any of them counts no line, so its resume is never read. A resume's log that is not the very file its launch counted -- another device or inode, or fewer bytes -- is invocation-unattributed, so a replaced or shortened log is never read past a count taken of another. The log is opened for the collection alone and closed as it ends, a collector that raises included, and read a line at a time, never held whole, no read asking for more than the bytes the bound has left and one more, the one that shows the log goes on past it: a line past MAX_LINE_CHARS bytes is skipped through without being kept and handed over as no line, an oversize-lines gap, a byte or line bound reached a scan-limit gap, and a read failing partway a native-read-interrupted one, each leaving the collection partial while the lines read before it keep what they prove. The same bounds hold the launch's count, which reads no further than MAX_LOG_BYTES of the log.

Nothing marks where one invocation's lines end, since a resume appends to the same file writing no session_meta, so a line is attributed only under two proofs, and where either fails nothing is and the collection says why -- never a guessed suffix. The log has to be the session's own: its first line a session_meta whose id is the returned session, an empty id naming none (native-identity-unproven otherwise). And the launch has to place the invocation. A fresh run's log did not exist before it, so every line is its own; a resumed run's lines are exactly the ones past the whole lines its log held at the launch, since the log only grows by appending -- a line stamped in the launch's own millisecond, or with no stamp at all, its sample then naming no source timestamp, included -- and a resume with no count, or one below a single line, is placed by nothing, and so is one whose log, read whole, holds fewer lines than the count. Every stamp is held against that placement, to the millisecond the CLI stamps to: an own line stamped more than a millisecond before the launch, or an earlier line stamped more than a millisecond after it, means the clock moved under the log, and so does a stamp earlier than the one before it, anywhere in the log. Each of these is invocation-unattributed, as is, where stdout was read whole, more root turns opened past the boundary than the turn.started lines it printed, none included -- a turn another process appended meanwhile, however much of the log's earlier history went unread -- or, where the log was read whole too, fewer, a turn whose parentage is unproven counted either way. A stdout line the scan could not read could have started one more turn, so such a stdout is compared with nothing, and a read cut short proves neither the turns nor the lines it never reached. A stamp no UTC moment reads as -- no ISO moment, one naming no offset, or one its offset carries out of range -- is malformed-metadata, kept as written, and places nothing.

A task_started opens a turn. One whose turn_attribution names a parent_turn_id is a child turn run in this log, whose requests are a branch of their own carrying its turn_id and the turn it was started from, opened once however often its start repeats; one naming none is a root turn of the thread, which abandons every turn still open. task_complete and turn_aborted close the turn they name, and a turn the invocation opened that none closed -- an interrupted run's, or a child turn its parent finished without, whatever requests it settled -- never finished, a no-terminal-result gap. A usage record settles in the open turn it names, else in the innermost open one, and a token_count in the turn the records written since the last report name, where that turn is still open -- a record whose turn closed since tells nothing -- or else in the one open turn; where several are open -- a parent and its child included -- and no record names one, or records name two still open, the report is placed in none: a conversation-ambiguous gap, no branch's running sum proven past it. A record naming its turn by an id this reading refused -- no string, or past MAX_METADATA_CHARS, a malformed-metadata or oversize-metadata gap -- is no record naming none: neither it nor the report after it is placed in any turn. The invocation opens its own turns before settling usage in them, so its usage settled in no turn it opened -- none open at all, the innermost open one being an earlier invocation's, which a resume printing no turn would otherwise adopt, or a record naming a turn the invocation never opened -- and a child turn it starts from a turn it did not open are invocation-unattributed too. A turn_attribution that is no object, or names a parent no string or past MAX_METADATA_CHARS, is malformed-metadata or oversize-metadata and leaves the turn's parentage unproven: it abandons no open turn, a report settling in it is a conversation-ambiguous gap, and it counts as a root turn or not. A line no reading could place -- one the scan left unread, or whose envelope nothing can be read off, a malformed-envelopes gap -- could have opened or closed any turn, the invocation's own root turn included, so past it no usage record or report is placed in any -- each report a conversation-ambiguous gap, no branch's running sum proven past it -- and neither a usage line nor a child turn's start is taken for another process's, until a root turn opens and leaves itself alone open. The turn state is bounded: past MAX_BRANCHES child turns named, or open at once, no later child turn is kept, since no later request could be told apart from its parent's, and the invocation's child turn refused there is a correlation-limit gap, whether or not a request follows it. A refused turn could make any request after it, its parent's included, so from there on no usage record or report is placed in any turn -- each of the invocation's reports a correlation-limit gap rather than a sample -- and no child turn's start is taken for another process's.

A turn_context sets the model of the turn it names, a child turn the log named or the thread's open root turn, which holds until the next -- one naming any other turn sets no model, and the invocation's is a conversation-ambiguous gap. On the capture, a resume switching models first compacts the thread with one request on the model the thread had, before the new turn's turn_context, so that request is the old model's. A thread request no turn_context precedes falls back to the configured -m model (configured-fallback); a child's without its own, or one after a turn_context naming a model this collection refused, is unestablished, and so is every branch's, the thread's included, past a line no reading could place -- which could have been a turn_context -- until a turn_context of its own names one, no model-change marked from a model left unknown. A turn_context naming another model than the one its branch last ran on is a model-change marker -- a child turn's naming that turn's turn_id and parent_turn_id -- a compacted line a compaction marker, and a thread_rolled_back event a reset marker; none is inferred. A child turn the invocation opened that settled no request, and each distinct subagent thread its lines name -- in an item_completed SubAgentActivity item, or in a legacy history's sub_agent_activity event, which a legacy history persists for every activity but completion -- whose requests are in a log of that thread's own, never read, is a subagent-usage-unavailable gap, the threads past MAX_BRANCHES a correlation-limit one, and a child turn the invocation opened or an activity naming no id a subagent-unidentified one, whether or not a request settles in it, since no branch can keep that request.

Each token_count carries a request's own counters in info.last_token_usage beside its branch's running sum in info.total_token_usage, and a request's counters are read off the first alone. A running sum equal to the last one its branch reported is a repeated notification and no request: the capture's resumed turn opens with the sum the earlier invocation left, and its compaction is followed by a context estimate whose sum does not move. A sum reporting a count of none of the counters the request beside it moves shows no repeat, however its other counters stay. A repeat giving other request usage than the report it repeats is conflicting-counters, short of the boundary, a compaction, or a reset between them. A repeat's own block and the metadata beside it are still evidence -- a block naming no counter is malformed-usage, a count no whole number invalid-counters, a part past its whole (cache reads or writes past the input, reasoning past the output) conflicting-counters, as is a count past the running sum beside it, and a malformed flag or context window malformed-metadata -- and a total its parts contradict conflicting-counters too, but for the estimate after a compaction, whose total stands beside parts all zero and is held to no running sum. One advancing by exactly the request's own counters -- on every counter all three report a count of, at least one of them moving by a count above zero, and no own count past what the sum can hold beside the least its branch's earlier reports establish it holds, which is the most any earlier sum gave or, where the last left the counter out, that and the requests proven since, an earlier invocation's included, and never less than a request any report of the branch gave, proven or not, a counter the request leaves out included, and compared as the whole number those add up to, past 30 digits as much as within them -- is a new request, so two requests of equal counts stay two; one advancing otherwise, one only counters staying at zero agree with -- the moving ones left unusable by an earlier sum -- or one after a line or envelope this collection could not read, or after a report no branch takes -- which could have held, or be, the report it repeats, an earlier invocation's included, on a branch opened after it as much as one kept before -- or any of the invocation's, on any branch, giving counters a request the earlier lines settled with no token_count reporting it could repeat, while that request is left -- a usage record no report answered, as below, which leaves the last running sum behind -- or answering such a record, which is that request reported late, or, once another branch has reported -- a report naming no running sum, or whose info is no object, included, since the request it stands for could be reported again with its sum -- any short of a record of the invocation's on its own branch, the earliest awaiting a report, giving counters it could report -- since a request records its usage before reporting it, the one evidence it repeats none of the other branch's reports, its last or an earlier one, whose sum could fit this branch's next step, as a notification the CLI repeats settles in whatever turn is open, a child turn the invocation opens included -- or one giving counters any record of the invocation's another branch awaits a report of could repeat -- within the branch bound, past which, as for one kept without its counters, none is ruled out -- which could be that request reported once its turn closed, or the first after a running sum holding less of a counter than an earlier one, or than the request reported beside it, before the boundary as much as past it, which contradicts it, and is no baseline, is an unreconciled-usage gap rather than a sample, so no earlier request is ever copied into a later invocation; its own counters are judged all the same, an invalid or contradictory one -- a count past its running sum included -- a gap beside it, a running sum holding less of a counter than that least conflicting-counters too, since a sum never shrinks, and so are a report's naming no running sum, and those of one no branch takes -- among overlapping turns, in a child turn naming no id, or past a bound -- with its running sum and its metadata. An info of null is a notification with no usage; one that is no object, or naming no running sum or no request usage, is malformed-usage. The CLI also writes a token_usage_record beside each request, repeating its counters under its response id before the report of it; no request is read off one, but every record, an earlier invocation's as much as the invocation's own, is kept with its counters on the branch of the turn it settles in, and awaits a later report of its branch whose running sum rises past the most its earlier reports establish on a counter it reports -- the one evidence a report repeats nothing, which no repeat shows, whether or not the sum it repeats is proven current, nor a sum agreeing with that on every counter it reports, however many it leaves out, nor one climbing back to it after shrinking, nor a report naming no running sum, so a resumed turn opening with the sum an earlier invocation left behind a record it left unanswered leaves that record to its own late report. Such a report answers the invocation's own earliest record whose counters it could give -- or, failing that, one kept without them -- else the earliest earlier invocation's record whose counters it could give -- every counter both give a count of holding the same count, so a record giving none rules nothing out -- so an earlier invocation's record is answered last wherever which record a report answers is in doubt; one branch's report never answers another's record, since nothing shows it is that record's report, and one of the invocation's no such report answers -- a record a report of other counts follows included -- is an unsupported-usage-source gap -- its records past MAX_TRACKED_STEPS awaiting a report, and every one behind such a record on the same branch, counted without their counters, each a correlation-limit gap -- so a log whose reports are missing never reads as an invocation that made no request. A record placed in no turn -- naming one by a refused id, or past a line no reading could place or the child turn bound -- is counted on no branch, the report after it placed in none or no branch proven past that line. An earlier invocation's record counted on no branch -- one of those, or one in a child turn naming no id or a turn whose parentage is unproven -- is answered by no report, since none can be shown to be its own. While an earlier invocation's record is left, on a branch or on none, its report could still come late, and a report coming late settles in whatever turn is open by then, a child turn the invocation opens included, so no report of the invocation's on any branch giving counters that record could repeat is proven new, nor the thread's baseline kept; no more such records are told apart than MAX_BRANCHES, past which one ruling nothing out stands for every one dropped. A record of the invocation's naming a turn it did not open is invocation-unattributed, as above; one that is no object is malformed-envelopes, and one whose usage names no counter malformed-usage, each still a record, in the innermost open turn where it names none, so one before the boundary leaves the running sum behind like any. The counters of the invocation's record are judged as any request usage is -- a count no whole number invalid-counters, one its own parts contradict conflicting-counters -- though no sample is read off them. A sample is keyed rollout-line:<line> (native-position), its position that line, its session_id and conversation_id the session, its turn_id the turn it settled in and, in a child turn, parent_turn_id the turn that child was started from, final as token-count settled it, with the line's stamp as source_timestamp, model_context_window as context_capacity -- one reported as no whole count is malformed-metadata, one left out the no-context-capacity limitation alone -- and last_usage_includes_reasoning in source_flags as reported -- a value that is no boolean is malformed-metadata. Only a fresh run names a source_version, its session_meta's cli_version: a resumed run's log was begun by an earlier process, whose version that is. Requests past MAX_TRACKED_STEPS and markers past MAX_MARKERS are correlation-limit gaps, and an id or model past MAX_METADATA_CHARS is refused metadata. A repeat's running sum still holds the request reported beside it, so one past the sum contradicts it as a smaller sum does -- but for the context estimate after a compaction, which moves its total alone and is no request; any other repeat after a compaction is held to its request as any is. A repeat of a sum its branch has proven current is read as one even once another branch has reported, since only a new request could be taken for another's report.

raw reads input_tokens, cached_input_tokens, cache_write_input_tokens, output_tokens, reasoning_output_tokens, and total_tokens and nothing else of a block. The context input is the input, which already holds the cache reads and writes; the output is apart, the reasoning a part of it, never added to it, and unknown where the block leaves it out; and total_tokens is the source total, the input plus the output. The CLI prints a write count the response did not report as 0, so a raw zero is kept in raw but establishes neither that nothing was written nor a lifetime: the normalized writes and their lifetimes are missing. The capture's first request -- 12,000 input tokens holding 4,000 cache reads and 7,000 cache writes, 500 output tokens holding 100 of reasoning -- has 12,000 context-input tokens and a total_tokens of 12,500. Contradictory and invalid counters are kept with their evidence, as on every profile. A usage record's counters are never a sample, nor a size a report leaving its own out falls back to.

The thread's running sums are checkpoints of conversation scope: an invocation-baseline, the last one before the boundary where it holds no less than an earlier one and nothing unread and no usage record no report answered followed it, and a cumulative-total for each one the invocation's requests advanced, the baseline and the last ones kept together within MAX_CHECKPOINTS -- none where it is zero -- each held to a request's arithmetic -- a counter it reports no usable count of, or that its own total or parts contradict, is invalid or conflicting in its evidence and an invalid-counters or conflicting-counters gap -- while a child turn's sums prove its requests and are no checkpoint, since nothing establishes what they span, though one reporting a counter no usable count, or contradicting its parts, is an invalid-counters or conflicting-counters gap all the same. A fresh run's last running sum is the sum of its complete samples, and a resumed run's samples are what its last advanced past its baseline -- a check, never a source of a request or a compaction -- while a thread total spanning earlier invocations is never forced to match. Where nothing else is a gap and the sum the invocation began from is known -- nothing at all for a fresh run, else the baseline -- the thread's samples add up exactly to what its last running sum advanced past it, on every counter all of them report, or the collection is unreconciled-usage. A resume no request settled usage for, such as one the provider failed, is complete-empty. Every collection lists no-request-ids, no-cache-write-lifetimes, and ambiguous-zero-cache-writes among its limitations, and adds no-source-version, no-source-timestamps, and no-context-capacity where its source left them out. No transcript text, working directory, or credential the log holds reaches the collection. The run accounting is unchanged: codex_requests.py and codex_summary.py still price the last cumulative turn.completed block once, and no sample is read by it.