@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,235 @@
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 { SessionEvent, TranscriptionProvider, TranscriptionSession } from "./stt/speech-recognition";
16
+ import { VoiceError } from "../contract/errors";
17
+ import type { TurnEvent } from "../contract/turns";
18
+
19
+ /** What the assistant does with its answer. The manager never knows which engine is behind it. */
20
+ export interface SpeechSink {
21
+ speak(text: string, options?: { signal?: AbortSignal }): { done: Promise<unknown>; cancel(): void };
22
+ }
23
+
24
+ /** The shared turn vocabulary (`@adea-ai/voice/contract`), re-exported for existing imports. */
25
+ export type { TurnEvent } from "../contract/turns";
26
+
27
+ export interface TurnManagerOptions {
28
+ readonly transcription: TranscriptionProvider;
29
+ readonly synthesis: SpeechSink;
30
+ /** Locale for every session this manager starts. */
31
+ readonly locale: string;
32
+ /** Whether the host has consented to the browser's service recognizer. */
33
+ readonly allowNetwork?: boolean;
34
+ /** Stop the assistant's speech when the person starts talking. Default true. */
35
+ readonly bargeInOnSpeech?: boolean;
36
+ /** Receives an error thrown by an event listener. Default: `console.error`. */
37
+ readonly onListenerError?: (error: unknown) => void;
38
+ }
39
+
40
+ /**
41
+ * One conversation's turns. `startListening()` and `speak()` are the two entry points a page
42
+ * needs; `events()` is one ordered stream for the UI.
43
+ */
44
+ export class VoiceTurnManager {
45
+ private readonly options: TurnManagerOptions;
46
+ private readonly listeners = new Set<(event: TurnEvent) => void>();
47
+
48
+ private session: TranscriptionSession | undefined;
49
+ private speech: { cancel(): void; done: Promise<unknown> } | undefined;
50
+ /** Bumped by every `startListening()` and by `cancel()`: an older start that resumes is stale. */
51
+ private generation = 0;
52
+ private finished = false;
53
+
54
+ constructor(options: TurnManagerOptions) {
55
+ this.options = options;
56
+ }
57
+
58
+ /** Subscribes to turn events. Returns an unsubscribe function. */
59
+ onEvent(listener: (event: TurnEvent) => void): () => void {
60
+ this.listeners.add(listener);
61
+ return () => this.listeners.delete(listener);
62
+ }
63
+
64
+ /**
65
+ * Starts a dictation turn. If the assistant is speaking, that speech is cancelled first and a
66
+ * `barge-in` event is emitted — the person talking over the assistant always wins.
67
+ */
68
+ async startListening(): Promise<void> {
69
+ if (this.finished) throw new VoiceError("cancelled", "the turn manager was cancelled");
70
+ const generation = ++this.generation;
71
+ const previous = this.session;
72
+ // Detach first, so the previous session's own `cancelled` event is not reported as this turn's.
73
+ this.session = undefined;
74
+ if (this.speech) this.stopSpeech("barge-in");
75
+ if (previous) await previous.cancel();
76
+ if (this.finished) throw new VoiceError("cancelled", "the turn manager was cancelled");
77
+ if (generation !== this.generation) return; // a newer startListening() owns the turn now
78
+
79
+ let session: TranscriptionSession;
80
+ try {
81
+ session = await this.options.transcription.createSession({
82
+ locale: this.options.locale,
83
+ allowNetwork: this.options.allowNetwork === true,
84
+ // The recognizer's speech start is barge-in: no host glue needed.
85
+ onSpeechStart: () => {
86
+ if (!this.finished && generation === this.generation) this.notifySpeechDetected();
87
+ },
88
+ });
89
+ } catch (error) {
90
+ if (this.finished) throw new VoiceError("cancelled", "the turn manager was cancelled");
91
+ if (generation !== this.generation) return;
92
+ this.emit({ type: "failed", error: VoiceError.wrapping(error) });
93
+ throw error;
94
+ }
95
+ if (this.finished || generation !== this.generation) {
96
+ // Cancelled, or superseded, while the session was being created: never leave it running.
97
+ await session.cancel();
98
+ if (this.finished) throw new VoiceError("cancelled", "the turn manager was cancelled");
99
+ return;
100
+ }
101
+ this.session = session;
102
+ this.emit({ type: "listening" });
103
+ void this.consume(session);
104
+ }
105
+
106
+ /** Stops needing audio: the session finalizes with what it heard. */
107
+ async stopListening(): Promise<void> {
108
+ await this.session?.end();
109
+ }
110
+
111
+ /** Speaks an answer. A previous answer is cancelled first; the sink decides how it plays. */
112
+ speak(text: string): { done: Promise<unknown>; cancel(): void } {
113
+ if (this.finished) {
114
+ return { done: Promise.reject(new VoiceError("cancelled")), cancel: () => {} };
115
+ }
116
+ if (this.speech) this.stopSpeech("replaced");
117
+ const handle = this.options.synthesis.speak(text);
118
+ this.speech = handle;
119
+ this.emit({ type: "speaking", text });
120
+ void handle.done
121
+ .then(() => {
122
+ if (this.speech !== handle) return;
123
+ this.speech = undefined;
124
+ this.emit({ type: "speech-finished" });
125
+ })
126
+ .catch((error) => {
127
+ if (this.speech !== handle) return;
128
+ this.speech = undefined;
129
+ const wrapped = VoiceError.wrapping(error);
130
+ this.emit(wrapped.code === "cancelled" ? { type: "speech-cancelled" } : { type: "failed", error: wrapped });
131
+ });
132
+ return {
133
+ done: handle.done,
134
+ // Only this answer: cancelling a handle that was already replaced must not stop the new one.
135
+ cancel: () => {
136
+ if (this.speech === handle) this.stopSpeech("replaced");
137
+ else handle.cancel();
138
+ },
139
+ };
140
+ }
141
+
142
+ /** The person started talking (voice detector, key press, or a new session). */
143
+ notifySpeechDetected(): void {
144
+ if (this.options.bargeInOnSpeech === false) return;
145
+ this.stopSpeech("barge-in");
146
+ }
147
+
148
+ /** Tears both halves down. Idempotent; emits one terminal event. */
149
+ async cancel(): Promise<void> {
150
+ if (this.finished) return;
151
+ this.finished = true;
152
+ this.generation += 1;
153
+ this.stopSpeech("cancel");
154
+ const session = this.session;
155
+ this.session = undefined;
156
+ await session?.cancel();
157
+ this.emit({ type: "cancelled" });
158
+ }
159
+
160
+ /**
161
+ * `barge-in`: the person talked over the answer (`barge-in` + `speech-cancelled`).
162
+ * `replaced`: a newer answer or the host stopped it (`speech-cancelled`).
163
+ * `cancel`: the manager is tearing down; its own `cancelled` is the terminal event.
164
+ */
165
+ private stopSpeech(reason: "barge-in" | "replaced" | "cancel"): void {
166
+ const speech = this.speech;
167
+ if (speech === undefined) return;
168
+ this.speech = undefined;
169
+ speech.cancel();
170
+ if (reason === "barge-in") this.emit({ type: "barge-in" });
171
+ if (reason !== "cancel") this.emit({ type: "speech-cancelled" });
172
+ }
173
+
174
+ private async consume(session: TranscriptionSession): Promise<void> {
175
+ try {
176
+ for await (const event of session.events()) {
177
+ if (this.session !== session) return;
178
+ this.forward(event);
179
+ }
180
+ } catch (error) {
181
+ if (this.session !== session) return;
182
+ this.session = undefined;
183
+ this.emit({ type: "failed", error: VoiceError.wrapping(error) });
184
+ }
185
+ }
186
+
187
+ private forward(event: SessionEvent): void {
188
+ switch (event.type) {
189
+ case "partial":
190
+ this.emit({ type: "partial", partial: event.partial });
191
+ return;
192
+ case "final":
193
+ this.session = undefined;
194
+ this.emit({ type: "transcript", text: event.text });
195
+ return;
196
+ case "failed":
197
+ this.session = undefined;
198
+ this.emit({ type: "failed", error: event.error });
199
+ return;
200
+ case "cancelled":
201
+ this.session = undefined;
202
+ this.emit({ type: "cancelled" });
203
+ return;
204
+ }
205
+ }
206
+
207
+ private emit(event: TurnEvent): void {
208
+ for (const listener of [...this.listeners]) {
209
+ try {
210
+ listener(event);
211
+ } catch (error) {
212
+ // One broken listener must not stop the session pump or starve the other listeners.
213
+ (this.options.onListenerError ?? defaultListenerError)(error);
214
+ }
215
+ }
216
+ }
217
+ }
218
+
219
+ function defaultListenerError(error: unknown): void {
220
+ console.error("voice turn listener threw", error);
221
+ }
222
+
223
+ /**
224
+ * For hosts that create recognition sessions themselves: spread into the session options so the
225
+ * recognizer's speech start stops the manager's answer (`notifySpeechDetected()`).
226
+ *
227
+ * ```ts
228
+ * const session = await provider.createSession({ locale, allowNetwork: false, ...bargeInOnSpeechStart(turns) });
229
+ * ```
230
+ */
231
+ export function bargeInOnSpeechStart(manager: Pick<VoiceTurnManager, "notifySpeechDetected">): {
232
+ readonly onSpeechStart: () => void;
233
+ } {
234
+ return { onSpeechStart: () => manager.notifySpeechDetected() };
235
+ }