A periodical about version control, git, and the future of agentic version control.

Token Cost Attribution in Production Agent Harnesses

Teams need per-agent visibility into token costs to diagnose and control production agent spending.

· 8 min read
Cover illustration for “Token Cost Attribution in Production Agent Harnesses”
AI Agent Observability · November 7, 2026 · 8 min read · 1,700 words

Token cost attribution in production agent harnesses is an infrastructure problem. Without per-agent, per-task, and per-skill visibility attached at request time, engineering teams cannot tell whether a design wastes tokens or the workload has simply grown. Useful attribution therefore begins where requests are created and enforced.

Why token cost attribution is an infrastructure problem, not a finance problem

A specific agent may be responsible, a skill may load excessive context, a retry loop may be running unchecked, or the workload may simply have grown. The total cannot distinguish among those causes. Without the identity and purpose of the requests behind it, the team has no reliable basis for deciding whether to change the agent, reduce context, constrain retries, or accept the increase.

OpenAI, Anthropic, and Snowflake Cortex expose total usage and limited user or project views, rather than the per-agent, per-task, and per-skill breakdowns needed across a production agent system. A project rollup identifies an owner, but not the behavior responsible for a spike. Several agents and tasks can contribute to the same project total while requiring very different interventions. Finance can allocate that total without giving engineering enough information to diagnose it.

Anthropic's Enterprise Analytics API, launched February 2026, adds per-user attribution but stops short of per-request granularity. Its engagement data has a three-day delay, and access is restricted to the enterprise tier. Those constraints limit its usefulness for diagnosing running agents. More fundamentally, user identity cannot substitute for the identity of an agent, task, or skill. A more detailed reporting interface does not recover operational context that was never attached to the underlying request.

GitHub Copilot, Cursor, and Windsurf migrated to token-consumption metering by mid-2026, moving AI coding costs away from a fixed per-seat line item. Usage now determines the bill more directly. Yet a majority of large organizations have deployed agents while only a minority have real-time cost visibility or direct token controls at the infrastructure level. Deployment has advanced further than the accounting and enforcement needed to govern it.

The engineering response is to preserve attribution as part of request handling. A request needs enough context to connect its usage to the agent that initiated it, the task it serves, and the skill being invoked. That context supports both diagnosis and control. A per-agent spending limit, for example, is meaningful only if consumption can be assigned to the correct agent while it runs.

Why agentic token consumption compounds in ways traditional cost models miss

A reasoning agent consumes tokens through a loop. At each step, it re-sends accumulated context, including the system prompt, conversation history, and tool definitions. As the conversation grows, the cost of continuing depends on what the agent has already accumulated. Counting only the initial user request leaves out the tokens used again and again that shape the cost profile of an agent run.

That profile can vary substantially even for the same task. Runs can differ by up to 30× in total tokens consumed, although the most expensive runs typically double the cost of the least expensive on average. Higher consumption does not imply higher accuracy. The agent also cannot predict its own usage precisely, because models tend to estimate less consumption than there will be. Self-prediction may provide a coarse signal of relative cost, but it cannot replace measurement of the requests actually made.

Parallel deployment amplifies this variability across a workforce. An agent pattern that produces manageable spend for one task can multiply consumption when deployed across a large engineering team. Predictable compute and storage models do not describe that behavior well. Attribution also becomes harder when one agent works across several repositories in a single turn. A shared-library read raises an ownership question that the overall run total cannot answer, because the work may serve more than one project.

The consequences can extend beyond the model bill. When agents create PRs faster than a merge queue can drain, conflicting PRs may trigger CI before they are found to be unmergeable. Those runs consume pipeline compute without producing mergeable work. Token attribution does not replace accounting for that compute, but task context helps connect the downstream expense to the agent workflow that caused it.

A useful accounting record must first separate what each request consumes. The four layers are prompt, tool, memory, and response. Prompt covers the system prompt, user message, and examples, and tool covers tool schemas and tool-call results. Memory covers RAG chunks and conversation history, and response covers the completion and hidden thinking or reasoning tokens.

Each layer supports a different engineering decision. The prompt is usually the largest fixed cost per request and offers substantial cache savings when stable, so separate measurement exposes prompt bloat. Memory grows as a session gets longer, so teams can tune RAG retrieval budgets on their own without changing core prompts. Tool usage needs its own accounting boundary. Otherwise, the cost of tool definitions and returned material becomes difficult to distinguish from the instructions and history surrounding them.

