@adea-ai/voice 0.2.0 → 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.
- package/README.md +86 -1
- package/dist/cli/helpers-cli.js +17 -2
- package/dist/contract/contract.d.ts +21 -2
- package/dist/contract/index.d.ts +1 -0
- package/dist/contract/index.js +12 -2
- package/dist/contract/session.d.ts +13 -0
- package/dist/contract/turns.d.ts +91 -0
- package/dist/contract/wire.d.ts +92 -1
- package/dist/desktop/conversation.d.ts +86 -0
- package/dist/desktop/desktop-voice.d.ts +61 -1
- package/dist/desktop/helper-lock.d.ts +45 -7
- package/dist/desktop/helper-process.d.ts +4 -0
- package/dist/desktop/index.d.ts +2 -0
- package/dist/desktop/index.js +427 -15
- package/dist/desktop/macho-digest.d.ts +9 -0
- package/dist/{index-rehs788p.js → index-7n7epq1a.js} +7 -2
- package/dist/{index-s270cw30.js → index-a7d617zr.js} +1 -1
- package/dist/{index-9kerqn9r.js → index-ght8wwpd.js} +9 -3
- package/dist/{index-acm1yvvv.js → index-m4g2tpeq.js} +258 -26
- package/dist/index.js +13 -3
- package/dist/settings/index.js +1 -1
- package/dist/web/index.d.ts +1 -0
- package/dist/web/index.js +459 -49
- package/dist/web/stt/speech-recognition.d.ts +128 -7
- package/dist/web/tts/locale-match.d.ts +40 -0
- package/dist/web/tts/system-voices.d.ts +44 -4
- package/dist/web/turns.d.ts +15 -25
- package/package.json +1 -1
- package/src/cli/helpers-cli.ts +18 -2
- package/src/contract/contract.ts +32 -4
- package/src/contract/index.ts +1 -0
- package/src/contract/session.ts +14 -2
- package/src/contract/turns.ts +48 -0
- package/src/contract/wire.ts +123 -2
- package/src/desktop/conversation.ts +347 -0
- package/src/desktop/desktop-voice.ts +197 -1
- package/src/desktop/helper-lock.ts +195 -20
- package/src/desktop/helper-process.ts +17 -10
- package/src/desktop/index.ts +2 -0
- package/src/desktop/macho-digest.ts +135 -0
- package/src/web/index.ts +1 -0
- package/src/web/stt/speech-recognition.ts +454 -24
- package/src/web/tts/locale-match.ts +131 -0
- package/src/web/tts/system-voices.ts +144 -35
- package/src/web/turns.ts +22 -11
|
@@ -36,12 +36,15 @@ import type {
|
|
|
36
36
|
LocaleEvent,
|
|
37
37
|
PermissionEvent,
|
|
38
38
|
PermissionPart,
|
|
39
|
+
SpeechVoiceIdentity,
|
|
39
40
|
SynthesisStatusEvent,
|
|
40
41
|
TranscribeStatusEvent,
|
|
41
42
|
VoiceEvent,
|
|
42
43
|
WireEvent,
|
|
43
44
|
} from "../contract/wire";
|
|
44
45
|
import { routingPolicyFor, type VoiceSettings } from "../settings/settings";
|
|
46
|
+
import { RELEASE_ASSETS_WIRE_MINOR, TURN_WIRE_MINOR } from "../contract/wire";
|
|
47
|
+
import { Conversation, type DesktopConversation } from "./conversation";
|
|
45
48
|
import { HelperConnection, IncompatibleHelperError, nextRequestId, nodeSpawner, type HelperSpawner } from "./helper-process";
|
|
46
49
|
|
|
47
50
|
// MARK: - Provider ids and the desktop routing table
|
|
@@ -192,14 +195,45 @@ export interface SpeakRequest {
|
|
|
192
195
|
|
|
193
196
|
export type SpeechOutcome = "finished" | "cancelled";
|
|
194
197
|
|
|
198
|
+
/** What the helper reports when audio starts. */
|
|
199
|
+
export interface SpeechStart {
|
|
200
|
+
/**
|
|
201
|
+
* The voice that resolved for the request (`speech-started.voice`), when the helper reports it
|
|
202
|
+
* (Apple helper builds after 0.2.0 do, for a `speak` that named a voice or a locale).
|
|
203
|
+
*/
|
|
204
|
+
readonly voice?: SpeechVoiceIdentity;
|
|
205
|
+
}
|
|
206
|
+
|
|
195
207
|
export interface DesktopSpeech {
|
|
196
208
|
readonly id: string;
|
|
197
209
|
readonly provider: string;
|
|
210
|
+
/**
|
|
211
|
+
* Resolves when the helper reports `speech-started` (audio begins), with the voice it resolved.
|
|
212
|
+
* Resolves `undefined` if the speech ends, is cancelled or fails before it started; never
|
|
213
|
+
* rejects.
|
|
214
|
+
*/
|
|
215
|
+
readonly started: Promise<SpeechStart | undefined>;
|
|
198
216
|
/** Resolves when playback ends or is cancelled; rejects with `VoiceError` on failure. */
|
|
199
217
|
readonly done: Promise<SpeechOutcome>;
|
|
200
218
|
cancel(): Promise<void>;
|
|
201
219
|
}
|
|
202
220
|
|
|
221
|
+
export interface ConversationRequest {
|
|
222
|
+
readonly settings: VoiceSettings;
|
|
223
|
+
/** BCP-47 for listening; defaults to the settings' locale, then the system language. */
|
|
224
|
+
readonly locale?: string;
|
|
225
|
+
/** Starting a turn while the answer plays stops it (a request cancel). Default true. */
|
|
226
|
+
readonly bargeIn?: boolean;
|
|
227
|
+
/**
|
|
228
|
+
* The microphone stays closed while the answer plays, so the assistant never hears itself.
|
|
229
|
+
* Default true; turn it off only with echo cancellation (a headset).
|
|
230
|
+
*/
|
|
231
|
+
readonly halfDuplex?: boolean;
|
|
232
|
+
/** Start the next turn by itself once an answer has played. Default true (hands-free). */
|
|
233
|
+
readonly continuous?: boolean;
|
|
234
|
+
readonly signal?: AbortSignal;
|
|
235
|
+
}
|
|
236
|
+
|
|
203
237
|
export interface DesktopVoiceInfo {
|
|
204
238
|
readonly id: string;
|
|
205
239
|
readonly name: string;
|
|
@@ -220,6 +254,26 @@ export interface InstallRequest {
|
|
|
220
254
|
readonly signal?: AbortSignal;
|
|
221
255
|
}
|
|
222
256
|
|
|
257
|
+
export interface ReleaseRequest {
|
|
258
|
+
/** BCP-47 locale whose Apple model to remove, e.g. `es-419` (released as its model locale, `es_MX`). */
|
|
259
|
+
readonly locale: string;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** What `releaseAssets` did, and the locale's model state afterwards. */
|
|
263
|
+
export interface ReleasedAsset {
|
|
264
|
+
readonly locale: string;
|
|
265
|
+
/** The model's own locale in BCP-47 (`es-MX` for `es-419`). */
|
|
266
|
+
readonly modelLocale: string;
|
|
267
|
+
/** False when this app held no reservation for the model (nothing was released). */
|
|
268
|
+
readonly released: boolean;
|
|
269
|
+
/**
|
|
270
|
+
* The status the system reports after the release. Usually `notInstalled`; a model shared with
|
|
271
|
+
* system dictation can stay `installed` until the OS reclaims it.
|
|
272
|
+
*/
|
|
273
|
+
readonly status: LocaleEvent["status"];
|
|
274
|
+
readonly canInstall: boolean;
|
|
275
|
+
}
|
|
276
|
+
|
|
223
277
|
export interface DesktopVoice {
|
|
224
278
|
/** Which helpers this build bundles (synchronous, no process started). */
|
|
225
279
|
bundled(): Readonly<Record<"voice" | "transcribe" | "tts", boolean>>;
|
|
@@ -228,9 +282,21 @@ export interface DesktopVoice {
|
|
|
228
282
|
listen(request: DictationRequest): Promise<DesktopDictation>;
|
|
229
283
|
speak(request: SpeakRequest): Promise<DesktopSpeech>;
|
|
230
284
|
stopSpeaking(): Promise<void>;
|
|
285
|
+
/**
|
|
286
|
+
* Starts a voice conversation (Octy-style turns with streamed answers and barge-in) and
|
|
287
|
+
* resolves once the first turn is listening. Runs on `adea-voice-helper` (Apple speech, wire
|
|
288
|
+
* 1.2+): a route to another engine is a typed `unavailable`.
|
|
289
|
+
*/
|
|
290
|
+
conversation(request: ConversationRequest): Promise<DesktopConversation>;
|
|
231
291
|
voices(settings: VoiceSettings, locale?: string): Promise<readonly DesktopVoiceInfo[]>;
|
|
232
292
|
locales(): Promise<readonly LocaleAsset[]>;
|
|
233
293
|
installAssets(request: InstallRequest): Promise<void>;
|
|
294
|
+
/**
|
|
295
|
+
* Removes an Apple on-device speech model: releases this app's reservation of it so the OS may
|
|
296
|
+
* reclaim the storage. Nothing is deleted directly; the system decides when the files go.
|
|
297
|
+
* Needs a voice helper on wire 1.3+ (`unavailable` otherwise).
|
|
298
|
+
*/
|
|
299
|
+
releaseAssets(request: ReleaseRequest): Promise<ReleasedAsset>;
|
|
234
300
|
/** Stops every helper. The instance can be used again; helpers restart on demand. */
|
|
235
301
|
dispose(): Promise<void>;
|
|
236
302
|
}
|
|
@@ -251,6 +317,7 @@ class DesktopVoiceService implements DesktopVoice {
|
|
|
251
317
|
/** The folders the running transcribe connection was started with. */
|
|
252
318
|
private transcribeConnectionFolders = "";
|
|
253
319
|
private active: DictationSession | undefined;
|
|
320
|
+
private activeConversation: Conversation | undefined;
|
|
254
321
|
private readonly spawner: HelperSpawner;
|
|
255
322
|
|
|
256
323
|
constructor(private readonly options: DesktopVoiceOptions) {
|
|
@@ -320,6 +387,9 @@ class DesktopVoiceService implements DesktopVoice {
|
|
|
320
387
|
|
|
321
388
|
async listen(request: DictationRequest): Promise<DesktopDictation> {
|
|
322
389
|
if (this.active && !this.active.isTerminal) throw new VoiceError("busy", "A dictation is already running.");
|
|
390
|
+
if (this.activeConversation && !this.activeConversation.isFinished) {
|
|
391
|
+
throw new VoiceError("busy", "A voice conversation is running.");
|
|
392
|
+
}
|
|
323
393
|
if (request.signal?.aborted) throw new VoiceError("cancelled", "Dictation was cancelled.");
|
|
324
394
|
const locale = request.locale ?? defaultLocale(request.settings.stt.locale);
|
|
325
395
|
const capabilities = await this.capabilities(request.settings, locale);
|
|
@@ -352,6 +422,63 @@ class DesktopVoiceService implements DesktopVoice {
|
|
|
352
422
|
return session;
|
|
353
423
|
}
|
|
354
424
|
|
|
425
|
+
// MARK: Conversation
|
|
426
|
+
|
|
427
|
+
async conversation(request: ConversationRequest): Promise<DesktopConversation> {
|
|
428
|
+
const busy = () =>
|
|
429
|
+
(this.active && !this.active.isTerminal) || (this.activeConversation && !this.activeConversation.isFinished);
|
|
430
|
+
if (busy()) throw new VoiceError("busy", "A dictation or conversation is already running.");
|
|
431
|
+
if (request.signal?.aborted) throw new VoiceError("cancelled", "The conversation was cancelled.");
|
|
432
|
+
if (!this.bundled().voice) {
|
|
433
|
+
throw new VoiceError("unavailable", "Voice conversations need the Apple voice helper, which this build does not include.");
|
|
434
|
+
}
|
|
435
|
+
const locale = request.locale ?? defaultLocale(request.settings.stt.locale);
|
|
436
|
+
const capabilities = await this.capabilities(request.settings, locale);
|
|
437
|
+
for (const decision of [capabilities.speechToText, capabilities.textToSpeech]) {
|
|
438
|
+
if (!decision.route || decision.availability.status !== "available") throw unavailableError(decision);
|
|
439
|
+
}
|
|
440
|
+
const sttID = capabilities.speechToText.route!.descriptor.id;
|
|
441
|
+
const ttsID = capabilities.textToSpeech.route!.descriptor.id;
|
|
442
|
+
if ((sttID !== APPLE_ANALYZER_ID && sttID !== APPLE_LEGACY_ID) || ttsID !== APPLE_VOICES_ID) {
|
|
443
|
+
throw new VoiceError(
|
|
444
|
+
"unavailable",
|
|
445
|
+
"Voice conversations run on Apple speech and Apple voices; the selected engines do not support them yet.",
|
|
446
|
+
);
|
|
447
|
+
}
|
|
448
|
+
const connection = this.connection("voice");
|
|
449
|
+
const minor = connection.version?.wireMinor ?? 0;
|
|
450
|
+
if (minor < TURN_WIRE_MINOR) {
|
|
451
|
+
throw new VoiceError("unavailable", "This build's voice helper is too old for conversations (it needs wire 1.2).");
|
|
452
|
+
}
|
|
453
|
+
if (busy()) throw new VoiceError("busy", "A dictation or conversation is already running.");
|
|
454
|
+
const voice = request.settings.tts.voice;
|
|
455
|
+
const rate = request.settings.tts.rate;
|
|
456
|
+
const ttsLocale = request.settings.tts.locale;
|
|
457
|
+
const conversation = new Conversation({
|
|
458
|
+
connection,
|
|
459
|
+
provider: sttID,
|
|
460
|
+
locale,
|
|
461
|
+
engine: sttID === APPLE_ANALYZER_ID ? "analyzer" : "legacy",
|
|
462
|
+
bargeIn: request.bargeIn ?? true,
|
|
463
|
+
halfDuplex: request.halfDuplex ?? true,
|
|
464
|
+
continuous: request.continuous ?? true,
|
|
465
|
+
voice: {
|
|
466
|
+
...(voice ? { voice } : {}),
|
|
467
|
+
...(ttsLocale ? { locale: ttsLocale } : {}),
|
|
468
|
+
...(rate !== undefined ? { rate: appleRate(rate) } : {}),
|
|
469
|
+
},
|
|
470
|
+
terminalGraceMs: this.options.terminalGraceMs ?? 5_000,
|
|
471
|
+
onStuck: () => void connection.stop(),
|
|
472
|
+
onFinished: () => {
|
|
473
|
+
if (this.activeConversation === conversation) this.activeConversation = undefined;
|
|
474
|
+
},
|
|
475
|
+
});
|
|
476
|
+
this.activeConversation = conversation;
|
|
477
|
+
if (request.signal) request.signal.addEventListener("abort", () => void conversation.cancel(), { once: true });
|
|
478
|
+
await conversation.begin();
|
|
479
|
+
return conversation;
|
|
480
|
+
}
|
|
481
|
+
|
|
355
482
|
// MARK: Speech
|
|
356
483
|
|
|
357
484
|
async speak(request: SpeakRequest): Promise<DesktopSpeech> {
|
|
@@ -370,6 +497,10 @@ class DesktopVoiceService implements DesktopVoice {
|
|
|
370
497
|
const id = nextRequestId("speech-");
|
|
371
498
|
const voice = request.voice ?? request.settings.tts.voice;
|
|
372
499
|
const rate = request.rate ?? request.settings.tts.rate;
|
|
500
|
+
let markStarted: (start: SpeechStart | undefined) => void = () => undefined;
|
|
501
|
+
const started = new Promise<SpeechStart | undefined>((resolve) => {
|
|
502
|
+
markStarted = resolve;
|
|
503
|
+
});
|
|
373
504
|
const done = connection
|
|
374
505
|
.request(
|
|
375
506
|
{
|
|
@@ -384,8 +515,14 @@ class DesktopVoiceService implements DesktopVoice {
|
|
|
384
515
|
},
|
|
385
516
|
(event): event is WireEvent =>
|
|
386
517
|
event.event === "speech-finished" || event.event === "speech-cancelled" || event.event === "speech-error",
|
|
387
|
-
{
|
|
518
|
+
{
|
|
519
|
+
timeoutMs: null,
|
|
520
|
+
onEvent: (event) => {
|
|
521
|
+
if (event.event === "speech-started") markStarted(speechStart(event.voice));
|
|
522
|
+
},
|
|
523
|
+
},
|
|
388
524
|
)
|
|
525
|
+
.finally(() => markStarted(undefined))
|
|
389
526
|
.then((event): SpeechOutcome => {
|
|
390
527
|
if (event.event === "speech-error") throw new VoiceError(event.code, event.message ?? "Speech failed.");
|
|
391
528
|
return event.event === "speech-finished" ? "finished" : "cancelled";
|
|
@@ -395,6 +532,7 @@ class DesktopVoiceService implements DesktopVoice {
|
|
|
395
532
|
return {
|
|
396
533
|
id,
|
|
397
534
|
provider: providerID,
|
|
535
|
+
started,
|
|
398
536
|
done,
|
|
399
537
|
cancel: async () => {
|
|
400
538
|
await connection.send({ cmd: "speech-stop" }).catch(() => undefined);
|
|
@@ -478,8 +616,45 @@ class DesktopVoiceService implements DesktopVoice {
|
|
|
478
616
|
).finally(() => request.signal?.removeEventListener("abort", onAbort));
|
|
479
617
|
}
|
|
480
618
|
|
|
619
|
+
async releaseAssets(request: ReleaseRequest): Promise<ReleasedAsset> {
|
|
620
|
+
if (!this.bundled().voice) throw new VoiceError("unavailable", "Speech assets are managed by the system on this device.");
|
|
621
|
+
const connection = this.connection("voice");
|
|
622
|
+
const tooOld = () =>
|
|
623
|
+
new VoiceError("unavailable", "This build's voice helper is too old to remove speech models (it needs wire 1.3).");
|
|
624
|
+
// A running helper's handshake is known; a helper not started yet answers an unknown command
|
|
625
|
+
// with `bad_request`, which means the same thing.
|
|
626
|
+
const minor = connection.version?.wireMinor;
|
|
627
|
+
if (minor !== undefined && minor < RELEASE_ASSETS_WIRE_MINOR) throw tooOld();
|
|
628
|
+
let answer: ReleasedAsset | undefined;
|
|
629
|
+
await connection.request(
|
|
630
|
+
{ cmd: "release-assets", id: nextRequestId("release-"), locale: request.locale },
|
|
631
|
+
(event): event is WireEvent => event.event === "asset-released",
|
|
632
|
+
{
|
|
633
|
+
onEvent: (event) => {
|
|
634
|
+
if (event.event !== "asset-released") return;
|
|
635
|
+
answer = {
|
|
636
|
+
locale: event.locale,
|
|
637
|
+
// Apple reports `es_MX`; the rest of the stack speaks BCP-47.
|
|
638
|
+
modelLocale: event.modelLocale.replace(/_/g, "-"),
|
|
639
|
+
released: event.released,
|
|
640
|
+
status: event.status,
|
|
641
|
+
canInstall: event.canInstall,
|
|
642
|
+
};
|
|
643
|
+
},
|
|
644
|
+
},
|
|
645
|
+
).catch((error: unknown) => {
|
|
646
|
+
if (error instanceof VoiceError && error.code === "bad_request" && (connection.version?.wireMinor ?? 0) < RELEASE_ASSETS_WIRE_MINOR) {
|
|
647
|
+
throw tooOld();
|
|
648
|
+
}
|
|
649
|
+
throw error;
|
|
650
|
+
});
|
|
651
|
+
if (!answer) throw new VoiceError("failed", "The voice helper did not report the removal.");
|
|
652
|
+
return answer;
|
|
653
|
+
}
|
|
654
|
+
|
|
481
655
|
async dispose(): Promise<void> {
|
|
482
656
|
await this.active?.cancel().catch(() => undefined);
|
|
657
|
+
await this.activeConversation?.cancel().catch(() => undefined);
|
|
483
658
|
await Promise.all([...this.connections.values()].map((connection) => connection.stop()));
|
|
484
659
|
}
|
|
485
660
|
|
|
@@ -513,6 +688,7 @@ class DesktopVoiceService implements DesktopVoice {
|
|
|
513
688
|
if (name === "transcribe") this.transcribeConnectionFolders = this.transcribeFolders;
|
|
514
689
|
connection = new HelperConnection({
|
|
515
690
|
path,
|
|
691
|
+
name: HELPER_LABEL[name],
|
|
516
692
|
spawn: (file, args, spawnOptions) => this.spawn(file, args, spawnOptions),
|
|
517
693
|
env: name === "transcribe" ? { ...this.options.env, ...this.transcribeEnv() } : this.options.env,
|
|
518
694
|
log: this.options.log,
|
|
@@ -744,6 +920,26 @@ function defaultLocale(chosen: string | undefined): string {
|
|
|
744
920
|
}
|
|
745
921
|
|
|
746
922
|
/** Settings store a rate of 0.5–2 (1 natural); AVSpeechUtterance's natural rate is 0.5 of 0–1. */
|
|
923
|
+
const VOICE_QUALITIES: ReadonlySet<string> = new Set(["default", "enhanced", "premium", "unknown"]);
|
|
924
|
+
|
|
925
|
+
/** The helper's `speech-started.voice`, kept only when it is well-formed. */
|
|
926
|
+
function speechStart(voice: unknown): SpeechStart {
|
|
927
|
+
if (voice === null || typeof voice !== "object") return {};
|
|
928
|
+
const { id, name, language, locale, quality } = voice as Record<string, unknown>;
|
|
929
|
+
// Helpers after 0.3.0 send `locale` alongside `language` (same value); older ones only `language`.
|
|
930
|
+
const tag = typeof language === "string" ? language : typeof locale === "string" ? locale : undefined;
|
|
931
|
+
if (typeof id !== "string" || typeof name !== "string" || tag === undefined) return {};
|
|
932
|
+
return {
|
|
933
|
+
voice: {
|
|
934
|
+
id,
|
|
935
|
+
name,
|
|
936
|
+
language: tag,
|
|
937
|
+
locale: typeof locale === "string" ? locale : tag,
|
|
938
|
+
quality: typeof quality === "string" && VOICE_QUALITIES.has(quality) ? (quality as SpeechVoiceIdentity["quality"]) : "unknown",
|
|
939
|
+
},
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
|
|
747
943
|
function appleRate(rate: number): number {
|
|
748
944
|
return Math.min(1, Math.max(0.05, rate * 0.5));
|
|
749
945
|
}
|
|
@@ -21,19 +21,40 @@
|
|
|
21
21
|
* "file": "adea-voice-helper-0.2.0-macos-arm64.tar.gz",
|
|
22
22
|
* "sha256": "<archive sha256>",
|
|
23
23
|
* "executableSha256": "<sha256 of the adea-voice-helper executable>",
|
|
24
|
+
* "codeSha256": "<machoCodeDigest of the executable>",
|
|
24
25
|
* "bytes": 812345
|
|
25
26
|
* }
|
|
26
27
|
* }
|
|
27
28
|
* }
|
|
28
29
|
* }
|
|
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`.
|
|
30
37
|
*/
|
|
31
38
|
import { createHash } from "node:crypto";
|
|
32
39
|
import { spawnSync } from "node:child_process";
|
|
33
|
-
import {
|
|
34
|
-
|
|
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";
|
|
35
55
|
import { tmpdir } from "node:os";
|
|
36
56
|
import { CONTRACT_MAJOR, WIRE_VERSION, parseWireLine } from "../contract/wire";
|
|
57
|
+
import { isMachO, machoCodeDigest } from "./macho-digest";
|
|
37
58
|
|
|
38
59
|
export const HELPER_LOCK_SCHEMA = 1;
|
|
39
60
|
export const HELPER_NAMES = ["adea-voice-helper", "adea-transcribe-helper", "adea-tts-helper"] as const;
|
|
@@ -48,6 +69,8 @@ export interface HelperArtifactPin {
|
|
|
48
69
|
readonly file: string;
|
|
49
70
|
readonly sha256: string;
|
|
50
71
|
readonly executableSha256: string;
|
|
72
|
+
/** The executable's `machoCodeDigest` (0.2.1+): what a re-signed packaged copy still matches. */
|
|
73
|
+
readonly codeSha256?: string;
|
|
51
74
|
readonly bytes?: number;
|
|
52
75
|
}
|
|
53
76
|
|
|
@@ -58,12 +81,26 @@ export interface HelperLock {
|
|
|
58
81
|
readonly helpers: Readonly<Partial<Record<HelperName, Readonly<Partial<Record<HelperTarget, HelperArtifactPin>>>>>>;
|
|
59
82
|
}
|
|
60
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
|
+
|
|
61
92
|
/** What a staged directory records about itself, written next to the helpers. */
|
|
62
93
|
export interface StagedHelperRecord {
|
|
63
94
|
readonly schema: 1;
|
|
64
95
|
readonly version: string;
|
|
65
96
|
readonly target: HelperTarget;
|
|
66
|
-
readonly helpers: Readonly<Partial<Record<HelperName,
|
|
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>>;
|
|
67
104
|
}
|
|
68
105
|
|
|
69
106
|
export const STAGED_RECORD_FILE = "voice-helpers.json";
|
|
@@ -101,6 +138,9 @@ export function validateHelperLock(value: unknown): HelperLock {
|
|
|
101
138
|
if (typeof entry.executableSha256 !== "string" || !SHA256.test(entry.executableSha256)) {
|
|
102
139
|
fail(`${name}/${target}: executableSha256 must be 64 hex`);
|
|
103
140
|
}
|
|
141
|
+
if (entry.codeSha256 !== undefined && (typeof entry.codeSha256 !== "string" || !SHA256.test(entry.codeSha256))) {
|
|
142
|
+
fail(`${name}/${target}: codeSha256 must be 64 hex`);
|
|
143
|
+
}
|
|
104
144
|
if (entry.bytes !== undefined && (typeof entry.bytes !== "number" || entry.bytes <= 0 || entry.bytes > MAX_HELPER_ARCHIVE_BYTES)) {
|
|
105
145
|
fail(`${name}/${target}: bytes out of range`);
|
|
106
146
|
}
|
|
@@ -180,19 +220,15 @@ export async function stageVoiceHelpers(options: StageHelpersOptions): Promise<S
|
|
|
180
220
|
const outDir = resolve(options.outDir);
|
|
181
221
|
const handshake = options.handshake ?? options.target === currentHelperTarget();
|
|
182
222
|
const existing = readStagedRecord(outDir);
|
|
183
|
-
const
|
|
184
|
-
|
|
185
|
-
version: options.localDir ? `local+${options.lock.version}` : options.lock.version,
|
|
186
|
-
target: options.target,
|
|
187
|
-
helpers: {},
|
|
188
|
-
};
|
|
223
|
+
const helpers: Record<string, StagedHelperEntry> = {};
|
|
224
|
+
const version = options.localDir ? `local+${options.lock.version}` : options.lock.version;
|
|
189
225
|
mkdirSync(outDir, { recursive: true });
|
|
190
226
|
try {
|
|
191
227
|
for (const helper of options.helpers) {
|
|
192
228
|
const executable = join(outDir, helper);
|
|
193
229
|
if (options.localDir) {
|
|
194
230
|
stageLocal(options.localDir, helper, outDir);
|
|
195
|
-
|
|
231
|
+
helpers[helper] = { sha256: "local", executableSha256: sha256File(executable), ...codeDigestEntry(executable) };
|
|
196
232
|
} else {
|
|
197
233
|
const pin = helperPin(options.lock, helper, options.target);
|
|
198
234
|
if (!pin) throw new HelperLockError(`voice helper lock pins no ${helper} for ${options.target}`);
|
|
@@ -218,14 +254,25 @@ export async function stageVoiceHelpers(options: StageHelpersOptions): Promise<S
|
|
|
218
254
|
chmodSync(executable, 0o755);
|
|
219
255
|
log(`staged ${helper} ${options.lock.version} (${options.target})`);
|
|
220
256
|
}
|
|
221
|
-
|
|
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 };
|
|
222
262
|
}
|
|
223
|
-
if (handshake) assertHandshake(executable);
|
|
263
|
+
if (handshake) assertHandshake(executable, options.localDir ? {} : { release: options.lock.version });
|
|
224
264
|
}
|
|
225
265
|
} catch (error) {
|
|
226
266
|
rmSync(outDir, { recursive: true, force: true });
|
|
227
267
|
throw error;
|
|
228
268
|
}
|
|
269
|
+
const record: StagedHelperRecord = {
|
|
270
|
+
schema: 1,
|
|
271
|
+
version,
|
|
272
|
+
target: options.target,
|
|
273
|
+
helpers,
|
|
274
|
+
files: supportFileDigests(outDir, Object.keys(helpers)),
|
|
275
|
+
};
|
|
229
276
|
writeFileSync(join(outDir, STAGED_RECORD_FILE), `${JSON.stringify(record, null, 2)}\n`);
|
|
230
277
|
return record;
|
|
231
278
|
}
|
|
@@ -235,13 +282,30 @@ export interface VerifyStagedOptions {
|
|
|
235
282
|
readonly target: HelperTarget;
|
|
236
283
|
readonly dir: string;
|
|
237
284
|
readonly helpers: readonly HelperName[];
|
|
238
|
-
/**
|
|
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
|
+
*/
|
|
239
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;
|
|
240
297
|
}
|
|
241
298
|
|
|
242
299
|
/**
|
|
243
300
|
* The release gate: the packaged directory holds exactly the pinned helpers. Throws
|
|
244
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.
|
|
245
309
|
*/
|
|
246
310
|
export function verifyStagedVoiceHelpers(options: VerifyStagedOptions): void {
|
|
247
311
|
const dir = resolve(options.dir);
|
|
@@ -251,16 +315,37 @@ export function verifyStagedVoiceHelpers(options: VerifyStagedOptions): void {
|
|
|
251
315
|
throw new HelperLockError(`staged voice helpers are ${record.version}; the lock pins ${options.lock.version}`);
|
|
252
316
|
}
|
|
253
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-"));
|
|
254
319
|
for (const helper of options.helpers) {
|
|
255
320
|
const pin = helperPin(options.lock, helper, options.target);
|
|
256
321
|
if (!pin) throw new HelperLockError(`voice helper lock pins no ${helper} for ${options.target}`);
|
|
257
322
|
const executable = join(dir, helper);
|
|
258
|
-
if (!existsSync(executable)) throw new HelperLockError(`${helper} is missing from ${dir}`);
|
|
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
|
+
}
|
|
259
328
|
const actual = sha256File(executable);
|
|
260
329
|
if (actual !== pin.executableSha256) {
|
|
261
|
-
|
|
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 });
|
|
262
348
|
}
|
|
263
|
-
if (options.handshake ?? options.target === currentHelperTarget()) assertHandshake(executable);
|
|
264
349
|
}
|
|
265
350
|
}
|
|
266
351
|
|
|
@@ -274,11 +359,30 @@ export function readStagedRecord(dir: string): StagedHelperRecord | undefined {
|
|
|
274
359
|
}
|
|
275
360
|
}
|
|
276
361
|
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
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" });
|
|
280
376
|
if (run.error || run.status !== 0) {
|
|
281
|
-
|
|
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})` : ""}`);
|
|
282
386
|
}
|
|
283
387
|
const version = run.stdout
|
|
284
388
|
.split("\n")
|
|
@@ -290,6 +394,77 @@ export function assertHandshake(executable: string): void {
|
|
|
290
394
|
`${executable} speaks wire ${version.wire} / contract ${version.contract}; need wire ${WIRE_VERSION} / contract ${CONTRACT_MAJOR}`,
|
|
291
395
|
);
|
|
292
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
|
+
}
|
|
293
468
|
}
|
|
294
469
|
|
|
295
470
|
async function obtainArchive(
|