@adea-ai/voice 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +51 -2
  2. package/dist/cli/helpers-cli.d.ts +2 -0
  3. package/dist/cli/helpers-cli.js +102 -0
  4. package/dist/contract/contract.d.ts +138 -0
  5. package/dist/contract/errors.d.ts +26 -0
  6. package/dist/contract/index.d.ts +9 -0
  7. package/dist/contract/index.js +54 -0
  8. package/dist/contract/session.d.ts +58 -0
  9. package/dist/contract/wire.d.ts +188 -0
  10. package/dist/desktop/desktop-voice.d.ts +152 -0
  11. package/dist/desktop/helper-lock.d.ts +83 -0
  12. package/dist/desktop/helper-process.d.ts +92 -0
  13. package/dist/desktop/index.d.ts +7 -0
  14. package/dist/desktop/index.js +1042 -0
  15. package/dist/index-9kerqn9r.js +150 -0
  16. package/dist/index-acm1yvvv.js +290 -0
  17. package/dist/index-r4hz8gk0.js +10 -0
  18. package/dist/index-rehs788p.js +42 -0
  19. package/dist/index-s270cw30.js +295 -0
  20. package/dist/index-tvz9s9nz.js +77 -0
  21. package/dist/index.d.ts +7 -0
  22. package/dist/index.js +86 -0
  23. package/dist/settings/index.d.ts +5 -0
  24. package/dist/settings/index.js +34 -0
  25. package/dist/settings/settings.d.ts +163 -0
  26. package/dist/web/index.d.ts +15 -0
  27. package/dist/web/index.js +1287 -0
  28. package/dist/web/stt/speech-recognition.d.ts +105 -0
  29. package/dist/web/tts/phonon.d.ts +139 -0
  30. package/dist/web/tts/player.d.ts +115 -0
  31. package/dist/web/tts/system-voices.d.ts +122 -0
  32. package/dist/web/turns.d.ts +101 -0
  33. package/package.json +68 -4
  34. package/src/cli/helpers-cli.ts +119 -0
  35. package/src/contract/contract.ts +365 -0
  36. package/src/contract/errors.ts +98 -0
  37. package/src/contract/index.ts +9 -0
  38. package/src/contract/session.ts +65 -0
  39. package/src/contract/wire.ts +263 -0
  40. package/src/desktop/desktop-voice.ts +933 -0
  41. package/src/desktop/helper-lock.ts +375 -0
  42. package/src/desktop/helper-process.ts +401 -0
  43. package/src/desktop/index.ts +16 -0
  44. package/src/index.ts +7 -0
  45. package/src/settings/index.ts +5 -0
  46. package/src/settings/settings.ts +478 -0
  47. package/src/web/index.ts +15 -0
  48. package/src/web/stt/speech-recognition.ts +583 -0
  49. package/src/web/tts/phonon.ts +386 -0
  50. package/src/web/tts/player.ts +271 -0
  51. package/src/web/tts/system-voices.ts +401 -0
  52. package/src/web/turns.ts +224 -0
