@adea-ai/voice 0.2.0 → 0.4.1

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 (45) hide show
  1. package/README.md +86 -1
  2. package/dist/cli/helpers-cli.js +17 -2
  3. package/dist/contract/contract.d.ts +21 -2
  4. package/dist/contract/index.d.ts +1 -0
  5. package/dist/contract/index.js +12 -2
  6. package/dist/contract/session.d.ts +13 -0
  7. package/dist/contract/turns.d.ts +91 -0
  8. package/dist/contract/wire.d.ts +92 -1
  9. package/dist/desktop/conversation.d.ts +86 -0
  10. package/dist/desktop/desktop-voice.d.ts +61 -1
  11. package/dist/desktop/helper-lock.d.ts +45 -7
  12. package/dist/desktop/helper-process.d.ts +4 -0
  13. package/dist/desktop/index.d.ts +2 -0
  14. package/dist/desktop/index.js +427 -15
  15. package/dist/desktop/macho-digest.d.ts +9 -0
  16. package/dist/{index-rehs788p.js → index-7n7epq1a.js} +7 -2
  17. package/dist/{index-s270cw30.js → index-a7d617zr.js} +1 -1
  18. package/dist/{index-9kerqn9r.js → index-ght8wwpd.js} +9 -3
  19. package/dist/{index-acm1yvvv.js → index-m4g2tpeq.js} +258 -26
  20. package/dist/index.js +13 -3
  21. package/dist/settings/index.js +1 -1
  22. package/dist/web/index.d.ts +1 -0
  23. package/dist/web/index.js +459 -49
  24. package/dist/web/stt/speech-recognition.d.ts +128 -7
  25. package/dist/web/tts/locale-match.d.ts +40 -0
  26. package/dist/web/tts/system-voices.d.ts +44 -4
  27. package/dist/web/turns.d.ts +15 -25
  28. package/package.json +1 -1
  29. package/src/cli/helpers-cli.ts +18 -2
  30. package/src/contract/contract.ts +32 -4
  31. package/src/contract/index.ts +1 -0
  32. package/src/contract/session.ts +14 -2
  33. package/src/contract/turns.ts +48 -0
  34. package/src/contract/wire.ts +123 -2
  35. package/src/desktop/conversation.ts +347 -0
  36. package/src/desktop/desktop-voice.ts +197 -1
  37. package/src/desktop/helper-lock.ts +195 -20
  38. package/src/desktop/helper-process.ts +17 -10
  39. package/src/desktop/index.ts +2 -0
  40. package/src/desktop/macho-digest.ts +135 -0
  41. package/src/web/index.ts +1 -0
  42. package/src/web/stt/speech-recognition.ts +454 -24
  43. package/src/web/tts/locale-match.ts +131 -0
  44. package/src/web/tts/system-voices.ts +144 -35
  45. package/src/web/turns.ts +22 -11
package/README.md CHANGED
@@ -32,7 +32,84 @@ await speech.done; // "finished" | "
32
32
  Guarantees: a helper missing from the build is `providerNotRegistered`, never a substitute; a helper
33
33
  on another wire/contract major is refused; one dictation at a time (`busy`); every dictation ends in
34
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`.
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.
36
113
 
37
114
  ## Pinning the helpers in an app
38
115
 
@@ -49,4 +126,12 @@ adea-voice-helpers verify --lock voice-helpers.lock.json --dir <app>/voice-helpe
49
126
  fails the release unless the packaged helpers are exactly the pinned ones (a `--local` developer
50
127
  staging is refused).
51
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
+
52
137
  Build and test: `bun install && bun test && bunx tsc --noEmit && bun run build`.
@@ -1,5 +1,6 @@
1
1
  #!/usr/bin/env bun
2
2
  import {
3
+ machoCodeDigestFile2,
3
4
  HELPER_NAMES2,
4
5
  HELPER_TARGETS2,
5
6
  HelperLockError2,
@@ -9,10 +10,10 @@ import {
9
10
  currentHelperTarget2,
10
11
  stageVoiceHelpers2,
11
12
  verifyStagedVoiceHelpers2
12
- } from "../index-acm1yvvv.js";
13
+ } from "../index-m4g2tpeq.js";
13
14
 
14
15
  // src/cli/helpers-cli.ts
15
- import { writeFileSync } from "node:fs";
16
+ import { existsSync, writeFileSync } from "node:fs";
16
17
  var [command, ...rest] = process.argv.slice(2);
17
18
  function flag(name) {
18
19
  const index = rest.indexOf(`--${name}`);
@@ -52,7 +53,21 @@ async function pin(lockPath) {
52
53
  `);
