agent-swarm.devagent-swarm.dev
Guides

Cost & context computation

How cost and context-window numbers are computed across harness providers, and how to read the costSource / contextFormula badges in the UI.

The swarm tracks two related but separate numbers for every model run:

  1. Cost (USD). Each adapter writes one session_costs row per CLI invocation. The API may recompute it from the seeded pricing table.
  2. Context-window usage. Each adapter emits context_usage events; the API persists snapshots and updates aggregate columns on agent_tasks.

This page is the single source of truth for how both numbers are produced.

New session_costs rows keep two USD values:

  • harnessCostUsd is the adapter-reported number. It is useful for comparison, but advisory: adapters can have stale local rates or incomplete usage.
  • totalCostUsd is the API's canonical stored total. For priced rows, the API recomputes it from the active server-side pricing table at the row timestamp; for the other costSource paths below, it intentionally equals the harness report.

How cost is computed

Cost flows through three layers, each annotated with the path's costSource enum value (the dashboard renders this as a small badge next to every cost).

1. Adapter (worker-local)

Every adapter emits a CostData event with its advisory local total, token breakdowns (inputTokens, cacheReadTokens, cacheWriteTokens, outputTokens, reasoningOutputTokens, thinkingTokens), and a provider tag. The dollar value comes from whatever the harness reports — Claude's stream-json carries it directly; Codex doesn't, so the adapter computes locally via computeCodexCostUsd (src/providers/codex-models.ts); pi-ai self-reports stats.cost; etc.

The adapter writes via POST /api/session-costs with the provider field set.

The runner supplies one UUID id per cost record and reuses it across retries. Repeated IDs return the stored record without changing spend.

ChatGPT subscription usage shares one reporting key across harnesses: openai-codex/gpt-5.6-luna on pi and gpt-5.6-luna on Codex both store gpt-5.6-luna in session_costs.model and its per-model breakdown. Migration 271 also normalizes historical subscription rows without changing tokens or USD. Runtime selection still uses the route-prefixed task model; latest-model reports and session logs retain that route. Pricing accepts both forms.

2. API recompute

When the API receives a POST /api/session-costs with a provider tag, it does a synchronous lookup against the pricing table for (provider, model, token_class) at the row's createdAt. Four outcomes:

OutcomecostSourceStored totalCostUsd
A tagged provider/model has the required pricing rows'pricing-table'Canonical server recompute
No provider tag supplied (legacy caller)'harness'Adapter report
A tag was supplied but pricing cannot be completed'unpriced'Adapter report
amp with a billed cost from amp threads usage'harness'What Amp billed for the thread; the token price fills the per-model breakdown
amp without a per-model breakdown (the thread export failed)'estimated'Stream token totals priced at an assumed model
claude posting estimated: true (the session ended before its result event)'estimated'Per-message usage summed per model and priced from the table
acp whose target reported a USD cost in usage_update'harness'The target's cumulative session cost
Any provider posting harnessCostBilled: true with a cost (opencode on OpenRouter)'harness'What the model provider billed

harnessCostUsd always preserves the adapter's submitted totalCostUsd, even when the server replaces totalCostUsd with the recomputed value.

Token classes, cache TTLs, and input semantics

Cached reads and cache creation use their own pricing token classes. For Anthropic-billed models, cache_write is the 5-minute creation class (1.25× the base input rate) and cache_write_1h is the one-hour class (2× the base input rate). Claude reports both TTL totals. When a modelBreakdown entry does not have its own TTL split, the recompute distributes its writes using the session's 5m/1h ratio; this is an approximation for sidechains, not a claim that each sidechain independently exposed TTL data.

Input counts have provider-specific cache-read semantics:

