@escapeaihq/client-core 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +122 -0
  3. package/dist/api.d.ts +836 -0
  4. package/dist/api.d.ts.map +1 -0
  5. package/dist/api.js +781 -0
  6. package/dist/api.js.map +1 -0
  7. package/dist/audio.d.ts +278 -0
  8. package/dist/audio.d.ts.map +1 -0
  9. package/dist/audio.js +758 -0
  10. package/dist/audio.js.map +1 -0
  11. package/dist/audioProtocol.d.ts +101 -0
  12. package/dist/audioProtocol.d.ts.map +1 -0
  13. package/dist/audioProtocol.js +62 -0
  14. package/dist/audioProtocol.js.map +1 -0
  15. package/dist/index.d.ts +28 -0
  16. package/dist/index.d.ts.map +1 -0
  17. package/dist/index.js +28 -0
  18. package/dist/index.js.map +1 -0
  19. package/dist/visemeGeometry.d.ts +198 -0
  20. package/dist/visemeGeometry.d.ts.map +1 -0
  21. package/dist/visemeGeometry.js +297 -0
  22. package/dist/visemeGeometry.js.map +1 -0
  23. package/dist/visemeScheduler.d.ts +28 -0
  24. package/dist/visemeScheduler.d.ts.map +1 -0
  25. package/dist/visemeScheduler.js +94 -0
  26. package/dist/visemeScheduler.js.map +1 -0
  27. package/dist/websocket.d.ts +196 -0
  28. package/dist/websocket.d.ts.map +1 -0
  29. package/dist/websocket.js +250 -0
  30. package/dist/websocket.js.map +1 -0
  31. package/package.json +40 -0
  32. package/src/__tests__/api-pollers.test.ts +524 -0
  33. package/src/__tests__/audio.test.ts +714 -0
  34. package/src/__tests__/visemeGeometry.test.ts +465 -0
  35. package/src/__tests__/visemeScheduler.test.ts +256 -0
  36. package/src/api.ts +1577 -0
  37. package/src/audio.ts +934 -0
  38. package/src/audioProtocol.ts +163 -0
  39. package/src/index.ts +28 -0
  40. package/src/visemeGeometry.ts +353 -0
  41. package/src/visemeScheduler.ts +133 -0
  42. package/src/websocket.ts +385 -0
