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