@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
package/README.md CHANGED
@@ -1,3 +1,137 @@
1
- # Temporary Holding Version
1
+ # `@adea-ai/voice`
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The one TypeScript SDK every Adea app uses for speech. Apps render; this package owns the protocol
4
+ parsing, error vocabulary, routing, fallback and privacy rules, so no app re-implements them.
5
+
6
+ | Entry | Runs in | What it is |
7
+ |---|---|---|
8
+ | `@adea-ai/voice/contract` | anywhere | Provider descriptors, typed availability and routing (#19), the snake_case `VoiceErrorCode` set every helper, plugin and browser provider shares, the dictation session shape, and the desktop helpers' JSON-lines wire types |
9
+ | `@adea-ai/voice/settings` | anywhere | The unified, versioned, per-device Voice settings (#32): provider/model/voice/locale per kind, consents, offline-only, BYOM folders, dictation auto-send, and a store over any `getItem`/`setItem` storage |
10
+ | `@adea-ai/voice/desktop` | Bun/Node (desktop shell) | `createDesktopVoice()`: the client for the pinned `adea-voice-helper`, `adea-transcribe-helper` and `adea-tts-helper`, plus the helper lock (`stageVoiceHelpers`, `verifyStagedVoiceHelpers`) |
11
+ | `@adea-ai/voice/web` | browser | On-device browser dictation with an explicit network policy, Phonon TTS, platform voices, and the turn manager |
12
+
13
+ The root entry re-exports `contract` and `settings`. Browser entries never import `node:` modules.
14
+
15
+ ## Desktop
16
+
17
+ ```ts
18
+ import { createDesktopVoice } from "@adea-ai/voice/desktop";
19
+ import { createVoiceSettingsStore } from "@adea-ai/voice/settings";
20
+
21
+ const voice = createDesktopVoice({ helpers: { voice: "/path/to/adea-voice-helper" } });
22
+ const { settings } = createVoiceSettingsStore(localStorage).read();
23
+
24
+ const capabilities = await voice.capabilities(settings); // routing decisions + reasons
25
+ const dictation = await voice.listen({ settings, onPartial: (p) => render(p.text) });
26
+ const text = await dictation.result; // or dictation.cancel()
27
+
28
+ const speech = await voice.speak({ settings, text: "Hola", locale: "es-419" });
29
+ await speech.done; // "finished" | "cancelled"
30
+ ```
31
+
32
+ Guarantees: a helper missing from the build is `providerNotRegistered`, never a substitute; a helper
33
+ on another wire/contract major is refused; one dictation at a time (`busy`); every dictation ends in
34
+ exactly one terminal event even when a helper crashes or stops answering; nothing goes to the
35
+ network and nothing downloads unless a person starts `installAssets`. `releaseAssets({ locale })`
36
+ removes an Apple model again (it releases the app's reservation; the OS may then reclaim the files)
37
+ and returns the status the system reports afterwards; it needs a voice helper on wire 1.3.
38
+
39
+ ## Browser
40
+
41
+ ### Platform voices pick the region, not just the language (#36)
42
+
43
+ `SystemVoiceProvider` ranks voices **exact tag > same region group > same language**. For `es-419`
44
+ the order is `es-419`, `es-MX`, `es-US`, `es-AR`, the other Latin-American regions, and `es-ES`
45
+ last, whatever order (or default flag) the browser lists them in. Local voices are preferred; with
46
+ `allowNetwork: true` a remote voice wins only on a strictly better match tier.
47
+
48
+ ```ts
49
+ const voices = new SystemVoiceProvider();
50
+ const availability = await voices.availability("pt-PT");
51
+ // { status: "available", match: "language", message: "no local pt-PT voice; only pt-BR ..." }
52
+ if (isLanguageOnly(availability)) showNotice("Portuguese (Brazil) voice will be used");
53
+
54
+ const speech = voices.speak("Hola", { locale: "es-419", onStart: (voice) => showVoice(voice) });
55
+ speech.voice; // { name: "Paulina", lang: "es-MX", localService: true, match: "region", offRegion: false }
56
+ ```
57
+
58
+ - `availability()` keeps `status: "available"` for a language-only match (old hosts keep working)
59
+ and adds `match: "exact" | "region" | "language"` plus a `message`. `isLanguageOnly()` tests it.
60
+ - `chooseVoice(options)` returns the voice `speak()` would use without speaking; `rankVoices()` and
61
+ `voices()` list voices best first. `offRegion: true` means only another region's voice exists.
62
+ - A cancelled utterance rejects with `cancelled` even in Firefox, which fires `end` instead of
63
+ `error`: an utterance that ends without having started is never reported as finished.
64
+
65
+ ### Offline Spanish model: when to revisit
66
+
67
+ ES-419 synthesis is platform voices because no bundled offline Spanish model is commercial-safe
68
+ today (Phonon 40M weights are CC BY-NC 4.0; see `docs/evaluation/licensing-and-dependencies.md`).
69
+ Revisit a bundled offline Spanish voice when **one candidate meets all of these**:
70
+
71
+ 1. Code **and** weights under a licence that allows commercial redistribution (Apache-2.0, MIT,
72
+ BSD, CC BY, or a signed commercial licence); no NC/ND terms and no GPL G2P (eSpeak-ng) in the
73
+ shipped path, recorded in the licensing table.
74
+ 2. A Latin-American voice (`es-419`/`es-MX`), not only `es-ES`, that is at least on par with the
75
+ platform `es-MX` voices in a blinded listening test.
76
+ 3. Runs in the browser WASM path within the Phonon English baselines in `docs/browser-voice.md`
77
+ (first PCM, RTF, cancel latency, offline replay) on the same reference machines.
78
+ 4. A download a person can reasonably opt into, served from Adea's pinned assets.
79
+
80
+ Also revisit if the platform path regresses: the local ES-419 platform-voice row stays without a
81
+ local voice on a target browser (today Chrome desktop exposes none) and that browser is a release
82
+ target. Until then `web.phonon` keeps refusing Spanish with `licenseNotAccepted`.
83
+
84
+ ### Dictation lifecycle (#37)
85
+
86
+ `browserRecognitionLocal()`/`browserRecognitionService()` sessions accept browser options on top
87
+ of the shared contract (`WebTranscriptionSessionOptions`):
88
+
89
+ - **Permission**: `navigator.permissions.query({ name: "microphone" })` runs first where it exists;
90
+ `denied` refuses the session (`denied`), and a later change to `denied` ends it with one
91
+ `failed: denied`. Browsers that cannot query the name are treated as "unknown", not denied.
92
+ - **Microphone choice**: `microphone: { deviceId }` opens that device and recognises from its track
93
+ (`start(track)`, Chrome 137+); a track the SDK opened is stopped on every terminal path. A host
94
+ track (`{ track, stopOnEnd? }`) stays the host's. Browsers that would ignore the track refuse the
95
+ choice instead of silently using another microphone.
96
+ - **Browsers that stop after one utterance** (Chrome on Android): by default the browser's early
97
+ `end` is one clean `final` with what was heard. `onEarlyEnd: "restart"` restarts the recognizer
98
+ inside the same session (up to `maxRestarts`, and never more than 3 times in a row without a
99
+ result) until endpointing, the hard cap or `end()` finishes it.
100
+ - **Page lifecycle**: `visibilitychange` to hidden or `pagehide` ends the session once:
101
+ `whenHidden: "finalize"` (default) reports the words so far, `"cancel"` reports `cancelled`,
102
+ `"ignore"` keeps listening.
103
+ - **Offline proof**: `final`/`failed` carry `execution: "local" | "service"`. Local sessions are
104
+ refused if the browser drops `processLocally`. Service sessions are refused offline, end with
105
+ `failed: unavailable` when the device goes offline, and are refused outright with
106
+ `settings: { privacy: { offlineOnly: true } }`.
107
+ - **Model install**: `installModel(locale, { allowDownload, onProgress, signal })` still resolves
108
+ the browser's boolean; it reports `started`/`downloading`/`installed`/`failed`/`cancelled` and
109
+ rejects with `cancelled` on abort (the browser may finish its own download in the background).
110
+ - **Barge-in**: `onSpeechStart` fires on the recognizer's `speechstart` (or the first words).
111
+ `VoiceTurnManager` wires it to `notifySpeechDetected()` itself; hosts with their own sessions
112
+ spread `bargeInOnSpeechStart(manager)` into the session options.
113
+
114
+ ## Pinning the helpers in an app
115
+
116
+ Each Voice release publishes the signed macOS helpers as `.tar.gz` artifacts with their sha256 at
117
+ `https://adea.dev/releases/voice/<helper>/<version>/`, and the matching lock at
118
+ `https://adea.dev/releases/voice/voice-helpers-<version>.lock.json`. An app commits that lock and:
119
+
120
+ ```sh
121
+ adea-voice-helpers stage --lock voice-helpers.lock.json --out build/voice-helpers # build
122
+ adea-voice-helpers verify --lock voice-helpers.lock.json --dir <app>/voice-helpers # release gate
123
+ ```
124
+
125
+ `stage` fails on a missing artifact or any digest mismatch and leaves nothing half-staged; `verify`
126
+ fails the release unless the packaged helpers are exactly the pinned ones (a `--local` developer
127
+ staging is refused).
128
+
129
+ The app's release build signs the helpers again, so `verify` does not compare the packaged file's
130
+ sha256. It compares the signature-independent code digest (`machoCodeDigest`, the lock's
131
+ `codeSha256`; for a lock without it, the digest `stage` recorded in `voice-helpers.json`, plus
132
+ `codesign --verify --strict`), checks every staged `Frameworks/` file, refuses symlinks and empty
133
+ files left by a copy that flattened them, and launches each helper with `--version` (10 s timeout)
134
+ to require the lock's release, wire 1 and contract 1. `adea-voice-helpers digest <file>` prints the
135
+ code digest.
136
+
137
+ Build and test: `bun install && bun test && bunx tsc --noEmit && bun run build`.
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env bun
2
+ export {};
@@ -0,0 +1,117 @@
1
+ #!/usr/bin/env bun
2
+ import {
3
+ machoCodeDigestFile2,
4
+ HELPER_NAMES2,
5
+ HELPER_TARGETS2,
6
+ HelperLockError2,
7
+ validateHelperLock2,
8
+ readHelperLock2,
9
+ helperArtifactUrl2,
10
+ currentHelperTarget2,
11
+ stageVoiceHelpers2,
12
+ verifyStagedVoiceHelpers2
13
+ } from "../index-m4g2tpeq.js";
14
+
15
+ // src/cli/helpers-cli.ts
16
+ import { existsSync, writeFileSync } from "node:fs";
17
+ var [command, ...rest] = process.argv.slice(2);
18
+ function flag(name) {
19
+ const index = rest.indexOf(`--${name}`);
20
+ return index >= 0 ? rest[index + 1] : undefined;
21
+ }
22
+ function usage(message) {
23
+ console.error(`adea-voice-helpers: ${message}`);
24
+ console.error("usage: adea-voice-helpers stage|verify|url --lock <lock.json> …");
25
+ process.exit(2);
26
+ }
27
+ function target() {
28
+ const value = flag("target") ?? currentHelperTarget2();
29
+ if (!value || !HELPER_TARGETS2.includes(value))
30
+ usage(`no helper target for this machine; pass --target`);
31
+ return value;
32
+ }
33
+ function helpers(lockHelpers) {
34
+ const value = flag("helpers");
35
+ const names = value ? value.split(",").map((name) => name.trim()).filter(Boolean) : lockHelpers;
36
+ for (const name of names) {
37
+ if (!HELPER_NAMES2.includes(name))
38
+ usage(`unknown helper ${name}`);
39
+ }
40
+ return names;
41
+ }
42
+ async function pin(lockPath) {
43
+ const version = flag("version") ?? usage("pin needs --version");
44
+ const base = flag("base") ?? "https://adea.dev/releases/voice/";
45
+ const url = `${base}voice-helpers-${version}.lock.json`;
46
+ const response = await fetch(url);
47
+ if (!response.ok)
48
+ throw new HelperLockError2(`GET ${url} answered ${response.status}: is ${version} released?`);
49
+ const lock = validateHelperLock2(await response.json());
50
+ if (lock.version !== version)
51
+ throw new HelperLockError2(`${url} pins ${lock.version}, not ${version}`);
52
+ writeFileSync(lockPath, `${JSON.stringify(lock, null, 2)}
53
+ `);
54
+ console.log(`voice helpers: ${lockPath} now pins ${version}`);
55
+ }
56
+ function digest(files) {
57
+ if (files.length === 0)
58
+ usage("digest needs a file");
59
+ for (const file of files) {
60
+ if (!existsSync(file))
61
+ throw new HelperLockError2(`${file} does not exist`);
62
+ const code = machoCodeDigestFile2(file);
63
+ if (!code)
64
+ throw new HelperLockError2(`${file} is not a Mach-O file this can digest`);
65
+ console.log(`${code} ${file}`);
66
+ }
67
+ }
68
+ async function main() {
69
+ if (command === "digest")
70
+ return digest(rest);
71
+ const lockPath = flag("lock");
72
+ if (!command || !lockPath)
73
+ usage("missing command or --lock");
74
+ if (command === "pin")
75
+ return await pin(lockPath);
76
+ const lock = readHelperLock2(lockPath);
77
+ const selectedTarget = target();
78
+ const pinned = Object.entries(lock.helpers).filter(([, targets]) => targets?.[selectedTarget]).map(([name]) => name);
79
+ switch (command) {
80
+ case "stage": {
81
+ const out = flag("out") ?? usage("stage needs --out");
82
+ const record = await stageVoiceHelpers2({
83
+ lock,
84
+ target: selectedTarget,
85
+ outDir: out,
86
+ helpers: helpers(pinned),
87
+ cacheDir: flag("cache"),
88
+ localDir: flag("local"),
89
+ handshake: rest.includes("--no-handshake") ? false : undefined,
90
+ log: (message) => console.log(`voice helpers: ${message}`)
91
+ });
92
+ console.log(`voice helpers: staged ${Object.keys(record.helpers).join(", ")} ${record.version} for ${record.target}`);
93
+ return;
94
+ }
95
+ case "verify": {
96
+ const dir = flag("dir") ?? usage("verify needs --dir");
97
+ verifyStagedVoiceHelpers2({ lock, target: selectedTarget, dir, helpers: helpers(pinned) });
98
+ console.log(`voice helpers: ${dir} holds the pinned ${lock.version} helpers for ${selectedTarget}`);
99
+ return;
100
+ }
101
+ case "url": {
102
+ const helper = flag("helper") ?? usage("url needs --helper");
103
+ console.log(helperArtifactUrl2(lock, helpers([helper])[0], selectedTarget));
104
+ return;
105
+ }
106
+ default:
107
+ usage(`unknown command ${command}`);
108
+ }
109
+ }
110
+ main().catch((error) => {
111
+ if (error instanceof HelperLockError2) {
112
+ console.error(`adea-voice-helpers: ${error.message}`);
113
+ process.exit(1);
114
+ }
115
+ console.error(error);
116
+ process.exit(1);
117
+ });
@@ -0,0 +1,157 @@
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
+ /** The contract this build speaks. Compatibility is by major version only. */
13
+ export declare const VOICE_CONTRACT: {
14
+ readonly major: 1;
15
+ readonly minor: 0;
16
+ };
17
+ export interface VoiceContract {
18
+ readonly major: number;
19
+ readonly minor: number;
20
+ }
21
+ /** Whether a provider speaking `candidate` can be used by an SDK speaking `supported`. */
22
+ export declare function isCompatibleContract(candidate: VoiceContract, supported?: VoiceContract): boolean;
23
+ export type VoiceProviderKind = "speechToText" | "textToSpeech";
24
+ export type VoicePlatform = "macOS" | "iOS" | "windows" | "linux" | "android" | "web";
25
+ export type VoiceExecutionLocation = "onDevice" | "systemProvided" | "network";
26
+ /** Code and asset licences stay separate: a permissive runtime can carry non-commercial weights. */
27
+ export interface VoiceAssetLicense {
28
+ readonly spdxIdentifier: string;
29
+ readonly commercialUse: boolean;
30
+ }
31
+ /** Capability, not availability: what the provider can do when it can run here. */
32
+ export interface VoiceProviderCapabilities {
33
+ readonly streamingPartials?: boolean;
34
+ readonly trueCancellation?: boolean;
35
+ readonly modelInstallation?: boolean;
36
+ readonly localeSelection?: boolean;
37
+ readonly voiceSelection?: boolean;
38
+ readonly utteranceQueueing?: boolean;
39
+ readonly wordBoundaryPause?: boolean;
40
+ }
41
+ /**
42
+ * The capability bits in wire order: bit `i` is `1 << i`. Same order as the Swift
43
+ * `VoiceProviderCapabilities` option set (`Sources/AdeaVoice/VoiceProvider.swift`); the integer
44
+ * mask is what every other surface (helper, Capacitor, Android) carries. Append only.
45
+ */
46
+ export declare const VOICE_CAPABILITY_BITS: readonly ["streamingPartials", "trueCancellation", "modelInstallation", "localeSelection", "voiceSelection", "utteranceQueueing", "wordBoundaryPause"];
47
+ /** The integer bit mask for a capabilities object (the wire form). */
48
+ export declare function capabilitiesToMask(capabilities: VoiceProviderCapabilities): number;
49
+ /**
50
+ * A capabilities object from an integer bit mask. Every known flag is present (true or false);
51
+ * bits this build does not know are ignored, as a higher contract minor may add them.
52
+ */
53
+ export declare function capabilitiesFromMask(mask: number): Required<VoiceProviderCapabilities>;
54
+ /** Static identity and constraints. Safe to cache and log. */
55
+ export interface VoiceProviderDescriptor {
56
+ readonly id: string;
57
+ readonly displayName: string;
58
+ readonly kind: VoiceProviderKind;
59
+ readonly platforms: readonly VoicePlatform[];
60
+ readonly execution: VoiceExecutionLocation;
61
+ readonly contract: VoiceContract;
62
+ readonly requiresModelDownload: boolean;
63
+ readonly modelFamilies: readonly string[];
64
+ readonly licenses: readonly VoiceAssetLicense[];
65
+ readonly capabilities: VoiceProviderCapabilities;
66
+ }
67
+ /** The closed set of reasons a provider cannot serve a request right now. */
68
+ export type VoiceUnavailabilityReason = "unsupportedOperatingSystem" | "unsupportedPlatform" | "unsupportedDevice" | "unsupportedLocale" | "modelNotInstalled" | "modelDownloadDisabled" | "licenseNotAccepted" | "networkRequired" | "permissionDenied" | "contractIncompatible" | "providerNotRegistered" | "engineFailed";
69
+ export type VoiceRemedyKind = "installModel" | "switchLocale" | "upgradeOperatingSystem" | "acceptLicense" | "grantPermission" | "chooseAnotherProvider" | "none";
70
+ export interface VoiceRemedy {
71
+ readonly kind: VoiceRemedyKind;
72
+ readonly detail: string;
73
+ }
74
+ export interface VoiceUnavailability {
75
+ readonly reason: VoiceUnavailabilityReason;
76
+ readonly message: string;
77
+ readonly remedy?: VoiceRemedy;
78
+ }
79
+ /**
80
+ * How well an available provider matches the requested locale (additive since contract 1.0; absent
81
+ * means the provider does not report it, which older hosts read as a plain "available").
82
+ *
83
+ * - `exact`: the requested tag itself (`es-419` for `es-419`).
84
+ * - `region`: the same language in the requested region group (`es-MX` for `es-419`), or any voice
85
+ * of the language when the request names no region.
86
+ * - `language`: the language only, outside the requested region (`es-ES` for `es-419`, `pt-BR` for
87
+ * `pt-PT`). Usable, but a host should say so instead of presenting it as the requested variant.
88
+ */
89
+ export type VoiceLocaleMatch = "exact" | "region" | "language";
90
+ export type VoiceProviderAvailability = {
91
+ readonly status: "available";
92
+ /** How well the locale is matched, when the provider can tell. */
93
+ readonly match?: VoiceLocaleMatch;
94
+ /** A human note, for example which off-region variant would be used. */
95
+ readonly message?: string;
96
+ } | {
97
+ readonly status: "unavailable";
98
+ readonly unavailable: VoiceUnavailability;
99
+ };
100
+ export declare const AVAILABLE: VoiceProviderAvailability;
101
+ /** `available`, annotated with how well the locale is matched. */
102
+ export declare function availableWithMatch(match: VoiceLocaleMatch, message?: string): VoiceProviderAvailability;
103
+ /** Available, but only in another region of the language (`pt-BR` when `pt-PT` was asked for). */
104
+ export declare function isLanguageOnly(availability: VoiceProviderAvailability): boolean;
105
+ export declare function unavailable(reason: VoiceUnavailabilityReason, message: string, remedy?: VoiceRemedy): VoiceProviderAvailability;
106
+ export declare function isAvailable(availability: VoiceProviderAvailability): availability is Extract<VoiceProviderAvailability, {
107
+ readonly status: "available";
108
+ }>;
109
+ /** One candidate for one request: the descriptor plus its truth here and now. */
110
+ export interface VoiceRoute {
111
+ readonly kind: VoiceProviderKind;
112
+ readonly locale: string;
113
+ readonly descriptor: VoiceProviderDescriptor;
114
+ readonly availability: VoiceProviderAvailability;
115
+ }
116
+ /** "Install, then start": both reasons mean an explicit install would resolve the route. */
117
+ export declare function requiresModelInstallation(route: VoiceRoute): boolean;
118
+ export interface VoiceRoutingDecision {
119
+ readonly kind: VoiceProviderKind;
120
+ readonly locale: string;
121
+ /** The selected provider, or null when none can serve the request. */
122
+ readonly route: VoiceRoute | null;
123
+ /** The registered candidates in policy order, each with its own truth. */
124
+ readonly candidates: readonly VoiceRoute[];
125
+ /** Chain identifiers this build does not register. */
126
+ readonly missing: readonly string[];
127
+ /** The selected provider's truth, or the most actionable failure when nothing resolved. */
128
+ readonly availability: VoiceProviderAvailability;
129
+ }
130
+ /** A provider: static descriptor, prompt-free probe, and a typed availability per locale. */
131
+ export interface VoiceProvider {
132
+ readonly descriptor: VoiceProviderDescriptor;
133
+ availability(locale: string): Promise<VoiceProviderAvailability>;
134
+ }
135
+ /** Routing is data: an ordered chain per kind, an explicit override, and one policy flag. */
136
+ export interface VoiceRoutingPolicy {
137
+ /** Ordered provider ids per kind. The first usable one wins. */
138
+ readonly chains: Partial<Record<VoiceProviderKind, readonly string[]>>;
139
+ /** An explicit choice replaces the chain: the caller gets that provider's truth, no substitute. */
140
+ readonly overrides?: Partial<Record<VoiceProviderKind, string>>;
141
+ /** Whether a provider whose models are absent may be selected so the host can install them. */
142
+ readonly allowsOptInModelInstallation: boolean;
143
+ }
144
+ /** The browser routing table: local recognition only, Phonon first for synthesis. */
145
+ export declare const WEB_ROUTING_POLICY: VoiceRoutingPolicy;
146
+ export interface RouteRequest {
147
+ readonly kind: VoiceProviderKind;
148
+ readonly locale: string;
149
+ readonly providers: readonly VoiceProvider[];
150
+ readonly policy?: VoiceRoutingPolicy;
151
+ }
152
+ /**
153
+ * Resolves one request. A provider on another contract major, a network provider in a chain, or a
154
+ * provider whose models are absent are all reported with their own reason; nothing is substituted
155
+ * and nothing is downloaded.
156
+ */
157
+ export declare function route(request: RouteRequest): Promise<VoiceRoutingDecision>;
@@ -0,0 +1,26 @@
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 declare const VOICE_ERROR_CODES: readonly ["denied", "restricted", "unavailable", "no_speech", "language_unsupported", "assets_missing", "assets_install_failed", "assets_locale_limit", "insufficient_storage", "audio_overrun", "busy", "cancelled", "bad_request", "failed"];
11
+ export type VoiceErrorCode = (typeof VOICE_ERROR_CODES)[number];
12
+ /**
13
+ * Maps any value received from a bridge, a helper or storage to a wire code: snake_case codes pass
14
+ * through, legacy camelCase codes are translated, and anything else becomes `failed`.
15
+ */
16
+ export declare function normalizeVoiceErrorCode(value: unknown): VoiceErrorCode;
17
+ /** The typed failure every public browser operation reports. */
18
+ export declare class VoiceError extends Error {
19
+ readonly code: VoiceErrorCode;
20
+ constructor(code: VoiceErrorCode, message?: string);
21
+ /**
22
+ * Preserve a typed error, map an abort to `cancelled`, keep a recognisable `code` from a bridge
23
+ * error, and fold anything else into `fallback`.
24
+ */
25
+ static wrapping(error: unknown, fallback?: VoiceErrorCode): VoiceError;
26
+ }
@@ -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,64 @@
1
+ import {
2
+ DEFAULT_ENDPOINTING2
3
+ } from "../index-r4hz8gk0.js";
4
+ import {
5
+ VOICE_CONTRACT2,
6
+ isCompatibleContract2,
7
+ VOICE_CAPABILITY_BITS2,
8
+ capabilitiesToMask2,
9
+ capabilitiesFromMask2,
10
+ AVAILABLE2,
11
+ availableWithMatch2,
12
+ isLanguageOnly2,
13
+ unavailable2,
14
+ isAvailable2,
15
+ requiresModelInstallation2,
16
+ WEB_ROUTING_POLICY2,
17
+ route2
18
+ } from "../index-ght8wwpd.js";
19
+ import {
20
+ WIRE_VERSION2,
21
+ TURN_WIRE_MINOR2,
22
+ RELEASE_ASSETS_WIRE_MINOR2,
23
+ CONTRACT_MAJOR2,
24
+ MAX_WIRE_LINE_BYTES2,
25
+ isTurnTerminal2,
26
+ parseWireLine2,
27
+ encodeWireCommand2,
28
+ correlationId2,
29
+ isCompatibleHandshake2
30
+ } from "../index-7n7epq1a.js";
31
+ import {
32
+ VOICE_ERROR_CODES2,
33
+ normalizeVoiceErrorCode2,
34
+ VoiceError2
35
+ } from "../index-tvz9s9nz.js";
36
+ export {
37
+ AVAILABLE2 as AVAILABLE,
38
+ CONTRACT_MAJOR2 as CONTRACT_MAJOR,
39
+ DEFAULT_ENDPOINTING2 as DEFAULT_ENDPOINTING,
40
+ MAX_WIRE_LINE_BYTES2 as MAX_WIRE_LINE_BYTES,
41
+ RELEASE_ASSETS_WIRE_MINOR2 as RELEASE_ASSETS_WIRE_MINOR,
42
+ TURN_WIRE_MINOR2 as TURN_WIRE_MINOR,
43
+ VOICE_CAPABILITY_BITS2 as VOICE_CAPABILITY_BITS,
44
+ VOICE_CONTRACT2 as VOICE_CONTRACT,
45
+ VOICE_ERROR_CODES2 as VOICE_ERROR_CODES,
46
+ VoiceError2 as VoiceError,
47
+ WEB_ROUTING_POLICY2 as WEB_ROUTING_POLICY,
48
+ WIRE_VERSION2 as WIRE_VERSION,
49
+ availableWithMatch2 as availableWithMatch,
50
+ capabilitiesFromMask2 as capabilitiesFromMask,
51
+ capabilitiesToMask2 as capabilitiesToMask,
52
+ correlationId2 as correlationId,
53
+ encodeWireCommand2 as encodeWireCommand,
54
+ isAvailable2 as isAvailable,
55
+ isCompatibleContract2 as isCompatibleContract,
56
+ isCompatibleHandshake2 as isCompatibleHandshake,
57
+ isLanguageOnly2 as isLanguageOnly,
58
+ isTurnTerminal2 as isTurnTerminal,
59
+ normalizeVoiceErrorCode2 as normalizeVoiceErrorCode,
60
+ parseWireLine2 as parseWireLine,
61
+ requiresModelInstallation2 as requiresModelInstallation,
62
+ route2 as route,
63
+ unavailable2 as unavailable
64
+ };
@@ -0,0 +1,71 @@
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
+ export interface PartialTranscript {
8
+ readonly finalizedText: string;
9
+ readonly volatileText: string;
10
+ /** Monotonic per session, starting at 0 on the first partial. */
11
+ readonly sequence: number;
12
+ }
13
+ /**
14
+ * Where recognition actually ran for a result, recorded at runtime: `local` only when the engine
15
+ * ran on the device (for the browser, `processLocally` held for the whole session), `service` when
16
+ * audio went to a recognition service. Optional: providers that cannot tell leave it out.
17
+ */
18
+ export type RecognitionExecution = "local" | "service";
19
+ export type SessionEvent = {
20
+ readonly type: "partial";
21
+ readonly partial: PartialTranscript;
22
+ } | {
23
+ readonly type: "final";
24
+ readonly text: string;
25
+ readonly execution?: RecognitionExecution;
26
+ } | {
27
+ readonly type: "failed";
28
+ readonly error: VoiceError;
29
+ readonly execution?: RecognitionExecution;
30
+ } | {
31
+ readonly type: "cancelled";
32
+ };
33
+ export interface EndpointingOptions {
34
+ /** Stop after this much silence following new words. Default 1.6 s. */
35
+ readonly silenceLimitSeconds: number;
36
+ /** Fail with `no_speech` if no words arrive within this time. Default 8 s. */
37
+ readonly noSpeechTimeoutSeconds: number;
38
+ /** Hard cap on one session; `null` means none. Default 60 s. */
39
+ readonly maxDurationSeconds: number | null;
40
+ /** Wait this long for a final result after audio stops. Default 3 s. */
41
+ readonly finalizationDeadlineSeconds: number;
42
+ /** Endpointing resolution. Default 0.25 s. */
43
+ readonly tickIntervalSeconds: number;
44
+ }
45
+ export declare const DEFAULT_ENDPOINTING: EndpointingOptions;
46
+ export interface TranscriptionSessionOptions {
47
+ readonly locale: string;
48
+ /** Whether this host has the person's consent to send audio to the browser's service. */
49
+ readonly allowNetwork: boolean;
50
+ readonly endpointing?: EndpointingOptions;
51
+ /**
52
+ * Called when the recognizer hears speech start (the browser's `speechstart`, or the first words
53
+ * where that event is missing). `VoiceTurnManager` wires it to `notifySpeechDetected()` itself.
54
+ */
55
+ readonly onSpeechStart?: () => void;
56
+ }
57
+ /** One running recognition session: the browser-facing half of the shared contract. */
58
+ export interface TranscriptionSession {
59
+ /** The session's events. Exactly one terminal event, then the iterator finishes. */
60
+ events(): AsyncIterable<SessionEvent>;
61
+ /** Whether recognition is running on the device (proven) or through a service. */
62
+ readonly execution: "onDevice" | "network";
63
+ /** Stop needing audio and finalize: yields `final` (or `failed`) by the deadline. */
64
+ end(): Promise<void>;
65
+ /** Tear down now: yields `cancelled` and releases the recognizer. Idempotent. */
66
+ cancel(): Promise<void>;
67
+ }
68
+ export interface TranscriptionProvider extends VoiceProvider {
69
+ /** Creates a session. Throws `VoiceError` before any audio when the combination is refused. */
70
+ createSession(options: TranscriptionSessionOptions): Promise<TranscriptionSession>;
71
+ }