Agent in Production
ObservabilityLong read

Choosing a Session Logging Stack That Captures Tool Calls, Diffs, and Token Attribution End to End

Token attribution, diffs, and tool traces must share a run ID to answer what the spend produced.

· 9 min read
Cover illustration for “Choosing a Session Logging Stack That Captures Tool Calls, Diffs, and Token Attribution End to End”
Observability · November 6, 2026 · 9 min read · 2,011 words

To see the whole AI coding agent session, three records must be joined: tool-call traces, file diffs, and token attribution. Choosing a session logging stack means choosing how those records share a run_id, preserve authorization history, and remain queryable when writes arrive at different times. OpenTelemetry provides the tracing foundation, but structured diff events, attribution metadata, and an independent logging path make the record accountable end to end.

Why session logging for coding agents is different from application logging

Vendor billing interfaces answer “who used how much?” Engineering leaders need to answer the CFO’s question, “what did we get for this spend?” Those are different queries over different evidence. Under a seat plan, how much the seats were used could show their value, while usage-based billing needs a link between what a session cost and what it produced. Total counts cannot show a silent seven-retry loop or explain why subagent fan-out drove up the bill for a small task.

Application logging leaves another gap in that evidence. It captures the API call at the end of an authorization chain, rather than the chain connecting the user, agent, MCP server, and downstream API. Incident review needs that chain to establish who authorized an action. This is not simply another observability configuration.

The useful mental model is a queryable join record, with one row per session connecting what the agent did, what it changed, and who or what triggered the spend. Each layer answers a different question. A trace alone helps with debugging, but cannot show whether the work was worth its cost.

Layer one: the tool-call trace and what it must record

The tool-call trace is the session record’s spine. Every run requires seven field groups, including run_id, user_id, model with model_params, token_usage split by input, output, and total, latency_ms, tool_invocations[], and status with error. Each invocation must be a structured entry containing the tool name, input parameters, output value, latency, token cost, and timestamp. A stringified invocation blob prevents reliable execution-path queries. Blocked and failed calls need the same fidelity because they can trigger expensive replanning.

Decision boundaries need their own entries in that path. The useful fields are the options considered, context-window token count, recent message window, selected tool, and stated reasoning when that output is enabled. For example, a boundary entry for a failed shell command can connect its returned error to the next selected tool and the context available at selection. This locates the branch. Each subagent also needs its own run_id linked to the parent, so fresh context windows and parallel inference remain visible.

OpenTelemetry’s GenAI semantic conventions provide the starting surface. They cover model calls, token counts, latency, and tool invocation trees through execute_tool spans, but not memory read/write logs, decision boundaries, or cost attribution. Langfuse and Arize Phoenix provide agent-specific observability layers when teams pipe traces into them.

Agent exports also differ in granularity. Claude Code exposes PreToolUse, PostToolUse, SubagentStart, and SubagentStop events through Settings > Hooks, with prompt bodies disabled by default. OpenAI Codex CLI added native OTel support in 2026-05 through the [otel] block in config.toml and emits codex.tool.call.duration_ms directly. AWS Kiro’s preview exports daily per-user usage metrics, but granular agentic-loop, file-write, and prompt-template spans are not currently available. Usage telemetry alone is not a step-level trace.

Layer two: capturing diffs as first-class log events

The concrete record “step 7, tool apply_patch, file auth/middleware.go, 42 lines added, 11 removed, as part of run_id X,” provides action-level detail beyond the summary “the session produced a PR. Beyond the patch body, the schema requires the session’s run_id, tool-call step number, file paths, and whether the write was agent-initiated or human-approved. Approval changes the audit interpretation of the same patch. Without these fields, git history can show what changed but cannot link it to the execution path being checked.

The StackPulsar case on 2026-07-22 illustrates that distinction. An internal session spent 11 minutes on “refactor the auth middleware to use the new token format,” while the dashboard reported “completed, 1 file edited, 3 subagents spawned.” It fired no alert. The missing evidence was the session-level diff record.

The link must also survive beyond the session. The diff event and annotated commit need the same run_id, allowing either repository history or the session record to begin a query. A “human modification ratio” field or an “agent-proposed, human-modified” flag prevents a substantially rewritten patch from being credited wholly to the agent. Infrastructure edits need a separate severity tier. Distinguishing application code, configuration, and infrastructure enables approval gates and alert routing without requiring a person to read every patch before it is logged.

Layer three: token attribution and what "who triggered this spend" actually means

The active repository is not a reliable cost owner. A single task can touch a shared library, three feature services, and an infrastructure module, making attribution to whichever repository is active systematically misleading. Equal division across touched repositories fails in the opposite direction, undercharging complex codebases and overcharging simple ones.

Zylos AI’s 2026 research identifies direct attribution and proportional allocation as viable approaches. Direct attribution injects mandatory project ID, team, pipeline step, and cost-center tags at the gateway, booking each request to one owner at dispatch. That approach requires rejecting untagged requests. Proportional allocation instead distributes shared costs using measurable dimensions, such as context lines pulled per repository or tool calls per project. A hybrid uses direct ownership for identifiable inference requests and proportional allocation for shared-context overhead.

