@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,1013 @@
1
+ /**
2
+ * Browser dictation over the Web Speech API, with an explicit local/network policy (issues #21
3
+ * and #37).
4
+ *
5
+ * The browser's recognizer is not automatically offline: Chrome's service-based recognition sends
6
+ * audio to Google, and Safari/Chrome differ per OS version. This module therefore exposes **two
7
+ * providers over one implementation**:
8
+ *
9
+ * - `web.speech-recognition-local` (`execution: "onDevice"`): only available when the browser can
10
+ * run recognition on-device *and* confirms a model for the locale. It is the only entry in the
11
+ * routing chain, so routing never silently reaches the network.
12
+ * - `web.speech-recognition-service` (`execution: "network"`): the host must select it explicitly,
13
+ * with a privacy notice and `allowNetwork: true`. Routing refuses it (`networkRequired`).
14
+ *
15
+ * The session keeps the platform-neutral event contract from #19: `partial` snapshots with
16
+ * `finalizedText`/`volatileText`/`sequence`, exactly one terminal `final`/`failed`/`cancelled`, and
17
+ * deadlines that end a stuck session instead of hanging it.
18
+ */
19
+ import {
20
+ AVAILABLE,
21
+ VOICE_CONTRACT,
22
+ isAvailable,
23
+ type VoiceProvider,
24
+ type VoiceProviderAvailability,
25
+ type VoiceProviderDescriptor,
26
+ type VoiceUnavailabilityReason,
27
+ unavailable,
28
+ } from "../../contract/contract";
29
+ import { VoiceError, type VoiceErrorCode } from "../../contract/errors";
30
+
31
+ // MARK: - The browser surface we depend on
32
+
33
+ export interface RecognitionAlternative {
34
+ readonly transcript: string;
35
+ readonly confidence?: number;
36
+ }
37
+
38
+ export interface RecognitionResult {
39
+ readonly isFinal: boolean;
40
+ readonly length: number;
41
+ readonly [index: number]: RecognitionAlternative;
42
+ }
43
+
44
+ export interface RecognitionResultList {
45
+ readonly length: number;
46
+ readonly [index: number]: RecognitionResult;
47
+ }
48
+
49
+ export interface SpeechRecognitionEventLike {
50
+ readonly resultIndex: number;
51
+ readonly results: RecognitionResultList;
52
+ }
53
+
54
+ export interface SpeechRecognitionErrorEventLike {
55
+ readonly error: string;
56
+ readonly message?: string;
57
+ }
58
+
59
+ /** The subset of `SpeechRecognition` this adapter uses. */
60
+ export interface SpeechRecognitionLike {
61
+ lang: string;
62
+ continuous: boolean;
63
+ interimResults: boolean;
64
+ maxAlternatives: number;
65
+ /** Chrome's on-device flag; ignored by browsers that do not implement it. */
66
+ processLocally?: boolean;
67
+ onstart: (() => void) | null;
68
+ onresult: ((event: SpeechRecognitionEventLike) => void) | null;
69
+ onerror: ((event: SpeechRecognitionErrorEventLike) => void) | null;
70
+ onend: (() => void) | null;
71
+ /** The browser heard speech begin. Not every engine fires it; the first words stand in. */
72
+ onspeechstart?: (() => void) | null;
73
+ /** Chrome 137+ accepts an audio track to recognise from (a chosen microphone). */
74
+ start(audioTrack?: MediaStreamTrackLike): void;
75
+ stop(): void;
76
+ abort(): void;
77
+ }
78
+
79
+ export type RecognitionModelState = "available" | "downloadable" | "downloading" | "unavailable";
80
+
81
+ /** Chrome's on-device lifecycle methods, which live on the constructor, not the instance. */
82
+ export interface SpeechRecognitionConstructor {
83
+ new (): SpeechRecognitionLike;
84
+ available?(options: { langs: string[]; processLocally?: boolean }): Promise<RecognitionModelState>;
85
+ install?(options: { langs: string[] }): Promise<boolean>;
86
+ }
87
+
88
+ /** The subset of `PermissionStatus` the microphone pre-check uses. */
89
+ export interface PermissionStatusLike {
90
+ readonly state: "granted" | "denied" | "prompt" | (string & {});
91
+ onchange?: (() => void) | null;
92
+ addEventListener?(type: "change", listener: () => void): void;
93
+ removeEventListener?(type: "change", listener: () => void): void;
94
+ }
95
+
96
+ /** The subset of `MediaStreamTrack` a chosen microphone needs. */
97
+ export interface MediaStreamTrackLike {
98
+ readonly kind?: string;
99
+ readonly readyState?: string;
100
+ stop(): void;
101
+ }
102
+
103
+ export interface MediaStreamLike {
104
+ getAudioTracks(): MediaStreamTrackLike[];
105
+ getTracks?(): MediaStreamTrackLike[];
106
+ }
107
+
108
+ /** The parts of `navigator` dictation reads: permissions, connectivity and microphones. */
109
+ export interface RecognitionNavigatorLike {
110
+ readonly onLine?: boolean;
111
+ readonly permissions?: { query(descriptor: { name: string }): Promise<PermissionStatusLike> };
112
+ readonly mediaDevices?: {
113
+ getUserMedia(constraints: { audio: boolean | { deviceId: { exact: string } } }): Promise<MediaStreamLike>;
114
+ };
115
+ }
116
+
117
+ /** `window`/`document` as event targets (`offline`, `pagehide`, `visibilitychange`). */
118
+ export interface EventTargetLike {
119
+ addEventListener(type: string, listener: () => void): void;
120
+ removeEventListener(type: string, listener: () => void): void;
121
+ }
122
+
123
+ export interface RecognitionDocumentLike extends EventTargetLike {
124
+ readonly visibilityState?: string;
125
+ }
126
+
127
+ export interface SpeechRecognitionEnvironment {
128
+ /** The constructor, or undefined where the browser has no Web Speech API. */
129
+ readonly SpeechRecognition?: SpeechRecognitionConstructor;
130
+ /** Safari's prefixed constructor. Present without the unprefixed name on Safari and older WebKit. */
131
+ readonly webkitSpeechRecognition?: SpeechRecognitionConstructor;
132
+ readonly now?: () => number;
133
+ readonly sleep?: (milliseconds: number) => Promise<void>;
134
+ /** Permissions, `onLine` and `mediaDevices`. Default: the global `navigator`. */
135
+ readonly navigator?: RecognitionNavigatorLike;
136
+ /** For `visibilitychange`. Default: the global `document`. */
137
+ readonly document?: RecognitionDocumentLike;
138
+ /** `window`'s listeners, for `offline` and `pagehide`. Default: the global ones. */
139
+ readonly addEventListener?: (type: string, listener: () => void) => void;
140
+ readonly removeEventListener?: (type: string, listener: () => void) => void;
141
+ /**
142
+ * Whether `start(audioTrack)` is honoured. Browsers that predate it ignore the argument and record
143
+ * the default microphone, so a chosen device would be silently dropped. Default: detected as
144
+ * Chrome's on-device recognizer (`processLocally` on the instance), which shipped after it.
145
+ */
146
+ readonly recognitionAcceptsAudioTrack?: boolean;
147
+ }
148
+
149
+ /** Progress of a browser model install. The browser reports states, not bytes. */
150
+ export interface ModelInstallProgress {
151
+ readonly locale: string;
152
+ readonly phase: "started" | "downloading" | "installed" | "failed" | "cancelled";
153
+ }
154
+
155
+ export interface InstallModelOptions {
156
+ /** The person agreed to the download (for example `allowsModelDownload(settings)`). */
157
+ readonly allowDownload: boolean;
158
+ /** Called on each phase change; `downloading` is observed by polling the browser's state. */
159
+ readonly onProgress?: (progress: ModelInstallProgress) => void;
160
+ /**
161
+ * Stops waiting and rejects with `cancelled`. The browser has no cancel for its own download, so
162
+ * it may finish in the background; the SDK only stops reporting and never claims it installed.
163
+ */
164
+ readonly signal?: AbortSignal;
165
+ /** How often `downloading` is polled. Default 500 ms. */
166
+ readonly pollIntervalMs?: number;
167
+ /** A settings object; `privacy.offlineOnly` refuses the download whatever `allowDownload` says. */
168
+ readonly settings?: { readonly privacy: { readonly offlineOnly: boolean } };
169
+ }
170
+
171
+ /** What dictation does when the page is hidden (`visibilitychange` to hidden, or `pagehide`). */
172
+ export type HiddenPagePolicy = "finalize" | "cancel" | "ignore";
173
+
174
+ /** Browser-specific session options on top of the shared contract. All optional. */
175
+ export interface WebTranscriptionSessionOptions extends TranscriptionSessionOptions {
176
+ /**
177
+ * A chosen microphone: a `deviceId` the SDK opens (and always stops on every terminal path), or a
178
+ * `track` the host owns (stopped at the end only with `stopOnEnd: true`). Needs a browser that
179
+ * honours `start(audioTrack)`, otherwise the session is refused instead of using another mic.
180
+ */
181
+ readonly microphone?: { readonly deviceId: string } | { readonly track: MediaStreamTrackLike; readonly stopOnEnd?: boolean };
182
+ /**
183
+ * What to do when the browser ends recognition on its own before `end()` (Chrome on Android
184
+ * ignores `continuous` and stops after one utterance): `finalize` (default) reports the words so
185
+ * far as a clean `final`; `restart` starts the recognizer again inside the same session, so the
186
+ * person can keep talking until endpointing, the hard cap or `end()` finishes it.
187
+ */
188
+ readonly onEarlyEnd?: "finalize" | "restart";
189
+ /** At most this many restarts per session with `onEarlyEnd: "restart"`. Default 50. */
190
+ readonly maxRestarts?: number;
191
+ /** Default `finalize`: a hidden page ends the session with one terminal event. */
192
+ readonly whenHidden?: HiddenPagePolicy;
193
+ /** A settings object; `privacy.offlineOnly` refuses the service recognizer outright. */
194
+ readonly settings?: { readonly privacy: { readonly offlineOnly: boolean } };
195
+ }
196
+
197
+ /** The recognizer constructor this browser exposes, unprefixed first. */
198
+ export function recognitionConstructor(
199
+ environment: SpeechRecognitionEnvironment,
200
+ ): SpeechRecognitionConstructor | undefined {
201
+ return environment.SpeechRecognition ?? environment.webkitSpeechRecognition;
202
+ }
203
+
204
+ export {
205
+ DEFAULT_ENDPOINTING,
206
+ type EndpointingOptions,
207
+ type RecognitionExecution,
208
+ type PartialTranscript,
209
+ type SessionEvent,
210
+ type TranscriptionProvider,
211
+ type TranscriptionSession,
212
+ type TranscriptionSessionOptions,
213
+ } from "../../contract/session";
214
+ import {
215
+ DEFAULT_ENDPOINTING,
216
+ type EndpointingOptions,
217
+ type RecognitionExecution,
218
+ type PartialTranscript,
219
+ type SessionEvent,
220
+ type TranscriptionProvider,
221
+ type TranscriptionSession,
222
+ type TranscriptionSessionOptions,
223
+ } from "../../contract/session";
224
+
225
+ // MARK: - Providers
226
+
227
+ const WEB = ["web"] as const;
228
+
229
+ export const LOCAL_RECOGNITION_ID = "web.speech-recognition-local";
230
+ export const SERVICE_RECOGNITION_ID = "web.speech-recognition-service";
231
+
232
+ export function browserRecognitionLocal(environment: SpeechRecognitionEnvironment = globalThis as never): BrowserRecognitionProvider {
233
+ return new BrowserRecognitionProvider("local", environment);
234
+ }
235
+
236
+ export function browserRecognitionService(environment: SpeechRecognitionEnvironment = globalThis as never): BrowserRecognitionProvider {
237
+ return new BrowserRecognitionProvider("service", environment);
238
+ }
239
+
240
+ /**
241
+ * The recognizer as a provider. `mode` decides which of the two descriptors it carries; the
242
+ * implementation is the same and the policy difference is the point.
243
+ */
244
+ export class BrowserRecognitionProvider implements TranscriptionProvider {
245
+ readonly descriptor: VoiceProviderDescriptor;
246
+ private readonly environment: SpeechRecognitionEnvironment;
247
+ private readonly mode: "local" | "service";
248
+
249
+ constructor(mode: "local" | "service", environment: SpeechRecognitionEnvironment) {
250
+ this.mode = mode;
251
+ this.environment = environment;
252
+ this.descriptor = {
253
+ id: mode === "local" ? LOCAL_RECOGNITION_ID : SERVICE_RECOGNITION_ID,
254
+ displayName: mode === "local" ? "Browser dictation (on-device)" : "Browser dictation (browser service)",
255
+ kind: "speechToText",
256
+ platforms: WEB,
257
+ execution: mode === "local" ? "onDevice" : "network",
258
+ contract: VOICE_CONTRACT,
259
+ requiresModelDownload: mode === "local",
260
+ modelFamilies: mode === "local" ? ["browser.on-device-recognition"] : [],
261
+ licenses: [
262
+ { spdxIdentifier: mode === "local" ? "Browser-On-Device-Recognition" : "Browser-Speech-Service", commercialUse: true },
263
+ ],
264
+ capabilities: {
265
+ streamingPartials: true,
266
+ trueCancellation: true,
267
+ modelInstallation: mode === "local",
268
+ localeSelection: true,
269
+ },
270
+ };
271
+ }
272
+
273
+ /** Probes the browser. Prompts for nothing, sends nothing. */
274
+ async availability(locale: string): Promise<VoiceProviderAvailability> {
275
+ const constructor = recognitionConstructor(this.environment);
276
+ if (constructor === undefined) {
277
+ return unavailable("unsupportedPlatform", "this browser has no Web Speech API", {
278
+ kind: "chooseAnotherProvider",
279
+ detail: "use a browser with speech recognition, or the native app",
280
+ });
281
+ }
282
+ if (this.mode === "service") {
283
+ return AVAILABLE;
284
+ }
285
+ if (constructor.available === undefined) {
286
+ return unavailable(
287
+ "unsupportedDevice",
288
+ "this browser cannot run recognition on-device, so offline dictation is not offered here",
289
+ { kind: "chooseAnotherProvider", detail: "use a browser with on-device recognition, or dictation with network consent" },
290
+ );
291
+ }
292
+ const state = await probeOnDevice(constructor, locale);
293
+ switch (state) {
294
+ case "available":
295
+ return AVAILABLE;
296
+ case "downloadable":
297
+ case "downloading":
298
+ return unavailable("modelNotInstalled", `the ${locale} recognition model is not installed on this device`, {
299
+ kind: "installModel",
300
+ detail: `install the ${locale} browser recognition model`,
301
+ });
302
+ case "unavailable":
303
+ return unavailable("unsupportedLocale", `${locale} has no on-device recognition model in this browser`, {
304
+ kind: "switchLocale",
305
+ detail: "choose a language this browser supports on-device",
306
+ });
307
+ }
308
+ }
309
+
310
+ /**
311
+ * Installs the on-device model where the browser exposes an install path (#37 consent step).
312
+ * Downloading is never implied: the host passes `allowDownload: true` only after the person
313
+ * agreed to it (for example `settings.models.allowDownload`), otherwise this refuses. Resolves
314
+ * with the browser's boolean; `onProgress` and `signal` are optional.
315
+ */
316
+ async installModel(locale: string, options: InstallModelOptions): Promise<boolean> {
317
+ if (options?.allowDownload !== true) {
318
+ throw new VoiceError("denied", "installing a recognition model needs the person's explicit download consent");
319
+ }
320
+ if (options.settings?.privacy.offlineOnly === true) {
321
+ throw new VoiceError("denied", "offline-only mode forbids downloading a recognition model");
322
+ }
323
+ const constructor = recognitionConstructor(this.environment);
324
+ const install = constructor?.install;
325
+ if (constructor === undefined || install === undefined) {
326
+ throw new VoiceError("assets_missing", "this browser has no on-device recognition install path");
327
+ }
328
+ const signal = options.signal;
329
+ if (signal?.aborted) throw new VoiceError("cancelled", "the model install was cancelled before it started");
330
+ const report = (phase: ModelInstallProgress["phase"]) => {
331
+ try {
332
+ options.onProgress?.({ locale, phase });
333
+ } catch {
334
+ // a broken progress listener must not fail the install
335
+ }
336
+ };
337
+ report("started");
338
+
339
+ let settled = false;
340
+ let onAbort: (() => void) | undefined;
341
+ const aborted = new Promise<never>((_, reject) => {
342
+ onAbort = () => reject(new VoiceError("cancelled", "the model install was cancelled; the browser may finish it in the background"));
343
+ signal?.addEventListener("abort", onAbort, { once: true });
344
+ });
345
+ void this.pollInstall(constructor, locale, options.pollIntervalMs ?? 500, () => settled, () => report("downloading"));
346
+ try {
347
+ const installed = await Promise.race([Promise.resolve(install.call(constructor, { langs: [locale] })), aborted]);
348
+ report(installed ? "installed" : "failed");
349
+ return installed;
350
+ } catch (error) {
351
+ const wrapped = VoiceError.wrapping(error);
352
+ report(wrapped.code === "cancelled" ? "cancelled" : "failed");
353
+ throw error instanceof VoiceError ? error : wrapped;
354
+ } finally {
355
+ settled = true;
356
+ if (onAbort) signal?.removeEventListener("abort", onAbort);
357
+ }
358
+ }
359
+
360
+ /** Reports `downloading` once the browser says so; the browser exposes no byte counts. */
361
+ private async pollInstall(
362
+ constructor: SpeechRecognitionConstructor,
363
+ locale: string,
364
+ intervalMs: number,
365
+ done: () => boolean,
366
+ downloading: () => void,
367
+ ): Promise<void> {
368
+ if (constructor.available === undefined) return;
369
+ const sleep = this.environment.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));
370
+ while (!done()) {
371
+ const state = await probeOnDevice(constructor, locale);
372
+ if (done()) return;
373
+ if (state === "downloading") {
374
+ downloading();
375
+ return;
376
+ }
377
+ await sleep(intervalMs);
378
+ }
379
+ }
380
+
381
+ async createSession(options: WebTranscriptionSessionOptions): Promise<TranscriptionSession> {
382
+ if (this.mode === "service" && options.settings?.privacy.offlineOnly === true) {
383
+ throw new VoiceError("denied", "offline-only mode forbids the browser's network recognition service");
384
+ }
385
+ const availability = await this.availability(options.locale);
386
+ if (!isAvailable(availability)) {
387
+ const reason = availability.unavailable;
388
+ throw new VoiceError(codeFor(reason.reason), reason.message);
389
+ }
390
+ if (this.mode === "service" && !options.allowNetwork) {
391
+ throw new VoiceError(
392
+ "denied",
393
+ "browser service recognition sends audio to the browser vendor; it needs explicit consent",
394
+ );
395
+ }
396
+ const navigator = this.navigator;
397
+ if (this.mode === "service" && navigator?.onLine === false) {
398
+ throw new VoiceError("unavailable", "the device is offline, so the browser's recognition service cannot be reached");
399
+ }
400
+ const permission = await queryMicrophone(navigator);
401
+ if (permission?.state === "denied") {
402
+ throw new VoiceError("denied", "microphone permission is denied for this site");
403
+ }
404
+ const constructor = recognitionConstructor(this.environment);
405
+ if (constructor === undefined) throw new VoiceError("unavailable");
406
+ const recognition = new constructor();
407
+ recognition.lang = options.locale;
408
+ recognition.continuous = true;
409
+ recognition.interimResults = true;
410
+ recognition.maxAlternatives = 1;
411
+ if (this.mode === "local") {
412
+ recognition.processLocally = true;
413
+ // The runtime half of the offline proof: a recognizer that drops the flag would fall back
414
+ // to the service, so the session is refused rather than labelled local.
415
+ if (recognition.processLocally !== true) {
416
+ throw new VoiceError("unavailable", "this browser did not accept on-device recognition, so offline dictation cannot be proven");
417
+ }
418
+ }
419
+ const audio = await this.openMicrophone(options, recognition);
420
+ return new WebRecognitionSession(recognition, this.mode === "local" ? "onDevice" : "network", {
421
+ endpointing: options.endpointing ?? DEFAULT_ENDPOINTING,
422
+ now: this.environment.now ?? (() => performance.now()),
423
+ sleep: this.environment.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
424
+ audio,
425
+ permission,
426
+ onSpeechStart: options.onSpeechStart,
427
+ onEarlyEnd: options.onEarlyEnd ?? "finalize",
428
+ maxRestarts: options.maxRestarts ?? 50,
429
+ whenHidden: options.whenHidden ?? "finalize",
430
+ document: this.environment.document,
431
+ window: this.window,
432
+ });
433
+ }
434
+
435
+ private get navigator(): RecognitionNavigatorLike | undefined {
436
+ return this.environment.navigator;
437
+ }
438
+
439
+ private get window(): EventTargetLike | undefined {
440
+ const add = this.environment.addEventListener;
441
+ const remove = this.environment.removeEventListener;
442
+ if (add && remove) {
443
+ const target = this.environment;
444
+ return { addEventListener: (type, listener) => add.call(target, type, listener), removeEventListener: (type, listener) => remove.call(target, type, listener) };
445
+ }
446
+ return undefined;
447
+ }
448
+
449
+ /** Opens (or adopts) the chosen microphone. Nothing is opened when no device was chosen. */
450
+ private async openMicrophone(
451
+ options: WebTranscriptionSessionOptions,
452
+ recognition: SpeechRecognitionLike,
453
+ ): Promise<SessionAudio | undefined> {
454
+ const microphone = options.microphone;
455
+ if (microphone === undefined) return undefined;
456
+ const accepts = this.environment.recognitionAcceptsAudioTrack ?? "processLocally" in recognition;
457
+ if (!accepts) {
458
+ throw new VoiceError("unavailable", "this browser cannot recognise from a chosen microphone, only the default one");
459
+ }
460
+ if ("track" in microphone) {
461
+ return { track: microphone.track, owned: [], stopTrack: microphone.stopOnEnd === true };
462
+ }
463
+ const getUserMedia = this.navigator?.mediaDevices?.getUserMedia;
464
+ if (getUserMedia === undefined) {
465
+ throw new VoiceError("unavailable", "this browser cannot open a chosen microphone");
466
+ }
467
+ let stream: MediaStreamLike;
468
+ try {
469
+ stream = await getUserMedia.call(this.navigator!.mediaDevices, { audio: { deviceId: { exact: microphone.deviceId } } });
470
+ } catch (error) {
471
+ throw mapMediaError(error);
472
+ }
473
+ const tracks = stream.getTracks?.() ?? stream.getAudioTracks();
474
+ const track = stream.getAudioTracks()[0];
475
+ if (track === undefined) {
476
+ for (const owned of tracks) owned.stop();
477
+ throw new VoiceError("unavailable", "the chosen microphone produced no audio track");
478
+ }
479
+ return { track, owned: tracks, stopTrack: true };
480
+ }
481
+ }
482
+
483
+ /** The audio a session records from, and what it must stop at the end. */
484
+ interface SessionAudio {
485
+ readonly track: MediaStreamTrackLike;
486
+ /** Tracks the SDK opened; always stopped on every terminal path. */
487
+ readonly owned: readonly MediaStreamTrackLike[];
488
+ /** Whether `track` itself is stopped at the end. */
489
+ readonly stopTrack: boolean;
490
+ }
491
+
492
+ /**
493
+ * `navigator.permissions.query({ name: "microphone" })` where it exists. Firefox before 131 and
494
+ * some WebViews throw for the name; that is "unknown", never "denied".
495
+ */
496
+ async function queryMicrophone(navigator: RecognitionNavigatorLike | undefined): Promise<PermissionStatusLike | undefined> {
497
+ const permissions = navigator?.permissions;
498
+ if (permissions === undefined || typeof permissions.query !== "function") return undefined;
499
+ try {
500
+ return await permissions.query({ name: "microphone" });
501
+ } catch {
502
+ return undefined;
503
+ }
504
+ }
505
+
506
+ function mapMediaError(error: unknown): VoiceError {
507
+ const name = (error as { name?: string } | undefined)?.name;
508
+ switch (name) {
509
+ case "NotAllowedError":
510
+ case "SecurityError":
511
+ return new VoiceError("denied", "microphone permission was denied");
512
+ case "NotFoundError":
513
+ case "OverconstrainedError":
514
+ return new VoiceError("unavailable", "the chosen microphone is not available");
515
+ case "NotReadableError":
516
+ case "AbortError":
517
+ return new VoiceError("busy", "the chosen microphone is in use or could not be opened");
518
+ default:
519
+ return VoiceError.wrapping(error);
520
+ }
521
+ }
522
+
523
+ async function probeOnDevice(constructor: SpeechRecognitionConstructor, locale: string): Promise<RecognitionModelState> {
524
+ try {
525
+ return (await constructor.available!({ langs: [locale], processLocally: true })) ?? "unavailable";
526
+ } catch {
527
+ return "unavailable";
528
+ }
529
+ }
530
+
531
+ function codeFor(reason: VoiceUnavailabilityReason): VoiceErrorCode {
532
+ switch (reason) {
533
+ case "unsupportedLocale":
534
+ return "language_unsupported";
535
+ case "modelNotInstalled":
536
+ case "modelDownloadDisabled":
537
+ return "assets_missing";
538
+ case "permissionDenied":
539
+ return "denied";
540
+ case "unsupportedDevice":
541
+ case "unsupportedOperatingSystem":
542
+ case "unsupportedPlatform":
543
+ return "unavailable";
544
+ default:
545
+ return "unavailable";
546
+ }
547
+ }
548
+
549
+ // MARK: - Session
550
+
551
+ type Terminal = "final" | "failed" | "cancelled";
552
+
553
+ const MAX_IDLE_RESTARTS = 3;
554
+
555
+ interface SessionConfig {
556
+ readonly endpointing: EndpointingOptions;
557
+ readonly now: () => number;
558
+ readonly sleep: (milliseconds: number) => Promise<void>;
559
+ readonly audio: SessionAudio | undefined;
560
+ readonly permission: PermissionStatusLike | undefined;
561
+ readonly onSpeechStart: (() => void) | undefined;
562
+ readonly onEarlyEnd: "finalize" | "restart";
563
+ readonly maxRestarts: number;
564
+ readonly whenHidden: HiddenPagePolicy;
565
+ readonly document: RecognitionDocumentLike | undefined;
566
+ readonly window: EventTargetLike | undefined;
567
+ }
568
+
569
+ class WebRecognitionSession implements TranscriptionSession {
570
+ readonly execution: "onDevice" | "network";
571
+ private readonly recognition: SpeechRecognitionLike;
572
+ private readonly endpointing: EndpointingOptions;
573
+ private readonly now: () => number;
574
+ private readonly sleep: (milliseconds: number) => Promise<void>;
575
+
576
+ private readonly queue: SessionEvent[] = [];
577
+ private resolved: (() => void) | undefined;
578
+ private finished = false;
579
+ private terminal: Terminal | undefined;
580
+ /** Whether the recognizer was started, or must never be (cancelled/ended before `events()`). */
581
+ private started = false;
582
+ /** `events()` hands out one stream: a second consumer would steal the first one's wake-ups. */
583
+ private iterated = false;
584
+ private resolveTerminal: (() => void) | undefined = undefined;
585
+ private readonly terminalSignal: Promise<void> = new Promise<void>((resolve) => {
586
+ this.resolveTerminal = resolve;
587
+ });
588
+
589
+ private finalizedText = "";
590
+ private volatileText = "";
591
+ private sequence = 0;
592
+ private lastWordAt = 0;
593
+ private words = false;
594
+ private stopRequested = false;
595
+ private endPromise: Promise<void> | undefined;
596
+
597
+ private readonly config: SessionConfig;
598
+ /** Listeners to remove on the terminal event (permission, offline, page lifecycle). */
599
+ private readonly cleanups: Array<() => void> = [];
600
+ /** Whether this recognizer run reported speech start (reset on restart). */
601
+ private speechSignalled = false;
602
+ private restarts = 0;
603
+ /** Restarts in a row that produced no result: a recognizer that ends at once is not restarted forever. */
604
+ private idleRestarts = 0;
605
+
606
+ constructor(recognition: SpeechRecognitionLike, execution: "onDevice" | "network", config: SessionConfig) {
607
+ this.recognition = recognition;
608
+ this.execution = execution;
609
+ this.config = config;
610
+ this.endpointing = config.endpointing;
611
+ this.now = config.now;
612
+ this.sleep = config.sleep;
613
+
614
+ recognition.onstart = () => {
615
+ this.started = true;
616
+ this.lastWordAt = this.now();
617
+ };
618
+ recognition.onresult = (event) => this.onResult(event);
619
+ recognition.onerror = (event) => this.onError(event);
620
+ recognition.onend = () => this.onEnd();
621
+ recognition.onspeechstart = () => this.signalSpeech();
622
+ this.watchEnvironment();
623
+ }
624
+
625
+ /** Permission revocation, connectivity (service mode) and page lifecycle each end the session once. */
626
+ private watchEnvironment(): void {
627
+ const permission = this.config.permission;
628
+ if (permission !== undefined) {
629
+ const onChange = () => {
630
+ if (permission.state === "denied") this.fail(new VoiceError("denied", "microphone permission was revoked"));
631
+ };
632
+ if (permission.addEventListener && permission.removeEventListener) {
633
+ permission.addEventListener("change", onChange);
634
+ this.cleanups.push(() => permission.removeEventListener!("change", onChange));
635
+ } else if ("onchange" in permission) {
636
+ const previous = permission.onchange ?? null;
637
+ permission.onchange = () => {
638
+ previous?.();
639
+ onChange();
640
+ };
641
+ this.cleanups.push(() => {
642
+ permission.onchange = previous;
643
+ });
644
+ }
645
+ }
646
+ const window = this.config.window;
647
+ if (window !== undefined) {
648
+ if (this.execution === "network") {
649
+ const onOffline = () =>
650
+ this.fail(new VoiceError("unavailable", "the device went offline, so the browser's recognition service was lost"));
651
+ window.addEventListener("offline", onOffline);
652
+ this.cleanups.push(() => window.removeEventListener("offline", onOffline));
653
+ }
654
+ if (this.config.whenHidden !== "ignore") {
655
+ const onPageHide = () => this.pageHidden();
656
+ window.addEventListener("pagehide", onPageHide);
657
+ this.cleanups.push(() => window.removeEventListener("pagehide", onPageHide));
658
+ }
659
+ }
660
+ const document = this.config.document;
661
+ if (document !== undefined && this.config.whenHidden !== "ignore") {
662
+ const onVisibility = () => {
663
+ if (document.visibilityState === "hidden") this.pageHidden();
664
+ };
665
+ document.addEventListener("visibilitychange", onVisibility);
666
+ this.cleanups.push(() => document.removeEventListener("visibilitychange", onVisibility));
667
+ }
668
+ }
669
+
670
+ /** The page went away: one terminal event, by policy, and the microphone closes. */
671
+ private pageHidden(): void {
672
+ if (this.terminal) return;
673
+ this.started = true; // never start later
674
+ if (this.config.whenHidden === "cancel") this.emitTerminal({ type: "cancelled" });
675
+ else this.finishWithCollected();
676
+ }
677
+
678
+ private signalSpeech(): void {
679
+ if (this.terminal || this.speechSignalled) return;
680
+ this.speechSignalled = true;
681
+ try {
682
+ this.config.onSpeechStart?.();
683
+ } catch {
684
+ // a host callback must not break the recognizer's event handling
685
+ }
686
+ }
687
+
688
+ private startRecognizer(): void {
689
+ const track = this.config.audio?.track;
690
+ if (track !== undefined) this.recognition.start(track);
691
+ else this.recognition.start();
692
+ }
693
+
694
+ events(): AsyncIterable<SessionEvent> {
695
+ if (this.iterated) {
696
+ throw new VoiceError("bad_request", "a transcription session's events() can be consumed only once");
697
+ }
698
+ this.iterated = true;
699
+ if (!this.started && !this.terminal) {
700
+ this.started = true;
701
+ this.lastWordAt = this.now();
702
+ // Endpointing starts with the recognizer, not with the first result: a silent session has
703
+ // to fail with `no_speech` by itself, and the hard cap has to hold when nothing arrives.
704
+ this.startWatching();
705
+ try {
706
+ this.startRecognizer();
707
+ } catch (error) {
708
+ this.fail(VoiceError.wrapping(error));
709
+ }
710
+ }
711
+ let handedOut = false;
712
+ return {
713
+ [Symbol.asyncIterator]: () => {
714
+ if (handedOut) throw new VoiceError("bad_request", "a transcription session's events can be iterated only once");
715
+ handedOut = true;
716
+ return { next: () => this.next() };
717
+ },
718
+ };
719
+ }
720
+
721
+ async end(): Promise<void> {
722
+ if (this.endPromise) return this.endPromise;
723
+ this.stopRequested = true;
724
+ if (!this.started) {
725
+ // Ended before `events()` started anything: nothing was heard, and nothing may start later.
726
+ this.started = true;
727
+ this.fail(new VoiceError("no_speech"));
728
+ this.endPromise = Promise.resolve();
729
+ return this.endPromise;
730
+ }
731
+ this.endPromise = this.finishByRequest();
732
+ return this.endPromise;
733
+ }
734
+
735
+ async cancel(): Promise<void> {
736
+ // A cancelled session never starts the recognizer, even if `events()` is called afterwards.
737
+ this.started = true;
738
+ if (this.terminal) return;
739
+ // `emitTerminal` aborts the recognizer: the microphone (and, in service mode, the upload) stops.
740
+ this.emitTerminal({ type: "cancelled" });
741
+ }
742
+
743
+ // MARK: internals
744
+
745
+ private async finishByRequest(): Promise<void> {
746
+ try {
747
+ this.recognition.stop();
748
+ } catch (error) {
749
+ this.fail(VoiceError.wrapping(error));
750
+ return;
751
+ }
752
+ // Wait for the browser's final (it fires `end` after `stop`), but never longer than the
753
+ // finalization deadline: an engine that ignores `stop` still yields the words it collected.
754
+ await Promise.race([
755
+ this.terminalSignal,
756
+ (async () => {
757
+ await this.sleep(this.endpointing.finalizationDeadlineSeconds * 1000);
758
+ if (!this.terminal) this.finishWithCollected();
759
+ })(),
760
+ ]);
761
+ }
762
+
763
+ private onResult(event: SpeechRecognitionEventLike): void {
764
+ if (this.terminal) return;
765
+ this.idleRestarts = 0;
766
+ let changed = false;
767
+ // Results before `resultIndex` are settled. From it on, finals are appended once and every
768
+ // non-final result is part of the current hypothesis, so the volatile text is all of them.
769
+ const volatile: string[] = [];
770
+ for (let index = event.resultIndex; index < event.results.length; index += 1) {
771
+ const result = event.results[index];
772
+ if (!result) continue;
773
+ const alternative = result[0];
774
+ const transcript = alternative?.transcript ?? "";
775
+ if (result.isFinal) {
776
+ const trimmed = transcript.trim();
777
+ if (trimmed.length > 0) {
778
+ this.finalizedText = joinText(this.finalizedText, trimmed);
779
+ changed = true;
780
+ this.words = true;
781
+ this.lastWordAt = this.now();
782
+ }
783
+ } else {
784
+ volatile.push(transcript);
785
+ if (transcript.trim().length > 0) {
786
+ this.words = true;
787
+ this.lastWordAt = this.now();
788
+ }
789
+ changed = true;
790
+ }
791
+ }
792
+ const volatileText = volatile.reduce(joinText, "");
793
+ if (this.words) this.signalSpeech(); // engines without `speechstart` (Safari) still barge in
794
+ if (volatileText !== this.volatileText) changed = true;
795
+ this.volatileText = volatileText;
796
+ if (changed) {
797
+ this.queue.push({
798
+ type: "partial",
799
+ partial: { finalizedText: this.finalizedText, volatileText: this.volatileText, sequence: this.sequence++ },
800
+ });
801
+ this.drain();
802
+ }
803
+ if (this.stopRequested && this.volatileText.length === 0) {
804
+ this.finishWithCollected();
805
+ }
806
+ }
807
+
808
+ private onError(event: SpeechRecognitionErrorEventLike): void {
809
+ if (this.terminal) return;
810
+ const error = mapRecognitionError(event);
811
+ if (error.code === "no_speech") {
812
+ // The browser's own silence timeout. Words already heard are a final, not a failure; with
813
+ // restarts on, a silent run just restarts and the session's own no-speech deadline decides.
814
+ if (this.words) {
815
+ this.finishWithCollected();
816
+ return;
817
+ }
818
+ if (this.config.onEarlyEnd === "restart" && !this.stopRequested) return;
819
+ }
820
+ if (error.code === "cancelled") {
821
+ this.emitTerminal({ type: "cancelled" });
822
+ return;
823
+ }
824
+ this.fail(error);
825
+ }
826
+
827
+ private onEnd(): void {
828
+ if (this.terminal) return;
829
+ if (!this.stopRequested && this.config.onEarlyEnd === "restart" && this.restart()) return;
830
+ this.finishWithCollected(true);
831
+ }
832
+
833
+ /**
834
+ * The browser ended recognition on its own (Chrome on Android after one utterance). Keep the
835
+ * session: what it heard becomes settled text and the recognizer starts again.
836
+ */
837
+ private restart(): boolean {
838
+ if (this.restarts >= this.config.maxRestarts || this.idleRestarts >= MAX_IDLE_RESTARTS) return false;
839
+ if (this.volatileText.length > 0) {
840
+ // The ended run's hypothesis will never be finalized by the browser now.
841
+ this.finalizedText = joinText(this.finalizedText, this.volatileText);
842
+ this.volatileText = "";
843
+ }
844
+ this.restarts += 1;
845
+ this.idleRestarts += 1;
846
+ this.speechSignalled = false;
847
+ try {
848
+ this.startRecognizer();
849
+ return true;
850
+ } catch {
851
+ return false;
852
+ }
853
+ }
854
+
855
+ /**
856
+ * The one rule for "the session is over, report what it heard": words make a `final`, no words
857
+ * is `no_speech` — whether the end came from the browser, `end()`, or the finalization deadline.
858
+ */
859
+ private finishWithCollected(fromEnd = false): void {
860
+ this.emitTerminal(
861
+ this.words
862
+ ? { type: "final", text: this.text, execution: this.recognitionExecution }
863
+ : { type: "failed", error: new VoiceError("no_speech"), execution: this.recognitionExecution },
864
+ fromEnd,
865
+ );
866
+ }
867
+
868
+ /** `local` only while the on-device flag still holds; anything else is reported as the service. */
869
+ private get recognitionExecution(): RecognitionExecution {
870
+ return this.execution === "onDevice" && this.recognition.processLocally === true ? "local" : "service";
871
+ }
872
+
873
+ /** Endpointing: silence after words, a silent session, and the hard cap. */
874
+ private startWatching(): void {
875
+ void this.watch();
876
+ }
877
+
878
+ private async watch(): Promise<void> {
879
+ if (this.watchTask) return;
880
+ this.watchTask = (async () => {
881
+ const startedAt = this.now();
882
+ for (;;) {
883
+ if (this.terminal) return;
884
+ await this.sleep(this.endpointing.tickIntervalSeconds * 1000);
885
+ if (this.terminal) return;
886
+ const now = this.now();
887
+ if (this.endpointing.maxDurationSeconds !== null && now - startedAt >= this.endpointing.maxDurationSeconds * 1000) {
888
+ await this.end();
889
+ return;
890
+ }
891
+ if (!this.words && now - startedAt >= this.endpointing.noSpeechTimeoutSeconds * 1000) {
892
+ this.fail(new VoiceError("no_speech"));
893
+ return;
894
+ }
895
+ if (this.words && now - this.lastWordAt >= this.endpointing.silenceLimitSeconds * 1000) {
896
+ await this.end();
897
+ return;
898
+ }
899
+ }
900
+ })();
901
+ }
902
+
903
+ private watchTask: Promise<void> | undefined;
904
+
905
+ private get text(): string {
906
+ return joinText(this.finalizedText, this.volatileText);
907
+ }
908
+
909
+ private fail(error: VoiceError): void {
910
+ this.emitTerminal({ type: "failed", error, execution: this.recognitionExecution });
911
+ }
912
+
913
+ /**
914
+ * Records the one terminal event. Unless the browser already ended the session (`onend`), the
915
+ * recognizer is aborted and detached here: a watchdog or deadline that ends the session must
916
+ * also close the microphone, and in service mode stop audio going to the network.
917
+ */
918
+ private emitTerminal(event: SessionEvent, fromEnd = false): void {
919
+ if (this.terminal) return;
920
+ this.terminal = event.type === "final" ? "final" : event.type === "failed" ? "failed" : "cancelled";
921
+ this.release(fromEnd);
922
+ this.queue.push(event);
923
+ this.finished = true;
924
+ this.drain();
925
+ this.resolveTerminal?.();
926
+ }
927
+
928
+ private release(fromEnd: boolean): void {
929
+ const recognition = this.recognition;
930
+ recognition.onstart = null;
931
+ recognition.onresult = null;
932
+ recognition.onerror = null;
933
+ recognition.onend = null;
934
+ if ("onspeechstart" in recognition) recognition.onspeechstart = null;
935
+ for (const cleanup of this.cleanups.splice(0)) {
936
+ try {
937
+ cleanup();
938
+ } catch {
939
+ // removing a listener never fails the session
940
+ }
941
+ }
942
+ if (!fromEnd) {
943
+ try {
944
+ recognition.abort();
945
+ } catch {
946
+ // aborting an already-ended or failed recognizer is not itself a failure
947
+ }
948
+ }
949
+ // Every terminal path closes the microphone the SDK opened.
950
+ const audio = this.config.audio;
951
+ if (audio !== undefined) {
952
+ const tracks = new Set(audio.owned);
953
+ if (audio.stopTrack) tracks.add(audio.track);
954
+ for (const track of tracks) {
955
+ try {
956
+ track.stop();
957
+ } catch {
958
+ // an already-stopped track is fine
959
+ }
960
+ }
961
+ }
962
+ }
963
+
964
+ private drain(): void {
965
+ const resolve = this.resolved;
966
+ this.resolved = undefined;
967
+ resolve?.();
968
+ }
969
+
970
+ private async next(): Promise<IteratorResult<SessionEvent>> {
971
+ // Single consumer (enforced in `events()`), so one resolver slot is enough.
972
+ for (;;) {
973
+ const event = this.queue.shift();
974
+ if (event) {
975
+ if (this.finished && this.queue.length === 0) this.resolved = undefined;
976
+ return { value: event, done: false };
977
+ }
978
+ if (this.finished) return { value: undefined, done: true };
979
+ await new Promise<void>((resolve) => {
980
+ this.resolved = resolve;
981
+ });
982
+ }
983
+ }
984
+ }
985
+
986
+ function mapRecognitionError(event: SpeechRecognitionErrorEventLike): VoiceError {
987
+ switch (event.error) {
988
+ case "not-allowed":
989
+ case "service-not-allowed":
990
+ return new VoiceError("denied", event.message ?? "microphone or recognition permission was denied");
991
+ case "no-speech":
992
+ return new VoiceError("no_speech");
993
+ case "language-not-supported":
994
+ return new VoiceError("language_unsupported");
995
+ case "audio-capture":
996
+ return new VoiceError("unavailable", "no microphone is available");
997
+ case "network":
998
+ return new VoiceError("failed", "the browser's recognition service could not be reached");
999
+ case "aborted":
1000
+ return new VoiceError("cancelled");
1001
+ default:
1002
+ return new VoiceError("failed", event.message ?? `recognition error: ${event.error}`);
1003
+ }
1004
+ }
1005
+
1006
+ /** Joins two transcript pieces with exactly one space between non-empty, trimmed parts. */
1007
+ function joinText(left: string, right: string): string {
1008
+ const a = left.trim();
1009
+ const b = right.trim();
1010
+ if (a.length === 0) return b;
1011
+ if (b.length === 0) return a;
1012
+ return `${a} ${b}`;
1013
+ }