Appearance
0032. The tokens of each model call, and a task's totals ​
Status: Accepted (2026-10-08), at the owner's request ("a token gauge: usage per model call from adam-rs to the orchestrator's log to the web, sub-agents counted apart"). The contract is the orchestration layer's usage/v1, https://github.com/vymalo/another-agentic-system/blob/main/docs/api/usage-v1.md, written beside this decision and implemented there in parallel (its ADR 0056); the page exists on main once that change merges, and until then it is in the change. Builds on ADR 0007 (run events, Caller::extensions, the journaled model step), ADR 0028 (an extension every card lists) and ADR 0031 (two bindings, one handler).
Amended 2026-10-11 (ADR 0037): OpenCode does send tokens over ACP (the last model call's on a turn's response, an unstable field, and usage_update only when the model's context limit is known, which the coder never sets); adam-acp drops both, and neither is a count per call. The per-call count is OpenCode's step-finish part, which a plugin can forward (verified in OpenCode v1.18.33's source).
Amended 2026-10-11 (ADR 0038, not built yet): the coder no longer delegates to OpenCode, so its totals have no unreported calls; the notes on OpenCode below are history.
Amended 2026-10-27 (ADR 0043): the totals object gains a sandbox member beside totals, the time the run's commands ran in a run pod weighted by the pod's shape, kept in the run's state next to usage_totals and written on the task under the same rules. The URI is the same and the card does not change; totals is always present when the object is written. Decision 5 and the Consequences below read with that member.
Context ​
Verified 2026-10-08 by reading the code at 61d2ade: adam_model::Usage held the prompt and completion tokens only, the OpenAI-compatible client dropped the rest of a response's usage, and LlmAgent summed both into Conversation::usage, which nothing reported. A subagent is a child run: its events are its own run's, and the A2A subscription of a task follows the task's run only (RunSubscription::recv filters by run), so a client never heard a subagent's work except as the parent's tool:<call id> step.
Facts the design rests on:
- OpenAI's
usage, verified 2026-10-08 in the API reference, https://developers.openai.com/api/reference/resources/chat/subresources/completions/methods/create:completion_tokens_details.reasoning_tokens("Tokens generated by the model for reasoning"; "like reasoning tokens, these tokens are still counted in the total completion tokens"),prompt_tokens_details.cached_tokens("Cached tokens present in the prompt") andprompt_tokens_details.cache_write_tokens("The unadjusted number of prompt tokens written to cache"); withstream_options.include_usage"an additional chunk will be streamed before thedata: [DONE]message", whosechoicesis empty and whoseusageis the whole request's, and "all other chunks will also include a usage field, but with a null value".platform.openai.comrefused this environment (403); the page above is OpenAI's own reference. - AG-UI's
TokenUsage, verified 2026-10-08 in the orchestration layer's vendored schema (orchestrator/crates/agui-proto/schema/ag-ui-1.0.schema.json,$defs.TokenUsage):inputTokensandoutputTokensare totals,reasoningTokens,cachedInputTokensandcacheWriteInputTokensparts of them ("never additions"), and "a provider that reports reasoning tokens beside a smaller completion count has them added in by the producer" (the same for the cache counts and the input); every count at most 9007199254740991. - A status update needs no message, verified 2026-10-08 in
a2a-lf0.3.1 (src/event.rs,src/types.rs):TaskStatusUpdateEvent.metadataandTaskStatus.messageare both optional. - ACP gives no count per call, verified 2026-10-08 in
agent-client-protocol-schema1.9.1 (src/v1/client.rs,src/v1/agent.rs):SessionUpdate::UsageUpdateis{used, size, cost}, the context used and its size, and the turn'susageofPromptResponseis behind the featureunstable_end_turn_token_usage, which this workspace does not turn on;adam-acpdropsusage_update(crates/adam-acp/src/update.rs). Whether OpenCode sendsusage_updateis unverified.
Decision ​
Usagecounts every token the contract names (adam-model). It gainsreasoning_tokens,cached_input_tokensandcache_write_input_tokens, each anOption(Nonewhen the provider did not say, left out of the JSON so a usage recorded before reads the same), and becomes#[non_exhaustive], built withUsage::newandwith_*.accounted()applies AG-UI's rule (a part above its total is added in; twice is once),saturating_addsums two calls part by part. The OpenAI-compatible client reads the three details named above, from a completion and from a stream's last chunk, and appliesaccounted().- Provider, model and window come from the model client and the deployment.
ModelClientgains two default methods:provider()(None; the OpenAI-compatible client saysopenai: nothing in a deployment names a provider today, and none is added) andcontext_window(alias)(None). The model is the alias the agent asks for.MODEL_CONTEXT_WINDOWis read with the otherMODEL_*variables (ModelConfig::context_window, a whole number from 1 to 2^53 - 1, anything else a startup problem, exit 78), and the client says it for the aliasMODELonly. It is not an agent file setting: a folder names an alias, and which model an alias is, and so its window, is the deployment's (the same folder runs against different gateways). A subagent whosemodel:names another alias reports no window rather than a wrong one. - One event per completed model call (
adam-runtime,adam-llm-agent):RunEvent::Usage(UsageEvent)with the call's id, the step it ran under, the provider, the model, theUsageand the window.LlmAgentemits it when the journaled stepmodel:<turn>returns an answer, each time the step is passed, a replay included. The id is<run id>-c<turn>-<8 hex>, made inside the step and recorded with the answer (the record'scallmember, besidestream), as the stream id is (ADR 0007, decision 10): a replay reads it from the journal and says the same report again; a call made again is another id (a process that died before the journal write asks again, and a transient retry starts at a fresh journal position). A journal written before this reports under<run id>-c<turn>. The run id makes it unique within the task, a child's too. - A subagent's call is its root's work.
ToolCtx::start_childputs, beside the root run, the root's step the child works under in the child's first message (root_step: the root'stool:<call id>, handed down to a child's children), and the child emits its reports as events of the root run (Emitter::emit_for) under that step. Not of its own run: nobody subscribes to a child over A2A, and the root's subscribers are the task's. - The A2A side (
adam-a2a-runtime). For a request that activatedusage/v1, each report is aworkingTaskStatusUpdateEventwith no message and the report in the event'smetadataunder the URI; for any other, nothing. A task that iscompleted,failed,canceledorinput-requiredcarriesTask.metadata[URI] = {"totals": [...]}for every reader, built when the task is read (task_from_view):GetTask,ListTasks, a stream's snapshot, a blocking send. A working task carries none. - The totals are the agent's state; the store does not change.
Conversation::usage_totals(adam_runtime::UsageTotals) counts every call of the run per provider and model, at most 32 entries, committed with the turn, so a task taken up again after a question goes on from them. When a child answers (its message, or the timer's read), the parent adds the child's totals, read with a new live read of a child's state,Ctx::child_state(the run's own children only, likechild_status).Conversation::usagestays the run's own calls. - Every card lists it:
ExtensionConfig::usage(),USAGE_EXTENSION, the contract's description;adam-agentandadam-coderadd it withsteps/v1andtext-stream/v1. - Bounds: a count is at most 2^53 - 1 and the counts stay consistent (
totalTokensthe sum, a part within its total); a call id, a step and a label at most 128 bytes, cut on a character boundary.
Consequences ​
- Breaking, said in the READMEs and in
adam-upgrade:Usageis#[non_exhaustive]with three new fields (a struct literal outsideadam-modelbecomesUsage::new(..));RunEventhas a new variant,Usage(an exhaustivematchneeds an arm; a process that predates it drops it, asadam-notify-postgresdoes every event it cannot read);ModelConfighas a new public field,context_window;Conversationhasusage_totalsandroot_step(both serde-defaulted, so a stored state reads);adam-runtimenow depends onadam-modelfor the token counts. No required trait method and no store change:ModelClient::providerandcontext_windowhave defaults, and the totals are in the state every store already keeps. - A journal entry of a model call holds one more member,
call; a build that predates it ignores it. - What the totals miss, by design: the call of a try that failed transiently and was retried (the try's state is abandoned, and the retry's own call is counted), the call of a turn a cancel ended, the calls of a child whose parent was canceled before it answered (the child is not canceled: child runs), a remote (
a2a:) subagent's calls (its own agent's task; AG-UI's rule: an agent run as a separate run reports its own) and OpenCode's (ACP says none). The sum of the live reports can therefore exceed the totals by exactly those; the contract keeps the totals as the record. - OpenCode reports nothing: the coder's
Hand to OpenCodestep has no report and its tokens are in no total. Counting them needs ACP's turn usage, an unstable feature of the protocol today. - A client that reads a stream gets the totals from the task (
GetTask, or the snapshot ofSubscribeToTask); the status update that ends a stream carries no metadata, as the contract places the totals on the task. - The SDK writes a number of metadata as a float on both bindings, a whole one (
41250.0); the bound of 2^53 - 1 keeps it exact. - The scripted models of
dev/wiremock/mock-openaisay cached and reasoning tokens in every answer (both forms),compose.yamlsetsMODEL_CONTEXT_WINDOWfor the coder, anddev/greeting-e2e.shactivates the extension and checks the greeting's report and the task's totals. The chart and the operator have no value of their own for the window yet:config.extraEnvsets it.
Alternatives considered ​
- Totals from the journal (every recorded
model:*entry, abandoned tries included). Rejected: aGetTaskor a page ofListTaskswould read every journal entry of every task and of every child, and nothing lists a run's children (Store::childrendoes not exist,docs/reference/child-runs.md). - Totals in a store column. Rejected: a
Storemethod and a migration in three stores for what the state already holds. - The subscription follows the children's runs. Rejected for the same reason: it would have to know the children.
- A call id from the journal position alone. Rejected: the position is the runtime's (
Ctxkeeps it), and a call made again after a crash would reuse the id of the call that was lost; the turn and a suffix made in the step mirror the stream id. - Reports as
RunEvent::Custom. Rejected: untyped, and every host would parse JSON to read them. - The window in the agent's files. Rejected in decision 2.
- The totals also on the last status update of a stream. Not done: the contract puts them on the task; a change of the contract would be the orchestration layer's to make.
Verified and unverified ​
- Verified 2026-10-08 by tests in this repository: the wire parsing of the three details, from a completion and a stream's last chunk, absent ones, and reasoning or cache counts beside a smaller total added in (
crates/adam-model-openai/src/wire.rs);MODEL_CONTEXT_WINDOW(crates/adam-service/src/config.rs,bin/adam-agent/src/config.rs); one report per call, a subagent's (and its own child's) on the root under the root's step, a replay under the recorded id, a retry under another, the totals (crates/adam-llm-agent/tests/usage.rs); the largest report fits aNOTIFYpayload (crates/adam-notify-postgres/src/wire.rs); the A2A side, both bindings over HTTP, a resubscribe, the totals of a completed, failed, canceled, waiting and resumed task (crates/adam-a2a-runtime/tests/usage.rs); the coder end to end over the OpenAI-compatible client with its explorer (bin/adam-coder/tests/e2e.rs); the cards (bin/adam-agent/tests/agent.rs,bin/adam-coder/tests/fixtures/agent/card.json). - Verified 2026-10-08 against the contract (
docs/api/usage-v1.mdof the orchestration layer, proposed 2026-10-08): the URI, the card entry, the activation, the report's members, the totals' place and states, the bounds. - Unverified: which OpenAI-compatible gateways send the details, and whether
cache_write_tokensis disjoint fromcached_tokenseverywhere; the dev stack's check (dev/greeting-e2e.sh) and the scripted models' twins (wiremock_compose), which CI'scoderandcomposejobs run and this change did not run (no Docker here); how the orchestrator and the screen read the reports, which is that repository's.