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

realtime-client.ts

662 lines19.4 KB

1import { convertSchemaToJsonSchema } from '@tanstack/ai/client'
2import {
3 createAtom,
4 freezeSnapshotMessages,
5 notifyListeners,
6 subscribeAtom,
7} from './snapshot-atom'
8import type { Atom } from './snapshot-atom'
9import type {
10 AnyClientTool,
11 AudioVisualization,
12 RealtimeConnection,
13 RealtimeMessage,
14 RealtimeMode,
15 RealtimeSessionConfig,
16 RealtimeStatus,
17 RealtimeToken,
18} from '@tanstack/ai/client'
19import type {
20 RealtimeClientOptions,
21 RealtimeClientState,
22 RealtimeStateChangeCallback,
23} from './realtime-types'
24​
25// Token refresh buffer - refresh 1 minute before expiry
26const TOKEN_REFRESH_BUFFER_MS = 60_000
27​
28/**
29 * Client for managing realtime voice conversations.
30 *
31 * Handles connection lifecycle, audio I/O, message state,
32 * and tool execution for realtime voice-to-voice AI interactions.
33 *
34 * @example
35 * ```typescript
36 * import { RealtimeClient } from '@tanstack/ai-client'
37 * import { openaiRealtime } from '@tanstack/ai-openai'
38 *
39 * const client = new RealtimeClient({
40 * getToken: () => fetch('/api/realtime-token').then(r => r.json()),
41 * adapter: openaiRealtime(),
42 * tools: [myTool.client(handler)],
43 * onMessage: (msg) => console.log('Message:', msg),
44 * })
45 *
46 * await client.connect()
47 * ```
48 */
49export class RealtimeClient {
50 private readonly options: RealtimeClientOptions
51 private connection: RealtimeConnection | null = null
52 private token: RealtimeToken | null = null
53 private tokenRefreshTimeout: ReturnType<typeof setTimeout> | null = null
54 private readonly clientTools: Map<string, AnyClientTool>
55 private readonly stateChangeCallbacks: Set<RealtimeStateChangeCallback> =
56 new Set()
57 private unsubscribers: Array<() => void> = []
58 // Declared before `snapshotAtom`, whose initializer reads it.
59 private readonly frozenMessages = new WeakMap<object, object>()
60​
61 private state: RealtimeClientState = {
62 status: 'idle',
63 mode: 'idle',
64 messages: [],
65 pendingUserTranscript: null,
66 pendingAssistantTranscript: null,
67 error: null,
68 }
69 private readonly snapshotAtom: Atom<RealtimeClientState> = createAtom(
70 this.buildSnapshot(),
71 )
72​
73 constructor(options: RealtimeClientOptions) {
74 this.options = {
75 autoPlayback: true,
76 autoCapture: true,
77 vadMode: 'server',
78 ...options,
79 }
80​
81 // Build client tools map
82 this.clientTools = new Map()
83 if (options.tools) {
84 for (const tool of options.tools) {
85 this.clientTools.set(tool.name, tool)
86 }
87 }
88 }
89​
90 // ============================================================================
91 // Connection Lifecycle
92 // ============================================================================
93​
94 /**
95 * Connect to the realtime session.
96 * Fetches a token and establishes the connection.
97 */
98 async connect(): Promise<void> {
99 if (this.state.status === 'connected') {
100 return
101 }
102​
103 this.updateState({
104 status: 'connecting',
105 error: null,
106 })
107​
108 try {
109 // Fetch token from server
110 this.token = await this.options.getToken()
111​
112 // Schedule token refresh
113 this.scheduleTokenRefresh()
114​
115 // Connect via adapter (pass tools for providers like ElevenLabs that need them at connect time)
116 const toolsList =
117 this.clientTools.size > 0
118 ? Array.from(this.clientTools.values())
119 : undefined
120​
121 this.connection = await this.options.adapter.connect(
122 this.token,
123 toolsList,
124 )
125​
126 // A new session starts here. Clear the last transcript before events
127 // flow, so a greeting that arrives while audio capture starts is kept.
128 // A connect that fails before this point keeps the last transcript.
129 this.updateState({
130 messages: [],
131 pendingUserTranscript: null,
132 pendingAssistantTranscript: null,
133 })
134​
135 // Subscribe to connection events
136 this.subscribeToConnectionEvents()
137​
138 // Auto-configure session with client-provided settings
139 this.applySessionConfig()
140​
141 // Start audio capture if configured
142 if (this.options.autoCapture) {
143 await this.connection.startAudioCapture()
144 }
145​
146 this.updateState({
147 status: 'connected',
148 mode: 'listening',
149 })
150 this.options.onConnect?.()
151 } catch (error) {
152 const err = error instanceof Error ? error : new Error(String(error))
153 this.updateState({ status: 'error', error: err })
154 this.options.onError?.(err)
155 throw err
156 }
157 }
158​
159 /**
160 * Disconnect from the realtime session.
161 */
162 async disconnect(): Promise<void> {
163 if (this.tokenRefreshTimeout) {
164 clearTimeout(this.tokenRefreshTimeout)
165 this.tokenRefreshTimeout = null
166 }
167​
168 // Unsubscribe from all events
169 for (const unsub of this.unsubscribers) {
170 unsub()
171 }
172 this.unsubscribers = []
173​
174 if (this.connection) {
175 await this.connection.disconnect()
176 this.connection = null
177 }
178​
179 this.token = null
180 this.updateState({
181 status: 'idle',
182 mode: 'idle',
183 pendingUserTranscript: null,
184 pendingAssistantTranscript: null,
185 })
186 this.options.onDisconnect?.()
187 }
188​
189 // ============================================================================
190 // Voice Control
191 // ============================================================================
192​
193 /**
194 * Start listening for voice input.
195 * Only needed when vadMode is 'manual'.
196 */
197 startListening(): void {
198 if (!this.connection || this.state.status !== 'connected') {
199 return
200 }
201 void this.connection.startAudioCapture()
202 this.updateState({ mode: 'listening' })
203 }
204​
205 /**
206 * Stop listening for voice input.
207 * Only needed when vadMode is 'manual'.
208 */
209 stopListening(): void {
210 if (!this.connection) {
211 return
212 }
213 this.connection.stopAudioCapture()
214 this.updateState({ mode: 'idle' })
215 }
216​
217 /**
218 * Interrupt the current assistant response.
219 */
220 interrupt(): void {
221 if (!this.connection) {
222 return
223 }
224 this.connection.interrupt()
225 this.updateState({ pendingAssistantTranscript: null })
226 }
227​
228 // ============================================================================
229 // Text Input
230 // ============================================================================
231​
232 /**
233 * Send a text message instead of voice.
234 */
235 sendText(text: string): void {
236 if (!this.connection || this.state.status !== 'connected') {
237 return
238 }
239​
240 // Add user message
241 const userMessage: RealtimeMessage = {
242 id: this.generateId(),
243 role: 'user',
244 timestamp: Date.now(),
245 parts: [{ type: 'text', content: text }],
246 }
247 this.addMessage(userMessage)
248​
249 // Send to provider
250 this.connection.sendText(text)
251 }
252​
253 /**
254 * Send an image to the conversation.
255 * @param imageData - Base64-encoded image data or a URL
256 * @param mimeType - MIME type of the image (e.g., 'image/png', 'image/jpeg')
257 */
258 sendImage(imageData: string, mimeType: string): void {
259 if (!this.connection || this.state.status !== 'connected') {
260 return
261 }
262​
263 // Add user message with image part
264 const userMessage: RealtimeMessage = {
265 id: this.generateId(),
266 role: 'user',
267 timestamp: Date.now(),
268 parts: [{ type: 'image', data: imageData, mimeType }],
269 }
270 this.addMessage(userMessage)
271​
272 // Send to provider
273 this.connection.sendImage(imageData, mimeType)
274 }
275​
276 // ============================================================================
277 // State Access
278 // ============================================================================
279​
280 /** Get current connection status */
281 get status(): RealtimeStatus {
282 return this.state.status
283 }
284​
285 /** Get current mode */
286 get mode(): RealtimeMode {
287 return this.state.mode
288 }
289​
290 /** Get conversation messages */
291 get messages(): ReadonlyArray<RealtimeMessage> {
292 return this.state.messages
293 }
294​
295 /** Get current error, if any */
296 get error(): Error | null {
297 return this.state.error
298 }
299​
300 /** Get pending user transcript (while user is speaking) */
301 get pendingUserTranscript(): string | null {
302 return this.state.pendingUserTranscript
303 }
304​
305 /** Get pending assistant transcript (while assistant is speaking) */
306 get pendingAssistantTranscript(): string | null {
307 return this.state.pendingAssistantTranscript
308 }
309​
310 /** Get audio visualization data */
311 get audio(): AudioVisualization | null {
312 return this.connection?.getAudioVisualization() ?? null
313 }
314​
315 /**
316 * Update the session configuration.
317 * This applies changes to the active connection and persists them for future reconnections.
318 */
319 updateSession(config: Partial<RealtimeSessionConfig>): void {
320 // Persist type-compatible fields so future (re)connections use the updated
321 // config. `tools` is intentionally excluded: a session's tool configs are
322 // serialized descriptors, whereas `options.tools` holds executable client
323 // tools tracked separately via `clientTools`.
324 const o = this.options
325 if (config.instructions !== undefined) o.instructions = config.instructions
326 if (config.voice !== undefined) o.voice = config.voice
327 if (config.vadMode !== undefined) o.vadMode = config.vadMode
328 if (config.outputModalities !== undefined) {
329 o.outputModalities = config.outputModalities
330 }
331 if (config.temperature !== undefined) o.temperature = config.temperature
332 if (config.maxOutputTokens !== undefined) {
333 o.maxOutputTokens = config.maxOutputTokens
334 }
335 if (config.semanticEagerness !== undefined) {
336 o.semanticEagerness = config.semanticEagerness
337 }
338 if (config.providerOptions !== undefined) {
339 o.providerOptions = config.providerOptions
340 }
341​
342 if (this.connection) {
343 this.applySessionConfig()
344 }
345 }
346​
347 // ============================================================================
348 // State Subscription
349 // ============================================================================
350​
351 /**
352 * Subscribe to state changes.
353 * @returns Unsubscribe function
354 */
355 onStateChange(callback: RealtimeStateChangeCallback): () => void {
356 this.stateChangeCallbacks.add(callback)
357 return () => {
358 this.stateChangeCallbacks.delete(callback)
359 }
360 }
361​
362 /**
363 * Subscribe to UI snapshot changes. Does not fire with the current value;
364 * read {@link getSnapshot} first.
365 */
366 subscribe = (listener: () => void): (() => void) =>
367 subscribeAtom(this.snapshotAtom, listener)
368​
369 /** Current UI snapshot. */
370 getSnapshot = (): RealtimeClientState => this.snapshotAtom.get()
371​
372 // ============================================================================
373 // Cleanup
374 // ============================================================================
375​
376 /**
377 * Clean up resources.
378 * Call this when disposing of the client.
379 */
380 destroy(): void {
381 void this.disconnect()
382 this.stateChangeCallbacks.clear()
383 }
384​
385 // ============================================================================
386 // Private Methods
387 // ============================================================================
388​
389 private updateState(updates: Partial<RealtimeClientState>): void {
390 const changed = Object.keys(updates).some((key) => {
391 const stateKey = key as keyof RealtimeClientState
392 return !Object.is(this.state[stateKey], updates[stateKey])
393 })
394 if (!changed) return
395 const messagesChanged =
396 'messages' in updates && updates.messages !== this.state.messages
397 this.state = { ...this.state, ...updates }
398 // A transcript or mode update keeps the same `messages` array, so UI
399 // memo keyed on it does not run again for every transcript token.
400 const snapshot = messagesChanged
401 ? this.buildSnapshot()
402 : Object.freeze({
403 ...this.state,
404 messages: this.snapshotAtom.get().messages,
405 })
406 this.snapshotAtom.set(snapshot)
407​
408 notifyListeners(this.stateChangeCallbacks, snapshot)
409​
410 // Notify specific callbacks
411 if ('status' in updates && updates.status !== undefined) {
412 this.options.onStatusChange?.(updates.status)
413 }
414 if ('mode' in updates && updates.mode !== undefined) {
415 this.options.onModeChange?.(updates.mode)
416 }
417 }
418​
419 private buildSnapshot(): RealtimeClientState {
420 return Object.freeze({
421 ...this.state,
422 messages: freezeSnapshotMessages(
423 this.frozenMessages,
424 this.state.messages,
425 ),
426 })
427 }
428​
429 private addMessage(message: RealtimeMessage): void {
430 this.updateState({
431 messages: [...this.state.messages, message],
432 })
433 this.options.onMessage?.(message)
434 }
435​
436 private scheduleTokenRefresh(): void {
437 if (!this.token) return
438​
439 const timeUntilExpiry = this.token.expiresAt - Date.now()
440 const refreshIn = Math.max(0, timeUntilExpiry - TOKEN_REFRESH_BUFFER_MS)
441​
442 this.tokenRefreshTimeout = setTimeout(() => {
443 void this.refreshToken()
444 }, refreshIn)
445 }
446​
447 private async refreshToken(): Promise<void> {
448 try {
449 this.token = await this.options.getToken()
450 this.scheduleTokenRefresh()
451 this.connection?.updateToken?.(this.token)
452 // Note: Some providers may require reconnection with new token
453 // This is handled by the adapter implementation
454 } catch (error) {
455 const err = error instanceof Error ? error : new Error(String(error))
456 this.updateState({ error: err })
457 this.options.onError?.(err)
458 }
459 }
460​
461 private subscribeToConnectionEvents(): void {
462 if (!this.connection) return
463​
464 // Status changes
465 this.unsubscribers.push(
466 this.connection.on('status_change', ({ status }) => {
467 this.updateState({ status })
468 }),
469 )
470​
471 // Mode changes
472 this.unsubscribers.push(
473 this.connection.on('mode_change', ({ mode }) => {
474 this.updateState({ mode })
475 }),
476 )
477​
478 // Transcripts (streaming)
479 // User transcripts are added as messages when final (no separate message_complete for user input)
480 // Assistant transcripts are streamed, final message comes via message_complete
481 this.unsubscribers.push(
482 this.connection.on('transcript', ({ role, transcript, isFinal }) => {
483 if (role === 'user') {
484 this.updateState({
485 pendingUserTranscript: isFinal ? null : transcript,
486 })
487 // Add user message when transcript is finalized
488 if (isFinal && transcript) {
489 this.addMessage({
490 id: this.generateId(),
491 role: 'user',
492 timestamp: Date.now(),
493 parts: [{ type: 'audio', transcript, durationMs: 0 }],
494 })
495 }
496 } else {
497 // Assistant transcripts - just update pending, message_complete handles final
498 this.updateState({
499 pendingAssistantTranscript: isFinal ? null : transcript,
500 })
501 }
502 }),
503 )
504​
505 // Tool calls
506 this.unsubscribers.push(
507 this.connection.on('tool_call', ({ toolCallId, toolName, input }) => {
508 if (!toolCallId) {
509 console.error(
510 '[RealtimeClient] tool_call missing toolCallId',
511 toolName,
512 )
513 return
514 }
515 const tool = this.clientTools.get(toolName)
516 const execute = tool?.execute
517 if (execute) {
518 void (async () => {
519 try {
520 const output = await execute(input)
521 this.connection?.sendToolResult(
522 toolCallId,
523 typeof output === 'string' ? output : JSON.stringify(output),
524 )
525 } catch (error) {
526 const errMsg =
527 error instanceof Error ? error.message : String(error)
528 this.connection?.sendToolResult(
529 toolCallId,
530 JSON.stringify({ error: errMsg }),
531 )
532 }
533 })()
534 } else {
535 this.connection?.sendToolResult(
536 toolCallId,
537 JSON.stringify({
538 error: `Unknown or non-executable tool: ${String(toolName)}`,
539 }),
540 )
541 }
542 }),
543 )
544​
545 // Message complete
546 this.unsubscribers.push(
547 this.connection.on('message_complete', ({ message }) => {
548 // Replace pending message with final version if needed
549 const existingIndex = this.state.messages.findIndex(
550 (m) => m.id === message.id,
551 )
552 if (existingIndex >= 0) {
553 const newMessages = [...this.state.messages]
554 newMessages[existingIndex] = message
555 this.updateState({ messages: newMessages })
556 } else {
557 this.addMessage(message)
558 }
559 }),
560 )
561​
562 // Interruption
563 this.unsubscribers.push(
564 this.connection.on('interrupted', ({ messageId }) => {
565 if (messageId) {
566 const newMessages = this.state.messages.map((m) =>
567 m.id === messageId ? { ...m, interrupted: true } : m,
568 )
569 this.updateState({ messages: newMessages })
570 }
571 this.updateState({
572 mode: 'listening',
573 pendingAssistantTranscript: null,
574 })
575 this.options.onInterrupted?.()
576 }),
577 )
578​
579 // Errors
580 this.unsubscribers.push(
581 this.connection.on('error', ({ error }) => {
582 this.updateState({ error })
583 this.options.onError?.(error)
584 }),
585 )
586​
587 this.unsubscribers.push(
588 this.connection.on('go_away', ({ timeLeft }) => {
589 this.options.onGoAway?.(timeLeft)
590 }),
591 )
592​
593 this.unsubscribers.push(
594 this.connection.on('usage', (usage) => {
595 this.options.onUsage?.(usage)
596 }),
597 )
598 }
599​
600 private applySessionConfig(): void {
601 if (!this.connection) return
602​
603 const {
604 instructions,
605 voice,
606 vadMode,
607 tools,
608 outputModalities,
609 temperature,
610 maxOutputTokens,
611 semanticEagerness,
612 } = this.options
613 const hasConfig =
614 instructions ||
615 voice ||
616 vadMode ||
617 (tools && tools.length > 0) ||
618 outputModalities ||
619 temperature !== undefined ||
620 maxOutputTokens !== undefined ||
621 semanticEagerness
622 if (!hasConfig) return
623​
624 // `RealtimeToolConfig.inputSchema`/`outputSchema` are `Record<string, any>`
625 // (no `undefined` under `exactOptionalPropertyTypes`). Conditionally spread
626 // each so we don't pass `undefined` when the tool has no such schema.
627 const toolsConfig = tools
628 ? Array.from(this.clientTools.values()).map((t) => {
629 const inputSchema = t.inputSchema
630 ? convertSchemaToJsonSchema(t.inputSchema)
631 : undefined
632 const outputSchema = t.outputSchema
633 ? convertSchemaToJsonSchema(t.outputSchema)
634 : undefined
635 return {
636 name: t.name,
637 description: t.description,
638 ...(inputSchema ? { inputSchema } : {}),
639 ...(outputSchema ? { outputSchema } : {}),
640 }
641 })
642 : undefined
643​
644 // `RealtimeSessionConfig` declares each field as `field?: T` (no
645 // `undefined`). Spread each one conditionally so we don't violate
646 // `exactOptionalPropertyTypes` when the source is `T | undefined`.
647 this.connection.updateSession({
648 ...(instructions !== undefined ? { instructions } : {}),
649 ...(voice !== undefined ? { voice } : {}),
650 ...(vadMode !== undefined ? { vadMode } : {}),
651 ...(toolsConfig !== undefined ? { tools: toolsConfig } : {}),
652 ...(outputModalities !== undefined ? { outputModalities } : {}),
653 ...(temperature !== undefined ? { temperature } : {}),
654 ...(maxOutputTokens !== undefined ? { maxOutputTokens } : {}),
655 ...(semanticEagerness !== undefined ? { semanticEagerness } : {}),
656 })
657 }
658​
659 private generateId(): string {
660 return `msg-${Date.now()}-${Math.random().toString(36).substring(7)}`
661 }