@adea-ai/voice 0.0.0-stage → 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 (60) hide show
  1. package/README.md +136 -2
  2. package/dist/cli/helpers-cli.d.ts +2 -0
  3. package/dist/cli/helpers-cli.js +117 -0
  4. package/dist/contract/contract.d.ts +157 -0
  5. package/dist/contract/errors.d.ts +26 -0
  6. package/dist/contract/index.d.ts +10 -0
  7. package/dist/contract/index.js +64 -0
  8. package/dist/contract/session.d.ts +71 -0
  9. package/dist/contract/turns.d.ts +91 -0
  10. package/dist/contract/wire.d.ts +279 -0
  11. package/dist/desktop/conversation.d.ts +86 -0
  12. package/dist/desktop/desktop-voice.d.ts +212 -0
  13. package/dist/desktop/helper-lock.d.ts +121 -0
  14. package/dist/desktop/helper-process.d.ts +96 -0
  15. package/dist/desktop/index.d.ts +9 -0
  16. package/dist/desktop/index.js +1454 -0
  17. package/dist/desktop/macho-digest.d.ts +9 -0
  18. package/dist/index-7n7epq1a.js +47 -0
  19. package/dist/index-a7d617zr.js +295 -0
  20. package/dist/index-ght8wwpd.js +156 -0
  21. package/dist/index-m4g2tpeq.js +522 -0
  22. package/dist/index-r4hz8gk0.js +10 -0
  23. package/dist/index-tvz9s9nz.js +77 -0
  24. package/dist/index.d.ts +7 -0
  25. package/dist/index.js +96 -0
  26. package/dist/settings/index.d.ts +5 -0
  27. package/dist/settings/index.js +34 -0
  28. package/dist/settings/settings.d.ts +163 -0
  29. package/dist/web/index.d.ts +16 -0
  30. package/dist/web/index.js +1697 -0
  31. package/dist/web/stt/speech-recognition.d.ts +226 -0
  32. package/dist/web/tts/locale-match.d.ts +40 -0
  33. package/dist/web/tts/phonon.d.ts +139 -0
  34. package/dist/web/tts/player.d.ts +115 -0
  35. package/dist/web/tts/system-voices.d.ts +162 -0
  36. package/dist/web/turns.d.ts +91 -0
  37. package/package.json +68 -4
  38. package/src/cli/helpers-cli.ts +135 -0
  39. package/src/contract/contract.ts +393 -0
  40. package/src/contract/errors.ts +98 -0
  41. package/src/contract/index.ts +10 -0
  42. package/src/contract/session.ts +77 -0
  43. package/src/contract/turns.ts +48 -0
  44. package/src/contract/wire.ts +384 -0
  45. package/src/desktop/conversation.ts +347 -0
  46. package/src/desktop/desktop-voice.ts +1129 -0
  47. package/src/desktop/helper-lock.ts +550 -0
  48. package/src/desktop/helper-process.ts +408 -0
  49. package/src/desktop/index.ts +18 -0
  50. package/src/desktop/macho-digest.ts +135 -0
  51. package/src/index.ts +7 -0
  52. package/src/settings/index.ts +5 -0
  53. package/src/settings/settings.ts +478 -0
  54. package/src/web/index.ts +16 -0
  55. package/src/web/stt/speech-recognition.ts +1013 -0
  56. package/src/web/tts/locale-match.ts +131 -0
  57. package/src/web/tts/phonon.ts +386 -0
  58. package/src/web/tts/player.ts +271 -0
  59. package/src/web/tts/system-voices.ts +510 -0
  60. package/src/web/turns.ts +235 -0
