Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

recording.ts

614 lines15.9 KB

1import * as fs from 'node:fs/promises'
2import * as path from 'node:path'
3import { EventType } from '@tanstack/ai'
4import { aiEventClient as baseAiEventClient } from '@tanstack/ai-event-client'
5import type { AIDevtoolsEventMap } from '@tanstack/ai-event-client'
6import type { AdapterYieldChunk, TokenUsage } from '@tanstack/ai'
7​
8/**
9 * Recording data structure matching the trace format produced by
10 * `wrapAdapterForRecording` in `routes/api.chat.ts` and consumed by the stream
11 * debugger. Each `chunk` is a `AdapterYieldChunk` (an AG-UI protocol event).
12 */
13export interface RecordedToolCall {
14 id: string
15 name: string
16 arguments: string
17 result?: unknown
19​
20export interface ChunkRecording {
21 version: '1.0'
22 timestamp: number
23 model: string
24 provider: string
25 chunks: Array<{
26 chunk: AdapterYieldChunk
27 timestamp: number
28 index: number
29 }>
30 result?: {
31 content: string
32 toolCalls: Array<RecordedToolCall>
33 finishReason: string | null
34 }
36​
37type FinishReason = 'stop' | 'length' | 'content_filter' | 'tool_calls' | null
38​
39const normalizeFinishReason = (finishReason: string | null): FinishReason => {
40 if (
41 finishReason === 'stop' ||
42 finishReason === 'length' ||
43 finishReason === 'content_filter' ||
44 finishReason === 'tool_calls'
45 ) {
46 return finishReason
47 }
48 return 'stop'
50​
51// ---------------------------------------------------------------------------
52// AG-UI event constructors.
53//
54// The devtools event stream is already decomposed into per-kind chunks
55// (`text:chunk:content`, `text:chunk:tool-call`, ...). We reconstruct the
56// equivalent AG-UI `AdapterYieldChunk`s — including the START/END boundary events the
57// StreamProcessor needs to open and close messages and tool calls — so the
58// recorded trace replays the same way an adapter-recorded one (from
59// `wrapAdapterForRecording`) does.
60// ---------------------------------------------------------------------------
61​
62const textMessageStart = (
63 messageId: string,
64 model: string,
65 timestamp: number,
66): AdapterYieldChunk => ({
67 type: EventType.TEXT_MESSAGE_START,
68 messageId,
69 role: 'assistant',
70 model,
71 timestamp,
72})
73​
74const textMessageContent = (
75 messageId: string,
76 content: string,
77 delta: string | undefined,
78 model: string,
79 timestamp: number,
80): AdapterYieldChunk => ({
81 type: EventType.TEXT_MESSAGE_CONTENT,
82 messageId,
83 delta: delta ?? '',
84 content,
85 model,
86 timestamp,
87})
88​
89const textMessageEnd = (
90 messageId: string,
91 model: string,
92 timestamp: number,
93): AdapterYieldChunk => ({
94 type: EventType.TEXT_MESSAGE_END,
95 messageId,
96 model,
97 timestamp,
98})
99​
100const toolCallStart = (
101 toolCallId: string,
102 toolName: string,
103 index: number,
104 model: string,
105 timestamp: number,
106): AdapterYieldChunk => ({
107 type: EventType.TOOL_CALL_START,
108 toolCallId,
109 toolCallName: toolName,
110 index,
111 model,
112 timestamp,
113})
114​
115const toolCallArgs = (
116 toolCallId: string,
117 delta: string,
118 args: string,
119 model: string,
120 timestamp: number,
121): AdapterYieldChunk => ({
122 type: EventType.TOOL_CALL_ARGS,
123 toolCallId,
124 delta,
125 args,
126 model,
127 timestamp,
128})
129​
130const toolCallResult = (
131 messageId: string,
132 toolCallId: string,
133 content: string,
134 model: string,
135 timestamp: number,
136): AdapterYieldChunk => ({
137 type: EventType.TOOL_CALL_RESULT,
138 messageId,
139 toolCallId,
140 content,
141 role: 'tool',
142 model,
143 timestamp,
144})
145​
146const runFinished = (
147 runId: string,
148 threadId: string,
149 finishReason: string | null,
150 usage: TokenUsage | undefined,
151 model: string,
152 timestamp: number,
153): AdapterYieldChunk => ({
154 type: EventType.RUN_FINISHED,
155 runId,
156 threadId,
157 finishReason: normalizeFinishReason(finishReason),
158 usage,
159 model,
160 timestamp,
161})
162​
163const runError = (
164 runId: string,
165 threadId: string,
166 message: string,
167 model: string,
168 timestamp: number,
169): AdapterYieldChunk => ({
170 type: EventType.RUN_ERROR,
171 runId,
172 threadId,
173 message,
174 model,
175 timestamp,
176})
177​
178const reasoningContent = (
179 messageId: string,
180 delta: string | undefined,
181 model: string,
182 timestamp: number,
183): AdapterYieldChunk => ({
184 type: EventType.REASONING_MESSAGE_CONTENT,
185 messageId,
186 delta: delta ?? '',
187 model,
188 timestamp,
189})
190​
191/**
192 * Creates an event-based recording that subscribes to aiEventClient events
193 * and saves recordings to a file when a stream completes.
194 *
195 * @param filePath - Path where the recording will be saved
196 * @param traceId - Optional trace ID to filter events (if not provided, records all streams)
197 * @returns Object with stop() method to unsubscribe from events
198 *
199 * @example
200 * const recording = createEventRecording('tmp/recording.json', 'trace_123')
201 * // Recording automatically starts listening to events for this traceId
202 * // Call recording.stop() when done to unsubscribe
203 */
204export function createEventRecording(
205 filePath: string,
206 traceId?: string,
207): {
208 stop: () => void
209 getStreamId: () => string | undefined
210} {
211 type RecordedChunk = {
212 chunk: AdapterYieldChunk
213 timestamp: number
214 index: number
215 }
216​
217 // Per-stream recording state, including the AG-UI message/tool ids and the
218 // boundary flags used to emit START/END events exactly once.
219 interface StreamState {
220 streamId: string
221 requestId: string
222 model: string
223 provider: string
224 runId: string
225 threadId: string
226 messageId: string
227 reasoningId: string
228 messageStarted: boolean
229 startedToolCalls: Set<string>
230 chunks: Array<RecordedChunk>
231 accumulatedContent: string
232 toolCalls: Map<string, RecordedToolCall>
233 finishReason: string | null
234 }
235​
236 const activeStreams = new Map<string, StreamState>()
237​
238 // Track which streamId belongs to this recording (if traceId is provided)
239 let recordingStreamId: string | undefined
240​
241 let chunkIndex = 0
242​
243 const pushChunk = (
244 stream: StreamState,
245 chunk: AdapterYieldChunk,
246 timestamp: number,
247 ): void => {
248 stream.chunks.push({ chunk, timestamp, index: chunkIndex++ })
249 }
250​
251 // Ensures a TEXT_MESSAGE_START has been emitted before any content/end.
252 const ensureMessageStarted = (
253 stream: StreamState,
254 timestamp: number,
255 ): void => {
256 if (stream.messageStarted) return
257 stream.messageStarted = true
258 pushChunk(
259 stream,
260 textMessageStart(stream.messageId, stream.model, timestamp),
261 timestamp,
262 )
263 }
264​
265 type DevtoolsEventHandler<TEventName extends keyof AIDevtoolsEventMap> =
266 (event: { payload: AIDevtoolsEventMap[TEventName] }) => void
267​
268 type DevtoolsEventClient = {
269 on: <TEventName extends keyof AIDevtoolsEventMap>(
270 eventName: TEventName,
271 handler: DevtoolsEventHandler<TEventName>,
272 options?: { withEventTarget?: boolean },
273 ) => () => void
274 }
275​
276 const aiEventClient = baseAiEventClient as DevtoolsEventClient
277​
278 // Subscribe to text:request:started to initialize recording
279 const unsubscribeStarted = aiEventClient.on(
280 'text:request:started',
281 (event) => {
282 const { streamId, model, provider, requestId, options, modelOptions } =
283 event.payload
284​
285 activeStreams.set(streamId, {
286 streamId,
287 requestId,
288 model,
289 provider,
290 runId: requestId || `run-${streamId}`,
291 threadId: `thread-${streamId}`,
292 messageId: `msg-${streamId}`,
293 reasoningId: `reasoning-${streamId}`,
294 messageStarted: false,
295 startedToolCalls: new Set<string>(),
296 chunks: [],
297 accumulatedContent: '',
298 toolCalls: new Map<string, RecordedToolCall>(),
299 finishReason: null,
300 })
301​
302 const optionsTraceId = options?.traceId
303 const modelOptionsTraceId = modelOptions?.traceId
304​
305 const eventTraceId = optionsTraceId || modelOptionsTraceId
306​
307 if (traceId && eventTraceId === traceId) {
308 recordingStreamId = streamId
309 } else if (!traceId) {
310 recordingStreamId = streamId
311 }
312 },
313 { withEventTarget: false },
314 )
315​
316 // Helper to check if we should record this stream
317 const shouldRecord = (streamId: string): boolean => {
318 if (!traceId) return true // Record all if no filter
319 return streamId === recordingStreamId
320 }
321​
322 // Subscribe to content chunks
323 const unsubscribeContent = aiEventClient.on(
324 'text:chunk:content',
325 (event) => {
326 const { streamId, content, delta, timestamp, model } = event.payload
327 if (!shouldRecord(streamId)) return
328 const stream = activeStreams.get(streamId)
329 if (stream) {
330 stream.accumulatedContent = content
331 const resolvedModel = model ?? stream.model
332 ensureMessageStarted(stream, timestamp)
333 pushChunk(
334 stream,
335 textMessageContent(
336 stream.messageId,
337 content,
338 delta,
339 resolvedModel,
340 timestamp,
341 ),
342 timestamp,
343 )
344 }
345 },
346 { withEventTarget: false },
347 )
348​
349 // Subscribe to tool call chunks
350 const unsubscribeToolCall = aiEventClient.on(
351 'text:chunk:tool-call',
352 (event) => {
353 const {
354 streamId,
355 toolCallId,
356 toolName,
357 index,
358 arguments: args,
359 timestamp,
360 model,
361 } = event.payload
362 if (!shouldRecord(streamId)) return
363 const stream = activeStreams.get(streamId)
364 if (stream) {
365 const resolvedModel = model ?? stream.model
366 // Emit a TOOL_CALL_START the first time we see this tool call.
367 if (!stream.startedToolCalls.has(toolCallId)) {
368 stream.startedToolCalls.add(toolCallId)
369 pushChunk(
370 stream,
371 toolCallStart(
372 toolCallId,
373 toolName,
374 index,
375 resolvedModel,
376 timestamp,
377 ),
378 timestamp,
379 )
380 }
381 pushChunk(
382 stream,
383 toolCallArgs(toolCallId, args, args, resolvedModel, timestamp),
384 timestamp,
385 )
386 // Store tool call info for final recording (update arguments as they stream)
387 const existing = stream.toolCalls.get(toolCallId)
388 if (existing) {
389 existing.arguments = args
390 } else {
391 stream.toolCalls.set(toolCallId, {
392 id: toolCallId,
393 name: toolName,
394 arguments: args,
395 result: undefined,
396 })
397 }
398 }
399 },
400 { withEventTarget: false },
401 )
402​
403 // Subscribe to tool result chunks
404 const unsubscribeToolResult = aiEventClient.on(
405 'text:chunk:tool-result',
406 (event) => {
407 const { streamId, toolCallId, result, timestamp, model } = event.payload
408 if (!shouldRecord(streamId)) return
409 const stream = activeStreams.get(streamId)
410 if (stream) {
411 const resolvedModel = model ?? stream.model
412 pushChunk(
413 stream,
414 toolCallResult(
415 stream.messageId,
416 toolCallId,
417 result,
418 resolvedModel,
419 timestamp,
420 ),
421 timestamp,
422 )
423 }
424 },
425 { withEventTarget: false },
426 )
427​
428 // Subscribe to done chunks
429 const unsubscribeDone = aiEventClient.on(
430 'text:chunk:done',
431 (event) => {
432 const { streamId, finishReason, usage, timestamp, model } = event.payload
433 if (!shouldRecord(streamId)) return
434 const stream = activeStreams.get(streamId)
435 if (stream) {
436 stream.finishReason = finishReason || null
437 const resolvedModel = model ?? stream.model
438 // Close the open text message (if any) before finishing the run.
439 if (stream.messageStarted) {
440 pushChunk(
441 stream,
442 textMessageEnd(stream.messageId, resolvedModel, timestamp),
443 timestamp,
444 )
445 stream.messageStarted = false
446 }
447 pushChunk(
448 stream,
449 runFinished(
450 stream.runId,
451 stream.threadId,
452 finishReason,
453 usage,
454 resolvedModel,
455 timestamp,
456 ),
457 timestamp,
458 )
459 }
460 },
461 { withEventTarget: false },
462 )
463​
464 // Subscribe to error chunks
465 const unsubscribeError = aiEventClient.on(
466 'text:chunk:error',
467 (event) => {
468 const { streamId, error, timestamp, model } = event.payload
469 if (!shouldRecord(streamId)) return
470 const stream = activeStreams.get(streamId)
471 if (stream) {
472 const resolvedModel = model ?? stream.model
473 pushChunk(
474 stream,
475 runError(
476 stream.runId,
477 stream.threadId,
478 error,
479 resolvedModel,
480 timestamp,
481 ),
482 timestamp,
483 )
484 }
485 },
486 { withEventTarget: false },
487 )
488​
489 // Subscribe to thinking chunks
490 const unsubscribeThinking = aiEventClient.on(
491 'text:chunk:thinking',
492 (event) => {
493 const { streamId, delta, timestamp, model } = event.payload
494 if (!shouldRecord(streamId)) return
495 const stream = activeStreams.get(streamId)
496 if (stream) {
497 const resolvedModel = model ?? stream.model
498 pushChunk(
499 stream,
500 reasoningContent(stream.reasoningId, delta, resolvedModel, timestamp),
501 timestamp,
502 )
503 }
504 },
505 { withEventTarget: false },
506 )
507​
508 // Subscribe to text:request:completed to get final content + finish reason
509 const unsubscribeChatCompleted = aiEventClient.on(
510 'text:request:completed',
511 (event) => {
512 const { streamId, content, finishReason } = event.payload
513 if (!shouldRecord(streamId)) return
514 const stream = activeStreams.get(streamId)
515 if (stream) {
516 stream.accumulatedContent = content
517 stream.finishReason = finishReason || null
518 }
519 },
520 { withEventTarget: false },
521 )
522​
523 // Subscribe to tools:call:completed to update tool call results
524 const unsubscribeToolCompleted = aiEventClient.on(
525 'tools:call:completed',
526 (event) => {
527 const { streamId, toolCallId, toolName, result } = event.payload
528 if (!shouldRecord(streamId)) return
529 const stream = activeStreams.get(streamId)
530 if (stream) {
531 // Update tool call result (arguments should already be set from tool-call chunks)
532 const existing = stream.toolCalls.get(toolCallId)
533 if (existing) {
534 existing.result = result
535 } else {
536 // Fallback if we missed the tool-call chunk
537 stream.toolCalls.set(toolCallId, {
538 id: toolCallId,
539 name: toolName,
540 arguments: '',
541 result,
542 })
543 }
544 }
545 },
546 { withEventTarget: false },
547 )
548​
549 // Subscribe to text:request:completed to save recording
550 const unsubscribeStreamEnded = aiEventClient.on(
551 'text:request:completed',
552 async (event) => {
553 const { streamId } = event.payload
554 if (!shouldRecord(streamId)) return
555 const stream = activeStreams.get(streamId)
556 if (!stream) {
557 return
558 }
559​
560 try {
561 // Ensure directory exists
562 const dir = path.dirname(filePath)
563 await fs.mkdir(dir, { recursive: true })
564​
565 // Build recording object
566 const recording: ChunkRecording = {
567 version: '1.0',
568 timestamp: Date.now(),
569 model: stream.model,
570 provider: stream.provider,
571 chunks: stream.chunks,
572 result: {
573 content: stream.accumulatedContent,
574 toolCalls: Array.from(stream.toolCalls.values()),
575 finishReason: stream.finishReason,
576 },
577 }
578​
579 // Write recording
580 await fs.writeFile(
581 filePath,
582 JSON.stringify(recording, null, 2),
583 'utf-8',
584 )
585​
586 console.log(`Recording saved to: ${filePath}`)
587​
588 // Clean up
589 activeStreams.delete(streamId)
590 } catch (error) {
591 console.error('Failed to save recording:', error)
592 }
593 },
594 { withEventTarget: false },
595 )
596​
597 // Return cleanup function
598 return {
599 stop: () => {
600 unsubscribeStarted()
601 unsubscribeContent()
602 unsubscribeToolCall()
603 unsubscribeToolResult()
604 unsubscribeDone()
605 unsubscribeError()
606 unsubscribeThinking()
607 unsubscribeChatCompleted()
608 unsubscribeToolCompleted()
609 unsubscribeStreamEnded()
610 activeStreams.clear()
611 },
612 getStreamId: () => recordingStreamId,
613 }