@d-id/client-sdk 1.1.18 → 1.1.19

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