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

events.ts

371 lines8.6 KB

1import {
2 aiEventClient,
3 createAIDevtoolsEventEnvelope,
4} from '@tanstack/ai-event-client'
5import type { ContentPart } from '@tanstack/ai/client'
6import type { UIMessage } from './types'
7​
8export interface ChatClientRunEventContext {
9 threadId: string
10 runId: string
11 toolCallId?: string
13​
14export interface ChatClientEventContext {
15 threadId?: string
16 runId?: string
17 toolCallId?: string
19​
20export interface ChatClientToolFixtureAppliedEvent {
21 hookId: string
22 threadId: string
23 toolName: string
24 input: unknown
25 output: unknown
26 execute?: boolean
27 message?: {
28 id: string
29 role: UIMessage['role']
30 parts: Array<unknown>
31 createdAt?: number | string
32 }
33 messageId: string
34 toolCallId: string
35 runId?: string
36 errorText?: string
38​
39export interface ChatClientStructuredOutputEvent {
40 status: 'streaming' | 'complete' | 'error'
41 raw?: string
42 partial?: unknown
43 data?: unknown
44 reasoning?: string
45 errorMessage?: string
46 delta?: string
48​
49export type ChatClientStructuredOutputEventName =
50 | 'structured-output:started'
51 | 'structured-output:updated'
52 | 'structured-output:completed'
53 | 'structured-output:errored'
54​
55/**
56 * Abstract base class for ChatClient event emission
57 */
58export abstract class ChatClientEventEmitter {
59 protected clientId: string
60​
61 constructor(clientId: string) {
62 this.clientId = clientId
63 }
64​
65 /**
66 * Protected abstract method for emitting events
67 * Implementations should handle adding clientId and timestamp
68 */
69 protected abstract emitEvent(
70 eventName: string,
71 data?: Record<string, unknown>,
72 ): void
73​
74 /**
75 * Emit client created event
76 */
77 clientCreated(initialMessageCount: number): void {
78 this.emitEvent('client:created', {
79 initialMessageCount,
80 })
81 }
82​
83 /**
84 * Emit loading state changed event
85 */
86 loadingChanged(isLoading: boolean): void {
87 this.emitEvent('client:loading:changed', { isLoading })
88 }
89​
90 /**
91 * Emit error state changed event
92 */
93 errorChanged(error: string | null): void {
94 this.emitEvent('client:error:changed', {
95 error,
96 })
97 }
98​
99 /**
100 * Emit text update events (combines processor and client events)
101 */
102 textUpdated(
103 streamId: string,
104 messageId: string,
105 content: string,
106 context?: ChatClientRunEventContext,
107 ): void {
108 this.emitEvent('text:chunk:content', {
109 streamId,
110 messageId,
111 content,
112 ...context,
113 })
114 }
115​
116 /**
117 * Emit tool call state change events (combines processor and client events)
118 */
119 toolCallStateChanged(
120 streamId: string,
121 messageId: string,
122 toolCallId: string,
123 toolName: string,
124 state: string,
125 args: string,
126 context?: ChatClientRunEventContext,
127 ): void {
128 this.emitEvent('tools:call:updated', {
129 streamId,
130 messageId,
131 toolCallId,
132 toolName,
133 state,
134 arguments: args,
135 ...context,
136 })
137 }
138​
139 /**
140 * Emit tool result state change event
141 */
142 /**
143 * Emit thinking update event
144 */
145 thinkingUpdated(
146 streamId: string,
147 messageId: string,
148 content: string,
149 delta?: string,
150 context?: ChatClientRunEventContext,
151 ): void {
152 this.emitEvent('text:chunk:thinking', {
153 streamId,
154 messageId,
155 content,
156 delta,
157 ...context,
158 })
159 }
160​
161 structuredOutputChanged(
162 eventName: ChatClientStructuredOutputEventName,
163 streamId: string,
164 messageId: string,
165 output: ChatClientStructuredOutputEvent,
166 context?: ChatClientRunEventContext,
167 ): void {
168 this.emitEvent(eventName, {
169 streamId,
170 messageId,
171 ...output,
172 ...context,
173 })
174 }
175​
176 /**
177 * Emit approval requested event
178 */
179 approvalRequested(
180 streamId: string,
181 messageId: string,
182 toolCallId: string,
183 toolName: string,
184 input: unknown,
185 approvalId: string,
186 context?: ChatClientRunEventContext,
187 ): void {
188 this.emitEvent('tools:approval:requested', {
189 streamId,
190 messageId,
191 toolCallId,
192 toolName,
193 input,
194 approvalId,
195 ...context,
196 })
197 }
198​
199 /**
200 * Emit message appended event
201 */
202 messageAppended(
203 uiMessage: UIMessage,
204 streamId?: string,
205 context?: ChatClientEventContext,
206 ): void {
207 const content = uiMessage.parts
208 .filter((part) => part.type === 'text')
209 .map((part) => part.content)
210 .join(' ')
211​
212 this.emitEvent('text:message:created', {
213 streamId,
214 messageId: uiMessage.id,
215 role: uiMessage.role,
216 content,
217 parts: uiMessage.parts,
218 ...context,
219 })
220 }
221​
222 /**
223 * Emit message sent event.
224 * Supports both simple string content and multimodal content arrays.
225 *
226 * @param messageId - The ID of the sent message
227 * @param content - The message content (string or array of ContentPart for multimodal)
228 */
229 messageSent(messageId: string, content: string | Array<ContentPart>): void {
230 // For text content, extract it; for multimodal, provide the array
231 const textContent =
232 typeof content === 'string'
233 ? content
234 : content
235 .filter((part) => part.type === 'text')
236 .map((part) => (part as { type: 'text'; content: string }).content)
237 .join('')
238​
239 this.emitEvent('text:message:created', {
240 messageId,
241 role: 'user',
242 content: textContent,
243 // Include full content for multimodal messages
244 ...(Array.isArray(content) && { parts: content }),
245 })
246​
247 this.emitEvent('text:message:user', {
248 messageId,
249 role: 'user',
250 content: textContent,
251 // Include full content for multimodal messages
252 ...(Array.isArray(content) && { parts: content }),
253 })
254 }
255​
256 /**
257 * Emit reloaded event
258 */
259 reloaded(fromMessageIndex: number): void {
260 this.emitEvent('client:reloaded', {
261 fromMessageIndex,
262 })
263 }
264 /**
265 * Emit stopped event
266 */
267 stopped(): void {
268 this.emitEvent('client:stopped')
269 }
270​
271 /**
272 * Emit messages cleared event
273 */
274 messagesCleared(): void {
275 this.emitEvent('client:messages:cleared')
276 }
277​
278 /**
279 * Emit tool result added event
280 */
281 toolResultAdded(
282 toolCallId: string,
283 toolName: string,
284 output: unknown,
285 state: string,
286 context?: ChatClientEventContext,
287 ): void {
288 this.emitEvent('tools:result:added', {
289 toolCallId,
290 toolName,
291 output,
292 state,
293 ...context,
294 })
295 }
296​
297 /**
298 * Emit tool fixture applied event.
299 */
300 toolFixtureApplied(fixture: ChatClientToolFixtureAppliedEvent): void {
301 this.emitEvent('devtools:tool-fixture:applied', { ...fixture })
302 }
304​
305/**
306 * Default implementation of ChatClientEventEmitter
307 */
308export class DefaultChatClientEventEmitter extends ChatClientEventEmitter {
309 /**
310 * Emit an event with automatic clientId and timestamp for client/tool events
311 */
312 protected emitEvent(eventName: string, data?: Record<string, any>): void {
313 const timestamp = Date.now()
314 const isUserVisibleEvent =
315 eventName.startsWith('text:') ||
316 eventName.startsWith('tools:') ||
317 eventName.startsWith('structured-output:') ||
318 eventName === 'devtools:tool-fixture:applied'
319 const includesClientContext =
320 eventName.startsWith('client:') ||
321 eventName.startsWith('tools:') ||
322 eventName.startsWith('text:') ||
323 eventName.startsWith('structured-output:') ||
324 eventName === 'devtools:tool-fixture:applied'
325 const visibility = isUserVisibleEvent ? 'user-visible' : 'client-state'
326 const envelopeContext = {
327 hookId: this.clientId,
328 ...(typeof data?.threadId === 'string'
329 ? { threadId: data.threadId }
330 : {}),
331 ...(typeof data?.runId === 'string' ? { runId: data.runId } : {}),
332 ...(typeof data?.streamId === 'string'
333 ? { streamId: data.streamId }
334 : {}),
335 ...(typeof data?.messageId === 'string'
336 ? { messageId: data.messageId }
337 : {}),
338 ...(typeof data?.toolCallId === 'string'
339 ? { toolCallId: data.toolCallId }
340 : {}),
341 }
342​
343 // For client:* and tool:* events, automatically add clientId and timestamp
344 if (includesClientContext) {
345 const envelope = createAIDevtoolsEventEnvelope({
346 eventType: eventName,
347 clientId: this.clientId,
348 ...envelopeContext,
349 source: 'client',
350 visibility,
351 timestamp,
352 })
353 aiEventClient.emit(eventName as any, {
354 ...data,
355 ...envelope,
356 })
357 } else {
358 const envelope = createAIDevtoolsEventEnvelope({
359 eventType: eventName,
360 source: 'client',
361 visibility: 'client-state',
362 timestamp,
363 })
364 // For other events, just add timestamp
365 aiEventClient.emit(eventName as any, {
366 ...data,
367 ...envelope,
368 })
369 }
370 }