@d-id/client-sdk 1.1.11-staging.39 → 1.1.11-staging.41

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.
@@ -0,0 +1,1274 @@
1
+ var ve = Object.defineProperty;
2
+ var ke = (e, t, n) => t in e ? ve(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
3
+ var Q = (e, t, n) => ke(e, typeof t != "symbol" ? t + "" : t, n);
4
+ class ee extends Error {
5
+ constructor({ kind: n, description: r, error: i }) {
6
+ super(JSON.stringify({ kind: n, description: r }));
7
+ Q(this, "kind");
8
+ Q(this, "description");
9
+ Q(this, "error");
10
+ this.kind = n, this.description = r, this.error = i;
11
+ }
12
+ }
13
+ class De extends ee {
14
+ constructor(t, n) {
15
+ super({
16
+ kind: "ChatCreationFailed",
17
+ description: `Failed to create ${n ? "persistent" : ""} chat, mode: ${t}`
18
+ });
19
+ }
20
+ }
21
+ class Ce extends ee {
22
+ constructor(t) {
23
+ super({ kind: "ChatModeDowngraded", description: `Chat mode downgraded to ${t}` });
24
+ }
25
+ }
26
+ class H extends ee {
27
+ constructor(n, r) {
28
+ super({ kind: "ValidationError", description: n });
29
+ Q(this, "key");
30
+ this.key = r;
31
+ }
32
+ }
33
+ class Re extends ee {
34
+ constructor(t) {
35
+ super({ kind: "WSError", description: t });
36
+ }
37
+ }
38
+ var Se = /* @__PURE__ */ ((e) => (e.TRIAL = "trial", e.BASIC = "basic", e.ENTERPRISE = "enterprise", e.LITE = "lite", e.ADVANCED = "advanced", e))(Se || {}), Ie = /* @__PURE__ */ ((e) => (e.TRIAL = "deid-trial", e.PRO = "deid-pro", e.ENTERPRISE = "deid-enterprise", e.LITE = "deid-lite", e.ADVANCED = "deid-advanced", e.BUILD = "deid-api-build", e.LAUNCH = "deid-api-launch", e.SCALE = "deid-api-scale", e))(Ie || {}), Ee = /* @__PURE__ */ ((e) => (e.Created = "created", e.Started = "started", e.Done = "done", e.Error = "error", e.Rejected = "rejected", e.Ready = "ready", e))(Ee || {}), Me = /* @__PURE__ */ ((e) => (e.Unrated = "Unrated", e.Positive = "Positive", e.Negative = "Negative", e))(Me || {}), E = /* @__PURE__ */ ((e) => (e.Functional = "Functional", e.TextOnly = "TextOnly", e.Maintenance = "Maintenance", e.Playground = "Playground", e.DirectPlayback = "DirectPlayback", e.Off = "Off", e))(E || {}), q = /* @__PURE__ */ ((e) => (e.Embed = "embed", e.Query = "query", e.Partial = "partial", e.Answer = "answer", e.Complete = "done", e))(q || {}), _e = /* @__PURE__ */ ((e) => (e.KnowledgeProcessing = "knowledge/processing", e.KnowledgeIndexing = "knowledge/indexing", e.KnowledgeFailed = "knowledge/error", e.KnowledgeDone = "knowledge/done", e))(_e || {}), Te = /* @__PURE__ */ ((e) => (e.Knowledge = "knowledge", e.Document = "document", e.Record = "record", e))(Te || {}), je = /* @__PURE__ */ ((e) => (e.Pdf = "pdf", e.Text = "text", e.Html = "html", e.Word = "word", e.Json = "json", e.Markdown = "markdown", e.Csv = "csv", e.Excel = "excel", e.Powerpoint = "powerpoint", e.Archive = "archive", e.Image = "image", e.Audio = "audio", e.Video = "video", e))(je || {}), ce = /* @__PURE__ */ ((e) => (e.Clip = "clip", e.Talk = "talk", e.Expressive = "expressive", e))(ce || {});
39
+ const Tt = (e) => {
40
+ switch (e) {
41
+ case "clip":
42
+ return "clip";
43
+ case "talk":
44
+ return "talk";
45
+ default:
46
+ throw new Error(`Unknown video type: ${e}`);
47
+ }
48
+ };
49
+ var w = /* @__PURE__ */ ((e) => (e.Start = "START", e.Stop = "STOP", e))(w || {}), Z = /* @__PURE__ */ ((e) => (e.Strong = "STRONG", e.Weak = "WEAK", e.Unknown = "UNKNOWN", e))(Z || {}), O = /* @__PURE__ */ ((e) => (e.Idle = "IDLE", e.Talking = "TALKING", e))(O || {}), A = /* @__PURE__ */ ((e) => (e.ChatAnswer = "chat/answer", e.ChatPartial = "chat/partial", e.StreamDone = "stream/done", e.StreamStarted = "stream/started", e.StreamFailed = "stream/error", e.StreamReady = "stream/ready", e.StreamCreated = "stream/created", e.StreamInterrupt = "stream/interrupt", e.StreamVideoCreated = "stream-video/started", e.StreamVideoDone = "stream-video/done", e.StreamVideoError = "stream-video/error", e.StreamVideoRejected = "stream-video/rejected", e))(A || {}), S = /* @__PURE__ */ ((e) => (e.New = "new", e.Fail = "fail", e.Connected = "connected", e.Connecting = "connecting", e.Closed = "closed", e.Completed = "completed", e.Disconnected = "disconnected", e))(S || {}), N = /* @__PURE__ */ ((e) => (e.Legacy = "legacy", e.Fluent = "fluent", e))(N || {}), be = /* @__PURE__ */ ((e) => (e.Livekit = "livekit", e))(be || {}), Ae = /* @__PURE__ */ ((e) => (e.Amazon = "amazon", e.Microsoft = "microsoft", e.Afflorithmics = "afflorithmics", e.Elevenlabs = "elevenlabs", e))(Ae || {}), Pe = /* @__PURE__ */ ((e) => (e.Public = "public", e.Premium = "premium", e.Private = "private", e))(Pe || {});
50
+ const Le = 45 * 1e3, Be = "X-Playground-Chat", G = "https://api.d-id.com", $e = "wss://notifications.d-id.com", ze = "79f81a83a67430be2bc0fd61042b8faa", de = (e) => new Promise((t) => setTimeout(t, e)), V = (e = 16) => {
51
+ const t = new Uint8Array(e);
52
+ return window.crypto.getRandomValues(t), Array.from(t, (n) => n.toString(16).padStart(2, "0")).join("").slice(0, 13);
53
+ }, xe = (e) => [E.TextOnly, E.Playground, E.Maintenance].includes(e), le = (e) => e && [E.DirectPlayback, E.Off].includes(e);
54
+ function Fe(e, t) {
55
+ let n;
56
+ return {
57
+ promise: new Promise((i, o) => {
58
+ n = setTimeout(() => o(new Error(t)), e);
59
+ }),
60
+ clear: () => clearTimeout(n)
61
+ };
62
+ }
63
+ async function re(e, t) {
64
+ const n = {
65
+ limit: (t == null ? void 0 : t.limit) ?? 3,
66
+ delayMs: (t == null ? void 0 : t.delayMs) ?? 0,
67
+ timeout: (t == null ? void 0 : t.timeout) ?? 3e4,
68
+ timeoutErrorMessage: (t == null ? void 0 : t.timeoutErrorMessage) || "Timeout error",
69
+ shouldRetryFn: (t == null ? void 0 : t.shouldRetryFn) ?? (() => !0),
70
+ onRetry: (t == null ? void 0 : t.onRetry) ?? (() => {
71
+ })
72
+ };
73
+ let r;
74
+ for (let i = 1; i <= n.limit; i++)
75
+ try {
76
+ if (!n.timeout)
77
+ return await e();
78
+ const { promise: o, clear: c } = Fe(n.timeout, n.timeoutErrorMessage), a = e().finally(c);
79
+ return await Promise.race([a, o]);
80
+ } catch (o) {
81
+ if (r = o, !n.shouldRetryFn(o) || i >= n.limit)
82
+ throw o;
83
+ await de(n.delayMs), n.onRetry(o);
84
+ }
85
+ throw r;
86
+ }
87
+ function ue() {
88
+ let e = window.localStorage.getItem("did_external_key_id");
89
+ if (!e) {
90
+ let t = V();
91
+ window.localStorage.setItem("did_external_key_id", t), e = t;
92
+ }
93
+ return e;
94
+ }
95
+ let Ne = V();
96
+ function fe(e) {
97
+ if (e.type === "bearer")
98
+ return `Bearer ${e.token}`;
99
+ if (e.type === "basic")
100
+ return `Basic ${btoa(`${e.username}:${e.password}`)}`;
101
+ if (e.type === "key")
102
+ return `Client-Key ${e.clientKey}.${ue()}_${Ne}`;
103
+ throw new Error(`Unknown auth type: ${e}`);
104
+ }
105
+ const Je = (e) => re(e, {
106
+ limit: 3,
107
+ delayMs: 1e3,
108
+ timeout: 0,
109
+ shouldRetryFn: (t) => t.status === 429
110
+ });
111
+ function me(e, t = G, n) {
112
+ const r = async (i, o) => {
113
+ const { skipErrorHandler: c, ...a } = o || {}, s = await Je(
114
+ () => fetch(t + (i != null && i.startsWith("/") ? i : `/${i}`), {
115
+ ...a,
116
+ headers: {
117
+ ...a.headers,
118
+ Authorization: fe(e),
119
+ "Content-Type": "application/json"
120
+ }
121
+ })
122
+ );
123
+ if (!s.ok) {
124
+ let d = await s.text().catch(() => `Failed to fetch with status ${s.status}`);
125
+ const l = new Error(d);
126
+ throw n && !c && n(l, { url: i, options: a, headers: s.headers }), l;
127
+ }
128
+ return s.json();
129
+ };
130
+ return {
131
+ get(i, o) {
132
+ return r(i, { ...o, method: "GET" });
133
+ },
134
+ post(i, o, c) {
135
+ return r(i, { ...c, body: JSON.stringify(o), method: "POST" });
136
+ },
137
+ delete(i, o, c) {
138
+ return r(i, { ...c, body: JSON.stringify(o), method: "DELETE" });
139
+ },
140
+ patch(i, o, c) {
141
+ return r(i, { ...c, body: JSON.stringify(o), method: "PATCH" });
142
+ }
143
+ };
144
+ }
145
+ function ge(e, t = G, n) {
146
+ const r = me(e, `${t}/agents`, n);
147
+ return {
148
+ create(i, o) {
149
+ return r.post("/", i, o);
150
+ },
151
+ getAgents(i, o) {
152
+ return r.get(`/${i ? `?tag=${i}` : ""}`, o).then((c) => c ?? []);
153
+ },
154
+ getById(i, o) {
155
+ return r.get(`/${i}`, o);
156
+ },
157
+ delete(i, o) {
158
+ return r.delete(`/${i}`, void 0, o);
159
+ },
160
+ update(i, o, c) {
161
+ return r.patch(`/${i}`, o, c);
162
+ },
163
+ newChat(i, o, c) {
164
+ return r.post(`/${i}/chat`, o, c);
165
+ },
166
+ chat(i, o, c, a) {
167
+ return r.post(`/${i}/chat/${o}`, c, a);
168
+ },
169
+ createRating(i, o, c, a) {
170
+ return r.post(`/${i}/chat/${o}/ratings`, c, a);
171
+ },
172
+ updateRating(i, o, c, a, s) {
173
+ return r.patch(`/${i}/chat/${o}/ratings/${c}`, a, s);
174
+ },
175
+ deleteRating(i, o, c, a) {
176
+ return r.delete(`/${i}/chat/${o}/ratings/${c}`, a);
177
+ },
178
+ getSTTToken(i, o) {
179
+ return r.get(`/${i}/stt-token`, o);
180
+ }
181
+ };
182
+ }
183
+ const he = (e) => e.type === "clip" && e.presenter_id.startsWith("v2_") ? "clip_v2" : e.type;
184
+ function We(e) {
185
+ var i, o, c, a;
186
+ const t = () => /Mobi|Android/i.test(navigator.userAgent) ? "Mobile" : "Desktop", n = () => {
187
+ const s = navigator.platform;
188
+ return s.toLowerCase().includes("win") ? "Windows" : s.toLowerCase().includes("mac") ? "Mac OS X" : s.toLowerCase().includes("linux") ? "Linux" : "Unknown";
189
+ }, r = e.presenter;
190
+ return {
191
+ $os: `${n()}`,
192
+ isMobile: `${t() == "Mobile"}`,
193
+ browser: navigator.userAgent,
194
+ origin: window.location.origin,
195
+ agentType: he(r),
196
+ agentVoice: {
197
+ voiceId: (o = (i = e.presenter) == null ? void 0 : i.voice) == null ? void 0 : o.voice_id,
198
+ provider: (a = (c = e.presenter) == null ? void 0 : c.voice) == null ? void 0 : a.type
199
+ }
200
+ };
201
+ }
202
+ function Ke(e) {
203
+ var n, r, i, o, c, a;
204
+ const t = (n = e.llm) == null ? void 0 : n.prompt_customization;
205
+ return {
206
+ agentType: he(e.presenter),
207
+ owner_id: e.owner_id ?? "",
208
+ promptVersion: (r = e.llm) == null ? void 0 : r.prompt_version,
209
+ behavior: {
210
+ role: t == null ? void 0 : t.role,
211
+ personality: t == null ? void 0 : t.personality,
212
+ instructions: (i = e.llm) == null ? void 0 : i.instructions
213
+ },
214
+ temperature: (o = e.llm) == null ? void 0 : o.temperature,
215
+ knowledgeSource: t == null ? void 0 : t.knowledge_source,
216
+ starterQuestionsCount: (a = (c = e.knowledge) == null ? void 0 : c.starter_message) == null ? void 0 : a.length,
217
+ topicsToAvoid: t == null ? void 0 : t.topics_to_avoid,
218
+ maxResponseLength: t == null ? void 0 : t.max_response_length,
219
+ agentId: e.id,
220
+ access: e.access,
221
+ name: e.preview_name,
222
+ ...e.access === "public" ? { from: "agent-template" } : {}
223
+ };
224
+ }
225
+ const Ue = (e) => e.reduce((t, n) => t + n, 0), ie = (e) => Ue(e) / e.length;
226
+ function He(e, t, n) {
227
+ var s, d, l;
228
+ const { event: r, ...i } = e, { template: o } = (t == null ? void 0 : t.llm) || {}, { language: c } = ((s = t == null ? void 0 : t.presenter) == null ? void 0 : s.voice) || {};
229
+ return {
230
+ ...i,
231
+ llm: { ...i.llm, template: o },
232
+ script: { ...i.script, provider: { ...(d = i == null ? void 0 : i.script) == null ? void 0 : d.provider, language: c } },
233
+ stitch: (t == null ? void 0 : t.presenter.type) === "talk" ? (l = t == null ? void 0 : t.presenter) == null ? void 0 : l.stitch : void 0,
234
+ ...n
235
+ };
236
+ }
237
+ let te = {};
238
+ const qe = "https://api-js.mixpanel.com/track/?verbose=1&ip=1";
239
+ function Ve(e) {
240
+ const t = window != null && window.hasOwnProperty("DID_AGENTS_API") ? "agents-ui" : "agents-sdk";
241
+ return {
242
+ token: e.token || "testKey",
243
+ distinct_id: e.distinctId || ue(),
244
+ agentId: e.agentId,
245
+ additionalProperties: {},
246
+ isEnabled: e.isEnabled ?? !0,
247
+ getRandom: V,
248
+ enrich(n) {
249
+ this.additionalProperties = { ...this.additionalProperties, ...n };
250
+ },
251
+ async track(n, r) {
252
+ if (!this.isEnabled)
253
+ return Promise.resolve();
254
+ const { audioPath: i, ...o } = r || {}, c = {
255
+ method: "POST",
256
+ headers: {
257
+ "Content-Type": "application/x-www-form-urlencoded"
258
+ },
259
+ body: new URLSearchParams({
260
+ data: JSON.stringify([
261
+ {
262
+ event: n,
263
+ properties: {
264
+ ...this.additionalProperties,
265
+ ...o,
266
+ agentId: this.agentId,
267
+ source: t,
268
+ token: this.token,
269
+ time: Date.now(),
270
+ $insert_id: this.getRandom(),
271
+ origin: window.location.href,
272
+ "Screen Height": window.screen.height || window.innerWidth,
273
+ "Screen Width": window.screen.width || window.innerHeight,
274
+ "User Agent": navigator.userAgent
275
+ }
276
+ }
277
+ ])
278
+ })
279
+ };
280
+ try {
281
+ return await fetch(qe, c).then((a) => a.json());
282
+ } catch (a) {
283
+ return console.error(a);
284
+ }
285
+ },
286
+ linkTrack(n, r, i, o) {
287
+ te[n] || (te[n] = { events: {}, resolvedDependencies: [] }), o.includes(i) || o.push(i);
288
+ const c = te[n];
289
+ if (c.events[i] = { props: r }, c.resolvedDependencies.push(i), o.every(
290
+ (s) => c.resolvedDependencies.includes(s)
291
+ )) {
292
+ const s = o.reduce((d, l) => c.events[l] ? { ...d, ...c.events[l].props } : d, {});
293
+ this.track(n, s), c.resolvedDependencies = c.resolvedDependencies.filter(
294
+ (d) => !o.includes(d)
295
+ ), o.forEach((d) => {
296
+ delete c.events[d];
297
+ });
298
+ }
299
+ }
300
+ };
301
+ }
302
+ function we() {
303
+ let e = 0;
304
+ return {
305
+ reset: () => e = 0,
306
+ update: () => e = Date.now(),
307
+ get: (t = !1) => t ? Date.now() - e : e
308
+ };
309
+ }
310
+ const B = we(), ne = we();
311
+ function pe(e) {
312
+ return e === E.Playground ? { headers: { [Be]: "true" } } : {};
313
+ }
314
+ async function ye(e, t, n, r, i = !1, o) {
315
+ try {
316
+ return !o && !le(r) && (o = await t.newChat(e.id, { persist: i }, pe(r)), n.track("agent-chat", {
317
+ event: "created",
318
+ chatId: o.id,
319
+ mode: r
320
+ })), { chat: o, chatMode: (o == null ? void 0 : o.chat_mode) ?? r };
321
+ } catch (c) {
322
+ try {
323
+ const a = JSON.parse(c.message);
324
+ if ((a == null ? void 0 : a.kind) === "InsufficientCreditsError")
325
+ throw new Error("InsufficientCreditsError");
326
+ } catch (a) {
327
+ console.error("Error parsing the error message:", a);
328
+ }
329
+ throw new Error("Cannot create new chat");
330
+ }
331
+ }
332
+ function Oe(e) {
333
+ return e && e.length > 0 ? e : [];
334
+ }
335
+ function Xe(e, t, n) {
336
+ if (!e)
337
+ throw new Error("Please connect to the agent first");
338
+ if (!e.interruptAvailable)
339
+ throw new Error("Interrupt is not enabled for this stream");
340
+ if (t !== N.Fluent)
341
+ throw new Error("Interrupt only available for Fluent streams");
342
+ if (!n)
343
+ throw new Error("No active video to interrupt");
344
+ }
345
+ async function Ye(e, t) {
346
+ const n = {
347
+ type: A.StreamInterrupt,
348
+ videoId: t,
349
+ timestamp: Date.now()
350
+ };
351
+ e.sendDataChannelMessage(JSON.stringify(n));
352
+ }
353
+ function Qe(e) {
354
+ return new Promise((t, n) => {
355
+ const { callbacks: r, host: i, auth: o } = e, { onMessage: c = null, onOpen: a = null, onClose: s = null, onError: d = null } = r || {}, l = new WebSocket(`${i}?authorization=${fe(o)}`);
356
+ l.onmessage = c, l.onclose = s, l.onerror = (v) => {
357
+ console.error(v), d == null || d("Websocket failed to connect", v), n(v);
358
+ }, l.onopen = (v) => {
359
+ a == null || a(v), t(l);
360
+ };
361
+ });
362
+ }
363
+ async function Ze(e) {
364
+ const { retries: t = 1 } = e;
365
+ let n = null;
366
+ for (let r = 0; (n == null ? void 0 : n.readyState) !== WebSocket.OPEN; r++)
367
+ try {
368
+ n = await Qe(e);
369
+ } catch (i) {
370
+ if (r === t)
371
+ throw i;
372
+ await de(r * 500);
373
+ }
374
+ return n;
375
+ }
376
+ async function Ge(e, t, n) {
377
+ const r = n != null && n.onMessage ? [n.onMessage] : [], i = await Ze({
378
+ auth: e,
379
+ host: t,
380
+ callbacks: {
381
+ onError: (o) => {
382
+ var c;
383
+ return (c = n.onError) == null ? void 0 : c.call(n, new Re(o));
384
+ },
385
+ onMessage(o) {
386
+ const c = JSON.parse(o.data);
387
+ r.forEach((a) => a(c.event, c));
388
+ }
389
+ }
390
+ });
391
+ return {
392
+ socket: i,
393
+ disconnect: () => i.close(),
394
+ subscribeToEvents: (o) => r.push(o)
395
+ };
396
+ }
397
+ function et(e) {
398
+ if (e.answer !== void 0)
399
+ return e.answer;
400
+ let t = 0, n = "";
401
+ for (; t in e; )
402
+ n += e[t++];
403
+ return n;
404
+ }
405
+ function tt(e, t, n, r, i) {
406
+ const o = r.messages[r.messages.length - 1];
407
+ if (!(e === q.Partial || e === q.Answer) || (o == null ? void 0 : o.role) !== "assistant")
408
+ return;
409
+ const { content: c, sequence: a } = t;
410
+ e === q.Partial ? n[a] = c : n.answer = c;
411
+ const s = et(n);
412
+ (o.content !== s || e === q.Answer) && (o.content = s, i == null || i([...r.messages], e));
413
+ }
414
+ function rt(e, t, n, r, i) {
415
+ let o = {};
416
+ return {
417
+ clearQueue: () => o = {},
418
+ onMessage: (c, a) => {
419
+ var s, d;
420
+ if ("content" in a)
421
+ tt(c, a, o, t, n.callbacks.onNewMessage), c === q.Answer && e.track("agent-message-received", {
422
+ messages: t.messages.length,
423
+ mode: t.chatMode
424
+ });
425
+ else {
426
+ const l = A, v = [l.StreamVideoDone, l.StreamVideoError, l.StreamVideoRejected], M = [l.StreamFailed, l.StreamVideoError, l.StreamVideoRejected], T = He(a, r, { mode: t.chatMode });
427
+ if (c = c, c === l.StreamVideoCreated)
428
+ e.linkTrack("agent-video", T, l.StreamVideoCreated, ["start"]);
429
+ else if (v.includes(c)) {
430
+ const b = c.split("/")[1];
431
+ M.includes(c) ? e.track("agent-video", { ...T, event: b }) : e.linkTrack("agent-video", { ...T, event: b }, c, ["done"]);
432
+ }
433
+ M.includes(c) && ((d = (s = n.callbacks).onError) == null || d.call(s, new Error(`Stream failed with event ${c}`), { data: a })), a.event === l.StreamDone && i();
434
+ }
435
+ }
436
+ };
437
+ }
438
+ function nt(e, t, n, r) {
439
+ const i = me(e, `${t}/agents/${n}`, r);
440
+ return {
441
+ createStream(o) {
442
+ return i.post("/streams", o);
443
+ },
444
+ startConnection(o, c, a) {
445
+ return i.post(`/streams/${o}/sdp`, {
446
+ session_id: a,
447
+ answer: c
448
+ });
449
+ },
450
+ addIceCandidate(o, c, a) {
451
+ return i.post(`/streams/${o}/ice`, {
452
+ session_id: a,
453
+ ...c
454
+ });
455
+ },
456
+ sendStreamRequest(o, c, a) {
457
+ return i.post(`/streams/${o}`, {
458
+ session_id: c,
459
+ ...a
460
+ });
461
+ },
462
+ close(o, c) {
463
+ return i.delete(`/streams/${o}`, { session_id: c });
464
+ }
465
+ };
466
+ }
467
+ const at = (e, t) => (n, r) => e && console.log(`[${t}] ${n}`, r ?? "");
468
+ function it(e, t, n) {
469
+ const r = (t.timestamp - e.timestamp) / 1e3;
470
+ return {
471
+ duration: r,
472
+ bytesReceived: t.bytesReceived - e.bytesReceived,
473
+ bitrate: Math.round((t.bytesReceived - e.bytesReceived) * 8 / r),
474
+ packetsReceived: t.packetsReceived - e.packetsReceived,
475
+ packetsLost: t.packetsLost - e.packetsLost,
476
+ framesDropped: t.framesDropped - e.framesDropped,
477
+ framesDecoded: t.framesDecoded - e.framesDecoded,
478
+ jitter: t.jitter,
479
+ avgJitterDelayInInterval: (t.jitterBufferDelay - e.jitterBufferDelay) / (t.jitterBufferEmittedCount - e.jitterBufferEmittedCount),
480
+ jitterBufferEmittedCount: t.jitterBufferEmittedCount - e.jitterBufferEmittedCount,
481
+ jitterBufferDelay: (t.jitterBufferDelay - e.jitterBufferDelay) / r,
482
+ framesPerSecond: t.framesPerSecond,
483
+ freezeCount: t.freezeCount - e.freezeCount,
484
+ freezeDuration: t.freezeDuration - e.freezeDuration,
485
+ lowFpsCount: n
486
+ };
487
+ }
488
+ function st(e) {
489
+ return e.filter(
490
+ (t) => t.freezeCount > 0 || t.framesPerSecond < 21 || t.framesDropped > 0 || t.packetsLost > 0
491
+ ).map((t) => {
492
+ const { timestamp: n, ...r } = t, i = [];
493
+ return t.freezeCount > 0 && i.push("freeze"), t.framesPerSecond < 21 && i.push("low fps"), t.framesDropped > 0 && i.push("frames dropped"), t.packetsLost > 0 && i.push("packet loss"), {
494
+ ...r,
495
+ causes: i
496
+ };
497
+ });
498
+ }
499
+ function ot(e) {
500
+ let t = "", n = 0;
501
+ for (const r of e.values())
502
+ if (r && r.type === "codec" && r.mimeType.startsWith("video") && (t = r.mimeType.split("/")[1]), r && r.type === "candidate-pair" && (n = r.currentRoundTripTime), r && r.type === "inbound-rtp" && r.kind === "video")
503
+ return {
504
+ codec: t,
505
+ rtt: n,
506
+ timestamp: r.timestamp,
507
+ bytesReceived: r.bytesReceived,
508
+ packetsReceived: r.packetsReceived,
509
+ packetsLost: r.packetsLost,
510
+ framesDropped: r.framesDropped,
511
+ framesDecoded: r.framesDecoded,
512
+ jitter: r.jitter,
513
+ jitterBufferDelay: r.jitterBufferDelay,
514
+ jitterBufferEmittedCount: r.jitterBufferEmittedCount,
515
+ avgJitterDelayInInterval: r.jitterBufferDelay / r.jitterBufferEmittedCount,
516
+ frameWidth: r.frameWidth,
517
+ frameHeight: r.frameHeight,
518
+ framesPerSecond: r.framesPerSecond,
519
+ freezeCount: r.freezeCount,
520
+ freezeDuration: r.totalFreezesDuration
521
+ };
522
+ return {};
523
+ }
524
+ function ct(e, t, n) {
525
+ const r = e.map((s, d) => d === 0 ? n ? {
526
+ timestamp: s.timestamp,
527
+ duration: 0,
528
+ rtt: s.rtt,
529
+ bytesReceived: s.bytesReceived - n.bytesReceived,
530
+ bitrate: (s.bytesReceived - n.bytesReceived) * 8 / (t / 1e3),
531
+ packetsReceived: s.packetsReceived - n.packetsReceived,
532
+ packetsLost: s.packetsLost - n.packetsLost,
533
+ framesDropped: s.framesDropped - n.framesDropped,
534
+ framesDecoded: s.framesDecoded - n.framesDecoded,
535
+ jitter: s.jitter,
536
+ jitterBufferDelay: s.jitterBufferDelay - n.jitterBufferDelay,
537
+ jitterBufferEmittedCount: s.jitterBufferEmittedCount - n.jitterBufferEmittedCount,
538
+ avgJitterDelayInInterval: (s.jitterBufferDelay - n.jitterBufferDelay) / (s.jitterBufferEmittedCount - n.jitterBufferEmittedCount),
539
+ framesPerSecond: s.framesPerSecond,
540
+ freezeCount: s.freezeCount - n.freezeCount,
541
+ freezeDuration: s.freezeDuration - n.freezeDuration
542
+ } : {
543
+ timestamp: s.timestamp,
544
+ rtt: s.rtt,
545
+ duration: 0,
546
+ bytesReceived: s.bytesReceived,
547
+ bitrate: s.bytesReceived * 8 / (t / 1e3),
548
+ packetsReceived: s.packetsReceived,
549
+ packetsLost: s.packetsLost,
550
+ framesDropped: s.framesDropped,
551
+ framesDecoded: s.framesDecoded,
552
+ jitter: s.jitter,
553
+ jitterBufferDelay: s.jitterBufferDelay,
554
+ jitterBufferEmittedCount: s.jitterBufferEmittedCount,
555
+ avgJitterDelayInInterval: s.jitterBufferDelay / s.jitterBufferEmittedCount,
556
+ framesPerSecond: s.framesPerSecond,
557
+ freezeCount: s.freezeCount,
558
+ freezeDuration: s.freezeDuration
559
+ } : {
560
+ timestamp: s.timestamp,
561
+ duration: t * d / 1e3,
562
+ rtt: s.rtt,
563
+ bytesReceived: s.bytesReceived - e[d - 1].bytesReceived,
564
+ bitrate: (s.bytesReceived - e[d - 1].bytesReceived) * 8 / (t / 1e3),
565
+ packetsReceived: s.packetsReceived - e[d - 1].packetsReceived,
566
+ packetsLost: s.packetsLost - e[d - 1].packetsLost,
567
+ framesDropped: s.framesDropped - e[d - 1].framesDropped,
568
+ framesDecoded: s.framesDecoded - e[d - 1].framesDecoded,
569
+ jitter: s.jitter,
570
+ jitterBufferDelay: s.jitterBufferDelay - e[d - 1].jitterBufferDelay,
571
+ jitterBufferEmittedCount: s.jitterBufferEmittedCount - e[d - 1].jitterBufferEmittedCount,
572
+ avgJitterDelayInInterval: (s.jitterBufferDelay - e[d - 1].jitterBufferDelay) / (s.jitterBufferEmittedCount - e[d - 1].jitterBufferEmittedCount),
573
+ framesPerSecond: s.framesPerSecond,
574
+ freezeCount: s.freezeCount - e[d - 1].freezeCount,
575
+ freezeDuration: s.freezeDuration - e[d - 1].freezeDuration
576
+ }), i = st(r), o = i.reduce((s, d) => s + (d.causes.includes("low fps") ? 1 : 0), 0), c = r.filter((s) => !!s.avgJitterDelayInInterval).map((s) => s.avgJitterDelayInInterval), a = r.filter((s) => !!s.rtt).map((s) => s.rtt);
577
+ return {
578
+ webRTCStats: {
579
+ anomalies: i,
580
+ minRtt: Math.min(...a),
581
+ avgRtt: ie(a),
582
+ maxRtt: Math.max(...a),
583
+ aggregateReport: it(e[0], e[e.length - 1], o),
584
+ minJitterDelayInInterval: Math.min(...c),
585
+ maxJitterDelayInInterval: Math.max(...c),
586
+ avgJitterDelayInInterval: ie(c)
587
+ },
588
+ codec: e[0].codec,
589
+ resolution: `${e[0].frameWidth}x${e[0].frameHeight}`
590
+ };
591
+ }
592
+ const ae = 100, dt = Math.max(Math.ceil(400 / ae), 1), lt = 0.25, ut = 0.28;
593
+ function ft() {
594
+ let e = 0, t, n, r = 0;
595
+ return (i) => {
596
+ for (const o of i.values())
597
+ if (o && o.type === "inbound-rtp" && o.kind === "video") {
598
+ const c = o.jitterBufferDelay, a = o.jitterBufferEmittedCount;
599
+ if (n && a > n) {
600
+ const l = c - t, v = a - n;
601
+ r = l / v;
602
+ }
603
+ t = c, n = a;
604
+ const s = o.framesDecoded, d = s - e > 0;
605
+ return e = s, { isReceiving: d, avgJitterDelayInInterval: r, freezeCount: o.freezeCount };
606
+ }
607
+ return { isReceiving: !1, avgJitterDelayInInterval: r };
608
+ };
609
+ }
610
+ function mt(e, t, n, r, i, o = !1) {
611
+ let c = [], a, s = 0, d = !1, l = Z.Unknown, v = Z.Unknown, M = 0, T = 0;
612
+ const b = ft();
613
+ return setInterval(async () => {
614
+ const F = await e.getStats(), { isReceiving: K, avgJitterDelayInInterval: J, freezeCount: R } = b(F), U = ot(F);
615
+ if (K)
616
+ s = 0, M = R - T, v = J < lt ? Z.Strong : J > ut && M > 1 ? Z.Weak : l, v !== l && (i == null || i(v), l = v, T += M, M = 0), d || (r == null || r(w.Start), a = c[c.length - 1], c = [], d = !0), c.push(U);
617
+ else if (d && (s++, s >= dt)) {
618
+ const u = ct(c, ae, a);
619
+ r == null || r(w.Stop, u), t() || n(), T = R, d = !1;
620
+ }
621
+ }, ae);
622
+ }
623
+ const gt = (window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection).bind(window);
624
+ function se(e) {
625
+ switch (e) {
626
+ case "connected":
627
+ return S.Connected;
628
+ case "checking":
629
+ return S.Connecting;
630
+ case "failed":
631
+ return S.Fail;
632
+ case "new":
633
+ return S.New;
634
+ case "closed":
635
+ return S.Closed;
636
+ case "disconnected":
637
+ return S.Disconnected;
638
+ case "completed":
639
+ return S.Completed;
640
+ default:
641
+ return S.New;
642
+ }
643
+ }
644
+ const ht = (e) => (t) => {
645
+ const [n, r = ""] = t.split(/:(.+)/);
646
+ try {
647
+ const i = JSON.parse(r);
648
+ return e("parsed data channel message", { subject: n, data: i }), { subject: n, data: i };
649
+ } catch (i) {
650
+ return e("Failed to parse data channel message, returning data as string", { subject: n, rawData: r, error: i }), { subject: n, data: r };
651
+ }
652
+ };
653
+ function wt({
654
+ statsSignal: e,
655
+ dataChannelSignal: t,
656
+ onVideoStateChange: n,
657
+ report: r
658
+ }) {
659
+ e === w.Start && t === w.Start ? n == null || n(w.Start) : e === w.Stop && t === w.Stop && (n == null || n(w.Stop, r));
660
+ }
661
+ function pt({
662
+ statsSignal: e,
663
+ dataChannelSignal: t,
664
+ onVideoStateChange: n,
665
+ onAgentActivityStateChange: r,
666
+ report: i
667
+ }) {
668
+ e === w.Start ? n == null || n(w.Start) : e === w.Stop && (n == null || n(w.Stop, i)), t === w.Start ? r == null || r(O.Talking) : t === w.Stop && (r == null || r(O.Idle));
669
+ }
670
+ function oe({
671
+ statsSignal: e,
672
+ dataChannelSignal: t,
673
+ onVideoStateChange: n,
674
+ onAgentActivityStateChange: r,
675
+ streamType: i,
676
+ report: o
677
+ }) {
678
+ i === N.Legacy ? wt({ statsSignal: e, dataChannelSignal: t, onVideoStateChange: n, report: o }) : i === N.Fluent && pt({
679
+ statsSignal: e,
680
+ dataChannelSignal: t,
681
+ onVideoStateChange: n,
682
+ onAgentActivityStateChange: r,
683
+ report: o
684
+ });
685
+ }
686
+ async function yt(e, t, { debug: n = !1, callbacks: r, auth: i, baseURL: o = G, analytics: c }) {
687
+ var X;
688
+ const a = at(n, "WebRTCStreamingManager"), s = ht(a);
689
+ let d = !1, l = !1, v = w.Stop, M = w.Stop;
690
+ const { startConnection: T, sendStreamRequest: b, close: F, createStream: K, addIceCandidate: J } = nt(
691
+ i,
692
+ o,
693
+ e,
694
+ r.onError
695
+ ), {
696
+ id: R,
697
+ offer: U,
698
+ ice_servers: u,
699
+ session_id: h,
700
+ fluent: p,
701
+ interrupt_enabled: _
702
+ } = await K(t);
703
+ (X = r.onStreamCreated) == null || X.call(r, { stream_id: R, session_id: h, agent_id: e });
704
+ const m = new gt({ iceServers: u }), y = m.createDataChannel("JanusDataChannel");
705
+ if (!h)
706
+ throw new Error("Could not create session_id");
707
+ const C = p ? N.Fluent : N.Legacy;
708
+ c.enrich({
709
+ "stream-type": C
710
+ });
711
+ const P = t.stream_warmup && !p, $ = () => d, k = () => {
712
+ var f;
713
+ d = !0, l && ((f = r.onConnectionStateChange) == null || f.call(r, S.Connected));
714
+ }, I = mt(
715
+ m,
716
+ $,
717
+ k,
718
+ (f, g) => oe({
719
+ statsSignal: M = f,
720
+ dataChannelSignal: C === N.Legacy ? v : void 0,
721
+ onVideoStateChange: r.onVideoStateChange,
722
+ onAgentActivityStateChange: r.onAgentActivityStateChange,
723
+ report: g,
724
+ streamType: C
725
+ }),
726
+ (f) => {
727
+ var g;
728
+ return (g = r.onConnectivityStateChange) == null ? void 0 : g.call(r, f);
729
+ },
730
+ P
731
+ );
732
+ m.onicecandidate = (f) => {
733
+ var g;
734
+ a("peerConnection.onicecandidate", f);
735
+ try {
736
+ f.candidate && f.candidate.sdpMid && f.candidate.sdpMLineIndex !== null ? J(
737
+ R,
738
+ {
739
+ candidate: f.candidate.candidate,
740
+ sdpMid: f.candidate.sdpMid,
741
+ sdpMLineIndex: f.candidate.sdpMLineIndex
742
+ },
743
+ h
744
+ ) : J(R, { candidate: null }, h);
745
+ } catch (j) {
746
+ (g = r.onError) == null || g.call(r, j, { streamId: R });
747
+ }
748
+ }, y.onopen = () => {
749
+ l = !0, (!P || d) && k();
750
+ };
751
+ const D = (f) => {
752
+ var g;
753
+ (g = r.onVideoIdChange) == null || g.call(r, f);
754
+ };
755
+ function z(f, g) {
756
+ if (f === A.StreamStarted && typeof g == "object" && "metadata" in g) {
757
+ const j = g.metadata;
758
+ D(j.videoId);
759
+ }
760
+ f === A.StreamDone && D(null), v = f === A.StreamStarted ? w.Start : w.Stop, oe({
761
+ statsSignal: C === N.Legacy ? M : void 0,
762
+ dataChannelSignal: v,
763
+ onVideoStateChange: r.onVideoStateChange,
764
+ onAgentActivityStateChange: r.onAgentActivityStateChange,
765
+ streamType: C
766
+ });
767
+ }
768
+ function x(f, g) {
769
+ const j = typeof g == "string" ? g : g == null ? void 0 : g.metadata;
770
+ j && c.enrich({ streamMetadata: j }), c.track("agent-chat", { event: "ready" });
771
+ }
772
+ const L = {
773
+ [A.StreamStarted]: z,
774
+ [A.StreamDone]: z,
775
+ [A.StreamReady]: x
776
+ };
777
+ y.onmessage = (f) => {
778
+ var Y;
779
+ const { subject: g, data: j } = s(f.data);
780
+ (Y = L[g]) == null || Y.call(L, g, j);
781
+ }, m.oniceconnectionstatechange = () => {
782
+ var g;
783
+ a("peerConnection.oniceconnectionstatechange => " + m.iceConnectionState);
784
+ const f = se(m.iceConnectionState);
785
+ f !== S.Connected && ((g = r.onConnectionStateChange) == null || g.call(r, f));
786
+ }, m.ontrack = (f) => {
787
+ var g;
788
+ a("peerConnection.ontrack", f), (g = r.onSrcObjectReady) == null || g.call(r, f.streams[0]);
789
+ }, await m.setRemoteDescription(U), a("set remote description OK");
790
+ const W = await m.createAnswer();
791
+ return a("create answer OK"), await m.setLocalDescription(W), a("set local description OK"), await T(R, W, h), a("start connection OK"), {
792
+ /**
793
+ * Method to send request to server to get clip or talk depend on you payload
794
+ * @param payload
795
+ */
796
+ speak(f) {
797
+ return b(R, h, f);
798
+ },
799
+ /**
800
+ * Method to close RTC connection
801
+ */
802
+ async disconnect() {
803
+ var f;
804
+ if (R) {
805
+ const g = se(m.iceConnectionState);
806
+ if (m) {
807
+ if (g === S.New) {
808
+ clearInterval(I);
809
+ return;
810
+ }
811
+ m.close(), m.oniceconnectionstatechange = null, m.onnegotiationneeded = null, m.onicecandidate = null, m.ontrack = null;
812
+ }
813
+ try {
814
+ g === S.Connected && await F(R, h).catch((j) => {
815
+ });
816
+ } catch (j) {
817
+ a("Error on close stream connection", j);
818
+ }
819
+ (f = r.onAgentActivityStateChange) == null || f.call(r, O.Idle), clearInterval(I);
820
+ }
821
+ },
822
+ /**
823
+ * Method to send data channel messages to the server
824
+ */
825
+ sendDataChannelMessage(f) {
826
+ var g, j;
827
+ if (!d || y.readyState !== "open") {
828
+ a("Data channel is not ready for sending messages"), (g = r.onError) == null || g.call(r, new Error("Data channel is not ready for sending messages"), {
829
+ streamId: R
830
+ });
831
+ return;
832
+ }
833
+ try {
834
+ y.send(f);
835
+ } catch (Y) {
836
+ a("Error sending data channel message", Y), (j = r.onError) == null || j.call(r, Y, { streamId: R });
837
+ }
838
+ },
839
+ /**
840
+ * Session identifier information, should be returned in the body of all streaming requests
841
+ */
842
+ sessionId: h,
843
+ /**
844
+ * Id of current RTC stream
845
+ */
846
+ streamId: R,
847
+ streamType: C,
848
+ interruptAvailable: _ ?? !1
849
+ };
850
+ }
851
+ const vt = (e) => e.presenter.type === ce.Expressive;
852
+ async function kt(e, t, n) {
853
+ const r = e.id;
854
+ if (vt(e)) {
855
+ const { createLiveKitStreamingManager: i } = await import("./livekit-manager-6i5Rpchn.js");
856
+ return i(r, t, n);
857
+ } else
858
+ return yt(r, t, n);
859
+ }
860
+ function Dt(e) {
861
+ const { streamOptions: t } = e ?? {};
862
+ return {
863
+ output_resolution: t == null ? void 0 : t.outputResolution,
864
+ session_timeout: t == null ? void 0 : t.sessionTimeout,
865
+ stream_warmup: t == null ? void 0 : t.streamWarmup,
866
+ compatibility_mode: t == null ? void 0 : t.compatibilityMode,
867
+ fluent: t == null ? void 0 : t.fluent
868
+ };
869
+ }
870
+ function Ct(e, t, n, r, i) {
871
+ i === N.Fluent ? Rt(e, t, n, r, i) : It(e, t, n, r, i);
872
+ }
873
+ function Rt(e, t, n, r, i) {
874
+ e === w.Start ? r.track("stream-session", { event: "start", "stream-type": i }) : e === w.Stop && r.track("stream-session", {
875
+ event: "stop",
876
+ is_greenscreen: t.presenter.type === "clip" && t.presenter.is_greenscreen,
877
+ background: t.presenter.type === "clip" && t.presenter.background,
878
+ "stream-type": i,
879
+ ...n
880
+ });
881
+ }
882
+ function St(e, t, n, r) {
883
+ B.get() <= 0 || (e === w.Start ? n.linkTrack(
884
+ "agent-video",
885
+ { event: "start", latency: B.get(!0), "stream-type": r },
886
+ "start",
887
+ [A.StreamVideoCreated]
888
+ ) : e === w.Stop && n.linkTrack(
889
+ "agent-video",
890
+ {
891
+ event: "stop",
892
+ is_greenscreen: t.presenter.type === "clip" && t.presenter.is_greenscreen,
893
+ background: t.presenter.type === "clip" && t.presenter.background,
894
+ "stream-type": r
895
+ },
896
+ "done",
897
+ [A.StreamVideoDone]
898
+ ));
899
+ }
900
+ function It(e, t, n, r, i) {
901
+ B.get() <= 0 || (e === w.Start ? r.linkTrack(
902
+ "agent-video",
903
+ { event: "start", latency: B.get(!0), "stream-type": i },
904
+ "start",
905
+ [A.StreamVideoCreated]
906
+ ) : e === w.Stop && r.linkTrack(
907
+ "agent-video",
908
+ {
909
+ event: "stop",
910
+ is_greenscreen: t.presenter.type === "clip" && t.presenter.is_greenscreen,
911
+ background: t.presenter.type === "clip" && t.presenter.background,
912
+ "stream-type": i,
913
+ ...n
914
+ },
915
+ "done",
916
+ [A.StreamVideoDone]
917
+ ));
918
+ }
919
+ function Et(e, t, n) {
920
+ return B.reset(), new Promise(async (r, i) => {
921
+ try {
922
+ let o;
923
+ o = await kt(e, Dt(t), {
924
+ ...t,
925
+ analytics: n,
926
+ callbacks: {
927
+ ...t.callbacks,
928
+ onConnectionStateChange: (c) => {
929
+ var a, s;
930
+ (s = (a = t.callbacks).onConnectionStateChange) == null || s.call(a, c), c === S.Connected && r(o);
931
+ },
932
+ onVideoStateChange: (c, a) => {
933
+ var s, d;
934
+ (d = (s = t.callbacks).onVideoStateChange) == null || d.call(s, c), Ct(
935
+ c,
936
+ e,
937
+ a,
938
+ n,
939
+ o.streamType
940
+ );
941
+ },
942
+ onAgentActivityStateChange: (c) => {
943
+ var a, s;
944
+ (s = (a = t.callbacks).onAgentActivityStateChange) == null || s.call(a, c), c === O.Talking ? ne.update() : ne.reset(), St(
945
+ c === O.Talking ? w.Start : w.Stop,
946
+ e,
947
+ n,
948
+ o.streamType
949
+ );
950
+ }
951
+ }
952
+ });
953
+ } catch (o) {
954
+ i(o);
955
+ }
956
+ });
957
+ }
958
+ async function Mt(e, t, n, r, i) {
959
+ var v, M, T, b;
960
+ const o = ye(e, n, r, t.mode, t.persistentChat, i), c = Et(e, t, r), [a, s] = await Promise.all([o, c]), { chat: d, chatMode: l } = a;
961
+ return l && l !== t.mode && (t.mode = l, (M = (v = t.callbacks).onModeChange) == null || M.call(v, l), l !== E.Functional) ? ((b = (T = t.callbacks).onError) == null || b.call(T, new Ce(l)), s == null || s.disconnect(), { chat: d }) : { chat: d, streamingManager: s };
962
+ }
963
+ async function jt(e, t) {
964
+ var J, R, U;
965
+ let n = !0, r = null;
966
+ const i = t.mixpanelKey || ze, o = t.wsURL || $e, c = t.baseURL || G, a = {
967
+ messages: [],
968
+ chatMode: t.mode || E.Functional
969
+ }, s = Ve({
970
+ token: i,
971
+ agentId: e,
972
+ isEnabled: t.enableAnalitics,
973
+ distinctId: t.distinctId
974
+ });
975
+ s.track("agent-sdk", { event: "init" });
976
+ const d = ge(t.auth, c, t.callbacks.onError), l = await d.getById(e);
977
+ s.enrich(Ke(l));
978
+ const { onMessage: v, clearQueue: M } = rt(
979
+ s,
980
+ a,
981
+ t,
982
+ l,
983
+ () => {
984
+ var u;
985
+ return (u = a.socketManager) == null ? void 0 : u.disconnect();
986
+ }
987
+ );
988
+ a.messages = Oe(t.initialMessages), (R = (J = t.callbacks).onNewMessage) == null || R.call(J, [...a.messages], "answer");
989
+ const T = (u) => {
990
+ r = u;
991
+ };
992
+ s.track("agent-sdk", { event: "loaded", ...We(l) });
993
+ async function b(u) {
994
+ var C, P, $, k, I, D, z;
995
+ (P = (C = t.callbacks).onConnectionStateChange) == null || P.call(C, S.Connecting), B.reset(), u && !n && (delete a.chat, (k = ($ = t.callbacks).onNewMessage) == null || k.call($, [...a.messages], "answer"));
996
+ const h = t.mode === E.DirectPlayback ? Promise.resolve(void 0) : Ge(t.auth, o, { onMessage: v, onError: t.callbacks.onError }), p = re(
997
+ () => Mt(
998
+ l,
999
+ { ...t, callbacks: { ...t.callbacks, onVideoIdChange: T } },
1000
+ d,
1001
+ s,
1002
+ a.chat
1003
+ ),
1004
+ {
1005
+ limit: 3,
1006
+ timeout: Le,
1007
+ timeoutErrorMessage: "Timeout initializing the stream",
1008
+ // Retry on all errors except for connection errors and rate limit errors, these are already handled in client level.
1009
+ shouldRetryFn: (x) => (x == null ? void 0 : x.message) !== "Could not connect" && x.status !== 429,
1010
+ delayMs: 1e3
1011
+ }
1012
+ ).catch((x) => {
1013
+ var L, W;
1014
+ throw K(E.Maintenance), (W = (L = t.callbacks).onConnectionStateChange) == null || W.call(L, S.Fail), x;
1015
+ }), [_, { streamingManager: m, chat: y }] = await Promise.all([h, p]);
1016
+ y && y.id !== ((I = a.chat) == null ? void 0 : I.id) && ((z = (D = t.callbacks).onNewChat) == null || z.call(D, y.id)), a.streamingManager = m, a.socketManager = _, a.chat = y, n = !1, s.enrich({
1017
+ chatId: y == null ? void 0 : y.id,
1018
+ streamId: m == null ? void 0 : m.streamId,
1019
+ mode: a.chatMode
1020
+ }), K((y == null ? void 0 : y.chat_mode) ?? t.mode ?? E.Functional);
1021
+ }
1022
+ async function F() {
1023
+ var u, h, p, _;
1024
+ (u = a.socketManager) == null || u.disconnect(), await ((h = a.streamingManager) == null ? void 0 : h.disconnect()), delete a.streamingManager, delete a.socketManager, (_ = (p = t.callbacks).onConnectionStateChange) == null || _.call(p, S.Disconnected);
1025
+ }
1026
+ async function K(u) {
1027
+ var h, p;
1028
+ u !== a.chatMode && (s.track("agent-mode-change", { mode: u }), a.chatMode = u, a.chatMode !== E.Functional && await F(), (p = (h = t.callbacks).onModeChange) == null || p.call(h, u));
1029
+ }
1030
+ return {
1031
+ agent: l,
1032
+ getStreamType: () => {
1033
+ var u;
1034
+ return (u = a.streamingManager) == null ? void 0 : u.streamType;
1035
+ },
1036
+ getIsInterruptAvailable: () => {
1037
+ var u;
1038
+ return ((u = a.streamingManager) == null ? void 0 : u.interruptAvailable) ?? !1;
1039
+ },
1040
+ starterMessages: ((U = l.knowledge) == null ? void 0 : U.starter_message) || [],
1041
+ getSTTToken: () => d.getSTTToken(l.id),
1042
+ changeMode: K,
1043
+ enrichAnalytics: s.enrich,
1044
+ async connect() {
1045
+ await b(!0), s.track("agent-chat", {
1046
+ event: "connect",
1047
+ mode: a.chatMode
1048
+ });
1049
+ },
1050
+ async reconnect() {
1051
+ await F(), await b(!1), s.track("agent-chat", {
1052
+ event: "reconnect",
1053
+ mode: a.chatMode
1054
+ });
1055
+ },
1056
+ async disconnect() {
1057
+ await F(), s.track("agent-chat", {
1058
+ event: "disconnect",
1059
+ mode: a.chatMode
1060
+ });
1061
+ },
1062
+ async chat(u) {
1063
+ var m, y, C, P, $;
1064
+ const h = () => {
1065
+ if (le(t.mode))
1066
+ throw new H(`${t.mode} is enabled, chat is disabled`);
1067
+ if (u.length >= 800)
1068
+ throw new H("Message cannot be more than 800 characters");
1069
+ if (u.length === 0)
1070
+ throw new H("Message cannot be empty");
1071
+ if (a.chatMode === E.Maintenance)
1072
+ throw new H("Chat is in maintenance mode");
1073
+ if (![E.TextOnly, E.Playground].includes(a.chatMode)) {
1074
+ if (!a.streamingManager)
1075
+ throw new H("Streaming manager is not initialized");
1076
+ if (!a.chat)
1077
+ throw new H("Chat is not initialized");
1078
+ }
1079
+ }, p = async () => {
1080
+ var k, I;
1081
+ if (!a.chat) {
1082
+ const D = await ye(
1083
+ l,
1084
+ d,
1085
+ s,
1086
+ a.chatMode,
1087
+ t.persistentChat
1088
+ );
1089
+ if (!D.chat)
1090
+ throw new De(a.chatMode, !!t.persistentChat);
1091
+ a.chat = D.chat, (I = (k = t.callbacks).onNewChat) == null || I.call(k, a.chat.id);
1092
+ }
1093
+ return a.chat.id;
1094
+ }, _ = async (k, I) => re(
1095
+ () => {
1096
+ var D, z;
1097
+ return d.chat(
1098
+ l.id,
1099
+ I,
1100
+ {
1101
+ chatMode: a.chatMode,
1102
+ streamId: (D = a.streamingManager) == null ? void 0 : D.streamId,
1103
+ sessionId: (z = a.streamingManager) == null ? void 0 : z.sessionId,
1104
+ messages: k.map(({ matches: x, ...L }) => L)
1105
+ },
1106
+ {
1107
+ ...pe(a.chatMode),
1108
+ skipErrorHandler: !0
1109
+ }
1110
+ );
1111
+ },
1112
+ {
1113
+ limit: 2,
1114
+ shouldRetryFn: (D) => {
1115
+ var L, W, X, f;
1116
+ const z = (L = D == null ? void 0 : D.message) == null ? void 0 : L.includes("missing or invalid session_id");
1117
+ return !((W = D == null ? void 0 : D.message) == null ? void 0 : W.includes("Stream Error")) && !z ? ((f = (X = t.callbacks).onError) == null || f.call(X, D), !1) : !0;
1118
+ },
1119
+ onRetry: async () => {
1120
+ await F(), await b(!1);
1121
+ }
1122
+ }
1123
+ );
1124
+ try {
1125
+ M(), h(), a.messages.push({
1126
+ id: V(),
1127
+ role: "user",
1128
+ content: u,
1129
+ created_at: new Date(B.update()).toISOString()
1130
+ }), (y = (m = t.callbacks).onNewMessage) == null || y.call(m, [...a.messages], "user");
1131
+ const k = await p(), I = await _([...a.messages], k);
1132
+ return a.messages.push({
1133
+ id: V(),
1134
+ role: "assistant",
1135
+ content: I.result || "",
1136
+ created_at: (/* @__PURE__ */ new Date()).toISOString(),
1137
+ context: I.context,
1138
+ matches: I.matches
1139
+ }), s.track("agent-message-send", {
1140
+ event: "success",
1141
+ messages: a.messages.length + 1
1142
+ }), I.result && ((P = (C = t.callbacks).onNewMessage) == null || P.call(C, [...a.messages], "answer"), s.track("agent-message-received", {
1143
+ latency: B.get(!0),
1144
+ messages: a.messages.length
1145
+ })), I;
1146
+ } catch (k) {
1147
+ throw (($ = a.messages[a.messages.length - 1]) == null ? void 0 : $.role) === "assistant" && a.messages.pop(), s.track("agent-message-send", {
1148
+ event: "error",
1149
+ messages: a.messages.length
1150
+ }), k;
1151
+ }
1152
+ },
1153
+ rate(u, h, p) {
1154
+ var y, C, P, $;
1155
+ const _ = a.messages.find((k) => k.id === u);
1156
+ if (a.chat) {
1157
+ if (!_)
1158
+ throw new Error("Message not found");
1159
+ } else throw new Error("Chat is not initialized");
1160
+ const m = ((y = _.matches) == null ? void 0 : y.map((k) => [k.document_id, k.id])) ?? [];
1161
+ return s.track("agent-rate", {
1162
+ event: p ? "update" : "create",
1163
+ thumb: h === 1 ? "up" : "down",
1164
+ knowledge_id: ((C = l.knowledge) == null ? void 0 : C.id) ?? "",
1165
+ matches: m,
1166
+ score: h
1167
+ }), p ? d.updateRating(l.id, a.chat.id, p, {
1168
+ knowledge_id: ((P = l.knowledge) == null ? void 0 : P.id) ?? "",
1169
+ message_id: u,
1170
+ matches: m,
1171
+ score: h
1172
+ }) : d.createRating(l.id, a.chat.id, {
1173
+ knowledge_id: (($ = l.knowledge) == null ? void 0 : $.id) ?? "",
1174
+ message_id: u,
1175
+ matches: m,
1176
+ score: h
1177
+ });
1178
+ },
1179
+ deleteRate(u) {
1180
+ if (!a.chat)
1181
+ throw new Error("Chat is not initialized");
1182
+ return s.track("agent-rate-delete", { type: "text" }), d.deleteRating(l.id, a.chat.id, u);
1183
+ },
1184
+ async speak(u) {
1185
+ var m, y, C;
1186
+ function h() {
1187
+ if (typeof u == "string") {
1188
+ if (!l.presenter.voice)
1189
+ throw new Error("Presenter voice is not initialized");
1190
+ return {
1191
+ type: "text",
1192
+ provider: l.presenter.voice,
1193
+ input: u,
1194
+ ssml: !1
1195
+ };
1196
+ }
1197
+ if (u.type === "text" && !u.provider) {
1198
+ if (!l.presenter.voice)
1199
+ throw new Error("Presenter voice is not initialized");
1200
+ return {
1201
+ type: "text",
1202
+ provider: l.presenter.voice,
1203
+ input: u.input,
1204
+ ssml: u.ssml
1205
+ };
1206
+ }
1207
+ return u;
1208
+ }
1209
+ const p = h();
1210
+ if (s.track("agent-speak", p), B.update(), a.messages && p.type === "text" && (a.messages.push({
1211
+ id: V(),
1212
+ role: "assistant",
1213
+ content: p.input,
1214
+ created_at: new Date(B.get(!0)).toISOString()
1215
+ }), (y = (m = t.callbacks).onNewMessage) == null || y.call(m, [...a.messages], "answer")), xe(a.chatMode))
1216
+ return {
1217
+ duration: 0,
1218
+ video_id: "",
1219
+ status: "success"
1220
+ };
1221
+ if (!a.streamingManager)
1222
+ throw new Error("Please connect to the agent first");
1223
+ return a.streamingManager.speak({
1224
+ script: p,
1225
+ metadata: { chat_id: (C = a.chat) == null ? void 0 : C.id, agent_id: l.id }
1226
+ });
1227
+ },
1228
+ async interrupt({ type: u }) {
1229
+ var p, _, m;
1230
+ Xe(a.streamingManager, (p = a.streamingManager) == null ? void 0 : p.streamType, r);
1231
+ const h = a.messages[a.messages.length - 1];
1232
+ s.track("agent-video-interrupt", {
1233
+ type: u || "click",
1234
+ video_duration_to_interrupt: ne.get(!0),
1235
+ message_duration_to_interrupt: B.get(!0)
1236
+ }), h.interrupted = !0, (m = (_ = t.callbacks).onNewMessage) == null || m.call(_, [...a.messages], "answer"), Ye(a.streamingManager, r);
1237
+ }
1238
+ };
1239
+ }
1240
+ function bt(e, t, n) {
1241
+ const { getById: r } = ge(t, n || G);
1242
+ return r(e);
1243
+ }
1244
+ export {
1245
+ O as A,
1246
+ S as C,
1247
+ je as D,
1248
+ Te as K,
1249
+ Ie as P,
1250
+ Me as R,
1251
+ N as S,
1252
+ be as T,
1253
+ Se as U,
1254
+ H as V,
1255
+ Re as W,
1256
+ at as a,
1257
+ Z as b,
1258
+ me as c,
1259
+ w as d,
1260
+ A as e,
1261
+ G as f,
1262
+ De as g,
1263
+ Ce as h,
1264
+ jt as i,
1265
+ bt as j,
1266
+ Ee as k,
1267
+ E as l,
1268
+ q as m,
1269
+ _e as n,
1270
+ ce as o,
1271
+ Tt as p,
1272
+ Ae as q,
1273
+ Pe as r
1274
+ };