orb-ui 0.9.0 → 0.10.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/dist/adapters.js CHANGED
@@ -927,4 +927,1222 @@ 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("agent-thinking", () => {
1318
+ t.ready && (t.generating = !0, t.ignoreAudio = !1, p(t));
1319
+ }), i("agent-started-speaking", () => {
1320
+ t.ready && (t.generating = !0, t.ignoreAudio = !1, p(t));
1321
+ }), i("agent-audio-done", () => {
1322
+ t.generating = !1, p(t);
1323
+ }), i("error", (e) => f(t, e ?? /* @__PURE__ */ Error("Deepgram agent error."))), i("sdk-error", (e) => {
1324
+ t.player.interrupt(), t.heardAudio = !1, u(), l("error", 0, 0, e ?? /* @__PURE__ */ Error("Deepgram transport error."));
1325
+ }), i("disconnected", (e) => f(t, /* @__PURE__ */ Error(`Deepgram disconnected: ${String(e ?? "connection closed")}`)));
1326
+ let a = (e) => {
1327
+ if (!(t.disposed || !t.ready || t.ignoreAudio)) try {
1328
+ t.player.queue(e), p(t);
1329
+ } catch (e) {
1330
+ f(t, e);
1331
+ }
1332
+ };
1333
+ t.session.on("audio", a), t.removers.push(() => t.session.off("audio", a));
1334
+ let o = (e) => f(t, e);
1335
+ 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);
1336
+ try {
1337
+ t.microphone.start().then(() => {
1338
+ if (t.disposed) {
1339
+ t.microphone.stop();
1340
+ return;
1341
+ }
1342
+ t.capturing = !0, m(t);
1343
+ }, (e) => f(t, e)), t.session.connect().catch((e) => f(t, e));
1344
+ } catch (e) {
1345
+ f(t, e);
1346
+ }
1347
+ let d = n.finally(() => {
1348
+ c === d && (c = void 0);
1349
+ });
1350
+ return c = d, d;
1351
+ },
1352
+ stop() {
1353
+ c = void 0;
1354
+ let e = s;
1355
+ e && (e.reject?.(new DOMException("Deepgram start cancelled.", "AbortError")), d(e)), u(), l("idle");
1356
+ }
1357
+ };
1358
+ }
1359
+ function R(e) {
1360
+ 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;
1361
+ function l() {
1362
+ try {
1363
+ let n = e.getSnapshot(), r = n.state === "connected" && n.mode === "speaking" && !n.outputMuted ? c(n.getOutputVolume()) : 0;
1364
+ (n.mode !== "speaking" || n.outputMuted || n.state !== "connected") && (s = !1), r > .001 && (s = !0);
1365
+ 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 = {
1366
+ state: o,
1367
+ inputVolume: o !== "idle" && o !== "connecting" && o !== "error" && n.micActive && !n.micMuted ? c(n.getInputVolume()) : 0,
1368
+ outputVolume: o === "speaking" ? r : 0,
1369
+ ...o === "error" ? { error: i ?? n.error } : {}
1370
+ };
1371
+ t.forEach((e) => e(l));
1372
+ } catch (e) {
1373
+ i = e, t.forEach((t) => t({
1374
+ state: "error",
1375
+ inputVolume: 0,
1376
+ outputVolume: 0,
1377
+ error: e
1378
+ }));
1379
+ }
1380
+ }
1381
+ return {
1382
+ subscribe(e) {
1383
+ return t.add(e), n === void 0 && (n = setInterval(l, 1e3 / 30)), l(), () => {
1384
+ t.delete(e), !t.size && n !== void 0 && (clearInterval(n), n = void 0);
1385
+ };
1386
+ },
1387
+ start() {
1388
+ if (r) return r;
1389
+ let t = ++o;
1390
+ s = !1, i = void 0, a = !1;
1391
+ let n;
1392
+ try {
1393
+ n = e.start();
1394
+ } catch (e) {
1395
+ n = Promise.reject(e);
1396
+ }
1397
+ let c = n.catch((n) => {
1398
+ throw o === t && (i = n, e.stop(), l()), n;
1399
+ }).finally(() => {
1400
+ r === c && (r = void 0);
1401
+ });
1402
+ return r = c, c;
1403
+ },
1404
+ stop() {
1405
+ o++, s = !1, r = void 0, a = !0, i = void 0, e.stop(), l();
1406
+ }
1407
+ };
1408
+ }
1409
+ //#endregion
1410
+ //#region src/adapters/agora/index.ts
1411
+ function z(e) {
1412
+ let t = /* @__PURE__ */ new Set(), n = i(a, e.inputVolumeCalibration), r = i(a, e.outputVolumeCalibration), o = {
1413
+ state: "idle",
1414
+ inputVolume: 0,
1415
+ outputVolume: 0
1416
+ }, s, c;
1417
+ function l(e, n = 0, r = 0, i) {
1418
+ o = {
1419
+ state: e,
1420
+ inputVolume: n,
1421
+ outputVolume: r,
1422
+ ...i === void 0 ? {} : { error: i }
1423
+ }, t.forEach((e) => e(o));
1424
+ }
1425
+ function u(e) {
1426
+ e.thinking = !1, e.producing = !1, e.lastAudibleAt = -Infinity, n.reset(), r.reset();
1427
+ }
1428
+ function d(e) {
1429
+ 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);
1430
+ }
1431
+ function f(e, t) {
1432
+ e.disposed || (e.failure = t, l("error", 0, 0, t), d(e).catch(() => void 0));
1433
+ }
1434
+ function p(e) {
1435
+ if (!(e.disposed || !e.session)) {
1436
+ if (e.session.rtc.connectionState !== "CONNECTED") {
1437
+ (e.session.rtc.connectionState === "CONNECTING" || e.session.rtc.connectionState === "RECONNECTING") && (u(e), l("connecting"));
1438
+ return;
1439
+ }
1440
+ try {
1441
+ let t = e.session.getMicrophoneTrack(), i = e.session.getAgentAudioTrack(), a = !e.interrupted && i?.isPlaying ? i.getVolumeLevel() : 0, o = performance.now();
1442
+ a > .001 && (e.lastAudibleAt = o);
1443
+ let s = !e.interrupted && !!i?.isPlaying && o - e.lastAudibleAt < 180;
1444
+ 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);
1445
+ } catch (t) {
1446
+ f(e, t);
1447
+ }
1448
+ }
1449
+ }
1450
+ function m(e, t) {
1451
+ 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) => {
1452
+ !n(t) || !r(i) || (e.thinking = i.state === "thinking", e.producing = i.state === "speaking", (e.thinking || e.producing) && (e.interrupted = !1), p(e));
1453
+ }, a = (t, r) => {
1454
+ n(t) && (e.thinking = r, r && (e.interrupted = !1), p(e));
1455
+ }, o = (t, r) => {
1456
+ n(t) && (e.producing = r, r && (e.interrupted = !1), p(e));
1457
+ }, s = (t, i) => {
1458
+ !n(t) || !r(i) || (u(e), e.interrupted = !0, p(e));
1459
+ }, c = (t, r) => {
1460
+ n(t) && f(e, r);
1461
+ }, d = (t) => {
1462
+ 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)));
1463
+ };
1464
+ 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));
1465
+ }
1466
+ return {
1467
+ subscribe(e) {
1468
+ return t.add(e), e(o), () => {
1469
+ t.delete(e), t.size || (s && d(s).catch(() => void 0), l("idle"));
1470
+ };
1471
+ },
1472
+ start() {
1473
+ if (c && s) return c;
1474
+ if (s) return Promise.resolve();
1475
+ let t = {
1476
+ abort: new AbortController(),
1477
+ disposed: !1,
1478
+ thinking: !1,
1479
+ producing: !1,
1480
+ interrupted: !1,
1481
+ lastAudibleAt: -Infinity,
1482
+ lastTimestamp: -Infinity,
1483
+ lastTurn: -Infinity,
1484
+ removers: []
1485
+ };
1486
+ s = t, l("connecting");
1487
+ let n = new Promise((e, n) => {
1488
+ t.abort.signal.addEventListener("abort", () => n(t.failure ?? new DOMException("Agora start cancelled.", "AbortError")), { once: !0 });
1489
+ });
1490
+ t.timeout = setTimeout(() => f(t, /* @__PURE__ */ Error("Agora application session timed out.")), e.startTimeoutMs ?? 3e4);
1491
+ let r;
1492
+ try {
1493
+ r = e.createSession(t.abort.signal);
1494
+ } catch (e) {
1495
+ f(t, e), r = Promise.reject(e);
1496
+ }
1497
+ let i = r.then(async (e) => {
1498
+ if (t.disposed) throw await e.close(), new DOMException("Agora start cancelled.", "AbortError");
1499
+ if (t.session = e, e.rtc.connectionState !== "CONNECTED") throw Error("createSession must return a connected Agora RTC session.");
1500
+ m(t, e), t.timeout !== void 0 && clearTimeout(t.timeout), t.poll = setInterval(() => p(t), 1e3 / 30), p(t);
1501
+ }), a = Promise.race([i, n]).catch((e) => {
1502
+ throw f(t, e), e;
1503
+ }).finally(() => {
1504
+ c === a && (c = void 0);
1505
+ });
1506
+ return c = a, a;
1507
+ },
1508
+ async stop() {
1509
+ c = void 0;
1510
+ let e = s;
1511
+ if (e) try {
1512
+ await d(e);
1513
+ } catch (e) {
1514
+ throw l("error", 0, 0, e), e;
1515
+ }
1516
+ s || l("idle");
1517
+ },
1518
+ async interrupt() {
1519
+ let e = s;
1520
+ if (!(!e?.session || e.disposed)) try {
1521
+ await e.session.toolkit.interrupt(e.session.agentUserId);
1522
+ } catch (t) {
1523
+ throw f(e, t), t;
1524
+ }
1525
+ }
1526
+ };
1527
+ }
1528
+ //#endregion
1529
+ //#region src/adapters/azure-voice-live/browser-audio.ts
1530
+ 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";
1531
+ async function V(e) {
1532
+ if (!e.audioWorklet) throw Error("AudioWorklet requires HTTPS or localhost.");
1533
+ let t = URL.createObjectURL(new Blob([B], { type: "text/javascript" }));
1534
+ try {
1535
+ return await e.audioWorklet.addModule(t), new AudioWorkletNode(e, "orb-pcm-capture");
1536
+ } finally {
1537
+ URL.revokeObjectURL(t);
1538
+ }
1539
+ }
1540
+ function H(e) {
1541
+ if (e.length === 0) return 0;
1542
+ let t = 0;
1543
+ for (let n of e) t += n * n;
1544
+ return Math.sqrt(t / e.length);
1545
+ }
1546
+ function U(e, t) {
1547
+ let n = e / t, r = 0, i = 0;
1548
+ return (e) => {
1549
+ let t = [];
1550
+ for (let a of e) {
1551
+ let e = 1;
1552
+ for (; e > 1e-8;) {
1553
+ let o = Math.min(e, n - i);
1554
+ 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);
1555
+ }
1556
+ }
1557
+ let a = new Uint8Array(t.length * 2), o = new DataView(a.buffer);
1558
+ return t.forEach((e, t) => {
1559
+ o.setInt16(t * 2, e < 0 ? e * 32768 : e * 32767, !0);
1560
+ }), a;
1561
+ };
1562
+ }
1563
+ function W(e) {
1564
+ if (e.byteLength % 2 != 0) throw Error("PCM16 audio must contain whole samples.");
1565
+ let t = new DataView(e.buffer, e.byteOffset, e.byteLength), n = new Float32Array(e.byteLength / 2);
1566
+ for (let e = 0; e < n.length; e++) n[e] = t.getInt16(e * 2, !0) / 32768;
1567
+ return n;
1568
+ }
1569
+ function G(e) {
1570
+ let t = "";
1571
+ for (let n of e) t += String.fromCharCode(n);
1572
+ return btoa(t);
1573
+ }
1574
+ function K(e) {
1575
+ let t = atob(e);
1576
+ return Uint8Array.from(t, (e) => e.charCodeAt(0));
1577
+ }
1578
+ function q(e) {
1579
+ 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 = () => {
1580
+ r || e.onError(/* @__PURE__ */ Error("The microphone track ended."));
1581
+ }, h = () => {
1582
+ !i || r || t.state === "running" || (_(), e.onError(/* @__PURE__ */ Error(`Browser audio is ${t.state}. Start a new session to resume.`)));
1583
+ };
1584
+ t.addEventListener("statechange", h);
1585
+ function g() {
1586
+ if (r) throw new DOMException("Audio startup canceled.", "AbortError");
1587
+ }
1588
+ function _() {
1589
+ f.forEach((e) => {
1590
+ e.onended = null;
1591
+ try {
1592
+ e.stop();
1593
+ } catch {}
1594
+ e.disconnect();
1595
+ }), f.clear(), d = t.currentTime, e.onOutputVolume(0), e.onPlayback(!1);
1596
+ }
1597
+ return {
1598
+ clear: _,
1599
+ get hasOutput() {
1600
+ return t.state === "running" && f.size > 0;
1601
+ },
1602
+ async open() {
1603
+ await n, g();
1604
+ let d = await (e.getUserMedia ?? ((e) => navigator.mediaDevices.getUserMedia(e)))(e.mediaStreamConstraints ?? { audio: {
1605
+ channelCount: 1,
1606
+ echoCancellation: !0,
1607
+ noiseSuppression: !0
1608
+ } });
1609
+ 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.`);
1610
+ 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) => {
1611
+ if (!r) try {
1612
+ let n = t.data;
1613
+ if (!(n instanceof Float32Array)) throw Error("Invalid microphone PCM frame.");
1614
+ let r = p(n);
1615
+ r.byteLength && e.onInput(r, H(n));
1616
+ } catch (t) {
1617
+ e.onError(t);
1618
+ }
1619
+ }, o.onprocessorerror = () => {
1620
+ r || e.onError(/* @__PURE__ */ Error("The microphone AudioWorklet failed."));
1621
+ }, l = t.createAnalyser(), l.fftSize = 512, l.connect(t.destination);
1622
+ let h = new Float32Array(l.fftSize);
1623
+ i = !0, u = setInterval(() => {
1624
+ if (!(r || !l)) {
1625
+ if (t.state !== "running" || f.size === 0) {
1626
+ e.onOutputVolume(0);
1627
+ return;
1628
+ }
1629
+ l.getFloatTimeDomainData(h), e.onOutputVolume(H(h));
1630
+ }
1631
+ }, 33);
1632
+ },
1633
+ play(n) {
1634
+ if (r || !l || n.byteLength === 0) return;
1635
+ if (t.state !== "running") throw Error(`Browser audio is ${t.state}. Start a new session to resume.`);
1636
+ if (d - t.currentTime > 5) throw Error("Audio playback fell more than five seconds behind.");
1637
+ let i = W(n), a = t.createBuffer(1, i.length, e.outputSampleRate);
1638
+ a.getChannelData(0).set(i);
1639
+ let o = t.createBufferSource();
1640
+ o.buffer = a, o.connect(l);
1641
+ let s = Math.max(t.currentTime, d);
1642
+ d = s + a.duration, f.add(o), o.onended = () => {
1643
+ f.delete(o) && (o.disconnect(), !r && f.size === 0 && (e.onOutputVolume(0), e.onPlayback(!1)));
1644
+ }, o.start(s), e.onPlayback(!0);
1645
+ },
1646
+ async close() {
1647
+ 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) => {
1648
+ e.removeEventListener("ended", m), e.stop();
1649
+ }), t.state !== "closed" && await t.close());
1650
+ }
1651
+ };
1652
+ }
1653
+ //#endregion
1654
+ //#region src/adapters/azure-voice-live/index.ts
1655
+ var J = {
1656
+ amplitude: {
1657
+ silenceFloor: .003,
1658
+ speechReference: .1,
1659
+ speechPeak: .3
1660
+ },
1661
+ envelope: {
1662
+ riseTimeMs: 100,
1663
+ fallTimeMs: 400
1664
+ }
1665
+ };
1666
+ function Y(e) {
1667
+ let t = /* @__PURE__ */ new Set(), n = {
1668
+ state: "idle",
1669
+ inputVolume: 0,
1670
+ outputVolume: 0
1671
+ }, r, a, o, s = i(J, e.inputVolumeCalibration), c = i(J, e.outputVolumeCalibration);
1672
+ function l(e) {
1673
+ n = e, t.forEach((t) => t(e));
1674
+ }
1675
+ function u(e, t) {
1676
+ let r = e === "idle" || e === "connecting" || e === "error";
1677
+ r && (s.reset(), c.reset()), l({
1678
+ state: e,
1679
+ inputVolume: r ? 0 : n.inputVolume,
1680
+ outputVolume: r ? 0 : n.outputVolume,
1681
+ ...t === void 0 ? {} : { error: t }
1682
+ });
1683
+ }
1684
+ async function d(e, t) {
1685
+ if (e.disposed) return;
1686
+ e.disposed = !0, e.abort.abort(t ?? new DOMException("Voice session canceled.", "AbortError")), r === e && (r = void 0);
1687
+ let n = (await Promise.allSettled([
1688
+ e.audio?.close(),
1689
+ e.subscription?.close(),
1690
+ e.sdk?.dispose()
1691
+ ])).find((e) => e.status === "rejected");
1692
+ if (n?.status === "rejected") throw n.reason;
1693
+ }
1694
+ function f(e) {
1695
+ return r === e && !e.disposed && !e.abort.signal.aborted;
1696
+ }
1697
+ function p(e) {
1698
+ if (!f(e)) throw new DOMException("Voice session canceled.", "AbortError");
1699
+ }
1700
+ function m(e, t) {
1701
+ f(e) && (u("error", t), d(e, t).catch(() => void 0));
1702
+ }
1703
+ function h(e) {
1704
+ e.audio?.hasOutput || (c.reset(), l({
1705
+ ...n,
1706
+ state: e.userSpeaking || e.responseComplete ? "listening" : "thinking",
1707
+ outputVolume: 0
1708
+ }));
1709
+ }
1710
+ function g(t, r) {
1711
+ if (f(t)) {
1712
+ if (r.type === "input_audio_buffer.speech_started") t.userSpeaking = !0, t.responseId && t.interruptedResponses.add(t.responseId), t.audio?.clear(), c.reset(), l({
1713
+ ...n,
1714
+ state: "listening",
1715
+ outputVolume: 0
1716
+ });
1717
+ else if (r.type === "input_audio_buffer.speech_stopped") t.userSpeaking = !1, u("thinking");
1718
+ else if (r.type === "response.created") t.responseId = r.response?.id, t.responseComplete = !1, !t.userSpeaking && !t.audio?.hasOutput && u("thinking");
1719
+ else if (r.type === "response.audio.delta") {
1720
+ if (!(r.delta instanceof Uint8Array)) throw Error("Expected Azure SDK PCM bytes.");
1721
+ !t.userSpeaking && (!r.responseId || !t.interruptedResponses.has(r.responseId)) && t.audio?.play(r.delta);
1722
+ } else if (r.type === "response.done") if (r.response?.id && t.interruptedResponses.has(r.response.id)) t.interruptedResponses.delete(r.response.id);
1723
+ else {
1724
+ if (t.responseComplete = !0, r.response?.status === "failed") throw Error("Azure Voice Live response failed.");
1725
+ h(t);
1726
+ }
1727
+ else if (r.type === "error") throw Error(r.error?.message ?? "Azure Voice Live server error.");
1728
+ e.onEvent?.(r);
1729
+ }
1730
+ }
1731
+ async function _(t) {
1732
+ t.audio = q({
1733
+ ...e,
1734
+ inputSampleRate: 24e3,
1735
+ outputSampleRate: 24e3,
1736
+ onInput(e, r) {
1737
+ if (f(t) && (l({
1738
+ ...n,
1739
+ inputVolume: s.sample(r).normalized
1740
+ }), !(!t.ready || !t.sdk))) {
1741
+ if (t.pendingAudio >= 16) {
1742
+ m(t, /* @__PURE__ */ Error("Azure microphone transport is falling behind."));
1743
+ return;
1744
+ }
1745
+ t.pendingAudio += 1, t.sdk.sendAudio(e).catch((e) => m(t, e)).finally(() => --t.pendingAudio);
1746
+ }
1747
+ },
1748
+ onOutputVolume(e) {
1749
+ f(t) && l({
1750
+ ...n,
1751
+ outputVolume: c.sample(e).normalized
1752
+ });
1753
+ },
1754
+ onPlayback(e) {
1755
+ f(t) && (e && !t.userSpeaking && u("speaking"), e || h(t));
1756
+ },
1757
+ onError(e) {
1758
+ m(t, e);
1759
+ }
1760
+ }), await t.audio.open(), p(t);
1761
+ let r = await e.createSession(t.abort.signal);
1762
+ f(t) || (await r.dispose(), p(t)), t.sdk = r, t.subscription = r.subscribe({
1763
+ onServerEvent: async (e) => {
1764
+ try {
1765
+ g(t, e);
1766
+ } catch (e) {
1767
+ m(t, e);
1768
+ }
1769
+ },
1770
+ onError: async ({ error: e }) => m(t, e),
1771
+ onDisconnected: async ({ code: e, reason: n }) => {
1772
+ f(t) && (!t.ready || e !== 1e3 ? m(t, /* @__PURE__ */ Error(`Azure session disconnected (${e}): ${n}`)) : (u("idle"), d(t).catch(() => void 0)));
1773
+ }
1774
+ }), await r.connect({
1775
+ abortSignal: t.abort.signal,
1776
+ timeoutInMs: e.startTimeoutMs ?? 3e4
1777
+ }), p(t), await r.updateSession({ turnDetection: {
1778
+ type: "server_vad",
1779
+ threshold: .5,
1780
+ prefixPaddingInMs: 300,
1781
+ silenceDurationInMs: 500
1782
+ } }), await e.configureSession?.(r, t.abort.signal), p(t), await r.updateSession({
1783
+ inputAudioFormat: "pcm16",
1784
+ inputAudioSamplingRate: 24e3,
1785
+ outputAudioFormat: "pcm16"
1786
+ }), p(t), t.ready = !0, u("listening");
1787
+ }
1788
+ return {
1789
+ subscribe(e) {
1790
+ return t.add(e), e(n), () => t.delete(e);
1791
+ },
1792
+ start() {
1793
+ if (a) return a;
1794
+ if (r?.ready) return Promise.resolve();
1795
+ if (o) return o.then(() => this.start());
1796
+ let t = {
1797
+ abort: new AbortController(),
1798
+ disposed: !1,
1799
+ ready: !1,
1800
+ userSpeaking: !1,
1801
+ responseComplete: !1,
1802
+ interruptedResponses: /* @__PURE__ */ new Set(),
1803
+ pendingAudio: 0
1804
+ };
1805
+ r = t, u("connecting");
1806
+ let n, i = new Promise((r, i) => {
1807
+ t.abort.signal.addEventListener("abort", () => i(t.abort.signal.reason), { once: !0 }), n = setTimeout(() => {
1808
+ let e = /* @__PURE__ */ Error("Azure Voice Live startup timed out.");
1809
+ m(t, e), i(e);
1810
+ }, e.startTimeoutMs ?? 3e4);
1811
+ });
1812
+ return a = Promise.race([_(t), i]).catch(async (e) => {
1813
+ throw f(t) && m(t, e), await d(t).catch(() => void 0), e;
1814
+ }).finally(() => {
1815
+ clearTimeout(n), a = void 0;
1816
+ }), a;
1817
+ },
1818
+ stop() {
1819
+ if (o) return o;
1820
+ let e = r;
1821
+ return o = (e ? d(e) : Promise.resolve()).then(() => u("idle")).catch((e) => {
1822
+ throw u("error", e), e;
1823
+ }).finally(() => o = void 0), o;
1824
+ }
1825
+ };
1826
+ }
1827
+ //#endregion
1828
+ //#region src/adapters/cartesia/index.ts
1829
+ var X = {
1830
+ amplitude: {
1831
+ silenceFloor: .003,
1832
+ speechReference: .1,
1833
+ speechPeak: .3
1834
+ },
1835
+ envelope: {
1836
+ riseTimeMs: 100,
1837
+ fallTimeMs: 400
1838
+ }
1839
+ };
1840
+ function Z(e) {
1841
+ if (!e.agentId.trim()) throw Error("A Cartesia Managed Agent ID is required.");
1842
+ let t = e.inputFormat ?? "pcm_24000", n = Number(t.slice(4));
1843
+ if (![
1844
+ 16e3,
1845
+ 24e3,
1846
+ 44100
1847
+ ].includes(n)) throw Error("Cartesia adapter requires a supported mono PCM16 format.");
1848
+ let r = /* @__PURE__ */ new Set(), a = {
1849
+ state: "idle",
1850
+ inputVolume: 0,
1851
+ outputVolume: 0
1852
+ }, o, s, c, l, u = i(X, e.inputVolumeCalibration), d = i(X, e.outputVolumeCalibration);
1853
+ function f(e) {
1854
+ a = e, r.forEach((t) => t(e));
1855
+ }
1856
+ function p(e, t) {
1857
+ let n = e === "idle" || e === "connecting" || e === "error";
1858
+ n && (u.reset(), d.reset()), f({
1859
+ state: e,
1860
+ inputVolume: n ? 0 : a.inputVolume,
1861
+ outputVolume: n ? 0 : a.outputVolume,
1862
+ ...t === void 0 ? {} : { error: t }
1863
+ });
1864
+ }
1865
+ function m(e) {
1866
+ return o === e && !e.disposed && !e.abort.signal.aborted;
1867
+ }
1868
+ function h(e) {
1869
+ if (!m(e)) throw new DOMException("Cartesia session canceled.", "AbortError");
1870
+ }
1871
+ async function g(e, t) {
1872
+ if (e.disposed) return;
1873
+ e.disposed = !0;
1874
+ let n = t ?? new DOMException("Cartesia session canceled.", "AbortError");
1875
+ 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();
1876
+ }
1877
+ function _(e, t) {
1878
+ m(e) && (p("error", t), e.readyReject?.(t), g(e, t).catch(() => void 0));
1879
+ }
1880
+ function v(e) {
1881
+ e.audio?.hasOutput || (d.reset(), f({
1882
+ ...a,
1883
+ state: e.userSpeaking || e.outputComplete ? "listening" : "thinking",
1884
+ outputVolume: 0
1885
+ }));
1886
+ }
1887
+ function y(e, t) {
1888
+ if (!m(e) || e.socket?.readyState !== 1) throw Error("Cartesia session is not connected.");
1889
+ if (e.socket.bufferedAmount > 128 * 1024) throw Error("Cartesia microphone transport is falling behind.");
1890
+ let n = JSON.stringify(t);
1891
+ if (new TextEncoder().encode(n).byteLength > 32 * 1024) throw Error("Cartesia JSON event exceeds 32 KiB.");
1892
+ e.socket.send(n);
1893
+ }
1894
+ function b(n, r) {
1895
+ if (m(n)) {
1896
+ if (r.type === "session_ready") {
1897
+ 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.");
1898
+ if (n.ready) throw Error("Duplicate Cartesia session_ready.");
1899
+ l = n.callId = r.call_id, n.ready = !0, p("listening"), n.readyResolve?.();
1900
+ } else if (r.type === "error") {
1901
+ if (r.fatal !== !1) throw Error(r.message ?? "Cartesia session failed.");
1902
+ e.onRecoverableError?.(r);
1903
+ } else {
1904
+ if (!n.ready) throw Error("Cartesia event arrived before session_ready.");
1905
+ if (r.type === "turn_started") n.outputComplete = !1, r.role === "user" ? (n.userSpeaking = !0, n.audio?.clear(), d.reset(), f({
1906
+ ...a,
1907
+ state: "listening",
1908
+ outputVolume: 0
1909
+ })) : r.role === "assistant" && !n.userSpeaking && !n.audio?.hasOutput && p("thinking");
1910
+ 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));
1911
+ else if (r.type === "audio_output") {
1912
+ if (typeof r.audio != "string") throw Error("Cartesia audio_output needs base64 PCM.");
1913
+ n.userSpeaking || n.audio?.play(K(r.audio));
1914
+ } else r.type === "audio_output_clear" && (n.userSpeaking = !0, n.outputComplete = !1, n.audio?.clear(), d.reset(), f({
1915
+ ...a,
1916
+ state: "listening",
1917
+ outputVolume: 0
1918
+ }));
1919
+ }
1920
+ e.onEvent?.(r);
1921
+ }
1922
+ }
1923
+ async function x(r) {
1924
+ r.audio = q({
1925
+ ...e,
1926
+ inputSampleRate: n,
1927
+ outputSampleRate: n,
1928
+ onInput(e, t) {
1929
+ if (m(r) && (f({
1930
+ ...a,
1931
+ inputVolume: u.sample(t).normalized
1932
+ }), r.ready)) try {
1933
+ y(r, {
1934
+ type: "audio_input",
1935
+ audio: G(e)
1936
+ });
1937
+ } catch (e) {
1938
+ _(r, e);
1939
+ }
1940
+ },
1941
+ onOutputVolume(e) {
1942
+ m(r) && f({
1943
+ ...a,
1944
+ outputVolume: d.sample(e).normalized
1945
+ });
1946
+ },
1947
+ onPlayback(e) {
1948
+ m(r) && (e && !r.userSpeaking && p("speaking"), e || v(r));
1949
+ },
1950
+ onError(e) {
1951
+ _(r, e);
1952
+ }
1953
+ }), await r.audio.open(), h(r);
1954
+ let i = await e.getAccessToken(r.abort.signal);
1955
+ if (h(r), !i.trim()) throw Error("An agent access token is required.");
1956
+ let o = new URL(`wss://api.cartesia.ai/v1/agents/websocket/${encodeURIComponent(e.agentId)}`);
1957
+ o.searchParams.set("cartesia_version", e.apiVersion ?? "2026-08-14"), o.searchParams.set("access_token", i);
1958
+ let s = (e.createWebSocket ?? ((e) => new WebSocket(e)))(o.toString());
1959
+ r.socket = s, await new Promise((n, i) => {
1960
+ r.readyResolve = n, r.readyReject = i, s.onopen = () => {
1961
+ if (m(r)) try {
1962
+ y(r, {
1963
+ type: "session_create",
1964
+ audio: {
1965
+ input_format: t,
1966
+ output_delivery: e.outputDelivery ?? "speaking_pace"
1967
+ }
1968
+ });
1969
+ } catch (e) {
1970
+ _(r, e);
1971
+ }
1972
+ }, s.onmessage = ({ data: e }) => {
1973
+ if (m(r)) try {
1974
+ if (typeof e != "string") throw Error("Cartesia requires JSON text frames.");
1975
+ let t = JSON.parse(e);
1976
+ if (!t || typeof t != "object" || !("type" in t) || typeof t.type != "string") throw Error("Invalid Cartesia event.");
1977
+ b(r, t);
1978
+ } catch (e) {
1979
+ _(r, e);
1980
+ }
1981
+ }, s.onerror = () => _(r, /* @__PURE__ */ Error("Cartesia WebSocket connection failed.")), s.onclose = ({ code: e, reason: t }) => {
1982
+ m(r) && (!r.ready || e !== 1e3 ? _(r, /* @__PURE__ */ Error(`Cartesia session closed (${e}): ${t}`)) : (p("idle"), g(r).catch(() => void 0)));
1983
+ };
1984
+ }), h(r);
1985
+ }
1986
+ return {
1987
+ get callId() {
1988
+ return l;
1989
+ },
1990
+ subscribe(e) {
1991
+ return r.add(e), e(a), () => r.delete(e);
1992
+ },
1993
+ start() {
1994
+ if (s) return s;
1995
+ if (o?.ready) return Promise.resolve();
1996
+ if (c) return c.then(() => this.start());
1997
+ let t = {
1998
+ abort: new AbortController(),
1999
+ disposed: !1,
2000
+ ready: !1,
2001
+ userSpeaking: !1,
2002
+ outputComplete: !1
2003
+ };
2004
+ o = t, l = void 0, p("connecting");
2005
+ let n, r = new Promise((r, i) => {
2006
+ t.abort.signal.addEventListener("abort", () => i(t.abort.signal.reason), { once: !0 }), n = setTimeout(() => {
2007
+ let e = /* @__PURE__ */ Error("Cartesia startup timed out before session_ready.");
2008
+ _(t, e), i(e);
2009
+ }, e.startTimeoutMs ?? 3e4);
2010
+ });
2011
+ return s = Promise.race([x(t), r]).catch(async (e) => {
2012
+ throw m(t) && _(t, e), await g(t).catch(() => void 0), e;
2013
+ }).finally(() => {
2014
+ clearTimeout(n), s = void 0;
2015
+ }), s;
2016
+ },
2017
+ stop() {
2018
+ if (c) return c;
2019
+ let e = o;
2020
+ return c = (e ? g(e) : Promise.resolve()).then(() => p("idle")).catch((e) => {
2021
+ throw p("error", e), e;
2022
+ }).finally(() => c = void 0), c;
2023
+ },
2024
+ sendToolResult(e, t, n = !1) {
2025
+ if (!o?.ready) throw Error("Cartesia session is not ready.");
2026
+ if (new TextEncoder().encode(t).byteLength > 4096) throw Error("Cartesia client tool result exceeds 4096 bytes.");
2027
+ y(o, {
2028
+ type: "client_tool_result",
2029
+ tool_call_id: e,
2030
+ result: t,
2031
+ is_error: n
2032
+ });
2033
+ }
2034
+ };
2035
+ }
2036
+ //#endregion
2037
+ //#region src/adapters/nova-sonic/index.ts
2038
+ var Q = (e) => Number.isFinite(e) ? Math.min(1, Math.max(0, e)) : 0;
2039
+ function $(e = {}) {
2040
+ let t = /* @__PURE__ */ new Set(), n = /* @__PURE__ */ new Map(), r = {
2041
+ state: "idle",
2042
+ inputVolume: 0,
2043
+ outputVolume: 0
2044
+ }, i = null, a = !1, o = !1;
2045
+ function s(e) {
2046
+ r = e, t.forEach((t) => t(e));
2047
+ }
2048
+ function c(e, t) {
2049
+ n.clear(), a = !1, o = !1, s({
2050
+ state: e,
2051
+ inputVolume: 0,
2052
+ outputVolume: 0,
2053
+ ...t === void 0 ? {} : { error: t }
2054
+ });
2055
+ }
2056
+ return {
2057
+ subscribe(e) {
2058
+ return t.add(e), e(r), () => t.delete(e);
2059
+ },
2060
+ beginSession(t) {
2061
+ if (!t) throw Error("Nova Sonic needs an app session ID");
2062
+ e.onInterrupt?.(), i = t, c("connecting");
2063
+ },
2064
+ connected(e) {
2065
+ e !== i || r.state !== "connecting" || s({
2066
+ state: "listening",
2067
+ inputVolume: 0,
2068
+ outputVolume: 0
2069
+ });
2070
+ },
2071
+ handleEvent(t, c) {
2072
+ if (t !== i || r.state === "error") return;
2073
+ let l = c.contentStart;
2074
+ if (l) {
2075
+ n.size >= 128 && n.delete(n.keys().next().value);
2076
+ let e = !1;
2077
+ try {
2078
+ let t = JSON.parse(l.additionalModelFields ?? "{}");
2079
+ e = typeof t == "object" && !!t && "generationStage" in t && t.generationStage === "FINAL";
2080
+ } catch {}
2081
+ n.set(l.contentId, {
2082
+ role: l.role,
2083
+ final: e,
2084
+ text: ""
2085
+ }), l.role === "USER" ? (o = !1, s({
2086
+ ...r,
2087
+ state: "listening"
2088
+ })) : l.role === "ASSISTANT" && !a && s({
2089
+ ...r,
2090
+ state: "thinking"
2091
+ });
2092
+ }
2093
+ let u = c.textOutput;
2094
+ if (u) {
2095
+ let t = n.get(u.contentId);
2096
+ t?.final && (t.role === "USER" || t.role === "ASSISTANT") && (t.text = (t.text + u.content).slice(0, 32768), e.onTranscript?.({
2097
+ contentId: u.contentId,
2098
+ role: t.role,
2099
+ text: t.text,
2100
+ final: !1
2101
+ }));
2102
+ }
2103
+ let d = c.contentEnd;
2104
+ if (d?.stopReason?.toUpperCase() === "INTERRUPTED" && (a = !1, o = !1, e.onInterrupt?.(), s({
2105
+ ...r,
2106
+ state: "listening",
2107
+ outputVolume: 0
2108
+ })), d) {
2109
+ let t = n.get(d.contentId);
2110
+ t?.final && (t.role === "USER" || t.role === "ASSISTANT") && e.onTranscript?.({
2111
+ contentId: d.contentId,
2112
+ role: t.role,
2113
+ text: t.text,
2114
+ final: !0
2115
+ }), t?.role === "USER" && !a && d.stopReason !== "INTERRUPTED" && s({
2116
+ ...r,
2117
+ state: "thinking"
2118
+ }), n.delete(d.contentId);
2119
+ }
2120
+ c.completionEnd && (o = !0, a || s({
2121
+ ...r,
2122
+ state: "listening",
2123
+ outputVolume: 0
2124
+ }));
2125
+ },
2126
+ setInputVolume(e, t) {
2127
+ e !== i || r.state === "error" || s({
2128
+ ...r,
2129
+ inputVolume: Q(t)
2130
+ });
2131
+ },
2132
+ setPlayback(e, t, n = 0) {
2133
+ e !== i || r.state === "error" || (a = t, s({
2134
+ ...r,
2135
+ state: t ? "speaking" : o ? "listening" : r.state,
2136
+ outputVolume: t ? Q(n) : 0
2137
+ }));
2138
+ },
2139
+ failed(t, n) {
2140
+ t === i && (e.onInterrupt?.(), c("error", n), i = null);
2141
+ },
2142
+ endSession(t) {
2143
+ t === i && (e.onInterrupt?.(), i = null, c("idle"));
2144
+ }
2145
+ };
2146
+ }
2147
+ //#endregion
2148
+ 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 };