@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,550 @@
1
+ /**
2
+ * Pinning the desktop helpers in an app: one lock file, staged and verified at build time.
3
+ *
4
+ * Voice publishes each helper as a versioned release artifact (a `.tar.gz` holding the signed
5
+ * executable and, for the local-model helpers, its `Frameworks/`), with its sha256, at
6
+ * `https://adea.dev/releases/voice/<helper>/<version>/`. An app commits a lock that names the
7
+ * version and the digests; its build stages the helper from the lock and its release check fails
8
+ * if the packaged helper is missing or is not the pinned one. Nothing here falls back to another
9
+ * build or compiles speech code.
10
+ *
11
+ * Lock shape (`voice-helpers.lock.json`):
12
+ *
13
+ * ```json
14
+ * {
15
+ * "schema": 1,
16
+ * "version": "0.2.0",
17
+ * "base": "https://adea.dev/releases/voice/",
18
+ * "helpers": {
19
+ * "adea-voice-helper": {
20
+ * "macos-arm64": {
21
+ * "file": "adea-voice-helper-0.2.0-macos-arm64.tar.gz",
22
+ * "sha256": "<archive sha256>",
23
+ * "executableSha256": "<sha256 of the adea-voice-helper executable>",
24
+ * "codeSha256": "<machoCodeDigest of the executable>",
25
+ * "bytes": 812345
26
+ * }
27
+ * }
28
+ * }
29
+ * }
30
+ * ```
31
+ *
32
+ * `codeSha256` (added in 0.2.1, optional) is the executable's signature-independent code digest
33
+ * (`machoCodeDigest`). A host app's release build signs the helpers again, so the packaged file's
34
+ * sha256 is not `executableSha256`; the release gate compares the code digest instead. Locks
35
+ * written before it existed still validate: the gate then uses the digest the staging recorded
36
+ * (`voice-helpers.json`) and `codesign --verify --strict`.
37
+ */
38
+ import { createHash } from "node:crypto";
39
+ import { spawnSync } from "node:child_process";
40
+ import {
41
+ chmodSync,
42
+ existsSync,
43
+ lstatSync,
44
+ mkdirSync,
45
+ mkdtempSync,
46
+ readdirSync,
47
+ readFileSync,
48
+ renameSync,
49
+ rmSync,
50
+ statSync,
51
+ writeFileSync,
52
+ type Stats,
53
+ } from "node:fs";
54
+ import { dirname, join, relative, resolve, sep } from "node:path";
55
+ import { tmpdir } from "node:os";
56
+ import { CONTRACT_MAJOR, WIRE_VERSION, parseWireLine } from "../contract/wire";
57
+ import { isMachO, machoCodeDigest } from "./macho-digest";
58
+
59
+ export const HELPER_LOCK_SCHEMA = 1;
60
+ export const HELPER_NAMES = ["adea-voice-helper", "adea-transcribe-helper", "adea-tts-helper"] as const;
61
+ export type HelperName = (typeof HELPER_NAMES)[number];
62
+ export const HELPER_TARGETS = ["macos-arm64", "macos-x64", "linux-x64", "linux-arm64", "windows-x64"] as const;
63
+ export type HelperTarget = (typeof HELPER_TARGETS)[number];
64
+
65
+ /** A pinned artifact can never be larger than this; a bigger body is refused while streaming. */
66
+ export const MAX_HELPER_ARCHIVE_BYTES = 256 * 1024 * 1024;
67
+
68
+ export interface HelperArtifactPin {
69
+ readonly file: string;
70
+ readonly sha256: string;
71
+ readonly executableSha256: string;
72
+ /** The executable's `machoCodeDigest` (0.2.1+): what a re-signed packaged copy still matches. */
73
+ readonly codeSha256?: string;
74
+ readonly bytes?: number;
75
+ }
76
+
77
+ export interface HelperLock {
78
+ readonly schema: 1;
79
+ readonly version: string;
80
+ readonly base: string;
81
+ readonly helpers: Readonly<Partial<Record<HelperName, Readonly<Partial<Record<HelperTarget, HelperArtifactPin>>>>>>;
82
+ }
83
+
84
+ /** One staged helper: the pins it was staged from and the code digest of what was staged. */
85
+ export interface StagedHelperEntry {
86
+ readonly sha256: string;
87
+ readonly executableSha256: string;
88
+ /** `machoCodeDigest` of the staged executable (absent in records staged before 0.2.1). */
89
+ readonly codeSha256?: string;
90
+ }
91
+
92
+ /** What a staged directory records about itself, written next to the helpers. */
93
+ export interface StagedHelperRecord {
94
+ readonly schema: 1;
95
+ readonly version: string;
96
+ readonly target: HelperTarget;
97
+ readonly helpers: Readonly<Partial<Record<HelperName, StagedHelperEntry>>>;
98
+ /**
99
+ * Every other staged file (the helpers' `Frameworks/`), relative path → digest: the code digest
100
+ * for Mach-O files (they are re-signed when packaged), the sha256 otherwise. Signature
101
+ * directories (`_CodeSignature/`) are left out. Absent in records staged before 0.2.1.
102
+ */
103
+ readonly files?: Readonly<Record<string, string>>;
104
+ }
105
+
106
+ export const STAGED_RECORD_FILE = "voice-helpers.json";
107
+
108
+ const SHA256 = /^[0-9a-f]{64}$/;
109
+ const SEMVER = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/;
110
+ const FILE_NAME = /^[A-Za-z0-9._-]+\.tar\.gz$/;
111
+
112
+ export class HelperLockError extends Error {
113
+ constructor(message: string) {
114
+ super(message);
115
+ this.name = "HelperLockError";
116
+ }
117
+ }
118
+
119
+ /** Validates a parsed lock. Every problem is a `HelperLockError`: a build must stop on it. */
120
+ export function validateHelperLock(value: unknown): HelperLock {
121
+ const fail = (message: string): never => {
122
+ throw new HelperLockError(`voice helper lock: ${message}`);
123
+ };
124
+ if (value === null || typeof value !== "object" || Array.isArray(value)) fail("must be a JSON object");
125
+ const lock = value as Record<string, unknown>;
126
+ if (lock.schema !== HELPER_LOCK_SCHEMA) fail(`schema must be ${HELPER_LOCK_SCHEMA}`);
127
+ if (typeof lock.version !== "string" || !SEMVER.test(lock.version)) fail("version must be a semver");
128
+ if (typeof lock.base !== "string" || !/^https:\/\/[^\s]+\/$/.test(lock.base)) fail("base must be an https URL ending in /");
129
+ if (lock.helpers === null || typeof lock.helpers !== "object") fail("helpers must be an object");
130
+ for (const [name, targets] of Object.entries(lock.helpers as Record<string, unknown>)) {
131
+ if (!(HELPER_NAMES as readonly string[]).includes(name)) fail(`unknown helper ${name}`);
132
+ if (targets === null || typeof targets !== "object") fail(`${name} must map targets to pins`);
133
+ for (const [target, pin] of Object.entries(targets as Record<string, unknown>)) {
134
+ if (!(HELPER_TARGETS as readonly string[]).includes(target)) fail(`${name}: unknown target ${target}`);
135
+ const entry = pin as Record<string, unknown>;
136
+ if (typeof entry?.file !== "string" || !FILE_NAME.test(entry.file)) fail(`${name}/${target}: file must be a .tar.gz name`);
137
+ if (typeof entry.sha256 !== "string" || !SHA256.test(entry.sha256)) fail(`${name}/${target}: sha256 must be 64 hex`);
138
+ if (typeof entry.executableSha256 !== "string" || !SHA256.test(entry.executableSha256)) {
139
+ fail(`${name}/${target}: executableSha256 must be 64 hex`);
140
+ }
141
+ if (entry.codeSha256 !== undefined && (typeof entry.codeSha256 !== "string" || !SHA256.test(entry.codeSha256))) {
142
+ fail(`${name}/${target}: codeSha256 must be 64 hex`);
143
+ }
144
+ if (entry.bytes !== undefined && (typeof entry.bytes !== "number" || entry.bytes <= 0 || entry.bytes > MAX_HELPER_ARCHIVE_BYTES)) {
145
+ fail(`${name}/${target}: bytes out of range`);
146
+ }
147
+ if (!(entry.file as string).includes(lock.version as string)) fail(`${name}/${target}: file does not carry version ${String(lock.version)}`);
148
+ }
149
+ }
150
+ return value as HelperLock;
151
+ }
152
+
153
+ export function readHelperLock(path: string): HelperLock {
154
+ let text: string;
155
+ try {
156
+ text = readFileSync(path, "utf8");
157
+ } catch (error) {
158
+ throw new HelperLockError(`voice helper lock: cannot read ${path}: ${String(error)}`);
159
+ }
160
+ let parsed: unknown;
161
+ try {
162
+ parsed = JSON.parse(text);
163
+ } catch (error) {
164
+ throw new HelperLockError(`voice helper lock: ${path} is not JSON: ${String(error)}`);
165
+ }
166
+ return validateHelperLock(parsed);
167
+ }
168
+
169
+ export function helperPin(lock: HelperLock, helper: HelperName, target: HelperTarget): HelperArtifactPin | undefined {
170
+ return lock.helpers[helper]?.[target];
171
+ }
172
+
173
+ export function helperArtifactUrl(lock: HelperLock, helper: HelperName, target: HelperTarget): string {
174
+ const pin = helperPin(lock, helper, target);
175
+ if (!pin) throw new HelperLockError(`voice helper lock pins no ${helper} for ${target}`);
176
+ return `${lock.base}${helper}/${lock.version}/${pin.file}`;
177
+ }
178
+
179
+ /** The lock target for this machine (or `undefined` where no helper is published). */
180
+ export function currentHelperTarget(platform: string = process.platform, arch: string = process.arch): HelperTarget | undefined {
181
+ const os = platform === "darwin" ? "macos" : platform === "win32" ? "windows" : platform === "linux" ? "linux" : undefined;
182
+ const cpu = arch === "arm64" ? "arm64" : arch === "x64" ? "x64" : undefined;
183
+ if (!os || !cpu) return undefined;
184
+ const target = `${os}-${cpu}`;
185
+ return (HELPER_TARGETS as readonly string[]).includes(target) ? (target as HelperTarget) : undefined;
186
+ }
187
+
188
+ export function sha256File(path: string): string {
189
+ return createHash("sha256").update(readFileSync(path)).digest("hex");
190
+ }
191
+
192
+ export interface StageHelpersOptions {
193
+ readonly lock: HelperLock;
194
+ readonly target: HelperTarget;
195
+ /** The directory the app bundles (each helper lands at `<outDir>/<helper>`). */
196
+ readonly outDir: string;
197
+ /** Which helpers must be staged; a pin missing for one is an error. */
198
+ readonly helpers: readonly HelperName[];
199
+ /** A cache of verified archives, keyed by sha256 (default: none). */
200
+ readonly cacheDir?: string;
201
+ /**
202
+ * A directory holding locally built helpers (`scripts/package-helper.sh` output) to use instead
203
+ * of downloading, for developing the helper itself. Its binaries are still checked for a
204
+ * compatible handshake, and the staged record says `local` so a release check refuses it.
205
+ */
206
+ readonly localDir?: string;
207
+ readonly fetch?: typeof fetch;
208
+ /** Run `--version` on the staged executable (default: when the target matches this machine). */
209
+ readonly handshake?: boolean;
210
+ readonly log?: (message: string) => void;
211
+ }
212
+
213
+ /**
214
+ * Downloads, verifies and unpacks the pinned helpers into `outDir`, then records what was staged.
215
+ * Reuses an already staged helper whose digests match. Throws `HelperLockError` on any mismatch;
216
+ * a partially staged directory is removed so a build never packages it.
217
+ */
218
+ export async function stageVoiceHelpers(options: StageHelpersOptions): Promise<StagedHelperRecord> {
219
+ const log = options.log ?? (() => undefined);
220
+ const outDir = resolve(options.outDir);
221
+ const handshake = options.handshake ?? options.target === currentHelperTarget();
222
+ const existing = readStagedRecord(outDir);
223
+ const helpers: Record<string, StagedHelperEntry> = {};
224
+ const version = options.localDir ? `local+${options.lock.version}` : options.lock.version;
225
+ mkdirSync(outDir, { recursive: true });
226
+ try {
227
+ for (const helper of options.helpers) {
228
+ const executable = join(outDir, helper);
229
+ if (options.localDir) {
230
+ stageLocal(options.localDir, helper, outDir);
231
+ helpers[helper] = { sha256: "local", executableSha256: sha256File(executable), ...codeDigestEntry(executable) };
232
+ } else {
233
+ const pin = helperPin(options.lock, helper, options.target);
234
+ if (!pin) throw new HelperLockError(`voice helper lock pins no ${helper} for ${options.target}`);
235
+ const reuse =
236
+ existing?.version === options.lock.version &&
237
+ existing.helpers[helper]?.sha256 === pin.sha256 &&
238
+ existsSync(executable) &&
239
+ sha256File(executable) === pin.executableSha256;
240
+ if (reuse) {
241
+ log(`${helper} ${options.lock.version} already staged`);
242
+ } else {
243
+ const archive = await obtainArchive(options, helper, pin, log);
244
+ try {
245
+ extractArchive(archive, outDir, helper);
246
+ } finally {
247
+ // An uncached download lives in its own scratch directory; do not leak it.
248
+ if (!options.cacheDir) rmSync(dirname(archive), { recursive: true, force: true });
249
+ }
250
+ const actual = existsSync(executable) ? sha256File(executable) : "missing";
251
+ if (actual !== pin.executableSha256) {
252
+ throw new HelperLockError(`${helper}: executable sha256 ${actual} is not the pinned ${pin.executableSha256}`);
253
+ }
254
+ chmodSync(executable, 0o755);
255
+ log(`staged ${helper} ${options.lock.version} (${options.target})`);
256
+ }
257
+ const code = codeDigestEntry(executable);
258
+ if (pin.codeSha256 && code.codeSha256 !== pin.codeSha256) {
259
+ throw new HelperLockError(`${helper}: code digest ${code.codeSha256 ?? "unavailable"} is not the pinned ${pin.codeSha256}`);
260
+ }
261
+ helpers[helper] = { sha256: pin.sha256, executableSha256: pin.executableSha256, ...code };
262
+ }
263
+ if (handshake) assertHandshake(executable, options.localDir ? {} : { release: options.lock.version });
264
+ }
265
+ } catch (error) {
266
+ rmSync(outDir, { recursive: true, force: true });
267
+ throw error;
268
+ }
269
+ const record: StagedHelperRecord = {
270
+ schema: 1,
271
+ version,
272
+ target: options.target,
273
+ helpers,
274
+ files: supportFileDigests(outDir, Object.keys(helpers)),
275
+ };
276
+ writeFileSync(join(outDir, STAGED_RECORD_FILE), `${JSON.stringify(record, null, 2)}\n`);
277
+ return record;
278
+ }
279
+
280
+ export interface VerifyStagedOptions {
281
+ readonly lock: HelperLock;
282
+ readonly target: HelperTarget;
283
+ readonly dir: string;
284
+ readonly helpers: readonly HelperName[];
285
+ /**
286
+ * Launch each helper with `--version` and require the lock's release and this SDK's wire and
287
+ * contract (only possible on a matching machine; default: when the target matches this one).
288
+ */
289
+ readonly handshake?: boolean;
290
+ /** How long one `--version` may take. Default 10 s. */
291
+ readonly handshakeTimeoutMs?: number;
292
+ /**
293
+ * Run `codesign --verify --strict` on a helper that was signed again after staging (default: on
294
+ * macOS for a macOS target).
295
+ */
296
+ readonly codesign?: boolean;
297
+ }
298
+
299
+ /**
300
+ * The release gate: the packaged directory holds exactly the pinned helpers. Throws
301
+ * `HelperLockError` naming the first difference; a local (unpinned) staging is refused.
302
+ *
303
+ * The directory may be the staged one or the copy inside a packaged, re-signed app. A helper whose
304
+ * file sha256 is not the pinned one must still have the pinned code (`machoCodeDigest`): the
305
+ * lock's `codeSha256`, or, for a lock written before it, the digest the staging recorded for the
306
+ * pinned executable, plus a valid signature. Every other staged file (`Frameworks/`) must still be
307
+ * a regular file with the staged digest: a copy that flattened or dropped a symlink fails here.
308
+ * Then each helper must start and report the lock's release.
309
+ */
310
+ export function verifyStagedVoiceHelpers(options: VerifyStagedOptions): void {
311
+ const dir = resolve(options.dir);
312
+ const record = readStagedRecord(dir);
313
+ if (!record) throw new HelperLockError(`no ${STAGED_RECORD_FILE} in ${dir}: the voice helpers were not staged from the lock`);
314
+ if (record.version !== options.lock.version) {
315
+ throw new HelperLockError(`staged voice helpers are ${record.version}; the lock pins ${options.lock.version}`);
316
+ }
317
+ if (record.target !== options.target) throw new HelperLockError(`staged voice helpers are for ${record.target}, not ${options.target}`);
318
+ const codesign = options.codesign ?? (process.platform === "darwin" && options.target.startsWith("macos-"));
319
+ for (const helper of options.helpers) {
320
+ const pin = helperPin(options.lock, helper, options.target);
321
+ if (!pin) throw new HelperLockError(`voice helper lock pins no ${helper} for ${options.target}`);
322
+ const executable = join(dir, helper);
323
+ if (!existsSync(executable) || !lstatSync(executable).isFile()) throw new HelperLockError(`${helper} is missing from ${dir}`);
324
+ const staged = record.helpers[helper];
325
+ if (staged && (staged.sha256 !== pin.sha256 || staged.executableSha256 !== pin.executableSha256)) {
326
+ throw new HelperLockError(`${helper} in ${dir} was staged from ${staged.sha256}, not the pinned ${pin.sha256}`);
327
+ }
328
+ const actual = sha256File(executable);
329
+ if (actual !== pin.executableSha256) {
330
+ // Signed again by the app build: the code must be the pinned code.
331
+ const expected = pin.codeSha256 ?? staged?.codeSha256;
332
+ if (!expected) {
333
+ throw new HelperLockError(
334
+ `${helper} in ${dir} has sha256 ${actual}, not the pinned ${pin.executableSha256}, and neither the lock nor ${STAGED_RECORD_FILE} records a code digest to compare a re-signed copy with (stage it with @adea-ai/voice 0.2.1 or later)`,
335
+ );
336
+ }
337
+ const code = machoCodeDigest(new Uint8Array(readFileSync(executable)));
338
+ if (code !== expected) {
339
+ throw new HelperLockError(`${helper} in ${dir} has code digest ${code ?? "unavailable"}, not the pinned ${expected}`);
340
+ }
341
+ if (codesign) assertSigned(executable);
342
+ }
343
+ }
344
+ verifySupportFiles(dir, record);
345
+ if (options.handshake ?? options.target === currentHelperTarget()) {
346
+ for (const helper of options.helpers) {
347
+ assertHandshake(join(dir, helper), { release: options.lock.version, timeoutMs: options.handshakeTimeoutMs });
348
+ }
349
+ }
350
+ }
351
+
352
+ export function readStagedRecord(dir: string): StagedHelperRecord | undefined {
353
+ const path = join(dir, STAGED_RECORD_FILE);
354
+ if (!existsSync(path)) return undefined;
355
+ try {
356
+ return JSON.parse(readFileSync(path, "utf8")) as StagedHelperRecord;
357
+ } catch {
358
+ return undefined;
359
+ }
360
+ }
361
+
362
+ export interface HandshakeExpectations {
363
+ /** The release the helper must report (`version.release`), e.g. the lock's version. */
364
+ readonly release?: string;
365
+ /** How long `--version` may take before the helper counts as hung. Default 10 s. */
366
+ readonly timeoutMs?: number;
367
+ }
368
+
369
+ /**
370
+ * Runs `<helper> --version` and refuses a helper that does not start (a missing library is a dyld
371
+ * abort here), hangs, or speaks another wire, contract or release.
372
+ */
373
+ export function assertHandshake(executable: string, expect: HandshakeExpectations = {}): void {
374
+ const timeoutMs = expect.timeoutMs ?? 10_000;
375
+ const run = spawnSync(executable, ["--version"], { encoding: "utf8", timeout: timeoutMs, killSignal: "SIGKILL" });
376
+ if (run.error || run.status !== 0) {
377
+ const reason = run.error
378
+ ? (run.error as NodeJS.ErrnoException).code === "ETIMEDOUT"
379
+ ? `did not answer within ${timeoutMs} ms`
380
+ : run.error.message
381
+ : run.signal
382
+ ? `was killed by ${run.signal}`
383
+ : `exited ${String(run.status)}`;
384
+ const detail = (run.stderr ?? "").trim().split("\n")[0]?.slice(0, 300);
385
+ throw new HelperLockError(`${executable} --version failed: ${reason}${detail ? ` (${detail})` : ""}`);
386
+ }
387
+ const version = run.stdout
388
+ .split("\n")
389
+ .map(parseWireLine)
390
+ .find((event) => event?.event === "version");
391
+ if (!version || version.event !== "version") throw new HelperLockError(`${executable} printed no version handshake`);
392
+ if (version.wire !== WIRE_VERSION || version.contractMajor !== CONTRACT_MAJOR) {
393
+ throw new HelperLockError(
394
+ `${executable} speaks wire ${version.wire} / contract ${version.contract}; need wire ${WIRE_VERSION} / contract ${CONTRACT_MAJOR}`,
395
+ );
396
+ }
397
+ if (expect.release !== undefined && version.release !== expect.release) {
398
+ throw new HelperLockError(`${executable} reports release ${version.release ?? "(none)"}; the lock pins ${expect.release}`);
399
+ }
400
+ }
401
+
402
+ /** `{ codeSha256 }` for a Mach-O executable, `{}` for anything else (a test's shell script). */
403
+ function codeDigestEntry(executable: string): { codeSha256?: string } {
404
+ const digest = machoCodeDigest(new Uint8Array(readFileSync(executable)));
405
+ return digest ? { codeSha256: digest } : {};
406
+ }
407
+
408
+ /** Throws unless `codesign --verify --strict` accepts the file. */
409
+ function assertSigned(path: string): void {
410
+ const run = spawnSync("codesign", ["--verify", "--strict", path], { encoding: "utf8", timeout: 30_000 });
411
+ if (run.error || run.status !== 0) {
412
+ throw new HelperLockError(`${path} is not validly signed: ${(run.stderr || run.error?.message || `exit ${String(run.status)}`).trim()}`);
413
+ }
414
+ }
415
+
416
+ /** Relative paths of every entry under `dir` (depth first), as `[path, lstat]`. */
417
+ function walk(dir: string, root = dir): [string, Stats][] {
418
+ const entries: [string, Stats][] = [];
419
+ for (const name of readdirSync(dir).sort()) {
420
+ const path = join(dir, name);
421
+ const stat = lstatSync(path);
422
+ entries.push([relative(root, path).split(sep).join("/"), stat]);
423
+ if (stat.isDirectory()) entries.push(...walk(path, root));
424
+ }
425
+ return entries;
426
+ }
427
+
428
+ function isSignatureFile(path: string): boolean {
429
+ return path.split("/").includes("_CodeSignature");
430
+ }
431
+
432
+ /** Digests of the staged files beside the helpers (see `StagedHelperRecord.files`). */
433
+ function supportFileDigests(dir: string, helpers: readonly string[]): Record<string, string> {
434
+ const files: Record<string, string> = {};
435
+ for (const [path, stat] of walk(dir)) {
436
+ if (!stat.isFile() || helpers.includes(path) || path === STAGED_RECORD_FILE || isSignatureFile(path)) continue;
437
+ files[path] = fileDigest(join(dir, path));
438
+ }
439
+ return files;
440
+ }
441
+
442
+ function fileDigest(path: string): string {
443
+ const bytes = new Uint8Array(readFileSync(path));
444
+ if (isMachO(bytes)) {
445
+ const code = machoCodeDigest(bytes);
446
+ if (code) return code;
447
+ }
448
+ return createHash("sha256").update(bytes).digest("hex");
449
+ }
450
+
451
+ function verifySupportFiles(dir: string, record: StagedHelperRecord): void {
452
+ for (const [path, expected] of Object.entries(record.files ?? {})) {
453
+ const absolute = join(dir, path);
454
+ if (!existsSync(absolute)) throw new HelperLockError(`${path} is missing from ${dir}`);
455
+ const stat = lstatSync(absolute);
456
+ if (!stat.isFile()) throw new HelperLockError(`${path} in ${dir} is not a regular file`);
457
+ const actual = fileDigest(absolute);
458
+ if (actual !== expected) throw new HelperLockError(`${path} in ${dir} has digest ${actual}, not the staged ${expected}`);
459
+ }
460
+ // Whatever a lock pinned, a packaged helper tree has no use for symlinks: a copy that does not
461
+ // keep them (Electrobun's, for one) leaves broken files behind.
462
+ for (const [path, stat] of walk(dir)) {
463
+ if (stat.isSymbolicLink()) throw new HelperLockError(`${path} in ${dir} is a symlink; packaged voice helpers must not contain symlinks`);
464
+ if (stat.isFile() && stat.size === 0 && path.split("/").includes("Frameworks")) {
465
+ throw new HelperLockError(`${path} in ${dir} is an empty file (a flattened symlink?)`);
466
+ }
467
+ }
468
+ }
469
+
470
+ async function obtainArchive(
471
+ options: StageHelpersOptions,
472
+ helper: HelperName,
473
+ pin: HelperArtifactPin,
474
+ log: (message: string) => void,
475
+ ): Promise<string> {
476
+ const cached = options.cacheDir ? join(options.cacheDir, `${pin.sha256}.tar.gz`) : undefined;
477
+ if (cached && existsSync(cached) && sha256File(cached) === pin.sha256) {
478
+ log(`${helper}: using cached ${pin.file}`);
479
+ return cached;
480
+ }
481
+ const url = helperArtifactUrl(options.lock, helper, options.target);
482
+ log(`${helper}: downloading ${url}`);
483
+ const response = await (options.fetch ?? fetch)(url, { redirect: "follow" });
484
+ if (!response.ok || !response.body) throw new HelperLockError(`${helper}: GET ${url} answered ${response.status}`);
485
+ const limit = pin.bytes ?? MAX_HELPER_ARCHIVE_BYTES;
486
+ const hash = createHash("sha256");
487
+ const chunks: Uint8Array[] = [];
488
+ let total = 0;
489
+ const reader = response.body.getReader();
490
+ for (;;) {
491
+ const { value, done } = await reader.read();
492
+ if (done) break;
493
+ total += value.byteLength;
494
+ if (total > limit) {
495
+ await reader.cancel();
496
+ throw new HelperLockError(`${helper}: ${url} is larger than the pinned ${limit} bytes`);
497
+ }
498
+ hash.update(value);
499
+ chunks.push(value);
500
+ }
501
+ const digest = hash.digest("hex");
502
+ if (digest !== pin.sha256) throw new HelperLockError(`${helper}: ${pin.file} has sha256 ${digest}, not the pinned ${pin.sha256}`);
503
+ const target = cached ?? join(mkdtempSync(join(tmpdir(), "adea-voice-helper-")), pin.file);
504
+ mkdirSync(dirname(target), { recursive: true });
505
+ const partial = `${target}.partial`;
506
+ writeFileSync(partial, Buffer.concat(chunks));
507
+ renameSync(partial, target);
508
+ return target;
509
+ }
510
+
511
+ /** Unpacks into a scratch directory, then moves only the expected entries into `outDir`. */
512
+ function extractArchive(archive: string, outDir: string, helper: HelperName): void {
513
+ const scratch = mkdtempSync(join(tmpdir(), "adea-voice-extract-"));
514
+ try {
515
+ const listing = spawnSync("tar", ["-tzf", archive], { encoding: "utf8" });
516
+ if (listing.status !== 0) throw new HelperLockError(`${helper}: cannot read ${archive}`);
517
+ for (const entry of listing.stdout.split("\n").filter(Boolean)) {
518
+ // No absolute paths, no parent traversal: the archive is pinned, but stay defensive.
519
+ if (entry.startsWith("/") || entry.split("/").includes("..")) throw new HelperLockError(`${helper}: unsafe archive entry ${entry}`);
520
+ }
521
+ const unpack = spawnSync("tar", ["-xzf", archive, "-C", scratch], { encoding: "utf8" });
522
+ if (unpack.status !== 0) throw new HelperLockError(`${helper}: cannot unpack ${archive}: ${unpack.stderr}`);
523
+ const executable = join(scratch, helper);
524
+ if (!existsSync(executable) || !statSync(executable).isFile()) throw new HelperLockError(`${helper}: the archive holds no ${helper}`);
525
+ rmSync(join(outDir, helper), { force: true });
526
+ renameSync(executable, join(outDir, helper));
527
+ const frameworks = join(scratch, "Frameworks");
528
+ if (existsSync(frameworks)) {
529
+ const destination = join(outDir, "Frameworks");
530
+ mkdirSync(destination, { recursive: true });
531
+ for (const entry of spawnSync("ls", ["-1", frameworks], { encoding: "utf8" }).stdout.split("\n").filter(Boolean)) {
532
+ rmSync(join(destination, entry), { recursive: true, force: true });
533
+ renameSync(join(frameworks, entry), join(destination, entry));
534
+ }
535
+ }
536
+ } finally {
537
+ rmSync(scratch, { recursive: true, force: true });
538
+ }
539
+ }
540
+
541
+ function stageLocal(localDir: string, helper: HelperName, outDir: string): void {
542
+ const source = join(resolve(localDir), helper);
543
+ if (!existsSync(source)) throw new HelperLockError(`${helper} is not in the local helper directory ${localDir}`);
544
+ const destination = join(outDir, helper);
545
+ rmSync(destination, { force: true });
546
+ writeFileSync(destination, readFileSync(source));
547
+ chmodSync(destination, 0o755);
548
+ const frameworks = join(resolve(localDir), "Frameworks");
549
+ if (existsSync(frameworks)) spawnSync("cp", ["-R", frameworks, outDir]);
550
+ }