@adea-ai/voice 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -92,7 +92,11 @@ of the shared contract (`WebTranscriptionSessionOptions`):
92
92
  - **Microphone choice**: `microphone: { deviceId }` opens that device and recognises from its track
93
93
  (`start(track)`, Chrome 137+); a track the SDK opened is stopped on every terminal path. A host
94
94
  track (`{ track, stopOnEnd? }`) stays the host's. Browsers that would ignore the track refuse the
95
- choice instead of silently using another microphone.
95
+ choice instead of silently using another microphone. That includes Microsoft Edge, which exposes
96
+ `processLocally` but records the default microphone whatever track it is given; it is recognised
97
+ by the `Microsoft Edge` client-hint brand or the `Edg/` user-agent token (`isMicrosoftEdge`).
98
+ `provider.acceptsChosenMicrophone()` says up front whether a choice would be honoured, so a host
99
+ can hide its picker; `recognitionAcceptsAudioTrack` in the environment overrides the detection.
96
100
  - **Browsers that stop after one utterance** (Chrome on Android): by default the browser's early
97
101
  `end` is one clean `final` with what was heard. `onEarlyEnd: "restart"` restarts the recognizer
98
102
  inside the same session (up to `maxRestarts`, and never more than 3 times in a row without a
@@ -107,6 +111,14 @@ of the shared contract (`WebTranscriptionSessionOptions`):
107
111
  - **Model install**: `installModel(locale, { allowDownload, onProgress, signal })` still resolves
108
112
  the browser's boolean; it reports `started`/`downloading`/`installed`/`failed`/`cancelled` and
109
113
  rejects with `cancelled` on abort (the browser may finish its own download in the background).
114
+ It always settles: after `timeoutMs` (default `DEFAULT_MODEL_INSTALL_TIMEOUT_MS`, 10 minutes) it
115
+ reports `failed` and rejects with `assets_install_failed`. Firefox 160 accepts `install()` and
116
+ never settles it, so a host that passes no `signal` would otherwise wait forever. `Infinity`
117
+ turns the deadline off. Call `installModel` from the person's click or key press, **one call per
118
+ gesture**: a browser may require transient user activation for `install()` and spend it on that
119
+ call (Firefox 160 refuses the next locale's install from the same click with "install() requires
120
+ transient user activation"). That refusal rejects with `denied` and
121
+ `reason: "needs_user_gesture"`; ask for another click and call again.
110
122
  - **Barge-in**: `onSpeechStart` fires on the recognizer's `speechstart` (or the first words).
111
123
  `VoiceTurnManager` wires it to `notifySpeechDetected()` itself; hosts with their own sessions
112
124
  spread `bargeInOnSpeechStart(manager)` into the session options.
@@ -140,4 +152,13 @@ files left by a copy that flattened them, and launches each helper with `--versi
140
152
  to require the lock's release, wire 1 and contract 1. `adea-voice-helpers digest <file>` prints the
141
153
  code digest.
142
154
 
155
+ `stageVoiceHelpers` and `verifyStagedVoiceHelpers` take an optional `launch` (how the `--version`
156
+ handshake starts a helper; by default the executable runs directly) and `stageVoiceHelpers` an
157
+ optional `tar` runner. Staging unpacks inside the output directory, from a copy of the verified
158
+ archive whose sha256 it checks again, so a cache on another volume works and every move is a
159
+ rename on one filesystem (symlinks in `Frameworks/` stay symlinks). It gives `tar` only relative
160
+ paths (`../<file>`, no `-C`), so Git for Windows' GNU tar, which reads `C:\...` as a remote
161
+ `host:path`, unpacks the same way as bsdtar. A `--local` staging copies the shared `Frameworks/`
162
+ once, however many helpers it stages, replacing each top-level entry.
163
+
143
164
  Build and test: `bun install && bun test && bunx tsc --noEmit && bun run build`.
@@ -10,7 +10,7 @@ import {
10
10
  currentHelperTarget2,
11
11
  stageVoiceHelpers2,
12
12
  verifyStagedVoiceHelpers2
13
- } from "../index-m4g2tpeq.js";
13
+ } from "../index-bt4dng98.js";
14
14
 
15
15
  // src/cli/helpers-cli.ts
16
16
  import { existsSync, writeFileSync } from "node:fs";
@@ -14,10 +14,22 @@ export type VoiceErrorCode = (typeof VOICE_ERROR_CODES)[number];
14
14
  * through, legacy camelCase codes are translated, and anything else becomes `failed`.
15
15
  */
16
16
  export declare function normalizeVoiceErrorCode(value: unknown): VoiceErrorCode;
17
+ /**
18
+ * A finer cause inside a code, for a case a host handles differently from the rest of that code.
19
+ * Not a wire code: it travels only on a browser `VoiceError`, and the code stays the wire value.
20
+ *
21
+ * - `needs_user_gesture` (with `denied`): the browser refused because the call did not run inside
22
+ * a user gesture (Firefox 160: "install() requires transient user activation"). Call it again
23
+ * from the person's click or key press.
24
+ */
25
+ export type VoiceErrorReason = "needs_user_gesture";
17
26
  /** The typed failure every public browser operation reports. */
18
27
  export declare class VoiceError extends Error {
19
28
  readonly code: VoiceErrorCode;
20
- constructor(code: VoiceErrorCode, message?: string);
29
+ readonly reason?: VoiceErrorReason;
30
+ constructor(code: VoiceErrorCode, message?: string, options?: {
31
+ readonly reason?: VoiceErrorReason;
32
+ });
21
33
  /**
22
34
  * Preserve a typed error, map an abort to `cancelled`, keep a recognisable `code` from a bridge
23
35
  * error, and fold anything else into `fallback`.
@@ -27,12 +27,12 @@ import {
27
27
  encodeWireCommand2,
28
28
  correlationId2,
29
29
  isCompatibleHandshake2
30
- } from "../index-7n7epq1a.js";
30
+ } from "../index-j6vkge53.js";
31
31
  import {
32
32
  VOICE_ERROR_CODES2,
33
33
  normalizeVoiceErrorCode2,
34
34
  VoiceError2
35
- } from "../index-tvz9s9nz.js";
35
+ } from "../index-3afbsw63.js";
36
36
  export {
37
37
  AVAILABLE2 as AVAILABLE,
38
38
  CONTRACT_MAJOR2 as CONTRACT_MAJOR,
@@ -1,3 +1,4 @@
1
+ import { type SpawnSyncReturns } from "node:child_process";
1
2
  export declare const HELPER_LOCK_SCHEMA = 1;
2
3
  export declare const HELPER_NAMES: readonly ["adea-voice-helper", "adea-transcribe-helper", "adea-tts-helper"];
3
4
  export type HelperName = (typeof HELPER_NAMES)[number];
@@ -69,8 +70,33 @@ export interface StageHelpersOptions {
69
70
  readonly fetch?: typeof fetch;
70
71
  /** Run `--version` on the staged executable (default: when the target matches this machine). */
71
72
  readonly handshake?: boolean;
73
+ /** How the `--version` handshake starts the helper (default: runs the executable directly). */
74
+ readonly launch?: HelperLauncher;
75
+ /** How `tar` runs (default: the `tar` on PATH). Every argument it gets is relative. */
76
+ readonly tar?: TarRunner;
77
+ /**
78
+ * How an unpacked entry moves into `outDir` (default `renameSync`). Unpacking happens inside
79
+ * `outDir`, so this never crosses a filesystem; tests pass one that fails with `EXDEV` across
80
+ * simulated volumes to prove it.
81
+ */
82
+ readonly rename?: (from: string, to: string) => void;
72
83
  readonly log?: (message: string) => void;
73
84
  }
85
+ /**
86
+ * Starts `executable` with `args` and waits for it, like `spawnSync`. The default runs the
87
+ * executable directly. A host whose helper needs a launcher (and the tests, whose stand-in helper is
88
+ * a script run by the JS runtime, which Windows cannot exec) passes its own.
89
+ */
90
+ export type HelperLauncher = (executable: string, args: readonly string[], options: {
91
+ readonly encoding: "utf8";
92
+ readonly timeout: number;
93
+ readonly killSignal: "SIGKILL";
94
+ }) => SpawnSyncReturns<string>;
95
+ /** Runs `tar` with `args` in `cwd`, like `spawnSync("tar", args, { cwd })`. */
96
+ export type TarRunner = (args: readonly string[], options: {
97
+ readonly cwd: string;
98
+ readonly encoding: "utf8";
99
+ }) => SpawnSyncReturns<string>;
74
100
  /**
75
101
  * Downloads, verifies and unpacks the pinned helpers into `outDir`, then records what was staged.
76
102
  * Reuses an already staged helper whose digests match. Throws `HelperLockError` on any mismatch;
@@ -89,6 +115,8 @@ export interface VerifyStagedOptions {
89
115
  readonly handshake?: boolean;
90
116
  /** How long one `--version` may take. Default 10 s. */
91
117
  readonly handshakeTimeoutMs?: number;
118
+ /** How the handshake starts each helper (default: runs the executable directly). */
119
+ readonly launch?: HelperLauncher;
92
120
  /**
93
121
  * Run `codesign --verify --strict` on a helper that was signed again after staging (default: on
94
122
  * macOS for a macOS target).
@@ -113,6 +141,8 @@ export interface HandshakeExpectations {
113
141
  readonly release?: string;
114
142
  /** How long `--version` may take before the helper counts as hung. Default 10 s. */
115
143
  readonly timeoutMs?: number;
144
+ /** How the helper is started (default: runs the executable directly). */
145
+ readonly launch?: HelperLauncher;
116
146
  }
117
147
  /**
118
148
  * Runs `<helper> --version` and refuses a helper that does not start (a missing library is a dyld
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  routingPolicyFor2
3
- } from "../index-a7d617zr.js";
3
+ } from "../index-b10aqmme.js";
4
4
  import {
5
5
  VOICE_CONTRACT2,
6
6
  AVAILABLE2,
@@ -27,7 +27,7 @@ import {
27
27
  verifyStagedVoiceHelpers2,
28
28
  readStagedRecord2,
29
29
  assertHandshake2
30
- } from "../index-m4g2tpeq.js";
30
+ } from "../index-bt4dng98.js";
31
31
  import {
32
32
  TURN_WIRE_MINOR2,
33
33
  RELEASE_ASSETS_WIRE_MINOR2,
@@ -37,10 +37,10 @@ import {
37
37
  encodeWireCommand2,
38
38
  correlationId2,
39
39
  isCompatibleHandshake2
40
- } from "../index-7n7epq1a.js";
40
+ } from "../index-j6vkge53.js";
41
41
  import {
42
42
  VoiceError2
43
- } from "../index-tvz9s9nz.js";
43
+ } from "../index-3afbsw63.js";
44
44
 
45
45
  // src/desktop/helper-process.ts
46
46
  import { spawn as spawnProcess } from "node:child_process";
@@ -55,10 +55,13 @@ var DEFAULT_MESSAGES = {
55
55
 
56
56
  class VoiceError2 extends Error {
57
57
  code;
58
- constructor(code, message = DEFAULT_MESSAGES[code]) {
58
+ reason;
59
+ constructor(code, message = DEFAULT_MESSAGES[code], options = {}) {
59
60
  super(message);
60
61
  this.name = "VoiceError";
61
62
  this.code = code;
63
+ if (options.reason !== undefined)
64
+ this.reason = options.reason;
62
65
  }
63
66
  static wrapping(error, fallback = "failed") {
64
67
  if (error instanceof VoiceError2)
@@ -3,7 +3,7 @@ import {
3
3
  } from "./index-ght8wwpd.js";
4
4
  import {
5
5
  VoiceError2
6
- } from "./index-tvz9s9nz.js";
6
+ } from "./index-3afbsw63.js";
7
7
 
8
8
  // src/settings/settings.ts
9
9
  var SETTINGS_SCHEMA_VERSION2 = 2;
@@ -2,13 +2,15 @@ import {
2
2
  WIRE_VERSION2,
3
3
  CONTRACT_MAJOR2,
4
4
  parseWireLine2
5
- } from "./index-7n7epq1a.js";
5
+ } from "./index-j6vkge53.js";
6
6
 
7
7
  // src/desktop/helper-lock.ts
8
8
  import { createHash as createHash2 } from "node:crypto";
9
9
  import { spawnSync } from "node:child_process";
10
10
  import {
11
11
  chmodSync,
12
+ copyFileSync,
13
+ cpSync,
12
14
  existsSync,
13
15
  lstatSync,
14
16
  mkdirSync,
@@ -20,7 +22,7 @@ import {
20
22
  statSync,
21
23
  writeFileSync
22
24
  } from "node:fs";
23
- import { dirname, join, relative, resolve, sep } from "node:path";
25
+ import { basename, dirname, join, relative, resolve, sep } from "node:path";
24
26
  import { tmpdir } from "node:os";
25
27
 
26
28
  // src/desktop/macho-digest.ts
@@ -238,6 +240,8 @@ function currentHelperTarget2(platform = process.platform, arch = process.arch)
238
240
  function sha256File2(path) {
239
241
  return createHash2("sha256").update(readFileSync2(path)).digest("hex");
240
242
  }
243
+ var directLauncher = (executable, args, options) => spawnSync(executable, [...args], options);
244
+ var pathTar = (args, options) => spawnSync("tar", [...args], options);
241
245
  async function stageVoiceHelpers2(options) {
242
246
  const log = options.log ?? (() => {
243
247
  return;
@@ -248,11 +252,13 @@ async function stageVoiceHelpers2(options) {
248
252
  const helpers = {};
249
253
  const version = options.localDir ? `local+${options.lock.version}` : options.lock.version;
250
254
  mkdirSync(outDir, { recursive: true });
255
+ let localFrameworksCopied = false;
251
256
  try {
252
257
  for (const helper of options.helpers) {
253
258
  const executable = join(outDir, helper);
254
259
  if (options.localDir) {
255
- stageLocal(options.localDir, helper, outDir);
260
+ stageLocal(options.localDir, helper, outDir, !localFrameworksCopied);
261
+ localFrameworksCopied = true;
256
262
  helpers[helper] = { sha256: "local", executableSha256: sha256File2(executable), ...codeDigestEntry(executable) };
257
263
  } else {
258
264
  const pin = helperPin2(options.lock, helper, options.target);
@@ -264,7 +270,7 @@ async function stageVoiceHelpers2(options) {
264
270
  } else {
265
271
  const archive = await obtainArchive(options, helper, pin, log);
266
272
  try {
267
- extractArchive(archive, outDir, helper);
273
+ extractArchive(archive, pin.sha256, outDir, helper, options.tar ?? pathTar, options.rename ?? renameSync);
268
274
  } finally {
269
275
  if (!options.cacheDir)
270
276
  rmSync(dirname(archive), { recursive: true, force: true });
@@ -283,7 +289,7 @@ async function stageVoiceHelpers2(options) {
283
289
  helpers[helper] = { sha256: pin.sha256, executableSha256: pin.executableSha256, ...code };
284
290
  }
285
291
  if (handshake)
286
- assertHandshake2(executable, options.localDir ? {} : { release: options.lock.version });
292
+ assertHandshake2(executable, options.localDir ? { launch: options.launch } : { release: options.lock.version, launch: options.launch });
287
293
  }
288
294
  } catch (error) {
289
295
  rmSync(outDir, { recursive: true, force: true });
@@ -339,7 +345,7 @@ function verifyStagedVoiceHelpers2(options) {
339
345
  verifySupportFiles(dir, record);
340
346
  if (options.handshake ?? options.target === currentHelperTarget2()) {
341
347
  for (const helper of options.helpers) {
342
- assertHandshake2(join(dir, helper), { release: options.lock.version, timeoutMs: options.handshakeTimeoutMs });
348
+ assertHandshake2(join(dir, helper), { release: options.lock.version, timeoutMs: options.handshakeTimeoutMs, launch: options.launch });
343
349
  }
344
350
  }
345
351
  }
@@ -355,7 +361,7 @@ function readStagedRecord2(dir) {
355
361
  }
356
362
  function assertHandshake2(executable, expect = {}) {
357
363
  const timeoutMs = expect.timeoutMs ?? 1e4;
358
- const run = spawnSync(executable, ["--version"], { encoding: "utf8", timeout: timeoutMs, killSignal: "SIGKILL" });
364
+ const run = (expect.launch ?? directLauncher)(executable, ["--version"], { encoding: "utf8", timeout: timeoutMs, killSignal: "SIGKILL" });
359
365
  if (run.error || run.status !== 0) {
360
366
  const reason = run.error ? run.error.code === "ETIMEDOUT" ? `did not answer within ${timeoutMs} ms` : run.error.message : run.signal ? `was killed by ${run.signal}` : `exited ${String(run.status)}`;
361
367
  const detail = (run.stderr ?? "").trim().split(`
@@ -383,9 +389,12 @@ function assertSigned(path) {
383
389
  throw new HelperLockError2(`${path} is not validly signed: ${(run.stderr || run.error?.message || `exit ${String(run.status)}`).trim()}`);
384
390
  }
385
391
  }
392
+ var EXTRACT_PREFIX = ".adea-voice-extract-";
386
393
  function walk(dir, root = dir) {
387
394
  const entries = [];
388
395
  for (const name of readdirSync(dir).sort()) {
396
+ if (dir === root && name.startsWith(EXTRACT_PREFIX))
397
+ continue;
389
398
  const path = join(dir, name);
390
399
  const stat = lstatSync(path);
391
400
  entries.push([relative(root, path).split(sep).join("/"), stat]);
@@ -473,40 +482,49 @@ async function obtainArchive(options, helper, pin, log) {
473
482
  renameSync(partial, target);
474
483
  return target;
475
484
  }
476
- function extractArchive(archive, outDir, helper) {
477
- const scratch = mkdtempSync(join(tmpdir(), "adea-voice-extract-"));
485
+ function extractArchive(archive, sha256, outDir, helper, tar, move) {
486
+ const work = mkdtempSync(join(outDir, EXTRACT_PREFIX));
478
487
  try {
479
- const listing = spawnSync("tar", ["-tzf", archive], { encoding: "utf8" });
488
+ const name = basename(archive);
489
+ const copy = join(work, name);
490
+ copyFileSync(archive, copy);
491
+ const copied = sha256File2(copy);
492
+ if (copied !== sha256)
493
+ throw new HelperLockError2(`${helper}: ${archive} changed while it was copied (sha256 ${copied}, pinned ${sha256})`);
494
+ const scratch = join(work, "unpacked");
495
+ mkdirSync(scratch);
496
+ const named = `../${name}`;
497
+ const listing = tar(["-tzf", named], { cwd: scratch, encoding: "utf8" });
480
498
  if (listing.status !== 0)
481
- throw new HelperLockError2(`${helper}: cannot read ${archive}`);
482
- for (const entry of listing.stdout.split(`
483
- `).filter(Boolean)) {
484
- if (entry.startsWith("/") || entry.split("/").includes(".."))
499
+ throw new HelperLockError2(`${helper}: cannot read ${archive}: ${listing.stderr ?? ""}`.trim());
500
+ for (const entry of listing.stdout.split(/\r?\n/).filter(Boolean)) {
501
+ const parts = entry.split(/[\\/]/);
502
+ if (entry.startsWith("/") || entry.startsWith("\\") || /^[A-Za-z]:/.test(entry) || parts.includes("..")) {
485
503
  throw new HelperLockError2(`${helper}: unsafe archive entry ${entry}`);
504
+ }
486
505
  }
487
- const unpack = spawnSync("tar", ["-xzf", archive, "-C", scratch], { encoding: "utf8" });
506
+ const unpack = tar(["-xzf", named], { cwd: scratch, encoding: "utf8" });
488
507
  if (unpack.status !== 0)
489
508
  throw new HelperLockError2(`${helper}: cannot unpack ${archive}: ${unpack.stderr}`);
490
509
  const executable = join(scratch, helper);
491
510
  if (!existsSync(executable) || !statSync(executable).isFile())
492
511
  throw new HelperLockError2(`${helper}: the archive holds no ${helper}`);
493
512
  rmSync(join(outDir, helper), { force: true });
494
- renameSync(executable, join(outDir, helper));
513
+ move(executable, join(outDir, helper));
495
514
  const frameworks = join(scratch, "Frameworks");
496
515
  if (existsSync(frameworks)) {
497
516
  const destination = join(outDir, "Frameworks");
498
517
  mkdirSync(destination, { recursive: true });
499
- for (const entry of spawnSync("ls", ["-1", frameworks], { encoding: "utf8" }).stdout.split(`
500
- `).filter(Boolean)) {
518
+ for (const entry of readdirSync(frameworks).filter((name) => !name.startsWith(".")).sort()) {
501
519
  rmSync(join(destination, entry), { recursive: true, force: true });
502
- renameSync(join(frameworks, entry), join(destination, entry));
520
+ move(join(frameworks, entry), join(destination, entry));
503
521
  }
504
522
  }
505
523
  } finally {
506
- rmSync(scratch, { recursive: true, force: true });
524
+ rmSync(work, { recursive: true, force: true });
507
525
  }
508
526
  }
509
- function stageLocal(localDir, helper, outDir) {
527
+ function stageLocal(localDir, helper, outDir, withFrameworks) {
510
528
  const source = join(resolve(localDir), helper);
511
529
  if (!existsSync(source))
512
530
  throw new HelperLockError2(`${helper} is not in the local helper directory ${localDir}`);
@@ -515,8 +533,14 @@ function stageLocal(localDir, helper, outDir) {
515
533
  writeFileSync(destination, readFileSync2(source));
516
534
  chmodSync(destination, 493);
517
535
  const frameworks = join(resolve(localDir), "Frameworks");
518
- if (existsSync(frameworks))
519
- spawnSync("cp", ["-R", frameworks, outDir]);
536
+ if (!withFrameworks || !existsSync(frameworks))
537
+ return;
538
+ const staged = join(outDir, "Frameworks");
539
+ mkdirSync(staged, { recursive: true });
540
+ for (const entry of readdirSync(frameworks).sort()) {
541
+ rmSync(join(staged, entry), { recursive: true, force: true });
542
+ cpSync(join(frameworks, entry), join(staged, entry), { recursive: true, verbatimSymlinks: true });
543
+ }
520
544
  }
521
545
 
522
546
  export { isMachO2, machoCodeDigest2, machoCodeDigestFile2, HELPER_LOCK_SCHEMA2, HELPER_NAMES2, HELPER_TARGETS2, MAX_HELPER_ARCHIVE_BYTES2, STAGED_RECORD_FILE2, HelperLockError2, validateHelperLock2, readHelperLock2, helperPin2, helperArtifactUrl2, currentHelperTarget2, sha256File2, stageVoiceHelpers2, verifyStagedVoiceHelpers2, readStagedRecord2, assertHandshake2 };
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  normalizeVoiceErrorCode2
3
- } from "./index-tvz9s9nz.js";
3
+ } from "./index-3afbsw63.js";
4
4
 
5
5
  // src/contract/wire.ts
6
6
  var WIRE_VERSION2 = 1;
package/dist/index.js CHANGED
@@ -17,7 +17,7 @@ import {
17
17
  createVoiceSettingsStore2,
18
18
  withLegacyDictationPreferences2,
19
19
  assertUsableSettings2
20
- } from "./index-a7d617zr.js";
20
+ } from "./index-b10aqmme.js";
21
21
  import {
22
22
  VOICE_CONTRACT2,
23
23
  isCompatibleContract2,
@@ -44,12 +44,12 @@ import {
44
44
  encodeWireCommand2,
45
45
  correlationId2,
46
46
  isCompatibleHandshake2
47
- } from "./index-7n7epq1a.js";
47
+ } from "./index-j6vkge53.js";
48
48
  import {
49
49
  VOICE_ERROR_CODES2,
50
50
  normalizeVoiceErrorCode2,
51
51
  VoiceError2
52
- } from "./index-tvz9s9nz.js";
52
+ } from "./index-3afbsw63.js";
53
53
  export {
54
54
  AVAILABLE2 as AVAILABLE,
55
55
  CONTRACT_MAJOR2 as CONTRACT_MAJOR,
@@ -14,7 +14,7 @@ import {
14
14
  createVoiceSettingsStore2,
15
15
  withLegacyDictationPreferences2,
16
16
  assertUsableSettings2
17
- } from "../index-a7d617zr.js";
17
+ } from "../index-b10aqmme.js";
18
18
  export {
19
19
  DEFAULT_VOICE_SETTINGS2 as DEFAULT_VOICE_SETTINGS,
20
20
  SETTINGS_SCHEMA_VERSION2 as SETTINGS_SCHEMA_VERSION,
package/dist/web/index.js CHANGED
@@ -10,8 +10,22 @@ import {
10
10
  } from "../index-ght8wwpd.js";
11
11
  import {
12
12
  VoiceError2
13
- } from "../index-tvz9s9nz.js";
13
+ } from "../index-3afbsw63.js";
14
14
  // src/web/stt/speech-recognition.ts
15
+ function needsUserGesture(error) {
16
+ const message = error !== null && typeof error === "object" ? error.message : undefined;
17
+ return typeof message === "string" && /\buser (?:activation|gesture)\b/i.test(message);
18
+ }
19
+ var MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
20
+ var DEFAULT_MODEL_INSTALL_TIMEOUT_MS = 10 * 60 * 1000;
21
+ function isMicrosoftEdge(navigator) {
22
+ const brands = navigator?.userAgentData?.brands;
23
+ if (Array.isArray(brands) && brands.some((entry) => typeof entry?.brand === "string" && entry.brand.startsWith("Microsoft Edge"))) {
24
+ return true;
25
+ }
26
+ const agent = navigator?.userAgent;
27
+ return typeof agent === "string" && /\bEdg(?:e|A|iOS)?\//.test(agent);
28
+ }
15
29
  function recognitionConstructor(environment) {
16
30
  return environment.SpeechRecognition ?? environment.webkitSpeechRecognition;
17
31
  }
@@ -95,6 +109,10 @@ class BrowserRecognitionProvider {
95
109
  if (constructor === undefined || install === undefined) {
96
110
  throw new VoiceError2("assets_missing", "this browser has no on-device recognition install path");
97
111
  }
112
+ const timeoutMs = options.timeoutMs ?? DEFAULT_MODEL_INSTALL_TIMEOUT_MS;
113
+ if (typeof timeoutMs !== "number" || Number.isNaN(timeoutMs) || timeoutMs <= 0 || Number.isFinite(timeoutMs) && timeoutMs > MAX_TIMER_DELAY_MS) {
114
+ throw new VoiceError2("bad_request", `installModel timeoutMs must be a positive number of milliseconds up to ${MAX_TIMER_DELAY_MS} (about 24.8 days), or Infinity for no deadline`);
115
+ }
98
116
  const signal = options.signal;
99
117
  if (signal?.aborted)
100
118
  throw new VoiceError2("cancelled", "the model install was cancelled before it started");
@@ -106,21 +124,27 @@ class BrowserRecognitionProvider {
106
124
  report("started");
107
125
  let settled = false;
108
126
  let onAbort;
109
- const aborted = new Promise((_, reject) => {
127
+ let deadline;
128
+ const stopped = new Promise((_, reject) => {
110
129
  onAbort = () => reject(new VoiceError2("cancelled", "the model install was cancelled; the browser may finish it in the background"));
111
130
  signal?.addEventListener("abort", onAbort, { once: true });
131
+ if (Number.isFinite(timeoutMs)) {
132
+ deadline = setTimeout(() => reject(new VoiceError2("assets_install_failed", `the ${locale} recognition model did not install within ${Math.round(timeoutMs / 1000)} s; the browser may still finish it in the background`)), timeoutMs);
133
+ }
112
134
  });
113
135
  this.pollInstall(constructor, locale, options.pollIntervalMs ?? 500, () => settled, () => report("downloading"));
114
136
  try {
115
- const installed = await Promise.race([Promise.resolve(install.call(constructor, { langs: [locale] })), aborted]);
137
+ const installed = await Promise.race([Promise.resolve(install.call(constructor, { langs: [locale] })), stopped]);
116
138
  report(installed ? "installed" : "failed");
117
139
  return installed;
118
140
  } catch (error) {
119
- const wrapped = VoiceError2.wrapping(error);
141
+ const wrapped = needsUserGesture(error) ? new VoiceError2("denied", `the browser installs the ${locale} recognition model only from a user gesture; call installModel again from the person's click or key press`, { reason: "needs_user_gesture" }) : VoiceError2.wrapping(error);
120
142
  report(wrapped.code === "cancelled" ? "cancelled" : "failed");
121
143
  throw error instanceof VoiceError2 ? error : wrapped;
122
144
  } finally {
123
145
  settled = true;
146
+ if (deadline !== undefined)
147
+ clearTimeout(deadline);
124
148
  if (onAbort)
125
149
  signal?.removeEventListener("abort", onAbort);
126
150
  }
@@ -189,6 +213,17 @@ class BrowserRecognitionProvider {
189
213
  window: this.window
190
214
  });
191
215
  }
216
+ acceptsChosenMicrophone() {
217
+ if (this.environment.recognitionAcceptsAudioTrack !== undefined)
218
+ return this.environment.recognitionAcceptsAudioTrack;
219
+ const constructor = recognitionConstructor(this.environment);
220
+ if (constructor === undefined)
221
+ return false;
222
+ return this.honoursAudioTrack(new constructor);
223
+ }
224
+ honoursAudioTrack(recognition) {
225
+ return this.environment.recognitionAcceptsAudioTrack ?? (("processLocally" in recognition) && !isMicrosoftEdge(this.navigator));
226
+ }
192
227
  get navigator() {
193
228
  return this.environment.navigator;
194
229
  }
@@ -205,9 +240,8 @@ class BrowserRecognitionProvider {
205
240
  const microphone = options.microphone;
206
241
  if (microphone === undefined)
207
242
  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");
243
+ if (!this.honoursAudioTrack(recognition)) {
244
+ throw new VoiceError2("unavailable", isMicrosoftEdge(this.navigator) && this.environment.recognitionAcceptsAudioTrack === undefined ? "Microsoft Edge recognises only the default microphone, so a chosen microphone cannot be used here" : "this browser cannot recognise from a chosen microphone, only the default one");
211
245
  }
212
246
  if ("track" in microphone) {
213
247
  return { track: microphone.track, owned: [], stopTrack: microphone.stopOnEnd === true };
@@ -1742,7 +1776,9 @@ function bargeInOnSpeechStart(manager) {
1742
1776
  export {
1743
1777
  BrowserRecognitionProvider,
1744
1778
  DEFAULT_ENDPOINTING2 as DEFAULT_ENDPOINTING,
1779
+ DEFAULT_MODEL_INSTALL_TIMEOUT_MS,
1745
1780
  LOCAL_RECOGNITION_ID,
1781
+ MAX_TIMER_DELAY_MS,
1746
1782
  PHONON_EN_FAMILY,
1747
1783
  PHONON_PROVIDER_ID,
1748
1784
  PhononProvider,
@@ -1759,6 +1795,7 @@ export {
1759
1795
  clearPhononCache,
1760
1796
  defaultAudioContextFactory,
1761
1797
  defaultPhononRuntime,
1798
+ isMicrosoftEdge,
1762
1799
  matchLocale,
1763
1800
  parseLocale,
1764
1801
  recognitionConstructor
@@ -86,9 +86,17 @@ export interface MediaStreamLike {
86
86
  getAudioTracks(): MediaStreamTrackLike[];
87
87
  getTracks?(): MediaStreamTrackLike[];
88
88
  }
89
- /** The parts of `navigator` dictation reads: permissions, connectivity and microphones. */
89
+ /** The parts of `navigator` dictation reads: permissions, connectivity, microphones and the browser. */
90
90
  export interface RecognitionNavigatorLike {
91
91
  readonly onLine?: boolean;
92
+ /** Read only to recognise Microsoft Edge (see `isMicrosoftEdge`). */
93
+ readonly userAgent?: string;
94
+ /** User-Agent Client Hints (Chromium); preferred over `userAgent` where present. */
95
+ readonly userAgentData?: {
96
+ readonly brands?: readonly {
97
+ readonly brand: string;
98
+ }[];
99
+ };
92
100
  readonly permissions?: {
93
101
  query(descriptor: {
94
102
  name: string;
@@ -129,7 +137,9 @@ export interface SpeechRecognitionEnvironment {
129
137
  /**
130
138
  * Whether `start(audioTrack)` is honoured. Browsers that predate it ignore the argument and record
131
139
  * the default microphone, so a chosen device would be silently dropped. Default: detected as
132
- * Chrome's on-device recognizer (`processLocally` on the instance), which shipped after it.
140
+ * Chrome's on-device recognizer (`processLocally` on the instance), which shipped after it, and
141
+ * not Microsoft Edge: Edge exposes `processLocally` too but records the default microphone
142
+ * whatever track it is given (see `isMicrosoftEdge`).
133
143
  */
134
144
  readonly recognitionAcceptsAudioTrack?: boolean;
135
145
  }
@@ -150,6 +160,16 @@ export interface InstallModelOptions {
150
160
  readonly signal?: AbortSignal;
151
161
  /** How often `downloading` is polled. Default 500 ms. */
152
162
  readonly pollIntervalMs?: number;
163
+ /**
164
+ * How long to wait for the browser's install, in milliseconds. Default
165
+ * `DEFAULT_MODEL_INSTALL_TIMEOUT_MS` (10 minutes). Firefox 160 accepts `install()` and never
166
+ * settles it, so without a deadline a host that passes no `signal` would wait forever. At the
167
+ * deadline the install rejects with `assets_install_failed` and reports `failed`; as with a
168
+ * cancel, the browser may still finish in the background and nothing claims it installed.
169
+ * `Infinity` turns the deadline off, leaving only `signal`. A finite value above
170
+ * `MAX_TIMER_DELAY_MS` (2^31 - 1, the browser timer limit) is `bad_request`.
171
+ */
172
+ readonly timeoutMs?: number;
153
173
  /** A settings object; `privacy.offlineOnly` refuses the download whatever `allowDownload` says. */
154
174
  readonly settings?: {
155
175
  readonly privacy: {
@@ -157,6 +177,23 @@ export interface InstallModelOptions {
157
177
  };
158
178
  };
159
179
  }
180
+ /**
181
+ * The longest delay a browser timer honours (2^31 - 1 ms, about 24.8 days). A longer one
182
+ * overflows and fires almost at once, so `installModel` refuses it rather than fail early.
183
+ */
184
+ export declare const MAX_TIMER_DELAY_MS: number;
185
+ /** The default `installModel` deadline: long enough for a slow download, short of forever. */
186
+ export declare const DEFAULT_MODEL_INSTALL_TIMEOUT_MS: number;
187
+ /**
188
+ * Whether this is Microsoft Edge (Chromium Edge on desktop or Android, or a WebView2 host). Edge
189
+ * exposes Chrome's `processLocally` but its recognition records the default microphone and ignores
190
+ * a track passed to `start()` (Edge 158 on Windows 11, 2026-11-26), so the SDK must not take
191
+ * `processLocally` as proof that a chosen microphone is honoured there. Detected by a brand
192
+ * starting with "Microsoft Edge" in User-Agent Client Hints, else the `Edg/`, `EdgA/`, `EdgiOS/`
193
+ * or legacy `Edge/` token in the user agent string. A spoofed user agent only makes the SDK refuse
194
+ * a chosen microphone it could have used, never use the wrong one.
195
+ */
196
+ export declare function isMicrosoftEdge(navigator: Pick<RecognitionNavigatorLike, "userAgent" | "userAgentData"> | undefined): boolean;
160
197
  /** What dictation does when the page is hidden (`visibilitychange` to hidden, or `pagehide`). */
161
198
  export type HiddenPagePolicy = "finalize" | "cancel" | "ignore";
162
199
  /** Browser-specific session options on top of the shared contract. All optional. */
@@ -213,12 +250,26 @@ export declare class BrowserRecognitionProvider implements TranscriptionProvider
213
250
  * Installs the on-device model where the browser exposes an install path (#37 consent step).
214
251
  * Downloading is never implied: the host passes `allowDownload: true` only after the person
215
252
  * agreed to it (for example `settings.models.allowDownload`), otherwise this refuses. Resolves
216
- * with the browser's boolean; `onProgress` and `signal` are optional.
253
+ * with the browser's boolean; `onProgress` and `signal` are optional. Gives up after `timeoutMs`
254
+ * (default 10 minutes) with `assets_install_failed`, so it always settles.
255
+ *
256
+ * Call it from the person's click or key press, once per locale: a browser may require transient
257
+ * user activation for `install()` and spend it on that call (Firefox 160), so a second locale
258
+ * installed from the same click, or after an `await`, is refused. That refusal rejects with
259
+ * `denied` and `reason: "needs_user_gesture"`; ask for another click and call again.
217
260
  */
218
261
  installModel(locale: string, options: InstallModelOptions): Promise<boolean>;
219
262
  /** Reports `downloading` once the browser says so; the browser exposes no byte counts. */
220
263
  private pollInstall;
221
264
  createSession(options: WebTranscriptionSessionOptions): Promise<TranscriptionSession>;
265
+ /**
266
+ * Whether a session here can record from a chosen microphone (`microphone` in the session
267
+ * options). Lets a host hide its microphone picker instead of offering a choice the session
268
+ * would refuse. Prompts for nothing; `false` when the browser has no recognizer.
269
+ */
270
+ acceptsChosenMicrophone(): boolean;
271
+ /** `recognitionAcceptsAudioTrack`, else Chrome's on-device recognizer that is not Edge's. */
272
+ private honoursAudioTrack;
222
273
  private get navigator();
223
274
  private get window();
224
275
  /** Opens (or adopts) the chosen microphone. Nothing is opened when no device was chosen. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adea-ai/voice",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "The Adea Voice SDK: the shared speech provider contract, unified per-device voice settings, the desktop client for the pinned Apple/transcribe.cpp/audio.cpp helpers, and the browser providers.",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -57,8 +57,8 @@
57
57
  "phonon-tts": "0.7.1"
58
58
  },
59
59
  "devDependencies": {
60
- "bun-types": "1.4.4",
61
- "typescript": "5.9.3"
60
+ "bun-types": "1.4.5",
61
+ "typescript": "7.0.2"
62
62
  },
63
63
  "engines": {
64
64
  "bun": ">=1.2",
@@ -72,14 +72,26 @@ const DEFAULT_MESSAGES: Record<VoiceErrorCode, string> = {
72
72
  failed: "The speech engine reported an unexpected failure.",
73
73
  };
74
74
 
75
+ /**
76
+ * A finer cause inside a code, for a case a host handles differently from the rest of that code.
77
+ * Not a wire code: it travels only on a browser `VoiceError`, and the code stays the wire value.
78
+ *
79
+ * - `needs_user_gesture` (with `denied`): the browser refused because the call did not run inside
80
+ * a user gesture (Firefox 160: "install() requires transient user activation"). Call it again
81
+ * from the person's click or key press.
82
+ */
83
+ export type VoiceErrorReason = "needs_user_gesture";
84
+
75
85
  /** The typed failure every public browser operation reports. */
76
86
  export class VoiceError extends Error {
77
87
  readonly code: VoiceErrorCode;
88
+ readonly reason?: VoiceErrorReason;
78
89
 
79
- constructor(code: VoiceErrorCode, message: string = DEFAULT_MESSAGES[code]) {
90
+ constructor(code: VoiceErrorCode, message: string = DEFAULT_MESSAGES[code], options: { readonly reason?: VoiceErrorReason } = {}) {
80
91
  super(message);
81
92
  this.name = "VoiceError";
82
93
  this.code = code;
94
+ if (options.reason !== undefined) this.reason = options.reason;
83
95
  }
84
96
 
85
97
  /**
@@ -36,9 +36,11 @@
36
36
  * (`voice-helpers.json`) and `codesign --verify --strict`.
37
37
  */
38
38
  import { createHash } from "node:crypto";
39
- import { spawnSync } from "node:child_process";
39
+ import { spawnSync, type SpawnSyncReturns } from "node:child_process";
40
40
  import {
41
41
  chmodSync,
42
+ copyFileSync,
43
+ cpSync,
42
44
  existsSync,
43
45
  lstatSync,
44
46
  mkdirSync,
@@ -51,7 +53,7 @@ import {
51
53
  writeFileSync,
52
54
  type Stats,
53
55
  } from "node:fs";
54
- import { dirname, join, relative, resolve, sep } from "node:path";
56
+ import { basename, dirname, join, relative, resolve, sep } from "node:path";
55
57
  import { tmpdir } from "node:os";
56
58
  import { CONTRACT_MAJOR, WIRE_VERSION, parseWireLine } from "../contract/wire";
57
59
  import { isMachO, machoCodeDigest } from "./macho-digest";
@@ -207,9 +209,36 @@ export interface StageHelpersOptions {
207
209
  readonly fetch?: typeof fetch;
208
210
  /** Run `--version` on the staged executable (default: when the target matches this machine). */
209
211
  readonly handshake?: boolean;
212
+ /** How the `--version` handshake starts the helper (default: runs the executable directly). */
213
+ readonly launch?: HelperLauncher;
214
+ /** How `tar` runs (default: the `tar` on PATH). Every argument it gets is relative. */
215
+ readonly tar?: TarRunner;
216
+ /**
217
+ * How an unpacked entry moves into `outDir` (default `renameSync`). Unpacking happens inside
218
+ * `outDir`, so this never crosses a filesystem; tests pass one that fails with `EXDEV` across
219
+ * simulated volumes to prove it.
220
+ */
221
+ readonly rename?: (from: string, to: string) => void;
210
222
  readonly log?: (message: string) => void;
211
223
  }
212
224
 
225
+ /**
226
+ * Starts `executable` with `args` and waits for it, like `spawnSync`. The default runs the
227
+ * executable directly. A host whose helper needs a launcher (and the tests, whose stand-in helper is
228
+ * a script run by the JS runtime, which Windows cannot exec) passes its own.
229
+ */
230
+ export type HelperLauncher = (
231
+ executable: string,
232
+ args: readonly string[],
233
+ options: { readonly encoding: "utf8"; readonly timeout: number; readonly killSignal: "SIGKILL" },
234
+ ) => SpawnSyncReturns<string>;
235
+
236
+ /** Runs `tar` with `args` in `cwd`, like `spawnSync("tar", args, { cwd })`. */
237
+ export type TarRunner = (args: readonly string[], options: { readonly cwd: string; readonly encoding: "utf8" }) => SpawnSyncReturns<string>;
238
+
239
+ const directLauncher: HelperLauncher = (executable, args, options) => spawnSync(executable, [...args], options);
240
+ const pathTar: TarRunner = (args, options) => spawnSync("tar", [...args], options);
241
+
213
242
  /**
214
243
  * Downloads, verifies and unpacks the pinned helpers into `outDir`, then records what was staged.
215
244
  * Reuses an already staged helper whose digests match. Throws `HelperLockError` on any mismatch;
@@ -223,11 +252,14 @@ export async function stageVoiceHelpers(options: StageHelpersOptions): Promise<S
223
252
  const helpers: Record<string, StagedHelperEntry> = {};
224
253
  const version = options.localDir ? `local+${options.lock.version}` : options.lock.version;
225
254
  mkdirSync(outDir, { recursive: true });
255
+ // The helpers share one `Frameworks/` tree: a local stage copies it once, not once per helper.
256
+ let localFrameworksCopied = false;
226
257
  try {
227
258
  for (const helper of options.helpers) {
228
259
  const executable = join(outDir, helper);
229
260
  if (options.localDir) {
230
- stageLocal(options.localDir, helper, outDir);
261
+ stageLocal(options.localDir, helper, outDir, !localFrameworksCopied);
262
+ localFrameworksCopied = true;
231
263
  helpers[helper] = { sha256: "local", executableSha256: sha256File(executable), ...codeDigestEntry(executable) };
232
264
  } else {
233
265
  const pin = helperPin(options.lock, helper, options.target);
@@ -242,7 +274,7 @@ export async function stageVoiceHelpers(options: StageHelpersOptions): Promise<S
242
274
  } else {
243
275
  const archive = await obtainArchive(options, helper, pin, log);
244
276
  try {
245
- extractArchive(archive, outDir, helper);
277
+ extractArchive(archive, pin.sha256, outDir, helper, options.tar ?? pathTar, options.rename ?? renameSync);
246
278
  } finally {
247
279
  // An uncached download lives in its own scratch directory; do not leak it.
248
280
  if (!options.cacheDir) rmSync(dirname(archive), { recursive: true, force: true });
@@ -260,7 +292,7 @@ export async function stageVoiceHelpers(options: StageHelpersOptions): Promise<S
260
292
  }
261
293
  helpers[helper] = { sha256: pin.sha256, executableSha256: pin.executableSha256, ...code };
262
294
  }
263
- if (handshake) assertHandshake(executable, options.localDir ? {} : { release: options.lock.version });
295
+ if (handshake) assertHandshake(executable, options.localDir ? { launch: options.launch } : { release: options.lock.version, launch: options.launch });
264
296
  }
265
297
  } catch (error) {
266
298
  rmSync(outDir, { recursive: true, force: true });
@@ -289,6 +321,8 @@ export interface VerifyStagedOptions {
289
321
  readonly handshake?: boolean;
290
322
  /** How long one `--version` may take. Default 10 s. */
291
323
  readonly handshakeTimeoutMs?: number;
324
+ /** How the handshake starts each helper (default: runs the executable directly). */
325
+ readonly launch?: HelperLauncher;
292
326
  /**
293
327
  * Run `codesign --verify --strict` on a helper that was signed again after staging (default: on
294
328
  * macOS for a macOS target).
@@ -344,7 +378,7 @@ export function verifyStagedVoiceHelpers(options: VerifyStagedOptions): void {
344
378
  verifySupportFiles(dir, record);
345
379
  if (options.handshake ?? options.target === currentHelperTarget()) {
346
380
  for (const helper of options.helpers) {
347
- assertHandshake(join(dir, helper), { release: options.lock.version, timeoutMs: options.handshakeTimeoutMs });
381
+ assertHandshake(join(dir, helper), { release: options.lock.version, timeoutMs: options.handshakeTimeoutMs, launch: options.launch });
348
382
  }
349
383
  }
350
384
  }
@@ -364,6 +398,8 @@ export interface HandshakeExpectations {
364
398
  readonly release?: string;
365
399
  /** How long `--version` may take before the helper counts as hung. Default 10 s. */
366
400
  readonly timeoutMs?: number;
401
+ /** How the helper is started (default: runs the executable directly). */
402
+ readonly launch?: HelperLauncher;
367
403
  }
368
404
 
369
405
  /**
@@ -372,7 +408,7 @@ export interface HandshakeExpectations {
372
408
  */
373
409
  export function assertHandshake(executable: string, expect: HandshakeExpectations = {}): void {
374
410
  const timeoutMs = expect.timeoutMs ?? 10_000;
375
- const run = spawnSync(executable, ["--version"], { encoding: "utf8", timeout: timeoutMs, killSignal: "SIGKILL" });
411
+ const run = (expect.launch ?? directLauncher)(executable, ["--version"], { encoding: "utf8", timeout: timeoutMs, killSignal: "SIGKILL" });
376
412
  if (run.error || run.status !== 0) {
377
413
  const reason = run.error
378
414
  ? (run.error as NodeJS.ErrnoException).code === "ETIMEDOUT"
@@ -413,10 +449,15 @@ function assertSigned(path: string): void {
413
449
  }
414
450
  }
415
451
 
452
+ /** Prefix of the private directory an archive is unpacked in, inside `outDir`. */
453
+ const EXTRACT_PREFIX = ".adea-voice-extract-";
454
+
416
455
  /** Relative paths of every entry under `dir` (depth first), as `[path, lstat]`. */
417
456
  function walk(dir: string, root = dir): [string, Stats][] {
418
457
  const entries: [string, Stats][] = [];
419
458
  for (const name of readdirSync(dir).sort()) {
459
+ // An unpack directory left by a killed staging is not part of the staged tree.
460
+ if (dir === root && name.startsWith(EXTRACT_PREFIX)) continue;
420
461
  const path = join(dir, name);
421
462
  const stat = lstatSync(path);
422
463
  entries.push([relative(root, path).split(sep).join("/"), stat]);
@@ -508,37 +549,75 @@ async function obtainArchive(
508
549
  return target;
509
550
  }
510
551
 
511
- /** Unpacks into a scratch directory, then moves only the expected entries into `outDir`. */
512
- function extractArchive(archive: string, outDir: string, helper: HelperName): void {
513
- const scratch = mkdtempSync(join(tmpdir(), "adea-voice-extract-"));
552
+ /**
553
+ * Unpacks into a private directory inside `outDir`, then moves only the expected entries into
554
+ * `outDir`. Everything happens on the output's filesystem: the archive (which may sit in a cache on
555
+ * another volume) is first copied in and its sha256 checked again, so the moves are plain renames
556
+ * that cannot fail with `EXDEV`, and symlinks in `Frameworks/` move as symlinks.
557
+ *
558
+ * Every path `tar` gets is relative, so none holds a drive letter: GNU tar (the one Git for
559
+ * Windows puts first on PATH) reads `C:\...` as a remote `host:path`, in `-f` and in `-C` alike.
560
+ * tar runs in `<private>/unpacked` and names the copy `../<file>` (forward slash, which every
561
+ * Windows tar accepts), so no `-C` is needed. bsdtar (macOS, Windows' own `tar.exe`) reads the same
562
+ * arguments the same way. The file name is `<sha256>.tar.gz` or a pinned `.tar.gz` name, which holds
563
+ * no colon.
564
+ */
565
+ function extractArchive(
566
+ archive: string,
567
+ sha256: string,
568
+ outDir: string,
569
+ helper: HelperName,
570
+ tar: TarRunner,
571
+ move: (from: string, to: string) => void,
572
+ ): void {
573
+ const work = mkdtempSync(join(outDir, EXTRACT_PREFIX));
514
574
  try {
515
- const listing = spawnSync("tar", ["-tzf", archive], { encoding: "utf8" });
516
- if (listing.status !== 0) throw new HelperLockError(`${helper}: cannot read ${archive}`);
517
- for (const entry of listing.stdout.split("\n").filter(Boolean)) {
518
- // No absolute paths, no parent traversal: the archive is pinned, but stay defensive.
519
- if (entry.startsWith("/") || entry.split("/").includes("..")) throw new HelperLockError(`${helper}: unsafe archive entry ${entry}`);
575
+ const name = basename(archive);
576
+ const copy = join(work, name);
577
+ copyFileSync(archive, copy);
578
+ const copied = sha256File(copy);
579
+ if (copied !== sha256) throw new HelperLockError(`${helper}: ${archive} changed while it was copied (sha256 ${copied}, pinned ${sha256})`);
580
+ const scratch = join(work, "unpacked");
581
+ mkdirSync(scratch);
582
+ const named = `../${name}`;
583
+ const listing = tar(["-tzf", named], { cwd: scratch, encoding: "utf8" });
584
+ if (listing.status !== 0) throw new HelperLockError(`${helper}: cannot read ${archive}: ${listing.stderr ?? ""}`.trim());
585
+ for (const entry of listing.stdout.split(/\r?\n/).filter(Boolean)) {
586
+ // No absolute paths (POSIX or Windows), no parent traversal: the archive is pinned, but stay defensive.
587
+ const parts = entry.split(/[\\/]/);
588
+ if (entry.startsWith("/") || entry.startsWith("\\") || /^[A-Za-z]:/.test(entry) || parts.includes("..")) {
589
+ throw new HelperLockError(`${helper}: unsafe archive entry ${entry}`);
590
+ }
520
591
  }
521
- const unpack = spawnSync("tar", ["-xzf", archive, "-C", scratch], { encoding: "utf8" });
592
+ const unpack = tar(["-xzf", named], { cwd: scratch, encoding: "utf8" });
522
593
  if (unpack.status !== 0) throw new HelperLockError(`${helper}: cannot unpack ${archive}: ${unpack.stderr}`);
523
594
  const executable = join(scratch, helper);
524
595
  if (!existsSync(executable) || !statSync(executable).isFile()) throw new HelperLockError(`${helper}: the archive holds no ${helper}`);
525
596
  rmSync(join(outDir, helper), { force: true });
526
- renameSync(executable, join(outDir, helper));
597
+ move(executable, join(outDir, helper));
527
598
  const frameworks = join(scratch, "Frameworks");
528
599
  if (existsSync(frameworks)) {
529
600
  const destination = join(outDir, "Frameworks");
530
601
  mkdirSync(destination, { recursive: true });
531
- for (const entry of spawnSync("ls", ["-1", frameworks], { encoding: "utf8" }).stdout.split("\n").filter(Boolean)) {
602
+ // `readdirSync`, not `ls -1` (absent on Windows). Like `ls -1`, it moves no dot entries.
603
+ for (const entry of readdirSync(frameworks).filter((name) => !name.startsWith(".")).sort()) {
532
604
  rmSync(join(destination, entry), { recursive: true, force: true });
533
- renameSync(join(frameworks, entry), join(destination, entry));
605
+ move(join(frameworks, entry), join(destination, entry));
534
606
  }
535
607
  }
536
608
  } finally {
537
- rmSync(scratch, { recursive: true, force: true });
609
+ rmSync(work, { recursive: true, force: true });
538
610
  }
539
611
  }
540
612
 
541
- function stageLocal(localDir: string, helper: HelperName, outDir: string): void {
613
+ /**
614
+ * Copies a locally built helper into `outDir`, and with `withFrameworks` its `Frameworks/` (once
615
+ * per stage: the helpers share the tree). Each top-level entry of `Frameworks/` replaces the staged
616
+ * one, as an unpacked archive's do; other staged entries stay. `cpSync`, not `cp -R` (absent on
617
+ * Windows), copies a symlink as a symlink with its target unchanged. Copying onto an existing
618
+ * symlink is never attempted: Node 24 throws `EEXIST` there.
619
+ */
620
+ function stageLocal(localDir: string, helper: HelperName, outDir: string, withFrameworks: boolean): void {
542
621
  const source = join(resolve(localDir), helper);
543
622
  if (!existsSync(source)) throw new HelperLockError(`${helper} is not in the local helper directory ${localDir}`);
544
623
  const destination = join(outDir, helper);
@@ -546,5 +625,11 @@ function stageLocal(localDir: string, helper: HelperName, outDir: string): void
546
625
  writeFileSync(destination, readFileSync(source));
547
626
  chmodSync(destination, 0o755);
548
627
  const frameworks = join(resolve(localDir), "Frameworks");
549
- if (existsSync(frameworks)) spawnSync("cp", ["-R", frameworks, outDir]);
628
+ if (!withFrameworks || !existsSync(frameworks)) return;
629
+ const staged = join(outDir, "Frameworks");
630
+ mkdirSync(staged, { recursive: true });
631
+ for (const entry of readdirSync(frameworks).sort()) {
632
+ rmSync(join(staged, entry), { recursive: true, force: true });
633
+ cpSync(join(frameworks, entry), join(staged, entry), { recursive: true, verbatimSymlinks: true });
634
+ }
550
635
  }
@@ -105,9 +105,13 @@ export interface MediaStreamLike {
105
105
  getTracks?(): MediaStreamTrackLike[];
106
106
  }
107
107
 
108
- /** The parts of `navigator` dictation reads: permissions, connectivity and microphones. */
108
+ /** The parts of `navigator` dictation reads: permissions, connectivity, microphones and the browser. */
109
109
  export interface RecognitionNavigatorLike {
110
110
  readonly onLine?: boolean;
111
+ /** Read only to recognise Microsoft Edge (see `isMicrosoftEdge`). */
112
+ readonly userAgent?: string;
113
+ /** User-Agent Client Hints (Chromium); preferred over `userAgent` where present. */
114
+ readonly userAgentData?: { readonly brands?: readonly { readonly brand: string }[] };
111
115
  readonly permissions?: { query(descriptor: { name: string }): Promise<PermissionStatusLike> };
112
116
  readonly mediaDevices?: {
113
117
  getUserMedia(constraints: { audio: boolean | { deviceId: { exact: string } } }): Promise<MediaStreamLike>;
@@ -141,7 +145,9 @@ export interface SpeechRecognitionEnvironment {
141
145
  /**
142
146
  * Whether `start(audioTrack)` is honoured. Browsers that predate it ignore the argument and record
143
147
  * 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.
148
+ * Chrome's on-device recognizer (`processLocally` on the instance), which shipped after it, and
149
+ * not Microsoft Edge: Edge exposes `processLocally` too but records the default microphone
150
+ * whatever track it is given (see `isMicrosoftEdge`).
145
151
  */
146
152
  readonly recognitionAcceptsAudioTrack?: boolean;
147
153
  }
@@ -164,10 +170,58 @@ export interface InstallModelOptions {
164
170
  readonly signal?: AbortSignal;
165
171
  /** How often `downloading` is polled. Default 500 ms. */
166
172
  readonly pollIntervalMs?: number;
173
+ /**
174
+ * How long to wait for the browser's install, in milliseconds. Default
175
+ * `DEFAULT_MODEL_INSTALL_TIMEOUT_MS` (10 minutes). Firefox 160 accepts `install()` and never
176
+ * settles it, so without a deadline a host that passes no `signal` would wait forever. At the
177
+ * deadline the install rejects with `assets_install_failed` and reports `failed`; as with a
178
+ * cancel, the browser may still finish in the background and nothing claims it installed.
179
+ * `Infinity` turns the deadline off, leaving only `signal`. A finite value above
180
+ * `MAX_TIMER_DELAY_MS` (2^31 - 1, the browser timer limit) is `bad_request`.
181
+ */
182
+ readonly timeoutMs?: number;
167
183
  /** A settings object; `privacy.offlineOnly` refuses the download whatever `allowDownload` says. */
168
184
  readonly settings?: { readonly privacy: { readonly offlineOnly: boolean } };
169
185
  }
170
186
 
187
+ /**
188
+ * Whether the browser refused `install()` for want of a user gesture (transient user activation).
189
+ * Firefox 160 throws "install() requires transient user activation"; other engines name the same
190
+ * rule "user activation" or "user gesture". Matched on the message, since the error's name
191
+ * (`NotAllowedError`, `InvalidStateError`) is shared with unrelated refusals.
192
+ */
193
+ function needsUserGesture(error: unknown): boolean {
194
+ const message = error !== null && typeof error === "object" ? (error as { message?: unknown }).message : undefined;
195
+ return typeof message === "string" && /\buser (?:activation|gesture)\b/i.test(message);
196
+ }
197
+
198
+ /**
199
+ * The longest delay a browser timer honours (2^31 - 1 ms, about 24.8 days). A longer one
200
+ * overflows and fires almost at once, so `installModel` refuses it rather than fail early.
201
+ */
202
+ export const MAX_TIMER_DELAY_MS = 2 ** 31 - 1;
203
+
204
+ /** The default `installModel` deadline: long enough for a slow download, short of forever. */
205
+ export const DEFAULT_MODEL_INSTALL_TIMEOUT_MS = 10 * 60 * 1000;
206
+
207
+ /**
208
+ * Whether this is Microsoft Edge (Chromium Edge on desktop or Android, or a WebView2 host). Edge
209
+ * exposes Chrome's `processLocally` but its recognition records the default microphone and ignores
210
+ * a track passed to `start()` (Edge 158 on Windows 11, 2026-11-26), so the SDK must not take
211
+ * `processLocally` as proof that a chosen microphone is honoured there. Detected by a brand
212
+ * starting with "Microsoft Edge" in User-Agent Client Hints, else the `Edg/`, `EdgA/`, `EdgiOS/`
213
+ * or legacy `Edge/` token in the user agent string. A spoofed user agent only makes the SDK refuse
214
+ * a chosen microphone it could have used, never use the wrong one.
215
+ */
216
+ export function isMicrosoftEdge(navigator: Pick<RecognitionNavigatorLike, "userAgent" | "userAgentData"> | undefined): boolean {
217
+ const brands = navigator?.userAgentData?.brands;
218
+ if (Array.isArray(brands) && brands.some((entry) => typeof entry?.brand === "string" && entry.brand.startsWith("Microsoft Edge"))) {
219
+ return true;
220
+ }
221
+ const agent = navigator?.userAgent;
222
+ return typeof agent === "string" && /\bEdg(?:e|A|iOS)?\//.test(agent);
223
+ }
224
+
171
225
  /** What dictation does when the page is hidden (`visibilitychange` to hidden, or `pagehide`). */
172
226
  export type HiddenPagePolicy = "finalize" | "cancel" | "ignore";
173
227
 
@@ -311,7 +365,13 @@ export class BrowserRecognitionProvider implements TranscriptionProvider {
311
365
  * Installs the on-device model where the browser exposes an install path (#37 consent step).
312
366
  * Downloading is never implied: the host passes `allowDownload: true` only after the person
313
367
  * agreed to it (for example `settings.models.allowDownload`), otherwise this refuses. Resolves
314
- * with the browser's boolean; `onProgress` and `signal` are optional.
368
+ * with the browser's boolean; `onProgress` and `signal` are optional. Gives up after `timeoutMs`
369
+ * (default 10 minutes) with `assets_install_failed`, so it always settles.
370
+ *
371
+ * Call it from the person's click or key press, once per locale: a browser may require transient
372
+ * user activation for `install()` and spend it on that call (Firefox 160), so a second locale
373
+ * installed from the same click, or after an `await`, is refused. That refusal rejects with
374
+ * `denied` and `reason: "needs_user_gesture"`; ask for another click and call again.
315
375
  */
316
376
  async installModel(locale: string, options: InstallModelOptions): Promise<boolean> {
317
377
  if (options?.allowDownload !== true) {
@@ -325,6 +385,13 @@ export class BrowserRecognitionProvider implements TranscriptionProvider {
325
385
  if (constructor === undefined || install === undefined) {
326
386
  throw new VoiceError("assets_missing", "this browser has no on-device recognition install path");
327
387
  }
388
+ const timeoutMs = options.timeoutMs ?? DEFAULT_MODEL_INSTALL_TIMEOUT_MS;
389
+ if (typeof timeoutMs !== "number" || Number.isNaN(timeoutMs) || timeoutMs <= 0 || (Number.isFinite(timeoutMs) && timeoutMs > MAX_TIMER_DELAY_MS)) {
390
+ throw new VoiceError(
391
+ "bad_request",
392
+ `installModel timeoutMs must be a positive number of milliseconds up to ${MAX_TIMER_DELAY_MS} (about 24.8 days), or Infinity for no deadline`,
393
+ );
394
+ }
328
395
  const signal = options.signal;
329
396
  if (signal?.aborted) throw new VoiceError("cancelled", "the model install was cancelled before it started");
330
397
  const report = (phase: ModelInstallProgress["phase"]) => {
@@ -338,21 +405,41 @@ export class BrowserRecognitionProvider implements TranscriptionProvider {
338
405
 
339
406
  let settled = false;
340
407
  let onAbort: (() => void) | undefined;
341
- const aborted = new Promise<never>((_, reject) => {
408
+ let deadline: ReturnType<typeof setTimeout> | undefined;
409
+ const stopped = new Promise<never>((_, reject) => {
342
410
  onAbort = () => reject(new VoiceError("cancelled", "the model install was cancelled; the browser may finish it in the background"));
343
411
  signal?.addEventListener("abort", onAbort, { once: true });
412
+ if (Number.isFinite(timeoutMs)) {
413
+ deadline = setTimeout(
414
+ () =>
415
+ reject(
416
+ new VoiceError(
417
+ "assets_install_failed",
418
+ `the ${locale} recognition model did not install within ${Math.round(timeoutMs / 1000)} s; the browser may still finish it in the background`,
419
+ ),
420
+ ),
421
+ timeoutMs,
422
+ );
423
+ }
344
424
  });
345
425
  void this.pollInstall(constructor, locale, options.pollIntervalMs ?? 500, () => settled, () => report("downloading"));
346
426
  try {
347
- const installed = await Promise.race([Promise.resolve(install.call(constructor, { langs: [locale] })), aborted]);
427
+ const installed = await Promise.race([Promise.resolve(install.call(constructor, { langs: [locale] })), stopped]);
348
428
  report(installed ? "installed" : "failed");
349
429
  return installed;
350
430
  } catch (error) {
351
- const wrapped = VoiceError.wrapping(error);
431
+ const wrapped = needsUserGesture(error)
432
+ ? new VoiceError(
433
+ "denied",
434
+ `the browser installs the ${locale} recognition model only from a user gesture; call installModel again from the person's click or key press`,
435
+ { reason: "needs_user_gesture" },
436
+ )
437
+ : VoiceError.wrapping(error);
352
438
  report(wrapped.code === "cancelled" ? "cancelled" : "failed");
353
439
  throw error instanceof VoiceError ? error : wrapped;
354
440
  } finally {
355
441
  settled = true;
442
+ if (deadline !== undefined) clearTimeout(deadline);
356
443
  if (onAbort) signal?.removeEventListener("abort", onAbort);
357
444
  }
358
445
  }
@@ -432,6 +519,23 @@ export class BrowserRecognitionProvider implements TranscriptionProvider {
432
519
  });
433
520
  }
434
521
 
522
+ /**
523
+ * Whether a session here can record from a chosen microphone (`microphone` in the session
524
+ * options). Lets a host hide its microphone picker instead of offering a choice the session
525
+ * would refuse. Prompts for nothing; `false` when the browser has no recognizer.
526
+ */
527
+ acceptsChosenMicrophone(): boolean {
528
+ if (this.environment.recognitionAcceptsAudioTrack !== undefined) return this.environment.recognitionAcceptsAudioTrack;
529
+ const constructor = recognitionConstructor(this.environment);
530
+ if (constructor === undefined) return false;
531
+ return this.honoursAudioTrack(new constructor());
532
+ }
533
+
534
+ /** `recognitionAcceptsAudioTrack`, else Chrome's on-device recognizer that is not Edge's. */
535
+ private honoursAudioTrack(recognition: SpeechRecognitionLike): boolean {
536
+ return this.environment.recognitionAcceptsAudioTrack ?? ("processLocally" in recognition && !isMicrosoftEdge(this.navigator));
537
+ }
538
+
435
539
  private get navigator(): RecognitionNavigatorLike | undefined {
436
540
  return this.environment.navigator;
437
541
  }
@@ -453,9 +557,13 @@ export class BrowserRecognitionProvider implements TranscriptionProvider {
453
557
  ): Promise<SessionAudio | undefined> {
454
558
  const microphone = options.microphone;
455
559
  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");
560
+ if (!this.honoursAudioTrack(recognition)) {
561
+ throw new VoiceError(
562
+ "unavailable",
563
+ isMicrosoftEdge(this.navigator) && this.environment.recognitionAcceptsAudioTrack === undefined
564
+ ? "Microsoft Edge recognises only the default microphone, so a chosen microphone cannot be used here"
565
+ : "this browser cannot recognise from a chosen microphone, only the default one",
566
+ );
459
567
  }
460
568
  if ("track" in microphone) {
461
569
  return { track: microphone.track, owned: [], stopTrack: microphone.stopOnEnd === true };