@runtypelabs/voice 0.2.3
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/LICENSE +21 -0
- package/README.md +147 -0
- package/dist/index.cjs +488 -0
- package/dist/index.d.cts +41 -0
- package/dist/index.d.ts +41 -0
- package/dist/index.js +465 -0
- package/dist/persona.cjs +580 -0
- package/dist/persona.d.cts +7 -0
- package/dist/persona.d.ts +7 -0
- package/dist/persona.js +557 -0
- package/dist/react.cjs +515 -0
- package/dist/react.d.cts +27 -0
- package/dist/react.d.ts +27 -0
- package/dist/react.js +495 -0
- package/dist/types-9SfA7oHc.d.cts +40 -0
- package/dist/types-9SfA7oHc.d.ts +40 -0
- package/package.json +73 -0
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { V as VoiceClientOptions, a as VoiceSnapshot } from './types-9SfA7oHc.js';
|
|
2
|
+
export { I as InterruptionMode, T as TranscriptEntry, b as VoiceMetrics, c as VoiceStatus } from './types-9SfA7oHc.js';
|
|
3
|
+
|
|
4
|
+
/** Browser microphone and playback lifecycle for Runtype's voice WebSocket endpoint. */
|
|
5
|
+
declare class VoiceClient {
|
|
6
|
+
private readonly options;
|
|
7
|
+
private snapshot;
|
|
8
|
+
private readonly listeners;
|
|
9
|
+
private socket;
|
|
10
|
+
private context;
|
|
11
|
+
private stream;
|
|
12
|
+
private source;
|
|
13
|
+
private processor;
|
|
14
|
+
private player;
|
|
15
|
+
private generation;
|
|
16
|
+
private playbackRevision;
|
|
17
|
+
private pushChain;
|
|
18
|
+
private awaitingClear;
|
|
19
|
+
private stoppedResponse;
|
|
20
|
+
private responseEnded;
|
|
21
|
+
private hasPendingAudio;
|
|
22
|
+
constructor(options: VoiceClientOptions);
|
|
23
|
+
getSnapshot: () => VoiceSnapshot;
|
|
24
|
+
subscribe: (listener: () => void) => (() => void);
|
|
25
|
+
private update;
|
|
26
|
+
private setStatus;
|
|
27
|
+
/** Acquire microphone access and open a call. Invoke from a user gesture. Failures populate snapshot.error. */
|
|
28
|
+
startCall: (tokenOverride?: string) => Promise<void>;
|
|
29
|
+
endCall: () => void;
|
|
30
|
+
toggleMute: () => void;
|
|
31
|
+
cancelResponse: () => void;
|
|
32
|
+
/** Stop the current reply explicitly, including local playback when interruptions are disabled. */
|
|
33
|
+
stopPlayback: () => void;
|
|
34
|
+
private fail;
|
|
35
|
+
private cleanup;
|
|
36
|
+
private clearPlayback;
|
|
37
|
+
private handleMessage;
|
|
38
|
+
private startCapture;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export { VoiceClient, VoiceClientOptions, VoiceSnapshot };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,465 @@
|
|
|
1
|
+
// src/pcm-player.ts
|
|
2
|
+
var PCM_SAMPLE_RATE = 24e3;
|
|
3
|
+
var PCM_WATERLINE_SAMPLES = 3600;
|
|
4
|
+
var PCM_PLAYER_WORKLET = `
|
|
5
|
+
class RuntypePcmPlayerProcessor extends AudioWorkletProcessor {
|
|
6
|
+
constructor() {
|
|
7
|
+
super()
|
|
8
|
+
this.chunks = []
|
|
9
|
+
this.readOffset = 0
|
|
10
|
+
this.buffered = 0
|
|
11
|
+
this.waiting = true
|
|
12
|
+
// INVARIANT: Only report drained after end-of-stream, never during a jitter gap.
|
|
13
|
+
this.eosSeen = false
|
|
14
|
+
this.revision = 0
|
|
15
|
+
this.port.onmessage = (e) => {
|
|
16
|
+
const msg = e.data
|
|
17
|
+
this.revision = msg.revision
|
|
18
|
+
if (msg.type === 'push') {
|
|
19
|
+
this.eosSeen = false
|
|
20
|
+
this.chunks.push(msg.samples)
|
|
21
|
+
this.buffered += msg.samples.length
|
|
22
|
+
if (this.waiting && this.buffered >= ${PCM_WATERLINE_SAMPLES}) {
|
|
23
|
+
this.waiting = false
|
|
24
|
+
}
|
|
25
|
+
} else if (msg.type === 'eos') {
|
|
26
|
+
this.eosSeen = true
|
|
27
|
+
// INVARIANT: Short replies drain even below the waterline.
|
|
28
|
+
if (this.waiting && this.buffered > 0) this.waiting = false
|
|
29
|
+
// INVARIANT: An empty completed stream reports drained immediately.
|
|
30
|
+
if (this.buffered === 0) {
|
|
31
|
+
this.eosSeen = false
|
|
32
|
+
this.port.postMessage({ type: 'drained', revision: this.revision })
|
|
33
|
+
}
|
|
34
|
+
} else if (msg.type === 'clear') {
|
|
35
|
+
this.chunks = []
|
|
36
|
+
this.readOffset = 0
|
|
37
|
+
this.buffered = 0
|
|
38
|
+
this.waiting = true
|
|
39
|
+
this.eosSeen = false
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
process(inputs, outputs) {
|
|
44
|
+
const out = outputs[0][0]
|
|
45
|
+
if (!out || this.waiting) return true // outputs are pre-zeroed: silence
|
|
46
|
+
let i = 0
|
|
47
|
+
while (i < out.length && this.buffered > 0) {
|
|
48
|
+
const chunk = this.chunks[0]
|
|
49
|
+
out[i++] = chunk[this.readOffset++]
|
|
50
|
+
this.buffered--
|
|
51
|
+
if (this.readOffset >= chunk.length) {
|
|
52
|
+
this.chunks.shift()
|
|
53
|
+
this.readOffset = 0
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
if (this.buffered === 0) {
|
|
57
|
+
this.waiting = true // mid-reply underrun: re-buffer silently
|
|
58
|
+
if (this.eosSeen) {
|
|
59
|
+
this.eosSeen = false
|
|
60
|
+
this.port.postMessage({ type: 'drained', revision: this.revision })
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return true
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
registerProcessor('runtype-pcm-player', RuntypePcmPlayerProcessor)
|
|
67
|
+
`;
|
|
68
|
+
async function createPcmPlayer(onDrained) {
|
|
69
|
+
let revision = 0;
|
|
70
|
+
const context = new AudioContext({ sampleRate: PCM_SAMPLE_RATE });
|
|
71
|
+
const moduleUrl = URL.createObjectURL(
|
|
72
|
+
new Blob([PCM_PLAYER_WORKLET], { type: "application/javascript" })
|
|
73
|
+
);
|
|
74
|
+
try {
|
|
75
|
+
if (context.state === "suspended") await context.resume();
|
|
76
|
+
await context.audioWorklet.addModule(moduleUrl);
|
|
77
|
+
} catch (err) {
|
|
78
|
+
context.close().catch(() => {
|
|
79
|
+
});
|
|
80
|
+
throw err;
|
|
81
|
+
} finally {
|
|
82
|
+
URL.revokeObjectURL(moduleUrl);
|
|
83
|
+
}
|
|
84
|
+
const node = new AudioWorkletNode(context, "runtype-pcm-player", {
|
|
85
|
+
numberOfInputs: 0,
|
|
86
|
+
numberOfOutputs: 1,
|
|
87
|
+
outputChannelCount: [1]
|
|
88
|
+
});
|
|
89
|
+
node.port.onmessage = (e) => {
|
|
90
|
+
if (e.data?.type === "drained" && e.data.revision === revision) onDrained();
|
|
91
|
+
};
|
|
92
|
+
node.connect(context.destination);
|
|
93
|
+
return {
|
|
94
|
+
async push(data) {
|
|
95
|
+
const pushRevision = revision;
|
|
96
|
+
const buffer = data instanceof Blob ? await data.arrayBuffer() : data;
|
|
97
|
+
if (pushRevision !== revision) return;
|
|
98
|
+
const samples = pcm16FrameToFloat32(buffer);
|
|
99
|
+
if (samples.length === 0) return;
|
|
100
|
+
node.port.postMessage({ type: "push", samples, revision }, [samples.buffer]);
|
|
101
|
+
},
|
|
102
|
+
endOfStream() {
|
|
103
|
+
node.port.postMessage({ type: "eos", revision });
|
|
104
|
+
},
|
|
105
|
+
clear() {
|
|
106
|
+
revision += 1;
|
|
107
|
+
node.port.postMessage({ type: "clear", revision });
|
|
108
|
+
},
|
|
109
|
+
close() {
|
|
110
|
+
revision += 1;
|
|
111
|
+
node.port.onmessage = null;
|
|
112
|
+
node.disconnect();
|
|
113
|
+
context.close().catch(() => {
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
function pcm16FrameToFloat32(buffer) {
|
|
119
|
+
const view = new DataView(buffer);
|
|
120
|
+
let offset = 0;
|
|
121
|
+
if (buffer.byteLength >= 44 && view.getUint32(0, false) === 1380533830) {
|
|
122
|
+
offset = 44;
|
|
123
|
+
}
|
|
124
|
+
const sampleCount = Math.floor((buffer.byteLength - offset) / 2);
|
|
125
|
+
const out = new Float32Array(sampleCount);
|
|
126
|
+
for (let i = 0; i < sampleCount; i++) {
|
|
127
|
+
out[i] = view.getInt16(offset + i * 2, true) / 32768;
|
|
128
|
+
}
|
|
129
|
+
return out;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// src/voice-client.ts
|
|
133
|
+
var CAPTURE_SAMPLE_RATE = 16e3;
|
|
134
|
+
var CAPTURE_BUFFER_SIZE = 4096;
|
|
135
|
+
function initialSnapshot() {
|
|
136
|
+
return {
|
|
137
|
+
status: "idle",
|
|
138
|
+
transcript: [],
|
|
139
|
+
interimTranscript: null,
|
|
140
|
+
metrics: null,
|
|
141
|
+
audioLevel: 0,
|
|
142
|
+
isMuted: false,
|
|
143
|
+
error: null,
|
|
144
|
+
errorDetails: void 0,
|
|
145
|
+
interruptionMode: "none",
|
|
146
|
+
canCancel: false
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
var VoiceClient = class {
|
|
150
|
+
constructor(options) {
|
|
151
|
+
this.options = options;
|
|
152
|
+
}
|
|
153
|
+
options;
|
|
154
|
+
snapshot = initialSnapshot();
|
|
155
|
+
listeners = /* @__PURE__ */ new Set();
|
|
156
|
+
socket = null;
|
|
157
|
+
context = null;
|
|
158
|
+
stream = null;
|
|
159
|
+
source = null;
|
|
160
|
+
processor = null;
|
|
161
|
+
player = null;
|
|
162
|
+
generation = 0;
|
|
163
|
+
playbackRevision = 0;
|
|
164
|
+
pushChain = Promise.resolve();
|
|
165
|
+
awaitingClear = false;
|
|
166
|
+
stoppedResponse = false;
|
|
167
|
+
responseEnded = true;
|
|
168
|
+
hasPendingAudio = false;
|
|
169
|
+
getSnapshot = () => this.snapshot;
|
|
170
|
+
subscribe = (listener) => {
|
|
171
|
+
this.listeners.add(listener);
|
|
172
|
+
return () => {
|
|
173
|
+
this.listeners.delete(listener);
|
|
174
|
+
};
|
|
175
|
+
};
|
|
176
|
+
update(patch) {
|
|
177
|
+
const next = { ...this.snapshot, ...patch };
|
|
178
|
+
next.canCancel = !this.awaitingClear && next.interruptionMode !== "none" && (next.status === "speaking" || next.status === "thinking");
|
|
179
|
+
this.snapshot = next;
|
|
180
|
+
for (const listener of this.listeners) listener();
|
|
181
|
+
}
|
|
182
|
+
setStatus(status) {
|
|
183
|
+
this.update({ status });
|
|
184
|
+
}
|
|
185
|
+
/** Acquire microphone access and open a call. Invoke from a user gesture. Failures populate snapshot.error. */
|
|
186
|
+
startCall = async (tokenOverride) => {
|
|
187
|
+
if (this.snapshot.status !== "idle" && this.snapshot.status !== "error") return;
|
|
188
|
+
this.cleanup();
|
|
189
|
+
const generation = this.generation;
|
|
190
|
+
this.update({ ...initialSnapshot(), status: "connecting" });
|
|
191
|
+
try {
|
|
192
|
+
const token = tokenOverride ?? (typeof this.options.clientToken === "function" ? await this.options.clientToken() : this.options.clientToken);
|
|
193
|
+
if (generation !== this.generation) return;
|
|
194
|
+
if (!token) throw new Error("Voice token unavailable. Please retry.");
|
|
195
|
+
if (!this.options.agentId) throw new Error("Voice requires an agentId.");
|
|
196
|
+
const url = new URL(this.options.apiUrl ?? "https://api.runtype.com");
|
|
197
|
+
if (!["https:", "http:", "wss:", "ws:"].includes(url.protocol) || url.username || url.password) {
|
|
198
|
+
throw new Error("Voice requires an HTTP or WebSocket API base URL without credentials.");
|
|
199
|
+
}
|
|
200
|
+
url.protocol = url.protocol === "https:" || url.protocol === "wss:" ? "wss:" : "ws:";
|
|
201
|
+
const basePath = url.pathname.replace(/\/+$/, "");
|
|
202
|
+
url.pathname = `${basePath}/ws/agents/${encodeURIComponent(this.options.agentId)}/voice`;
|
|
203
|
+
url.search = "";
|
|
204
|
+
url.searchParams.set("voiceProtocol", "runtype-browser-v1");
|
|
205
|
+
url.hash = "";
|
|
206
|
+
const stream = await navigator.mediaDevices.getUserMedia({
|
|
207
|
+
audio: { sampleRate: CAPTURE_SAMPLE_RATE, channelCount: 1, echoCancellation: true }
|
|
208
|
+
});
|
|
209
|
+
if (generation !== this.generation) {
|
|
210
|
+
stream.getTracks().forEach((track) => track.stop());
|
|
211
|
+
return;
|
|
212
|
+
}
|
|
213
|
+
this.stream = stream;
|
|
214
|
+
const context = new AudioContext({ sampleRate: CAPTURE_SAMPLE_RATE });
|
|
215
|
+
this.context = context;
|
|
216
|
+
if (context.state === "suspended") await context.resume();
|
|
217
|
+
if (generation !== this.generation) return;
|
|
218
|
+
const player = await createPcmPlayer(() => {
|
|
219
|
+
if (generation !== this.generation) return;
|
|
220
|
+
this.hasPendingAudio = false;
|
|
221
|
+
if (this.snapshot.status === "speaking") this.setStatus("listening");
|
|
222
|
+
});
|
|
223
|
+
if (generation !== this.generation) {
|
|
224
|
+
player.close();
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
this.player = player;
|
|
228
|
+
const socket = new WebSocket(url.toString(), ["runtype.bearer", token]);
|
|
229
|
+
socket.binaryType = "arraybuffer";
|
|
230
|
+
this.socket = socket;
|
|
231
|
+
socket.onopen = () => {
|
|
232
|
+
if (generation !== this.generation) return;
|
|
233
|
+
try {
|
|
234
|
+
this.startCapture(context, stream, socket, generation);
|
|
235
|
+
this.setStatus("listening");
|
|
236
|
+
} catch (error) {
|
|
237
|
+
this.fail(error);
|
|
238
|
+
}
|
|
239
|
+
};
|
|
240
|
+
socket.onmessage = (event) => {
|
|
241
|
+
if (generation === this.generation) this.handleMessage(event.data, player);
|
|
242
|
+
};
|
|
243
|
+
socket.onerror = () => {
|
|
244
|
+
if (generation === this.generation) this.fail(new Error("Voice connection failed"));
|
|
245
|
+
};
|
|
246
|
+
socket.onclose = (event) => {
|
|
247
|
+
if (generation !== this.generation) return;
|
|
248
|
+
if (event.code === 1e3) this.endCall();
|
|
249
|
+
else this.fail(new Error(`Connection closed: ${event.reason || "unknown reason"}`));
|
|
250
|
+
};
|
|
251
|
+
} catch (error) {
|
|
252
|
+
if (generation === this.generation) this.fail(error);
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
endCall = () => {
|
|
256
|
+
this.cleanup();
|
|
257
|
+
this.update({ status: "idle", interimTranscript: null, audioLevel: 0, isMuted: false });
|
|
258
|
+
};
|
|
259
|
+
toggleMute = () => {
|
|
260
|
+
this.update({ isMuted: !this.snapshot.isMuted, audioLevel: 0 });
|
|
261
|
+
};
|
|
262
|
+
cancelResponse = () => {
|
|
263
|
+
if (!this.snapshot.canCancel) return;
|
|
264
|
+
this.stopPlayback();
|
|
265
|
+
};
|
|
266
|
+
/** Stop the current reply explicitly, including local playback when interruptions are disabled. */
|
|
267
|
+
stopPlayback = () => {
|
|
268
|
+
if (this.awaitingClear || this.socket?.readyState !== WebSocket.OPEN || !["speaking", "thinking"].includes(this.snapshot.status))
|
|
269
|
+
return;
|
|
270
|
+
this.clearPlayback();
|
|
271
|
+
if (this.snapshot.interruptionMode === "none") {
|
|
272
|
+
this.stoppedResponse = !this.responseEnded;
|
|
273
|
+
this.setStatus("listening");
|
|
274
|
+
return;
|
|
275
|
+
}
|
|
276
|
+
this.awaitingClear = true;
|
|
277
|
+
this.setStatus("listening");
|
|
278
|
+
this.socket.send(JSON.stringify({ type: "cancel" }));
|
|
279
|
+
};
|
|
280
|
+
fail(error) {
|
|
281
|
+
this.cleanup();
|
|
282
|
+
const denied = error instanceof Error && (error.name === "NotAllowedError" || /Permission denied|NotAllowed/.test(error.message));
|
|
283
|
+
this.update({
|
|
284
|
+
status: "error",
|
|
285
|
+
errorDetails: void 0,
|
|
286
|
+
audioLevel: 0,
|
|
287
|
+
interimTranscript: null,
|
|
288
|
+
error: denied ? "Microphone access denied. Please check browser permissions." : error instanceof Error ? error.message : "Failed to start voice call"
|
|
289
|
+
});
|
|
290
|
+
}
|
|
291
|
+
cleanup() {
|
|
292
|
+
this.generation += 1;
|
|
293
|
+
if (this.processor) this.processor.onaudioprocess = null;
|
|
294
|
+
this.processor?.disconnect();
|
|
295
|
+
this.processor = null;
|
|
296
|
+
this.source?.disconnect();
|
|
297
|
+
this.source = null;
|
|
298
|
+
this.stream?.getTracks().forEach((track) => track.stop());
|
|
299
|
+
this.stream = null;
|
|
300
|
+
void this.context?.close().catch(() => {
|
|
301
|
+
});
|
|
302
|
+
this.context = null;
|
|
303
|
+
this.player?.close();
|
|
304
|
+
this.player = null;
|
|
305
|
+
const socket = this.socket;
|
|
306
|
+
this.socket = null;
|
|
307
|
+
if (socket) {
|
|
308
|
+
socket.onopen = socket.onmessage = socket.onerror = socket.onclose = null;
|
|
309
|
+
socket.close(1e3, "User ended call");
|
|
310
|
+
}
|
|
311
|
+
this.playbackRevision += 1;
|
|
312
|
+
this.pushChain = Promise.resolve();
|
|
313
|
+
this.hasPendingAudio = false;
|
|
314
|
+
this.awaitingClear = false;
|
|
315
|
+
this.stoppedResponse = false;
|
|
316
|
+
this.responseEnded = true;
|
|
317
|
+
}
|
|
318
|
+
clearPlayback() {
|
|
319
|
+
this.playbackRevision += 1;
|
|
320
|
+
this.pushChain = Promise.resolve();
|
|
321
|
+
this.player?.clear();
|
|
322
|
+
this.hasPendingAudio = false;
|
|
323
|
+
}
|
|
324
|
+
handleMessage(data, player) {
|
|
325
|
+
if (data instanceof ArrayBuffer || data instanceof Blob) {
|
|
326
|
+
if (this.awaitingClear || this.stoppedResponse) return;
|
|
327
|
+
this.responseEnded = false;
|
|
328
|
+
this.hasPendingAudio = true;
|
|
329
|
+
this.setStatus("speaking");
|
|
330
|
+
const revision = this.playbackRevision;
|
|
331
|
+
this.pushChain = this.pushChain.then(async () => {
|
|
332
|
+
if (revision !== this.playbackRevision) return;
|
|
333
|
+
try {
|
|
334
|
+
await player.push(data);
|
|
335
|
+
} catch (error) {
|
|
336
|
+
if (revision === this.playbackRevision) this.fail(error);
|
|
337
|
+
}
|
|
338
|
+
});
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
if (typeof data !== "string") return;
|
|
342
|
+
let msg;
|
|
343
|
+
try {
|
|
344
|
+
const parsed = JSON.parse(data);
|
|
345
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return;
|
|
346
|
+
msg = parsed;
|
|
347
|
+
} catch {
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
switch (msg.type) {
|
|
351
|
+
case "session_config":
|
|
352
|
+
if (msg.interruptionMode === "none" || msg.interruptionMode === "cancel" || msg.interruptionMode === "barge-in") {
|
|
353
|
+
this.update({ interruptionMode: msg.interruptionMode });
|
|
354
|
+
}
|
|
355
|
+
break;
|
|
356
|
+
case "transcript_interim":
|
|
357
|
+
this.update({ interimTranscript: typeof msg.text === "string" ? msg.text || null : null });
|
|
358
|
+
break;
|
|
359
|
+
case "transcript_final":
|
|
360
|
+
if (typeof msg.text !== "string" || msg.role !== "user" && msg.role !== "assistant") break;
|
|
361
|
+
if (msg.role === "assistant" && (this.awaitingClear || this.stoppedResponse)) break;
|
|
362
|
+
this.responseEnded = false;
|
|
363
|
+
this.update({
|
|
364
|
+
interimTranscript: null,
|
|
365
|
+
transcript: [
|
|
366
|
+
...this.snapshot.transcript,
|
|
367
|
+
{
|
|
368
|
+
role: msg.role,
|
|
369
|
+
content: msg.text,
|
|
370
|
+
timestamp: Date.now(),
|
|
371
|
+
...typeof msg.turnId === "string" && msg.turnId ? { turnId: msg.turnId } : {}
|
|
372
|
+
}
|
|
373
|
+
],
|
|
374
|
+
status: this.awaitingClear ? this.snapshot.status : msg.role === "user" ? "thinking" : "speaking"
|
|
375
|
+
});
|
|
376
|
+
break;
|
|
377
|
+
case "audio_end": {
|
|
378
|
+
this.responseEnded = true;
|
|
379
|
+
if (this.stoppedResponse) {
|
|
380
|
+
this.stoppedResponse = false;
|
|
381
|
+
break;
|
|
382
|
+
}
|
|
383
|
+
if (this.awaitingClear) break;
|
|
384
|
+
const revision = this.playbackRevision;
|
|
385
|
+
this.pushChain = this.pushChain.then(() => {
|
|
386
|
+
if (revision === this.playbackRevision) player.endOfStream();
|
|
387
|
+
});
|
|
388
|
+
if (!this.hasPendingAudio && this.snapshot.status === "speaking")
|
|
389
|
+
this.setStatus("listening");
|
|
390
|
+
break;
|
|
391
|
+
}
|
|
392
|
+
case "audio_clear":
|
|
393
|
+
this.clearPlayback();
|
|
394
|
+
this.awaitingClear = false;
|
|
395
|
+
this.stoppedResponse = false;
|
|
396
|
+
this.responseEnded = true;
|
|
397
|
+
this.setStatus("listening");
|
|
398
|
+
break;
|
|
399
|
+
case "metrics": {
|
|
400
|
+
const number = (value) => typeof value === "number" && Number.isFinite(value) ? value : void 0;
|
|
401
|
+
this.update({
|
|
402
|
+
metrics: {
|
|
403
|
+
llmMs: number(msg.llm_ms),
|
|
404
|
+
// @snake-case-ok: Existing voice wire contract.
|
|
405
|
+
ttsMs: number(msg.tts_ms),
|
|
406
|
+
// @snake-case-ok: Existing voice wire contract.
|
|
407
|
+
firstAudioMs: number(msg.first_audio_ms),
|
|
408
|
+
// @snake-case-ok: Existing voice wire contract.
|
|
409
|
+
totalMs: number(msg.total_ms)
|
|
410
|
+
// @snake-case-ok: Existing voice wire contract.
|
|
411
|
+
}
|
|
412
|
+
});
|
|
413
|
+
break;
|
|
414
|
+
}
|
|
415
|
+
case "error": {
|
|
416
|
+
const details = msg.details;
|
|
417
|
+
this.fail(
|
|
418
|
+
new Error(
|
|
419
|
+
typeof msg.error === "string" ? msg.error : typeof msg.message === "string" ? msg.message : "Voice error"
|
|
420
|
+
)
|
|
421
|
+
);
|
|
422
|
+
if (details && typeof details.code === "string" && details.code.startsWith("MCP_") && typeof details.serverName === "string" && typeof details.diagnosticId === "string") {
|
|
423
|
+
this.update({
|
|
424
|
+
errorDetails: {
|
|
425
|
+
code: details.code,
|
|
426
|
+
...typeof details.serverId === "string" ? { serverId: details.serverId } : {},
|
|
427
|
+
serverName: details.serverName,
|
|
428
|
+
diagnosticId: details.diagnosticId
|
|
429
|
+
}
|
|
430
|
+
});
|
|
431
|
+
}
|
|
432
|
+
break;
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
startCapture(context, stream, socket, generation) {
|
|
437
|
+
const source = context.createMediaStreamSource(stream);
|
|
438
|
+
this.source = source;
|
|
439
|
+
const processor = context.createScriptProcessor(CAPTURE_BUFFER_SIZE, 1, 1);
|
|
440
|
+
this.processor = processor;
|
|
441
|
+
processor.onaudioprocess = (event) => {
|
|
442
|
+
if (generation !== this.generation || this.snapshot.isMuted) return;
|
|
443
|
+
const input = event.inputBuffer.getChannelData(0);
|
|
444
|
+
let sum = 0;
|
|
445
|
+
for (const sample of input) sum += sample * sample;
|
|
446
|
+
this.update({ audioLevel: Math.sqrt(sum / input.length) });
|
|
447
|
+
if (socket.readyState !== WebSocket.OPEN) return;
|
|
448
|
+
const pcm = new Int16Array(input.length);
|
|
449
|
+
if (this.snapshot.interruptionMode === "cancel" && (this.awaitingClear || this.snapshot.status === "thinking" || this.hasPendingAudio || this.snapshot.status === "speaking")) {
|
|
450
|
+
socket.send(pcm.buffer);
|
|
451
|
+
return;
|
|
452
|
+
}
|
|
453
|
+
for (let i = 0; i < input.length; i++) {
|
|
454
|
+
const sample = Math.max(-1, Math.min(1, input[i]));
|
|
455
|
+
pcm[i] = sample < 0 ? sample * 32768 : sample * 32767;
|
|
456
|
+
}
|
|
457
|
+
socket.send(pcm.buffer);
|
|
458
|
+
};
|
|
459
|
+
source.connect(processor);
|
|
460
|
+
processor.connect(context.destination);
|
|
461
|
+
}
|
|
462
|
+
};
|
|
463
|
+
export {
|
|
464
|
+
VoiceClient
|
|
465
|
+
};
|