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

devtools-middleware.ts

621 lines18.0 KB

1import { aiEventClient } from './index.js'
2import type { TokenUsage } from './index.js'
3​
4// Local mirrors of @tanstack/ai middleware types — do not import from `@tanstack/ai`
5// here: during `@tanstack/ai`'s own build that resolves to `dist/*.d.ts` while the
6// engine compiles from `src/`, producing incompatible duplicate types.
7​
8interface DevtoolsModelMessage {
9 role: string
10 content: unknown
11 toolCalls?: unknown
13​
14type DevtoolsSystemPrompt = string | { content: string; metadata?: unknown }
15​
16interface DevtoolsSpecTokenUsage {
17 inputTokens?: number
18 outputTokens?: number
19 totalTokens?: number
20 reasoningTokens?: number
21 cachedInputTokens?: number
23​
24interface DevtoolsTextMessageContentChunk {
25 type: 'TEXT_MESSAGE_CONTENT'
26 delta: string
28interface DevtoolsToolCallStartChunk {
29 type: 'TOOL_CALL_START'
30 toolCallId: string
31 toolCallName: string
32 index?: number
34interface DevtoolsToolCallArgsChunk {
35 type: 'TOOL_CALL_ARGS'
36 toolCallId: string
37 delta: string
39interface DevtoolsToolCallEndChunk {
40 type: 'TOOL_CALL_END'
41 toolCallId: string
43interface DevtoolsToolCallResultChunk {
44 type: 'TOOL_CALL_RESULT'
45 toolCallId: string
46 content?: string
48interface DevtoolsRunFinishedChunk {
49 type: 'RUN_FINISHED'
50 finishReason?: 'stop' | 'length' | 'content_filter' | 'tool_calls' | null
51 usage?: Array<DevtoolsSpecTokenUsage> | TokenUsage
52 metadata?: {
53 tanstack?: {
54 finishReason?: 'stop' | 'length' | 'content_filter' | 'tool_calls' | null
55 usage?: Omit<
56 TokenUsage,
57 'promptTokens' | 'completionTokens' | 'totalTokens'
58 >
59 }
60 }
62interface DevtoolsRunErrorChunk {
63 type: 'RUN_ERROR'
64 message?: string
65 code?: string
67interface DevtoolsReasoningMessageContentChunk {
68 type: 'REASONING_MESSAGE_CONTENT'
69 delta: string
71type DevtoolsKnownChunk =
72 | DevtoolsTextMessageContentChunk
73 | DevtoolsToolCallStartChunk
74 | DevtoolsToolCallArgsChunk
75 | DevtoolsToolCallEndChunk
76 | DevtoolsToolCallResultChunk
77 | DevtoolsRunFinishedChunk
78 | DevtoolsRunErrorChunk
79 | DevtoolsReasoningMessageContentChunk
80​
81// The engine emits more chunk types than this middleware acts on
82// (TEXT_MESSAGE_START, MESSAGES_SNAPSHOT, REASONING_*, CUSTOM, etc.).
83// Spec events have no index signature. `unknown` is a supertype of every
84// AG-UI event, so this middleware stays assignable to ChatMiddleware.
85type DevtoolsStreamChunk = { type: string }
86​
87const KNOWN_CHUNK_TYPES: ReadonlySet<DevtoolsKnownChunk['type']> = new Set([
88 'TEXT_MESSAGE_CONTENT',
89 'TOOL_CALL_START',
90 'TOOL_CALL_ARGS',
91 'TOOL_CALL_END',
92 'TOOL_CALL_RESULT',
93 'RUN_FINISHED',
94 'RUN_ERROR',
95 'REASONING_MESSAGE_CONTENT',
96])
97​
98function isTypedChunk(chunk: unknown): chunk is DevtoolsStreamChunk {
99 return (
100 typeof chunk === 'object' &&
101 chunk !== null &&
102 'type' in chunk &&
103 typeof chunk.type === 'string'
104 )
106​
107function isKnownChunk(chunk: unknown): chunk is DevtoolsKnownChunk {
108 return (
109 isTypedChunk(chunk) &&
110 (KNOWN_CHUNK_TYPES as ReadonlySet<string>).has(chunk.type)
111 )
113​
114function chunkTanstack(chunk: DevtoolsRunFinishedChunk) {
115 const tanstack = chunk.metadata?.tanstack
116 if (tanstack == null || typeof tanstack !== 'object') return undefined
117 return tanstack
119​
120function definedDetails<T extends object>(value: T): T | undefined {
121 return Object.keys(value).length > 0 ? value : undefined
123​
124// Local copy of `@tanstack/ai`'s fromSpecTokenUsage. This package cannot
125// import `@tanstack/ai` (circular: the engine injects this middleware).
126function fromSpecTokenUsage(
127 usage: ReadonlyArray<DevtoolsSpecTokenUsage> | undefined,
128 leftover?: Omit<
129 TokenUsage,
130 'promptTokens' | 'completionTokens' | 'totalTokens'
131 >,
132): TokenUsage | undefined {
133 const spec = usage?.[0]
134 if (spec == null && leftover == null) {
135 return undefined
136 }
137​
138 const {
139 promptTokensDetails: leftoverPromptDetails,
140 completionTokensDetails: leftoverCompletionDetails,
141 ...leftoverRest
142 } = leftover ?? {}
143​
144 const promptTokensDetails = definedDetails({
145 ...(spec?.cachedInputTokens !== undefined
146 ? { cachedTokens: spec.cachedInputTokens }
147 : {}),
148 ...leftoverPromptDetails,
149 })
150 const completionTokensDetails = definedDetails({
151 ...(spec?.reasoningTokens !== undefined
152 ? { reasoningTokens: spec.reasoningTokens }
153 : {}),
154 ...leftoverCompletionDetails,
155 })
156​
157 return {
158 promptTokens: spec?.inputTokens ?? 0,
159 completionTokens: spec?.outputTokens ?? 0,
160 totalTokens: spec?.totalTokens ?? 0,
161 ...leftoverRest,
162 ...(promptTokensDetails !== undefined ? { promptTokensDetails } : {}),
163 ...(completionTokensDetails !== undefined
164 ? { completionTokensDetails }
165 : {}),
166 }
168​
169interface DevtoolsMiddlewareContext {
170 requestId: string
171 streamId: string
172 runId: string
173 threadId: string
174 provider: string
175 model: string
176 source: 'client' | 'server'
177 systemPrompts: ReadonlyArray<DevtoolsSystemPrompt>
178 toolNames?: Array<string>
179 options?: Record<string, unknown>
180 modelOptions?: Record<string, unknown>
181 messageCount: number
182 hasTools: boolean
183 streaming: boolean
184 messages: ReadonlyArray<DevtoolsModelMessage>
185 createId: (prefix: string) => string
187​
188interface DevtoolsIterationInfo {
189 iteration: number
190 messageId: string
192​
193interface DevtoolsToolPhaseCompleteInfo {
194 toolCalls: Array<unknown>
195 needsApproval: Array<{
196 toolCallId: string
197 toolName: string
198 input: unknown
199 approvalId: string
200 }>
201 needsClientExecution: Array<{
202 toolCallId: string
203 toolName: string
204 input: unknown
205 }>
206 results: Array<{
207 toolCallId: string
208 toolName: string
209 result: unknown
210 duration?: number
211 }>
213​
214interface DevtoolsFinishInfo {
215 content: string
216 finishReason: string | null
217 duration: number
218 usage?: {
219 promptTokens: number
220 completionTokens: number
221 totalTokens: number
222 }
224​
225// Observation-only middleware returned by {@link devtoolsMiddleware}.
226// Structurally compatible with `ChatMiddleware` from `@tanstack/ai`.
227export interface DevtoolsChatMiddleware {
228 name?: string
229 onStart?: (ctx: DevtoolsMiddlewareContext) => void | Promise<void>
230 onIteration?: (
231 ctx: DevtoolsMiddlewareContext,
232 info: DevtoolsIterationInfo,
233 ) => void | Promise<void>
234 onChunk?: (
235 ctx: DevtoolsMiddlewareContext,
236 chunk: unknown,
237 ) => void | Promise<void>
238 onToolPhaseComplete?: (
239 ctx: DevtoolsMiddlewareContext,
240 info: DevtoolsToolPhaseCompleteInfo,
241 ) => void | Promise<void>
242 onFinish?: (
243 ctx: DevtoolsMiddlewareContext,
244 info: DevtoolsFinishInfo,
245 ) => void | Promise<void>
247​
248// Wrap an emit so a misbehaving subscriber cannot bubble into the host chat
249// engine. Instrumentation must never break the host app.
250const safeEmit: typeof aiEventClient.emit = (...args) => {
251 try {
252 aiEventClient.emit(...args)
253 } catch (error) {
254 console.error(
255 `[ai-devtools] subscriber threw while handling "${String(args[0])}" event`,
256 error,
257 )
258 }
260​
261function buildEventContext(ctx: DevtoolsMiddlewareContext) {
262 return {
263 requestId: ctx.requestId,
264 streamId: ctx.streamId,
265 runId: ctx.runId,
266 threadId: ctx.threadId,
267 provider: ctx.provider,
268 model: ctx.model,
269 clientId: ctx.threadId,
270 source: ctx.source,
271 // Devtools wire payload is plain strings; per-prompt metadata is
272 // irrelevant for observation and would require devtools-UI changes to
273 // render. Project metadata away here so the wire shape is unchanged.
274 systemPrompts:
275 ctx.systemPrompts.length > 0
276 ? ctx.systemPrompts.map((p) => (typeof p === 'string' ? p : p.content))
277 : undefined,
278 toolNames: ctx.toolNames,
279 options: ctx.options,
280 modelOptions: ctx.modelOptions,
281 messageCount: ctx.messageCount,
282 hasTools: ctx.hasTools,
283 streaming: ctx.streaming,
284 }
286​
287/**
288 * Extract text content from a ModelMessage content field.
289 */
290function getContentString(content: DevtoolsModelMessage['content']): string {
291 if (typeof content === 'string') return content
292 if (!Array.isArray(content)) return ''
293 return (
294 content
295 .map((part) =>
296 part &&
297 typeof part === 'object' &&
298 (part as { type?: string }).type === 'text'
299 ? String((part as { content?: unknown }).content ?? '')
300 : '',
301 )
302 .join('') || ''
303 )
305​
306/**
307 * Internal devtools middleware that emits all DevTools events.
308 * Auto-injected as the FIRST middleware in the TextEngine.
309 *
310 * All hooks are observation-only — `onChunk` returns void to pass through
311 * without transforming chunks.
312 */
313export function devtoolsMiddleware(): DevtoolsChatMiddleware {
314 // Local mutable state — tracked here because the devtools middleware
315 // runs first, before the engine updates ctx.currentMessageId / ctx.accumulatedContent
316 let localMessageId: string | null = null
317 let localAccumulatedContent = ''
318 let localAccumulatedThinking = ''
319 let currentIteration = -1
320 let iterationStartTime = 0
321 const activeToolCalls = new Map<string, { toolName: string; index: number }>()
322​
323 return {
324 name: 'devtools',
325​
326 onStart(ctx) {
327 // Emit text:request:started
328 safeEmit('text:request:started', {
329 ...buildEventContext(ctx),
330 timestamp: Date.now(),
331 })
332​
333 // Emit text:message:created for the new user message
334 const messages = ctx.messages
335 const messagesToEmit = messages.slice(-1).filter((m) => m.role === 'user')
336​
337 messagesToEmit.forEach((message) => {
338 const messageIndex = messages.length - 1
339 const messageId = ctx.createId('msg')
340 const base = buildEventContext(ctx)
341 const content = getContentString(message.content)
342​
343 safeEmit('text:message:created', {
344 ...base,
345 messageId,
346 role: message.role as 'user' | 'assistant' | 'system' | 'tool',
347 content,
348 toolCalls: message.toolCalls as never,
349 messageIndex,
350 timestamp: Date.now(),
351 })
352​
353 if (message.role === 'user') {
354 safeEmit('text:message:user', {
355 ...base,
356 messageId,
357 role: 'user' as const,
358 content,
359 messageIndex,
360 timestamp: Date.now(),
361 })
362 }
363 })
364 },
365​
366 onIteration(ctx: DevtoolsMiddlewareContext, info: DevtoolsIterationInfo) {
367 const now = Date.now()
368​
369 // Emit completed for previous iteration (it ended with tool_calls if we got here)
370 if (currentIteration >= 0) {
371 safeEmit('text:iteration:completed', {
372 ...buildEventContext(ctx),
373 iteration: currentIteration,
374 messageId: localMessageId || undefined,
375 duration: now - iterationStartTime,
376 finishReason: 'tool_calls',
377 timestamp: now,
378 })
379 }
380​
381 // Track new iteration
382 currentIteration = info.iteration
383 iterationStartTime = now
384 localMessageId = info.messageId
385 localAccumulatedContent = ''
386 localAccumulatedThinking = ''
387​
388 // Emit iteration:started with config snapshot
389 safeEmit('text:iteration:started', {
390 ...buildEventContext(ctx),
391 iteration: info.iteration,
392 messageId: info.messageId,
393 timestamp: now,
394 })
395​
396 // Emit assistant message placeholder
397 safeEmit('text:message:created', {
398 ...buildEventContext(ctx),
399 messageId: info.messageId,
400 role: 'assistant' as const,
401 content: '',
402 timestamp: now,
403 })
404 },
405​
406 onChunk(ctx, rawChunk) {
407 if (!isKnownChunk(rawChunk)) return
408 const chunk = rawChunk
409 const base = buildEventContext(ctx)
410​
411 switch (chunk.type) {
412 case 'TEXT_MESSAGE_CONTENT': {
413 localAccumulatedContent += chunk.delta
414 safeEmit('text:chunk:content', {
415 ...base,
416 messageId: localMessageId || undefined,
417 content: localAccumulatedContent,
418 delta: chunk.delta,
419 timestamp: Date.now(),
420 })
421 break
422 }
423 case 'TOOL_CALL_START': {
424 const toolIndex = chunk.index ?? 0
425 const toolName = chunk.toolCallName
426 activeToolCalls.set(chunk.toolCallId, {
427 toolName,
428 index: toolIndex,
429 })
430 safeEmit('text:chunk:tool-call', {
431 ...base,
432 messageId: localMessageId || undefined,
433 toolCallId: chunk.toolCallId,
434 toolName,
435 index: toolIndex,
436 arguments: '',
437 timestamp: Date.now(),
438 })
439 break
440 }
441 case 'TOOL_CALL_ARGS': {
442 const active = activeToolCalls.get(chunk.toolCallId)
443 safeEmit('text:chunk:tool-call', {
444 ...base,
445 messageId: localMessageId || undefined,
446 toolCallId: chunk.toolCallId,
447 toolName: active?.toolName ?? '',
448 index: active?.index ?? 0,
449 arguments: chunk.delta,
450 timestamp: Date.now(),
451 })
452 break
453 }
454 case 'TOOL_CALL_END': {
455 activeToolCalls.delete(chunk.toolCallId)
456 break
457 }
458 case 'TOOL_CALL_RESULT': {
459 // Server-executed tool results arrive on the spec-compliant
460 // TOOL_CALL_RESULT event (the adapter's TOOL_CALL_END carries only
461 // the parsed input). Surface them to devtools from here so results
462 // still show up now that the post-execution END is no longer
463 // re-emitted (#519).
464 safeEmit('text:chunk:tool-result', {
465 ...base,
466 messageId: localMessageId || undefined,
467 toolCallId: chunk.toolCallId,
468 result: chunk.content || '',
469 timestamp: Date.now(),
470 })
471 break
472 }
473 case 'RUN_FINISHED': {
474 const rawUsage = chunk.usage
475 const usage =
476 rawUsage != null &&
477 typeof rawUsage === 'object' &&
478 !Array.isArray(rawUsage) &&
479 'promptTokens' in rawUsage
480 ? rawUsage
481 : fromSpecTokenUsage(
482 Array.isArray(rawUsage) ? rawUsage : undefined,
483 chunkTanstack(chunk)?.usage,
484 )
485 safeEmit('text:chunk:done', {
486 ...base,
487 messageId: localMessageId || undefined,
488 finishReason:
489 chunk.finishReason ?? chunkTanstack(chunk)?.finishReason ?? null,
490 usage,
491 timestamp: Date.now(),
492 })
493 if (usage) {
494 safeEmit('text:usage', {
495 ...base,
496 messageId: localMessageId || undefined,
497 usage,
498 timestamp: Date.now(),
499 })
500 }
501 break
502 }
503 case 'RUN_ERROR': {
504 const errorMessage =
505 chunk.message ??
506 `[ai-devtools] RUN_ERROR chunk had no message; raw chunk: ${JSON.stringify(chunk)}`
507 safeEmit('text:chunk:error', {
508 ...base,
509 messageId: localMessageId || undefined,
510 error: errorMessage,
511 timestamp: Date.now(),
512 })
513 break
514 }
515 case 'REASONING_MESSAGE_CONTENT': {
516 localAccumulatedThinking += chunk.delta
517 safeEmit('text:chunk:thinking', {
518 ...base,
519 messageId: localMessageId || undefined,
520 content: localAccumulatedThinking,
521 delta: chunk.delta,
522 timestamp: Date.now(),
523 })
524 break
525 }
526 }
527​
528 // Return void — observation only, pass through unchanged
529 },
530​
531 onToolPhaseComplete(ctx, info: DevtoolsToolPhaseCompleteInfo) {
532 const base = buildEventContext(ctx)
533​
534 // Emit text:message:created for assistant message with tool calls
535 if (info.toolCalls.length > 0) {
536 safeEmit('text:message:created', {
537 ...base,
538 messageId: localMessageId ?? ctx.createId('msg'),
539 role: 'assistant' as const,
540 content: localAccumulatedContent || '',
541 toolCalls: info.toolCalls as never,
542 timestamp: Date.now(),
543 })
544 }
545​
546 // Emit tools:approval:requested for each pending approval
547 for (const approval of info.needsApproval) {
548 safeEmit('tools:approval:requested', {
549 ...base,
550 messageId: localMessageId || undefined,
551 toolCallId: approval.toolCallId,
552 toolName: approval.toolName,
553 input: approval.input,
554 approvalId: approval.approvalId,
555 timestamp: Date.now(),
556 })
557 }
558​
559 // Emit tools:input:available for each client tool
560 for (const clientTool of info.needsClientExecution) {
561 safeEmit('tools:input:available', {
562 ...base,
563 messageId: localMessageId || undefined,
564 toolCallId: clientTool.toolCallId,
565 toolName: clientTool.toolName,
566 input: clientTool.input,
567 timestamp: Date.now(),
568 })
569 }
570​
571 // Emit tools:call:completed and text:message:created (tool role) for each result
572 for (const result of info.results) {
573 safeEmit('tools:call:completed', {
574 ...base,
575 messageId: localMessageId || undefined,
576 toolCallId: result.toolCallId,
577 toolName: result.toolName,
578 result: result.result,
579 duration: result.duration ?? 0,
580 timestamp: Date.now(),
581 })
582​
583 const content = JSON.stringify(result.result)
584 safeEmit('text:message:created', {
585 ...base,
586 messageId: ctx.createId('msg'),
587 role: 'tool' as const,
588 content,
589 timestamp: Date.now(),
590 })
591 }
592 },
593​
594 onFinish(ctx, info) {
595 const now = Date.now()
596​
597 // Emit completed for the final iteration
598 if (currentIteration >= 0) {
599 safeEmit('text:iteration:completed', {
600 ...buildEventContext(ctx),
601 iteration: currentIteration,
602 messageId: localMessageId || undefined,
603 duration: now - iterationStartTime,
604 finishReason: info.finishReason || undefined,
605 usage: info.usage,
606 timestamp: now,
607 })
608 }
609​
610 safeEmit('text:request:completed', {
611 ...buildEventContext(ctx),
612 content: info.content,
613 messageId: localMessageId || undefined,
614 finishReason: info.finishReason || undefined,
615 usage: info.usage,
616 duration: info.duration,
617 timestamp: now,
618 })
619 },
620 }