53
54
  console.log(`voice helpers: ${lockPath} now pins ${version}`);
54
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
+ }
55
68
  async function main() {
69
+ if (command === "digest")
70
+ return digest(rest);
56
71
  const lockPath = flag("lock");
57
72
  if (!command || !lockPath)
58
73
  usage("missing command or --lock");
@@ -76,17 +76,36 @@ export interface VoiceUnavailability {
76
76
  readonly message: string;
77
77
  readonly remedy?: VoiceRemedy;
78
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";
79
90
  export type VoiceProviderAvailability = {
80
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;
81
96
  } | {
82
97
  readonly status: "unavailable";
83
98
  readonly unavailable: VoiceUnavailability;
84
99
  };
85
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;
86
105
  export declare function unavailable(reason: VoiceUnavailabilityReason, message: string, remedy?: VoiceRemedy): VoiceProviderAvailability;
87
- export declare function isAvailable(availability: VoiceProviderAvailability): availability is {
106
+ export declare function isAvailable(availability: VoiceProviderAvailability): availability is Extract<VoiceProviderAvailability, {
88
107
  readonly status: "available";
89
- };
108
+ }>;
90
109
  /** One candidate for one request: the descriptor plus its truth here and now. */
91
110
  export interface VoiceRoute {
92
111
  readonly kind: VoiceProviderKind;
@@ -6,4 +6,5 @@
6
6
  export * from "./contract";
7
7
  export * from "./errors";
8
8
  export * from "./session";
9
+ export * from "./turns";
9
10
  export * from "./wire";
@@ -8,21 +8,26 @@ import {
8
8
  capabilitiesToMask2,
9
9
  capabilitiesFromMask2,
10
10
  AVAILABLE2,
11
+ availableWithMatch2,
12
+ isLanguageOnly2,
11
13
  unavailable2,
12
14
  isAvailable2,
13
15
  requiresModelInstallation2,
14
16
  WEB_ROUTING_POLICY2,
15
17
  route2
16
- } from "../index-9kerqn9r.js";
18
+ } from "../index-ght8wwpd.js";
17
19
  import {
18
20
  WIRE_VERSION2,
21
+ TURN_WIRE_MINOR2,
22
+ RELEASE_ASSETS_WIRE_MINOR2,
19
23
  CONTRACT_MAJOR2,
20
24
  MAX_WIRE_LINE_BYTES2,
25
+ isTurnTerminal2,
21
26
  parseWireLine2,
22
27
  encodeWireCommand2,
23
28
  correlationId2,
24
29
  isCompatibleHandshake2
25
- } from "../index-rehs788p.js";
30
+ } from "../index-7n7epq1a.js";
26
31
  import {
27
32
  VOICE_ERROR_CODES2,
28
33
  normalizeVoiceErrorCode2,
@@ -33,12 +38,15 @@ export {
33
38
  CONTRACT_MAJOR2 as CONTRACT_MAJOR,
34
39
  DEFAULT_ENDPOINTING2 as DEFAULT_ENDPOINTING,
35
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,
36
43
  VOICE_CAPABILITY_BITS2 as VOICE_CAPABILITY_BITS,
37
44
  VOICE_CONTRACT2 as VOICE_CONTRACT,
38
45
  VOICE_ERROR_CODES2 as VOICE_ERROR_CODES,
39
46
  VoiceError2 as VoiceError,
40
47
  WEB_ROUTING_POLICY2 as WEB_ROUTING_POLICY,
41
48
  WIRE_VERSION2 as WIRE_VERSION,
49
+ availableWithMatch2 as availableWithMatch,
42
50
  capabilitiesFromMask2 as capabilitiesFromMask,
43
51
  capabilitiesToMask2 as capabilitiesToMask,
44
52
  correlationId2 as correlationId,
@@ -46,6 +54,8 @@ export {
46
54
  isAvailable2 as isAvailable,
47
55
  isCompatibleContract2 as isCompatibleContract,
48
56
  isCompatibleHandshake2 as isCompatibleHandshake,
57
+ isLanguageOnly2 as isLanguageOnly,
58
+ isTurnTerminal2 as isTurnTerminal,
49
59
  normalizeVoiceErrorCode2 as normalizeVoiceErrorCode,
50
60
  parseWireLine2 as parseWireLine,
51
61
  requiresModelInstallation2 as requiresModelInstallation,
@@ -10,15 +10,23 @@ export interface PartialTranscript {
10
10
  /** Monotonic per session, starting at 0 on the first partial. */
11
11
  readonly sequence: number;
12
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";
13
19
  export type SessionEvent = {
14
20
  readonly type: "partial";
15
21
  readonly partial: PartialTranscript;
16
22
  } | {
17
23
  readonly type: "final";
18
24
  readonly text: string;
25
+ readonly execution?: RecognitionExecution;
19
26
  } | {
20
27
  readonly type: "failed";
21
28
  readonly error: VoiceError;
29
+ readonly execution?: RecognitionExecution;
22
30
  } | {
23
31
  readonly type: "cancelled";
24
32
  };
@@ -40,6 +48,11 @@ export interface TranscriptionSessionOptions {
40
48
  /** Whether this host has the person's consent to send audio to the browser's service. */
41
49
  readonly allowNetwork: boolean;
42
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;
43
56
  }
44
57
  /** One running recognition session: the browser-facing half of the shared contract. */
45
58
  export interface TranscriptionSession {
@@ -0,0 +1,91 @@
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
+ /** Why a turn ended without an error. */
13
+ export type TurnEndReason = "completed" | "cancelled" | "barge-in" | "superseded";
14
+ /** One turn's timings in milliseconds from its start. Never text or audio. */
15
+ export interface TurnMetrics {
16
+ readonly firstPartialMs: number | null;
17
+ readonly transcriptMs: number | null;
18
+ /** When the answer's first utterance started playing. */
19
+ readonly firstAudioMs: number | null;
20
+ readonly speechFinishedMs: number | null;
21
+ }
22
+ export type TurnEvent =
23
+ /** The microphone is open. */
24
+ {
25
+ readonly type: "listening";
26
+ readonly turn?: string;
27
+ } | {
28
+ readonly type: "partial";
29
+ readonly partial: PartialTranscript;
30
+ readonly turn?: string;
31
+ }
32
+ /** The transcript is final; the host produces the answer next. */
33
+ | {
34
+ readonly type: "transcript";
35
+ readonly text: string;
36
+ readonly turn?: string;
37
+ }
38
+ /** Waiting on the host's answer (after the transcript, or between streamed chunks). */
39
+ | {
40
+ readonly type: "responding";
41
+ readonly turn?: string;
42
+ }
43
+ /** The answer is playing. `text` is the chunk the browser manager was given. */
44
+ | {
45
+ readonly type: "speaking";
46
+ readonly text?: string;
47
+ readonly turn?: string;
48
+ } | {
49
+ readonly type: "speech-started";
50
+ readonly utterance?: string;
51
+ readonly turn?: string;
52
+ } | {
53
+ readonly type: "speech-finished";
54
+ readonly utterance?: string;
55
+ readonly turn?: string;
56
+ } | {
57
+ readonly type: "speech-cancelled";
58
+ readonly utterance?: string;
59
+ readonly turn?: string;
60
+ }
61
+ /** The person talked over the answer; it was stopped (a request cancel, not a mute). */
62
+ | {
63
+ readonly type: "barge-in";
64
+ readonly turn?: string;
65
+ }
66
+ /** The answer was stopped from outside the turn (a system interruption); the turn is open. */
67
+ | {
68
+ readonly type: "idle";
69
+ readonly turn?: string;
70
+ } | {
71
+ readonly type: "metrics";
72
+ readonly metrics: TurnMetrics;
73
+ readonly turn?: string;
74
+ }
75
+ /** Terminal: the turn is over. */
76
+ | {
77
+ readonly type: "ended";
78
+ readonly reason: TurnEndReason;
79
+ readonly turn?: string;
80
+ }
81
+ /** Terminal: the turn failed. */
82
+ | {
83
+ readonly type: "failed";
84
+ readonly error: VoiceError;
85
+ readonly turn?: string;
86
+ }
87
+ /** Terminal for the whole conversation (the browser manager's `cancel()`). */
88
+ | {
89
+ readonly type: "cancelled";
90
+ readonly turn?: string;
91
+ };
@@ -7,8 +7,13 @@
7
7
  * parses these lines itself; `@adea-ai/voice/desktop` does, and maps them to the session contract.
8
8
  */
9
9
  import { type VoiceErrorCode } from "./errors";
10
+ import type { TurnEndReason } from "./turns";
10
11
  /** The wire major this SDK speaks. A helper on another major is refused, never guessed at. */
11
12
  export declare const WIRE_VERSION = 1;
13
+ /** The wire minor that added conversation turns (`turn-*`); older helpers cannot run them. */
14
+ export declare const TURN_WIRE_MINOR = 2;
15
+ /** The wire minor that added model removal (`release-assets` → `asset-released`). */
16
+ export declare const RELEASE_ASSETS_WIRE_MINOR = 3;
12
17
  /** The provider-contract major this SDK speaks. */
13
18
  export declare const CONTRACT_MAJOR = 1;
14
19
  /** One line may not exceed this many bytes (the helpers enforce the same bound on input). */
@@ -20,6 +25,8 @@ export interface VersionEvent {
20
25
  readonly contract: string;
21
26
  readonly contractMajor: number;
22
27
  readonly helper?: string;
28
+ /** The voice release the helper was built from (e.g. `0.2.0`); a lock pins it. */
29
+ readonly release?: string;
23
30
  readonly id?: string;
24
31
  }
25
32
  export type CombinedPermission = "granted" | "denied" | "prompt" | "unavailable";
@@ -142,9 +149,45 @@ export interface AssetInstalledEvent {
142
149
  readonly locale: string;
143
150
  readonly id?: string;
144
151
  }
152
+ /**
153
+ * `release-assets`'s answer: this app's reservation of the locale's model is released (the system
154
+ * may then reclaim the model) and `status` is what the system reports afterwards. A model shared
155
+ * with system dictation can still read `installed`.
156
+ */
157
+ export interface AssetReleasedEvent {
158
+ readonly event: "asset-released";
159
+ /** The locale as requested, e.g. `es-419`. */
160
+ readonly locale: string;
161
+ /** The model's own locale, the one the reservation was held for, e.g. `es_MX`. */
162
+ readonly modelLocale: string;
163
+ /** False when this app held no reservation for the model (nothing to release). */
164
+ readonly released: boolean;
165
+ readonly status: AssetStatus;
166
+ readonly canInstall: boolean;
167
+ readonly id?: string;
168
+ }
169
+ /** The system voice speaking an utterance, as `speech-started` names it. */
170
+ export interface SpeechVoiceIdentity {
171
+ /** The system voice identifier (the `voice` a `speak` can pin). */
172
+ readonly id: string;
173
+ readonly name: string;
174
+ /** The voice's own locale, e.g. `es-MX` when `es-419` was requested. */
175
+ readonly language: string;
176
+ /**
177
+ * The same value as `language`, under the name the voice list items use. Additive: helpers
178
+ * from 0.3.0 and earlier send only `language`, and the SDK fills this in from it.
179
+ */
180
+ readonly locale: string;
181
+ readonly quality: "default" | "enhanced" | "premium" | "unknown";
182
+ }
145
183
  export interface SpeechLifecycleEvent {
146
184
  readonly event: "speech-started" | "speech-finished" | "speech-cancelled";
147
185
  readonly id: string;
186
+ /**
187
+ * On `speech-started` only, when the `speak` named a voice or a locale: the voice that
188
+ * resolved. Additive within wire 1; older helpers omit it.
189
+ */
190
+ readonly voice?: SpeechVoiceIdentity;
148
191
  }
149
192
  export interface SpeechErrorEvent {
150
193
  readonly event: "speech-error";
@@ -160,6 +203,54 @@ export interface SpeechInterruptedEvent {
160
203
  readonly event: "speech-interrupted" | "speech-route-changed";
161
204
  readonly reason?: string;
162
205
  }
206
+ export type TurnWireState = "idle" | "listening" | "responding" | "speaking" | "interrupted" | "ended";
207
+ export interface TurnStateEvent {
208
+ readonly event: "turn-state";
209
+ readonly id: string;
210
+ readonly state: TurnWireState;
211
+ /** Set on `ended`. */
212
+ readonly reason?: TurnEndReason;
213
+ }
214
+ export interface TurnPartialEvent {
215
+ readonly event: "turn-partial";
216
+ readonly id: string;
217
+ readonly text?: string;
218
+ readonly finalizedText: string;
219
+ readonly volatileText: string;
220
+ readonly sequence: number;
221
+ }
222
+ export interface TurnTranscriptEvent {
223
+ readonly event: "turn-transcript";
224
+ readonly id: string;
225
+ readonly text: string;
226
+ }
227
+ export interface TurnBargeInEvent {
228
+ readonly event: "turn-barge-in";
229
+ readonly id: string;
230
+ }
231
+ export interface TurnSpeechEvent {
232
+ readonly event: "turn-speech-started" | "turn-speech-finished" | "turn-speech-cancelled";
233
+ readonly id: string;
234
+ readonly utterance: string;
235
+ }
236
+ /** Timings only, in milliseconds from `turn-start`; never text or audio. */
237
+ export interface TurnMetricsEvent {
238
+ readonly event: "turn-metrics";
239
+ readonly id: string;
240
+ readonly firstPartialMs: number | null;
241
+ readonly transcriptMs: number | null;
242
+ readonly firstAudioMs: number | null;
243
+ readonly speechFinishedMs: number | null;
244
+ }
245
+ export interface TurnErrorEvent {
246
+ readonly event: "turn-error";
247
+ readonly id: string;
248
+ readonly code: VoiceErrorCode;
249
+ readonly message?: string;
250
+ }
251
+ export type TurnWireEvent = TurnStateEvent | TurnPartialEvent | TurnTranscriptEvent | TurnBargeInEvent | TurnSpeechEvent | TurnMetricsEvent | TurnErrorEvent;
252
+ /** Whether an event is a turn's one terminal (`turn-state` `ended` or `turn-error`). */
253
+ export declare function isTurnTerminal(event: WireEvent): event is TurnStateEvent | TurnErrorEvent;
163
254
  /** A second line the local-model helpers print after `version`. */
164
255
  export interface HelperIdentityEvent {
165
256
  readonly event: "helper";
@@ -167,7 +258,7 @@ export interface HelperIdentityEvent {
167
258
  readonly engine: string;
168
259
  readonly library?: string;
169
260
  }
170
- export type WireEvent = VersionEvent | HelperIdentityEvent | PermissionEvent | AppleStatusEvent | TranscribeStatusEvent | SynthesisStatusEvent | LocaleEvent | ListDoneEvent | VoiceEvent | ListeningEvent | PartialEvent | FinalEvent | ErrorEvent | CancelledEvent | IdleEvent | AssetProgressEvent | AssetInstalledEvent | SpeechLifecycleEvent | SpeechErrorEvent | SpeechStateEvent | SpeechInterruptedEvent;
261
+ export type WireEvent = VersionEvent | HelperIdentityEvent | PermissionEvent | AppleStatusEvent | TranscribeStatusEvent | SynthesisStatusEvent | LocaleEvent | ListDoneEvent | VoiceEvent | ListeningEvent | PartialEvent | FinalEvent | ErrorEvent | CancelledEvent | IdleEvent | AssetProgressEvent | AssetInstalledEvent | AssetReleasedEvent | SpeechLifecycleEvent | SpeechErrorEvent | SpeechStateEvent | SpeechInterruptedEvent | TurnWireEvent;
171
262
  /** A command line. `cmd` is the helpers' key; `command` is sent too for the transcribe helper. */
172
263
  export interface WireCommand {
173
264
  readonly cmd: string;
@@ -0,0 +1,86 @@
1
+ import type { TurnEvent } from "../contract/turns";
2
+ import { type HelperConnection } from "./helper-process";
3
+ export interface ConversationRespondOptions {
4
+ /** Whether this is the answer's last chunk. Default true: one call is one whole answer. */
5
+ readonly final?: boolean;
6
+ }
7
+ /** A running conversation. */
8
+ export interface DesktopConversation {
9
+ readonly provider: string;
10
+ readonly locale: string;
11
+ /**
12
+ * Every turn's events in order, each tagged with `turn`. Finishes after the conversation's
13
+ * last terminal: a `failed` turn, `cancelled` (from `cancel()` or the helper), or the `ended`
14
+ * of the last turn after `end()`. Can be read once.
15
+ */
16
+ events(): AsyncIterable<TurnEvent>;
17
+ /**
18
+ * Speaks (part of) the current turn's answer. Chunks queue without gaps, so a streaming model's
19
+ * text can be spoken as it arrives; send `{ final: true }` (an empty text is fine) to finish
20
+ * the answer. Responding while the person is still talking closes the microphone.
21
+ */
22
+ respond(textChunk: string, options?: ConversationRespondOptions): Promise<void>;
23
+ /** Starts the next turn now; while the answer plays this is a barge-in. */
24
+ listen(): Promise<void>;
25
+ /** Push-to-talk release: stop needing audio; the transcript of what was heard follows. */
26
+ stopListening(): Promise<void>;
27
+ /**
28
+ * Finishes after the current exchange: no further turns start. A turn waiting for an answer
29
+ * closes now; one that is listening finalizes first (then `end()` again, or `respond()`).
30
+ */
31
+ end(): Promise<void>;
32
+ /** Stops everything now: speech, microphone, further turns. Ends with `cancelled`. Idempotent. */
33
+ cancel(): Promise<void>;
34
+ }
35
+ export interface ConversationOptions {
36
+ readonly connection: HelperConnection;
37
+ readonly provider: string;
38
+ readonly locale: string;
39
+ readonly engine: "analyzer" | "legacy" | undefined;
40
+ readonly bargeIn: boolean;
41
+ readonly halfDuplex: boolean;
42
+ readonly continuous: boolean;
43
+ /** Voice fields sent with every `turn-respond` (already on the helper's scale). */
44
+ readonly voice: {
45
+ readonly voice?: string;
46
+ readonly locale?: string;
47
+ readonly rate?: number;
48
+ };
49
+ /** After `cancel()`, how long the helper gets to report the terminal before it is restarted. */
50
+ readonly terminalGraceMs: number;
51
+ readonly onStuck: () => void;
52
+ readonly onFinished: () => void;
53
+ }
54
+ export declare class Conversation implements DesktopConversation {
55
+ private readonly options;
56
+ readonly provider: string;
57
+ readonly locale: string;
58
+ private current;
59
+ private readonly queue;
60
+ private waiter;
61
+ private consumed;
62
+ private finished;
63
+ private ending;
64
+ private cancelling;
65
+ private graceTimer;
66
+ constructor(options: ConversationOptions);
67
+ get isFinished(): boolean;
68
+ /** Starts the first turn; resolves once the microphone is open, rejects if the turn failed. */
69
+ begin(): Promise<void>;
70
+ events(): AsyncIterable<TurnEvent>;
71
+ respond(textChunk: string, options?: ConversationRespondOptions): Promise<void>;
72
+ listen(): Promise<void>;
73
+ stopListening(): Promise<void>;
74
+ end(): Promise<void>;
75
+ cancel(): Promise<void>;
76
+ private startTurn;
77
+ /** Maps one helper line of this turn to the shared vocabulary. */
78
+ private forward;
79
+ private closeTurn;
80
+ /** What the conversation does once a turn has ended. */
81
+ private afterTerminal;
82
+ /** How each turn ended (`failed` for an error), until the conversation has acted on it. */
83
+ private readonly reasons;
84
+ private finish;
85
+ private push;
86
+ }