orb-ui 0.9.0 → 0.10.1

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/dist/adapters.js CHANGED
@@ -927,4 +927,1224 @@ function M(e) {
927
927
  };
928
928
  }
929
929
  //#endregion
930
- export { a as DEFAULT_VOLUME_CALIBRATION, r as PROVIDER_VOLUME_CALIBRATIONS, n as calibrateVolume, d as createElevenLabsAdapter, M as createGeminiLiveAdapter, s as createLiveKitAdapter, v as createOpenAILiveAdapter, T as createOpenAIRealtimeAdapter, g as createPipecatAdapter, u as createVapiAdapter, i as createVolumeNormalizer, o as fitVolumeCalibration, t as mapVolumeAmplitude };
930
+ //#region src/adapters/retell/index.ts
931
+ function N(e, t) {
932
+ let n = /* @__PURE__ */ new Set(), r = i({
933
+ amplitude: {
934
+ silenceFloor: .003,
935
+ speechReference: .08,
936
+ speechPeak: .3
937
+ },
938
+ envelope: {
939
+ riseTimeMs: 100,
940
+ fallTimeMs: 200
941
+ }
942
+ }, t.outputVolumeCalibration), a = {
943
+ state: "idle",
944
+ inputVolume: 0,
945
+ outputVolume: 0
946
+ }, o = 0, s, c, l, u, d = !1, f = !1, p, m = Number.isFinite(t.outputActivityThreshold) ? Math.max(1e-6, Math.min(1, t.outputActivityThreshold)) : .01, h = Number.isFinite(t.outputActivityHoldMs) ? Math.max(20, Math.min(2e3, t.outputActivityHoldMs)) : 180;
947
+ function g() {
948
+ clearTimeout(p), p = void 0, r.reset();
949
+ }
950
+ function _() {
951
+ return d ? "thinking" : "listening";
952
+ }
953
+ function v(e) {
954
+ a = e, n.forEach((t) => t(e));
955
+ }
956
+ function y(e, t) {
957
+ d = !1, f = !1, g(), v({
958
+ state: e,
959
+ inputVolume: 0,
960
+ outputVolume: 0,
961
+ ...t === void 0 ? {} : { error: t }
962
+ });
963
+ }
964
+ function b(e) {
965
+ e === o && (o += 1, c = void 0, s = void 0, a.state !== "error" && y("idle"));
966
+ }
967
+ async function x() {
968
+ let n = ++o, i = new AbortController();
969
+ c = i, y("connecting");
970
+ let l = () => n === o && !i.signal.aborted, u;
971
+ try {
972
+ let o = await t.getCallOptions(i.signal);
973
+ if (!l()) return;
974
+ let c = o.hooks, x = {
975
+ onStatus(e) {
976
+ l() && (e === "ended" ? a.state !== "error" && y("idle") : e === "connecting" ? y("connecting") : e === "live" && a.state !== "error" && v({
977
+ ...a,
978
+ state: _(),
979
+ error: void 0
980
+ }), c?.onStatus?.(e));
981
+ },
982
+ onAudio(e) {
983
+ if (!l() || a.state === "error" || s?.status !== "live") return;
984
+ if (!(t.isAudioPlaybackActive ? t.isAudioPlaybackActive(s) : s.analyzerComponent?.analyser.context.state === "running")) {
985
+ g(), v({
986
+ ...a,
987
+ state: _(),
988
+ outputVolume: 0
989
+ });
990
+ return;
991
+ }
992
+ let n = 0;
993
+ for (let t of e) n += Number.isFinite(t) ? t * t : 0;
994
+ let i = e.length ? Math.sqrt(n / e.length) : 0, o = r.sample(i);
995
+ t.onOutputVolumeSample?.(o), f && i < m && (f = !1), i >= m && !f ? (d = !1, clearTimeout(p), v({
996
+ ...a,
997
+ state: "speaking",
998
+ outputVolume: o.normalized
999
+ }), p = setTimeout(() => {
1000
+ !l() || a.state === "error" || (g(), v({
1001
+ ...a,
1002
+ state: _(),
1003
+ outputVolume: 0
1004
+ }));
1005
+ }, h)) : v({
1006
+ ...a,
1007
+ outputVolume: a.state === "speaking" ? o.normalized : 0
1008
+ }), c?.onAudio?.(e);
1009
+ },
1010
+ onError(e) {
1011
+ l() && (u = e, y("error", e), c?.onError?.(e));
1012
+ },
1013
+ onEnd(e) {
1014
+ l() && (b(n), c?.onEnd?.(e));
1015
+ }
1016
+ }, S = e.createWebCall({
1017
+ ...o,
1018
+ audio: {
1019
+ ...o.audio,
1020
+ emitRawAudioSamples: !0
1021
+ },
1022
+ hooks: x
1023
+ });
1024
+ if (!l()) {
1025
+ await S.end();
1026
+ return;
1027
+ }
1028
+ s = S, await S.ready, l() && a.state === "connecting" && S.status === "live" && v({
1029
+ ...a,
1030
+ state: "listening"
1031
+ });
1032
+ } catch (e) {
1033
+ if (!l()) {
1034
+ if (u !== void 0 && !i.signal.aborted) throw u;
1035
+ return;
1036
+ }
1037
+ y("error", e);
1038
+ let t = s;
1039
+ s = void 0, o += 1, i.abort();
1040
+ try {
1041
+ await t?.end();
1042
+ } catch {}
1043
+ throw e;
1044
+ }
1045
+ }
1046
+ function S() {
1047
+ if (u) return u;
1048
+ o += 1, c?.abort(), c = void 0, l = void 0;
1049
+ let e = s;
1050
+ s = void 0, y("idle");
1051
+ let t = (async () => {
1052
+ try {
1053
+ await e?.end();
1054
+ } catch (e) {
1055
+ throw y("error", e), e;
1056
+ }
1057
+ })();
1058
+ return u = t, t.finally(() => {
1059
+ u === t && (u = void 0);
1060
+ }).catch(() => void 0), t;
1061
+ }
1062
+ return {
1063
+ subscribe(e) {
1064
+ return n.add(e), e(a), () => {
1065
+ n.delete(e), !n.size && t.stopOnUnsubscribe !== !1 && S().catch(() => void 0);
1066
+ };
1067
+ },
1068
+ start() {
1069
+ if (l) return l;
1070
+ if (s && a.state !== "error") return Promise.resolve();
1071
+ let e = s ? S() : u, t = o, n = (async () => {
1072
+ e && await e, t === o && await x();
1073
+ })();
1074
+ return l = n, n.finally(() => {
1075
+ l === n && (l = void 0);
1076
+ }).catch(() => void 0), n;
1077
+ },
1078
+ stop: S,
1079
+ getTurnObserver() {
1080
+ let e = o;
1081
+ return (t) => {
1082
+ e !== o || s?.status !== "live" || a.state === "error" || (d = t === "thinking", !(t === "thinking" && a.state === "speaking") && (f = t === "interrupted", g(), v({
1083
+ ...a,
1084
+ state: _(),
1085
+ outputVolume: 0
1086
+ })));
1087
+ };
1088
+ },
1089
+ async resumeAudio() {
1090
+ let e = s;
1091
+ if (!e) return;
1092
+ let t = o;
1093
+ try {
1094
+ await e.startAudioPlayback(), t === o && a.state === "error" && v({
1095
+ ...a,
1096
+ state: "listening",
1097
+ error: void 0
1098
+ });
1099
+ } catch (e) {
1100
+ throw t === o && y("error", e), e;
1101
+ }
1102
+ }
1103
+ };
1104
+ }
1105
+ //#endregion
1106
+ //#region src/adapters/hume/index.ts
1107
+ function P(e) {
1108
+ if (!e?.length) return 0;
1109
+ let t = 0;
1110
+ for (let n of e) {
1111
+ let e = Number.isFinite(n) ? Math.max(0, Math.min(1, n / 2)) : 0;
1112
+ t += e * e;
1113
+ }
1114
+ return Math.sqrt(t / e.length);
1115
+ }
1116
+ function F(e) {
1117
+ return e.status.value === "error" || e.error ? {
1118
+ state: "error",
1119
+ inputVolume: 0,
1120
+ outputVolume: 0,
1121
+ error: e.error ?? Error(e.status.reason ?? "Hume session failed")
1122
+ } : e.status.value === "connected" ? {
1123
+ state: e.isPlaying && !e.isAudioMuted ? "speaking" : e.isThinking ? "thinking" : "listening",
1124
+ inputVolume: e.isMuted ? 0 : P(e.micFft),
1125
+ outputVolume: e.isPlaying && !e.isAudioMuted ? P(e.playerFft) : 0
1126
+ } : {
1127
+ state: e.status.value === "connecting" ? "connecting" : "idle",
1128
+ inputVolume: 0,
1129
+ outputVolume: 0
1130
+ };
1131
+ }
1132
+ function I(e = {}) {
1133
+ let t = /* @__PURE__ */ new Set(), n = {
1134
+ state: "idle",
1135
+ inputVolume: 0,
1136
+ outputVolume: 0
1137
+ }, r = 0, i, a, o;
1138
+ function s(e) {
1139
+ n = e, t.forEach((t) => t(e));
1140
+ }
1141
+ function c() {
1142
+ i?.abort(), i = void 0;
1143
+ let e = ++r, t = {
1144
+ status: { value: "connecting" },
1145
+ isPlaying: !1
1146
+ }, a = !1, o = !1;
1147
+ s(F(t));
1148
+ let c = () => e === r, l = () => {
1149
+ c() && s(F({
1150
+ ...t,
1151
+ isPlaying: t.isPlaying && !o,
1152
+ isThinking: t.isThinking ?? a
1153
+ }));
1154
+ };
1155
+ return {
1156
+ observe(e) {
1157
+ c() && (n.state === "error" && e.status.value === "connected" || (e.isPlaying || (o = !1), e.isPlaying && !o && (a = !1), t = e, l(), e.status.value === "disconnected" && (r += 1)));
1158
+ },
1159
+ onMessage(e) {
1160
+ !c() || t.status.value !== "connected" || n.state === "error" || (e.type === "user_interruption" ? (o = !0, a = !1) : e.type === "user_message" && e.interim !== !0 || e.type === "tool_call" ? a = !0 : e.type === "assistant_end" && (a = !1), l());
1161
+ },
1162
+ onInterruption() {
1163
+ !c() || t.status.value !== "connected" || (o = !0, a = !1, l());
1164
+ },
1165
+ onError(e) {
1166
+ c() && (t = {
1167
+ ...t,
1168
+ status: { value: "error" },
1169
+ error: e
1170
+ }, l());
1171
+ },
1172
+ close() {
1173
+ c() && (r += 1, i?.abort(), i = void 0, n.state !== "error" && s({
1174
+ state: "idle",
1175
+ inputVolume: 0,
1176
+ outputVolume: 0
1177
+ }));
1178
+ }
1179
+ };
1180
+ }
1181
+ function l() {
1182
+ if (o) return o;
1183
+ r += 1, i?.abort(), i = void 0, a = void 0, s({
1184
+ state: "idle",
1185
+ inputVolume: 0,
1186
+ outputVolume: 0
1187
+ });
1188
+ let t = (async () => {
1189
+ try {
1190
+ await e.disconnect?.();
1191
+ } catch (e) {
1192
+ throw s({
1193
+ state: "error",
1194
+ inputVolume: 0,
1195
+ outputVolume: 0,
1196
+ error: e
1197
+ }), e;
1198
+ }
1199
+ })();
1200
+ return o = t, t.finally(() => {
1201
+ o === t && (o = void 0);
1202
+ }).catch(() => void 0), t;
1203
+ }
1204
+ return {
1205
+ subscribe(e) {
1206
+ return t.add(e), e(n), () => {
1207
+ t.delete(e);
1208
+ };
1209
+ },
1210
+ createSession: c,
1211
+ ...e.connect ? { start() {
1212
+ if (a) return a;
1213
+ if (n.state !== "idle" && n.state !== "error") return Promise.resolve();
1214
+ let t = r, s = (async () => {
1215
+ if (o && await o, t !== r) return;
1216
+ let n = c(), a = new AbortController(), s = r;
1217
+ i = a;
1218
+ try {
1219
+ await e.connect?.(n, a.signal);
1220
+ } catch (t) {
1221
+ if (s !== r || a.signal.aborted) return;
1222
+ n.onError(t);
1223
+ try {
1224
+ await e.disconnect?.();
1225
+ } catch {}
1226
+ throw t;
1227
+ }
1228
+ })();
1229
+ return a = s, s.finally(() => {
1230
+ a === s && (a = void 0);
1231
+ }).catch(() => void 0), s;
1232
+ } } : {},
1233
+ stop: l
1234
+ };
1235
+ }
1236
+ //#endregion
1237
+ //#region src/adapters/deepgram/index.ts
1238
+ function L(e) {
1239
+ let t = /* @__PURE__ */ new Set(), n = i(a, e.inputVolumeCalibration), r = i(a, e.outputVolumeCalibration), o = {
1240
+ state: "idle",
1241
+ inputVolume: 0,
1242
+ outputVolume: 0
1243
+ }, s, c;
1244
+ function l(e, n = 0, r = 0, i) {
1245
+ o = {
1246
+ state: e,
1247
+ inputVolume: n,
1248
+ outputVolume: r,
1249
+ ...i === void 0 ? {} : { error: i }
1250
+ }, t.forEach((e) => e(o));
1251
+ }
1252
+ function u() {
1253
+ n.reset(), r.reset();
1254
+ }
1255
+ function d(e) {
1256
+ e.disposed || (e.disposed = !0, s === e && (s = void 0), e.poll !== void 0 && clearInterval(e.poll), e.timeout !== void 0 && clearTimeout(e.timeout), e.removers.forEach((e) => e()), e.microphone.stop(), e.player.interrupt(), e.player.dispose(), e.session.disconnect(), u());
1257
+ }
1258
+ function f(e, t) {
1259
+ e.disposed || (e.reject?.(t), d(e), l("error", 0, 0, t));
1260
+ }
1261
+ function p(e) {
1262
+ if (!(e.disposed || !e.ready || !e.capturing)) try {
1263
+ let t = e.player.muted ? 0 : e.player.getOutputVolume(), i = e.player.muted ? 0 : e.player.getRemainingPlaybackTime();
1264
+ t > .001 && !e.ignoreAudio && (e.heardAudio = !0);
1265
+ let a = e.heardAudio && i > 0 && !e.ignoreAudio;
1266
+ !a && i <= 0 && (e.heardAudio = !1), l(a ? "speaking" : e.generating ? "thinking" : "listening", n.sample(e.microphone.muted ? 0 : e.microphone.getInputVolume()).normalized, a ? r.sample(t).normalized : 0);
1267
+ } catch (t) {
1268
+ f(e, t);
1269
+ }
1270
+ }
1271
+ function m(e) {
1272
+ e.disposed || !e.ready || !e.capturing || (e.timeout !== void 0 && clearTimeout(e.timeout), e.resolve?.(), e.resolve = void 0, e.reject = void 0, p(e));
1273
+ }
1274
+ return {
1275
+ subscribe(e) {
1276
+ return t.add(e), e(o), () => {
1277
+ if (t.delete(e), !t.size) {
1278
+ let e = s;
1279
+ e && (e.reject?.(new DOMException("Deepgram start cancelled.", "AbortError")), d(e)), l("idle");
1280
+ }
1281
+ };
1282
+ },
1283
+ start() {
1284
+ if (c && s) return c;
1285
+ if (s) return Promise.resolve();
1286
+ u(), l("connecting");
1287
+ let t;
1288
+ try {
1289
+ t = {
1290
+ ...e.createResources(),
1291
+ disposed: !1,
1292
+ ready: !1,
1293
+ capturing: !1,
1294
+ generating: !1,
1295
+ heardAudio: !1,
1296
+ ignoreAudio: !1,
1297
+ removers: []
1298
+ };
1299
+ } catch (e) {
1300
+ return l("error", 0, 0, e), Promise.reject(e);
1301
+ }
1302
+ s = t;
1303
+ let n = new Promise((e, n) => {
1304
+ t.resolve = e, t.reject = n;
1305
+ }), i = (e, n) => {
1306
+ let r = (e) => {
1307
+ t.disposed || n(e);
1308
+ };
1309
+ t.session.on(e, r), t.removers.push(() => t.session.off(e, r));
1310
+ };
1311
+ i("connecting", () => l("connecting")), i("connected", () => {}), i("reconnecting", () => {
1312
+ t.ready = !1, t.generating = !1, t.heardAudio = !1, t.ignoreAudio = !0, t.player.interrupt(), u(), l("connecting");
1313
+ }), i("settings-applied", () => {
1314
+ t.ready = !0, t.ignoreAudio = !1, m(t);
1315
+ }), i("user-started-speaking", () => {
1316
+ t.player.interrupt(), t.heardAudio = !1, t.generating = !1, t.ignoreAudio = !0, r.reset(), p(t);
1317
+ }), i("conversation-text", (e) => {
1318
+ !t.ready || !e || typeof e != "object" || "role" in e && e.role === "user" && (t.ignoreAudio = !1);
1319
+ }), i("agent-thinking", () => {
1320
+ t.ready && (t.generating = !0, t.ignoreAudio = !1, p(t));
1321
+ }), i("agent-started-speaking", () => {
1322
+ t.ready && (t.generating = !0, t.ignoreAudio = !1, p(t));
1323
+ }), i("agent-audio-done", () => {
1324
+ t.generating = !1, p(t);
1325
+ }), i("error", (e) => f(t, e ?? /* @__PURE__ */ Error("Deepgram agent error."))), i("sdk-error", (e) => {
1326
+ t.player.interrupt(), t.heardAudio = !1, u(), l("error", 0, 0, e ?? /* @__PURE__ */ Error("Deepgram transport error."));
1327
+ }), i("disconnected", (e) => f(t, /* @__PURE__ */ Error(`Deepgram disconnected: ${String(e ?? "connection closed")}`)));
1328
+ let a = (e) => {
1329
+ if (!(t.disposed || !t.ready || t.ignoreAudio)) try {
1330
+ t.player.queue(e), p(t);
1331
+ } catch (e) {
1332
+ f(t, e);
1333
+ }
1334
+ };
1335
+ t.session.on("audio", a), t.removers.push(() => t.session.off("audio", a));
1336
+ let o = (e) => f(t, e);
1337
+ t.microphone.on("error", o), t.removers.push(() => t.microphone.off("error", o)), t.poll = setInterval(() => p(t), 1e3 / 30), t.timeout = setTimeout(() => f(t, /* @__PURE__ */ Error("Deepgram microphone or agent readiness timed out.")), e.startTimeoutMs ?? 3e4);
1338
+ try {
1339
+ t.microphone.start().then(() => {
1340
+ if (t.disposed) {
1341
+ t.microphone.stop();
1342
+ return;
1343
+ }
1344
+ t.capturing = !0, m(t);
1345
+ }, (e) => f(t, e)), t.session.connect().catch((e) => f(t, e));
1346
+ } catch (e) {
1347
+ f(t, e);
1348
+ }
1349
+ let d = n.finally(() => {
1350
+ c === d && (c = void 0);
1351
+ });
1352
+ return c = d, d;
1353
+ },
1354
+ stop() {
1355
+ c = void 0;
1356
+ let e = s;
1357
+ e && (e.reject?.(new DOMException("Deepgram start cancelled.", "AbortError")), d(e)), u(), l("idle");
1358
+ }
1359
+ };
1360
+ }
1361
+ function R(e) {
1362
+ let t = /* @__PURE__ */ new Set(), n, r, i, a = !1, o = 0, s = !1, c = (e) => Number.isFinite(e) ? Math.max(0, Math.min(1, e)) : 0;
1363
+ function l() {
1364
+ try {
1365
+ let n = e.getSnapshot(), r = n.state === "connected" && n.mode === "speaking" && !n.outputMuted ? c(n.getOutputVolume()) : 0;
1366
+ (n.mode !== "speaking" || n.outputMuted || n.state !== "connected") && (s = !1), r > .001 && (s = !0);
1367
+ let o = i !== void 0 || n.error !== void 0 ? "error" : a ? "idle" : n.state === "connecting" || n.state === "reconnecting" ? "connecting" : n.state === "connected" ? n.mode === "speaking" && (n.outputMuted || !s) ? n.outputMuted ? "listening" : "thinking" : n.mode === "idle" ? "listening" : n.mode : "idle", l = {
1368
+ state: o,
1369
+ inputVolume: o !== "idle" && o !== "connecting" && o !== "error" && n.micActive && !n.micMuted ? c(n.getInputVolume()) : 0,
1370
+ outputVolume: o === "speaking" ? r : 0,
1371
+ ...o === "error" ? { error: i ?? n.error } : {}
1372
+ };
1373
+ t.forEach((e) => e(l));
1374
+ } catch (e) {
1375
+ i = e, t.forEach((t) => t({
1376
+ state: "error",
1377
+ inputVolume: 0,
1378
+ outputVolume: 0,
1379
+ error: e
1380
+ }));
1381
+ }
1382
+ }
1383
+ return {
1384
+ subscribe(e) {
1385
+ return t.add(e), n === void 0 && (n = setInterval(l, 1e3 / 30)), l(), () => {
1386
+ t.delete(e), !t.size && n !== void 0 && (clearInterval(n), n = void 0);
1387
+ };
1388
+ },
1389
+ start() {
1390
+ if (r) return r;
1391
+ let t = ++o;
1392
+ s = !1, i = void 0, a = !1;
1393
+ let n;
1394
+ try {
1395
+ n = e.start();
1396
+ } catch (e) {
1397
+ n = Promise.reject(e);
1398
+ }
1399
+ let c = n.catch((n) => {
1400
+ throw o === t && (i = n, e.stop(), l()), n;
1401
+ }).finally(() => {
1402
+ r === c && (r = void 0);
1403
+ });
1404
+ return r = c, c;
1405
+ },
1406
+ stop() {
1407
+ o++, s = !1, r = void 0, a = !0, i = void 0, e.stop(), l();
1408
+ }
1409
+ };
1410
+ }
1411
+ //#endregion
1412
+ //#region src/adapters/agora/index.ts
1413
+ function z(e) {
1414
+ let t = /* @__PURE__ */ new Set(), n = i(a, e.inputVolumeCalibration), r = i(a, e.outputVolumeCalibration), o = {
1415
+ state: "idle",
1416
+ inputVolume: 0,
1417
+ outputVolume: 0
1418
+ }, s, c;
1419
+ function l(e, n = 0, r = 0, i) {
1420
+ o = {
1421
+ state: e,
1422
+ inputVolume: n,
1423
+ outputVolume: r,
1424
+ ...i === void 0 ? {} : { error: i }
1425
+ }, t.forEach((e) => e(o));
1426
+ }
1427
+ function u(e) {
1428
+ e.thinking = !1, e.producing = !1, e.lastAudibleAt = -Infinity, n.reset(), r.reset();
1429
+ }
1430
+ function d(e) {
1431
+ return e.closed ? e.closed : (e.disposed = !0, e.abort.abort(), s === e && (s = void 0), e.poll !== void 0 && clearInterval(e.poll), e.timeout !== void 0 && clearTimeout(e.timeout), e.removers.forEach((e) => e()), u(e), e.closed = Promise.resolve().then(() => e.session?.close()).then(() => void 0), e.closed);
1432
+ }
1433
+ function f(e, t) {
1434
+ e.disposed || (e.failure = t, l("error", 0, 0, t), d(e).catch(() => void 0));
1435
+ }
1436
+ function p(e) {
1437
+ if (!(e.disposed || !e.session)) {
1438
+ if (e.session.rtc.connectionState !== "CONNECTED") {
1439
+ (e.session.rtc.connectionState === "CONNECTING" || e.session.rtc.connectionState === "RECONNECTING") && (u(e), l("connecting"));
1440
+ return;
1441
+ }
1442
+ try {
1443
+ let t = e.session.getMicrophoneTrack(), i = e.session.getAgentAudioTrack(), a = !e.interrupted && i?.isPlaying ? i.getVolumeLevel() : 0, o = performance.now();
1444
+ a > .001 && (e.lastAudibleAt = o);
1445
+ let s = !e.interrupted && !!i?.isPlaying && o - e.lastAudibleAt < 180;
1446
+ l(s ? "speaking" : e.thinking || e.producing ? "thinking" : "listening", n.sample(t?.enabled === !1 ? 0 : t?.getVolumeLevel() ?? 0).normalized, s ? r.sample(a).normalized : 0);
1447
+ } catch (t) {
1448
+ f(e, t);
1449
+ }
1450
+ }
1451
+ }
1452
+ function m(e, t) {
1453
+ let n = (n) => !e.disposed && n === t.agentUserId && t.rtc.connectionState === "CONNECTED", r = (t) => t.turnID < e.lastTurn || t.timestamp < e.lastTimestamp ? !1 : (e.lastTurn = t.turnID, e.lastTimestamp = t.timestamp, !0), i = (t, i) => {
1454
+ !n(t) || !r(i) || (e.thinking = i.state === "thinking", e.producing = i.state === "speaking", (e.thinking || e.producing) && (e.interrupted = !1), p(e));
1455
+ }, a = (t, r) => {
1456
+ n(t) && (e.thinking = r, r && (e.interrupted = !1), p(e));
1457
+ }, o = (t, r) => {
1458
+ n(t) && (e.producing = r, r && (e.interrupted = !1), p(e));
1459
+ }, s = (t, i) => {
1460
+ !n(t) || !r(i) || (u(e), e.interrupted = !0, p(e));
1461
+ }, c = (t, r) => {
1462
+ n(t) && f(e, r);
1463
+ }, d = (t) => {
1464
+ e.disposed || (t === "DISCONNECTED" ? f(e, /* @__PURE__ */ Error("Agora RTC disconnected. Start a new application session to retry.")) : t === "CONNECTING" || t === "RECONNECTING" ? (u(e), e.interrupted = !0, l("connecting")) : t === "CONNECTED" && (e.interrupted = !1, p(e)));
1465
+ };
1466
+ t.toolkit.on("agent-state-changed", i), t.toolkit.on("agent-thinking-changed", a), t.toolkit.on("agent-speaking-changed", o), t.toolkit.on("agent-interrupted", s), t.toolkit.on("agent-error", c), t.toolkit.on("message-error", c), t.rtc.on("connection-state-change", d), e.removers.push(() => t.toolkit.off("agent-state-changed", i), () => t.toolkit.off("agent-thinking-changed", a), () => t.toolkit.off("agent-speaking-changed", o), () => t.toolkit.off("agent-interrupted", s), () => t.toolkit.off("agent-error", c), () => t.toolkit.off("message-error", c), () => t.rtc.off("connection-state-change", d));
1467
+ }
1468
+ return {
1469
+ subscribe(e) {
1470
+ return t.add(e), e(o), () => {
1471
+ t.delete(e), t.size || (s && d(s).catch(() => void 0), l("idle"));
1472
+ };
1473
+ },
1474
+ start() {
1475
+ if (c && s) return c;
1476
+ if (s) return Promise.resolve();
1477
+ let t = {
1478
+ abort: new AbortController(),
1479
+ disposed: !1,
1480
+ thinking: !1,
1481
+ producing: !1,
1482
+ interrupted: !1,
1483
+ lastAudibleAt: -Infinity,
1484
+ lastTimestamp: -Infinity,
1485
+ lastTurn: -Infinity,
1486
+ removers: []
1487
+ };
1488
+ s = t, l("connecting");
1489
+ let n = new Promise((e, n) => {
1490
+ t.abort.signal.addEventListener("abort", () => n(t.failure ?? new DOMException("Agora start cancelled.", "AbortError")), { once: !0 });
1491
+ });
1492
+ t.timeout = setTimeout(() => f(t, /* @__PURE__ */ Error("Agora application session timed out.")), e.startTimeoutMs ?? 3e4);
1493
+ let r;
1494
+ try {
1495
+ r = e.createSession(t.abort.signal);
1496
+ } catch (e) {
1497
+ f(t, e), r = Promise.reject(e);
1498
+ }
1499
+ let i = r.then(async (e) => {
1500
+ if (t.disposed) throw await e.close(), new DOMException("Agora start cancelled.", "AbortError");
1501
+ if (t.session = e, e.rtc.connectionState !== "CONNECTED") throw Error("createSession must return a connected Agora RTC session.");
1502
+ m(t, e), t.timeout !== void 0 && clearTimeout(t.timeout), t.poll = setInterval(() => p(t), 1e3 / 30), p(t);
1503
+ }), a = Promise.race([i, n]).catch((e) => {
1504
+ throw f(t, e), e;
1505
+ }).finally(() => {
1506
+ c === a && (c = void 0);
1507
+ });
1508
+ return c = a, a;
1509
+ },
1510
+ async stop() {
1511
+ c = void 0;
1512
+ let e = s;
1513
+ if (e) try {
1514
+ await d(e);
1515
+ } catch (e) {
1516
+ throw l("error", 0, 0, e), e;
1517
+ }
1518
+ s || l("idle");
1519
+ },
1520
+ async interrupt() {
1521
+ let e = s;
1522
+ if (!(!e?.session || e.disposed)) try {
1523
+ await e.session.toolkit.interrupt(e.session.agentUserId);
1524
+ } catch (t) {
1525
+ throw f(e, t), t;
1526
+ }
1527
+ }
1528
+ };
1529
+ }
1530
+ //#endregion
1531
+ //#region src/adapters/azure-voice-live/browser-audio.ts
1532
+ var B = "\nclass OrbPcmCapture extends AudioWorkletProcessor {\n constructor() { super(); this.samples = new Float32Array(2048); this.offset = 0; }\n process(inputs) {\n const channels = inputs[0];\n if (!channels || !channels.length) return true;\n for (let i = 0; i < channels[0].length; i++) {\n let mono = 0;\n for (const channel of channels) mono += channel[i] / channels.length;\n this.samples[this.offset++] = mono;\n if (this.offset === this.samples.length) {\n this.port.postMessage(this.samples, [this.samples.buffer]);\n this.samples = new Float32Array(2048); this.offset = 0;\n }\n }\n return true;\n }\n}\nregisterProcessor('orb-pcm-capture', OrbPcmCapture);\n";
1533
+ async function V(e) {
1534
+ if (!e.audioWorklet) throw Error("AudioWorklet requires HTTPS or localhost.");
1535
+ let t = URL.createObjectURL(new Blob([B], { type: "text/javascript" }));
1536
+ try {
1537
+ return await e.audioWorklet.addModule(t), new AudioWorkletNode(e, "orb-pcm-capture");
1538
+ } finally {
1539
+ URL.revokeObjectURL(t);
1540
+ }
1541
+ }
1542
+ function H(e) {
1543
+ if (e.length === 0) return 0;
1544
+ let t = 0;
1545
+ for (let n of e) t += n * n;
1546
+ return Math.sqrt(t / e.length);
1547
+ }
1548
+ function U(e, t) {
1549
+ let n = e / t, r = 0, i = 0;
1550
+ return (e) => {
1551
+ let t = [];
1552
+ for (let a of e) {
1553
+ let e = 1;
1554
+ for (; e > 1e-8;) {
1555
+ let o = Math.min(e, n - i);
1556
+ r += a * o, i += o, e -= o, i >= n - 1e-8 && (t.push(Math.max(-1, Math.min(1, r / n))), r = 0, i = 0);
1557
+ }
1558
+ }
1559
+ let a = new Uint8Array(t.length * 2), o = new DataView(a.buffer);
1560
+ return t.forEach((e, t) => {
1561
+ o.setInt16(t * 2, e < 0 ? e * 32768 : e * 32767, !0);
1562
+ }), a;
1563
+ };
1564
+ }
1565
+ function W(e) {
1566
+ if (e.byteLength % 2 != 0) throw Error("PCM16 audio must contain whole samples.");
1567
+ let t = new DataView(e.buffer, e.byteOffset, e.byteLength), n = new Float32Array(e.byteLength / 2);
1568
+ for (let e = 0; e < n.length; e++) n[e] = t.getInt16(e * 2, !0) / 32768;
1569
+ return n;
1570
+ }
1571
+ function G(e) {
1572
+ let t = "";
1573
+ for (let n of e) t += String.fromCharCode(n);
1574
+ return btoa(t);
1575
+ }
1576
+ function K(e) {
1577
+ let t = atob(e);
1578
+ return Uint8Array.from(t, (e) => e.charCodeAt(0));
1579
+ }
1580
+ function q(e) {
1581
+ let t = (e.createAudioContext ?? (() => new AudioContext()))(), n = t.state === "suspended" ? t.resume() : Promise.resolve(), r = !1, i = !1, a, o, s, c, l, u, d = 0, f = /* @__PURE__ */ new Set(), p = U(t.sampleRate, e.inputSampleRate), m = () => {
1582
+ r || e.onError(/* @__PURE__ */ Error("The microphone track ended."));
1583
+ }, h = () => {
1584
+ !i || r || t.state === "running" || (_(), e.onError(/* @__PURE__ */ Error(`Browser audio is ${t.state}. Start a new session to resume.`)));
1585
+ };
1586
+ t.addEventListener("statechange", h);
1587
+ function g() {
1588
+ if (r) throw new DOMException("Audio startup canceled.", "AbortError");
1589
+ }
1590
+ function _() {
1591
+ f.forEach((e) => {
1592
+ e.onended = null;
1593
+ try {
1594
+ e.stop();
1595
+ } catch {}
1596
+ e.disconnect();
1597
+ }), f.clear(), d = t.currentTime, e.onOutputVolume(0), e.onPlayback(!1);
1598
+ }
1599
+ return {
1600
+ clear: _,
1601
+ get hasOutput() {
1602
+ return t.state === "running" && f.size > 0;
1603
+ },
1604
+ async open() {
1605
+ await n, g();
1606
+ let d = await (e.getUserMedia ?? ((e) => navigator.mediaDevices.getUserMedia(e)))(e.mediaStreamConstraints ?? { audio: {
1607
+ channelCount: 1,
1608
+ echoCancellation: !0,
1609
+ noiseSuppression: !0
1610
+ } });
1611
+ if (r && (d.getTracks().forEach((e) => e.stop()), g()), a = d, t.state !== "running" || (a.getTracks().forEach((e) => e.addEventListener("ended", m)), o = await (e.createCaptureNode ?? V)(t), r && (o.port.close(), o.disconnect(), g()), t.state !== "running")) throw Error(`Browser audio is ${t.state}. Start a new session to resume.`);
1612
+ s = t.createMediaStreamSource(a), c = t.createGain(), c.gain.value = 0, s.connect(o), o.connect(c), c.connect(t.destination), o.port.onmessage = (t) => {
1613
+ if (!r) try {
1614
+ let n = t.data;
1615
+ if (!(n instanceof Float32Array)) throw Error("Invalid microphone PCM frame.");
1616
+ let r = p(n);
1617
+ r.byteLength && e.onInput(r, H(n));
1618
+ } catch (t) {
1619
+ e.onError(t);
1620
+ }
1621
+ }, o.onprocessorerror = () => {
1622
+ r || e.onError(/* @__PURE__ */ Error("The microphone AudioWorklet failed."));
1623
+ }, l = t.createAnalyser(), l.fftSize = 512, l.connect(t.destination);
1624
+ let h = new Float32Array(l.fftSize);
1625
+ i = !0, u = setInterval(() => {
1626
+ if (!(r || !l)) {
1627
+ if (t.state !== "running" || f.size === 0) {
1628
+ e.onOutputVolume(0);
1629
+ return;
1630
+ }
1631
+ l.getFloatTimeDomainData(h), e.onOutputVolume(H(h));
1632
+ }
1633
+ }, 33);
1634
+ },
1635
+ play(n) {
1636
+ if (r || !l || n.byteLength === 0) return;
1637
+ if (t.state !== "running") throw Error(`Browser audio is ${t.state}. Start a new session to resume.`);
1638
+ if (d - t.currentTime > 5) throw Error("Audio playback fell more than five seconds behind.");
1639
+ let i = W(n), a = t.createBuffer(1, i.length, e.outputSampleRate);
1640
+ a.getChannelData(0).set(i);
1641
+ let o = t.createBufferSource();
1642
+ o.buffer = a, o.connect(l);
1643
+ let s = Math.max(t.currentTime, d);
1644
+ d = s + a.duration, f.add(o), o.onended = () => {
1645
+ f.delete(o) && (o.disconnect(), !r && f.size === 0 && (e.onOutputVolume(0), e.onPlayback(!1)));
1646
+ }, o.start(s), e.onPlayback(!0);
1647
+ },
1648
+ async close() {
1649
+ r || (r = !0, t.removeEventListener("statechange", h), _(), u && clearInterval(u), o && (o.port.onmessage = null, o.onprocessorerror = null, o.port.close(), o.disconnect()), s?.disconnect(), c?.disconnect(), l?.disconnect(), a?.getTracks().forEach((e) => {
1650
+ e.removeEventListener("ended", m), e.stop();
1651
+ }), t.state !== "closed" && await t.close());
1652
+ }
1653
+ };
1654
+ }
1655
+ //#endregion
1656
+ //#region src/adapters/azure-voice-live/index.ts
1657
+ var J = {
1658
+ amplitude: {
1659
+ silenceFloor: .003,
1660
+ speechReference: .1,
1661
+ speechPeak: .3
1662
+ },
1663
+ envelope: {
1664
+ riseTimeMs: 100,
1665
+ fallTimeMs: 400
1666
+ }
1667
+ };
1668
+ function Y(e) {
1669
+ let t = /* @__PURE__ */ new Set(), n = {
1670
+ state: "idle",
1671
+ inputVolume: 0,
1672
+ outputVolume: 0
1673
+ }, r, a, o, s = i(J, e.inputVolumeCalibration), c = i(J, e.outputVolumeCalibration);
1674
+ function l(e) {
1675
+ n = e, t.forEach((t) => t(e));
1676
+ }
1677
+ function u(e, t) {
1678
+ let r = e === "idle" || e === "connecting" || e === "error";
1679
+ r && (s.reset(), c.reset()), l({
1680
+ state: e,
1681
+ inputVolume: r ? 0 : n.inputVolume,
1682
+ outputVolume: r ? 0 : n.outputVolume,
1683
+ ...t === void 0 ? {} : { error: t }
1684
+ });
1685
+ }
1686
+ async function d(e, t) {
1687
+ if (e.disposed) return;
1688
+ e.disposed = !0, e.abort.abort(t ?? new DOMException("Voice session canceled.", "AbortError")), r === e && (r = void 0);
1689
+ let n = (await Promise.allSettled([
1690
+ e.audio?.close(),
1691
+ e.subscription?.close(),
1692
+ e.sdk?.dispose()
1693
+ ])).find((e) => e.status === "rejected");
1694
+ if (n?.status === "rejected") throw n.reason;
1695
+ }
1696
+ function f(e) {
1697
+ return r === e && !e.disposed && !e.abort.signal.aborted;
1698
+ }
1699
+ function p(e) {
1700
+ if (!f(e)) throw new DOMException("Voice session canceled.", "AbortError");
1701
+ }
1702
+ function m(e, t) {
1703
+ f(e) && (u("error", t), d(e, t).catch(() => void 0));
1704
+ }
1705
+ function h(e) {
1706
+ e.audio?.hasOutput || (c.reset(), l({
1707
+ ...n,
1708
+ state: e.userSpeaking || e.responseComplete ? "listening" : "thinking",
1709
+ outputVolume: 0
1710
+ }));
1711
+ }
1712
+ function g(t, r) {
1713
+ if (f(t)) {
1714
+ if (r.type === "input_audio_buffer.speech_started") t.userSpeaking = !0, t.responseId && t.interruptedResponses.add(t.responseId), t.audio?.clear(), c.reset(), l({
1715
+ ...n,
1716
+ state: "listening",
1717
+ outputVolume: 0
1718
+ });
1719
+ else if (r.type === "input_audio_buffer.speech_stopped") t.userSpeaking = !1, u("thinking");
1720
+ else if (r.type === "response.created") t.responseId = r.response?.id, t.responseComplete = !1, !t.userSpeaking && !t.audio?.hasOutput && u("thinking");
1721
+ else if (r.type === "response.audio.delta") {
1722
+ if (!(r.delta instanceof Uint8Array)) throw Error("Expected Azure SDK PCM bytes.");
1723
+ !t.userSpeaking && (!r.responseId || !t.interruptedResponses.has(r.responseId)) && t.audio?.play(r.delta);
1724
+ } else if (r.type === "response.done") if (r.response?.id && t.interruptedResponses.has(r.response.id)) t.interruptedResponses.delete(r.response.id);
1725
+ else {
1726
+ if (t.responseComplete = !0, r.response?.status === "failed") throw Error("Azure Voice Live response failed.");
1727
+ h(t);
1728
+ }
1729
+ else if (r.type === "error") throw Error(r.error?.message ?? "Azure Voice Live server error.");
1730
+ e.onEvent?.(r);
1731
+ }
1732
+ }
1733
+ async function _(t) {
1734
+ t.audio = q({
1735
+ ...e,
1736
+ inputSampleRate: 24e3,
1737
+ outputSampleRate: 24e3,
1738
+ onInput(e, r) {
1739
+ if (f(t) && (l({
1740
+ ...n,
1741
+ inputVolume: s.sample(r).normalized
1742
+ }), !(!t.ready || !t.sdk))) {
1743
+ if (t.pendingAudio >= 16) {
1744
+ m(t, /* @__PURE__ */ Error("Azure microphone transport is falling behind."));
1745
+ return;
1746
+ }
1747
+ t.pendingAudio += 1, t.sdk.sendAudio(e).catch((e) => m(t, e)).finally(() => --t.pendingAudio);
1748
+ }
1749
+ },
1750
+ onOutputVolume(e) {
1751
+ f(t) && l({
1752
+ ...n,
1753
+ outputVolume: c.sample(e).normalized
1754
+ });
1755
+ },
1756
+ onPlayback(e) {
1757
+ f(t) && (e && !t.userSpeaking && u("speaking"), e || h(t));
1758
+ },
1759
+ onError(e) {
1760
+ m(t, e);
1761
+ }
1762
+ }), await t.audio.open(), p(t);
1763
+ let r = await e.createSession(t.abort.signal);
1764
+ f(t) || (await r.dispose(), p(t)), t.sdk = r, t.subscription = r.subscribe({
1765
+ onServerEvent: async (e) => {
1766
+ try {
1767
+ g(t, e);
1768
+ } catch (e) {
1769
+ m(t, e);
1770
+ }
1771
+ },
1772
+ onError: async ({ error: e }) => m(t, e),
1773
+ onDisconnected: async ({ code: e, reason: n }) => {
1774
+ f(t) && (!t.ready || e !== 1e3 ? m(t, /* @__PURE__ */ Error(`Azure session disconnected (${e}): ${n}`)) : (u("idle"), d(t).catch(() => void 0)));
1775
+ }
1776
+ }), await r.connect({
1777
+ abortSignal: t.abort.signal,
1778
+ timeoutInMs: e.startTimeoutMs ?? 3e4
1779
+ }), p(t), await r.updateSession({ turnDetection: {
1780
+ type: "server_vad",
1781
+ threshold: .5,
1782
+ prefixPaddingInMs: 300,
1783
+ silenceDurationInMs: 500
1784
+ } }), await e.configureSession?.(r, t.abort.signal), p(t), await r.updateSession({
1785
+ inputAudioFormat: "pcm16",
1786
+ inputAudioSamplingRate: 24e3,
1787
+ outputAudioFormat: "pcm16"
1788
+ }), p(t), t.ready = !0, u("listening");
1789
+ }
1790
+ return {
1791
+ subscribe(e) {
1792
+ return t.add(e), e(n), () => t.delete(e);
1793
+ },
1794
+ start() {
1795
+ if (a) return a;
1796
+ if (r?.ready) return Promise.resolve();
1797
+ if (o) return o.then(() => this.start());
1798
+ let t = {
1799
+ abort: new AbortController(),
1800
+ disposed: !1,
1801
+ ready: !1,
1802
+ userSpeaking: !1,
1803
+ responseComplete: !1,
1804
+ interruptedResponses: /* @__PURE__ */ new Set(),
1805
+ pendingAudio: 0
1806
+ };
1807
+ r = t, u("connecting");
1808
+ let n, i = new Promise((r, i) => {
1809
+ t.abort.signal.addEventListener("abort", () => i(t.abort.signal.reason), { once: !0 }), n = setTimeout(() => {
1810
+ let e = /* @__PURE__ */ Error("Azure Voice Live startup timed out.");
1811
+ m(t, e), i(e);
1812
+ }, e.startTimeoutMs ?? 3e4);
1813
+ });
1814
+ return a = Promise.race([_(t), i]).catch(async (e) => {
1815
+ throw f(t) && m(t, e), await d(t).catch(() => void 0), e;
1816
+ }).finally(() => {
1817
+ clearTimeout(n), a = void 0;
1818
+ }), a;
1819
+ },
1820
+ stop() {
1821
+ if (o) return o;
1822
+ let e = r;
1823
+ return o = (e ? d(e) : Promise.resolve()).then(() => u("idle")).catch((e) => {
1824
+ throw u("error", e), e;
1825
+ }).finally(() => o = void 0), o;
1826
+ }
1827
+ };
1828
+ }
1829
+ //#endregion
1830
+ //#region src/adapters/cartesia/index.ts
1831
+ var X = {
1832
+ amplitude: {
1833
+ silenceFloor: .003,
1834
+ speechReference: .1,
1835
+ speechPeak: .3
1836
+ },
1837
+ envelope: {
1838
+ riseTimeMs: 100,
1839
+ fallTimeMs: 400
1840
+ }
1841
+ };
1842
+ function Z(e) {
1843
+ if (!e.agentId.trim()) throw Error("A Cartesia Managed Agent ID is required.");
1844
+ let t = e.inputFormat ?? "pcm_24000", n = Number(t.slice(4));
1845
+ if (![
1846
+ 16e3,
1847
+ 24e3,
1848
+ 44100
1849
+ ].includes(n)) throw Error("Cartesia adapter requires a supported mono PCM16 format.");
1850
+ let r = /* @__PURE__ */ new Set(), a = {
1851
+ state: "idle",
1852
+ inputVolume: 0,
1853
+ outputVolume: 0
1854
+ }, o, s, c, l, u = i(X, e.inputVolumeCalibration), d = i(X, e.outputVolumeCalibration);
1855
+ function f(e) {
1856
+ a = e, r.forEach((t) => t(e));
1857
+ }
1858
+ function p(e, t) {
1859
+ let n = e === "idle" || e === "connecting" || e === "error";
1860
+ n && (u.reset(), d.reset()), f({
1861
+ state: e,
1862
+ inputVolume: n ? 0 : a.inputVolume,
1863
+ outputVolume: n ? 0 : a.outputVolume,
1864
+ ...t === void 0 ? {} : { error: t }
1865
+ });
1866
+ }
1867
+ function m(e) {
1868
+ return o === e && !e.disposed && !e.abort.signal.aborted;
1869
+ }
1870
+ function h(e) {
1871
+ if (!m(e)) throw new DOMException("Cartesia session canceled.", "AbortError");
1872
+ }
1873
+ async function g(e, t) {
1874
+ if (e.disposed) return;
1875
+ e.disposed = !0;
1876
+ let n = t ?? new DOMException("Cartesia session canceled.", "AbortError");
1877
+ e.abort.abort(n), e.readyReject?.(n), o === e && (o = void 0), e.socket && (e.socket.onopen = null, e.socket.onmessage = null, e.socket.onclose = null, e.socket.onerror = null, e.socket.readyState < 2 && e.socket.close(1e3, "session completed")), await e.audio?.close();
1878
+ }
1879
+ function _(e, t) {
1880
+ m(e) && (p("error", t), e.readyReject?.(t), g(e, t).catch(() => void 0));
1881
+ }
1882
+ function v(e) {
1883
+ e.audio?.hasOutput || (d.reset(), f({
1884
+ ...a,
1885
+ state: e.userSpeaking || e.outputComplete ? "listening" : "thinking",
1886
+ outputVolume: 0
1887
+ }));
1888
+ }
1889
+ function y(e, t) {
1890
+ if (!m(e) || e.socket?.readyState !== 1) throw Error("Cartesia session is not connected.");
1891
+ if (e.socket.bufferedAmount > 128 * 1024) throw Error("Cartesia microphone transport is falling behind.");
1892
+ let n = JSON.stringify(t);
1893
+ if (new TextEncoder().encode(n).byteLength > 32 * 1024) throw Error("Cartesia JSON event exceeds 32 KiB.");
1894
+ e.socket.send(n);
1895
+ }
1896
+ function b(n, r) {
1897
+ if (m(n)) {
1898
+ if (r.type === "session_ready") {
1899
+ if (typeof r.call_id != "string" || typeof r.audio != "object" || r.audio.input_format !== t || r.audio.output_delivery !== (e.outputDelivery ?? "speaking_pace")) throw Error("Cartesia session_ready did not confirm the requested audio format.");
1900
+ if (n.ready) throw Error("Duplicate Cartesia session_ready.");
1901
+ l = n.callId = r.call_id, n.ready = !0, p("listening"), n.readyResolve?.();
1902
+ } else if (r.type === "error") {
1903
+ if (r.fatal !== !1) throw Error(r.message ?? "Cartesia session failed.");
1904
+ e.onRecoverableError?.(r);
1905
+ } else {
1906
+ if (!n.ready) throw Error("Cartesia event arrived before session_ready.");
1907
+ if (r.type === "turn_started") n.outputComplete = !1, r.role === "user" ? (n.userSpeaking = !0, n.audio?.clear(), d.reset(), f({
1908
+ ...a,
1909
+ state: "listening",
1910
+ outputVolume: 0
1911
+ })) : r.role === "assistant" && !n.userSpeaking && !n.audio?.hasOutput && p("thinking");
1912
+ else if (r.type === "turn_ended") r.role === "user" ? (n.userSpeaking = !1, p("thinking")) : r.role === "assistant" && (n.outputComplete = !0, r.interrupted && n.audio?.clear(), v(n));
1913
+ else if (r.type === "audio_output") {
1914
+ if (typeof r.audio != "string") throw Error("Cartesia audio_output needs base64 PCM.");
1915
+ n.userSpeaking || n.audio?.play(K(r.audio));
1916
+ } else r.type === "audio_output_clear" && (n.userSpeaking = !0, n.outputComplete = !1, n.audio?.clear(), d.reset(), f({
1917
+ ...a,
1918
+ state: "listening",
1919
+ outputVolume: 0
1920
+ }));
1921
+ }
1922
+ e.onEvent?.(r);
1923
+ }
1924
+ }
1925
+ async function x(r) {
1926
+ r.audio = q({
1927
+ ...e,
1928
+ inputSampleRate: n,
1929
+ outputSampleRate: n,
1930
+ onInput(e, t) {
1931
+ if (m(r) && (f({
1932
+ ...a,
1933
+ inputVolume: u.sample(t).normalized
1934
+ }), r.ready)) try {
1935
+ y(r, {
1936
+ type: "audio_input",
1937
+ audio: G(e)
1938
+ });
1939
+ } catch (e) {
1940
+ _(r, e);
1941
+ }
1942
+ },
1943
+ onOutputVolume(e) {
1944
+ m(r) && f({
1945
+ ...a,
1946
+ outputVolume: d.sample(e).normalized
1947
+ });
1948
+ },
1949
+ onPlayback(e) {
1950
+ m(r) && (e && !r.userSpeaking && p("speaking"), e || v(r));
1951
+ },
1952
+ onError(e) {
1953
+ _(r, e);
1954
+ }
1955
+ }), await r.audio.open(), h(r);
1956
+ let i = await e.getAccessToken(r.abort.signal);
1957
+ if (h(r), !i.trim()) throw Error("An agent access token is required.");
1958
+ let o = new URL(`wss://api.cartesia.ai/v1/agents/websocket/${encodeURIComponent(e.agentId)}`);
1959
+ o.searchParams.set("cartesia_version", e.apiVersion ?? "2026-08-14"), o.searchParams.set("access_token", i);
1960
+ let s = (e.createWebSocket ?? ((e) => new WebSocket(e)))(o.toString());
1961
+ r.socket = s, await new Promise((n, i) => {
1962
+ r.readyResolve = n, r.readyReject = i, s.onopen = () => {
1963
+ if (m(r)) try {
1964
+ y(r, {
1965
+ type: "session_create",
1966
+ audio: {
1967
+ input_format: t,
1968
+ output_delivery: e.outputDelivery ?? "speaking_pace"
1969
+ }
1970
+ });
1971
+ } catch (e) {
1972
+ _(r, e);
1973
+ }
1974
+ }, s.onmessage = ({ data: e }) => {
1975
+ if (m(r)) try {
1976
+ if (typeof e != "string") throw Error("Cartesia requires JSON text frames.");
1977
+ let t = JSON.parse(e);
1978
+ if (!t || typeof t != "object" || !("type" in t) || typeof t.type != "string") throw Error("Invalid Cartesia event.");
1979
+ b(r, t);
1980
+ } catch (e) {
1981
+ _(r, e);
1982
+ }
1983
+ }, s.onerror = () => _(r, /* @__PURE__ */ Error("Cartesia WebSocket connection failed.")), s.onclose = ({ code: e, reason: t }) => {
1984
+ m(r) && (!r.ready || e !== 1e3 ? _(r, /* @__PURE__ */ Error(`Cartesia session closed (${e}): ${t}`)) : (p("idle"), g(r).catch(() => void 0)));
1985
+ };
1986
+ }), h(r);
1987
+ }
1988
+ return {
1989
+ get callId() {
1990
+ return l;
1991
+ },
1992
+ subscribe(e) {
1993
+ return r.add(e), e(a), () => r.delete(e);
1994
+ },
1995
+ start() {
1996
+ if (s) return s;
1997
+ if (o?.ready) return Promise.resolve();
1998
+ if (c) return c.then(() => this.start());
1999
+ let t = {
2000
+ abort: new AbortController(),
2001
+ disposed: !1,
2002
+ ready: !1,
2003
+ userSpeaking: !1,
2004
+ outputComplete: !1
2005
+ };
2006
+ o = t, l = void 0, p("connecting");
2007
+ let n, r = new Promise((r, i) => {
2008
+ t.abort.signal.addEventListener("abort", () => i(t.abort.signal.reason), { once: !0 }), n = setTimeout(() => {
2009
+ let e = /* @__PURE__ */ Error("Cartesia startup timed out before session_ready.");
2010
+ _(t, e), i(e);
2011
+ }, e.startTimeoutMs ?? 3e4);
2012
+ });
2013
+ return s = Promise.race([x(t), r]).catch(async (e) => {
2014
+ throw m(t) && _(t, e), await g(t).catch(() => void 0), e;
2015
+ }).finally(() => {
2016
+ clearTimeout(n), s = void 0;
2017
+ }), s;
2018
+ },
2019
+ stop() {
2020
+ if (c) return c;
2021
+ let e = o;
2022
+ return c = (e ? g(e) : Promise.resolve()).then(() => p("idle")).catch((e) => {
2023
+ throw p("error", e), e;
2024
+ }).finally(() => c = void 0), c;
2025
+ },
2026
+ sendToolResult(e, t, n = !1) {
2027
+ if (!o?.ready) throw Error("Cartesia session is not ready.");
2028
+ if (new TextEncoder().encode(t).byteLength > 4096) throw Error("Cartesia client tool result exceeds 4096 bytes.");
2029
+ y(o, {
2030
+ type: "client_tool_result",
2031
+ tool_call_id: e,
2032
+ result: t,
2033
+ is_error: n
2034
+ });
2035
+ }
2036
+ };
2037
+ }
2038
+ //#endregion
2039
+ //#region src/adapters/nova-sonic/index.ts
2040
+ var Q = (e) => Number.isFinite(e) ? Math.min(1, Math.max(0, e)) : 0;
2041
+ function $(e = {}) {
2042
+ let t = /* @__PURE__ */ new Set(), n = /* @__PURE__ */ new Map(), r = {
2043
+ state: "idle",
2044
+ inputVolume: 0,
2045
+ outputVolume: 0
2046
+ }, i = null, a = !1, o = !1;
2047
+ function s(e) {
2048
+ r = e, t.forEach((t) => t(e));
2049
+ }
2050
+ function c(e, t) {
2051
+ n.clear(), a = !1, o = !1, s({
2052
+ state: e,
2053
+ inputVolume: 0,
2054
+ outputVolume: 0,
2055
+ ...t === void 0 ? {} : { error: t }
2056
+ });
2057
+ }
2058
+ return {
2059
+ subscribe(e) {
2060
+ return t.add(e), e(r), () => t.delete(e);
2061
+ },
2062
+ beginSession(t) {
2063
+ if (!t) throw Error("Nova Sonic needs an app session ID");
2064
+ e.onInterrupt?.(), i = t, c("connecting");
2065
+ },
2066
+ connected(e) {
2067
+ e !== i || r.state !== "connecting" || s({
2068
+ state: "listening",
2069
+ inputVolume: 0,
2070
+ outputVolume: 0
2071
+ });
2072
+ },
2073
+ handleEvent(t, c) {
2074
+ if (t !== i || r.state === "error") return;
2075
+ let l = c.contentStart;
2076
+ if (l) {
2077
+ n.size >= 128 && n.delete(n.keys().next().value);
2078
+ let e = !1;
2079
+ try {
2080
+ let t = JSON.parse(l.additionalModelFields ?? "{}");
2081
+ e = typeof t == "object" && !!t && "generationStage" in t && t.generationStage === "FINAL";
2082
+ } catch {}
2083
+ n.set(l.contentId, {
2084
+ role: l.role,
2085
+ final: e,
2086
+ text: ""
2087
+ }), l.role === "USER" ? (o = !1, s({
2088
+ ...r,
2089
+ state: "listening"
2090
+ })) : l.role === "ASSISTANT" && !a && s({
2091
+ ...r,
2092
+ state: "thinking"
2093
+ });
2094
+ }
2095
+ let u = c.textOutput;
2096
+ if (u) {
2097
+ let t = n.get(u.contentId);
2098
+ t?.final && (t.role === "USER" || t.role === "ASSISTANT") && (t.text = (t.text + u.content).slice(0, 32768), e.onTranscript?.({
2099
+ contentId: u.contentId,
2100
+ role: t.role,
2101
+ text: t.text,
2102
+ final: !1
2103
+ }));
2104
+ }
2105
+ let d = c.contentEnd;
2106
+ if (d?.stopReason?.toUpperCase() === "INTERRUPTED" && (a = !1, o = !1, e.onInterrupt?.(), s({
2107
+ ...r,
2108
+ state: "listening",
2109
+ outputVolume: 0
2110
+ })), d) {
2111
+ let t = n.get(d.contentId);
2112
+ t?.final && (t.role === "USER" || t.role === "ASSISTANT") && e.onTranscript?.({
2113
+ contentId: d.contentId,
2114
+ role: t.role,
2115
+ text: t.text,
2116
+ final: !0
2117
+ }), t?.role === "USER" && !a && d.stopReason !== "INTERRUPTED" && s({
2118
+ ...r,
2119
+ state: "thinking"
2120
+ }), n.delete(d.contentId);
2121
+ }
2122
+ c.completionEnd && (o = !0, a || s({
2123
+ ...r,
2124
+ state: "listening",
2125
+ outputVolume: 0
2126
+ }));
2127
+ },
2128
+ setInputVolume(e, t) {
2129
+ e !== i || r.state === "error" || s({
2130
+ ...r,
2131
+ inputVolume: Q(t)
2132
+ });
2133
+ },
2134
+ setPlayback(e, t, n = 0) {
2135
+ e !== i || r.state === "error" || (a = t, s({
2136
+ ...r,
2137
+ state: t ? "speaking" : o ? "listening" : r.state,
2138
+ outputVolume: t ? Q(n) : 0
2139
+ }));
2140
+ },
2141
+ failed(t, n) {
2142
+ t === i && (e.onInterrupt?.(), c("error", n), i = null);
2143
+ },
2144
+ endSession(t) {
2145
+ t === i && (e.onInterrupt?.(), i = null, c("idle"));
2146
+ }
2147
+ };
2148
+ }
2149
+ //#endregion
2150
+ export { a as DEFAULT_VOLUME_CALIBRATION, r as PROVIDER_VOLUME_CALIBRATIONS, n as calibrateVolume, z as createAgoraAdapter, Y as createAzureVoiceLiveAdapter, Z as createCartesiaAdapter, L as createDeepgramAdapter, R as createDeepgramReactAdapter, d as createElevenLabsAdapter, M as createGeminiLiveAdapter, I as createHumeAdapter, s as createLiveKitAdapter, $ as createNovaSonicBridge, v as createOpenAILiveAdapter, T as createOpenAIRealtimeAdapter, g as createPipecatAdapter, N as createRetellAdapter, u as createVapiAdapter, i as createVolumeNormalizer, o as fitVolumeCalibration, P as humeFftToVolume, F as humeVoiceToOrbSignal, t as mapVolumeAmplitude };