@adea-ai/voice 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/README.md +136 -2
  2. package/dist/cli/helpers-cli.d.ts +2 -0
  3. package/dist/cli/helpers-cli.js +117 -0
  4. package/dist/contract/contract.d.ts +157 -0
  5. package/dist/contract/errors.d.ts +26 -0
  6. package/dist/contract/index.d.ts +10 -0
  7. package/dist/contract/index.js +64 -0
  8. package/dist/contract/session.d.ts +71 -0
  9. package/dist/contract/turns.d.ts +91 -0
  10. package/dist/contract/wire.d.ts +279 -0
  11. package/dist/desktop/conversation.d.ts +86 -0
  12. package/dist/desktop/desktop-voice.d.ts +212 -0
  13. package/dist/desktop/helper-lock.d.ts +121 -0
  14. package/dist/desktop/helper-process.d.ts +96 -0
  15. package/dist/desktop/index.d.ts +9 -0
  16. package/dist/desktop/index.js +1454 -0
  17. package/dist/desktop/macho-digest.d.ts +9 -0
  18. package/dist/index-7n7epq1a.js +47 -0
  19. package/dist/index-a7d617zr.js +295 -0
  20. package/dist/index-ght8wwpd.js +156 -0
  21. package/dist/index-m4g2tpeq.js +522 -0
  22. package/dist/index-r4hz8gk0.js +10 -0
  23. package/dist/index-tvz9s9nz.js +77 -0
  24. package/dist/index.d.ts +7 -0
  25. package/dist/index.js +96 -0
  26. package/dist/settings/index.d.ts +5 -0
  27. package/dist/settings/index.js +34 -0
  28. package/dist/settings/settings.d.ts +163 -0
  29. package/dist/web/index.d.ts +16 -0
  30. package/dist/web/index.js +1697 -0
  31. package/dist/web/stt/speech-recognition.d.ts +226 -0
  32. package/dist/web/tts/locale-match.d.ts +40 -0
  33. package/dist/web/tts/phonon.d.ts +139 -0
  34. package/dist/web/tts/player.d.ts +115 -0
  35. package/dist/web/tts/system-voices.d.ts +162 -0
  36. package/dist/web/turns.d.ts +91 -0
  37. package/package.json +68 -4
  38. package/src/cli/helpers-cli.ts +135 -0
  39. package/src/contract/contract.ts +393 -0
  40. package/src/contract/errors.ts +98 -0
  41. package/src/contract/index.ts +10 -0
  42. package/src/contract/session.ts +77 -0
  43. package/src/contract/turns.ts +48 -0
  44. package/src/contract/wire.ts +384 -0
  45. package/src/desktop/conversation.ts +347 -0
  46. package/src/desktop/desktop-voice.ts +1129 -0
  47. package/src/desktop/helper-lock.ts +550 -0
  48. package/src/desktop/helper-process.ts +408 -0
  49. package/src/desktop/index.ts +18 -0
  50. package/src/desktop/macho-digest.ts +135 -0
  51. package/src/index.ts +7 -0
  52. package/src/settings/index.ts +5 -0
  53. package/src/settings/settings.ts +478 -0
  54. package/src/web/index.ts +16 -0
  55. package/src/web/stt/speech-recognition.ts +1013 -0
  56. package/src/web/tts/locale-match.ts +131 -0
  57. package/src/web/tts/phonon.ts +386 -0
  58. package/src/web/tts/player.ts +271 -0
  59. package/src/web/tts/system-voices.ts +510 -0
  60. package/src/web/turns.ts +235 -0
