@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.
- package/README.md +136 -2
- package/dist/cli/helpers-cli.d.ts +2 -0
- package/dist/cli/helpers-cli.js +117 -0
- package/dist/contract/contract.d.ts +157 -0
- package/dist/contract/errors.d.ts +26 -0
- package/dist/contract/index.d.ts +10 -0
- package/dist/contract/index.js +64 -0
- package/dist/contract/session.d.ts +71 -0
- package/dist/contract/turns.d.ts +91 -0
- package/dist/contract/wire.d.ts +279 -0
- package/dist/desktop/conversation.d.ts +86 -0
- package/dist/desktop/desktop-voice.d.ts +212 -0
- package/dist/desktop/helper-lock.d.ts +121 -0
- package/dist/desktop/helper-process.d.ts +96 -0
- package/dist/desktop/index.d.ts +9 -0
- package/dist/desktop/index.js +1454 -0
- package/dist/desktop/macho-digest.d.ts +9 -0
- package/dist/index-7n7epq1a.js +47 -0
- package/dist/index-a7d617zr.js +295 -0
- package/dist/index-ght8wwpd.js +156 -0
- package/dist/index-m4g2tpeq.js +522 -0
- package/dist/index-r4hz8gk0.js +10 -0
- package/dist/index-tvz9s9nz.js +77 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +96 -0
- package/dist/settings/index.d.ts +5 -0
- package/dist/settings/index.js +34 -0
- package/dist/settings/settings.d.ts +163 -0
- package/dist/web/index.d.ts +16 -0
- package/dist/web/index.js +1697 -0
- package/dist/web/stt/speech-recognition.d.ts +226 -0
- package/dist/web/tts/locale-match.d.ts +40 -0
- package/dist/web/tts/phonon.d.ts +139 -0
- package/dist/web/tts/player.d.ts +115 -0
- package/dist/web/tts/system-voices.d.ts +162 -0
- package/dist/web/turns.d.ts +91 -0
- package/package.json +68 -4
- package/src/cli/helpers-cli.ts +135 -0
- package/src/contract/contract.ts +393 -0
- package/src/contract/errors.ts +98 -0
- package/src/contract/index.ts +10 -0
- package/src/contract/session.ts +77 -0
- package/src/contract/turns.ts +48 -0
- package/src/contract/wire.ts +384 -0
- package/src/desktop/conversation.ts +347 -0
- package/src/desktop/desktop-voice.ts +1129 -0
- package/src/desktop/helper-lock.ts +550 -0
- package/src/desktop/helper-process.ts +408 -0
- package/src/desktop/index.ts +18 -0
- package/src/desktop/macho-digest.ts +135 -0
- package/src/index.ts +7 -0
- package/src/settings/index.ts +5 -0
- package/src/settings/settings.ts +478 -0
- package/src/web/index.ts +16 -0
- package/src/web/stt/speech-recognition.ts +1013 -0
- package/src/web/tts/locale-match.ts +131 -0
- package/src/web/tts/phonon.ts +386 -0
- package/src/web/tts/player.ts +271 -0
- package/src/web/tts/system-voices.ts +510 -0
- package/src/web/turns.ts +235 -0
|
@@ -0,0 +1,1129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@adea-ai/voice/desktop`: the one desktop speech client every Adea app uses.
|
|
3
|
+
*
|
|
4
|
+
* It runs the pinned helpers the app bundles — `adea-voice-helper` (Apple speech on macOS),
|
|
5
|
+
* `adea-transcribe-helper` (transcribe.cpp) and `adea-tts-helper` (audio.cpp) — and exposes them
|
|
6
|
+
* as providers of the shared contract. Routing, availability reasons, error codes, cancellation and
|
|
7
|
+
* the privacy rules live here and in the helpers; an app only renders what this returns.
|
|
8
|
+
*
|
|
9
|
+
* Rules it keeps for every host:
|
|
10
|
+
* - a helper that is missing from the build is an explicit `providerNotRegistered`, never a
|
|
11
|
+
* silent substitute; a helper on another wire/contract major is refused;
|
|
12
|
+
* - one dictation at a time; a second is `busy`;
|
|
13
|
+
* - every dictation ends in exactly one terminal event (`final`, `failed` or `cancelled`), even if
|
|
14
|
+
* the helper crashes or stops answering (the process is then killed and restarted on demand);
|
|
15
|
+
* - no network: every desktop provider runs on the device, and model installs happen only through
|
|
16
|
+
* `installAssets`, which a person starts.
|
|
17
|
+
*/
|
|
18
|
+
import {
|
|
19
|
+
AVAILABLE,
|
|
20
|
+
VOICE_CONTRACT,
|
|
21
|
+
route,
|
|
22
|
+
unavailable,
|
|
23
|
+
type VoicePlatform,
|
|
24
|
+
type VoiceProvider,
|
|
25
|
+
type VoiceProviderAvailability,
|
|
26
|
+
type VoiceProviderDescriptor,
|
|
27
|
+
type VoiceProviderKind,
|
|
28
|
+
type VoiceRoutingDecision,
|
|
29
|
+
type VoiceRoutingPolicy,
|
|
30
|
+
} from "../contract/contract";
|
|
31
|
+
import { VoiceError, type VoiceErrorCode } from "../contract/errors";
|
|
32
|
+
import type { PartialTranscript, SessionEvent, TranscriptionSession } from "../contract/session";
|
|
33
|
+
import type {
|
|
34
|
+
AppleStatusEvent,
|
|
35
|
+
CombinedPermission,
|
|
36
|
+
LocaleEvent,
|
|
37
|
+
PermissionEvent,
|
|
38
|
+
PermissionPart,
|
|
39
|
+
SpeechVoiceIdentity,
|
|
40
|
+
SynthesisStatusEvent,
|
|
41
|
+
TranscribeStatusEvent,
|
|
42
|
+
VoiceEvent,
|
|
43
|
+
WireEvent,
|
|
44
|
+
} from "../contract/wire";
|
|
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";
|
|
48
|
+
import { HelperConnection, IncompatibleHelperError, nextRequestId, nodeSpawner, type HelperSpawner } from "./helper-process";
|
|
49
|
+
|
|
50
|
+
// MARK: - Provider ids and the desktop routing table
|
|
51
|
+
|
|
52
|
+
export const APPLE_ANALYZER_ID = "apple.analyzer";
|
|
53
|
+
export const APPLE_LEGACY_ID = "apple.legacy";
|
|
54
|
+
export const APPLE_VOICES_ID = "apple.system-voices";
|
|
55
|
+
export const TRANSCRIBE_CPP_ID = "transcribe.cpp";
|
|
56
|
+
export const AUDIO_CPP_ID = "audio.cpp";
|
|
57
|
+
|
|
58
|
+
export type DesktopOS = "darwin" | "win32" | "linux";
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* The SDK-wide desktop table (docs/provider-contract.md, "Default matrix"). transcribe.cpp is the
|
|
62
|
+
* one optional desktop STT engine on macOS: a person selects it, it is never a silent fallback.
|
|
63
|
+
*/
|
|
64
|
+
export function desktopRoutingPolicy(os: DesktopOS): VoiceRoutingPolicy {
|
|
65
|
+
if (os === "darwin") {
|
|
66
|
+
return {
|
|
67
|
+
chains: { speechToText: [APPLE_ANALYZER_ID, APPLE_LEGACY_ID], textToSpeech: [APPLE_VOICES_ID] },
|
|
68
|
+
allowsOptInModelInstallation: false,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
chains: { speechToText: [TRANSCRIBE_CPP_ID], textToSpeech: [AUDIO_CPP_ID] },
|
|
73
|
+
allowsOptInModelInstallation: false,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const DESKTOP_PLATFORMS: readonly VoicePlatform[] = ["macOS", "windows", "linux"];
|
|
78
|
+
|
|
79
|
+
function descriptor(
|
|
80
|
+
id: string,
|
|
81
|
+
displayName: string,
|
|
82
|
+
kind: VoiceProviderKind,
|
|
83
|
+
platforms: readonly VoicePlatform[],
|
|
84
|
+
extra: Partial<VoiceProviderDescriptor> = {},
|
|
85
|
+
): VoiceProviderDescriptor {
|
|
86
|
+
return {
|
|
87
|
+
id,
|
|
88
|
+
displayName,
|
|
89
|
+
kind,
|
|
90
|
+
platforms,
|
|
91
|
+
execution: "onDevice",
|
|
92
|
+
contract: VOICE_CONTRACT,
|
|
93
|
+
requiresModelDownload: false,
|
|
94
|
+
modelFamilies: [],
|
|
95
|
+
licenses: [],
|
|
96
|
+
capabilities: { streamingPartials: kind === "speechToText", trueCancellation: true, localeSelection: true },
|
|
97
|
+
...extra,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export const DESKTOP_DESCRIPTORS: Readonly<Record<string, VoiceProviderDescriptor>> = {
|
|
102
|
+
[APPLE_ANALYZER_ID]: descriptor(APPLE_ANALYZER_ID, "Apple Speech", "speechToText", ["macOS"]),
|
|
103
|
+
[APPLE_LEGACY_ID]: descriptor(APPLE_LEGACY_ID, "Apple Speech (compatibility)", "speechToText", ["macOS"]),
|
|
104
|
+
[TRANSCRIBE_CPP_ID]: descriptor(TRANSCRIBE_CPP_ID, "transcribe.cpp", "speechToText", DESKTOP_PLATFORMS, {
|
|
105
|
+
requiresModelDownload: true,
|
|
106
|
+
modelFamilies: ["whisper", "parakeet", "canary", "moonshine"],
|
|
107
|
+
}),
|
|
108
|
+
[APPLE_VOICES_ID]: descriptor(APPLE_VOICES_ID, "Apple voices", "textToSpeech", ["macOS"], {
|
|
109
|
+
capabilities: { trueCancellation: true, voiceSelection: true, utteranceQueueing: true, wordBoundaryPause: true, localeSelection: true },
|
|
110
|
+
}),
|
|
111
|
+
[AUDIO_CPP_ID]: descriptor(AUDIO_CPP_ID, "audio.cpp", "textToSpeech", DESKTOP_PLATFORMS, {
|
|
112
|
+
requiresModelDownload: true,
|
|
113
|
+
modelFamilies: ["phonon", "kokoro", "qwen3-tts"],
|
|
114
|
+
capabilities: { trueCancellation: true, voiceSelection: true, utteranceQueueing: true },
|
|
115
|
+
}),
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
// MARK: - Public types
|
|
119
|
+
|
|
120
|
+
export interface DesktopHelperPaths {
|
|
121
|
+
/** `adea-voice-helper` (macOS). `null`/absent: not in this build. */
|
|
122
|
+
readonly voice?: string | null;
|
|
123
|
+
/** `adea-transcribe-helper`. */
|
|
124
|
+
readonly transcribe?: string | null;
|
|
125
|
+
/** `adea-tts-helper`. */
|
|
126
|
+
readonly tts?: string | null;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export interface DesktopVoiceOptions {
|
|
130
|
+
readonly helpers: DesktopHelperPaths;
|
|
131
|
+
readonly os?: DesktopOS;
|
|
132
|
+
readonly spawn?: HelperSpawner;
|
|
133
|
+
/** Extra environment for the helpers (never secrets: the helpers need none). */
|
|
134
|
+
readonly env?: Readonly<Record<string, string | undefined>>;
|
|
135
|
+
readonly log?: (message: string) => void;
|
|
136
|
+
/** A dictation never runs longer than this. Default 75 s (the helper's own cap is 60 s). */
|
|
137
|
+
readonly maxListenMs?: number;
|
|
138
|
+
/** After `end`/`cancel`, how long the helper gets to send the terminal event. Default 5 s. */
|
|
139
|
+
readonly terminalGraceMs?: number;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
export type PermissionState = CombinedPermission;
|
|
143
|
+
|
|
144
|
+
export interface PermissionReport {
|
|
145
|
+
/** The combined answer for dictation. */
|
|
146
|
+
readonly state: PermissionState;
|
|
147
|
+
readonly microphone: PermissionPart | "unknown";
|
|
148
|
+
readonly speech: PermissionPart | "unknown";
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export interface ProviderStatus {
|
|
152
|
+
readonly id: string;
|
|
153
|
+
readonly displayName: string;
|
|
154
|
+
readonly kind: VoiceProviderKind;
|
|
155
|
+
/** Whether this build bundles the provider's helper. */
|
|
156
|
+
readonly bundled: boolean;
|
|
157
|
+
readonly availability: VoiceProviderAvailability;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export interface VoiceCapabilities {
|
|
161
|
+
readonly os: DesktopOS;
|
|
162
|
+
readonly speechToText: VoiceRoutingDecision;
|
|
163
|
+
readonly textToSpeech: VoiceRoutingDecision;
|
|
164
|
+
readonly providers: readonly ProviderStatus[];
|
|
165
|
+
readonly permission: PermissionReport;
|
|
166
|
+
/** Local models transcribe.cpp can see (BYOM folders included). */
|
|
167
|
+
readonly localModels: TranscribeStatusEvent["models"];
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export interface DictationRequest {
|
|
171
|
+
readonly settings: VoiceSettings;
|
|
172
|
+
/** BCP-47; defaults to the settings' locale, then the system language. */
|
|
173
|
+
readonly locale?: string;
|
|
174
|
+
readonly onPartial?: (partial: PartialTranscript & { readonly text: string }) => void;
|
|
175
|
+
readonly signal?: AbortSignal;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** A running dictation: the shared session contract plus the resolved route. */
|
|
179
|
+
export interface DesktopDictation extends TranscriptionSession {
|
|
180
|
+
readonly provider: string;
|
|
181
|
+
readonly locale: string;
|
|
182
|
+
/** Resolves with the final text; rejects with `VoiceError` (`cancelled`, `no_speech`, …). */
|
|
183
|
+
readonly result: Promise<string>;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export interface SpeakRequest {
|
|
187
|
+
readonly settings: VoiceSettings;
|
|
188
|
+
readonly text: string;
|
|
189
|
+
readonly locale?: string;
|
|
190
|
+
readonly voice?: string;
|
|
191
|
+
readonly rate?: number;
|
|
192
|
+
/** `replace` (default) stops what is playing; `after-current` queues. */
|
|
193
|
+
readonly queue?: "replace" | "after-current";
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
export type SpeechOutcome = "finished" | "cancelled";
|
|
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
|
+
|
|
207
|
+
export interface DesktopSpeech {
|
|
208
|
+
readonly id: string;
|
|
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>;
|
|
216
|
+
/** Resolves when playback ends or is cancelled; rejects with `VoiceError` on failure. */
|
|
217
|
+
readonly done: Promise<SpeechOutcome>;
|
|
218
|
+
cancel(): Promise<void>;
|
|
219
|
+
}
|
|
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
|
+
|
|
237
|
+
export interface DesktopVoiceInfo {
|
|
238
|
+
readonly id: string;
|
|
239
|
+
readonly name: string;
|
|
240
|
+
readonly locale: string;
|
|
241
|
+
readonly quality: VoiceEvent["quality"];
|
|
242
|
+
readonly provider: string;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
export interface LocaleAsset {
|
|
246
|
+
readonly locale: string;
|
|
247
|
+
readonly status: LocaleEvent["status"];
|
|
248
|
+
readonly canInstall: boolean;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
export interface InstallRequest {
|
|
252
|
+
readonly locale: string;
|
|
253
|
+
readonly onProgress?: (fraction: number | null) => void;
|
|
254
|
+
readonly signal?: AbortSignal;
|
|
255
|
+
}
|
|
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
|
+
|
|
277
|
+
export interface DesktopVoice {
|
|
278
|
+
/** Which helpers this build bundles (synchronous, no process started). */
|
|
279
|
+
bundled(): Readonly<Record<"voice" | "transcribe" | "tts", boolean>>;
|
|
280
|
+
capabilities(settings: VoiceSettings, locale?: string): Promise<VoiceCapabilities>;
|
|
281
|
+
permission(options?: { readonly request?: boolean }): Promise<PermissionReport>;
|
|
282
|
+
listen(request: DictationRequest): Promise<DesktopDictation>;
|
|
283
|
+
speak(request: SpeakRequest): Promise<DesktopSpeech>;
|
|
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>;
|
|
291
|
+
voices(settings: VoiceSettings, locale?: string): Promise<readonly DesktopVoiceInfo[]>;
|
|
292
|
+
locales(): Promise<readonly LocaleAsset[]>;
|
|
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>;
|
|
300
|
+
/** Stops every helper. The instance can be used again; helpers restart on demand. */
|
|
301
|
+
dispose(): Promise<void>;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
// MARK: - Implementation
|
|
305
|
+
|
|
306
|
+
export function createDesktopVoice(options: DesktopVoiceOptions): DesktopVoice {
|
|
307
|
+
return new DesktopVoiceService(options);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const HELPER_LABEL = { voice: "adea-voice-helper", transcribe: "adea-transcribe-helper", tts: "adea-tts-helper" } as const;
|
|
311
|
+
type HelperName = keyof typeof HELPER_LABEL;
|
|
312
|
+
|
|
313
|
+
class DesktopVoiceService implements DesktopVoice {
|
|
314
|
+
private readonly os: DesktopOS;
|
|
315
|
+
private readonly connections = new Map<HelperName, HelperConnection>();
|
|
316
|
+
private transcribeFolders = "";
|
|
317
|
+
/** The folders the running transcribe connection was started with. */
|
|
318
|
+
private transcribeConnectionFolders = "";
|
|
319
|
+
private active: DictationSession | undefined;
|
|
320
|
+
private activeConversation: Conversation | undefined;
|
|
321
|
+
private readonly spawner: HelperSpawner;
|
|
322
|
+
|
|
323
|
+
constructor(private readonly options: DesktopVoiceOptions) {
|
|
324
|
+
this.os = options.os ?? (process.platform as DesktopOS);
|
|
325
|
+
this.spawner = options.spawn ?? nodeSpawner;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
bundled() {
|
|
329
|
+
return {
|
|
330
|
+
voice: this.os === "darwin" && Boolean(this.options.helpers.voice),
|
|
331
|
+
transcribe: Boolean(this.options.helpers.transcribe),
|
|
332
|
+
tts: Boolean(this.options.helpers.tts),
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// MARK: Capabilities
|
|
337
|
+
|
|
338
|
+
async capabilities(settings: VoiceSettings, locale = defaultLocale(settings.stt.locale)): Promise<VoiceCapabilities> {
|
|
339
|
+
const probe = new Probe(this, settings);
|
|
340
|
+
const providers = this.providers(probe);
|
|
341
|
+
const policy = routingPolicyFor(withModelChoice(settings), desktopRoutingPolicy(this.os));
|
|
342
|
+
const ttsLocale = settings.tts.locale ?? locale;
|
|
343
|
+
const [speechToText, textToSpeech, permission] = await Promise.all([
|
|
344
|
+
route({ kind: "speechToText", locale, providers, policy }),
|
|
345
|
+
route({ kind: "textToSpeech", locale: ttsLocale, providers, policy }),
|
|
346
|
+
probe.permission(),
|
|
347
|
+
]);
|
|
348
|
+
const statuses = await Promise.all(
|
|
349
|
+
Object.values(DESKTOP_DESCRIPTORS)
|
|
350
|
+
.filter((entry) => entry.platforms.includes(platformOf(this.os)))
|
|
351
|
+
.map(async (entry): Promise<ProviderStatus> => {
|
|
352
|
+
const provider = providers.find((candidate) => candidate.descriptor.id === entry.id);
|
|
353
|
+
const kindLocale = entry.kind === "speechToText" ? locale : ttsLocale;
|
|
354
|
+
return {
|
|
355
|
+
id: entry.id,
|
|
356
|
+
displayName: entry.displayName,
|
|
357
|
+
kind: entry.kind,
|
|
358
|
+
bundled: provider !== undefined,
|
|
359
|
+
availability: provider
|
|
360
|
+
? await provider.availability(kindLocale)
|
|
361
|
+
: unavailable("providerNotRegistered", `${entry.displayName} is not included in this build.`, {
|
|
362
|
+
kind: "chooseAnotherProvider",
|
|
363
|
+
detail: "Choose another engine.",
|
|
364
|
+
}),
|
|
365
|
+
};
|
|
366
|
+
}),
|
|
367
|
+
);
|
|
368
|
+
const localModels = this.bundled().transcribe ? (await probe.transcribeStatus(locale).catch(() => undefined))?.models ?? [] : [];
|
|
369
|
+
return { os: this.os, speechToText, textToSpeech, providers: statuses, permission, localModels };
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
async permission(options: { readonly request?: boolean } = {}): Promise<PermissionReport> {
|
|
373
|
+
if (!this.bundled().voice) {
|
|
374
|
+
// Local-model engines read the microphone through the OS prompt on first capture.
|
|
375
|
+
return { state: this.bundled().transcribe ? "prompt" : "unavailable", microphone: "unknown", speech: "unknown" };
|
|
376
|
+
}
|
|
377
|
+
const event = await this.connection("voice").request(
|
|
378
|
+
{ cmd: "permission", request: options.request === true },
|
|
379
|
+
(candidate): candidate is PermissionEvent => candidate.event === "permission",
|
|
380
|
+
// A prompt waits for a person.
|
|
381
|
+
{ timeoutMs: options.request ? null : undefined },
|
|
382
|
+
);
|
|
383
|
+
return { state: event.state, microphone: event.microphone ?? "unknown", speech: event.speech ?? "unknown" };
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
// MARK: Dictation
|
|
387
|
+
|
|
388
|
+
async listen(request: DictationRequest): Promise<DesktopDictation> {
|
|
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
|
+
}
|
|
393
|
+
if (request.signal?.aborted) throw new VoiceError("cancelled", "Dictation was cancelled.");
|
|
394
|
+
const locale = request.locale ?? defaultLocale(request.settings.stt.locale);
|
|
395
|
+
const capabilities = await this.capabilities(request.settings, locale);
|
|
396
|
+
const decision = capabilities.speechToText;
|
|
397
|
+
if (!decision.route || decision.availability.status !== "available") {
|
|
398
|
+
throw unavailableError(decision);
|
|
399
|
+
}
|
|
400
|
+
if (this.active && !this.active.isTerminal) throw new VoiceError("busy", "A dictation is already running.");
|
|
401
|
+
const providerID = decision.route.descriptor.id;
|
|
402
|
+
const helper: HelperName = providerID === TRANSCRIBE_CPP_ID ? "transcribe" : "voice";
|
|
403
|
+
if (helper === "transcribe") this.applyTranscribeFolders(request.settings);
|
|
404
|
+
const engine = providerID === APPLE_ANALYZER_ID ? "analyzer" : providerID === APPLE_LEGACY_ID ? "legacy" : undefined;
|
|
405
|
+
const session = new DictationSession({
|
|
406
|
+
connection: this.connection(helper),
|
|
407
|
+
provider: providerID,
|
|
408
|
+
locale,
|
|
409
|
+
engine,
|
|
410
|
+
onPartial: request.onPartial,
|
|
411
|
+
maxListenMs: this.options.maxListenMs ?? 75_000,
|
|
412
|
+
terminalGraceMs: this.options.terminalGraceMs ?? 5_000,
|
|
413
|
+
onStuck: () => void this.connection(helper).stop(),
|
|
414
|
+
});
|
|
415
|
+
this.active = session;
|
|
416
|
+
if (request.signal) {
|
|
417
|
+
// Aborted while the capabilities were probed: the helper was already asked to listen.
|
|
418
|
+
if (request.signal.aborted) void session.cancel();
|
|
419
|
+
else request.signal.addEventListener("abort", () => void session.cancel(), { once: true });
|
|
420
|
+
}
|
|
421
|
+
await session.started;
|
|
422
|
+
return session;
|
|
423
|
+
}
|
|
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
|
+
|
|
482
|
+
// MARK: Speech
|
|
483
|
+
|
|
484
|
+
async speak(request: SpeakRequest): Promise<DesktopSpeech> {
|
|
485
|
+
const text = request.text.trim();
|
|
486
|
+
if (text.length === 0) throw new VoiceError("bad_request", "There is nothing to read aloud.");
|
|
487
|
+
const locale = request.locale ?? defaultLocale(request.settings.tts.locale);
|
|
488
|
+
const decision = await route({
|
|
489
|
+
kind: "textToSpeech",
|
|
490
|
+
locale,
|
|
491
|
+
providers: this.providers(new Probe(this, request.settings)),
|
|
492
|
+
policy: routingPolicyFor(request.settings, desktopRoutingPolicy(this.os)),
|
|
493
|
+
});
|
|
494
|
+
if (!decision.route || decision.availability.status !== "available") throw unavailableError(decision);
|
|
495
|
+
const providerID = decision.route.descriptor.id;
|
|
496
|
+
const connection = this.connection(providerID === AUDIO_CPP_ID ? "tts" : "voice");
|
|
497
|
+
const id = nextRequestId("speech-");
|
|
498
|
+
const voice = request.voice ?? request.settings.tts.voice;
|
|
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
|
+
});
|
|
504
|
+
const done = connection
|
|
505
|
+
.request(
|
|
506
|
+
{
|
|
507
|
+
cmd: "speak",
|
|
508
|
+
id,
|
|
509
|
+
text,
|
|
510
|
+
locale,
|
|
511
|
+
...(voice ? { voice } : {}),
|
|
512
|
+
// Apple's rate scale differs; audio.cpp's `speaking_rate` is the settings' scale (1 natural).
|
|
513
|
+
...(rate !== undefined ? { rate: providerID === AUDIO_CPP_ID ? rate : appleRate(rate) } : {}),
|
|
514
|
+
queue: request.queue ?? "replace",
|
|
515
|
+
},
|
|
516
|
+
(event): event is WireEvent =>
|
|
517
|
+
event.event === "speech-finished" || event.event === "speech-cancelled" || event.event === "speech-error",
|
|
518
|
+
{
|
|
519
|
+
timeoutMs: null,
|
|
520
|
+
onEvent: (event) => {
|
|
521
|
+
if (event.event === "speech-started") markStarted(speechStart(event.voice));
|
|
522
|
+
},
|
|
523
|
+
},
|
|
524
|
+
)
|
|
525
|
+
.finally(() => markStarted(undefined))
|
|
526
|
+
.then((event): SpeechOutcome => {
|
|
527
|
+
if (event.event === "speech-error") throw new VoiceError(event.code, event.message ?? "Speech failed.");
|
|
528
|
+
return event.event === "speech-finished" ? "finished" : "cancelled";
|
|
529
|
+
});
|
|
530
|
+
// A rejected `done` must not become an unhandled rejection when the caller only cancels.
|
|
531
|
+
done.catch(() => undefined);
|
|
532
|
+
return {
|
|
533
|
+
id,
|
|
534
|
+
provider: providerID,
|
|
535
|
+
started,
|
|
536
|
+
done,
|
|
537
|
+
cancel: async () => {
|
|
538
|
+
await connection.send({ cmd: "speech-stop" }).catch(() => undefined);
|
|
539
|
+
},
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
async stopSpeaking(): Promise<void> {
|
|
544
|
+
const sends: Promise<void>[] = [];
|
|
545
|
+
for (const name of ["voice", "tts"] as const) {
|
|
546
|
+
const connection = this.connections.get(name);
|
|
547
|
+
if (connection?.running) sends.push(connection.send({ cmd: "speech-stop" }).catch(() => undefined));
|
|
548
|
+
}
|
|
549
|
+
await Promise.all(sends);
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
async voices(settings: VoiceSettings, locale?: string): Promise<readonly DesktopVoiceInfo[]> {
|
|
553
|
+
const exact = await this.voicesFor(locale);
|
|
554
|
+
if (exact.length > 0 || !locale) return exact;
|
|
555
|
+
// No voice for the exact region (es-419 on a Mac with es-ES and es-MX voices): offer the
|
|
556
|
+
// language's voices, so a person can still pick one. Region first, then the rest.
|
|
557
|
+
const language = locale.split(/[-_]/)[0]!.toLowerCase();
|
|
558
|
+
return (await this.voicesFor(undefined)).filter((voice) => voice.locale.split(/[-_]/)[0]!.toLowerCase() === language);
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
private async voicesFor(locale: string | undefined): Promise<readonly DesktopVoiceInfo[]> {
|
|
562
|
+
const lists = await Promise.all(
|
|
563
|
+
(["voice", "tts"] as const)
|
|
564
|
+
.filter((name) => this.bundled()[name])
|
|
565
|
+
.map(async (name) => {
|
|
566
|
+
const collected: DesktopVoiceInfo[] = [];
|
|
567
|
+
const provider = name === "voice" ? APPLE_VOICES_ID : AUDIO_CPP_ID;
|
|
568
|
+
await this.connection(name).request(
|
|
569
|
+
{ cmd: "voices", ...(locale ? { locale } : {}) },
|
|
570
|
+
(event): event is WireEvent => event.event === "voices-done",
|
|
571
|
+
{
|
|
572
|
+
onEvent: (event) => {
|
|
573
|
+
if (event.event === "voice") {
|
|
574
|
+
collected.push({ id: event.id, name: event.name, locale: event.locale, quality: event.quality, provider });
|
|
575
|
+
}
|
|
576
|
+
},
|
|
577
|
+
},
|
|
578
|
+
).catch((error: unknown) => {
|
|
579
|
+
this.options.log?.(`voices from ${HELPER_LABEL[name]}: ${String(error)}`);
|
|
580
|
+
});
|
|
581
|
+
return collected;
|
|
582
|
+
}),
|
|
583
|
+
);
|
|
584
|
+
return lists.flat();
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
async locales(): Promise<readonly LocaleAsset[]> {
|
|
588
|
+
if (!this.bundled().voice) return [];
|
|
589
|
+
const collected: LocaleAsset[] = [];
|
|
590
|
+
await this.connection("voice").request({ cmd: "locales" }, (event): event is WireEvent => event.event === "locales-done", {
|
|
591
|
+
onEvent: (event) => {
|
|
592
|
+
// Apple reports `es_MX`; the rest of the stack speaks BCP-47.
|
|
593
|
+
if (event.event === "locale") collected.push({ locale: event.locale.replace(/_/g, "-"), status: event.status, canInstall: event.canInstall });
|
|
594
|
+
},
|
|
595
|
+
});
|
|
596
|
+
return collected;
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
async installAssets(request: InstallRequest): Promise<void> {
|
|
600
|
+
if (!this.bundled().voice) throw new VoiceError("unavailable", "Speech assets are managed by the system on this device.");
|
|
601
|
+
const connection = this.connection("voice");
|
|
602
|
+
const id = nextRequestId("install-");
|
|
603
|
+
// Aborting stops the download in the helper too, not only this wait.
|
|
604
|
+
const onAbort = () => void connection.send({ cmd: "install-cancel", id }).catch(() => undefined);
|
|
605
|
+
request.signal?.addEventListener("abort", onAbort, { once: true });
|
|
606
|
+
await connection.request(
|
|
607
|
+
{ cmd: "install-assets", id, locale: request.locale },
|
|
608
|
+
(event): event is WireEvent => event.event === "asset-installed",
|
|
609
|
+
{
|
|
610
|
+
timeoutMs: null,
|
|
611
|
+
signal: request.signal,
|
|
612
|
+
onEvent: (event) => {
|
|
613
|
+
if (event.event === "asset-progress") request.onProgress?.(event.fraction);
|
|
614
|
+
},
|
|
615
|
+
},
|
|
616
|
+
).finally(() => request.signal?.removeEventListener("abort", onAbort));
|
|
617
|
+
}
|
|
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
|
+
|
|
655
|
+
async dispose(): Promise<void> {
|
|
656
|
+
await this.active?.cancel().catch(() => undefined);
|
|
657
|
+
await this.activeConversation?.cancel().catch(() => undefined);
|
|
658
|
+
await Promise.all([...this.connections.values()].map((connection) => connection.stop()));
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
// MARK: Internals
|
|
662
|
+
|
|
663
|
+
/** The providers this build can offer (helpers present on this OS). */
|
|
664
|
+
providers(probe: Probe): VoiceProvider[] {
|
|
665
|
+
const bundled = this.bundled();
|
|
666
|
+
const providers: VoiceProvider[] = [];
|
|
667
|
+
if (bundled.voice) {
|
|
668
|
+
providers.push(
|
|
669
|
+
{ descriptor: DESKTOP_DESCRIPTORS[APPLE_ANALYZER_ID]!, availability: (locale) => probe.apple(locale, "analyzer") },
|
|
670
|
+
{ descriptor: DESKTOP_DESCRIPTORS[APPLE_LEGACY_ID]!, availability: (locale) => probe.apple(locale, "legacy") },
|
|
671
|
+
{ descriptor: DESKTOP_DESCRIPTORS[APPLE_VOICES_ID]!, availability: (locale) => probe.appleVoices(locale) },
|
|
672
|
+
);
|
|
673
|
+
}
|
|
674
|
+
if (bundled.transcribe) {
|
|
675
|
+
providers.push({ descriptor: DESKTOP_DESCRIPTORS[TRANSCRIBE_CPP_ID]!, availability: (locale) => probe.transcribe(locale) });
|
|
676
|
+
}
|
|
677
|
+
if (bundled.tts) {
|
|
678
|
+
providers.push({ descriptor: DESKTOP_DESCRIPTORS[AUDIO_CPP_ID]!, availability: (locale) => probe.synthesis(locale) });
|
|
679
|
+
}
|
|
680
|
+
return providers;
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
connection(name: HelperName): HelperConnection {
|
|
684
|
+
let connection = this.connections.get(name);
|
|
685
|
+
if (connection) return connection;
|
|
686
|
+
const path = this.options.helpers[name];
|
|
687
|
+
if (!path) throw new VoiceError("unavailable", `${HELPER_LABEL[name]} is not included in this build.`);
|
|
688
|
+
if (name === "transcribe") this.transcribeConnectionFolders = this.transcribeFolders;
|
|
689
|
+
connection = new HelperConnection({
|
|
690
|
+
path,
|
|
691
|
+
name: HELPER_LABEL[name],
|
|
692
|
+
spawn: (file, args, spawnOptions) => this.spawn(file, args, spawnOptions),
|
|
693
|
+
env: name === "transcribe" ? { ...this.options.env, ...this.transcribeEnv() } : this.options.env,
|
|
694
|
+
log: this.options.log,
|
|
695
|
+
});
|
|
696
|
+
this.connections.set(name, connection);
|
|
697
|
+
return connection;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
private spawn(file: string, args: readonly string[], spawnOptions: { env?: Readonly<Record<string, string | undefined>> }) {
|
|
701
|
+
return this.spawner(file, args, spawnOptions);
|
|
702
|
+
}
|
|
703
|
+
|
|
704
|
+
private transcribeEnv(): Record<string, string> {
|
|
705
|
+
return this.transcribeFolders ? { ADEA_TRANSCRIBE_MODEL_DIRS: this.transcribeFolders } : {};
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
/** BYOM folders reach transcribe.cpp through its environment; a change restarts it when idle. */
|
|
709
|
+
applyTranscribeFolders(settings: VoiceSettings): void {
|
|
710
|
+
this.transcribeFolders = settings.models.folders.join(this.os === "win32" ? ";" : ":");
|
|
711
|
+
const existing = this.connections.get("transcribe");
|
|
712
|
+
// Compared with what the running helper got, so a change made mid-dictation still applies
|
|
713
|
+
// on the next call once the dictation has ended.
|
|
714
|
+
if (!existing || this.transcribeConnectionFolders === this.transcribeFolders) return;
|
|
715
|
+
if (!(this.active && !this.active.isTerminal && this.active.provider === TRANSCRIBE_CPP_ID)) {
|
|
716
|
+
this.connections.delete("transcribe");
|
|
717
|
+
void existing.stop();
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
/** One capability pass: each helper is asked once per locale, however many providers ask. */
|
|
723
|
+
class Probe {
|
|
724
|
+
private readonly cache = new Map<string, Promise<unknown>>();
|
|
725
|
+
|
|
726
|
+
constructor(
|
|
727
|
+
private readonly service: DesktopVoiceService,
|
|
728
|
+
private readonly settings: VoiceSettings,
|
|
729
|
+
) {}
|
|
730
|
+
|
|
731
|
+
private once<T>(key: string, load: () => Promise<T>): Promise<T> {
|
|
732
|
+
let entry = this.cache.get(key) as Promise<T> | undefined;
|
|
733
|
+
if (!entry) {
|
|
734
|
+
entry = load();
|
|
735
|
+
this.cache.set(key, entry);
|
|
736
|
+
}
|
|
737
|
+
return entry;
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
permission(): Promise<PermissionReport> {
|
|
741
|
+
return this.once("permission", () =>
|
|
742
|
+
this.service.permission().catch(
|
|
743
|
+
(): PermissionReport => ({ state: "unavailable", microphone: "unknown", speech: "unknown" }),
|
|
744
|
+
),
|
|
745
|
+
);
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
appleStatus(locale: string): Promise<AppleStatusEvent> {
|
|
749
|
+
return this.once(`apple:${locale}`, () =>
|
|
750
|
+
this.service
|
|
751
|
+
.connection("voice")
|
|
752
|
+
.request({ cmd: "status", locale }, (event): event is AppleStatusEvent => event.event === "status"),
|
|
753
|
+
);
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
async apple(locale: string, engine: "analyzer" | "legacy"): Promise<VoiceProviderAvailability> {
|
|
757
|
+
let status: AppleStatusEvent;
|
|
758
|
+
try {
|
|
759
|
+
status = await this.appleStatus(locale);
|
|
760
|
+
} catch (error) {
|
|
761
|
+
return helperFailure(error);
|
|
762
|
+
}
|
|
763
|
+
const permission = await this.permission();
|
|
764
|
+
const micDenied = permission.microphone === "denied" || permission.microphone === "restricted";
|
|
765
|
+
const speechDenied = permission.speech === "denied" || permission.speech === "restricted";
|
|
766
|
+
if (micDenied || (engine === "legacy" && speechDenied)) {
|
|
767
|
+
return unavailable("permissionDenied", "Microphone or speech recognition access is off.", {
|
|
768
|
+
kind: "grantPermission",
|
|
769
|
+
detail: "Allow access in System Settings › Privacy & Security.",
|
|
770
|
+
});
|
|
771
|
+
}
|
|
772
|
+
const state = engine === "analyzer" ? status.analyzer : status.legacy;
|
|
773
|
+
switch (state) {
|
|
774
|
+
case "available":
|
|
775
|
+
return AVAILABLE;
|
|
776
|
+
case "needsAssetInstall":
|
|
777
|
+
return unavailable("modelNotInstalled", `The speech model for ${locale} is not on this Mac yet.`, {
|
|
778
|
+
kind: "installModel",
|
|
779
|
+
detail: "Download the language in Voice settings.",
|
|
780
|
+
});
|
|
781
|
+
case "unavailableOS":
|
|
782
|
+
return unavailable("unsupportedOperatingSystem", "This engine needs a newer macOS.", {
|
|
783
|
+
kind: "upgradeOperatingSystem",
|
|
784
|
+
detail: "Update macOS, or use the compatibility engine.",
|
|
785
|
+
});
|
|
786
|
+
case "localeUnsupported":
|
|
787
|
+
return unavailable("unsupportedLocale", `${locale} is not supported on this Mac.`, {
|
|
788
|
+
kind: "switchLocale",
|
|
789
|
+
detail: "Choose another dictation language.",
|
|
790
|
+
});
|
|
791
|
+
default:
|
|
792
|
+
return unavailable("engineFailed", "Speech recognition is unavailable on this Mac.");
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
async appleVoices(locale: string): Promise<VoiceProviderAvailability> {
|
|
797
|
+
try {
|
|
798
|
+
const voices = await this.once(`voices:${locale}`, () => this.service.voices(this.settings, locale));
|
|
799
|
+
if (voices.some((voice) => voice.provider === APPLE_VOICES_ID)) return AVAILABLE;
|
|
800
|
+
const language = locale.split("-")[0];
|
|
801
|
+
const all = await this.once("voices:*", () => this.service.voices(this.settings));
|
|
802
|
+
if (all.some((voice) => voice.provider === APPLE_VOICES_ID && voice.locale.split(/[-_]/)[0] === language)) {
|
|
803
|
+
return AVAILABLE;
|
|
804
|
+
}
|
|
805
|
+
return unavailable("unsupportedLocale", `No voice for ${locale} is installed.`, {
|
|
806
|
+
kind: "installModel",
|
|
807
|
+
detail: "Add a voice in System Settings › Accessibility › Spoken Content.",
|
|
808
|
+
});
|
|
809
|
+
} catch (error) {
|
|
810
|
+
return helperFailure(error);
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
transcribeStatus(locale: string): Promise<TranscribeStatusEvent> {
|
|
815
|
+
this.service.applyTranscribeFolders(this.settings);
|
|
816
|
+
return this.once(`transcribe:${locale}`, () =>
|
|
817
|
+
this.service
|
|
818
|
+
.connection("transcribe")
|
|
819
|
+
.request({ cmd: "status", locale }, (event): event is TranscribeStatusEvent => event.event === "status", {
|
|
820
|
+
// Status loads model headers; give it time.
|
|
821
|
+
timeoutMs: 60_000,
|
|
822
|
+
}),
|
|
823
|
+
);
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
async transcribe(locale: string): Promise<VoiceProviderAvailability> {
|
|
827
|
+
let status: TranscribeStatusEvent;
|
|
828
|
+
try {
|
|
829
|
+
status = await this.transcribeStatus(locale);
|
|
830
|
+
} catch (error) {
|
|
831
|
+
return helperFailure(error);
|
|
832
|
+
}
|
|
833
|
+
if (status.models.length === 0) {
|
|
834
|
+
return unavailable("modelNotInstalled", "No transcribe.cpp model was found.", {
|
|
835
|
+
kind: "installModel",
|
|
836
|
+
detail: "Add a folder with a model in Voice settings.",
|
|
837
|
+
});
|
|
838
|
+
}
|
|
839
|
+
if (!status.selected) {
|
|
840
|
+
return unavailable("unsupportedLocale", `No local model supports ${locale}.`, {
|
|
841
|
+
kind: "switchLocale",
|
|
842
|
+
detail: "Choose another language or add a multilingual model.",
|
|
843
|
+
});
|
|
844
|
+
}
|
|
845
|
+
return AVAILABLE;
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
async synthesis(locale: string): Promise<VoiceProviderAvailability> {
|
|
849
|
+
try {
|
|
850
|
+
const status = await this.once(`tts:${locale}`, () =>
|
|
851
|
+
this.service
|
|
852
|
+
.connection("tts")
|
|
853
|
+
.request({ cmd: "status", locale }, (event): event is SynthesisStatusEvent => event.event === "status"),
|
|
854
|
+
);
|
|
855
|
+
if (status.ready) return AVAILABLE;
|
|
856
|
+
const reason = status.reason;
|
|
857
|
+
if (reason === "modelNotInstalled") {
|
|
858
|
+
return unavailable("modelNotInstalled", status.message ?? "No audio.cpp model is installed.", {
|
|
859
|
+
kind: "installModel",
|
|
860
|
+
detail: "Add a voice model in Voice settings.",
|
|
861
|
+
});
|
|
862
|
+
}
|
|
863
|
+
if (reason === "unsupportedLocale") return unavailable("unsupportedLocale", status.message ?? `No voice for ${locale}.`);
|
|
864
|
+
if (reason === "unsupportedPlatform") return unavailable("unsupportedPlatform", status.message ?? "Not supported here.");
|
|
865
|
+
return unavailable("engineFailed", status.message ?? "audio.cpp is unavailable.");
|
|
866
|
+
} catch (error) {
|
|
867
|
+
return helperFailure(error);
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
/**
|
|
873
|
+
* Apple's engine variant (`stt.model` `analyzer`/`legacy`) is a provider choice: with no explicit
|
|
874
|
+
* provider it pins that engine, so "Modern" or "Compatibility" in settings is what dictation runs.
|
|
875
|
+
*/
|
|
876
|
+
export function withModelChoice(settings: VoiceSettings): VoiceSettings {
|
|
877
|
+
if (settings.stt.provider) return settings;
|
|
878
|
+
const model = settings.stt.model;
|
|
879
|
+
if (model !== "analyzer" && model !== "legacy") return settings;
|
|
880
|
+
return { ...settings, stt: { ...settings.stt, provider: model === "analyzer" ? APPLE_ANALYZER_ID : APPLE_LEGACY_ID } };
|
|
881
|
+
}
|
|
882
|
+
|
|
883
|
+
function helperFailure(error: unknown): VoiceProviderAvailability {
|
|
884
|
+
if (error instanceof IncompatibleHelperError) {
|
|
885
|
+
return unavailable("contractIncompatible", error.message, {
|
|
886
|
+
kind: "chooseAnotherProvider",
|
|
887
|
+
detail: "Install an app build with a matching voice helper.",
|
|
888
|
+
});
|
|
889
|
+
}
|
|
890
|
+
const typed = VoiceError.wrapping(error);
|
|
891
|
+
return unavailable("engineFailed", typed.message);
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
function unavailableError(decision: VoiceRoutingDecision): VoiceError {
|
|
895
|
+
const availability = decision.availability;
|
|
896
|
+
if (availability.status === "available") return new VoiceError("unavailable", "No engine can serve this request.");
|
|
897
|
+
const reason = availability.unavailable.reason;
|
|
898
|
+
const code: VoiceErrorCode =
|
|
899
|
+
reason === "permissionDenied"
|
|
900
|
+
? "denied"
|
|
901
|
+
: reason === "unsupportedLocale"
|
|
902
|
+
? "language_unsupported"
|
|
903
|
+
: reason === "modelNotInstalled" || reason === "modelDownloadDisabled"
|
|
904
|
+
? "assets_missing"
|
|
905
|
+
: "unavailable";
|
|
906
|
+
return new VoiceError(code, availability.unavailable.message);
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
function platformOf(os: DesktopOS): VoicePlatform {
|
|
910
|
+
return os === "darwin" ? "macOS" : os === "win32" ? "windows" : "linux";
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
function defaultLocale(chosen: string | undefined): string {
|
|
914
|
+
if (chosen) return chosen;
|
|
915
|
+
try {
|
|
916
|
+
return Intl.DateTimeFormat().resolvedOptions().locale || "en-US";
|
|
917
|
+
} catch {
|
|
918
|
+
return "en-US";
|
|
919
|
+
}
|
|
920
|
+
}
|
|
921
|
+
|
|
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
|
+
|
|
943
|
+
function appleRate(rate: number): number {
|
|
944
|
+
return Math.min(1, Math.max(0.05, rate * 0.5));
|
|
945
|
+
}
|
|
946
|
+
|
|
947
|
+
// MARK: - One dictation
|
|
948
|
+
|
|
949
|
+
interface DictationSessionOptions {
|
|
950
|
+
readonly connection: HelperConnection;
|
|
951
|
+
readonly provider: string;
|
|
952
|
+
readonly locale: string;
|
|
953
|
+
readonly engine: "analyzer" | "legacy" | undefined;
|
|
954
|
+
readonly onPartial: DictationRequest["onPartial"];
|
|
955
|
+
readonly maxListenMs: number;
|
|
956
|
+
readonly terminalGraceMs: number;
|
|
957
|
+
readonly onStuck: () => void;
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
class DictationSession implements DesktopDictation {
|
|
961
|
+
readonly provider: string;
|
|
962
|
+
readonly locale: string;
|
|
963
|
+
readonly execution = "onDevice" as const;
|
|
964
|
+
readonly result: Promise<string>;
|
|
965
|
+
readonly started: Promise<void>;
|
|
966
|
+
private readonly id = nextRequestId("listen-");
|
|
967
|
+
private readonly queue: SessionEvent[] = [];
|
|
968
|
+
private waiter: ((value: IteratorResult<SessionEvent>) => void) | undefined;
|
|
969
|
+
private terminal: SessionEvent | undefined;
|
|
970
|
+
private consumed = false;
|
|
971
|
+
private lastSequence = -1;
|
|
972
|
+
private maxTimer: ReturnType<typeof setTimeout> | undefined;
|
|
973
|
+
private graceTimer: ReturnType<typeof setTimeout> | undefined;
|
|
974
|
+
private settle!: { resolve: (text: string) => void; reject: (error: VoiceError) => void };
|
|
975
|
+
|
|
976
|
+
constructor(private readonly options: DictationSessionOptions) {
|
|
977
|
+
this.provider = options.provider;
|
|
978
|
+
this.locale = options.locale;
|
|
979
|
+
this.result = new Promise<string>((resolve, reject) => {
|
|
980
|
+
this.settle = { resolve, reject };
|
|
981
|
+
});
|
|
982
|
+
this.result.catch(() => undefined);
|
|
983
|
+
let resolveStarted!: () => void;
|
|
984
|
+
let rejectStarted!: (error: VoiceError) => void;
|
|
985
|
+
this.started = new Promise<void>((resolve, reject) => {
|
|
986
|
+
resolveStarted = resolve;
|
|
987
|
+
rejectStarted = reject;
|
|
988
|
+
});
|
|
989
|
+
options.connection
|
|
990
|
+
.request(
|
|
991
|
+
{ cmd: "listen", id: this.id, locale: options.locale, ...(options.engine ? { engine: options.engine } : {}) },
|
|
992
|
+
(event): event is WireEvent => event.event === "final" || event.event === "cancelled" || event.event === "error",
|
|
993
|
+
{
|
|
994
|
+
timeoutMs: null,
|
|
995
|
+
onEvent: (event) => {
|
|
996
|
+
if (event.event === "listening") resolveStarted();
|
|
997
|
+
if (event.event === "partial") this.partial(event.finalizedText, event.volatileText, event.sequence);
|
|
998
|
+
},
|
|
999
|
+
},
|
|
1000
|
+
)
|
|
1001
|
+
.then(
|
|
1002
|
+
(event) => {
|
|
1003
|
+
if (event.event === "final") this.finish({ type: "final", text: event.text });
|
|
1004
|
+
else if (event.event === "error") {
|
|
1005
|
+
// `isDone` accepts the helper's error terminal, so it arrives here, not as a rejection.
|
|
1006
|
+
this.finish({ type: "failed", error: new VoiceError(event.code, event.message ?? "Dictation failed.") });
|
|
1007
|
+
} else this.finish({ type: "cancelled" });
|
|
1008
|
+
},
|
|
1009
|
+
(error: unknown) => this.finish({ type: "failed", error: VoiceError.wrapping(error) }),
|
|
1010
|
+
)
|
|
1011
|
+
.finally(() => {
|
|
1012
|
+
const terminal = this.terminal;
|
|
1013
|
+
if (terminal?.type === "failed") rejectStarted(terminal.error);
|
|
1014
|
+
else if (terminal?.type === "cancelled") rejectStarted(new VoiceError("cancelled", "Dictation was cancelled."));
|
|
1015
|
+
else resolveStarted();
|
|
1016
|
+
});
|
|
1017
|
+
this.maxTimer = setTimeout(() => void this.end(), options.maxListenMs);
|
|
1018
|
+
}
|
|
1019
|
+
|
|
1020
|
+
get isTerminal(): boolean {
|
|
1021
|
+
return this.terminal !== undefined;
|
|
1022
|
+
}
|
|
1023
|
+
|
|
1024
|
+
events(): AsyncIterable<SessionEvent> {
|
|
1025
|
+
if (this.consumed) throw new VoiceError("bad_request", "A dictation's events can be read once.");
|
|
1026
|
+
this.consumed = true;
|
|
1027
|
+
return {
|
|
1028
|
+
[Symbol.asyncIterator]: () => ({
|
|
1029
|
+
next: () => {
|
|
1030
|
+
const next = this.queue.shift();
|
|
1031
|
+
if (next) return Promise.resolve({ value: next, done: false });
|
|
1032
|
+
if (this.terminal && this.queue.length === 0 && this.drained) {
|
|
1033
|
+
return Promise.resolve({ value: undefined, done: true } as IteratorResult<SessionEvent>);
|
|
1034
|
+
}
|
|
1035
|
+
return new Promise<IteratorResult<SessionEvent>>((resolve) => {
|
|
1036
|
+
this.waiter = resolve;
|
|
1037
|
+
});
|
|
1038
|
+
},
|
|
1039
|
+
return: async () => {
|
|
1040
|
+
await this.cancel();
|
|
1041
|
+
return { value: undefined, done: true } as IteratorResult<SessionEvent>;
|
|
1042
|
+
},
|
|
1043
|
+
}),
|
|
1044
|
+
};
|
|
1045
|
+
}
|
|
1046
|
+
|
|
1047
|
+
private drained = false;
|
|
1048
|
+
|
|
1049
|
+
private cancelRequested = false;
|
|
1050
|
+
|
|
1051
|
+
async end(): Promise<void> {
|
|
1052
|
+
// After a cancel, an end must not let a late final win over the requested cancel.
|
|
1053
|
+
if (this.terminal || this.cancelRequested) return;
|
|
1054
|
+
await this.options.connection.send({ cmd: "listen-end", id: this.id }).catch(() => undefined);
|
|
1055
|
+
this.armGrace();
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
async cancel(): Promise<void> {
|
|
1059
|
+
if (this.terminal) return;
|
|
1060
|
+
this.cancelRequested = true;
|
|
1061
|
+
await this.options.connection.send({ cmd: "listen-cancel", id: this.id }).catch(() => undefined);
|
|
1062
|
+
this.armGrace(true);
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
/** A helper that never answers is killed; the session still ends with exactly one terminal. */
|
|
1066
|
+
private armGrace(cancelling = false): void {
|
|
1067
|
+
if (this.graceTimer || this.terminal) return;
|
|
1068
|
+
this.graceTimer = setTimeout(() => {
|
|
1069
|
+
if (this.terminal) return;
|
|
1070
|
+
this.finish(
|
|
1071
|
+
cancelling
|
|
1072
|
+
? { type: "cancelled" }
|
|
1073
|
+
: { type: "failed", error: new VoiceError("failed", "The speech engine stopped answering.") },
|
|
1074
|
+
);
|
|
1075
|
+
this.options.onStuck();
|
|
1076
|
+
}, this.options.terminalGraceMs);
|
|
1077
|
+
}
|
|
1078
|
+
|
|
1079
|
+
private partial(finalizedText: string, volatileText: string, sequence: number): void {
|
|
1080
|
+
if (this.terminal || sequence <= this.lastSequence) return;
|
|
1081
|
+
this.lastSequence = sequence;
|
|
1082
|
+
const partial = { finalizedText, volatileText, sequence };
|
|
1083
|
+
this.options.onPartial?.({ ...partial, text: joinTranscript(finalizedText, volatileText) });
|
|
1084
|
+
this.push({ type: "partial", partial });
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
private finish(event: SessionEvent): void {
|
|
1088
|
+
if (this.terminal) return;
|
|
1089
|
+
this.terminal = event;
|
|
1090
|
+
clearTimeout(this.maxTimer);
|
|
1091
|
+
clearTimeout(this.graceTimer);
|
|
1092
|
+
this.push(event);
|
|
1093
|
+
this.drained = true;
|
|
1094
|
+
if (event.type === "final") this.settle.resolve(event.text);
|
|
1095
|
+
else if (event.type === "cancelled") this.settle.reject(new VoiceError("cancelled", "Dictation was cancelled."));
|
|
1096
|
+
else if (event.type === "failed") this.settle.reject(event.error);
|
|
1097
|
+
// Wake an iterator that is waiting after the terminal was consumed.
|
|
1098
|
+
queueMicrotask(() => {
|
|
1099
|
+
if (this.queue.length === 0 && this.waiter) {
|
|
1100
|
+
const waiter = this.waiter;
|
|
1101
|
+
this.waiter = undefined;
|
|
1102
|
+
waiter({ value: undefined, done: true } as IteratorResult<SessionEvent>);
|
|
1103
|
+
}
|
|
1104
|
+
});
|
|
1105
|
+
}
|
|
1106
|
+
|
|
1107
|
+
private push(event: SessionEvent): void {
|
|
1108
|
+
if (this.waiter) {
|
|
1109
|
+
const waiter = this.waiter;
|
|
1110
|
+
this.waiter = undefined;
|
|
1111
|
+
waiter({ value: event, done: false });
|
|
1112
|
+
return;
|
|
1113
|
+
}
|
|
1114
|
+
// Bounded: partials replace each other, so only the latest pending partial is kept.
|
|
1115
|
+
if (event.type === "partial") {
|
|
1116
|
+
const last = this.queue.at(-1);
|
|
1117
|
+
if (last?.type === "partial") this.queue.pop();
|
|
1118
|
+
}
|
|
1119
|
+
this.queue.push(event);
|
|
1120
|
+
}
|
|
1121
|
+
}
|
|
1122
|
+
|
|
1123
|
+
/** Finalized + volatile text, with exactly one space between them where needed. */
|
|
1124
|
+
export function joinTranscript(finalizedText: string, volatileText: string): string {
|
|
1125
|
+
if (!finalizedText) return volatileText.trimStart();
|
|
1126
|
+
if (!volatileText) return finalizedText;
|
|
1127
|
+
const needsSpace = !/\s$/.test(finalizedText) && !/^[\s.,;:!?]/.test(volatileText);
|
|
1128
|
+
return needsSpace ? `${finalizedText} ${volatileText}` : `${finalizedText}${volatileText}`;
|
|
1129
|
+
}
|