@adea-ai/voice 0.2.0 → 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.
- package/README.md +86 -1
- package/dist/cli/helpers-cli.js +17 -2
- package/dist/contract/contract.d.ts +21 -2
- package/dist/contract/index.d.ts +1 -0
- package/dist/contract/index.js +12 -2
- package/dist/contract/session.d.ts +13 -0
- package/dist/contract/turns.d.ts +91 -0
- package/dist/contract/wire.d.ts +92 -1
- package/dist/desktop/conversation.d.ts +86 -0
- package/dist/desktop/desktop-voice.d.ts +61 -1
- package/dist/desktop/helper-lock.d.ts +45 -7
- package/dist/desktop/helper-process.d.ts +4 -0
- package/dist/desktop/index.d.ts +2 -0
- package/dist/desktop/index.js +427 -15
- package/dist/desktop/macho-digest.d.ts +9 -0
- package/dist/{index-rehs788p.js → index-7n7epq1a.js} +7 -2
- package/dist/{index-s270cw30.js → index-a7d617zr.js} +1 -1
- package/dist/{index-9kerqn9r.js → index-ght8wwpd.js} +9 -3
- package/dist/{index-acm1yvvv.js → index-m4g2tpeq.js} +258 -26
- package/dist/index.js +13 -3
- package/dist/settings/index.js +1 -1
- package/dist/web/index.d.ts +1 -0
- package/dist/web/index.js +459 -49
- package/dist/web/stt/speech-recognition.d.ts +128 -7
- package/dist/web/tts/locale-match.d.ts +40 -0
- package/dist/web/tts/system-voices.d.ts +44 -4
- package/dist/web/turns.d.ts +15 -25
- package/package.json +1 -1
- package/src/cli/helpers-cli.ts +18 -2
- package/src/contract/contract.ts +32 -4
- package/src/contract/index.ts +1 -0
- package/src/contract/session.ts +14 -2
- package/src/contract/turns.ts +48 -0
- package/src/contract/wire.ts +123 -2
- package/src/desktop/conversation.ts +347 -0
- package/src/desktop/desktop-voice.ts +197 -1
- package/src/desktop/helper-lock.ts +195 -20
- package/src/desktop/helper-process.ts +17 -10
- package/src/desktop/index.ts +2 -0
- package/src/desktop/macho-digest.ts +135 -0
- package/src/web/index.ts +1 -0
- package/src/web/stt/speech-recognition.ts +454 -24
- package/src/web/tts/locale-match.ts +131 -0
- package/src/web/tts/system-voices.ts +144 -35
- package/src/web/turns.ts +22 -11
package/src/contract/wire.ts
CHANGED
|
@@ -7,9 +7,14 @@
|
|
|
7
7
|
* parses these lines itself; `@adea-ai/voice/desktop` does, and maps them to the session contract.
|
|
8
8
|
*/
|
|
9
9
|
import { normalizeVoiceErrorCode, type VoiceErrorCode } from "./errors";
|
|
10
|
+
import type { TurnEndReason } from "./turns";
|
|
10
11
|
|
|
11
12
|
/** The wire major this SDK speaks. A helper on another major is refused, never guessed at. */
|
|
12
13
|
export const WIRE_VERSION = 1;
|
|
14
|
+
/** The wire minor that added conversation turns (`turn-*`); older helpers cannot run them. */
|
|
15
|
+
export const TURN_WIRE_MINOR = 2;
|
|
16
|
+
/** The wire minor that added model removal (`release-assets` → `asset-released`). */
|
|
17
|
+
export const RELEASE_ASSETS_WIRE_MINOR = 3;
|
|
13
18
|
/** The provider-contract major this SDK speaks. */
|
|
14
19
|
export const CONTRACT_MAJOR = 1;
|
|
15
20
|
/** One line may not exceed this many bytes (the helpers enforce the same bound on input). */
|
|
@@ -22,6 +27,8 @@ export interface VersionEvent {
|
|
|
22
27
|
readonly contract: string;
|
|
23
28
|
readonly contractMajor: number;
|
|
24
29
|
readonly helper?: string;
|
|
30
|
+
/** The voice release the helper was built from (e.g. `0.2.0`); a lock pins it. */
|
|
31
|
+
readonly release?: string;
|
|
25
32
|
readonly id?: string;
|
|
26
33
|
}
|
|
27
34
|
|
|
@@ -162,9 +169,47 @@ export interface AssetInstalledEvent {
|
|
|
162
169
|
readonly id?: string;
|
|
163
170
|
}
|
|
164
171
|
|
|
172
|
+
/**
|
|
173
|
+
* `release-assets`'s answer: this app's reservation of the locale's model is released (the system
|
|
174
|
+
* may then reclaim the model) and `status` is what the system reports afterwards. A model shared
|
|
175
|
+
* with system dictation can still read `installed`.
|
|
176
|
+
*/
|
|
177
|
+
export interface AssetReleasedEvent {
|
|
178
|
+
readonly event: "asset-released";
|
|
179
|
+
/** The locale as requested, e.g. `es-419`. */
|
|
180
|
+
readonly locale: string;
|
|
181
|
+
/** The model's own locale, the one the reservation was held for, e.g. `es_MX`. */
|
|
182
|
+
readonly modelLocale: string;
|
|
183
|
+
/** False when this app held no reservation for the model (nothing to release). */
|
|
184
|
+
readonly released: boolean;
|
|
185
|
+
readonly status: AssetStatus;
|
|
186
|
+
readonly canInstall: boolean;
|
|
187
|
+
readonly id?: string;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** The system voice speaking an utterance, as `speech-started` names it. */
|
|
191
|
+
export interface SpeechVoiceIdentity {
|
|
192
|
+
/** The system voice identifier (the `voice` a `speak` can pin). */
|
|
193
|
+
readonly id: string;
|
|
194
|
+
readonly name: string;
|
|
195
|
+
/** The voice's own locale, e.g. `es-MX` when `es-419` was requested. */
|
|
196
|
+
readonly language: string;
|
|
197
|
+
/**
|
|
198
|
+
* The same value as `language`, under the name the voice list items use. Additive: helpers
|
|
199
|
+
* from 0.3.0 and earlier send only `language`, and the SDK fills this in from it.
|
|
200
|
+
*/
|
|
201
|
+
readonly locale: string;
|
|
202
|
+
readonly quality: "default" | "enhanced" | "premium" | "unknown";
|
|
203
|
+
}
|
|
204
|
+
|
|
165
205
|
export interface SpeechLifecycleEvent {
|
|
166
206
|
readonly event: "speech-started" | "speech-finished" | "speech-cancelled";
|
|
167
207
|
readonly id: string;
|
|
208
|
+
/**
|
|
209
|
+
* On `speech-started` only, when the `speak` named a voice or a locale: the voice that
|
|
210
|
+
* resolved. Additive within wire 1; older helpers omit it.
|
|
211
|
+
*/
|
|
212
|
+
readonly voice?: SpeechVoiceIdentity;
|
|
168
213
|
}
|
|
169
214
|
|
|
170
215
|
export interface SpeechErrorEvent {
|
|
@@ -184,6 +229,80 @@ export interface SpeechInterruptedEvent {
|
|
|
184
229
|
readonly reason?: string;
|
|
185
230
|
}
|
|
186
231
|
|
|
232
|
+
// MARK: Conversation turns (wire 1.2)
|
|
233
|
+
//
|
|
234
|
+
// Commands: `turn-start {id, locale?, engine?, bargeIn?, halfDuplex?}`,
|
|
235
|
+
// `turn-respond {id, text, final?, voice?, locale?, rate?}`, `turn-end {id}`, `turn-cancel {id}`.
|
|
236
|
+
// Every turn ends in exactly one terminal: `turn-state` `ended` or `turn-error`; `turn-metrics`
|
|
237
|
+
// precedes it. A command naming a closed turn is answered with `idle`.
|
|
238
|
+
|
|
239
|
+
export type TurnWireState = "idle" | "listening" | "responding" | "speaking" | "interrupted" | "ended";
|
|
240
|
+
|
|
241
|
+
export interface TurnStateEvent {
|
|
242
|
+
readonly event: "turn-state";
|
|
243
|
+
readonly id: string;
|
|
244
|
+
readonly state: TurnWireState;
|
|
245
|
+
/** Set on `ended`. */
|
|
246
|
+
readonly reason?: TurnEndReason;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
export interface TurnPartialEvent {
|
|
250
|
+
readonly event: "turn-partial";
|
|
251
|
+
readonly id: string;
|
|
252
|
+
readonly text?: string;
|
|
253
|
+
readonly finalizedText: string;
|
|
254
|
+
readonly volatileText: string;
|
|
255
|
+
readonly sequence: number;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
export interface TurnTranscriptEvent {
|
|
259
|
+
readonly event: "turn-transcript";
|
|
260
|
+
readonly id: string;
|
|
261
|
+
readonly text: string;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
export interface TurnBargeInEvent {
|
|
265
|
+
readonly event: "turn-barge-in";
|
|
266
|
+
readonly id: string;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
export interface TurnSpeechEvent {
|
|
270
|
+
readonly event: "turn-speech-started" | "turn-speech-finished" | "turn-speech-cancelled";
|
|
271
|
+
readonly id: string;
|
|
272
|
+
readonly utterance: string;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** Timings only, in milliseconds from `turn-start`; never text or audio. */
|
|
276
|
+
export interface TurnMetricsEvent {
|
|
277
|
+
readonly event: "turn-metrics";
|
|
278
|
+
readonly id: string;
|
|
279
|
+
readonly firstPartialMs: number | null;
|
|
280
|
+
readonly transcriptMs: number | null;
|
|
281
|
+
readonly firstAudioMs: number | null;
|
|
282
|
+
readonly speechFinishedMs: number | null;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
export interface TurnErrorEvent {
|
|
286
|
+
readonly event: "turn-error";
|
|
287
|
+
readonly id: string;
|
|
288
|
+
readonly code: VoiceErrorCode;
|
|
289
|
+
readonly message?: string;
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
export type TurnWireEvent =
|
|
293
|
+
| TurnStateEvent
|
|
294
|
+
| TurnPartialEvent
|
|
295
|
+
| TurnTranscriptEvent
|
|
296
|
+
| TurnBargeInEvent
|
|
297
|
+
| TurnSpeechEvent
|
|
298
|
+
| TurnMetricsEvent
|
|
299
|
+
| TurnErrorEvent;
|
|
300
|
+
|
|
301
|
+
/** Whether an event is a turn's one terminal (`turn-state` `ended` or `turn-error`). */
|
|
302
|
+
export function isTurnTerminal(event: WireEvent): event is TurnStateEvent | TurnErrorEvent {
|
|
303
|
+
return event.event === "turn-error" || (event.event === "turn-state" && event.state === "ended");
|
|
304
|
+
}
|
|
305
|
+
|
|
187
306
|
/** A second line the local-model helpers print after `version`. */
|
|
188
307
|
export interface HelperIdentityEvent {
|
|
189
308
|
readonly event: "helper";
|
|
@@ -210,10 +329,12 @@ export type WireEvent =
|
|
|
210
329
|
| IdleEvent
|
|
211
330
|
| AssetProgressEvent
|
|
212
331
|
| AssetInstalledEvent
|
|
332
|
+
| AssetReleasedEvent
|
|
213
333
|
| SpeechLifecycleEvent
|
|
214
334
|
| SpeechErrorEvent
|
|
215
335
|
| SpeechStateEvent
|
|
216
|
-
| SpeechInterruptedEvent
|
|
336
|
+
| SpeechInterruptedEvent
|
|
337
|
+
| TurnWireEvent;
|
|
217
338
|
|
|
218
339
|
/** A command line. `cmd` is the helpers' key; `command` is sent too for the transcribe helper. */
|
|
219
340
|
export interface WireCommand {
|
|
@@ -238,7 +359,7 @@ export function parseWireLine(line: string): WireEvent | undefined {
|
|
|
238
359
|
if (value === null || typeof value !== "object" || Array.isArray(value)) return undefined;
|
|
239
360
|
const object = value as Record<string, unknown>;
|
|
240
361
|
if (typeof object.event !== "string") return undefined;
|
|
241
|
-
if (object.event === "error" || object.event === "speech-error") {
|
|
362
|
+
if (object.event === "error" || object.event === "speech-error" || object.event === "turn-error") {
|
|
242
363
|
return { ...object, code: normalizeVoiceErrorCode(object.code) } as unknown as WireEvent;
|
|
243
364
|
}
|
|
244
365
|
return object as unknown as WireEvent;
|
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Octy-style voice conversations on the desktop: `DesktopVoice.conversation()` over the
|
|
3
|
+
* `adea-voice-helper` turn protocol (wire 1.2, #34).
|
|
4
|
+
*
|
|
5
|
+
* A conversation is a run of turns on one helper. Each turn listens, finalizes a transcript, and
|
|
6
|
+
* speaks the answer the host streams back with `respond()`; the next turn starts by itself when the
|
|
7
|
+
* answer has played (`continuous`, the default) or when the host calls `listen()`. Starting a turn
|
|
8
|
+
* while the answer plays is a barge-in: the helper stops the speech with a request cancel before
|
|
9
|
+
* the microphone opens. Every turn reports the shared `TurnEvent` vocabulary (the browser
|
|
10
|
+
* `VoiceTurnManager` speaks it too), tagged with the turn's id, and ends in exactly one `ended` or
|
|
11
|
+
* `failed`.
|
|
12
|
+
*/
|
|
13
|
+
import { VoiceError } from "../contract/errors";
|
|
14
|
+
import type { TurnEvent } from "../contract/turns";
|
|
15
|
+
import { isTurnTerminal, type WireEvent } from "../contract/wire";
|
|
16
|
+
import { nextRequestId, type HelperConnection } from "./helper-process";
|
|
17
|
+
|
|
18
|
+
export interface ConversationRespondOptions {
|
|
19
|
+
/** Whether this is the answer's last chunk. Default true: one call is one whole answer. */
|
|
20
|
+
readonly final?: boolean;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** A running conversation. */
|
|
24
|
+
export interface DesktopConversation {
|
|
25
|
+
readonly provider: string;
|
|
26
|
+
readonly locale: string;
|
|
27
|
+
/**
|
|
28
|
+
* Every turn's events in order, each tagged with `turn`. Finishes after the conversation's
|
|
29
|
+
* last terminal: a `failed` turn, `cancelled` (from `cancel()` or the helper), or the `ended`
|
|
30
|
+
* of the last turn after `end()`. Can be read once.
|
|
31
|
+
*/
|
|
32
|
+
events(): AsyncIterable<TurnEvent>;
|
|
33
|
+
/**
|
|
34
|
+
* Speaks (part of) the current turn's answer. Chunks queue without gaps, so a streaming model's
|
|
35
|
+
* text can be spoken as it arrives; send `{ final: true }` (an empty text is fine) to finish
|
|
36
|
+
* the answer. Responding while the person is still talking closes the microphone.
|
|
37
|
+
*/
|
|
38
|
+
respond(textChunk: string, options?: ConversationRespondOptions): Promise<void>;
|
|
39
|
+
/** Starts the next turn now; while the answer plays this is a barge-in. */
|
|
40
|
+
listen(): Promise<void>;
|
|
41
|
+
/** Push-to-talk release: stop needing audio; the transcript of what was heard follows. */
|
|
42
|
+
stopListening(): Promise<void>;
|
|
43
|
+
/**
|
|
44
|
+
* Finishes after the current exchange: no further turns start. A turn waiting for an answer
|
|
45
|
+
* closes now; one that is listening finalizes first (then `end()` again, or `respond()`).
|
|
46
|
+
*/
|
|
47
|
+
end(): Promise<void>;
|
|
48
|
+
/** Stops everything now: speech, microphone, further turns. Ends with `cancelled`. Idempotent. */
|
|
49
|
+
cancel(): Promise<void>;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export interface ConversationOptions {
|
|
53
|
+
readonly connection: HelperConnection;
|
|
54
|
+
readonly provider: string;
|
|
55
|
+
readonly locale: string;
|
|
56
|
+
readonly engine: "analyzer" | "legacy" | undefined;
|
|
57
|
+
readonly bargeIn: boolean;
|
|
58
|
+
readonly halfDuplex: boolean;
|
|
59
|
+
readonly continuous: boolean;
|
|
60
|
+
/** Voice fields sent with every `turn-respond` (already on the helper's scale). */
|
|
61
|
+
readonly voice: { readonly voice?: string; readonly locale?: string; readonly rate?: number };
|
|
62
|
+
/** After `cancel()`, how long the helper gets to report the terminal before it is restarted. */
|
|
63
|
+
readonly terminalGraceMs: number;
|
|
64
|
+
readonly onStuck: () => void;
|
|
65
|
+
readonly onFinished: () => void;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
interface Turn {
|
|
69
|
+
readonly id: string;
|
|
70
|
+
state: string | undefined;
|
|
71
|
+
/** The host sent the answer's last chunk. */
|
|
72
|
+
final: boolean;
|
|
73
|
+
ended: boolean;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export class Conversation implements DesktopConversation {
|
|
77
|
+
readonly provider: string;
|
|
78
|
+
readonly locale: string;
|
|
79
|
+
private current: Turn | undefined;
|
|
80
|
+
private readonly queue: TurnEvent[] = [];
|
|
81
|
+
private waiter: ((result: IteratorResult<TurnEvent>) => void) | undefined;
|
|
82
|
+
private consumed = false;
|
|
83
|
+
private finished = false;
|
|
84
|
+
private ending = false;
|
|
85
|
+
private cancelling = false;
|
|
86
|
+
private graceTimer: ReturnType<typeof setTimeout> | undefined;
|
|
87
|
+
|
|
88
|
+
constructor(private readonly options: ConversationOptions) {
|
|
89
|
+
this.provider = options.provider;
|
|
90
|
+
this.locale = options.locale;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
get isFinished(): boolean {
|
|
94
|
+
return this.finished;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Starts the first turn; resolves once the microphone is open, rejects if the turn failed. */
|
|
98
|
+
async begin(): Promise<void> {
|
|
99
|
+
await this.startTurn();
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
events(): AsyncIterable<TurnEvent> {
|
|
103
|
+
if (this.consumed) throw new VoiceError("bad_request", "A conversation's events can be read once.");
|
|
104
|
+
this.consumed = true;
|
|
105
|
+
return {
|
|
106
|
+
[Symbol.asyncIterator]: () => ({
|
|
107
|
+
next: () => {
|
|
108
|
+
const next = this.queue.shift();
|
|
109
|
+
if (next) return Promise.resolve({ value: next, done: false });
|
|
110
|
+
if (this.finished) return Promise.resolve({ value: undefined, done: true } as IteratorResult<TurnEvent>);
|
|
111
|
+
return new Promise<IteratorResult<TurnEvent>>((resolve) => {
|
|
112
|
+
this.waiter = resolve;
|
|
113
|
+
});
|
|
114
|
+
},
|
|
115
|
+
return: async () => {
|
|
116
|
+
await this.cancel();
|
|
117
|
+
return { value: undefined, done: true } as IteratorResult<TurnEvent>;
|
|
118
|
+
},
|
|
119
|
+
}),
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
async respond(textChunk: string, options: ConversationRespondOptions = {}): Promise<void> {
|
|
124
|
+
const final = options.final ?? true;
|
|
125
|
+
if (this.finished || this.cancelling) throw new VoiceError("cancelled", "The conversation is over.");
|
|
126
|
+
const turn = this.current;
|
|
127
|
+
if (!turn || turn.ended) throw new VoiceError("bad_request", "No turn is waiting for an answer.");
|
|
128
|
+
if (turn.final) throw new VoiceError("bad_request", "This turn's answer is already complete.");
|
|
129
|
+
if (textChunk.length === 0 && !final) return;
|
|
130
|
+
if (final) turn.final = true;
|
|
131
|
+
await this.options.connection.send({
|
|
132
|
+
cmd: "turn-respond",
|
|
133
|
+
id: turn.id,
|
|
134
|
+
text: textChunk,
|
|
135
|
+
final,
|
|
136
|
+
...this.options.voice,
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async listen(): Promise<void> {
|
|
141
|
+
if (this.finished || this.cancelling) throw new VoiceError("cancelled", "The conversation is over.");
|
|
142
|
+
const turn = this.current;
|
|
143
|
+
if (turn && !turn.ended && turn.state === "speaking" && !this.options.bargeIn && this.options.halfDuplex) {
|
|
144
|
+
// The helper would refuse the new turn; refusing here keeps the playing turn current.
|
|
145
|
+
throw new VoiceError("busy", "The answer is still playing and barge-in is off.");
|
|
146
|
+
}
|
|
147
|
+
this.ending = false;
|
|
148
|
+
await this.startTurn();
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async stopListening(): Promise<void> {
|
|
152
|
+
const turn = this.current;
|
|
153
|
+
if (!turn || turn.ended || (turn.state !== "listening" && turn.state !== undefined)) return;
|
|
154
|
+
await this.options.connection.send({ cmd: "turn-end", id: turn.id }).catch(() => undefined);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
async end(): Promise<void> {
|
|
158
|
+
if (this.finished) return;
|
|
159
|
+
this.ending = true;
|
|
160
|
+
const turn = this.current;
|
|
161
|
+
if (!turn || turn.ended) return this.finish();
|
|
162
|
+
await this.options.connection.send({ cmd: "turn-end", id: turn.id }).catch(() => undefined);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async cancel(): Promise<void> {
|
|
166
|
+
if (this.finished || this.cancelling) return;
|
|
167
|
+
this.cancelling = true;
|
|
168
|
+
const turn = this.current;
|
|
169
|
+
if (!turn || turn.ended) {
|
|
170
|
+
this.push({ type: "cancelled" });
|
|
171
|
+
return this.finish();
|
|
172
|
+
}
|
|
173
|
+
await this.options.connection.send({ cmd: "turn-cancel", id: turn.id }).catch(() => undefined);
|
|
174
|
+
// A helper that never answers is restarted; the conversation still ends exactly once.
|
|
175
|
+
this.graceTimer ??= setTimeout(() => {
|
|
176
|
+
if (this.finished) return;
|
|
177
|
+
this.closeTurn(turn, { type: "ended", reason: "cancelled", turn: turn.id });
|
|
178
|
+
this.push({ type: "cancelled" });
|
|
179
|
+
this.finish();
|
|
180
|
+
this.options.onStuck();
|
|
181
|
+
}, this.options.terminalGraceMs);
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// MARK: - Turns
|
|
185
|
+
|
|
186
|
+
private startTurn(): Promise<void> {
|
|
187
|
+
const turn: Turn = { id: nextRequestId("turn-"), state: undefined, final: false, ended: false };
|
|
188
|
+
this.current = turn;
|
|
189
|
+
let settleStart!: { resolve: () => void; reject: (error: VoiceError) => void };
|
|
190
|
+
const started = new Promise<void>((resolve, reject) => {
|
|
191
|
+
settleStart = { resolve, reject };
|
|
192
|
+
});
|
|
193
|
+
this.options.connection
|
|
194
|
+
.request(
|
|
195
|
+
{
|
|
196
|
+
cmd: "turn-start",
|
|
197
|
+
id: turn.id,
|
|
198
|
+
locale: this.locale,
|
|
199
|
+
...(this.options.engine ? { engine: this.options.engine } : {}),
|
|
200
|
+
bargeIn: this.options.bargeIn,
|
|
201
|
+
halfDuplex: this.options.halfDuplex,
|
|
202
|
+
},
|
|
203
|
+
isTurnTerminal,
|
|
204
|
+
{
|
|
205
|
+
timeoutMs: null,
|
|
206
|
+
onEvent: (event) => {
|
|
207
|
+
this.forward(turn, event);
|
|
208
|
+
if (event.event === "turn-state" && event.state === "listening") settleStart.resolve();
|
|
209
|
+
},
|
|
210
|
+
},
|
|
211
|
+
)
|
|
212
|
+
.then(
|
|
213
|
+
(terminal) => {
|
|
214
|
+
if (terminal.event === "turn-error") {
|
|
215
|
+
settleStart.reject(new VoiceError(terminal.code, terminal.message ?? "The turn failed."));
|
|
216
|
+
} else {
|
|
217
|
+
settleStart.resolve();
|
|
218
|
+
}
|
|
219
|
+
this.afterTerminal(turn);
|
|
220
|
+
},
|
|
221
|
+
(error: unknown) => {
|
|
222
|
+
// The helper crashed, refused the command or was stopped: the turn still ends once.
|
|
223
|
+
const typed = VoiceError.wrapping(error);
|
|
224
|
+
this.closeTurn(turn, { type: "failed", error: typed, turn: turn.id });
|
|
225
|
+
settleStart.reject(typed);
|
|
226
|
+
this.afterTerminal(turn);
|
|
227
|
+
},
|
|
228
|
+
);
|
|
229
|
+
// `begin()`/`listen()` callers see the failure; the events stream has it too.
|
|
230
|
+
started.catch(() => undefined);
|
|
231
|
+
return started;
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Maps one helper line of this turn to the shared vocabulary. */
|
|
235
|
+
private forward(turn: Turn, event: WireEvent): void {
|
|
236
|
+
if (turn.ended) return;
|
|
237
|
+
const tag = { turn: turn.id };
|
|
238
|
+
switch (event.event) {
|
|
239
|
+
case "turn-state":
|
|
240
|
+
turn.state = event.state;
|
|
241
|
+
switch (event.state) {
|
|
242
|
+
case "listening":
|
|
243
|
+
case "responding":
|
|
244
|
+
case "speaking":
|
|
245
|
+
case "idle":
|
|
246
|
+
if (event.state === "idle") turn.final = false; // the host may answer again
|
|
247
|
+
return this.push({ type: event.state, ...tag });
|
|
248
|
+
case "interrupted":
|
|
249
|
+
return; // `barge-in` already said it
|
|
250
|
+
case "ended":
|
|
251
|
+
return this.closeTurn(turn, { type: "ended", reason: event.reason ?? "completed", ...tag });
|
|
252
|
+
}
|
|
253
|
+
return;
|
|
254
|
+
case "turn-partial":
|
|
255
|
+
return this.push({
|
|
256
|
+
type: "partial",
|
|
257
|
+
partial: { finalizedText: event.finalizedText, volatileText: event.volatileText, sequence: event.sequence },
|
|
258
|
+
...tag,
|
|
259
|
+
});
|
|
260
|
+
case "turn-transcript":
|
|
261
|
+
return this.push({ type: "transcript", text: event.text, ...tag });
|
|
262
|
+
case "turn-barge-in":
|
|
263
|
+
return this.push({ type: "barge-in", ...tag });
|
|
264
|
+
case "turn-speech-started":
|
|
265
|
+
return this.push({ type: "speech-started", utterance: event.utterance, ...tag });
|
|
266
|
+
case "turn-speech-finished":
|
|
267
|
+
return this.push({ type: "speech-finished", utterance: event.utterance, ...tag });
|
|
268
|
+
case "turn-speech-cancelled":
|
|
269
|
+
return this.push({ type: "speech-cancelled", utterance: event.utterance, ...tag });
|
|
270
|
+
case "turn-metrics":
|
|
271
|
+
return this.push({
|
|
272
|
+
type: "metrics",
|
|
273
|
+
metrics: {
|
|
274
|
+
firstPartialMs: event.firstPartialMs,
|
|
275
|
+
transcriptMs: event.transcriptMs,
|
|
276
|
+
firstAudioMs: event.firstAudioMs,
|
|
277
|
+
speechFinishedMs: event.speechFinishedMs,
|
|
278
|
+
},
|
|
279
|
+
...tag,
|
|
280
|
+
});
|
|
281
|
+
case "turn-error":
|
|
282
|
+
return this.closeTurn(turn, {
|
|
283
|
+
type: "failed",
|
|
284
|
+
error: new VoiceError(event.code, event.message ?? "The turn failed."),
|
|
285
|
+
...tag,
|
|
286
|
+
});
|
|
287
|
+
default:
|
|
288
|
+
return; // `idle` answers to a late command; nothing to report
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
private closeTurn(turn: Turn, terminal: TurnEvent): void {
|
|
293
|
+
if (turn.ended) return;
|
|
294
|
+
turn.ended = true;
|
|
295
|
+
this.push(terminal);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** What the conversation does once a turn has ended. */
|
|
299
|
+
private afterTerminal(turn: Turn): void {
|
|
300
|
+
const reason = this.reasons.get(turn.id);
|
|
301
|
+
this.reasons.delete(turn.id);
|
|
302
|
+
// A turn that a newer one replaced (barge-in, `listen()`) has nothing more to decide.
|
|
303
|
+
if (turn !== this.current || this.finished) return;
|
|
304
|
+
this.current = undefined;
|
|
305
|
+
if (this.cancelling || reason === "cancelled") {
|
|
306
|
+
this.push({ type: "cancelled" });
|
|
307
|
+
return this.finish();
|
|
308
|
+
}
|
|
309
|
+
if (reason === "failed" || this.ending) return this.finish();
|
|
310
|
+
if (reason === "completed" && this.options.continuous) {
|
|
311
|
+
void this.startTurn().catch(() => undefined);
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
/** How each turn ended (`failed` for an error), until the conversation has acted on it. */
|
|
316
|
+
private readonly reasons = new Map<string, string>();
|
|
317
|
+
|
|
318
|
+
private finish(): void {
|
|
319
|
+
if (this.finished) return;
|
|
320
|
+
this.finished = true;
|
|
321
|
+
clearTimeout(this.graceTimer);
|
|
322
|
+
this.options.onFinished();
|
|
323
|
+
if (this.queue.length === 0 && this.waiter) {
|
|
324
|
+
const waiter = this.waiter;
|
|
325
|
+
this.waiter = undefined;
|
|
326
|
+
waiter({ value: undefined, done: true } as IteratorResult<TurnEvent>);
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
private push(event: TurnEvent): void {
|
|
331
|
+
if (event.type === "ended" && event.turn) this.reasons.set(event.turn, event.reason);
|
|
332
|
+
if (event.type === "failed" && event.turn) this.reasons.set(event.turn, "failed");
|
|
333
|
+
if (this.finished) return;
|
|
334
|
+
if (this.waiter) {
|
|
335
|
+
const waiter = this.waiter;
|
|
336
|
+
this.waiter = undefined;
|
|
337
|
+
waiter({ value: event, done: false });
|
|
338
|
+
return;
|
|
339
|
+
}
|
|
340
|
+
// Bounded: partials replace each other, so only the latest pending partial is kept.
|
|
341
|
+
if (event.type === "partial") {
|
|
342
|
+
const last = this.queue.at(-1);
|
|
343
|
+
if (last?.type === "partial" && last.turn === event.turn) this.queue.pop();
|
|
344
|
+
}
|
|
345
|
+
this.queue.push(event);
|
|
346
|
+
}
|
|
347
|
+
}
|