@guideai/react-native 0.8.0 → 0.9.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 +19 -0
- package/dist/GuideAIChat-BFu10t6D.cjs +2794 -0
- package/dist/GuideAIChat-BFu10t6D.cjs.map +1 -0
- package/dist/GuideAIChat-BQQ8lUKs.js +2795 -0
- package/dist/GuideAIChat-BQQ8lUKs.js.map +1 -0
- package/dist/GuideAIChat-CNmEo5bZ.cjs +2794 -0
- package/dist/GuideAIChat-CNmEo5bZ.cjs.map +1 -0
- package/dist/GuideAIChat-SU0CVNby.js +2795 -0
- package/dist/GuideAIChat-SU0CVNby.js.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +61 -6
- package/dist/index.mjs +2 -2
- package/dist/ui.cjs +2 -2
- package/dist/ui.d.ts +11 -5
- package/dist/ui.mjs +3 -3
- package/dist/useConversations-C-OmzdeA.js +4300 -0
- package/dist/useConversations-C-OmzdeA.js.map +1 -0
- package/dist/useConversations-Chn_GKOz.cjs +4299 -0
- package/dist/useConversations-Chn_GKOz.cjs.map +1 -0
- package/dist/useConversations-Ckyqbxqi.cjs +4299 -0
- package/dist/useConversations-Ckyqbxqi.cjs.map +1 -0
- package/dist/useConversations-DzhYCIiY.js +4300 -0
- package/dist/useConversations-DzhYCIiY.js.map +1 -0
- package/dist/voice.cjs +2835 -19
- package/dist/voice.cjs.map +1 -1
- package/dist/voice.d.ts +12 -6
- package/dist/voice.mjs +2836 -20
- package/dist/voice.mjs.map +1 -1
- package/package.json +6 -2
package/dist/voice.mjs
CHANGED
|
@@ -1,10 +1,93 @@
|
|
|
1
1
|
import { useSyncExternalStore, useEffect, useCallback, useRef, useState } from "react";
|
|
2
2
|
import { useAudioRecorder, RecordingPresets, setAudioModeAsync, requestRecordingPermissionsAsync, createAudioPlayer } from "expo-audio";
|
|
3
|
-
import { r as requireConfigured, G as GuideAI, E as EP } from "./useConversations-
|
|
3
|
+
import { r as requireConfigured, G as GuideAI, E as EP } from "./useConversations-C-OmzdeA.js";
|
|
4
4
|
import { File, Paths } from "expo-file-system";
|
|
5
5
|
import { jsx } from "react/jsx-runtime";
|
|
6
|
-
import { G as GuideAIChat } from "./GuideAIChat-
|
|
7
|
-
import { D, a, b, c } from "./GuideAIChat-
|
|
6
|
+
import { G as GuideAIChat } from "./GuideAIChat-SU0CVNby.js";
|
|
7
|
+
import { D, a, b, c } from "./GuideAIChat-SU0CVNby.js";
|
|
8
|
+
const CATALOG = {
|
|
9
|
+
en: {
|
|
10
|
+
label: "English",
|
|
11
|
+
transcriptionLanguages: ["en"],
|
|
12
|
+
transcriptionPrompt: "The selected language is English. Transcribe English exactly as spoken. Do not switch languages, translate, summarize, or answer.",
|
|
13
|
+
speechInstructions: "Speak in English only."
|
|
14
|
+
},
|
|
15
|
+
// Nigerian Pidgin has no recognizer or voice of its own at our providers.
|
|
16
|
+
// It is English-lexified, so it is heard as English, primed with its common
|
|
17
|
+
// words; the agent already answers in the visitor's own dialect. Opt-in
|
|
18
|
+
// only (data-voice-language-codes), never a default.
|
|
19
|
+
pcm: {
|
|
20
|
+
label: "Nigerian Pidgin",
|
|
21
|
+
transcriptionLanguages: ["en"],
|
|
22
|
+
transcriptionPrompt: "The speaker talks Nigerian Pidgin English (Naija). Common words: wetin, abeg, dey, una, oya, wahala, sabi, abi, sef, don, na, dem, pikin, how far, no wahala, I no fit, make I, wey. Transcribe the Pidgin words exactly as spoken; do not convert them to standard English, translate, summarize, or answer.",
|
|
23
|
+
speechInstructions: "Speak in Nigerian Pidgin English with a warm Nigerian accent."
|
|
24
|
+
},
|
|
25
|
+
fr: {
|
|
26
|
+
label: "French",
|
|
27
|
+
transcriptionLanguages: ["fr"],
|
|
28
|
+
transcriptionPrompt: "Transcribe French exactly as spoken. Do not translate, summarize, or answer."
|
|
29
|
+
},
|
|
30
|
+
pt: {
|
|
31
|
+
label: "Portuguese",
|
|
32
|
+
transcriptionLanguages: ["pt"],
|
|
33
|
+
transcriptionPrompt: "Transcribe Portuguese exactly as spoken. Do not translate, summarize, or answer."
|
|
34
|
+
},
|
|
35
|
+
es: {
|
|
36
|
+
label: "Spanish",
|
|
37
|
+
transcriptionLanguages: ["es"],
|
|
38
|
+
transcriptionPrompt: "Transcribe Spanish exactly as spoken. Do not translate, summarize, or answer."
|
|
39
|
+
},
|
|
40
|
+
ar: {
|
|
41
|
+
label: "Arabic",
|
|
42
|
+
transcriptionLanguages: ["ar"],
|
|
43
|
+
transcriptionPrompt: "Transcribe Arabic exactly as spoken. Do not translate, summarize, or answer."
|
|
44
|
+
},
|
|
45
|
+
"zh-cn": {
|
|
46
|
+
label: "Chinese (Mandarin)",
|
|
47
|
+
transcriptionLanguages: ["zh-cn"],
|
|
48
|
+
transcriptionPrompt: "Transcribe Mandarin Chinese exactly as spoken. Do not translate, summarize, or answer."
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
function normalizeVoiceLanguageCode(code) {
|
|
52
|
+
return code.trim().replace(/_/g, "-").toLowerCase().slice(0, 35);
|
|
53
|
+
}
|
|
54
|
+
function resolveVoiceLanguage(code) {
|
|
55
|
+
const normalized = normalizeVoiceLanguageCode(code) || "en";
|
|
56
|
+
const exact = CATALOG[normalized];
|
|
57
|
+
if (exact) return { code: canonicalCode(normalized), ...exact };
|
|
58
|
+
const primary = normalized.split("-")[0];
|
|
59
|
+
const primaryEntry = CATALOG[primary];
|
|
60
|
+
if (primaryEntry) return { code: canonicalCode(normalized), ...primaryEntry };
|
|
61
|
+
return {
|
|
62
|
+
code: canonicalCode(normalized),
|
|
63
|
+
label: displayLanguageName(normalized),
|
|
64
|
+
transcriptionLanguages: [primary],
|
|
65
|
+
transcriptionPrompt: `The speaker selected ${displayLanguageName(normalized)}. Transcribe exactly as spoken. Do not translate, summarize, or answer.`
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
function isUnexpectedTranscriptScript(text, language) {
|
|
69
|
+
if (!(language == null ? void 0 : language.transcriptionLanguages.includes("en"))) return false;
|
|
70
|
+
const letters = Array.from(text).filter((char) => /\p{L}/u.test(char));
|
|
71
|
+
if (letters.length < 3) return false;
|
|
72
|
+
const latin = letters.filter((char) => /\p{Script=Latin}/u.test(char)).length;
|
|
73
|
+
const unrelated = letters.filter((char) => /\p{Script=Han}|\p{Script=Hiragana}|\p{Script=Katakana}|\p{Script=Arabic}|\p{Script=Cyrillic}/u.test(char)).length;
|
|
74
|
+
return unrelated >= 3 && unrelated / letters.length >= 0.45 && latin / letters.length < 0.35;
|
|
75
|
+
}
|
|
76
|
+
function canonicalCode(normalized) {
|
|
77
|
+
return normalized.split("-").map((part, index) => {
|
|
78
|
+
if (index === 0) return part.toLowerCase();
|
|
79
|
+
return part.length === 2 ? part.toUpperCase() : part;
|
|
80
|
+
}).join("-");
|
|
81
|
+
}
|
|
82
|
+
function displayLanguageName(code) {
|
|
83
|
+
try {
|
|
84
|
+
const DisplayNames = Intl.DisplayNames;
|
|
85
|
+
const label = DisplayNames ? new DisplayNames(["en"], { type: "language" }).of(code) : void 0;
|
|
86
|
+
if (label) return label;
|
|
87
|
+
} catch {
|
|
88
|
+
}
|
|
89
|
+
return code.toUpperCase();
|
|
90
|
+
}
|
|
8
91
|
const DEFAULT_VOICE_LANGUAGES = [
|
|
9
92
|
{ code: "en", label: "English" },
|
|
10
93
|
{ code: "fr", label: "Français" },
|
|
@@ -18,10 +101,10 @@ const DEFAULT_VOICE_LANGUAGES = [
|
|
|
18
101
|
const KEY = "guideai_voice_language";
|
|
19
102
|
let state = { code: null, choosing: false, asker: null, resume: null };
|
|
20
103
|
let loadedFor = null;
|
|
21
|
-
const listeners = /* @__PURE__ */ new Set();
|
|
104
|
+
const listeners$1 = /* @__PURE__ */ new Set();
|
|
22
105
|
function set(next) {
|
|
23
106
|
state = { ...state, ...next };
|
|
24
|
-
for (const listener of listeners) listener();
|
|
107
|
+
for (const listener of listeners$1) listener();
|
|
25
108
|
}
|
|
26
109
|
function load() {
|
|
27
110
|
if (!GuideAI.isConfigured()) return;
|
|
@@ -37,9 +120,9 @@ function load() {
|
|
|
37
120
|
if (saved && saved !== state.code) set({ code: saved });
|
|
38
121
|
}
|
|
39
122
|
const subscribe = (listener) => {
|
|
40
|
-
listeners.add(listener);
|
|
123
|
+
listeners$1.add(listener);
|
|
41
124
|
return () => {
|
|
42
|
-
listeners.delete(listener);
|
|
125
|
+
listeners$1.delete(listener);
|
|
43
126
|
};
|
|
44
127
|
};
|
|
45
128
|
const snapshot = () => state;
|
|
@@ -238,7 +321,7 @@ function speechLines(text, max = MAX_LINE_CHARS) {
|
|
|
238
321
|
return lines;
|
|
239
322
|
}
|
|
240
323
|
const MIN_HEARD_MS = 400;
|
|
241
|
-
const MAX_LINE_MS = 6e4;
|
|
324
|
+
const MAX_LINE_MS$1 = 6e4;
|
|
242
325
|
function wavFromPcm(pcm, sampleRate) {
|
|
243
326
|
const out = new Uint8Array(44 + pcm.length);
|
|
244
327
|
const view = new DataView(out.buffer);
|
|
@@ -269,6 +352,10 @@ async function fetchLine(text) {
|
|
|
269
352
|
file.write(wav);
|
|
270
353
|
return file;
|
|
271
354
|
}
|
|
355
|
+
const OURS = /* @__PURE__ */ new WeakSet();
|
|
356
|
+
function isOwnSpeech(speech) {
|
|
357
|
+
return !!speech && OURS.has(speech);
|
|
358
|
+
}
|
|
272
359
|
function forget(file) {
|
|
273
360
|
try {
|
|
274
361
|
file == null ? void 0 : file.delete();
|
|
@@ -305,7 +392,7 @@ function createSpeech() {
|
|
|
305
392
|
player = current;
|
|
306
393
|
const timer = setTimeout(() => {
|
|
307
394
|
if (player === current) silence();
|
|
308
|
-
}, MAX_LINE_MS);
|
|
395
|
+
}, MAX_LINE_MS$1);
|
|
309
396
|
finish = () => {
|
|
310
397
|
clearTimeout(timer);
|
|
311
398
|
resolve();
|
|
@@ -341,7 +428,2631 @@ function createSpeech() {
|
|
|
341
428
|
if (mine !== session) void next.then(forget);
|
|
342
429
|
return Date.now() - started >= MIN_HEARD_MS;
|
|
343
430
|
};
|
|
344
|
-
|
|
431
|
+
const speech = { say, stop };
|
|
432
|
+
OURS.add(speech);
|
|
433
|
+
return speech;
|
|
434
|
+
}
|
|
435
|
+
class VoiceProviderError extends Error {
|
|
436
|
+
constructor(message) {
|
|
437
|
+
super(message);
|
|
438
|
+
this.name = "VoiceProviderError";
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
function resampleMono(input, inputRate, outputRate) {
|
|
442
|
+
if (inputRate === outputRate) return input;
|
|
443
|
+
const ratio = inputRate / outputRate;
|
|
444
|
+
const length = Math.max(1, Math.floor(input.length / ratio));
|
|
445
|
+
const output = new Float32Array(length);
|
|
446
|
+
for (let index = 0; index < length; index += 1) {
|
|
447
|
+
const start = Math.floor(index * ratio);
|
|
448
|
+
const end = Math.min(input.length, Math.floor((index + 1) * ratio));
|
|
449
|
+
let sum = 0;
|
|
450
|
+
for (let sample = start; sample < end; sample += 1) sum += input[sample];
|
|
451
|
+
output[index] = sum / Math.max(1, end - start);
|
|
452
|
+
}
|
|
453
|
+
return output;
|
|
454
|
+
}
|
|
455
|
+
function floatToPcm16(input) {
|
|
456
|
+
const output = new Int16Array(input.length);
|
|
457
|
+
for (let index = 0; index < input.length; index += 1) {
|
|
458
|
+
const sample = Math.max(-1, Math.min(1, input[index]));
|
|
459
|
+
output[index] = sample < 0 ? sample * 32768 : sample * 32767;
|
|
460
|
+
}
|
|
461
|
+
return output;
|
|
462
|
+
}
|
|
463
|
+
const BASE64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
464
|
+
function decodeBase64(value) {
|
|
465
|
+
if (typeof atob === "function") return atob(value);
|
|
466
|
+
const clean = value.replace(/[^A-Za-z0-9+/]/g, "");
|
|
467
|
+
let out = "";
|
|
468
|
+
for (let i = 0; i < clean.length; i += 4) {
|
|
469
|
+
const n = [0, 1, 2, 3].map((k) => i + k < clean.length ? BASE64.indexOf(clean[i + k]) : -1);
|
|
470
|
+
const bits = (n[0] & 63) << 18 | (n[1] & 63) << 12 | (Math.max(0, n[2]) & 63) << 6 | Math.max(0, n[3]) & 63;
|
|
471
|
+
out += String.fromCharCode(bits >> 16 & 255);
|
|
472
|
+
if (n[2] >= 0) out += String.fromCharCode(bits >> 8 & 255);
|
|
473
|
+
if (n[3] >= 0) out += String.fromCharCode(bits & 255);
|
|
474
|
+
}
|
|
475
|
+
return out;
|
|
476
|
+
}
|
|
477
|
+
function base64ToBytes(value) {
|
|
478
|
+
const binary = decodeBase64(value);
|
|
479
|
+
const bytes = new Uint8Array(binary.length);
|
|
480
|
+
for (let index = 0; index < binary.length; index += 1) bytes[index] = binary.charCodeAt(index);
|
|
481
|
+
return bytes;
|
|
482
|
+
}
|
|
483
|
+
function makeId(prefix) {
|
|
484
|
+
if (typeof crypto !== "undefined" && typeof crypto.randomUUID === "function") {
|
|
485
|
+
return `${prefix}_${crypto.randomUUID()}`;
|
|
486
|
+
}
|
|
487
|
+
return `${prefix}_${Date.now()}_${Math.random().toString(36).slice(2, 9)}`;
|
|
488
|
+
}
|
|
489
|
+
function socketUrl(url, sessionUrl) {
|
|
490
|
+
var _a, _b;
|
|
491
|
+
if (/^wss?:\/\//i.test(url)) return url;
|
|
492
|
+
let absolute = url;
|
|
493
|
+
if (!/^https?:\/\//i.test(url)) {
|
|
494
|
+
const session = /^https?:\/\//i.test(sessionUrl) || typeof location === "undefined" ? sessionUrl : new URL(sessionUrl, location.href).toString();
|
|
495
|
+
const origin = (_b = (_a = /^https?:\/\/[^/]+/i.exec(session)) == null ? void 0 : _a[0]) != null ? _b : "";
|
|
496
|
+
absolute = url.startsWith("/") ? `${origin}${url}` : `${session.replace(/[?#].*$/, "").replace(/[^/]*$/, "")}${url}`;
|
|
497
|
+
}
|
|
498
|
+
return absolute.replace(/^http(s?):/i, (_, secure) => secure ? "wss:" : "ws:");
|
|
499
|
+
}
|
|
500
|
+
function isAbortError(error) {
|
|
501
|
+
return !!error && typeof error === "object" && error.name === "AbortError";
|
|
502
|
+
}
|
|
503
|
+
function abortError(message) {
|
|
504
|
+
if (typeof DOMException !== "undefined") return new DOMException(message, "AbortError");
|
|
505
|
+
return Object.assign(new Error(message), { name: "AbortError" });
|
|
506
|
+
}
|
|
507
|
+
function isRetryableConnectionError(error) {
|
|
508
|
+
const name = error && typeof error === "object" ? error.name : void 0;
|
|
509
|
+
if (typeof DOMException !== "undefined" && !(error instanceof DOMException)) return true;
|
|
510
|
+
return !["NotAllowedError", "SecurityError", "NotFoundError"].includes(String(name));
|
|
511
|
+
}
|
|
512
|
+
function pushStream(onCancel) {
|
|
513
|
+
const queued = [];
|
|
514
|
+
const waiting = [];
|
|
515
|
+
let closed = false;
|
|
516
|
+
let failure = null;
|
|
517
|
+
const settle = () => {
|
|
518
|
+
while (waiting.length && (queued.length || closed || failure)) {
|
|
519
|
+
const next = waiting.shift();
|
|
520
|
+
if (queued.length) next.resolve({ done: false, value: queued.shift() });
|
|
521
|
+
else if (failure) next.reject(failure);
|
|
522
|
+
else next.resolve({ done: true });
|
|
523
|
+
}
|
|
524
|
+
};
|
|
525
|
+
const reader = {
|
|
526
|
+
read: () => {
|
|
527
|
+
if (queued.length) return Promise.resolve({ done: false, value: queued.shift() });
|
|
528
|
+
if (failure) return Promise.reject(failure);
|
|
529
|
+
if (closed) return Promise.resolve({ done: true });
|
|
530
|
+
return new Promise((resolve, reject) => {
|
|
531
|
+
waiting.push({ resolve, reject });
|
|
532
|
+
});
|
|
533
|
+
},
|
|
534
|
+
cancel: () => {
|
|
535
|
+
if (closed) return;
|
|
536
|
+
closed = true;
|
|
537
|
+
queued.length = 0;
|
|
538
|
+
settle();
|
|
539
|
+
onCancel == null ? void 0 : onCancel();
|
|
540
|
+
},
|
|
541
|
+
releaseLock: () => void 0
|
|
542
|
+
};
|
|
543
|
+
return {
|
|
544
|
+
stream: { getReader: () => reader },
|
|
545
|
+
enqueue(chunk) {
|
|
546
|
+
if (closed || failure) return;
|
|
547
|
+
queued.push(chunk);
|
|
548
|
+
settle();
|
|
549
|
+
},
|
|
550
|
+
close() {
|
|
551
|
+
closed = true;
|
|
552
|
+
settle();
|
|
553
|
+
},
|
|
554
|
+
error(error) {
|
|
555
|
+
if (closed || failure) return;
|
|
556
|
+
failure = error;
|
|
557
|
+
settle();
|
|
558
|
+
}
|
|
559
|
+
};
|
|
560
|
+
}
|
|
561
|
+
class VoiceTelemetry {
|
|
562
|
+
constructor(options = {}) {
|
|
563
|
+
this.options = options;
|
|
564
|
+
this.entries = [];
|
|
565
|
+
this.marks = /* @__PURE__ */ new Map();
|
|
566
|
+
}
|
|
567
|
+
record(name, value, detail) {
|
|
568
|
+
var _a, _b, _c;
|
|
569
|
+
const entry = {
|
|
570
|
+
name: name.slice(0, 80),
|
|
571
|
+
at: Date.now(),
|
|
572
|
+
value: Number.isFinite(value) ? value : void 0,
|
|
573
|
+
detail: detail ? redact(detail).slice(0, 300) : void 0
|
|
574
|
+
};
|
|
575
|
+
this.entries.push(entry);
|
|
576
|
+
const maxEntries = (_a = this.options.maxEntries) != null ? _a : 300;
|
|
577
|
+
if (this.entries.length > maxEntries) this.entries.splice(0, this.entries.length - maxEntries);
|
|
578
|
+
(_c = (_b = this.options).onEntry) == null ? void 0 : _c.call(_b, entry);
|
|
579
|
+
}
|
|
580
|
+
mark(name) {
|
|
581
|
+
this.marks.set(name, performance.now());
|
|
582
|
+
}
|
|
583
|
+
measure(name, mark, detail) {
|
|
584
|
+
const started = this.marks.get(mark);
|
|
585
|
+
if (started == null) return null;
|
|
586
|
+
const duration = performance.now() - started;
|
|
587
|
+
this.marks.delete(mark);
|
|
588
|
+
this.record(name, duration, detail);
|
|
589
|
+
return duration;
|
|
590
|
+
}
|
|
591
|
+
snapshot() {
|
|
592
|
+
return this.entries.map((entry) => ({ ...entry }));
|
|
593
|
+
}
|
|
594
|
+
summary() {
|
|
595
|
+
var _a, _b;
|
|
596
|
+
const grouped = {};
|
|
597
|
+
for (const entry of this.entries) {
|
|
598
|
+
if (entry.value == null) continue;
|
|
599
|
+
((_b = grouped[_a = entry.name]) != null ? _b : grouped[_a] = []).push(entry.value);
|
|
600
|
+
}
|
|
601
|
+
return Object.fromEntries(Object.entries(grouped).map(([name, values]) => [name, {
|
|
602
|
+
count: values.length,
|
|
603
|
+
average: values.reduce((sum, value) => sum + value, 0) / values.length,
|
|
604
|
+
maximum: Math.max(...values)
|
|
605
|
+
}]));
|
|
606
|
+
}
|
|
607
|
+
clear() {
|
|
608
|
+
this.entries.length = 0;
|
|
609
|
+
this.marks.clear();
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
function redact(value) {
|
|
613
|
+
return value.replace(/\bsk-[A-Za-z0-9_-]{12,}/gi, "[REDACTED]").replace(/\b(?:sk|pk|ok)[_-](?:live|test)[_-][A-Za-z0-9_-]{8,}/gi, "[REDACTED]").replace(/Bearer\s+\S+/gi, "Bearer [REDACTED]");
|
|
614
|
+
}
|
|
615
|
+
let assistantClaims = 0;
|
|
616
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
617
|
+
function acquireAssistantAudio() {
|
|
618
|
+
const wasIdle = assistantClaims === 0;
|
|
619
|
+
assistantClaims += 1;
|
|
620
|
+
if (wasIdle) notify(true);
|
|
621
|
+
let released = false;
|
|
622
|
+
return () => {
|
|
623
|
+
if (released) return;
|
|
624
|
+
released = true;
|
|
625
|
+
assistantClaims = Math.max(0, assistantClaims - 1);
|
|
626
|
+
if (assistantClaims === 0) notify(false);
|
|
627
|
+
};
|
|
628
|
+
}
|
|
629
|
+
function notify(assistantSpeaking) {
|
|
630
|
+
for (const listener of [...listeners]) {
|
|
631
|
+
try {
|
|
632
|
+
listener(assistantSpeaking);
|
|
633
|
+
} catch {
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
}
|
|
637
|
+
const DEFAULT_TRANSCRIPTION_MODEL = "gpt-4o-mini-transcribe";
|
|
638
|
+
function conversationalTurnDetection(eagerness = "medium") {
|
|
639
|
+
return { type: "semantic_vad", eagerness };
|
|
640
|
+
}
|
|
641
|
+
const LEADING_FILLERS = [
|
|
642
|
+
"go ahead and",
|
|
643
|
+
"can you please",
|
|
644
|
+
"could you please",
|
|
645
|
+
"can you",
|
|
646
|
+
"could you",
|
|
647
|
+
"would you",
|
|
648
|
+
"will you",
|
|
649
|
+
"i want you to",
|
|
650
|
+
"i want to",
|
|
651
|
+
"i d like to",
|
|
652
|
+
"i would like to",
|
|
653
|
+
"you can",
|
|
654
|
+
"help me",
|
|
655
|
+
"okay",
|
|
656
|
+
"ok",
|
|
657
|
+
"alright",
|
|
658
|
+
"all right",
|
|
659
|
+
"so",
|
|
660
|
+
"now",
|
|
661
|
+
"then",
|
|
662
|
+
"yes",
|
|
663
|
+
"yeah",
|
|
664
|
+
"yep",
|
|
665
|
+
"sure",
|
|
666
|
+
"right",
|
|
667
|
+
"oya",
|
|
668
|
+
"abeg",
|
|
669
|
+
"please",
|
|
670
|
+
"pls",
|
|
671
|
+
"just",
|
|
672
|
+
"and",
|
|
673
|
+
"um",
|
|
674
|
+
"uh",
|
|
675
|
+
"hey",
|
|
676
|
+
"hmm",
|
|
677
|
+
"well",
|
|
678
|
+
"click on the",
|
|
679
|
+
"click on",
|
|
680
|
+
"click the",
|
|
681
|
+
"click",
|
|
682
|
+
"press the",
|
|
683
|
+
"press",
|
|
684
|
+
"tap the",
|
|
685
|
+
"tap",
|
|
686
|
+
"hit the",
|
|
687
|
+
"hit",
|
|
688
|
+
"select the",
|
|
689
|
+
"select"
|
|
690
|
+
];
|
|
691
|
+
const TRAILING_FILLERS = ["please", "now", "then", "abeg", "o", "thanks", "thank you", "button", "for me please"];
|
|
692
|
+
function commandCore(normalized) {
|
|
693
|
+
let text = ` ${normalized} `;
|
|
694
|
+
for (let changed = true; changed; ) {
|
|
695
|
+
changed = false;
|
|
696
|
+
for (const filler of LEADING_FILLERS) {
|
|
697
|
+
if (text.startsWith(` ${filler} `) && text.trim() !== filler) {
|
|
698
|
+
text = text.slice(filler.length + 1);
|
|
699
|
+
changed = true;
|
|
700
|
+
}
|
|
701
|
+
}
|
|
702
|
+
for (const filler of TRAILING_FILLERS) {
|
|
703
|
+
if (text.endsWith(` ${filler} `) && text.trim() !== filler) {
|
|
704
|
+
text = text.slice(0, text.length - filler.length - 1);
|
|
705
|
+
changed = true;
|
|
706
|
+
}
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
return text.trim();
|
|
710
|
+
}
|
|
711
|
+
const CONFIRM_ANSWERS = /* @__PURE__ */ new Set([
|
|
712
|
+
// "yes please" reduces to "please" once the filler is stripped.
|
|
713
|
+
"yes",
|
|
714
|
+
"yeah",
|
|
715
|
+
"yep",
|
|
716
|
+
"yup",
|
|
717
|
+
"sure",
|
|
718
|
+
"ok",
|
|
719
|
+
"okay",
|
|
720
|
+
"please",
|
|
721
|
+
"yes please",
|
|
722
|
+
"go ahead",
|
|
723
|
+
"do it",
|
|
724
|
+
"yes do it",
|
|
725
|
+
"confirm",
|
|
726
|
+
"confirm it",
|
|
727
|
+
"proceed",
|
|
728
|
+
"approve",
|
|
729
|
+
"approve it",
|
|
730
|
+
"go on",
|
|
731
|
+
"carry on",
|
|
732
|
+
"please do",
|
|
733
|
+
"that s fine",
|
|
734
|
+
"sounds good",
|
|
735
|
+
"oya",
|
|
736
|
+
"oya do am",
|
|
737
|
+
"do am",
|
|
738
|
+
"make e happen"
|
|
739
|
+
]);
|
|
740
|
+
const CANCEL_ANSWERS = /* @__PURE__ */ new Set([
|
|
741
|
+
"no",
|
|
742
|
+
"nope",
|
|
743
|
+
"nah",
|
|
744
|
+
"cancel",
|
|
745
|
+
"cancel it",
|
|
746
|
+
"don t",
|
|
747
|
+
"don t do it",
|
|
748
|
+
"do not do it",
|
|
749
|
+
"never mind",
|
|
750
|
+
"no thanks",
|
|
751
|
+
"no thank you",
|
|
752
|
+
"leave it",
|
|
753
|
+
"stop",
|
|
754
|
+
"abeg no",
|
|
755
|
+
"no o",
|
|
756
|
+
"no no",
|
|
757
|
+
"forget it"
|
|
758
|
+
]);
|
|
759
|
+
function isConfirmationAnswer(text) {
|
|
760
|
+
const core = commandCore(normalizeCommand(text));
|
|
761
|
+
return CONFIRM_ANSWERS.has(core) || CANCEL_ANSWERS.has(core);
|
|
762
|
+
}
|
|
763
|
+
function confirmationAnswer(text) {
|
|
764
|
+
const core = commandCore(normalizeCommand(text));
|
|
765
|
+
if (CONFIRM_ANSWERS.has(core)) return "yes";
|
|
766
|
+
if (CANCEL_ANSWERS.has(core)) return "no";
|
|
767
|
+
return null;
|
|
768
|
+
}
|
|
769
|
+
function normalizeCommand(text) {
|
|
770
|
+
return text.toLocaleLowerCase().replace(/[^\p{L}\p{N}\s]/gu, " ").replace(/\s+/g, " ").trim();
|
|
771
|
+
}
|
|
772
|
+
function isStreamingSpeechProvider(provider) {
|
|
773
|
+
return typeof (provider == null ? void 0 : provider.open) === "function";
|
|
774
|
+
}
|
|
775
|
+
const SOCKET_OPEN_TIMEOUT_MS = 2500;
|
|
776
|
+
const SOCKET_OPEN_ATTEMPTS = 3;
|
|
777
|
+
class SonioxSpeechProvider {
|
|
778
|
+
constructor(options) {
|
|
779
|
+
this.options = options;
|
|
780
|
+
}
|
|
781
|
+
open(request, signal) {
|
|
782
|
+
var _a, _b;
|
|
783
|
+
const fetcher = (_a = this.options.fetcher) != null ? _a : ((...args) => globalThis.fetch(...args));
|
|
784
|
+
const socketFactory = (_b = this.options.webSocketFactory) != null ? _b : ((url) => new WebSocket(url));
|
|
785
|
+
const baseId = makeId("guideai_tts");
|
|
786
|
+
const answer = { id: baseId, pending: [], configured: false, held: [], done: false };
|
|
787
|
+
const streams = /* @__PURE__ */ new Map([[answer.id, answer]]);
|
|
788
|
+
const order = [];
|
|
789
|
+
let playIndex = 0;
|
|
790
|
+
let fillers = 0;
|
|
791
|
+
let socket = null;
|
|
792
|
+
let token = null;
|
|
793
|
+
let socketOpen = false;
|
|
794
|
+
let openTimer = null;
|
|
795
|
+
let openAttempts = 0;
|
|
796
|
+
let ended = false;
|
|
797
|
+
let finished = false;
|
|
798
|
+
const audioController = pushStream(() => abort());
|
|
799
|
+
const audio = audioController.stream;
|
|
800
|
+
const anyConfigured = () => order.some((stream) => stream.configured);
|
|
801
|
+
const finish = (error) => {
|
|
802
|
+
if (finished) return;
|
|
803
|
+
finished = true;
|
|
804
|
+
if (openTimer) clearTimeout(openTimer);
|
|
805
|
+
openTimer = null;
|
|
806
|
+
signal.removeEventListener("abort", abort);
|
|
807
|
+
try {
|
|
808
|
+
if (error) audioController.error(error);
|
|
809
|
+
else audioController.close();
|
|
810
|
+
} catch {
|
|
811
|
+
}
|
|
812
|
+
if (socket) {
|
|
813
|
+
socket.onmessage = null;
|
|
814
|
+
socket.onclose = null;
|
|
815
|
+
socket.onerror = null;
|
|
816
|
+
try {
|
|
817
|
+
socket.close();
|
|
818
|
+
} catch {
|
|
819
|
+
}
|
|
820
|
+
}
|
|
821
|
+
};
|
|
822
|
+
function abort() {
|
|
823
|
+
if (finished) return;
|
|
824
|
+
if (socket && socketOpen && socket.readyState === WebSocket.OPEN) {
|
|
825
|
+
for (const stream of order) {
|
|
826
|
+
if (!stream.configured || stream.done) continue;
|
|
827
|
+
try {
|
|
828
|
+
socket.send(JSON.stringify({ stream_id: stream.id, cancel: true }));
|
|
829
|
+
} catch {
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
finish();
|
|
834
|
+
}
|
|
835
|
+
const enqueue = (bytes) => {
|
|
836
|
+
try {
|
|
837
|
+
audioController.enqueue(bytes);
|
|
838
|
+
} catch {
|
|
839
|
+
}
|
|
840
|
+
};
|
|
841
|
+
const advance = () => {
|
|
842
|
+
while (playIndex < order.length) {
|
|
843
|
+
const current = order[playIndex];
|
|
844
|
+
for (const bytes of current.held) enqueue(bytes);
|
|
845
|
+
current.held = [];
|
|
846
|
+
if (!current.done) return;
|
|
847
|
+
playIndex += 1;
|
|
848
|
+
}
|
|
849
|
+
if (ended && (answer.done || !order.includes(answer))) finish();
|
|
850
|
+
};
|
|
851
|
+
const connect = () => {
|
|
852
|
+
if (finished || !token) return;
|
|
853
|
+
const ws = socketFactory(token.url);
|
|
854
|
+
socket = ws;
|
|
855
|
+
socketOpen = false;
|
|
856
|
+
openAttempts += 1;
|
|
857
|
+
if (openTimer) clearTimeout(openTimer);
|
|
858
|
+
openTimer = setTimeout(() => {
|
|
859
|
+
openTimer = null;
|
|
860
|
+
if (finished || socket !== ws || socketOpen) return;
|
|
861
|
+
ws.onopen = null;
|
|
862
|
+
ws.onmessage = null;
|
|
863
|
+
ws.onclose = null;
|
|
864
|
+
ws.onerror = null;
|
|
865
|
+
try {
|
|
866
|
+
ws.close();
|
|
867
|
+
} catch {
|
|
868
|
+
}
|
|
869
|
+
socket = null;
|
|
870
|
+
if (openAttempts >= SOCKET_OPEN_ATTEMPTS) {
|
|
871
|
+
finish(new VoiceProviderError("Voice speech connection timed out."));
|
|
872
|
+
return;
|
|
873
|
+
}
|
|
874
|
+
connect();
|
|
875
|
+
}, SOCKET_OPEN_TIMEOUT_MS);
|
|
876
|
+
ws.onopen = () => {
|
|
877
|
+
if (openTimer) clearTimeout(openTimer);
|
|
878
|
+
openTimer = null;
|
|
879
|
+
openAttempts = 0;
|
|
880
|
+
socketOpen = true;
|
|
881
|
+
flush();
|
|
882
|
+
};
|
|
883
|
+
ws.onmessage = (event) => {
|
|
884
|
+
var _a2;
|
|
885
|
+
let message;
|
|
886
|
+
try {
|
|
887
|
+
message = JSON.parse(String(event.data));
|
|
888
|
+
} catch {
|
|
889
|
+
return;
|
|
890
|
+
}
|
|
891
|
+
if (message.error_code) {
|
|
892
|
+
finish(new VoiceProviderError("Voice speech failed."));
|
|
893
|
+
return;
|
|
894
|
+
}
|
|
895
|
+
const stream = streams.get((_a2 = message.stream_id) != null ? _a2 : answer.id);
|
|
896
|
+
if (!stream) return;
|
|
897
|
+
if (message.audio) {
|
|
898
|
+
const bytes = base64ToBytes(message.audio);
|
|
899
|
+
if (order[playIndex] === stream) enqueue(bytes);
|
|
900
|
+
else stream.held.push(bytes);
|
|
901
|
+
}
|
|
902
|
+
if (message.audio_end || message.terminated) {
|
|
903
|
+
stream.done = true;
|
|
904
|
+
advance();
|
|
905
|
+
}
|
|
906
|
+
};
|
|
907
|
+
ws.onerror = () => {
|
|
908
|
+
if (anyConfigured()) finish(new VoiceProviderError("Voice speech connection failed."));
|
|
909
|
+
};
|
|
910
|
+
ws.onclose = () => {
|
|
911
|
+
if (anyConfigured()) {
|
|
912
|
+
const complete = ended && order.every((stream) => stream.done);
|
|
913
|
+
finish(complete ? void 0 : new VoiceProviderError("Voice speech connection closed."));
|
|
914
|
+
return;
|
|
915
|
+
}
|
|
916
|
+
socket = null;
|
|
917
|
+
socketOpen = false;
|
|
918
|
+
if (order.some((stream) => stream.pending.length)) connect();
|
|
919
|
+
};
|
|
920
|
+
};
|
|
921
|
+
const flush = () => {
|
|
922
|
+
if (finished || !token) return;
|
|
923
|
+
if (!order.some((stream) => stream.pending.length)) return;
|
|
924
|
+
if (!socket) {
|
|
925
|
+
connect();
|
|
926
|
+
return;
|
|
927
|
+
}
|
|
928
|
+
if (!socketOpen || socket.readyState !== WebSocket.OPEN) return;
|
|
929
|
+
for (const stream of order) {
|
|
930
|
+
if (!stream.pending.length) continue;
|
|
931
|
+
if (!stream.configured) {
|
|
932
|
+
socket.send(JSON.stringify({
|
|
933
|
+
api_key: token.apiKey,
|
|
934
|
+
...token.model ? { model: token.model } : {},
|
|
935
|
+
voice: token.voice,
|
|
936
|
+
language: token.language,
|
|
937
|
+
audio_format: token.audioFormat,
|
|
938
|
+
sample_rate: token.sampleRate,
|
|
939
|
+
stream_id: stream.id
|
|
940
|
+
}));
|
|
941
|
+
stream.configured = true;
|
|
942
|
+
}
|
|
943
|
+
while (stream.pending.length) socket.send(JSON.stringify(stream.pending.shift()));
|
|
944
|
+
}
|
|
945
|
+
};
|
|
946
|
+
const queue = (stream, message) => {
|
|
947
|
+
stream.pending.push({ ...message, stream_id: stream.id });
|
|
948
|
+
flush();
|
|
949
|
+
};
|
|
950
|
+
if (signal.aborted) {
|
|
951
|
+
finish();
|
|
952
|
+
} else {
|
|
953
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
954
|
+
const tokenRequest = fetcher(this.options.tokenUrl, {
|
|
955
|
+
method: "POST",
|
|
956
|
+
headers: { "Content-Type": "application/json", "X-API-Key": this.options.token },
|
|
957
|
+
body: JSON.stringify({ voice: request.voice, language: request.language }),
|
|
958
|
+
signal
|
|
959
|
+
}).then(async (response) => {
|
|
960
|
+
if (response.status >= 500) throw new VoiceProviderError(`Voice speech failed (${response.status}).`);
|
|
961
|
+
if (!response.ok) throw new Error(`Voice speech failed (${response.status}).`);
|
|
962
|
+
const minted = await response.json();
|
|
963
|
+
return { ...minted, url: socketUrl(minted.url, this.options.tokenUrl) };
|
|
964
|
+
});
|
|
965
|
+
void tokenRequest.then((minted) => {
|
|
966
|
+
if (finished) return;
|
|
967
|
+
token = minted;
|
|
968
|
+
connect();
|
|
969
|
+
}).catch((error) => {
|
|
970
|
+
if (signal.aborted) {
|
|
971
|
+
finish();
|
|
972
|
+
return;
|
|
973
|
+
}
|
|
974
|
+
finish(error instanceof Error ? error : new Error(String(error)));
|
|
975
|
+
});
|
|
976
|
+
}
|
|
977
|
+
return {
|
|
978
|
+
audio,
|
|
979
|
+
push(text) {
|
|
980
|
+
if (finished || ended || !text) return;
|
|
981
|
+
if (!order.includes(answer)) order.push(answer);
|
|
982
|
+
for (let index = 0; index < text.length; index += 4e3) {
|
|
983
|
+
queue(answer, { text: text.slice(index, index + 4e3), text_end: false });
|
|
984
|
+
}
|
|
985
|
+
},
|
|
986
|
+
say(text) {
|
|
987
|
+
if (finished || ended || !text.trim() || order.includes(answer)) return;
|
|
988
|
+
fillers += 1;
|
|
989
|
+
const filler = {
|
|
990
|
+
id: `${baseId}_f${fillers}`,
|
|
991
|
+
pending: [],
|
|
992
|
+
configured: false,
|
|
993
|
+
held: [],
|
|
994
|
+
done: false
|
|
995
|
+
};
|
|
996
|
+
streams.set(filler.id, filler);
|
|
997
|
+
order.push(filler);
|
|
998
|
+
queue(filler, { text, text_end: false });
|
|
999
|
+
queue(filler, { text: "", text_end: true });
|
|
1000
|
+
},
|
|
1001
|
+
end() {
|
|
1002
|
+
if (finished || ended) return;
|
|
1003
|
+
ended = true;
|
|
1004
|
+
if (order.includes(answer)) {
|
|
1005
|
+
queue(answer, { text: "", text_end: true });
|
|
1006
|
+
return;
|
|
1007
|
+
}
|
|
1008
|
+
advance();
|
|
1009
|
+
}
|
|
1010
|
+
};
|
|
1011
|
+
}
|
|
1012
|
+
}
|
|
1013
|
+
function toSpeakableChunk(text) {
|
|
1014
|
+
return text.replace(/\]\([^)\s]*\)/g, "").replace(/https?:\/\/\S+/g, "").replace(/(^|\n)[ \t]{0,3}(?:#{1,6}|[-*+]|>)[ \t]+/g, "$1").replace(/[*`#[\]]/g, "");
|
|
1015
|
+
}
|
|
1016
|
+
const THINKING_LINES = {
|
|
1017
|
+
en: [
|
|
1018
|
+
["Hmm, let me check that.", "Okay, give me a second.", "Let me look into that.", "Sure, one moment."],
|
|
1019
|
+
["Still looking into it.", "Bear with me, I’m checking.", "Just a moment more."],
|
|
1020
|
+
["Almost there.", "Nearly done.", "Thanks for waiting."]
|
|
1021
|
+
],
|
|
1022
|
+
pcm: [
|
|
1023
|
+
["Hmm, make I check am.", "Okay, give me small time.", "Make I look am."],
|
|
1024
|
+
["I still dey find am.", "Hold on small, I dey check."],
|
|
1025
|
+
["E don almost ready.", "Na small remain."]
|
|
1026
|
+
],
|
|
1027
|
+
fr: [
|
|
1028
|
+
["Hmm, je vérifie.", "D’accord, une seconde."],
|
|
1029
|
+
["Je cherche encore.", "Un petit instant."],
|
|
1030
|
+
["Presque fini."]
|
|
1031
|
+
],
|
|
1032
|
+
es: [
|
|
1033
|
+
["Mmm, déjame revisarlo.", "Vale, un segundo."],
|
|
1034
|
+
["Sigo buscando.", "Un momento más."],
|
|
1035
|
+
["Ya casi está."]
|
|
1036
|
+
],
|
|
1037
|
+
pt: [
|
|
1038
|
+
["Hmm, deixa eu verificar.", "Certo, um segundo."],
|
|
1039
|
+
["Ainda estou procurando.", "Só mais um momento."],
|
|
1040
|
+
["Quase lá."]
|
|
1041
|
+
]
|
|
1042
|
+
};
|
|
1043
|
+
const STILL_WORKING_LINES = {
|
|
1044
|
+
en: [
|
|
1045
|
+
"Yes, I’m still working on it.",
|
|
1046
|
+
"I’m here, still working on that.",
|
|
1047
|
+
"Still on it, just a moment.",
|
|
1048
|
+
"Yep, still working on this for you."
|
|
1049
|
+
],
|
|
1050
|
+
pcm: ["I dey here, I still dey work on am.", "I still dey on am, small time."],
|
|
1051
|
+
fr: ["Oui, je m’en occupe toujours.", "Je suis là, je travaille encore dessus."],
|
|
1052
|
+
es: ["Sí, sigo trabajando en ello.", "Aquí estoy, sigo con eso."],
|
|
1053
|
+
pt: ["Sim, ainda estou trabalhando nisso.", "Estou aqui, ainda cuidando disso."]
|
|
1054
|
+
};
|
|
1055
|
+
function primaryLanguage(languageCode) {
|
|
1056
|
+
return (languageCode != null ? languageCode : "en").toLowerCase().split("-")[0];
|
|
1057
|
+
}
|
|
1058
|
+
function pick(options, avoid) {
|
|
1059
|
+
if (!(options == null ? void 0 : options.length)) return null;
|
|
1060
|
+
const pool = options.length > 1 && avoid ? options.filter((line) => line !== avoid) : options;
|
|
1061
|
+
return pool[Math.floor(Math.random() * pool.length)];
|
|
1062
|
+
}
|
|
1063
|
+
function thinkingLine(languageCode, index, previous) {
|
|
1064
|
+
const primary = primaryLanguage(languageCode);
|
|
1065
|
+
const sets = THINKING_LINES[primary];
|
|
1066
|
+
if (!sets) return null;
|
|
1067
|
+
if (index < sets.length) return pick(sets[index], previous);
|
|
1068
|
+
return pick(STILL_WORKING_LINES[primary], previous);
|
|
1069
|
+
}
|
|
1070
|
+
function stillWorkingLine(languageCode, previous) {
|
|
1071
|
+
return pick(STILL_WORKING_LINES[primaryLanguage(languageCode)], previous);
|
|
1072
|
+
}
|
|
1073
|
+
const PCM_SAMPLE_RATE = 24e3;
|
|
1074
|
+
const PCM_START_BUFFER_SECONDS = 0.06;
|
|
1075
|
+
const SESSION_READY_TIMEOUT_MS = 2500;
|
|
1076
|
+
const SESSION_CREATED_EVENTS = /* @__PURE__ */ new Set(["session.created", "transcription_session.created"]);
|
|
1077
|
+
const SESSION_UPDATED_EVENTS = /* @__PURE__ */ new Set(["session.updated", "transcription_session.updated"]);
|
|
1078
|
+
const THINKING_ALOUD_AT_MS = [1e3, 4500, 9e3];
|
|
1079
|
+
const STILL_WORKING_EVERY_MS = 7e3;
|
|
1080
|
+
const STILL_WORKING_UNTIL_MS = 6e4;
|
|
1081
|
+
const CHECK_IN_MAX_WORDS = 8;
|
|
1082
|
+
const CHECK_IN_COOLDOWN_MS = 6e3;
|
|
1083
|
+
const LINE_SPACING_MS = 3e3;
|
|
1084
|
+
const ECHO_ONSET_MS = 600;
|
|
1085
|
+
const ECHO_MEMORY_MS = 3e4;
|
|
1086
|
+
const DUCKED_VOLUME = 0.2;
|
|
1087
|
+
const INTERRUPTION_CONFIRM_MS = 1500;
|
|
1088
|
+
const TRANSCRIPT_VERDICT_TIMEOUT_MS = 3e3;
|
|
1089
|
+
const HESITATIONS = /* @__PURE__ */ new Set([
|
|
1090
|
+
"um",
|
|
1091
|
+
"umm",
|
|
1092
|
+
"uh",
|
|
1093
|
+
"uhh",
|
|
1094
|
+
"uhm",
|
|
1095
|
+
"er",
|
|
1096
|
+
"erm",
|
|
1097
|
+
"hm",
|
|
1098
|
+
"hmm",
|
|
1099
|
+
"hmmm",
|
|
1100
|
+
"mm",
|
|
1101
|
+
"mmm",
|
|
1102
|
+
"ah",
|
|
1103
|
+
"ahh",
|
|
1104
|
+
"eh"
|
|
1105
|
+
]);
|
|
1106
|
+
const AGREEMENT_SOUNDS = /* @__PURE__ */ new Set([
|
|
1107
|
+
"mhm",
|
|
1108
|
+
"mhmm",
|
|
1109
|
+
"mm hm",
|
|
1110
|
+
"mm hmm",
|
|
1111
|
+
"mmhmm",
|
|
1112
|
+
"uh huh",
|
|
1113
|
+
"uh hum",
|
|
1114
|
+
"ehen",
|
|
1115
|
+
"ehn"
|
|
1116
|
+
]);
|
|
1117
|
+
const BACKCHANNELS = /* @__PURE__ */ new Set([
|
|
1118
|
+
"mm",
|
|
1119
|
+
"mmm",
|
|
1120
|
+
"mhm",
|
|
1121
|
+
"mhmm",
|
|
1122
|
+
"mm hm",
|
|
1123
|
+
"mm hmm",
|
|
1124
|
+
"mmhmm",
|
|
1125
|
+
"hmm",
|
|
1126
|
+
"hm",
|
|
1127
|
+
"uh huh",
|
|
1128
|
+
"uh hum",
|
|
1129
|
+
"um",
|
|
1130
|
+
"uh",
|
|
1131
|
+
"er",
|
|
1132
|
+
"ah",
|
|
1133
|
+
"oh",
|
|
1134
|
+
"oh ok",
|
|
1135
|
+
"oh okay",
|
|
1136
|
+
"ok",
|
|
1137
|
+
"okay",
|
|
1138
|
+
"ok ok",
|
|
1139
|
+
"okay okay",
|
|
1140
|
+
"yeah",
|
|
1141
|
+
"yeah yeah",
|
|
1142
|
+
"yes",
|
|
1143
|
+
"yep",
|
|
1144
|
+
"yup",
|
|
1145
|
+
"right",
|
|
1146
|
+
"sure",
|
|
1147
|
+
"alright",
|
|
1148
|
+
"all right",
|
|
1149
|
+
"i see",
|
|
1150
|
+
"got it",
|
|
1151
|
+
"cool",
|
|
1152
|
+
"nice",
|
|
1153
|
+
"great",
|
|
1154
|
+
"thanks",
|
|
1155
|
+
"thank you",
|
|
1156
|
+
"ehen",
|
|
1157
|
+
"ehn",
|
|
1158
|
+
"na so",
|
|
1159
|
+
"true",
|
|
1160
|
+
"i hear",
|
|
1161
|
+
"o",
|
|
1162
|
+
"oh o"
|
|
1163
|
+
]);
|
|
1164
|
+
const INTERRUPT_WORDS = /* @__PURE__ */ new Set([
|
|
1165
|
+
"stop",
|
|
1166
|
+
"wait",
|
|
1167
|
+
"pause",
|
|
1168
|
+
"quiet",
|
|
1169
|
+
"hold",
|
|
1170
|
+
"no",
|
|
1171
|
+
"sorry",
|
|
1172
|
+
"excuse",
|
|
1173
|
+
"cancel",
|
|
1174
|
+
"enough",
|
|
1175
|
+
"abeg",
|
|
1176
|
+
"shh",
|
|
1177
|
+
"shush"
|
|
1178
|
+
]);
|
|
1179
|
+
const SHORT_TURN_GRACE_MS = 1200;
|
|
1180
|
+
const HELD_WORDS_TTL_MS = 2e4;
|
|
1181
|
+
const CONTINUATION_TIMEOUT_MS = 8e3;
|
|
1182
|
+
const HOLD_HEADS = [
|
|
1183
|
+
"wait",
|
|
1184
|
+
"hold on",
|
|
1185
|
+
"hold up",
|
|
1186
|
+
"hang on",
|
|
1187
|
+
"sec",
|
|
1188
|
+
"second",
|
|
1189
|
+
"moment",
|
|
1190
|
+
"minute",
|
|
1191
|
+
"sorry",
|
|
1192
|
+
"pause",
|
|
1193
|
+
"shh",
|
|
1194
|
+
"shush",
|
|
1195
|
+
"not yet",
|
|
1196
|
+
"let me think",
|
|
1197
|
+
"let me see",
|
|
1198
|
+
"let me check",
|
|
1199
|
+
"brb",
|
|
1200
|
+
"be right back",
|
|
1201
|
+
"slow down",
|
|
1202
|
+
"too fast"
|
|
1203
|
+
];
|
|
1204
|
+
const HOLD_WORDS = /* @__PURE__ */ new Set([
|
|
1205
|
+
"wait",
|
|
1206
|
+
"hold",
|
|
1207
|
+
"on",
|
|
1208
|
+
"up",
|
|
1209
|
+
"hang",
|
|
1210
|
+
"one",
|
|
1211
|
+
"a",
|
|
1212
|
+
"sec",
|
|
1213
|
+
"secs",
|
|
1214
|
+
"second",
|
|
1215
|
+
"seconds",
|
|
1216
|
+
"moment",
|
|
1217
|
+
"minute",
|
|
1218
|
+
"min",
|
|
1219
|
+
"just",
|
|
1220
|
+
"give",
|
|
1221
|
+
"me",
|
|
1222
|
+
"sorry",
|
|
1223
|
+
"pause",
|
|
1224
|
+
"shh",
|
|
1225
|
+
"shush",
|
|
1226
|
+
"not",
|
|
1227
|
+
"yet",
|
|
1228
|
+
"let",
|
|
1229
|
+
"think",
|
|
1230
|
+
"see",
|
|
1231
|
+
"check",
|
|
1232
|
+
"something",
|
|
1233
|
+
"i'm",
|
|
1234
|
+
"im",
|
|
1235
|
+
"i",
|
|
1236
|
+
"am",
|
|
1237
|
+
"coming",
|
|
1238
|
+
"come",
|
|
1239
|
+
"back",
|
|
1240
|
+
"be",
|
|
1241
|
+
"right",
|
|
1242
|
+
"brb",
|
|
1243
|
+
"abeg",
|
|
1244
|
+
"small",
|
|
1245
|
+
"please",
|
|
1246
|
+
"ok",
|
|
1247
|
+
"okay",
|
|
1248
|
+
"oh",
|
|
1249
|
+
"um",
|
|
1250
|
+
"uh",
|
|
1251
|
+
"no",
|
|
1252
|
+
"yeah",
|
|
1253
|
+
"you're",
|
|
1254
|
+
"youre",
|
|
1255
|
+
"you",
|
|
1256
|
+
"are",
|
|
1257
|
+
"too",
|
|
1258
|
+
"fast",
|
|
1259
|
+
"slow",
|
|
1260
|
+
"down",
|
|
1261
|
+
"again"
|
|
1262
|
+
]);
|
|
1263
|
+
const DANGLING_ENDINGS = /* @__PURE__ */ new Set([
|
|
1264
|
+
"and",
|
|
1265
|
+
"but",
|
|
1266
|
+
"or",
|
|
1267
|
+
"so",
|
|
1268
|
+
"because",
|
|
1269
|
+
"cause",
|
|
1270
|
+
"cuz",
|
|
1271
|
+
"the",
|
|
1272
|
+
"a",
|
|
1273
|
+
"an",
|
|
1274
|
+
"to",
|
|
1275
|
+
"of",
|
|
1276
|
+
"for",
|
|
1277
|
+
"with",
|
|
1278
|
+
"from",
|
|
1279
|
+
"into",
|
|
1280
|
+
"about",
|
|
1281
|
+
"my",
|
|
1282
|
+
"your",
|
|
1283
|
+
"our",
|
|
1284
|
+
"their",
|
|
1285
|
+
"is",
|
|
1286
|
+
"are",
|
|
1287
|
+
"was",
|
|
1288
|
+
"were",
|
|
1289
|
+
"am",
|
|
1290
|
+
"i",
|
|
1291
|
+
"i'm",
|
|
1292
|
+
"im",
|
|
1293
|
+
"we",
|
|
1294
|
+
"if",
|
|
1295
|
+
"when",
|
|
1296
|
+
"whether",
|
|
1297
|
+
"than",
|
|
1298
|
+
"like",
|
|
1299
|
+
"can",
|
|
1300
|
+
"could",
|
|
1301
|
+
"should",
|
|
1302
|
+
"would",
|
|
1303
|
+
"will",
|
|
1304
|
+
"gonna",
|
|
1305
|
+
"wanna",
|
|
1306
|
+
"want",
|
|
1307
|
+
"need",
|
|
1308
|
+
"trying",
|
|
1309
|
+
"also",
|
|
1310
|
+
"plus",
|
|
1311
|
+
"which",
|
|
1312
|
+
"who",
|
|
1313
|
+
"let",
|
|
1314
|
+
"how",
|
|
1315
|
+
"what",
|
|
1316
|
+
"where",
|
|
1317
|
+
"why"
|
|
1318
|
+
]);
|
|
1319
|
+
const OPENING_FILLERS = /* @__PURE__ */ new Set([
|
|
1320
|
+
"um",
|
|
1321
|
+
"umm",
|
|
1322
|
+
"uh",
|
|
1323
|
+
"er",
|
|
1324
|
+
"erm",
|
|
1325
|
+
"hmm",
|
|
1326
|
+
"so",
|
|
1327
|
+
"okay",
|
|
1328
|
+
"ok",
|
|
1329
|
+
"and",
|
|
1330
|
+
"well",
|
|
1331
|
+
"yeah",
|
|
1332
|
+
"alright",
|
|
1333
|
+
"like",
|
|
1334
|
+
"oh",
|
|
1335
|
+
"now"
|
|
1336
|
+
]);
|
|
1337
|
+
const PREAMBLE = new RegExp("^(?:what (?:i|we) (?:really )?(?:want|need|wanna|would like|d like|(?:i'm|im|am) trying|was trying|was going|was gonna|mean)(?: to(?: do| ask| say| know)?| is)?|the thing is|here s the thing|here is the thing|my question is|the question is|question|i have a question|i (?:want|wanna) to ask(?: you)?|i wanna ask(?: you)?|let me ask(?: you)?|i was (?:going to|gonna) (?:say|ask)|basically|i mean)$");
|
|
1338
|
+
function thinkingAloudSchedule() {
|
|
1339
|
+
const delays = [...THINKING_ALOUD_AT_MS];
|
|
1340
|
+
for (let at = delays[delays.length - 1] + STILL_WORKING_EVERY_MS; at <= STILL_WORKING_UNTIL_MS; at += STILL_WORKING_EVERY_MS) {
|
|
1341
|
+
delays.push(at);
|
|
1342
|
+
}
|
|
1343
|
+
return delays;
|
|
1344
|
+
}
|
|
1345
|
+
function normalizeUtterance(text) {
|
|
1346
|
+
return text.toLowerCase().replace(/[’‘]/g, "'").replace(/[-_]/g, " ").replace(/[^\p{L}\p{N}\s']/gu, " ").split(/\s+/).filter(Boolean);
|
|
1347
|
+
}
|
|
1348
|
+
function classifyUtterance(text, answersQuestion = false) {
|
|
1349
|
+
const words = normalizeUtterance(text);
|
|
1350
|
+
if (!words.length) return "complete";
|
|
1351
|
+
const joined = ` ${words.join(" ")} `;
|
|
1352
|
+
if (words.length <= 8 && HOLD_HEADS.some((head) => joined.includes(` ${head} `)) && words.every((word) => HOLD_WORDS.has(word))) {
|
|
1353
|
+
return "hold";
|
|
1354
|
+
}
|
|
1355
|
+
const raw = text.trim();
|
|
1356
|
+
const asks = /\?["')\]]*$/.test(raw);
|
|
1357
|
+
if (/(?:\.\.\.|…|[,:\-–—])["')\]]*$/.test(raw)) return "incomplete";
|
|
1358
|
+
if (!asks) {
|
|
1359
|
+
if (DANGLING_ENDINGS.has(words[words.length - 1])) return "incomplete";
|
|
1360
|
+
let start = 0;
|
|
1361
|
+
while (start < words.length - 1 && OPENING_FILLERS.has(words[start])) start += 1;
|
|
1362
|
+
if (PREAMBLE.test(words.slice(start).join(" ").replace(/'/g, " ").replace(/\bi m\b/g, "im"))) {
|
|
1363
|
+
return "incomplete";
|
|
1364
|
+
}
|
|
1365
|
+
}
|
|
1366
|
+
if (answersQuestion) return "complete";
|
|
1367
|
+
if (BACKCHANNELS.has(words.join(" "))) return "acknowledgement";
|
|
1368
|
+
const unspaced = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Thai}]/u.test(raw);
|
|
1369
|
+
if (unspaced) return words.join("").length <= 3 ? "short" : "complete";
|
|
1370
|
+
return words.length <= 2 ? "short" : "complete";
|
|
1371
|
+
}
|
|
1372
|
+
function isBackchannel(text) {
|
|
1373
|
+
const words = normalizeUtterance(text);
|
|
1374
|
+
return words.length > 0 && BACKCHANNELS.has(words.join(" "));
|
|
1375
|
+
}
|
|
1376
|
+
function isFillerOnly(text, answersQuestion = false) {
|
|
1377
|
+
const words = normalizeUtterance(text);
|
|
1378
|
+
if (!words.length) return false;
|
|
1379
|
+
if (AGREEMENT_SOUNDS.has(words.join(" "))) return !answersQuestion;
|
|
1380
|
+
return words.every((word) => HESITATIONS.has(word));
|
|
1381
|
+
}
|
|
1382
|
+
function isEchoOf(heard, spoken) {
|
|
1383
|
+
const words = normalizeUtterance(heard);
|
|
1384
|
+
const said = normalizeUtterance(spoken);
|
|
1385
|
+
if (!words.length || !said.length) return false;
|
|
1386
|
+
const last = words.length - 1;
|
|
1387
|
+
const matches = (word, index, spokenWord) => word === spokenWord || index === last && spokenWord.startsWith(word) || word.length >= 4 && spokenWord.length >= 4 && word.slice(0, 3) === spokenWord.slice(0, 3) && Math.abs(word.length - spokenWord.length) <= 4;
|
|
1388
|
+
const known = words.filter((word, index) => said.some((spokenWord) => matches(word, index, spokenWord))).length;
|
|
1389
|
+
if (known / words.length < 0.6) return false;
|
|
1390
|
+
if (words.length === 1) return true;
|
|
1391
|
+
let inOrder = 0;
|
|
1392
|
+
for (let index = 1; index < words.length; index += 1) {
|
|
1393
|
+
const follows = said.some((spokenWord, at) => at > 0 && matches(words[index - 1], index - 1, said[at - 1]) && matches(words[index], index, spokenWord));
|
|
1394
|
+
if (follows) inOrder += 1;
|
|
1395
|
+
}
|
|
1396
|
+
return inOrder / last >= 0.5;
|
|
1397
|
+
}
|
|
1398
|
+
function createFenceFilter() {
|
|
1399
|
+
let carry = "";
|
|
1400
|
+
let inFence = false;
|
|
1401
|
+
return (delta) => {
|
|
1402
|
+
var _a, _b;
|
|
1403
|
+
let text = carry + delta;
|
|
1404
|
+
carry = "";
|
|
1405
|
+
let out = "";
|
|
1406
|
+
while (text) {
|
|
1407
|
+
const fence = text.indexOf("```");
|
|
1408
|
+
if (fence < 0) {
|
|
1409
|
+
const tail = (_b = (_a = /`{1,2}$/.exec(text)) == null ? void 0 : _a[0]) != null ? _b : "";
|
|
1410
|
+
if (!inFence) out += text.slice(0, text.length - tail.length);
|
|
1411
|
+
carry = tail;
|
|
1412
|
+
break;
|
|
1413
|
+
}
|
|
1414
|
+
if (!inFence) out += text.slice(0, fence);
|
|
1415
|
+
inFence = !inFence;
|
|
1416
|
+
text = text.slice(fence + 3);
|
|
1417
|
+
}
|
|
1418
|
+
return out;
|
|
1419
|
+
};
|
|
1420
|
+
}
|
|
1421
|
+
function isRealInterruption(text) {
|
|
1422
|
+
const words = normalizeUtterance(text);
|
|
1423
|
+
if (!words.length) return false;
|
|
1424
|
+
if (words.some((word) => INTERRUPT_WORDS.has(word))) return true;
|
|
1425
|
+
if (BACKCHANNELS.has(words.join(" "))) return false;
|
|
1426
|
+
return words.length >= 2;
|
|
1427
|
+
}
|
|
1428
|
+
class PcmStreamPlayer {
|
|
1429
|
+
constructor(options = {}) {
|
|
1430
|
+
this.options = options;
|
|
1431
|
+
this.context = null;
|
|
1432
|
+
this.output = null;
|
|
1433
|
+
this.sources = /* @__PURE__ */ new Set();
|
|
1434
|
+
this.idleWaiters = /* @__PURE__ */ new Set();
|
|
1435
|
+
this.nextOutputAt = 0;
|
|
1436
|
+
this.playbackEpoch = 0;
|
|
1437
|
+
this.lastAudibleAt = 0;
|
|
1438
|
+
}
|
|
1439
|
+
async prepare() {
|
|
1440
|
+
var _a;
|
|
1441
|
+
const context = (_a = this.context) != null ? _a : this.createContext();
|
|
1442
|
+
this.context = context;
|
|
1443
|
+
if (!this.output && typeof context.createGain === "function") {
|
|
1444
|
+
this.output = context.createGain();
|
|
1445
|
+
this.output.connect(context.destination);
|
|
1446
|
+
}
|
|
1447
|
+
if (context.state === "suspended") {
|
|
1448
|
+
try {
|
|
1449
|
+
await context.resume();
|
|
1450
|
+
} catch {
|
|
1451
|
+
}
|
|
1452
|
+
}
|
|
1453
|
+
if (this.sources.size === 0) this.nextOutputAt = context.currentTime;
|
|
1454
|
+
}
|
|
1455
|
+
/** Play a speech response, or a stream of its PCM chunks (a ReadableStream fits). */
|
|
1456
|
+
async play(source, signal) {
|
|
1457
|
+
var _a, _b;
|
|
1458
|
+
await this.prepare();
|
|
1459
|
+
const reader = "getReader" in source ? source.getReader() : (_a = source.body) == null ? void 0 : _a.getReader();
|
|
1460
|
+
if (!reader) throw new Error("Pipeline speech stream is unreadable.");
|
|
1461
|
+
const epoch = ++this.playbackEpoch;
|
|
1462
|
+
let carry = new Uint8Array(0);
|
|
1463
|
+
try {
|
|
1464
|
+
while (!signal.aborted && epoch === this.playbackEpoch) {
|
|
1465
|
+
const { done, value } = await reader.read();
|
|
1466
|
+
if (done) break;
|
|
1467
|
+
if (!(value == null ? void 0 : value.byteLength)) continue;
|
|
1468
|
+
const merged = new Uint8Array(carry.byteLength + value.byteLength);
|
|
1469
|
+
merged.set(carry);
|
|
1470
|
+
merged.set(value, carry.byteLength);
|
|
1471
|
+
const evenLength = merged.byteLength - merged.byteLength % 2;
|
|
1472
|
+
if (evenLength) this.schedule(merged.subarray(0, evenLength));
|
|
1473
|
+
carry = merged.slice(evenLength);
|
|
1474
|
+
}
|
|
1475
|
+
} finally {
|
|
1476
|
+
try {
|
|
1477
|
+
await ((_b = reader.cancel) == null ? void 0 : _b.call(reader));
|
|
1478
|
+
} catch {
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
await this.waitUntilIdle(signal, epoch);
|
|
1482
|
+
}
|
|
1483
|
+
/**
|
|
1484
|
+
* A short rising two-note tone: "you can talk now". Synthesized locally, so
|
|
1485
|
+
* it costs no TTS request and plays the instant the session is ready.
|
|
1486
|
+
*/
|
|
1487
|
+
cue() {
|
|
1488
|
+
const context = this.context;
|
|
1489
|
+
if (!context || context.state !== "running") return;
|
|
1490
|
+
try {
|
|
1491
|
+
const start = context.currentTime + 0.01;
|
|
1492
|
+
for (const [offset, frequency] of [[0, 660], [0.1, 880]]) {
|
|
1493
|
+
const oscillator = context.createOscillator();
|
|
1494
|
+
const gain = context.createGain();
|
|
1495
|
+
oscillator.type = "sine";
|
|
1496
|
+
oscillator.frequency.value = frequency;
|
|
1497
|
+
gain.gain.setValueAtTime(1e-4, start + offset);
|
|
1498
|
+
gain.gain.exponentialRampToValueAtTime(0.08, start + offset + 0.015);
|
|
1499
|
+
gain.gain.exponentialRampToValueAtTime(1e-4, start + offset + 0.09);
|
|
1500
|
+
oscillator.connect(gain);
|
|
1501
|
+
gain.connect(context.destination);
|
|
1502
|
+
oscillator.start(start + offset);
|
|
1503
|
+
oscillator.stop(start + offset + 0.1);
|
|
1504
|
+
}
|
|
1505
|
+
} catch {
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
/**
|
|
1509
|
+
* Lower (or restore) the voice without stopping it: the assistant yields
|
|
1510
|
+
* while it works out whether the visitor is really interrupting.
|
|
1511
|
+
*/
|
|
1512
|
+
duck(level) {
|
|
1513
|
+
const output = this.output;
|
|
1514
|
+
const context = this.context;
|
|
1515
|
+
if (!output || !context) return;
|
|
1516
|
+
try {
|
|
1517
|
+
output.gain.cancelScheduledValues(context.currentTime);
|
|
1518
|
+
output.gain.setTargetAtTime(level, context.currentTime, 0.03);
|
|
1519
|
+
} catch {
|
|
1520
|
+
output.gain.value = level;
|
|
1521
|
+
}
|
|
1522
|
+
}
|
|
1523
|
+
/**
|
|
1524
|
+
* Sound is coming out of the speaker now, or stopped within `withinMs`.
|
|
1525
|
+
* The visible state can say "listening" while a filler still plays.
|
|
1526
|
+
*/
|
|
1527
|
+
isAudible(withinMs = 0) {
|
|
1528
|
+
return this.sources.size > 0 || withinMs > 0 && Date.now() - this.lastAudibleAt < withinMs;
|
|
1529
|
+
}
|
|
1530
|
+
stop() {
|
|
1531
|
+
if (this.sources.size) this.lastAudibleAt = Date.now();
|
|
1532
|
+
this.playbackEpoch += 1;
|
|
1533
|
+
for (const source of this.sources) {
|
|
1534
|
+
try {
|
|
1535
|
+
source.stop();
|
|
1536
|
+
} catch {
|
|
1537
|
+
}
|
|
1538
|
+
}
|
|
1539
|
+
this.sources.clear();
|
|
1540
|
+
if (this.context) this.nextOutputAt = this.context.currentTime;
|
|
1541
|
+
this.notifyIdleWaiters();
|
|
1542
|
+
}
|
|
1543
|
+
close() {
|
|
1544
|
+
this.stop();
|
|
1545
|
+
const context = this.context;
|
|
1546
|
+
this.context = null;
|
|
1547
|
+
this.output = null;
|
|
1548
|
+
if (context) void context.close().catch(() => void 0);
|
|
1549
|
+
}
|
|
1550
|
+
createContext() {
|
|
1551
|
+
if (this.options.audioContextFactory) return this.options.audioContextFactory();
|
|
1552
|
+
const Context = typeof AudioContext !== "undefined" ? AudioContext : window.webkitAudioContext;
|
|
1553
|
+
return new Context();
|
|
1554
|
+
}
|
|
1555
|
+
schedule(bytes) {
|
|
1556
|
+
var _a;
|
|
1557
|
+
const context = this.context;
|
|
1558
|
+
if (!context || !bytes.byteLength) return;
|
|
1559
|
+
const samples = Math.floor(bytes.byteLength / 2);
|
|
1560
|
+
const buffer = context.createBuffer(1, samples, PCM_SAMPLE_RATE);
|
|
1561
|
+
const channel = buffer.getChannelData(0);
|
|
1562
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, samples * 2);
|
|
1563
|
+
for (let index = 0; index < samples; index += 1) {
|
|
1564
|
+
channel[index] = view.getInt16(index * 2, true) / 32768;
|
|
1565
|
+
}
|
|
1566
|
+
const source = context.createBufferSource();
|
|
1567
|
+
source.buffer = buffer;
|
|
1568
|
+
source.connect((_a = this.output) != null ? _a : context.destination);
|
|
1569
|
+
source.onended = () => {
|
|
1570
|
+
this.sources.delete(source);
|
|
1571
|
+
this.lastAudibleAt = Date.now();
|
|
1572
|
+
this.notifyIdleWaiters();
|
|
1573
|
+
};
|
|
1574
|
+
const lead = this.sources.size === 0 ? PCM_START_BUFFER_SECONDS : 0;
|
|
1575
|
+
const startAt = Math.max(context.currentTime + lead, this.nextOutputAt);
|
|
1576
|
+
source.start(startAt);
|
|
1577
|
+
this.nextOutputAt = startAt + buffer.duration;
|
|
1578
|
+
this.sources.add(source);
|
|
1579
|
+
}
|
|
1580
|
+
waitUntilIdle(signal, epoch) {
|
|
1581
|
+
if (signal.aborted || epoch !== this.playbackEpoch || this.sources.size === 0) {
|
|
1582
|
+
return Promise.resolve();
|
|
1583
|
+
}
|
|
1584
|
+
return new Promise((resolve) => {
|
|
1585
|
+
const finish = () => {
|
|
1586
|
+
if (!signal.aborted && epoch === this.playbackEpoch && this.sources.size > 0) return;
|
|
1587
|
+
signal.removeEventListener("abort", finish);
|
|
1588
|
+
this.idleWaiters.delete(finish);
|
|
1589
|
+
resolve();
|
|
1590
|
+
};
|
|
1591
|
+
this.idleWaiters.add(finish);
|
|
1592
|
+
signal.addEventListener("abort", finish, { once: true });
|
|
1593
|
+
finish();
|
|
1594
|
+
});
|
|
1595
|
+
}
|
|
1596
|
+
notifyIdleWaiters() {
|
|
1597
|
+
for (const waiter of [...this.idleWaiters]) waiter();
|
|
1598
|
+
}
|
|
1599
|
+
}
|
|
1600
|
+
class PipelineVoiceAgent {
|
|
1601
|
+
constructor(options) {
|
|
1602
|
+
var _a, _b;
|
|
1603
|
+
this.options = options;
|
|
1604
|
+
this.cleanupEvent = null;
|
|
1605
|
+
this.cleanupState = null;
|
|
1606
|
+
this.speechAbort = null;
|
|
1607
|
+
this.turnEpoch = 0;
|
|
1608
|
+
this.currentTurnId = null;
|
|
1609
|
+
this.transcript = "";
|
|
1610
|
+
this.activity = "listening";
|
|
1611
|
+
this.activityBeforeSpeech = "listening";
|
|
1612
|
+
this.started = false;
|
|
1613
|
+
this.ready = false;
|
|
1614
|
+
this.awaitingSessionUpdate = false;
|
|
1615
|
+
this.readyTimer = null;
|
|
1616
|
+
this.pendingInterruption = false;
|
|
1617
|
+
this.interruptionTimer = null;
|
|
1618
|
+
this.lastAnswerAsked = false;
|
|
1619
|
+
this.fillerDucked = false;
|
|
1620
|
+
this.held = null;
|
|
1621
|
+
this.heldTimer = null;
|
|
1622
|
+
this.grace = null;
|
|
1623
|
+
this.graceTimer = null;
|
|
1624
|
+
this.spoken = [];
|
|
1625
|
+
this.speechEndedAt = 0;
|
|
1626
|
+
this.heardOverSpeech = false;
|
|
1627
|
+
this.reassuredAt = 0;
|
|
1628
|
+
this.greeting = false;
|
|
1629
|
+
this.inFlight = null;
|
|
1630
|
+
this.telemetry = (_a = options.telemetry) != null ? _a : new VoiceTelemetry();
|
|
1631
|
+
this.player = (_b = options.player) != null ? _b : new PcmStreamPlayer();
|
|
1632
|
+
}
|
|
1633
|
+
async start() {
|
|
1634
|
+
if (this.started) return;
|
|
1635
|
+
this.started = true;
|
|
1636
|
+
this.cleanupEvent = this.options.inputTransport.subscribeEvents((event) => {
|
|
1637
|
+
void this.handleEvent(event).catch((error) => this.report(error));
|
|
1638
|
+
});
|
|
1639
|
+
this.cleanupState = this.options.inputTransport.subscribeState((state2) => {
|
|
1640
|
+
var _a, _b;
|
|
1641
|
+
if (state2 === "connected") {
|
|
1642
|
+
this.armReadyTimeout();
|
|
1643
|
+
return;
|
|
1644
|
+
}
|
|
1645
|
+
this.ready = false;
|
|
1646
|
+
this.clearReadyTimer();
|
|
1647
|
+
(_b = (_a = this.options).onState) == null ? void 0 : _b.call(_a, state2);
|
|
1648
|
+
});
|
|
1649
|
+
try {
|
|
1650
|
+
await this.player.prepare();
|
|
1651
|
+
const session = this.transcriptionSession();
|
|
1652
|
+
this.awaitingSessionUpdate = this.options.inputTransport.supportsSessionUpdates;
|
|
1653
|
+
await this.options.inputTransport.connect(session);
|
|
1654
|
+
if (this.options.inputTransport.supportsSessionUpdates) {
|
|
1655
|
+
this.options.inputTransport.updateSession(session);
|
|
1656
|
+
}
|
|
1657
|
+
} catch (error) {
|
|
1658
|
+
this.started = false;
|
|
1659
|
+
this.cleanup();
|
|
1660
|
+
this.options.inputTransport.disconnect();
|
|
1661
|
+
throw error;
|
|
1662
|
+
}
|
|
1663
|
+
}
|
|
1664
|
+
stop() {
|
|
1665
|
+
var _a;
|
|
1666
|
+
if (!this.started) return;
|
|
1667
|
+
this.started = false;
|
|
1668
|
+
this.ready = false;
|
|
1669
|
+
this.clearReadyTimer();
|
|
1670
|
+
this.clearPendingInterruption();
|
|
1671
|
+
this.clearGrace();
|
|
1672
|
+
this.clearHeld();
|
|
1673
|
+
this.turnEpoch += 1;
|
|
1674
|
+
(_a = this.speechAbort) == null ? void 0 : _a.abort();
|
|
1675
|
+
this.speechAbort = null;
|
|
1676
|
+
this.player.close();
|
|
1677
|
+
this.options.inputTransport.disconnect();
|
|
1678
|
+
this.cleanup();
|
|
1679
|
+
this.currentTurnId = null;
|
|
1680
|
+
this.transcript = "";
|
|
1681
|
+
}
|
|
1682
|
+
/**
|
|
1683
|
+
* Say a line the agent did not have to think about — the opening line of a
|
|
1684
|
+
* conversation it starts — as its own turn, in the session's voice, then
|
|
1685
|
+
* listen. The mic stays open, so the visitor can talk over it. The caller
|
|
1686
|
+
* has already put the line in the chat.
|
|
1687
|
+
*/
|
|
1688
|
+
async speakLine(text) {
|
|
1689
|
+
var _a;
|
|
1690
|
+
const line = text.trim().slice(0, 8e3);
|
|
1691
|
+
if (!this.started || !line) return false;
|
|
1692
|
+
this.clearGrace();
|
|
1693
|
+
this.clearHeld();
|
|
1694
|
+
const epoch = ++this.turnEpoch;
|
|
1695
|
+
(_a = this.speechAbort) == null ? void 0 : _a.abort();
|
|
1696
|
+
this.speechAbort = null;
|
|
1697
|
+
this.player.stop();
|
|
1698
|
+
this.player.duck(1);
|
|
1699
|
+
this.greeting = true;
|
|
1700
|
+
this.lastAnswerAsked = /\?[^\p{L}\p{N}]*$/u.test(line);
|
|
1701
|
+
try {
|
|
1702
|
+
let spoken;
|
|
1703
|
+
if (isStreamingSpeechProvider(this.options.speechProvider)) {
|
|
1704
|
+
const streaming = this.streamingSpeech(this.options.speechProvider, epoch);
|
|
1705
|
+
streaming.finish(line);
|
|
1706
|
+
spoken = await streaming.played();
|
|
1707
|
+
} else {
|
|
1708
|
+
this.noteSpoken(line);
|
|
1709
|
+
spoken = await this.playSpeech(line, epoch, "pipeline_tts_wait", "tts_first_byte_ms");
|
|
1710
|
+
}
|
|
1711
|
+
if (spoken && this.started && epoch === this.turnEpoch) this.setActivity("listening");
|
|
1712
|
+
return spoken;
|
|
1713
|
+
} catch (error) {
|
|
1714
|
+
if (isAbortError(error)) return false;
|
|
1715
|
+
if (epoch === this.turnEpoch && this.started) this.report(error);
|
|
1716
|
+
return false;
|
|
1717
|
+
} finally {
|
|
1718
|
+
this.greeting = false;
|
|
1719
|
+
}
|
|
1720
|
+
}
|
|
1721
|
+
/**
|
|
1722
|
+
* A turn the visitor gave without saying it — a tapped reply chip — taken
|
|
1723
|
+
* and answered aloud exactly as a spoken one would be.
|
|
1724
|
+
*/
|
|
1725
|
+
async submitText(text) {
|
|
1726
|
+
const said = text.trim();
|
|
1727
|
+
if (!this.started || !said) return;
|
|
1728
|
+
await this.commitTurn(said, null, null);
|
|
1729
|
+
}
|
|
1730
|
+
destroy() {
|
|
1731
|
+
this.stop();
|
|
1732
|
+
}
|
|
1733
|
+
isStarted() {
|
|
1734
|
+
return this.started;
|
|
1735
|
+
}
|
|
1736
|
+
setMuted(muted) {
|
|
1737
|
+
this.options.inputTransport.setMuted(muted);
|
|
1738
|
+
}
|
|
1739
|
+
transcriptionSession() {
|
|
1740
|
+
const language = this.options.language;
|
|
1741
|
+
return {
|
|
1742
|
+
type: "transcription",
|
|
1743
|
+
audio: {
|
|
1744
|
+
input: {
|
|
1745
|
+
noise_reduction: { type: "far_field" },
|
|
1746
|
+
transcription: {
|
|
1747
|
+
model: DEFAULT_TRANSCRIPTION_MODEL,
|
|
1748
|
+
...(language == null ? void 0 : language.transcriptionLanguages.length) ? { language: language.transcriptionLanguages[0] } : {},
|
|
1749
|
+
...(language == null ? void 0 : language.transcriptionPrompt) ? { prompt: language.transcriptionPrompt } : {}
|
|
1750
|
+
},
|
|
1751
|
+
turn_detection: conversationalTurnDetection()
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1754
|
+
};
|
|
1755
|
+
}
|
|
1756
|
+
armReadyTimeout() {
|
|
1757
|
+
if (this.ready || this.readyTimer) return;
|
|
1758
|
+
this.readyTimer = setTimeout(() => {
|
|
1759
|
+
this.readyTimer = null;
|
|
1760
|
+
this.telemetry.record("session_ready_timeout", SESSION_READY_TIMEOUT_MS);
|
|
1761
|
+
this.markReady();
|
|
1762
|
+
}, SESSION_READY_TIMEOUT_MS);
|
|
1763
|
+
}
|
|
1764
|
+
clearReadyTimer() {
|
|
1765
|
+
if (this.readyTimer) clearTimeout(this.readyTimer);
|
|
1766
|
+
this.readyTimer = null;
|
|
1767
|
+
}
|
|
1768
|
+
confirmInterruption() {
|
|
1769
|
+
var _a;
|
|
1770
|
+
if (!this.pendingInterruption) return;
|
|
1771
|
+
const inFlight = this.inFlight;
|
|
1772
|
+
if (inFlight && inFlight.epoch === this.turnEpoch && !inFlight.answering()) {
|
|
1773
|
+
this.clearPendingInterruption();
|
|
1774
|
+
this.player.duck(DUCKED_VOLUME);
|
|
1775
|
+
this.fillerDucked = true;
|
|
1776
|
+
return;
|
|
1777
|
+
}
|
|
1778
|
+
this.clearPendingInterruption();
|
|
1779
|
+
this.turnEpoch += 1;
|
|
1780
|
+
(_a = this.speechAbort) == null ? void 0 : _a.abort();
|
|
1781
|
+
this.speechAbort = null;
|
|
1782
|
+
this.player.stop();
|
|
1783
|
+
this.player.duck(1);
|
|
1784
|
+
this.telemetry.record("barge_in", 1);
|
|
1785
|
+
this.setActivity("listening");
|
|
1786
|
+
}
|
|
1787
|
+
clearPendingInterruption() {
|
|
1788
|
+
this.pendingInterruption = false;
|
|
1789
|
+
if (this.interruptionTimer) clearTimeout(this.interruptionTimer);
|
|
1790
|
+
this.interruptionTimer = null;
|
|
1791
|
+
}
|
|
1792
|
+
markReady() {
|
|
1793
|
+
var _a, _b;
|
|
1794
|
+
if (this.ready || !this.started) return;
|
|
1795
|
+
this.ready = true;
|
|
1796
|
+
this.awaitingSessionUpdate = false;
|
|
1797
|
+
this.clearReadyTimer();
|
|
1798
|
+
(_b = (_a = this.options).onState) == null ? void 0 : _b.call(_a, "connected");
|
|
1799
|
+
if (this.activity === "speaking") return;
|
|
1800
|
+
this.setActivity("listening");
|
|
1801
|
+
if (!this.greeting) this.player.cue();
|
|
1802
|
+
}
|
|
1803
|
+
async handleEvent(event) {
|
|
1804
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n;
|
|
1805
|
+
if (SESSION_UPDATED_EVENTS.has(event.type) || SESSION_CREATED_EVENTS.has(event.type) && !this.awaitingSessionUpdate) {
|
|
1806
|
+
this.markReady();
|
|
1807
|
+
return;
|
|
1808
|
+
}
|
|
1809
|
+
switch (event.type) {
|
|
1810
|
+
case "input_audio_buffer.speech_started": {
|
|
1811
|
+
if (this.grace) {
|
|
1812
|
+
const { text, turnId } = this.grace;
|
|
1813
|
+
this.clearGrace();
|
|
1814
|
+
this.hold(text, turnId, true);
|
|
1815
|
+
}
|
|
1816
|
+
this.activityBeforeSpeech = this.activity;
|
|
1817
|
+
this.heardOverSpeech = this.activity === "speaking" || Date.now() - this.speechEndedAt < ECHO_ONSET_MS || !!((_b = (_a = this.player).isAudible) == null ? void 0 : _b.call(_a, ECHO_ONSET_MS));
|
|
1818
|
+
this.telemetry.mark("pipeline_user_speech");
|
|
1819
|
+
this.transcript = "";
|
|
1820
|
+
if (this.activityBeforeSpeech === "speaking") {
|
|
1821
|
+
this.pendingInterruption = true;
|
|
1822
|
+
this.player.duck(DUCKED_VOLUME);
|
|
1823
|
+
if (!this.options.inputTransport.interimTranscripts) {
|
|
1824
|
+
this.interruptionTimer = setTimeout(() => this.confirmInterruption(), INTERRUPTION_CONFIRM_MS);
|
|
1825
|
+
}
|
|
1826
|
+
} else {
|
|
1827
|
+
this.setActivity("listening");
|
|
1828
|
+
}
|
|
1829
|
+
this.currentTurnId = event.item_id || `voice_${Date.now()}`;
|
|
1830
|
+
return;
|
|
1831
|
+
}
|
|
1832
|
+
case "input_audio_buffer.speech_stopped":
|
|
1833
|
+
if (!this.pendingInterruption) return;
|
|
1834
|
+
if (this.interruptionTimer) clearTimeout(this.interruptionTimer);
|
|
1835
|
+
this.interruptionTimer = setTimeout(() => {
|
|
1836
|
+
this.interruptionTimer = null;
|
|
1837
|
+
if (!this.pendingInterruption) return;
|
|
1838
|
+
this.clearPendingInterruption();
|
|
1839
|
+
this.player.duck(1);
|
|
1840
|
+
}, TRANSCRIPT_VERDICT_TIMEOUT_MS);
|
|
1841
|
+
return;
|
|
1842
|
+
case "conversation.item.input_audio_transcription.delta":
|
|
1843
|
+
case "input_audio_transcription.delta":
|
|
1844
|
+
this.transcript += String((_c = event.delta) != null ? _c : "");
|
|
1845
|
+
this.emitHeard();
|
|
1846
|
+
if (this.pendingInterruption && isRealInterruption(this.transcript) && !this.isOwnEcho(this.transcript)) {
|
|
1847
|
+
this.confirmInterruption();
|
|
1848
|
+
}
|
|
1849
|
+
return;
|
|
1850
|
+
// Recognizers that revise their guess (Soniox) send the whole current
|
|
1851
|
+
// text rather than an append-only delta.
|
|
1852
|
+
case "input_audio_transcription.snapshot":
|
|
1853
|
+
this.transcript = String((_d = event.transcript) != null ? _d : "");
|
|
1854
|
+
this.emitHeard();
|
|
1855
|
+
if (this.pendingInterruption && isRealInterruption(this.transcript) && !this.isOwnEcho(this.transcript)) {
|
|
1856
|
+
this.confirmInterruption();
|
|
1857
|
+
}
|
|
1858
|
+
return;
|
|
1859
|
+
case "conversation.item.input_audio_transcription.completed":
|
|
1860
|
+
case "input_audio_transcription.completed": {
|
|
1861
|
+
const text = String((_e = event.transcript) != null ? _e : this.transcript).trim();
|
|
1862
|
+
this.transcript = text;
|
|
1863
|
+
if (this.fillerDucked) {
|
|
1864
|
+
this.fillerDucked = false;
|
|
1865
|
+
this.player.duck(1);
|
|
1866
|
+
}
|
|
1867
|
+
if (text && this.isOwnEcho(text)) {
|
|
1868
|
+
if (this.pendingInterruption) {
|
|
1869
|
+
this.clearPendingInterruption();
|
|
1870
|
+
this.player.duck(1);
|
|
1871
|
+
}
|
|
1872
|
+
this.currentTurnId = null;
|
|
1873
|
+
if (this.activity !== "speaking") {
|
|
1874
|
+
this.setActivity(this.inFlight || this.activityBeforeSpeech === "thinking" ? "thinking" : "listening");
|
|
1875
|
+
}
|
|
1876
|
+
return;
|
|
1877
|
+
}
|
|
1878
|
+
if (this.pendingInterruption) {
|
|
1879
|
+
const answersQuestion2 = !!text && !!((_g = (_f = this.options.host).hasPendingConfirmation) == null ? void 0 : _g.call(_f)) && isConfirmationAnswer(text);
|
|
1880
|
+
if (!text || isBackchannel(text) && !answersQuestion2) {
|
|
1881
|
+
this.clearPendingInterruption();
|
|
1882
|
+
this.player.duck(1);
|
|
1883
|
+
this.currentTurnId = null;
|
|
1884
|
+
this.telemetry.record("false_interruption", 1);
|
|
1885
|
+
return;
|
|
1886
|
+
}
|
|
1887
|
+
this.confirmInterruption();
|
|
1888
|
+
}
|
|
1889
|
+
const answersQuestion = this.lastAnswerAsked || !!((_i = (_h = this.options.host).hasPendingConfirmation) == null ? void 0 : _i.call(_h));
|
|
1890
|
+
if (!text || isFillerOnly(text, answersQuestion)) {
|
|
1891
|
+
if (text) this.telemetry.record("filler_ignored", 1);
|
|
1892
|
+
this.currentTurnId = null;
|
|
1893
|
+
if ((_j = this.held) == null ? void 0 : _j.sendIfNothingFollows) {
|
|
1894
|
+
const held = this.held;
|
|
1895
|
+
this.clearHeld();
|
|
1896
|
+
await this.commitTurn(held.text, held.turnId);
|
|
1897
|
+
return;
|
|
1898
|
+
}
|
|
1899
|
+
this.setActivity(this.activityBeforeSpeech === "thinking" ? "thinking" : "listening");
|
|
1900
|
+
return;
|
|
1901
|
+
}
|
|
1902
|
+
if (this.held && classifyUtterance(text, answersQuestion) === "hold") {
|
|
1903
|
+
this.hold("", this.currentTurnId, this.held.sendIfNothingFollows);
|
|
1904
|
+
this.currentTurnId = null;
|
|
1905
|
+
await this.takeTurn(text, null, answersQuestion);
|
|
1906
|
+
return;
|
|
1907
|
+
}
|
|
1908
|
+
const turnId = (_l = (_k = this.held) == null ? void 0 : _k.turnId) != null ? _l : this.currentTurnId;
|
|
1909
|
+
const said = this.held ? `${this.held.text} ${text}` : text;
|
|
1910
|
+
this.clearHeld();
|
|
1911
|
+
this.currentTurnId = null;
|
|
1912
|
+
await this.takeTurn(said, turnId, answersQuestion);
|
|
1913
|
+
return;
|
|
1914
|
+
}
|
|
1915
|
+
case "error": {
|
|
1916
|
+
const message = ((_m = event.error) == null ? void 0 : _m.message) || "Realtime transcription failed.";
|
|
1917
|
+
throw ((_n = event.error) == null ? void 0 : _n.type) === "provider" ? new VoiceProviderError(message) : new Error(message);
|
|
1918
|
+
}
|
|
1919
|
+
default:
|
|
1920
|
+
return;
|
|
1921
|
+
}
|
|
1922
|
+
}
|
|
1923
|
+
/** Decide whether a finished turn is worth a request yet, and send it if so. */
|
|
1924
|
+
async takeTurn(text, turnId, answersQuestion) {
|
|
1925
|
+
var _a, _b, _c, _d;
|
|
1926
|
+
const listen = () => this.setActivity(
|
|
1927
|
+
this.inFlight || this.activityBeforeSpeech === "thinking" ? "thinking" : "listening"
|
|
1928
|
+
);
|
|
1929
|
+
const kind = classifyUtterance(text, answersQuestion);
|
|
1930
|
+
const inFlight = this.inFlight;
|
|
1931
|
+
const words = normalizeUtterance(text);
|
|
1932
|
+
if (inFlight && inFlight.epoch === this.turnEpoch && (kind === "short" || kind === "complete") && words.length <= CHECK_IN_MAX_WORDS && !words.some((word) => INTERRUPT_WORDS.has(word))) {
|
|
1933
|
+
const direct = await ((_a = this.options.actionRouter) == null ? void 0 : _a.route(text));
|
|
1934
|
+
if (direct) {
|
|
1935
|
+
await this.commitTurn(text, turnId, direct);
|
|
1936
|
+
return;
|
|
1937
|
+
}
|
|
1938
|
+
this.player.duck(1);
|
|
1939
|
+
if (Date.now() - this.reassuredAt < CHECK_IN_COOLDOWN_MS) {
|
|
1940
|
+
this.telemetry.record("check_in_quiet", 1);
|
|
1941
|
+
if (this.activity !== "speaking") this.setActivity("thinking");
|
|
1942
|
+
return;
|
|
1943
|
+
}
|
|
1944
|
+
if (this.inFlight === inFlight && inFlight.reassure()) {
|
|
1945
|
+
this.reassuredAt = Date.now();
|
|
1946
|
+
this.telemetry.record("check_in_reassured", 1);
|
|
1947
|
+
if (this.activity !== "speaking") this.setActivity("thinking");
|
|
1948
|
+
return;
|
|
1949
|
+
}
|
|
1950
|
+
await this.commitTurn(text, turnId, null);
|
|
1951
|
+
return;
|
|
1952
|
+
}
|
|
1953
|
+
switch (kind) {
|
|
1954
|
+
case "hold":
|
|
1955
|
+
this.telemetry.record("hold_request", 1);
|
|
1956
|
+
this.turnEpoch += 1;
|
|
1957
|
+
(_b = this.speechAbort) == null ? void 0 : _b.abort();
|
|
1958
|
+
this.speechAbort = null;
|
|
1959
|
+
this.player.stop();
|
|
1960
|
+
this.player.duck(1);
|
|
1961
|
+
this.setActivity("listening");
|
|
1962
|
+
return;
|
|
1963
|
+
case "incomplete":
|
|
1964
|
+
this.telemetry.record("incomplete_turn_held", 1);
|
|
1965
|
+
this.hold(text, turnId, false);
|
|
1966
|
+
listen();
|
|
1967
|
+
return;
|
|
1968
|
+
case "acknowledgement": {
|
|
1969
|
+
const direct = await ((_c = this.options.actionRouter) == null ? void 0 : _c.route(text));
|
|
1970
|
+
if (direct) {
|
|
1971
|
+
await this.commitTurn(text, turnId, direct);
|
|
1972
|
+
return;
|
|
1973
|
+
}
|
|
1974
|
+
this.telemetry.record("acknowledgement_ignored", 1);
|
|
1975
|
+
listen();
|
|
1976
|
+
return;
|
|
1977
|
+
}
|
|
1978
|
+
case "short": {
|
|
1979
|
+
const direct = await ((_d = this.options.actionRouter) == null ? void 0 : _d.route(text));
|
|
1980
|
+
if (direct) {
|
|
1981
|
+
await this.commitTurn(text, turnId, direct);
|
|
1982
|
+
return;
|
|
1983
|
+
}
|
|
1984
|
+
this.clearGrace();
|
|
1985
|
+
this.grace = { text, turnId };
|
|
1986
|
+
this.graceTimer = setTimeout(() => {
|
|
1987
|
+
const pending = this.grace;
|
|
1988
|
+
this.clearGrace();
|
|
1989
|
+
if (pending && this.started) {
|
|
1990
|
+
void this.commitTurn(pending.text, pending.turnId, null).catch((error) => this.report(error));
|
|
1991
|
+
}
|
|
1992
|
+
}, SHORT_TURN_GRACE_MS);
|
|
1993
|
+
listen();
|
|
1994
|
+
return;
|
|
1995
|
+
}
|
|
1996
|
+
default:
|
|
1997
|
+
await this.commitTurn(text, turnId);
|
|
1998
|
+
}
|
|
1999
|
+
}
|
|
2000
|
+
/**
|
|
2001
|
+
* Send a turn to the agent. `routed` is the action router's verdict when it
|
|
2002
|
+
* was already asked (null: nothing matched), so the action never runs twice.
|
|
2003
|
+
*/
|
|
2004
|
+
async commitTurn(text, turnId, routed) {
|
|
2005
|
+
var _a;
|
|
2006
|
+
this.clearGrace();
|
|
2007
|
+
this.clearHeld();
|
|
2008
|
+
const epoch = ++this.turnEpoch;
|
|
2009
|
+
(_a = this.speechAbort) == null ? void 0 : _a.abort();
|
|
2010
|
+
this.speechAbort = null;
|
|
2011
|
+
this.player.stop();
|
|
2012
|
+
this.player.duck(1);
|
|
2013
|
+
this.options.host.dispatchConversationEvent({
|
|
2014
|
+
type: "input.started",
|
|
2015
|
+
turnId: turnId != null ? turnId : `voice_${Date.now()}`,
|
|
2016
|
+
modality: "voice"
|
|
2017
|
+
});
|
|
2018
|
+
this.emitTranscript("user", text, true);
|
|
2019
|
+
this.telemetry.measure("user_speech_ms", "pipeline_user_speech");
|
|
2020
|
+
this.telemetry.mark("pipeline_turn_end");
|
|
2021
|
+
this.setActivity("thinking");
|
|
2022
|
+
await this.runTurn(text, epoch, routed);
|
|
2023
|
+
}
|
|
2024
|
+
hold(text, turnId, sendIfNothingFollows) {
|
|
2025
|
+
var _a;
|
|
2026
|
+
const previous = this.held;
|
|
2027
|
+
this.clearHeld();
|
|
2028
|
+
this.held = {
|
|
2029
|
+
text: [previous == null ? void 0 : previous.text, text].filter(Boolean).join(" "),
|
|
2030
|
+
turnId: (_a = previous == null ? void 0 : previous.turnId) != null ? _a : turnId,
|
|
2031
|
+
sendIfNothingFollows
|
|
2032
|
+
};
|
|
2033
|
+
this.heldTimer = setTimeout(() => {
|
|
2034
|
+
const held = this.held;
|
|
2035
|
+
this.clearHeld();
|
|
2036
|
+
if (!held || !this.started) return;
|
|
2037
|
+
if (held.sendIfNothingFollows) {
|
|
2038
|
+
void this.commitTurn(held.text, held.turnId, null).catch((error) => this.report(error));
|
|
2039
|
+
} else {
|
|
2040
|
+
this.telemetry.record("incomplete_turn_dropped", 1);
|
|
2041
|
+
}
|
|
2042
|
+
}, sendIfNothingFollows ? CONTINUATION_TIMEOUT_MS : HELD_WORDS_TTL_MS);
|
|
2043
|
+
}
|
|
2044
|
+
clearHeld() {
|
|
2045
|
+
this.held = null;
|
|
2046
|
+
if (this.heldTimer) clearTimeout(this.heldTimer);
|
|
2047
|
+
this.heldTimer = null;
|
|
2048
|
+
}
|
|
2049
|
+
clearGrace() {
|
|
2050
|
+
this.grace = null;
|
|
2051
|
+
if (this.graceTimer) clearTimeout(this.graceTimer);
|
|
2052
|
+
this.graceTimer = null;
|
|
2053
|
+
}
|
|
2054
|
+
async runTurn(text, epoch, routed) {
|
|
2055
|
+
var _a, _b, _c, _d, _e, _f, _g, _h, _i, _j;
|
|
2056
|
+
const streaming = isStreamingSpeechProvider(this.options.speechProvider) ? this.streamingSpeech(this.options.speechProvider, epoch) : null;
|
|
2057
|
+
try {
|
|
2058
|
+
let answer = "";
|
|
2059
|
+
let streamedAnswer = "";
|
|
2060
|
+
if (isUnexpectedTranscriptScript(text, this.options.language)) {
|
|
2061
|
+
answer = "I may have misheard that. Please repeat in your selected language.";
|
|
2062
|
+
(_b = (_a = this.options.host).recordRealtimeTurn) == null ? void 0 : _b.call(_a, "user", text);
|
|
2063
|
+
(_d = (_c = this.options.host).recordRealtimeTurn) == null ? void 0 : _d.call(_c, "assistant", answer);
|
|
2064
|
+
this.telemetry.record("voice_language_guard", 1, (_e = this.options.language) == null ? void 0 : _e.code);
|
|
2065
|
+
} else {
|
|
2066
|
+
const direct = routed !== void 0 ? routed : await ((_f = this.options.actionRouter) == null ? void 0 : _f.route(text));
|
|
2067
|
+
if (direct) {
|
|
2068
|
+
answer = direct.response.trim();
|
|
2069
|
+
(_h = (_g = this.options.host).recordRealtimeTurn) == null ? void 0 : _h.call(_g, "user", text);
|
|
2070
|
+
if (!direct.alreadyInChat) (_j = (_i = this.options.host).recordRealtimeTurn) == null ? void 0 : _j.call(_i, "assistant", answer);
|
|
2071
|
+
this.telemetry.record("voice_direct_action", 1, direct.actionId);
|
|
2072
|
+
} else {
|
|
2073
|
+
this.telemetry.mark("pipeline_brain_wait");
|
|
2074
|
+
streaming == null ? void 0 : streaming.thinkAloud();
|
|
2075
|
+
const request = {
|
|
2076
|
+
epoch,
|
|
2077
|
+
reassure: () => {
|
|
2078
|
+
var _a2;
|
|
2079
|
+
return (_a2 = streaming == null ? void 0 : streaming.reassure()) != null ? _a2 : false;
|
|
2080
|
+
},
|
|
2081
|
+
answering: () => {
|
|
2082
|
+
var _a2;
|
|
2083
|
+
return (_a2 = streaming == null ? void 0 : streaming.answering()) != null ? _a2 : true;
|
|
2084
|
+
}
|
|
2085
|
+
};
|
|
2086
|
+
this.inFlight = request;
|
|
2087
|
+
answer = (await this.options.host.submitAgentTurn(
|
|
2088
|
+
text,
|
|
2089
|
+
this.options.mode,
|
|
2090
|
+
(delta) => {
|
|
2091
|
+
if (epoch !== this.turnEpoch || !this.started) return;
|
|
2092
|
+
streamedAnswer += delta;
|
|
2093
|
+
this.emitTranscript("assistant", streamedAnswer, false);
|
|
2094
|
+
streaming == null ? void 0 : streaming.push(delta);
|
|
2095
|
+
}
|
|
2096
|
+
).finally(() => {
|
|
2097
|
+
if (this.inFlight === request) this.inFlight = null;
|
|
2098
|
+
})).trim();
|
|
2099
|
+
this.telemetry.measure("brain_response_ms", "pipeline_brain_wait");
|
|
2100
|
+
}
|
|
2101
|
+
}
|
|
2102
|
+
if (!answer || epoch !== this.turnEpoch || !this.started) {
|
|
2103
|
+
streaming == null ? void 0 : streaming.cancel();
|
|
2104
|
+
if (this.started) this.setActivity("listening");
|
|
2105
|
+
return;
|
|
2106
|
+
}
|
|
2107
|
+
this.emitTranscript("assistant", answer, true);
|
|
2108
|
+
this.lastAnswerAsked = /\?[^\p{L}\p{N}]*$/u.test(answer);
|
|
2109
|
+
if (streaming) {
|
|
2110
|
+
streaming.finish(answer.slice(0, 8e3));
|
|
2111
|
+
const spoken2 = await streaming.played();
|
|
2112
|
+
if (spoken2 && this.started && epoch === this.turnEpoch) this.setActivity("listening");
|
|
2113
|
+
return;
|
|
2114
|
+
}
|
|
2115
|
+
this.noteSpoken(answer.slice(0, 8e3));
|
|
2116
|
+
const spoken = await this.playSpeech(
|
|
2117
|
+
answer.slice(0, 8e3),
|
|
2118
|
+
epoch,
|
|
2119
|
+
"pipeline_tts_wait",
|
|
2120
|
+
"tts_first_byte_ms"
|
|
2121
|
+
);
|
|
2122
|
+
if (spoken && this.started && epoch === this.turnEpoch) this.setActivity("listening");
|
|
2123
|
+
} catch (error) {
|
|
2124
|
+
streaming == null ? void 0 : streaming.cancel();
|
|
2125
|
+
if (isAbortError(error)) return;
|
|
2126
|
+
if (epoch !== this.turnEpoch || !this.started) return;
|
|
2127
|
+
this.report(error);
|
|
2128
|
+
}
|
|
2129
|
+
}
|
|
2130
|
+
/**
|
|
2131
|
+
* Feed the answer to a text-streaming voice as it is written, one whole
|
|
2132
|
+
* word at a time, so speech starts on the first words and stays one
|
|
2133
|
+
* utterance. The provider session is opened as soon as the visitor's turn
|
|
2134
|
+
* ends — its key and connection are ready by the time the first word is —
|
|
2135
|
+
* which means a turn is charged once it reaches the agent, even if the
|
|
2136
|
+
* visitor interrupts before it speaks.
|
|
2137
|
+
*/
|
|
2138
|
+
streamingSpeech(provider, epoch) {
|
|
2139
|
+
const controller = new AbortController();
|
|
2140
|
+
let session = null;
|
|
2141
|
+
let played = Promise.resolve(false);
|
|
2142
|
+
let pending = "";
|
|
2143
|
+
const visible = createFenceFilter();
|
|
2144
|
+
let consumed = "";
|
|
2145
|
+
const thinkingTimers = [];
|
|
2146
|
+
const stopThinking = () => {
|
|
2147
|
+
for (const timer of thinkingTimers) clearTimeout(timer);
|
|
2148
|
+
thinkingTimers.length = 0;
|
|
2149
|
+
};
|
|
2150
|
+
controller.signal.addEventListener("abort", stopThinking, { once: true });
|
|
2151
|
+
const live = () => epoch === this.turnEpoch && this.started && !controller.signal.aborted;
|
|
2152
|
+
const ensureSession = () => {
|
|
2153
|
+
var _a, _b, _c;
|
|
2154
|
+
if (session || !live()) return session;
|
|
2155
|
+
this.speechAbort = controller;
|
|
2156
|
+
this.telemetry.mark("pipeline_tts_wait");
|
|
2157
|
+
session = provider.open({
|
|
2158
|
+
voice: this.options.voice,
|
|
2159
|
+
// Speak in the recognizer's language: a dialect such as Pidgin
|
|
2160
|
+
// (`pcm`) has no voice of its own and is read by the English one.
|
|
2161
|
+
language: (_c = (_a = this.options.language) == null ? void 0 : _a.transcriptionLanguages[0]) != null ? _c : (_b = this.options.language) == null ? void 0 : _b.code
|
|
2162
|
+
}, controller.signal);
|
|
2163
|
+
played = this.playStreamedSpeech(session.audio, epoch, controller);
|
|
2164
|
+
return session;
|
|
2165
|
+
};
|
|
2166
|
+
ensureSession();
|
|
2167
|
+
const speak = (raw) => {
|
|
2168
|
+
var _a;
|
|
2169
|
+
consumed += raw;
|
|
2170
|
+
const speakable = toSpeakableChunk(raw);
|
|
2171
|
+
if (!speakable.trim() || !live()) return;
|
|
2172
|
+
stopThinking();
|
|
2173
|
+
this.noteSpoken(speakable);
|
|
2174
|
+
(_a = ensureSession()) == null ? void 0 : _a.push(speakable);
|
|
2175
|
+
};
|
|
2176
|
+
let lastLine = null;
|
|
2177
|
+
let lastSaidAt = 0;
|
|
2178
|
+
const sayLine = (line) => {
|
|
2179
|
+
var _a;
|
|
2180
|
+
const say = (_a = session == null ? void 0 : session.say) == null ? void 0 : _a.bind(session);
|
|
2181
|
+
if (!say || !line || !live() || consumed.trim()) return false;
|
|
2182
|
+
lastLine = line;
|
|
2183
|
+
lastSaidAt = Date.now();
|
|
2184
|
+
this.noteSpoken(line);
|
|
2185
|
+
say(line);
|
|
2186
|
+
return true;
|
|
2187
|
+
};
|
|
2188
|
+
return {
|
|
2189
|
+
/**
|
|
2190
|
+
* Fill a slow agent's silence the way a person would. Spoken only, never
|
|
2191
|
+
* added to the transcript, and stopped by the answer's first words.
|
|
2192
|
+
*/
|
|
2193
|
+
thinkAloud: () => {
|
|
2194
|
+
if (!(session == null ? void 0 : session.say)) return;
|
|
2195
|
+
const delays = thinkingAloudSchedule();
|
|
2196
|
+
delays.forEach((delay, index) => {
|
|
2197
|
+
thinkingTimers.push(setTimeout(() => {
|
|
2198
|
+
var _a;
|
|
2199
|
+
if (Date.now() - lastSaidAt < LINE_SPACING_MS) return;
|
|
2200
|
+
if (sayLine(thinkingLine((_a = this.options.language) == null ? void 0 : _a.code, index, lastLine))) {
|
|
2201
|
+
this.telemetry.record("thinking_aloud", index + 1);
|
|
2202
|
+
}
|
|
2203
|
+
}, delay));
|
|
2204
|
+
});
|
|
2205
|
+
},
|
|
2206
|
+
answering: () => !!consumed.trim(),
|
|
2207
|
+
/** Answer a check-in now; false once the answer itself has started. */
|
|
2208
|
+
reassure: () => {
|
|
2209
|
+
var _a;
|
|
2210
|
+
return sayLine(stillWorkingLine((_a = this.options.language) == null ? void 0 : _a.code, lastLine));
|
|
2211
|
+
},
|
|
2212
|
+
push: (delta) => {
|
|
2213
|
+
if (!live()) return;
|
|
2214
|
+
pending += visible(delta);
|
|
2215
|
+
const cut = Math.max(pending.lastIndexOf(" "), pending.lastIndexOf("\n"));
|
|
2216
|
+
if (cut < 0) return;
|
|
2217
|
+
speak(pending.slice(0, cut + 1));
|
|
2218
|
+
pending = pending.slice(cut + 1);
|
|
2219
|
+
},
|
|
2220
|
+
finish: (answer) => {
|
|
2221
|
+
if (!live()) return;
|
|
2222
|
+
const said = consumed.trimStart();
|
|
2223
|
+
const at = said.trim() ? answer.indexOf(said) : -1;
|
|
2224
|
+
const rest = !said.trim() ? answer : at >= 0 ? answer.slice(at + said.length) : said.trim().length < answer.length * 0.4 ? answer : pending;
|
|
2225
|
+
pending = "";
|
|
2226
|
+
stopThinking();
|
|
2227
|
+
speak(rest);
|
|
2228
|
+
session == null ? void 0 : session.end();
|
|
2229
|
+
},
|
|
2230
|
+
cancel: () => controller.abort(),
|
|
2231
|
+
played: () => played
|
|
2232
|
+
};
|
|
2233
|
+
}
|
|
2234
|
+
async playStreamedSpeech(audio, epoch, controller) {
|
|
2235
|
+
var _a;
|
|
2236
|
+
const reader = audio.getReader();
|
|
2237
|
+
try {
|
|
2238
|
+
const first = await reader.read();
|
|
2239
|
+
if (first.done || controller.signal.aborted || epoch !== this.turnEpoch || !this.started) {
|
|
2240
|
+
return false;
|
|
2241
|
+
}
|
|
2242
|
+
this.telemetry.measure("tts_first_byte_ms", "pipeline_tts_wait");
|
|
2243
|
+
this.telemetry.measure("turn_first_audio_ms", "pipeline_turn_end");
|
|
2244
|
+
this.setActivity("speaking");
|
|
2245
|
+
let head = first.value;
|
|
2246
|
+
const body = {
|
|
2247
|
+
getReader: () => ({
|
|
2248
|
+
read: async () => {
|
|
2249
|
+
if (!head) return reader.read();
|
|
2250
|
+
const value = head;
|
|
2251
|
+
head = void 0;
|
|
2252
|
+
return { done: false, value };
|
|
2253
|
+
}
|
|
2254
|
+
})
|
|
2255
|
+
};
|
|
2256
|
+
const releaseAudio = acquireAssistantAudio();
|
|
2257
|
+
try {
|
|
2258
|
+
await this.player.play(body, controller.signal);
|
|
2259
|
+
} finally {
|
|
2260
|
+
releaseAudio();
|
|
2261
|
+
}
|
|
2262
|
+
return this.started && epoch === this.turnEpoch && !controller.signal.aborted;
|
|
2263
|
+
} catch (error) {
|
|
2264
|
+
if (!controller.signal.aborted) this.report(error);
|
|
2265
|
+
return false;
|
|
2266
|
+
} finally {
|
|
2267
|
+
try {
|
|
2268
|
+
(_a = reader.releaseLock) == null ? void 0 : _a.call(reader);
|
|
2269
|
+
} catch {
|
|
2270
|
+
}
|
|
2271
|
+
if (this.speechAbort === controller) this.speechAbort = null;
|
|
2272
|
+
}
|
|
2273
|
+
}
|
|
2274
|
+
async playSpeech(text, epoch, waitMark, latencyMetric, turnId, chunkIndex) {
|
|
2275
|
+
var _a, _b;
|
|
2276
|
+
if (epoch !== this.turnEpoch || !this.started) return false;
|
|
2277
|
+
const controller = new AbortController();
|
|
2278
|
+
this.speechAbort = controller;
|
|
2279
|
+
try {
|
|
2280
|
+
this.telemetry.mark(waitMark);
|
|
2281
|
+
const provider = this.options.speechProvider;
|
|
2282
|
+
const response = await provider.createStream({
|
|
2283
|
+
text,
|
|
2284
|
+
voice: this.options.voice,
|
|
2285
|
+
instructions: (_b = this.options.speechInstructions) != null ? _b : (_a = this.options.language) == null ? void 0 : _a.speechInstructions,
|
|
2286
|
+
...turnId ? { turnId, chunkIndex } : {}
|
|
2287
|
+
}, controller.signal);
|
|
2288
|
+
this.telemetry.measure(latencyMetric, waitMark);
|
|
2289
|
+
this.telemetry.measure("turn_first_audio_ms", "pipeline_turn_end");
|
|
2290
|
+
if (epoch !== this.turnEpoch || !this.started) {
|
|
2291
|
+
controller.abort();
|
|
2292
|
+
return false;
|
|
2293
|
+
}
|
|
2294
|
+
this.setActivity("speaking");
|
|
2295
|
+
const releaseAudio = acquireAssistantAudio();
|
|
2296
|
+
try {
|
|
2297
|
+
await this.player.play(response, controller.signal);
|
|
2298
|
+
} finally {
|
|
2299
|
+
releaseAudio();
|
|
2300
|
+
}
|
|
2301
|
+
return this.started && epoch === this.turnEpoch && !controller.signal.aborted;
|
|
2302
|
+
} finally {
|
|
2303
|
+
if (this.speechAbort === controller) this.speechAbort = null;
|
|
2304
|
+
}
|
|
2305
|
+
}
|
|
2306
|
+
/**
|
|
2307
|
+
* Show the visitor's words as they come — unless they are the assistant's
|
|
2308
|
+
* own voice heard back, which would paint "You're speaking" over its line.
|
|
2309
|
+
*/
|
|
2310
|
+
emitHeard() {
|
|
2311
|
+
if (this.heardOverSpeech && this.spoken.length && isEchoOf(this.transcript, this.spoken.map((entry) => entry.text).join(" "))) return;
|
|
2312
|
+
this.emitTranscript("user", this.transcript, false);
|
|
2313
|
+
}
|
|
2314
|
+
noteSpoken(text) {
|
|
2315
|
+
if (!text.trim()) return;
|
|
2316
|
+
const now = Date.now();
|
|
2317
|
+
this.spoken = this.spoken.filter((entry) => now - entry.at < ECHO_MEMORY_MS);
|
|
2318
|
+
this.spoken.push({ text, at: now });
|
|
2319
|
+
}
|
|
2320
|
+
/** Started while the assistant spoke, and it is the assistant's own words. */
|
|
2321
|
+
isOwnEcho(text) {
|
|
2322
|
+
if (!this.heardOverSpeech || !this.spoken.length) return false;
|
|
2323
|
+
const echo = isEchoOf(text, this.spoken.map((entry) => entry.text).join(" "));
|
|
2324
|
+
if (echo) this.telemetry.record("echo_ignored", 1);
|
|
2325
|
+
return echo;
|
|
2326
|
+
}
|
|
2327
|
+
emitTranscript(role, text, final) {
|
|
2328
|
+
var _a, _b;
|
|
2329
|
+
(_b = (_a = this.options).onTranscript) == null ? void 0 : _b.call(_a, { role, text, final });
|
|
2330
|
+
}
|
|
2331
|
+
setActivity(activity) {
|
|
2332
|
+
var _a, _b;
|
|
2333
|
+
if (this.activity === "speaking" && activity !== "speaking") this.speechEndedAt = Date.now();
|
|
2334
|
+
this.activity = activity;
|
|
2335
|
+
(_b = (_a = this.options).onActivity) == null ? void 0 : _b.call(_a, activity);
|
|
2336
|
+
}
|
|
2337
|
+
report(error) {
|
|
2338
|
+
var _a, _b;
|
|
2339
|
+
const normalized = error instanceof Error ? error : new Error(String(error));
|
|
2340
|
+
this.telemetry.record("transport_error", 1, normalized.message);
|
|
2341
|
+
(_b = (_a = this.options).onError) == null ? void 0 : _b.call(_a, normalized);
|
|
2342
|
+
}
|
|
2343
|
+
cleanup() {
|
|
2344
|
+
var _a, _b;
|
|
2345
|
+
(_a = this.cleanupEvent) == null ? void 0 : _a.call(this);
|
|
2346
|
+
(_b = this.cleanupState) == null ? void 0 : _b.call(this);
|
|
2347
|
+
this.cleanupEvent = null;
|
|
2348
|
+
this.cleanupState = null;
|
|
2349
|
+
}
|
|
2350
|
+
}
|
|
2351
|
+
const INPUT_SAMPLE_RATE = 16e3;
|
|
2352
|
+
const MAX_PRECONNECT_BYTES = INPUT_SAMPLE_RATE * 2 * 10;
|
|
2353
|
+
const KEEPALIVE_INTERVAL_MS = 8e3;
|
|
2354
|
+
const DEFAULT_AUDIO_CONSTRAINTS = {
|
|
2355
|
+
channelCount: 1,
|
|
2356
|
+
echoCancellation: true,
|
|
2357
|
+
noiseSuppression: true,
|
|
2358
|
+
autoGainControl: true,
|
|
2359
|
+
voiceIsolation: true
|
|
2360
|
+
};
|
|
2361
|
+
class SonioxSttTransport {
|
|
2362
|
+
constructor(options) {
|
|
2363
|
+
this.options = options;
|
|
2364
|
+
this.supportsSessionUpdates = false;
|
|
2365
|
+
this.interimTranscripts = true;
|
|
2366
|
+
this.state = "idle";
|
|
2367
|
+
this.socket = null;
|
|
2368
|
+
this.socketReady = false;
|
|
2369
|
+
this.localStream = null;
|
|
2370
|
+
this.microphoneOn = false;
|
|
2371
|
+
this.audioContext = null;
|
|
2372
|
+
this.inputSource = null;
|
|
2373
|
+
this.inputProcessor = null;
|
|
2374
|
+
this.silentSink = null;
|
|
2375
|
+
this.preconnect = [];
|
|
2376
|
+
this.preconnectBytes = 0;
|
|
2377
|
+
this.keepaliveTimer = null;
|
|
2378
|
+
this.lastSentAt = 0;
|
|
2379
|
+
this.languageHints = [];
|
|
2380
|
+
this.contextText = "";
|
|
2381
|
+
this.connectionAbort = null;
|
|
2382
|
+
this.reconnectTimer = null;
|
|
2383
|
+
this.reconnectAttempts = 0;
|
|
2384
|
+
this.userClosed = false;
|
|
2385
|
+
this.muted = false;
|
|
2386
|
+
this.finalText = "";
|
|
2387
|
+
this.utteranceId = null;
|
|
2388
|
+
this.eventListeners = /* @__PURE__ */ new Set();
|
|
2389
|
+
this.stateListeners = /* @__PURE__ */ new Set();
|
|
2390
|
+
}
|
|
2391
|
+
getState() {
|
|
2392
|
+
return this.state;
|
|
2393
|
+
}
|
|
2394
|
+
isConnected() {
|
|
2395
|
+
return this.state === "connected" && this.socketReady;
|
|
2396
|
+
}
|
|
2397
|
+
subscribeEvents(listener) {
|
|
2398
|
+
this.eventListeners.add(listener);
|
|
2399
|
+
return () => this.eventListeners.delete(listener);
|
|
2400
|
+
}
|
|
2401
|
+
subscribeState(listener) {
|
|
2402
|
+
this.stateListeners.add(listener);
|
|
2403
|
+
return () => this.stateListeners.delete(listener);
|
|
2404
|
+
}
|
|
2405
|
+
async connect(session) {
|
|
2406
|
+
var _a, _b, _c, _d, _e, _f, _g;
|
|
2407
|
+
if (this.state === "connecting" || this.state === "connected") return;
|
|
2408
|
+
this.userClosed = false;
|
|
2409
|
+
const language = (_c = (_b = (_a = session.audio) == null ? void 0 : _a.input) == null ? void 0 : _b.transcription) == null ? void 0 : _c.language;
|
|
2410
|
+
this.languageHints = language ? [String(language).split("-")[0].toLowerCase()] : [];
|
|
2411
|
+
this.contextText = String((_g = (_f = (_e = (_d = session.audio) == null ? void 0 : _d.input) == null ? void 0 : _e.transcription) == null ? void 0 : _f.prompt) != null ? _g : "").slice(0, 2e3);
|
|
2412
|
+
this.setState("connecting");
|
|
2413
|
+
try {
|
|
2414
|
+
await this.startMicrophone();
|
|
2415
|
+
} catch (error) {
|
|
2416
|
+
this.cleanupAll();
|
|
2417
|
+
this.setState("failed");
|
|
2418
|
+
throw error;
|
|
2419
|
+
}
|
|
2420
|
+
this.emit({ type: "session.created" });
|
|
2421
|
+
await this.openSocket("connecting");
|
|
2422
|
+
}
|
|
2423
|
+
send(_event) {
|
|
2424
|
+
}
|
|
2425
|
+
updateSession(_session) {
|
|
2426
|
+
}
|
|
2427
|
+
cancelResponse() {
|
|
2428
|
+
}
|
|
2429
|
+
stopOutput() {
|
|
2430
|
+
}
|
|
2431
|
+
async resumeOutput() {
|
|
2432
|
+
}
|
|
2433
|
+
setMuted(muted) {
|
|
2434
|
+
var _a, _b;
|
|
2435
|
+
this.muted = muted;
|
|
2436
|
+
for (const track of (_b = (_a = this.localStream) == null ? void 0 : _a.getAudioTracks()) != null ? _b : []) track.enabled = !muted;
|
|
2437
|
+
}
|
|
2438
|
+
async reconnect() {
|
|
2439
|
+
this.userClosed = false;
|
|
2440
|
+
this.reconnectAttempts += 1;
|
|
2441
|
+
await this.openSocket("reconnecting");
|
|
2442
|
+
}
|
|
2443
|
+
disconnect() {
|
|
2444
|
+
var _a;
|
|
2445
|
+
this.userClosed = true;
|
|
2446
|
+
this.setState("closing");
|
|
2447
|
+
if (this.reconnectTimer) clearTimeout(this.reconnectTimer);
|
|
2448
|
+
this.reconnectTimer = null;
|
|
2449
|
+
(_a = this.connectionAbort) == null ? void 0 : _a.abort();
|
|
2450
|
+
this.connectionAbort = null;
|
|
2451
|
+
this.cleanupAll();
|
|
2452
|
+
this.setState("closed");
|
|
2453
|
+
}
|
|
2454
|
+
async startMicrophone() {
|
|
2455
|
+
var _a, _b;
|
|
2456
|
+
if (this.localStream || this.microphoneOn) return;
|
|
2457
|
+
const microphone = this.options.microphone;
|
|
2458
|
+
if (microphone) {
|
|
2459
|
+
this.microphoneOn = true;
|
|
2460
|
+
try {
|
|
2461
|
+
await microphone.start((samples, sampleRate) => this.captureAudio(samples, sampleRate));
|
|
2462
|
+
} catch (error) {
|
|
2463
|
+
this.microphoneOn = false;
|
|
2464
|
+
throw error;
|
|
2465
|
+
}
|
|
2466
|
+
return;
|
|
2467
|
+
}
|
|
2468
|
+
const getUserMedia = (_a = this.options.getUserMedia) != null ? _a : ((constraints) => navigator.mediaDevices.getUserMedia(constraints));
|
|
2469
|
+
const stream = await getUserMedia({
|
|
2470
|
+
audio: { ...DEFAULT_AUDIO_CONSTRAINTS, ...this.options.mediaConstraints }
|
|
2471
|
+
});
|
|
2472
|
+
this.localStream = stream;
|
|
2473
|
+
for (const track of stream.getAudioTracks()) track.enabled = !this.muted;
|
|
2474
|
+
const contextFactory = (_b = this.options.audioContextFactory) != null ? _b : (() => {
|
|
2475
|
+
const AudioContextCtor = typeof AudioContext !== "undefined" ? AudioContext : window.webkitAudioContext;
|
|
2476
|
+
return new AudioContextCtor();
|
|
2477
|
+
});
|
|
2478
|
+
const context = contextFactory();
|
|
2479
|
+
this.audioContext = context;
|
|
2480
|
+
const source = context.createMediaStreamSource(stream);
|
|
2481
|
+
const processor = context.createScriptProcessor(2048, 1, 1);
|
|
2482
|
+
const sink = context.createGain();
|
|
2483
|
+
sink.gain.value = 0;
|
|
2484
|
+
source.connect(processor);
|
|
2485
|
+
processor.connect(sink);
|
|
2486
|
+
sink.connect(context.destination);
|
|
2487
|
+
processor.onaudioprocess = (event) => {
|
|
2488
|
+
this.captureAudio(event.inputBuffer.getChannelData(0), context.sampleRate);
|
|
2489
|
+
};
|
|
2490
|
+
this.inputSource = source;
|
|
2491
|
+
this.inputProcessor = processor;
|
|
2492
|
+
this.silentSink = sink;
|
|
2493
|
+
if (context.state === "suspended") {
|
|
2494
|
+
try {
|
|
2495
|
+
await context.resume();
|
|
2496
|
+
} catch {
|
|
2497
|
+
}
|
|
2498
|
+
}
|
|
2499
|
+
}
|
|
2500
|
+
captureAudio(samples, sampleRate) {
|
|
2501
|
+
if (this.muted) return;
|
|
2502
|
+
const pcm = floatToPcm16(resampleMono(samples, sampleRate, INPUT_SAMPLE_RATE));
|
|
2503
|
+
const bytes = new Uint8Array(pcm.buffer);
|
|
2504
|
+
if (this.socket && this.socketReady && this.socket.readyState === WebSocket.OPEN) {
|
|
2505
|
+
this.socket.send(bytes);
|
|
2506
|
+
this.lastSentAt = Date.now();
|
|
2507
|
+
return;
|
|
2508
|
+
}
|
|
2509
|
+
this.preconnect.push(bytes);
|
|
2510
|
+
this.preconnectBytes += bytes.byteLength;
|
|
2511
|
+
while (this.preconnectBytes > MAX_PRECONNECT_BYTES && this.preconnect.length) {
|
|
2512
|
+
this.preconnectBytes -= this.preconnect.shift().byteLength;
|
|
2513
|
+
}
|
|
2514
|
+
}
|
|
2515
|
+
async openSocket(startState) {
|
|
2516
|
+
var _a, _b;
|
|
2517
|
+
this.closeSocket();
|
|
2518
|
+
this.resetUtterance();
|
|
2519
|
+
this.setState(startState);
|
|
2520
|
+
const startedAt = performance.now();
|
|
2521
|
+
const controller = new AbortController();
|
|
2522
|
+
this.connectionAbort = controller;
|
|
2523
|
+
const timeoutMs = (_a = this.options.connectTimeoutMs) != null ? _a : 15e3;
|
|
2524
|
+
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
|
2525
|
+
try {
|
|
2526
|
+
const session = await this.options.sessionProvider.createSession(controller.signal);
|
|
2527
|
+
const factory = (_b = this.options.webSocketFactory) != null ? _b : ((url) => new WebSocket(url));
|
|
2528
|
+
const socket = factory(session.url);
|
|
2529
|
+
socket.binaryType = "arraybuffer";
|
|
2530
|
+
this.socket = socket;
|
|
2531
|
+
await waitForOpen(socket, controller.signal);
|
|
2532
|
+
socket.onmessage = (message) => this.handleMessage(message.data);
|
|
2533
|
+
socket.onclose = () => {
|
|
2534
|
+
if (this.socket !== socket) return;
|
|
2535
|
+
this.socketReady = false;
|
|
2536
|
+
if (!this.userClosed) this.scheduleReconnect("socket_closed");
|
|
2537
|
+
};
|
|
2538
|
+
socket.onerror = () => this.metric("transport_error", 1, "socket_error");
|
|
2539
|
+
socket.send(JSON.stringify(this.config(session)));
|
|
2540
|
+
for (const chunk of this.preconnect) socket.send(chunk);
|
|
2541
|
+
this.preconnect = [];
|
|
2542
|
+
this.preconnectBytes = 0;
|
|
2543
|
+
this.socketReady = true;
|
|
2544
|
+
this.lastSentAt = Date.now();
|
|
2545
|
+
this.startKeepalive();
|
|
2546
|
+
this.reconnectAttempts = 0;
|
|
2547
|
+
this.setState("connected");
|
|
2548
|
+
this.metric("connect_ms", performance.now() - startedAt);
|
|
2549
|
+
if (startState === "reconnecting") this.metric("reconnect_succeeded", 1);
|
|
2550
|
+
} catch (error) {
|
|
2551
|
+
this.closeSocket();
|
|
2552
|
+
this.metric("transport_error", 1, error instanceof Error ? error.message : String(error));
|
|
2553
|
+
if (!this.userClosed && isRetryableConnectionError(error)) {
|
|
2554
|
+
this.scheduleReconnect("connect_error");
|
|
2555
|
+
} else {
|
|
2556
|
+
this.setState("failed");
|
|
2557
|
+
}
|
|
2558
|
+
throw error;
|
|
2559
|
+
} finally {
|
|
2560
|
+
clearTimeout(timeout);
|
|
2561
|
+
if (this.connectionAbort === controller) this.connectionAbort = null;
|
|
2562
|
+
}
|
|
2563
|
+
}
|
|
2564
|
+
config(session) {
|
|
2565
|
+
var _a, _b, _c, _d, _e;
|
|
2566
|
+
const endpoint = (_a = this.options.endpoint) != null ? _a : {};
|
|
2567
|
+
const terms = ((_b = this.options.terms) != null ? _b : []).filter(Boolean).slice(0, 100);
|
|
2568
|
+
return {
|
|
2569
|
+
api_key: session.apiKey,
|
|
2570
|
+
...session.model ? { model: session.model } : {},
|
|
2571
|
+
audio_format: "pcm_s16le",
|
|
2572
|
+
sample_rate: INPUT_SAMPLE_RATE,
|
|
2573
|
+
num_channels: 1,
|
|
2574
|
+
...this.languageHints.length ? { language_hints: this.languageHints } : {},
|
|
2575
|
+
...terms.length || this.contextText ? { context: { ...terms.length ? { terms } : {}, ...this.contextText ? { text: this.contextText } : {} } } : {},
|
|
2576
|
+
enable_endpoint_detection: true,
|
|
2577
|
+
endpoint_latency_adjustment_level: (_c = endpoint.latencyAdjustmentLevel) != null ? _c : 2,
|
|
2578
|
+
endpoint_sensitivity: (_d = endpoint.sensitivity) != null ? _d : 0.3,
|
|
2579
|
+
max_endpoint_delay_ms: (_e = endpoint.maxDelayMs) != null ? _e : 1500
|
|
2580
|
+
};
|
|
2581
|
+
}
|
|
2582
|
+
handleMessage(data) {
|
|
2583
|
+
var _a, _b, _c;
|
|
2584
|
+
let message;
|
|
2585
|
+
try {
|
|
2586
|
+
message = JSON.parse(typeof data === "string" ? data : new TextDecoder().decode(data));
|
|
2587
|
+
} catch (error) {
|
|
2588
|
+
this.metric("event_parse_error", 1, error instanceof Error ? error.message : String(error));
|
|
2589
|
+
return;
|
|
2590
|
+
}
|
|
2591
|
+
if (message.error_code) {
|
|
2592
|
+
this.metric("transport_error", 1, `stream_${message.error_code}`);
|
|
2593
|
+
this.emit({
|
|
2594
|
+
type: "error",
|
|
2595
|
+
error: { message: "Voice transcription failed.", type: "provider" }
|
|
2596
|
+
});
|
|
2597
|
+
return;
|
|
2598
|
+
}
|
|
2599
|
+
let provisional = "";
|
|
2600
|
+
let endOfTurn = false;
|
|
2601
|
+
for (const token of (_a = message.tokens) != null ? _a : []) {
|
|
2602
|
+
const text = (_b = token.text) != null ? _b : "";
|
|
2603
|
+
if (text === "<end>") {
|
|
2604
|
+
endOfTurn = true;
|
|
2605
|
+
continue;
|
|
2606
|
+
}
|
|
2607
|
+
if (text === "<fin>") continue;
|
|
2608
|
+
if (token.is_final) this.finalText += text;
|
|
2609
|
+
else provisional += text;
|
|
2610
|
+
}
|
|
2611
|
+
const current = `${this.finalText}${provisional}`.trim();
|
|
2612
|
+
if (current && !this.utteranceId) {
|
|
2613
|
+
this.utteranceId = makeId("stream_input");
|
|
2614
|
+
this.emit({ type: "input_audio_buffer.speech_started", item_id: this.utteranceId });
|
|
2615
|
+
}
|
|
2616
|
+
if (this.utteranceId && current) {
|
|
2617
|
+
this.emit({
|
|
2618
|
+
type: "input_audio_transcription.snapshot",
|
|
2619
|
+
item_id: this.utteranceId,
|
|
2620
|
+
transcript: current
|
|
2621
|
+
});
|
|
2622
|
+
}
|
|
2623
|
+
if (endOfTurn) {
|
|
2624
|
+
const transcript = this.finalText.trim();
|
|
2625
|
+
if (this.utteranceId || transcript) {
|
|
2626
|
+
this.emit({
|
|
2627
|
+
type: "conversation.item.input_audio_transcription.completed",
|
|
2628
|
+
item_id: (_c = this.utteranceId) != null ? _c : makeId("stream_input"),
|
|
2629
|
+
transcript
|
|
2630
|
+
});
|
|
2631
|
+
}
|
|
2632
|
+
this.resetUtterance();
|
|
2633
|
+
}
|
|
2634
|
+
}
|
|
2635
|
+
resetUtterance() {
|
|
2636
|
+
this.finalText = "";
|
|
2637
|
+
this.utteranceId = null;
|
|
2638
|
+
}
|
|
2639
|
+
startKeepalive() {
|
|
2640
|
+
this.stopKeepalive();
|
|
2641
|
+
this.keepaliveTimer = setInterval(() => {
|
|
2642
|
+
const socket = this.socket;
|
|
2643
|
+
if (!socket || !this.socketReady || socket.readyState !== WebSocket.OPEN) return;
|
|
2644
|
+
if (Date.now() - this.lastSentAt < KEEPALIVE_INTERVAL_MS) return;
|
|
2645
|
+
socket.send(JSON.stringify({ type: "keepalive" }));
|
|
2646
|
+
this.lastSentAt = Date.now();
|
|
2647
|
+
}, KEEPALIVE_INTERVAL_MS / 2);
|
|
2648
|
+
}
|
|
2649
|
+
stopKeepalive() {
|
|
2650
|
+
if (this.keepaliveTimer) clearInterval(this.keepaliveTimer);
|
|
2651
|
+
this.keepaliveTimer = null;
|
|
2652
|
+
}
|
|
2653
|
+
scheduleReconnect(reason) {
|
|
2654
|
+
var _a, _b;
|
|
2655
|
+
if (this.userClosed || this.reconnectTimer) return;
|
|
2656
|
+
const maxAttempts = (_a = this.options.maxReconnectAttempts) != null ? _a : 3;
|
|
2657
|
+
if (this.reconnectAttempts >= maxAttempts) {
|
|
2658
|
+
this.setState("failed");
|
|
2659
|
+
return;
|
|
2660
|
+
}
|
|
2661
|
+
const base = (_b = this.options.reconnectBaseDelayMs) != null ? _b : 500;
|
|
2662
|
+
const delay = Math.min(base * 2 ** this.reconnectAttempts, 8e3);
|
|
2663
|
+
this.metric("reconnect_scheduled", delay, reason);
|
|
2664
|
+
this.setState("reconnecting");
|
|
2665
|
+
this.reconnectTimer = setTimeout(() => {
|
|
2666
|
+
this.reconnectTimer = null;
|
|
2667
|
+
void this.reconnect().catch(() => {
|
|
2668
|
+
});
|
|
2669
|
+
}, delay);
|
|
2670
|
+
}
|
|
2671
|
+
closeSocket() {
|
|
2672
|
+
this.stopKeepalive();
|
|
2673
|
+
this.socketReady = false;
|
|
2674
|
+
const socket = this.socket;
|
|
2675
|
+
this.socket = null;
|
|
2676
|
+
if (!socket) return;
|
|
2677
|
+
socket.onopen = null;
|
|
2678
|
+
socket.onmessage = null;
|
|
2679
|
+
socket.onclose = null;
|
|
2680
|
+
socket.onerror = null;
|
|
2681
|
+
try {
|
|
2682
|
+
if (socket.readyState === WebSocket.OPEN) socket.send("");
|
|
2683
|
+
socket.close();
|
|
2684
|
+
} catch {
|
|
2685
|
+
}
|
|
2686
|
+
}
|
|
2687
|
+
cleanupAll() {
|
|
2688
|
+
var _a, _b, _c, _d, _e, _f;
|
|
2689
|
+
this.closeSocket();
|
|
2690
|
+
this.resetUtterance();
|
|
2691
|
+
this.preconnect = [];
|
|
2692
|
+
this.preconnectBytes = 0;
|
|
2693
|
+
if (this.inputProcessor) this.inputProcessor.onaudioprocess = null;
|
|
2694
|
+
try {
|
|
2695
|
+
(_a = this.inputSource) == null ? void 0 : _a.disconnect();
|
|
2696
|
+
} catch {
|
|
2697
|
+
}
|
|
2698
|
+
try {
|
|
2699
|
+
(_b = this.inputProcessor) == null ? void 0 : _b.disconnect();
|
|
2700
|
+
} catch {
|
|
2701
|
+
}
|
|
2702
|
+
try {
|
|
2703
|
+
(_c = this.silentSink) == null ? void 0 : _c.disconnect();
|
|
2704
|
+
} catch {
|
|
2705
|
+
}
|
|
2706
|
+
this.inputSource = null;
|
|
2707
|
+
this.inputProcessor = null;
|
|
2708
|
+
this.silentSink = null;
|
|
2709
|
+
const context = this.audioContext;
|
|
2710
|
+
this.audioContext = null;
|
|
2711
|
+
if (context) void context.close().catch(() => void 0);
|
|
2712
|
+
for (const track of (_e = (_d = this.localStream) == null ? void 0 : _d.getTracks()) != null ? _e : []) track.stop();
|
|
2713
|
+
this.localStream = null;
|
|
2714
|
+
if (this.microphoneOn) {
|
|
2715
|
+
this.microphoneOn = false;
|
|
2716
|
+
try {
|
|
2717
|
+
(_f = this.options.microphone) == null ? void 0 : _f.stop();
|
|
2718
|
+
} catch {
|
|
2719
|
+
}
|
|
2720
|
+
}
|
|
2721
|
+
}
|
|
2722
|
+
emit(event) {
|
|
2723
|
+
for (const listener of this.eventListeners) listener(event);
|
|
2724
|
+
}
|
|
2725
|
+
setState(next) {
|
|
2726
|
+
if (next === this.state) return;
|
|
2727
|
+
const previous = this.state;
|
|
2728
|
+
this.state = next;
|
|
2729
|
+
for (const listener of this.stateListeners) listener(next, previous);
|
|
2730
|
+
}
|
|
2731
|
+
metric(name, value, detail) {
|
|
2732
|
+
var _a, _b;
|
|
2733
|
+
(_b = (_a = this.options).onMetric) == null ? void 0 : _b.call(_a, { name, value, detail, at: Date.now() });
|
|
2734
|
+
}
|
|
2735
|
+
}
|
|
2736
|
+
function waitForOpen(socket, signal) {
|
|
2737
|
+
if (socket.readyState === WebSocket.OPEN) return Promise.resolve();
|
|
2738
|
+
return new Promise((resolve, reject) => {
|
|
2739
|
+
const onAbort = () => {
|
|
2740
|
+
cleanup();
|
|
2741
|
+
reject(abortError("Connection aborted"));
|
|
2742
|
+
};
|
|
2743
|
+
const cleanup = () => {
|
|
2744
|
+
socket.onopen = null;
|
|
2745
|
+
socket.onerror = null;
|
|
2746
|
+
signal.removeEventListener("abort", onAbort);
|
|
2747
|
+
};
|
|
2748
|
+
if (signal.aborted) {
|
|
2749
|
+
onAbort();
|
|
2750
|
+
return;
|
|
2751
|
+
}
|
|
2752
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
2753
|
+
socket.onopen = () => {
|
|
2754
|
+
cleanup();
|
|
2755
|
+
resolve();
|
|
2756
|
+
};
|
|
2757
|
+
socket.onerror = () => {
|
|
2758
|
+
cleanup();
|
|
2759
|
+
reject(new Error("Voice connection failed."));
|
|
2760
|
+
};
|
|
2761
|
+
});
|
|
2762
|
+
}
|
|
2763
|
+
const MIC_RATE = 16e3;
|
|
2764
|
+
const MIC_BLOCK = 800;
|
|
2765
|
+
const SPEECH_RATE = 24e3;
|
|
2766
|
+
const failed = (result) => {
|
|
2767
|
+
var _a;
|
|
2768
|
+
return result && typeof result === "object" && result.status === "error" ? String((_a = result.message) != null ? _a : "The microphone did not start.") : null;
|
|
2769
|
+
};
|
|
2770
|
+
function phoneMicrophone(audio, onLevel) {
|
|
2771
|
+
let recorder = null;
|
|
2772
|
+
let levelAt = 0;
|
|
2773
|
+
return {
|
|
2774
|
+
async start(onAudio) {
|
|
2775
|
+
const mine = new audio.AudioRecorder({ iosVoiceProcessing: true, androidInputPreset: "voiceCommunication" });
|
|
2776
|
+
recorder = mine;
|
|
2777
|
+
const listening = failed(mine.onAudioReady(
|
|
2778
|
+
{ sampleRate: MIC_RATE, bufferLength: MIC_BLOCK, channelCount: 1 },
|
|
2779
|
+
(event) => {
|
|
2780
|
+
if (recorder !== mine) return;
|
|
2781
|
+
const all = event.buffer.getChannelData(0);
|
|
2782
|
+
const samples = event.numFrames < all.length ? all.subarray(0, event.numFrames) : all;
|
|
2783
|
+
onAudio(samples, event.buffer.sampleRate);
|
|
2784
|
+
const now = Date.now();
|
|
2785
|
+
if (onLevel && now - levelAt >= 100) {
|
|
2786
|
+
levelAt = now;
|
|
2787
|
+
let sum = 0;
|
|
2788
|
+
for (let i = 0; i < samples.length; i += 1) sum += samples[i] * samples[i];
|
|
2789
|
+
const db = 10 * Math.log10(sum / Math.max(1, samples.length) + 1e-12);
|
|
2790
|
+
onLevel(Math.max(0, Math.min(1, (db + 60) / 50)));
|
|
2791
|
+
}
|
|
2792
|
+
}
|
|
2793
|
+
));
|
|
2794
|
+
if (listening) throw new Error(listening);
|
|
2795
|
+
const started = failed(await mine.start());
|
|
2796
|
+
if (started) throw new Error(started);
|
|
2797
|
+
},
|
|
2798
|
+
stop() {
|
|
2799
|
+
const mine = recorder;
|
|
2800
|
+
recorder = null;
|
|
2801
|
+
if (!mine) return;
|
|
2802
|
+
try {
|
|
2803
|
+
mine.clearOnAudioReady();
|
|
2804
|
+
} catch {
|
|
2805
|
+
}
|
|
2806
|
+
void mine.stop().catch(() => void 0);
|
|
2807
|
+
}
|
|
2808
|
+
};
|
|
2809
|
+
}
|
|
2810
|
+
async function openCallAudio(audio) {
|
|
2811
|
+
var _a, _b, _c, _d;
|
|
2812
|
+
const permission = await audio.AudioManager.requestRecordingPermissions().catch(() => "Denied");
|
|
2813
|
+
if (permission !== "Granted") return false;
|
|
2814
|
+
try {
|
|
2815
|
+
(_b = (_a = audio.AudioManager).setSystemOptions) == null ? void 0 : _b.call(_a, {
|
|
2816
|
+
ios: { category: "playAndRecord", mode: "voiceChat", options: ["defaultToSpeaker", "allowBluetoothHFP"] }
|
|
2817
|
+
});
|
|
2818
|
+
await ((_d = (_c = audio.AudioManager).setAudioSessionActivity) == null ? void 0 : _d.call(_c, true));
|
|
2819
|
+
} catch {
|
|
2820
|
+
}
|
|
2821
|
+
return true;
|
|
2822
|
+
}
|
|
2823
|
+
function closeCallAudio(audio) {
|
|
2824
|
+
var _a, _b, _c, _d;
|
|
2825
|
+
void ((_d = (_c = (_b = (_a = audio.AudioManager).setAudioSessionActivity) == null ? void 0 : _b.call(_a, false)) == null ? void 0 : _c.catch) == null ? void 0 : _d.call(_c, () => void 0));
|
|
2826
|
+
}
|
|
2827
|
+
const KEY_TIMEOUT_MS = 15e3;
|
|
2828
|
+
const refused = (error) => {
|
|
2829
|
+
const status = Number(error == null ? void 0 : error.status) || 503;
|
|
2830
|
+
return { ok: false, status, json: async () => ({}) };
|
|
2831
|
+
};
|
|
2832
|
+
async function startStreamingCall(options) {
|
|
2833
|
+
const { audio, api } = options;
|
|
2834
|
+
if (!await openCallAudio(audio)) return null;
|
|
2835
|
+
const listenPath = EP.listenSession();
|
|
2836
|
+
const speakPath = EP.speakSession();
|
|
2837
|
+
const transport = new SonioxSttTransport({
|
|
2838
|
+
microphone: phoneMicrophone(audio, options.onLevel),
|
|
2839
|
+
sessionProvider: {
|
|
2840
|
+
async createSession() {
|
|
2841
|
+
const session = await api.post(listenPath, {}, KEY_TIMEOUT_MS);
|
|
2842
|
+
return { ...session, url: socketUrl(session.url, `${api.apiBase}${listenPath}`) };
|
|
2843
|
+
}
|
|
2844
|
+
}
|
|
2845
|
+
});
|
|
2846
|
+
const speech = new SonioxSpeechProvider({
|
|
2847
|
+
tokenUrl: `${api.apiBase}${speakPath}`,
|
|
2848
|
+
token: "",
|
|
2849
|
+
fetcher: async (_url, init) => {
|
|
2850
|
+
try {
|
|
2851
|
+
const minted = await api.post(speakPath, init.body ? JSON.parse(init.body) : {}, KEY_TIMEOUT_MS);
|
|
2852
|
+
return { ok: true, status: 200, json: async () => minted };
|
|
2853
|
+
} catch (error) {
|
|
2854
|
+
return refused(error);
|
|
2855
|
+
}
|
|
2856
|
+
}
|
|
2857
|
+
});
|
|
2858
|
+
const player = new PcmStreamPlayer({ audioContextFactory: () => new audio.AudioContext({ sampleRate: SPEECH_RATE }) });
|
|
2859
|
+
let speaking = false;
|
|
2860
|
+
const agent = new PipelineVoiceAgent({
|
|
2861
|
+
host: {
|
|
2862
|
+
getConversationState: () => null,
|
|
2863
|
+
dispatchConversationEvent: () => null,
|
|
2864
|
+
hasPendingConfirmation: () => {
|
|
2865
|
+
var _a, _b;
|
|
2866
|
+
return (_b = (_a = options.pendingAction) == null ? void 0 : _a.call(options)) != null ? _b : false;
|
|
2867
|
+
},
|
|
2868
|
+
submitAgentTurn: async (text, _mode, onTextDelta) => {
|
|
2869
|
+
const answer = await options.ask(text, onTextDelta != null ? onTextDelta : (() => void 0));
|
|
2870
|
+
if (!answer) throw new Error("The assistant did not answer.");
|
|
2871
|
+
return answer;
|
|
2872
|
+
}
|
|
2873
|
+
},
|
|
2874
|
+
// "Yes" or "no" to an action waiting for approval settles it, as a tap would.
|
|
2875
|
+
actionRouter: {
|
|
2876
|
+
async route(text) {
|
|
2877
|
+
var _a;
|
|
2878
|
+
if (!((_a = options.pendingAction) == null ? void 0 : _a.call(options)) || !options.answerAction) return null;
|
|
2879
|
+
const answer = confirmationAnswer(text);
|
|
2880
|
+
if (!answer) return null;
|
|
2881
|
+
const said = await options.answerAction(answer);
|
|
2882
|
+
return said ? { actionId: `confirmation_${answer}`, response: said, alreadyInChat: true } : null;
|
|
2883
|
+
}
|
|
2884
|
+
},
|
|
2885
|
+
inputTransport: transport,
|
|
2886
|
+
speechProvider: speech,
|
|
2887
|
+
player,
|
|
2888
|
+
language: options.language,
|
|
2889
|
+
onActivity: (state2) => {
|
|
2890
|
+
speaking = state2 === "speaking";
|
|
2891
|
+
options.onActivity(state2);
|
|
2892
|
+
},
|
|
2893
|
+
// Words arriving while nobody is speaking: the visitor has started a turn.
|
|
2894
|
+
onTranscript: (event) => {
|
|
2895
|
+
if (event.role === "user" && !event.final && event.text.trim() && !speaking) options.onActivity("hearing");
|
|
2896
|
+
},
|
|
2897
|
+
onError: options.onError
|
|
2898
|
+
});
|
|
2899
|
+
try {
|
|
2900
|
+
await agent.start();
|
|
2901
|
+
} catch (error) {
|
|
2902
|
+
agent.destroy();
|
|
2903
|
+
closeCallAudio(audio);
|
|
2904
|
+
throw error;
|
|
2905
|
+
}
|
|
2906
|
+
let stopped = false;
|
|
2907
|
+
return {
|
|
2908
|
+
interrupt: () => player.stop(),
|
|
2909
|
+
stop: () => {
|
|
2910
|
+
if (stopped) return;
|
|
2911
|
+
stopped = true;
|
|
2912
|
+
agent.destroy();
|
|
2913
|
+
closeCallAudio(audio);
|
|
2914
|
+
}
|
|
2915
|
+
};
|
|
2916
|
+
}
|
|
2917
|
+
const MAX_LINE_MS = 6e4;
|
|
2918
|
+
const MIN_PIECE_CHARS = 12;
|
|
2919
|
+
const fillerFiles = /* @__PURE__ */ new Map();
|
|
2920
|
+
function createLiveSpeaker(onSpeaking) {
|
|
2921
|
+
const queue = [];
|
|
2922
|
+
const fence = createFenceFilter();
|
|
2923
|
+
let written = "";
|
|
2924
|
+
let answered = false;
|
|
2925
|
+
let heard = false;
|
|
2926
|
+
let done = false;
|
|
2927
|
+
let stopped = false;
|
|
2928
|
+
let player = null;
|
|
2929
|
+
let ended = null;
|
|
2930
|
+
let wake = null;
|
|
2931
|
+
const nudge = () => {
|
|
2932
|
+
const go = wake;
|
|
2933
|
+
wake = null;
|
|
2934
|
+
go == null ? void 0 : go();
|
|
2935
|
+
};
|
|
2936
|
+
const fetchFor = (line) => {
|
|
2937
|
+
if (line.file) return line.file;
|
|
2938
|
+
if (line.filler) {
|
|
2939
|
+
let cached = fillerFiles.get(line.text);
|
|
2940
|
+
if (!cached) {
|
|
2941
|
+
cached = fetchLine(line.text).catch(() => null);
|
|
2942
|
+
fillerFiles.set(line.text, cached);
|
|
2943
|
+
void cached.then((file) => {
|
|
2944
|
+
if (!file) fillerFiles.delete(line.text);
|
|
2945
|
+
});
|
|
2946
|
+
}
|
|
2947
|
+
line.file = cached;
|
|
2948
|
+
} else {
|
|
2949
|
+
line.file = fetchLine(line.text).catch((error) => {
|
|
2950
|
+
console.log("[GuideAI] ✗ could not say a line:", error);
|
|
2951
|
+
return null;
|
|
2952
|
+
});
|
|
2953
|
+
}
|
|
2954
|
+
return line.file;
|
|
2955
|
+
};
|
|
2956
|
+
const play = (file) => new Promise((resolve) => {
|
|
2957
|
+
const current = createAudioPlayer({ uri: file.uri });
|
|
2958
|
+
player = current;
|
|
2959
|
+
const timer = setTimeout(() => ended == null ? void 0 : ended(), MAX_LINE_MS);
|
|
2960
|
+
ended = () => {
|
|
2961
|
+
clearTimeout(timer);
|
|
2962
|
+
ended = null;
|
|
2963
|
+
if (player === current) player = null;
|
|
2964
|
+
try {
|
|
2965
|
+
current.pause();
|
|
2966
|
+
current.remove();
|
|
2967
|
+
} catch {
|
|
2968
|
+
}
|
|
2969
|
+
resolve();
|
|
2970
|
+
};
|
|
2971
|
+
current.addListener("playbackStatusUpdate", (status) => {
|
|
2972
|
+
if (status.didJustFinish && player === current) ended == null ? void 0 : ended();
|
|
2973
|
+
});
|
|
2974
|
+
current.play();
|
|
2975
|
+
});
|
|
2976
|
+
const loop = (async () => {
|
|
2977
|
+
var _a;
|
|
2978
|
+
while (!stopped) {
|
|
2979
|
+
const line = queue.shift();
|
|
2980
|
+
if (!line) {
|
|
2981
|
+
if (done) break;
|
|
2982
|
+
await new Promise((resolve) => {
|
|
2983
|
+
wake = resolve;
|
|
2984
|
+
});
|
|
2985
|
+
continue;
|
|
2986
|
+
}
|
|
2987
|
+
if (line.filler && answered) continue;
|
|
2988
|
+
const next = queue[0];
|
|
2989
|
+
if (next && !(next.filler && answered)) void fetchFor(next);
|
|
2990
|
+
const file = await fetchFor(line);
|
|
2991
|
+
if (stopped) {
|
|
2992
|
+
if (!line.filler) forget(file);
|
|
2993
|
+
break;
|
|
2994
|
+
}
|
|
2995
|
+
if (!file) continue;
|
|
2996
|
+
if (!line.filler && !heard) {
|
|
2997
|
+
heard = true;
|
|
2998
|
+
onSpeaking == null ? void 0 : onSpeaking();
|
|
2999
|
+
}
|
|
3000
|
+
await play(file);
|
|
3001
|
+
if (!line.filler) forget(file);
|
|
3002
|
+
}
|
|
3003
|
+
for (const left of queue) if (!left.filler) void ((_a = left.file) == null ? void 0 : _a.then(forget));
|
|
3004
|
+
queue.length = 0;
|
|
3005
|
+
})();
|
|
3006
|
+
const say = (markdown) => {
|
|
3007
|
+
const lines = speechLines(toSpeakable(markdown).trim());
|
|
3008
|
+
if (!lines.length) return;
|
|
3009
|
+
if (!answered) {
|
|
3010
|
+
answered = true;
|
|
3011
|
+
for (let i = queue.length - 1; i >= 0; i -= 1) if (queue[i].filler) queue.splice(i, 1);
|
|
3012
|
+
}
|
|
3013
|
+
for (const text of lines) queue.push({ text, filler: false });
|
|
3014
|
+
void fetchFor(queue[0]);
|
|
3015
|
+
nudge();
|
|
3016
|
+
};
|
|
3017
|
+
return {
|
|
3018
|
+
get answering() {
|
|
3019
|
+
return answered;
|
|
3020
|
+
},
|
|
3021
|
+
filler(text) {
|
|
3022
|
+
if (stopped || done || answered || !text.trim()) return;
|
|
3023
|
+
if (queue.some((line) => line.filler)) return;
|
|
3024
|
+
queue.push({ text: text.trim(), filler: true });
|
|
3025
|
+
nudge();
|
|
3026
|
+
},
|
|
3027
|
+
push(delta) {
|
|
3028
|
+
var _a;
|
|
3029
|
+
if (stopped || done) return;
|
|
3030
|
+
written += fence(delta);
|
|
3031
|
+
let cut = -1;
|
|
3032
|
+
for (const match of written.matchAll(/[.!?](?=\s)|\n/g)) cut = ((_a = match.index) != null ? _a : 0) + 1;
|
|
3033
|
+
if (cut < 0 || written.slice(0, cut).trim().length < MIN_PIECE_CHARS) return;
|
|
3034
|
+
const piece = written.slice(0, cut);
|
|
3035
|
+
written = written.slice(cut);
|
|
3036
|
+
say(piece);
|
|
3037
|
+
},
|
|
3038
|
+
async finish(answer) {
|
|
3039
|
+
if (stopped) return heard;
|
|
3040
|
+
if (!answered) say(answer);
|
|
3041
|
+
else if (written.trim()) say(written);
|
|
3042
|
+
written = "";
|
|
3043
|
+
done = true;
|
|
3044
|
+
nudge();
|
|
3045
|
+
await loop;
|
|
3046
|
+
return heard;
|
|
3047
|
+
},
|
|
3048
|
+
stop() {
|
|
3049
|
+
if (stopped) return;
|
|
3050
|
+
stopped = true;
|
|
3051
|
+
done = true;
|
|
3052
|
+
ended == null ? void 0 : ended();
|
|
3053
|
+
nudge();
|
|
3054
|
+
}
|
|
3055
|
+
};
|
|
345
3056
|
}
|
|
346
3057
|
const RECORDING = { ...RecordingPresets.HIGH_QUALITY, isMeteringEnabled: true };
|
|
347
3058
|
const POLL_MS = 100;
|
|
@@ -391,8 +3102,16 @@ function useLiveVoice(chat, options = {}) {
|
|
|
391
3102
|
} catch {
|
|
392
3103
|
}
|
|
393
3104
|
}, [recorder]);
|
|
3105
|
+
const streaming = useRef(null);
|
|
3106
|
+
const speaking = useRef(null);
|
|
3107
|
+
const roomNoise = useRef(null);
|
|
394
3108
|
const stop = useCallback(() => {
|
|
3109
|
+
var _a2, _b2;
|
|
395
3110
|
call.current += 1;
|
|
3111
|
+
(_a2 = streaming.current) == null ? void 0 : _a2.stop();
|
|
3112
|
+
streaming.current = null;
|
|
3113
|
+
(_b2 = speaking.current) == null ? void 0 : _b2.stop();
|
|
3114
|
+
speaking.current = null;
|
|
396
3115
|
voice().stop();
|
|
397
3116
|
void stopRecorder();
|
|
398
3117
|
void setAudioModeAsync({ allowsRecording: false }).catch(() => void 0);
|
|
@@ -400,10 +3119,72 @@ function useLiveVoice(chat, options = {}) {
|
|
|
400
3119
|
if (mounted.current) setLevel(0);
|
|
401
3120
|
}, [show, stopRecorder]);
|
|
402
3121
|
useEffect(() => () => {
|
|
3122
|
+
var _a2;
|
|
403
3123
|
mounted.current = false;
|
|
404
3124
|
call.current += 1;
|
|
3125
|
+
(_a2 = streaming.current) == null ? void 0 : _a2.stop();
|
|
3126
|
+
streaming.current = null;
|
|
405
3127
|
voice().stop();
|
|
406
3128
|
}, []);
|
|
3129
|
+
const startStreaming = useCallback(async (mine) => {
|
|
3130
|
+
var _a2;
|
|
3131
|
+
const { audio, api } = requireConfigured();
|
|
3132
|
+
if (!audio || !chatRef.current.send) return null;
|
|
3133
|
+
const pendingId = () => {
|
|
3134
|
+
var _a3;
|
|
3135
|
+
const last = (_a3 = chatRef.current.messages) == null ? void 0 : _a3[chatRef.current.messages.length - 1];
|
|
3136
|
+
return (last == null ? void 0 : last.role) === "assistant" && last.pendingAction ? last.id : null;
|
|
3137
|
+
};
|
|
3138
|
+
show("thinking");
|
|
3139
|
+
const started = await startStreamingCall({
|
|
3140
|
+
audio,
|
|
3141
|
+
api,
|
|
3142
|
+
language: resolveVoiceLanguage((_a2 = languageRef.current) != null ? _a2 : "en"),
|
|
3143
|
+
ask: async (text, onDelta) => {
|
|
3144
|
+
var _a3, _b2, _c;
|
|
3145
|
+
for (let waited = 0; chatRef.current.busy && waited < 6e4; waited += 100) await sleep(100);
|
|
3146
|
+
return (_c = await ((_b2 = (_a3 = chatRef.current).send) == null ? void 0 : _b2.call(_a3, text, { onDelta }))) != null ? _c : "";
|
|
3147
|
+
},
|
|
3148
|
+
pendingAction: () => pendingId() !== null,
|
|
3149
|
+
answerAction: async (answer) => {
|
|
3150
|
+
var _a3, _b2, _c, _d, _e;
|
|
3151
|
+
const id = pendingId();
|
|
3152
|
+
if (!id) return null;
|
|
3153
|
+
if (answer === "yes") return (_c = await ((_b2 = (_a3 = chatRef.current).confirm) == null ? void 0 : _b2.call(_a3, id))) != null ? _c : "Done.";
|
|
3154
|
+
(_e = (_d = chatRef.current).cancel) == null ? void 0 : _e.call(_d, id);
|
|
3155
|
+
return "Okay, I won't do that.";
|
|
3156
|
+
},
|
|
3157
|
+
onActivity: (next) => {
|
|
3158
|
+
if (mine === call.current) show(next);
|
|
3159
|
+
},
|
|
3160
|
+
onLevel: (next) => {
|
|
3161
|
+
if (mine === call.current && mounted.current) setLevel(next);
|
|
3162
|
+
},
|
|
3163
|
+
onError: (cause) => {
|
|
3164
|
+
console.log("[GuideAI] ✗ live voice:", cause);
|
|
3165
|
+
if (mine === call.current && mounted.current) setError(cause.message || START_FAILED);
|
|
3166
|
+
}
|
|
3167
|
+
}).catch((cause) => {
|
|
3168
|
+
console.log("[GuideAI] ✗ live voice: the call did not start:", cause);
|
|
3169
|
+
return void 0;
|
|
3170
|
+
});
|
|
3171
|
+
if (started === null) {
|
|
3172
|
+
if (mounted.current) setError(MIC_REFUSED);
|
|
3173
|
+
show("off");
|
|
3174
|
+
return false;
|
|
3175
|
+
}
|
|
3176
|
+
if (!started) {
|
|
3177
|
+
if (mounted.current) setError(START_FAILED);
|
|
3178
|
+
show("off");
|
|
3179
|
+
return false;
|
|
3180
|
+
}
|
|
3181
|
+
if (mine !== call.current) {
|
|
3182
|
+
started.stop();
|
|
3183
|
+
return false;
|
|
3184
|
+
}
|
|
3185
|
+
streaming.current = started;
|
|
3186
|
+
return true;
|
|
3187
|
+
}, [show]);
|
|
407
3188
|
const listen = useCallback(async (mine) => {
|
|
408
3189
|
var _a2, _b2;
|
|
409
3190
|
await setAudioModeAsync({ allowsRecording: true, playsInSilentMode: true });
|
|
@@ -411,7 +3192,8 @@ function useLiveVoice(chat, options = {}) {
|
|
|
411
3192
|
recorder.record();
|
|
412
3193
|
show("listening");
|
|
413
3194
|
const began = Date.now();
|
|
414
|
-
let noise =
|
|
3195
|
+
let noise = roomNoise.current;
|
|
3196
|
+
const learning = noise === null;
|
|
415
3197
|
let speechSince = null;
|
|
416
3198
|
let quietSince = null;
|
|
417
3199
|
let spoke = false;
|
|
@@ -420,10 +3202,11 @@ function useLiveVoice(chat, options = {}) {
|
|
|
420
3202
|
if (mine !== call.current) break;
|
|
421
3203
|
const db = (_a2 = recorder.getStatus().metering) != null ? _a2 : -160;
|
|
422
3204
|
const now = Date.now();
|
|
423
|
-
if (now - began < 500) {
|
|
3205
|
+
if (learning && now - began < 500) {
|
|
424
3206
|
noise = noise === null ? db : Math.max(noise, db);
|
|
425
3207
|
continue;
|
|
426
3208
|
}
|
|
3209
|
+
if (learning && roomNoise.current === null) roomNoise.current = noise;
|
|
427
3210
|
const threshold = Math.max(SPEECH_FLOOR_DB, (noise != null ? noise : -60) + OVER_NOISE_DB);
|
|
428
3211
|
if (mounted.current) setLevel(Math.max(0, Math.min(1, (db + 60) / 50)));
|
|
429
3212
|
if (db >= threshold) {
|
|
@@ -456,13 +3239,16 @@ function useLiveVoice(chat, options = {}) {
|
|
|
456
3239
|
lang.ask();
|
|
457
3240
|
return false;
|
|
458
3241
|
}
|
|
3242
|
+
call.current += 1;
|
|
3243
|
+
const mine = call.current;
|
|
3244
|
+
roomNoise.current = null;
|
|
3245
|
+
const streamed = await startStreaming(mine);
|
|
3246
|
+
if (streamed !== null) return streamed;
|
|
459
3247
|
const permission = await requestRecordingPermissionsAsync().catch(() => null);
|
|
460
3248
|
if (!(permission == null ? void 0 : permission.granted)) {
|
|
461
3249
|
if (mounted.current) setError(MIC_REFUSED);
|
|
462
3250
|
return false;
|
|
463
3251
|
}
|
|
464
|
-
call.current += 1;
|
|
465
|
-
const mine = call.current;
|
|
466
3252
|
void (async () => {
|
|
467
3253
|
var _a2;
|
|
468
3254
|
while (mine === call.current) {
|
|
@@ -485,20 +3271,50 @@ function useLiveVoice(chat, options = {}) {
|
|
|
485
3271
|
}
|
|
486
3272
|
if (!heard) continue;
|
|
487
3273
|
show("thinking");
|
|
488
|
-
await setAudioModeAsync({ allowsRecording: false }).catch(() => void 0);
|
|
489
|
-
const
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
3274
|
+
await setAudioModeAsync({ allowsRecording: false, playsInSilentMode: true }).catch(() => void 0);
|
|
3275
|
+
const configured = requireConfigured().speech;
|
|
3276
|
+
const own = !configured || isOwnSpeech(configured);
|
|
3277
|
+
const speaker = own ? createLiveSpeaker(() => {
|
|
3278
|
+
if (mine === call.current) show("speaking");
|
|
3279
|
+
}) : null;
|
|
3280
|
+
speaking.current = speaker;
|
|
3281
|
+
let lastLine = null;
|
|
3282
|
+
const timers = speaker ? thinkingAloudSchedule().map((delay, index) => setTimeout(() => {
|
|
3283
|
+
var _a3;
|
|
3284
|
+
if (speaker.answering) return;
|
|
3285
|
+
const line = thinkingLine((_a3 = languageRef.current) != null ? _a3 : void 0, index, lastLine);
|
|
3286
|
+
if (line) {
|
|
3287
|
+
lastLine = line;
|
|
3288
|
+
speaker.filler(line);
|
|
3289
|
+
}
|
|
3290
|
+
}, delay)) : [];
|
|
3291
|
+
const result = await chatRef.current.sendVoice(
|
|
3292
|
+
{ uri: heard, languageCode: (_a2 = languageRef.current) != null ? _a2 : void 0 },
|
|
3293
|
+
speaker ? { onDelta: (delta) => speaker.push(delta) } : void 0
|
|
3294
|
+
).finally(() => timers.forEach(clearTimeout));
|
|
3295
|
+
if (mine !== call.current) {
|
|
3296
|
+
speaker == null ? void 0 : speaker.stop();
|
|
3297
|
+
return;
|
|
3298
|
+
}
|
|
3299
|
+
if (!result.text || !result.answer) {
|
|
3300
|
+
speaker == null ? void 0 : speaker.stop();
|
|
3301
|
+
continue;
|
|
3302
|
+
}
|
|
3303
|
+
if (speaker) await speaker.finish(result.answer);
|
|
3304
|
+
else {
|
|
493
3305
|
show("speaking");
|
|
494
3306
|
await voice().say(toSpeakable(result.answer));
|
|
495
3307
|
}
|
|
3308
|
+
if (speaking.current === speaker) speaking.current = null;
|
|
496
3309
|
}
|
|
497
3310
|
})();
|
|
498
3311
|
return true;
|
|
499
|
-
}, [state2, lang, listen, show, stop]);
|
|
3312
|
+
}, [state2, lang, listen, show, stop, startStreaming]);
|
|
500
3313
|
startRef.current = start;
|
|
501
3314
|
const interrupt = useCallback(() => {
|
|
3315
|
+
var _a2, _b2;
|
|
3316
|
+
(_a2 = streaming.current) == null ? void 0 : _a2.interrupt();
|
|
3317
|
+
(_b2 = speaking.current) == null ? void 0 : _b2.stop();
|
|
502
3318
|
voice().stop();
|
|
503
3319
|
}, []);
|
|
504
3320
|
return {
|