@adea-ai/voice 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +51 -2
  2. package/dist/cli/helpers-cli.d.ts +2 -0
  3. package/dist/cli/helpers-cli.js +102 -0
  4. package/dist/contract/contract.d.ts +138 -0
  5. package/dist/contract/errors.d.ts +26 -0
  6. package/dist/contract/index.d.ts +9 -0
  7. package/dist/contract/index.js +54 -0
  8. package/dist/contract/session.d.ts +58 -0
  9. package/dist/contract/wire.d.ts +188 -0
  10. package/dist/desktop/desktop-voice.d.ts +152 -0
  11. package/dist/desktop/helper-lock.d.ts +83 -0
  12. package/dist/desktop/helper-process.d.ts +92 -0
  13. package/dist/desktop/index.d.ts +7 -0
  14. package/dist/desktop/index.js +1042 -0
  15. package/dist/index-9kerqn9r.js +150 -0
  16. package/dist/index-acm1yvvv.js +290 -0
  17. package/dist/index-r4hz8gk0.js +10 -0
  18. package/dist/index-rehs788p.js +42 -0
  19. package/dist/index-s270cw30.js +295 -0
  20. package/dist/index-tvz9s9nz.js +77 -0
  21. package/dist/index.d.ts +7 -0
  22. package/dist/index.js +86 -0
  23. package/dist/settings/index.d.ts +5 -0
  24. package/dist/settings/index.js +34 -0
  25. package/dist/settings/settings.d.ts +163 -0
  26. package/dist/web/index.d.ts +15 -0
  27. package/dist/web/index.js +1287 -0
  28. package/dist/web/stt/speech-recognition.d.ts +105 -0
  29. package/dist/web/tts/phonon.d.ts +139 -0
  30. package/dist/web/tts/player.d.ts +115 -0
  31. package/dist/web/tts/system-voices.d.ts +122 -0
  32. package/dist/web/turns.d.ts +101 -0
  33. package/package.json +68 -4
  34. package/src/cli/helpers-cli.ts +119 -0
  35. package/src/contract/contract.ts +365 -0
  36. package/src/contract/errors.ts +98 -0
  37. package/src/contract/index.ts +9 -0
  38. package/src/contract/session.ts +65 -0
  39. package/src/contract/wire.ts +263 -0
  40. package/src/desktop/desktop-voice.ts +933 -0
  41. package/src/desktop/helper-lock.ts +375 -0
  42. package/src/desktop/helper-process.ts +401 -0
  43. package/src/desktop/index.ts +16 -0
  44. package/src/index.ts +7 -0
  45. package/src/settings/index.ts +5 -0
  46. package/src/settings/settings.ts +478 -0
  47. package/src/web/index.ts +15 -0
  48. package/src/web/stt/speech-recognition.ts +583 -0
  49. package/src/web/tts/phonon.ts +386 -0
  50. package/src/web/tts/player.ts +271 -0
  51. package/src/web/tts/system-voices.ts +401 -0
  52. package/src/web/turns.ts +224 -0
