Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import { z } from 'zod'
3import { EventType, defineAgent, toolDefinition } from '@tanstack/ai'
4import { memoryLogStore, memoryPersistence } from '@tanstack/ai-persistence'
5import { createHarnessHost, defineHarness, logIdOf } from '../src'
6import { emptySharedLogState, foldLogEntry, sessionOf } from '../src/log'
7import { addUsage, emptyUsage } from '../src/usage'
8import { mockAdapter, text, toolCall } from './helpers'
9import type { StreamChunk } from '@tanstack/ai'
10import type { SessionEvent } from '../src'
11import type { Reply } from './helpers'
12
13const THREAD = 't1'
14/** The id of the log of `THREAD` in the store. */
15const LOG = logIdOf({ logId: THREAD })
16const alice = { id: 'alice' }
17const bob = { id: 'bob' }
18
19/** `chunks` with this usage on RUN_FINISHED, as a provider reports it. */
20function withUsage(
21 chunks: Array<StreamChunk>,
22 usage: { prompt: number; completion: number; cost?: number },
23): Array<StreamChunk> {
24 return chunks.map((chunk) =>
25 chunk.type === EventType.RUN_FINISHED
26 ? {
27 ...chunk,
28 usage: {
29 promptTokens: usage.prompt,
30 completionTokens: usage.completion,
31 totalTokens: usage.prompt + usage.completion,
32 ...(usage.cost !== undefined ? { cost: usage.cost } : {}),
33 },
34 }
35 : chunk,
36 )
37}
38
39/** A mock model with its own model id, so totals can be told apart. */
40function model(id: string, replies: Array<Reply>) {
41 const { adapter, calls } = mockAdapter(replies)
42 return { adapter: { ...adapter, model: id }, calls }
43}
44
45const lookup = toolDefinition({
46 name: 'lookup',
47 description: 'Look something up',
48 inputSchema: z.object({}),
49}).server(async () => ({ found: true }))
50
51/** A model call that uses `lookup`, then one that answers. */
52const lookupThenAnswer = (cost?: [number, number]): Array<Reply> => [
53 () =>
54 withUsage(toolCall('lookup', {}), {
55 prompt: 10,
56 completion: 5,
57 ...(cost ? { cost: cost[0] } : {}),
58 }),
59 () =>
60 withUsage(text('done'), {
61 prompt: 20,
62 completion: 10,
63 ...(cost ? { cost: cost[1] } : {}),
64 }),
65]
66
67const usageEvents = (events: Array<SessionEvent>) =>
68 events.filter(
69 (entry) =>
70 entry.event.type === EventType.CUSTOM &&
71 entry.event.name === 'harness.usage',
72 )
73
74async function readEvents(session: {
75 events: (options?: { signal?: AbortSignal }) => AsyncIterable<SessionEvent>
76}) {
77 const seen: Array<SessionEvent> = []
78 const reader = new AbortController()
79 const done = (async () => {
80 for await (const entry of session.events({ signal: reader.signal }))
81 seen.push(entry)
82 })()
83 return {
84 seen,
85 stop: async () => {
86 reader.abort()
87 await done.catch(() => {})
88 },
89 }
90}
91
92describe('session usage totals', () => {
93 it('adds every model call of a turn, by model and by sender, with the reported cost', async () => {
94 const main = model('main-model', lookupThenAnswer([0.01, 0.02]))
95 const host = createHarnessHost({ persistence: memoryPersistence() })
96 const session = await host.open(
97 defineHarness({
98 name: 'test/usage',
99 adapter: main.adapter,
100 tools: [lookup],
101 }),
102 {
103 threadId: THREAD,
104 user: alice,
105 },
106 )
107 const events = await readEvents(session)
108
109 const turn = session.send('Find it.')
110 await turn
111
112 const usage = session.usage()
113 expect(usage.total).toMatchObject({
114 calls: 2,
115 promptTokens: 30,
116 completionTokens: 15,
117 totalTokens: 45,
118 })
119 expect(usage.total.cost).toBeCloseTo(0.03)
120 expect(Object.keys(usage.byModel)).toEqual(['mock/main-model'])
121 expect(usage.byModel['mock/main-model']).toEqual(usage.total)
122 expect(usage.bySender).toEqual({ alice: usage.total })
123 expect(session.snapshot().usage).toEqual(usage)
124
125 await events.stop()
126 const published = usageEvents(events.seen)
127 expect(published).toHaveLength(2)
128 expect(published.every((entry) => entry.operationId === turn.id)).toBe(true)
129 expect(published.at(-1)?.event).toMatchObject({
130 value: {
131 model: 'mock/main-model',
132 sender: 'alice',
133 usage: { promptTokens: 20, completionTokens: 10, totalTokens: 30 },
134 total: { calls: 2, totalTokens: 45 },
135 },
136 })
137 await host.close()
138 })
139
140 it('keeps one total for each sender, and has no cost when no call reported one', async () => {
141 const main = model('main-model', [
142 () => withUsage(text('for alice'), { prompt: 4, completion: 1 }),
143 () => withUsage(text('for bob'), { prompt: 8, completion: 2 }),
144 ])
145 const host = createHarnessHost({ persistence: memoryPersistence() })
146 const session = await host.open(
147 defineHarness({
148 name: 'test/usage-senders',
149 adapter: main.adapter,
150 }),
151 {
152 threadId: THREAD,
153 user: alice,
154 },
155 )
156
157 await session.send('Hi.')
158 await session.send('Hello.', { user: bob })
159
160 const usage = session.usage()
161 expect(usage.total).toEqual({
162 calls: 2,
163 promptTokens: 12,
164 completionTokens: 3,
165 totalTokens: 15,
166 cachedTokens: 0,
167 cacheWriteTokens: 0,
168 })
169 expect(usage.bySender.alice?.totalTokens).toBe(5)
170 expect(usage.bySender.bob?.totalTokens).toBe(10)
171 await host.close()
172 })
173
174 it('adds the model calls of a subagent and of a background agent', async () => {
175 const helperModel = model('helper-model', [
176 () => withUsage(text('helped'), { prompt: 5, completion: 2 }),
177 ])
178 const workerModel = model('worker-model', [
179 () => withUsage(text('worked'), { prompt: 6, completion: 3 }),
180 ])
181 const lead = model('lead-model', [
182 () => withUsage(toolCall('helper', {}), { prompt: 1, completion: 1 }),
183 () => withUsage(text('lead done'), { prompt: 2, completion: 1 }),
184 ])
185 const helper = defineAgent({
186 name: 'helper',
187 description: 'Helps',
188 run: (ctx) => ctx.chat({ adapter: helperModel.adapter }),
189 })
190 const worker = defineAgent({
191 name: 'worker',
192 description: 'Works',
193 run: (ctx) => ctx.chat({ adapter: workerModel.adapter }),
194 })
195 const host = createHarnessHost({ persistence: memoryPersistence() })
196 const session = await host.open(
197 defineHarness({
198 name: 'test/usage-agents',
199 adapter: lead.adapter,
200 subagents: { agents: [helper] },
201 agents: [worker],
202 }),
203 {
204 threadId: THREAD,
205 user: alice,
206 },
207 )
208
209 expect((await session.send('Get help.')).text).toBe('lead done')
210 expect(await session.agent('worker')?.start()).toBe('worked')
211
212 const usage = session.usage()
213 expect(usage.byModel['mock/lead-model']?.totalTokens).toBe(5)
214 expect(usage.byModel['mock/helper-model']?.totalTokens).toBe(7)
215 expect(usage.byModel['mock/worker-model']?.totalTokens).toBe(9)
216 expect(usage.total).toMatchObject({ calls: 4, totalTokens: 21 })
217 expect(usage.bySender.alice?.totalTokens).toBe(21)
218 await host.close()
219 })
220})
221
222describe('usage totals after a restart', () => {
223 it('keeps the totals in the log', async () => {
224 const { metadata } = memoryPersistence().stores
225 const log = memoryLogStore()
226 const persistence = { stores: { log, metadata } }
227 const first = model('main-model', lookupThenAnswer([0.01, 0.02]))
228 const harness = (adapter: typeof first.adapter) =>
229 defineHarness({ name: 'test/usage-durable', adapter, tools: [lookup] })
230 const host = createHarnessHost({ persistence })
231 const session = await host.open(harness(first.adapter), {
232 threadId: THREAD,
233 user: alice,
234 })
235 await session.send('Find it.')
236 const before = session.usage()
237 await host.close()
238
239 const records = (await log.read({ logId: LOG })).filter(
240 (entry) => entry.record.type === 'harness.usage',
241 )
242 expect(records).toHaveLength(2)
243
244 const next = createHarnessHost({ persistence })
245 const reopened = await next.open(harness(model('main-model', []).adapter), {
246 threadId: THREAD,
247 user: alice,
248 })
249 expect(reopened.usage()).toEqual(before)
250 expect(reopened.usage().total.totalTokens).toBe(45)
251 await next.close()
252 })
253})
254
255describe('usage of each run', () => {
256 it('names the run of each call, adds a child call to its parent, and drops the sum when the run ends', async () => {
257 const workerModel = model('worker-model', [
258 () => withUsage(text('worked'), { prompt: 6, completion: 3 }),
259 ])
260 const worker = defineAgent({
261 name: 'worker',
262 description: 'Works',
263 run: (ctx) => ctx.chat({ adapter: workerModel.adapter }),
264 })
265 const lead = defineAgent({
266 name: 'lead',
267 description: 'Runs the worker',
268 run: async (ctx) => ctx.harness!.agents.run(worker),
269 })
270 const { metadata } = memoryPersistence().stores
271 const log = memoryLogStore()
272 const host = createHarnessHost({
273 persistence: { stores: { log, metadata } },
274 })
275 const session = await host.open(
276 defineHarness({
277 name: 'test/usage-runs',
278 adapter: model('main-model', []).adapter,
279 agents: [lead, worker],
280 }),
281 { threadId: THREAD, user: alice },
282 )
283
284 const run = session.agents.lead.start(undefined, { addResultNote: false })
285 expect(await run).toBe('worked')
286 const workerRun = session
287 .agentRuns()
288 .find((item) => item.agent === 'worker')
289
290 const entries = await log.read({ logId: LOG })
291 const usage = entries.filter(
292 (entry) => entry.record.type === 'harness.usage',
293 )
294 expect(usage.map((entry) => entry.record.runId)).toEqual([workerRun?.runId])
295 /** The run sums of the thread after the log up to `seq`. */
296 const sumsAt = (seq: number) => {
297 const state = emptySharedLogState()
298 for (const entry of entries) {
299 if (entry.seq <= seq) foldLogEntry(state, entry, { rootThread: THREAD })
300 }
301 return sessionOf(state, THREAD).runUsage
302 }
303 const afterCall = sumsAt(usage[0]?.seq ?? 0)
304 expect(afterCall.get(workerRun?.runId ?? '')?.totalTokens).toBe(9)
305 expect(afterCall.get(run.id)?.totalTokens).toBe(9)
306 expect(sumsAt(Infinity).size).toBe(0)
307 // The run record of each run keeps its final usage.
308 const finalUsage = (runId: string) =>
309 entries.find(
310 (entry) =>
311 entry.record.type === 'harness.run.update' &&
312 entry.record.runId === runId &&
313 isRecordWithUsage(entry.record.patch),
314 )?.record.patch
315 expect(finalUsage(run.id)).toMatchObject({ usage: { totalTokens: 9 } })
316 expect(finalUsage(workerRun?.runId ?? '')).toMatchObject({
317 usage: { totalTokens: 9 },
318 })
319 await host.close()
320 })
321})
322
323/** Is `value` a run record change that sets `usage`? */
324const isRecordWithUsage = (value: unknown) =>
325 typeof value === 'object' && value !== null && 'usage' in value
326
327describe('usage totals by source', () => {
328 const counts = (totalTokens: number) => ({
329 promptTokens: totalTokens,
330 completionTokens: 0,
331 totalTokens,
332 cachedTokens: 0,
333 cacheWriteTokens: 0,
334 })
335
336 it('adds a call with a source under it, and keeps a turn call out of bySource', () => {
337 const totals = emptyUsage()
338
339 addUsage(totals, { model: 'm', usage: counts(5) })
340 addUsage(totals, {
341 model: 'm',
342 source: 'plugin:tanstack/title',
343 label: 'title',
344 usage: counts(2),
345 })
346 addUsage(totals, {
347 model: 'm',
348 source: 'plugin:tanstack/title',
349 usage: counts(3),
350 })
351 addUsage(totals, {
352 model: 'm',
353 source: 'plugin:tanstack/goal',
354 usage: counts(4),
355 })
356
357 expect(totals.total).toMatchObject({ calls: 4, totalTokens: 14 })
358 expect(totals.bySource).toEqual({
359 'plugin:tanstack/title': expect.objectContaining({
360 calls: 2,
361 totalTokens: 5,
362 }),
363 'plugin:tanstack/goal': expect.objectContaining({
364 calls: 1,
365 totalTokens: 4,
366 }),
367 })
368 })
369})
370
371describe('usage totals of an odd key', () => {
372 it('keeps a sender with the id __proto__ as its own entry', () => {
373 const totals = emptyUsage()
374
375 addUsage(totals, {
376 model: 'm',
377 user: { id: '__proto__' },
378 usage: {
379 promptTokens: 1,
380 completionTokens: 2,
381 totalTokens: 3,
382 cachedTokens: 0,
383 cacheWriteTokens: 0,
384 },
385 })
386
387 expect(Object.keys(totals.bySender)).toEqual(['__proto__'])
388 expect(JSON.stringify(totals.bySender)).toBe(
389 JSON.stringify({ ['__proto__']: totals.total }),
390 )
391 expect(Object.hasOwn(Object.prototype, 'calls')).toBe(false)
392 })
393})