← Back to Pull requests

feat(cli): add `docker agent usage` to report token and cost spend #3944

Closed
dwin-gharibi closed this pull request without merging on Aug 19, 2026 05:47 UTC
View on GitHub
dwin-gharibi dwin-gharibi commented on Aug 07, 2026 05:42 UTC
Author

Token and cost figures were reachable only from the TUI's cost dialog and from OTel, so every
headless path — --exec in CI, the API server, MCP/A2A — was blind to spend. This adds a CLI report
over the session store.

Closes #3943.

$ docker agent usage --since 24h
SESSION   CREATED           INPUT   CACHED  OUTPUT  COST   TITLE
a1b2c3d4  2026-08-06 12:04  128.4K  96.2K   4.1K    $0.42  fix the failing cache test
3 session(s)                412.7K  310.1K  11.9K   $1.28

MODEL                    CALLS  INPUT   CACHED  OUTPUT
anthropic/claude-opus-5     41  380.2K  295.0K  10.4K

TOOL             CALLS
read_file           58
shell               21

--json for CI, --session <id> for one session, --since <dur> for a window.

No schema change

This is aggregation over data already persisted: chat.Message.Usage and .Model per message,
session.Item.Cost/.Usage/.Model for non-message spend such as compaction, and
session.Session.Cost for the cumulative total.

The CACHED column is the reason token figures are summed from per-message usage rather than the
session's scalar counters — cached-input and cache-write are only broken out per message, and
without them prompt-caching wins are invisible.

Cost is reported honestly, including where it can't be

Three deliberate limitations, all surfaced rather than papered over:

Unpriced models are flagged, not shown as $0.00. A model missing from the pricing catalogue
records zero cost against real tokens — the runtime logs it, and it happens routinely. A session
that moved tokens but recorded no cost is marked CostIncomplete, its cost prints with a trailing
+, and the report ends with:

! Cost is understated: no pricing for test/fake-root

A report that quietly understates spend is worse than no report.

No per-model cost. Cost is persisted per session and per non-message item, never per message, so
attributing it across the models used inside one session is not possible without a schema change.
Tokens per model are attributable and are reported; cost per model is simply absent rather than
guessed. The package doc says so.

Tokens and cost come from different sources and can disagree. An older session whose messages
carry no usage reports zero tokens while still reporting a cost. Documented in the package doc.

Structure

pkg/usage — Aggregate([]session.Session) Report, a pure function with no I/O, so the
aggregation is unit-testable without a database or a CLI. Report is JSON-tagged and is exactly
what --json emits.

cmd/root/usage.go — flags, store access, and two more pure functions (filterSessions,
renderUsage) that are tested directly against bytes.Buffer rather than through a live command.

Sessions are newest-first; models and tools are ordered by size descending so the cost drivers come
first. Ties break on name so output is deterministic.

Tests

pkg/usage/usage_test.go (9 tests): per-session token/cost sums including the cached and
cache-write breakdown; per-model attribution with descending order; per-tool call counts;
unpriced-model flagging; newest-first ordering; non-message (compaction) item usage counted;
tolerance for items with no message, no usage, and no model; Tokens.Total() semantics.

cmd/root/usage_test.go (8 tests): --since filtering including that an undated* session is
kept (an unknown timestamp is not evidence of age) and that filtering does not mutate the caller's
slice; text rendering; the unpriced warning and the + marker; the empty case; JSON round-trip;
JSON emitting [] rather than null so jq '.sessions[]' works on a quiet day; token
abbreviation; rune-safe title truncation.

