@d-id/client-sdk 1.1.17-staging.73 → 1.1.17-staging.76

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