@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
package/src/audio.ts ADDED
@@ -0,0 +1,934 @@
1
+ import {
2
+ BYTES_PER_SAMPLE,
3
+ HELLO_VERSION,
4
+ SAMPLE_RATE,
5
+ SAMPLES_PER_FRAME,
6
+ TAG_AI,
7
+ TAG_MIC,
8
+ encodeAudioFrame,
9
+ decodeAudioFrame,
10
+ buildBargeInMessage,
11
+ buildPlaybackPositionMessage,
12
+ type AudioFormat,
13
+ type AudioMetadataMessage,
14
+ type PhonemeInfo,
15
+ type WordPhonemeInfo,
16
+ type WordTimestampInfo,
17
+ type BargeInMessage,
18
+ type PlaybackPositionMessage,
19
+ } from './audioProtocol';
20
+ import { VisemeScheduler } from './visemeScheduler';
21
+
22
+ const FLOAT_DIVISOR = 32768;
23
+
24
+ const floatTo16BitPCM = (input: Float32Array): Int16Array => {
25
+ const output = new Int16Array(input.length);
26
+ for (let i = 0; i < input.length; i += 1) {
27
+ const s = Math.max(-1, Math.min(1, input[i]));
28
+ output[i] = s < 0 ? s * 32768 : s * 32767;
29
+ }
30
+ return output;
31
+ };
32
+
33
+ const resampleToTarget = (
34
+ input: Float32Array,
35
+ sourceRate: number,
36
+ targetRate: number = SAMPLE_RATE,
37
+ ): Int16Array => {
38
+ if (sourceRate === targetRate) {
39
+ return floatTo16BitPCM(input);
40
+ }
41
+
42
+ const ratio = targetRate / sourceRate;
43
+ const targetLength = Math.round(input.length * ratio);
44
+ const output = new Float32Array(targetLength);
45
+
46
+ for (let i = 0; i < targetLength; i += 1) {
47
+ const origin = i / ratio;
48
+ const index = Math.floor(origin);
49
+ const nextIndex = Math.min(index + 1, input.length - 1);
50
+ const weight = origin - index;
51
+ output[i] = input[index] * (1 - weight) + input[nextIndex] * weight;
52
+ }
53
+
54
+ return floatTo16BitPCM(output);
55
+ };
56
+
57
+ export class MicrophoneRecorder {
58
+ private audioContext: AudioContext | null = null;
59
+
60
+ private processor: ScriptProcessorNode | null = null;
61
+
62
+ private workletNode: AudioWorkletNode | null = null;
63
+
64
+ private source: MediaStreamAudioSourceNode | null = null;
65
+
66
+ private mediaStream: MediaStream | null = null;
67
+
68
+ private sampleBuffer: Int16Array = new Int16Array();
69
+
70
+ constructor(
71
+ private readonly onFrame: (frame: Uint8Array) => void,
72
+ private readonly onError?: (message: string) => void,
73
+ ) {}
74
+
75
+ /** Synchronously create the AudioContext and kick off `resume()` so iOS
76
+ * Safari unlocks audio while the user-gesture activation chain is still
77
+ * fresh. Idempotent — safe to call multiple times. Callers that already
78
+ * have an awaited code path before `start()` (e.g. an `await
79
+ * player.resume()` ahead of `await recorder.start()`) MUST call
80
+ * `prime()` from the synchronous prefix of the click handler, otherwise
81
+ * `start()`'s own internal `prime()` runs after the gesture has
82
+ * unwound and iOS leaves the context in `suspended` state.
83
+ *
84
+ * No I/O, no awaits, no permission prompts — just `new AudioContext`
85
+ * and a fire-and-forget `resume()`. */
86
+ prime(): void {
87
+ if (this.audioContext) return;
88
+ this.audioContext = new AudioContext({ sampleRate: SAMPLE_RATE });
89
+ void this.audioContext.resume();
90
+ }
91
+
92
+ async start(): Promise<void> {
93
+ if (this.mediaStream) {
94
+ // Already started — idempotent guard.
95
+ return;
96
+ }
97
+
98
+ // iOS Safari requires AudioContext creation + a resume() call inside
99
+ // the synchronous prefix of a user-gesture handler. We call prime()
100
+ // here as a safety net for callers that hit start() directly, but
101
+ // for callers with awaits between the click and start() (e.g. the
102
+ // /chat-ws path that awaits `player.resume()` first), prime() must
103
+ // be invoked from the click handler's synchronous prefix instead —
104
+ // by the time we reach this line, the gesture chain may already be
105
+ // unwound and the context would stay suspended.
106
+ this.prime();
107
+
108
+ try {
109
+ this.mediaStream = await navigator.mediaDevices.getUserMedia({
110
+ audio: {
111
+ echoCancellation: true,
112
+ noiseSuppression: true,
113
+ channelCount: 1,
114
+ sampleRate: SAMPLE_RATE,
115
+ sampleSize: BYTES_PER_SAMPLE * 8,
116
+ },
117
+ });
118
+ } catch (err) {
119
+ // Tear down the context we just created (or that was primed) so a
120
+ // permission denial doesn't leave a dangling suspended context
121
+ // behind, and so a retry from a fresh user gesture starts clean.
122
+ if (this.audioContext) {
123
+ void this.audioContext.close();
124
+ this.audioContext = null;
125
+ }
126
+ const message = err instanceof Error ? err.message : 'Microphone permission denied';
127
+ this.onError?.(message);
128
+ throw err;
129
+ }
130
+
131
+ // After the prime()-created context potentially fast-pathed above,
132
+ // assert the invariant for the type checker.
133
+ if (!this.audioContext) {
134
+ throw new Error('AudioContext missing after prime() — should never happen');
135
+ }
136
+ this.source = this.audioContext.createMediaStreamSource(this.mediaStream);
137
+
138
+ // Try AudioWorklet first (runs off main thread), fall back to ScriptProcessorNode
139
+ let useWorklet = false;
140
+ if (this.audioContext.audioWorklet) {
141
+ try {
142
+ await this.audioContext.audioWorklet.addModule('/audio-worklet-processor.js');
143
+ useWorklet = true;
144
+ } catch {
145
+ // AudioWorklet not supported or module failed to load — fall back
146
+ console.warn('AudioWorklet unavailable, falling back to ScriptProcessorNode');
147
+ }
148
+ }
149
+
150
+ if (useWorklet) {
151
+ this.workletNode = new AudioWorkletNode(this.audioContext, 'mic-processor');
152
+ this.workletNode.port.onmessage = (event: MessageEvent<Float32Array>) => {
153
+ // Guard: worklet message can arrive after stop() has nulled the context
154
+ if (!this.audioContext) return;
155
+ const pcm = resampleToTarget(event.data, this.audioContext.sampleRate);
156
+ this.enqueueSamples(pcm);
157
+ };
158
+ this.source.connect(this.workletNode);
159
+ // Connect worklet through silent gain to destination so it keeps processing
160
+ const silentGain = this.audioContext.createGain();
161
+ silentGain.gain.value = 0;
162
+ this.workletNode.connect(silentGain);
163
+ silentGain.connect(this.audioContext.destination);
164
+ } else {
165
+ this.processor = this.audioContext.createScriptProcessor(4096, 1, 1);
166
+ this.processor.onaudioprocess = (event) => {
167
+ const input = event.inputBuffer.getChannelData(0);
168
+ const pcm = resampleToTarget(input, event.inputBuffer.sampleRate);
169
+ this.enqueueSamples(pcm);
170
+ };
171
+ this.source.connect(this.processor);
172
+ this.processor.connect(this.audioContext.destination);
173
+ }
174
+
175
+ if (this.audioContext.state === 'suspended') {
176
+ await this.audioContext.resume();
177
+ }
178
+ }
179
+
180
+ stop(): void {
181
+ if (this.workletNode) {
182
+ // Drain the handler before disconnect so any browser-buffered
183
+ // messages already in flight don't run with a half-torn-down
184
+ // context. The `if (!this.audioContext) return;` null-check at the
185
+ // top of the worklet's onmessage already protects against the same
186
+ // failure mode, but clearing the handler first is the more
187
+ // defensive pattern.
188
+ this.workletNode.port.onmessage = null;
189
+ this.workletNode.disconnect();
190
+ this.workletNode = null;
191
+ }
192
+ if (this.processor) {
193
+ this.processor.disconnect();
194
+ this.processor = null;
195
+ }
196
+ if (this.source) {
197
+ this.source.disconnect();
198
+ this.source = null;
199
+ }
200
+ if (this.audioContext) {
201
+ void this.audioContext.close();
202
+ this.audioContext = null;
203
+ }
204
+ if (this.mediaStream) {
205
+ this.mediaStream.getTracks().forEach((track) => track.stop());
206
+ this.mediaStream = null;
207
+ }
208
+ this.sampleBuffer = new Int16Array();
209
+ }
210
+
211
+ private enqueueSamples(pcm: Int16Array): void {
212
+ const combined = new Int16Array(this.sampleBuffer.length + pcm.length);
213
+ combined.set(this.sampleBuffer);
214
+ combined.set(pcm, this.sampleBuffer.length);
215
+ this.sampleBuffer = combined;
216
+
217
+ while (this.sampleBuffer.length >= SAMPLES_PER_FRAME) {
218
+ const frameSamples = this.sampleBuffer.slice(0, SAMPLES_PER_FRAME);
219
+ const remaining = this.sampleBuffer.slice(SAMPLES_PER_FRAME);
220
+ this.sampleBuffer = remaining;
221
+
222
+ const tagged = encodeAudioFrame(TAG_MIC, frameSamples);
223
+ this.onFrame(tagged);
224
+ }
225
+ }
226
+ }
227
+
228
+ export class AudioFramePlayer {
229
+ private context: AudioContext;
230
+
231
+ private gainNode: GainNode;
232
+
233
+ private activeSources = new Set<AudioBufferSourceNode>();
234
+
235
+ private queuedTime = 0;
236
+
237
+ /** Timestamp (AudioContext.currentTime) when the first frame started playing. */
238
+ public playbackOrigin = 0;
239
+
240
+ /** Start time of the first audio frame in the current chunk.
241
+ * Reset each time getChunkStartTime() is called (consumed by viseme scheduler). */
242
+ private chunkStartTime = 0;
243
+
244
+ private chunkStartTimeSet = false;
245
+
246
+ constructor() {
247
+ this.context = new AudioContext({ sampleRate: SAMPLE_RATE });
248
+ this.gainNode = this.context.createGain();
249
+ this.gainNode.connect(this.context.destination);
250
+ }
251
+
252
+ /** Return the playback time elapsed since the first frame was scheduled. */
253
+ getPlaybackTime(): number {
254
+ if (this.playbackOrigin === 0) return 0;
255
+ return this.context.currentTime - this.playbackOrigin;
256
+ }
257
+
258
+ /**
259
+ * Return the AudioContext time at which the first frame was scheduled,
260
+ * or 0 if no frame has played yet. Used by `AudioPipeline` to convert
261
+ * absolute chunk start times into the relative coordinate frame the
262
+ * playback tracker uses for word timestamps.
263
+ */
264
+ getPlaybackOrigin(): number {
265
+ return this.playbackOrigin;
266
+ }
267
+
268
+ /** Expose the AudioContext for external time queries. */
269
+ getContext(): AudioContext {
270
+ return this.context;
271
+ }
272
+
273
+ /** Get the AudioContext time at which the next queued frame will start. */
274
+ getNextFrameStartTime(): number {
275
+ return Math.max(this.context.currentTime, this.queuedTime);
276
+ }
277
+
278
+ /** Get the start time of the first audio frame in the current chunk.
279
+ * Call this from the audio_metadata handler to schedule visemes at the
280
+ * correct time. Resets after each call so the next chunk gets a fresh start. */
281
+ getChunkStartTime(): number {
282
+ const t = this.chunkStartTime || this.getNextFrameStartTime();
283
+ this.chunkStartTime = 0;
284
+ this.chunkStartTimeSet = false;
285
+ return t;
286
+ }
287
+
288
+ /** True iff a binary frame has set `chunkStartTime` for the current chunk.
289
+ * Callers that schedule visemes can use this to defer scheduling when
290
+ * audio_metadata races ahead of the binary frames (Inworld ASYNC mode):
291
+ * without binary, `getChunkStartTime()` falls back to `currentTime`,
292
+ * which anchors visemes to "now" instead of the actual chunk start. */
293
+ hasChunkStart(): boolean {
294
+ return this.chunkStartTimeSet;
295
+ }
296
+
297
+ async resume(): Promise<void> {
298
+ if (this.context.state === 'suspended') {
299
+ await this.context.resume();
300
+ }
301
+ }
302
+
303
+ /** Immediately silence and stop all scheduled/playing audio. */
304
+ clearQueue(): void {
305
+ // Stopping each source is sufficient to silence playback — the
306
+ // gainNode stays in the chain only as a stable mix point.
307
+ for (const src of this.activeSources) {
308
+ try {
309
+ src.stop();
310
+ } catch {
311
+ /* already ended */
312
+ }
313
+ }
314
+ this.activeSources.clear();
315
+ this.queuedTime = this.context.currentTime;
316
+ this.playbackOrigin = 0;
317
+ this.chunkStartTime = 0;
318
+ this.chunkStartTimeSet = false;
319
+ }
320
+
321
+ async stop(): Promise<void> {
322
+ // Reuse clearQueue so the source-stop loop only lives in one place,
323
+ // then zero out the queuedTime watermark and close the context.
324
+ this.clearQueue();
325
+ this.queuedTime = 0;
326
+ await this.context.close();
327
+ }
328
+
329
+ playFrame(data: ArrayBuffer): void {
330
+ const { tag, audio } = decodeAudioFrame(data);
331
+ if (tag !== TAG_AI) {
332
+ return;
333
+ }
334
+
335
+ const floatData = new Float32Array(audio.length);
336
+ for (let i = 0; i < audio.length; i += 1) {
337
+ floatData[i] = audio[i] / FLOAT_DIVISOR;
338
+ }
339
+
340
+ const buffer = this.context.createBuffer(1, floatData.length, SAMPLE_RATE);
341
+ buffer.copyToChannel(floatData, 0);
342
+
343
+ const source = this.context.createBufferSource();
344
+ source.buffer = buffer;
345
+ source.connect(this.gainNode);
346
+
347
+ // Track source so barge-in can stop it cleanly
348
+ this.activeSources.add(source);
349
+ source.onended = () => this.activeSources.delete(source);
350
+
351
+ const startTime = Math.max(this.context.currentTime, this.queuedTime);
352
+
353
+ // Record the origin time when the very first frame is scheduled
354
+ if (this.playbackOrigin === 0) {
355
+ this.playbackOrigin = startTime;
356
+ }
357
+
358
+ // Track the start time of the first frame in this chunk.
359
+ // audio_metadata arrives AFTER the binary frames for the same chunk,
360
+ // so this captures the correct base time for viseme scheduling.
361
+ if (!this.chunkStartTimeSet) {
362
+ this.chunkStartTime = startTime;
363
+ this.chunkStartTimeSet = true;
364
+ }
365
+
366
+ source.start(startTime);
367
+ this.queuedTime = startTime + buffer.duration;
368
+ }
369
+ }
370
+
371
+
372
+ export const buildHelloPayload = ({
373
+ videoId,
374
+ personaId,
375
+ mode = 'tts_stt',
376
+ audioFormat = 'PCM16',
377
+ enableAudioMarkups = false,
378
+ voiceTemperature = 1.0,
379
+ speakingRate = 1.0,
380
+ voiceId = 'Ashley',
381
+ systemPrompt,
382
+ systemPromptOverride = false,
383
+ modelId,
384
+ ttsModelId,
385
+ }: {
386
+ videoId?: string;
387
+ personaId?: string;
388
+ mode?: 'tts_stt' | 'text';
389
+ audioFormat?: AudioFormat;
390
+ enableAudioMarkups?: boolean;
391
+ voiceTemperature?: number;
392
+ speakingRate?: number;
393
+ voiceId?: string;
394
+ systemPrompt?: string;
395
+ systemPromptOverride?: boolean;
396
+ modelId?: string;
397
+ ttsModelId?: string;
398
+ }) => ({
399
+ action: 'hello' as const,
400
+ version: HELLO_VERSION,
401
+ videoId,
402
+ personaId,
403
+ mode,
404
+ audioFormat,
405
+ enableAudioMarkups,
406
+ voiceTemperature,
407
+ speakingRate,
408
+ voiceId,
409
+ ...(systemPrompt ? { systemPrompt, systemPromptOverride } : {}),
410
+ ...(modelId ? { modelId } : {}),
411
+ ...(ttsModelId ? { ttsModelId } : {}),
412
+ });
413
+
414
+ export type HelloPayload = ReturnType<typeof buildHelloPayload>;
415
+
416
+ // ─────────────────────────────────────────────────────────────
417
+ // Playback Tracking for Barge-In Support
418
+ // ─────────────────────────────────────────────────────────────
419
+
420
+ /**
421
+ * Result of an interrupt operation.
422
+ */
423
+ export interface InterruptResult {
424
+ spokenText: string;
425
+ interruptedAt: number;
426
+ wordsSpoken: string[];
427
+ }
428
+
429
+ /**
430
+ * PlaybackTracker - Tracks word-level playback position for barge-in support.
431
+ *
432
+ * Accumulates word timestamps from audio metadata messages and provides
433
+ * information about what has been spoken at any given playback position.
434
+ */
435
+ export class PlaybackTracker {
436
+ private wordTimestamps: WordTimestampInfo[] = [];
437
+
438
+ private currentPosition: number = 0;
439
+
440
+ /**
441
+ * Add word timestamps from an audio metadata message.
442
+ */
443
+ addWordTimestamps(timestamps: WordTimestampInfo[]): void {
444
+ this.wordTimestamps.push(...timestamps);
445
+ }
446
+
447
+ /**
448
+ * Update the current playback position.
449
+ */
450
+ updatePosition(position: number): void {
451
+ this.currentPosition = position;
452
+ }
453
+
454
+ /**
455
+ * Get the current playback position.
456
+ */
457
+ getPosition(): number {
458
+ return this.currentPosition;
459
+ }
460
+
461
+ /**
462
+ * Get all words that have been completely spoken (end time <= current position).
463
+ */
464
+ getSpokenWords(): string[] {
465
+ return this.wordTimestamps
466
+ .filter((ts) => ts.endTime <= this.currentPosition)
467
+ .map((ts) => ts.word);
468
+ }
469
+
470
+ /**
471
+ * Get the word currently being spoken (if any).
472
+ */
473
+ getCurrentWord(): string | null {
474
+ const current = this.wordTimestamps.find(
475
+ (ts) => ts.startTime <= this.currentPosition && ts.endTime > this.currentPosition,
476
+ );
477
+ return current ? current.word : null;
478
+ }
479
+
480
+ /**
481
+ * Get all word timestamps for highlighting.
482
+ */
483
+ getAllTimestamps(): WordTimestampInfo[] {
484
+ return [...this.wordTimestamps];
485
+ }
486
+
487
+ /**
488
+ * Handle an interrupt and return what was spoken.
489
+ */
490
+ interrupt(): InterruptResult {
491
+ const wordsSpoken = this.getSpokenWords();
492
+ const spokenText = wordsSpoken.join(' ');
493
+
494
+ return {
495
+ spokenText,
496
+ interruptedAt: this.currentPosition,
497
+ wordsSpoken,
498
+ };
499
+ }
500
+
501
+ /**
502
+ * Reset the tracker for a new turn.
503
+ */
504
+ reset(): void {
505
+ this.wordTimestamps = [];
506
+ this.currentPosition = 0;
507
+ }
508
+ }
509
+
510
+ /**
511
+ * AudioSessionClient - WebSocket client with barge-in support.
512
+ *
513
+ * Wraps a WebSocket connection and provides methods for:
514
+ * - Sending playback position updates
515
+ * - Triggering barge-in interruptions
516
+ * - Tracking word-level playback
517
+ */
518
+ export class AudioSessionClient {
519
+ private ws: WebSocket;
520
+
521
+ private playbackTracker: PlaybackTracker;
522
+
523
+ private positionUpdateInterval: ReturnType<typeof setInterval> | null = null;
524
+
525
+ private audioPlayer: AudioFramePlayer | null = null;
526
+
527
+ constructor(ws: WebSocket) {
528
+ this.ws = ws;
529
+ this.playbackTracker = new PlaybackTracker();
530
+ }
531
+
532
+ /**
533
+ * Set the audio player for coordinated barge-in.
534
+ */
535
+ setAudioPlayer(player: AudioFramePlayer): void {
536
+ this.audioPlayer = player;
537
+ }
538
+
539
+ /**
540
+ * Get the playback tracker for word highlighting.
541
+ */
542
+ getPlaybackTracker(): PlaybackTracker {
543
+ return this.playbackTracker;
544
+ }
545
+
546
+ /**
547
+ * Add word timestamps from an audio metadata message.
548
+ */
549
+ addWordTimestamps(timestamps: WordTimestampInfo[]): void {
550
+ this.playbackTracker.addWordTimestamps(timestamps);
551
+ }
552
+
553
+ /**
554
+ * Start sending periodic playback position updates.
555
+ * Uses the audio player's actual playback time when available so the
556
+ * server's barge-in arbitration works against the real playhead, not
557
+ * a stale tracker value.
558
+ * @param intervalMs - Update interval in milliseconds (default: 100ms)
559
+ */
560
+ startPlaybackTracking(intervalMs: number = 100): void {
561
+ this.stopPlaybackTracking();
562
+
563
+ this.positionUpdateInterval = setInterval(() => {
564
+ const position = this.audioPlayer
565
+ ? this.audioPlayer.getPlaybackTime()
566
+ : this.playbackTracker.getPosition();
567
+ this.playbackTracker.updatePosition(position);
568
+ this.sendPlaybackPosition(position);
569
+ }, intervalMs);
570
+ }
571
+
572
+ /**
573
+ * Stop sending playback position updates.
574
+ */
575
+ stopPlaybackTracking(): void {
576
+ if (this.positionUpdateInterval) {
577
+ clearInterval(this.positionUpdateInterval);
578
+ this.positionUpdateInterval = null;
579
+ }
580
+ }
581
+
582
+ /**
583
+ * Send a playback position update to the server.
584
+ */
585
+ sendPlaybackPosition(position: number): void {
586
+ if (this.ws.readyState === WebSocket.OPEN) {
587
+ const msg = buildPlaybackPositionMessage(position);
588
+ this.ws.send(JSON.stringify(msg));
589
+ }
590
+ }
591
+
592
+ /**
593
+ * Trigger a barge-in interruption.
594
+ * Clears the audio queue and notifies the server.
595
+ */
596
+ async bargeIn(): Promise<InterruptResult> {
597
+ // Get what was spoken before clearing
598
+ const result = this.playbackTracker.interrupt();
599
+
600
+ // Clear audio queue
601
+ if (this.audioPlayer) {
602
+ this.audioPlayer.clearQueue();
603
+ }
604
+
605
+ // Stop position tracking
606
+ this.stopPlaybackTracking();
607
+
608
+ // Send barge-in message to server
609
+ if (this.ws.readyState === WebSocket.OPEN) {
610
+ const msg = buildBargeInMessage();
611
+ this.ws.send(JSON.stringify(msg));
612
+ }
613
+
614
+ // Reset tracker for next turn
615
+ this.playbackTracker.reset();
616
+
617
+ return result;
618
+ }
619
+
620
+ /**
621
+ * Reset for a new assistant turn.
622
+ */
623
+ resetForNewTurn(): void {
624
+ this.playbackTracker.reset();
625
+ this.stopPlaybackTracking();
626
+ }
627
+
628
+ /**
629
+ * Cleanup resources.
630
+ */
631
+ cleanup(): void {
632
+ this.stopPlaybackTracking();
633
+ this.playbackTracker.reset();
634
+ }
635
+ }
636
+
637
+ // ─────────────────────────────────────────────────────────────
638
+ // AudioPipeline — orchestrates player, visemes, and session
639
+ // ─────────────────────────────────────────────────────────────
640
+
641
+ /**
642
+ * Tolerance (seconds) for deciding whether a fresh chunk's first phoneme
643
+ * starts "before" the previous chunk's last phoneme ended. Anything
644
+ * inside this 10ms window is treated as continuation of the same
645
+ * sentence; anything earlier is treated as a new sentence and re-anchors
646
+ * the timeline.
647
+ */
648
+ const SENTENCE_OVERLAP_EPSILON_S = 0.01;
649
+
650
+ /** Walk a phoneme message from the back, return the last phoneme with
651
+ * non-empty `phones`. Returns null only when every word is empty. */
652
+ function findLastPhone(words: WordPhonemeInfo[]): PhonemeInfo | null {
653
+ for (let i = words.length - 1; i >= 0; i -= 1) {
654
+ const phones = words[i]?.phones;
655
+ if (phones && phones.length > 0) return phones[phones.length - 1];
656
+ }
657
+ return null;
658
+ }
659
+
660
+ /**
661
+ * AudioPipeline bundles AudioFramePlayer, VisemeScheduler, and
662
+ * AudioSessionClient into a single reusable unit with sentence-boundary
663
+ * viseme scheduling and barge-in tracking.
664
+ *
665
+ * Used so audio/viseme handling stays in one place across consumers
666
+ * (chat-ws page, future 3D character integration, etc.).
667
+ */
668
+ export class AudioPipeline {
669
+ // These are exposed so consumers (today: chat-ws/page.tsx mid-migration,
670
+ // tomorrow: tests + 3D integrations) can read state without going through
671
+ // accessor wrappers. `readonly` prevents reassignment of the refs but
672
+ // does NOT prevent calling lifecycle methods on them — consumers must
673
+ // route teardown through `destroy()` rather than calling `player.stop()`
674
+ // / `visemeScheduler.destroy()` directly, otherwise `_sessionClient`
675
+ // and the orchestrator's sentence-state will leak.
676
+ readonly player: AudioFramePlayer;
677
+
678
+ readonly visemeScheduler: VisemeScheduler;
679
+
680
+ // sessionClient is read-only externally (write only via `attachSession`).
681
+ // Allowing direct write would let callers null it out and bypass the
682
+ // orchestrator's reset logic.
683
+ private _sessionClient: AudioSessionClient | null = null;
684
+
685
+ get sessionClient(): AudioSessionClient | null {
686
+ return this._sessionClient;
687
+ }
688
+
689
+ private sentenceStartTime: number | null = null;
690
+
691
+ private lastPhonemeEnd = 0;
692
+
693
+ // Metadata that arrived before any binary frame for the current chunk.
694
+ // Inworld ASYNC mode delivers audio_metadata first, so without buffering
695
+ // the scheduler would anchor to AudioContext.currentTime (= "now") instead
696
+ // of the actual chunk start time set by the binary frame, producing a
697
+ // 20–100 ms forward drift of visemes vs audio.
698
+ private pendingMetadata: AudioMetadataMessage[] = [];
699
+
700
+ constructor(onVisemeChange: (viseme: string) => void) {
701
+ this.player = new AudioFramePlayer();
702
+ this.visemeScheduler = new VisemeScheduler(
703
+ this.player.getContext(),
704
+ onVisemeChange,
705
+ );
706
+ }
707
+
708
+ async resume(): Promise<void> {
709
+ await this.player.resume();
710
+ }
711
+
712
+ /**
713
+ * Attach a WebSocket for barge-in support.
714
+ *
715
+ * Safe to call multiple times — on a reconnect the previous session's
716
+ * `setInterval` (if any) is cleaned up before swapping in the new one,
717
+ * otherwise it would keep ticking against a dead WebSocket.
718
+ *
719
+ * **Caller responsibility:** if you need the server's barge-in
720
+ * arbitration to work, also call
721
+ * `sessionClient.startPlaybackTracking()` after this — the position-
722
+ * update interval is opt-in. Without it, the server only learns about
723
+ * playback position from `handleBinaryFrame` writes, which is enough
724
+ * for end-of-turn arbitration but not for a smooth barge-in window.
725
+ */
726
+ attachSession(ws: WebSocket): void {
727
+ this._sessionClient?.cleanup();
728
+ this._sessionClient = new AudioSessionClient(ws);
729
+ this._sessionClient.setAudioPlayer(this.player);
730
+ }
731
+
732
+ /** Handle an incoming binary TTS audio frame. */
733
+ handleBinaryFrame(data: ArrayBuffer): void {
734
+ try {
735
+ const state = this.player.getContext().state;
736
+ // 'closed' shouldn't normally happen here because callers go
737
+ // through `destroy()` before letting the context close, but a
738
+ // stray frame after a teardown race would crash `playFrame` with
739
+ // an InvalidStateError. Drop it explicitly.
740
+ if (state === 'closed') {
741
+ return;
742
+ }
743
+ if (state === 'running') {
744
+ this.player.playFrame(data);
745
+ this.updateTrackerPosition();
746
+ this.drainPendingMetadata();
747
+ } else {
748
+ // Suspended-context path (typical: first frame before any user
749
+ // gesture). `playFrame` runs after `resume()` resolves, so a
750
+ // synchronous follow-up frame can land first and write
751
+ // `chunkStartTimeSet` before this one. This is acceptable
752
+ // because the chunk-start anchor is only used for viseme
753
+ // scheduling, which receives metadata in the same chunk as
754
+ // these frames — the frames within a chunk all share an audio
755
+ // source, so a one-frame misattribution at the very start
756
+ // produces a viseme drift well under one phoneme. If this ever
757
+ // shows up as audible drift, switch to a small in-memory queue
758
+ // here that drains in arrival order on resume.
759
+ this.player
760
+ .resume()
761
+ .then(() => {
762
+ this.player.playFrame(data);
763
+ // Update tracker INSIDE then() so the position read is taken
764
+ // after playFrame schedules — outside, we'd write a stale
765
+ // position before the frame even reaches the audio graph.
766
+ this.updateTrackerPosition();
767
+ this.drainPendingMetadata();
768
+ })
769
+ .catch((err) =>
770
+ console.error('[AudioPipeline] Failed to resume audio:', err),
771
+ );
772
+ }
773
+ } catch (err) {
774
+ console.error('[AudioPipeline] Failed to play audio frame:', err);
775
+ }
776
+ }
777
+
778
+ /**
779
+ * Push the current playhead into the session's playback tracker in the
780
+ * same coordinate frame everything else uses (relative — elapsed since
781
+ * `playbackOrigin`). `addWordTimestamps` stores word ranges relative
782
+ * to `playbackOrigin` too, so `getSpokenWords` compares apples to apples.
783
+ */
784
+ private updateTrackerPosition(): void {
785
+ if (this._sessionClient) {
786
+ this._sessionClient
787
+ .getPlaybackTracker()
788
+ .updatePosition(this.player.getPlaybackTime());
789
+ }
790
+ }
791
+
792
+ /** Handle an audio_metadata JSON message (visemes + word timestamps).
793
+ *
794
+ * In Inworld ASYNC mode the metadata frame can arrive before any binary
795
+ * audio frames for the chunk. If we scheduled now, `getChunkStartTime()`
796
+ * would fall back to `AudioContext.currentTime`, anchoring visemes ~20–
797
+ * 100 ms ahead of the audio. Buffer until a binary frame lands and the
798
+ * real chunk start is known. */
799
+ handleAudioMetadata(msg: AudioMetadataMessage): void {
800
+ if (!this.player.hasChunkStart()) {
801
+ this.pendingMetadata.push(msg);
802
+ return;
803
+ }
804
+ this.processAudioMetadata(msg);
805
+ }
806
+
807
+ private drainPendingMetadata(): void {
808
+ // Drain ONE message per binary-frame landing. ``processAudioMetadata``
809
+ // calls ``getChunkStartTime()`` which consumes-and-clears the
810
+ // player's ``chunkStartTime``; if we drained multiple queued
811
+ // messages back-to-back here, only the first would receive the
812
+ // real chunk start — subsequent messages (which may belong to
813
+ // *different* chunks whose binary frames haven't landed yet)
814
+ // would fall back to ``getNextFrameStartTime()`` and re-introduce
815
+ // the multi-chunk drift this buffer is meant to prevent (Codex
816
+ // P2 on PR #168). The next binary frame re-arms ``hasChunkStart``
817
+ // and triggers another drain for the next queued message.
818
+ if (this.pendingMetadata.length === 0) return;
819
+ const msg = this.pendingMetadata.shift();
820
+ if (msg !== undefined) {
821
+ this.processAudioMetadata(msg);
822
+ }
823
+ }
824
+
825
+ private processAudioMetadata(msg: AudioMetadataMessage): void {
826
+ const chunkStartTime = this.player.getChunkStartTime();
827
+
828
+ // Word timestamps must be stored in the same coordinate frame as
829
+ // `currentPosition` (relative — elapsed since playbackOrigin), or
830
+ // `PlaybackTracker.getSpokenWords()` will silently always return [].
831
+ // If `playbackOrigin` is still 0 (metadata raced ahead of any binary
832
+ // frames), fall back to chunkStartTime so the very-first-chunk math
833
+ // still produces a 0-based offset.
834
+ if (msg.wordTimestamps?.length && this.sessionClient) {
835
+ const origin = this.player.getPlaybackOrigin() || chunkStartTime;
836
+ const chunkRelativeStart = chunkStartTime - origin;
837
+ this.sessionClient.addWordTimestamps(
838
+ msg.wordTimestamps.map((ts) => ({
839
+ word: ts.word,
840
+ startTime: chunkRelativeStart + ts.startTime,
841
+ endTime: chunkRelativeStart + ts.endTime,
842
+ })),
843
+ );
844
+ }
845
+
846
+ // Viseme scheduling with sentence-boundary detection: if the next
847
+ // chunk's first phoneme starts before the previous chunk's last
848
+ // phoneme ended, treat it as a new sentence and re-anchor the
849
+ // sentence start time so visemes don't overlap with the tail.
850
+ //
851
+ // The lastPhonemeEnd update lives outside the firstPhone branch on
852
+ // purpose — if a server message has a non-empty phonemes array but
853
+ // an empty phones[] in its first word, we still want to advance our
854
+ // tail anchor by scanning from the back, otherwise the next chunk's
855
+ // sentence-boundary test runs against stale data.
856
+ if (msg.phonemes?.length) {
857
+ const lastNonEmptyPhone = findLastPhone(msg.phonemes);
858
+ if (lastNonEmptyPhone) {
859
+ // Capture the new tail before deciding whether to schedule, so
860
+ // a malformed-first-word message still advances the anchor.
861
+ const candidateTail = lastNonEmptyPhone.startTime + lastNonEmptyPhone.duration;
862
+
863
+ const firstPhone = msg.phonemes[0]?.phones?.[0];
864
+ if (firstPhone) {
865
+ const rawFirstStart = firstPhone.startTime;
866
+ const isNewSentence =
867
+ this.sentenceStartTime === null ||
868
+ rawFirstStart < this.lastPhonemeEnd - SENTENCE_OVERLAP_EPSILON_S;
869
+
870
+ if (isNewSentence) {
871
+ this.sentenceStartTime = chunkStartTime;
872
+ }
873
+
874
+ this.visemeScheduler.scheduleChunk(
875
+ msg.phonemes,
876
+ this.sentenceStartTime!,
877
+ );
878
+ }
879
+
880
+ this.lastPhonemeEnd = candidateTail;
881
+ }
882
+ }
883
+ }
884
+
885
+ /** Reset state for a new conversational turn. */
886
+ resetTurn(): void {
887
+ this.sentenceStartTime = null;
888
+ this.lastPhonemeEnd = 0;
889
+ this.pendingMetadata = [];
890
+ this.sessionClient?.resetForNewTurn();
891
+ }
892
+
893
+ /**
894
+ * Handle barge-in: notify the server, clear local audio, clear visemes.
895
+ *
896
+ * When a session is attached, delegates to `AudioSessionClient.bargeIn()`
897
+ * which sends the `barge_in` WebSocket action to the server, clears the
898
+ * player queue, stops position tracking, and resets the playback tracker.
899
+ * Without a session we still clear local audio/visemes so the UI is sane,
900
+ * but the server has no way to know — the next chunk it streams will
901
+ * resume playback.
902
+ *
903
+ * Returns the `InterruptResult` describing what was spoken when a session
904
+ * is attached; returns null when there is no session.
905
+ */
906
+ async bargeIn(): Promise<InterruptResult | null> {
907
+ let result: InterruptResult | null = null;
908
+ if (this.sessionClient) {
909
+ result = await this.sessionClient.bargeIn();
910
+ } else {
911
+ this.player.clearQueue();
912
+ }
913
+ this.visemeScheduler.clear();
914
+ this.sentenceStartTime = null;
915
+ this.lastPhonemeEnd = 0;
916
+ this.pendingMetadata = [];
917
+ return result;
918
+ }
919
+
920
+ /** Clean up all resources. */
921
+ async destroy(): Promise<void> {
922
+ this._sessionClient?.cleanup();
923
+ this._sessionClient = null;
924
+ this.visemeScheduler.destroy();
925
+ await this.player.stop();
926
+ this.sentenceStartTime = null;
927
+ this.lastPhonemeEnd = 0;
928
+ this.pendingMetadata = [];
929
+ }
930
+ }
931
+
932
+ // Re-export message types for convenience
933
+ export type { WordTimestampInfo, BargeInMessage, PlaybackPositionMessage };
934
+