@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.
package/dist/stt.cjs ADDED
@@ -0,0 +1,858 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var stt_exports = {};
20
+ __export(stt_exports, {
21
+ DEFAULT_MODEL: () => DEFAULT_MODEL,
22
+ DEFAULT_URL: () => DEFAULT_URL,
23
+ MAX_COMPLETED_TURNS: () => MAX_COMPLETED_TURNS,
24
+ STT: () => STT,
25
+ SpeechStream: () => SpeechStream,
26
+ closeError: () => closeError,
27
+ normalizeAccessToken: () => normalizeAccessToken,
28
+ normalizeLanguageHint: () => normalizeLanguageHint,
29
+ speechStreamTestState: () => speechStreamTestState
30
+ });
31
+ module.exports = __toCommonJS(stt_exports);
32
+ var import_agents = require("@livekit/agents");
33
+ var import_node_perf_hooks = require("node:perf_hooks");
34
+ var import_ws = require("ws");
35
+ var import_log = require("./log.cjs");
36
+ const DEFAULT_URL = "wss://api.meta.ai/v1/asr/realtime";
37
+ const DEFAULT_MODEL = "muse-voice-transcribe-1.0";
38
+ const SAMPLE_RATE = 24e3;
39
+ const CHANNELS = 1;
40
+ const SAMPLE_WIDTH_BYTES = 2;
41
+ const CHUNK_DURATION_MS = 80;
42
+ const CHUNK_BYTES = SAMPLE_RATE * CHANNELS * SAMPLE_WIDTH_BYTES * CHUNK_DURATION_MS / 1e3;
43
+ const MAX_MESSAGE_BYTES = 1024 * 1024;
44
+ const MAX_COMPLETED_TURNS = 128;
45
+ const SUPPORTED_LANGUAGES = [
46
+ "Arabic",
47
+ "Bengali",
48
+ "Dutch",
49
+ "English",
50
+ "French",
51
+ "German",
52
+ "Hebrew",
53
+ "Hindi",
54
+ "Indonesian",
55
+ "Italian",
56
+ "Japanese",
57
+ "Kannada",
58
+ "Korean",
59
+ "Malay",
60
+ "Mandarin Chinese",
61
+ "Marathi",
62
+ "Polish",
63
+ "Portuguese",
64
+ "Spanish",
65
+ "Tagalog",
66
+ "Tamil",
67
+ "Telugu",
68
+ "Thai",
69
+ "Turkish",
70
+ "Vietnamese"
71
+ ];
72
+ const LANGUAGE_NAMES = new Map(
73
+ SUPPORTED_LANGUAGES.map((language) => [language.toLowerCase(), language])
74
+ );
75
+ const LANGUAGE_CODES = {
76
+ ar: "Arabic",
77
+ bn: "Bengali",
78
+ de: "German",
79
+ en: "English",
80
+ es: "Spanish",
81
+ fil: "Tagalog",
82
+ fr: "French",
83
+ he: "Hebrew",
84
+ hi: "Hindi",
85
+ id: "Indonesian",
86
+ it: "Italian",
87
+ iw: "Hebrew",
88
+ ja: "Japanese",
89
+ kn: "Kannada",
90
+ ko: "Korean",
91
+ ms: "Malay",
92
+ mr: "Marathi",
93
+ nl: "Dutch",
94
+ pl: "Polish",
95
+ pt: "Portuguese",
96
+ ta: "Tamil",
97
+ te: "Telugu",
98
+ th: "Thai",
99
+ tl: "Tagalog",
100
+ tr: "Turkish",
101
+ vi: "Vietnamese",
102
+ zh: "Mandarin Chinese"
103
+ };
104
+ const RETRYABLE_CLOSE_CODES = /* @__PURE__ */ new Set([1011, 1013]);
105
+ const NON_RETRYABLE_CLOSE_CODES = /* @__PURE__ */ new Set([1008]);
106
+ const SPEECH_STREAM_TEST_STATES = /* @__PURE__ */ new WeakMap();
107
+ const SPEECH_STREAM_CLOSE_PROMISES = /* @__PURE__ */ new WeakMap();
108
+ function speechStreamTestState(stream) {
109
+ const state = SPEECH_STREAM_TEST_STATES.get(stream);
110
+ if (!state) throw new Error("unknown Meta speech stream");
111
+ return state();
112
+ }
113
+ function sanitizedErrorName(error) {
114
+ if (!(error instanceof Error)) return "Error";
115
+ const name = error.constructor.name;
116
+ return /^[A-Za-z_$][\w$]*$/.test(name) ? name : "Error";
117
+ }
118
+ function normalizeHints(values, name) {
119
+ const normalized = [];
120
+ for (const value of values ?? []) {
121
+ const hint = value.trim();
122
+ if (!hint) throw new Error(`${name} entries must be non-empty`);
123
+ if (!normalized.includes(hint)) normalized.push(hint);
124
+ }
125
+ return normalized;
126
+ }
127
+ function normalizeAccessToken(apiKey) {
128
+ var _a, _b;
129
+ const match = apiKey.match(/^(\S+)(?:\s+([\s\S]*))?$/);
130
+ if (((_a = match == null ? void 0 : match[1]) == null ? void 0 : _a.toLowerCase()) === "bearer") {
131
+ const token = (_b = match[2]) == null ? void 0 : _b.trim();
132
+ if (!token) throw new Error("Meta Model API key must include a token after Bearer");
133
+ return `Bearer ${token}`;
134
+ }
135
+ return `Bearer ${apiKey}`;
136
+ }
137
+ function normalizeLanguageBias(values) {
138
+ const normalized = [];
139
+ for (const value of values ?? []) {
140
+ const documentedName = LANGUAGE_NAMES.get(value.trim().toLowerCase());
141
+ if (!documentedName) {
142
+ throw new Error(
143
+ `unsupported languageBias entry ${JSON.stringify(value)}; supported: ${SUPPORTED_LANGUAGES.join(", ")}`
144
+ );
145
+ }
146
+ if (!normalized.includes(documentedName)) normalized.push(documentedName);
147
+ }
148
+ return normalized;
149
+ }
150
+ function normalizeLanguageHint(language) {
151
+ const value = language.trim();
152
+ if (!value) throw new Error("language must be non-empty");
153
+ const documentedName = LANGUAGE_NAMES.get(value.toLowerCase());
154
+ if (documentedName) return documentedName;
155
+ const primary = value.replaceAll("_", "-").split("-", 1)[0].toLowerCase();
156
+ const mappedName = LANGUAGE_CODES[primary];
157
+ if (!mappedName) {
158
+ throw new Error(
159
+ `unsupported Muse Voice language ${JSON.stringify(language)}; supported: ${SUPPORTED_LANGUAGES.join(", ")}`
160
+ );
161
+ }
162
+ return mappedName;
163
+ }
164
+ function protocolError(detail) {
165
+ return new import_agents.APIConnectionError({
166
+ message: `Meta Muse realtime ASR protocol error: ${detail}`,
167
+ options: { retryable: false }
168
+ });
169
+ }
170
+ function serverError(phase) {
171
+ return new import_agents.APIStatusError({
172
+ message: `Meta Muse realtime ASR ${phase} error`,
173
+ options: { statusCode: 400, requestId: null, body: null, retryable: false }
174
+ });
175
+ }
176
+ function closeError(closeCode, phase, retryableOnNormalClose = false) {
177
+ const code = closeCode || -1;
178
+ let retryable;
179
+ if (code === 1e3) retryable = retryableOnNormalClose;
180
+ else if (NON_RETRYABLE_CLOSE_CODES.has(code)) retryable = false;
181
+ else if (RETRYABLE_CLOSE_CODES.has(code)) retryable = true;
182
+ else retryable = true;
183
+ return new import_agents.APIStatusError({
184
+ message: `Meta Muse realtime ASR closed during ${phase}`,
185
+ options: { statusCode: code, body: null, retryable }
186
+ });
187
+ }
188
+ function parseMessage(event, phase, retryableOnNormalClose = false) {
189
+ if (event.kind === "close") {
190
+ throw closeError(event.code, phase, retryableOnNormalClose);
191
+ }
192
+ if (event.kind === "error") {
193
+ throw new import_agents.APIConnectionError({
194
+ message: `Meta Muse realtime ASR ${phase} failed (${event.error.name})`
195
+ });
196
+ }
197
+ if (event.isBinary) throw protocolError(`unexpected message type during ${phase}`);
198
+ try {
199
+ const message = JSON.parse(event.data.toString());
200
+ if (message === null || typeof message !== "object" || Array.isArray(message)) {
201
+ throw protocolError(`non-object message during ${phase}`);
202
+ }
203
+ return message;
204
+ } catch (error) {
205
+ if (error instanceof import_agents.APIError) throw error;
206
+ throw protocolError(`invalid JSON during ${phase}`);
207
+ }
208
+ }
209
+ function normalizeTurnId(value, event) {
210
+ if (typeof value !== "string" && typeof value !== "number" || typeof value === "boolean") {
211
+ throw protocolError(`${event} event has an invalid turnId`);
212
+ }
213
+ const turnId = String(value).trim();
214
+ if (!turnId) throw protocolError(`${event} event has an invalid turnId`);
215
+ return turnId;
216
+ }
217
+ function emptyTurn() {
218
+ return {
219
+ providerStarted: false,
220
+ emittedStart: false,
221
+ finalEmitted: false,
222
+ ended: false,
223
+ usageSeconds: 0,
224
+ usageCaptured: false
225
+ };
226
+ }
227
+ class WebSocketInbox {
228
+ #events = [];
229
+ #waiters = [];
230
+ constructor(ws) {
231
+ ws.on("message", (data, isBinary) => this.#push({ kind: "message", data, isBinary }));
232
+ ws.on("close", (code) => this.#push({ kind: "close", code }));
233
+ ws.on("error", (error) => this.#push({ kind: "error", error }));
234
+ }
235
+ #push(event) {
236
+ const waiter = this.#waiters.shift();
237
+ if (waiter) waiter(event);
238
+ else this.#events.push(event);
239
+ }
240
+ async next(signal) {
241
+ const event = this.#events.shift();
242
+ if (event) return event;
243
+ if (signal == null ? void 0 : signal.aborted) throw signal.reason;
244
+ return new Promise((resolve, reject) => {
245
+ const onAbort = () => {
246
+ const index = this.#waiters.indexOf(onEvent);
247
+ if (index >= 0) this.#waiters.splice(index, 1);
248
+ reject(signal == null ? void 0 : signal.reason);
249
+ };
250
+ const onEvent = (nextEvent) => {
251
+ signal == null ? void 0 : signal.removeEventListener("abort", onAbort);
252
+ resolve(nextEvent);
253
+ };
254
+ this.#waiters.push(onEvent);
255
+ signal == null ? void 0 : signal.addEventListener("abort", onAbort, { once: true });
256
+ });
257
+ }
258
+ }
259
+ function withTimeout(promise, timeoutMs, error) {
260
+ return new Promise((resolve, reject) => {
261
+ const timer = setTimeout(() => reject(error()), timeoutMs);
262
+ promise.then(
263
+ (value) => {
264
+ clearTimeout(timer);
265
+ resolve(value);
266
+ },
267
+ (reason) => {
268
+ clearTimeout(timer);
269
+ reject(reason);
270
+ }
271
+ );
272
+ });
273
+ }
274
+ function send(ws, data) {
275
+ return new Promise((resolve, reject) => {
276
+ try {
277
+ ws.send(data, (error) => error ? reject(error) : resolve());
278
+ } catch (error) {
279
+ reject(error);
280
+ }
281
+ });
282
+ }
283
+ class STT extends import_agents.stt.STT {
284
+ #opts;
285
+ #streams = /* @__PURE__ */ new Set();
286
+ #streamRegistry = new FinalizationRegistry((ref) => {
287
+ this.#streams.delete(ref);
288
+ });
289
+ #closed = false;
290
+ label = "meta.STT";
291
+ constructor(opts = {}) {
292
+ var _a, _b;
293
+ super({
294
+ streaming: true,
295
+ interimResults: true,
296
+ diarization: false,
297
+ alignedTranscript: false,
298
+ keyterms: false
299
+ });
300
+ const resolvedKey = opts.apiKey !== void 0 ? opts.apiKey.trim() : ((_a = process.env.MODEL_API_KEY) == null ? void 0 : _a.trim()) || ((_b = process.env.META_API_KEY) == null ? void 0 : _b.trim()) || "";
301
+ if (!resolvedKey) {
302
+ throw new Error(
303
+ "Meta Model API key is required. Pass apiKey or set MODEL_API_KEY or META_API_KEY"
304
+ );
305
+ }
306
+ const model = (opts.model ?? DEFAULT_MODEL).trim();
307
+ if (!model) throw new Error("model must be non-empty");
308
+ const url = opts.url ?? DEFAULT_URL;
309
+ let parsedUrl;
310
+ try {
311
+ parsedUrl = new URL(url);
312
+ } catch {
313
+ throw new Error("url must be an absolute wss:// URL without credentials or a fragment");
314
+ }
315
+ if (parsedUrl.protocol !== "wss:" || !parsedUrl.hostname || parsedUrl.username || parsedUrl.password || parsedUrl.hash) {
316
+ throw new Error("url must be an absolute wss:// URL without credentials or a fragment");
317
+ }
318
+ this.#opts = {
319
+ apiKey: normalizeAccessToken(resolvedKey),
320
+ model,
321
+ url,
322
+ keywords: normalizeHints(opts.keywords, "keywords"),
323
+ languageBias: normalizeLanguageBias(opts.languageBias),
324
+ webSocketFactory: opts.webSocketFactory ?? ((socketUrl, options) => new import_ws.WebSocket(socketUrl, options))
325
+ };
326
+ }
327
+ get model() {
328
+ return this.#opts.model;
329
+ }
330
+ get provider() {
331
+ return "Meta";
332
+ }
333
+ async _recognize(_buffer) {
334
+ throw new import_agents.APIError("Meta Muse Voice Transcribe supports streaming recognition only", {
335
+ retryable: false
336
+ });
337
+ }
338
+ stream(options = {}) {
339
+ if (this.#closed) throw new Error("Meta STT is closed");
340
+ const languageBias = [...this.#opts.languageBias];
341
+ if (options.language !== void 0) {
342
+ const language = normalizeLanguageHint(options.language);
343
+ if (!languageBias.includes(language)) languageBias.push(language);
344
+ }
345
+ const stream = new SpeechStream(
346
+ this,
347
+ { ...this.#opts, keywords: [...this.#opts.keywords], languageBias },
348
+ options.connOptions
349
+ );
350
+ const ref = new WeakRef(stream);
351
+ this.#streams.add(ref);
352
+ this.#streamRegistry.register(stream, ref);
353
+ return stream;
354
+ }
355
+ async close() {
356
+ var _a;
357
+ this.#closed = true;
358
+ const closing = [];
359
+ for (const ref of this.#streams) {
360
+ const stream = ref.deref();
361
+ if (!stream) {
362
+ this.#streams.delete(ref);
363
+ continue;
364
+ }
365
+ stream.close();
366
+ closing.push(((_a = SPEECH_STREAM_CLOSE_PROMISES.get(stream)) == null ? void 0 : _a()) ?? Promise.resolve());
367
+ }
368
+ await Promise.all(closing);
369
+ }
370
+ }
371
+ class SpeechStream extends import_agents.stt.SpeechStream {
372
+ #opts;
373
+ #timeoutMs;
374
+ #logger = (0, import_log.log)();
375
+ #turns = /* @__PURE__ */ new Map();
376
+ #completedTurnIds = /* @__PURE__ */ new Set();
377
+ #completedTurnOrder = [];
378
+ #providerActiveTurnId;
379
+ #sessionId = "";
380
+ #audioConsumed = false;
381
+ #endStreamSent = false;
382
+ #lastAudioProcessedMs = 0;
383
+ #pendingUsageSeconds = 0;
384
+ #ws;
385
+ #attemptDone = Promise.resolve();
386
+ #resolveAttemptDone;
387
+ label = "meta.SpeechStream";
388
+ constructor(sttInstance, opts, connOptions) {
389
+ super(sttInstance, SAMPLE_RATE, connOptions);
390
+ this.#opts = opts;
391
+ this.#timeoutMs = (connOptions == null ? void 0 : connOptions.timeoutMs) ?? import_agents.DEFAULT_API_CONNECT_OPTIONS.timeoutMs;
392
+ SPEECH_STREAM_TEST_STATES.set(this, () => ({
393
+ audioConsumed: this.#audioConsumed,
394
+ turns: this.#turns,
395
+ completedTurnIds: this.#completedTurnIds,
396
+ completedTurnOrder: this.#completedTurnOrder
397
+ }));
398
+ SPEECH_STREAM_CLOSE_PROMISES.set(this, () => this.#attemptDone);
399
+ }
400
+ async run() {
401
+ var _a;
402
+ if (this.abortSignal.aborted) return;
403
+ this.#attemptDone = new Promise((resolve) => this.#resolveAttemptDone = resolve);
404
+ this.#endStreamSent = false;
405
+ this.#lastAudioProcessedMs = 0;
406
+ const attemptController = new AbortController();
407
+ const abortAttempt = () => attemptController.abort(this.abortSignal.reason);
408
+ this.abortSignal.addEventListener("abort", abortAttempt, { once: true });
409
+ let sender;
410
+ let receiver;
411
+ try {
412
+ const { ws, inbox } = await this.#connect(attemptController.signal);
413
+ this.#ws = ws;
414
+ sender = this.#sendAudio(ws, attemptController.signal);
415
+ receiver = this.#receiveEvents(inbox, attemptController.signal);
416
+ await this.#driveTasks(sender, receiver);
417
+ this.#validateCleanClose();
418
+ } catch (error) {
419
+ if (this.abortSignal.aborted) return;
420
+ if (error instanceof import_agents.APIError) {
421
+ if (this.#audioConsumed && error.retryable) {
422
+ throw new import_agents.APIConnectionError({
423
+ message: "Meta Muse realtime ASR failed after audio was consumed",
424
+ options: { retryable: false }
425
+ });
426
+ }
427
+ throw error;
428
+ }
429
+ const phase = this.#audioConsumed ? "audio streaming" : "connection";
430
+ const errorName = sanitizedErrorName(error);
431
+ throw new import_agents.APIConnectionError({
432
+ message: `Meta Muse realtime ASR ${phase} failed (${errorName})`,
433
+ options: { retryable: !this.#audioConsumed }
434
+ });
435
+ } finally {
436
+ this.abortSignal.removeEventListener("abort", abortAttempt);
437
+ attemptController.abort();
438
+ this.#closeSocket();
439
+ await Promise.allSettled([sender, receiver].filter((task) => !!task));
440
+ try {
441
+ if (!this.closed) this.#flushUsage();
442
+ } finally {
443
+ (_a = this.#resolveAttemptDone) == null ? void 0 : _a.call(this);
444
+ this.#resolveAttemptDone = void 0;
445
+ }
446
+ }
447
+ }
448
+ flush() {
449
+ if (this.input.closed) throw new Error("Input is closed");
450
+ if (this.closed) throw new Error("Stream is closed");
451
+ this.#flushInputResampler();
452
+ this.input.put(SpeechStream.FLUSH_SENTINEL);
453
+ }
454
+ endInput() {
455
+ if (this.input.closed) throw new Error("Input is closed");
456
+ if (this.closed) throw new Error("Stream is closed");
457
+ this.#flushInputResampler();
458
+ this.input.close();
459
+ }
460
+ #flushInputResampler() {
461
+ if (!this.resampler) return;
462
+ const resampler = this.resampler;
463
+ this.resampler = void 0;
464
+ for (const frame of resampler.flush()) this.input.put(frame);
465
+ resampler.close();
466
+ }
467
+ async #connect(signal) {
468
+ const startedAt = import_node_perf_hooks.performance.now();
469
+ let ws;
470
+ try {
471
+ ws = this.#opts.webSocketFactory(this.#opts.url, {
472
+ handshakeTimeout: this.#timeoutMs,
473
+ maxPayload: MAX_MESSAGE_BYTES
474
+ });
475
+ } catch (error) {
476
+ const errorName = sanitizedErrorName(error);
477
+ throw new import_agents.APIConnectionError({
478
+ message: `Meta Muse realtime ASR connection failed (${errorName})`
479
+ });
480
+ }
481
+ const inbox = new WebSocketInbox(ws);
482
+ try {
483
+ await withTimeout(
484
+ new Promise((resolve, reject) => {
485
+ const cleanup = () => {
486
+ ws.off("open", onOpen);
487
+ ws.off("unexpected-response", onUnexpectedResponse);
488
+ ws.off("error", onError);
489
+ ws.off("close", onClose);
490
+ signal.removeEventListener("abort", onAbort);
491
+ };
492
+ const onOpen = () => {
493
+ cleanup();
494
+ resolve();
495
+ };
496
+ const onUnexpectedResponse = (_request, response) => {
497
+ cleanup();
498
+ reject(
499
+ new import_agents.APIStatusError({
500
+ message: "Meta Muse realtime ASR connection was rejected",
501
+ options: { statusCode: response.statusCode ?? -1, body: null }
502
+ })
503
+ );
504
+ };
505
+ const onError = (error) => {
506
+ cleanup();
507
+ reject(
508
+ new import_agents.APIConnectionError({
509
+ message: `Meta Muse realtime ASR connection failed (${sanitizedErrorName(error)})`
510
+ })
511
+ );
512
+ };
513
+ const onClose = (code) => {
514
+ cleanup();
515
+ reject(closeError(code, "connection", true));
516
+ };
517
+ const onAbort = () => {
518
+ cleanup();
519
+ reject(signal.reason);
520
+ };
521
+ ws.once("open", onOpen);
522
+ ws.once("unexpected-response", onUnexpectedResponse);
523
+ ws.once("error", onError);
524
+ ws.once("close", onClose);
525
+ signal.addEventListener("abort", onAbort, { once: true });
526
+ if (ws.readyState === import_ws.WebSocket.OPEN) onOpen();
527
+ }),
528
+ this.#timeoutMs,
529
+ () => new import_agents.APITimeoutError({ message: "Meta Muse realtime ASR connection timed out" })
530
+ );
531
+ await send(ws, JSON.stringify(this.#handshake()));
532
+ const event = await withTimeout(
533
+ inbox.next(signal),
534
+ this.#timeoutMs,
535
+ () => new import_agents.APITimeoutError({ message: "Meta Muse realtime ASR handshake timed out" })
536
+ );
537
+ this.#acceptHandshake(parseMessage(event, "handshake", true));
538
+ } catch (error) {
539
+ this.#closeSocket(ws);
540
+ throw error;
541
+ }
542
+ this.#logger.debug(
543
+ { durationMs: import_node_perf_hooks.performance.now() - startedAt },
544
+ "Muse STT connection acquired"
545
+ );
546
+ return { ws, inbox };
547
+ }
548
+ #handshake() {
549
+ const handshake = {
550
+ mode: "ENDPOINTING",
551
+ authorization: { accessToken: this.#opts.apiKey },
552
+ audioEncoding: "PCM_24KHZ",
553
+ model: this.#opts.model,
554
+ partialMode: "CUMULATIVE",
555
+ emitAudioProgress: true
556
+ };
557
+ if (this.#opts.keywords.length) handshake.keywords = this.#opts.keywords;
558
+ if (this.#opts.languageBias.length) handshake.languageBias = this.#opts.languageBias;
559
+ return handshake;
560
+ }
561
+ #acceptHandshake(message) {
562
+ if (message.type === "error") throw serverError("handshake");
563
+ if (typeof message.sessionId !== "string" || !message.sessionId) {
564
+ throw new import_agents.APIConnectionError({
565
+ message: "Meta Muse realtime ASR sent an invalid handshake response",
566
+ options: { retryable: false }
567
+ });
568
+ }
569
+ this.#sessionId = message.sessionId;
570
+ }
571
+ async #driveTasks(sender, receiver) {
572
+ const first = await Promise.race([
573
+ sender.then(
574
+ () => ({ task: "sender" }),
575
+ (error) => ({ task: "sender", error })
576
+ ),
577
+ receiver.then(
578
+ () => ({ task: "receiver" }),
579
+ (error) => ({ task: "receiver", error })
580
+ )
581
+ ]);
582
+ if ("error" in first) throw first.error;
583
+ if (first.task === "receiver") {
584
+ if (!this.#endStreamSent) {
585
+ throw new import_agents.APIConnectionError({
586
+ message: "Meta Muse realtime ASR closed before input ended",
587
+ options: { retryable: !this.#audioConsumed }
588
+ });
589
+ }
590
+ await sender;
591
+ return;
592
+ }
593
+ await withTimeout(
594
+ receiver,
595
+ this.#timeoutMs,
596
+ () => new import_agents.APITimeoutError({
597
+ message: "Meta Muse realtime ASR timed out while draining final events",
598
+ options: { retryable: !this.#audioConsumed }
599
+ })
600
+ );
601
+ }
602
+ async #sendAudio(ws, signal) {
603
+ let pending = Buffer.alloc(0);
604
+ let pacingOrigin;
605
+ let sentDurationMs = 0;
606
+ const abortPromise = (0, import_agents.waitForAbort)(signal);
607
+ const iterator = this.input[Symbol.asyncIterator]();
608
+ const sendPacket = async (packet) => {
609
+ if (!packet.length) return;
610
+ pacingOrigin ??= import_node_perf_hooks.performance.now();
611
+ const delayMs = pacingOrigin + sentDurationMs - import_node_perf_hooks.performance.now();
612
+ if (delayMs > 0) {
613
+ const result = await Promise.race([
614
+ new Promise((resolve) => setTimeout(() => resolve("elapsed"), delayMs)),
615
+ abortPromise
616
+ ]);
617
+ if (result !== "elapsed") return;
618
+ }
619
+ try {
620
+ await send(ws, packet);
621
+ } catch (error) {
622
+ const errorName = sanitizedErrorName(error);
623
+ throw new import_agents.APIConnectionError({
624
+ message: `Meta Muse realtime ASR audio send failed (${errorName})`,
625
+ options: { retryable: false }
626
+ });
627
+ }
628
+ sentDurationMs += packet.length / (SAMPLE_RATE * CHANNELS * SAMPLE_WIDTH_BYTES) * 1e3;
629
+ };
630
+ while (true) {
631
+ const result = await Promise.race([iterator.next(), abortPromise]);
632
+ if (result === void 0) return;
633
+ if (result.done) break;
634
+ const item = result.value;
635
+ if (item === SpeechStream.FLUSH_SENTINEL) {
636
+ await sendPacket(pending);
637
+ pending = Buffer.alloc(0);
638
+ continue;
639
+ }
640
+ this.#audioConsumed = true;
641
+ if (item.channels !== CHANNELS) {
642
+ throw new import_agents.APIError("Meta Muse realtime ASR requires mono audio", { retryable: false });
643
+ }
644
+ pending = Buffer.concat([
645
+ pending,
646
+ Buffer.from(item.data.buffer, item.data.byteOffset, item.data.byteLength)
647
+ ]);
648
+ while (pending.length >= CHUNK_BYTES) {
649
+ await sendPacket(pending.subarray(0, CHUNK_BYTES));
650
+ pending = pending.subarray(CHUNK_BYTES);
651
+ }
652
+ }
653
+ await sendPacket(pending);
654
+ if (!this.#endStreamSent) {
655
+ try {
656
+ await send(ws, '{"type":"endStream"}');
657
+ } catch (error) {
658
+ const errorName = sanitizedErrorName(error);
659
+ throw new import_agents.APIConnectionError({
660
+ message: `Meta Muse realtime ASR end-of-input send failed (${errorName})`,
661
+ options: { retryable: false }
662
+ });
663
+ }
664
+ this.#endStreamSent = true;
665
+ }
666
+ }
667
+ async #receiveEvents(inbox, signal) {
668
+ while (true) {
669
+ const event = await inbox.next(signal);
670
+ if (event.kind === "close") {
671
+ if (this.#endStreamSent && event.code === 1e3) return;
672
+ throw closeError(event.code, "stream", !this.#audioConsumed);
673
+ }
674
+ if (event.kind === "error") {
675
+ throw new import_agents.APIConnectionError({
676
+ message: "Meta Muse realtime ASR WebSocket failed",
677
+ options: { retryable: !this.#audioConsumed }
678
+ });
679
+ }
680
+ const message = parseMessage(event, "stream");
681
+ const eventType = message.type;
682
+ if (eventType === "error") throw serverError("stream");
683
+ if (eventType === "speechStart") this.#speechStart(message);
684
+ else if (eventType === "transcript") this.#transcript(message);
685
+ else if (eventType === "speechEnd") this.#speechEnd(message);
686
+ else if (eventType === "speechComplete") this.#speechComplete(message);
687
+ else if (eventType === "audioProgress") this.#audioProgress(message);
688
+ }
689
+ }
690
+ #audioProgress(message) {
691
+ const processedMs = message.audioProcessedMs;
692
+ if (typeof processedMs !== "number" || !Number.isFinite(processedMs) || processedMs < 0) {
693
+ throw protocolError("audioProgress event has invalid audioProcessedMs");
694
+ }
695
+ if (processedMs <= this.#lastAudioProcessedMs) return;
696
+ this.#pendingUsageSeconds += (processedMs - this.#lastAudioProcessedMs) / 1e3;
697
+ this.#lastAudioProcessedMs = processedMs;
698
+ }
699
+ #speechStart(message) {
700
+ const turnId = this.#requiredTurnId(message, "speechStart");
701
+ if (this.#completedTurnIds.has(turnId)) return;
702
+ const turn = this.#getTurn(turnId);
703
+ turn.providerStarted = true;
704
+ this.#providerActiveTurnId = turnId;
705
+ this.#drainTurns();
706
+ }
707
+ #transcript(message) {
708
+ const text = message.transcript;
709
+ if (typeof text !== "string") throw protocolError("transcript event has invalid text");
710
+ if (!text && message.turnId === void 0 && this.#providerActiveTurnId === void 0) return;
711
+ const turnId = this.#transcriptTurnId(message);
712
+ if (this.#completedTurnIds.has(turnId)) return;
713
+ const turn = this.#getTurn(turnId);
714
+ if (turn.finalText !== void 0 || turn.latestInterim === text) return;
715
+ turn.latestInterim = text;
716
+ this.#drainTurns();
717
+ }
718
+ #speechEnd(message) {
719
+ const turnId = this.#requiredTurnId(message, "speechEnd");
720
+ if (this.#completedTurnIds.has(turnId)) return;
721
+ const turn = this.#getTurn(turnId);
722
+ turn.ended = true;
723
+ if (this.#providerActiveTurnId === turnId) this.#providerActiveTurnId = void 0;
724
+ this.#captureTurnUsage(turn);
725
+ this.#drainTurns();
726
+ }
727
+ #speechComplete(message) {
728
+ const turnId = this.#requiredTurnId(message, "speechComplete");
729
+ if (this.#completedTurnIds.has(turnId)) return;
730
+ const text = message.transcript;
731
+ if (typeof text !== "string")
732
+ throw protocolError("speechComplete event has invalid transcript");
733
+ const turn = this.#getTurn(turnId);
734
+ turn.finalText ??= text;
735
+ this.#captureTurnUsage(turn);
736
+ this.#drainTurns();
737
+ }
738
+ #getTurn(turnId) {
739
+ let turn = this.#turns.get(turnId);
740
+ if (!turn) {
741
+ turn = emptyTurn();
742
+ this.#turns.set(turnId, turn);
743
+ }
744
+ return turn;
745
+ }
746
+ #captureTurnUsage(turn) {
747
+ if (turn.usageCaptured || !turn.ended) return;
748
+ turn.usageSeconds = this.#pendingUsageSeconds;
749
+ turn.usageCaptured = true;
750
+ this.#pendingUsageSeconds = 0;
751
+ }
752
+ #drainTurns() {
753
+ while (this.#turns.size) {
754
+ const [turnId, turn] = this.#turns.entries().next().value;
755
+ const hasContent = turn.latestInterim !== void 0 || turn.finalText !== void 0;
756
+ if (!turn.emittedStart && (turn.providerStarted || hasContent)) {
757
+ turn.emittedStart = true;
758
+ this.#emit(import_agents.stt.SpeechEventType.START_OF_SPEECH, turnId);
759
+ }
760
+ if (turn.emittedStart && !turn.finalEmitted && turn.latestInterim !== void 0 && turn.latestInterim !== turn.emittedInterim) {
761
+ turn.emittedInterim = turn.latestInterim;
762
+ this.#emit(import_agents.stt.SpeechEventType.INTERIM_TRANSCRIPT, turnId, turn.latestInterim);
763
+ }
764
+ if (turn.emittedStart && !turn.finalEmitted && turn.finalText !== void 0) {
765
+ turn.finalEmitted = true;
766
+ this.#emit(import_agents.stt.SpeechEventType.FINAL_TRANSCRIPT, turnId, turn.finalText);
767
+ }
768
+ if (!(turn.finalEmitted && turn.ended)) return;
769
+ this.#emit(import_agents.stt.SpeechEventType.END_OF_SPEECH, turnId);
770
+ this.#emitUsage(turn.usageSeconds);
771
+ this.#turns.delete(turnId);
772
+ this.#rememberCompletedTurn(turnId);
773
+ }
774
+ }
775
+ #rememberCompletedTurn(turnId) {
776
+ if (this.#completedTurnIds.has(turnId)) return;
777
+ if (this.#completedTurnOrder.length >= MAX_COMPLETED_TURNS) {
778
+ this.#completedTurnIds.delete(this.#completedTurnOrder.shift());
779
+ }
780
+ this.#completedTurnOrder.push(turnId);
781
+ this.#completedTurnIds.add(turnId);
782
+ }
783
+ #emit(type, requestId, text) {
784
+ this.queue.put({
785
+ type,
786
+ requestId,
787
+ ...text === void 0 ? {} : {
788
+ alternatives: [
789
+ {
790
+ language: (0, import_agents.normalizeLanguage)(""),
791
+ text,
792
+ startTime: 0,
793
+ endTime: 0,
794
+ confidence: 0
795
+ }
796
+ ]
797
+ }
798
+ });
799
+ }
800
+ #emitUsage(duration) {
801
+ if (duration <= 0) return;
802
+ this.queue.put({
803
+ type: import_agents.stt.SpeechEventType.RECOGNITION_USAGE,
804
+ requestId: this.#sessionId,
805
+ recognitionUsage: { audioDuration: duration }
806
+ });
807
+ }
808
+ #flushUsage() {
809
+ let duration = this.#pendingUsageSeconds;
810
+ this.#pendingUsageSeconds = 0;
811
+ for (const turn of this.#turns.values()) {
812
+ duration += turn.usageSeconds;
813
+ turn.usageSeconds = 0;
814
+ }
815
+ this.#emitUsage(duration);
816
+ }
817
+ #transcriptTurnId(message) {
818
+ if (message.turnId !== void 0) return normalizeTurnId(message.turnId, "transcript");
819
+ if (this.#providerActiveTurnId !== void 0) return this.#providerActiveTurnId;
820
+ throw protocolError("transcript event is missing turnId outside an active turn");
821
+ }
822
+ #requiredTurnId(message, event) {
823
+ if (message.turnId === void 0) throw protocolError(`${event} event is missing turnId`);
824
+ return normalizeTurnId(message.turnId, event);
825
+ }
826
+ #validateCleanClose() {
827
+ if (this.#turns.size) {
828
+ throw new import_agents.APIConnectionError({
829
+ message: "Meta Muse realtime ASR closed with incomplete speech turns",
830
+ options: { retryable: false }
831
+ });
832
+ }
833
+ }
834
+ #closeSocket(ws = this.#ws) {
835
+ if (!ws) return;
836
+ try {
837
+ if (ws.readyState === import_ws.WebSocket.OPEN || ws.readyState === import_ws.WebSocket.CONNECTING) ws.close();
838
+ } catch {
839
+ }
840
+ }
841
+ close() {
842
+ this.#closeSocket();
843
+ super.close();
844
+ }
845
+ }
846
+ // Annotate the CommonJS export names for ESM import in node:
847
+ 0 && (module.exports = {
848
+ DEFAULT_MODEL,
849
+ DEFAULT_URL,
850
+ MAX_COMPLETED_TURNS,
851
+ STT,
852
+ SpeechStream,
853
+ closeError,
854
+ normalizeAccessToken,
855
+ normalizeLanguageHint,
856
+ speechStreamTestState
857
+ });
858
+ //# sourceMappingURL=stt.cjs.map