@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.
Files changed (52) hide show
  1. package/README.md +51 -2
  2. package/dist/cli/helpers-cli.d.ts +2 -0
  3. package/dist/cli/helpers-cli.js +102 -0
  4. package/dist/contract/contract.d.ts +138 -0
  5. package/dist/contract/errors.d.ts +26 -0
  6. package/dist/contract/index.d.ts +9 -0
  7. package/dist/contract/index.js +54 -0
  8. package/dist/contract/session.d.ts +58 -0
  9. package/dist/contract/wire.d.ts +188 -0
  10. package/dist/desktop/desktop-voice.d.ts +152 -0
  11. package/dist/desktop/helper-lock.d.ts +83 -0
  12. package/dist/desktop/helper-process.d.ts +92 -0
  13. package/dist/desktop/index.d.ts +7 -0
  14. package/dist/desktop/index.js +1042 -0
  15. package/dist/index-9kerqn9r.js +150 -0
  16. package/dist/index-acm1yvvv.js +290 -0
  17. package/dist/index-r4hz8gk0.js +10 -0
  18. package/dist/index-rehs788p.js +42 -0
  19. package/dist/index-s270cw30.js +295 -0
  20. package/dist/index-tvz9s9nz.js +77 -0
  21. package/dist/index.d.ts +7 -0
  22. package/dist/index.js +86 -0
  23. package/dist/settings/index.d.ts +5 -0
  24. package/dist/settings/index.js +34 -0
  25. package/dist/settings/settings.d.ts +163 -0
  26. package/dist/web/index.d.ts +15 -0
  27. package/dist/web/index.js +1287 -0
  28. package/dist/web/stt/speech-recognition.d.ts +105 -0
  29. package/dist/web/tts/phonon.d.ts +139 -0
  30. package/dist/web/tts/player.d.ts +115 -0
  31. package/dist/web/tts/system-voices.d.ts +122 -0
  32. package/dist/web/turns.d.ts +101 -0
  33. package/package.json +68 -4
  34. package/src/cli/helpers-cli.ts +119 -0
  35. package/src/contract/contract.ts +365 -0
  36. package/src/contract/errors.ts +98 -0
  37. package/src/contract/index.ts +9 -0
  38. package/src/contract/session.ts +65 -0
  39. package/src/contract/wire.ts +263 -0
  40. package/src/desktop/desktop-voice.ts +933 -0
  41. package/src/desktop/helper-lock.ts +375 -0
  42. package/src/desktop/helper-process.ts +401 -0
  43. package/src/desktop/index.ts +16 -0
  44. package/src/index.ts +7 -0
  45. package/src/settings/index.ts +5 -0
  46. package/src/settings/settings.ts +478 -0
  47. package/src/web/index.ts +15 -0
  48. package/src/web/stt/speech-recognition.ts +583 -0
  49. package/src/web/tts/phonon.ts +386 -0
  50. package/src/web/tts/player.ts +271 -0
  51. package/src/web/tts/system-voices.ts +401 -0
  52. package/src/web/turns.ts +224 -0