Input tokens constitute the largest share of overall consumption, which makes this separation especially useful in coding workflows. Iterative refinement and verification account for the majority of token spend. The first completion is not the whole workload. Measuring only that visible output obscures the context repeatedly supplied while the agent checks and revises its work. Layer accounting makes those later stages legible without treating every additional token as an equivalent optimization target.

In practice, instrumentation should attach a four-column usage record to each span at request time, using prompt_tokens, tool_tokens, memory_tokens, and response_tokens. Retroactive reconstruction from logs misses edge cases and under-reports long agentic traces. Pricing needs a separate distinction as well. Cached-read, cached-write, and batch tokens have different prices, so multiplying total tokens by a list price can materially overstate spend on cache-heavy workloads. Layer counts describe what was consumed, while cache and batch accounting help translate that consumption into cost.

Three attribution dimensions that answer different operational questions

Per-agent attribution shows which agent caused a spike. It supports detection of runaway behavior and comparisons between agent designs without conflating their consumption with the rest of a project. Per-task attribution answers a different question. It identifies the product surface or pipeline step responsible for expense, using a task identifier and a route label such as pr-review, conflict-resolution, or test-triage. Platform and product teams can then prioritize work against a specific operation.

Per-skill attribution connects that operation to the behavior used to complete it. Agent transcripts reveal which skills were invoked, how frequently they appeared, their token cost, and their contribution to the task outcome. Skills that appear in traces without contributing to successful completions are candidates for removal. The agent, task, and skill dimensions must therefore be built in parallel, because changing reporting views later without re-instrumentation depends on having all three tag types at request creation.

The gateway is the enforcement point for those tags. In a multi-agent architecture, it is the common point through which every request passes, whereas agent-level tagging alone does not reliably propagate through spawned sub-agents and shared tools. Missing attribution must be a request failure. Production systems using direct attribution reject untagged requests with a hard error instead of silently assigning them to a default bucket.

The gateway's mandatory metadata headers should include, at minimum, project ID, team, pipeline step, and cost center. Requests missing those fields are rejected with a 400 error. Project and cost center show where a cost belongs, while agent, task, and skill show the work and behavior behind it. Both belong at request creation, with gateway enforcement protecting the completeness of the record.

Shared vector database queries and system prompts loaded once for use across multiple projects may not belong cleanly to one agent or task. Proportional allocation is the appropriate complement in those cases. The allocation should be based on things teams can measure, including lines of context pulled, tool calls per project, or output tokens written. This distinguishes an explicit allocation of shared consumption from a default bucket that merely conceals missing tags.

OpenTelemetry GenAI Semantic Conventions provide an emerging schema still under development for this instrumentation. The core metric, gen_ai.client.token.usage, records token consumption per request as a histogram and allows integration with existing observability infrastructure. Trace structure is equally important to completeness. Retries and tool-call loops must have their own child spans, even when they are also recorded through the user-facing parent request. Otherwise, the telemetry omits the sub-calls where the actual consumption occurs.

Claude Code's local hook approach stores per-project usage in JSONL files, with message.usage fields for input, output, cache creation, and cache read tokens, together with model identifiers and timestamps. Teams can use those records for analytics without a live API call. They are useful for local agent tooling, but they do not replace gateway enforcement across a multi-agent production system. The distinction is whether attribution covers every dispatched request, including work delegated beyond the initial agent.

Once teams have task-level costs, model routing gives them the biggest chance to cut costs. The data shows which pipeline steps need frontier model reasoning and which can use cheaper models without a drop in quality. Without task attribution, those routing decisions are guesses. Merge-time attribution provides another concrete use by exposing CI runs spent on conflicting PRs that were never going to merge. Assigning that expense to the conflict-detection gap points to resolving conflicts earlier in the queue, before CI, rather than treating the CI system itself as the cause.

Operational protection should precede dashboard completeness. Rate limits, spend caps, and degradation fallbacks protect margin even when reporting lags, and a per-agent daily cap is the highest-leverage single control. The Linux Foundation's Tokenomics Foundation, announced June 2026 and launched August 2026, is building a standardization layer for this discipline, modeled on the FinOps Foundation's work on cloud spend.

Average cost per agent can conceal the small fraction of agents or tasks responsible for a disproportionate share of consumption. Percentiles expose that long tail more clearly. Legitimate workload growth instead appears as costs that scale proportionally with task volume and distribute evenly across agents, without disproportionate outliers. That distinction gives engineering a basis for deciding whether the next action belongs in workload planning, agent design, or runtime control.

More in AI Agent Observability