@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,1454 @@
1
+ import {
2
+ routingPolicyFor2
3
+ } from "../index-a7d617zr.js";
4
+ import {
5
+ VOICE_CONTRACT2,
6
+ AVAILABLE2,
7
+ unavailable2,
8
+ route2
9
+ } from "../index-ght8wwpd.js";
10
+ import {
11
+ isMachO2,
12
+ machoCodeDigest2,
13
+ machoCodeDigestFile2,
14
+ HELPER_LOCK_SCHEMA2,
15
+ HELPER_NAMES2,
16
+ HELPER_TARGETS2,
17
+ MAX_HELPER_ARCHIVE_BYTES2,
18
+ STAGED_RECORD_FILE2,
19
+ HelperLockError2,
20
+ validateHelperLock2,
21
+ readHelperLock2,
22
+ helperPin2,
23
+ helperArtifactUrl2,
24
+ currentHelperTarget2,
25
+ sha256File2,
26
+ stageVoiceHelpers2,
27
+ verifyStagedVoiceHelpers2,
28
+ readStagedRecord2,
29
+ assertHandshake2
30
+ } from "../index-m4g2tpeq.js";
31
+ import {
32
+ TURN_WIRE_MINOR2,
33
+ RELEASE_ASSETS_WIRE_MINOR2,
34
+ MAX_WIRE_LINE_BYTES2,
35
+ isTurnTerminal2,
36
+ parseWireLine2,
37
+ encodeWireCommand2,
38
+ correlationId2,
39
+ isCompatibleHandshake2
40
+ } from "../index-7n7epq1a.js";
41
+ import {
42
+ VoiceError2
43
+ } from "../index-tvz9s9nz.js";
44
+
45
+ // src/desktop/helper-process.ts
46
+ import { spawn as spawnProcess } from "node:child_process";
47
+ class IncompatibleHelperError extends VoiceError2 {
48
+ constructor(message) {
49
+ super("unavailable", message);
50
+ this.name = "IncompatibleHelperError";
51
+ }
52
+ }
53
+
54
+ class LineSplitter {
55
+ limit;
56
+ buffer = "";
57
+ discarding = false;
58
+ constructor(limit = MAX_WIRE_LINE_BYTES2) {
59
+ this.limit = limit;
60
+ }
61
+ push(chunk) {
62
+ const lines = [];
63
+ let rest = chunk;
64
+ while (rest.length > 0) {
65
+ const newline = rest.indexOf(`
66
+ `);
67
+ if (newline === -1) {
68
+ if (!this.discarding) {
69
+ if (this.buffer.length + rest.length > this.limit) {
70
+ this.buffer = "";
71
+ this.discarding = true;
72
+ } else {
73
+ this.buffer += rest;
74
+ }
75
+ }
76
+ break;
77
+ }
78
+ const piece = rest.slice(0, newline);
79
+ rest = rest.slice(newline + 1);
80
+ if (this.discarding) {
81
+ this.discarding = false;
82
+ this.buffer = "";
83
+ continue;
84
+ }
85
+ const line = (this.buffer + piece).replace(/\r$/, "");
86
+ this.buffer = "";
87
+ if (line.length <= this.limit && line.length > 0)
88
+ lines.push(line);
89
+ }
90
+ return lines;
91
+ }
92
+ }
93
+ var requestCounter = 0;
94
+ function nextRequestId(prefix = "r") {
95
+ requestCounter = (requestCounter + 1) % Number.MAX_SAFE_INTEGER;
96
+ return `${prefix}${requestCounter.toString(36)}`;
97
+ }
98
+
99
+ class HelperConnection {
100
+ options;
101
+ child;
102
+ starting;
103
+ handshake;
104
+ pending = new Map;
105
+ broadcast = new Set;
106
+ crashes = [];
107
+ disposed = false;
108
+ incompatible;
109
+ constructor(options) {
110
+ this.options = options;
111
+ }
112
+ get label() {
113
+ return this.options.name ?? "the voice helper";
114
+ }
115
+ get version() {
116
+ return this.handshake;
117
+ }
118
+ onEvent(listener) {
119
+ this.broadcast.add(listener);
120
+ return () => this.broadcast.delete(listener);
121
+ }
122
+ async request(command, isDone, options = {}) {
123
+ const id = command.id ?? nextRequestId();
124
+ const child = await this.ensureStarted();
125
+ return await new Promise((resolve, reject) => {
126
+ let timer;
127
+ const finish = (outcome) => {
128
+ if (!this.pending.has(id))
129
+ return;
130
+ this.pending.delete(id);
131
+ if (timer)
132
+ clearTimeout(timer);
133
+ options.signal?.removeEventListener("abort", onAbort);
134
+ outcome();
135
+ };
136
+ const onAbort = () => finish(() => reject(new VoiceError2("cancelled", "request aborted")));
137
+ if (options.signal?.aborted)
138
+ return reject(new VoiceError2("cancelled", "request aborted"));
139
+ options.signal?.addEventListener("abort", onAbort, { once: true });
140
+ this.pending.set(id, {
141
+ fail: (error) => finish(() => reject(error)),
142
+ listener: (event) => {
143
+ options.onEvent?.(event);
144
+ if (isDone(event))
145
+ return finish(() => resolve(event));
146
+ if (event.event === "error") {
147
+ return finish(() => reject(new VoiceError2(event.code, event.message ?? `helper refused ${command.cmd}`)));
148
+ }
149
+ }
150
+ });
151
+ const timeoutMs = options.timeoutMs === undefined ? this.options.requestTimeoutMs ?? 15000 : options.timeoutMs;
152
+ if (timeoutMs !== null) {
153
+ timer = setTimeout(() => finish(() => reject(new VoiceError2("failed", `${command.cmd} timed out after ${timeoutMs} ms`))), timeoutMs);
154
+ }
155
+ try {
156
+ child.write(`${encodeWireCommand2({ ...command, id })}
157
+ `);
158
+ } catch (error) {
159
+ finish(() => reject(new VoiceError2("failed", `could not reach the helper: ${String(error)}`)));
160
+ }
161
+ });
162
+ }
163
+ async send(command) {
164
+ const child = await this.ensureStarted();
165
+ try {
166
+ child.write(`${encodeWireCommand2(command)}
167
+ `);
168
+ } catch (error) {
169
+ throw new VoiceError2("failed", `could not reach the helper: ${String(error)}`);
170
+ }
171
+ }
172
+ get running() {
173
+ return this.child !== undefined;
174
+ }
175
+ async stop() {
176
+ const child = this.child ?? await this.starting?.catch(() => {
177
+ return;
178
+ });
179
+ this.child = undefined;
180
+ this.starting = undefined;
181
+ if (!child)
182
+ return;
183
+ this.failAll(new VoiceError2("cancelled", `${this.label} was stopped`));
184
+ await new Promise((resolve) => {
185
+ let exited = false;
186
+ child.onExit(() => {
187
+ exited = true;
188
+ resolve();
189
+ });
190
+ try {
191
+ child.write(`${encodeWireCommand2({ cmd: "quit" })}
192
+ `);
193
+ child.closeInput();
194
+ } catch {}
195
+ const grace = this.options.exitGraceMs ?? 2000;
196
+ setTimeout(() => {
197
+ if (exited)
198
+ return;
199
+ child.kill("SIGTERM");
200
+ setTimeout(() => {
201
+ if (!exited)
202
+ child.kill("SIGKILL");
203
+ resolve();
204
+ }, grace).unref?.();
205
+ }, grace).unref?.();
206
+ });
207
+ }
208
+ async dispose() {
209
+ this.disposed = true;
210
+ await this.stop();
211
+ this.failAll(new VoiceError2("cancelled", `${this.label} was shut down`));
212
+ }
213
+ async ensureStarted() {
214
+ if (this.disposed)
215
+ throw new VoiceError2("unavailable", `${this.label} was shut down`);
216
+ if (this.incompatible)
217
+ throw this.incompatible;
218
+ if (this.child)
219
+ return this.child;
220
+ if (!this.starting) {
221
+ this.starting = this.start().finally(() => {
222
+ this.starting = undefined;
223
+ });
224
+ }
225
+ return await this.starting;
226
+ }
227
+ async start() {
228
+ const now = this.options.now ?? Date.now;
229
+ const window = this.options.crashWindowMs ?? 60000;
230
+ this.crashes = this.crashes.filter((at) => now() - at < window);
231
+ if (this.crashes.length >= (this.options.maxCrashes ?? 3)) {
232
+ throw new VoiceError2("unavailable", `${this.label} keeps crashing; restart the app to try again`);
233
+ }
234
+ let version;
235
+ try {
236
+ version = await this.versionHandshake();
237
+ } catch (error) {
238
+ this.crashes.push(now());
239
+ throw error;
240
+ }
241
+ if (!isCompatibleHandshake2(version)) {
242
+ this.incompatible = new IncompatibleHelperError(`${this.options.name ?? "voice helper"} speaks wire ${version.wire} / contract ${version.contract}; this app needs wire 1 / contract 1`);
243
+ throw this.incompatible;
244
+ }
245
+ this.handshake = version;
246
+ const child = this.options.spawn(this.options.path, ["--serve"], { env: this.options.env });
247
+ const splitter = new LineSplitter;
248
+ child.onStdout((chunk) => {
249
+ for (const line of splitter.push(chunk))
250
+ this.dispatch(line);
251
+ });
252
+ child.onStderr?.((chunk) => this.options.log?.(`${this.options.name ?? "voice helper"}: ${chunk.trimEnd().slice(0, 500)}`));
253
+ child.onExit((code, signal) => {
254
+ if (this.child !== child)
255
+ return;
256
+ this.child = undefined;
257
+ if (!this.disposed)
258
+ this.crashes.push(now());
259
+ this.failAll(new VoiceError2("failed", `${this.label} exited (${signal ?? `code ${String(code)}`}); it restarts on the next request`));
260
+ });
261
+ this.child = child;
262
+ return child;
263
+ }
264
+ async versionHandshake() {
265
+ const child = this.options.spawn(this.options.path, ["--version"], { env: this.options.env });
266
+ const splitter = new LineSplitter;
267
+ return await new Promise((resolve, reject) => {
268
+ let settled = false;
269
+ const settle = (outcome) => {
270
+ if (settled)
271
+ return;
272
+ settled = true;
273
+ clearTimeout(timer);
274
+ outcome();
275
+ };
276
+ const timer = setTimeout(() => {
277
+ settle(() => reject(new VoiceError2("unavailable", `${this.label} did not answer its version handshake`)));
278
+ child.kill("SIGKILL");
279
+ }, this.options.handshakeTimeoutMs ?? 5000);
280
+ child.onStdout((chunk) => {
281
+ for (const line of splitter.push(chunk)) {
282
+ const event = parseWireLine2(line);
283
+ if (event?.event === "version")
284
+ settle(() => resolve(event));
285
+ }
286
+ });
287
+ child.onExit((code) => {
288
+ settle(() => reject(new VoiceError2("unavailable", `${this.label} failed to start (exit ${String(code)})`)));
289
+ });
290
+ try {
291
+ child.closeInput();
292
+ } catch {}
293
+ });
294
+ }
295
+ dispatch(line) {
296
+ const event = parseWireLine2(line);
297
+ if (!event) {
298
+ this.options.log?.(`${this.options.name ?? "voice helper"}: ignored a malformed line (${line.slice(0, 80)})`);
299
+ return;
300
+ }
301
+ const id = correlationId2(event);
302
+ if (id !== undefined)
303
+ this.pending.get(id)?.listener(event);
304
+ for (const listener of this.broadcast)
305
+ listener(event);
306
+ }
307
+ failAll(error) {
308
+ const pending = [...this.pending.values()];
309
+ for (const entry of pending)
310
+ entry.fail(error);
311
+ }
312
+ }
313
+ var nodeSpawner = (path, args, options) => {
314
+ {
315
+ const spawn = spawnProcess;
316
+ const env = {};
317
+ for (const [key, value] of Object.entries({ ...process.env, ...options.env })) {
318
+ if (value !== undefined)
319
+ env[key] = value;
320
+ }
321
+ const child = spawn(path, [...args], { stdio: ["pipe", "pipe", "pipe"], env });
322
+ child.stdout?.setEncoding("utf8");
323
+ child.stderr?.setEncoding("utf8");
324
+ child.stdin?.on("error", () => {
325
+ return;
326
+ });
327
+ let closed;
328
+ const exitListeners = [];
329
+ const settle = (code, signal) => {
330
+ if (closed)
331
+ return;
332
+ closed = [code, signal];
333
+ for (const listener of exitListeners.splice(0))
334
+ listener(code, signal);
335
+ };
336
+ child.once("close", (code, signal) => settle(code, signal));
337
+ child.once("error", () => settle(-1, null));
338
+ return {
339
+ write(data) {
340
+ if (!child.stdin || child.stdin.destroyed || !child.stdin.writable)
341
+ throw new Error("stdin closed");
342
+ child.stdin.write(data);
343
+ },
344
+ closeInput() {
345
+ child.stdin?.end();
346
+ },
347
+ onStdout(listener) {
348
+ child.stdout?.on("data", (chunk) => listener(chunk));
349
+ },
350
+ onStderr(listener) {
351
+ child.stderr?.on("data", (chunk) => listener(chunk));
352
+ },
353
+ onExit(listener) {
354
+ if (closed) {
355
+ const [code, signal] = closed;
356
+ queueMicrotask(() => listener(code, signal));
357
+ return;
358
+ }
359
+ exitListeners.push(listener);
360
+ },
361
+ kill(signal = "SIGTERM") {
362
+ child.kill(signal);
363
+ }
364
+ };
365
+ }
366
+ };
367
+
368
+ // src/desktop/conversation.ts
369
+ class Conversation {
370
+ options;
371
+ provider;
372
+ locale;
373
+ current;
374
+ queue = [];
375
+ waiter;
376
+ consumed = false;
377
+ finished = false;
378
+ ending = false;
379
+ cancelling = false;
380
+ graceTimer;
381
+ constructor(options) {
382
+ this.options = options;
383
+ this.provider = options.provider;
384
+ this.locale = options.locale;
385
+ }
386
+ get isFinished() {
387
+ return this.finished;
388
+ }
389
+ async begin() {
390
+ await this.startTurn();
391
+ }
392
+ events() {
393
+ if (this.consumed)
394
+ throw new VoiceError2("bad_request", "A conversation's events can be read once.");
395
+ this.consumed = true;
396
+ return {
397
+ [Symbol.asyncIterator]: () => ({
398
+ next: () => {
399
+ const next = this.queue.shift();
400
+ if (next)
401
+ return Promise.resolve({ value: next, done: false });
402
+ if (this.finished)
403
+ return Promise.resolve({ value: undefined, done: true });
404
+ return new Promise((resolve) => {
405
+ this.waiter = resolve;
406
+ });
407
+ },
408
+ return: async () => {
409
+ await this.cancel();
410
+ return { value: undefined, done: true };
411
+ }
412
+ })
413
+ };
414
+ }
415
+ async respond(textChunk, options = {}) {
416
+ const final = options.final ?? true;
417
+ if (this.finished || this.cancelling)
418
+ throw new VoiceError2("cancelled", "The conversation is over.");
419
+ const turn = this.current;
420
+ if (!turn || turn.ended)
421
+ throw new VoiceError2("bad_request", "No turn is waiting for an answer.");
422
+ if (turn.final)
423
+ throw new VoiceError2("bad_request", "This turn's answer is already complete.");
424
+ if (textChunk.length === 0 && !final)
425
+ return;
426
+ if (final)
427
+ turn.final = true;
428
+ await this.options.connection.send({
429
+ cmd: "turn-respond",
430
+ id: turn.id,
431
+ text: textChunk,
432
+ final,
433
+ ...this.options.voice
434
+ });
435
+ }
436
+ async listen() {
437
+ if (this.finished || this.cancelling)
438
+ throw new VoiceError2("cancelled", "The conversation is over.");
439
+ const turn = this.current;
440
+ if (turn && !turn.ended && turn.state === "speaking" && !this.options.bargeIn && this.options.halfDuplex) {
441
+ throw new VoiceError2("busy", "The answer is still playing and barge-in is off.");
442
+ }
443
+ this.ending = false;
444
+ await this.startTurn();
445
+ }
446
+ async stopListening() {
447
+ const turn = this.current;
448
+ if (!turn || turn.ended || turn.state !== "listening" && turn.state !== undefined)
449
+ return;
450
+ await this.options.connection.send({ cmd: "turn-end", id: turn.id }).catch(() => {
451
+ return;
452
+ });
453
+ }
454
+ async end() {
455
+ if (this.finished)
456
+ return;
457
+ this.ending = true;
458
+ const turn = this.current;
459
+ if (!turn || turn.ended)
460
+ return this.finish();
461
+ await this.options.connection.send({ cmd: "turn-end", id: turn.id }).catch(() => {
462
+ return;
463
+ });
464
+ }
465
+ async cancel() {
466
+ if (this.finished || this.cancelling)
467
+ return;
468
+ this.cancelling = true;
469
+ const turn = this.current;
470
+ if (!turn || turn.ended) {
471
+ this.push({ type: "cancelled" });
472
+ return this.finish();
473
+ }
474
+ await this.options.connection.send({ cmd: "turn-cancel", id: turn.id }).catch(() => {
475
+ return;
476
+ });
477
+ this.graceTimer ??= setTimeout(() => {
478
+ if (this.finished)
479
+ return;
480
+ this.closeTurn(turn, { type: "ended", reason: "cancelled", turn: turn.id });
481
+ this.push({ type: "cancelled" });
482
+ this.finish();
483
+ this.options.onStuck();
484
+ }, this.options.terminalGraceMs);
485
+ }
486
+ startTurn() {
487
+ const turn = { id: nextRequestId("turn-"), state: undefined, final: false, ended: false };
488
+ this.current = turn;
489
+ let settleStart;
490
+ const started = new Promise((resolve, reject) => {
491
+ settleStart = { resolve, reject };
492
+ });
493
+ this.options.connection.request({
494
+ cmd: "turn-start",
495
+ id: turn.id,
496
+ locale: this.locale,
497
+ ...this.options.engine ? { engine: this.options.engine } : {},
498
+ bargeIn: this.options.bargeIn,
499
+ halfDuplex: this.options.halfDuplex
500
+ }, isTurnTerminal2, {
501
+ timeoutMs: null,
502
+ onEvent: (event) => {
503
+ this.forward(turn, event);
504
+ if (event.event === "turn-state" && event.state === "listening")
505
+ settleStart.resolve();
506
+ }
507
+ }).then((terminal) => {
508
+ if (terminal.event === "turn-error") {
509
+ settleStart.reject(new VoiceError2(terminal.code, terminal.message ?? "The turn failed."));
510
+ } else {
511
+ settleStart.resolve();
512
+ }
513
+ this.afterTerminal(turn);
514
+ }, (error) => {
515
+ const typed = VoiceError2.wrapping(error);
516
+ this.closeTurn(turn, { type: "failed", error: typed, turn: turn.id });
517
+ settleStart.reject(typed);
518
+ this.afterTerminal(turn);
519
+ });
520
+ started.catch(() => {
521
+ return;
522
+ });
523
+ return started;
524
+ }
525
+ forward(turn, event) {
526
+ if (turn.ended)
527
+ return;
528
+ const tag = { turn: turn.id };
529
+ switch (event.event) {
530
+ case "turn-state":
531
+ turn.state = event.state;
532
+ switch (event.state) {
533
+ case "listening":
534
+ case "responding":
535
+ case "speaking":
536
+ case "idle":
537
+ if (event.state === "idle")
538
+ turn.final = false;
539
+ return this.push({ type: event.state, ...tag });
540
+ case "interrupted":
541
+ return;
542
+ case "ended":
543
+ return this.closeTurn(turn, { type: "ended", reason: event.reason ?? "completed", ...tag });
544
+ }
545
+ return;
546
+ case "turn-partial":
547
+ return this.push({
548
+ type: "partial",
549
+ partial: { finalizedText: event.finalizedText, volatileText: event.volatileText, sequence: event.sequence },
550
+ ...tag
551
+ });
552
+ case "turn-transcript":
553
+ return this.push({ type: "transcript", text: event.text, ...tag });
554
+ case "turn-barge-in":
555
+ return this.push({ type: "barge-in", ...tag });
556
+ case "turn-speech-started":
557
+ return this.push({ type: "speech-started", utterance: event.utterance, ...tag });
558
+ case "turn-speech-finished":
559
+ return this.push({ type: "speech-finished", utterance: event.utterance, ...tag });
560
+ case "turn-speech-cancelled":
561
+ return this.push({ type: "speech-cancelled", utterance: event.utterance, ...tag });
562
+ case "turn-metrics":
563
+ return this.push({
564
+ type: "metrics",
565
+ metrics: {
566
+ firstPartialMs: event.firstPartialMs,
567
+ transcriptMs: event.transcriptMs,
568
+ firstAudioMs: event.firstAudioMs,
569
+ speechFinishedMs: event.speechFinishedMs
570
+ },
571
+ ...tag
572
+ });
573
+ case "turn-error":
574
+ return this.closeTurn(turn, {
575
+ type: "failed",
576
+ error: new VoiceError2(event.code, event.message ?? "The turn failed."),
577
+ ...tag
578
+ });
579
+ default:
580
+ return;
581
+ }
582
+ }
583
+ closeTurn(turn, terminal) {
584
+ if (turn.ended)
585
+ return;
586
+ turn.ended = true;
587
+ this.push(terminal);
588
+ }
589
+ afterTerminal(turn) {
590
+ const reason = this.reasons.get(turn.id);
591
+ this.reasons.delete(turn.id);
592
+ if (turn !== this.current || this.finished)
593
+ return;
594
+ this.current = undefined;
595
+ if (this.cancelling || reason === "cancelled") {
596
+ this.push({ type: "cancelled" });
597
+ return this.finish();
598
+ }
599
+ if (reason === "failed" || this.ending)
600
+ return this.finish();
601
+ if (reason === "completed" && this.options.continuous) {
602
+ this.startTurn().catch(() => {
603
+ return;
604
+ });
605
+ }
606
+ }
607
+ reasons = new Map;
608
+ finish() {
609
+ if (this.finished)
610
+ return;
611
+ this.finished = true;
612
+ clearTimeout(this.graceTimer);
613
+ this.options.onFinished();
614
+ if (this.queue.length === 0 && this.waiter) {
615
+ const waiter = this.waiter;
616
+ this.waiter = undefined;
617
+ waiter({ value: undefined, done: true });
618
+ }
619
+ }
620
+ push(event) {
621
+ if (event.type === "ended" && event.turn)
622
+ this.reasons.set(event.turn, event.reason);
623
+ if (event.type === "failed" && event.turn)
624
+ this.reasons.set(event.turn, "failed");
625
+ if (this.finished)
626
+ return;
627
+ if (this.waiter) {
628
+ const waiter = this.waiter;
629
+ this.waiter = undefined;
630
+ waiter({ value: event, done: false });
631
+ return;
632
+ }
633
+ if (event.type === "partial") {
634
+ const last = this.queue.at(-1);
635
+ if (last?.type === "partial" && last.turn === event.turn)
636
+ this.queue.pop();
637
+ }
638
+ this.queue.push(event);
639
+ }
640
+ }
641
+
642
+ // src/desktop/desktop-voice.ts
643
+ var APPLE_ANALYZER_ID = "apple.analyzer";
644
+ var APPLE_LEGACY_ID = "apple.legacy";
645
+ var APPLE_VOICES_ID = "apple.system-voices";
646
+ var TRANSCRIBE_CPP_ID = "transcribe.cpp";
647
+ var AUDIO_CPP_ID = "audio.cpp";
648
+ function desktopRoutingPolicy(os) {
649
+ if (os === "darwin") {
650
+ return {
651
+ chains: { speechToText: [APPLE_ANALYZER_ID, APPLE_LEGACY_ID], textToSpeech: [APPLE_VOICES_ID] },
652
+ allowsOptInModelInstallation: false
653
+ };
654
+ }
655
+ return {
656
+ chains: { speechToText: [TRANSCRIBE_CPP_ID], textToSpeech: [AUDIO_CPP_ID] },
657
+ allowsOptInModelInstallation: false
658
+ };
659
+ }
660
+ var DESKTOP_PLATFORMS = ["macOS", "windows", "linux"];
661
+ function descriptor(id, displayName, kind, platforms, extra = {}) {
662
+ return {
663
+ id,
664
+ displayName,
665
+ kind,
666
+ platforms,
667
+ execution: "onDevice",
668
+ contract: VOICE_CONTRACT2,
669
+ requiresModelDownload: false,
670
+ modelFamilies: [],
671
+ licenses: [],
672
+ capabilities: { streamingPartials: kind === "speechToText", trueCancellation: true, localeSelection: true },
673
+ ...extra
674
+ };
675
+ }
676
+ var DESKTOP_DESCRIPTORS = {
677
+ [APPLE_ANALYZER_ID]: descriptor(APPLE_ANALYZER_ID, "Apple Speech", "speechToText", ["macOS"]),
678
+ [APPLE_LEGACY_ID]: descriptor(APPLE_LEGACY_ID, "Apple Speech (compatibility)", "speechToText", ["macOS"]),
679
+ [TRANSCRIBE_CPP_ID]: descriptor(TRANSCRIBE_CPP_ID, "transcribe.cpp", "speechToText", DESKTOP_PLATFORMS, {
680
+ requiresModelDownload: true,
681
+ modelFamilies: ["whisper", "parakeet", "canary", "moonshine"]
682
+ }),
683
+ [APPLE_VOICES_ID]: descriptor(APPLE_VOICES_ID, "Apple voices", "textToSpeech", ["macOS"], {
684
+ capabilities: { trueCancellation: true, voiceSelection: true, utteranceQueueing: true, wordBoundaryPause: true, localeSelection: true }
685
+ }),
686
+ [AUDIO_CPP_ID]: descriptor(AUDIO_CPP_ID, "audio.cpp", "textToSpeech", DESKTOP_PLATFORMS, {
687
+ requiresModelDownload: true,
688
+ modelFamilies: ["phonon", "kokoro", "qwen3-tts"],
689
+ capabilities: { trueCancellation: true, voiceSelection: true, utteranceQueueing: true }
690
+ })
691
+ };
692
+ function createDesktopVoice(options) {
693
+ return new DesktopVoiceService(options);
694
+ }
695
+ var HELPER_LABEL = { voice: "adea-voice-helper", transcribe: "adea-transcribe-helper", tts: "adea-tts-helper" };
696
+
697
+ class DesktopVoiceService {
698
+ options;
699
+ os;
700
+ connections = new Map;
701
+ transcribeFolders = "";
702
+ transcribeConnectionFolders = "";
703
+ active;
704
+ activeConversation;
705
+ spawner;
706
+ constructor(options) {
707
+ this.options = options;
708
+ this.os = options.os ?? process.platform;
709
+ this.spawner = options.spawn ?? nodeSpawner;
710
+ }
711
+ bundled() {
712
+ return {
713
+ voice: this.os === "darwin" && Boolean(this.options.helpers.voice),
714
+ transcribe: Boolean(this.options.helpers.transcribe),
715
+ tts: Boolean(this.options.helpers.tts)
716
+ };
717
+ }
718
+ async capabilities(settings, locale = defaultLocale(settings.stt.locale)) {
719
+ const probe = new Probe(this, settings);
720
+ const providers = this.providers(probe);
721
+ const policy = routingPolicyFor2(withModelChoice(settings), desktopRoutingPolicy(this.os));
722
+ const ttsLocale = settings.tts.locale ?? locale;
723
+ const [speechToText, textToSpeech, permission] = await Promise.all([
724
+ route2({ kind: "speechToText", locale, providers, policy }),
725
+ route2({ kind: "textToSpeech", locale: ttsLocale, providers, policy }),
726
+ probe.permission()
727
+ ]);
728
+ const statuses = await Promise.all(Object.values(DESKTOP_DESCRIPTORS).filter((entry) => entry.platforms.includes(platformOf(this.os))).map(async (entry) => {
729
+ const provider = providers.find((candidate) => candidate.descriptor.id === entry.id);
730
+ const kindLocale = entry.kind === "speechToText" ? locale : ttsLocale;
731
+ return {
732
+ id: entry.id,
733
+ displayName: entry.displayName,
734
+ kind: entry.kind,
735
+ bundled: provider !== undefined,
736
+ availability: provider ? await provider.availability(kindLocale) : unavailable2("providerNotRegistered", `${entry.displayName} is not included in this build.`, {
737
+ kind: "chooseAnotherProvider",
738
+ detail: "Choose another engine."
739
+ })
740
+ };
741
+ }));
742
+ const localModels = this.bundled().transcribe ? (await probe.transcribeStatus(locale).catch(() => {
743
+ return;
744
+ }))?.models ?? [] : [];
745
+ return { os: this.os, speechToText, textToSpeech, providers: statuses, permission, localModels };
746
+ }
747
+ async permission(options = {}) {
748
+ if (!this.bundled().voice) {
749
+ return { state: this.bundled().transcribe ? "prompt" : "unavailable", microphone: "unknown", speech: "unknown" };
750
+ }
751
+ const event = await this.connection("voice").request({ cmd: "permission", request: options.request === true }, (candidate) => candidate.event === "permission", { timeoutMs: options.request ? null : undefined });
752
+ return { state: event.state, microphone: event.microphone ?? "unknown", speech: event.speech ?? "unknown" };
753
+ }
754
+ async listen(request) {
755
+ if (this.active && !this.active.isTerminal)
756
+ throw new VoiceError2("busy", "A dictation is already running.");
757
+ if (this.activeConversation && !this.activeConversation.isFinished) {
758
+ throw new VoiceError2("busy", "A voice conversation is running.");
759
+ }
760
+ if (request.signal?.aborted)
761
+ throw new VoiceError2("cancelled", "Dictation was cancelled.");
762
+ const locale = request.locale ?? defaultLocale(request.settings.stt.locale);
763
+ const capabilities = await this.capabilities(request.settings, locale);
764
+ const decision = capabilities.speechToText;
765
+ if (!decision.route || decision.availability.status !== "available") {
766
+ throw unavailableError(decision);
767
+ }
768
+ if (this.active && !this.active.isTerminal)
769
+ throw new VoiceError2("busy", "A dictation is already running.");
770
+ const providerID = decision.route.descriptor.id;
771
+ const helper = providerID === TRANSCRIBE_CPP_ID ? "transcribe" : "voice";
772
+ if (helper === "transcribe")
773
+ this.applyTranscribeFolders(request.settings);
774
+ const engine = providerID === APPLE_ANALYZER_ID ? "analyzer" : providerID === APPLE_LEGACY_ID ? "legacy" : undefined;
775
+ const session = new DictationSession({
776
+ connection: this.connection(helper),
777
+ provider: providerID,
778
+ locale,
779
+ engine,
780
+ onPartial: request.onPartial,
781
+ maxListenMs: this.options.maxListenMs ?? 75000,
782
+ terminalGraceMs: this.options.terminalGraceMs ?? 5000,
783
+ onStuck: () => void this.connection(helper).stop()
784
+ });
785
+ this.active = session;
786
+ if (request.signal) {
787
+ if (request.signal.aborted)
788
+ session.cancel();
789
+ else
790
+ request.signal.addEventListener("abort", () => void session.cancel(), { once: true });
791
+ }
792
+ await session.started;
793
+ return session;
794
+ }
795
+ async conversation(request) {
796
+ const busy = () => this.active && !this.active.isTerminal || this.activeConversation && !this.activeConversation.isFinished;
797
+ if (busy())
798
+ throw new VoiceError2("busy", "A dictation or conversation is already running.");
799
+ if (request.signal?.aborted)
800
+ throw new VoiceError2("cancelled", "The conversation was cancelled.");
801
+ if (!this.bundled().voice) {
802
+ throw new VoiceError2("unavailable", "Voice conversations need the Apple voice helper, which this build does not include.");
803
+ }
804
+ const locale = request.locale ?? defaultLocale(request.settings.stt.locale);
805
+ const capabilities = await this.capabilities(request.settings, locale);
806
+ for (const decision of [capabilities.speechToText, capabilities.textToSpeech]) {
807
+ if (!decision.route || decision.availability.status !== "available")
808
+ throw unavailableError(decision);
809
+ }
810
+ const sttID = capabilities.speechToText.route.descriptor.id;
811
+ const ttsID = capabilities.textToSpeech.route.descriptor.id;
812
+ if (sttID !== APPLE_ANALYZER_ID && sttID !== APPLE_LEGACY_ID || ttsID !== APPLE_VOICES_ID) {
813
+ throw new VoiceError2("unavailable", "Voice conversations run on Apple speech and Apple voices; the selected engines do not support them yet.");
814
+ }
815
+ const connection = this.connection("voice");
816
+ const minor = connection.version?.wireMinor ?? 0;
817
+ if (minor < TURN_WIRE_MINOR2) {
818
+ throw new VoiceError2("unavailable", "This build's voice helper is too old for conversations (it needs wire 1.2).");
819
+ }
820
+ if (busy())
821
+ throw new VoiceError2("busy", "A dictation or conversation is already running.");
822
+ const voice = request.settings.tts.voice;
823
+ const rate = request.settings.tts.rate;
824
+ const ttsLocale = request.settings.tts.locale;
825
+ const conversation = new Conversation({
826
+ connection,
827
+ provider: sttID,
828
+ locale,
829
+ engine: sttID === APPLE_ANALYZER_ID ? "analyzer" : "legacy",
830
+ bargeIn: request.bargeIn ?? true,
831
+ halfDuplex: request.halfDuplex ?? true,
832
+ continuous: request.continuous ?? true,
833
+ voice: {
834
+ ...voice ? { voice } : {},
835
+ ...ttsLocale ? { locale: ttsLocale } : {},
836
+ ...rate !== undefined ? { rate: appleRate(rate) } : {}
837
+ },
838
+ terminalGraceMs: this.options.terminalGraceMs ?? 5000,
839
+ onStuck: () => void connection.stop(),
840
+ onFinished: () => {
841
+ if (this.activeConversation === conversation)
842
+ this.activeConversation = undefined;
843
+ }
844
+ });
845
+ this.activeConversation = conversation;
846
+ if (request.signal)
847
+ request.signal.addEventListener("abort", () => void conversation.cancel(), { once: true });
848
+ await conversation.begin();
849
+ return conversation;
850
+ }
851
+ async speak(request) {
852
+ const text = request.text.trim();
853
+ if (text.length === 0)
854
+ throw new VoiceError2("bad_request", "There is nothing to read aloud.");
855
+ const locale = request.locale ?? defaultLocale(request.settings.tts.locale);
856
+ const decision = await route2({
857
+ kind: "textToSpeech",
858
+ locale,
859
+ providers: this.providers(new Probe(this, request.settings)),
860
+ policy: routingPolicyFor2(request.settings, desktopRoutingPolicy(this.os))
861
+ });
862
+ if (!decision.route || decision.availability.status !== "available")
863
+ throw unavailableError(decision);
864
+ const providerID = decision.route.descriptor.id;
865
+ const connection = this.connection(providerID === AUDIO_CPP_ID ? "tts" : "voice");
866
+ const id = nextRequestId("speech-");
867
+ const voice = request.voice ?? request.settings.tts.voice;
868
+ const rate = request.rate ?? request.settings.tts.rate;
869
+ let markStarted = () => {
870
+ return;
871
+ };
872
+ const started = new Promise((resolve) => {
873
+ markStarted = resolve;
874
+ });
875
+ const done = connection.request({
876
+ cmd: "speak",
877
+ id,
878
+ text,
879
+ locale,
880
+ ...voice ? { voice } : {},
881
+ ...rate !== undefined ? { rate: providerID === AUDIO_CPP_ID ? rate : appleRate(rate) } : {},
882
+ queue: request.queue ?? "replace"
883
+ }, (event) => event.event === "speech-finished" || event.event === "speech-cancelled" || event.event === "speech-error", {
884
+ timeoutMs: null,
885
+ onEvent: (event) => {
886
+ if (event.event === "speech-started")
887
+ markStarted(speechStart(event.voice));
888
+ }
889
+ }).finally(() => markStarted(undefined)).then((event) => {
890
+ if (event.event === "speech-error")
891
+ throw new VoiceError2(event.code, event.message ?? "Speech failed.");
892
+ return event.event === "speech-finished" ? "finished" : "cancelled";
893
+ });
894
+ done.catch(() => {
895
+ return;
896
+ });
897
+ return {
898
+ id,
899
+ provider: providerID,
900
+ started,
901
+ done,
902
+ cancel: async () => {
903
+ await connection.send({ cmd: "speech-stop" }).catch(() => {
904
+ return;
905
+ });
906
+ }
907
+ };
908
+ }
909
+ async stopSpeaking() {
910
+ const sends = [];
911
+ for (const name of ["voice", "tts"]) {
912
+ const connection = this.connections.get(name);
913
+ if (connection?.running)
914
+ sends.push(connection.send({ cmd: "speech-stop" }).catch(() => {
915
+ return;
916
+ }));
917
+ }
918
+ await Promise.all(sends);
919
+ }
920
+ async voices(settings, locale) {
921
+ const exact = await this.voicesFor(locale);
922
+ if (exact.length > 0 || !locale)
923
+ return exact;
924
+ const language = locale.split(/[-_]/)[0].toLowerCase();
925
+ return (await this.voicesFor(undefined)).filter((voice) => voice.locale.split(/[-_]/)[0].toLowerCase() === language);
926
+ }
927
+ async voicesFor(locale) {
928
+ const lists = await Promise.all(["voice", "tts"].filter((name) => this.bundled()[name]).map(async (name) => {
929
+ const collected = [];
930
+ const provider = name === "voice" ? APPLE_VOICES_ID : AUDIO_CPP_ID;
931
+ await this.connection(name).request({ cmd: "voices", ...locale ? { locale } : {} }, (event) => event.event === "voices-done", {
932
+ onEvent: (event) => {
933
+ if (event.event === "voice") {
934
+ collected.push({ id: event.id, name: event.name, locale: event.locale, quality: event.quality, provider });
935
+ }
936
+ }
937
+ }).catch((error) => {
938
+ this.options.log?.(`voices from ${HELPER_LABEL[name]}: ${String(error)}`);
939
+ });
940
+ return collected;
941
+ }));
942
+ return lists.flat();
943
+ }
944
+ async locales() {
945
+ if (!this.bundled().voice)
946
+ return [];
947
+ const collected = [];
948
+ await this.connection("voice").request({ cmd: "locales" }, (event) => event.event === "locales-done", {
949
+ onEvent: (event) => {
950
+ if (event.event === "locale")
951
+ collected.push({ locale: event.locale.replace(/_/g, "-"), status: event.status, canInstall: event.canInstall });
952
+ }
953
+ });
954
+ return collected;
955
+ }
956
+ async installAssets(request) {
957
+ if (!this.bundled().voice)
958
+ throw new VoiceError2("unavailable", "Speech assets are managed by the system on this device.");
959
+ const connection = this.connection("voice");
960
+ const id = nextRequestId("install-");
961
+ const onAbort = () => void connection.send({ cmd: "install-cancel", id }).catch(() => {
962
+ return;
963
+ });
964
+ request.signal?.addEventListener("abort", onAbort, { once: true });
965
+ await connection.request({ cmd: "install-assets", id, locale: request.locale }, (event) => event.event === "asset-installed", {
966
+ timeoutMs: null,
967
+ signal: request.signal,
968
+ onEvent: (event) => {
969
+ if (event.event === "asset-progress")
970
+ request.onProgress?.(event.fraction);
971
+ }
972
+ }).finally(() => request.signal?.removeEventListener("abort", onAbort));
973
+ }
974
+ async releaseAssets(request) {
975
+ if (!this.bundled().voice)
976
+ throw new VoiceError2("unavailable", "Speech assets are managed by the system on this device.");
977
+ const connection = this.connection("voice");
978
+ const tooOld = () => new VoiceError2("unavailable", "This build's voice helper is too old to remove speech models (it needs wire 1.3).");
979
+ const minor = connection.version?.wireMinor;
980
+ if (minor !== undefined && minor < RELEASE_ASSETS_WIRE_MINOR2)
981
+ throw tooOld();
982
+ let answer;
983
+ await connection.request({ cmd: "release-assets", id: nextRequestId("release-"), locale: request.locale }, (event) => event.event === "asset-released", {
984
+ onEvent: (event) => {
985
+ if (event.event !== "asset-released")
986
+ return;
987
+ answer = {
988
+ locale: event.locale,
989
+ modelLocale: event.modelLocale.replace(/_/g, "-"),
990
+ released: event.released,
991
+ status: event.status,
992
+ canInstall: event.canInstall
993
+ };
994
+ }
995
+ }).catch((error) => {
996
+ if (error instanceof VoiceError2 && error.code === "bad_request" && (connection.version?.wireMinor ?? 0) < RELEASE_ASSETS_WIRE_MINOR2) {
997
+ throw tooOld();
998
+ }
999
+ throw error;
1000
+ });
1001
+ if (!answer)
1002
+ throw new VoiceError2("failed", "The voice helper did not report the removal.");
1003
+ return answer;
1004
+ }
1005
+ async dispose() {
1006
+ await this.active?.cancel().catch(() => {
1007
+ return;
1008
+ });
1009
+ await this.activeConversation?.cancel().catch(() => {
1010
+ return;
1011
+ });
1012
+ await Promise.all([...this.connections.values()].map((connection) => connection.stop()));
1013
+ }
1014
+ providers(probe) {
1015
+ const bundled = this.bundled();
1016
+ const providers = [];
1017
+ if (bundled.voice) {
1018
+ providers.push({ descriptor: DESKTOP_DESCRIPTORS[APPLE_ANALYZER_ID], availability: (locale) => probe.apple(locale, "analyzer") }, { descriptor: DESKTOP_DESCRIPTORS[APPLE_LEGACY_ID], availability: (locale) => probe.apple(locale, "legacy") }, { descriptor: DESKTOP_DESCRIPTORS[APPLE_VOICES_ID], availability: (locale) => probe.appleVoices(locale) });
1019
+ }
1020
+ if (bundled.transcribe) {
1021
+ providers.push({ descriptor: DESKTOP_DESCRIPTORS[TRANSCRIBE_CPP_ID], availability: (locale) => probe.transcribe(locale) });
1022
+ }
1023
+ if (bundled.tts) {
1024
+ providers.push({ descriptor: DESKTOP_DESCRIPTORS[AUDIO_CPP_ID], availability: (locale) => probe.synthesis(locale) });
1025
+ }
1026
+ return providers;
1027
+ }
1028
+ connection(name) {
1029
+ let connection = this.connections.get(name);
1030
+ if (connection)
1031
+ return connection;
1032
+ const path = this.options.helpers[name];
1033
+ if (!path)
1034
+ throw new VoiceError2("unavailable", `${HELPER_LABEL[name]} is not included in this build.`);
1035
+ if (name === "transcribe")
1036
+ this.transcribeConnectionFolders = this.transcribeFolders;
1037
+ connection = new HelperConnection({
1038
+ path,
1039
+ name: HELPER_LABEL[name],
1040
+ spawn: (file, args, spawnOptions) => this.spawn(file, args, spawnOptions),
1041
+ env: name === "transcribe" ? { ...this.options.env, ...this.transcribeEnv() } : this.options.env,
1042
+ log: this.options.log
1043
+ });
1044
+ this.connections.set(name, connection);
1045
+ return connection;
1046
+ }
1047
+ spawn(file, args, spawnOptions) {
1048
+ return this.spawner(file, args, spawnOptions);
1049
+ }
1050
+ transcribeEnv() {
1051
+ return this.transcribeFolders ? { ADEA_TRANSCRIBE_MODEL_DIRS: this.transcribeFolders } : {};
1052
+ }
1053
+ applyTranscribeFolders(settings) {
1054
+ this.transcribeFolders = settings.models.folders.join(this.os === "win32" ? ";" : ":");
1055
+ const existing = this.connections.get("transcribe");
1056
+ if (!existing || this.transcribeConnectionFolders === this.transcribeFolders)
1057
+ return;
1058
+ if (!(this.active && !this.active.isTerminal && this.active.provider === TRANSCRIBE_CPP_ID)) {
1059
+ this.connections.delete("transcribe");
1060
+ existing.stop();
1061
+ }
1062
+ }
1063
+ }
1064
+
1065
+ class Probe {
1066
+ service;
1067
+ settings;
1068
+ cache = new Map;
1069
+ constructor(service, settings) {
1070
+ this.service = service;
1071
+ this.settings = settings;
1072
+ }
1073
+ once(key, load) {
1074
+ let entry = this.cache.get(key);
1075
+ if (!entry) {
1076
+ entry = load();
1077
+ this.cache.set(key, entry);
1078
+ }
1079
+ return entry;
1080
+ }
1081
+ permission() {
1082
+ return this.once("permission", () => this.service.permission().catch(() => ({ state: "unavailable", microphone: "unknown", speech: "unknown" })));
1083
+ }
1084
+ appleStatus(locale) {
1085
+ return this.once(`apple:${locale}`, () => this.service.connection("voice").request({ cmd: "status", locale }, (event) => event.event === "status"));
1086
+ }
1087
+ async apple(locale, engine) {
1088
+ let status;
1089
+ try {
1090
+ status = await this.appleStatus(locale);
1091
+ } catch (error) {
1092
+ return helperFailure(error);
1093
+ }
1094
+ const permission = await this.permission();
1095
+ const micDenied = permission.microphone === "denied" || permission.microphone === "restricted";
1096
+ const speechDenied = permission.speech === "denied" || permission.speech === "restricted";
1097
+ if (micDenied || engine === "legacy" && speechDenied) {
1098
+ return unavailable2("permissionDenied", "Microphone or speech recognition access is off.", {
1099
+ kind: "grantPermission",
1100
+ detail: "Allow access in System Settings › Privacy & Security."
1101
+ });
1102
+ }
1103
+ const state = engine === "analyzer" ? status.analyzer : status.legacy;
1104
+ switch (state) {
1105
+ case "available":
1106
+ return AVAILABLE2;
1107
+ case "needsAssetInstall":
1108
+ return unavailable2("modelNotInstalled", `The speech model for ${locale} is not on this Mac yet.`, {
1109
+ kind: "installModel",
1110
+ detail: "Download the language in Voice settings."
1111
+ });
1112
+ case "unavailableOS":
1113
+ return unavailable2("unsupportedOperatingSystem", "This engine needs a newer macOS.", {
1114
+ kind: "upgradeOperatingSystem",
1115
+ detail: "Update macOS, or use the compatibility engine."
1116
+ });
1117
+ case "localeUnsupported":
1118
+ return unavailable2("unsupportedLocale", `${locale} is not supported on this Mac.`, {
1119
+ kind: "switchLocale",
1120
+ detail: "Choose another dictation language."
1121
+ });
1122
+ default:
1123
+ return unavailable2("engineFailed", "Speech recognition is unavailable on this Mac.");
1124
+ }
1125
+ }
1126
+ async appleVoices(locale) {
1127
+ try {
1128
+ const voices = await this.once(`voices:${locale}`, () => this.service.voices(this.settings, locale));
1129
+ if (voices.some((voice) => voice.provider === APPLE_VOICES_ID))
1130
+ return AVAILABLE2;
1131
+ const language = locale.split("-")[0];
1132
+ const all = await this.once("voices:*", () => this.service.voices(this.settings));
1133
+ if (all.some((voice) => voice.provider === APPLE_VOICES_ID && voice.locale.split(/[-_]/)[0] === language)) {
1134
+ return AVAILABLE2;
1135
+ }
1136
+ return unavailable2("unsupportedLocale", `No voice for ${locale} is installed.`, {
1137
+ kind: "installModel",
1138
+ detail: "Add a voice in System Settings › Accessibility › Spoken Content."
1139
+ });
1140
+ } catch (error) {
1141
+ return helperFailure(error);
1142
+ }
1143
+ }
1144
+ transcribeStatus(locale) {
1145
+ this.service.applyTranscribeFolders(this.settings);
1146
+ return this.once(`transcribe:${locale}`, () => this.service.connection("transcribe").request({ cmd: "status", locale }, (event) => event.event === "status", {
1147
+ timeoutMs: 60000
1148
+ }));
1149
+ }
1150
+ async transcribe(locale) {
1151
+ let status;
1152
+ try {
1153
+ status = await this.transcribeStatus(locale);
1154
+ } catch (error) {
1155
+ return helperFailure(error);
1156
+ }
1157
+ if (status.models.length === 0) {
1158
+ return unavailable2("modelNotInstalled", "No transcribe.cpp model was found.", {
1159
+ kind: "installModel",
1160
+ detail: "Add a folder with a model in Voice settings."
1161
+ });
1162
+ }
1163
+ if (!status.selected) {
1164
+ return unavailable2("unsupportedLocale", `No local model supports ${locale}.`, {
1165
+ kind: "switchLocale",
1166
+ detail: "Choose another language or add a multilingual model."
1167
+ });
1168
+ }
1169
+ return AVAILABLE2;
1170
+ }
1171
+ async synthesis(locale) {
1172
+ try {
1173
+ const status = await this.once(`tts:${locale}`, () => this.service.connection("tts").request({ cmd: "status", locale }, (event) => event.event === "status"));
1174
+ if (status.ready)
1175
+ return AVAILABLE2;
1176
+ const reason = status.reason;
1177
+ if (reason === "modelNotInstalled") {
1178
+ return unavailable2("modelNotInstalled", status.message ?? "No audio.cpp model is installed.", {
1179
+ kind: "installModel",
1180
+ detail: "Add a voice model in Voice settings."
1181
+ });
1182
+ }
1183
+ if (reason === "unsupportedLocale")
1184
+ return unavailable2("unsupportedLocale", status.message ?? `No voice for ${locale}.`);
1185
+ if (reason === "unsupportedPlatform")
1186
+ return unavailable2("unsupportedPlatform", status.message ?? "Not supported here.");
1187
+ return unavailable2("engineFailed", status.message ?? "audio.cpp is unavailable.");
1188
+ } catch (error) {
1189
+ return helperFailure(error);
1190
+ }
1191
+ }
1192
+ }
1193
+ function withModelChoice(settings) {
1194
+ if (settings.stt.provider)
1195
+ return settings;
1196
+ const model = settings.stt.model;
1197
+ if (model !== "analyzer" && model !== "legacy")
1198
+ return settings;
1199
+ return { ...settings, stt: { ...settings.stt, provider: model === "analyzer" ? APPLE_ANALYZER_ID : APPLE_LEGACY_ID } };
1200
+ }
1201
+ function helperFailure(error) {
1202
+ if (error instanceof IncompatibleHelperError) {
1203
+ return unavailable2("contractIncompatible", error.message, {
1204
+ kind: "chooseAnotherProvider",
1205
+ detail: "Install an app build with a matching voice helper."
1206
+ });
1207
+ }
1208
+ const typed = VoiceError2.wrapping(error);
1209
+ return unavailable2("engineFailed", typed.message);
1210
+ }
1211
+ function unavailableError(decision) {
1212
+ const availability = decision.availability;
1213
+ if (availability.status === "available")
1214
+ return new VoiceError2("unavailable", "No engine can serve this request.");
1215
+ const reason = availability.unavailable.reason;
1216
+ const code = reason === "permissionDenied" ? "denied" : reason === "unsupportedLocale" ? "language_unsupported" : reason === "modelNotInstalled" || reason === "modelDownloadDisabled" ? "assets_missing" : "unavailable";
1217
+ return new VoiceError2(code, availability.unavailable.message);
1218
+ }
1219
+ function platformOf(os) {
1220
+ return os === "darwin" ? "macOS" : os === "win32" ? "windows" : "linux";
1221
+ }
1222
+ function defaultLocale(chosen) {
1223
+ if (chosen)
1224
+ return chosen;
1225
+ try {
1226
+ return Intl.DateTimeFormat().resolvedOptions().locale || "en-US";
1227
+ } catch {
1228
+ return "en-US";
1229
+ }
1230
+ }
1231
+ var VOICE_QUALITIES = new Set(["default", "enhanced", "premium", "unknown"]);
1232
+ function speechStart(voice) {
1233
+ if (voice === null || typeof voice !== "object")
1234
+ return {};
1235
+ const { id, name, language, locale, quality } = voice;
1236
+ const tag = typeof language === "string" ? language : typeof locale === "string" ? locale : undefined;
1237
+ if (typeof id !== "string" || typeof name !== "string" || tag === undefined)
1238
+ return {};
1239
+ return {
1240
+ voice: {
1241
+ id,
1242
+ name,
1243
+ language: tag,
1244
+ locale: typeof locale === "string" ? locale : tag,
1245
+ quality: typeof quality === "string" && VOICE_QUALITIES.has(quality) ? quality : "unknown"
1246
+ }
1247
+ };
1248
+ }
1249
+ function appleRate(rate) {
1250
+ return Math.min(1, Math.max(0.05, rate * 0.5));
1251
+ }
1252
+
1253
+ class DictationSession {
1254
+ options;
1255
+ provider;
1256
+ locale;
1257
+ execution = "onDevice";
1258
+ result;
1259
+ started;
1260
+ id = nextRequestId("listen-");
1261
+ queue = [];
1262
+ waiter;
1263
+ terminal;
1264
+ consumed = false;
1265
+ lastSequence = -1;
1266
+ maxTimer;
1267
+ graceTimer;
1268
+ settle;
1269
+ constructor(options) {
1270
+ this.options = options;
1271
+ this.provider = options.provider;
1272
+ this.locale = options.locale;
1273
+ this.result = new Promise((resolve, reject) => {
1274
+ this.settle = { resolve, reject };
1275
+ });
1276
+ this.result.catch(() => {
1277
+ return;
1278
+ });
1279
+ let resolveStarted;
1280
+ let rejectStarted;
1281
+ this.started = new Promise((resolve, reject) => {
1282
+ resolveStarted = resolve;
1283
+ rejectStarted = reject;
1284
+ });
1285
+ options.connection.request({ cmd: "listen", id: this.id, locale: options.locale, ...options.engine ? { engine: options.engine } : {} }, (event) => event.event === "final" || event.event === "cancelled" || event.event === "error", {
1286
+ timeoutMs: null,
1287
+ onEvent: (event) => {
1288
+ if (event.event === "listening")
1289
+ resolveStarted();
1290
+ if (event.event === "partial")
1291
+ this.partial(event.finalizedText, event.volatileText, event.sequence);
1292
+ }
1293
+ }).then((event) => {
1294
+ if (event.event === "final")
1295
+ this.finish({ type: "final", text: event.text });
1296
+ else if (event.event === "error") {
1297
+ this.finish({ type: "failed", error: new VoiceError2(event.code, event.message ?? "Dictation failed.") });
1298
+ } else
1299
+ this.finish({ type: "cancelled" });
1300
+ }, (error) => this.finish({ type: "failed", error: VoiceError2.wrapping(error) })).finally(() => {
1301
+ const terminal = this.terminal;
1302
+ if (terminal?.type === "failed")
1303
+ rejectStarted(terminal.error);
1304
+ else if (terminal?.type === "cancelled")
1305
+ rejectStarted(new VoiceError2("cancelled", "Dictation was cancelled."));
1306
+ else
1307
+ resolveStarted();
1308
+ });
1309
+ this.maxTimer = setTimeout(() => void this.end(), options.maxListenMs);
1310
+ }
1311
+ get isTerminal() {
1312
+ return this.terminal !== undefined;
1313
+ }
1314
+ events() {
1315
+ if (this.consumed)
1316
+ throw new VoiceError2("bad_request", "A dictation's events can be read once.");
1317
+ this.consumed = true;
1318
+ return {
1319
+ [Symbol.asyncIterator]: () => ({
1320
+ next: () => {
1321
+ const next = this.queue.shift();
1322
+ if (next)
1323
+ return Promise.resolve({ value: next, done: false });
1324
+ if (this.terminal && this.queue.length === 0 && this.drained) {
1325
+ return Promise.resolve({ value: undefined, done: true });
1326
+ }
1327
+ return new Promise((resolve) => {
1328
+ this.waiter = resolve;
1329
+ });
1330
+ },
1331
+ return: async () => {
1332
+ await this.cancel();
1333
+ return { value: undefined, done: true };
1334
+ }
1335
+ })
1336
+ };
1337
+ }
1338
+ drained = false;
1339
+ cancelRequested = false;
1340
+ async end() {
1341
+ if (this.terminal || this.cancelRequested)
1342
+ return;
1343
+ await this.options.connection.send({ cmd: "listen-end", id: this.id }).catch(() => {
1344
+ return;
1345
+ });
1346
+ this.armGrace();
1347
+ }
1348
+ async cancel() {
1349
+ if (this.terminal)
1350
+ return;
1351
+ this.cancelRequested = true;
1352
+ await this.options.connection.send({ cmd: "listen-cancel", id: this.id }).catch(() => {
1353
+ return;
1354
+ });
1355
+ this.armGrace(true);
1356
+ }
1357
+ armGrace(cancelling = false) {
1358
+ if (this.graceTimer || this.terminal)
1359
+ return;
1360
+ this.graceTimer = setTimeout(() => {
1361
+ if (this.terminal)
1362
+ return;
1363
+ this.finish(cancelling ? { type: "cancelled" } : { type: "failed", error: new VoiceError2("failed", "The speech engine stopped answering.") });
1364
+ this.options.onStuck();
1365
+ }, this.options.terminalGraceMs);
1366
+ }
1367
+ partial(finalizedText, volatileText, sequence) {
1368
+ if (this.terminal || sequence <= this.lastSequence)
1369
+ return;
1370
+ this.lastSequence = sequence;
1371
+ const partial = { finalizedText, volatileText, sequence };
1372
+ this.options.onPartial?.({ ...partial, text: joinTranscript(finalizedText, volatileText) });
1373
+ this.push({ type: "partial", partial });
1374
+ }
1375
+ finish(event) {
1376
+ if (this.terminal)
1377
+ return;
1378
+ this.terminal = event;
1379
+ clearTimeout(this.maxTimer);
1380
+ clearTimeout(this.graceTimer);
1381
+ this.push(event);
1382
+ this.drained = true;
1383
+ if (event.type === "final")
1384
+ this.settle.resolve(event.text);
1385
+ else if (event.type === "cancelled")
1386
+ this.settle.reject(new VoiceError2("cancelled", "Dictation was cancelled."));
1387
+ else if (event.type === "failed")
1388
+ this.settle.reject(event.error);
1389
+ queueMicrotask(() => {
1390
+ if (this.queue.length === 0 && this.waiter) {
1391
+ const waiter = this.waiter;
1392
+ this.waiter = undefined;
1393
+ waiter({ value: undefined, done: true });
1394
+ }
1395
+ });
1396
+ }
1397
+ push(event) {
1398
+ if (this.waiter) {
1399
+ const waiter = this.waiter;
1400
+ this.waiter = undefined;
1401
+ waiter({ value: event, done: false });
1402
+ return;
1403
+ }
1404
+ if (event.type === "partial") {
1405
+ const last = this.queue.at(-1);
1406
+ if (last?.type === "partial")
1407
+ this.queue.pop();
1408
+ }
1409
+ this.queue.push(event);
1410
+ }
1411
+ }
1412
+ function joinTranscript(finalizedText, volatileText) {
1413
+ if (!finalizedText)
1414
+ return volatileText.trimStart();
1415
+ if (!volatileText)
1416
+ return finalizedText;
1417
+ const needsSpace = !/\s$/.test(finalizedText) && !/^[\s.,;:!?]/.test(volatileText);
1418
+ return needsSpace ? `${finalizedText} ${volatileText}` : `${finalizedText}${volatileText}`;
1419
+ }
1420
+ export {
1421
+ APPLE_ANALYZER_ID,
1422
+ APPLE_LEGACY_ID,
1423
+ APPLE_VOICES_ID,
1424
+ AUDIO_CPP_ID,
1425
+ DESKTOP_DESCRIPTORS,
1426
+ HELPER_LOCK_SCHEMA2 as HELPER_LOCK_SCHEMA,
1427
+ HELPER_NAMES2 as HELPER_NAMES,
1428
+ HELPER_TARGETS2 as HELPER_TARGETS,
1429
+ HelperConnection,
1430
+ HelperLockError2 as HelperLockError,
1431
+ IncompatibleHelperError,
1432
+ LineSplitter,
1433
+ MAX_HELPER_ARCHIVE_BYTES2 as MAX_HELPER_ARCHIVE_BYTES,
1434
+ STAGED_RECORD_FILE2 as STAGED_RECORD_FILE,
1435
+ TRANSCRIBE_CPP_ID,
1436
+ assertHandshake2 as assertHandshake,
1437
+ createDesktopVoice,
1438
+ currentHelperTarget2 as currentHelperTarget,
1439
+ desktopRoutingPolicy,
1440
+ helperArtifactUrl2 as helperArtifactUrl,
1441
+ helperPin2 as helperPin,
1442
+ isMachO2 as isMachO,
1443
+ joinTranscript,
1444
+ machoCodeDigest2 as machoCodeDigest,
1445
+ machoCodeDigestFile2 as machoCodeDigestFile,
1446
+ nodeSpawner,
1447
+ readHelperLock2 as readHelperLock,
1448
+ readStagedRecord2 as readStagedRecord,
1449
+ sha256File2 as sha256File,
1450
+ stageVoiceHelpers2 as stageVoiceHelpers,
1451
+ validateHelperLock2 as validateHelperLock,
1452
+ verifyStagedVoiceHelpers2 as verifyStagedVoiceHelpers,
1453
+ withModelChoice
1454
+ };