@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,226 @@
1
+ /**
2
+ * Browser dictation over the Web Speech API, with an explicit local/network policy (issues #21
3
+ * and #37).
4
+ *
5
+ * The browser's recognizer is not automatically offline: Chrome's service-based recognition sends
6
+ * audio to Google, and Safari/Chrome differ per OS version. This module therefore exposes **two
7
+ * providers over one implementation**:
8
+ *
9
+ * - `web.speech-recognition-local` (`execution: "onDevice"`): only available when the browser can
10
+ * run recognition on-device *and* confirms a model for the locale. It is the only entry in the
11
+ * routing chain, so routing never silently reaches the network.
12
+ * - `web.speech-recognition-service` (`execution: "network"`): the host must select it explicitly,
13
+ * with a privacy notice and `allowNetwork: true`. Routing refuses it (`networkRequired`).
14
+ *
15
+ * The session keeps the platform-neutral event contract from #19: `partial` snapshots with
16
+ * `finalizedText`/`volatileText`/`sequence`, exactly one terminal `final`/`failed`/`cancelled`, and
17
+ * deadlines that end a stuck session instead of hanging it.
18
+ */
19
+ import { type VoiceProviderAvailability, type VoiceProviderDescriptor } from "../../contract/contract";
20
+ export interface RecognitionAlternative {
21
+ readonly transcript: string;
22
+ readonly confidence?: number;
23
+ }
24
+ export interface RecognitionResult {
25
+ readonly isFinal: boolean;
26
+ readonly length: number;
27
+ readonly [index: number]: RecognitionAlternative;
28
+ }
29
+ export interface RecognitionResultList {
30
+ readonly length: number;
31
+ readonly [index: number]: RecognitionResult;
32
+ }
33
+ export interface SpeechRecognitionEventLike {
34
+ readonly resultIndex: number;
35
+ readonly results: RecognitionResultList;
36
+ }
37
+ export interface SpeechRecognitionErrorEventLike {
38
+ readonly error: string;
39
+ readonly message?: string;
40
+ }
41
+ /** The subset of `SpeechRecognition` this adapter uses. */
42
+ export interface SpeechRecognitionLike {
43
+ lang: string;
44
+ continuous: boolean;
45
+ interimResults: boolean;
46
+ maxAlternatives: number;
47
+ /** Chrome's on-device flag; ignored by browsers that do not implement it. */
48
+ processLocally?: boolean;
49
+ onstart: (() => void) | null;
50
+ onresult: ((event: SpeechRecognitionEventLike) => void) | null;
51
+ onerror: ((event: SpeechRecognitionErrorEventLike) => void) | null;
52
+ onend: (() => void) | null;
53
+ /** The browser heard speech begin. Not every engine fires it; the first words stand in. */
54
+ onspeechstart?: (() => void) | null;
55
+ /** Chrome 137+ accepts an audio track to recognise from (a chosen microphone). */
56
+ start(audioTrack?: MediaStreamTrackLike): void;
57
+ stop(): void;
58
+ abort(): void;
59
+ }
60
+ export type RecognitionModelState = "available" | "downloadable" | "downloading" | "unavailable";
61
+ /** Chrome's on-device lifecycle methods, which live on the constructor, not the instance. */
62
+ export interface SpeechRecognitionConstructor {
63
+ new (): SpeechRecognitionLike;
64
+ available?(options: {
65
+ langs: string[];
66
+ processLocally?: boolean;
67
+ }): Promise<RecognitionModelState>;
68
+ install?(options: {
69
+ langs: string[];
70
+ }): Promise<boolean>;
71
+ }
72
+ /** The subset of `PermissionStatus` the microphone pre-check uses. */
73
+ export interface PermissionStatusLike {
74
+ readonly state: "granted" | "denied" | "prompt" | (string & {});
75
+ onchange?: (() => void) | null;
76
+ addEventListener?(type: "change", listener: () => void): void;
77
+ removeEventListener?(type: "change", listener: () => void): void;
78
+ }
79
+ /** The subset of `MediaStreamTrack` a chosen microphone needs. */
80
+ export interface MediaStreamTrackLike {
81
+ readonly kind?: string;
82
+ readonly readyState?: string;
83
+ stop(): void;
84
+ }
85
+ export interface MediaStreamLike {
86
+ getAudioTracks(): MediaStreamTrackLike[];
87
+ getTracks?(): MediaStreamTrackLike[];
88
+ }
89
+ /** The parts of `navigator` dictation reads: permissions, connectivity and microphones. */
90
+ export interface RecognitionNavigatorLike {
91
+ readonly onLine?: boolean;
92
+ readonly permissions?: {
93
+ query(descriptor: {
94
+ name: string;
95
+ }): Promise<PermissionStatusLike>;
96
+ };
97
+ readonly mediaDevices?: {
98
+ getUserMedia(constraints: {
99
+ audio: boolean | {
100
+ deviceId: {
101
+ exact: string;
102
+ };
103
+ };
104
+ }): Promise<MediaStreamLike>;
105
+ };
106
+ }
107
+ /** `window`/`document` as event targets (`offline`, `pagehide`, `visibilitychange`). */
108
+ export interface EventTargetLike {
109
+ addEventListener(type: string, listener: () => void): void;
110
+ removeEventListener(type: string, listener: () => void): void;
111
+ }
112
+ export interface RecognitionDocumentLike extends EventTargetLike {
113
+ readonly visibilityState?: string;
114
+ }
115
+ export interface SpeechRecognitionEnvironment {
116
+ /** The constructor, or undefined where the browser has no Web Speech API. */
117
+ readonly SpeechRecognition?: SpeechRecognitionConstructor;
118
+ /** Safari's prefixed constructor. Present without the unprefixed name on Safari and older WebKit. */
119
+ readonly webkitSpeechRecognition?: SpeechRecognitionConstructor;
120
+ readonly now?: () => number;
121
+ readonly sleep?: (milliseconds: number) => Promise<void>;
122
+ /** Permissions, `onLine` and `mediaDevices`. Default: the global `navigator`. */
123
+ readonly navigator?: RecognitionNavigatorLike;
124
+ /** For `visibilitychange`. Default: the global `document`. */
125
+ readonly document?: RecognitionDocumentLike;
126
+ /** `window`'s listeners, for `offline` and `pagehide`. Default: the global ones. */
127
+ readonly addEventListener?: (type: string, listener: () => void) => void;
128
+ readonly removeEventListener?: (type: string, listener: () => void) => void;
129
+ /**
130
+ * Whether `start(audioTrack)` is honoured. Browsers that predate it ignore the argument and record
131
+ * the default microphone, so a chosen device would be silently dropped. Default: detected as
132
+ * Chrome's on-device recognizer (`processLocally` on the instance), which shipped after it.
133
+ */
134
+ readonly recognitionAcceptsAudioTrack?: boolean;
135
+ }
136
+ /** Progress of a browser model install. The browser reports states, not bytes. */
137
+ export interface ModelInstallProgress {
138
+ readonly locale: string;
139
+ readonly phase: "started" | "downloading" | "installed" | "failed" | "cancelled";
140
+ }
141
+ export interface InstallModelOptions {
142
+ /** The person agreed to the download (for example `allowsModelDownload(settings)`). */
143
+ readonly allowDownload: boolean;
144
+ /** Called on each phase change; `downloading` is observed by polling the browser's state. */
145
+ readonly onProgress?: (progress: ModelInstallProgress) => void;
146
+ /**
147
+ * Stops waiting and rejects with `cancelled`. The browser has no cancel for its own download, so
148
+ * it may finish in the background; the SDK only stops reporting and never claims it installed.
149
+ */
150
+ readonly signal?: AbortSignal;
151
+ /** How often `downloading` is polled. Default 500 ms. */
152
+ readonly pollIntervalMs?: number;
153
+ /** A settings object; `privacy.offlineOnly` refuses the download whatever `allowDownload` says. */
154
+ readonly settings?: {
155
+ readonly privacy: {
156
+ readonly offlineOnly: boolean;
157
+ };
158
+ };
159
+ }
160
+ /** What dictation does when the page is hidden (`visibilitychange` to hidden, or `pagehide`). */
161
+ export type HiddenPagePolicy = "finalize" | "cancel" | "ignore";
162
+ /** Browser-specific session options on top of the shared contract. All optional. */
163
+ export interface WebTranscriptionSessionOptions extends TranscriptionSessionOptions {
164
+ /**
165
+ * A chosen microphone: a `deviceId` the SDK opens (and always stops on every terminal path), or a
166
+ * `track` the host owns (stopped at the end only with `stopOnEnd: true`). Needs a browser that
167
+ * honours `start(audioTrack)`, otherwise the session is refused instead of using another mic.
168
+ */
169
+ readonly microphone?: {
170
+ readonly deviceId: string;
171
+ } | {
172
+ readonly track: MediaStreamTrackLike;
173
+ readonly stopOnEnd?: boolean;
174
+ };
175
+ /**
176
+ * What to do when the browser ends recognition on its own before `end()` (Chrome on Android
177
+ * ignores `continuous` and stops after one utterance): `finalize` (default) reports the words so
178
+ * far as a clean `final`; `restart` starts the recognizer again inside the same session, so the
179
+ * person can keep talking until endpointing, the hard cap or `end()` finishes it.
180
+ */
181
+ readonly onEarlyEnd?: "finalize" | "restart";
182
+ /** At most this many restarts per session with `onEarlyEnd: "restart"`. Default 50. */
183
+ readonly maxRestarts?: number;
184
+ /** Default `finalize`: a hidden page ends the session with one terminal event. */
185
+ readonly whenHidden?: HiddenPagePolicy;
186
+ /** A settings object; `privacy.offlineOnly` refuses the service recognizer outright. */
187
+ readonly settings?: {
188
+ readonly privacy: {
189
+ readonly offlineOnly: boolean;
190
+ };
191
+ };
192
+ }
193
+ /** The recognizer constructor this browser exposes, unprefixed first. */
194
+ export declare function recognitionConstructor(environment: SpeechRecognitionEnvironment): SpeechRecognitionConstructor | undefined;
195
+ export { DEFAULT_ENDPOINTING, type EndpointingOptions, type RecognitionExecution, type PartialTranscript, type SessionEvent, type TranscriptionProvider, type TranscriptionSession, type TranscriptionSessionOptions, } from "../../contract/session";
196
+ import { type TranscriptionProvider, type TranscriptionSession, type TranscriptionSessionOptions } from "../../contract/session";
197
+ export declare const LOCAL_RECOGNITION_ID = "web.speech-recognition-local";
198
+ export declare const SERVICE_RECOGNITION_ID = "web.speech-recognition-service";
199
+ export declare function browserRecognitionLocal(environment?: SpeechRecognitionEnvironment): BrowserRecognitionProvider;
200
+ export declare function browserRecognitionService(environment?: SpeechRecognitionEnvironment): BrowserRecognitionProvider;
201
+ /**
202
+ * The recognizer as a provider. `mode` decides which of the two descriptors it carries; the
203
+ * implementation is the same and the policy difference is the point.
204
+ */
205
+ export declare class BrowserRecognitionProvider implements TranscriptionProvider {
206
+ readonly descriptor: VoiceProviderDescriptor;
207
+ private readonly environment;
208
+ private readonly mode;
209
+ constructor(mode: "local" | "service", environment: SpeechRecognitionEnvironment);
210
+ /** Probes the browser. Prompts for nothing, sends nothing. */
211
+ availability(locale: string): Promise<VoiceProviderAvailability>;
212
+ /**
213
+ * Installs the on-device model where the browser exposes an install path (#37 consent step).
214
+ * Downloading is never implied: the host passes `allowDownload: true` only after the person
215
+ * agreed to it (for example `settings.models.allowDownload`), otherwise this refuses. Resolves
216
+ * with the browser's boolean; `onProgress` and `signal` are optional.
217
+ */
218
+ installModel(locale: string, options: InstallModelOptions): Promise<boolean>;
219
+ /** Reports `downloading` once the browser says so; the browser exposes no byte counts. */
220
+ private pollInstall;
221
+ createSession(options: WebTranscriptionSessionOptions): Promise<TranscriptionSession>;
222
+ private get navigator();
223
+ private get window();
224
+ /** Opens (or adopts) the chosen microphone. Nothing is opened when no device was chosen. */
225
+ private openMicrophone;
226
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Region-aware locale matching for platform voices (#36).
3
+ *
4
+ * Matching only the language subtag picks `es-ES` for an `es-419` request whenever the browser lists
5
+ * Spain first, which is what the 2026-11-19 acceptance run recorded in Firefox and Safari. The rule
6
+ * here is: **exact tag > same region group > same language**, with an explicit preference order
7
+ * inside a group. For Latin-American Spanish that order is `es-419`, `es-MX`, `es-US`, `es-AR`, then
8
+ * the other Latin-American regions, and `es-ES` only last.
9
+ *
10
+ * Pure functions over tags: no browser, no voices list.
11
+ */
12
+ import type { VoiceLocaleMatch } from "../../contract/contract";
13
+ /** A parsed BCP-47 tag: language, optional script, optional region (upper case or 3 digits). */
14
+ export interface ParsedLocale {
15
+ readonly language: string;
16
+ readonly script?: string;
17
+ readonly region?: string;
18
+ }
19
+ export declare function parseLocale(tag: string): ParsedLocale;
20
+ /**
21
+ * Region groups per language, each in preference order. A region's group is the first group that
22
+ * lists it; the first group of a language is not privileged. Chinese groups by script as well, so
23
+ * `zh-Hant` finds `zh-TW` and never `zh-CN`.
24
+ */
25
+ export declare const REGION_GROUPS: Readonly<Record<string, readonly (readonly string[])[]>>;
26
+ export interface LocaleMatch {
27
+ readonly match: VoiceLocaleMatch;
28
+ /** Lower is better. Stable across calls, so it can sort a list of voices. */
29
+ readonly rank: number;
30
+ }
31
+ /**
32
+ * How well a voice's language tag serves a requested locale, or undefined for another language.
33
+ *
34
+ * - exact tag (case and `_`/`-` insensitive) is `exact`, rank 0;
35
+ * - a voice in the requested region's group is `region`, ranked by the group's preference order;
36
+ * - a request without a region accepts every voice of the language as `region`;
37
+ * - anything else of the same language is `language`: a region-less voice (`es`) before an
38
+ * off-region one (`es-ES` for `es-419`).
39
+ */
40
+ export declare function matchLocale(requested: string, voiceLang: string): LocaleMatch | undefined;
@@ -0,0 +1,139 @@
1
+ /**
2
+ * Phonon 31M as the browser's local English voice (issue #27).
3
+ *
4
+ * Three rules shape this adapter:
5
+ *
6
+ * 1. **Nothing downloads by itself.** `availability` is `modelNotInstalled` until the host has the
7
+ * person's consent and calls `load()`; routing reports `modelDownloadDisabled` unless the host
8
+ * opted into the install, so a page that never uses voice never fetches a model.
9
+ * 2. **Only the cleared family.** Phonon 31M English is Apache-2.0 and is the only family this
10
+ * adapter accepts. Phonon 40M (Spanish/multilingual) is CC BY-NC 4.0 and reports
11
+ * `licenseNotAccepted` rather than loading; the ES-419 path belongs to platform voices (#36).
12
+ * 3. **Cancellation is a request cancel, not a mute.** The engine's `AbortSignal` stops generation
13
+ * in the worker; the player flushes what this utterance scheduled (and only that). Both happen in
14
+ * `cancel()`, and `done` settles when playback drained, not when generation finished.
15
+ *
16
+ * The runtime, the player and the clock are injected so the policies and the pump are testable
17
+ * without a browser.
18
+ */
19
+ import type { LoadProgress, ModelSpec } from "phonon-tts";
20
+ import { type VoiceProvider, type VoiceProviderAvailability, type VoiceProviderDescriptor } from "../../contract/contract";
21
+ import { type AudioContextFactory } from "./player";
22
+ export type PhononFamily = "phonon-31m-en" | "phonon-40m";
23
+ /** Where the checkpoint comes from. Both forms are explicit; there is no implicit default. */
24
+ export type PhononModelSource = {
25
+ readonly kind: "pinned";
26
+ } | {
27
+ readonly kind: "urls";
28
+ readonly spec: ModelSpec;
29
+ };
30
+ export interface PhononSpeechStats {
31
+ readonly frames?: number;
32
+ readonly samples?: number;
33
+ readonly firstAudioMs?: number | null;
34
+ readonly totalMs?: number;
35
+ readonly cancelled: boolean;
36
+ }
37
+ export interface PhononSpeechStream extends AsyncIterable<Float32Array> {
38
+ readonly sampleRate: number;
39
+ readonly done: Promise<PhononSpeechStats>;
40
+ cancel(): void;
41
+ }
42
+ /** The subset of `phonon-tts`'s `PhononTTS` this adapter uses. */
43
+ export interface PhononEngine {
44
+ readonly sampleRate: number;
45
+ readonly voices: string[];
46
+ readonly languages: string[];
47
+ readonly device?: string;
48
+ readonly threads?: number;
49
+ stream(text: string, options?: {
50
+ voice?: string;
51
+ temperature?: number;
52
+ seed?: number | bigint;
53
+ signal?: AbortSignal;
54
+ }): PhononSpeechStream;
55
+ dispose(): void;
56
+ }
57
+ export interface PhononLoadRequest {
58
+ readonly lang: string;
59
+ readonly model?: ModelSpec | string;
60
+ readonly quant?: "q8" | "f32";
61
+ readonly cache?: boolean;
62
+ readonly onProgress?: (progress: LoadProgress) => void;
63
+ readonly device?: "cpu" | "auto" | "webgpu";
64
+ readonly threads?: number | "auto";
65
+ }
66
+ export interface PhononRuntime {
67
+ load(request: PhononLoadRequest): Promise<PhononEngine>;
68
+ }
69
+ /** The shipped runtime: `phonon-tts@0.7.1`, loaded on demand so nothing loads it eagerly. */
70
+ export declare const defaultPhononRuntime: PhononRuntime;
71
+ /** Deletes every model file the package cached. Exposed so settings can offer it. */
72
+ export declare function clearPhononCache(): Promise<boolean>;
73
+ export interface PhononProviderOptions {
74
+ /** Only `en` locales are served. Default `en`. */
75
+ readonly locale?: string;
76
+ /** Which family this build carries. Default `phonon-31m-en`. */
77
+ readonly family?: PhononFamily;
78
+ /** Required for `family: "phonon-31m-en"`: pinned Hub revision or explicit asset URLs. */
79
+ readonly model?: PhononModelSource;
80
+ readonly runtime?: PhononRuntime;
81
+ readonly device?: "cpu" | "auto" | "webgpu";
82
+ readonly threads?: number | "auto";
83
+ readonly cache?: boolean;
84
+ /** WebAssembly SIMD probe; injected in tests. */
85
+ readonly supportsSimd?: () => boolean;
86
+ readonly audioContextFactory?: AudioContextFactory;
87
+ readonly now?: () => number;
88
+ }
89
+ export interface SpeakOptions {
90
+ readonly voice?: string;
91
+ readonly temperature?: number;
92
+ readonly seed?: number | bigint;
93
+ /** Called with the first scheduled PCM chunk's latency, in milliseconds. */
94
+ readonly onFirstAudio?: (milliseconds: number) => void;
95
+ readonly onChunk?: (samples: number) => void;
96
+ }
97
+ export interface SpeechHandle {
98
+ /** Resolves when playback drained or cancellation finished; rejects with a `VoiceError`. */
99
+ readonly done: Promise<PhononSpeechStats>;
100
+ /** Request cancel: stops the worker's generation and flushes playback. Idempotent. */
101
+ cancel(): void;
102
+ }
103
+ export declare const PHONON_PROVIDER_ID = "web.phonon";
104
+ export declare const PHONON_EN_FAMILY = "phonon-31m-en";
105
+ export declare class PhononProvider implements VoiceProvider {
106
+ readonly descriptor: VoiceProviderDescriptor;
107
+ private readonly options;
108
+ private engine;
109
+ private player;
110
+ private loading;
111
+ /** Callers still waiting on `loading` (not aborted). Zero when it lands means nobody wants it. */
112
+ private loadWaiters;
113
+ private readonly progressListeners;
114
+ constructor(options?: PhononProviderOptions);
115
+ /** Whether the checkpoint is loaded in this page. */
116
+ get isLoaded(): boolean;
117
+ /** Voices the loaded checkpoint offers. Empty before `load()`. */
118
+ get voices(): readonly string[];
119
+ availability(locale: string): Promise<VoiceProviderAvailability>;
120
+ /**
121
+ * Downloads the checkpoint (explicitly, with progress) and loads it in a worker. Idempotent:
122
+ * concurrent callers share one download, and each gets its own progress callbacks.
123
+ *
124
+ * `signal` is per caller: aborting it rejects *that* caller with `cancelled` right away and
125
+ * detaches its progress listener, without affecting other callers. `phonon-tts@0.7.1`'s
126
+ * `PhononTTS.load` takes no `AbortSignal`, so the download itself cannot be interrupted; when it
127
+ * lands and every caller has aborted, the engine is disposed instead of kept.
128
+ */
129
+ load(options?: {
130
+ onProgress?: (progress: LoadProgress) => void;
131
+ signal?: AbortSignal;
132
+ }): Promise<PhononEngine>;
133
+ private startLoading;
134
+ /** Speaks one request: streams PCM into the player, cancellable at any point. */
135
+ speak(text: string, options?: SpeakOptions): SpeechHandle;
136
+ /** Stops generation and playback and frees the worker. */
137
+ dispose(): void;
138
+ private playerFor;
139
+ }
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Scheduled PCM playback for streaming synthesis.
3
+ *
4
+ * The engine yields mono float chunks in real time; this player schedules each one on the
5
+ * AudioContext clock with a small lead so chunk boundaries do not click, and it owns the only
6
+ * mutable playback state: stop (barge-in) flushes every scheduled source, suspend/resume follow
7
+ * the platform's audio focus rules, and dispose closes the context so nothing outlives the
8
+ * component.
9
+ *
10
+ * Browser globals are injected (`AudioContextFactory`), so the scheduling logic is testable.
11
+ */
12
+ export interface AudioBufferLike {
13
+ readonly duration: number;
14
+ readonly numberOfChannels?: number;
15
+ readonly length?: number;
16
+ getChannelData?(channel: number): Float32Array;
17
+ }
18
+ export interface AudioBufferSourceLike {
19
+ buffer: unknown;
20
+ onended: (() => void) | null;
21
+ connect(destination: unknown): void;
22
+ disconnect?(destination?: unknown): void;
23
+ start(when?: number): void;
24
+ stop(when?: number): void;
25
+ }
26
+ export interface AudioContextLike {
27
+ readonly currentTime: number;
28
+ readonly destination: unknown;
29
+ readonly state?: string;
30
+ createBuffer(channels: number, length: number, sampleRate: number): AudioBufferLike;
31
+ createBufferSource(): AudioBufferSourceLike;
32
+ resume?(): Promise<void>;
33
+ suspend?(): Promise<void>;
34
+ close?(): Promise<void>;
35
+ }
36
+ export interface AudioContextFactory {
37
+ create(options: {
38
+ sampleRate: number;
39
+ }): AudioContextLike;
40
+ }
41
+ export interface StreamingPcmPlayerOptions {
42
+ readonly sampleRate: number;
43
+ readonly factory?: AudioContextFactory;
44
+ /** Scheduling lead ahead of the context clock, in seconds. Default 0.05. */
45
+ readonly leadSeconds?: number;
46
+ /** Called when the first chunk of the current utterance is scheduled. */
47
+ readonly onFirstAudio?: (atContextTime: number) => void;
48
+ /** Called when every scheduled chunk has played. */
49
+ readonly onDrained?: () => void;
50
+ }
51
+ export declare const defaultAudioContextFactory: AudioContextFactory;
52
+ /**
53
+ * One utterance's slice of the player's schedule: its own sources, its own stop, and a `drained`
54
+ * promise that settles when its last scheduled chunk has played (or it was stopped). Stopping one
55
+ * utterance leaves the others scheduled.
56
+ */
57
+ export declare class PlaybackUtterance {
58
+ private readonly player;
59
+ readonly sources: Set<AudioBufferSourceLike>;
60
+ private sealed;
61
+ private stoppedFlag;
62
+ private settled;
63
+ private resolveDrained;
64
+ /** Resolves `true` when everything scheduled played, `false` when the utterance was stopped. */
65
+ readonly drained: Promise<boolean>;
66
+ constructor(player: StreamingPcmPlayer);
67
+ /** Whether `stop()` (or the player's stop/dispose) ended this utterance. */
68
+ get stopped(): boolean;
69
+ /** Schedules one chunk of this utterance; null after `finish()`/`stop()` or when disposed. */
70
+ enqueue(pcm: Float32Array): number | null;
71
+ /** No more chunks will come: `drained` resolves once the scheduled ones have played. */
72
+ finish(): Promise<boolean>;
73
+ /** Stops and discards only this utterance's scheduled audio. Idempotent. */
74
+ stop(): void;
75
+ /** @internal called by the player when one of this utterance's sources ended. */
76
+ ended(source: AudioBufferSourceLike): void;
77
+ private check;
78
+ private settle;
79
+ }
80
+ export declare class StreamingPcmPlayer {
81
+ private readonly context;
82
+ private readonly sampleRate;
83
+ private readonly leadSeconds;
84
+ private readonly onFirstAudio;
85
+ private readonly onDrained;
86
+ private sources;
87
+ private readonly endsAt;
88
+ private readonly owners;
89
+ private readonly utterances;
90
+ private nextStartTime;
91
+ private firstAudioReported;
92
+ private disposed;
93
+ constructor(options: StreamingPcmPlayerOptions);
94
+ /**
95
+ * Starts an utterance: a group of chunks with its own stop and drain. Utterances queue behind
96
+ * each other on the same schedule, so they never overlap.
97
+ */
98
+ beginUtterance(): PlaybackUtterance;
99
+ /** Schedules one chunk and returns the context time it starts at, or null when disposed. */
100
+ enqueue(pcm: Float32Array): number | null;
101
+ /** @internal Schedules one chunk for `owner` (or for no utterance). */
102
+ schedule(pcm: Float32Array, owner: PlaybackUtterance | undefined): number | null;
103
+ /** Stops playback and throws away everything scheduled, for every utterance: the barge-in path. */
104
+ stop(): void;
105
+ /** @internal Stops only `utterance`'s sources and closes the gap they leave in the schedule. */
106
+ unschedule(utterance: PlaybackUtterance): void;
107
+ private forget;
108
+ private halt;
109
+ /** Whether something is scheduled or playing. */
110
+ get isPlaying(): boolean;
111
+ suspend(): Promise<void>;
112
+ resume(): Promise<void>;
113
+ /** Stops playback and closes the context. Idempotent. */
114
+ dispose(): Promise<void>;
115
+ }