Provider familyMeaning of reported inputTokensUncached-input calculation
claude, claude-managed, pi, opencode, dsh, amp, grokExcludes cache readsinputTokens as reported
fxReports no cache split: cache reads, if any, are inside inputTokensinputTokens as reported, all at the uncached rate (an over-estimate when the provider caches)
codexIncludes cache readsmax(0, inputTokens - cacheReadTokens)
cursorExcludes cache reads and writes (the adapter subtracts both, clamped to zero; Cursor's own count includes both)inputTokens as reported

Although OpenCode can route to OpenAI models, the currently shipped recompute treats its input as disjoint from cache reads; production event evidence showed that subtracting cache reads would zero most OpenCode input.

Per-model and request-priced usage

Claude's final result.modelUsage is preserved as modelBreakdown, including sidechain/subagent entries. The API prices every entry at that entry's own model rate, sums those totals, and stores the per-model computed costUsd in the breakdown. Top-level stored token totals are the corresponding breakdown sums when one exists, rather than only the main-thread usage. Because the breakdown takes precedence, the adapter refuses to zero-fill it: a missing, non-finite, or negative token counter on any entry drops the whole breakdown and the session falls back to top-level usage (advisory fields like webSearchRequests and per-model costUSD degrade per-field instead).

web_search is a request-priced class, not a token rate. The manual rows for claude and claude-managed encode Anthropic's $10 per 1,000 requests ($0.01/request); request counts in a model breakdown are added to that model's token cost. A missing web-search rate is treated as $0 so a small search fee cannot discard an otherwise complete token recompute.

claude-managed also adds its $0.08/session-hour runtime_hour fee during the server recompute, using the session duration and the manual runtime_hour pricing row.

3. UI badge

The task-detail and task-detail-sheet views render the costSource next to every cost via <CostSourceBadge> (PRICED, HARNESS, NO RATE, ESTIMATED). Mixed sources within a task aggregate render as HARNESS (the weakest claim).

When both USD values are available and differ, the badge tooltip shows harness and recomputed numbers. The task cost view adds a visible Δ hint above 2%. The OpenTelemetry counter agentswarm.cost.drift.usd records the absolute non-zero difference with a drift_sign attribute, making it the operational watchdog for stale adapter-local pricing or recompute drift.

SystemOne decisions on a task

A SystemOne decision (Jev, Clef) made through the system-one-decide tool is charged to the task it serves. The tool takes the task from its taskId argument, else from the caller's X-Source-Task-Id header. A caller may charge only its own task; an extension may charge the task whose event it handles. A call with no task in scope records nothing.

Each decision writes one session_costs row with kind: 'system-one', sessionId: 'system-one:<uuid>', model <host>/<model> (for example cloudflare/clef) and the decision's input and output tokens. The API prices it from pricing rows under provider system-one. None are seeded, so a decision is unpriced at $0 with its tokens kept until an operator adds rates through POST /api/pricing. Harness rows carry kind: 'harness'.

Task totals sum every row, and a SystemOne cost is never inside a harness session's cost, so totals do not double count. Filter on kind to split the two. A workflow system-one-decision node has no task and records no row.

Attribution coverage and autonomous work

The usage summary separates total spend from spend that could truthfully be assigned to a person. attributableCostUsd is totalCostUsd minus the cost of structurally human-free work. Attribution coverage is therefore attributedCostUsd / attributableCostUsd, not attributed cost divided by all spend. The response also exposes excludedCostUsd and excludedTaskCount so the autonomous population remains visible rather than disappearing from the report.

A task is structurally human-free when its stored task type is heartbeat, heartbeat-checklist, or boot-triage; when its stored JSON tags contain the heartbeat tag (including legacy rows found by the tags LIKE check); or when it is launched by a schedule with no human creator. The schedule rule covers both direct scheduled tasks and workflow roots whose run records that creatorless schedule in its trigger data. Requester-less system follow-ups of requester-less parents are also autonomous.

That classification follows the task tree recursively while descendants have no human requester. This keeps autonomous fan-out out of the denominator, but an explicitly attributed child is treated as a human handoff and stops the classification along that branch. Structurally human-free rows are excluded from attributedCostUsd even if an old or inherited requester id remains on the row, keeping the numerator and denominator a consistent partition.

The classification is computed once, when the task is created, and stored in agent_tasks.isHumanFree (migration 182 backfilled existing tasks). The usage reports read that column instead of walking every task tree per request. Every input to the rule is fixed at creation except where a mutation rewrites one: deleting a user without a replacement clears the requester and the workflow run creator, deleting a workflow removes its runs, deleting a task removes a parent, and completing a task can add tags. Each of those reclassifies the affected tasks and their descendants, so the stored flag matches the rule over the current rows.

The work per request is bounded, because the size of a task tree is not. A request reclassifies at most 500 tasks, walking down from the changed task breadth first, in the same transaction as the change. Whatever is left of a larger tree is recorded in human_free_reclassify_queue in that transaction, and a background drain finishes it in batches of 500, one transaction each. Until the queue is empty the stored flag of a queued descendant is its previous value, so the usage reports can lag by seconds for a very large tree. The queue survives a restart.

The usage endpoints (/api/session-costs/summary, /api/attribution/by-person) cache each reply per filter set. A reply is fresh for 30 seconds. Until its total age reaches 120 seconds (counted from when it was loaded), requests still get it while one background query refreshes it. A request that finds it older than that waits for a new query. The first request past the 30 seconds only starts the refresh and still receives the old reply, so a new session shows up on the request after that: about one poll later for a client that polls every 30 seconds. Changing a credential's plan or name clears the cache.

The By Person view uses the same requester data model, but it is not a grouping of the cost denominator and reads the same stored flag. It reports work outcomes rather than a cost score: human-requested root tasks supply Problems Initiated and Problems Shipped, while each person's full task trees supply Agents Reached, Repos Reached, and Surfaces Reached. Requester-less autonomous roots and heartbeat-classified roots do not belong to a person. The metrics stay side by side and are never summed into a composite ranking.

How the pricing table is populated

The pricing table starts with a boot seed from the vendored models.dev snapshot at src/be/modelsdev-cache.json plus a small set of manual overrides for items models.dev doesn't carry. The committed snapshot is now fallback-only for pricing freshness: it gives a cold-start DB usable rows when models.dev is unavailable, while src/be/pricing-refresh.ts owns live price updates.

After boot, the API server runs an in-process models.dev refresher once immediately and then every 12 hours. It fetches https://models.dev/api.json with If-None-Match, projects the response through the same buildModelsDevSeedRows() logic, inserts a new effective row only for new models or changed prices, and prunes history to the latest two rows per (provider, model, token_class).

The same refresh also feeds the runtime model catalog at GET /api/models-catalog (src/be/models-catalog.ts) — a slim projection of the picker-reachable providers. The UI model picker prefers that live catalog, so newly released models appear without redeploying; the committed snapshot (still symlinked at ui/src/lib/modelsdev-cache.json) remains the build-time fallback for names, labels, and context windows while the request is in flight or the server predates the endpoint.

  • Projection rules live in src/be/seed-pricing.ts:
    • Anthropic models → rows under both provider='claude' AND provider='claude-managed'. Shortnames (opus/sonnet/haiku/fable/mythos) also land under the current default full id; Fable 5.1 and Mythos 5.1 use verified fallback rates until the vendored models.dev snapshot includes them.
    • OpenAI models → provider='codex'.
    • OpenRouter models → provider='opencode', provider='pi', provider='dsh' and provider='grok'; google/* models also land under provider='gemini'.
    • DeepSeek direct-API models (the models.dev deepseek section, bare ids such as deepseek-v4-pro) → provider='dsh'.
    • Anthropic, OpenAI, Google and Fireworks models (the models.dev anthropic, openai, google and fireworks-ai sections, in the vendor's own ids) → provider='amp'. Amp reports gpt-5-nano-2025-08-07 and accounts/fireworks/models/glm-5p3-flash; the lookup drops -YYYY-MM-DD snapshot dates and a provider/ pin prefix.
    • xAI models (the models.dev xai section, bare ids such as grok-4.6) → provider='grok'. The base rates only: xAI's higher rate above 200k context is not applied. They price the per-model breakdown; the row's total is what xAI billed (see grok below).
    • OpenAI, Anthropic, Google and xAI models (bare vendor ids) → provider='cursor'. Cursor bills the vendor's API rates and names the models by the vendor's id.
    • NaN and Helmcode models (the models.dev nan section and the helmcode section built from the provider registry) → provider='pi' and provider='opencode' under their nan/<id> and helmcode/<id> ids, at $0 input and $0 output. Both providers bill a flat rate per key, so the marginal cost of a session is $0. The rows come from the same projection, so they land at boot seed and on refresh, and sessions on these models record $0 with costSource: 'pricing-table', not unpriced. Helmcode is not on models.dev; its five models come from the provider registry (packages/model-catalog/src/openai-compatible-providers.ts).
    • Cursor's own Composer models → provider='cursor' from CURSOR_FIRST_PARTY_PRICING, at Cursor's published Composer 2.5 (Fast) rates: $3.00 input, $0.50 cache read, $15.00 output per million tokens. Fast is Composer's default variant, and composer-2 is retired and rerouted to Composer 2.5. default (Auto) bills at the routed model's price, has no rate of its own, and stays unpriced. See Cursor.
  • Manual overrides (claude-managed runtime_hour at $0.08/hr, devin acu at $2.25): MANUAL_PRICING_OVERRIDES in the same file. Each entry carries its source URL and a verified date.
  • Runtime refresh: src/be/pricing-refresh.ts updates pricing rows in-place after boot and every 12 hours. It only adds newer effective rows and never deletes pinned entries from the committed snapshot.
  • Snapshot refresh procedure: run bun run scripts/refresh-modelsdev-pricing.ts when the committed fallback/UI catalog needs a source update. Commit it alongside the PR.

Operator reference: src/providers/pricing-sources.md.

How context-window usage is computed

The unified formula

After Phase 9, every adapter uses one formula:

contextUsedTokens = inputTokens + cacheReadTokens + cacheCreateTokens + outputTokens

Helpers: computeContextUsedUnified and clampContextPercent in src/utils/context-window.ts. The emitted event carries contextFormula: 'input-cache-output'.

Pi-mono is the exception: pi-ai owns the formula and we just relay its numbers. Those snapshots are tagged contextFormula: 'pi-delegated'. Devin's API doesn't report context info at all; we omit the event rather than fake zeros.

Per-model window resolution

getContextWindowSize(model, reportedWindow) prefers a positive finite window reported or enforced by the running harness. The runner retains the latest valid window from context or compaction events, including throttled events, and uses it for the completion snapshot. For example, a live 272k window stays 272k at completion even when the API catalog advertises 1.05M. Codex retains its last reported window when a subsequent notification omits it. The runner and adapter-side lifecycle handler resolve their completion snapshots independently. A result without prior context updates still carries the result model's catalog window.

Without a live window, the helper resolves the model catalog:

  • Shortnames (opus/sonnet/haiku/fable/mythos)
  • Family-versioned ids (claude-sonnet-4-6)
  • Claude 5.1 premium ids (claude-fable-5-1/claude-mythos-5-1)
  • Dated full ids (claude-sonnet-4-6-20251004) — by stripping the 8-digit date suffix and retrying

Fallback is 200k. Pre-Phase 4 the dated form fell to 200k unconditionally — wildly wrong for opus/sonnet 4.x.

peakContextTokens and contextWindowSize

agent_tasks.peakContextTokens (renamed from totalContextTokensUsed in migration 063) is a monotonic max across all snapshots for the task — never regresses when a later snapshot reports a smaller value. This mirrors Claude Code's status-line "peak context" idea.

agent_tasks.contextWindowSize is set on the FIRST snapshot that carries one, not gated on eventType='completion'. Subsequent snapshots leave it alone.

Request composition and cache-hit ratio

Cache-hit ratio per call

The session log shows one chip per LLM call: hit = cacheRead / promptTokens. The session ratio is Σ cacheRead / Σ promptTokens over all calls. promptTokens is everything the call sent, cached or not:

HarnessSource linepromptTokens
claudeeach assistant line's message.usage, deduped by message.idinput_tokens + cache_read_input_tokens + cache_creation_input_tokens
codexcontext.updated → lastinput_tokens (already includes cached input)
opencodesession.step.ended → tokensinput + cache.read + cache.write (input excludes cache)
picall_usage line from message_endinput + cacheRead + cacheWrite

Composition manifest

POST /api/tasks/{id}/request-composition stores one manifest per session (request_composition, seq 0) and a new seq only when the static parts change. Each part has chars, estTokens = ceil(chars / 4) and a fidelity:

  • exact: we measured the text that was sent. Our system-prompt sections, persona, CLAUDE.md, operator SYSTEM_PROMPT, task prompt and memories are always exact.
  • estimate: the server sized it. Swarm tool schemas on claude and codex, and the skills listing where the harness formats it.

Two values are derived at read time and never stored. The residual (harness base, unattributed) is max(0, P_first − Σ estTokens × tokenRatio), where P_first is the session's first main-thread call. History for call k is P_k − Σ estTokens × tokenRatio − residual.

Exact parts on pi and opencode

Pi and OpenCode let an extension see the request before it is sent, so their sessions also post a source: "harness-hook" manifest (seq 1):

  • pi: before_provider_request gives the provider payload (Anthropic, OpenAI Chat, OpenAI Responses or Google shape).
  • opencode: the plugin's context hook gives system, messages and tools. OpenCode fires it once per agent-loop step (SessionModelRequest.prepare("primary") in @opencode/core 2.1.4), so every primary call is seen. Subagent child sessions are skipped.

The worker measures the system prompt, each tool group (mcp:agent-swarm, other MCP servers, harness:builtin) and pi/OpenCode's own <available_skills> block. It posts after the call's usage arrives, and only when the system prompt or tool set changed. The server merges this with the session's worker manifest. Our parts carry over. The system-prompt chars they do not cover become an exact harness:base part. On the first call, message text beyond the task prompt becomes harness:messages. Measured tool groups replace the estimate. The residual of a hook manifest is near 0 by construction.

Token ratio calibration

Each hook manifest yields ratio_obs = promptTokens / (payloadChars / 4). The manifest keeps its own ratio_obs as tokenRatio. The server folds it into a per-provider EMA (α = 0.2, seeded by the first observation, bounded 0.5 to 2.0) in KV, namespace swarm, key request-composition/token-ratio/<provider>, value { ratio, samples }. Every later manifest for that provider stores the current EMA as its tokenRatio. The ratio lives in KV because a global swarm_config write reloads every integration.

Claude and codex have no payload hook, so their ratio stays 1.0 unless an operator sets the key (a bare number or { "ratio": 1.1 }):

curl -X PUT "$MCP_BASE_URL/api/kv/_/swarm/request-composition%2Ftoken-ratio%2Fclaude" \
  -H "Authorization: Bearer $AGENT_SWARM_API_KEY" -H "X-Agent-ID: $AGENT_ID" \
  -H "Content-Type: application/json" -d '{"value": {"ratio": 1.1}}'

Per-provider notes

  • claude / claude-managed: token rates from models.dev. claude-managed also has a per-session-hour runtime fee (token_class='runtime_hour'); the worker computes a preview locally via claude-managed-pricing.ts, and the API's recompute path overrides with the canonical value.
  • codex: each thread/tokenUsage/updated notification carries total (cumulative for the thread), last (the most recent model request), and modelContextWindow. On each terminal turn, including failed and interrupted turns, the adapter converts the latest total to a delta before it updates CostData. This prevents the same usage from being charged again after a later turn. Context comes from last on every notification, so it updates during the turn: last.inputTokens (which already includes cached input) plus last.outputTokens, against the latest reported modelContextWindow, with a models.dev fallback before the first valid window report. A turn's summed usage is never reported as context, because one turn can span many model requests and tool calls. Cache writes are input details. Codex 0.153.4 reports cache-write tokens separately, and the adapter includes them in CostData.
  • pi-mono: cost passes through verbatim from pi-ai's stats.cost. The adapter sums assistant message_end.message.usage.reasoning into reasoningOutputTokens, including partial usage on failed or aborted sessions. These tokens are already included in outputTokens, so they do not add cost. Context snapshots tag contextFormula: 'pi-delegated'. durationMs is real wallclock. Per-turn outputTokens are derived from session-stats delta.
  • opencode: OpenCode 2 runs in-process. Each session.step.ended becomes a context snapshot with the unified formula; contextPercent is clamped to [0, 100]. session.usage.updated carries the session's cumulative tokens. Its output excludes reasoning, so the adapter reports output + reasoning as outputTokens. OpenCode prices tokens from its own catalog, and the opencode rows hold OpenRouter's model-level list price; both are the cheapest endpoint's rate, while OpenRouter bills the endpoint that served the request (measured 2026-10-14: deepseek/deepseek-v4.1-flash lists $0.0441/M input but Together served it at $0.30/M). For an openrouter/ model the swarm plugin reads each OpenRouter response's usage.cost through OpenCode's http.response hook. When every response carried one, the adapter posts the sum with harnessCostBilled: true and the API keeps it (costSource: 'harness'); otherwise it posts OpenCode's estimate and the API prices the tokens from the table. The plugin also answers OpenCode's title hook, so no title request runs on OpenCode's small model.
  • dsh: dsh reports tokens, not money. Each status.step_end.usage (one model call) becomes a context snapshot with the unified formula; the summed tokens become CostData with totalCostUsd: 0 and provider: 'dsh', and the API prices them from the dsh rows (openrouter/ stripped for OpenRouter models). dsh's own deepseek-flash id is not in models.dev, so it stays unpriced.
  • amp: Amp's stream reports tokens but no money and no model. Each assistant message's usage becomes a context snapshot with the unified formula (window unknown until the session ends). At the end the adapter reads amp threads usage <id> --details for what Amp billed and amp threads export <id> for the model of every request and Amp's context window. When every request was billed through Amp, the billed dollars go out as totalCostUsd and the API keeps them as costSource: 'harness': they cover subagent threads and title requests the export misses (on short live threads the token price was 30 to 70% of the billed figure). Otherwise totalCostUsd is 0 and the API prices the per-model breakdown; a request routed through a linked provider such as a ChatGPT subscription records $0 in Amp and is billed outside it, so the token price is the conservative figure. Amp's cache_creation_input_tokens is billed as cache writes for Anthropic models and as plain input for every other vendor. When the export fails, the adapter posts the stream's raw counts under the requested mode or pin with no breakdown. The API never records $0 for it, because budget admission sums totalCostUsd and a zero row would let repeated sessions spend unchecked. It prices the stream totals at an assumed model and tags the row estimated: the pin when the table has its rates, otherwise the model the mode runs (AMP_ESTIMATE_MODELS in src/utils/amp-models.ts, measured 2026-10-05: low → GLM-5.3 Flash, medium → Claude Opus 5.5, high → GPT-6 Astra, ultra → Claude Fable 5.1), otherwise the medium model. Cache-creation tokens follow the same Anthropic-only cache-write rule. Only a broken pricing seed (no rates for the fallback model) leaves the row unpriced.
  • grok: the Grok CLI runs on the shared ACP client but sends no ACP usage. The prompt response's _meta.usage carries the prompt's cumulative tokens and costUsdTicks (xAI's bill, 1e-10 USD). Grok's inputTokens include cache reads and its outputTokens exclude reasoning (verified live: the converted tokens at models.dev rates equal the ticks exactly), so the adapter reports input − cacheRead and output + reasoning. The billed USD wins over the table (costSource: 'harness'), as for amp; the grok rows fill the breakdown, one entry per _meta.usage.modelUsage model. The row's model and its context window are _meta.modelId, the model that ran, not the one requested. An openrouter/<id> model reports no ticks and prices from the OpenRouter rows, each reported model keeping the openrouter/ prefix. An abort waits up to 3s for the cancelled prompt's answer, so a session the server already closed keeps its cost row.
  • fx: fx runs on the shared ACP client. Each session/prompt answer carries usage { inputTokens, outputTokens }, and usage_update { used, size } gives the context fill and window. fx reports no USD and no cache-read or cache-write split, and its counts exclude its sub-agent and helper-model calls. The adapter posts the tokens with totalCostUsd: 0 and provider: 'fx'; the API prices them from the pricing table with the openrouter/ or vercel/ routing prefix stripped (costSource: 'pricing-table'). The figure is an estimate: every input token is priced uncached, and sub-agent usage is missing.
  • cursor: @cursor/sdk reports tokens per run, summed over the run's model calls, and no per-call figure. agent.getUsage() (billed cents) answers feature_unavailable for local agents, so CostData carries tokens with totalCostUsd: 0 and provider: 'cursor', and the API prices them from the cursor rows. Cursor's inputTokens includes cache reads and writes; the adapter subtracts both, clamped to zero, to report fresh input separately. The context snapshot is the run's per-call average ((input + cacheWrite + output) / (tool rounds + 1)), tagged peak-proxy because it under-reads the last call. Composer models price from Cursor's published rates (see above); default (Auto) stays unpriced. The result is a list-price estimate: it ignores plan discounts, included usage, and the Teams/Enterprise Cursor Token Rate.
  • devin: ACU-based pricing (token_class='acu', $2.25 per ACU). No per-token cost. No context events (the API doesn't report context info) — peakContextTokens remains null for devin tasks.

Gotchas & known limitations

  • Internal-ai Gemini calls are not yet costed. src/utils/internal-ai/models.ts:19-25 routes through OpenRouter for summarization/rating but doesn't yet emit session_costs rows. The pricing table now has gemini rows ready; instrumentation is a follow-up.
  • Codex context is the latest request, not the turn. Cost uses per-turn deltas of the cumulative total; context uses the per-request last snapshot. Rows written before this split summed a whole turn and could exceed the window (clamped to 100%). Old peak-proxy rows in task_context_snapshots remain correct for their original formula and are not directly comparable to current input-cache-output rows.
  • Claude Haiku 5.5 long-context tier is not applied. A Haiku 5.5 request with a prompt over 100k tokens bills at 5x the base rates. The recompute sees session totals, not per-request prompt sizes, so it prices every Haiku 5.5 token at the base tier and under-counts those sessions. harnessCostUsd carries the tiered figure.
  • Claude thinkingTokens is a subset of outputTokens. The adapter reads it from the result line's usage.output_tokens_details.thinking_tokens. It is informational; the output rate already prices it.
  • Model-id key mismatch. Some adapters use harness-prefixed ids (openai-codex/gpt-5.4-mini); pricing-table seeds use the stripped form (gpt-5.4-mini). Pick one convention if you're adding a new mapping.
  • Timestamp convention split. session_costs.createdAt and task_context_snapshots.createdAt are TEXT ISO 8601; pricing.effective_from / budgets.createdAt are INTEGER epoch-ms. Documented in 046_budgets_and_pricing.sql:17-22; not a near-term cleanup.

ACP prompt usage

ACP targets can supply optional token usage in the session/prompt response. The adapter maps inputTokens and outputTokens directly, and maps cachedReadTokens / cachedWriteTokens to the corresponding cache counters. Missing counts remain undefined at the adapter boundary. JSON serialization omits them; the session-cost API and DB deliberately retain their existing zero-coalescing behavior for input, output, cache-read, and cache-write counters. Persisted costs, pricing computation, and UI displays therefore cannot distinguish absent usage from measured zero. Preserving that distinction end to end would require a separate request/DB/response contract change. Context-window usage_update totals never substitute for billing tokens.

The acp_prompt_response raw session log retains the bounded, scrubbed usage payload and optional _meta; usage: null records an absent payload.

A target can report money in usage_update.cost (amount plus an ISO 4217 currency). ACP defines amount as the session's cumulative cost, and OpenCode 1.18.34 sends it that way: two turns in one session reported $0.0172 and then $0.0345. The swarm sends one prompt per session, so the adapter takes the latest USD amount as the session total and sends it as totalCostUsd. The API stores it as costSource: 'harness'.

ACP does not infer USD or a pricing alias from its target. When the target reports no cost, or reports it in a currency other than USD, totalCostUsd stays 0 and a session with an unresolved (acp, model) pricing identity remains unpriced, even when token counts are available. The raw usage_update session log keeps the reported value. A requested model ID is insufficient evidence for a rate mapping when the target can reject that model and fall back to another; a target-reported cost does not depend on the model ID, so it needs no rate.

Session credential attribution

Workers capture credential type, credential suffix, and harness at execution start. Each resume uses a new runner session and captures its own credential. The cost API accepts attribution only from operator keys and matching worker tokens, including runtime tokens. Task tokens, script tokens, and user tokens cannot assert attribution. The API rejects conflicting session identities and preserves the first stored report on repost. Legacy reports remain accepted with null attribution. Historical rows remain null because the task's latest credential cannot prove which credential executed an earlier session. Summary totals and daily rows expose credentialUnattributedCostUsd and credentialUnattributedSessions separately from subscription cost. The Usage page labels these costs as unattributed because their billing type is unknown.

Session counters retain their harness semantics. Codex input includes cache reads. Claude and Pi input exclude cache reads, including Pi sessions that use a Codex credential. Do not add cache reads to Codex input when calculating combined usage. Missing cache measurements remain null, while measured zeroes remain zero. Historical cache zeroes retain their original values because their measurement provenance is unknown. The existing summary counters remain separate. They do not normalize mixed harness input.

Observed usage within provider windows

GET /api/keys/window-usage returns independent provider windows and Swarm-observed usage. It accepts optional keyType, keySuffix, scope, and scopeId filters. It uses the same authenticated read posture as /api/keys/status. Scope filters select telemetry records. Session attribution spans every execution of that credential, across agents and scopes.

Each window includes credential identity, windowKey, startsAt, endsAt, dataThrough, observedAt, and observationAgeMs. Bounds use [reset - duration, reset). dataThrough is an exclusive upper bound that never exceeds query time. Cached totals retain their original dataThrough. Fresh metadata supplies the observation age on each response. Expired windows disappear, including during the cache lifetime. Removed slots cannot return through cached totals. Unknown durations, resets, or model scopes return usage: null and an explicit unavailableReason. Legacy Claude windows use known duration and family rules. Codex primary has no assumed duration. Windows without a reset remain unavailable records. They do not assert a current quota period.

Usage calculations accept at most 256 windows and 16 distinct periods or model scopes per credential. The maximum lookback is 90 days. Queries stop after 100,001 session rows and reject results above 100,000 rows. Requests beyond these bounds return HTTP 422 without partial totals. Credential and scope filters can reduce the requested population. Longer provider limits remain visible on the Providers page, even when observed usage is unavailable. Cache misses share a process-wide budget: eight immediate calculations, then one additional calculation per second. HTTP 429 includes Retry-After: 1. Cached reads remain available when the calculation budget is exhausted. Telemetry reports accept at most 256 KiB, 64 windows, and 64 account limits. The database also rejects cumulative growth beyond those counts. It preserves existing facts and removal timestamps.

accounting: "session_cost_receipt_time" describes an approximation. Tokens belong to the window containing the server insertion time of their session-cost report. A delayed report belongs to its receipt window, even when execution started before a reset. The API cannot distribute tokens across reset boundaries without event-level billing measurements. Error sessions contribute their reported tokens. completedTasks counts distinct completed tasks by task completion time and immutable session credentials. An attributable session can precede the window. Its task can still complete within the window. Retries do not multiply a task within one window. A task that used two credentials can appear under both.

modelScope distinguishes account, known Claude family, and unknown scope. The default Codex limit remains account-wide, including when it carries a normalModelSlug display alias. Other Codex limits retain unknown model scope until their chargeable models are established. Model windows require matching entries from modelBreakdown. They never substitute whole-session totals for a missing or invalid breakdown. modelUnattributedSessions counts receipt-window sessions whose stored models cannot establish attribution to a model window. Labels never establish model scope.

Each tokens counter contains value, measuredSessions, and missingSessions. A non-null value sums available measurements only. Missing measurements never become zero. No measurements produce value: null. An explicit measured zero remains zero. uncachedInput subtracts cache reads from Codex input. Claude, Claude Managed, Pi, and OpenCode input already exclude cache reads. Unknown harness semantics leave normalized input unavailable. Output, cache reads, and cache writes remain separate counters. Reasoning and thinking can overlap output. Never add them to output. Stored reasoning and thinking zeroes lack presence evidence, so this endpoint treats them as unavailable. Positive session measurements remain available for account windows. Model breakdowns cannot allocate session-level reasoning or thinking.

swarmUnattributedSessions counts reports with missing credential identity in the same receipt interval across the entire visible swarm. It includes all key types, even when the request filters one key type. It is coverage context, not missing usage for the selected credential. Historical unknown credentials never contribute to a credential's totals.

Do not add overlapping windows together. These counters describe observed activity, not provider allowance, quota consumption, or remaining capacity. Pi-only slots have no quota collector. Shared native Codex observations can still supply their windows. The endpoint caches aggregation with the existing 30-second freshness and 120-second maximum stale age. Filters, window bounds, and model scope partition cache entries. Authenticated callers share the same visibility and reuse the same cached totals. Quota reports do not invalidate the entire usage cache. Current telemetry reads prevent stale removals and resets from reusing incompatible totals.

On this page