@@ -0,0 +1,401 @@
1
+ /**
2
+ * One persistent helper process (`<helper> --serve`) and the JSON-lines conversation with it.
3
+ *
4
+ * The connection owns the process lifecycle so no host has to: a `--version` handshake before the
5
+ * first command (a helper on another wire or contract major is refused, typed
6
+ * `contractIncompatible`), request/response correlation by `id`, subscribers for a request's
7
+ * streamed events (a listen's partials), a crash that fails every pending request instead of
8
+ * hanging it, a bounded restart budget, and a clean `quit` → drain → kill on dispose.
9
+ */
10
+ import { spawn as spawnProcess } from "node:child_process";
11
+ import { VoiceError } from "../contract/errors";
12
+ import {
13
+ MAX_WIRE_LINE_BYTES,
14
+ correlationId,
15
+ encodeWireCommand,
16
+ isCompatibleHandshake,
17
+ parseWireLine,
18
+ type VersionEvent,
19
+ type WireCommand,
20
+ type WireEvent,
21
+ } from "../contract/wire";
22
+
23
+ /** The few process operations the connection needs; injectable for tests. */
24
+ export interface HelperChild {
25
+ /** Writes one line (the connection adds the newline). Throws once input is closed. */
26
+ write(data: string): void;
27
+ closeInput(): void;
28
+ onStdout(listener: (chunk: string) => void): void;
29
+ onStderr?(listener: (chunk: string) => void): void;
30
+ onExit(listener: (code: number | null, signal: string | null) => void): void;
31
+ kill(signal?: "SIGTERM" | "SIGKILL"): void;
32
+ }
33
+
34
+ export interface HelperSpawnOptions {
35
+ readonly env?: Readonly<Record<string, string | undefined>>;
36
+ }
37
+
38
+ export type HelperSpawner = (path: string, args: readonly string[], options: HelperSpawnOptions) => HelperChild;
39
+
40
+ export interface HelperConnectionOptions {
41
+ readonly path: string;
42
+ readonly spawn: HelperSpawner;
43
+ readonly env?: Readonly<Record<string, string | undefined>>;
44
+ /** How long `--version` may take. Default 5 s. */
45
+ readonly handshakeTimeoutMs?: number;
46
+ /** How long a plain request (status, voices) may take. Default 15 s. */
47
+ readonly requestTimeoutMs?: number;
48
+ /** After `quit`/stdin close, how long the process gets to exit before SIGKILL. Default 2 s. */
49
+ readonly exitGraceMs?: number;
50
+ /** Crashes tolerated inside `crashWindowMs` before the helper is reported unavailable. */
51
+ readonly maxCrashes?: number;
52
+ readonly crashWindowMs?: number;
53
+ readonly log?: (message: string) => void;
54
+ readonly now?: () => number;
55
+ }
56
+
57
+ type Listener = (event: WireEvent) => void;
58
+
59
+ /** A helper on another wire or contract major: refused for the life of the connection. */
60
+ export class IncompatibleHelperError extends VoiceError {
61
+ constructor(message: string) {
62
+ super("unavailable", message);
63
+ this.name = "IncompatibleHelperError";
64
+ }
65
+ }
66
+
67
+ interface Pending {
68
+ readonly listener: Listener;
69
+ readonly fail: (error: VoiceError) => void;
70
+ }
71
+
72
+ /** Splits a stream of text chunks into lines with a hard bound per line. */
73
+ export class LineSplitter {
74
+ private buffer = "";
75
+ private discarding = false;
76
+
77
+ constructor(private readonly limit = MAX_WIRE_LINE_BYTES) {}
78
+
79
+ push(chunk: string): string[] {
80
+ const lines: string[] = [];
81
+ let rest = chunk;
82
+ while (rest.length > 0) {
83
+ const newline = rest.indexOf("\n");
84
+ if (newline === -1) {
85
+ if (!this.discarding) {
86
+ if (this.buffer.length + rest.length > this.limit) {
87
+ this.buffer = "";
88
+ this.discarding = true;
89
+ } else {
90
+ this.buffer += rest;
91
+ }
92
+ }
93
+ break;
94
+ }
95
+ const piece = rest.slice(0, newline);
96
+ rest = rest.slice(newline + 1);
97
+ if (this.discarding) {
98
+ this.discarding = false;
99
+ this.buffer = "";
100
+ continue;
101
+ }
102
+ const line = (this.buffer + piece).replace(/\r$/, "");
103
+ this.buffer = "";
104
+ if (line.length <= this.limit && line.length > 0) lines.push(line);
105
+ }
106
+ return lines;
107
+ }
108
+ }
109
+
110
+ let requestCounter = 0;
111
+ /** A process-unique request id. */
112
+ export function nextRequestId(prefix = "r"): string {
113
+ requestCounter = (requestCounter + 1) % Number.MAX_SAFE_INTEGER;
114
+ return `${prefix}${requestCounter.toString(36)}`;
115
+ }
116
+
117
+ export class HelperConnection {
118
+ private child: HelperChild | undefined;
119
+ private starting: Promise<HelperChild> | undefined;
120
+ private handshake: VersionEvent | undefined;
121
+ private readonly pending = new Map<string, Pending>();
122
+ private readonly broadcast = new Set<Listener>();
123
+ private crashes: number[] = [];
124
+ private disposed = false;
125
+ private incompatible: VoiceError | undefined;
126
+
127
+ constructor(private readonly options: HelperConnectionOptions) {}
128
+
129
+ /** The handshake the running helper answered, once it has started. */
130
+ get version(): VersionEvent | undefined {
131
+ return this.handshake;
132
+ }
133
+
134
+ /** Receives every event, correlated or not (speech-state, route changes). */
135
+ onEvent(listener: Listener): () => void {
136
+ this.broadcast.add(listener);
137
+ return () => this.broadcast.delete(listener);
138
+ }
139
+
140
+ /**
141
+ * Sends a command and resolves with the first event `isDone` accepts (also delivering every
142
+ * correlated event to `onEvent`). Rejects with a typed `VoiceError` on a helper `error` event
143
+ * (unless `isDone` accepts it), a crash, the timeout, or `signal`.
144
+ */
145
+ async request<T extends WireEvent>(
146
+ command: WireCommand,
147
+ isDone: (event: WireEvent) => event is T,
148
+ options: { readonly timeoutMs?: number | null; readonly onEvent?: Listener; readonly signal?: AbortSignal } = {},
149
+ ): Promise<T> {
150
+ const id = command.id ?? nextRequestId();
151
+ const child = await this.ensureStarted();
152
+ return await new Promise<T>((resolve, reject) => {
153
+ let timer: ReturnType<typeof setTimeout> | undefined;
154
+ const finish = (outcome: () => void) => {
155
+ if (!this.pending.has(id)) return;
156
+ this.pending.delete(id);
157
+ if (timer) clearTimeout(timer);
158
+ options.signal?.removeEventListener("abort", onAbort);
159
+ outcome();
160
+ };
161
+ const onAbort = () => finish(() => reject(new VoiceError("cancelled", "request aborted")));
162
+ if (options.signal?.aborted) return reject(new VoiceError("cancelled", "request aborted"));
163
+ options.signal?.addEventListener("abort", onAbort, { once: true });
164
+ this.pending.set(id, {
165
+ fail: (error) => finish(() => reject(error)),
166
+ listener: (event) => {
167
+ options.onEvent?.(event);
168
+ if (isDone(event)) return finish(() => resolve(event));
169
+ if (event.event === "error") {
170
+ return finish(() => reject(new VoiceError(event.code, event.message ?? `helper refused ${command.cmd}`)));
171
+ }
172
+ },
173
+ });
174
+ const timeoutMs = options.timeoutMs === undefined ? this.options.requestTimeoutMs ?? 15_000 : options.timeoutMs;
175
+ if (timeoutMs !== null) {
176
+ timer = setTimeout(
177
+ () => finish(() => reject(new VoiceError("failed", `${command.cmd} timed out after ${timeoutMs} ms`))),
178
+ timeoutMs,
179
+ );
180
+ }
181
+ try {
182
+ child.write(`${encodeWireCommand({ ...command, id })}\n`);
183
+ } catch (error) {
184
+ finish(() => reject(new VoiceError("failed", `could not reach the helper: ${String(error)}`)));
185
+ }
186
+ });
187
+ }
188
+
189
+ /** Sends a command that has no correlated answer (speech-stop). */
190
+ async send(command: WireCommand): Promise<void> {
191
+ const child = await this.ensureStarted();
192
+ try {
193
+ child.write(`${encodeWireCommand(command)}\n`);
194
+ } catch (error) {
195
+ throw new VoiceError("failed", `could not reach the helper: ${String(error)}`);
196
+ }
197
+ }
198
+
199
+ /** Whether a process is running now. */
200
+ get running(): boolean {
201
+ return this.child !== undefined;
202
+ }
203
+
204
+ /**
205
+ * Stops the helper: `quit`, close stdin, then SIGTERM/SIGKILL after the grace period. Requests
206
+ * still waiting on this process are failed (`cancelled`): its exit is not reported as a crash,
207
+ * so nothing else would ever settle them.
208
+ */
209
+ async stop(): Promise<void> {
210
+ const child = this.child ?? (await this.starting?.catch(() => undefined));
211
+ this.child = undefined;
212
+ this.starting = undefined;
213
+ if (!child) return;
214
+ this.failAll(new VoiceError("cancelled", "the voice helper was stopped"));
215
+ await new Promise<void>((resolve) => {
216
+ let exited = false;
217
+ child.onExit(() => {
218
+ exited = true;
219
+ resolve();
220
+ });
221
+ try {
222
+ child.write(`${encodeWireCommand({ cmd: "quit" })}\n`);
223
+ child.closeInput();
224
+ } catch {
225
+ // already gone
226
+ }
227
+ const grace = this.options.exitGraceMs ?? 2_000;
228
+ setTimeout(() => {
229
+ if (exited) return;
230
+ child.kill("SIGTERM");
231
+ setTimeout(() => {
232
+ if (!exited) child.kill("SIGKILL");
233
+ resolve();
234
+ }, grace).unref?.();
235
+ }, grace).unref?.();
236
+ });
237
+ }
238
+
239
+ async dispose(): Promise<void> {
240
+ this.disposed = true;
241
+ await this.stop();
242
+ this.failAll(new VoiceError("cancelled", "the voice helper was shut down"));
243
+ }
244
+
245
+ // MARK: - Process
246
+
247
+ private async ensureStarted(): Promise<HelperChild> {
248
+ if (this.disposed) throw new VoiceError("unavailable", "the voice helper was shut down");
249
+ if (this.incompatible) throw this.incompatible;
250
+ if (this.child) return this.child;
251
+ if (!this.starting) {
252
+ this.starting = this.start().finally(() => {
253
+ this.starting = undefined;
254
+ });
255
+ }
256
+ return await this.starting;
257
+ }
258
+
259
+ private async start(): Promise<HelperChild> {
260
+ const now = this.options.now ?? Date.now;
261
+ const window = this.options.crashWindowMs ?? 60_000;
262
+ this.crashes = this.crashes.filter((at) => now() - at < window);
263
+ if (this.crashes.length >= (this.options.maxCrashes ?? 3)) {
264
+ throw new VoiceError("unavailable", "the voice helper keeps crashing; restart the app to try again");
265
+ }
266
+ let version: VersionEvent;
267
+ try {
268
+ version = await this.versionHandshake();
269
+ } catch (error) {
270
+ // A helper that cannot even answer its handshake counts toward the crash budget, so a
271
+ // broken binary is not re-spawned on every request.
272
+ this.crashes.push(now());
273
+ throw error;
274
+ }
275
+ if (!isCompatibleHandshake(version)) {
276
+ this.incompatible = new IncompatibleHelperError(
277
+ `voice helper speaks wire ${version.wire} / contract ${version.contract}; this app needs wire 1 / contract 1`,
278
+ );
279
+ throw this.incompatible;
280
+ }
281
+ this.handshake = version;
282
+ const child = this.options.spawn(this.options.path, ["--serve"], { env: this.options.env });
283
+ const splitter = new LineSplitter();
284
+ child.onStdout((chunk) => {
285
+ for (const line of splitter.push(chunk)) this.dispatch(line);
286
+ });
287
+ child.onStderr?.((chunk) => this.options.log?.(`voice helper: ${chunk.trimEnd().slice(0, 500)}`));
288
+ child.onExit((code, signal) => {
289
+ if (this.child !== child) return;
290
+ this.child = undefined;
291
+ if (!this.disposed) this.crashes.push(now());
292
+ this.failAll(
293
+ new VoiceError("failed", `the voice helper exited (${signal ?? `code ${String(code)}`}); it restarts on the next request`),
294
+ );
295
+ });
296
+ this.child = child;
297
+ return child;
298
+ }
299
+
300
+ private async versionHandshake(): Promise<VersionEvent> {
301
+ const child = this.options.spawn(this.options.path, ["--version"], { env: this.options.env });
302
+ const splitter = new LineSplitter();
303
+ return await new Promise<VersionEvent>((resolve, reject) => {
304
+ let settled = false;
305
+ const settle = (outcome: () => void) => {
306
+ if (settled) return;
307
+ settled = true;
308
+ clearTimeout(timer);
309
+ outcome();
310
+ };
311
+ const timer = setTimeout(() => {
312
+ settle(() => reject(new VoiceError("unavailable", "the voice helper did not answer its version handshake")));
313
+ child.kill("SIGKILL");
314
+ }, this.options.handshakeTimeoutMs ?? 5_000);
315
+ child.onStdout((chunk) => {
316
+ for (const line of splitter.push(chunk)) {
317
+ const event = parseWireLine(line);
318
+ if (event?.event === "version") settle(() => resolve(event));
319
+ }
320
+ });
321
+ child.onExit((code) => {
322
+ settle(() => reject(new VoiceError("unavailable", `the voice helper failed to start (exit ${String(code)})`)));
323
+ });
324
+ try {
325
+ child.closeInput();
326
+ } catch {
327
+ // no stdin; fine
328
+ }
329
+ });
330
+ }
331
+
332
+ private dispatch(line: string): void {
333
+ const event = parseWireLine(line);
334
+ if (!event) {
335
+ this.options.log?.(`voice helper: ignored a malformed line (${line.slice(0, 80)})`);
336
+ return;
337
+ }
338
+ const id = correlationId(event);
339
+ if (id !== undefined) this.pending.get(id)?.listener(event);
340
+ for (const listener of this.broadcast) listener(event);
341
+ }
342
+
343
+ private failAll(error: VoiceError): void {
344
+ const pending = [...this.pending.values()];
345
+ for (const entry of pending) entry.fail(error);
346
+ }
347
+ }
348
+
349
+ /** The default spawner: `node:child_process`, which Bun implements. */
350
+ export const nodeSpawner: HelperSpawner = (path, args, options) => {
351
+ {
352
+ const spawn = spawnProcess;
353
+ const env: Record<string, string> = {};
354
+ for (const [key, value] of Object.entries({ ...process.env, ...options.env })) {
355
+ if (value !== undefined) env[key] = value;
356
+ }
357
+ const child = spawn(path, [...args], { stdio: ["pipe", "pipe", "pipe"], env });
358
+ child.stdout?.setEncoding("utf8");
359
+ child.stderr?.setEncoding("utf8");
360
+ // A helper that exits mid-write must not crash the host with EPIPE.
361
+ child.stdin?.on("error", () => undefined);
362
+ let closed: [number | null, string | null] | undefined;
363
+ const exitListeners: Array<(code: number | null, signal: string | null) => void> = [];
364
+ const settle = (code: number | null, signal: string | null) => {
365
+ if (closed) return;
366
+ closed = [code, signal];
367
+ for (const listener of exitListeners.splice(0)) listener(code, signal);
368
+ };
369
+ child.once("close", (code: number | null, signal: string | null) => settle(code, signal));
370
+ // A spawn failure (ENOENT, EACCES) may emit `error` without `close`.
371
+ child.once("error", () => settle(-1, null));
372
+ return {
373
+ write(data) {
374
+ if (!child.stdin || child.stdin.destroyed || !child.stdin.writable) throw new Error("stdin closed");
375
+ child.stdin.write(data);
376
+ },
377
+ closeInput() {
378
+ child.stdin?.end();
379
+ },
380
+ onStdout(listener) {
381
+ child.stdout?.on("data", (chunk: string) => listener(chunk));
382
+ },
383
+ onStderr(listener) {
384
+ child.stderr?.on("data", (chunk: string) => listener(chunk));
385
+ },
386
+ onExit(listener) {
387
+ // `close`, not `exit`: `exit` can fire before stdout is drained, which would drop a
388
+ // `--version` line printed just before a fast exit (and fail the handshake).
389
+ if (closed) {
390
+ const [code, signal] = closed;
391
+ queueMicrotask(() => listener(code, signal));
392
+ return;
393
+ }
394
+ exitListeners.push(listener);
395
+ },
396
+ kill(signal = "SIGTERM") {
397
+ child.kill(signal);
398
+ },
399
+ };
400
+ }
401
+ };
@@ -0,0 +1,16 @@
1
+ /**
2
+ * `@adea-ai/voice/desktop`: the Bun/Node client for the pinned desktop speech helpers. Import it
3
+ * from a desktop shell process only (it spawns processes); a renderer talks to the shell.
4
+ */
5
+ export * from "./desktop-voice";
6
+ export {
7
+ HelperConnection,
8
+ IncompatibleHelperError,
9
+ LineSplitter,
10
+ nodeSpawner,
11
+ type HelperChild,
12
+ type HelperConnectionOptions,
13
+ type HelperSpawnOptions,
14
+ type HelperSpawner,
15
+ } from "./helper-process";
16
+ export * from "./helper-lock";
package/src/index.ts ADDED
@@ -0,0 +1,7 @@
1
+ /**
2
+ * `@adea-ai/voice`: the root entry re-exports the platform-neutral parts (contract and settings).
3
+ * Platform code lives on its own subpath so a browser bundle never pulls in `node:child_process`
4
+ * and a desktop shell never pulls in Web Audio: `@adea-ai/voice/web`, `@adea-ai/voice/desktop`.
5
+ */
6
+ export * from "./contract/index";
7
+ export * from "./settings/index";
@@ -0,0 +1,5 @@
1
+ /**
2
+ * `@adea-ai/voice/settings`: the unified, versioned, per-device Voice settings (#32). Pure: it
3
+ * validates, migrates and serialises, and persists only through the storage a host hands it.
4
+ */
5
+ export * from "./settings";