@livekit/agents-plugin-meta 1.8.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.
@@ -0,0 +1,782 @@
1
+ // SPDX-FileCopyrightText: 2026 LiveKit, Inc.
2
+ //
3
+ // SPDX-License-Identifier: Apache-2.0
4
+ import { type APIError, APIStatusError, stt } from '@livekit/agents';
5
+ import { AudioFrame } from '@livekit/rtc-node';
6
+ import { EventEmitter } from 'node:events';
7
+ import { afterEach, describe, expect, it } from 'vitest';
8
+ import type { ClientOptions, WebSocket } from 'ws';
9
+ import {
10
+ DEFAULT_MODEL,
11
+ DEFAULT_URL,
12
+ MAX_COMPLETED_TURNS,
13
+ STT,
14
+ closeError,
15
+ normalizeAccessToken,
16
+ normalizeLanguageHint,
17
+ speechStreamTestState,
18
+ } from './stt.js';
19
+
20
+ const CLOSE_AFTER_END = Symbol('close-after-end');
21
+ const CLOSE_1011_AFTER_END = Symbol('close-1011-after-end');
22
+ const TEST_OPTIONS = { maxRetry: 0, retryIntervalMs: 0, timeoutMs: 200 };
23
+
24
+ class Deferred {
25
+ readonly promise: Promise<void>;
26
+ #resolve!: () => void;
27
+ constructor() {
28
+ this.promise = new Promise((resolve) => (this.#resolve = resolve));
29
+ }
30
+ resolve() {
31
+ this.#resolve();
32
+ }
33
+ }
34
+
35
+ type Incoming =
36
+ | Record<string, unknown>
37
+ | string
38
+ | Error
39
+ | typeof CLOSE_AFTER_END
40
+ | typeof CLOSE_1011_AFTER_END;
41
+
42
+ class FakeWebSocket extends EventEmitter {
43
+ readyState = 0;
44
+ sentText: string[] = [];
45
+ sentBytes: Buffer[] = [];
46
+ sentAt: number[] = [];
47
+ handshakeSent = new Deferred();
48
+ handshakeAccepted = false;
49
+ audioStarted = new Deferred();
50
+ releaseAudio = new Deferred();
51
+ endStreamSent = new Deferred();
52
+ closed = false;
53
+ sendError?: Error;
54
+ sendDelayMs = 0;
55
+ #incoming: Incoming[];
56
+ #blockAudio: boolean;
57
+ #startedIncoming = false;
58
+
59
+ constructor(
60
+ incoming: Incoming[] = [],
61
+ options: { blockAudio?: boolean; sendError?: Error } = {},
62
+ ) {
63
+ super();
64
+ this.#incoming = [...incoming];
65
+ this.#blockAudio = options.blockAudio ?? false;
66
+ this.sendError = options.sendError;
67
+ queueMicrotask(() => {
68
+ if (this.closed) return;
69
+ this.readyState = 1;
70
+ this.emit('open');
71
+ });
72
+ }
73
+
74
+ send(data: string | Buffer | ArrayBuffer | ArrayBufferView, callback?: (error?: Error) => void) {
75
+ if (typeof data === 'string') {
76
+ this.sentText.push(data);
77
+ const payload = JSON.parse(data) as Record<string, unknown>;
78
+ if (payload.authorization) {
79
+ this.handshakeSent.resolve();
80
+ this.#drainIncoming();
81
+ }
82
+ if (payload.type === 'endStream') {
83
+ this.endStreamSent.resolve();
84
+ this.#drainIncoming();
85
+ }
86
+ callback?.();
87
+ return;
88
+ }
89
+
90
+ this.audioStarted.resolve();
91
+ const complete = () => {
92
+ if (this.sendError) callback?.(this.sendError);
93
+ else {
94
+ const buffer = Buffer.isBuffer(data)
95
+ ? Buffer.from(data)
96
+ : data instanceof ArrayBuffer
97
+ ? Buffer.from(data)
98
+ : Buffer.from(data.buffer, data.byteOffset, data.byteLength);
99
+ this.sentBytes.push(buffer);
100
+ this.sentAt.push(performance.now());
101
+ callback?.();
102
+ }
103
+ };
104
+ if (this.#blockAudio) this.releaseAudio.promise.then(complete);
105
+ else if (this.sendDelayMs) setTimeout(complete, this.sendDelayMs);
106
+ else complete();
107
+ }
108
+
109
+ queueJson(payload: Record<string, unknown>) {
110
+ this.#emitIncoming(payload);
111
+ }
112
+
113
+ #drainIncoming() {
114
+ if (!this.#startedIncoming) this.#startedIncoming = true;
115
+ while (this.#incoming.length) {
116
+ const item = this.#incoming[0]!;
117
+ if (
118
+ (item === CLOSE_AFTER_END || item === CLOSE_1011_AFTER_END) &&
119
+ !this.sentText.some(isEndStream)
120
+ ) {
121
+ return;
122
+ }
123
+ this.#incoming.shift();
124
+ this.#emitIncoming(item);
125
+ }
126
+ }
127
+
128
+ #emitIncoming(item: Incoming) {
129
+ if (item === CLOSE_AFTER_END || item === CLOSE_1011_AFTER_END) {
130
+ const code = item === CLOSE_AFTER_END ? 1000 : 1011;
131
+ this.readyState = 3;
132
+ this.emit('close', code, Buffer.from('unsafe close reason'));
133
+ return;
134
+ }
135
+ if (item instanceof Error) {
136
+ this.emit('error', item);
137
+ return;
138
+ }
139
+ const text = typeof item === 'string' ? item : JSON.stringify(item);
140
+ if (typeof item === 'object' && item.sessionId) this.handshakeAccepted = true;
141
+ this.emit('message', Buffer.from(text), false);
142
+ }
143
+
144
+ close() {
145
+ if (this.closed) return;
146
+ this.closed = true;
147
+ this.releaseAudio.resolve();
148
+ if (this.readyState !== 3) {
149
+ this.readyState = 3;
150
+ this.emit('close', 1000, Buffer.alloc(0));
151
+ }
152
+ }
153
+ }
154
+
155
+ function isEndStream(text: string): boolean {
156
+ return (JSON.parse(text) as Record<string, unknown>).type === 'endStream';
157
+ }
158
+
159
+ class FakeFactory {
160
+ readonly calls: Array<{ url: string; options: ClientOptions }> = [];
161
+ readonly outcomes: Array<FakeWebSocket | Error>;
162
+ constructor(outcomes: Array<FakeWebSocket | Error>) {
163
+ this.outcomes = [...outcomes];
164
+ }
165
+ create = (url: string, options: ClientOptions): WebSocket => {
166
+ this.calls.push({ url, options });
167
+ const outcome = this.outcomes.shift();
168
+ if (!outcome) throw new Error('no fake WebSocket outcome');
169
+ if (outcome instanceof Error) throw outcome;
170
+ return outcome as unknown as WebSocket;
171
+ };
172
+ }
173
+
174
+ function websocket(events: Record<string, unknown>[] = []): FakeWebSocket {
175
+ return new FakeWebSocket([{ sessionId: 'session-1' }, ...events, CLOSE_AFTER_END]);
176
+ }
177
+
178
+ function frame(byteLength: number, sampleRate = 24_000, channels = 1): AudioFrame {
179
+ const samplesPerChannel = byteLength / (2 * channels);
180
+ return new AudioFrame(new Int16Array(byteLength / 2), sampleRate, channels, samplesPerChannel);
181
+ }
182
+
183
+ async function waitUntil(predicate: () => boolean, timeoutMs = 1000): Promise<void> {
184
+ const started = performance.now();
185
+ while (!predicate()) {
186
+ if (performance.now() - started > timeoutMs) throw new Error('timed out waiting for condition');
187
+ await new Promise((resolve) => setTimeout(resolve, 1));
188
+ }
189
+ }
190
+
191
+ async function collect(
192
+ provider: STT,
193
+ options: { audio?: AudioFrame; language?: string; connOptions?: typeof TEST_OPTIONS } = {},
194
+ ) {
195
+ let streamError: Error | undefined;
196
+ const onError = (event: Parameters<stt.STTCallbacks['error']>[0]) => (streamError = event.error);
197
+ provider.on('error', onError);
198
+ const stream = provider.stream({
199
+ language: options.language,
200
+ connOptions: options.connOptions ?? TEST_OPTIONS,
201
+ });
202
+ if (options.audio) stream.pushFrame(options.audio);
203
+ stream.endInput();
204
+ const events = await collectEvents(stream);
205
+ provider.off('error', onError);
206
+ return { events, stream, error: streamError };
207
+ }
208
+
209
+ async function collectEvents(stream: stt.SpeechStream): Promise<stt.SpeechEvent[]> {
210
+ const events: stt.SpeechEvent[] = [];
211
+ for await (const event of stream) events.push(event);
212
+ return events;
213
+ }
214
+
215
+ function speechEvents(events: stt.SpeechEvent[]) {
216
+ return events.filter((event) => event.type !== stt.SpeechEventType.RECOGNITION_USAGE);
217
+ }
218
+
219
+ function summaries(events: stt.SpeechEvent[]) {
220
+ return speechEvents(events).map((event) => [
221
+ event.type,
222
+ event.requestId,
223
+ event.alternatives?.[0].text ?? '',
224
+ ]);
225
+ }
226
+
227
+ const originalModelKey = process.env.MODEL_API_KEY;
228
+ const originalMetaKey = process.env.META_API_KEY;
229
+ afterEach(() => {
230
+ if (originalModelKey === undefined) delete process.env.MODEL_API_KEY;
231
+ else process.env.MODEL_API_KEY = originalModelKey;
232
+ if (originalMetaKey === undefined) delete process.env.META_API_KEY;
233
+ else process.env.META_API_KEY = originalMetaKey;
234
+ });
235
+
236
+ describe('Meta Muse STT', () => {
237
+ it('constructs with source-parity capabilities and exports', () => {
238
+ delete process.env.MODEL_API_KEY;
239
+ delete process.env.META_API_KEY;
240
+ expect(() => new STT()).toThrow(/MODEL_API_KEY or META_API_KEY/);
241
+ process.env.MODEL_API_KEY = 'model-environment-key';
242
+ process.env.META_API_KEY = 'meta-environment-key';
243
+ const provider = new STT({ webSocketFactory: new FakeFactory([]).create });
244
+ expect(provider.model).toBe(DEFAULT_MODEL);
245
+ expect(provider.provider).toBe('Meta');
246
+ expect(provider.label).toBe('meta.STT');
247
+ expect(provider.capabilities).toEqual({
248
+ streaming: true,
249
+ interimResults: true,
250
+ diarization: false,
251
+ alignedTranscript: false,
252
+ keyterms: false,
253
+ });
254
+ });
255
+
256
+ it('falls back from blank MODEL_API_KEY to META_API_KEY', async () => {
257
+ process.env.MODEL_API_KEY = ' ';
258
+ process.env.META_API_KEY = ' meta-environment-key ';
259
+ const ws = websocket();
260
+ await collect(new STT({ webSocketFactory: new FakeFactory([ws]).create }));
261
+ expect(JSON.parse(ws.sentText[0]!).authorization).toEqual({
262
+ accessToken: 'Bearer meta-environment-key',
263
+ });
264
+ });
265
+
266
+ it('does not fall back from an explicit blank API key', () => {
267
+ process.env.MODEL_API_KEY = 'model-key';
268
+ expect(() => new STT({ apiKey: ' ' })).toThrow(/MODEL_API_KEY or META_API_KEY/);
269
+ });
270
+
271
+ it.each([
272
+ 'ws://api.meta.ai/v1/asr/realtime',
273
+ 'https://api.meta.ai',
274
+ '/relative',
275
+ 'wss://user:secret@api.meta.ai/v1/asr/realtime',
276
+ 'wss://api.meta.ai/v1/asr/realtime#secret',
277
+ ])('rejects insecure, relative, credentialed, or fragmented URLs: %s', (url) => {
278
+ expect(() => new STT({ apiKey: 'test-key', url })).toThrow(/wss/);
279
+ });
280
+
281
+ it('normalizes bearer access tokens', () => {
282
+ expect(normalizeAccessToken('secret')).toBe('Bearer secret');
283
+ expect(normalizeAccessToken('bearer secret')).toBe('Bearer secret');
284
+ expect(normalizeAccessToken('Bearer secret ')).toBe('Bearer secret');
285
+ expect(() => new STT({ apiKey: 'Bearer' })).toThrow(/token after Bearer/);
286
+ });
287
+
288
+ it('normalizes and validates static hints', async () => {
289
+ const ws = websocket();
290
+ await collect(
291
+ new STT({
292
+ apiKey: 'test-key',
293
+ keywords: [' Muse ', 'Muse'],
294
+ languageBias: [' english ', 'English', 'French'],
295
+ webSocketFactory: new FakeFactory([ws]).create,
296
+ }),
297
+ );
298
+ expect(JSON.parse(ws.sentText[0]!)).toMatchObject({
299
+ keywords: ['Muse'],
300
+ languageBias: ['English', 'French'],
301
+ });
302
+ expect(() => new STT({ apiKey: 'test-key', keywords: [' '] })).toThrow(/keywords entries/);
303
+ expect(() => new STT({ apiKey: 'test-key', languageBias: [''] })).toThrow(/languageBias/);
304
+ expect(() => new STT({ apiKey: 'test-key', languageBias: ['en'] })).toThrow(/languageBias/);
305
+ });
306
+
307
+ it('maps stream languages to documented names', () => {
308
+ expect(normalizeLanguageHint('pt_BR')).toBe('Portuguese');
309
+ expect(normalizeLanguageHint('EN-us')).toBe('English');
310
+ expect(normalizeLanguageHint('zh-CN')).toBe('Mandarin Chinese');
311
+ expect(normalizeLanguageHint('fil-PH')).toBe('Tagalog');
312
+ expect(() => normalizeLanguageHint('not a language')).toThrow(
313
+ /unsupported Muse Voice language/,
314
+ );
315
+ });
316
+
317
+ it('rejects batch recognition as non-retryable', async () => {
318
+ const provider = new STT({ apiKey: 'test-key' });
319
+ await expect(provider.recognize([])).rejects.toMatchObject({ retryable: false });
320
+ });
321
+
322
+ it('handshakes before audio and matches the Muse contract', async () => {
323
+ const ws = new FakeWebSocket();
324
+ const factory = new FakeFactory([ws]);
325
+ const provider = new STT({
326
+ apiKey: 'explicit-secret',
327
+ keywords: ['Muse', 'Muse'],
328
+ languageBias: ['English', 'French'],
329
+ webSocketFactory: factory.create,
330
+ });
331
+ const stream = provider.stream({ language: 'fr-FR', connOptions: TEST_OPTIONS });
332
+ stream.pushFrame(frame(3840));
333
+ await ws.handshakeSent.promise;
334
+ expect(ws.sentBytes).toEqual([]);
335
+ expect(speechStreamTestState(stream).audioConsumed).toBe(false);
336
+ ws.queueJson({ sessionId: 'session-1' });
337
+ await ws.audioStarted.promise;
338
+ stream.endInput();
339
+ ws.queueJson({ type: 'audioProgress', audioProcessedMs: 0 });
340
+ await ws.endStreamSent.promise;
341
+ ws.emit('close', 1000, Buffer.alloc(0));
342
+ await collectEvents(stream);
343
+ expect(JSON.parse(ws.sentText[0]!)).toEqual({
344
+ mode: 'ENDPOINTING',
345
+ authorization: { accessToken: 'Bearer explicit-secret' },
346
+ audioEncoding: 'PCM_24KHZ',
347
+ model: 'muse-voice-transcribe-1.0',
348
+ partialMode: 'CUMULATIVE',
349
+ emitAudioProgress: true,
350
+ keywords: ['Muse'],
351
+ languageBias: ['English', 'French'],
352
+ });
353
+ expect(factory.calls[0]!.url).toBe(DEFAULT_URL);
354
+ expect(JSON.stringify(factory.calls[0]!.options)).not.toContain('explicit-secret');
355
+ });
356
+
357
+ it('packetizes PCM16 into paced 80 ms chunks and preserves the tail', async () => {
358
+ const ws = websocket();
359
+ const { events } = await collect(
360
+ new STT({ apiKey: 'test-key', webSocketFactory: new FakeFactory([ws]).create }),
361
+ { audio: frame(3840 * 2 + 100) },
362
+ );
363
+ expect(ws.sentBytes.map((packet) => packet.length)).toEqual([3840, 3840, 100]);
364
+ expect(events.every((event) => !event.recognitionUsage)).toBe(true);
365
+ });
366
+
367
+ it('resamples 48 kHz mono input to 24 kHz wire audio', async () => {
368
+ const ws = websocket();
369
+ await collect(new STT({ apiKey: 'test-key', webSocketFactory: new FakeFactory([ws]).create }), {
370
+ audio: frame(48_000 * 2 * 0.2, 48_000),
371
+ });
372
+ expect(ws.sentBytes.reduce((sum, packet) => sum + packet.length, 0)).toBe(24_000 * 2 * 0.2);
373
+ expect(ws.sentBytes.map((packet) => packet.length)).toEqual([3840, 3840, 1920]);
374
+ });
375
+
376
+ it('flushes a tail without ending and accepts more audio', async () => {
377
+ const ws = websocket();
378
+ const provider = new STT({
379
+ apiKey: 'test-key',
380
+ webSocketFactory: new FakeFactory([ws]).create,
381
+ });
382
+ const stream = provider.stream({ connOptions: TEST_OPTIONS });
383
+ stream.pushFrame(frame(1000));
384
+ stream.flush();
385
+ await waitUntil(() => ws.sentBytes.length === 1);
386
+ expect(ws.sentText.some(isEndStream)).toBe(false);
387
+ stream.pushFrame(frame(3840));
388
+ stream.endInput();
389
+ await collectEvents(stream);
390
+ expect(ws.sentBytes.map((packet) => packet.length)).toEqual([1000, 3840]);
391
+ expect(ws.sentText.filter(isEndStream)).toHaveLength(1);
392
+ });
393
+
394
+ it('does not retry stereo after consuming input', async () => {
395
+ const factory = new FakeFactory([websocket(), websocket()]);
396
+ const provider = new STT({ apiKey: 'test-key', webSocketFactory: factory.create });
397
+ const { error } = await collect(provider, {
398
+ audio: frame(7680, 24_000, 2),
399
+ connOptions: { maxRetry: 1, retryIntervalMs: 0, timeoutMs: 200 },
400
+ });
401
+ expect(error).toMatchObject({ retryable: false });
402
+ expect(error?.message).toMatch(/mono audio/);
403
+ expect(factory.calls).toHaveLength(1);
404
+ });
405
+
406
+ it('uses absolute pacing that accounts for send time', async () => {
407
+ const ws = websocket();
408
+ ws.sendDelayMs = 30;
409
+ await collect(new STT({ apiKey: 'test-key', webSocketFactory: new FakeFactory([ws]).create }), {
410
+ audio: frame(3840 * 3),
411
+ });
412
+ expect(ws.sentAt).toHaveLength(3);
413
+ expect(ws.sentAt[1]! - ws.sentAt[0]!).toBeGreaterThanOrEqual(45);
414
+ expect(ws.sentAt[2]! - ws.sentAt[1]!).toBeGreaterThanOrEqual(45);
415
+ });
416
+
417
+ it('uses audio progress without duplicating sent-byte usage', async () => {
418
+ const ws = websocket([
419
+ { type: 'audioProgress', audioProcessedMs: 80 },
420
+ { type: 'audioProgress', audioProcessedMs: 80 },
421
+ { type: 'audioProgress', audioProcessedMs: 160 },
422
+ ]);
423
+ const { events } = await collect(
424
+ new STT({ apiKey: 'test-key', webSocketFactory: new FakeFactory([ws]).create }),
425
+ { audio: frame(7680) },
426
+ );
427
+ expect(events.flatMap((event) => event.recognitionUsage?.audioDuration ?? [])).toEqual([0.16]);
428
+ });
429
+
430
+ it('emits usage once after each completed turn', async () => {
431
+ const ws = websocket([
432
+ { type: 'speechStart', turnId: 'turn-1' },
433
+ { type: 'audioProgress', audioProcessedMs: 80 },
434
+ { type: 'audioProgress', audioProcessedMs: 160 },
435
+ { type: 'transcript', turnId: 'turn-1', transcript: 'hello' },
436
+ { type: 'speechEnd', turnId: 'turn-1' },
437
+ { type: 'speechComplete', turnId: 'turn-1', transcript: 'hello' },
438
+ { type: 'speechStart', turnId: 'turn-2' },
439
+ { type: 'audioProgress', audioProcessedMs: 240 },
440
+ { type: 'audioProgress', audioProcessedMs: 400 },
441
+ { type: 'speechEnd', turnId: 'turn-2' },
442
+ { type: 'speechComplete', turnId: 'turn-2', transcript: 'again' },
443
+ ]);
444
+ const { events } = await collect(
445
+ new STT({ apiKey: 'test-key', webSocketFactory: new FakeFactory([ws]).create }),
446
+ );
447
+ const usage = events.filter((event) => event.recognitionUsage);
448
+ expect(usage.map((event) => event.requestId)).toEqual(['session-1', 'session-1']);
449
+ expect(usage.map((event) => event.recognitionUsage!.audioDuration)).toEqual([0.16, 0.24]);
450
+ expect(events.indexOf(usage[0]!)).toBeGreaterThan(
451
+ events.findIndex((event) => event.type === stt.SpeechEventType.END_OF_SPEECH),
452
+ );
453
+ });
454
+
455
+ it('deduplicates cumulative partials/finals/end and evicts completed state', async () => {
456
+ const ws = websocket([
457
+ { type: 'speechStart', turnId: 1 },
458
+ { type: 'transcript', transcript: 'hel' },
459
+ { type: 'transcript', turnId: 1, transcript: 'hel' },
460
+ { type: 'transcript', turnId: 1, transcript: 'hello' },
461
+ { type: 'speechEnd', turnId: 1 },
462
+ { type: 'speechEnd', turnId: 1 },
463
+ { type: 'speechComplete', turnId: 1, transcript: 'hello there' },
464
+ { type: 'speechComplete', turnId: 1, transcript: 'duplicate' },
465
+ { type: 'speechEnd', turnId: 1 },
466
+ ]);
467
+ const { events, stream } = await collect(
468
+ new STT({ apiKey: 'test-key', webSocketFactory: new FakeFactory([ws]).create }),
469
+ );
470
+ expect(summaries(events)).toEqual([
471
+ [stt.SpeechEventType.START_OF_SPEECH, '1', ''],
472
+ [stt.SpeechEventType.INTERIM_TRANSCRIPT, '1', 'hel'],
473
+ [stt.SpeechEventType.INTERIM_TRANSCRIPT, '1', 'hello'],
474
+ [stt.SpeechEventType.FINAL_TRANSCRIPT, '1', 'hello there'],
475
+ [stt.SpeechEventType.END_OF_SPEECH, '1', ''],
476
+ ]);
477
+ expect(speechStreamTestState(stream).turns.size).toBe(0);
478
+ expect(speechStreamTestState(stream).completedTurnIds).toEqual(new Set(['1']));
479
+ expect(events.at(-2)?.alternatives?.[0].language).toBe('');
480
+ });
481
+
482
+ it('bounds completed-turn tombstones', async () => {
483
+ const events: Record<string, unknown>[] = [];
484
+ for (let i = 0; i < MAX_COMPLETED_TURNS + 2; i++) {
485
+ events.push(
486
+ { type: 'speechStart', turnId: i },
487
+ { type: 'speechEnd', turnId: i },
488
+ { type: 'speechComplete', turnId: i, transcript: String(i) },
489
+ );
490
+ }
491
+ const { stream } = await collect(
492
+ new STT({
493
+ apiKey: 'test-key',
494
+ webSocketFactory: new FakeFactory([websocket(events)]).create,
495
+ }),
496
+ );
497
+ expect(speechStreamTestState(stream).completedTurnIds.size).toBe(MAX_COMPLETED_TURNS);
498
+ expect(speechStreamTestState(stream).completedTurnIds.has('0')).toBe(false);
499
+ expect(speechStreamTestState(stream).completedTurnIds.has('1')).toBe(false);
500
+ });
501
+
502
+ it('globally serializes interleaved turns and usage', async () => {
503
+ const ws = websocket([
504
+ { type: 'speechStart', turnId: 'first' },
505
+ { type: 'transcript', turnId: 'first', transcript: 'one' },
506
+ { type: 'audioProgress', audioProcessedMs: 150 },
507
+ { type: 'speechEnd', turnId: 'first' },
508
+ { type: 'speechStart', turnId: 'second' },
509
+ { type: 'transcript', transcript: 'two' },
510
+ { type: 'audioProgress', audioProcessedMs: 400 },
511
+ { type: 'speechEnd', turnId: 'second' },
512
+ { type: 'speechComplete', turnId: 'second', transcript: 'turn two' },
513
+ { type: 'speechComplete', turnId: 'first', transcript: 'turn one' },
514
+ ]);
515
+ const { events } = await collect(
516
+ new STT({ apiKey: 'test-key', webSocketFactory: new FakeFactory([ws]).create }),
517
+ );
518
+ expect(summaries(events)).toEqual([
519
+ [stt.SpeechEventType.START_OF_SPEECH, 'first', ''],
520
+ [stt.SpeechEventType.INTERIM_TRANSCRIPT, 'first', 'one'],
521
+ [stt.SpeechEventType.FINAL_TRANSCRIPT, 'first', 'turn one'],
522
+ [stt.SpeechEventType.END_OF_SPEECH, 'first', ''],
523
+ [stt.SpeechEventType.START_OF_SPEECH, 'second', ''],
524
+ [stt.SpeechEventType.INTERIM_TRANSCRIPT, 'second', 'two'],
525
+ [stt.SpeechEventType.FINAL_TRANSCRIPT, 'second', 'turn two'],
526
+ [stt.SpeechEventType.END_OF_SPEECH, 'second', ''],
527
+ ]);
528
+ expect(events.flatMap((event) => event.recognitionUsage?.audioDuration ?? [])).toEqual([
529
+ 0.15, 0.25,
530
+ ]);
531
+ });
532
+
533
+ it('counts only positive audio progress deltas', async () => {
534
+ const ws = websocket(
535
+ [80, 200, 200, 150, 350.5].map((audioProcessedMs) => ({
536
+ type: 'audioProgress',
537
+ audioProcessedMs,
538
+ })),
539
+ );
540
+ const { events } = await collect(
541
+ new STT({ apiKey: 'test-key', webSocketFactory: new FakeFactory([ws]).create }),
542
+ );
543
+ expect(events.flatMap((event) => event.recognitionUsage?.audioDuration ?? [])[0]).toBeCloseTo(
544
+ 0.3505,
545
+ );
546
+ });
547
+
548
+ it('flushes pending usage before a stream error', async () => {
549
+ const ws = new FakeWebSocket([
550
+ { sessionId: 'session-1' },
551
+ { type: 'audioProgress', audioProcessedMs: 240 },
552
+ '{invalid-json',
553
+ ]);
554
+ const { events, error } = await collect(
555
+ new STT({ apiKey: 'test-key', webSocketFactory: new FakeFactory([ws]).create }),
556
+ );
557
+ expect(error?.message).toMatch(/invalid JSON/);
558
+ expect(events.flatMap((event) => event.recognitionUsage?.audioDuration ?? [])).toEqual([0.24]);
559
+ });
560
+
561
+ it.each([true, -1, Number.NaN, Number.POSITIVE_INFINITY, '80', null])(
562
+ 'rejects invalid audio progress as non-retryable: %s',
563
+ async (audioProcessedMs) => {
564
+ const { error } = await collect(
565
+ new STT({
566
+ apiKey: 'test-key',
567
+ webSocketFactory: new FakeFactory([
568
+ websocket([{ type: 'audioProgress', audioProcessedMs }]),
569
+ ]).create,
570
+ }),
571
+ );
572
+ expect(error).toMatchObject({ retryable: false });
573
+ expect(error?.message).toMatch(/invalid audioProcessedMs/);
574
+ },
575
+ );
576
+
577
+ it('ignores an empty turnless transcript outside speech', async () => {
578
+ const { events } = await collect(
579
+ new STT({
580
+ apiKey: 'test-key',
581
+ webSocketFactory: new FakeFactory([
582
+ websocket([{ type: 'transcript', transcript: '', final: false }]),
583
+ ]).create,
584
+ }),
585
+ );
586
+ expect(speechEvents(events)).toEqual([]);
587
+ });
588
+
589
+ it('rejects a turnless transcript outside an active turn without leaking it', async () => {
590
+ const secret = 'unsafe transcript body';
591
+ const { error } = await collect(
592
+ new STT({
593
+ apiKey: 'test-key',
594
+ webSocketFactory: new FakeFactory([
595
+ websocket([
596
+ { type: 'speechStart', turnId: 1 },
597
+ { type: 'speechEnd', turnId: 1 },
598
+ { type: 'transcript', transcript: secret },
599
+ ]),
600
+ ]).create,
601
+ }),
602
+ );
603
+ expect(error?.message).toMatch(/missing turnId outside an active turn/);
604
+ expect(String(error)).not.toContain(secret);
605
+ });
606
+
607
+ it('uses the close event code and rejects incomplete turns', async () => {
608
+ const { error } = await collect(
609
+ new STT({
610
+ apiKey: 'test-key',
611
+ webSocketFactory: new FakeFactory([
612
+ websocket([{ type: 'speechStart', turnId: 'unfinished' }]),
613
+ ]).create,
614
+ }),
615
+ );
616
+ expect(error).toMatchObject({ retryable: false });
617
+ expect(error?.message).toMatch(/incomplete speech turns/);
618
+ });
619
+
620
+ it('retries pre-audio connection failures without losing input', async () => {
621
+ const ws = websocket();
622
+ const factory = new FakeFactory([new Error('transient connection detail'), ws]);
623
+ const { error } = await collect(
624
+ new STT({ apiKey: 'test-key', webSocketFactory: factory.create }),
625
+ {
626
+ audio: frame(3840),
627
+ connOptions: { maxRetry: 1, retryIntervalMs: 0, timeoutMs: 200 },
628
+ },
629
+ );
630
+ expect(error).toBeUndefined();
631
+ expect(factory.calls).toHaveLength(2);
632
+ expect(ws.sentBytes.map((packet) => packet.length)).toEqual([3840]);
633
+ });
634
+
635
+ it('retries normal and transient closes during handshake', async () => {
636
+ for (const code of [1000, 1011, 1013]) {
637
+ const first = new FakeWebSocket();
638
+ const second = websocket();
639
+ const factory = new FakeFactory([first, second]);
640
+ const result = collect(new STT({ apiKey: 'test-key', webSocketFactory: factory.create }), {
641
+ connOptions: { maxRetry: 1, retryIntervalMs: 0, timeoutMs: 200 },
642
+ });
643
+ await first.handshakeSent.promise;
644
+ first.emit('close', code, Buffer.from('unsafe reason'));
645
+ const { error } = await result;
646
+ expect(error).toBeUndefined();
647
+ expect(factory.calls).toHaveLength(2);
648
+ }
649
+ });
650
+
651
+ it('does not retry policy-violation close during handshake or leak its reason', async () => {
652
+ const first = new FakeWebSocket();
653
+ const factory = new FakeFactory([first, websocket()]);
654
+ const result = collect(new STT({ apiKey: 'test-key', webSocketFactory: factory.create }), {
655
+ connOptions: { maxRetry: 1, retryIntervalMs: 0, timeoutMs: 200 },
656
+ });
657
+ await first.handshakeSent.promise;
658
+ first.emit('close', 1008, Buffer.from('unsafe reason'));
659
+ const { error } = await result;
660
+ expect(error).toBeInstanceOf(APIStatusError);
661
+ expect(error).toMatchObject({ statusCode: 1008, retryable: false });
662
+ expect(String(error)).not.toContain('unsafe reason');
663
+ expect(factory.calls).toHaveLength(1);
664
+ });
665
+
666
+ it('sends endStream on every empty-input retry attempt', async () => {
667
+ const first = new FakeWebSocket([{ sessionId: 'session-1' }, CLOSE_1011_AFTER_END]);
668
+ const second = websocket();
669
+ const factory = new FakeFactory([first, second]);
670
+ const { error } = await collect(
671
+ new STT({ apiKey: 'test-key', webSocketFactory: factory.create }),
672
+ { connOptions: { maxRetry: 1, retryIntervalMs: 0, timeoutMs: 200 } },
673
+ );
674
+ expect(error).toBeUndefined();
675
+ expect(first.sentText.filter(isEndStream)).toHaveLength(1);
676
+ expect(second.sentText.filter(isEndStream)).toHaveLength(1);
677
+ });
678
+
679
+ it('classifies normal close before audio as retryable', () => {
680
+ expect(closeError(1000, 'stream', true)).toMatchObject({ statusCode: 1000, retryable: true });
681
+ });
682
+
683
+ it.each([1000, 1011, 1013])('does not retry close %i after audio consumption', async (code) => {
684
+ const first = new FakeWebSocket([{ sessionId: 'session-1' }], { blockAudio: true });
685
+ first.on('message', () =>
686
+ queueMicrotask(() => first.emit('close', code, Buffer.from('unsafe reason'))),
687
+ );
688
+ const factory = new FakeFactory([first, websocket()]);
689
+ const promise = collect(new STT({ apiKey: 'test-key', webSocketFactory: factory.create }), {
690
+ audio: frame(3840),
691
+ connOptions: { maxRetry: 1, retryIntervalMs: 0, timeoutMs: 200 },
692
+ });
693
+ await first.audioStarted.promise;
694
+ const { error } = await promise;
695
+ expect(error).toMatchObject({ retryable: false });
696
+ expect(String(error)).not.toContain('unsafe reason');
697
+ expect(factory.calls).toHaveLength(1);
698
+ });
699
+
700
+ it('does not retry or leak post-consumption send failures', async () => {
701
+ const first = new FakeWebSocket([{ sessionId: 'session-1' }], {
702
+ sendError: new Error('secret send failure'),
703
+ });
704
+ const factory = new FakeFactory([first, websocket()]);
705
+ const { error } = await collect(
706
+ new STT({ apiKey: 'test-key', webSocketFactory: factory.create }),
707
+ {
708
+ audio: frame(3840),
709
+ connOptions: { maxRetry: 1, retryIntervalMs: 0, timeoutMs: 200 },
710
+ },
711
+ );
712
+ expect(error).toMatchObject({ retryable: false });
713
+ expect(String(error)).not.toContain('secret send failure');
714
+ expect(factory.calls).toHaveLength(1);
715
+ });
716
+
717
+ it('closes the socket when closed during handshake or blocked audio', async () => {
718
+ const handshakeSocket = new FakeWebSocket();
719
+ const handshakeStream = new STT({
720
+ apiKey: 'test-key',
721
+ webSocketFactory: new FakeFactory([handshakeSocket]).create,
722
+ }).stream({ connOptions: TEST_OPTIONS });
723
+ await handshakeSocket.handshakeSent.promise;
724
+ handshakeStream.close();
725
+ await waitUntil(() => handshakeSocket.closed);
726
+
727
+ const blockedSocket = new FakeWebSocket([{ sessionId: 'session-1' }], { blockAudio: true });
728
+ const blockedProvider = new STT({
729
+ apiKey: 'test-key',
730
+ webSocketFactory: new FakeFactory([blockedSocket]).create,
731
+ });
732
+ const blockedStream = blockedProvider.stream({ connOptions: TEST_OPTIONS });
733
+ blockedStream.pushFrame(frame(3840));
734
+ await blockedSocket.audioStarted.promise;
735
+ await blockedProvider.close();
736
+ expect(blockedSocket.closed).toBe(true);
737
+ });
738
+
739
+ it.each([
740
+ ['connect-secret', Object.assign(new Error('connect-secret'), { name: 'connect-secret' })],
741
+ [
742
+ 'provider-secret',
743
+ new FakeWebSocket([
744
+ { sessionId: 'session-1' },
745
+ { type: 'error', errorCode: 'invalid_request', message: 'provider-secret' },
746
+ ]),
747
+ ],
748
+ ['close-secret', new FakeWebSocket([{ sessionId: 'session-1' }])],
749
+ ['payload-secret', new FakeWebSocket([{ sessionId: 'session-1' }, '{payload-secret'])],
750
+ ] as const)('redacts transport/provider details: %s', async (secret, outcome) => {
751
+ if (secret === 'close-secret' && outcome instanceof FakeWebSocket) {
752
+ outcome.on('message', () =>
753
+ queueMicrotask(() => outcome.emit('close', 1011, Buffer.from(secret))),
754
+ );
755
+ }
756
+ const { error } = await collect(
757
+ new STT({
758
+ apiKey: 'api-key-secret',
759
+ webSocketFactory: new FakeFactory([outcome]).create,
760
+ }),
761
+ );
762
+ const rendered = `${String(error)}\n${JSON.stringify(error)}`;
763
+ expect(rendered).not.toContain(secret);
764
+ expect(rendered).not.toContain('api-key-secret');
765
+ expect((error as APIError).body).toBeNull();
766
+ expect(error?.cause).toBeUndefined();
767
+ });
768
+
769
+ it('redacts token and body from handshake rejection', async () => {
770
+ const ws = new FakeWebSocket([
771
+ { type: 'error', errorCode: 'unauthorized', message: 'credential api-key-secret rejected' },
772
+ ]);
773
+ const { error } = await collect(
774
+ new STT({ apiKey: 'api-key-secret', webSocketFactory: new FakeFactory([ws]).create }),
775
+ );
776
+ expect(error).toBeInstanceOf(APIStatusError);
777
+ expect(error).toMatchObject({ statusCode: 400, body: null });
778
+ expect(String(error)).not.toContain('api-key-secret');
779
+ expect(String(error)).not.toContain('credential');
780
+ expect(ws.closed).toBe(true);
781
+ });
782
+ });