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