@@ -0,0 +1,393 @@
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
+ /**
139
+ * How well an available provider matches the requested locale (additive since contract 1.0; absent
140
+ * means the provider does not report it, which older hosts read as a plain "available").
141
+ *
142
+ * - `exact`: the requested tag itself (`es-419` for `es-419`).
143
+ * - `region`: the same language in the requested region group (`es-MX` for `es-419`), or any voice
144
+ * of the language when the request names no region.
145
+ * - `language`: the language only, outside the requested region (`es-ES` for `es-419`, `pt-BR` for
146
+ * `pt-PT`). Usable, but a host should say so instead of presenting it as the requested variant.
147
+ */
148
+ export type VoiceLocaleMatch = "exact" | "region" | "language";
149
+
150
+ export type VoiceProviderAvailability =
151
+ | {
152
+ readonly status: "available";
153
+ /** How well the locale is matched, when the provider can tell. */
154
+ readonly match?: VoiceLocaleMatch;
155
+ /** A human note, for example which off-region variant would be used. */
156
+ readonly message?: string;
157
+ }
158
+ | { readonly status: "unavailable"; readonly unavailable: VoiceUnavailability };
159
+
160
+ export const AVAILABLE: VoiceProviderAvailability = { status: "available" };
161
+
162
+ /** `available`, annotated with how well the locale is matched. */
163
+ export function availableWithMatch(match: VoiceLocaleMatch, message?: string): VoiceProviderAvailability {
164
+ return message === undefined ? { status: "available", match } : { status: "available", match, message };
165
+ }
166
+
167
+ /** Available, but only in another region of the language (`pt-BR` when `pt-PT` was asked for). */
168
+ export function isLanguageOnly(availability: VoiceProviderAvailability): boolean {
169
+ return availability.status === "available" && availability.match === "language";
170
+ }
171
+
172
+ export function unavailable(
173
+ reason: VoiceUnavailabilityReason,
174
+ message: string,
175
+ remedy?: VoiceRemedy,
176
+ ): VoiceProviderAvailability {
177
+ return { status: "unavailable", unavailable: remedy ? { reason, message, remedy } : { reason, message } };
178
+ }
179
+
180
+ export function isAvailable(
181
+ availability: VoiceProviderAvailability,
182
+ ): availability is Extract<VoiceProviderAvailability, { readonly status: "available" }> {
183
+ return availability.status === "available";
184
+ }
185
+
186
+ /** One candidate for one request: the descriptor plus its truth here and now. */
187
+ export interface VoiceRoute {
188
+ readonly kind: VoiceProviderKind;
189
+ readonly locale: string;
190
+ readonly descriptor: VoiceProviderDescriptor;
191
+ readonly availability: VoiceProviderAvailability;
192
+ }
193
+
194
+ /** "Install, then start": both reasons mean an explicit install would resolve the route. */
195
+ export function requiresModelInstallation(route: VoiceRoute): boolean {
196
+ const reason = route.availability.status === "unavailable" ? route.availability.unavailable.reason : undefined;
197
+ return reason === "modelNotInstalled" || reason === "modelDownloadDisabled";
198
+ }
199
+
200
+ export interface VoiceRoutingDecision {
201
+ readonly kind: VoiceProviderKind;
202
+ readonly locale: string;
203
+ /** The selected provider, or null when none can serve the request. */
204
+ readonly route: VoiceRoute | null;
205
+ /** The registered candidates in policy order, each with its own truth. */
206
+ readonly candidates: readonly VoiceRoute[];
207
+ /** Chain identifiers this build does not register. */
208
+ readonly missing: readonly string[];
209
+ /** The selected provider's truth, or the most actionable failure when nothing resolved. */
210
+ readonly availability: VoiceProviderAvailability;
211
+ }
212
+
213
+ /** A provider: static descriptor, prompt-free probe, and a typed availability per locale. */
214
+ export interface VoiceProvider {
215
+ readonly descriptor: VoiceProviderDescriptor;
216
+ availability(locale: string): Promise<VoiceProviderAvailability>;
217
+ }
218
+
219
+ /** Swift `VoiceUnavailability.Reason.actionability`, value for value. */
220
+ const ACTIONABILITY: Record<VoiceUnavailabilityReason, number> = {
221
+ modelNotInstalled: 100,
222
+ modelDownloadDisabled: 95,
223
+ unsupportedLocale: 90,
224
+ unsupportedOperatingSystem: 80,
225
+ unsupportedDevice: 70,
226
+ permissionDenied: 60,
227
+ licenseNotAccepted: 50,
228
+ contractIncompatible: 40,
229
+ engineFailed: 30,
230
+ networkRequired: 20,
231
+ providerNotRegistered: 10,
232
+ unsupportedPlatform: 0,
233
+ };
234
+
235
+ /** Routing is data: an ordered chain per kind, an explicit override, and one policy flag. */
236
+ export interface VoiceRoutingPolicy {
237
+ /** Ordered provider ids per kind. The first usable one wins. */
238
+ readonly chains: Partial<Record<VoiceProviderKind, readonly string[]>>;
239
+ /** An explicit choice replaces the chain: the caller gets that provider's truth, no substitute. */
240
+ readonly overrides?: Partial<Record<VoiceProviderKind, string>>;
241
+ /** Whether a provider whose models are absent may be selected so the host can install them. */
242
+ readonly allowsOptInModelInstallation: boolean;
243
+ }
244
+
245
+ /** The browser routing table: local recognition only, Phonon first for synthesis. */
246
+ export const WEB_ROUTING_POLICY: VoiceRoutingPolicy = {
247
+ chains: {
248
+ speechToText: ["web.speech-recognition-local"],
249
+ textToSpeech: ["web.phonon", "web.system-voices"],
250
+ },
251
+ allowsOptInModelInstallation: false,
252
+ };
253
+
254
+ export interface RouteRequest {
255
+ readonly kind: VoiceProviderKind;
256
+ readonly locale: string;
257
+ readonly providers: readonly VoiceProvider[];
258
+ readonly policy?: VoiceRoutingPolicy;
259
+ }
260
+
261
+ /**
262
+ * Resolves one request. A provider on another contract major, a network provider in a chain, or a
263
+ * provider whose models are absent are all reported with their own reason; nothing is substituted
264
+ * and nothing is downloaded.
265
+ */
266
+ export async function route(request: RouteRequest): Promise<VoiceRoutingDecision> {
267
+ const policy = request.policy ?? WEB_ROUTING_POLICY;
268
+ const override = policy.overrides?.[request.kind];
269
+ const configured = override ? [override] : policy.chains[request.kind];
270
+ if (configured === undefined) {
271
+ // Same as Swift: no chain for this kind at all is `unsupportedPlatform`, not "not registered".
272
+ return {
273
+ kind: request.kind,
274
+ locale: request.locale,
275
+ route: null,
276
+ candidates: [],
277
+ missing: [],
278
+ availability: unavailable("unsupportedPlatform", `no ${request.kind} provider is defined for this platform`, {
279
+ kind: "chooseAnotherProvider",
280
+ detail: "run on a platform the Voice SDK has a provider for",
281
+ }),
282
+ };
283
+ }
284
+ const chain = configured;
285
+ const byId = new Map(request.providers.map((provider) => [provider.descriptor.id, provider]));
286
+
287
+ const candidates: VoiceRoute[] = [];
288
+ const missing: string[] = [];
289
+ for (const id of chain) {
290
+ const provider = byId.get(id);
291
+ if (!provider) {
292
+ missing.push(id);
293
+ continue;
294
+ }
295
+ candidates.push({
296
+ kind: request.kind,
297
+ locale: request.locale,
298
+ descriptor: provider.descriptor,
299
+ availability: await evaluate(provider, request.locale, policy),
300
+ });
301
+ }
302
+
303
+ const selection = candidates.find((candidate) =>
304
+ isAvailable(candidate.availability) ||
305
+ (policy.allowsOptInModelInstallation && requiresModelInstallation(candidate)),
306
+ );
307
+
308
+ // Swift `VoiceRoutingDecision.availability`: the selected route's truth, else the most
309
+ // actionable candidate failure, else (no candidate at all) `providerNotRegistered`.
310
+ const availability: VoiceProviderAvailability = selection
311
+ ? selection.availability
312
+ : mostActionable(candidates) ??
313
+ unavailable(
314
+ "providerNotRegistered",
315
+ `this build registers no ${request.kind} provider from its routing chain (${chain.join(", ")})`,
316
+ { kind: "chooseAnotherProvider", detail: "install a build that includes the provider" },
317
+ );
318
+
319
+ return {
320
+ kind: request.kind,
321
+ locale: request.locale,
322
+ route: selection ?? null,
323
+ candidates,
324
+ missing,
325
+ availability,
326
+ };
327
+ }
328
+
329
+ async function evaluate(
330
+ provider: VoiceProvider,
331
+ locale: string,
332
+ policy: VoiceRoutingPolicy,
333
+ ): Promise<VoiceProviderAvailability> {
334
+ const descriptor = provider.descriptor;
335
+ if (descriptor.execution === "network") {
336
+ return unavailable("networkRequired", `${descriptor.displayName} requires a network path; the Voice SDK is offline-only`);
337
+ }
338
+ // An incompatible provider is never trusted, so it is not probed either: its probe's meaning
339
+ // may have changed under another contract major.
340
+ if (!isCompatibleContract(descriptor.contract)) {
341
+ return unavailable(
342
+ "contractIncompatible",
343
+ `${descriptor.displayName} speaks contract ${descriptor.contract.major}.${descriptor.contract.minor}; this SDK speaks ${VOICE_CONTRACT.major}.${VOICE_CONTRACT.minor}`,
344
+ { kind: "chooseAnotherProvider", detail: "update the provider or the SDK" },
345
+ );
346
+ }
347
+ let reported: VoiceProviderAvailability;
348
+ try {
349
+ reported = await provider.availability(locale);
350
+ } catch (error) {
351
+ // A throwing probe is that candidate's failure, not the whole decision's.
352
+ return unavailable(
353
+ "engineFailed",
354
+ `${descriptor.displayName} failed while being probed: ${error instanceof Error ? error.message : String(error)}`,
355
+ );
356
+ }
357
+ if (
358
+ reported.status === "unavailable" &&
359
+ reported.unavailable.reason === "modelNotInstalled" &&
360
+ !policy.allowsOptInModelInstallation
361
+ ) {
362
+ return unavailable("modelDownloadDisabled", reported.unavailable.message, {
363
+ kind: "installModel",
364
+ detail: "Download the language in Voice settings.",
365
+ });
366
+ }
367
+ return reported;
368
+ }
369
+
370
+ /**
371
+ * Swift `candidates.map(\.availability).max(by:)` over `Reason.actionability`, with `available`
372
+ * ranked `Int.max`. `max(by:)` replaces only on a strictly greater value, so ties keep the earliest
373
+ * candidate in chain order; this loop does the same.
374
+ */
375
+ function mostActionable(candidates: readonly VoiceRoute[]): VoiceProviderAvailability | undefined {
376
+ let best: VoiceRoute | undefined;
377
+ for (const candidate of candidates) {
378
+ if (best === undefined) {
379
+ best = candidate;
380
+ continue;
381
+ }
382
+ const current = actionability(candidate.availability);
383
+ const incumbent = actionability(best.availability);
384
+ if (current > incumbent) best = candidate;
385
+ }
386
+ return best?.availability;
387
+ }
388
+
389
+ function actionability(availability: VoiceProviderAvailability): number {
390
+ if (availability.status === "available") return Number.MAX_SAFE_INTEGER;
391
+ // A reason from a newer contract minor ranks below every known one rather than poisoning the max.
392
+ return ACTIONABILITY[availability.unavailable.reason] ?? -1;
393
+ }
@@ -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,10 @@
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 "./turns";
10
+ export * from "./wire";
@@ -0,0 +1,77 @@
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
+ /**
16
+ * Where recognition actually ran for a result, recorded at runtime: `local` only when the engine
17
+ * ran on the device (for the browser, `processLocally` held for the whole session), `service` when
18
+ * audio went to a recognition service. Optional: providers that cannot tell leave it out.
19
+ */
20
+ export type RecognitionExecution = "local" | "service";
21
+
22
+ export type SessionEvent =
23
+ | { readonly type: "partial"; readonly partial: PartialTranscript }
24
+ | { readonly type: "final"; readonly text: string; readonly execution?: RecognitionExecution }
25
+ | { readonly type: "failed"; readonly error: VoiceError; readonly execution?: RecognitionExecution }
26
+ | { readonly type: "cancelled" };
27
+
28
+ export interface EndpointingOptions {
29
+ /** Stop after this much silence following new words. Default 1.6 s. */
30
+ readonly silenceLimitSeconds: number;
31
+ /** Fail with `no_speech` if no words arrive within this time. Default 8 s. */
32
+ readonly noSpeechTimeoutSeconds: number;
33
+ /** Hard cap on one session; `null` means none. Default 60 s. */
34
+ readonly maxDurationSeconds: number | null;
35
+ /** Wait this long for a final result after audio stops. Default 3 s. */
36
+ readonly finalizationDeadlineSeconds: number;
37
+ /** Endpointing resolution. Default 0.25 s. */
38
+ readonly tickIntervalSeconds: number;
39
+ }
40
+
41
+ export const DEFAULT_ENDPOINTING: EndpointingOptions = {
42
+ silenceLimitSeconds: 1.6,
43
+ noSpeechTimeoutSeconds: 8,
44
+ maxDurationSeconds: 60,
45
+ finalizationDeadlineSeconds: 3,
46
+ tickIntervalSeconds: 0.25,
47
+ };
48
+
49
+ export interface TranscriptionSessionOptions {
50
+ readonly locale: string;
51
+ /** Whether this host has the person's consent to send audio to the browser's service. */
52
+ readonly allowNetwork: boolean;
53
+ readonly endpointing?: EndpointingOptions;
54
+ /**
55
+ * Called when the recognizer hears speech start (the browser's `speechstart`, or the first words
56
+ * where that event is missing). `VoiceTurnManager` wires it to `notifySpeechDetected()` itself.
57
+ */
58
+ readonly onSpeechStart?: () => void;
59
+ }
60
+
61
+ /** One running recognition session: the browser-facing half of the shared contract. */
62
+ export interface TranscriptionSession {
63
+ /** The session's events. Exactly one terminal event, then the iterator finishes. */
64
+ events(): AsyncIterable<SessionEvent>;
65
+ /** Whether recognition is running on the device (proven) or through a service. */
66
+ readonly execution: "onDevice" | "network";
67
+ /** Stop needing audio and finalize: yields `final` (or `failed`) by the deadline. */
68
+ end(): Promise<void>;
69
+ /** Tear down now: yields `cancelled` and releases the recognizer. Idempotent. */
70
+ cancel(): Promise<void>;
71
+ }
72
+
73
+ export interface TranscriptionProvider extends VoiceProvider {
74
+ /** Creates a session. Throws `VoiceError` before any audio when the combination is refused. */
75
+ createSession(options: TranscriptionSessionOptions): Promise<TranscriptionSession>;
76
+ }
77
+
@@ -0,0 +1,48 @@
1
+ /**
2
+ * The conversation-turn vocabulary every platform reports (#34): the browser `VoiceTurnManager`
3
+ * and the desktop `DesktopVoice.conversation()` emit the same events, so one UI can render either.
4
+ *
5
+ * A turn is one person→assistant exchange: listen, transcript, answer, and the person may talk
6
+ * over the answer. Fields a platform cannot supply are optional (the browser manager has no
7
+ * utterance ids or helper metrics); `turn` names the turn on platforms that run several per
8
+ * conversation.
9
+ */
10
+ import type { VoiceError } from "./errors";
11
+ import type { PartialTranscript } from "./session";
12
+
13
+ /** Why a turn ended without an error. */
14
+ export type TurnEndReason = "completed" | "cancelled" | "barge-in" | "superseded";
15
+
16
+ /** One turn's timings in milliseconds from its start. Never text or audio. */
17
+ export interface TurnMetrics {
18
+ readonly firstPartialMs: number | null;
19
+ readonly transcriptMs: number | null;
20
+ /** When the answer's first utterance started playing. */
21
+ readonly firstAudioMs: number | null;
22
+ readonly speechFinishedMs: number | null;
23
+ }
24
+
25
+ export type TurnEvent =
26
+ /** The microphone is open. */
27
+ | { readonly type: "listening"; readonly turn?: string }
28
+ | { readonly type: "partial"; readonly partial: PartialTranscript; readonly turn?: string }
29
+ /** The transcript is final; the host produces the answer next. */
30
+ | { readonly type: "transcript"; readonly text: string; readonly turn?: string }
31
+ /** Waiting on the host's answer (after the transcript, or between streamed chunks). */
32
+ | { readonly type: "responding"; readonly turn?: string }
33
+ /** The answer is playing. `text` is the chunk the browser manager was given. */
34
+ | { readonly type: "speaking"; readonly text?: string; readonly turn?: string }
35
+ | { readonly type: "speech-started"; readonly utterance?: string; readonly turn?: string }
36
+ | { readonly type: "speech-finished"; readonly utterance?: string; readonly turn?: string }
37
+ | { readonly type: "speech-cancelled"; readonly utterance?: string; readonly turn?: string }
38
+ /** The person talked over the answer; it was stopped (a request cancel, not a mute). */
39
+ | { readonly type: "barge-in"; readonly turn?: string }
40
+ /** The answer was stopped from outside the turn (a system interruption); the turn is open. */
41
+ | { readonly type: "idle"; readonly turn?: string }
42
+ | { readonly type: "metrics"; readonly metrics: TurnMetrics; readonly turn?: string }
43
+ /** Terminal: the turn is over. */
44
+ | { readonly type: "ended"; readonly reason: TurnEndReason; readonly turn?: string }
45
+ /** Terminal: the turn failed. */
46
+ | { readonly type: "failed"; readonly error: VoiceError; readonly turn?: string }
47
+ /** Terminal for the whole conversation (the browser manager's `cancel()`). */
48
+ | { readonly type: "cancelled"; readonly turn?: string };