@@ -0,0 +1,385 @@
1
+ /**
2
+ * WebSocket client for real-time chat
3
+ *
4
+ * Provides a wrapper around the native WebSocket API with:
5
+ * - Automatic reconnection
6
+ * - Message queueing during connection
7
+ * - Event-based message handling
8
+ * - Auth token forwarding
9
+ */
10
+
11
+ import type { HelloPayload } from './audio';
12
+ import type { WordPhonemeInfo } from './audioProtocol';
13
+
14
+ export interface Citation {
15
+ videoId: string;
16
+ t0: number;
17
+ t1: number;
18
+ shotId?: string;
19
+ }
20
+
21
+ export interface ToolResult {
22
+ results: Array<{
23
+ text?: string;
24
+ content?: string;
25
+ }>;
26
+ citations: Citation[];
27
+ }
28
+
29
+ export interface WebSocketMessage {
30
+ type:
31
+ | 'token'
32
+ | 'tool_use'
33
+ | 'tool_result'
34
+ | 'citation'
35
+ | 'image'
36
+ | 'error'
37
+ | 'done'
38
+ | 'heartbeat'
39
+ | 'pong'
40
+ | 'hello_ack'
41
+ | 'transcript'
42
+ | 'audio_metadata'
43
+ | 'barge_in_ack'
44
+ | 'audio_chunk'
45
+ | 'metrics';
46
+ timestamp?: number;
47
+ content?: string;
48
+ tool?: string;
49
+ toolUseId?: string;
50
+ result?: ToolResult;
51
+ citation?: Citation;
52
+ span?: string;
53
+ message?: string;
54
+ final?: boolean;
55
+ text?: string;
56
+ resultId?: string;
57
+ mode?: 'hybrid' | 'sonic';
58
+ sessionId?: string;
59
+ // Image regeneration fields
60
+ imageUrl?: string;
61
+ entity?: string;
62
+ prompt?: string;
63
+ sourceTimestamp?: number;
64
+ // Audio metadata fields
65
+ chunkId?: string;
66
+ wordTimestamps?: Array<{ word: string; startTime: number; endTime: number }>;
67
+ phonemes?: WordPhonemeInfo[];
68
+ processedChars?: number;
69
+ isFinal?: boolean;
70
+ cumulativeTime?: number;
71
+ // Barge-in ack fields
72
+ spokenText?: string;
73
+ cancelledText?: string;
74
+ interruptionTime?: number;
75
+ wordsSpoken?: string[];
76
+ // Audio chunk fields (MP3 from Inworld)
77
+ audio?: string;
78
+ format?: 'mp3' | 'pcm16' | 'ogg_opus';
79
+ // Pipeline timing metrics
80
+ llm_first_token_ms?: number;
81
+ tts_first_chunk_ms?: number;
82
+ transcript_to_first_audio_ms?: number;
83
+ }
84
+
85
+ export type MessageHandler = (message: WebSocketMessage) => void;
86
+ export type BinaryHandler = (data: ArrayBuffer) => void;
87
+
88
+ export interface ChatWebSocketOptions {
89
+ url: string;
90
+ authToken?: string;
91
+ onOpen?: () => void;
92
+ onClose?: () => void;
93
+ onError?: (error: Event) => void;
94
+ onReconnecting?: (attempt: number) => void;
95
+ onReconnected?: () => void;
96
+ }
97
+
98
+ export class ChatWebSocket {
99
+ private ws: WebSocket | null = null;
100
+ private messageHandlers: MessageHandler[] = [];
101
+ private binaryHandlers: BinaryHandler[] = [];
102
+ private url: string;
103
+ private authToken?: string;
104
+ private onOpenCallback?: () => void;
105
+ private onCloseCallback?: () => void;
106
+ private onErrorCallback?: (error: Event) => void;
107
+ private onReconnectingCallback?: (attempt: number) => void;
108
+ private onReconnectedCallback?: () => void;
109
+
110
+ // Reconnection state
111
+ private maxReconnectAttempts = 5;
112
+ private reconnectDelay = 1000;
113
+ private reconnectAttempts = 0;
114
+ private intentionalDisconnect = false;
115
+ private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
116
+
117
+ constructor(options: ChatWebSocketOptions) {
118
+ this.url = options.url;
119
+ this.authToken = options.authToken;
120
+ this.onOpenCallback = options.onOpen;
121
+ this.onCloseCallback = options.onClose;
122
+ this.onErrorCallback = options.onError;
123
+ this.onReconnectingCallback = options.onReconnecting;
124
+ this.onReconnectedCallback = options.onReconnected;
125
+ }
126
+
127
+ /**
128
+ * Connect to the WebSocket server
129
+ */
130
+ connect(): Promise<void> {
131
+ this.intentionalDisconnect = false;
132
+ return this._connect(false);
133
+ }
134
+
135
+ /**
136
+ * Internal connect method. When isReconnect is true, calls
137
+ * onReconnected instead of onOpen on success.
138
+ */
139
+ private _connect(isReconnect: boolean): Promise<void> {
140
+ return new Promise((resolve, reject) => {
141
+ // Append auth token to URL if provided
142
+ const urlWithAuth = this.authToken
143
+ ? `${this.url}?token=${encodeURIComponent(this.authToken)}`
144
+ : this.url;
145
+
146
+ this.ws = new WebSocket(urlWithAuth);
147
+ this.ws.binaryType = 'arraybuffer';
148
+
149
+ this.ws.onopen = () => {
150
+ console.log('WebSocket connected');
151
+ this.reconnectAttempts = 0;
152
+ if (isReconnect) {
153
+ this.onReconnectedCallback?.();
154
+ }
155
+ this.onOpenCallback?.();
156
+ resolve();
157
+ };
158
+
159
+ this.ws.onerror = (error) => {
160
+ console.error('WebSocket error:', error);
161
+ this.onErrorCallback?.(error);
162
+ // Only reject on the initial connect; reconnect attempts are
163
+ // handled by the onclose handler below.
164
+ if (!isReconnect) {
165
+ reject(error);
166
+ }
167
+ };
168
+
169
+ this.ws.onmessage = async (event) => {
170
+ try {
171
+ if (typeof event.data === 'string') {
172
+ const message: WebSocketMessage = JSON.parse(event.data);
173
+ this.messageHandlers.forEach((handler) => handler(message));
174
+ return;
175
+ }
176
+
177
+ if (event.data instanceof ArrayBuffer) {
178
+ this.binaryHandlers.forEach((handler) => handler(event.data));
179
+ return;
180
+ }
181
+
182
+ if (event.data instanceof Blob) {
183
+ const buffer = await event.data.arrayBuffer();
184
+ this.binaryHandlers.forEach((handler) => handler(buffer));
185
+ }
186
+ } catch (error) {
187
+ console.error('Failed to parse WebSocket message:', error);
188
+ }
189
+ };
190
+
191
+ this.ws.onclose = () => {
192
+ console.log('WebSocket disconnected');
193
+ this.onCloseCallback?.();
194
+
195
+ // Attempt reconnection if this was not an intentional disconnect
196
+ if (!this.intentionalDisconnect) {
197
+ this._attemptReconnect();
198
+ }
199
+ };
200
+ });
201
+ }
202
+
203
+ /**
204
+ * Attempt to reconnect with exponential backoff.
205
+ */
206
+ private _attemptReconnect(): void {
207
+ if (this.reconnectAttempts >= this.maxReconnectAttempts) {
208
+ console.error(
209
+ `WebSocket reconnection failed after ${this.maxReconnectAttempts} attempts`
210
+ );
211
+ return;
212
+ }
213
+
214
+ this.reconnectAttempts += 1;
215
+ const delay = this.reconnectDelay * Math.pow(2, this.reconnectAttempts - 1);
216
+ console.log(
217
+ `WebSocket reconnecting in ${delay}ms (attempt ${this.reconnectAttempts}/${this.maxReconnectAttempts})`
218
+ );
219
+ this.onReconnectingCallback?.(this.reconnectAttempts);
220
+
221
+ this.reconnectTimer = setTimeout(() => {
222
+ this._connect(true).catch((err) => {
223
+ console.error('Reconnection attempt failed:', err);
224
+ // The onclose handler will trigger the next attempt automatically
225
+ });
226
+ }, delay);
227
+ }
228
+
229
+ /**
230
+ * Send a chat message
231
+ */
232
+ send(
233
+ prompt: string,
234
+ options?: {
235
+ videoId?: string;
236
+ modelId?: string;
237
+ messages?: Array<{ role: string; content: string; modelId?: string }>;
238
+ systemPrompt?: string;
239
+ systemPromptOverride?: boolean;
240
+ heartbeatInterval?: number;
241
+ idleTimeout?: number;
242
+ }
243
+ ): void {
244
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
245
+ throw new Error('WebSocket not connected');
246
+ }
247
+
248
+ this.ws.send(
249
+ JSON.stringify({
250
+ action: 'send',
251
+ prompt,
252
+ ...options,
253
+ })
254
+ );
255
+ }
256
+
257
+ /**
258
+ * Send an audio hello handshake for hybrid audio/text sessions.
259
+ * Serializes the payload as-is — all defaults are applied by buildHelloPayload().
260
+ */
261
+ sendHello(payload: HelloPayload): void {
262
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
263
+ throw new Error('WebSocket not connected');
264
+ }
265
+
266
+ this.ws.send(JSON.stringify(payload));
267
+ }
268
+
269
+ /**
270
+ * Send a binary microphone frame (tagged with TAG_MIC)
271
+ */
272
+ sendAudioFrame(frame: ArrayBuffer | Uint8Array): void {
273
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
274
+ throw new Error('WebSocket not connected');
275
+ }
276
+
277
+ this.ws.send(frame);
278
+ }
279
+
280
+ /**
281
+ * Send a ping keepalive
282
+ */
283
+ ping(): void {
284
+ if (!this.ws || this.ws.readyState !== WebSocket.OPEN) {
285
+ throw new Error('WebSocket not connected');
286
+ }
287
+
288
+ this.ws.send(JSON.stringify({ action: 'ping' }));
289
+ }
290
+
291
+ /**
292
+ * Get the raw WebSocket instance for advanced operations (e.g., barge-in)
293
+ */
294
+ getRawSocket(): WebSocket | null {
295
+ return this.ws;
296
+ }
297
+
298
+ /**
299
+ * Register a message handler
300
+ */
301
+ onMessage(handler: MessageHandler): void {
302
+ this.messageHandlers.push(handler);
303
+ }
304
+
305
+ /**
306
+ * Register a binary message handler
307
+ */
308
+ onBinary(handler: BinaryHandler): void {
309
+ this.binaryHandlers.push(handler);
310
+ }
311
+
312
+ /**
313
+ * Remove a message handler
314
+ */
315
+ offMessage(handler: MessageHandler): void {
316
+ this.messageHandlers = this.messageHandlers.filter((h) => h !== handler);
317
+ }
318
+
319
+ /**
320
+ * Remove a binary handler
321
+ */
322
+ offBinary(handler: BinaryHandler): void {
323
+ this.binaryHandlers = this.binaryHandlers.filter((h) => h !== handler);
324
+ }
325
+
326
+ /**
327
+ * Disconnect from the WebSocket server.
328
+ * Marks the close as intentional so no reconnection is attempted.
329
+ */
330
+ disconnect(): void {
331
+ this.intentionalDisconnect = true;
332
+ if (this.reconnectTimer) {
333
+ clearTimeout(this.reconnectTimer);
334
+ this.reconnectTimer = null;
335
+ }
336
+ this.reconnectAttempts = 0;
337
+ if (this.ws) {
338
+ this.ws.close();
339
+ this.ws = null;
340
+ }
341
+ }
342
+
343
+ /**
344
+ * Get the current connection state
345
+ */
346
+ get readyState(): number {
347
+ return this.ws?.readyState ?? WebSocket.CLOSED;
348
+ }
349
+
350
+ /**
351
+ * Check if the WebSocket is connected
352
+ */
353
+ get isConnected(): boolean {
354
+ return this.ws?.readyState === WebSocket.OPEN;
355
+ }
356
+ }
357
+
358
+ /**
359
+ * Example usage:
360
+ *
361
+ * ```typescript
362
+ * const ws = new ChatWebSocket({
363
+ * url: 'ws://localhost:8080/api/chat/ws',
364
+ * authToken: 'Bearer xyz123',
365
+ * onOpen: () => console.log('Connected!'),
366
+ * onClose: () => console.log('Disconnected'),
367
+ * onError: (error) => console.error('Error:', error),
368
+ * });
369
+ *
370
+ * await ws.connect();
371
+ *
372
+ * ws.onMessage((message) => {
373
+ * if (message.type === 'token') {
374
+ * console.log('Token:', message.content);
375
+ * } else if (message.type === 'done') {
376
+ * console.log('Chat complete');
377
+ * }
378
+ * });
379
+ *
380
+ * ws.send('What happens in the opening scene?', {
381
+ * videoId: 'video-001',
382
+ * modelId: 'amazon.nova-pro-v1:0',
383
+ * });
384
+ * ```
385
+ */