@convai/web-sdk 2.0.2 → 2.1.0-beta.1

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.
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Plays a character's voice delivered over the data channel
3
+ * (`audioRouting: 'data_only'`): `audio-data` chunks of 16-bit PCM go into ONE
4
+ * continuous ring buffer played by an AudioWorklet (the web counterpart of the
5
+ * Unreal plugin's USoundWaveProcedural), so chunks join with no seams.
6
+ *
7
+ * A {@link StreamController} decides when each reply starts, pauses and resumes;
8
+ * a pause is placed on the last silent stretch already buffered, never mid-word.
9
+ * The player is the source of truth for "the bot is speaking" on this path: the
10
+ * server's speaking flags follow when it SENT the audio, which is seconds before
11
+ * a buffered reply is heard.
12
+ *
13
+ * Embody-style consumers clock lipsync from {@link DataAudioPlayer.getSynchronizationSources},
14
+ * which mirrors an RTCRtpReceiver's: the reply's heard position in 48 kHz RTP units.
15
+ */
16
+ import { EventEmitter } from "./EventEmitter.js";
17
+ import { StreamController, type StreamControllerOptions, type StreamState } from "./streamController.js";
18
+ import type { AudioDataEvent, DataAudioPlayback } from "./types.js";
19
+ /** Where the samples go. The default is an AudioWorklet ring buffer; tests use a fake. */
20
+ export interface DataAudioSink {
21
+ readonly sampleRate: number;
22
+ /** Append samples to the stream. */
23
+ push(samples: Float32Array): void;
24
+ /** Start (or resume) consuming the stream. */
25
+ play(): void;
26
+ /** Stop consuming when the read position reaches `index` (immediately if already past it). */
27
+ pauseAt(index: number): void;
28
+ /** Drop everything not yet played. */
29
+ clear(): void;
30
+ setMuted(muted: boolean): void;
31
+ /** RMS of what is being played, 0–1; null before audio can be read. */
32
+ level(): number | null;
33
+ /** Seconds between a sample being consumed and being heard. */
34
+ outputLatency(): number;
35
+ /** The sink reports its read position (absolute sample index) and whether it is playing. */
36
+ onReport(cb: (read: number, playing: boolean) => void): void;
37
+ /** The sink ran out while playing. */
38
+ onUnderrun(cb: (read: number) => void): void;
39
+ resume(): Promise<void>;
40
+ dispose(): void;
41
+ }
42
+ export interface DataAudioPlayerOptions {
43
+ controller?: Partial<StreamControllerOptions>;
44
+ /** Build the sink for a sample rate. Default: an AudioWorklet ring buffer. */
45
+ createSink?: (sampleRate: number) => Promise<DataAudioSink>;
46
+ /** Wall clock in seconds. */
47
+ now?: () => number;
48
+ /**
49
+ * With no word from the server on whether it is still sending: a reply with no
50
+ * new audio for this long, s, is treated as fully arrived. Default 1.5.
51
+ */
52
+ idleEnd?: number;
53
+ /**
54
+ * While the server says it is still sending, a gap in delivery is a slow link,
55
+ * not the end of the reply; only a gap this long, s, ends it. Default 10.
56
+ */
57
+ stallEnd?: number;
58
+ }
59
+ export interface DataAudioStats {
60
+ chunks: number;
61
+ pauses: number;
62
+ underruns: number;
63
+ }
64
+ /** Decode a base64 16-bit little-endian PCM chunk to mono Float32. */
65
+ export declare function decodePcm16(base64: string, channels: number): Float32Array;
66
+ export declare class DataAudioPlayer extends EventEmitter implements DataAudioPlayback {
67
+ readonly controller: StreamController;
68
+ readonly stats: DataAudioStats;
69
+ private readonly makeSink;
70
+ private readonly now;
71
+ private readonly idleEnd;
72
+ private readonly stallEnd;
73
+ /** The server's speaking flag: true sending, false done sending, null never heard. */
74
+ private serverSending;
75
+ private sink;
76
+ private sinkPromise;
77
+ private pending;
78
+ private muted;
79
+ private read;
80
+ private readAt;
81
+ private playing;
82
+ private written;
83
+ private replyStart;
84
+ private replyPcm;
85
+ private announced;
86
+ private lastChunkAt;
87
+ private heardStarted;
88
+ private endedAt;
89
+ private rtpBase;
90
+ private timer;
91
+ constructor(options?: DataAudioPlayerOptions);
92
+ /** Where playback is in the open reply's lifecycle. */
93
+ get state(): StreamState;
94
+ /** Queue an audio-data chunk. */
95
+ pushChunk(chunk: AudioDataEvent): void;
96
+ /** The turn announced the reply's audio length (blendshape-turn-stats). */
97
+ setTurnTotal(seconds: number): void;
98
+ /** The server's own speaking flag: true while it is still sending this reply. */
99
+ setServerSpeaking(speaking: boolean): void;
100
+ /** Lipsync seconds that arrived for the open reply. */
101
+ addFrames(seconds: number): void;
102
+ /** Drop everything (an interruption). */
103
+ clear(): void;
104
+ setMuted(muted: boolean): void;
105
+ /** Resume the audio context (call from a user gesture if the page blocks autoplay). */
106
+ resume(): Promise<void>;
107
+ /** Seconds of the open reply heard so far; null before it starts. Holds through a pause, runs on 3 s past the end. */
108
+ position(): number | null;
109
+ /** RMS of the voice now playing; null when nothing can be read. */
110
+ level(): number | null;
111
+ /** Seconds buffered ahead of what is heard. */
112
+ queuedSeconds(): number;
113
+ /** RTCRtpReceiver-shaped clock: the open reply's heard position in 48 kHz RTP units. */
114
+ getSynchronizationSources(): Array<{
115
+ rtpTimestamp: number;
116
+ timestamp: number;
117
+ audioLevel?: number;
118
+ }>;
119
+ dispose(): void;
120
+ private ensureSink;
121
+ private flushPending;
122
+ private beginReply;
123
+ private checkEnded;
124
+ private heardIndex;
125
+ private replyPlayed;
126
+ private tick;
127
+ /** The last silent window in the buffered audio between two sample indices; null if none. */
128
+ private lastSilence;
129
+ }
130
+ /** An AudioWorklet ring buffer at the stream's own sample rate (no per-chunk resampling). */
131
+ export declare function createWorkletSink(sampleRate: number): Promise<DataAudioSink>;
@@ -0,0 +1,397 @@
1
+ /**
2
+ * Plays a character's voice delivered over the data channel
3
+ * (`audioRouting: 'data_only'`): `audio-data` chunks of 16-bit PCM go into ONE
4
+ * continuous ring buffer played by an AudioWorklet (the web counterpart of the
5
+ * Unreal plugin's USoundWaveProcedural), so chunks join with no seams.
6
+ *
7
+ * A {@link StreamController} decides when each reply starts, pauses and resumes;
8
+ * a pause is placed on the last silent stretch already buffered, never mid-word.
9
+ * The player is the source of truth for "the bot is speaking" on this path: the
10
+ * server's speaking flags follow when it SENT the audio, which is seconds before
11
+ * a buffered reply is heard.
12
+ *
13
+ * Embody-style consumers clock lipsync from {@link DataAudioPlayer.getSynchronizationSources},
14
+ * which mirrors an RTCRtpReceiver's: the reply's heard position in 48 kHz RTP units.
15
+ */
16
+ import { EventEmitter } from "./EventEmitter.js";
17
+ import { StreamController } from "./streamController.js";
18
+ const RTP_RATE = 48000;
19
+ const SILENCE_RMS = 0.008;
20
+ const SILENCE_WINDOW = 0.03;
21
+ /** Decode a base64 16-bit little-endian PCM chunk to mono Float32. */
22
+ export function decodePcm16(base64, channels) {
23
+ const bin = atob(base64);
24
+ const frames = Math.floor(bin.length / 2 / Math.max(1, channels));
25
+ const out = new Float32Array(frames);
26
+ for (let i = 0; i < frames; i++) {
27
+ let sum = 0;
28
+ for (let c = 0; c < channels; c++) {
29
+ const k = 2 * (i * channels + c);
30
+ let v = bin.charCodeAt(k) | (bin.charCodeAt(k + 1) << 8);
31
+ if (v >= 32768)
32
+ v -= 65536;
33
+ sum += v / 32768;
34
+ }
35
+ out[i] = sum / Math.max(1, channels);
36
+ }
37
+ return out;
38
+ }
39
+ export class DataAudioPlayer extends EventEmitter {
40
+ constructor(options = {}) {
41
+ super();
42
+ this.stats = { chunks: 0, pauses: 0, underruns: 0 };
43
+ /** The server's speaking flag: true sending, false done sending, null never heard. */
44
+ this.serverSending = null;
45
+ this.sink = null;
46
+ this.sinkPromise = null;
47
+ this.pending = [];
48
+ this.muted = false;
49
+ this.read = 0; // last reported read index
50
+ this.readAt = 0; // wall s of that report
51
+ this.playing = false;
52
+ this.written = 0; // samples pushed in total
53
+ this.replyStart = 0; // sample index where the open reply begins
54
+ this.replyPcm = [];
55
+ this.announced = null;
56
+ this.lastChunkAt = 0;
57
+ this.heardStarted = false;
58
+ this.endedAt = null;
59
+ this.rtpBase = 0;
60
+ this.timer = null;
61
+ this.controller = new StreamController(options.controller);
62
+ this.makeSink = options.createSink ?? createWorkletSink;
63
+ this.now = options.now ?? (() => performance.now() / 1000);
64
+ this.idleEnd = options.idleEnd ?? 1.5;
65
+ this.stallEnd = options.stallEnd ?? 10;
66
+ }
67
+ /** Where playback is in the open reply's lifecycle. */
68
+ get state() {
69
+ return this.controller.state;
70
+ }
71
+ /** Queue an audio-data chunk. */
72
+ pushChunk(chunk) {
73
+ if (chunk.includes_wav_header)
74
+ return; // the data channel sends raw PCM; a WAV file is not a stream chunk
75
+ this.pending.push(chunk);
76
+ void this.ensureSink(chunk.sample_rate).then(() => this.flushPending());
77
+ }
78
+ /** The turn announced the reply's audio length (blendshape-turn-stats). */
79
+ setTurnTotal(seconds) {
80
+ if (!(seconds > 0))
81
+ return;
82
+ this.announced = seconds;
83
+ this.controller.onTotal(seconds);
84
+ this.checkEnded();
85
+ }
86
+ /** The server's own speaking flag: true while it is still sending this reply. */
87
+ setServerSpeaking(speaking) {
88
+ this.serverSending = speaking;
89
+ }
90
+ /** Lipsync seconds that arrived for the open reply. */
91
+ addFrames(seconds) {
92
+ this.controller.onFrames(seconds);
93
+ }
94
+ /** Drop everything (an interruption). */
95
+ clear() {
96
+ this.pending = [];
97
+ this.sink?.clear();
98
+ this.read = this.written;
99
+ this.playing = false;
100
+ const wasActive = this.heardStarted && this.endedAt == null;
101
+ this.controller.reset();
102
+ this.replyPcm = [];
103
+ this.announced = null;
104
+ this.heardStarted = false;
105
+ this.endedAt = null;
106
+ if (wasActive)
107
+ this.emit("replyEnded", { interrupted: true });
108
+ }
109
+ setMuted(muted) {
110
+ this.muted = muted;
111
+ this.sink?.setMuted(muted);
112
+ }
113
+ /** Resume the audio context (call from a user gesture if the page blocks autoplay). */
114
+ async resume() {
115
+ await this.sink?.resume();
116
+ }
117
+ /** Seconds of the open reply heard so far; null before it starts. Holds through a pause, runs on 3 s past the end. */
118
+ position() {
119
+ const st = this.controller.state;
120
+ if (!this.sink || st === "idle" || st === "buffering")
121
+ return null;
122
+ if (this.endedAt != null) {
123
+ const extra = this.now() - this.endedAt;
124
+ return extra < 3 ? this.controller.snapshot.audio + extra : null;
125
+ }
126
+ return this.replyPlayed();
127
+ }
128
+ /** RMS of the voice now playing; null when nothing can be read. */
129
+ level() {
130
+ return this.sink?.level() ?? null;
131
+ }
132
+ /** Seconds buffered ahead of what is heard. */
133
+ queuedSeconds() {
134
+ if (!this.sink)
135
+ return 0;
136
+ return Math.max(0, (this.written - this.heardIndex()) / this.sink.sampleRate);
137
+ }
138
+ /** RTCRtpReceiver-shaped clock: the open reply's heard position in 48 kHz RTP units. */
139
+ getSynchronizationSources() {
140
+ const p = this.position();
141
+ if (p == null)
142
+ return [];
143
+ return [{ rtpTimestamp: this.rtpBase + p * RTP_RATE, timestamp: Date.now(), audioLevel: this.level() ?? 0 }];
144
+ }
145
+ dispose() {
146
+ if (this.timer)
147
+ clearInterval(this.timer);
148
+ this.timer = null;
149
+ this.sink?.dispose();
150
+ this.sink = null;
151
+ this.sinkPromise = null;
152
+ }
153
+ // ── internals ─────────────────────────────────────────────────────────────
154
+ ensureSink(rate) {
155
+ this.sinkPromise ?? (this.sinkPromise = this.makeSink(rate).then((sink) => {
156
+ this.sink = sink;
157
+ sink.setMuted(this.muted);
158
+ sink.onReport((read, playing) => {
159
+ this.read = read;
160
+ this.readAt = this.now();
161
+ this.playing = playing;
162
+ });
163
+ sink.onUnderrun((read) => {
164
+ // Running out at the true end of a reply is not a stutter.
165
+ const atEnd = this.controller.snapshot.ended && this.written - read < 0.05 * sink.sampleRate;
166
+ if (!atEnd) {
167
+ this.stats.underruns++;
168
+ this.emit("underrun", { read });
169
+ }
170
+ });
171
+ this.timer ?? (this.timer = setInterval(() => this.tick(), 20));
172
+ return sink;
173
+ }));
174
+ return this.sinkPromise;
175
+ }
176
+ flushPending() {
177
+ const sink = this.sink;
178
+ if (!sink)
179
+ return;
180
+ while (this.pending.length) {
181
+ const chunk = this.pending.shift();
182
+ let samples = decodePcm16(chunk.audio, chunk.channels);
183
+ if (chunk.sample_rate !== sink.sampleRate)
184
+ samples = resampleLinear(samples, chunk.sample_rate, sink.sampleRate);
185
+ const st = this.controller.state;
186
+ if (st === "idle" || st === "done")
187
+ this.beginReply();
188
+ this.replyPcm.push([this.written, samples]);
189
+ sink.push(samples);
190
+ this.written += samples.length;
191
+ this.lastChunkAt = this.now();
192
+ this.controller.onAudio(this.now(), samples.length / sink.sampleRate);
193
+ this.stats.chunks++;
194
+ this.checkEnded();
195
+ }
196
+ }
197
+ beginReply() {
198
+ this.replyStart = this.written;
199
+ this.replyPcm = [];
200
+ this.announced = null;
201
+ this.heardStarted = false;
202
+ this.endedAt = null;
203
+ // A "stopped" left over from the last reply says nothing about this one.
204
+ if (this.serverSending === false)
205
+ this.serverSending = null;
206
+ this.rtpBase += 10 * RTP_RATE; // a jump the RTP clock reads as a new talk spurt
207
+ }
208
+ checkEnded() {
209
+ const s = this.controller.snapshot;
210
+ if (s.ended || s.state === "idle")
211
+ return;
212
+ if (this.announced != null && s.audio >= this.announced - 0.02)
213
+ this.controller.onEnded();
214
+ }
215
+ heardIndex() {
216
+ const sink = this.sink;
217
+ const est = this.playing ? this.read + (this.now() - this.readAt) * sink.sampleRate : this.read;
218
+ return Math.min(est, this.written) - (this.playing ? sink.outputLatency() * sink.sampleRate : 0);
219
+ }
220
+ replyPlayed() {
221
+ return Math.max(0, (this.heardIndex() - this.replyStart) / this.sink.sampleRate);
222
+ }
223
+ tick() {
224
+ const sink = this.sink;
225
+ if (!sink)
226
+ return;
227
+ const t = this.now();
228
+ const s = this.controller.snapshot;
229
+ // Has the reply fully arrived? The server's stop follows its last chunk on the same
230
+ // channel, so once it has stopped nothing more is coming. While it is still sending,
231
+ // a gap is a slow link: ending on it would play a fragment as the whole reply.
232
+ const quiet = t - this.lastChunkAt;
233
+ const endAfter = this.serverSending === false ? 0.25 : this.serverSending ? this.stallEnd : this.idleEnd;
234
+ if (!s.ended && s.state !== "idle" && s.state !== "done" && quiet > endAfter)
235
+ this.controller.onEnded();
236
+ // The sink has played everything this reply had: it is over, whatever the latency estimate says.
237
+ if (s.ended && s.state === "playing" && this.read >= this.written)
238
+ this.controller.finish();
239
+ const syncedEnd = () => Math.min(this.written, this.replyStart + Math.floor(this.controller.synced * sink.sampleRate));
240
+ const searchFrom = () => Math.ceil(this.heardIndex() + 0.05 * sink.sampleRate);
241
+ const silenceAhead = () => this.lastSilence(searchFrom(), syncedEnd() - Math.round(0.02 * sink.sampleRate)) != null;
242
+ const cmd = this.controller.tick(t, this.replyPlayed(), silenceAhead);
243
+ if (cmd === "play") {
244
+ sink.play();
245
+ this.playing = true;
246
+ this.readAt = t;
247
+ if (this.controller.snapshot.pauses > 0)
248
+ this.emit("resumed", {});
249
+ }
250
+ else if (cmd === "pause") {
251
+ this.stats.pauses++;
252
+ // Only synced audio (blendshapes in hand) may play: stop at its end, or at the last
253
+ // silence before it.
254
+ const end = syncedEnd();
255
+ const at = this.lastSilence(searchFrom(), end - Math.round(0.02 * sink.sampleRate));
256
+ sink.pauseAt(at ?? end);
257
+ this.emit("paused", { atSilence: at != null });
258
+ }
259
+ if (!this.heardStarted && (this.state === "playing" || this.state === "paused") && this.replyPlayed() > 0) {
260
+ this.heardStarted = true;
261
+ this.emit("replyStarted", {});
262
+ }
263
+ if (this.state === "done" && this.endedAt == null) {
264
+ this.endedAt = t;
265
+ if (this.heardStarted)
266
+ this.emit("replyEnded", { interrupted: false });
267
+ }
268
+ }
269
+ /** The last silent window in the buffered audio between two sample indices; null if none. */
270
+ lastSilence(from, to) {
271
+ const rate = this.sink.sampleRate;
272
+ const win = Math.max(1, Math.round(SILENCE_WINDOW * rate));
273
+ let best = null;
274
+ for (const [start, f] of this.replyPcm) {
275
+ for (let i = 0; i + win <= f.length; i += win >> 1) {
276
+ const at = start + i;
277
+ if (at < from || at + win > to)
278
+ continue;
279
+ let sum = 0;
280
+ for (let k = 0; k < win; k++)
281
+ sum += f[i + k] * f[i + k];
282
+ if (Math.sqrt(sum / win) < SILENCE_RMS)
283
+ best = at + (win >> 1);
284
+ }
285
+ }
286
+ return best;
287
+ }
288
+ }
289
+ function resampleLinear(input, from, to) {
290
+ const n = Math.max(1, Math.round((input.length * to) / from));
291
+ const out = new Float32Array(n);
292
+ for (let i = 0; i < n; i++) {
293
+ const x = (i * from) / to;
294
+ const a = Math.floor(x);
295
+ const b = Math.min(a + 1, input.length - 1);
296
+ out[i] = input[a] + (input[b] - input[a]) * (x - a);
297
+ }
298
+ return out;
299
+ }
300
+ // ── The default sink: an AudioWorklet ring buffer ─────────────────────────────
301
+ const RING_SECONDS = 180;
302
+ function workletSource(capacity) {
303
+ return `
304
+ class ConvaiDataAudioRing extends AudioWorkletProcessor {
305
+ constructor() {
306
+ super()
307
+ this.L = ${capacity}; this.buf = new Float32Array(this.L); this.w = 0; this.r = 0
308
+ this.playing = false; this.pauseAt = -1; this.n = 0; this.under = false
309
+ this.port.onmessage = (e) => {
310
+ const m = e.data
311
+ if (m.cmd === 'push') { const s = m.samples; for (let i = 0; i < s.length; i++) this.buf[(this.w + i) % this.L] = s[i]; this.w += s.length }
312
+ else if (m.cmd === 'play') { this.playing = true; this.pauseAt = -1; this.under = false }
313
+ else if (m.cmd === 'pauseAt') { this.pauseAt = Math.max(this.r, m.at) }
314
+ else if (m.cmd === 'clear') { this.r = this.w; this.playing = false; this.pauseAt = -1 }
315
+ }
316
+ }
317
+ process(_inputs, outputs) {
318
+ const out = outputs[0][0]
319
+ for (let i = 0; i < out.length; i++) {
320
+ if (this.playing && this.pauseAt >= 0 && this.r >= this.pauseAt) { this.playing = false; this.pauseAt = -1 }
321
+ if (this.playing && this.r < this.w) { out[i] = this.buf[this.r % this.L]; this.r++ }
322
+ else { out[i] = 0; if (this.playing && !this.under) { this.under = true; this.port.postMessage({ ev: 'underrun', r: this.r }) } }
323
+ }
324
+ if (++this.n % 4 === 0) this.port.postMessage({ ev: 'pos', r: this.r, playing: this.playing })
325
+ return true
326
+ }
327
+ }
328
+ registerProcessor('convai-data-audio-ring', ConvaiDataAudioRing)`;
329
+ }
330
+ const GESTURES = ["pointerdown", "keydown", "touchstart"];
331
+ /** An AudioWorklet ring buffer at the stream's own sample rate (no per-chunk resampling). */
332
+ export async function createWorkletSink(sampleRate) {
333
+ const ctx = new AudioContext({ sampleRate });
334
+ const url = URL.createObjectURL(new Blob([workletSource(sampleRate * RING_SECONDS)], { type: "text/javascript" }));
335
+ try {
336
+ await ctx.audioWorklet.addModule(url);
337
+ }
338
+ finally {
339
+ URL.revokeObjectURL(url);
340
+ }
341
+ const node = new AudioWorkletNode(ctx, "convai-data-audio-ring", { numberOfOutputs: 1, outputChannelCount: [1] });
342
+ const gain = ctx.createGain();
343
+ const analyser = ctx.createAnalyser();
344
+ analyser.fftSize = 512;
345
+ node.connect(gain);
346
+ gain.connect(analyser);
347
+ analyser.connect(ctx.destination);
348
+ const abuf = new Float32Array(analyser.fftSize);
349
+ let report = () => { };
350
+ let underrun = () => { };
351
+ node.port.onmessage = (e) => {
352
+ const m = e.data;
353
+ if (m.ev === "pos")
354
+ report(m.r, m.playing);
355
+ else if (m.ev === "underrun")
356
+ underrun(m.r);
357
+ };
358
+ // Autoplay policy: a context made before a gesture starts suspended.
359
+ const unlock = () => { void ctx.resume(); };
360
+ if (typeof document !== "undefined")
361
+ for (const g of GESTURES)
362
+ document.addEventListener(g, unlock, { capture: true, passive: true });
363
+ if (ctx.state !== "running")
364
+ void ctx.resume().catch(() => { });
365
+ return {
366
+ sampleRate: ctx.sampleRate,
367
+ push: (samples) => {
368
+ if (ctx.state !== "running")
369
+ void ctx.resume().catch(() => { });
370
+ node.port.postMessage({ cmd: "push", samples });
371
+ },
372
+ play: () => node.port.postMessage({ cmd: "play" }),
373
+ pauseAt: (index) => node.port.postMessage({ cmd: "pauseAt", at: index }),
374
+ clear: () => node.port.postMessage({ cmd: "clear" }),
375
+ setMuted: (muted) => { gain.gain.value = muted ? 0 : 1; },
376
+ level: () => {
377
+ if (ctx.state !== "running")
378
+ return null;
379
+ analyser.getFloatTimeDomainData(abuf);
380
+ let s = 0;
381
+ for (let i = 0; i < abuf.length; i++)
382
+ s += abuf[i] * abuf[i];
383
+ return Math.sqrt(s / abuf.length);
384
+ },
385
+ outputLatency: () => ctx.outputLatency || ctx.baseLatency || 0,
386
+ onReport: (cb) => { report = cb; },
387
+ onUnderrun: (cb) => { underrun = cb; },
388
+ resume: () => ctx.resume(),
389
+ dispose: () => {
390
+ if (typeof document !== "undefined")
391
+ for (const g of GESTURES)
392
+ document.removeEventListener(g, unlock, { capture: true });
393
+ node.disconnect();
394
+ void ctx.close().catch(() => { });
395
+ },
396
+ };
397
+ }
@@ -15,6 +15,8 @@ export declare class MessageHandler extends EventEmitter {
15
15
  private isBotResponding;
16
16
  private isSpeaking;
17
17
  private isListening;
18
+ /** Data-channel audio: speaking follows the client's player, not the server's flags. */
19
+ private speakingFromPlayback;
18
20
  private totalBlendshapesReceived;
19
21
  private blendshapeQueue;
20
22
  private _currentEmotion;
@@ -68,6 +70,17 @@ export declare class MessageHandler extends EventEmitter {
68
70
  * next bot-started-speaking can activate cleanly.
69
71
  */
70
72
  interruptLipsyncPlayback(): void;
73
+ /**
74
+ * Data-channel audio (`audioRouting: 'data_only'`): the client's player, not
75
+ * the server's bot-started/stopped-speaking, says when the bot is speaking.
76
+ * Those flags follow when the server SENT the audio; a buffered reply is
77
+ * heard seconds later, and a stop flag ended lipsync mid-sentence.
78
+ */
79
+ setSpeakingFromPlayback(enabled: boolean): void;
80
+ /** The player started hearing a reply (data-channel audio). */
81
+ playbackStarted(): void;
82
+ /** The player finished a reply (data-channel audio). */
83
+ playbackEnded(): void;
71
84
  /**
72
85
  * Finalize local response state after the client intentionally aborts a
73
86
  * transport before the server can deliver its terminal response frame.
@@ -35,6 +35,8 @@ export class MessageHandler extends EventEmitter {
35
35
  this.isBotResponding = false;
36
36
  this.isSpeaking = false;
37
37
  this.isListening = false;
38
+ /** Data-channel audio: speaking follows the client's player, not the server's flags. */
39
+ this.speakingFromPlayback = false;
38
40
  this.totalBlendshapesReceived = 0;
39
41
  this._currentEmotion = null;
40
42
  this.modelOutputVersion = 1;
@@ -114,10 +116,38 @@ export class MessageHandler extends EventEmitter {
114
116
  const wasSpeaking = this.isSpeaking;
115
117
  this.isSpeaking = false;
116
118
  this.blendshapeQueue.interrupt();
119
+ this.emit("playbackInterrupted");
117
120
  if (wasSpeaking) {
118
121
  this.emit("speakingChange", false);
119
122
  }
120
123
  }
124
+ /**
125
+ * Data-channel audio (`audioRouting: 'data_only'`): the client's player, not
126
+ * the server's bot-started/stopped-speaking, says when the bot is speaking.
127
+ * Those flags follow when the server SENT the audio; a buffered reply is
128
+ * heard seconds later, and a stop flag ended lipsync mid-sentence.
129
+ */
130
+ setSpeakingFromPlayback(enabled) {
131
+ this.speakingFromPlayback = enabled;
132
+ }
133
+ /** The player started hearing a reply (data-channel audio). */
134
+ playbackStarted() {
135
+ if (this.isSpeaking)
136
+ return;
137
+ const allowed = this.blendshapeQueue.startBotSpeaking();
138
+ if (allowed) {
139
+ this.isSpeaking = true;
140
+ this.emit("speakingChange", true);
141
+ }
142
+ }
143
+ /** The player finished a reply (data-channel audio). */
144
+ playbackEnded() {
145
+ if (!this.isSpeaking)
146
+ return;
147
+ this.isSpeaking = false;
148
+ this.blendshapeQueue.stopBotSpeaking();
149
+ this.emit("speakingChange", false);
150
+ }
121
151
  /**
122
152
  * Finalize local response state after the client intentionally aborts a
123
153
  * transport before the server can deliver its terminal response frame.
@@ -637,6 +667,11 @@ export class MessageHandler extends EventEmitter {
637
667
  break;
638
668
  // Bot Started Speaking (priority over listening: state becomes speaking)
639
669
  case "bot-started-speaking": {
670
+ if (this.speakingFromPlayback) {
671
+ // Data-channel audio: the player decides (see setSpeakingFromPlayback).
672
+ this.emit("serverSpeakingChange", true);
673
+ break;
674
+ }
640
675
  const owner = this.lifecycleOwner(messageData.data);
641
676
  if (this.blendshapeQueue.isStaleOwner(owner)) {
642
677
  break;
@@ -651,6 +686,10 @@ export class MessageHandler extends EventEmitter {
651
686
  }
652
687
  // Bot Stopped Speaking
653
688
  case "bot-stopped-speaking":
689
+ if (this.speakingFromPlayback) {
690
+ this.emit("serverSpeakingChange", false);
691
+ break;
692
+ }
654
693
  if (this.blendshapeQueue.isStaleOwner(this.lifecycleOwner(messageData.data))) {
655
694
  break;
656
695
  }
@@ -695,6 +734,22 @@ export class MessageHandler extends EventEmitter {
695
734
  if (messageData.data) {
696
735
  const serverData = messageData.data;
697
736
  switch (serverData.type) {
737
+ // Data-channel audio (audio_routing: data_only) arrives wrapped in a
738
+ // server-message on LiveKit; same payload as the top-level audio-data.
739
+ case "audio-data": {
740
+ const data = serverData;
741
+ if (typeof data.audio === "string" &&
742
+ typeof data.sample_rate === "number" &&
743
+ typeof data.channels === "number") {
744
+ this.emit("audioData", {
745
+ audio: data.audio,
746
+ sample_rate: data.sample_rate,
747
+ channels: data.channels,
748
+ includes_wav_header: data.includes_wav_header === true,
749
+ }, sseRequest);
750
+ }
751
+ break;
752
+ }
698
753
  // How production delivers usage: wrapped in a server-message,
699
754
  // the record's fields beside `type`. Strip the envelope's type.
700
755
  case "usage-update": {
@@ -793,6 +848,8 @@ export class MessageHandler extends EventEmitter {
793
848
  break;
794
849
  case "neurosync-blendshapes-cancel": {
795
850
  const cancelledActive = this.blendshapeQueue.cancelOwner(this.lifecycleOwner(serverData));
851
+ if (cancelledActive)
852
+ this.emit("playbackInterrupted");
796
853
  if (cancelledActive && this.isSpeaking) {
797
854
  this.isSpeaking = false;
798
855
  this.emit("speakingChange", false);
@@ -15,6 +15,8 @@ export interface SSESessionOptions {
15
15
  onCharacterSessionId: (characterSessionId: string) => void;
16
16
  endUserId?: string;
17
17
  endUserMetadata?: Record<string, unknown>;
18
+ /** Read before every request, so each message carries a current token. */
19
+ getEndUserToken?: () => Promise<string | undefined>;
18
20
  takeStateOfMind: () => string | null;
19
21
  enableEmotion?: ConvaiConfig["enableEmotion"];
20
22
  emotionConfig?: ConvaiConfig["emotionConfig"];