@@ -0,0 +1,1697 @@
1
+ import {
2
+ DEFAULT_ENDPOINTING2
3
+ } from "../index-r4hz8gk0.js";
4
+ import {
5
+ VOICE_CONTRACT2,
6
+ AVAILABLE2,
7
+ availableWithMatch2,
8
+ unavailable2,
9
+ isAvailable2
10
+ } from "../index-ght8wwpd.js";
11
+ import {
12
+ VoiceError2
13
+ } from "../index-tvz9s9nz.js";
14
+ // src/web/stt/speech-recognition.ts
15
+ function recognitionConstructor(environment) {
16
+ return environment.SpeechRecognition ?? environment.webkitSpeechRecognition;
17
+ }
18
+ var WEB = ["web"];
19
+ var LOCAL_RECOGNITION_ID = "web.speech-recognition-local";
20
+ var SERVICE_RECOGNITION_ID = "web.speech-recognition-service";
21
+ function browserRecognitionLocal(environment = globalThis) {
22
+ return new BrowserRecognitionProvider("local", environment);
23
+ }
24
+ function browserRecognitionService(environment = globalThis) {
25
+ return new BrowserRecognitionProvider("service", environment);
26
+ }
27
+
28
+ class BrowserRecognitionProvider {
29
+ descriptor;
30
+ environment;
31
+ mode;
32
+ constructor(mode, environment) {
33
+ this.mode = mode;
34
+ this.environment = environment;
35
+ this.descriptor = {
36
+ id: mode === "local" ? LOCAL_RECOGNITION_ID : SERVICE_RECOGNITION_ID,
37
+ displayName: mode === "local" ? "Browser dictation (on-device)" : "Browser dictation (browser service)",
38
+ kind: "speechToText",
39
+ platforms: WEB,
40
+ execution: mode === "local" ? "onDevice" : "network",
41
+ contract: VOICE_CONTRACT2,
42
+ requiresModelDownload: mode === "local",
43
+ modelFamilies: mode === "local" ? ["browser.on-device-recognition"] : [],
44
+ licenses: [
45
+ { spdxIdentifier: mode === "local" ? "Browser-On-Device-Recognition" : "Browser-Speech-Service", commercialUse: true }
46
+ ],
47
+ capabilities: {
48
+ streamingPartials: true,
49
+ trueCancellation: true,
50
+ modelInstallation: mode === "local",
51
+ localeSelection: true
52
+ }
53
+ };
54
+ }
55
+ async availability(locale) {
56
+ const constructor = recognitionConstructor(this.environment);
57
+ if (constructor === undefined) {
58
+ return unavailable2("unsupportedPlatform", "this browser has no Web Speech API", {
59
+ kind: "chooseAnotherProvider",
60
+ detail: "use a browser with speech recognition, or the native app"
61
+ });
62
+ }
63
+ if (this.mode === "service") {
64
+ return AVAILABLE2;
65
+ }
66
+ if (constructor.available === undefined) {
67
+ return unavailable2("unsupportedDevice", "this browser cannot run recognition on-device, so offline dictation is not offered here", { kind: "chooseAnotherProvider", detail: "use a browser with on-device recognition, or dictation with network consent" });
68
+ }
69
+ const state = await probeOnDevice(constructor, locale);
70
+ switch (state) {
71
+ case "available":
72
+ return AVAILABLE2;
73
+ case "downloadable":
74
+ case "downloading":
75
+ return unavailable2("modelNotInstalled", `the ${locale} recognition model is not installed on this device`, {
76
+ kind: "installModel",
77
+ detail: `install the ${locale} browser recognition model`
78
+ });
79
+ case "unavailable":
80
+ return unavailable2("unsupportedLocale", `${locale} has no on-device recognition model in this browser`, {
81
+ kind: "switchLocale",
82
+ detail: "choose a language this browser supports on-device"
83
+ });
84
+ }
85
+ }
86
+ async installModel(locale, options) {
87
+ if (options?.allowDownload !== true) {
88
+ throw new VoiceError2("denied", "installing a recognition model needs the person's explicit download consent");
89
+ }
90
+ if (options.settings?.privacy.offlineOnly === true) {
91
+ throw new VoiceError2("denied", "offline-only mode forbids downloading a recognition model");
92
+ }
93
+ const constructor = recognitionConstructor(this.environment);
94
+ const install = constructor?.install;
95
+ if (constructor === undefined || install === undefined) {
96
+ throw new VoiceError2("assets_missing", "this browser has no on-device recognition install path");
97
+ }
98
+ const signal = options.signal;
99
+ if (signal?.aborted)
100
+ throw new VoiceError2("cancelled", "the model install was cancelled before it started");
101
+ const report = (phase) => {
102
+ try {
103
+ options.onProgress?.({ locale, phase });
104
+ } catch {}
105
+ };
106
+ report("started");
107
+ let settled = false;
108
+ let onAbort;
109
+ const aborted = new Promise((_, reject) => {
110
+ onAbort = () => reject(new VoiceError2("cancelled", "the model install was cancelled; the browser may finish it in the background"));
111
+ signal?.addEventListener("abort", onAbort, { once: true });
112
+ });
113
+ this.pollInstall(constructor, locale, options.pollIntervalMs ?? 500, () => settled, () => report("downloading"));
114
+ try {
115
+ const installed = await Promise.race([Promise.resolve(install.call(constructor, { langs: [locale] })), aborted]);
116
+ report(installed ? "installed" : "failed");
117
+ return installed;
118
+ } catch (error) {
119
+ const wrapped = VoiceError2.wrapping(error);
120
+ report(wrapped.code === "cancelled" ? "cancelled" : "failed");
121
+ throw error instanceof VoiceError2 ? error : wrapped;
122
+ } finally {
123
+ settled = true;
124
+ if (onAbort)
125
+ signal?.removeEventListener("abort", onAbort);
126
+ }
127
+ }
128
+ async pollInstall(constructor, locale, intervalMs, done, downloading) {
129
+ if (constructor.available === undefined)
130
+ return;
131
+ const sleep = this.environment.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
132
+ while (!done()) {
133
+ const state = await probeOnDevice(constructor, locale);
134
+ if (done())
135
+ return;
136
+ if (state === "downloading") {
137
+ downloading();
138
+ return;
139
+ }
140
+ await sleep(intervalMs);
141
+ }
142
+ }
143
+ async createSession(options) {
144
+ if (this.mode === "service" && options.settings?.privacy.offlineOnly === true) {
145
+ throw new VoiceError2("denied", "offline-only mode forbids the browser's network recognition service");
146
+ }
147
+ const availability = await this.availability(options.locale);
148
+ if (!isAvailable2(availability)) {
149
+ const reason = availability.unavailable;
150
+ throw new VoiceError2(codeFor(reason.reason), reason.message);
151
+ }
152
+ if (this.mode === "service" && !options.allowNetwork) {
153
+ throw new VoiceError2("denied", "browser service recognition sends audio to the browser vendor; it needs explicit consent");
154
+ }
155
+ const navigator = this.navigator;
156
+ if (this.mode === "service" && navigator?.onLine === false) {
157
+ throw new VoiceError2("unavailable", "the device is offline, so the browser's recognition service cannot be reached");
158
+ }
159
+ const permission = await queryMicrophone(navigator);
160
+ if (permission?.state === "denied") {
161
+ throw new VoiceError2("denied", "microphone permission is denied for this site");
162
+ }
163
+ const constructor = recognitionConstructor(this.environment);
164
+ if (constructor === undefined)
165
+ throw new VoiceError2("unavailable");
166
+ const recognition = new constructor;
167
+ recognition.lang = options.locale;
168
+ recognition.continuous = true;
169
+ recognition.interimResults = true;
170
+ recognition.maxAlternatives = 1;
171
+ if (this.mode === "local") {
172
+ recognition.processLocally = true;
173
+ if (recognition.processLocally !== true) {
174
+ throw new VoiceError2("unavailable", "this browser did not accept on-device recognition, so offline dictation cannot be proven");
175
+ }
176
+ }
177
+ const audio = await this.openMicrophone(options, recognition);
178
+ return new WebRecognitionSession(recognition, this.mode === "local" ? "onDevice" : "network", {
179
+ endpointing: options.endpointing ?? DEFAULT_ENDPOINTING2,
180
+ now: this.environment.now ?? (() => performance.now()),
181
+ sleep: this.environment.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
182
+ audio,
183
+ permission,
184
+ onSpeechStart: options.onSpeechStart,
185
+ onEarlyEnd: options.onEarlyEnd ?? "finalize",
186
+ maxRestarts: options.maxRestarts ?? 50,
187
+ whenHidden: options.whenHidden ?? "finalize",
188
+ document: this.environment.document,
189
+ window: this.window
190
+ });
191
+ }
192
+ get navigator() {
193
+ return this.environment.navigator;
194
+ }
195
+ get window() {
196
+ const add = this.environment.addEventListener;
197
+ const remove = this.environment.removeEventListener;
198
+ if (add && remove) {
199
+ const target = this.environment;
200
+ return { addEventListener: (type, listener) => add.call(target, type, listener), removeEventListener: (type, listener) => remove.call(target, type, listener) };
201
+ }
202
+ return;
203
+ }
204
+ async openMicrophone(options, recognition) {
205
+ const microphone = options.microphone;
206
+ if (microphone === undefined)
207
+ return;
208
+ const accepts = this.environment.recognitionAcceptsAudioTrack ?? "processLocally" in recognition;
209
+ if (!accepts) {
210
+ throw new VoiceError2("unavailable", "this browser cannot recognise from a chosen microphone, only the default one");
211
+ }
212
+ if ("track" in microphone) {
213
+ return { track: microphone.track, owned: [], stopTrack: microphone.stopOnEnd === true };
214
+ }
215
+ const getUserMedia = this.navigator?.mediaDevices?.getUserMedia;
216
+ if (getUserMedia === undefined) {
217
+ throw new VoiceError2("unavailable", "this browser cannot open a chosen microphone");
218
+ }
219
+ let stream;
220
+ try {
221
+ stream = await getUserMedia.call(this.navigator.mediaDevices, { audio: { deviceId: { exact: microphone.deviceId } } });
222
+ } catch (error) {
223
+ throw mapMediaError(error);
224
+ }
225
+ const tracks = stream.getTracks?.() ?? stream.getAudioTracks();
226
+ const track = stream.getAudioTracks()[0];
227
+ if (track === undefined) {
228
+ for (const owned of tracks)
229
+ owned.stop();
230
+ throw new VoiceError2("unavailable", "the chosen microphone produced no audio track");
231
+ }
232
+ return { track, owned: tracks, stopTrack: true };
233
+ }
234
+ }
235
+ async function queryMicrophone(navigator) {
236
+ const permissions = navigator?.permissions;
237
+ if (permissions === undefined || typeof permissions.query !== "function")
238
+ return;
239
+ try {
240
+ return await permissions.query({ name: "microphone" });
241
+ } catch {
242
+ return;
243
+ }
244
+ }
245
+ function mapMediaError(error) {
246
+ const name = error?.name;
247
+ switch (name) {
248
+ case "NotAllowedError":
249
+ case "SecurityError":
250
+ return new VoiceError2("denied", "microphone permission was denied");
251
+ case "NotFoundError":
252
+ case "OverconstrainedError":
253
+ return new VoiceError2("unavailable", "the chosen microphone is not available");
254
+ case "NotReadableError":
255
+ case "AbortError":
256
+ return new VoiceError2("busy", "the chosen microphone is in use or could not be opened");
257
+ default:
258
+ return VoiceError2.wrapping(error);
259
+ }
260
+ }
261
+ async function probeOnDevice(constructor, locale) {
262
+ try {
263
+ return await constructor.available({ langs: [locale], processLocally: true }) ?? "unavailable";
264
+ } catch {
265
+ return "unavailable";
266
+ }
267
+ }
268
+ function codeFor(reason) {
269
+ switch (reason) {
270
+ case "unsupportedLocale":
271
+ return "language_unsupported";
272
+ case "modelNotInstalled":
273
+ case "modelDownloadDisabled":
274
+ return "assets_missing";
275
+ case "permissionDenied":
276
+ return "denied";
277
+ case "unsupportedDevice":
278
+ case "unsupportedOperatingSystem":
279
+ case "unsupportedPlatform":
280
+ return "unavailable";
281
+ default:
282
+ return "unavailable";
283
+ }
284
+ }
285
+ var MAX_IDLE_RESTARTS = 3;
286
+
287
+ class WebRecognitionSession {
288
+ execution;
289
+ recognition;
290
+ endpointing;
291
+ now;
292
+ sleep;
293
+ queue = [];
294
+ resolved;
295
+ finished = false;
296
+ terminal;
297
+ started = false;
298
+ iterated = false;
299
+ resolveTerminal = undefined;
300
+ terminalSignal = new Promise((resolve) => {
301
+ this.resolveTerminal = resolve;
302
+ });
303
+ finalizedText = "";
304
+ volatileText = "";
305
+ sequence = 0;
306
+ lastWordAt = 0;
307
+ words = false;
308
+ stopRequested = false;
309
+ endPromise;
310
+ config;
311
+ cleanups = [];
312
+ speechSignalled = false;
313
+ restarts = 0;
314
+ idleRestarts = 0;
315
+ constructor(recognition, execution, config) {
316
+ this.recognition = recognition;
317
+ this.execution = execution;
318
+ this.config = config;
319
+ this.endpointing = config.endpointing;
320
+ this.now = config.now;
321
+ this.sleep = config.sleep;
322
+ recognition.onstart = () => {
323
+ this.started = true;
324
+ this.lastWordAt = this.now();
325
+ };
326
+ recognition.onresult = (event) => this.onResult(event);
327
+ recognition.onerror = (event) => this.onError(event);
328
+ recognition.onend = () => this.onEnd();
329
+ recognition.onspeechstart = () => this.signalSpeech();
330
+ this.watchEnvironment();
331
+ }
332
+ watchEnvironment() {
333
+ const permission = this.config.permission;
334
+ if (permission !== undefined) {
335
+ const onChange = () => {
336
+ if (permission.state === "denied")
337
+ this.fail(new VoiceError2("denied", "microphone permission was revoked"));
338
+ };
339
+ if (permission.addEventListener && permission.removeEventListener) {
340
+ permission.addEventListener("change", onChange);
341
+ this.cleanups.push(() => permission.removeEventListener("change", onChange));
342
+ } else if ("onchange" in permission) {
343
+ const previous = permission.onchange ?? null;
344
+ permission.onchange = () => {
345
+ previous?.();
346
+ onChange();
347
+ };
348
+ this.cleanups.push(() => {
349
+ permission.onchange = previous;
350
+ });
351
+ }
352
+ }
353
+ const window = this.config.window;
354
+ if (window !== undefined) {
355
+ if (this.execution === "network") {
356
+ const onOffline = () => this.fail(new VoiceError2("unavailable", "the device went offline, so the browser's recognition service was lost"));
357
+ window.addEventListener("offline", onOffline);
358
+ this.cleanups.push(() => window.removeEventListener("offline", onOffline));
359
+ }
360
+ if (this.config.whenHidden !== "ignore") {
361
+ const onPageHide = () => this.pageHidden();
362
+ window.addEventListener("pagehide", onPageHide);
363
+ this.cleanups.push(() => window.removeEventListener("pagehide", onPageHide));
364
+ }
365
+ }
366
+ const document = this.config.document;
367
+ if (document !== undefined && this.config.whenHidden !== "ignore") {
368
+ const onVisibility = () => {
369
+ if (document.visibilityState === "hidden")
370
+ this.pageHidden();
371
+ };
372
+ document.addEventListener("visibilitychange", onVisibility);
373
+ this.cleanups.push(() => document.removeEventListener("visibilitychange", onVisibility));
374
+ }
375
+ }
376
+ pageHidden() {
377
+ if (this.terminal)
378
+ return;
379
+ this.started = true;
380
+ if (this.config.whenHidden === "cancel")
381
+ this.emitTerminal({ type: "cancelled" });
382
+ else
383
+ this.finishWithCollected();
384
+ }
385
+ signalSpeech() {
386
+ if (this.terminal || this.speechSignalled)
387
+ return;
388
+ this.speechSignalled = true;
389
+ try {
390
+ this.config.onSpeechStart?.();
391
+ } catch {}
392
+ }
393
+ startRecognizer() {
394
+ const track = this.config.audio?.track;
395
+ if (track !== undefined)
396
+ this.recognition.start(track);
397
+ else
398
+ this.recognition.start();
399
+ }
400
+ events() {
401
+ if (this.iterated) {
402
+ throw new VoiceError2("bad_request", "a transcription session's events() can be consumed only once");
403
+ }
404
+ this.iterated = true;
405
+ if (!this.started && !this.terminal) {
406
+ this.started = true;
407
+ this.lastWordAt = this.now();
408
+ this.startWatching();
409
+ try {
410
+ this.startRecognizer();
411
+ } catch (error) {
412
+ this.fail(VoiceError2.wrapping(error));
413
+ }
414
+ }
415
+ let handedOut = false;
416
+ return {
417
+ [Symbol.asyncIterator]: () => {
418
+ if (handedOut)
419
+ throw new VoiceError2("bad_request", "a transcription session's events can be iterated only once");
420
+ handedOut = true;
421
+ return { next: () => this.next() };
422
+ }
423
+ };
424
+ }
425
+ async end() {
426
+ if (this.endPromise)
427
+ return this.endPromise;
428
+ this.stopRequested = true;
429
+ if (!this.started) {
430
+ this.started = true;
431
+ this.fail(new VoiceError2("no_speech"));
432
+ this.endPromise = Promise.resolve();
433
+ return this.endPromise;
434
+ }
435
+ this.endPromise = this.finishByRequest();
436
+ return this.endPromise;
437
+ }
438
+ async cancel() {
439
+ this.started = true;
440
+ if (this.terminal)
441
+ return;
442
+ this.emitTerminal({ type: "cancelled" });
443
+ }
444
+ async finishByRequest() {
445
+ try {
446
+ this.recognition.stop();
447
+ } catch (error) {
448
+ this.fail(VoiceError2.wrapping(error));
449
+ return;
450
+ }
451
+ await Promise.race([
452
+ this.terminalSignal,
453
+ (async () => {
454
+ await this.sleep(this.endpointing.finalizationDeadlineSeconds * 1000);
455
+ if (!this.terminal)
456
+ this.finishWithCollected();
457
+ })()
458
+ ]);
459
+ }
460
+ onResult(event) {
461
+ if (this.terminal)
462
+ return;
463
+ this.idleRestarts = 0;
464
+ let changed = false;
465
+ const volatile = [];
466
+ for (let index = event.resultIndex;index < event.results.length; index += 1) {
467
+ const result = event.results[index];
468
+ if (!result)
469
+ continue;
470
+ const alternative = result[0];
471
+ const transcript = alternative?.transcript ?? "";
472
+ if (result.isFinal) {
473
+ const trimmed = transcript.trim();
474
+ if (trimmed.length > 0) {
475
+ this.finalizedText = joinText(this.finalizedText, trimmed);
476
+ changed = true;
477
+ this.words = true;
478
+ this.lastWordAt = this.now();
479
+ }
480
+ } else {
481
+ volatile.push(transcript);
482
+ if (transcript.trim().length > 0) {
483
+ this.words = true;
484
+ this.lastWordAt = this.now();
485
+ }
486
+ changed = true;
487
+ }
488
+ }
489
+ const volatileText = volatile.reduce(joinText, "");
490
+ if (this.words)
491
+ this.signalSpeech();
492
+ if (volatileText !== this.volatileText)
493
+ changed = true;
494
+ this.volatileText = volatileText;
495
+ if (changed) {
496
+ this.queue.push({
497
+ type: "partial",
498
+ partial: { finalizedText: this.finalizedText, volatileText: this.volatileText, sequence: this.sequence++ }
499
+ });
500
+ this.drain();
501
+ }
502
+ if (this.stopRequested && this.volatileText.length === 0) {
503
+ this.finishWithCollected();
504
+ }
505
+ }
506
+ onError(event) {
507
+ if (this.terminal)
508
+ return;
509
+ const error = mapRecognitionError(event);
510
+ if (error.code === "no_speech") {
511
+ if (this.words) {
512
+ this.finishWithCollected();
513
+ return;
514
+ }
515
+ if (this.config.onEarlyEnd === "restart" && !this.stopRequested)
516
+ return;
517
+ }
518
+ if (error.code === "cancelled") {
519
+ this.emitTerminal({ type: "cancelled" });
520
+ return;
521
+ }
522
+ this.fail(error);
523
+ }
524
+ onEnd() {
525
+ if (this.terminal)
526
+ return;
527
+ if (!this.stopRequested && this.config.onEarlyEnd === "restart" && this.restart())
528
+ return;
529
+ this.finishWithCollected(true);
530
+ }
531
+ restart() {
532
+ if (this.restarts >= this.config.maxRestarts || this.idleRestarts >= MAX_IDLE_RESTARTS)
533
+ return false;
534
+ if (this.volatileText.length > 0) {
535
+ this.finalizedText = joinText(this.finalizedText, this.volatileText);
536
+ this.volatileText = "";
537
+ }
538
+ this.restarts += 1;
539
+ this.idleRestarts += 1;
540
+ this.speechSignalled = false;
541
+ try {
542
+ this.startRecognizer();
543
+ return true;
544
+ } catch {
545
+ return false;
546
+ }
547
+ }
548
+ finishWithCollected(fromEnd = false) {
549
+ this.emitTerminal(this.words ? { type: "final", text: this.text, execution: this.recognitionExecution } : { type: "failed", error: new VoiceError2("no_speech"), execution: this.recognitionExecution }, fromEnd);
550
+ }
551
+ get recognitionExecution() {
552
+ return this.execution === "onDevice" && this.recognition.processLocally === true ? "local" : "service";
553
+ }
554
+ startWatching() {
555
+ this.watch();
556
+ }
557
+ async watch() {
558
+ if (this.watchTask)
559
+ return;
560
+ this.watchTask = (async () => {
561
+ const startedAt = this.now();
562
+ for (;; ) {
563
+ if (this.terminal)
564
+ return;
565
+ await this.sleep(this.endpointing.tickIntervalSeconds * 1000);
566
+ if (this.terminal)
567
+ return;
568
+ const now = this.now();
569
+ if (this.endpointing.maxDurationSeconds !== null && now - startedAt >= this.endpointing.maxDurationSeconds * 1000) {
570
+ await this.end();
571
+ return;
572
+ }
573
+ if (!this.words && now - startedAt >= this.endpointing.noSpeechTimeoutSeconds * 1000) {
574
+ this.fail(new VoiceError2("no_speech"));
575
+ return;
576
+ }
577
+ if (this.words && now - this.lastWordAt >= this.endpointing.silenceLimitSeconds * 1000) {
578
+ await this.end();
579
+ return;
580
+ }
581
+ }
582
+ })();
583
+ }
584
+ watchTask;
585
+ get text() {
586
+ return joinText(this.finalizedText, this.volatileText);
587
+ }
588
+ fail(error) {
589
+ this.emitTerminal({ type: "failed", error, execution: this.recognitionExecution });
590
+ }
591
+ emitTerminal(event, fromEnd = false) {
592
+ if (this.terminal)
593
+ return;
594
+ this.terminal = event.type === "final" ? "final" : event.type === "failed" ? "failed" : "cancelled";
595
+ this.release(fromEnd);
596
+ this.queue.push(event);
597
+ this.finished = true;
598
+ this.drain();
599
+ this.resolveTerminal?.();
600
+ }
601
+ release(fromEnd) {
602
+ const recognition = this.recognition;
603
+ recognition.onstart = null;
604
+ recognition.onresult = null;
605
+ recognition.onerror = null;
606
+ recognition.onend = null;
607
+ if ("onspeechstart" in recognition)
608
+ recognition.onspeechstart = null;
609
+ for (const cleanup of this.cleanups.splice(0)) {
610
+ try {
611
+ cleanup();
612
+ } catch {}
613
+ }
614
+ if (!fromEnd) {
615
+ try {
616
+ recognition.abort();
617
+ } catch {}
618
+ }
619
+ const audio = this.config.audio;
620
+ if (audio !== undefined) {
621
+ const tracks = new Set(audio.owned);
622
+ if (audio.stopTrack)
623
+ tracks.add(audio.track);
624
+ for (const track of tracks) {
625
+ try {
626
+ track.stop();
627
+ } catch {}
628
+ }
629
+ }
630
+ }
631
+ drain() {
632
+ const resolve = this.resolved;
633
+ this.resolved = undefined;
634
+ resolve?.();
635
+ }
636
+ async next() {
637
+ for (;; ) {
638
+ const event = this.queue.shift();
639
+ if (event) {
640
+ if (this.finished && this.queue.length === 0)
641
+ this.resolved = undefined;
642
+ return { value: event, done: false };
643
+ }
644
+ if (this.finished)
645
+ return { value: undefined, done: true };
646
+ await new Promise((resolve) => {
647
+ this.resolved = resolve;
648
+ });
649
+ }
650
+ }
651
+ }
652
+ function mapRecognitionError(event) {
653
+ switch (event.error) {
654
+ case "not-allowed":
655
+ case "service-not-allowed":
656
+ return new VoiceError2("denied", event.message ?? "microphone or recognition permission was denied");
657
+ case "no-speech":
658
+ return new VoiceError2("no_speech");
659
+ case "language-not-supported":
660
+ return new VoiceError2("language_unsupported");
661
+ case "audio-capture":
662
+ return new VoiceError2("unavailable", "no microphone is available");
663
+ case "network":
664
+ return new VoiceError2("failed", "the browser's recognition service could not be reached");
665
+ case "aborted":
666
+ return new VoiceError2("cancelled");
667
+ default:
668
+ return new VoiceError2("failed", event.message ?? `recognition error: ${event.error}`);
669
+ }
670
+ }
671
+ function joinText(left, right) {
672
+ const a = left.trim();
673
+ const b = right.trim();
674
+ if (a.length === 0)
675
+ return b;
676
+ if (b.length === 0)
677
+ return a;
678
+ return `${a} ${b}`;
679
+ }
680
+ // src/web/tts/player.ts
681
+ var defaultAudioContextFactory = {
682
+ create(options) {
683
+ const Constructor = globalThis.AudioContext;
684
+ if (Constructor === undefined) {
685
+ throw new Error("this environment has no AudioContext");
686
+ }
687
+ return new Constructor({ sampleRate: options.sampleRate });
688
+ }
689
+ };
690
+
691
+ class PlaybackUtterance {
692
+ player;
693
+ sources = new Set;
694
+ sealed = false;
695
+ stoppedFlag = false;
696
+ settled = false;
697
+ resolveDrained = () => {};
698
+ drained;
699
+ constructor(player) {
700
+ this.player = player;
701
+ this.drained = new Promise((resolve) => {
702
+ this.resolveDrained = resolve;
703
+ });
704
+ }
705
+ get stopped() {
706
+ return this.stoppedFlag;
707
+ }
708
+ enqueue(pcm) {
709
+ if (this.sealed || this.stoppedFlag)
710
+ return null;
711
+ return this.player.schedule(pcm, this);
712
+ }
713
+ finish() {
714
+ this.sealed = true;
715
+ this.check();
716
+ return this.drained;
717
+ }
718
+ stop() {
719
+ if (this.stoppedFlag)
720
+ return;
721
+ this.stoppedFlag = true;
722
+ this.sealed = true;
723
+ this.player.unschedule(this);
724
+ this.settle(false);
725
+ }
726
+ ended(source) {
727
+ this.sources.delete(source);
728
+ this.check();
729
+ }
730
+ check() {
731
+ if (this.sealed && this.sources.size === 0)
732
+ this.settle(!this.stoppedFlag);
733
+ }
734
+ settle(played) {
735
+ if (this.settled)
736
+ return;
737
+ this.settled = true;
738
+ this.resolveDrained(played);
739
+ }
740
+ }
741
+
742
+ class StreamingPcmPlayer {
743
+ context;
744
+ sampleRate;
745
+ leadSeconds;
746
+ onFirstAudio;
747
+ onDrained;
748
+ sources = [];
749
+ endsAt = new Map;
750
+ owners = new Map;
751
+ utterances = new Set;
752
+ nextStartTime = 0;
753
+ firstAudioReported = false;
754
+ disposed = false;
755
+ constructor(options) {
756
+ this.sampleRate = options.sampleRate;
757
+ this.context = (options.factory ?? defaultAudioContextFactory).create({ sampleRate: options.sampleRate });
758
+ this.leadSeconds = options.leadSeconds ?? 0.05;
759
+ this.onFirstAudio = options.onFirstAudio;
760
+ this.onDrained = options.onDrained;
761
+ }
762
+ beginUtterance() {
763
+ const utterance = new PlaybackUtterance(this);
764
+ if (this.disposed) {
765
+ utterance.stop();
766
+ return utterance;
767
+ }
768
+ this.utterances.add(utterance);
769
+ utterance.drained.then(() => this.utterances.delete(utterance));
770
+ return utterance;
771
+ }
772
+ enqueue(pcm) {
773
+ return this.schedule(pcm, undefined);
774
+ }
775
+ schedule(pcm, owner) {
776
+ if (this.disposed || pcm.length === 0)
777
+ return null;
778
+ const buffer = this.context.createBuffer(1, pcm.length, this.sampleRate);
779
+ buffer.getChannelData?.(0).set(pcm);
780
+ const source = this.context.createBufferSource();
781
+ source.buffer = buffer;
782
+ source.connect(this.context.destination);
783
+ const startAt = Math.max(this.context.currentTime + this.leadSeconds, this.nextStartTime);
784
+ source.onended = () => {
785
+ this.forget(source);
786
+ source.disconnect?.();
787
+ owner?.ended(source);
788
+ if (this.sources.length === 0)
789
+ this.onDrained?.();
790
+ };
791
+ this.sources.push(source);
792
+ this.endsAt.set(source, startAt + buffer.duration);
793
+ if (owner) {
794
+ this.owners.set(source, owner);
795
+ owner.sources.add(source);
796
+ }
797
+ source.start(startAt);
798
+ this.nextStartTime = startAt + buffer.duration;
799
+ if (!this.firstAudioReported) {
800
+ this.firstAudioReported = true;
801
+ this.onFirstAudio?.(startAt);
802
+ }
803
+ return startAt;
804
+ }
805
+ stop() {
806
+ const scheduled = this.sources;
807
+ this.sources = [];
808
+ this.endsAt.clear();
809
+ this.owners.clear();
810
+ for (const source of scheduled)
811
+ this.halt(source);
812
+ for (const utterance of [...this.utterances]) {
813
+ utterance.sources.clear();
814
+ utterance.stop();
815
+ }
816
+ this.utterances.clear();
817
+ this.nextStartTime = 0;
818
+ this.firstAudioReported = false;
819
+ }
820
+ unschedule(utterance) {
821
+ for (const source of utterance.sources) {
822
+ this.forget(source);
823
+ this.halt(source);
824
+ }
825
+ utterance.sources.clear();
826
+ this.utterances.delete(utterance);
827
+ let latest = 0;
828
+ for (const end of this.endsAt.values())
829
+ latest = Math.max(latest, end);
830
+ this.nextStartTime = latest;
831
+ if (this.sources.length === 0)
832
+ this.firstAudioReported = false;
833
+ }
834
+ forget(source) {
835
+ this.sources = this.sources.filter((candidate) => candidate !== source);
836
+ this.endsAt.delete(source);
837
+ this.owners.delete(source);
838
+ }
839
+ halt(source) {
840
+ source.onended = null;
841
+ try {
842
+ source.stop();
843
+ } catch {}
844
+ source.disconnect?.();
845
+ }
846
+ get isPlaying() {
847
+ return this.sources.length > 0;
848
+ }
849
+ async suspend() {
850
+ await this.context.suspend?.();
851
+ }
852
+ async resume() {
853
+ await this.context.resume?.();
854
+ }
855
+ async dispose() {
856
+ if (this.disposed)
857
+ return;
858
+ this.stop();
859
+ this.disposed = true;
860
+ await this.context.close?.();
861
+ }
862
+ }
863
+
864
+ // src/web/tts/phonon.ts
865
+ var defaultPhononRuntime = {
866
+ async load(request) {
867
+ const module = await import("phonon-tts");
868
+ const engine = await module.PhononTTS.load(request);
869
+ return engine;
870
+ }
871
+ };
872
+ async function clearPhononCache() {
873
+ const module = await import("phonon-tts");
874
+ return module.clearCache();
875
+ }
876
+ var PHONON_PROVIDER_ID = "web.phonon";
877
+ var PHONON_EN_FAMILY = "phonon-31m-en";
878
+
879
+ class PhononProvider {
880
+ descriptor;
881
+ options;
882
+ engine;
883
+ player;
884
+ loading;
885
+ loadWaiters = 0;
886
+ progressListeners = new Set;
887
+ constructor(options = {}) {
888
+ this.options = { locale: options.locale ?? "en", family: options.family ?? PHONON_EN_FAMILY, ...options };
889
+ this.descriptor = {
890
+ id: PHONON_PROVIDER_ID,
891
+ displayName: "Phonon 31M (on-device)",
892
+ kind: "textToSpeech",
893
+ platforms: ["web"],
894
+ execution: "onDevice",
895
+ contract: VOICE_CONTRACT2,
896
+ requiresModelDownload: true,
897
+ modelFamilies: [PHONON_EN_FAMILY],
898
+ licenses: [{ spdxIdentifier: "Apache-2.0", commercialUse: true }],
899
+ capabilities: {
900
+ trueCancellation: true,
901
+ voiceSelection: true,
902
+ utteranceQueueing: true,
903
+ localeSelection: false
904
+ }
905
+ };
906
+ }
907
+ get isLoaded() {
908
+ return this.engine !== undefined;
909
+ }
910
+ get voices() {
911
+ return this.engine?.voices ?? [];
912
+ }
913
+ async availability(locale) {
914
+ if (this.options.family !== PHONON_EN_FAMILY) {
915
+ return unavailable2("licenseNotAccepted", "Phonon 40M weights are CC BY-NC 4.0 and are not approved for commercial distribution", { kind: "switchLocale", detail: "use platform voices for non-English speech" });
916
+ }
917
+ const language = locale.toLowerCase().split(/[-_]/)[0] ?? "";
918
+ if (language !== "en") {
919
+ if (language === "es") {
920
+ return unavailable2("licenseNotAccepted", "Spanish needs the Phonon 40M weights, which are CC BY-NC 4.0 and not approved for commercial use", { kind: "chooseAnotherProvider", detail: "use the platform voice for ES-419" });
921
+ }
922
+ return unavailable2("unsupportedLocale", `${locale} is not supported by Phonon 31M`, {
923
+ kind: "chooseAnotherProvider",
924
+ detail: "use a platform voice for this language"
925
+ });
926
+ }
927
+ const supportsSimd = this.options.supportsSimd ?? defaultSupportsSimd;
928
+ if (!supportsSimd()) {
929
+ return unavailable2("unsupportedDevice", "this browser has no WebAssembly SIMD, so Phonon cannot run", {
930
+ kind: "chooseAnotherProvider",
931
+ detail: "use a platform voice in this browser"
932
+ });
933
+ }
934
+ if (this.isLoaded)
935
+ return AVAILABLE2;
936
+ return unavailable2("modelNotInstalled", "the Phonon 31M checkpoint is not installed in this browser", {
937
+ kind: "installModel",
938
+ detail: "download Phonon 31M (about 85 MB) for on-device speech"
939
+ });
940
+ }
941
+ async load(options = {}) {
942
+ const signal = options.signal;
943
+ if (signal?.aborted)
944
+ throw new VoiceError2("cancelled");
945
+ if (this.engine)
946
+ return this.engine;
947
+ const shared = this.loading ?? this.startLoading();
948
+ const listener = options.onProgress;
949
+ if (listener)
950
+ this.progressListeners.add(listener);
951
+ this.loadWaiters += 1;
952
+ let waiting = true;
953
+ const release = () => {
954
+ if (!waiting)
955
+ return;
956
+ waiting = false;
957
+ this.loadWaiters -= 1;
958
+ if (listener)
959
+ this.progressListeners.delete(listener);
960
+ };
961
+ let detach = () => {};
962
+ const aborted = new Promise((_, reject) => {
963
+ if (signal === undefined)
964
+ return;
965
+ const onAbort = () => {
966
+ release();
967
+ reject(new VoiceError2("cancelled"));
968
+ };
969
+ signal.addEventListener("abort", onAbort, { once: true });
970
+ detach = () => signal.removeEventListener("abort", onAbort);
971
+ });
972
+ try {
973
+ return await Promise.race([shared, aborted]);
974
+ } finally {
975
+ release();
976
+ detach();
977
+ }
978
+ }
979
+ startLoading() {
980
+ if (this.options.model === undefined) {
981
+ return Promise.reject(new VoiceError2("assets_missing", "no Phonon model source is configured; the host must pin a revision or serve the assets"));
982
+ }
983
+ const runtime = this.options.runtime ?? defaultPhononRuntime;
984
+ const request = {
985
+ lang: "en",
986
+ model: this.options.model.kind === "pinned" ? undefined : this.options.model.spec,
987
+ quant: "q8",
988
+ cache: this.options.cache ?? true,
989
+ device: this.options.device ?? "cpu",
990
+ threads: this.options.threads ?? "auto",
991
+ onProgress: (progress) => {
992
+ for (const listener of [...this.progressListeners])
993
+ listener(progress);
994
+ }
995
+ };
996
+ const loading = (async () => {
997
+ try {
998
+ const engine = await runtime.load(request);
999
+ if (this.loadWaiters === 0) {
1000
+ engine.dispose();
1001
+ throw new VoiceError2("cancelled");
1002
+ }
1003
+ this.engine = engine;
1004
+ return engine;
1005
+ } catch (error) {
1006
+ throw VoiceError2.wrapping(error);
1007
+ } finally {
1008
+ this.loading = undefined;
1009
+ }
1010
+ })();
1011
+ this.loading = loading;
1012
+ return loading;
1013
+ }
1014
+ speak(text, options = {}) {
1015
+ const engine = this.engine;
1016
+ if (engine === undefined) {
1017
+ return {
1018
+ done: Promise.reject(new VoiceError2("assets_missing", "call load() after the person consents to the download")),
1019
+ cancel: () => {}
1020
+ };
1021
+ }
1022
+ const controller = new AbortController;
1023
+ const player = this.playerFor(engine.sampleRate);
1024
+ const startedAt = (this.options.now ?? defaultNow)();
1025
+ const stream = engine.stream(text, {
1026
+ voice: options.voice,
1027
+ temperature: options.temperature,
1028
+ seed: options.seed,
1029
+ signal: controller.signal
1030
+ });
1031
+ const clock = this.options.now ?? defaultNow;
1032
+ const playback = player.beginUtterance();
1033
+ const signal = controller.signal;
1034
+ const done = (async () => {
1035
+ let firstChunk = true;
1036
+ try {
1037
+ for await (const pcm of stream) {
1038
+ if (signal.aborted)
1039
+ break;
1040
+ if (firstChunk) {
1041
+ firstChunk = false;
1042
+ options.onFirstAudio?.(clock() - startedAt);
1043
+ }
1044
+ playback.enqueue(pcm);
1045
+ options.onChunk?.(pcm.length);
1046
+ }
1047
+ if (signal.aborted)
1048
+ throw new VoiceError2("cancelled");
1049
+ const stats = await stream.done;
1050
+ await playback.finish();
1051
+ if (signal.aborted || playback.stopped)
1052
+ throw new VoiceError2("cancelled");
1053
+ return stats;
1054
+ } catch (error) {
1055
+ playback.stop();
1056
+ throw VoiceError2.wrapping(error);
1057
+ }
1058
+ })();
1059
+ return {
1060
+ done,
1061
+ cancel: () => {
1062
+ if (signal.aborted)
1063
+ return;
1064
+ controller.abort();
1065
+ stream.cancel();
1066
+ playback.stop();
1067
+ }
1068
+ };
1069
+ }
1070
+ dispose() {
1071
+ this.engine?.dispose();
1072
+ this.engine = undefined;
1073
+ this.player?.dispose();
1074
+ this.player = undefined;
1075
+ }
1076
+ playerFor(sampleRate) {
1077
+ if (this.player === undefined) {
1078
+ this.player = new StreamingPcmPlayer({
1079
+ sampleRate,
1080
+ factory: this.options.audioContextFactory
1081
+ });
1082
+ }
1083
+ return this.player;
1084
+ }
1085
+ }
1086
+ var defaultNow = () => typeof performance === "undefined" ? Date.now() : performance.now();
1087
+ function defaultSupportsSimd() {
1088
+ const wasm = globalThis.WebAssembly;
1089
+ if (wasm?.validate === undefined)
1090
+ return false;
1091
+ const probe = new Uint8Array([
1092
+ 0,
1093
+ 97,
1094
+ 115,
1095
+ 109,
1096
+ 1,
1097
+ 0,
1098
+ 0,
1099
+ 0,
1100
+ 1,
1101
+ 5,
1102
+ 1,
1103
+ 96,
1104
+ 0,
1105
+ 1,
1106
+ 123
1107
+ ]);
1108
+ try {
1109
+ return wasm.validate(probe);
1110
+ } catch {
1111
+ return false;
1112
+ }
1113
+ }
1114
+ // src/web/tts/locale-match.ts
1115
+ function parseLocale(tag) {
1116
+ const parts = tag.trim().replace(/_/g, "-").split("-").filter((part) => part.length > 0);
1117
+ const language = (parts[0] ?? "").toLowerCase();
1118
+ let script;
1119
+ let region;
1120
+ for (const part of parts.slice(1)) {
1121
+ if (script === undefined && region === undefined && /^[a-z]{4}$/i.test(part)) {
1122
+ script = part[0].toUpperCase() + part.slice(1).toLowerCase();
1123
+ } else if (region === undefined && (/^[a-z]{2}$/i.test(part) || /^\d{3}$/.test(part))) {
1124
+ region = part.toUpperCase();
1125
+ }
1126
+ }
1127
+ return { language, ...script ? { script } : {}, ...region ? { region } : {} };
1128
+ }
1129
+ var REGION_GROUPS = {
1130
+ es: [
1131
+ ["419", "MX", "US", "AR", "CO", "CL", "PE", "VE", "EC", "GT", "CU", "BO", "DO", "HN", "PY", "SV", "NI", "CR", "PA", "UY", "PR"],
1132
+ ["ES", "GQ", "150"]
1133
+ ],
1134
+ pt: [
1135
+ ["BR"],
1136
+ ["PT", "AO", "MZ", "CV", "GW", "ST", "TL", "MO", "150"]
1137
+ ],
1138
+ en: [
1139
+ ["US", "CA", "PH"],
1140
+ ["GB", "IE", "AU", "NZ", "ZA", "IN", "SG", "HK", "150"]
1141
+ ],
1142
+ fr: [
1143
+ ["FR", "BE", "CH", "LU", "MC", "150"],
1144
+ ["CA"]
1145
+ ],
1146
+ zh: [
1147
+ ["HANS", "CN", "SG", "MY"],
1148
+ ["HANT", "TW", "HK", "MO"]
1149
+ ]
1150
+ };
1151
+ function groupKey(locale) {
1152
+ if (locale.language === "zh" && locale.script)
1153
+ return locale.script.toUpperCase();
1154
+ return locale.region;
1155
+ }
1156
+ function groupOf(locale) {
1157
+ const key = groupKey(locale);
1158
+ if (key === undefined)
1159
+ return;
1160
+ const group = REGION_GROUPS[locale.language]?.find((candidate) => candidate.includes(key));
1161
+ return group ? { group } : undefined;
1162
+ }
1163
+ function matchLocale(requested, voiceLang) {
1164
+ const want = parseLocale(requested);
1165
+ const have = parseLocale(voiceLang);
1166
+ if (want.language.length === 0 || want.language !== have.language)
1167
+ return;
1168
+ if (normalize(requested) === normalize(voiceLang))
1169
+ return { match: "exact", rank: 0 };
1170
+ const wantKey = groupKey(want);
1171
+ const haveKey = groupKey(have);
1172
+ if (wantKey === undefined) {
1173
+ return { match: "region", rank: haveKey === undefined ? 100 : 200 + preferenceIndex(have) };
1174
+ }
1175
+ if (haveKey === wantKey && (want.region === have.region || want.region === undefined || have.region === undefined)) {
1176
+ return { match: "exact", rank: 1 };
1177
+ }
1178
+ const wanted = groupOf(want);
1179
+ if (wanted && haveKey !== undefined && wanted.group.includes(haveKey)) {
1180
+ return { match: "region", rank: 100 + wanted.group.indexOf(haveKey) };
1181
+ }
1182
+ if (have.region === undefined && haveKey === undefined)
1183
+ return { match: "language", rank: 1000 };
1184
+ return { match: "language", rank: 1100 + preferenceIndex(have) };
1185
+ }
1186
+ function preferenceIndex(locale) {
1187
+ const key = groupKey(locale);
1188
+ const groups = REGION_GROUPS[locale.language];
1189
+ if (key === undefined || groups === undefined)
1190
+ return 99;
1191
+ let offset = 0;
1192
+ for (const group of groups) {
1193
+ const index = group.indexOf(key);
1194
+ if (index >= 0)
1195
+ return offset + index;
1196
+ offset += group.length;
1197
+ }
1198
+ return 99;
1199
+ }
1200
+ function normalize(tag) {
1201
+ return tag.trim().replace(/_/g, "-").toLowerCase();
1202
+ }
1203
+ // src/web/tts/system-voices.ts
1204
+ var SYSTEM_VOICES_ID = "web.system-voices";
1205
+ var DEFAULT_VOICES_TIMEOUT_MS = 1500;
1206
+
1207
+ class SystemVoiceProvider {
1208
+ descriptor;
1209
+ environment;
1210
+ inFlight = [];
1211
+ voicesReady;
1212
+ constructor(environment = globalThis) {
1213
+ this.environment = environment;
1214
+ this.descriptor = {
1215
+ id: SYSTEM_VOICES_ID,
1216
+ displayName: "Platform voices",
1217
+ kind: "textToSpeech",
1218
+ platforms: ["web"],
1219
+ execution: "systemProvided",
1220
+ contract: VOICE_CONTRACT2,
1221
+ requiresModelDownload: false,
1222
+ modelFamilies: ["browser.speechSynthesis"],
1223
+ licenses: [{ spdxIdentifier: "Browser-System-Voices", commercialUse: true }],
1224
+ capabilities: { trueCancellation: true, voiceSelection: true, wordBoundaryPause: true, localeSelection: true }
1225
+ };
1226
+ }
1227
+ get Utterance() {
1228
+ return this.environment.Utterance ?? this.environment.SpeechSynthesisUtterance;
1229
+ }
1230
+ voices(locale) {
1231
+ const ranked = this.rankVoices(locale);
1232
+ return {
1233
+ local: ranked.filter((entry) => entry.voice.localService === true).map((entry) => entry.voice),
1234
+ remote: ranked.filter((entry) => entry.voice.localService !== true).map((entry) => entry.voice)
1235
+ };
1236
+ }
1237
+ rankVoices(locale) {
1238
+ const synthesis = this.environment.speechSynthesis;
1239
+ if (synthesis === undefined)
1240
+ return [];
1241
+ return rank(synthesis.getVoices(), locale).map(({ voice, match }) => ({ voice, match: match.match }));
1242
+ }
1243
+ chooseVoice(options = {}) {
1244
+ const synthesis = this.environment.speechSynthesis;
1245
+ if (synthesis === undefined)
1246
+ return new VoiceError2("unavailable");
1247
+ const selection = this.selectVoice(synthesis.getVoices(), options);
1248
+ return selection === undefined || selection instanceof VoiceError2 ? selection : describe(selection);
1249
+ }
1250
+ waitForVoices() {
1251
+ const synthesis = this.environment.speechSynthesis;
1252
+ if (synthesis === undefined || synthesis.getVoices().length > 0)
1253
+ return Promise.resolve();
1254
+ if (this.voicesReady)
1255
+ return this.voicesReady;
1256
+ this.voicesReady = new Promise((resolve) => {
1257
+ let timer;
1258
+ const finish = () => {
1259
+ synthesis.removeEventListener?.("voiceschanged", finish);
1260
+ if (timer !== undefined)
1261
+ this.clearTimer(timer);
1262
+ resolve();
1263
+ };
1264
+ if (synthesis.addEventListener === undefined) {
1265
+ resolve();
1266
+ return;
1267
+ }
1268
+ synthesis.addEventListener("voiceschanged", finish);
1269
+ timer = this.setTimer(finish, this.environment.voicesTimeoutMs ?? DEFAULT_VOICES_TIMEOUT_MS);
1270
+ });
1271
+ return this.voicesReady;
1272
+ }
1273
+ async availability(locale) {
1274
+ if (this.environment.speechSynthesis === undefined || this.Utterance === undefined) {
1275
+ return unavailable2("unsupportedPlatform", "this browser has no speech synthesis", {
1276
+ kind: "chooseAnotherProvider",
1277
+ detail: "use a browser with platform voices"
1278
+ });
1279
+ }
1280
+ await this.waitForVoices();
1281
+ const ranked = this.rankVoices(locale);
1282
+ const local = ranked.filter((entry) => entry.voice.localService === true);
1283
+ const remote = ranked.filter((entry) => entry.voice.localService !== true);
1284
+ const best = local[0];
1285
+ if (best !== undefined) {
1286
+ if (best.match === "language") {
1287
+ return availableWithMatch2("language", `no local ${locale} voice; only ${best.voice.lang} (${best.voice.name}) of the language is installed`);
1288
+ }
1289
+ return availableWithMatch2(best.match);
1290
+ }
1291
+ if (remote.length > 0) {
1292
+ return unavailable2("networkRequired", `only remote ${locale} voices are installed`, {
1293
+ kind: "grantPermission",
1294
+ detail: "use a network voice only with an explicit privacy choice"
1295
+ });
1296
+ }
1297
+ return unavailable2("unsupportedLocale", `no ${locale} voice is installed`, {
1298
+ kind: "installModel",
1299
+ detail: `install a ${locale} voice in the operating system`
1300
+ });
1301
+ }
1302
+ speak(text, options = {}) {
1303
+ const synthesis = this.environment.speechSynthesis;
1304
+ const Utterance = this.Utterance;
1305
+ if (synthesis === undefined || Utterance === undefined) {
1306
+ return { done: Promise.reject(new VoiceError2("unavailable")), cancel: () => {} };
1307
+ }
1308
+ if (text.trim().length === 0) {
1309
+ return { done: Promise.reject(new VoiceError2("bad_request", "cannot speak empty text")), cancel: () => {} };
1310
+ }
1311
+ const selection = this.selectVoice(synthesis.getVoices(), options);
1312
+ if (selection instanceof VoiceError2) {
1313
+ return { done: Promise.reject(selection), cancel: () => {} };
1314
+ }
1315
+ const chosen = selection;
1316
+ const voice = chosen?.voice;
1317
+ const build = () => {
1318
+ const utterance = new Utterance(text);
1319
+ utterance.lang = voice?.lang ?? options.locale ?? "";
1320
+ utterance.voice = voice ?? null;
1321
+ utterance.rate = options.rate ?? 1;
1322
+ utterance.pitch = options.pitch ?? 1;
1323
+ utterance.volume = options.volume ?? 1;
1324
+ return utterance;
1325
+ };
1326
+ const info = chosen === undefined ? undefined : describe(chosen);
1327
+ let request;
1328
+ const done = new Promise((resolve, reject) => {
1329
+ request = { build, options, voice: info, utterance: build(), started: false, settled: false, zombie: false, watchdog: undefined, resolve, reject };
1330
+ });
1331
+ this.inFlight.push(request);
1332
+ this.bind(request);
1333
+ const timeout = options.timeoutMs ?? 15000 + text.length * 200 / Math.max(0.1, options.rate ?? 1);
1334
+ request.watchdog = this.setTimer(() => {
1335
+ this.abandon(request, new VoiceError2("failed", "the platform voice never reported the end of the speech"));
1336
+ }, timeout);
1337
+ try {
1338
+ synthesis.speak(request.utterance);
1339
+ } catch (error) {
1340
+ this.settle(request, VoiceError2.wrapping(error));
1341
+ }
1342
+ return {
1343
+ done,
1344
+ ...info === undefined ? {} : { voice: info },
1345
+ cancel: () => this.abandon(request, new VoiceError2("cancelled"))
1346
+ };
1347
+ }
1348
+ get isSpeaking() {
1349
+ return this.environment.speechSynthesis?.speaking === true || this.environment.speechSynthesis?.pending === true;
1350
+ }
1351
+ selectVoice(available, options) {
1352
+ const allowNetwork = options.allowNetwork === true;
1353
+ if (options.voiceName) {
1354
+ const requested = available.find((voice) => voice.name === options.voiceName);
1355
+ if (requested !== undefined) {
1356
+ if (requested.localService !== true && !allowNetwork) {
1357
+ return new VoiceError2("denied", "a remote voice needs explicit consent");
1358
+ }
1359
+ const match = options.locale ? matchLocale(options.locale, requested.lang)?.match ?? "language" : "named";
1360
+ return { voice: requested, match, offRegion: options.locale ? isOffRegion(options.locale, match) : false };
1361
+ }
1362
+ }
1363
+ if (options.locale) {
1364
+ const ranked = rank(available, options.locale);
1365
+ const local = ranked.find((entry) => entry.voice.localService === true);
1366
+ const remote = ranked.find((entry) => entry.voice.localService !== true);
1367
+ let pick = local;
1368
+ if (allowNetwork && remote !== undefined && (pick === undefined || tier(remote.match.match) < tier(pick.match.match))) {
1369
+ pick = remote;
1370
+ }
1371
+ if (pick === undefined) {
1372
+ return new VoiceError2("language_unsupported", `no local ${options.locale} voice is installed`);
1373
+ }
1374
+ return { voice: pick.voice, match: pick.match.match, offRegion: isOffRegion(options.locale, pick.match.match) };
1375
+ }
1376
+ const fallback = available.find((voice) => voice.localService === true && voice.default === true) ?? available.find((voice) => voice.localService === true);
1377
+ if (fallback === undefined && !allowNetwork) {
1378
+ return new VoiceError2("language_unsupported", "no local voice is installed");
1379
+ }
1380
+ return fallback === undefined ? undefined : { voice: fallback, match: "default", offRegion: false };
1381
+ }
1382
+ bind(request) {
1383
+ const utterance = request.utterance;
1384
+ const options = request.options;
1385
+ utterance.onstart = () => {
1386
+ if (request.utterance !== utterance)
1387
+ return;
1388
+ if (request.zombie) {
1389
+ this.purge();
1390
+ return;
1391
+ }
1392
+ request.started = true;
1393
+ options.onStart?.(request.voice);
1394
+ };
1395
+ utterance.onend = () => {
1396
+ if (request.utterance !== utterance || request.settled)
1397
+ return;
1398
+ if (!request.started) {
1399
+ this.settle(request, new VoiceError2("cancelled", "the platform voice was cancelled before it started"));
1400
+ return;
1401
+ }
1402
+ options.onEnd?.();
1403
+ this.settle(request);
1404
+ };
1405
+ utterance.onerror = (event) => {
1406
+ if (request.utterance !== utterance || request.settled)
1407
+ return;
1408
+ this.settle(request, mapSynthesisError(event.error));
1409
+ };
1410
+ }
1411
+ abandon(request, error) {
1412
+ if (request.settled)
1413
+ return;
1414
+ const speakerIsOther = this.inFlight.some((other) => other !== request && other.started);
1415
+ this.settle(request, error);
1416
+ if (!request.started && speakerIsOther) {
1417
+ request.zombie = true;
1418
+ return;
1419
+ }
1420
+ this.purge();
1421
+ }
1422
+ purge() {
1423
+ const synthesis = this.environment.speechSynthesis;
1424
+ if (synthesis === undefined)
1425
+ return;
1426
+ const survivors = this.inFlight.filter((request) => !request.settled && !request.started);
1427
+ for (const request of this.inFlight)
1428
+ detach(request.utterance);
1429
+ synthesis.cancel();
1430
+ for (const request of survivors) {
1431
+ request.utterance = request.build();
1432
+ this.bind(request);
1433
+ try {
1434
+ synthesis.speak(request.utterance);
1435
+ } catch (error) {
1436
+ this.settle(request, VoiceError2.wrapping(error));
1437
+ }
1438
+ }
1439
+ }
1440
+ settle(request, error) {
1441
+ if (request.settled)
1442
+ return;
1443
+ request.settled = true;
1444
+ if (request.watchdog !== undefined)
1445
+ this.clearTimer(request.watchdog);
1446
+ request.watchdog = undefined;
1447
+ this.inFlight = this.inFlight.filter((candidate) => candidate !== request);
1448
+ if (error)
1449
+ request.reject(error);
1450
+ else
1451
+ request.resolve();
1452
+ }
1453
+ setTimer(callback, milliseconds) {
1454
+ if (this.environment.setTimeout)
1455
+ return this.environment.setTimeout(callback, milliseconds);
1456
+ const handle = setTimeout(callback, milliseconds);
1457
+ handle.unref?.();
1458
+ return handle;
1459
+ }
1460
+ clearTimer(handle) {
1461
+ if (this.environment.clearTimeout)
1462
+ this.environment.clearTimeout(handle);
1463
+ else
1464
+ clearTimeout(handle);
1465
+ }
1466
+ }
1467
+ function detach(utterance) {
1468
+ utterance.onstart = null;
1469
+ utterance.onend = null;
1470
+ utterance.onerror = null;
1471
+ }
1472
+ function rank(available, locale) {
1473
+ return available.map((voice, index) => ({ voice, index, match: matchLocale(locale, voice.lang) })).filter((entry) => entry.match !== undefined).sort((a, b) => a.match.rank - b.match.rank || Number(b.voice.default === true) - Number(a.voice.default === true) || a.index - b.index);
1474
+ }
1475
+ function tier(match) {
1476
+ return match === "exact" ? 0 : match === "region" ? 1 : 2;
1477
+ }
1478
+ function isOffRegion(locale, match) {
1479
+ return match === "language" && /[-_]/.test(locale.trim());
1480
+ }
1481
+ function describe(selection) {
1482
+ const voice = selection.voice;
1483
+ return {
1484
+ name: voice.name,
1485
+ ...voice.voiceURI === undefined ? {} : { voiceURI: voice.voiceURI },
1486
+ lang: voice.lang,
1487
+ localService: voice.localService === true,
1488
+ match: selection.match,
1489
+ offRegion: selection.offRegion
1490
+ };
1491
+ }
1492
+ function mapSynthesisError(error) {
1493
+ switch (error) {
1494
+ case "interrupted":
1495
+ case "canceled":
1496
+ case "cancelled":
1497
+ return new VoiceError2("cancelled");
1498
+ case "not-allowed":
1499
+ return new VoiceError2("denied");
1500
+ case "language-unavailable":
1501
+ case "voice-unavailable":
1502
+ return new VoiceError2("language_unsupported");
1503
+ default:
1504
+ return new VoiceError2("failed", `platform synthesis error: ${error}`);
1505
+ }
1506
+ }
1507
+ // src/web/turns.ts
1508
+ class VoiceTurnManager {
1509
+ options;
1510
+ listeners = new Set;
1511
+ session;
1512
+ speech;
1513
+ generation = 0;
1514
+ finished = false;
1515
+ constructor(options) {
1516
+ this.options = options;
1517
+ }
1518
+ onEvent(listener) {
1519
+ this.listeners.add(listener);
1520
+ return () => this.listeners.delete(listener);
1521
+ }
1522
+ async startListening() {
1523
+ if (this.finished)
1524
+ throw new VoiceError2("cancelled", "the turn manager was cancelled");
1525
+ const generation = ++this.generation;
1526
+ const previous = this.session;
1527
+ this.session = undefined;
1528
+ if (this.speech)
1529
+ this.stopSpeech("barge-in");
1530
+ if (previous)
1531
+ await previous.cancel();
1532
+ if (this.finished)
1533
+ throw new VoiceError2("cancelled", "the turn manager was cancelled");
1534
+ if (generation !== this.generation)
1535
+ return;
1536
+ let session;
1537
+ try {
1538
+ session = await this.options.transcription.createSession({
1539
+ locale: this.options.locale,
1540
+ allowNetwork: this.options.allowNetwork === true,
1541
+ onSpeechStart: () => {
1542
+ if (!this.finished && generation === this.generation)
1543
+ this.notifySpeechDetected();
1544
+ }
1545
+ });
1546
+ } catch (error) {
1547
+ if (this.finished)
1548
+ throw new VoiceError2("cancelled", "the turn manager was cancelled");
1549
+ if (generation !== this.generation)
1550
+ return;
1551
+ this.emit({ type: "failed", error: VoiceError2.wrapping(error) });
1552
+ throw error;
1553
+ }
1554
+ if (this.finished || generation !== this.generation) {
1555
+ await session.cancel();
1556
+ if (this.finished)
1557
+ throw new VoiceError2("cancelled", "the turn manager was cancelled");
1558
+ return;
1559
+ }
1560
+ this.session = session;
1561
+ this.emit({ type: "listening" });
1562
+ this.consume(session);
1563
+ }
1564
+ async stopListening() {
1565
+ await this.session?.end();
1566
+ }
1567
+ speak(text) {
1568
+ if (this.finished) {
1569
+ return { done: Promise.reject(new VoiceError2("cancelled")), cancel: () => {} };
1570
+ }
1571
+ if (this.speech)
1572
+ this.stopSpeech("replaced");
1573
+ const handle = this.options.synthesis.speak(text);
1574
+ this.speech = handle;
1575
+ this.emit({ type: "speaking", text });
1576
+ handle.done.then(() => {
1577
+ if (this.speech !== handle)
1578
+ return;
1579
+ this.speech = undefined;
1580
+ this.emit({ type: "speech-finished" });
1581
+ }).catch((error) => {
1582
+ if (this.speech !== handle)
1583
+ return;
1584
+ this.speech = undefined;
1585
+ const wrapped = VoiceError2.wrapping(error);
1586
+ this.emit(wrapped.code === "cancelled" ? { type: "speech-cancelled" } : { type: "failed", error: wrapped });
1587
+ });
1588
+ return {
1589
+ done: handle.done,
1590
+ cancel: () => {
1591
+ if (this.speech === handle)
1592
+ this.stopSpeech("replaced");
1593
+ else
1594
+ handle.cancel();
1595
+ }
1596
+ };
1597
+ }
1598
+ notifySpeechDetected() {
1599
+ if (this.options.bargeInOnSpeech === false)
1600
+ return;
1601
+ this.stopSpeech("barge-in");
1602
+ }
1603
+ async cancel() {
1604
+ if (this.finished)
1605
+ return;
1606
+ this.finished = true;
1607
+ this.generation += 1;
1608
+ this.stopSpeech("cancel");
1609
+ const session = this.session;
1610
+ this.session = undefined;
1611
+ await session?.cancel();
1612
+ this.emit({ type: "cancelled" });
1613
+ }
1614
+ stopSpeech(reason) {
1615
+ const speech = this.speech;
1616
+ if (speech === undefined)
1617
+ return;
1618
+ this.speech = undefined;
1619
+ speech.cancel();
1620
+ if (reason === "barge-in")
1621
+ this.emit({ type: "barge-in" });
1622
+ if (reason !== "cancel")
1623
+ this.emit({ type: "speech-cancelled" });
1624
+ }
1625
+ async consume(session) {
1626
+ try {
1627
+ for await (const event of session.events()) {
1628
+ if (this.session !== session)
1629
+ return;
1630
+ this.forward(event);
1631
+ }
1632
+ } catch (error) {
1633
+ if (this.session !== session)
1634
+ return;
1635
+ this.session = undefined;
1636
+ this.emit({ type: "failed", error: VoiceError2.wrapping(error) });
1637
+ }
1638
+ }
1639
+ forward(event) {
1640
+ switch (event.type) {
1641
+ case "partial":
1642
+ this.emit({ type: "partial", partial: event.partial });
1643
+ return;
1644
+ case "final":
1645
+ this.session = undefined;
1646
+ this.emit({ type: "transcript", text: event.text });
1647
+ return;
1648
+ case "failed":
1649
+ this.session = undefined;
1650
+ this.emit({ type: "failed", error: event.error });
1651
+ return;
1652
+ case "cancelled":
1653
+ this.session = undefined;
1654
+ this.emit({ type: "cancelled" });
1655
+ return;
1656
+ }
1657
+ }
1658
+ emit(event) {
1659
+ for (const listener of [...this.listeners]) {
1660
+ try {
1661
+ listener(event);
1662
+ } catch (error) {
1663
+ (this.options.onListenerError ?? defaultListenerError)(error);
1664
+ }
1665
+ }
1666
+ }
1667
+ }
1668
+ function defaultListenerError(error) {
1669
+ console.error("voice turn listener threw", error);
1670
+ }
1671
+ function bargeInOnSpeechStart(manager) {
1672
+ return { onSpeechStart: () => manager.notifySpeechDetected() };
1673
+ }
1674
+ export {
1675
+ BrowserRecognitionProvider,
1676
+ DEFAULT_ENDPOINTING2 as DEFAULT_ENDPOINTING,
1677
+ LOCAL_RECOGNITION_ID,
1678
+ PHONON_EN_FAMILY,
1679
+ PHONON_PROVIDER_ID,
1680
+ PhononProvider,
1681
+ PlaybackUtterance,
1682
+ REGION_GROUPS,
1683
+ SERVICE_RECOGNITION_ID,
1684
+ SYSTEM_VOICES_ID,
1685
+ StreamingPcmPlayer,
1686
+ SystemVoiceProvider,
1687
+ VoiceTurnManager,
1688
+ bargeInOnSpeechStart,
1689
+ browserRecognitionLocal,
1690
+ browserRecognitionService,
1691
+ clearPhononCache,
1692
+ defaultAudioContextFactory,
1693
+ defaultPhononRuntime,
1694
+ matchLocale,
1695
+ parseLocale,
1696
+ recognitionConstructor
1697
+ };