import type { Message, TurnEntry, Usage, UsageRecord } from './types.js'; /** * Fold one usage tally into a running total; optional fields are summed only when either side has them. * * `reported` sums **numeric values key-wise** and drops the rest: a total `service_tier` is meaningless * and a summed `latency_checkpoint` is nonsense, so non-numeric retained values stay per-call facts that * a consumer reads off the entries. Callers must fold only within ONE provider — `usageByProvider` does, * by grouping first — since the same key means different things under different protocols. */ export function addUsage(acc: Usage | undefined, next: Usage): Usage { const a = acc ?? { inputTokens: 0, outputTokens: 0 }; const add = (x: number | undefined, y: number | undefined): number | undefined => x === undefined && y === undefined ? undefined : (x ?? 0) + (y ?? 0); const cacheReadTokens = add(a.cacheReadTokens, next.cacheReadTokens); const cacheCreationTokens = add(a.cacheCreationTokens, next.cacheCreationTokens); const reported = addReported(a.reported, next.reported); return { inputTokens: a.inputTokens + next.inputTokens, outputTokens: a.outputTokens + next.outputTokens, ...(cacheReadTokens !== undefined ? { cacheReadTokens } : {}), ...(cacheCreationTokens !== undefined ? { cacheCreationTokens } : {}), ...(reported !== undefined ? { reported } : {}), }; } function addReported( a: Record | undefined, b: Record | undefined, ): Record | undefined { if (a === undefined) return b; if (b === undefined) return a; const out: Record = { ...a }; for (const [k, v] of Object.entries(b)) { const prev = out[k]; out[k] = typeof v === 'number' && typeof prev === 'number' ? prev + v : v; } return out; } /** * Everything a set of messages records about what happened — provider calls and the brackets around * them — in message order. * * Entries are anchored on turn heads and are self-describing (`site`, `traceId`), so this is a flat * read with no correlation to do: filter it for whatever question is being asked — one turn * (`traceId`), one tool call (`site`), one session (pass the lot) — and the same one fact set answers * "what did this tool cost", "what did this user cost" and "how long did that take". */ export function turnActivity(messages: Iterable): TurnEntry[] { const out: TurnEntry[] = []; for (const m of messages) { if (m.activity !== undefined) out.push(...m.activity); } return out; } /** The provider calls in a set of messages — `turnActivity` less the spans. */ export function usageEntries(messages: Iterable): UsageRecord[] { return turnActivity(messages).filter((e): e is { kind: 'call' } & UsageRecord => e.kind === 'call'); } /** * Aggregate the token accounting on a set of messages, keyed by the provider billed. Pass a single * turn's messages (filtered by `traceId`) for a per-turn breakdown, or a whole session for its total. * * Note what this deliberately does NOT do: sum a provider's `reported` fields across providers. The * same key means different things under different protocols (`prompt_tokens` includes cache hits, * `input_tokens` does not), so only the normalised counters are comparable across a mixed turn. */ export function usageByProvider(messages: Iterable): Map { const out = new Map(); for (const r of usageEntries(messages)) { out.set(r.provider, addUsage(out.get(r.provider), r.usage)); } return out; }