The ownership record must keep token categories separate. Input, output, cache write, and cache read tokens each have their own price. Repeatedly sending a large context can cost roughly ten to forty times more with a cold cache than with a warm cache, depending on the model. Claude Code’s local ~/.claude/projects/*/*.jsonl records expose those categories through message.usage, with model identifiers and timestamps. Extended reasoning also needs visibility separate from aggregate totals.

The harness is another attributable cost driver. Rule files, skills, MCP server definitions, and memory loaded at session start affect the context used on later model turns. A large CLAUDE.md in a 40-turn session is included in context 40 times. Claude Code’s /usage already attributes recent usage to skills, subagents, plugins, and individual MCP servers per machine, while team-level collection remains the gap.

Joining the three layers into a single queryable session record

The streams arrive through different write paths and at different times. Agent traces appear near real time, diffs appear after edits or PR creation, and attribution may arrive at session end or through later computation. Timestamps are therefore insufficient as join keys. A run_id must be minted before execution and propagated through every tool call, diff, and attribution entry. Parent-child links carry that identity into the work done by subagents.

Identity alone does not make the record trustworthy. The 2026 paper “LLM Agents Can Easily Tamper With Their Own Traces” describes the risk of agents altering their own execution evidence. A compliance-grade write path must therefore sit beyond the agent’s reach, using a sidecar collector or gateway-level interceptor.

The highest-leverage starting move is a dedicated identity for each agent and a single wrapper that logs tool calls before and after execution. Its records must be immutable and include blocked and failed actions. Sampling is not acceptable for an audit trail. Gateway rejection of untagged requests also prevents missing ownership from becoming an invisible accounting default.

Authorization scopes, the user-to-agent-to-MCP-server-to-downstream-API chain, and whether the session was human-approved or automated belong in the queryable evidence. NIST’s Center for AI Standards and Innovation AI Agent Standards Initiative, launched February 2026, frames the underlying gap as agents being treated as generic service accounts without dedicated identity, authorization, or accountability controls.

The GDPR split and what it does to the join

Stripping prompt bodies protects privacy but removes diagnostic context. A wrong tool parameter may originate in the prompt, an ambiguous instruction, or a misread CLAUDE.md rule. Operational telemetry can show the failure without showing where it began. The architecture must accommodate that tension rather than treating prompt collection as a single global switch.

The two-tier design separates operational evidence from conversation content. Tier 1 contains tool calls, token counts, latency, error codes, and cost, without prompt text, user content, or PII. Tier 2 may hold user data, so it needs field-level redaction before the data is stored, its own retention and access controls, and a way to handle deletion requests. The stores remain connected through a session pointer. Authorized incident review can follow that pointer without making conversation content part of the default operational query.

That separation also constrains attribution fields and tool payloads. Ownership must come from authenticated session-start metadata rather than identities extracted from prompts, while content-bearing parameters and outputs must respect the tier boundary. A user_id is not automatically free of privacy obligations merely because it is structured metadata. The intended design preserves non-personal operational evidence through deletion of conversation data, but its validity depends on what each store actually contains. Teams need counsel to verify their specific regulatory obligations, including identity treatment and retention, rather than treating the split as a compliance guarantee.

Sandbox isolation and credential lifecycle as prerequisites for a trustworthy session record

A perfect schema cannot compensate for an unbounded execution environment. Persistent, over-scoped credentials and shared state allow actions that the session record may not be designed to distinguish. Ramp Inspect illustrates the isolated pattern, running each session in its own Modal Sandbox with the application stack, agent, browser, tests, and internal tooling. Fresh filesystem snapshots move cloning, dependency installation, and initial builds out of the request path.

Credentials need the same boundary as the session. Fresh credentials minted at session start and revoked at its end make API activity attributable to that lifetime. Shared persistent credentials instead leave ambiguity about which session initiated a call. Sandbox availability is consequently a logging architecture dependency. Daytona’s June 2026 move to a closed-source production repository and end of maintained open-source self-hosting requires teams relying on self-hosted Daytona to re-evaluate their isolation layer.

The agents-as-code pattern stores configuration in reviewed repository files, allowing the session record to reference a specific configuration commit. That makes the harness auditable after execution ends. Files such as CLAUDE.md, AGENTS.md, and agents.yaml describe the rules and setup under which work occurred. Both the behavioral intent file and the capability boundary file need references in the record, connecting what the agent was instructed to do with what it was permitted to do.

What breaks in production and how to catch it before the audit does

Orphaned subagent cost appears when attribution totals exceed the sum of tool-call span costs. Without the parent-child relationship, the spend has no link to its execution path. Harness drift produces a different signal. A fingerprint of loaded configuration files can be compared with the team’s versioned configuration, exposing local divergence that changes token volume or tool selection. The loaded-file hash is the discriminator between otherwise similar sessions.

Sessions with substantially more tool calls than the median for the same task type, filtered by tool name, reveal repeated failures without requiring prompt bodies in operational logs. Write-path manipulation requires an independent source of evidence. Comparing gateway or sidecar entry counts against agent-reported trace counts exposes discrepancies as tamper indicators.

These records support four operational SLO axes. Cost per session type tracks median and 95th-percentile cost over a rolling window, so rising spend at the high end is visible in the 95th-percentile measure before the monthly bill. Diff-to-rework ratio links lines written by the agent to what humans rewrite before merge, while tool-call depth compares how long execution takes with how complex the task is. Attribution coverage measures the fraction of sessions where every token has a tagged project, team, and trigger.

The build does not require every SLO on day one. The minimum viable session record contains run_id, user_id, the tool-call trace, a diff pointer, and a harness fingerprint. Those fields establish the join before richer attribution and reliability measures are added. The SLOs then make that joined record useful for detecting cost, quality, and control failures before an audit demands the explanation.

Filed underObservability

More in Observability