Open History to see the last commit
1import type { TokenUsage } from '@tanstack/ai'
2
3/** The token counts of some model calls, and their cost when known. */
4export interface UsageCounts {
5 /** How many model calls reported usage. */
6 calls: number
7 promptTokens: number
8 completionTokens: number
9 totalTokens: number
10 /** Prompt tokens read from the cache of the provider. */
11 cachedTokens: number
12 /** Prompt tokens written to the cache of the provider. */
13 cacheWriteTokens: number
14 /**
15 * The sum of the cost that the providers reported, in their currency (USD
16 * for most). Set only when at least one call reported a cost.
17 */
18 cost?: number
19}
20
21/**
22 * The usage of a thread: every model call of its turns, their subagents, its
23 * agent runs, the model calls of plugins (`ctx.model.chat`), of the router,
24 * and of a transfer summary. `bySender` has the calls of a known sender
25 * only, keyed by the user id, and `bySource` has only the calls that
26 * have a source, so their sums can be less than `total`.
27 */
28export interface SessionUsage {
29 total: UsageCounts
30 /** By `provider/model`, for example `anthropic/claude-sonnet-5-5`. */
31 byModel: Record<string, UsageCounts>
32 /** By user id. */
33 bySender: Record<string, UsageCounts>
34 /**
35 * By the source of a call: `plugin:<name>` (for example
36 * `plugin:tanstack/title`), `router`, or `transfer`. Turns and agent runs
37 * have no source, so they are not in it.
38 */
39 bySource: Record<string, UsageCounts>
40}
41
42/** One model call, as the log keeps it. A type, so it is a log record field set. */
43export type UsageCall = {
44 model: string
45 user?: { id: string; name?: string; tenantId?: string }
46 /**
47 * The run that made the call: a turn, or an agent run. Its usage also
48 * counts for each run above it in the run tree.
49 */
50 runId?: string
51 /**
52 * Who made a call that is not a turn or an agent run: `plugin:<name>`
53 * for `ctx.model.chat`, `router` for `model.chat` of `routing.router`,
54 * and `transfer` for the summary of `host.transfer`.
55 */
56 source?: string
57 /** The `label` of the call, for example `judge`, or `summary` for a transfer. */
58 label?: string
59 usage: Omit<UsageCounts, 'calls'>
60}
61
62export const emptyCounts = (): UsageCounts => ({
63 calls: 0,
64 promptTokens: 0,
65 completionTokens: 0,
66 totalTokens: 0,
67 cachedTokens: 0,
68 cacheWriteTokens: 0,
69})
70
71export const emptyUsage = (): SessionUsage => ({
72 total: emptyCounts(),
73 byModel: {},
74 bySender: {},
75 bySource: {},
76})
77
78/** The counts that one call adds, from what the provider reported. */
79export function callUsage(usage: TokenUsage): UsageCall['usage'] {
80 return {
81 promptTokens: usage.promptTokens,
82 completionTokens: usage.completionTokens,
83 totalTokens: usage.totalTokens,
84 cachedTokens: usage.promptTokensDetails?.cachedTokens ?? 0,
85 cacheWriteTokens: usage.promptTokensDetails?.cacheWriteTokens ?? 0,
86 ...(typeof usage.cost === 'number' ? { cost: usage.cost } : {}),
87 }
88}
89
90/** Add the counts of one call to `counts`, in place. */
91export function addCounts(counts: UsageCounts, usage: UsageCall['usage']) {
92 counts.calls += 1
93 counts.promptTokens += usage.promptTokens
94 counts.completionTokens += usage.completionTokens
95 counts.totalTokens += usage.totalTokens
96 counts.cachedTokens += usage.cachedTokens
97 counts.cacheWriteTokens += usage.cacheWriteTokens
98 if (usage.cost !== undefined) counts.cost = (counts.cost ?? 0) + usage.cost
99}
100
101/**
102 * The counts under `key`, added when missing. An own property, so a key like
103 * `__proto__` (a user id) never reaches the prototype.
104 */
105function countsOf(map: Record<string, UsageCounts>, key: string) {
106 if (!Object.hasOwn(map, key)) {
107 Object.defineProperty(map, key, {
108 value: emptyCounts(),
109 enumerable: true,
110 writable: true,
111 configurable: true,
112 })
113 }
114 return map[key] as UsageCounts
115}
116
117/** Add one call to `totals`, in place. */
118export function addUsage(totals: SessionUsage, call: UsageCall) {
119 addCounts(totals.total, call.usage)
120 addCounts(countsOf(totals.byModel, call.model), call.usage)
121 if (call.user) {
122 addCounts(countsOf(totals.bySender, call.user.id), call.usage)
123 }
124 if (call.source !== undefined) {
125 addCounts(countsOf(totals.bySource, call.source), call.usage)
126 }
127}
128
129/** Is `value` usage totals that the harness wrote? */
130export function isSessionUsage(value: unknown): value is SessionUsage {
131 return (
132 typeof value === 'object' &&
133 value !== null &&
134 'total' in value &&
135 'byModel' in value &&
136 'bySender' in value &&
137 'bySource' in value
138 )
139}