@@ -0,0 +1,401 @@
1
+ /**
2
+ * Platform voices as the browser's fallback for languages Phonon cannot ship (issue #36).
3
+ *
4
+ * `speechSynthesis` is not uniformly offline: the voices a browser exposes can be local
5
+ * (`localService === true`) or remote, and the two are indistinguishable to a person unless the
6
+ * app says so. This provider is therefore **local-voice only** by default: a locale with no local
7
+ * voice reports `networkRequired`, not "available", and a remote voice is only used when the host
8
+ * passes `allowNetwork: true` after a privacy notice.
9
+ *
10
+ * Phonon stays the English default; this provider answers for ES-419 and for English devices where
11
+ * the person declines the model download.
12
+ */
13
+ import {
14
+ AVAILABLE,
15
+ VOICE_CONTRACT,
16
+ unavailable,
17
+ type VoiceProvider,
18
+ type VoiceProviderAvailability,
19
+ type VoiceProviderDescriptor,
20
+ } from "../../contract/contract";
21
+ import { VoiceError } from "../../contract/errors";
22
+
23
+ export interface SynthesisVoiceLike {
24
+ readonly name: string;
25
+ readonly lang: string;
26
+ readonly localService?: boolean;
27
+ readonly default?: boolean;
28
+ readonly voiceURI?: string;
29
+ }
30
+
31
+ export interface SynthesisUtteranceLike {
32
+ text: string;
33
+ lang: string;
34
+ voice: SynthesisVoiceLike | null;
35
+ rate: number;
36
+ pitch: number;
37
+ volume: number;
38
+ onstart: (() => void) | null;
39
+ onend: (() => void) | null;
40
+ onerror: ((event: { error: string }) => void) | null;
41
+ }
42
+
43
+ export interface SpeechSynthesisLike {
44
+ getVoices(): SynthesisVoiceLike[];
45
+ speak(utterance: SynthesisUtteranceLike): void;
46
+ cancel(): void;
47
+ pause?(): void;
48
+ resume?(): void;
49
+ readonly speaking?: boolean;
50
+ readonly pending?: boolean;
51
+ /** `voiceschanged` fires when the browser finished loading its voice list (Chrome loads late). */
52
+ addEventListener?(type: "voiceschanged", listener: () => void): void;
53
+ removeEventListener?(type: "voiceschanged", listener: () => void): void;
54
+ }
55
+
56
+ /** A timer handle; only passed back to `clearTimeout`. */
57
+ export type TimerHandle = unknown;
58
+
59
+ export interface SystemVoicesEnvironment {
60
+ readonly speechSynthesis?: SpeechSynthesisLike;
61
+ readonly Utterance?: new (text: string) => SynthesisUtteranceLike;
62
+ /** The browser's own constructor name; used when `Utterance` is not injected. */
63
+ readonly SpeechSynthesisUtterance?: new (text: string) => SynthesisUtteranceLike;
64
+ readonly now?: () => number;
65
+ /** Timers for the voice-list wait and the speech watchdog. Default: the global timers. */
66
+ readonly setTimeout?: (callback: () => void, milliseconds: number) => TimerHandle;
67
+ readonly clearTimeout?: (handle: TimerHandle) => void;
68
+ /** How long the first probe waits for `voiceschanged` when the list is empty. Default 1500 ms. */
69
+ readonly voicesTimeoutMs?: number;
70
+ }
71
+
72
+ export interface SpeakWithPlatformVoiceOptions {
73
+ /** A BCP-47 tag. Selects a local voice of this language and sets the utterance language. */
74
+ readonly locale?: string;
75
+ /** An exact voice name; wins over `locale` when both are given. */
76
+ readonly voiceName?: string;
77
+ readonly rate?: number;
78
+ readonly pitch?: number;
79
+ readonly volume?: number;
80
+ /** Whether the host has consent for a remote voice. Default false. */
81
+ readonly allowNetwork?: boolean;
82
+ readonly onStart?: () => void;
83
+ readonly onEnd?: () => void;
84
+ /**
85
+ * Reject with `failed` if the browser never reports an end (Chrome can drop `end` events).
86
+ * Default: 15 s plus 200 ms per character, scaled by `rate`.
87
+ */
88
+ readonly timeoutMs?: number;
89
+ }
90
+
91
+ export interface PlatformSpeechHandle {
92
+ readonly done: Promise<void>;
93
+ cancel(): void;
94
+ }
95
+
96
+ export const SYSTEM_VOICES_ID = "web.system-voices";
97
+
98
+ const DEFAULT_VOICES_TIMEOUT_MS = 1_500;
99
+
100
+ /** One `speak()` call's state. Every handle settles its own promise; nothing is shared. */
101
+ interface Request {
102
+ readonly build: () => SynthesisUtteranceLike;
103
+ readonly options: SpeakWithPlatformVoiceOptions;
104
+ utterance: SynthesisUtteranceLike;
105
+ started: boolean;
106
+ settled: boolean;
107
+ /** Cancelled while queued behind another request's audio: drop it the moment it starts. */
108
+ zombie: boolean;
109
+ watchdog: TimerHandle | undefined;
110
+ resolve: () => void;
111
+ reject: (error: unknown) => void;
112
+ }
113
+
114
+ export class SystemVoiceProvider implements VoiceProvider {
115
+ readonly descriptor: VoiceProviderDescriptor;
116
+ private readonly environment: SystemVoicesEnvironment;
117
+ /** Requests in browser queue order that have not settled. */
118
+ private inFlight: Request[] = [];
119
+ private voicesReady: Promise<void> | undefined;
120
+
121
+ constructor(environment: SystemVoicesEnvironment = globalThis as never) {
122
+ this.environment = environment;
123
+ this.descriptor = {
124
+ id: SYSTEM_VOICES_ID,
125
+ displayName: "Platform voices",
126
+ kind: "textToSpeech",
127
+ platforms: ["web"],
128
+ execution: "systemProvided",
129
+ contract: VOICE_CONTRACT,
130
+ requiresModelDownload: false,
131
+ modelFamilies: ["browser.speechSynthesis"],
132
+ licenses: [{ spdxIdentifier: "Browser-System-Voices", commercialUse: true }],
133
+ capabilities: { trueCancellation: true, voiceSelection: true, wordBoundaryPause: true, localeSelection: true },
134
+ };
135
+ }
136
+
137
+ private get Utterance(): (new (text: string) => SynthesisUtteranceLike) | undefined {
138
+ return this.environment.Utterance ?? this.environment.SpeechSynthesisUtterance;
139
+ }
140
+
141
+ /** Voices the browser exposes for a locale, split by where they run. */
142
+ voices(locale: string): { local: SynthesisVoiceLike[]; remote: SynthesisVoiceLike[] } {
143
+ const synthesis = this.environment.speechSynthesis;
144
+ if (synthesis === undefined) return { local: [], remote: [] };
145
+ const wanted = language(locale);
146
+ const matches = synthesis.getVoices().filter((voice) => language(voice.lang) === wanted);
147
+ return {
148
+ local: matches.filter((voice) => voice.localService === true),
149
+ remote: matches.filter((voice) => voice.localService !== true),
150
+ };
151
+ }
152
+
153
+ /**
154
+ * Resolves once the browser has a voice list, or after `voicesTimeoutMs`. Chrome returns an empty
155
+ * list until `voiceschanged`, which would otherwise read as "no voice installed".
156
+ */
157
+ waitForVoices(): Promise<void> {
158
+ const synthesis = this.environment.speechSynthesis;
159
+ if (synthesis === undefined || synthesis.getVoices().length > 0) return Promise.resolve();
160
+ if (this.voicesReady) return this.voicesReady;
161
+ this.voicesReady = new Promise<void>((resolve) => {
162
+ let timer: TimerHandle | undefined;
163
+ const finish = () => {
164
+ synthesis.removeEventListener?.("voiceschanged", finish);
165
+ if (timer !== undefined) this.clearTimer(timer);
166
+ resolve();
167
+ };
168
+ if (synthesis.addEventListener === undefined) {
169
+ resolve();
170
+ return;
171
+ }
172
+ synthesis.addEventListener("voiceschanged", finish);
173
+ timer = this.setTimer(finish, this.environment.voicesTimeoutMs ?? DEFAULT_VOICES_TIMEOUT_MS);
174
+ });
175
+ return this.voicesReady;
176
+ }
177
+
178
+ async availability(locale: string): Promise<VoiceProviderAvailability> {
179
+ if (this.environment.speechSynthesis === undefined || this.Utterance === undefined) {
180
+ return unavailable("unsupportedPlatform", "this browser has no speech synthesis", {
181
+ kind: "chooseAnotherProvider",
182
+ detail: "use a browser with platform voices",
183
+ });
184
+ }
185
+ await this.waitForVoices();
186
+ const { local, remote } = this.voices(locale);
187
+ if (local.length > 0) return AVAILABLE;
188
+ if (remote.length > 0) {
189
+ return unavailable("networkRequired", `only remote ${locale} voices are installed`, {
190
+ kind: "grantPermission",
191
+ detail: "use a network voice only with an explicit privacy choice",
192
+ });
193
+ }
194
+ return unavailable("unsupportedLocale", `no ${locale} voice is installed`, {
195
+ kind: "installModel",
196
+ detail: `install a ${locale} voice in the operating system`,
197
+ });
198
+ }
199
+
200
+ /**
201
+ * Speaks with a platform voice. Local voices only unless `allowNetwork` is set. With `locale`,
202
+ * the voice is a local voice of that language (exact tag first, then the language's default).
203
+ */
204
+ speak(text: string, options: SpeakWithPlatformVoiceOptions = {}): PlatformSpeechHandle {
205
+ const synthesis = this.environment.speechSynthesis;
206
+ const Utterance = this.Utterance;
207
+ if (synthesis === undefined || Utterance === undefined) {
208
+ return { done: Promise.reject(new VoiceError("unavailable")), cancel: () => {} };
209
+ }
210
+ if (text.trim().length === 0) {
211
+ return { done: Promise.reject(new VoiceError("bad_request", "cannot speak empty text")), cancel: () => {} };
212
+ }
213
+ const selection = this.selectVoice(synthesis.getVoices(), options);
214
+ if (selection instanceof VoiceError) {
215
+ return { done: Promise.reject(selection), cancel: () => {} };
216
+ }
217
+ const voice = selection;
218
+ const build = () => {
219
+ const utterance = new Utterance(text);
220
+ utterance.lang = voice?.lang ?? options.locale ?? "";
221
+ utterance.voice = voice ?? null;
222
+ utterance.rate = options.rate ?? 1;
223
+ utterance.pitch = options.pitch ?? 1;
224
+ utterance.volume = options.volume ?? 1;
225
+ return utterance;
226
+ };
227
+
228
+ let request!: Request;
229
+ const done = new Promise<void>((resolve, reject) => {
230
+ request = { build, options, utterance: build(), started: false, settled: false, zombie: false, watchdog: undefined, resolve, reject };
231
+ });
232
+ this.inFlight.push(request);
233
+ this.bind(request);
234
+ const timeout = options.timeoutMs ?? 15_000 + (text.length * 200) / Math.max(0.1, options.rate ?? 1);
235
+ request.watchdog = this.setTimer(() => {
236
+ this.abandon(request, new VoiceError("failed", "the platform voice never reported the end of the speech"));
237
+ }, timeout);
238
+ try {
239
+ synthesis.speak(request.utterance);
240
+ } catch (error) {
241
+ this.settle(request, VoiceError.wrapping(error));
242
+ }
243
+
244
+ return { done, cancel: () => this.abandon(request, new VoiceError("cancelled")) };
245
+ }
246
+
247
+ /** Whether a synthesis request is in flight. */
248
+ get isSpeaking(): boolean {
249
+ return this.environment.speechSynthesis?.speaking === true || this.environment.speechSynthesis?.pending === true;
250
+ }
251
+
252
+ private selectVoice(
253
+ available: SynthesisVoiceLike[],
254
+ options: SpeakWithPlatformVoiceOptions,
255
+ ): SynthesisVoiceLike | undefined | VoiceError {
256
+ const allowNetwork = options.allowNetwork === true;
257
+ if (options.voiceName) {
258
+ const requested = available.find((voice) => voice.name === options.voiceName);
259
+ if (requested !== undefined) {
260
+ if (requested.localService !== true && !allowNetwork) {
261
+ return new VoiceError("denied", "a remote voice needs explicit consent");
262
+ }
263
+ return requested;
264
+ }
265
+ }
266
+ if (options.locale) {
267
+ const wanted = language(options.locale);
268
+ const tag = normalizeTag(options.locale);
269
+ const sameLanguage = available.filter((voice) => language(voice.lang) === wanted);
270
+ const pick = (pool: SynthesisVoiceLike[]) =>
271
+ pool.find((voice) => normalizeTag(voice.lang) === tag && voice.default === true) ??
272
+ pool.find((voice) => normalizeTag(voice.lang) === tag) ??
273
+ pool.find((voice) => voice.default === true) ??
274
+ pool[0];
275
+ const local = pick(sameLanguage.filter((voice) => voice.localService === true));
276
+ if (local) return local;
277
+ if (allowNetwork) return pick(sameLanguage);
278
+ return new VoiceError("language_unsupported", `no local ${options.locale} voice is installed`);
279
+ }
280
+ const fallback =
281
+ available.find((voice) => voice.localService === true && voice.default === true) ??
282
+ available.find((voice) => voice.localService === true);
283
+ if (fallback === undefined && !allowNetwork) {
284
+ return new VoiceError("language_unsupported", "no local voice is installed");
285
+ }
286
+ return fallback;
287
+ }
288
+
289
+ /** Wires one utterance object's events to its request. A rebuilt utterance is wired again. */
290
+ private bind(request: Request): void {
291
+ const utterance = request.utterance;
292
+ const options = request.options;
293
+ utterance.onstart = () => {
294
+ if (request.utterance !== utterance) return;
295
+ if (request.zombie) {
296
+ // It was cancelled while queued behind other audio: drop it now that it is the speaker.
297
+ this.purge();
298
+ return;
299
+ }
300
+ request.started = true;
301
+ options.onStart?.();
302
+ };
303
+ utterance.onend = () => {
304
+ if (request.utterance !== utterance || request.settled) return;
305
+ options.onEnd?.();
306
+ this.settle(request);
307
+ };
308
+ utterance.onerror = (event) => {
309
+ if (request.utterance !== utterance || request.settled) return;
310
+ this.settle(request, mapSynthesisError(event.error));
311
+ };
312
+ }
313
+
314
+ /**
315
+ * Ends one request early (cancel or watchdog) without touching the others' promises. The browser
316
+ * can only cancel its whole queue, so the other unstarted requests are re-queued afterwards.
317
+ */
318
+ private abandon(request: Request, error: VoiceError): void {
319
+ if (request.settled) return;
320
+ const speakerIsOther = this.inFlight.some((other) => other !== request && other.started);
321
+ this.settle(request, error);
322
+ if (!request.started && speakerIsOther) {
323
+ // Another request is audible right now; cancelling would cut it off. Drop this one when its
324
+ // turn comes instead.
325
+ request.zombie = true;
326
+ return;
327
+ }
328
+ this.purge();
329
+ }
330
+
331
+ /** Cancels the browser queue and re-queues every unsettled request that had not started. */
332
+ private purge(): void {
333
+ const synthesis = this.environment.speechSynthesis;
334
+ if (synthesis === undefined) return;
335
+ const survivors = this.inFlight.filter((request) => !request.settled && !request.started);
336
+ for (const request of this.inFlight) detach(request.utterance);
337
+ synthesis.cancel();
338
+ for (const request of survivors) {
339
+ // A fresh object: late events from the cancelled one can never be mistaken for this run.
340
+ request.utterance = request.build();
341
+ this.bind(request);
342
+ try {
343
+ synthesis.speak(request.utterance);
344
+ } catch (error) {
345
+ this.settle(request, VoiceError.wrapping(error));
346
+ }
347
+ }
348
+ }
349
+
350
+ private settle(request: Request, error?: VoiceError): void {
351
+ if (request.settled) return;
352
+ request.settled = true;
353
+ if (request.watchdog !== undefined) this.clearTimer(request.watchdog);
354
+ request.watchdog = undefined;
355
+ this.inFlight = this.inFlight.filter((candidate) => candidate !== request);
356
+ if (error) request.reject(error);
357
+ else request.resolve();
358
+ }
359
+
360
+ private setTimer(callback: () => void, milliseconds: number): TimerHandle {
361
+ if (this.environment.setTimeout) return this.environment.setTimeout(callback, milliseconds);
362
+ const handle = setTimeout(callback, milliseconds) as unknown as { unref?: () => void };
363
+ handle.unref?.();
364
+ return handle;
365
+ }
366
+
367
+ private clearTimer(handle: TimerHandle): void {
368
+ if (this.environment.clearTimeout) this.environment.clearTimeout(handle);
369
+ else clearTimeout(handle as ReturnType<typeof setTimeout>);
370
+ }
371
+ }
372
+
373
+ function detach(utterance: SynthesisUtteranceLike): void {
374
+ utterance.onstart = null;
375
+ utterance.onend = null;
376
+ utterance.onerror = null;
377
+ }
378
+
379
+ function normalizeTag(tag: string): string {
380
+ return tag.replace(/_/g, "-").toLowerCase();
381
+ }
382
+
383
+ function language(locale: string): string {
384
+ return locale.toLowerCase().split(/[-_]/)[0] ?? locale.toLowerCase();
385
+ }
386
+
387
+ function mapSynthesisError(error: string): VoiceError {
388
+ switch (error) {
389
+ case "interrupted":
390
+ case "canceled":
391
+ case "cancelled":
392
+ return new VoiceError("cancelled");
393
+ case "not-allowed":
394
+ return new VoiceError("denied");
395
+ case "language-unavailable":
396
+ case "voice-unavailable":
397
+ return new VoiceError("language_unsupported");
398
+ default:
399
+ return new VoiceError("failed", `platform synthesis error: ${error}`);
400
+ }
401
+ }
@@ -0,0 +1,224 @@
1
+ /**
2
+ * The browser side of the engine-agnostic voice turn manager (#34).
3
+ *
4
+ * A turn is one person→assistant exchange: the person speaks, they get a transcript, the assistant
5
+ * answers, and the person can talk over it. The manager owns exactly that state machine and nothing
6
+ * engine-specific: dictation arrives through the shared `TranscriptionSession` contract, speech
7
+ * leaves through a `SpeechSink` the host provides (Phonon, a platform voice, anything), and
8
+ * barge-in arrives through `notifySpeechDetected()` — from the microphone's voice detector, a
9
+ * key press, or the start of a new recognition session.
10
+ *
11
+ * The rule that matters: **barge-in stops speech with a request cancel, not a mute**, and a turn
12
+ * always ends in exactly one terminal event. Starting a new turn while the assistant is still
13
+ * talking is the common case on a page, so it is the default, not an option.
14
+ */
15
+ import type { PartialTranscript, SessionEvent, TranscriptionProvider, TranscriptionSession } from "./stt/speech-recognition";
16
+ import { VoiceError } from "../contract/errors";
17
+
18
+ /** What the assistant does with its answer. The manager never knows which engine is behind it. */
19
+ export interface SpeechSink {
20
+ speak(text: string, options?: { signal?: AbortSignal }): { done: Promise<unknown>; cancel(): void };
21
+ }
22
+
23
+ export type TurnEvent =
24
+ | { readonly type: "listening" }
25
+ | { readonly type: "partial"; readonly partial: PartialTranscript }
26
+ | { readonly type: "transcript"; readonly text: string }
27
+ | { readonly type: "speaking"; readonly text: string }
28
+ | { readonly type: "speech-finished" }
29
+ | { readonly type: "speech-cancelled" }
30
+ | { readonly type: "barge-in" }
31
+ | { readonly type: "failed"; readonly error: VoiceError }
32
+ | { readonly type: "cancelled" };
33
+
34
+ export interface TurnManagerOptions {
35
+ readonly transcription: TranscriptionProvider;
36
+ readonly synthesis: SpeechSink;
37
+ /** Locale for every session this manager starts. */
38
+ readonly locale: string;
39
+ /** Whether the host has consented to the browser's service recognizer. */
40
+ readonly allowNetwork?: boolean;
41
+ /** Stop the assistant's speech when the person starts talking. Default true. */
42
+ readonly bargeInOnSpeech?: boolean;
43
+ /** Receives an error thrown by an event listener. Default: `console.error`. */
44
+ readonly onListenerError?: (error: unknown) => void;
45
+ }
46
+
47
+ /**
48
+ * One conversation's turns. `startListening()` and `speak()` are the two entry points a page
49
+ * needs; `events()` is one ordered stream for the UI.
50
+ */
51
+ export class VoiceTurnManager {
52
+ private readonly options: TurnManagerOptions;
53
+ private readonly listeners = new Set<(event: TurnEvent) => void>();
54
+
55
+ private session: TranscriptionSession | undefined;
56
+ private speech: { cancel(): void; done: Promise<unknown> } | undefined;
57
+ /** Bumped by every `startListening()` and by `cancel()`: an older start that resumes is stale. */
58
+ private generation = 0;
59
+ private finished = false;
60
+
61
+ constructor(options: TurnManagerOptions) {
62
+ this.options = options;
63
+ }
64
+
65
+ /** Subscribes to turn events. Returns an unsubscribe function. */
66
+ onEvent(listener: (event: TurnEvent) => void): () => void {
67
+ this.listeners.add(listener);
68
+ return () => this.listeners.delete(listener);
69
+ }
70
+
71
+ /**
72
+ * Starts a dictation turn. If the assistant is speaking, that speech is cancelled first and a
73
+ * `barge-in` event is emitted — the person talking over the assistant always wins.
74
+ */
75
+ async startListening(): Promise<void> {
76
+ if (this.finished) throw new VoiceError("cancelled", "the turn manager was cancelled");
77
+ const generation = ++this.generation;
78
+ const previous = this.session;
79
+ // Detach first, so the previous session's own `cancelled` event is not reported as this turn's.
80
+ this.session = undefined;
81
+ if (this.speech) this.stopSpeech("barge-in");
82
+ if (previous) await previous.cancel();
83
+ if (this.finished) throw new VoiceError("cancelled", "the turn manager was cancelled");
84
+ if (generation !== this.generation) return; // a newer startListening() owns the turn now
85
+
86
+ let session: TranscriptionSession;
87
+ try {
88
+ session = await this.options.transcription.createSession({
89
+ locale: this.options.locale,
90
+ allowNetwork: this.options.allowNetwork === true,
91
+ });
92
+ } catch (error) {
93
+ if (this.finished) throw new VoiceError("cancelled", "the turn manager was cancelled");
94
+ if (generation !== this.generation) return;
95
+ this.emit({ type: "failed", error: VoiceError.wrapping(error) });
96
+ throw error;
97
+ }
98
+ if (this.finished || generation !== this.generation) {
99
+ // Cancelled, or superseded, while the session was being created: never leave it running.
100
+ await session.cancel();
101
+ if (this.finished) throw new VoiceError("cancelled", "the turn manager was cancelled");
102
+ return;
103
+ }
104
+ this.session = session;
105
+ this.emit({ type: "listening" });
106
+ void this.consume(session);
107
+ }
108
+
109
+ /** Stops needing audio: the session finalizes with what it heard. */
110
+ async stopListening(): Promise<void> {
111
+ await this.session?.end();
112
+ }
113
+
114
+ /** Speaks an answer. A previous answer is cancelled first; the sink decides how it plays. */
115
+ speak(text: string): { done: Promise<unknown>; cancel(): void } {
116
+ if (this.finished) {
117
+ return { done: Promise.reject(new VoiceError("cancelled")), cancel: () => {} };
118
+ }
119
+ if (this.speech) this.stopSpeech("replaced");
120
+ const handle = this.options.synthesis.speak(text);
121
+ this.speech = handle;
122
+ this.emit({ type: "speaking", text });
123
+ void handle.done
124
+ .then(() => {
125
+ if (this.speech !== handle) return;
126
+ this.speech = undefined;
127
+ this.emit({ type: "speech-finished" });
128
+ })
129
+ .catch((error) => {
130
+ if (this.speech !== handle) return;
131
+ this.speech = undefined;
132
+ const wrapped = VoiceError.wrapping(error);
133
+ this.emit(wrapped.code === "cancelled" ? { type: "speech-cancelled" } : { type: "failed", error: wrapped });
134
+ });
135
+ return {
136
+ done: handle.done,
137
+ // Only this answer: cancelling a handle that was already replaced must not stop the new one.
138
+ cancel: () => {
139
+ if (this.speech === handle) this.stopSpeech("replaced");
140
+ else handle.cancel();
141
+ },
142
+ };
143
+ }
144
+
145
+ /** The person started talking (voice detector, key press, or a new session). */
146
+ notifySpeechDetected(): void {
147
+ if (this.options.bargeInOnSpeech === false) return;
148
+ this.stopSpeech("barge-in");
149
+ }
150
+
151
+ /** Tears both halves down. Idempotent; emits one terminal event. */
152
+ async cancel(): Promise<void> {
153
+ if (this.finished) return;
154
+ this.finished = true;
155
+ this.generation += 1;
156
+ this.stopSpeech("cancel");
157
+ const session = this.session;
158
+ this.session = undefined;
159
+ await session?.cancel();
160
+ this.emit({ type: "cancelled" });
161
+ }
162
+
163
+ /**
164
+ * `barge-in`: the person talked over the answer (`barge-in` + `speech-cancelled`).
165
+ * `replaced`: a newer answer or the host stopped it (`speech-cancelled`).
166
+ * `cancel`: the manager is tearing down; its own `cancelled` is the terminal event.
167
+ */
168
+ private stopSpeech(reason: "barge-in" | "replaced" | "cancel"): void {
169
+ const speech = this.speech;
170
+ if (speech === undefined) return;
171
+ this.speech = undefined;
172
+ speech.cancel();
173
+ if (reason === "barge-in") this.emit({ type: "barge-in" });
174
+ if (reason !== "cancel") this.emit({ type: "speech-cancelled" });
175
+ }
176
+
177
+ private async consume(session: TranscriptionSession): Promise<void> {
178
+ try {
179
+ for await (const event of session.events()) {
180
+ if (this.session !== session) return;
181
+ this.forward(event);
182
+ }
183
+ } catch (error) {
184
+ if (this.session !== session) return;
185
+ this.session = undefined;
186
+ this.emit({ type: "failed", error: VoiceError.wrapping(error) });
187
+ }
188
+ }
189
+
190
+ private forward(event: SessionEvent): void {
191
+ switch (event.type) {
192
+ case "partial":
193
+ this.emit({ type: "partial", partial: event.partial });
194
+ return;
195
+ case "final":
196
+ this.session = undefined;
197
+ this.emit({ type: "transcript", text: event.text });
198
+ return;
199
+ case "failed":
200
+ this.session = undefined;
201
+ this.emit({ type: "failed", error: event.error });
202
+ return;
203
+ case "cancelled":
204
+ this.session = undefined;
205
+ this.emit({ type: "cancelled" });
206
+ return;
207
+ }
208
+ }
209
+
210
+ private emit(event: TurnEvent): void {
211
+ for (const listener of [...this.listeners]) {
212
+ try {
213
+ listener(event);
214
+ } catch (error) {
215
+ // One broken listener must not stop the session pump or starve the other listeners.
216
+ (this.options.onListenerError ?? defaultListenerError)(error);
217
+ }
218
+ }
219
+ }
220
+ }
221
+
222
+ function defaultListenerError(error: unknown): void {
223
+ console.error("voice turn listener threw", error);
224
+ }