Two details worth noting because they came from testing rather than from design:

  • filterSessions originally filtered in place; the "does not mutate the caller's slice" test is

  • why it clones.
  • The JSON path originally emitted "sessions": null for an empty report, which would break the

  • --json | jq use case the help text advertises. Caught by smoke-running the real command.

    Smoke-tested end to end against a real (empty) SQLite store for the text, JSON, and --help paths.

    Verification

    Toolchain go1.26.5, darwin/arm64.

    | Check | Result |
    | --- | --- |
    | go test ./pkg/usage/ ./cmd/root/ | ok |
    | golangci-lint run ./pkg/usage/... ./cmd/root/... (v2.12.2, CI's pin) | 0 issues |
    | go run ./lint . | 1770 files, no offenses |
    | go build ./..., gofmt -l | clean |
    | go test ./... | only pkg/teamloader fails — pre-existing (Google Cloud ADC), unrelated |

    Lint initially reported 5 issues in the new code (gofumpt, perfsprint, recvcheck,
    testifylint, unparam) — all fixed. The recvcheck one was worth having: Tokens had a
    value-receiver Total() alongside a pointer-receiver add(), and since Tokens is embedded in
    JSON-serialized rows a mixed receiver set is a genuine trap. It is now a free addUsage function
    with value receivers throughout.

    One flake to be aware of: pkg/tools/mcp's TestOAuthTransport_DoesNotForwardBearerAcrossOrigins
    failed once during a full-suite run with HTTP/1.x transport connection broken: CloseIdleConnections
    called
    . It passes in isolation and this PR does not touch MCP or HTTP — noting it because it will
    bite someone else on a loaded machine.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: aheritier Review duration: 17285m
    All Vouch review confidence checks passed
    Residual risk 0.17 = Change Risk (0.80) × (1 − Review Confidence (0.78)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.80 · 650 lines diff across 8 files
    0.80
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.68 · 5 substantive comment(s)
    0.68
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    78%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Sensitive Paths sensitive_paths
    0.080
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    14 items
    docker-agent docker-agent commented on Aug 07, 2026 06:14 UTC
    Reviewer

    Assessment: 🟡 NEEDS ATTENTION

    Two logic issues found in the new aggregation code in pkg/usage/usage.go:

    1. Per-model call count can be over-counted when an item carries a model name but no usage data — see inline comment at line 141.
    2. CostIncomplete flag is not triggered for sessions whose only token spend is Reasoning tokens, because Total() returns Input + Output and excludes Reasoning — see inline comment at line 158.

    Both findings are in newly added + lines. No issues found in cmd/root/usage.go, cmd/root/root.go, or the test files.

    docker-agent docker-agent commented on code on Aug 07, 2026 06:14 UTC
    Code Review
    pkg/usage/usage.go:1
    @@ -0,0 +1,224 @@
    +// Package usage aggregates token and cost figures out of persisted sessions.
    +//
    +// It exists so the numbers the TUI shows in its cost dialog are also reachable
    +// from a headless run: `docker agent usage` reads the session store and reports
    +// what was spent, per session, per model, and per tool.
    +//
    +// # What the numbers mean
    +//
    +// Cost is taken from each session's own cumulative counter, which is what the
    +// runtime recorded as it ran — this package never re-prices anything. Token
    +// figures are summed from per-message usage, which is the only place the
    +// cached-input and cache-write breakdown is persisted.
    +//
    +// Those two sources can disagree: a session whose messages carry no usage (an
    +// older session, or one recorded by a provider with usage tracking disabled)
    +// reports zero tokens while still reporting a cost. The reverse — tokens with no
    +// cost — means the model was missing from the pricing catalogue, and is surfaced
    +// as [SessionRow.CostIncomplete] and [Report.UnpricedModels] rather than being
    +// silently reported as $0.00.
    +//
    +// Per-model *cost* is deliberately absent: cost is persisted per session and per
    +// non-message item, never per message, so attributing it across the models used
    +// inside one session is not possible without a schema change.
    +package usage
    +
    +import (
    +	"cmp"
    +	"slices"
    +	"time"
    +
    +	"github.com/docker/docker-agent/pkg/chat"
    +	"github.com/docker/docker-agent/pkg/session"
    +)
    +
    +// Tokens is a token breakdown. CachedInput and CacheWrite are reported
    +// separately from Input so the effect of prompt caching is visible.
    +type Tokens struct {
    +	Input       int64 `json:"input"`
    +	CachedInput int64 `json:"cached_input"`
    +	CacheWrite  int64 `json:"cache_write"`
    +	Output      int64 `json:"output"`
    +	Reasoning   int64 `json:"reasoning"`
    +}
    +
    +// Total is the headline "tokens moved" figure: input plus output. CachedInput is
    +// already a subset of Input, and CacheWrite/Reasoning are reported on their own
    +// rather than folded in, so adding them would double-count.
    +func (t Tokens) Total() int64 { return t.Input + t.Output }
    +
    +// addUsage accumulates u into dst. A free function rather than a method so
    +// Tokens keeps value receivers throughout (it is embedded in JSON-serialized
    +// rows, where a mixed receiver set is a trap). A nil u is a no-op so callers can
    +// pass an optional usage without checking.
    +func addUsage(dst *Tokens, u *chat.Usage) {
    +	if u == nil {
    +		return
    +	}
    +	dst.Input += u.InputTokens
    +	dst.CachedInput += u.CachedInputTokens
    +	dst.CacheWrite += u.CacheWriteTokens
    +	dst.Output += u.OutputTokens
    +	dst.Reasoning += u.ReasoningTokens
    +}
    +
    +// SessionRow is one session's spend.
    +type SessionRow struct {
    +	ID        string    `json:"id"`
    +	Title     string    `json:"title,omitempty"`
    +	CreatedAt time.Time `json:"created_at"`
    +	// Models used in the session, sorted and de-duplicated.
    +	Models []string `json:"models,omitempty"`
    +	Tokens Tokens   `json:"tokens"`
    +	Cost   float64  `json:"cost"`
    +	// CostIncomplete marks a session that moved tokens but recorded no cost,
    +	// i.e. at least one model was missing from the pricing catalogue.
    +	CostIncomplete bool `json:"cost_incomplete,omitempty"`
    +}
    +
    +// ModelRow is one model's token spend across every session in the report.
    +// Calls counts model responses, not tool calls.
    +type ModelRow struct {
    +	Model  string `json:"model"`
    +	Calls  int    `json:"calls"`
    +	Tokens Tokens `json:"tokens"`
    +}
    +
    +// ToolRow is how often a tool was called across every session in the report.
    +type ToolRow struct {
    +	Tool  string `json:"tool"`
    +	Calls int    `json:"calls"`
    +}
    +
    +// Report is the aggregate view. Sessions are newest first; Models and Tools are
    +// ordered by size descending so the cost drivers come first.
    +type Report struct {
    +	Sessions []SessionRow `json:"sessions"`
    +	Models   []ModelRow   `json:"models"`
    +	Tools    []ToolRow    `json:"tools"`
    +	Tokens   Tokens       `json:"tokens"`
    +	Cost     float64      `json:"cost"`
    +	// UnpricedModels lists models that moved tokens in a session that recorded
    +	// no cost. Sorted.
    +	UnpricedModels []string `json:"unpriced_models,omitempty"`
    +}
    +
    +// Aggregate builds a [Report] from the supplied sessions. Nil entries are
    +// skipped, so a caller can pass a store listing straight through.
    +func Aggregate(sessions []*session.Session) Report {
    +	var report Report
    +
    +	modelTokens := map[string]*ModelRow{}
    +	toolCalls := map[string]int{}
    +	unpriced := map[string]struct{}{}
    +
    +	for _, s := range sessions {
    +		if s == nil {
    +			continue
    +		}
    +
    +		row := SessionRow{ID: s.ID, Title: s.Title, CreatedAt: s.CreatedAt, Cost: s.Cost}
    +		sessionModels := map[string]struct{}{}
    +
    +		for i := range s.Messages {
    +			item := &s.Messages[i]
    +
    +			// Non-message items (compaction summaries and the like) carry their
    +			// own model and usage; they are real spend.
    +			model, itemUsage := itemModelAndUsage(item)
    +			if itemUsage == nil && model == "" {
    +				continue
    +			}
    +
    +			addUsage(&row.Tokens, itemUsage)
    +			if model != "" {
    +				sessionModels[model] = struct{}{}
    +				mr, ok := modelTokens[model]
    +				if !ok {
    +					mr = &ModelRow{Model: model}
    +					modelTokens[model] = mr
    +				}
    +				mr.Calls++

    [medium] Per-model call count inflated when item has a model name but nil usage

    The guard at line 129 is if itemUsage == nil && model == "" { continue } — an AND condition. An item that carries a model name but no usage object (e.g. a compaction summary whose model field was populated but whose usage field was not) passes the guard and reaches mr.Calls++ on line 141. addUsage correctly no-ops on nil, so token counts are unaffected, but the Calls column in the MODEL table will over-count these items as real LLM interactions.

    The intent expressed in the comment is "non-message items with their own model and usage are real spend." A consistent implementation should only increment mr.Calls when there is actual usage data to accompany the model attribution:

    			if model != "" {
    				sessionModels[model] = struct{}{}
    				mr, ok := modelTokens[model]
    				if !ok {
    					mr = &ModelRow{Model: model}
    					modelTokens[model] = mr
    				}
    				if itemUsage != nil {
    					mr.Calls++
    				}
    				addUsage(&mr.Tokens, itemUsage)
    			}
    

    | Confidence | Score |
    | :--: | :--: |
    | 🟡 moderate | 67/100 |

    <!-- docker-agent-review -->

    docker-agent docker-agent commented on code on Aug 07, 2026 06:14 UTC
    Code Review
    pkg/usage/usage.go:1
    @@ -0,0 +1,224 @@
    +// Package usage aggregates token and cost figures out of persisted sessions.
    +//
    +// It exists so the numbers the TUI shows in its cost dialog are also reachable
    +// from a headless run: `docker agent usage` reads the session store and reports
    +// what was spent, per session, per model, and per tool.
    +//
    +// # What the numbers mean
    +//
    +// Cost is taken from each session's own cumulative counter, which is what the
    +// runtime recorded as it ran — this package never re-prices anything. Token
    +// figures are summed from per-message usage, which is the only place the
    +// cached-input and cache-write breakdown is persisted.
    +//
    +// Those two sources can disagree: a session whose messages carry no usage (an
    +// older session, or one recorded by a provider with usage tracking disabled)
    +// reports zero tokens while still reporting a cost. The reverse — tokens with no
    +// cost — means the model was missing from the pricing catalogue, and is surfaced
    +// as [SessionRow.CostIncomplete] and [Report.UnpricedModels] rather than being
    +// silently reported as $0.00.
    +//
    +// Per-model *cost* is deliberately absent: cost is persisted per session and per
    +// non-message item, never per message, so attributing it across the models used
    +// inside one session is not possible without a schema change.
    +package usage
    +
    +import (
    +	"cmp"
    +	"slices"
    +	"time"
    +
    +	"github.com/docker/docker-agent/pkg/chat"
    +	"github.com/docker/docker-agent/pkg/session"
    +)
    +
    +// Tokens is a token breakdown. CachedInput and CacheWrite are reported
    +// separately from Input so the effect of prompt caching is visible.
    +type Tokens struct {
    +	Input       int64 `json:"input"`
    +	CachedInput int64 `json:"cached_input"`
    +	CacheWrite  int64 `json:"cache_write"`
    +	Output      int64 `json:"output"`
    +	Reasoning   int64 `json:"reasoning"`
    +}
    +
    +// Total is the headline "tokens moved" figure: input plus output. CachedInput is
    +// already a subset of Input, and CacheWrite/Reasoning are reported on their own
    +// rather than folded in, so adding them would double-count.
    +func (t Tokens) Total() int64 { return t.Input + t.Output }
    +
    +// addUsage accumulates u into dst. A free function rather than a method so
    +// Tokens keeps value receivers throughout (it is embedded in JSON-serialized
    +// rows, where a mixed receiver set is a trap). A nil u is a no-op so callers can
    +// pass an optional usage without checking.
    +func addUsage(dst *Tokens, u *chat.Usage) {
    +	if u == nil {
    +		return
    +	}
    +	dst.Input += u.InputTokens
    +	dst.CachedInput += u.CachedInputTokens
    +	dst.CacheWrite += u.CacheWriteTokens
    +	dst.Output += u.OutputTokens
    +	dst.Reasoning += u.ReasoningTokens
    +}
    +
    +// SessionRow is one session's spend.
    +type SessionRow struct {
    +	ID        string    `json:"id"`
    +	Title     string    `json:"title,omitempty"`
    +	CreatedAt time.Time `json:"created_at"`
    +	// Models used in the session, sorted and de-duplicated.
    +	Models []string `json:"models,omitempty"`
    +	Tokens Tokens   `json:"tokens"`
    +	Cost   float64  `json:"cost"`
    +	// CostIncomplete marks a session that moved tokens but recorded no cost,
    +	// i.e. at least one model was missing from the pricing catalogue.
    +	CostIncomplete bool `json:"cost_incomplete,omitempty"`
    +}
    +
    +// ModelRow is one model's token spend across every session in the report.
    +// Calls counts model responses, not tool calls.
    +type ModelRow struct {
    +	Model  string `json:"model"`
    +	Calls  int    `json:"calls"`
    +	Tokens Tokens `json:"tokens"`
    +}
    +
    +// ToolRow is how often a tool was called across every session in the report.
    +type ToolRow struct {
    +	Tool  string `json:"tool"`
    +	Calls int    `json:"calls"`
    +}
    +
    +// Report is the aggregate view. Sessions are newest first; Models and Tools are
    +// ordered by size descending so the cost drivers come first.
    +type Report struct {
    +	Sessions []SessionRow `json:"sessions"`
    +	Models   []ModelRow   `json:"models"`
    +	Tools    []ToolRow    `json:"tools"`
    +	Tokens   Tokens       `json:"tokens"`
    +	Cost     float64      `json:"cost"`
    +	// UnpricedModels lists models that moved tokens in a session that recorded
    +	// no cost. Sorted.
    +	UnpricedModels []string `json:"unpriced_models,omitempty"`
    +}
    +
    +// Aggregate builds a [Report] from the supplied sessions. Nil entries are
    +// skipped, so a caller can pass a store listing straight through.
    +func Aggregate(sessions []*session.Session) Report {
    +	var report Report
    +
    +	modelTokens := map[string]*ModelRow{}
    +	toolCalls := map[string]int{}
    +	unpriced := map[string]struct{}{}
    +
    +	for _, s := range sessions {
    +		if s == nil {
    +			continue
    +		}
    +
    +		row := SessionRow{ID: s.ID, Title: s.Title, CreatedAt: s.CreatedAt, Cost: s.Cost}
    +		sessionModels := map[string]struct{}{}
    +
    +		for i := range s.Messages {
    +			item := &s.Messages[i]
    +
    +			// Non-message items (compaction summaries and the like) carry their
    +			// own model and usage; they are real spend.
    +			model, itemUsage := itemModelAndUsage(item)
    +			if itemUsage == nil && model == "" {
    +				continue
    +			}
    +
    +			addUsage(&row.Tokens, itemUsage)
    +			if model != "" {
    +				sessionModels[model] = struct{}{}
    +				mr, ok := modelTokens[model]
    +				if !ok {
    +					mr = &ModelRow{Model: model}
    +					modelTokens[model] = mr
    +				}
    +				mr.Calls++
    +				addUsage(&mr.Tokens, itemUsage)
    +			}
    +
    +			if item.Message != nil {
    +				for _, tc := range item.Message.Message.ToolCalls {
    +					if tc.Function.Name != "" {
    +						toolCalls[tc.Function.Name]++
    +					}
    +				}
    +			}
    +		}
    +
    +		row.Models = sortedKeys(sessionModels)
    +
    +		// Tokens moved but nothing was charged: the model is unpriced.
    +		if row.Tokens.Total() > 0 && row.Cost == 0 {
    +			row.CostIncomplete = true

    [low] CostIncomplete flag not set for sessions with only Reasoning tokens

    Tokens.Total() is defined as Input + Output (line 48 of pkg/usage/usage.go). The CostIncomplete guard on line 157 reads:

    if row.Tokens.Total() > 0 && row.Cost == 0 {
    

    A session whose items produced only Reasoning tokens — and zero Input or Output tokens — will have Total() == 0 even though real compute was consumed and billed. If the model is unpriced, row.Cost stays at 0, the CostIncomplete flag is never set, and the warning ! Cost is understated: no pricing for … is silently suppressed. This contradicts the stated goal of "surfacing rather than papering over" cost understatement.

    Including Reasoning tokens in the check closes the gap:

    		if row.Tokens.Total() > 0 || row.Tokens.Reasoning > 0 && row.Cost == 0 {
    

    Note: depending on operator precedence you may want explicit parentheses; the cleaner fix is to add a HasTokens() method or fold Reasoning into Total(). Reasoning tokens are a distinct cost driver and omitting them from Total() is the root cause.

    | Confidence | Score |
    | :--: | :--: |
    | 🟡 moderate | 57/100 |

    <!-- docker-agent-review -->

    dwin-gharibi dwin-gharibi commented on code on Aug 07, 2026 08:14 UTC
    Code Review
    pkg/usage/usage.go:1
    @@ -0,0 +1,224 @@
    +// Package usage aggregates token and cost figures out of persisted sessions.
    +//
    +// It exists so the numbers the TUI shows in its cost dialog are also reachable
    +// from a headless run: `docker agent usage` reads the session store and reports
    +// what was spent, per session, per model, and per tool.
    +//
    +// # What the numbers mean
    +//
    +// Cost is taken from each session's own cumulative counter, which is what the
    +// runtime recorded as it ran — this package never re-prices anything. Token
    +// figures are summed from per-message usage, which is the only place the
    +// cached-input and cache-write breakdown is persisted.
    +//
    +// Those two sources can disagree: a session whose messages carry no usage (an
    +// older session, or one recorded by a provider with usage tracking disabled)
    +// reports zero tokens while still reporting a cost. The reverse — tokens with no
    +// cost — means the model was missing from the pricing catalogue, and is surfaced
    +// as [SessionRow.CostIncomplete] and [Report.UnpricedModels] rather than being
    +// silently reported as $0.00.
    +//
    +// Per-model *cost* is deliberately absent: cost is persisted per session and per
    +// non-message item, never per message, so attributing it across the models used
    +// inside one session is not possible without a schema change.
    +package usage
    +
    +import (
    +	"cmp"
    +	"slices"
    +	"time"
    +
    +	"github.com/docker/docker-agent/pkg/chat"
    +	"github.com/docker/docker-agent/pkg/session"
    +)
    +
    +// Tokens is a token breakdown. CachedInput and CacheWrite are reported
    +// separately from Input so the effect of prompt caching is visible.
    +type Tokens struct {
    +	Input       int64 `json:"input"`
    +	CachedInput int64 `json:"cached_input"`
    +	CacheWrite  int64 `json:"cache_write"`
    +	Output      int64 `json:"output"`
    +	Reasoning   int64 `json:"reasoning"`
    +}
    +
    +// Total is the headline "tokens moved" figure: input plus output. CachedInput is
    +// already a subset of Input, and CacheWrite/Reasoning are reported on their own
    +// rather than folded in, so adding them would double-count.
    +func (t Tokens) Total() int64 { return t.Input + t.Output }
    +
    +// addUsage accumulates u into dst. A free function rather than a method so
    +// Tokens keeps value receivers throughout (it is embedded in JSON-serialized
    +// rows, where a mixed receiver set is a trap). A nil u is a no-op so callers can
    +// pass an optional usage without checking.
    +func addUsage(dst *Tokens, u *chat.Usage) {
    +	if u == nil {
    +		return
    +	}
    +	dst.Input += u.InputTokens
    +	dst.CachedInput += u.CachedInputTokens
    +	dst.CacheWrite += u.CacheWriteTokens
    +	dst.Output += u.OutputTokens
    +	dst.Reasoning += u.ReasoningTokens
    +}
    +
    +// SessionRow is one session's spend.
    +type SessionRow struct {
    +	ID        string    `json:"id"`
    +	Title     string    `json:"title,omitempty"`
    +	CreatedAt time.Time `json:"created_at"`
    +	// Models used in the session, sorted and de-duplicated.
    +	Models []string `json:"models,omitempty"`
    +	Tokens Tokens   `json:"tokens"`
    +	Cost   float64  `json:"cost"`
    +	// CostIncomplete marks a session that moved tokens but recorded no cost,
    +	// i.e. at least one model was missing from the pricing catalogue.
    +	CostIncomplete bool `json:"cost_incomplete,omitempty"`
    +}
    +
    +// ModelRow is one model's token spend across every session in the report.
    +// Calls counts model responses, not tool calls.
    +type ModelRow struct {
    +	Model  string `json:"model"`
    +	Calls  int    `json:"calls"`
    +	Tokens Tokens `json:"tokens"`
    +}
    +
    +// ToolRow is how often a tool was called across every session in the report.
    +type ToolRow struct {
    +	Tool  string `json:"tool"`
    +	Calls int    `json:"calls"`
    +}
    +
    +// Report is the aggregate view. Sessions are newest first; Models and Tools are
    +// ordered by size descending so the cost drivers come first.
    +type Report struct {
    +	Sessions []SessionRow `json:"sessions"`
    +	Models   []ModelRow   `json:"models"`
    +	Tools    []ToolRow    `json:"tools"`
    +	Tokens   Tokens       `json:"tokens"`
    +	Cost     float64      `json:"cost"`
    +	// UnpricedModels lists models that moved tokens in a session that recorded
    +	// no cost. Sorted.
    +	UnpricedModels []string `json:"unpriced_models,omitempty"`
    +}
    +
    +// Aggregate builds a [Report] from the supplied sessions. Nil entries are
    +// skipped, so a caller can pass a store listing straight through.
    +func Aggregate(sessions []*session.Session) Report {
    +	var report Report
    +
    +	modelTokens := map[string]*ModelRow{}
    +	toolCalls := map[string]int{}
    +	unpriced := map[string]struct{}{}
    +
    +	for _, s := range sessions {
    +		if s == nil {
    +			continue
    +		}
    +
    +		row := SessionRow{ID: s.ID, Title: s.Title, CreatedAt: s.CreatedAt, Cost: s.Cost}
    +		sessionModels := map[string]struct{}{}
    +
    +		for i := range s.Messages {
    +			item := &s.Messages[i]
    +
    +			// Non-message items (compaction summaries and the like) carry their
    +			// own model and usage; they are real spend.
    +			model, itemUsage := itemModelAndUsage(item)
    +			if itemUsage == nil && model == "" {
    +				continue
    +			}
    +
    +			addUsage(&row.Tokens, itemUsage)
    +			if model != "" {
    +				sessionModels[model] = struct{}{}
    +				mr, ok := modelTokens[model]
    +				if !ok {
    +					mr = &ModelRow{Model: model}
    +					modelTokens[model] = mr
    +				}
    +				mr.Calls++
    +				addUsage(&mr.Tokens, itemUsage)
    +			}
    +
    +			if item.Message != nil {
    +				for _, tc := range item.Message.Message.ToolCalls {
    +					if tc.Function.Name != "" {
    +						toolCalls[tc.Function.Name]++
    +					}
    +				}
    +			}
    +		}
    +
    +		row.Models = sortedKeys(sessionModels)
    +
    +		// Tokens moved but nothing was charged: the model is unpriced.
    +		if row.Tokens.Total() > 0 && row.Cost == 0 {
    +			row.CostIncomplete = true

    Done.

    dwin-gharibi dwin-gharibi commented on code on Aug 07, 2026 08:14 UTC
    Code Review
    pkg/usage/usage.go:1
    @@ -0,0 +1,224 @@
    +// Package usage aggregates token and cost figures out of persisted sessions.
    +//
    +// It exists so the numbers the TUI shows in its cost dialog are also reachable
    +// from a headless run: `docker agent usage` reads the session store and reports
    +// what was spent, per session, per model, and per tool.
    +//
    +// # What the numbers mean
    +//
    +// Cost is taken from each session's own cumulative counter, which is what the
    +// runtime recorded as it ran — this package never re-prices anything. Token
    +// figures are summed from per-message usage, which is the only place the
    +// cached-input and cache-write breakdown is persisted.
    +//
    +// Those two sources can disagree: a session whose messages carry no usage (an
    +// older session, or one recorded by a provider with usage tracking disabled)
    +// reports zero tokens while still reporting a cost. The reverse — tokens with no
    +// cost — means the model was missing from the pricing catalogue, and is surfaced
    +// as [SessionRow.CostIncomplete] and [Report.UnpricedModels] rather than being
    +// silently reported as $0.00.
    +//
    +// Per-model *cost* is deliberately absent: cost is persisted per session and per
    +// non-message item, never per message, so attributing it across the models used
    +// inside one session is not possible without a schema change.
    +package usage
    +
    +import (
    +	"cmp"
    +	"slices"
    +	"time"
    +
    +	"github.com/docker/docker-agent/pkg/chat"
    +	"github.com/docker/docker-agent/pkg/session"
    +)
    +
    +// Tokens is a token breakdown. CachedInput and CacheWrite are reported
    +// separately from Input so the effect of prompt caching is visible.
    +type Tokens struct {
    +	Input       int64 `json:"input"`
    +	CachedInput int64 `json:"cached_input"`
    +	CacheWrite  int64 `json:"cache_write"`
    +	Output      int64 `json:"output"`
    +	Reasoning   int64 `json:"reasoning"`
    +}
    +
    +// Total is the headline "tokens moved" figure: input plus output. CachedInput is
    +// already a subset of Input, and CacheWrite/Reasoning are reported on their own
    +// rather than folded in, so adding them would double-count.
    +func (t Tokens) Total() int64 { return t.Input + t.Output }
    +
    +// addUsage accumulates u into dst. A free function rather than a method so
    +// Tokens keeps value receivers throughout (it is embedded in JSON-serialized
    +// rows, where a mixed receiver set is a trap). A nil u is a no-op so callers can
    +// pass an optional usage without checking.
    +func addUsage(dst *Tokens, u *chat.Usage) {
    +	if u == nil {
    +		return
    +	}
    +	dst.Input += u.InputTokens
    +	dst.CachedInput += u.CachedInputTokens
    +	dst.CacheWrite += u.CacheWriteTokens
    +	dst.Output += u.OutputTokens
    +	dst.Reasoning += u.ReasoningTokens
    +}
    +
    +// SessionRow is one session's spend.
    +type SessionRow struct {
    +	ID        string    `json:"id"`
    +	Title     string    `json:"title,omitempty"`
    +	CreatedAt time.Time `json:"created_at"`
    +	// Models used in the session, sorted and de-duplicated.
    +	Models []string `json:"models,omitempty"`
    +	Tokens Tokens   `json:"tokens"`
    +	Cost   float64  `json:"cost"`
    +	// CostIncomplete marks a session that moved tokens but recorded no cost,
    +	// i.e. at least one model was missing from the pricing catalogue.
    +	CostIncomplete bool `json:"cost_incomplete,omitempty"`
    +}
    +
    +// ModelRow is one model's token spend across every session in the report.
    +// Calls counts model responses, not tool calls.
    +type ModelRow struct {
    +	Model  string `json:"model"`
    +	Calls  int    `json:"calls"`
    +	Tokens Tokens `json:"tokens"`
    +}
    +
    +// ToolRow is how often a tool was called across every session in the report.
    +type ToolRow struct {
    +	Tool  string `json:"tool"`
    +	Calls int    `json:"calls"`
    +}
    +
    +// Report is the aggregate view. Sessions are newest first; Models and Tools are
    +// ordered by size descending so the cost drivers come first.
    +type Report struct {
    +	Sessions []SessionRow `json:"sessions"`
    +	Models   []ModelRow   `json:"models"`
    +	Tools    []ToolRow    `json:"tools"`
    +	Tokens   Tokens       `json:"tokens"`
    +	Cost     float64      `json:"cost"`
    +	// UnpricedModels lists models that moved tokens in a session that recorded
    +	// no cost. Sorted.
    +	UnpricedModels []string `json:"unpriced_models,omitempty"`
    +}
    +
    +// Aggregate builds a [Report] from the supplied sessions. Nil entries are
    +// skipped, so a caller can pass a store listing straight through.
    +func Aggregate(sessions []*session.Session) Report {
    +	var report Report
    +
    +	modelTokens := map[string]*ModelRow{}
    +	toolCalls := map[string]int{}
    +	unpriced := map[string]struct{}{}
    +
    +	for _, s := range sessions {
    +		if s == nil {
    +			continue
    +		}
    +
    +		row := SessionRow{ID: s.ID, Title: s.Title, CreatedAt: s.CreatedAt, Cost: s.Cost}
    +		sessionModels := map[string]struct{}{}
    +
    +		for i := range s.Messages {
    +			item := &s.Messages[i]
    +
    +			// Non-message items (compaction summaries and the like) carry their
    +			// own model and usage; they are real spend.
    +			model, itemUsage := itemModelAndUsage(item)
    +			if itemUsage == nil && model == "" {
    +				continue
    +			}
    +
    +			addUsage(&row.Tokens, itemUsage)
    +			if model != "" {
    +				sessionModels[model] = struct{}{}
    +				mr, ok := modelTokens[model]
    +				if !ok {
    +					mr = &ModelRow{Model: model}
    +					modelTokens[model] = mr
    +				}
    +				mr.Calls++

    Done.

    dwin-gharibi dwin-gharibi commented on Aug 07, 2026 08:15 UTC
    Author

    Done. @aheritier

    aheritier aheritier requested changes on Aug 07, 2026 21:40 UTC
    Changes Requested Reviewer

    Assessment: 🔴 Request changes — the aggregation misses sub-agent spend, and cost is read from the legacy session field

    The shape of this is right: a pure Aggregate over data that is already persisted, no schema change, a thin CLI on top, --json for CI. The gap it closes is real, and the care shows (deterministic tie-breaks, [] rather than null, rune-safe truncation). The unmetered-calls instinct from the last round is also validated by data — in a 145,644-message store only 3 assistant messages carry no usage, so that warning won't be noisy.

    But two defects make the reported numbers wrong on the sessions that matter most, and I could only find them by running the command against a real store rather than fixtures.

    Verified against PR head 38d3dd12, built and tested on top of current main, and smoke-run against a copy of a real 1.5 GB session store (4,642 sessions, 145,644 messages).

    ---

    🔴 [blocking] Sub-agent (sub-session) spend is dropped from every breakdown

    pkg/usage/usage.go:159-196 walks only s.Messages, and itemModelAndUsage (pkg/usage/usage.go:238-244) handles item.Message and the non-message item fields but never item.SubSession. Sub-sessions are not reachable from the top level either: GetSessions is root-only (pkg/session/store.go:777-779, WHERE parent_id IS NULL OR parent_id = ''). The TUI cost dialog this command mirrors does recurse — pkg/tui/dialog/cost.go:305-308.

    One real root session with 46 sub-sessions:

    | | truth (recursive, as the TUI computes) | this command |
    |---|---|---|
    | input tokens | 219,577 | 334 (0.2%) |
    | output tokens | 327,351 | 136,234 |
    | model calls | 471 | 167 |
    | tool calls | 492 | 156 |

    Store-wide: 87,982 of 145,644 messages (60%) live in sub-sessions, holding 63.8M input tokens, 2.63B cached-input tokens and $2,273 of recorded cost — none of it reported. transfer_task shows up in the tool table, so multi-agent sessions are the normal case. "Which agent is expensive?" — the use case in #3943 — gets a wrong answer with no warning.

    🔴 [blocking] Cost comes from the legacy session-level field, producing $0.00 plus a false "no pricing" warning

    pkg/usage/usage.go:161 uses Cost: s.Cost. pkg/session/session.go:1518-1521 documents that field as existing "only for backward-compatible persistence", with TotalCost() as the canonical figure — and every other consumer uses TotalCost(): pkg/server/session_manager.go:527, pkg/app/export/html.go:119, pkg/tui/dialog/cost.go:347, pkg/tui/components/sidebar/sidebar.go:972.

    Combined with the AnySpend() && Cost == 0 heuristic at pkg/usage/usage.go:198-204, here is the actual output of the built binary for session 6047f54d:

    6047f54d  ...  334  24.8M  136.2K  $0.0000+  <title>
    ! Cost is understated: no pricing for anthropic/claude-opus-4-8
    

    That session's TotalCost() is $44.45, and its own messages carry $34.82 of recorded per-message cost — the model is priced. Store-wide the total is understated ~25% ($7,224.17 from the cost column vs ~$9,611 actually recorded). This inverts the principle the PR argues for: rather than refusing to understate, it asserts something false and attributes it to a priced model.

    🟠 [should-fix] The package doc states a constraint that isn't true — per-model cost is attributable

    pkg/usage/usage.go:22-25 says cost is "persisted per session and per non-message item, never per message". chat.Message.Cost (pkg/chat/chat.go:91-92) is persisted inside message_json and reloads intact (I read $34.82 back out of the store), is summed by session.TotalCost() (pkg/session/session.go:1529), and is already attributed per model by pkg/tui/dialog/cost.go:303. The msg.Cost = 0 at pkg/session/session.go:1978 only clears a request-assembly copy. So the doc encodes a false data-model claim, and it is the justification for the finding above and for an omitted feature: fix the cost source and per-model cost falls out for free.

    🟠 [should-fix] No test touches the sub-session path

    25 tests, none constructing session.NewSubSessionItem, and nothing exercising loadUsageSessions or a real store. That gap is why both blocking findings shipped; two tests close it.

    🟠 [should-fix] The whole store is loaded into memory before --since is applied

    cmd/root/usage.go:104-108 calls GetSessions (every session, every item) and filters afterwards. Measured: --since 24h on a 1.5 GB store took 11.7 s and 2.70 GB peak RSS to print 3 sessions — enough to OOM a 2 GB CI runner, which is the advertised --json-in-CI use case. GetSessionSummaries (pkg/session/store.go:812-815) exists for exactly this reason; filter on metadata, then load items for the survivors.

    🟠 [should-fix] --session rejects the ID the command prints

    The table prints 8 chars via shortSessionID (cmd/root/usage.go:245-250), but --session 6047f54d fails with session not found. Accepting a unique prefix would make the output self-consistent.

    🟠 [should-fix] Docs not updated

    docs/features/cli/index.md documents every user-facing command (### docker agent eval at line 450, models at 192, toolsets at 216, plus share and serve *). A new top-level command belongs there in the same change.

    🔵 [optional] A read-only report opens the store read-write and runs migrations

    sqlitestore.New (pkg/session/sqlitestore/sqlitestore.go:24-60) runs migrations and, on failure, moves the database aside to .bak; it also takes a write lock, so usage can contend with a running agent. A read-only open would be proportionate for a reporting command.

    🔵 [optional] Fourth divergent aggregation site

    pkg/tui/dialog/cost.go:296-320 already walks a session for these exact numbers. Extracting that walker into pkg/usage and having the TUI consume it would stop the two from disagreeing — they currently disagree in both ways described above.

    ---

    Worth doing: yes. The gap is genuine (figures reachable only from the TUI and OTel), the approach is proportionate, and no schema change is needed. It just needs the aggregation to see sub-sessions and to take cost from TotalCost(); do that and the per-model cost breakdown you documented as impossible becomes available too.

    copilot-pull-request-reviewer[bot] copilot-pull-request-reviewer[bot] commented on Aug 08, 2026 18:57 UTC
    Reviewer

    Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

    dwin-gharibi dwin-gharibi commented on Aug 08, 2026 19:47 UTC
    Author

    Done. @aheritier

    aheritier aheritier approved these changes on Aug 13, 2026 19:40 UTC
    Approved Reviewer

    CI is green. Cost aggregation now mirrors session.TotalCost, including message/item costs and recursive sub-sessions; filtering occurs before full-session loads; documented session references work; and sub-agent/unpriced behavior is covered. Please update Long help: it still says cost comes from each session\x27s recorded counter, though this change correctly derives per-message/item costs; clarify that --session accepts prefixes and relative references. Optional: a read-only report should preferably avoid opening/migrating the store read-write. This is a durable CLI surface; maintainer agreement on docker agent usage alongside #3948\x27s sessions surface is appropriate. Approve.

    aheritier aheritier commented on Aug 13, 2026 19:46 UTC
    Contributor

    While the code is technically ok I prefer to take some time to verify with the team if the improvement is coherent with the direction we want to give to the project. More code we code, more maintenance we'll get...

    aheritier aheritier commented on Aug 17, 2026 12:31 UTC
    Contributor

    👋 This PR has merge conflicts with the base branch. Please rebase or merge the latest base branch and resolve them. I've moved it to draft and added status/needs-rebase; it'll be picked back up automatically once the conflicts are cleared.

    dwin-gharibi dwin-gharibi commented on Aug 19, 2026 09:01 UTC
    Author

    @aheritier @Sayt-0

    Reviewers
    Assignees
    dwin-gharibi dwin-gharibi
    Labels
    risk: low confidence: 78.4% reviewed sensitive_module
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 80.2% (HIGH) · Higher = larger blast radius
    80.2%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 78.4% · Lower = rushed or shallow review
    78.4%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 17.3% · Safe to merge
    17.3%