@@ -0,0 +1,119 @@
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * adea-voice-helpers: stage and verify the pinned desktop speech helpers.
4
+ *
5
+ * adea-voice-helpers stage --lock <lock.json> --out <dir> [--helpers a,b] [--target t]
6
+ * [--cache <dir>] [--local <dir>] [--no-handshake]
7
+ * adea-voice-helpers verify --lock <lock.json> --dir <dir> [--helpers a,b] [--target t]
8
+ * adea-voice-helpers url --lock <lock.json> --helper <name> [--target t]
9
+ * adea-voice-helpers pin --lock <lock.json> --version <x.y.z> [--base <url>]
10
+ *
11
+ * `stage` fails (exit 1) when an artifact is missing or does not match its pins and leaves no
12
+ * half-staged directory. `verify` is the release gate: the packaged directory must hold exactly the
13
+ * pinned helpers, never a local build. Exit 2 is a usage error.
14
+ */
15
+ import { writeFileSync } from "node:fs";
16
+ import {
17
+ HELPER_NAMES,
18
+ HELPER_TARGETS,
19
+ HelperLockError,
20
+ currentHelperTarget,
21
+ helperArtifactUrl,
22
+ readHelperLock,
23
+ validateHelperLock,
24
+ stageVoiceHelpers,
25
+ verifyStagedVoiceHelpers,
26
+ type HelperName,
27
+ type HelperTarget,
28
+ } from "../desktop/helper-lock";
29
+
30
+ const [command, ...rest] = process.argv.slice(2);
31
+
32
+ function flag(name: string): string | undefined {
33
+ const index = rest.indexOf(`--${name}`);
34
+ return index >= 0 ? rest[index + 1] : undefined;
35
+ }
36
+
37
+ function usage(message: string): never {
38
+ console.error(`adea-voice-helpers: ${message}`);
39
+ console.error("usage: adea-voice-helpers stage|verify|url --lock <lock.json> …");
40
+ process.exit(2);
41
+ }
42
+
43
+ function target(): HelperTarget {
44
+ const value = flag("target") ?? currentHelperTarget();
45
+ if (!value || !(HELPER_TARGETS as readonly string[]).includes(value)) usage(`no helper target for this machine; pass --target`);
46
+ return value as HelperTarget;
47
+ }
48
+
49
+ function helpers(lockHelpers: readonly string[]): HelperName[] {
50
+ const value = flag("helpers");
51
+ const names = value ? value.split(",").map((name) => name.trim()).filter(Boolean) : lockHelpers;
52
+ for (const name of names) {
53
+ if (!(HELPER_NAMES as readonly string[]).includes(name)) usage(`unknown helper ${name}`);
54
+ }
55
+ return names as HelperName[];
56
+ }
57
+
58
+ /** `pin`: replace the lock with the published lock of another release (the bump an app makes). */
59
+ async function pin(lockPath: string): Promise<void> {
60
+ const version = flag("version") ?? usage("pin needs --version");
61
+ const base = flag("base") ?? "https://adea.dev/releases/voice/";
62
+ const url = `${base}voice-helpers-${version}.lock.json`;
63
+ const response = await fetch(url);
64
+ if (!response.ok) throw new HelperLockError(`GET ${url} answered ${response.status}: is ${version} released?`);
65
+ const lock = validateHelperLock(await response.json());
66
+ if (lock.version !== version) throw new HelperLockError(`${url} pins ${lock.version}, not ${version}`);
67
+ writeFileSync(lockPath, `${JSON.stringify(lock, null, 2)}\n`);
68
+ console.log(`voice helpers: ${lockPath} now pins ${version}`);
69
+ }
70
+
71
+ async function main(): Promise<void> {
72
+ const lockPath = flag("lock");
73
+ if (!command || !lockPath) usage("missing command or --lock");
74
+ if (command === "pin") return await pin(lockPath);
75
+ const lock = readHelperLock(lockPath);
76
+ const selectedTarget = target();
77
+ const pinned = Object.entries(lock.helpers)
78
+ .filter(([, targets]) => targets?.[selectedTarget])
79
+ .map(([name]) => name);
80
+ switch (command) {
81
+ case "stage": {
82
+ const out = flag("out") ?? usage("stage needs --out");
83
+ const record = await stageVoiceHelpers({
84
+ lock,
85
+ target: selectedTarget,
86
+ outDir: out,
87
+ helpers: helpers(pinned),
88
+ cacheDir: flag("cache"),
89
+ localDir: flag("local"),
90
+ handshake: rest.includes("--no-handshake") ? false : undefined,
91
+ log: (message) => console.log(`voice helpers: ${message}`),
92
+ });
93
+ console.log(`voice helpers: staged ${Object.keys(record.helpers).join(", ")} ${record.version} for ${record.target}`);
94
+ return;
95
+ }
96
+ case "verify": {
97
+ const dir = flag("dir") ?? usage("verify needs --dir");
98
+ verifyStagedVoiceHelpers({ lock, target: selectedTarget, dir, helpers: helpers(pinned) });
99
+ console.log(`voice helpers: ${dir} holds the pinned ${lock.version} helpers for ${selectedTarget}`);
100
+ return;
101
+ }
102
+ case "url": {
103
+ const helper = flag("helper") ?? usage("url needs --helper");
104
+ console.log(helperArtifactUrl(lock, helpers([helper])[0]!, selectedTarget));
105
+ return;
106
+ }
107
+ default:
108
+ usage(`unknown command ${command}`);
109
+ }
110
+ }
111
+
112
+ main().catch((error: unknown) => {
113
+ if (error instanceof HelperLockError) {
114
+ console.error(`adea-voice-helpers: ${error.message}`);
115
+ process.exit(1);
116
+ }
117
+ console.error(error);
118
+ process.exit(1);
119
+ });
@@ -0,0 +1,365 @@
1
+ /**
2
+ * The shared Voice provider contract in TypeScript (issue #19).
3
+ *
4
+ * Field names and values mirror the Swift implementation in `Sources/AdeaVoice/VoiceProvider.swift`
5
+ * so a web adapter, a Capacitor bridge and the desktop helper describe the same provider, the same
6
+ * reasons and the same routing decision. The version is checked, not assumed: a provider on another
7
+ * contract major is refused rather than reinterpreted.
8
+ *
9
+ * Browser specifics live above this layer (`browserSttProvider`, `phononProvider`, `systemVoices`),
10
+ * not in it.
11
+ */
12
+
13
+ /** The contract this build speaks. Compatibility is by major version only. */
14
+ export const VOICE_CONTRACT = { major: 1, minor: 0 } as const;
15
+
16
+ export interface VoiceContract {
17
+ readonly major: number;
18
+ readonly minor: number;
19
+ }
20
+
21
+ /** Whether a provider speaking `candidate` can be used by an SDK speaking `supported`. */
22
+ export function isCompatibleContract(
23
+ candidate: VoiceContract,
24
+ supported: VoiceContract = VOICE_CONTRACT,
25
+ ): boolean {
26
+ return candidate.major === supported.major;
27
+ }
28
+
29
+ export type VoiceProviderKind = "speechToText" | "textToSpeech";
30
+
31
+ export type VoicePlatform = "macOS" | "iOS" | "windows" | "linux" | "android" | "web";
32
+
33
+ export type VoiceExecutionLocation = "onDevice" | "systemProvided" | "network";
34
+
35
+ /** Code and asset licences stay separate: a permissive runtime can carry non-commercial weights. */
36
+ export interface VoiceAssetLicense {
37
+ readonly spdxIdentifier: string;
38
+ readonly commercialUse: boolean;
39
+ }
40
+
41
+ /** Capability, not availability: what the provider can do when it can run here. */
42
+ export interface VoiceProviderCapabilities {
43
+ readonly streamingPartials?: boolean;
44
+ readonly trueCancellation?: boolean;
45
+ readonly modelInstallation?: boolean;
46
+ readonly localeSelection?: boolean;
47
+ readonly voiceSelection?: boolean;
48
+ readonly utteranceQueueing?: boolean;
49
+ readonly wordBoundaryPause?: boolean;
50
+ }
51
+
52
+ /**
53
+ * The capability bits in wire order: bit `i` is `1 << i`. Same order as the Swift
54
+ * `VoiceProviderCapabilities` option set (`Sources/AdeaVoice/VoiceProvider.swift`); the integer
55
+ * mask is what every other surface (helper, Capacitor, Android) carries. Append only.
56
+ */
57
+ export const VOICE_CAPABILITY_BITS = [
58
+ "streamingPartials",
59
+ "trueCancellation",
60
+ "modelInstallation",
61
+ "localeSelection",
62
+ "voiceSelection",
63
+ "utteranceQueueing",
64
+ "wordBoundaryPause",
65
+ ] as const satisfies readonly (keyof VoiceProviderCapabilities)[];
66
+
67
+ /** The integer bit mask for a capabilities object (the wire form). */
68
+ export function capabilitiesToMask(capabilities: VoiceProviderCapabilities): number {
69
+ let mask = 0;
70
+ VOICE_CAPABILITY_BITS.forEach((name, bit) => {
71
+ if (capabilities[name] === true) mask |= 1 << bit;
72
+ });
73
+ return mask;
74
+ }
75
+
76
+ /**
77
+ * A capabilities object from an integer bit mask. Every known flag is present (true or false);
78
+ * bits this build does not know are ignored, as a higher contract minor may add them.
79
+ */
80
+ export function capabilitiesFromMask(mask: number): Required<VoiceProviderCapabilities> {
81
+ const value = Number.isInteger(mask) && mask > 0 ? mask : 0;
82
+ const capabilities = {} as Record<(typeof VOICE_CAPABILITY_BITS)[number], boolean>;
83
+ VOICE_CAPABILITY_BITS.forEach((name, bit) => {
84
+ capabilities[name] = (value & (1 << bit)) !== 0;
85
+ });
86
+ return capabilities;
87
+ }
88
+
89
+ /** Static identity and constraints. Safe to cache and log. */
90
+ export interface VoiceProviderDescriptor {
91
+ readonly id: string;
92
+ readonly displayName: string;
93
+ readonly kind: VoiceProviderKind;
94
+ readonly platforms: readonly VoicePlatform[];
95
+ readonly execution: VoiceExecutionLocation;
96
+ readonly contract: VoiceContract;
97
+ readonly requiresModelDownload: boolean;
98
+ readonly modelFamilies: readonly string[];
99
+ readonly licenses: readonly VoiceAssetLicense[];
100
+ readonly capabilities: VoiceProviderCapabilities;
101
+ }
102
+
103
+ /** The closed set of reasons a provider cannot serve a request right now. */
104
+ export type VoiceUnavailabilityReason =
105
+ | "unsupportedOperatingSystem"
106
+ | "unsupportedPlatform"
107
+ | "unsupportedDevice"
108
+ | "unsupportedLocale"
109
+ | "modelNotInstalled"
110
+ | "modelDownloadDisabled"
111
+ | "licenseNotAccepted"
112
+ | "networkRequired"
113
+ | "permissionDenied"
114
+ | "contractIncompatible"
115
+ | "providerNotRegistered"
116
+ | "engineFailed";
117
+
118
+ export type VoiceRemedyKind =
119
+ | "installModel"
120
+ | "switchLocale"
121
+ | "upgradeOperatingSystem"
122
+ | "acceptLicense"
123
+ | "grantPermission"
124
+ | "chooseAnotherProvider"
125
+ | "none";
126
+
127
+ export interface VoiceRemedy {
128
+ readonly kind: VoiceRemedyKind;
129
+ readonly detail: string;
130
+ }
131
+
132
+ export interface VoiceUnavailability {
133
+ readonly reason: VoiceUnavailabilityReason;
134
+ readonly message: string;
135
+ readonly remedy?: VoiceRemedy;
136
+ }
137
+
138
+ export type VoiceProviderAvailability =
139
+ | { readonly status: "available" }
140
+ | { readonly status: "unavailable"; readonly unavailable: VoiceUnavailability };
141
+
142
+ export const AVAILABLE: VoiceProviderAvailability = { status: "available" };
143
+
144
+ export function unavailable(
145
+ reason: VoiceUnavailabilityReason,
146
+ message: string,
147
+ remedy?: VoiceRemedy,
148
+ ): VoiceProviderAvailability {
149
+ return { status: "unavailable", unavailable: remedy ? { reason, message, remedy } : { reason, message } };
150
+ }
151
+
152
+ export function isAvailable(
153
+ availability: VoiceProviderAvailability,
154
+ ): availability is { readonly status: "available" } {
155
+ return availability.status === "available";
156
+ }
157
+
158
+ /** One candidate for one request: the descriptor plus its truth here and now. */
159
+ export interface VoiceRoute {
160
+ readonly kind: VoiceProviderKind;
161
+ readonly locale: string;
162
+ readonly descriptor: VoiceProviderDescriptor;
163
+ readonly availability: VoiceProviderAvailability;
164
+ }
165
+
166
+ /** "Install, then start": both reasons mean an explicit install would resolve the route. */
167
+ export function requiresModelInstallation(route: VoiceRoute): boolean {
168
+ const reason = route.availability.status === "unavailable" ? route.availability.unavailable.reason : undefined;
169
+ return reason === "modelNotInstalled" || reason === "modelDownloadDisabled";
170
+ }
171
+
172
+ export interface VoiceRoutingDecision {
173
+ readonly kind: VoiceProviderKind;
174
+ readonly locale: string;
175
+ /** The selected provider, or null when none can serve the request. */
176
+ readonly route: VoiceRoute | null;
177
+ /** The registered candidates in policy order, each with its own truth. */
178
+ readonly candidates: readonly VoiceRoute[];
179
+ /** Chain identifiers this build does not register. */
180
+ readonly missing: readonly string[];
181
+ /** The selected provider's truth, or the most actionable failure when nothing resolved. */
182
+ readonly availability: VoiceProviderAvailability;
183
+ }
184
+
185
+ /** A provider: static descriptor, prompt-free probe, and a typed availability per locale. */
186
+ export interface VoiceProvider {
187
+ readonly descriptor: VoiceProviderDescriptor;
188
+ availability(locale: string): Promise<VoiceProviderAvailability>;
189
+ }
190
+
191
+ /** Swift `VoiceUnavailability.Reason.actionability`, value for value. */
192
+ const ACTIONABILITY: Record<VoiceUnavailabilityReason, number> = {
193
+ modelNotInstalled: 100,
194
+ modelDownloadDisabled: 95,
195
+ unsupportedLocale: 90,
196
+ unsupportedOperatingSystem: 80,
197
+ unsupportedDevice: 70,
198
+ permissionDenied: 60,
199
+ licenseNotAccepted: 50,
200
+ contractIncompatible: 40,
201
+ engineFailed: 30,
202
+ networkRequired: 20,
203
+ providerNotRegistered: 10,
204
+ unsupportedPlatform: 0,
205
+ };
206
+
207
+ /** Routing is data: an ordered chain per kind, an explicit override, and one policy flag. */
208
+ export interface VoiceRoutingPolicy {
209
+ /** Ordered provider ids per kind. The first usable one wins. */
210
+ readonly chains: Partial<Record<VoiceProviderKind, readonly string[]>>;
211
+ /** An explicit choice replaces the chain: the caller gets that provider's truth, no substitute. */
212
+ readonly overrides?: Partial<Record<VoiceProviderKind, string>>;
213
+ /** Whether a provider whose models are absent may be selected so the host can install them. */
214
+ readonly allowsOptInModelInstallation: boolean;
215
+ }
216
+
217
+ /** The browser routing table: local recognition only, Phonon first for synthesis. */
218
+ export const WEB_ROUTING_POLICY: VoiceRoutingPolicy = {
219
+ chains: {
220
+ speechToText: ["web.speech-recognition-local"],
221
+ textToSpeech: ["web.phonon", "web.system-voices"],
222
+ },
223
+ allowsOptInModelInstallation: false,
224
+ };
225
+
226
+ export interface RouteRequest {
227
+ readonly kind: VoiceProviderKind;
228
+ readonly locale: string;
229
+ readonly providers: readonly VoiceProvider[];
230
+ readonly policy?: VoiceRoutingPolicy;
231
+ }
232
+
233
+ /**
234
+ * Resolves one request. A provider on another contract major, a network provider in a chain, or a
235
+ * provider whose models are absent are all reported with their own reason; nothing is substituted
236
+ * and nothing is downloaded.
237
+ */
238
+ export async function route(request: RouteRequest): Promise<VoiceRoutingDecision> {
239
+ const policy = request.policy ?? WEB_ROUTING_POLICY;
240
+ const override = policy.overrides?.[request.kind];
241
+ const configured = override ? [override] : policy.chains[request.kind];
242
+ if (configured === undefined) {
243
+ // Same as Swift: no chain for this kind at all is `unsupportedPlatform`, not "not registered".
244
+ return {
245
+ kind: request.kind,
246
+ locale: request.locale,
247
+ route: null,
248
+ candidates: [],
249
+ missing: [],
250
+ availability: unavailable("unsupportedPlatform", `no ${request.kind} provider is defined for web`, {
251
+ kind: "chooseAnotherProvider",
252
+ detail: "run on a platform the Voice SDK has a provider for",
253
+ }),
254
+ };
255
+ }
256
+ const chain = configured;
257
+ const byId = new Map(request.providers.map((provider) => [provider.descriptor.id, provider]));
258
+
259
+ const candidates: VoiceRoute[] = [];
260
+ const missing: string[] = [];
261
+ for (const id of chain) {
262
+ const provider = byId.get(id);
263
+ if (!provider) {
264
+ missing.push(id);
265
+ continue;
266
+ }
267
+ candidates.push({
268
+ kind: request.kind,
269
+ locale: request.locale,
270
+ descriptor: provider.descriptor,
271
+ availability: await evaluate(provider, request.locale, policy),
272
+ });
273
+ }
274
+
275
+ const selection = candidates.find((candidate) =>
276
+ isAvailable(candidate.availability) ||
277
+ (policy.allowsOptInModelInstallation && requiresModelInstallation(candidate)),
278
+ );
279
+
280
+ // Swift `VoiceRoutingDecision.availability`: the selected route's truth, else the most
281
+ // actionable candidate failure, else (no candidate at all) `providerNotRegistered`.
282
+ const availability: VoiceProviderAvailability = selection
283
+ ? selection.availability
284
+ : mostActionable(candidates) ??
285
+ unavailable(
286
+ "providerNotRegistered",
287
+ `no ${request.kind} provider from the web chain is registered in this build: ${chain.join(", ")}`,
288
+ { kind: "chooseAnotherProvider", detail: "install a build that includes the provider" },
289
+ );
290
+
291
+ return {
292
+ kind: request.kind,
293
+ locale: request.locale,
294
+ route: selection ?? null,
295
+ candidates,
296
+ missing,
297
+ availability,
298
+ };
299
+ }
300
+
301
+ async function evaluate(
302
+ provider: VoiceProvider,
303
+ locale: string,
304
+ policy: VoiceRoutingPolicy,
305
+ ): Promise<VoiceProviderAvailability> {
306
+ const descriptor = provider.descriptor;
307
+ if (descriptor.execution === "network") {
308
+ return unavailable("networkRequired", `${descriptor.displayName} requires a network path; the Voice SDK is offline-only`);
309
+ }
310
+ // An incompatible provider is never trusted, so it is not probed either: its probe's meaning
311
+ // may have changed under another contract major.
312
+ if (!isCompatibleContract(descriptor.contract)) {
313
+ return unavailable(
314
+ "contractIncompatible",
315
+ `${descriptor.displayName} speaks contract ${descriptor.contract.major}.${descriptor.contract.minor}; this SDK speaks ${VOICE_CONTRACT.major}.${VOICE_CONTRACT.minor}`,
316
+ { kind: "chooseAnotherProvider", detail: "update the provider or the SDK" },
317
+ );
318
+ }
319
+ let reported: VoiceProviderAvailability;
320
+ try {
321
+ reported = await provider.availability(locale);
322
+ } catch (error) {
323
+ // A throwing probe is that candidate's failure, not the whole decision's.
324
+ return unavailable(
325
+ "engineFailed",
326
+ `${descriptor.displayName} failed while being probed: ${error instanceof Error ? error.message : String(error)}`,
327
+ );
328
+ }
329
+ if (
330
+ reported.status === "unavailable" &&
331
+ reported.unavailable.reason === "modelNotInstalled" &&
332
+ !policy.allowsOptInModelInstallation
333
+ ) {
334
+ return unavailable("modelDownloadDisabled", reported.unavailable.message, {
335
+ kind: "installModel",
336
+ detail: "Download the language in Voice settings.",
337
+ });
338
+ }
339
+ return reported;
340
+ }
341
+
342
+ /**
343
+ * Swift `candidates.map(\.availability).max(by:)` over `Reason.actionability`, with `available`
344
+ * ranked `Int.max`. `max(by:)` replaces only on a strictly greater value, so ties keep the earliest
345
+ * candidate in chain order; this loop does the same.
346
+ */
347
+ function mostActionable(candidates: readonly VoiceRoute[]): VoiceProviderAvailability | undefined {
348
+ let best: VoiceRoute | undefined;
349
+ for (const candidate of candidates) {
350
+ if (best === undefined) {
351
+ best = candidate;
352
+ continue;
353
+ }
354
+ const current = actionability(candidate.availability);
355
+ const incumbent = actionability(best.availability);
356
+ if (current > incumbent) best = candidate;
357
+ }
358
+ return best?.availability;
359
+ }
360
+
361
+ function actionability(availability: VoiceProviderAvailability): number {
362
+ if (availability.status === "available") return Number.MAX_SAFE_INTEGER;
363
+ // A reason from a newer contract minor ranks below every known one rather than poisoning the max.
364
+ return ACTIONABILITY[availability.unavailable.reason] ?? -1;
365
+ }
@@ -0,0 +1,98 @@
1
+ /**
2
+ * The error codes the Voice SDK reports on every platform, as values.
3
+ *
4
+ * These are the **wire strings**: the same snake_case codes the desktop helper, the Capacitor
5
+ * bridge and the Android plugin send, so an adapter matches one code across a native helper, a
6
+ * Capacitor bridge and a browser provider without a translation table. Additive only: a code is
7
+ * never renamed or reused for another meaning. `normalizeVoiceErrorCode` accepts the legacy
8
+ * camelCase spellings (Swift enum case names, earlier builds of this package) for stored values.
9
+ */
10
+ export const VOICE_ERROR_CODES = [
11
+ "denied",
12
+ "restricted",
13
+ "unavailable",
14
+ "no_speech",
15
+ "language_unsupported",
16
+ "assets_missing",
17
+ "assets_install_failed",
18
+ "assets_locale_limit",
19
+ "insufficient_storage",
20
+ "audio_overrun",
21
+ "busy",
22
+ "cancelled",
23
+ "bad_request",
24
+ "failed",
25
+ ] as const;
26
+
27
+ export type VoiceErrorCode = (typeof VOICE_ERROR_CODES)[number];
28
+
29
+ const WIRE_CODES: ReadonlySet<string> = new Set(VOICE_ERROR_CODES);
30
+
31
+ /** camelCase spellings (Swift `VoiceErrorCode` case names, pre-wire builds) to wire codes. */
32
+ const LEGACY_CODES: Readonly<Record<string, VoiceErrorCode>> = {
33
+ noSpeech: "no_speech",
34
+ languageUnsupported: "language_unsupported",
35
+ assetsMissing: "assets_missing",
36
+ assetsInstallFailed: "assets_install_failed",
37
+ assetsLocaleLimit: "assets_locale_limit",
38
+ insufficientStorage: "insufficient_storage",
39
+ audioOverrun: "audio_overrun",
40
+ badRequest: "bad_request",
41
+ };
42
+
43
+ /** The wire code for a known spelling (snake_case or legacy camelCase), else undefined. */
44
+ function knownVoiceErrorCode(value: unknown): VoiceErrorCode | undefined {
45
+ if (typeof value !== "string") return undefined;
46
+ if (WIRE_CODES.has(value)) return value as VoiceErrorCode;
47
+ return Object.prototype.hasOwnProperty.call(LEGACY_CODES, value) ? LEGACY_CODES[value] : undefined;
48
+ }
49
+
50
+ /**
51
+ * Maps any value received from a bridge, a helper or storage to a wire code: snake_case codes pass
52
+ * through, legacy camelCase codes are translated, and anything else becomes `failed`.
53
+ */
54
+ export function normalizeVoiceErrorCode(value: unknown): VoiceErrorCode {
55
+ return knownVoiceErrorCode(value) ?? "failed";
56
+ }
57
+
58
+ const DEFAULT_MESSAGES: Record<VoiceErrorCode, string> = {
59
+ denied: "Microphone or speech-recognition permission was denied.",
60
+ restricted: "Microphone or speech-recognition permission is restricted.",
61
+ unavailable: "This device or browser cannot run the selected speech engine.",
62
+ no_speech: "No speech was recognized before the session ended.",
63
+ language_unsupported: "The selected language has no on-device speech model.",
64
+ assets_missing: "The speech model for this language is not installed; it must be downloaded first.",
65
+ assets_install_failed: "Installing the speech model assets failed.",
66
+ assets_locale_limit: "Too many languages are reserved for on-device speech; release one before adding another.",
67
+ insufficient_storage: "There is not enough storage to install the speech model assets.",
68
+ audio_overrun: "Audio arrived faster than the speech engine could consume it.",
69
+ busy: "A speech session is already running.",
70
+ cancelled: "The operation was cancelled.",
71
+ bad_request: "The request was malformed or used the API incorrectly.",
72
+ failed: "The speech engine reported an unexpected failure.",
73
+ };
74
+
75
+ /** The typed failure every public browser operation reports. */
76
+ export class VoiceError extends Error {
77
+ readonly code: VoiceErrorCode;
78
+
79
+ constructor(code: VoiceErrorCode, message: string = DEFAULT_MESSAGES[code]) {
80
+ super(message);
81
+ this.name = "VoiceError";
82
+ this.code = code;
83
+ }
84
+
85
+ /**
86
+ * Preserve a typed error, map an abort to `cancelled`, keep a recognisable `code` from a bridge
87
+ * error, and fold anything else into `fallback`.
88
+ */
89
+ static wrapping(error: unknown, fallback: VoiceErrorCode = "failed"): VoiceError {
90
+ if (error instanceof VoiceError) return error;
91
+ if (error instanceof DOMException && error.name === "AbortError") return new VoiceError("cancelled");
92
+ if (error instanceof Error && error.name === "AbortError") return new VoiceError("cancelled");
93
+ const shaped = error !== null && typeof error === "object" ? (error as { code?: unknown; message?: unknown }) : undefined;
94
+ const bridged = knownVoiceErrorCode(shaped?.code);
95
+ const message = typeof shaped?.message === "string" ? shaped.message : String(error);
96
+ return new VoiceError(bridged ?? fallback, message);
97
+ }
98
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * `@adea-ai/voice/contract`: the shared provider contract — descriptors, typed availability,
3
+ * routing, the snake_case error vocabulary, the dictation session shape and the desktop helpers'
4
+ * wire protocol. Pure TypeScript: safe in a browser, a worker, Bun or Node.
5
+ */
6
+ export * from "./contract";
7
+ export * from "./errors";
8
+ export * from "./session";
9
+ export * from "./wire";
@@ -0,0 +1,65 @@
1
+ /**
2
+ * The platform-neutral dictation session contract: the shape every speech-to-text provider hands a
3
+ * host, whether it runs in a browser, behind the desktop helper or in a mobile plugin.
4
+ */
5
+ import type { VoiceProvider } from "./contract";
6
+ import type { VoiceError } from "./errors";
7
+
8
+ export interface PartialTranscript {
9
+ readonly finalizedText: string;
10
+ readonly volatileText: string;
11
+ /** Monotonic per session, starting at 0 on the first partial. */
12
+ readonly sequence: number;
13
+ }
14
+
15
+ export type SessionEvent =
16
+ | { readonly type: "partial"; readonly partial: PartialTranscript }
17
+ | { readonly type: "final"; readonly text: string }
18
+ | { readonly type: "failed"; readonly error: VoiceError }
19
+ | { readonly type: "cancelled" };
20
+
21
+ export interface EndpointingOptions {
22
+ /** Stop after this much silence following new words. Default 1.6 s. */
23
+ readonly silenceLimitSeconds: number;
24
+ /** Fail with `no_speech` if no words arrive within this time. Default 8 s. */
25
+ readonly noSpeechTimeoutSeconds: number;
26
+ /** Hard cap on one session; `null` means none. Default 60 s. */
27
+ readonly maxDurationSeconds: number | null;
28
+ /** Wait this long for a final result after audio stops. Default 3 s. */
29
+ readonly finalizationDeadlineSeconds: number;
30
+ /** Endpointing resolution. Default 0.25 s. */
31
+ readonly tickIntervalSeconds: number;
32
+ }
33
+
34
+ export const DEFAULT_ENDPOINTING: EndpointingOptions = {
35
+ silenceLimitSeconds: 1.6,
36
+ noSpeechTimeoutSeconds: 8,
37
+ maxDurationSeconds: 60,
38
+ finalizationDeadlineSeconds: 3,
39
+ tickIntervalSeconds: 0.25,
40
+ };
41
+
42
+ export interface TranscriptionSessionOptions {
43
+ readonly locale: string;
44
+ /** Whether this host has the person's consent to send audio to the browser's service. */
45
+ readonly allowNetwork: boolean;
46
+ readonly endpointing?: EndpointingOptions;
47
+ }
48
+
49
+ /** One running recognition session: the browser-facing half of the shared contract. */
50
+ export interface TranscriptionSession {
51
+ /** The session's events. Exactly one terminal event, then the iterator finishes. */
52
+ events(): AsyncIterable<SessionEvent>;
53
+ /** Whether recognition is running on the device (proven) or through a service. */
54
+ readonly execution: "onDevice" | "network";
55
+ /** Stop needing audio and finalize: yields `final` (or `failed`) by the deadline. */
56
+ end(): Promise<void>;
57
+ /** Tear down now: yields `cancelled` and releases the recognizer. Idempotent. */
58
+ cancel(): Promise<void>;
59
+ }
60
+
61
+ export interface TranscriptionProvider extends VoiceProvider {
62
+ /** Creates a session. Throws `VoiceError` before any audio when the combination is refused. */
63
+ createSession(options: TranscriptionSessionOptions): Promise<TranscriptionSession>;
64
+ }
65
+