@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,408 @@
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
+ /** Names the helper in errors and logs, e.g. `adea-transcribe-helper`. Default "voice helper". */
43
+ readonly name?: string;
44
+ readonly spawn: HelperSpawner;
45
+ readonly env?: Readonly<Record<string, string | undefined>>;
46
+ /** How long `--version` may take. Default 5 s. */
47
+ readonly handshakeTimeoutMs?: number;
48
+ /** How long a plain request (status, voices) may take. Default 15 s. */
49
+ readonly requestTimeoutMs?: number;
50
+ /** After `quit`/stdin close, how long the process gets to exit before SIGKILL. Default 2 s. */
51
+ readonly exitGraceMs?: number;
52
+ /** Crashes tolerated inside `crashWindowMs` before the helper is reported unavailable. */
53
+ readonly maxCrashes?: number;
54
+ readonly crashWindowMs?: number;
55
+ readonly log?: (message: string) => void;
56
+ readonly now?: () => number;
57
+ }
58
+
59
+ type Listener = (event: WireEvent) => void;
60
+
61
+ /** A helper on another wire or contract major: refused for the life of the connection. */
62
+ export class IncompatibleHelperError extends VoiceError {
63
+ constructor(message: string) {
64
+ super("unavailable", message);
65
+ this.name = "IncompatibleHelperError";
66
+ }
67
+ }
68
+
69
+ interface Pending {
70
+ readonly listener: Listener;
71
+ readonly fail: (error: VoiceError) => void;
72
+ }
73
+
74
+ /** Splits a stream of text chunks into lines with a hard bound per line. */
75
+ export class LineSplitter {
76
+ private buffer = "";
77
+ private discarding = false;
78
+
79
+ constructor(private readonly limit = MAX_WIRE_LINE_BYTES) {}
80
+
81
+ push(chunk: string): string[] {
82
+ const lines: string[] = [];
83
+ let rest = chunk;
84
+ while (rest.length > 0) {
85
+ const newline = rest.indexOf("\n");
86
+ if (newline === -1) {
87
+ if (!this.discarding) {
88
+ if (this.buffer.length + rest.length > this.limit) {
89
+ this.buffer = "";
90
+ this.discarding = true;
91
+ } else {
92
+ this.buffer += rest;
93
+ }
94
+ }
95
+ break;
96
+ }
97
+ const piece = rest.slice(0, newline);
98
+ rest = rest.slice(newline + 1);
99
+ if (this.discarding) {
100
+ this.discarding = false;
101
+ this.buffer = "";
102
+ continue;
103
+ }
104
+ const line = (this.buffer + piece).replace(/\r$/, "");
105
+ this.buffer = "";
106
+ if (line.length <= this.limit && line.length > 0) lines.push(line);
107
+ }
108
+ return lines;
109
+ }
110
+ }
111
+
112
+ let requestCounter = 0;
113
+ /** A process-unique request id. */
114
+ export function nextRequestId(prefix = "r"): string {
115
+ requestCounter = (requestCounter + 1) % Number.MAX_SAFE_INTEGER;
116
+ return `${prefix}${requestCounter.toString(36)}`;
117
+ }
118
+
119
+ export class HelperConnection {
120
+ private child: HelperChild | undefined;
121
+ private starting: Promise<HelperChild> | undefined;
122
+ private handshake: VersionEvent | undefined;
123
+ private readonly pending = new Map<string, Pending>();
124
+ private readonly broadcast = new Set<Listener>();
125
+ private crashes: number[] = [];
126
+ private disposed = false;
127
+ private incompatible: VoiceError | undefined;
128
+
129
+ constructor(private readonly options: HelperConnectionOptions) {}
130
+
131
+ /** "the voice helper", or the configured helper name. */
132
+ private get label(): string {
133
+ return this.options.name ?? "the voice helper";
134
+ }
135
+
136
+ /** The handshake the running helper answered, once it has started. */
137
+ get version(): VersionEvent | undefined {
138
+ return this.handshake;
139
+ }
140
+
141
+ /** Receives every event, correlated or not (speech-state, route changes). */
142
+ onEvent(listener: Listener): () => void {
143
+ this.broadcast.add(listener);
144
+ return () => this.broadcast.delete(listener);
145
+ }
146
+
147
+ /**
148
+ * Sends a command and resolves with the first event `isDone` accepts (also delivering every
149
+ * correlated event to `onEvent`). Rejects with a typed `VoiceError` on a helper `error` event
150
+ * (unless `isDone` accepts it), a crash, the timeout, or `signal`.
151
+ */
152
+ async request<T extends WireEvent>(
153
+ command: WireCommand,
154
+ isDone: (event: WireEvent) => event is T,
155
+ options: { readonly timeoutMs?: number | null; readonly onEvent?: Listener; readonly signal?: AbortSignal } = {},
156
+ ): Promise<T> {
157
+ const id = command.id ?? nextRequestId();
158
+ const child = await this.ensureStarted();
159
+ return await new Promise<T>((resolve, reject) => {
160
+ let timer: ReturnType<typeof setTimeout> | undefined;
161
+ const finish = (outcome: () => void) => {
162
+ if (!this.pending.has(id)) return;
163
+ this.pending.delete(id);
164
+ if (timer) clearTimeout(timer);
165
+ options.signal?.removeEventListener("abort", onAbort);
166
+ outcome();
167
+ };
168
+ const onAbort = () => finish(() => reject(new VoiceError("cancelled", "request aborted")));
169
+ if (options.signal?.aborted) return reject(new VoiceError("cancelled", "request aborted"));
170
+ options.signal?.addEventListener("abort", onAbort, { once: true });
171
+ this.pending.set(id, {
172
+ fail: (error) => finish(() => reject(error)),
173
+ listener: (event) => {
174
+ options.onEvent?.(event);
175
+ if (isDone(event)) return finish(() => resolve(event));
176
+ if (event.event === "error") {
177
+ return finish(() => reject(new VoiceError(event.code, event.message ?? `helper refused ${command.cmd}`)));
178
+ }
179
+ },
180
+ });
181
+ const timeoutMs = options.timeoutMs === undefined ? this.options.requestTimeoutMs ?? 15_000 : options.timeoutMs;
182
+ if (timeoutMs !== null) {
183
+ timer = setTimeout(
184
+ () => finish(() => reject(new VoiceError("failed", `${command.cmd} timed out after ${timeoutMs} ms`))),
185
+ timeoutMs,
186
+ );
187
+ }
188
+ try {
189
+ child.write(`${encodeWireCommand({ ...command, id })}\n`);
190
+ } catch (error) {
191
+ finish(() => reject(new VoiceError("failed", `could not reach the helper: ${String(error)}`)));
192
+ }
193
+ });
194
+ }
195
+
196
+ /** Sends a command that has no correlated answer (speech-stop). */
197
+ async send(command: WireCommand): Promise<void> {
198
+ const child = await this.ensureStarted();
199
+ try {
200
+ child.write(`${encodeWireCommand(command)}\n`);
201
+ } catch (error) {
202
+ throw new VoiceError("failed", `could not reach the helper: ${String(error)}`);
203
+ }
204
+ }
205
+
206
+ /** Whether a process is running now. */
207
+ get running(): boolean {
208
+ return this.child !== undefined;
209
+ }
210
+
211
+ /**
212
+ * Stops the helper: `quit`, close stdin, then SIGTERM/SIGKILL after the grace period. Requests
213
+ * still waiting on this process are failed (`cancelled`): its exit is not reported as a crash,
214
+ * so nothing else would ever settle them.
215
+ */
216
+ async stop(): Promise<void> {
217
+ const child = this.child ?? (await this.starting?.catch(() => undefined));
218
+ this.child = undefined;
219
+ this.starting = undefined;
220
+ if (!child) return;
221
+ this.failAll(new VoiceError("cancelled", `${this.label} was stopped`));
222
+ await new Promise<void>((resolve) => {
223
+ let exited = false;
224
+ child.onExit(() => {
225
+ exited = true;
226
+ resolve();
227
+ });
228
+ try {
229
+ child.write(`${encodeWireCommand({ cmd: "quit" })}\n`);
230
+ child.closeInput();
231
+ } catch {
232
+ // already gone
233
+ }
234
+ const grace = this.options.exitGraceMs ?? 2_000;
235
+ setTimeout(() => {
236
+ if (exited) return;
237
+ child.kill("SIGTERM");
238
+ setTimeout(() => {
239
+ if (!exited) child.kill("SIGKILL");
240
+ resolve();
241
+ }, grace).unref?.();
242
+ }, grace).unref?.();
243
+ });
244
+ }
245
+
246
+ async dispose(): Promise<void> {
247
+ this.disposed = true;
248
+ await this.stop();
249
+ this.failAll(new VoiceError("cancelled", `${this.label} was shut down`));
250
+ }
251
+
252
+ // MARK: - Process
253
+
254
+ private async ensureStarted(): Promise<HelperChild> {
255
+ if (this.disposed) throw new VoiceError("unavailable", `${this.label} was shut down`);
256
+ if (this.incompatible) throw this.incompatible;
257
+ if (this.child) return this.child;
258
+ if (!this.starting) {
259
+ this.starting = this.start().finally(() => {
260
+ this.starting = undefined;
261
+ });
262
+ }
263
+ return await this.starting;
264
+ }
265
+
266
+ private async start(): Promise<HelperChild> {
267
+ const now = this.options.now ?? Date.now;
268
+ const window = this.options.crashWindowMs ?? 60_000;
269
+ this.crashes = this.crashes.filter((at) => now() - at < window);
270
+ if (this.crashes.length >= (this.options.maxCrashes ?? 3)) {
271
+ throw new VoiceError("unavailable", `${this.label} keeps crashing; restart the app to try again`);
272
+ }
273
+ let version: VersionEvent;
274
+ try {
275
+ version = await this.versionHandshake();
276
+ } catch (error) {
277
+ // A helper that cannot even answer its handshake counts toward the crash budget, so a
278
+ // broken binary is not re-spawned on every request.
279
+ this.crashes.push(now());
280
+ throw error;
281
+ }
282
+ if (!isCompatibleHandshake(version)) {
283
+ this.incompatible = new IncompatibleHelperError(
284
+ `${this.options.name ?? "voice helper"} speaks wire ${version.wire} / contract ${version.contract}; this app needs wire 1 / contract 1`,
285
+ );
286
+ throw this.incompatible;
287
+ }
288
+ this.handshake = version;
289
+ const child = this.options.spawn(this.options.path, ["--serve"], { env: this.options.env });
290
+ const splitter = new LineSplitter();
291
+ child.onStdout((chunk) => {
292
+ for (const line of splitter.push(chunk)) this.dispatch(line);
293
+ });
294
+ child.onStderr?.((chunk) => this.options.log?.(`${this.options.name ?? "voice helper"}: ${chunk.trimEnd().slice(0, 500)}`));
295
+ child.onExit((code, signal) => {
296
+ if (this.child !== child) return;
297
+ this.child = undefined;
298
+ if (!this.disposed) this.crashes.push(now());
299
+ this.failAll(
300
+ new VoiceError("failed", `${this.label} exited (${signal ?? `code ${String(code)}`}); it restarts on the next request`),
301
+ );
302
+ });
303
+ this.child = child;
304
+ return child;
305
+ }
306
+
307
+ private async versionHandshake(): Promise<VersionEvent> {
308
+ const child = this.options.spawn(this.options.path, ["--version"], { env: this.options.env });
309
+ const splitter = new LineSplitter();
310
+ return await new Promise<VersionEvent>((resolve, reject) => {
311
+ let settled = false;
312
+ const settle = (outcome: () => void) => {
313
+ if (settled) return;
314
+ settled = true;
315
+ clearTimeout(timer);
316
+ outcome();
317
+ };
318
+ const timer = setTimeout(() => {
319
+ settle(() => reject(new VoiceError("unavailable", `${this.label} did not answer its version handshake`)));
320
+ child.kill("SIGKILL");
321
+ }, this.options.handshakeTimeoutMs ?? 5_000);
322
+ child.onStdout((chunk) => {
323
+ for (const line of splitter.push(chunk)) {
324
+ const event = parseWireLine(line);
325
+ if (event?.event === "version") settle(() => resolve(event));
326
+ }
327
+ });
328
+ child.onExit((code) => {
329
+ settle(() => reject(new VoiceError("unavailable", `${this.label} failed to start (exit ${String(code)})`)));
330
+ });
331
+ try {
332
+ child.closeInput();
333
+ } catch {
334
+ // no stdin; fine
335
+ }
336
+ });
337
+ }
338
+
339
+ private dispatch(line: string): void {
340
+ const event = parseWireLine(line);
341
+ if (!event) {
342
+ this.options.log?.(`${this.options.name ?? "voice helper"}: ignored a malformed line (${line.slice(0, 80)})`);
343
+ return;
344
+ }
345
+ const id = correlationId(event);
346
+ if (id !== undefined) this.pending.get(id)?.listener(event);
347
+ for (const listener of this.broadcast) listener(event);
348
+ }
349
+
350
+ private failAll(error: VoiceError): void {
351
+ const pending = [...this.pending.values()];
352
+ for (const entry of pending) entry.fail(error);
353
+ }
354
+ }
355
+
356
+ /** The default spawner: `node:child_process`, which Bun implements. */
357
+ export const nodeSpawner: HelperSpawner = (path, args, options) => {
358
+ {
359
+ const spawn = spawnProcess;
360
+ const env: Record<string, string> = {};
361
+ for (const [key, value] of Object.entries({ ...process.env, ...options.env })) {
362
+ if (value !== undefined) env[key] = value;
363
+ }
364
+ const child = spawn(path, [...args], { stdio: ["pipe", "pipe", "pipe"], env });
365
+ child.stdout?.setEncoding("utf8");
366
+ child.stderr?.setEncoding("utf8");
367
+ // A helper that exits mid-write must not crash the host with EPIPE.
368
+ child.stdin?.on("error", () => undefined);
369
+ let closed: [number | null, string | null] | undefined;
370
+ const exitListeners: Array<(code: number | null, signal: string | null) => void> = [];
371
+ const settle = (code: number | null, signal: string | null) => {
372
+ if (closed) return;
373
+ closed = [code, signal];
374
+ for (const listener of exitListeners.splice(0)) listener(code, signal);
375
+ };
376
+ child.once("close", (code: number | null, signal: string | null) => settle(code, signal));
377
+ // A spawn failure (ENOENT, EACCES) may emit `error` without `close`.
378
+ child.once("error", () => settle(-1, null));
379
+ return {
380
+ write(data) {
381
+ if (!child.stdin || child.stdin.destroyed || !child.stdin.writable) throw new Error("stdin closed");
382
+ child.stdin.write(data);
383
+ },
384
+ closeInput() {
385
+ child.stdin?.end();
386
+ },
387
+ onStdout(listener) {
388
+ child.stdout?.on("data", (chunk: string) => listener(chunk));
389
+ },
390
+ onStderr(listener) {
391
+ child.stderr?.on("data", (chunk: string) => listener(chunk));
392
+ },
393
+ onExit(listener) {
394
+ // `close`, not `exit`: `exit` can fire before stdout is drained, which would drop a
395
+ // `--version` line printed just before a fast exit (and fail the handshake).
396
+ if (closed) {
397
+ const [code, signal] = closed;
398
+ queueMicrotask(() => listener(code, signal));
399
+ return;
400
+ }
401
+ exitListeners.push(listener);
402
+ },
403
+ kill(signal = "SIGTERM") {
404
+ child.kill(signal);
405
+ },
406
+ };
407
+ }
408
+ };
@@ -0,0 +1,18 @@
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 type { ConversationRespondOptions, DesktopConversation } from "./conversation";
7
+ export {
8
+ HelperConnection,
9
+ IncompatibleHelperError,
10
+ LineSplitter,
11
+ nodeSpawner,
12
+ type HelperChild,
13
+ type HelperConnectionOptions,
14
+ type HelperSpawnOptions,
15
+ type HelperSpawner,
16
+ } from "./helper-process";
17
+ export * from "./helper-lock";
18
+ export { isMachO, machoCodeDigest, machoCodeDigestFile } from "./macho-digest";
@@ -0,0 +1,135 @@
1
+ /**
2
+ * A digest of a Mach-O file's code that does not change when the file is signed again.
3
+ *
4
+ * A host app's release build signs every nested executable again (its own identity, the hardened
5
+ * runtime), so the packaged helper's file sha256 never equals the one the lock pins. This digest
6
+ * covers everything except the code signature: the signature blob, the `LC_CODE_SIGNATURE` load
7
+ * command that points at it, the `__LINKEDIT` sizes that grow with it, and trailing zero padding
8
+ * are left out. Any other byte that differs, code or data, changes it.
9
+ *
10
+ * Handles thin 64-bit little-endian images with the signature command anywhere in the table (the
11
+ * transcribe helper gains rpaths after it was first signed, so its signature command is not last),
12
+ * and universal (fat) files, whose slices are digested one by one: re-signing moves slices, so the
13
+ * fat header's offsets and sizes are not part of the digest.
14
+ *
15
+ * For a thin image whose signature command is last, the result equals the digest Adea's
16
+ * `macho-code-digest.mjs` computes for Herdr Core.
17
+ */
18
+ import { createHash } from "node:crypto";
19
+ import { readFileSync } from "node:fs";
20
+
21
+ const MH_MAGIC_64 = 0xfeedfacf;
22
+ const FAT_MAGIC = 0xcafebabe;
23
+ const FAT_MAGIC_64 = 0xcafebabf;
24
+ const LC_SEGMENT_64 = 0x19;
25
+ const LC_CODE_SIGNATURE = 0x1d;
26
+ const HEADER_SIZE = 32;
27
+ const SIGNATURE_COMMAND_SIZE = 16;
28
+ /** More slices than this is not a Mach-O universal file (Java class files share the magic). */
29
+ const MAX_FAT_ARCHS = 16;
30
+
31
+ /** True when `bytes` starts like a Mach-O image or a universal file. */
32
+ export function isMachO(bytes: Uint8Array): boolean {
33
+ if (bytes.byteLength < 8) return false;
34
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
35
+ const little = view.getUint32(0, true);
36
+ if (little === MH_MAGIC_64 || little === 0xfeedface) return true;
37
+ const big = view.getUint32(0, false);
38
+ return (big === FAT_MAGIC || big === FAT_MAGIC_64) && view.getUint32(4, false) > 0 && view.getUint32(4, false) <= MAX_FAT_ARCHS;
39
+ }
40
+
41
+ /**
42
+ * The sha256 (hex) of a Mach-O file with its code signature left out, or `undefined` for a file
43
+ * this cannot digest (not Mach-O, 32-bit, big-endian, or malformed).
44
+ */
45
+ export function machoCodeDigest(bytes: Uint8Array): string | undefined {
46
+ if (bytes.byteLength < 8) return undefined;
47
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
48
+ const magic = view.getUint32(0, false);
49
+ if (magic === FAT_MAGIC || magic === FAT_MAGIC_64) return fatDigest(bytes, view, magic === FAT_MAGIC_64);
50
+ return thinDigest(bytes);
51
+ }
52
+
53
+ /** `machoCodeDigest` of a file on disk. */
54
+ export function machoCodeDigestFile(path: string): string | undefined {
55
+ return machoCodeDigest(new Uint8Array(readFileSync(path)));
56
+ }
57
+
58
+ function fatDigest(bytes: Uint8Array, view: DataView, wide: boolean): string | undefined {
59
+ const count = view.getUint32(4, false);
60
+ if (count === 0 || count > MAX_FAT_ARCHS) return undefined;
61
+ const entrySize = wide ? 32 : 20;
62
+ if (8 + count * entrySize > bytes.byteLength) return undefined;
63
+ const lines: string[] = [];
64
+ for (let index = 0; index < count; index += 1) {
65
+ const at = 8 + index * entrySize;
66
+ const cpuType = view.getUint32(at, false);
67
+ const cpuSubtype = view.getUint32(at + 4, false);
68
+ const offset = wide ? Number(view.getBigUint64(at + 8, false)) : view.getUint32(at + 8, false);
69
+ const size = wide ? Number(view.getBigUint64(at + 16, false)) : view.getUint32(at + 12, false);
70
+ if (offset + size > bytes.byteLength || size < HEADER_SIZE) return undefined;
71
+ const slice = thinDigest(bytes.subarray(offset, offset + size));
72
+ if (!slice) return undefined;
73
+ lines.push(`${cpuType}:${cpuSubtype}:${slice}\n`);
74
+ }
75
+ lines.sort();
76
+ return createHash("sha256").update(`fat\n${lines.join("")}`).digest("hex");
77
+ }
78
+
79
+ function thinDigest(bytes: Uint8Array): string | undefined {
80
+ if (bytes.byteLength < HEADER_SIZE) return undefined;
81
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
82
+ if (view.getUint32(0, true) !== MH_MAGIC_64) return undefined;
83
+ const commandCount = view.getUint32(16, true);
84
+ const commandsSize = view.getUint32(20, true);
85
+ const commandsEnd = HEADER_SIZE + commandsSize;
86
+ if (commandsEnd > bytes.byteLength) return undefined;
87
+
88
+ let signature: { offset: number; dataOffset: number } | undefined;
89
+ const linkedit: number[] = [];
90
+ let offset = HEADER_SIZE;
91
+ for (let index = 0; index < commandCount; index += 1) {
92
+ if (offset + 8 > commandsEnd) return undefined;
93
+ const command = view.getUint32(offset, true);
94
+ const size = view.getUint32(offset + 4, true);
95
+ if (size < 8 || offset + size > commandsEnd) return undefined;
96
+ if (command === LC_CODE_SIGNATURE) {
97
+ if (signature || size !== SIGNATURE_COMMAND_SIZE) return undefined;
98
+ signature = { offset, dataOffset: view.getUint32(offset + 8, true) };
99
+ } else if (command === LC_SEGMENT_64 && size >= 72 && segmentName(bytes, offset + 8) === "__LINKEDIT") {
100
+ linkedit.push(offset);
101
+ }
102
+ offset += size;
103
+ }
104
+ if (offset !== commandsEnd) return undefined;
105
+
106
+ const end = signature ? signature.dataOffset : bytes.byteLength;
107
+ if (end > bytes.byteLength || end < commandsEnd) return undefined;
108
+ const code = Buffer.from(bytes.subarray(0, end));
109
+ // __LINKEDIT's vmsize and filesize include the signature; zero them before moving commands.
110
+ for (const segment of linkedit) {
111
+ code.fill(0, segment + 32, segment + 40);
112
+ code.fill(0, segment + 48, segment + 56);
113
+ }
114
+ if (signature) {
115
+ // Take the signature command out of the table: later commands move up, the freed bytes at the
116
+ // end of the table become zero, as if the file had never been signed.
117
+ code.copy(code, signature.offset, signature.offset + SIGNATURE_COMMAND_SIZE, commandsEnd);
118
+ code.fill(0, commandsEnd - SIGNATURE_COMMAND_SIZE, commandsEnd);
119
+ code.writeUInt32LE(commandCount - 1, 16);
120
+ code.writeUInt32LE(commandsSize - SIGNATURE_COMMAND_SIZE, 20);
121
+ }
122
+ let length = code.length;
123
+ while (length > 0 && code[length - 1] === 0) length -= 1;
124
+ return createHash("sha256").update(code.subarray(0, length)).digest("hex");
125
+ }
126
+
127
+ function segmentName(bytes: Uint8Array, at: number): string {
128
+ let name = "";
129
+ for (let index = 0; index < 16; index += 1) {
130
+ const byte = bytes[at + index]!;
131
+ if (byte === 0) break;
132
+ name += String.fromCharCode(byte);
133
+ }
134
+ return name;
135
+ }
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";