Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-5810: fix(agent): reconcile ACP terminal usage (#6503)

Bohan Jiangb24634e6eb1d
diff --git a/server/pkg/agent/acp_usage.go b/server/pkg/agent/acp_usage.go
new file mode 100644
index 0000000000..92a619aff7
--- /dev/null
+++ b/server/pkg/agent/acp_usage.go
@@ -0,0 +1,291 @@
+package agent
+
+import (
+ "bytes"
+ "encoding/json"
+ "strconv"
+ "strings"
+)
+
+type acpUsageFields uint8
+
+const (
+ acpUsageInput acpUsageFields = 1 << iota
+ acpUsageOutput
+ acpUsageCacheRead
+ acpUsageCacheWrite
+ acpUsageCost
+)
+
+// acpUsageSnapshot keeps field presence separate from the parsed values.
+// Prompt results are frequently partial, so a zero value alone cannot tell us
+// whether a runtime explicitly reported zero or omitted the bucket entirely.
+type acpUsageSnapshot struct {
+ TokenUsage
+ rawInputTokens int64
+ fields acpUsageFields
+ totalTokens int64
+ hasTotalTokens bool
+ inputNormalized bool
+}
+
+func (s acpUsageSnapshot) has(field acpUsageFields) bool {
+ return s.fields&field != 0
+}
+
+// acpUsageAccumulator reconciles the two metering paths shared by ACP
+// backends: cumulative usage_update snapshots and terminal prompt usage.
+//
+// Per-bucket maxima deduplicate equivalent snapshots while retaining buckets
+// omitted from one path. Input is special: self-describing normalized and
+// ambiguous candidates are retained separately, then resolved from the whole
+// observed set. This makes the result independent of whether a late
+// usage_update arrives before or after the terminal prompt response.
+type acpUsageAccumulator struct {
+ TokenUsage
+ fields acpUsageFields
+
+ ambiguousInput int64
+ hasAmbiguousInput bool
+ normalizedInput int64
+ normalizedTotal int64
+ hasNormalized bool
+}
+
+func (a *acpUsageAccumulator) merge(next acpUsageSnapshot) {
+ if next.has(acpUsageInput) {
+ if next.inputNormalized {
+ if !a.hasNormalized ||
+ next.totalTokens > a.normalizedTotal ||
+ (next.totalTokens == a.normalizedTotal && next.InputTokens > a.normalizedInput) {
+ a.normalizedInput = next.InputTokens
+ a.normalizedTotal = next.totalTokens
+ a.hasNormalized = true
+ }
+ } else if !a.hasAmbiguousInput || next.InputTokens > a.ambiguousInput {
+ a.ambiguousInput = next.InputTokens
+ a.hasAmbiguousInput = true
+ }
+ }
+ if next.has(acpUsageOutput) && (!a.has(acpUsageOutput) || next.OutputTokens > a.OutputTokens) {
+ a.OutputTokens = next.OutputTokens
+ }
+ if next.has(acpUsageCacheRead) && (!a.has(acpUsageCacheRead) || next.CacheReadTokens > a.CacheReadTokens) {
+ a.CacheReadTokens = next.CacheReadTokens
+ }
+ if next.has(acpUsageCacheWrite) && (!a.has(acpUsageCacheWrite) || next.CacheWriteTokens > a.CacheWriteTokens) {
+ a.CacheWriteTokens = next.CacheWriteTokens
+ }
+ // Provider cost is a cumulative turn total on the ACP backends that expose
+ // it. Max consolidation preserves a late/richer report without charging a
+ // duplicate prompt-result and usage_update twice.
+ if next.has(acpUsageCost) && (!a.has(acpUsageCost) || next.CostUSDTicks > a.CostUSDTicks) {
+ a.CostUSDTicks = next.CostUSDTicks
+ }
+
+ a.fields |= next.fields
+ a.resolveInput()
+}
+
+func (a acpUsageAccumulator) has(field acpUsageFields) bool {
+ return a.fields&field != 0
+}
+
+func (a *acpUsageAccumulator) resolveInput() {
+ switch {
+ case !a.hasAmbiguousInput && a.hasNormalized:
+ a.InputTokens = a.normalizedInput
+ case a.hasAmbiguousInput && !a.hasNormalized:
+ a.InputTokens = a.ambiguousInput
+ case a.hasAmbiguousInput && a.hasNormalized:
+ // input + output is a conservative cumulative floor even when input
+ // includes cached reads. A normalized record below that floor is a
+ // per-call delta and must not replace the larger cumulative stream.
+ if a.normalizedTotal >= a.ambiguousInput+a.OutputTokens {
+ a.InputTokens = a.normalizedInput
+ } else {
+ a.InputTokens = a.ambiguousInput
+ }
+ }
+}
+
+// withFallback fills fields omitted (or reported as zero) by a preferred
+// representation. ACP's standard top-level usage is authoritative over vendor
+// `_meta`, and nested `_meta.usage` is authoritative over its flat mirror.
+// Provider cost still takes the maximum because zero means "not reported" and
+// runtimes may expose the priced total in only one representation.
+func (s acpUsageSnapshot) withFallback(fallback acpUsageSnapshot) acpUsageSnapshot {
+ result := s
+ inputFromFallback := false
+ if fallback.has(acpUsageInput) && (!result.has(acpUsageInput) || result.rawInputTokens == 0) {
+ result.InputTokens = fallback.InputTokens
+ result.rawInputTokens = fallback.rawInputTokens
+ result.inputNormalized = fallback.inputNormalized
+ inputFromFallback = true
+ }
+ if fallback.has(acpUsageOutput) && (!result.has(acpUsageOutput) || result.OutputTokens == 0) {
+ result.OutputTokens = fallback.OutputTokens
+ }
+ if fallback.has(acpUsageCacheRead) && (!result.has(acpUsageCacheRead) || result.CacheReadTokens == 0) {
+ result.CacheReadTokens = fallback.CacheReadTokens
+ }
+ if fallback.has(acpUsageCacheWrite) && (!result.has(acpUsageCacheWrite) || result.CacheWriteTokens == 0) {
+ result.CacheWriteTokens = fallback.CacheWriteTokens
+ }
+ if fallback.has(acpUsageCost) && (!result.has(acpUsageCost) || fallback.CostUSDTicks > result.CostUSDTicks) {
+ result.CostUSDTicks = fallback.CostUSDTicks
+ }
+
+ result.fields |= fallback.fields
+ if inputFromFallback && fallback.inputNormalized {
+ result.totalTokens = fallback.totalTokens
+ result.hasTotalTokens = fallback.hasTotalTokens
+ } else if !result.hasTotalTokens && fallback.hasTotalTokens {
+ result.totalTokens = fallback.totalTokens
+ result.hasTotalTokens = true
+ }
+ result.normalizeInput()
+ return result
+}
+
+// normalizeInput always starts from the provider's raw input count so a
+// preferred/fallback merge can be normalized after all complementary fields
+// are present without subtracting cached reads twice.
+func (s *acpUsageSnapshot) normalizeInput() {
+ s.InputTokens = s.rawInputTokens
+ s.inputNormalized = false
+ if !s.has(acpUsageInput) || !s.has(acpUsageOutput) || !s.has(acpUsageCacheRead) {
+ return
+ }
+ s.TokenUsage, s.inputNormalized = normalizeACPTokenUsage(s.TokenUsage, s.totalTokens)
+}
+
+func parseACPTokenUsage(data json.RawMessage) TokenUsage {
+ return parseACPTokenUsageSnapshot(data).TokenUsage
+}
+
+func parseACPTokenUsageSnapshot(data json.RawMessage) acpUsageSnapshot {
+ if len(data) == 0 || string(data) == "null" {
+ return acpUsageSnapshot{}
+ }
+ var rawFields map[string]json.RawMessage
+ if err := json.Unmarshal(data, &rawFields); err != nil {
+ return acpUsageSnapshot{}
+ }
+
+ var snapshot acpUsageSnapshot
+ if value, ok := acpUsageInt64(rawFields, "inputTokens", "input_tokens"); ok {
+ snapshot.InputTokens = value
+ snapshot.rawInputTokens = value
+ snapshot.fields |= acpUsageInput
+ }
+ if value, ok := acpUsageInt64(rawFields, "outputTokens", "output_tokens"); ok {
+ snapshot.OutputTokens = value
+ snapshot.fields |= acpUsageOutput
+ }
+ if value, ok := acpUsageInt64(rawFields,
+ "cachedReadTokens",
+ "cacheReadTokens",
+ "cached_input_tokens",
+ "cache_read_tokens",
+ "cache_read_input_tokens",
+ ); ok {
+ snapshot.CacheReadTokens = value
+ snapshot.fields |= acpUsageCacheRead
+ }
+ if value, ok := acpUsageInt64(rawFields,
+ "cachedWriteTokens",
+ "cacheWriteTokens",
+ "cache_write_tokens",
+ "cache_creation_input_tokens",
+ ); ok {
+ snapshot.CacheWriteTokens = value
+ snapshot.fields |= acpUsageCacheWrite
+ }
+ if value, ok := acpUsageInt64(rawFields, "costUsdTicks", "cost_usd_ticks"); ok {
+ snapshot.CostUSDTicks = value
+ snapshot.fields |= acpUsageCost
+ }
+ if value, ok := acpUsageInt64(rawFields, "totalTokens", "total_tokens"); ok {
+ snapshot.totalTokens = value
+ snapshot.hasTotalTokens = true
+ }
+
+ snapshot.normalizeInput()
+ return snapshot
+}
+
+// parseACPTokenUsageSnapshotFromMeta extracts and reconciles token usage from
+// an ACP result `_meta` object. Grok Build returns both nested `_meta.usage`
+// and flat mirror fields; merging them preserves fields omitted from either
+// representation without double counting their duplicate values.
+func parseACPTokenUsageSnapshotFromMeta(meta json.RawMessage) acpUsageSnapshot {
+ if len(meta) == 0 || string(meta) == "null" {
+ return acpUsageSnapshot{}
+ }
+
+ var envelope struct {
+ Usage json.RawMessage `json:"usage"`
+ }
+ var preferred acpUsageSnapshot
+ if err := json.Unmarshal(meta, &envelope); err == nil &&
+ len(envelope.Usage) > 0 && string(envelope.Usage) != "null" {
+ preferred = parseACPTokenUsageSnapshot(envelope.Usage)
+ }
+ return preferred.withFallback(parseACPTokenUsageSnapshot(meta))
+}
+
+func parseACPTokenUsageFromMeta(meta json.RawMessage) TokenUsage {
+ return parseACPTokenUsageSnapshotFromMeta(meta).TokenUsage
+}
+
+// normalizeACPTokenUsage re-buckets a usage record whose inputTokens already
+// contains cachedReadTokens, so the persisted buckets stay mutually exclusive
+// and dashboard cost math does not charge the cached prefix twice.
+//
+// ACP does not specify whether cached reads are counted inside inputTokens.
+// Grok Build counts them inside: totalTokens == inputTokens + outputTokens.
+// The re-bucketing only happens when totalTokens proves that shape. Agents
+// reporting exclusive buckets or omitting totalTokens remain unchanged.
+func normalizeACPTokenUsage(usage TokenUsage, totalTokens int64) (TokenUsage, bool) {
+ if totalTokens <= 0 || usage.CacheReadTokens <= 0 || usage.CacheReadTokens > usage.InputTokens {
+ return usage, false
+ }
+ if totalTokens != usage.InputTokens+usage.OutputTokens {
+ return usage, false
+ }
+ usage.InputTokens -= usage.CacheReadTokens
+ return usage, true
+}
+
+func excludeACPCachedInput(usage TokenUsage, totalTokens int64) TokenUsage {
+ normalized, _ := normalizeACPTokenUsage(usage, totalTokens)
+ return normalized
+}
+
+func acpUsageInt64(fields map[string]json.RawMessage, names ...string) (int64, bool) {
+ for _, name := range names {
+ raw, ok := fields[name]
+ if !ok {
+ continue
+ }
+ var n json.Number
+ dec := json.NewDecoder(bytes.NewReader(raw))
+ dec.UseNumber()
+ if err := dec.Decode(&n); err == nil {
+ if value, err := n.Int64(); err == nil && value >= 0 {
+ return value, true
+ }
+ if value, err := n.Float64(); err == nil && value >= 0 {
+ return int64(value), true
+ }
+ }
+ var s string
+ if err := json.Unmarshal(raw, &s); err == nil {
+ if value, err := strconv.ParseInt(strings.TrimSpace(s), 10, 64); err == nil && value >= 0 {
+ return value, true
+ }
+ }
+ }
+ return 0, false
+}
diff --git a/server/pkg/agent/acp_usage_test.go b/server/pkg/agent/acp_usage_test.go
new file mode 100644
index 0000000000..bc93a7d7f1
--- /dev/null
+++ b/server/pkg/agent/acp_usage_test.go
@@ -0,0 +1,214 @@
+package agent
+
+import (
+ "encoding/json"
+ "testing"
+)
+
+func TestACPUsageAccumulatorMatrix(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ snapshots []string
+ want TokenUsage
+ }{
+ {
+ name: "prompt only",
+ snapshots: []string{
+ `{"inputTokens":100,"outputTokens":30,"cacheReadTokens":20,"cacheWriteTokens":5,"costUsdTicks":900}`,
+ },
+ want: TokenUsage{InputTokens: 100, OutputTokens: 30, CacheReadTokens: 20, CacheWriteTokens: 5, CostUSDTicks: 900},
+ },
+ {
+ name: "stream only",
+ snapshots: []string{
+ `{"inputTokens":80,"outputTokens":10,"cacheReadTokens":15,"cacheWriteTokens":3,"costUsdTicks":700}`,
+ `{"inputTokens":100,"outputTokens":30,"cacheReadTokens":20,"cacheWriteTokens":5,"costUsdTicks":900}`,
+ },
+ want: TokenUsage{InputTokens: 100, OutputTokens: 30, CacheReadTokens: 20, CacheWriteTokens: 5, CostUSDTicks: 900},
+ },
+ {
+ name: "duplicate stream and prompt snapshots",
+ snapshots: []string{
+ `{"inputTokens":120,"outputTokens":30,"totalTokens":150,"cacheReadTokens":20,"cacheWriteTokens":5,"costUsdTicks":900}`,
+ `{"inputTokens":120,"outputTokens":30,"totalTokens":150,"cacheReadTokens":20,"cacheWriteTokens":5,"costUsdTicks":900}`,
+ },
+ want: TokenUsage{InputTokens: 100, OutputTokens: 30, CacheReadTokens: 20, CacheWriteTokens: 5, CostUSDTicks: 900},
+ },
+ {
+ name: "partial terminal preserves stream-only bucket",
+ snapshots: []string{
+ `{"cacheWriteTokens":500,"costUsdTicks":700}`,
+ `{"inputTokens":120,"outputTokens":30,"totalTokens":150,"cacheReadTokens":20,"costUsdTicks":900}`,
+ },
+ want: TokenUsage{InputTokens: 100, OutputTokens: 30, CacheReadTokens: 20, CacheWriteTokens: 500, CostUSDTicks: 900},
+ },
+ {
+ name: "unknown terminal bucket shape cannot erase known usage",
+ snapshots: []string{
+ `{"inputTokens":100,"outputTokens":30,"cacheReadTokens":20,"cacheWriteTokens":5,"costUsdTicks":900}`,
+ `{"prompt_tokens":200,"completion_tokens":50,"totalTokens":250,"costUsdTicks":1000}`,
+ },
+ want: TokenUsage{InputTokens: 100, OutputTokens: 30, CacheReadTokens: 20, CacheWriteTokens: 5, CostUSDTicks: 1000},
+ },
+ {
+ name: "cumulative stream outranks smaller normalized prompt delta",
+ snapshots: []string{
+ `{"inputTokens":300,"outputTokens":120,"cacheReadTokens":80,"costUsdTicks":900}`,
+ `{"inputTokens":120,"outputTokens":30,"totalTokens":150,"cacheReadTokens":20,"cacheWriteTokens":7,"costUsdTicks":400}`,
+ },
+ want: TokenUsage{InputTokens: 300, OutputTokens: 120, CacheReadTokens: 80, CacheWriteTokens: 7, CostUSDTicks: 900},
+ },
+ {
+ name: "late cumulative stream outranks earlier normalized prompt delta",
+ snapshots: []string{
+ `{"inputTokens":120,"outputTokens":30,"totalTokens":150,"cacheReadTokens":20,"cacheWriteTokens":7,"costUsdTicks":400}`,
+ `{"inputTokens":300,"outputTokens":120,"cacheReadTokens":80,"costUsdTicks":900}`,
+ },
+ want: TokenUsage{InputTokens: 300, OutputTokens: 120, CacheReadTokens: 80, CacheWriteTokens: 7, CostUSDTicks: 900},
+ },
+ {
+ name: "normalized cumulative prompt replaces overlapping stream input",
+ snapshots: []string{
+ `{"inputTokens":120,"outputTokens":30,"cacheReadTokens":20,"costUsdTicks":800}`,
+ `{"inputTokens":120,"outputTokens":30,"totalTokens":150,"cacheReadTokens":20,"costUsdTicks":900}`,
+ `{"inputTokens":120,"outputTokens":30,"cacheReadTokens":20,"costUsdTicks":1000}`,
+ },
+ want: TokenUsage{InputTokens: 100, OutputTokens: 30, CacheReadTokens: 20, CostUSDTicks: 1000},
+ },
+ {
+ name: "unknown total cannot block later normalized snapshot",
+ snapshots: []string{
+ `{"inputTokens":120,"outputTokens":30,"cacheReadTokens":20,"costUsdTicks":800}`,
+ `{"prompt_tokens":200,"completion_tokens":50,"totalTokens":250,"costUsdTicks":1000}`,
+ `{"inputTokens":120,"outputTokens":30,"totalTokens":150,"cacheReadTokens":20,"cacheWriteTokens":5,"costUsdTicks":900}`,
+ },
+ want: TokenUsage{InputTokens: 100, OutputTokens: 30, CacheReadTokens: 20, CacheWriteTokens: 5, CostUSDTicks: 1000},
+ },
+ {
+ name: "provider cost uses largest cumulative report",
+ snapshots: []string{
+ `{"inputTokens":100,"costUsdTicks":900}`,
+ `{"outputTokens":30,"costUsdTicks":500}`,
+ `{"cacheReadTokens":20,"costUsdTicks":1200}`,
+ },
+ want: TokenUsage{InputTokens: 100, OutputTokens: 30, CacheReadTokens: 20, CostUSDTicks: 1200},
+ },
+ }
+
+ for _, test := range tests {
+ test := test
+ t.Run(test.name, func(t *testing.T) {
+ t.Parallel()
+
+ var accumulator acpUsageAccumulator
+ for _, raw := range test.snapshots {
+ accumulator.merge(parseACPTokenUsageSnapshot(json.RawMessage(raw)))
+ }
+ if got := accumulator.TokenUsage; got != test.want {
+ t.Fatalf("usage = %+v, want %+v", got, test.want)
+ }
+ })
+ }
+}
+
+func TestACPPromptUsageFillsPartialTopLevelFromMeta(t *testing.T) {
+ t.Parallel()
+
+ var got hermesPromptResult
+ client := &hermesClient{
+ pending: make(map[int]*pendingRPC),
+ onPromptDone: func(result hermesPromptResult) {
+ got = result
+ },
+ }
+ client.extractPromptResult(json.RawMessage(`{
+ "stopReason":"end_turn",
+ "usage":{"inputTokens":100,"outputTokens":30},
+ "_meta":{
+ "inputTokens":999,
+ "usage":{"inputTokens":999,"cacheReadTokens":20,"cacheWriteTokens":5,"costUsdTicks":900}
+ }
+ }`))
+
+ want := TokenUsage{
+ InputTokens: 100,
+ OutputTokens: 30,
+ CacheReadTokens: 20,
+ CacheWriteTokens: 5,
+ CostUSDTicks: 900,
+ }
+ if got.usage.TokenUsage != want {
+ t.Fatalf("usage = %+v, want %+v", got.usage.TokenUsage, want)
+ }
+}
+
+func TestACPPromptUsageNormalizesComplementaryRepresentations(t *testing.T) {
+ t.Parallel()
+
+ tests := []struct {
+ name string
+ raw string
+ want TokenUsage
+ }{
+ {
+ name: "top-level tokens and nested meta cache",
+ raw: `{
+ "stopReason":"end_turn",
+ "usage":{"inputTokens":120,"outputTokens":30},
+ "_meta":{"usage":{"cacheReadTokens":20,"totalTokens":150}}
+ }`,
+ want: TokenUsage{InputTokens: 100, OutputTokens: 30, CacheReadTokens: 20},
+ },
+ {
+ name: "nested meta tokens and flat meta cache",
+ raw: `{
+ "stopReason":"end_turn",
+ "_meta":{
+ "usage":{"inputTokens":120,"outputTokens":30},
+ "cacheReadTokens":20,
+ "totalTokens":150
+ }
+ }`,
+ want: TokenUsage{InputTokens: 100, OutputTokens: 30, CacheReadTokens: 20},
+ },
+ {
+ name: "already normalized input is not subtracted twice",
+ raw: `{
+ "stopReason":"end_turn",
+ "usage":{"inputTokens":120,"outputTokens":30,"cacheReadTokens":20,"totalTokens":150},
+ "_meta":{"usage":{"cacheWriteTokens":5,"costUsdTicks":900}}
+ }`,
+ want: TokenUsage{InputTokens: 100, OutputTokens: 30, CacheReadTokens: 20, CacheWriteTokens: 5, CostUSDTicks: 900},
+ },
+ }
+
+ for _, test := range tests {
+ test := test
+ t.Run(test.name, func(t *testing.T) {
+ t.Parallel()
+
+ var got hermesPromptResult
+ client := &hermesClient{
+ pending: make(map[int]*pendingRPC),
+ onPromptDone: func(result hermesPromptResult) {
+ got = result
+ },
+ }
+ client.extractPromptResult(json.RawMessage(test.raw))
+
+ if got.usage.TokenUsage != test.want {
+ t.Fatalf("usage = %+v, want %+v", got.usage.TokenUsage, test.want)
+ }
+ })
+ }
+}
+
+func TestACPUsagePresentWithProviderCostOnly(t *testing.T) {
+ t.Parallel()
+
+ if !acpUsagePresent(TokenUsage{CostUSDTicks: 42}) {
+ t.Fatal("provider-reported cost must produce a Result.Usage entry even without token buckets")
+ }
+}
diff --git a/server/pkg/agent/grok.go b/server/pkg/agent/grok.go
index 310e424393..4c3c7718e8 100644
--- a/server/pkg/agent/grok.go
+++ b/server/pkg/agent/grok.go
@@ -447,16 +447,11 @@ func (b *grokBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
if effectiveModel == "" {
effectiveModel = pr.modelID
}
- c.usageMu.Lock()
- c.usage.InputTokens += pr.usage.InputTokens
- c.usage.OutputTokens += pr.usage.OutputTokens
- c.usage.CacheReadTokens += pr.usage.CacheReadTokens
// xAI prices the turn itself and reports the result here.
// Carrying it through is the only way the ≥200K long-context
// surcharge reaches the bill — token counts alone cannot
// reconstruct which tier a request hit.
- c.usage.CostUSDTicks += pr.usage.CostUSDTicks
- c.usageMu.Unlock()
+ c.mergeUsage(pr.usage)
default:
}
waitForGrokNotificationQuiescence(runCtx, activity, readerDone)
@@ -490,12 +485,10 @@ func (b *grokBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
// lands before a tool call stays visible.
finalStatus, finalError = promoteACPResultOnProviderError(finalStatus, finalError, providerErrorOutput, providerErr)
- c.usageMu.Lock()
- u := c.usage
- c.usageMu.Unlock()
+ u := c.accumulatedUsage()
var usageMap map[string]TokenUsage
- if u.InputTokens > 0 || u.OutputTokens > 0 || u.CacheReadTokens > 0 || u.CacheWriteTokens > 0 {
+ if acpUsagePresent(u) {
model := effectiveModel
if model == "" {
model = "unknown"
diff --git a/server/pkg/agent/grok_test.go b/server/pkg/agent/grok_test.go
index df0728fc9f..59104bab5e 100644
--- a/server/pkg/agent/grok_test.go
+++ b/server/pkg/agent/grok_test.go
@@ -109,7 +109,7 @@ while IFS= read -r line; do
if [ -n "$GROK_USAGE" ]; then
# Match live Grok Build ACP (0.2.x): metering lives under result._meta,
# not a top-level usage field or sessionUpdate=usage_update.
- printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","_meta":{"sessionId":"ses_new","modelId":"grok-4.5","inputTokens":120,"outputTokens":30,"cachedReadTokens":20,"usage":{"inputTokens":120,"outputTokens":30,"totalTokens":150,"cachedReadTokens":20,"modelCalls":1,"costUsdTicks":98765}}}}\n' "$id"
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","_meta":{"sessionId":"ses_new","modelId":"grok-4.5","inputTokens":120,"outputTokens":30,"cachedReadTokens":20,"cachedWriteTokens":5,"usage":{"inputTokens":120,"outputTokens":30,"totalTokens":150,"cachedReadTokens":20,"cachedWriteTokens":5,"modelCalls":1,"costUsdTicks":98765}}}}\n' "$id"
else
printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn"}}\n' "$id"
fi
@@ -613,7 +613,7 @@ func TestGrokPropagatesMCPAndUsage(t *testing.T) {
// The fixture's totalTokens (150) equals input + output, so its 20 cached
// reads sit inside inputTokens and are billed once: input is stored as the
// uncached remainder 120 - 20 = 100.
- if usage.InputTokens != 100 || usage.OutputTokens != 30 || usage.CacheReadTokens != 20 {
+ if usage.InputTokens != 100 || usage.OutputTokens != 30 || usage.CacheReadTokens != 20 || usage.CacheWriteTokens != 5 {
t.Fatalf("unexpected usage: %+v", usage)
}
// xAI's own price for the turn has to survive the whole backend, not just
@@ -667,9 +667,12 @@ func TestGrokAttributesUsageOnResumeWithoutConfiguredModel(t *testing.T) {
if !ok {
t.Fatalf("usage missing grok-4.5 key: %+v", result.Usage)
}
- if usage.InputTokens != 100 || usage.OutputTokens != 30 || usage.CacheReadTokens != 20 {
+ if usage.InputTokens != 100 || usage.OutputTokens != 30 || usage.CacheReadTokens != 20 || usage.CacheWriteTokens != 5 {
t.Fatalf("unexpected usage: %+v", usage)
}
+ if usage.CostUSDTicks != 98765 {
+ t.Fatalf("cost ticks = %d, want 98765", usage.CostUSDTicks)
+ }
}
func TestGrokTimeoutAndCancellation(t *testing.T) {
diff --git a/server/pkg/agent/hermes.go b/server/pkg/agent/hermes.go
index 2aae808383..1b04efbb43 100644
--- a/server/pkg/agent/hermes.go
+++ b/server/pkg/agent/hermes.go
@@ -562,12 +562,7 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
finalStatus = "aborted"
finalError = "hermes cancelled the prompt"
}
- // Merge usage from the PromptResponse.
- c.usageMu.Lock()
- c.usage.InputTokens += pr.usage.InputTokens
- c.usage.OutputTokens += pr.usage.OutputTokens
- c.usage.CacheReadTokens += pr.usage.CacheReadTokens
- c.usageMu.Unlock()
+ c.mergeUsage(pr.usage)
default:
}
waitForHermesNotificationQuiescence(runCtx, activity, readerDone)
@@ -648,12 +643,10 @@ func (b *hermesBackend) Execute(ctx context.Context, prompt string, opts ExecOpt
}
// Build usage map.
- c.usageMu.Lock()
- u := c.usage
- c.usageMu.Unlock()
+ u := c.accumulatedUsage()
var usageMap map[string]TokenUsage
- if u.InputTokens > 0 || u.OutputTokens > 0 || u.CacheReadTokens > 0 || u.CacheWriteTokens > 0 {
+ if acpUsagePresent(u) {
model := effectiveModel
if model == "" {
model = "unknown"
@@ -747,7 +740,7 @@ func waitForHermesPipeDrain(readerDone, stderrDone <-chan struct{}, timeout time
type hermesPromptResult struct {
stopReason string
- usage TokenUsage
+ usage acpUsageSnapshot
// modelID is the model the agent actually billed this turn against, as
// reported on `result._meta.modelId`. Empty for agents that don't report
// it. Backends use it to attribute usage when the session handshake
@@ -792,7 +785,7 @@ type hermesClient struct {
pendingTools map[string]*pendingToolCall
usageMu sync.Mutex
- usage TokenUsage
+ usage acpUsageAccumulator
}
// pendingToolCall buffers state for a tool call while its arguments
@@ -1232,19 +1225,15 @@ func (c *hermesClient) extractPromptResult(data json.RawMessage) {
stopReason: resp.StopReason,
modelID: parseACPModelIDFromMeta(resp.Meta),
}
+ var usage acpUsageSnapshot
if len(resp.Usage) > 0 && string(resp.Usage) != "null" {
- pr.usage = parseACPTokenUsage(resp.Usage)
- }
- // Prefer the standard top-level ACP `usage` field when present. Some
- // agents (notably xAI Grok Build) put per-turn metering only under
- // result._meta — either as `_meta.usage` or as flat token counters on
- // `_meta` itself. Without this fallback, tasks complete with an empty
- // usage map and Multica's Usage/cost dashboards stay at zero.
- if !acpTokenUsagePresent(pr.usage) {
- if metaUsage := parseACPTokenUsageFromMeta(resp.Meta); acpTokenUsagePresent(metaUsage) {
- pr.usage = metaUsage
- }
+ usage = parseACPTokenUsageSnapshot(resp.Usage)
}
+ // Some agents (notably xAI Grok Build) put per-turn metering under
+ // result._meta instead of, or in addition to, the standard top-level
+ // usage field. Reconcile both shapes so partial mirrors cannot drop a
+ // cache bucket or provider-reported cost.
+ pr.usage = usage.withFallback(parseACPTokenUsageSnapshotFromMeta(resp.Meta))
if c.onPromptDone != nil {
c.onPromptDone(pr)
@@ -1256,28 +1245,8 @@ func acpTokenUsagePresent(u TokenUsage) bool {
return u.InputTokens > 0 || u.OutputTokens > 0 || u.CacheReadTokens > 0 || u.CacheWriteTokens > 0
}
-// parseACPTokenUsageFromMeta extracts token usage from an ACP result `_meta`
-// object. Grok Build returns shapes like:
-//
-// {"inputTokens":…,"outputTokens":…,"cachedReadTokens":…,"usage":{…}}
-//
-// Prefer the nested `usage` object when it carries counters; otherwise parse
-// the flat `_meta` fields with the same alias rules as top-level usage.
-func parseACPTokenUsageFromMeta(meta json.RawMessage) TokenUsage {
- if len(meta) == 0 || string(meta) == "null" {
- return TokenUsage{}
- }
- var envelope struct {
- Usage json.RawMessage `json:"usage"`
- }
- if err := json.Unmarshal(meta, &envelope); err == nil {
- if len(envelope.Usage) > 0 && string(envelope.Usage) != "null" {
- if u := parseACPTokenUsage(envelope.Usage); acpTokenUsagePresent(u) {
- return u
- }
- }
- }
- return parseACPTokenUsage(meta)
+func acpUsagePresent(u TokenUsage) bool {
+ return acpTokenUsagePresent(u) || u.CostUSDTicks > 0
}
// parseACPModelIDFromMeta pulls the model id off an ACP result `_meta`
@@ -1763,115 +1732,19 @@ func (c *hermesClient) handleUsageUpdate(data json.RawMessage) {
if err := json.Unmarshal(data, &msg); err != nil {
return
}
- usage := parseACPTokenUsage(msg.Usage)
+ c.mergeUsage(parseACPTokenUsageSnapshot(msg.Usage))
+}
+func (c *hermesClient) mergeUsage(usage acpUsageSnapshot) {
c.usageMu.Lock()
- // Usage updates from ACP are cumulative snapshots, so take the latest.
- if usage.InputTokens > c.usage.InputTokens {
- c.usage.InputTokens = usage.InputTokens
- }
- if usage.OutputTokens > c.usage.OutputTokens {
- c.usage.OutputTokens = usage.OutputTokens
- }
- if usage.CacheReadTokens > c.usage.CacheReadTokens {
- c.usage.CacheReadTokens = usage.CacheReadTokens
- }
- if usage.CacheWriteTokens > c.usage.CacheWriteTokens {
- c.usage.CacheWriteTokens = usage.CacheWriteTokens
- }
- if usage.CostUSDTicks > c.usage.CostUSDTicks {
- c.usage.CostUSDTicks = usage.CostUSDTicks
- }
+ c.usage.merge(usage)
c.usageMu.Unlock()
}
-func parseACPTokenUsage(data json.RawMessage) TokenUsage {
- if len(data) == 0 || string(data) == "null" {
- return TokenUsage{}
- }
- var fields map[string]json.RawMessage
- if err := json.Unmarshal(data, &fields); err != nil {
- return TokenUsage{}
- }
- usage := TokenUsage{
- InputTokens: acpUsageInt64(fields, "inputTokens", "input_tokens"),
- OutputTokens: acpUsageInt64(fields, "outputTokens", "output_tokens"),
- CacheReadTokens: acpUsageInt64(fields,
- "cachedReadTokens",
- "cacheReadTokens",
- "cached_input_tokens",
- "cache_read_tokens",
- "cache_read_input_tokens",
- ),
- CacheWriteTokens: acpUsageInt64(fields,
- "cachedWriteTokens",
- "cacheWriteTokens",
- "cache_write_tokens",
- "cache_creation_input_tokens",
- ),
- // The provider's own price for this turn, already inclusive of
- // request-level pricing rules we cannot reconstruct from token
- // counts (see TokenUsage.CostUSDTicks).
- CostUSDTicks: acpUsageInt64(fields, "costUsdTicks", "cost_usd_ticks"),
- }
- return excludeACPCachedInput(usage, acpUsageInt64(fields, "totalTokens", "total_tokens"))
-}
-
-// excludeACPCachedInput re-buckets a usage record whose `inputTokens` already
-// contains `cachedReadTokens`, so the persisted buckets stay mutually
-// exclusive and dashboard cost math does not charge the cached prefix twice
-// (same normalization codex.go applies via codexUncachedInputTokens).
-//
-// ACP does not specify whether cached reads are counted inside inputTokens.
-// Grok Build counts them inside: a real `grok 0.2.106` turn reports
-// inputTokens=12929, cachedReadTokens=10880, outputTokens=29,
-// totalTokens=12958 — i.e. total == input + output, so the cached prefix is
-// counted once, within input. The same payload's costUsdTicks=75360000
-// ($0.007536) matches exactly (12929-10880) uncached input + 10880 cached
-// read + 29 output at xAI's published grok-4.5 rates, confirming how xAI
-// bills it. Kept raw, that turn is priced as if 12929 tokens were uncached —
-// ~4x the real spend on a cache-heavy turn.
-//
-// `totalTokens` is the only self-describing signal available, so the
-// re-bucketing only happens when it is present and equals input + output.
-// Agents that report exclusive buckets (total == input + cached + output) or
-// omit totalTokens keep their counters untouched.
-func excludeACPCachedInput(usage TokenUsage, totalTokens int64) TokenUsage {
- if totalTokens <= 0 || usage.CacheReadTokens <= 0 || usage.CacheReadTokens > usage.InputTokens {
- return usage
- }
- if totalTokens != usage.InputTokens+usage.OutputTokens {
- return usage
- }
- usage.InputTokens -= usage.CacheReadTokens
- return usage
-}
-
-func acpUsageInt64(fields map[string]json.RawMessage, names ...string) int64 {
- for _, name := range names {
- raw, ok := fields[name]
- if !ok {
- continue
- }
- var n json.Number
- dec := json.NewDecoder(bytes.NewReader(raw))
- dec.UseNumber()
- if err := dec.Decode(&n); err == nil {
- if v, err := n.Int64(); err == nil {
- return v
- }
- if f, err := n.Float64(); err == nil {
- return int64(f)
- }
- }
- var s string
- if err := json.Unmarshal(raw, &s); err == nil {
- if v, err := strconv.ParseInt(strings.TrimSpace(s), 10, 64); err == nil {
- return v
- }
- }
- }
- return 0
+func (c *hermesClient) accumulatedUsage() TokenUsage {
+ c.usageMu.Lock()
+ defer c.usageMu.Unlock()
+ return c.usage.TokenUsage
}
// ── Helpers ──
diff --git a/server/pkg/agent/hermes_integration_test.go b/server/pkg/agent/hermes_integration_test.go
new file mode 100644
index 0000000000..2ef0f7bf33
--- /dev/null
+++ b/server/pkg/agent/hermes_integration_test.go
@@ -0,0 +1,84 @@
+//go:build agentintegration
+
+package agent
+
+import (
+ "context"
+ "log/slog"
+ "os/exec"
+ "strings"
+ "testing"
+ "time"
+)
+
+// TestHermesRealACPUsageSmoke drives the real `hermes acp` binary end-to-end
+// and verifies its metering survives the shared ACP reconciliation path.
+func TestHermesRealACPUsageSmoke(t *testing.T) {
+ requireRealAgentSmoke(t)
+ if testing.Short() {
+ t.Skip("skipping real-binary smoke test in -short mode")
+ }
+ path, err := exec.LookPath("hermes")
+ if err != nil {
+ t.Skip("hermes not on PATH; skipping real-binary smoke test")
+ }
+ if version, err := exec.Command(path, "--version").CombinedOutput(); err == nil {
+ t.Logf("hermes CLI version: %s", strings.TrimSpace(string(version)))
+ }
+
+ backend, err := New("hermes", Config{ExecutablePath: path, Logger: slog.Default()})
+ if err != nil {
+ t.Fatalf("new hermes backend: %v", err)
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 180*time.Second)
+ defer cancel()
+
+ session, err := backend.Execute(ctx, "Reply with exactly one word: alpha. Do not use any tools.", ExecOptions{
+ Cwd: t.TempDir(),
+ Timeout: 150 * time.Second,
+ })
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+
+ result := <-session.Result
+ t.Logf("status=%q error=%q output=%q session=%q", result.Status, result.Error, result.Output, result.SessionID)
+ if result.Status != "completed" {
+ t.Fatalf("expected completed, got %q (%s)", result.Status, result.Error)
+ }
+ if !strings.Contains(strings.ToLower(result.Output), "alpha") {
+ t.Fatalf("expected output to contain alpha, got %q", result.Output)
+ }
+ if result.SessionID == "" {
+ t.Error("expected a non-empty session id")
+ }
+ if len(result.Usage) == 0 {
+ t.Fatal("no usage reported by the real Hermes ACP run")
+ }
+
+ var total TokenUsage
+ for model, usage := range result.Usage {
+ t.Logf("usage[%s] = input:%d output:%d cacheRead:%d cacheWrite:%d costTicks:%d",
+ model,
+ usage.InputTokens,
+ usage.OutputTokens,
+ usage.CacheReadTokens,
+ usage.CacheWriteTokens,
+ usage.CostUSDTicks,
+ )
+ total.InputTokens += usage.InputTokens
+ total.OutputTokens += usage.OutputTokens
+ total.CacheReadTokens += usage.CacheReadTokens
+ total.CacheWriteTokens += usage.CacheWriteTokens
+ }
+ if total.InputTokens <= 0 {
+ t.Errorf("input tokens = %d, want > 0", total.InputTokens)
+ }
+ if total.OutputTokens <= 0 {
+ t.Errorf("output tokens = %d, want > 0", total.OutputTokens)
+ }
+}
diff --git a/server/pkg/agent/hermes_test.go b/server/pkg/agent/hermes_test.go
index cbb1a2deea..ac0d66afc3 100644
--- a/server/pkg/agent/hermes_test.go
+++ b/server/pkg/agent/hermes_test.go
@@ -1831,7 +1831,7 @@ func TestHermesClientExtractPromptResultTopLevelZeroFallsBackToMeta(t *testing.T
c.extractPromptResult(data)
want := TokenUsage{InputTokens: 100, OutputTokens: 20, CacheReadTokens: 5, CacheWriteTokens: 2}
- if got.usage != want {
+ if got.usage.TokenUsage != want {
t.Fatalf("zero top-level usage should fall back to _meta: got %+v, want %+v", got.usage, want)
}
}
@@ -2184,7 +2184,13 @@ while IFS= read -r line; do
printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_model","models":{"currentModelId":"nous:moonshotai/kimi-k2.6","availableModels":[{"modelId":"nous:moonshotai/kimi-k2.6","name":"moonshotai/kimi-k2.6"}]}}}\n' "$id"
;;
*'"method":"session/prompt"'*)
- printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","usage":{"inputTokens":17,"outputTokens":5,"cachedReadTokens":3}}}\n' "$id"
+ if [ -n "$HERMES_LATE_USAGE" ]; then
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","usage":{"inputTokens":120,"outputTokens":30,"totalTokens":150,"cachedReadTokens":20,"cachedWriteTokens":7,"costUsdTicks":400}}}\n' "$id"
+ sleep 0.05
+ printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_model","update":{"sessionUpdate":"usage_update","usage":{"inputTokens":300,"outputTokens":120,"cachedReadTokens":80,"costUsdTicks":900}}}}\n'
+ exit 0
+ fi
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","usage":{"inputTokens":17,"outputTokens":5,"cachedReadTokens":3,"cachedWriteTokens":2,"costUsdTicks":900}}}\n' "$id"
exit 0
;;
esac
@@ -2232,14 +2238,48 @@ func TestHermesBackendAttributesUsageToACPDefaultModel(t *testing.T) {
if !ok {
t.Fatalf("expected usage under Hermes current model, got %+v", result.Usage)
}
- if usage.InputTokens != 17 || usage.OutputTokens != 5 || usage.CacheReadTokens != 3 {
- t.Fatalf("usage = %+v, want input=17 output=5 cache_read=3", usage)
+ if usage != (TokenUsage{InputTokens: 17, OutputTokens: 5, CacheReadTokens: 3, CacheWriteTokens: 2, CostUSDTicks: 900}) {
+ t.Fatalf("usage = %+v, want all prompt-result fields", usage)
}
case <-time.After(10 * time.Second):
t.Fatal("timeout waiting for result")
}
}
+func TestHermesBackendMergesLateCumulativeUsageAfterPromptResponse(t *testing.T) {
+ t.Parallel()
+
+ fakePath := filepath.Join(t.TempDir(), "hermes")
+ writeTestExecutable(t, fakePath, []byte(fakeHermesACPUsageWithDefaultModelScript()))
+
+ backend, err := New("hermes", Config{
+ ExecutablePath: fakePath,
+ Logger: slog.Default(),
+ Env: map[string]string{"HERMES_LATE_USAGE": "1"},
+ })
+ if err != nil {
+ t.Fatalf("new hermes backend: %v", err)
+ }
+
+ session, err := backend.Execute(context.Background(), "prompt", ExecOptions{Timeout: 5 * time.Second})
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+
+ result := <-session.Result
+ if result.Status != "completed" {
+ t.Fatalf("status=%q error=%q", result.Status, result.Error)
+ }
+ want := TokenUsage{InputTokens: 300, OutputTokens: 120, CacheReadTokens: 80, CacheWriteTokens: 7, CostUSDTicks: 900}
+ if usage := result.Usage["nous:moonshotai/kimi-k2.6"]; usage != want {
+ t.Fatalf("usage = %+v, want %+v", usage, want)
+ }
+}
+
// fakeHermesACPRateLimitScript impersonates hermes for the GitHub
// multica#1952 scenario: the upstream LLM returns HTTP 429 (rate
// limited / no credit), hermes retries internally and ultimately
diff --git a/server/pkg/agent/kimi.go b/server/pkg/agent/kimi.go
index 87b3d73479..237cc23ebf 100644
--- a/server/pkg/agent/kimi.go
+++ b/server/pkg/agent/kimi.go
@@ -375,17 +375,12 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
finalStatus = "aborted"
finalError = "kimi cancelled the prompt"
}
- c.usageMu.Lock()
- c.usage.InputTokens += pr.usage.InputTokens
- c.usage.OutputTokens += pr.usage.OutputTokens
// kimi-code 0.33.0 sends no usage at all on this path,
- // so these two are inert today; they exist so a future
+ // so this is inert today; it exists so a future
// kimi that does populate the ACP result is billed
- // correctly instead of silently dropping its cache
- // split. scanKimiSessionUsage below is the live path.
- c.usage.CacheReadTokens += pr.usage.CacheReadTokens
- c.usage.CacheWriteTokens += pr.usage.CacheWriteTokens
- c.usageMu.Unlock()
+ // correctly instead of silently dropping cache or cost
+ // fields. scanKimiSessionUsage below is the live path.
+ c.mergeUsage(pr.usage)
default:
}
waitForACPNotificationQuiescence(runCtx, activity, readerDone, acpNotificationQuietTime, kimiReaderDrainGrace)
@@ -415,9 +410,7 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
// stays visible.
finalStatus, finalError = promoteACPResultOnProviderError(finalStatus, finalError, providerErrorOutput, providerErr)
- c.usageMu.Lock()
- u := c.usage
- c.usageMu.Unlock()
+ u := c.accumulatedUsage()
// Fallback: kimi-code 0.33.0 exports no token counters over ACP.
// Its session/prompt result carries only stopReason, and its
@@ -449,6 +442,17 @@ func (b *kimiBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
resumed: opts.ResumeSessionID != "",
fallbackModel: fallbackModel,
})
+ // A future Kimi build may expose provider cost before it exposes
+ // token buckets over ACP. Preserve that cost alongside the current
+ // wire-log fallback instead of dropping either source.
+ if u.CostUSDTicks > 0 {
+ modelUsage := usageMap[fallbackModel]
+ modelUsage.CostUSDTicks = u.CostUSDTicks
+ if usageMap == nil {
+ usageMap = make(map[string]TokenUsage)
+ }
+ usageMap[fallbackModel] = modelUsage
+ }
}
resCh <- Result{
diff --git a/server/pkg/agent/kimi_test.go b/server/pkg/agent/kimi_test.go
index 87b8892399..0fc1fe970c 100644
--- a/server/pkg/agent/kimi_test.go
+++ b/server/pkg/agent/kimi_test.go
@@ -713,6 +713,56 @@ done
`
}
+func fakeKimiACPPromptUsageScript() string {
+ return `#!/bin/sh
+while IFS= read -r line; do
+ id=$(printf '%s' "$line" | sed -n 's/.*"id":\([0-9]*\).*/\1/p')
+ case "$line" in
+ *'"method":"initialize"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"protocolVersion":1,"agentCapabilities":{}}}\n' "$id"
+ ;;
+ *'"method":"session/new"'*)
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"session_prompt_usage"}}\n' "$id"
+ ;;
+ *'"method":"session/prompt"'*)
+ printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"session_prompt_usage","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"done"}}}}\n'
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","usage":{"inputTokens":17,"outputTokens":5,"cachedReadTokens":3,"cachedWriteTokens":2,"costUsdTicks":900}}}\n' "$id"
+ exit 0
+ ;;
+ esac
+done
+`
+}
+
+func TestKimiBackendPropagatesACPPromptUsage(t *testing.T) {
+ t.Parallel()
+
+ fakePath := filepath.Join(t.TempDir(), "kimi")
+ writeTestExecutable(t, fakePath, []byte(fakeKimiACPPromptUsageScript()))
+
+ backend, err := New("kimi", Config{ExecutablePath: fakePath, Logger: slog.Default()})
+ if err != nil {
+ t.Fatalf("new kimi backend: %v", err)
+ }
+ session, err := backend.Execute(context.Background(), "task", ExecOptions{Timeout: 5 * time.Second})
+ if err != nil {
+ t.Fatalf("execute: %v", err)
+ }
+ go func() {
+ for range session.Messages {
+ }
+ }()
+
+ result := <-session.Result
+ if result.Status != "completed" {
+ t.Fatalf("status=%q error=%q", result.Status, result.Error)
+ }
+ want := TokenUsage{InputTokens: 17, OutputTokens: 5, CacheReadTokens: 3, CacheWriteTokens: 2, CostUSDTicks: 900}
+ if usage := result.Usage["unknown"]; usage != want {
+ t.Fatalf("usage = %+v, want %+v", usage, want)
+ }
+}
+
// TestKimiBackendReportsUsageFromWireLog is the end-to-end proof for
// MUL-5773 / #6448: with an ACP peer that reports no usage at all — which is
// what kimi-code 0.33.0 actually does — the task still lands on the dashboard
diff --git a/server/pkg/agent/kiro.go b/server/pkg/agent/kiro.go
index 1fcc20f3b8..073ca4d2c6 100644
--- a/server/pkg/agent/kiro.go
+++ b/server/pkg/agent/kiro.go
@@ -432,12 +432,7 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
finalStatus = "aborted"
finalError = "kiro cancelled the prompt"
}
- c.usageMu.Lock()
- c.usage.InputTokens += pr.usage.InputTokens
- c.usage.OutputTokens += pr.usage.OutputTokens
- c.usage.CacheReadTokens += pr.usage.CacheReadTokens
- c.usage.CacheWriteTokens += pr.usage.CacheWriteTokens
- c.usageMu.Unlock()
+ c.mergeUsage(pr.usage)
default:
}
waitForACPNotificationQuiescence(runCtx, activity, readerDone, acpNotificationQuietTime, kiroReaderDrainGrace)
@@ -466,12 +461,10 @@ func (b *kiroBackend) Execute(ctx context.Context, prompt string, opts ExecOptio
// stays visible.
finalStatus, finalError = promoteACPResultOnProviderError(finalStatus, finalError, providerErrorOutput, providerErr)
- c.usageMu.Lock()
- u := c.usage
- c.usageMu.Unlock()
+ u := c.accumulatedUsage()
var usageMap map[string]TokenUsage
- if u.InputTokens > 0 || u.OutputTokens > 0 || u.CacheReadTokens > 0 || u.CacheWriteTokens > 0 {
+ if acpUsagePresent(u) {
model := effectiveModel
if model == "" {
model = "unknown"
diff --git a/server/pkg/agent/kiro_test.go b/server/pkg/agent/kiro_test.go
index 43ce2589bc..bb319041f8 100644
--- a/server/pkg/agent/kiro_test.go
+++ b/server/pkg/agent/kiro_test.go
@@ -106,7 +106,7 @@ while IFS= read -r line; do
esac
printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_loaded","update":{"type":"ToolCallUpdate","toolCallId":"tc-current","status":"completed","name":"Shell","parameters":{"command":"echo current"},"output":"current tool output\\n"}}}\n'
printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_loaded","update":{"type":"AgentMessageChunk","content":{"type":"text","text":"loaded"}}}}\n'
- printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","usage":{"inputTokens":2,"outputTokens":1,"cacheReadTokens":7,"cacheWriteTokens":3}}}\n' "$id"
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","usage":{"inputTokens":2,"outputTokens":1,"cacheReadTokens":7,"cacheWriteTokens":3,"costUsdTicks":900}}}\n' "$id"
if [ -n "$KIRO_LATE_CHUNK" ]; then
sleep 0.05
printf '{"jsonrpc":"2.0","method":"session/notification","params":{"sessionId":"ses_loaded","update":{"type":"AgentMessageChunk","content":{"type":"text","text":" tail"}}}}\n'
@@ -202,8 +202,8 @@ func TestKiroBackendAttributesUsageToCurrentModel(t *testing.T) {
if !ok {
t.Fatalf("expected usage under current model auto, got %+v", result.Usage)
}
- if usage.InputTokens != 2 || usage.OutputTokens != 1 || usage.CacheReadTokens != 7 || usage.CacheWriteTokens != 3 {
- t.Fatalf("usage = %+v, want input=2 output=1 cache_read=7 cache_write=3", usage)
+ if usage != (TokenUsage{InputTokens: 2, OutputTokens: 1, CacheReadTokens: 7, CacheWriteTokens: 3, CostUSDTicks: 900}) {
+ t.Fatalf("usage = %+v, want all prompt-result fields", usage)
}
}
@@ -1010,8 +1010,8 @@ func TestKiroBackendUsesSessionLoadForResume(t *testing.T) {
if result.Output != "loaded" {
t.Fatalf("output = %q, want loaded", result.Output)
}
- if usage := result.Usage["unknown"]; usage.InputTokens != 2 || usage.OutputTokens != 1 || usage.CacheReadTokens != 7 || usage.CacheWriteTokens != 3 {
- t.Fatalf("usage = %+v, want input=2 output=1 cache_read=7 cache_write=3", usage)
+ if usage := result.Usage["unknown"]; usage != (TokenUsage{InputTokens: 2, OutputTokens: 1, CacheReadTokens: 7, CacheWriteTokens: 3, CostUSDTicks: 900}) {
+ t.Fatalf("usage = %+v, want all prompt-result fields", usage)
}
if len(messages) != 3 {
t.Fatalf("messages = %+v, want current tool use, tool result, and text only", messages)
diff --git a/server/pkg/agent/qoder.go b/server/pkg/agent/qoder.go
index 5f6a9e9cfc..4bae2a12cf 100644
--- a/server/pkg/agent/qoder.go
+++ b/server/pkg/agent/qoder.go
@@ -377,11 +377,7 @@ func (b *qoderBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
finalStatus = "aborted"
finalError = "qoder cancelled the prompt"
}
- c.usageMu.Lock()
- c.usage.InputTokens += pr.usage.InputTokens
- c.usage.OutputTokens += pr.usage.OutputTokens
- c.usage.CacheReadTokens += pr.usage.CacheReadTokens
- c.usageMu.Unlock()
+ c.mergeUsage(pr.usage)
default:
}
waitForACPNotificationQuiescence(runCtx, activity, readerDone, acpNotificationQuietTime, qoderReaderDrainGrace)
@@ -426,12 +422,10 @@ func (b *qoderBackend) Execute(ctx context.Context, prompt string, opts ExecOpti
// even though qodercli wrote a terminal error to stderr.
finalStatus, finalError = promoteACPResultOnProviderError(finalStatus, finalError, providerErrorOutput, providerErr)
- c.usageMu.Lock()
- u := c.usage
- c.usageMu.Unlock()
+ u := c.accumulatedUsage()
var usageMap map[string]TokenUsage
- if u.InputTokens > 0 || u.OutputTokens > 0 || u.CacheReadTokens > 0 || u.CacheWriteTokens > 0 {
+ if acpUsagePresent(u) {
model := effectiveModel
if model == "" {
model = "unknown"
diff --git a/server/pkg/agent/qoder_test.go b/server/pkg/agent/qoder_test.go
index 9f2fd416b3..33721cc666 100644
--- a/server/pkg/agent/qoder_test.go
+++ b/server/pkg/agent/qoder_test.go
@@ -262,7 +262,7 @@ while IFS= read -r line; do
printf '{"jsonrpc":"2.0","id":%s,"result":{"sessionId":"ses_model","models":{"currentModelId":"qoder:auto","availableModels":[{"modelId":"qoder:auto","name":"Qoder Auto"}]}}}\n' "$id"
;;
*'"method":"session/prompt"'*)
- printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","usage":{"inputTokens":17,"outputTokens":5,"cachedReadTokens":3}}}\n' "$id"
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","usage":{"inputTokens":17,"outputTokens":5,"cachedReadTokens":3,"cachedWriteTokens":2,"costUsdTicks":900}}}\n' "$id"
exit 0
;;
esac
@@ -899,8 +899,8 @@ func TestQoderBackendAttributesUsageToACPDefaultModel(t *testing.T) {
if !ok {
t.Fatalf("expected usage under Qoder current model, got %+v", result.Usage)
}
- if usage.InputTokens != 17 || usage.OutputTokens != 5 || usage.CacheReadTokens != 3 {
- t.Fatalf("usage = %+v, want input=17 output=5 cache_read=3", usage)
+ if usage != (TokenUsage{InputTokens: 17, OutputTokens: 5, CacheReadTokens: 3, CacheWriteTokens: 2, CostUSDTicks: 900}) {
+ t.Fatalf("usage = %+v, want all prompt-result fields", usage)
}
case <-time.After(10 * time.Second):
t.Fatal("timeout waiting for result")
diff --git a/server/pkg/agent/qwenpaw.go b/server/pkg/agent/qwenpaw.go
index b1a070d563..11a98fe67e 100644
--- a/server/pkg/agent/qwenpaw.go
+++ b/server/pkg/agent/qwenpaw.go
@@ -317,10 +317,7 @@ func (b *qwenpawBackend) Execute(ctx context.Context, prompt string, opts ExecOp
duration := time.Since(startTime)
b.cfg.Logger.Info("qwenpaw prompt cancelled", "stopReason", pr.stopReason, "duration", duration.Round(time.Millisecond).String())
}
- c.usageMu.Lock()
- c.usage.InputTokens += pr.usage.InputTokens
- c.usage.OutputTokens += pr.usage.OutputTokens
- c.usageMu.Unlock()
+ c.mergeUsage(pr.usage)
default:
}
}
@@ -340,12 +337,10 @@ func (b *qwenpawBackend) Execute(ctx context.Context, prompt string, opts ExecOp
finalStatus, finalError = promoteACPResultOnProviderError(finalStatus, finalError, finalOutput, providerErr)
- c.usageMu.Lock()
- u := c.usage
- c.usageMu.Unlock()
+ u := c.accumulatedUsage()
var usageMap map[string]TokenUsage
- if u.InputTokens > 0 || u.OutputTokens > 0 || u.CacheReadTokens > 0 || u.CacheWriteTokens > 0 {
+ if acpUsagePresent(u) {
// QwenPaw's model selection is unsupported — the backend never
// sends opts.Model to the agent. Always attribute usage to
// "unknown" rather than a model that was never applied.
diff --git a/server/pkg/agent/qwenpaw_test.go b/server/pkg/agent/qwenpaw_test.go
index dd105bac79..5530e3f829 100644
--- a/server/pkg/agent/qwenpaw_test.go
+++ b/server/pkg/agent/qwenpaw_test.go
@@ -68,7 +68,7 @@ while IFS= read -r line; do
printf '{"jsonrpc":"2.0","id":%s,"result":{}}\n' "$id"
;;
*'"method":"session/prompt"'*)
- printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","usage":{"inputTokens":10,"outputTokens":20}}}\n' "$id"
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","usage":{"inputTokens":10,"outputTokens":20,"cacheReadTokens":3,"cacheWriteTokens":2,"costUsdTicks":900}}}\n' "$id"
;;
*)
printf '{"jsonrpc":"2.0","id":%s,"error":{"code":-32601,"message":"method not found"}}\n' "$id"
@@ -380,11 +380,9 @@ func TestQwenpawBackendUsage(t *testing.T) {
if !ok {
t.Fatalf("expected usage entry for model 'unknown', got %+v", result.Usage)
}
- if usage.InputTokens != 10 {
- t.Fatalf("expected 10 input tokens, got %d", usage.InputTokens)
- }
- if usage.OutputTokens != 20 {
- t.Fatalf("expected 20 output tokens, got %d", usage.OutputTokens)
+ want := TokenUsage{InputTokens: 10, OutputTokens: 20, CacheReadTokens: 3, CacheWriteTokens: 2, CostUSDTicks: 900}
+ if usage != want {
+ t.Fatalf("usage = %+v, want %+v", usage, want)
}
}
diff --git a/server/pkg/agent/reasonix.go b/server/pkg/agent/reasonix.go
index de5a3beae0..7d6a7987bd 100644
--- a/server/pkg/agent/reasonix.go
+++ b/server/pkg/agent/reasonix.go
@@ -148,8 +148,6 @@ func (b *reasonixBackend) Execute(ctx context.Context, prompt string, opts ExecO
var streamingCurrentTurn atomic.Bool
var blockedQuestion atomic.Value // string; set by the stdout reader
var statusUsage reasonixStatusUsageTracker
- var promptUsageMu sync.Mutex
- var promptUsage TokenUsage
promptDone := make(chan hermesPromptResult, 1)
activity := make(chan struct{}, 1)
@@ -417,9 +415,7 @@ func (b *reasonixBackend) Execute(ctx context.Context, prompt string, opts ExecO
finalStatus = "failed"
finalError = fmt.Sprintf("reasonix returned unsupported stopReason %q", pr.stopReason)
}
- promptUsageMu.Lock()
- promptUsage = pr.usage
- promptUsageMu.Unlock()
+ c.mergeUsage(pr.usage)
default:
finalStatus = "failed"
finalError = "reasonix returned no prompt completion result"
@@ -458,15 +454,7 @@ func (b *reasonixBackend) Execute(ctx context.Context, prompt string, opts ExecO
}
}
- c.usageMu.Lock()
- u := c.usage
- c.usageMu.Unlock()
- promptUsageMu.Lock()
- standardPromptUsage := promptUsage
- promptUsageMu.Unlock()
- if reasonixUsagePresent(standardPromptUsage) {
- u = standardPromptUsage
- }
+ u := c.accumulatedUsage()
statusSnapshot, statusModel := statusUsage.snapshot()
if !reasonixUsagePresent(u) {
u = statusSnapshot
diff --git a/server/pkg/agent/traecli.go b/server/pkg/agent/traecli.go
index 57459520e4..9bce64ad0c 100644
--- a/server/pkg/agent/traecli.go
+++ b/server/pkg/agent/traecli.go
@@ -377,11 +377,7 @@ func (b *traecliBackend) Execute(ctx context.Context, prompt string, opts ExecOp
finalStatus = "aborted"
finalError = "traecli cancelled the prompt"
}
- c.usageMu.Lock()
- c.usage.InputTokens += pr.usage.InputTokens
- c.usage.OutputTokens += pr.usage.OutputTokens
- c.usage.CacheReadTokens += pr.usage.CacheReadTokens
- c.usageMu.Unlock()
+ c.mergeUsage(pr.usage)
default:
}
waitForACPNotificationQuiescence(runCtx, activity, readerDone, acpNotificationQuietTime, traecliReaderDrainGrace)
@@ -422,12 +418,10 @@ func (b *traecliBackend) Execute(ctx context.Context, prompt string, opts ExecOp
// give-up turn that lands before a tool call stays visible.
finalStatus, finalError = promoteACPResultOnProviderError(finalStatus, finalError, providerErrorOutput, providerErr)
- c.usageMu.Lock()
- u := c.usage
- c.usageMu.Unlock()
+ u := c.accumulatedUsage()
var usageMap map[string]TokenUsage
- if u.InputTokens > 0 || u.OutputTokens > 0 || u.CacheReadTokens > 0 || u.CacheWriteTokens > 0 {
+ if acpUsagePresent(u) {
model := effectiveModel
if model == "" {
model = "unknown"
diff --git a/server/pkg/agent/traecli_test.go b/server/pkg/agent/traecli_test.go
index af3a98f9b0..7a08b470ef 100644
--- a/server/pkg/agent/traecli_test.go
+++ b/server/pkg/agent/traecli_test.go
@@ -67,7 +67,7 @@ while IFS= read -r line; do
printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_new","update":{"sessionUpdate":"tool_call","toolCallId":"tc-1","name":"Shell","status":"pending","parameters":{"command":"echo hi"}}}}\n'
printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_new","update":{"sessionUpdate":"tool_call_update","toolCallId":"tc-1","status":"completed","name":"Shell","output":"hi\\n"}}}\n'
printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_new","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":"pong"}}}}\n'
- printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn"}}\n' "$id"
+ printf '{"jsonrpc":"2.0","id":%s,"result":{"stopReason":"end_turn","usage":{"inputTokens":17,"outputTokens":5,"cachedReadTokens":3,"cachedWriteTokens":2,"costUsdTicks":900}}}\n' "$id"
if [ -n "$TRAECLI_LATE_CHUNK" ]; then
sleep 0.05
printf '{"jsonrpc":"2.0","method":"session/update","params":{"sessionId":"ses_new","update":{"sessionUpdate":"agent_message_chunk","content":{"type":"text","text":" tail"}}}}\n'
@@ -115,6 +115,9 @@ func TestTraecliBackendStreamsAndCompletes(t *testing.T) {
if result.SessionID != "ses_new" {
t.Fatalf("session id = %q, want ses_new", result.SessionID)
}
+ if usage := result.Usage["unknown"]; usage != (TokenUsage{InputTokens: 17, OutputTokens: 5, CacheReadTokens: 3, CacheWriteTokens: 2, CostUSDTicks: 900}) {
+ t.Fatalf("usage = %+v, want all prompt-result fields", usage)
+ }
// The agent_message_chunk must surface as MessageText; the tool_call must
// surface as a MessageToolUse normalized to a canonical tool name.
var sawText, sawToolUse bool