@adea-ai/voice 0.0.0-stage → 0.2.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 +51 -2
- package/dist/cli/helpers-cli.d.ts +2 -0
- package/dist/cli/helpers-cli.js +102 -0
- package/dist/contract/contract.d.ts +138 -0
- package/dist/contract/errors.d.ts +26 -0
- package/dist/contract/index.d.ts +9 -0
- package/dist/contract/index.js +54 -0
- package/dist/contract/session.d.ts +58 -0
- package/dist/contract/wire.d.ts +188 -0
- package/dist/desktop/desktop-voice.d.ts +152 -0
- package/dist/desktop/helper-lock.d.ts +83 -0
- package/dist/desktop/helper-process.d.ts +92 -0
- package/dist/desktop/index.d.ts +7 -0
- package/dist/desktop/index.js +1042 -0
- package/dist/index-9kerqn9r.js +150 -0
- package/dist/index-acm1yvvv.js +290 -0
- package/dist/index-r4hz8gk0.js +10 -0
- package/dist/index-rehs788p.js +42 -0
- package/dist/index-s270cw30.js +295 -0
- package/dist/index-tvz9s9nz.js +77 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +86 -0
- package/dist/settings/index.d.ts +5 -0
- package/dist/settings/index.js +34 -0
- package/dist/settings/settings.d.ts +163 -0
- package/dist/web/index.d.ts +15 -0
- package/dist/web/index.js +1287 -0
- package/dist/web/stt/speech-recognition.d.ts +105 -0
- package/dist/web/tts/phonon.d.ts +139 -0
- package/dist/web/tts/player.d.ts +115 -0
- package/dist/web/tts/system-voices.d.ts +122 -0
- package/dist/web/turns.d.ts +101 -0
- package/package.json +68 -4
- package/src/cli/helpers-cli.ts +119 -0
- package/src/contract/contract.ts +365 -0
- package/src/contract/errors.ts +98 -0
- package/src/contract/index.ts +9 -0
- package/src/contract/session.ts +65 -0
- package/src/contract/wire.ts +263 -0
- package/src/desktop/desktop-voice.ts +933 -0
- package/src/desktop/helper-lock.ts +375 -0
- package/src/desktop/helper-process.ts +401 -0
- package/src/desktop/index.ts +16 -0
- package/src/index.ts +7 -0
- package/src/settings/index.ts +5 -0
- package/src/settings/settings.ts +478 -0
- package/src/web/index.ts +15 -0
- package/src/web/stt/speech-recognition.ts +583 -0
- package/src/web/tts/phonon.ts +386 -0
- package/src/web/tts/player.ts +271 -0
- package/src/web/tts/system-voices.ts +401 -0
- package/src/web/turns.ts +224 -0
|
@@ -0,0 +1,1042 @@
|
|
|
1
|
+
import {
|
|
2
|
+
routingPolicyFor2
|
|
3
|
+
} from "../index-s270cw30.js";
|
|
4
|
+
import {
|
|
5
|
+
VOICE_CONTRACT2,
|
|
6
|
+
AVAILABLE2,
|
|
7
|
+
unavailable2,
|
|
8
|
+
route2
|
|
9
|
+
} from "../index-9kerqn9r.js";
|
|
10
|
+
import {
|
|
11
|
+
HELPER_LOCK_SCHEMA2,
|
|
12
|
+
HELPER_NAMES2,
|
|
13
|
+
HELPER_TARGETS2,
|
|
14
|
+
MAX_HELPER_ARCHIVE_BYTES2,
|
|
15
|
+
STAGED_RECORD_FILE2,
|
|
16
|
+
HelperLockError2,
|
|
17
|
+
validateHelperLock2,
|
|
18
|
+
readHelperLock2,
|
|
19
|
+
helperPin2,
|
|
20
|
+
helperArtifactUrl2,
|
|
21
|
+
currentHelperTarget2,
|
|
22
|
+
sha256File2,
|
|
23
|
+
stageVoiceHelpers2,
|
|
24
|
+
verifyStagedVoiceHelpers2,
|
|
25
|
+
readStagedRecord2,
|
|
26
|
+
assertHandshake2
|
|
27
|
+
} from "../index-acm1yvvv.js";
|
|
28
|
+
import {
|
|
29
|
+
MAX_WIRE_LINE_BYTES2,
|
|
30
|
+
parseWireLine2,
|
|
31
|
+
encodeWireCommand2,
|
|
32
|
+
correlationId2,
|
|
33
|
+
isCompatibleHandshake2
|
|
34
|
+
} from "../index-rehs788p.js";
|
|
35
|
+
import {
|
|
36
|
+
VoiceError2
|
|
37
|
+
} from "../index-tvz9s9nz.js";
|
|
38
|
+
|
|
39
|
+
// src/desktop/helper-process.ts
|
|
40
|
+
import { spawn as spawnProcess } from "node:child_process";
|
|
41
|
+
class IncompatibleHelperError extends VoiceError2 {
|
|
42
|
+
constructor(message) {
|
|
43
|
+
super("unavailable", message);
|
|
44
|
+
this.name = "IncompatibleHelperError";
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
class LineSplitter {
|
|
49
|
+
limit;
|
|
50
|
+
buffer = "";
|
|
51
|
+
discarding = false;
|
|
52
|
+
constructor(limit = MAX_WIRE_LINE_BYTES2) {
|
|
53
|
+
this.limit = limit;
|
|
54
|
+
}
|
|
55
|
+
push(chunk) {
|
|
56
|
+
const lines = [];
|
|
57
|
+
let rest = chunk;
|
|
58
|
+
while (rest.length > 0) {
|
|
59
|
+
const newline = rest.indexOf(`
|
|
60
|
+
`);
|
|
61
|
+
if (newline === -1) {
|
|
62
|
+
if (!this.discarding) {
|
|
63
|
+
if (this.buffer.length + rest.length > this.limit) {
|
|
64
|
+
this.buffer = "";
|
|
65
|
+
this.discarding = true;
|
|
66
|
+
} else {
|
|
67
|
+
this.buffer += rest;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
break;
|
|
71
|
+
}
|
|
72
|
+
const piece = rest.slice(0, newline);
|
|
73
|
+
rest = rest.slice(newline + 1);
|
|
74
|
+
if (this.discarding) {
|
|
75
|
+
this.discarding = false;
|
|
76
|
+
this.buffer = "";
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
const line = (this.buffer + piece).replace(/\r$/, "");
|
|
80
|
+
this.buffer = "";
|
|
81
|
+
if (line.length <= this.limit && line.length > 0)
|
|
82
|
+
lines.push(line);
|
|
83
|
+
}
|
|
84
|
+
return lines;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
var requestCounter = 0;
|
|
88
|
+
function nextRequestId(prefix = "r") {
|
|
89
|
+
requestCounter = (requestCounter + 1) % Number.MAX_SAFE_INTEGER;
|
|
90
|
+
return `${prefix}${requestCounter.toString(36)}`;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
class HelperConnection {
|
|
94
|
+
options;
|
|
95
|
+
child;
|
|
96
|
+
starting;
|
|
97
|
+
handshake;
|
|
98
|
+
pending = new Map;
|
|
99
|
+
broadcast = new Set;
|
|
100
|
+
crashes = [];
|
|
101
|
+
disposed = false;
|
|
102
|
+
incompatible;
|
|
103
|
+
constructor(options) {
|
|
104
|
+
this.options = options;
|
|
105
|
+
}
|
|
106
|
+
get version() {
|
|
107
|
+
return this.handshake;
|
|
108
|
+
}
|
|
109
|
+
onEvent(listener) {
|
|
110
|
+
this.broadcast.add(listener);
|
|
111
|
+
return () => this.broadcast.delete(listener);
|
|
112
|
+
}
|
|
113
|
+
async request(command, isDone, options = {}) {
|
|
114
|
+
const id = command.id ?? nextRequestId();
|
|
115
|
+
const child = await this.ensureStarted();
|
|
116
|
+
return await new Promise((resolve, reject) => {
|
|
117
|
+
let timer;
|
|
118
|
+
const finish = (outcome) => {
|
|
119
|
+
if (!this.pending.has(id))
|
|
120
|
+
return;
|
|
121
|
+
this.pending.delete(id);
|
|
122
|
+
if (timer)
|
|
123
|
+
clearTimeout(timer);
|
|
124
|
+
options.signal?.removeEventListener("abort", onAbort);
|
|
125
|
+
outcome();
|
|
126
|
+
};
|
|
127
|
+
const onAbort = () => finish(() => reject(new VoiceError2("cancelled", "request aborted")));
|
|
128
|
+
if (options.signal?.aborted)
|
|
129
|
+
return reject(new VoiceError2("cancelled", "request aborted"));
|
|
130
|
+
options.signal?.addEventListener("abort", onAbort, { once: true });
|
|
131
|
+
this.pending.set(id, {
|
|
132
|
+
fail: (error) => finish(() => reject(error)),
|
|
133
|
+
listener: (event) => {
|
|
134
|
+
options.onEvent?.(event);
|
|
135
|
+
if (isDone(event))
|
|
136
|
+
return finish(() => resolve(event));
|
|
137
|
+
if (event.event === "error") {
|
|
138
|
+
return finish(() => reject(new VoiceError2(event.code, event.message ?? `helper refused ${command.cmd}`)));
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
const timeoutMs = options.timeoutMs === undefined ? this.options.requestTimeoutMs ?? 15000 : options.timeoutMs;
|
|
143
|
+
if (timeoutMs !== null) {
|
|
144
|
+
timer = setTimeout(() => finish(() => reject(new VoiceError2("failed", `${command.cmd} timed out after ${timeoutMs} ms`))), timeoutMs);
|
|
145
|
+
}
|
|
146
|
+
try {
|
|
147
|
+
child.write(`${encodeWireCommand2({ ...command, id })}
|
|
148
|
+
`);
|
|
149
|
+
} catch (error) {
|
|
150
|
+
finish(() => reject(new VoiceError2("failed", `could not reach the helper: ${String(error)}`)));
|
|
151
|
+
}
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
async send(command) {
|
|
155
|
+
const child = await this.ensureStarted();
|
|
156
|
+
try {
|
|
157
|
+
child.write(`${encodeWireCommand2(command)}
|
|
158
|
+
`);
|
|
159
|
+
} catch (error) {
|
|
160
|
+
throw new VoiceError2("failed", `could not reach the helper: ${String(error)}`);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
get running() {
|
|
164
|
+
return this.child !== undefined;
|
|
165
|
+
}
|
|
166
|
+
async stop() {
|
|
167
|
+
const child = this.child ?? await this.starting?.catch(() => {
|
|
168
|
+
return;
|
|
169
|
+
});
|
|
170
|
+
this.child = undefined;
|
|
171
|
+
this.starting = undefined;
|
|
172
|
+
if (!child)
|
|
173
|
+
return;
|
|
174
|
+
this.failAll(new VoiceError2("cancelled", "the voice helper was stopped"));
|
|
175
|
+
await new Promise((resolve) => {
|
|
176
|
+
let exited = false;
|
|
177
|
+
child.onExit(() => {
|
|
178
|
+
exited = true;
|
|
179
|
+
resolve();
|
|
180
|
+
});
|
|
181
|
+
try {
|
|
182
|
+
child.write(`${encodeWireCommand2({ cmd: "quit" })}
|
|
183
|
+
`);
|
|
184
|
+
child.closeInput();
|
|
185
|
+
} catch {}
|
|
186
|
+
const grace = this.options.exitGraceMs ?? 2000;
|
|
187
|
+
setTimeout(() => {
|
|
188
|
+
if (exited)
|
|
189
|
+
return;
|
|
190
|
+
child.kill("SIGTERM");
|
|
191
|
+
setTimeout(() => {
|
|
192
|
+
if (!exited)
|
|
193
|
+
child.kill("SIGKILL");
|
|
194
|
+
resolve();
|
|
195
|
+
}, grace).unref?.();
|
|
196
|
+
}, grace).unref?.();
|
|
197
|
+
});
|
|
198
|
+
}
|
|
199
|
+
async dispose() {
|
|
200
|
+
this.disposed = true;
|
|
201
|
+
await this.stop();
|
|
202
|
+
this.failAll(new VoiceError2("cancelled", "the voice helper was shut down"));
|
|
203
|
+
}
|
|
204
|
+
async ensureStarted() {
|
|
205
|
+
if (this.disposed)
|
|
206
|
+
throw new VoiceError2("unavailable", "the voice helper was shut down");
|
|
207
|
+
if (this.incompatible)
|
|
208
|
+
throw this.incompatible;
|
|
209
|
+
if (this.child)
|
|
210
|
+
return this.child;
|
|
211
|
+
if (!this.starting) {
|
|
212
|
+
this.starting = this.start().finally(() => {
|
|
213
|
+
this.starting = undefined;
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
return await this.starting;
|
|
217
|
+
}
|
|
218
|
+
async start() {
|
|
219
|
+
const now = this.options.now ?? Date.now;
|
|
220
|
+
const window = this.options.crashWindowMs ?? 60000;
|
|
221
|
+
this.crashes = this.crashes.filter((at) => now() - at < window);
|
|
222
|
+
if (this.crashes.length >= (this.options.maxCrashes ?? 3)) {
|
|
223
|
+
throw new VoiceError2("unavailable", "the voice helper keeps crashing; restart the app to try again");
|
|
224
|
+
}
|
|
225
|
+
let version;
|
|
226
|
+
try {
|
|
227
|
+
version = await this.versionHandshake();
|
|
228
|
+
} catch (error) {
|
|
229
|
+
this.crashes.push(now());
|
|
230
|
+
throw error;
|
|
231
|
+
}
|
|
232
|
+
if (!isCompatibleHandshake2(version)) {
|
|
233
|
+
this.incompatible = new IncompatibleHelperError(`voice helper speaks wire ${version.wire} / contract ${version.contract}; this app needs wire 1 / contract 1`);
|
|
234
|
+
throw this.incompatible;
|
|
235
|
+
}
|
|
236
|
+
this.handshake = version;
|
|
237
|
+
const child = this.options.spawn(this.options.path, ["--serve"], { env: this.options.env });
|
|
238
|
+
const splitter = new LineSplitter;
|
|
239
|
+
child.onStdout((chunk) => {
|
|
240
|
+
for (const line of splitter.push(chunk))
|
|
241
|
+
this.dispatch(line);
|
|
242
|
+
});
|
|
243
|
+
child.onStderr?.((chunk) => this.options.log?.(`voice helper: ${chunk.trimEnd().slice(0, 500)}`));
|
|
244
|
+
child.onExit((code, signal) => {
|
|
245
|
+
if (this.child !== child)
|
|
246
|
+
return;
|
|
247
|
+
this.child = undefined;
|
|
248
|
+
if (!this.disposed)
|
|
249
|
+
this.crashes.push(now());
|
|
250
|
+
this.failAll(new VoiceError2("failed", `the voice helper exited (${signal ?? `code ${String(code)}`}); it restarts on the next request`));
|
|
251
|
+
});
|
|
252
|
+
this.child = child;
|
|
253
|
+
return child;
|
|
254
|
+
}
|
|
255
|
+
async versionHandshake() {
|
|
256
|
+
const child = this.options.spawn(this.options.path, ["--version"], { env: this.options.env });
|
|
257
|
+
const splitter = new LineSplitter;
|
|
258
|
+
return await new Promise((resolve, reject) => {
|
|
259
|
+
let settled = false;
|
|
260
|
+
const settle = (outcome) => {
|
|
261
|
+
if (settled)
|
|
262
|
+
return;
|
|
263
|
+
settled = true;
|
|
264
|
+
clearTimeout(timer);
|
|
265
|
+
outcome();
|
|
266
|
+
};
|
|
267
|
+
const timer = setTimeout(() => {
|
|
268
|
+
settle(() => reject(new VoiceError2("unavailable", "the voice helper did not answer its version handshake")));
|
|
269
|
+
child.kill("SIGKILL");
|
|
270
|
+
}, this.options.handshakeTimeoutMs ?? 5000);
|
|
271
|
+
child.onStdout((chunk) => {
|
|
272
|
+
for (const line of splitter.push(chunk)) {
|
|
273
|
+
const event = parseWireLine2(line);
|
|
274
|
+
if (event?.event === "version")
|
|
275
|
+
settle(() => resolve(event));
|
|
276
|
+
}
|
|
277
|
+
});
|
|
278
|
+
child.onExit((code) => {
|
|
279
|
+
settle(() => reject(new VoiceError2("unavailable", `the voice helper failed to start (exit ${String(code)})`)));
|
|
280
|
+
});
|
|
281
|
+
try {
|
|
282
|
+
child.closeInput();
|
|
283
|
+
} catch {}
|
|
284
|
+
});
|
|
285
|
+
}
|
|
286
|
+
dispatch(line) {
|
|
287
|
+
const event = parseWireLine2(line);
|
|
288
|
+
if (!event) {
|
|
289
|
+
this.options.log?.(`voice helper: ignored a malformed line (${line.slice(0, 80)})`);
|
|
290
|
+
return;
|
|
291
|
+
}
|
|
292
|
+
const id = correlationId2(event);
|
|
293
|
+
if (id !== undefined)
|
|
294
|
+
this.pending.get(id)?.listener(event);
|
|
295
|
+
for (const listener of this.broadcast)
|
|
296
|
+
listener(event);
|
|
297
|
+
}
|
|
298
|
+
failAll(error) {
|
|
299
|
+
const pending = [...this.pending.values()];
|
|
300
|
+
for (const entry of pending)
|
|
301
|
+
entry.fail(error);
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
var nodeSpawner = (path, args, options) => {
|
|
305
|
+
{
|
|
306
|
+
const spawn = spawnProcess;
|
|
307
|
+
const env = {};
|
|
308
|
+
for (const [key, value] of Object.entries({ ...process.env, ...options.env })) {
|
|
309
|
+
if (value !== undefined)
|
|
310
|
+
env[key] = value;
|
|
311
|
+
}
|
|
312
|
+
const child = spawn(path, [...args], { stdio: ["pipe", "pipe", "pipe"], env });
|
|
313
|
+
child.stdout?.setEncoding("utf8");
|
|
314
|
+
child.stderr?.setEncoding("utf8");
|
|
315
|
+
child.stdin?.on("error", () => {
|
|
316
|
+
return;
|
|
317
|
+
});
|
|
318
|
+
let closed;
|
|
319
|
+
const exitListeners = [];
|
|
320
|
+
const settle = (code, signal) => {
|
|
321
|
+
if (closed)
|
|
322
|
+
return;
|
|
323
|
+
closed = [code, signal];
|
|
324
|
+
for (const listener of exitListeners.splice(0))
|
|
325
|
+
listener(code, signal);
|
|
326
|
+
};
|
|
327
|
+
child.once("close", (code, signal) => settle(code, signal));
|
|
328
|
+
child.once("error", () => settle(-1, null));
|
|
329
|
+
return {
|
|
330
|
+
write(data) {
|
|
331
|
+
if (!child.stdin || child.stdin.destroyed || !child.stdin.writable)
|
|
332
|
+
throw new Error("stdin closed");
|
|
333
|
+
child.stdin.write(data);
|
|
334
|
+
},
|
|
335
|
+
closeInput() {
|
|
336
|
+
child.stdin?.end();
|
|
337
|
+
},
|
|
338
|
+
onStdout(listener) {
|
|
339
|
+
child.stdout?.on("data", (chunk) => listener(chunk));
|
|
340
|
+
},
|
|
341
|
+
onStderr(listener) {
|
|
342
|
+
child.stderr?.on("data", (chunk) => listener(chunk));
|
|
343
|
+
},
|
|
344
|
+
onExit(listener) {
|
|
345
|
+
if (closed) {
|
|
346
|
+
const [code, signal] = closed;
|
|
347
|
+
queueMicrotask(() => listener(code, signal));
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
exitListeners.push(listener);
|
|
351
|
+
},
|
|
352
|
+
kill(signal = "SIGTERM") {
|
|
353
|
+
child.kill(signal);
|
|
354
|
+
}
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
};
|
|
358
|
+
|
|
359
|
+
// src/desktop/desktop-voice.ts
|
|
360
|
+
var APPLE_ANALYZER_ID = "apple.analyzer";
|
|
361
|
+
var APPLE_LEGACY_ID = "apple.legacy";
|
|
362
|
+
var APPLE_VOICES_ID = "apple.system-voices";
|
|
363
|
+
var TRANSCRIBE_CPP_ID = "transcribe.cpp";
|
|
364
|
+
var AUDIO_CPP_ID = "audio.cpp";
|
|
365
|
+
function desktopRoutingPolicy(os) {
|
|
366
|
+
if (os === "darwin") {
|
|
367
|
+
return {
|
|
368
|
+
chains: { speechToText: [APPLE_ANALYZER_ID, APPLE_LEGACY_ID], textToSpeech: [APPLE_VOICES_ID] },
|
|
369
|
+
allowsOptInModelInstallation: false
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
return {
|
|
373
|
+
chains: { speechToText: [TRANSCRIBE_CPP_ID], textToSpeech: [AUDIO_CPP_ID] },
|
|
374
|
+
allowsOptInModelInstallation: false
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
var DESKTOP_PLATFORMS = ["macOS", "windows", "linux"];
|
|
378
|
+
function descriptor(id, displayName, kind, platforms, extra = {}) {
|
|
379
|
+
return {
|
|
380
|
+
id,
|
|
381
|
+
displayName,
|
|
382
|
+
kind,
|
|
383
|
+
platforms,
|
|
384
|
+
execution: "onDevice",
|
|
385
|
+
contract: VOICE_CONTRACT2,
|
|
386
|
+
requiresModelDownload: false,
|
|
387
|
+
modelFamilies: [],
|
|
388
|
+
licenses: [],
|
|
389
|
+
capabilities: { streamingPartials: kind === "speechToText", trueCancellation: true, localeSelection: true },
|
|
390
|
+
...extra
|
|
391
|
+
};
|
|
392
|
+
}
|
|
393
|
+
var DESKTOP_DESCRIPTORS = {
|
|
394
|
+
[APPLE_ANALYZER_ID]: descriptor(APPLE_ANALYZER_ID, "Apple Speech", "speechToText", ["macOS"]),
|
|
395
|
+
[APPLE_LEGACY_ID]: descriptor(APPLE_LEGACY_ID, "Apple Speech (compatibility)", "speechToText", ["macOS"]),
|
|
396
|
+
[TRANSCRIBE_CPP_ID]: descriptor(TRANSCRIBE_CPP_ID, "transcribe.cpp", "speechToText", DESKTOP_PLATFORMS, {
|
|
397
|
+
requiresModelDownload: true,
|
|
398
|
+
modelFamilies: ["whisper", "parakeet", "canary", "moonshine"]
|
|
399
|
+
}),
|
|
400
|
+
[APPLE_VOICES_ID]: descriptor(APPLE_VOICES_ID, "Apple voices", "textToSpeech", ["macOS"], {
|
|
401
|
+
capabilities: { trueCancellation: true, voiceSelection: true, utteranceQueueing: true, wordBoundaryPause: true, localeSelection: true }
|
|
402
|
+
}),
|
|
403
|
+
[AUDIO_CPP_ID]: descriptor(AUDIO_CPP_ID, "audio.cpp", "textToSpeech", DESKTOP_PLATFORMS, {
|
|
404
|
+
requiresModelDownload: true,
|
|
405
|
+
modelFamilies: ["phonon", "kokoro", "qwen3-tts"],
|
|
406
|
+
capabilities: { trueCancellation: true, voiceSelection: true, utteranceQueueing: true }
|
|
407
|
+
})
|
|
408
|
+
};
|
|
409
|
+
function createDesktopVoice(options) {
|
|
410
|
+
return new DesktopVoiceService(options);
|
|
411
|
+
}
|
|
412
|
+
var HELPER_LABEL = { voice: "adea-voice-helper", transcribe: "adea-transcribe-helper", tts: "adea-tts-helper" };
|
|
413
|
+
|
|
414
|
+
class DesktopVoiceService {
|
|
415
|
+
options;
|
|
416
|
+
os;
|
|
417
|
+
connections = new Map;
|
|
418
|
+
transcribeFolders = "";
|
|
419
|
+
transcribeConnectionFolders = "";
|
|
420
|
+
active;
|
|
421
|
+
spawner;
|
|
422
|
+
constructor(options) {
|
|
423
|
+
this.options = options;
|
|
424
|
+
this.os = options.os ?? process.platform;
|
|
425
|
+
this.spawner = options.spawn ?? nodeSpawner;
|
|
426
|
+
}
|
|
427
|
+
bundled() {
|
|
428
|
+
return {
|
|
429
|
+
voice: this.os === "darwin" && Boolean(this.options.helpers.voice),
|
|
430
|
+
transcribe: Boolean(this.options.helpers.transcribe),
|
|
431
|
+
tts: Boolean(this.options.helpers.tts)
|
|
432
|
+
};
|
|
433
|
+
}
|
|
434
|
+
async capabilities(settings, locale = defaultLocale(settings.stt.locale)) {
|
|
435
|
+
const probe = new Probe(this, settings);
|
|
436
|
+
const providers = this.providers(probe);
|
|
437
|
+
const policy = routingPolicyFor2(withModelChoice(settings), desktopRoutingPolicy(this.os));
|
|
438
|
+
const ttsLocale = settings.tts.locale ?? locale;
|
|
439
|
+
const [speechToText, textToSpeech, permission] = await Promise.all([
|
|
440
|
+
route2({ kind: "speechToText", locale, providers, policy }),
|
|
441
|
+
route2({ kind: "textToSpeech", locale: ttsLocale, providers, policy }),
|
|
442
|
+
probe.permission()
|
|
443
|
+
]);
|
|
444
|
+
const statuses = await Promise.all(Object.values(DESKTOP_DESCRIPTORS).filter((entry) => entry.platforms.includes(platformOf(this.os))).map(async (entry) => {
|
|
445
|
+
const provider = providers.find((candidate) => candidate.descriptor.id === entry.id);
|
|
446
|
+
const kindLocale = entry.kind === "speechToText" ? locale : ttsLocale;
|
|
447
|
+
return {
|
|
448
|
+
id: entry.id,
|
|
449
|
+
displayName: entry.displayName,
|
|
450
|
+
kind: entry.kind,
|
|
451
|
+
bundled: provider !== undefined,
|
|
452
|
+
availability: provider ? await provider.availability(kindLocale) : unavailable2("providerNotRegistered", `${entry.displayName} is not included in this build.`, {
|
|
453
|
+
kind: "chooseAnotherProvider",
|
|
454
|
+
detail: "Choose another engine."
|
|
455
|
+
})
|
|
456
|
+
};
|
|
457
|
+
}));
|
|
458
|
+
const localModels = this.bundled().transcribe ? (await probe.transcribeStatus(locale).catch(() => {
|
|
459
|
+
return;
|
|
460
|
+
}))?.models ?? [] : [];
|
|
461
|
+
return { os: this.os, speechToText, textToSpeech, providers: statuses, permission, localModels };
|
|
462
|
+
}
|
|
463
|
+
async permission(options = {}) {
|
|
464
|
+
if (!this.bundled().voice) {
|
|
465
|
+
return { state: this.bundled().transcribe ? "prompt" : "unavailable", microphone: "unknown", speech: "unknown" };
|
|
466
|
+
}
|
|
467
|
+
const event = await this.connection("voice").request({ cmd: "permission", request: options.request === true }, (candidate) => candidate.event === "permission", { timeoutMs: options.request ? null : undefined });
|
|
468
|
+
return { state: event.state, microphone: event.microphone ?? "unknown", speech: event.speech ?? "unknown" };
|
|
469
|
+
}
|
|
470
|
+
async listen(request) {
|
|
471
|
+
if (this.active && !this.active.isTerminal)
|
|
472
|
+
throw new VoiceError2("busy", "A dictation is already running.");
|
|
473
|
+
if (request.signal?.aborted)
|
|
474
|
+
throw new VoiceError2("cancelled", "Dictation was cancelled.");
|
|
475
|
+
const locale = request.locale ?? defaultLocale(request.settings.stt.locale);
|
|
476
|
+
const capabilities = await this.capabilities(request.settings, locale);
|
|
477
|
+
const decision = capabilities.speechToText;
|
|
478
|
+
if (!decision.route || decision.availability.status !== "available") {
|
|
479
|
+
throw unavailableError(decision);
|
|
480
|
+
}
|
|
481
|
+
if (this.active && !this.active.isTerminal)
|
|
482
|
+
throw new VoiceError2("busy", "A dictation is already running.");
|
|
483
|
+
const providerID = decision.route.descriptor.id;
|
|
484
|
+
const helper = providerID === TRANSCRIBE_CPP_ID ? "transcribe" : "voice";
|
|
485
|
+
if (helper === "transcribe")
|
|
486
|
+
this.applyTranscribeFolders(request.settings);
|
|
487
|
+
const engine = providerID === APPLE_ANALYZER_ID ? "analyzer" : providerID === APPLE_LEGACY_ID ? "legacy" : undefined;
|
|
488
|
+
const session = new DictationSession({
|
|
489
|
+
connection: this.connection(helper),
|
|
490
|
+
provider: providerID,
|
|
491
|
+
locale,
|
|
492
|
+
engine,
|
|
493
|
+
onPartial: request.onPartial,
|
|
494
|
+
maxListenMs: this.options.maxListenMs ?? 75000,
|
|
495
|
+
terminalGraceMs: this.options.terminalGraceMs ?? 5000,
|
|
496
|
+
onStuck: () => void this.connection(helper).stop()
|
|
497
|
+
});
|
|
498
|
+
this.active = session;
|
|
499
|
+
if (request.signal) {
|
|
500
|
+
if (request.signal.aborted)
|
|
501
|
+
session.cancel();
|
|
502
|
+
else
|
|
503
|
+
request.signal.addEventListener("abort", () => void session.cancel(), { once: true });
|
|
504
|
+
}
|
|
505
|
+
await session.started;
|
|
506
|
+
return session;
|
|
507
|
+
}
|
|
508
|
+
async speak(request) {
|
|
509
|
+
const text = request.text.trim();
|
|
510
|
+
if (text.length === 0)
|
|
511
|
+
throw new VoiceError2("bad_request", "There is nothing to read aloud.");
|
|
512
|
+
const locale = request.locale ?? defaultLocale(request.settings.tts.locale);
|
|
513
|
+
const decision = await route2({
|
|
514
|
+
kind: "textToSpeech",
|
|
515
|
+
locale,
|
|
516
|
+
providers: this.providers(new Probe(this, request.settings)),
|
|
517
|
+
policy: routingPolicyFor2(request.settings, desktopRoutingPolicy(this.os))
|
|
518
|
+
});
|
|
519
|
+
if (!decision.route || decision.availability.status !== "available")
|
|
520
|
+
throw unavailableError(decision);
|
|
521
|
+
const providerID = decision.route.descriptor.id;
|
|
522
|
+
const connection = this.connection(providerID === AUDIO_CPP_ID ? "tts" : "voice");
|
|
523
|
+
const id = nextRequestId("speech-");
|
|
524
|
+
const voice = request.voice ?? request.settings.tts.voice;
|
|
525
|
+
const rate = request.rate ?? request.settings.tts.rate;
|
|
526
|
+
const done = connection.request({
|
|
527
|
+
cmd: "speak",
|
|
528
|
+
id,
|
|
529
|
+
text,
|
|
530
|
+
locale,
|
|
531
|
+
...voice ? { voice } : {},
|
|
532
|
+
...rate !== undefined ? { rate: providerID === AUDIO_CPP_ID ? rate : appleRate(rate) } : {},
|
|
533
|
+
queue: request.queue ?? "replace"
|
|
534
|
+
}, (event) => event.event === "speech-finished" || event.event === "speech-cancelled" || event.event === "speech-error", { timeoutMs: null }).then((event) => {
|
|
535
|
+
if (event.event === "speech-error")
|
|
536
|
+
throw new VoiceError2(event.code, event.message ?? "Speech failed.");
|
|
537
|
+
return event.event === "speech-finished" ? "finished" : "cancelled";
|
|
538
|
+
});
|
|
539
|
+
done.catch(() => {
|
|
540
|
+
return;
|
|
541
|
+
});
|
|
542
|
+
return {
|
|
543
|
+
id,
|
|
544
|
+
provider: providerID,
|
|
545
|
+
done,
|
|
546
|
+
cancel: async () => {
|
|
547
|
+
await connection.send({ cmd: "speech-stop" }).catch(() => {
|
|
548
|
+
return;
|
|
549
|
+
});
|
|
550
|
+
}
|
|
551
|
+
};
|
|
552
|
+
}
|
|
553
|
+
async stopSpeaking() {
|
|
554
|
+
const sends = [];
|
|
555
|
+
for (const name of ["voice", "tts"]) {
|
|
556
|
+
const connection = this.connections.get(name);
|
|
557
|
+
if (connection?.running)
|
|
558
|
+
sends.push(connection.send({ cmd: "speech-stop" }).catch(() => {
|
|
559
|
+
return;
|
|
560
|
+
}));
|
|
561
|
+
}
|
|
562
|
+
await Promise.all(sends);
|
|
563
|
+
}
|
|
564
|
+
async voices(settings, locale) {
|
|
565
|
+
const exact = await this.voicesFor(locale);
|
|
566
|
+
if (exact.length > 0 || !locale)
|
|
567
|
+
return exact;
|
|
568
|
+
const language = locale.split(/[-_]/)[0].toLowerCase();
|
|
569
|
+
return (await this.voicesFor(undefined)).filter((voice) => voice.locale.split(/[-_]/)[0].toLowerCase() === language);
|
|
570
|
+
}
|
|
571
|
+
async voicesFor(locale) {
|
|
572
|
+
const lists = await Promise.all(["voice", "tts"].filter((name) => this.bundled()[name]).map(async (name) => {
|
|
573
|
+
const collected = [];
|
|
574
|
+
const provider = name === "voice" ? APPLE_VOICES_ID : AUDIO_CPP_ID;
|
|
575
|
+
await this.connection(name).request({ cmd: "voices", ...locale ? { locale } : {} }, (event) => event.event === "voices-done", {
|
|
576
|
+
onEvent: (event) => {
|
|
577
|
+
if (event.event === "voice") {
|
|
578
|
+
collected.push({ id: event.id, name: event.name, locale: event.locale, quality: event.quality, provider });
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
}).catch((error) => {
|
|
582
|
+
this.options.log?.(`voices from ${HELPER_LABEL[name]}: ${String(error)}`);
|
|
583
|
+
});
|
|
584
|
+
return collected;
|
|
585
|
+
}));
|
|
586
|
+
return lists.flat();
|
|
587
|
+
}
|
|
588
|
+
async locales() {
|
|
589
|
+
if (!this.bundled().voice)
|
|
590
|
+
return [];
|
|
591
|
+
const collected = [];
|
|
592
|
+
await this.connection("voice").request({ cmd: "locales" }, (event) => event.event === "locales-done", {
|
|
593
|
+
onEvent: (event) => {
|
|
594
|
+
if (event.event === "locale")
|
|
595
|
+
collected.push({ locale: event.locale.replace(/_/g, "-"), status: event.status, canInstall: event.canInstall });
|
|
596
|
+
}
|
|
597
|
+
});
|
|
598
|
+
return collected;
|
|
599
|
+
}
|
|
600
|
+
async installAssets(request) {
|
|
601
|
+
if (!this.bundled().voice)
|
|
602
|
+
throw new VoiceError2("unavailable", "Speech assets are managed by the system on this device.");
|
|
603
|
+
const connection = this.connection("voice");
|
|
604
|
+
const id = nextRequestId("install-");
|
|
605
|
+
const onAbort = () => void connection.send({ cmd: "install-cancel", id }).catch(() => {
|
|
606
|
+
return;
|
|
607
|
+
});
|
|
608
|
+
request.signal?.addEventListener("abort", onAbort, { once: true });
|
|
609
|
+
await connection.request({ cmd: "install-assets", id, locale: request.locale }, (event) => event.event === "asset-installed", {
|
|
610
|
+
timeoutMs: null,
|
|
611
|
+
signal: request.signal,
|
|
612
|
+
onEvent: (event) => {
|
|
613
|
+
if (event.event === "asset-progress")
|
|
614
|
+
request.onProgress?.(event.fraction);
|
|
615
|
+
}
|
|
616
|
+
}).finally(() => request.signal?.removeEventListener("abort", onAbort));
|
|
617
|
+
}
|
|
618
|
+
async dispose() {
|
|
619
|
+
await this.active?.cancel().catch(() => {
|
|
620
|
+
return;
|
|
621
|
+
});
|
|
622
|
+
await Promise.all([...this.connections.values()].map((connection) => connection.stop()));
|
|
623
|
+
}
|
|
624
|
+
providers(probe) {
|
|
625
|
+
const bundled = this.bundled();
|
|
626
|
+
const providers = [];
|
|
627
|
+
if (bundled.voice) {
|
|
628
|
+
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) });
|
|
629
|
+
}
|
|
630
|
+
if (bundled.transcribe) {
|
|
631
|
+
providers.push({ descriptor: DESKTOP_DESCRIPTORS[TRANSCRIBE_CPP_ID], availability: (locale) => probe.transcribe(locale) });
|
|
632
|
+
}
|
|
633
|
+
if (bundled.tts) {
|
|
634
|
+
providers.push({ descriptor: DESKTOP_DESCRIPTORS[AUDIO_CPP_ID], availability: (locale) => probe.synthesis(locale) });
|
|
635
|
+
}
|
|
636
|
+
return providers;
|
|
637
|
+
}
|
|
638
|
+
connection(name) {
|
|
639
|
+
let connection = this.connections.get(name);
|
|
640
|
+
if (connection)
|
|
641
|
+
return connection;
|
|
642
|
+
const path = this.options.helpers[name];
|
|
643
|
+
if (!path)
|
|
644
|
+
throw new VoiceError2("unavailable", `${HELPER_LABEL[name]} is not included in this build.`);
|
|
645
|
+
if (name === "transcribe")
|
|
646
|
+
this.transcribeConnectionFolders = this.transcribeFolders;
|
|
647
|
+
connection = new HelperConnection({
|
|
648
|
+
path,
|
|
649
|
+
spawn: (file, args, spawnOptions) => this.spawn(file, args, spawnOptions),
|
|
650
|
+
env: name === "transcribe" ? { ...this.options.env, ...this.transcribeEnv() } : this.options.env,
|
|
651
|
+
log: this.options.log
|
|
652
|
+
});
|
|
653
|
+
this.connections.set(name, connection);
|
|
654
|
+
return connection;
|
|
655
|
+
}
|
|
656
|
+
spawn(file, args, spawnOptions) {
|
|
657
|
+
return this.spawner(file, args, spawnOptions);
|
|
658
|
+
}
|
|
659
|
+
transcribeEnv() {
|
|
660
|
+
return this.transcribeFolders ? { ADEA_TRANSCRIBE_MODEL_DIRS: this.transcribeFolders } : {};
|
|
661
|
+
}
|
|
662
|
+
applyTranscribeFolders(settings) {
|
|
663
|
+
this.transcribeFolders = settings.models.folders.join(this.os === "win32" ? ";" : ":");
|
|
664
|
+
const existing = this.connections.get("transcribe");
|
|
665
|
+
if (!existing || this.transcribeConnectionFolders === this.transcribeFolders)
|
|
666
|
+
return;
|
|
667
|
+
if (!(this.active && !this.active.isTerminal && this.active.provider === TRANSCRIBE_CPP_ID)) {
|
|
668
|
+
this.connections.delete("transcribe");
|
|
669
|
+
existing.stop();
|
|
670
|
+
}
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
class Probe {
|
|
675
|
+
service;
|
|
676
|
+
settings;
|
|
677
|
+
cache = new Map;
|
|
678
|
+
constructor(service, settings) {
|
|
679
|
+
this.service = service;
|
|
680
|
+
this.settings = settings;
|
|
681
|
+
}
|
|
682
|
+
once(key, load) {
|
|
683
|
+
let entry = this.cache.get(key);
|
|
684
|
+
if (!entry) {
|
|
685
|
+
entry = load();
|
|
686
|
+
this.cache.set(key, entry);
|
|
687
|
+
}
|
|
688
|
+
return entry;
|
|
689
|
+
}
|
|
690
|
+
permission() {
|
|
691
|
+
return this.once("permission", () => this.service.permission().catch(() => ({ state: "unavailable", microphone: "unknown", speech: "unknown" })));
|
|
692
|
+
}
|
|
693
|
+
appleStatus(locale) {
|
|
694
|
+
return this.once(`apple:${locale}`, () => this.service.connection("voice").request({ cmd: "status", locale }, (event) => event.event === "status"));
|
|
695
|
+
}
|
|
696
|
+
async apple(locale, engine) {
|
|
697
|
+
let status;
|
|
698
|
+
try {
|
|
699
|
+
status = await this.appleStatus(locale);
|
|
700
|
+
} catch (error) {
|
|
701
|
+
return helperFailure(error);
|
|
702
|
+
}
|
|
703
|
+
const permission = await this.permission();
|
|
704
|
+
const micDenied = permission.microphone === "denied" || permission.microphone === "restricted";
|
|
705
|
+
const speechDenied = permission.speech === "denied" || permission.speech === "restricted";
|
|
706
|
+
if (micDenied || engine === "legacy" && speechDenied) {
|
|
707
|
+
return unavailable2("permissionDenied", "Microphone or speech recognition access is off.", {
|
|
708
|
+
kind: "grantPermission",
|
|
709
|
+
detail: "Allow access in System Settings › Privacy & Security."
|
|
710
|
+
});
|
|
711
|
+
}
|
|
712
|
+
const state = engine === "analyzer" ? status.analyzer : status.legacy;
|
|
713
|
+
switch (state) {
|
|
714
|
+
case "available":
|
|
715
|
+
return AVAILABLE2;
|
|
716
|
+
case "needsAssetInstall":
|
|
717
|
+
return unavailable2("modelNotInstalled", `The speech model for ${locale} is not on this Mac yet.`, {
|
|
718
|
+
kind: "installModel",
|
|
719
|
+
detail: "Download the language in Voice settings."
|
|
720
|
+
});
|
|
721
|
+
case "unavailableOS":
|
|
722
|
+
return unavailable2("unsupportedOperatingSystem", "This engine needs a newer macOS.", {
|
|
723
|
+
kind: "upgradeOperatingSystem",
|
|
724
|
+
detail: "Update macOS, or use the compatibility engine."
|
|
725
|
+
});
|
|
726
|
+
case "localeUnsupported":
|
|
727
|
+
return unavailable2("unsupportedLocale", `${locale} is not supported on this Mac.`, {
|
|
728
|
+
kind: "switchLocale",
|
|
729
|
+
detail: "Choose another dictation language."
|
|
730
|
+
});
|
|
731
|
+
default:
|
|
732
|
+
return unavailable2("engineFailed", "Speech recognition is unavailable on this Mac.");
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
async appleVoices(locale) {
|
|
736
|
+
try {
|
|
737
|
+
const voices = await this.once(`voices:${locale}`, () => this.service.voices(this.settings, locale));
|
|
738
|
+
if (voices.some((voice) => voice.provider === APPLE_VOICES_ID))
|
|
739
|
+
return AVAILABLE2;
|
|
740
|
+
const language = locale.split("-")[0];
|
|
741
|
+
const all = await this.once("voices:*", () => this.service.voices(this.settings));
|
|
742
|
+
if (all.some((voice) => voice.provider === APPLE_VOICES_ID && voice.locale.split(/[-_]/)[0] === language)) {
|
|
743
|
+
return AVAILABLE2;
|
|
744
|
+
}
|
|
745
|
+
return unavailable2("unsupportedLocale", `No voice for ${locale} is installed.`, {
|
|
746
|
+
kind: "installModel",
|
|
747
|
+
detail: "Add a voice in System Settings › Accessibility › Spoken Content."
|
|
748
|
+
});
|
|
749
|
+
} catch (error) {
|
|
750
|
+
return helperFailure(error);
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
transcribeStatus(locale) {
|
|
754
|
+
this.service.applyTranscribeFolders(this.settings);
|
|
755
|
+
return this.once(`transcribe:${locale}`, () => this.service.connection("transcribe").request({ cmd: "status", locale }, (event) => event.event === "status", {
|
|
756
|
+
timeoutMs: 60000
|
|
757
|
+
}));
|
|
758
|
+
}
|
|
759
|
+
async transcribe(locale) {
|
|
760
|
+
let status;
|
|
761
|
+
try {
|
|
762
|
+
status = await this.transcribeStatus(locale);
|
|
763
|
+
} catch (error) {
|
|
764
|
+
return helperFailure(error);
|
|
765
|
+
}
|
|
766
|
+
if (status.models.length === 0) {
|
|
767
|
+
return unavailable2("modelNotInstalled", "No transcribe.cpp model was found.", {
|
|
768
|
+
kind: "installModel",
|
|
769
|
+
detail: "Add a folder with a model in Voice settings."
|
|
770
|
+
});
|
|
771
|
+
}
|
|
772
|
+
if (!status.selected) {
|
|
773
|
+
return unavailable2("unsupportedLocale", `No local model supports ${locale}.`, {
|
|
774
|
+
kind: "switchLocale",
|
|
775
|
+
detail: "Choose another language or add a multilingual model."
|
|
776
|
+
});
|
|
777
|
+
}
|
|
778
|
+
return AVAILABLE2;
|
|
779
|
+
}
|
|
780
|
+
async synthesis(locale) {
|
|
781
|
+
try {
|
|
782
|
+
const status = await this.once(`tts:${locale}`, () => this.service.connection("tts").request({ cmd: "status", locale }, (event) => event.event === "status"));
|
|
783
|
+
if (status.ready)
|
|
784
|
+
return AVAILABLE2;
|
|
785
|
+
const reason = status.reason;
|
|
786
|
+
if (reason === "modelNotInstalled") {
|
|
787
|
+
return unavailable2("modelNotInstalled", status.message ?? "No audio.cpp model is installed.", {
|
|
788
|
+
kind: "installModel",
|
|
789
|
+
detail: "Add a voice model in Voice settings."
|
|
790
|
+
});
|
|
791
|
+
}
|
|
792
|
+
if (reason === "unsupportedLocale")
|
|
793
|
+
return unavailable2("unsupportedLocale", status.message ?? `No voice for ${locale}.`);
|
|
794
|
+
if (reason === "unsupportedPlatform")
|
|
795
|
+
return unavailable2("unsupportedPlatform", status.message ?? "Not supported here.");
|
|
796
|
+
return unavailable2("engineFailed", status.message ?? "audio.cpp is unavailable.");
|
|
797
|
+
} catch (error) {
|
|
798
|
+
return helperFailure(error);
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
}
|
|
802
|
+
function withModelChoice(settings) {
|
|
803
|
+
if (settings.stt.provider)
|
|
804
|
+
return settings;
|
|
805
|
+
const model = settings.stt.model;
|
|
806
|
+
if (model !== "analyzer" && model !== "legacy")
|
|
807
|
+
return settings;
|
|
808
|
+
return { ...settings, stt: { ...settings.stt, provider: model === "analyzer" ? APPLE_ANALYZER_ID : APPLE_LEGACY_ID } };
|
|
809
|
+
}
|
|
810
|
+
function helperFailure(error) {
|
|
811
|
+
if (error instanceof IncompatibleHelperError) {
|
|
812
|
+
return unavailable2("contractIncompatible", error.message, {
|
|
813
|
+
kind: "chooseAnotherProvider",
|
|
814
|
+
detail: "Install an app build with a matching voice helper."
|
|
815
|
+
});
|
|
816
|
+
}
|
|
817
|
+
const typed = VoiceError2.wrapping(error);
|
|
818
|
+
return unavailable2("engineFailed", typed.message);
|
|
819
|
+
}
|
|
820
|
+
function unavailableError(decision) {
|
|
821
|
+
const availability = decision.availability;
|
|
822
|
+
if (availability.status === "available")
|
|
823
|
+
return new VoiceError2("unavailable", "No engine can serve this request.");
|
|
824
|
+
const reason = availability.unavailable.reason;
|
|
825
|
+
const code = reason === "permissionDenied" ? "denied" : reason === "unsupportedLocale" ? "language_unsupported" : reason === "modelNotInstalled" || reason === "modelDownloadDisabled" ? "assets_missing" : "unavailable";
|
|
826
|
+
return new VoiceError2(code, availability.unavailable.message);
|
|
827
|
+
}
|
|
828
|
+
function platformOf(os) {
|
|
829
|
+
return os === "darwin" ? "macOS" : os === "win32" ? "windows" : "linux";
|
|
830
|
+
}
|
|
831
|
+
function defaultLocale(chosen) {
|
|
832
|
+
if (chosen)
|
|
833
|
+
return chosen;
|
|
834
|
+
try {
|
|
835
|
+
return Intl.DateTimeFormat().resolvedOptions().locale || "en-US";
|
|
836
|
+
} catch {
|
|
837
|
+
return "en-US";
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
function appleRate(rate) {
|
|
841
|
+
return Math.min(1, Math.max(0.05, rate * 0.5));
|
|
842
|
+
}
|
|
843
|
+
|
|
844
|
+
class DictationSession {
|
|
845
|
+
options;
|
|
846
|
+
provider;
|
|
847
|
+
locale;
|
|
848
|
+
execution = "onDevice";
|
|
849
|
+
result;
|
|
850
|
+
started;
|
|
851
|
+
id = nextRequestId("listen-");
|
|
852
|
+
queue = [];
|
|
853
|
+
waiter;
|
|
854
|
+
terminal;
|
|
855
|
+
consumed = false;
|
|
856
|
+
lastSequence = -1;
|
|
857
|
+
maxTimer;
|
|
858
|
+
graceTimer;
|
|
859
|
+
settle;
|
|
860
|
+
constructor(options) {
|
|
861
|
+
this.options = options;
|
|
862
|
+
this.provider = options.provider;
|
|
863
|
+
this.locale = options.locale;
|
|
864
|
+
this.result = new Promise((resolve, reject) => {
|
|
865
|
+
this.settle = { resolve, reject };
|
|
866
|
+
});
|
|
867
|
+
this.result.catch(() => {
|
|
868
|
+
return;
|
|
869
|
+
});
|
|
870
|
+
let resolveStarted;
|
|
871
|
+
let rejectStarted;
|
|
872
|
+
this.started = new Promise((resolve, reject) => {
|
|
873
|
+
resolveStarted = resolve;
|
|
874
|
+
rejectStarted = reject;
|
|
875
|
+
});
|
|
876
|
+
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", {
|
|
877
|
+
timeoutMs: null,
|
|
878
|
+
onEvent: (event) => {
|
|
879
|
+
if (event.event === "listening")
|
|
880
|
+
resolveStarted();
|
|
881
|
+
if (event.event === "partial")
|
|
882
|
+
this.partial(event.finalizedText, event.volatileText, event.sequence);
|
|
883
|
+
}
|
|
884
|
+
}).then((event) => {
|
|
885
|
+
if (event.event === "final")
|
|
886
|
+
this.finish({ type: "final", text: event.text });
|
|
887
|
+
else if (event.event === "error") {
|
|
888
|
+
this.finish({ type: "failed", error: new VoiceError2(event.code, event.message ?? "Dictation failed.") });
|
|
889
|
+
} else
|
|
890
|
+
this.finish({ type: "cancelled" });
|
|
891
|
+
}, (error) => this.finish({ type: "failed", error: VoiceError2.wrapping(error) })).finally(() => {
|
|
892
|
+
const terminal = this.terminal;
|
|
893
|
+
if (terminal?.type === "failed")
|
|
894
|
+
rejectStarted(terminal.error);
|
|
895
|
+
else if (terminal?.type === "cancelled")
|
|
896
|
+
rejectStarted(new VoiceError2("cancelled", "Dictation was cancelled."));
|
|
897
|
+
else
|
|
898
|
+
resolveStarted();
|
|
899
|
+
});
|
|
900
|
+
this.maxTimer = setTimeout(() => void this.end(), options.maxListenMs);
|
|
901
|
+
}
|
|
902
|
+
get isTerminal() {
|
|
903
|
+
return this.terminal !== undefined;
|
|
904
|
+
}
|
|
905
|
+
events() {
|
|
906
|
+
if (this.consumed)
|
|
907
|
+
throw new VoiceError2("bad_request", "A dictation's events can be read once.");
|
|
908
|
+
this.consumed = true;
|
|
909
|
+
return {
|
|
910
|
+
[Symbol.asyncIterator]: () => ({
|
|
911
|
+
next: () => {
|
|
912
|
+
const next = this.queue.shift();
|
|
913
|
+
if (next)
|
|
914
|
+
return Promise.resolve({ value: next, done: false });
|
|
915
|
+
if (this.terminal && this.queue.length === 0 && this.drained) {
|
|
916
|
+
return Promise.resolve({ value: undefined, done: true });
|
|
917
|
+
}
|
|
918
|
+
return new Promise((resolve) => {
|
|
919
|
+
this.waiter = resolve;
|
|
920
|
+
});
|
|
921
|
+
},
|
|
922
|
+
return: async () => {
|
|
923
|
+
await this.cancel();
|
|
924
|
+
return { value: undefined, done: true };
|
|
925
|
+
}
|
|
926
|
+
})
|
|
927
|
+
};
|
|
928
|
+
}
|
|
929
|
+
drained = false;
|
|
930
|
+
cancelRequested = false;
|
|
931
|
+
async end() {
|
|
932
|
+
if (this.terminal || this.cancelRequested)
|
|
933
|
+
return;
|
|
934
|
+
await this.options.connection.send({ cmd: "listen-end", id: this.id }).catch(() => {
|
|
935
|
+
return;
|
|
936
|
+
});
|
|
937
|
+
this.armGrace();
|
|
938
|
+
}
|
|
939
|
+
async cancel() {
|
|
940
|
+
if (this.terminal)
|
|
941
|
+
return;
|
|
942
|
+
this.cancelRequested = true;
|
|
943
|
+
await this.options.connection.send({ cmd: "listen-cancel", id: this.id }).catch(() => {
|
|
944
|
+
return;
|
|
945
|
+
});
|
|
946
|
+
this.armGrace(true);
|
|
947
|
+
}
|
|
948
|
+
armGrace(cancelling = false) {
|
|
949
|
+
if (this.graceTimer || this.terminal)
|
|
950
|
+
return;
|
|
951
|
+
this.graceTimer = setTimeout(() => {
|
|
952
|
+
if (this.terminal)
|
|
953
|
+
return;
|
|
954
|
+
this.finish(cancelling ? { type: "cancelled" } : { type: "failed", error: new VoiceError2("failed", "The speech engine stopped answering.") });
|
|
955
|
+
this.options.onStuck();
|
|
956
|
+
}, this.options.terminalGraceMs);
|
|
957
|
+
}
|
|
958
|
+
partial(finalizedText, volatileText, sequence) {
|
|
959
|
+
if (this.terminal || sequence <= this.lastSequence)
|
|
960
|
+
return;
|
|
961
|
+
this.lastSequence = sequence;
|
|
962
|
+
const partial = { finalizedText, volatileText, sequence };
|
|
963
|
+
this.options.onPartial?.({ ...partial, text: joinTranscript(finalizedText, volatileText) });
|
|
964
|
+
this.push({ type: "partial", partial });
|
|
965
|
+
}
|
|
966
|
+
finish(event) {
|
|
967
|
+
if (this.terminal)
|
|
968
|
+
return;
|
|
969
|
+
this.terminal = event;
|
|
970
|
+
clearTimeout(this.maxTimer);
|
|
971
|
+
clearTimeout(this.graceTimer);
|
|
972
|
+
this.push(event);
|
|
973
|
+
this.drained = true;
|
|
974
|
+
if (event.type === "final")
|
|
975
|
+
this.settle.resolve(event.text);
|
|
976
|
+
else if (event.type === "cancelled")
|
|
977
|
+
this.settle.reject(new VoiceError2("cancelled", "Dictation was cancelled."));
|
|
978
|
+
else if (event.type === "failed")
|
|
979
|
+
this.settle.reject(event.error);
|
|
980
|
+
queueMicrotask(() => {
|
|
981
|
+
if (this.queue.length === 0 && this.waiter) {
|
|
982
|
+
const waiter = this.waiter;
|
|
983
|
+
this.waiter = undefined;
|
|
984
|
+
waiter({ value: undefined, done: true });
|
|
985
|
+
}
|
|
986
|
+
});
|
|
987
|
+
}
|
|
988
|
+
push(event) {
|
|
989
|
+
if (this.waiter) {
|
|
990
|
+
const waiter = this.waiter;
|
|
991
|
+
this.waiter = undefined;
|
|
992
|
+
waiter({ value: event, done: false });
|
|
993
|
+
return;
|
|
994
|
+
}
|
|
995
|
+
if (event.type === "partial") {
|
|
996
|
+
const last = this.queue.at(-1);
|
|
997
|
+
if (last?.type === "partial")
|
|
998
|
+
this.queue.pop();
|
|
999
|
+
}
|
|
1000
|
+
this.queue.push(event);
|
|
1001
|
+
}
|
|
1002
|
+
}
|
|
1003
|
+
function joinTranscript(finalizedText, volatileText) {
|
|
1004
|
+
if (!finalizedText)
|
|
1005
|
+
return volatileText.trimStart();
|
|
1006
|
+
if (!volatileText)
|
|
1007
|
+
return finalizedText;
|
|
1008
|
+
const needsSpace = !/\s$/.test(finalizedText) && !/^[\s.,;:!?]/.test(volatileText);
|
|
1009
|
+
return needsSpace ? `${finalizedText} ${volatileText}` : `${finalizedText}${volatileText}`;
|
|
1010
|
+
}
|
|
1011
|
+
export {
|
|
1012
|
+
APPLE_ANALYZER_ID,
|
|
1013
|
+
APPLE_LEGACY_ID,
|
|
1014
|
+
APPLE_VOICES_ID,
|
|
1015
|
+
AUDIO_CPP_ID,
|
|
1016
|
+
DESKTOP_DESCRIPTORS,
|
|
1017
|
+
HELPER_LOCK_SCHEMA2 as HELPER_LOCK_SCHEMA,
|
|
1018
|
+
HELPER_NAMES2 as HELPER_NAMES,
|
|
1019
|
+
HELPER_TARGETS2 as HELPER_TARGETS,
|
|
1020
|
+
HelperConnection,
|
|
1021
|
+
HelperLockError2 as HelperLockError,
|
|
1022
|
+
IncompatibleHelperError,
|
|
1023
|
+
LineSplitter,
|
|
1024
|
+
MAX_HELPER_ARCHIVE_BYTES2 as MAX_HELPER_ARCHIVE_BYTES,
|
|
1025
|
+
STAGED_RECORD_FILE2 as STAGED_RECORD_FILE,
|
|
1026
|
+
TRANSCRIBE_CPP_ID,
|
|
1027
|
+
assertHandshake2 as assertHandshake,
|
|
1028
|
+
createDesktopVoice,
|
|
1029
|
+
currentHelperTarget2 as currentHelperTarget,
|
|
1030
|
+
desktopRoutingPolicy,
|
|
1031
|
+
helperArtifactUrl2 as helperArtifactUrl,
|
|
1032
|
+
helperPin2 as helperPin,
|
|
1033
|
+
joinTranscript,
|
|
1034
|
+
nodeSpawner,
|
|
1035
|
+
readHelperLock2 as readHelperLock,
|
|
1036
|
+
readStagedRecord2 as readStagedRecord,
|
|
1037
|
+
sha256File2 as sha256File,
|
|
1038
|
+
stageVoiceHelpers2 as stageVoiceHelpers,
|
|
1039
|
+
validateHelperLock2 as validateHelperLock,
|
|
1040
|
+
verifyStagedVoiceHelpers2 as verifyStagedVoiceHelpers,
|
|
1041
|
+
withModelChoice
|
|
1042
|
+
};
|