@d-id/client-sdk 1.1.17-staging.75 → 1.1.18

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.
@@ -1,1340 +0,0 @@
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 Z = (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
- Z(this, "kind");
8
- Z(this, "description");
9
- Z(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 V extends ee {
27
- constructor(a, r) {
28
- super({ kind: "ValidationError", description: a });
29
- Z(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))(_ || {}), q = /* @__PURE__ */ ((e) => (e.Embed = "embed", e.Query = "query", e.Partial = "partial", e.Answer = "answer", e.Complete = "done", e))(q || {}), be = /* @__PURE__ */ ((e) => (e.KnowledgeProcessing = "knowledge/processing", e.KnowledgeIndexing = "knowledge/indexing", e.KnowledgeFailed = "knowledge/error", e.KnowledgeDone = "knowledge/done", e))(be || {}), Pe = /* @__PURE__ */ ((e) => (e.Knowledge = "knowledge", e.Document = "document", e.Record = "record", e))(Pe || {}), 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 Pt = (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 || {}), G = /* @__PURE__ */ ((e) => (e.Strong = "STRONG", e.Weak = "WEAK", e.Unknown = "UNKNOWN", e))(G || {}), X = /* @__PURE__ */ ((e) => (e.Idle = "IDLE", e.Talking = "TALKING", e))(X || {}), 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)), O = (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 = O();
93
- window.localStorage.setItem("did_external_key_id", a), t = a;
94
- }
95
- return t;
96
- }
97
- let Ue = O();
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: O,
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 = (y) => {
361
- console.error(y), l == null || l("Websocket failed to connect", y), a(y);
362
- }, h.onopen = (y) => {
363
- s == null || s(y), 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 === q.Partial || e === q.Answer) || (i == null ? void 0 : i.role) !== "assistant")
413
- return;
414
- const { content: c, sequence: n } = t;
415
- e === q.Partial ? a[n] = c : a.answer = c;
416
- const s = at(a);
417
- (i.content !== s || e === q.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 === q.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], y = [l.StreamFailed, l.StreamVideoError, l.StreamVideoRejected], A = Xe(n, r, { mode: t.chatMode });
432
- if (c = c, c === l.StreamVideoCreated)
433
- e.linkTrack("agent-video", A, l.StreamVideoCreated, ["start"]);
434
- else if (h.includes(c)) {
435
- const B = c.split("/")[1];
436
- y.includes(c) ? e.track("agent-video", { ...A, event: B }) : e.linkTrack("agent-video", { ...A, event: B }, c, ["done"]);
437
- }
438
- 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();
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" && (a = r.currentRoundTripTime), r && r.type === "inbound-rtp" && r.kind === "video")
508
- return {
509
- codec: t,
510
- rtt: a,
511
- timestamp: r.timestamp,
512
- bytesReceived: r.bytesReceived,
513
- packetsReceived: r.packetsReceived,
514
- packetsLost: r.packetsLost,
515
- framesDropped: r.framesDropped,
516
- framesDecoded: r.framesDecoded,
517
- jitter: r.jitter,
518
- jitterBufferDelay: r.jitterBufferDelay,
519
- jitterBufferEmittedCount: r.jitterBufferEmittedCount,
520
- avgJitterDelayInInterval: r.jitterBufferDelay / r.jitterBufferEmittedCount,
521
- frameWidth: r.frameWidth,
522
- frameHeight: r.frameHeight,
523
- framesPerSecond: r.framesPerSecond,
524
- freezeCount: r.freezeCount,
525
- freezeDuration: r.totalFreezesDuration
526
- };
527
- return {};
528
- }
529
- function ft(e, t, a) {
530
- const r = e.map((s, d) => d === 0 ? a ? {
531
- timestamp: s.timestamp,
532
- duration: 0,
533
- rtt: s.rtt,
534
- bytesReceived: s.bytesReceived - a.bytesReceived,
535
- bitrate: (s.bytesReceived - a.bytesReceived) * 8 / (t / 1e3),
536
- packetsReceived: s.packetsReceived - a.packetsReceived,
537
- packetsLost: s.packetsLost - a.packetsLost,
538
- framesDropped: s.framesDropped - a.framesDropped,
539
- framesDecoded: s.framesDecoded - a.framesDecoded,
540
- jitter: s.jitter,
541
- jitterBufferDelay: s.jitterBufferDelay - a.jitterBufferDelay,
542
- jitterBufferEmittedCount: s.jitterBufferEmittedCount - a.jitterBufferEmittedCount,
543
- avgJitterDelayInInterval: (s.jitterBufferDelay - a.jitterBufferDelay) / (s.jitterBufferEmittedCount - a.jitterBufferEmittedCount),
544
- framesPerSecond: s.framesPerSecond,
545
- freezeCount: s.freezeCount - a.freezeCount,
546
- freezeDuration: s.freezeDuration - a.freezeDuration
547
- } : {
548
- timestamp: s.timestamp,
549
- rtt: s.rtt,
550
- duration: 0,
551
- bytesReceived: s.bytesReceived,
552
- bitrate: s.bytesReceived * 8 / (t / 1e3),
553
- packetsReceived: s.packetsReceived,
554
- packetsLost: s.packetsLost,
555
- framesDropped: s.framesDropped,
556
- framesDecoded: s.framesDecoded,
557
- jitter: s.jitter,
558
- jitterBufferDelay: s.jitterBufferDelay,
559
- jitterBufferEmittedCount: s.jitterBufferEmittedCount,
560
- avgJitterDelayInInterval: s.jitterBufferDelay / s.jitterBufferEmittedCount,
561
- framesPerSecond: s.framesPerSecond,
562
- freezeCount: s.freezeCount,
563
- freezeDuration: s.freezeDuration
564
- } : {
565
- timestamp: s.timestamp,
566
- duration: t * d / 1e3,
567
- rtt: s.rtt,
568
- bytesReceived: s.bytesReceived - e[d - 1].bytesReceived,
569
- bitrate: (s.bytesReceived - e[d - 1].bytesReceived) * 8 / (t / 1e3),
570
- packetsReceived: s.packetsReceived - e[d - 1].packetsReceived,
571
- packetsLost: s.packetsLost - e[d - 1].packetsLost,
572
- framesDropped: s.framesDropped - e[d - 1].framesDropped,
573
- framesDecoded: s.framesDecoded - e[d - 1].framesDecoded,
574
- jitter: s.jitter,
575
- jitterBufferDelay: s.jitterBufferDelay - e[d - 1].jitterBufferDelay,
576
- jitterBufferEmittedCount: s.jitterBufferEmittedCount - e[d - 1].jitterBufferEmittedCount,
577
- avgJitterDelayInInterval: (s.jitterBufferDelay - e[d - 1].jitterBufferDelay) / (s.jitterBufferEmittedCount - e[d - 1].jitterBufferEmittedCount),
578
- framesPerSecond: s.framesPerSecond,
579
- freezeCount: s.freezeCount - e[d - 1].freezeCount,
580
- freezeDuration: s.freezeDuration - e[d - 1].freezeDuration
581
- }), 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);
582
- return {
583
- webRTCStats: {
584
- anomalies: o,
585
- minRtt: Math.min(...n),
586
- avgRtt: ue(n),
587
- maxRtt: Math.max(...n),
588
- aggregateReport: dt(e[0], e[e.length - 1], i),
589
- minJitterDelayInInterval: Math.min(...c),
590
- maxJitterDelayInInterval: Math.max(...c),
591
- avgJitterDelayInInterval: ue(c)
592
- },
593
- codec: e[0].codec,
594
- resolution: `${e[0].frameWidth}x${e[0].frameHeight}`
595
- };
596
- }
597
- const oe = 100, mt = Math.max(Math.ceil(400 / oe), 1), gt = 0.25, ht = 0.28;
598
- function wt() {
599
- let e = 0, t, a, r = 0;
600
- return (o) => {
601
- for (const i of o.values())
602
- if (i && i.type === "inbound-rtp" && i.kind === "video") {
603
- const c = i.jitterBufferDelay, n = i.jitterBufferEmittedCount;
604
- if (a && n > a) {
605
- const l = c - t, h = n - a;
606
- r = l / h;
607
- }
608
- t = c, a = n;
609
- const s = i.framesDecoded, d = s - e > 0;
610
- return e = s, { isReceiving: d, avgJitterDelayInInterval: r, freezeCount: i.freezeCount };
611
- }
612
- return { isReceiving: !1, avgJitterDelayInInterval: r };
613
- };
614
- }
615
- function pt(e, t, a, r, o, i = !1) {
616
- let c = [], n, s = 0, d = !1, l = G.Unknown, h = G.Unknown, y = 0, A = 0;
617
- const B = wt();
618
- return setInterval(async () => {
619
- const b = await e.getStats(), { isReceiving: L, avgJitterDelayInInterval: $, freezeCount: C } = B(b), K = ut(b);
620
- if (L)
621
- s = 0, y = C - A, h = $ < gt ? G.Strong : $ > ht && y > 1 ? G.Weak : l, h !== l && (o == null || o(h), l = h, A += y, y = 0), d || (r == null || r(w.Start), n = c[c.length - 1], c = [], d = !0), c.push(K);
622
- else if (d && (s++, s >= mt)) {
623
- const H = ft(c, oe, n);
624
- r == null || r(w.Stop, H), t() || a(), A = C, d = !1;
625
- }
626
- }, oe);
627
- }
628
- const vt = (window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection).bind(window);
629
- function fe(e) {
630
- switch (e) {
631
- case "connected":
632
- return I.Connected;
633
- case "checking":
634
- return I.Connecting;
635
- case "failed":
636
- return I.Fail;
637
- case "new":
638
- return I.New;
639
- case "closed":
640
- return I.Closed;
641
- case "disconnected":
642
- return I.Disconnected;
643
- case "completed":
644
- return I.Completed;
645
- default:
646
- return I.New;
647
- }
648
- }
649
- const yt = (e) => (t) => {
650
- const [a, r = ""] = t.split(/:(.+)/);
651
- try {
652
- const o = JSON.parse(r);
653
- return e("parsed data channel message", { subject: a, data: o }), { subject: a, data: o };
654
- } catch (o) {
655
- return e("Failed to parse data channel message, returning data as string", { subject: a, rawData: r, error: o }), { subject: a, data: r };
656
- }
657
- };
658
- function kt({
659
- statsSignal: e,
660
- dataChannelSignal: t,
661
- onVideoStateChange: a,
662
- report: r
663
- }) {
664
- e === w.Start && t === w.Start ? a == null || a(w.Start) : e === w.Stop && t === w.Stop && (a == null || a(w.Stop, r));
665
- }
666
- function Rt({
667
- statsSignal: e,
668
- dataChannelSignal: t,
669
- onVideoStateChange: a,
670
- onAgentActivityStateChange: r,
671
- report: o
672
- }) {
673
- e === w.Start ? a == null || a(w.Start) : e === w.Stop && (a == null || a(w.Stop, o)), t === w.Start ? r == null || r(X.Talking) : t === w.Stop && (r == null || r(X.Idle));
674
- }
675
- function me({
676
- statsSignal: e,
677
- dataChannelSignal: t,
678
- onVideoStateChange: a,
679
- onAgentActivityStateChange: r,
680
- streamType: o,
681
- report: i
682
- }) {
683
- o === W.Legacy ? kt({ statsSignal: e, dataChannelSignal: t, onVideoStateChange: a, report: i }) : o === W.Fluent && Rt({
684
- statsSignal: e,
685
- dataChannelSignal: t,
686
- onVideoStateChange: a,
687
- onAgentActivityStateChange: r,
688
- report: i
689
- });
690
- }
691
- async function Ct(e, t, { debug: a = !1, callbacks: r, auth: o, baseURL: i = te, analytics: c }) {
692
- var Y;
693
- const n = ct(a, "WebRTCStreamingManager"), s = yt(n);
694
- let d = !1, l = !1, h = w.Stop, y = w.Stop;
695
- const { startConnection: A, sendStreamRequest: B, close: b, createStream: L, addIceCandidate: $ } = ot(
696
- o,
697
- i,
698
- e,
699
- r.onError
700
- ), {
701
- id: C,
702
- offer: K,
703
- ice_servers: H,
704
- session_id: u,
705
- fluent: k,
706
- interrupt_enabled: v,
707
- triggers_enabled: T
708
- } = await L(t);
709
- (Y = r.onStreamCreated) == null || Y.call(r, { stream_id: C, session_id: u, agent_id: e });
710
- const g = new vt({ iceServers: H }), p = g.createDataChannel("JanusDataChannel");
711
- if (!u)
712
- throw new Error("Could not create session_id");
713
- const S = k ? W.Fluent : W.Legacy;
714
- c.enrich({
715
- "stream-type": S
716
- });
717
- const x = t.stream_warmup && !k, z = () => d, D = () => {
718
- var f;
719
- d = !0, l && ((f = r.onConnectionStateChange) == null || f.call(r, I.Connected));
720
- }, E = pt(
721
- g,
722
- z,
723
- D,
724
- (f, m) => me({
725
- statsSignal: y = f,
726
- dataChannelSignal: S === W.Legacy ? h : void 0,
727
- onVideoStateChange: r.onVideoStateChange,
728
- onAgentActivityStateChange: r.onAgentActivityStateChange,
729
- report: m,
730
- streamType: S
731
- }),
732
- (f) => {
733
- var m;
734
- return (m = r.onConnectivityStateChange) == null ? void 0 : m.call(r, f);
735
- },
736
- x
737
- );
738
- g.onicecandidate = (f) => {
739
- var m;
740
- n("peerConnection.onicecandidate", f);
741
- try {
742
- f.candidate && f.candidate.sdpMid && f.candidate.sdpMLineIndex !== null ? $(
743
- C,
744
- {
745
- candidate: f.candidate.candidate,
746
- sdpMid: f.candidate.sdpMid,
747
- sdpMLineIndex: f.candidate.sdpMLineIndex
748
- },
749
- u
750
- ) : $(C, { candidate: null }, u);
751
- } catch (j) {
752
- (m = r.onError) == null || m.call(r, j, { streamId: C });
753
- }
754
- }, p.onopen = () => {
755
- l = !0, (!x || d) && D();
756
- };
757
- const J = (f) => {
758
- var m;
759
- (m = r.onVideoIdChange) == null || m.call(r, f);
760
- };
761
- function R(f, m) {
762
- if (f === P.StreamStarted && typeof m == "object" && "metadata" in m) {
763
- const j = m.metadata;
764
- J(j.videoId);
765
- }
766
- f === P.StreamDone && J(null), h = f === P.StreamStarted ? w.Start : w.Stop, me({
767
- statsSignal: S === W.Legacy ? y : void 0,
768
- dataChannelSignal: h,
769
- onVideoStateChange: r.onVideoStateChange,
770
- onAgentActivityStateChange: r.onAgentActivityStateChange,
771
- streamType: S
772
- });
773
- }
774
- function M(f, m) {
775
- const j = typeof m == "string" ? m : m == null ? void 0 : m.metadata;
776
- j && c.enrich({ streamMetadata: j }), c.track("agent-chat", { event: "ready" });
777
- }
778
- const U = {
779
- [P.StreamStarted]: R,
780
- [P.StreamDone]: R,
781
- [P.StreamReady]: M
782
- };
783
- p.onmessage = (f) => {
784
- var Q;
785
- const { subject: m, data: j } = s(f.data);
786
- (Q = U[m]) == null || Q.call(U, m, j);
787
- }, g.oniceconnectionstatechange = () => {
788
- var m;
789
- n("peerConnection.oniceconnectionstatechange => " + g.iceConnectionState);
790
- const f = fe(g.iceConnectionState);
791
- f !== I.Connected && ((m = r.onConnectionStateChange) == null || m.call(r, f));
792
- }, g.ontrack = (f) => {
793
- var m;
794
- n("peerConnection.ontrack", f), (m = r.onSrcObjectReady) == null || m.call(r, f.streams[0]);
795
- }, await g.setRemoteDescription(K), n("set remote description OK");
796
- const F = await g.createAnswer();
797
- return n("create answer OK"), await g.setLocalDescription(F), n("set local description OK"), await A(C, F, u), n("start connection OK"), {
798
- /**
799
- * Method to send request to server to get clip or talk depend on you payload
800
- * @param payload
801
- */
802
- speak(f) {
803
- return B(C, u, f);
804
- },
805
- /**
806
- * Method to close RTC connection
807
- */
808
- async disconnect() {
809
- var f;
810
- if (C) {
811
- const m = fe(g.iceConnectionState);
812
- if (g) {
813
- if (m === I.New) {
814
- clearInterval(E);
815
- return;
816
- }
817
- g.close(), g.oniceconnectionstatechange = null, g.onnegotiationneeded = null, g.onicecandidate = null, g.ontrack = null;
818
- }
819
- try {
820
- m === I.Connected && await b(C, u).catch((j) => {
821
- });
822
- } catch (j) {
823
- n("Error on close stream connection", j);
824
- }
825
- (f = r.onAgentActivityStateChange) == null || f.call(r, X.Idle), clearInterval(E);
826
- }
827
- },
828
- /**
829
- * Method to send data channel messages to the server
830
- */
831
- sendDataChannelMessage(f) {
832
- var m, j;
833
- if (!d || p.readyState !== "open") {
834
- 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"), {
835
- streamId: C
836
- });
837
- return;
838
- }
839
- try {
840
- p.send(f);
841
- } catch (Q) {
842
- n("Error sending data channel message", Q), (j = r.onError) == null || j.call(r, Q, { streamId: C });
843
- }
844
- },
845
- /**
846
- * Session identifier information, should be returned in the body of all streaming requests
847
- */
848
- sessionId: u,
849
- /**
850
- * Id of current RTC stream
851
- */
852
- streamId: C,
853
- streamType: S,
854
- interruptAvailable: v ?? !1,
855
- triggersAvailable: T ?? !1
856
- };
857
- }
858
- var ce = /* @__PURE__ */ ((e) => (e.V1 = "v1", e.V2 = "v2", e))(ce || {});
859
- async function Dt(e, t, a) {
860
- const r = e.id;
861
- switch (t.version) {
862
- case "v1": {
863
- const { version: o, ...i } = t;
864
- return Ct(r, i, a);
865
- }
866
- case "v2": {
867
- const { version: o, ...i } = t;
868
- switch (i.transport_provider) {
869
- case de.Livekit:
870
- const { createLiveKitStreamingManager: c } = await import("./livekit-manager-jsPsU3VP.js");
871
- return c(r, i, a);
872
- default:
873
- throw new Error(`Unsupported transport provider: ${i.transport_provider}`);
874
- }
875
- }
876
- default:
877
- throw new Error(`Invalid stream version: ${t.version}`);
878
- }
879
- }
880
- function St(e) {
881
- return {
882
- transport_provider: de.Livekit,
883
- chat_id: e == null ? void 0 : e.chatId
884
- };
885
- }
886
- function It(e) {
887
- var o, i;
888
- const { streamOptions: t } = e ?? {}, a = ((o = e == null ? void 0 : e.mixpanelAdditionalProperties) == null ? void 0 : o.plan) !== void 0 ? {
889
- plan: (i = e.mixpanelAdditionalProperties) == null ? void 0 : i.plan
890
- } : void 0;
891
- return { ...{
892
- output_resolution: t == null ? void 0 : t.outputResolution,
893
- session_timeout: t == null ? void 0 : t.sessionTimeout,
894
- stream_warmup: t == null ? void 0 : t.streamWarmup,
895
- compatibility_mode: t == null ? void 0 : t.compatibilityMode,
896
- fluent: t == null ? void 0 : t.fluent
897
- }, ...a && { end_user_data: a } };
898
- }
899
- function Et(e, t) {
900
- return le(e.presenter.type) ? { version: ce.V2, ...St(t) } : { version: ce.V1, ...It(t) };
901
- }
902
- function Mt(e, t, a, r, o) {
903
- o === W.Fluent ? _t(e, t, a, r, o) : At(e, t, a, r, o);
904
- }
905
- function _t(e, t, a, r, o) {
906
- e === w.Start ? r.track("stream-session", { event: "start", "stream-type": o }) : e === w.Stop && r.track("stream-session", {
907
- event: "stop",
908
- is_greenscreen: t.presenter.type === "clip" && t.presenter.is_greenscreen,
909
- background: t.presenter.type === "clip" && t.presenter.background,
910
- "stream-type": o,
911
- ...a
912
- });
913
- }
914
- function Tt(e, t, a, r) {
915
- N.get() <= 0 || (e === w.Start ? a.linkTrack(
916
- "agent-video",
917
- { event: "start", latency: N.get(!0), "stream-type": r },
918
- "start",
919
- [P.StreamVideoCreated]
920
- ) : e === w.Stop && a.linkTrack(
921
- "agent-video",
922
- {
923
- event: "stop",
924
- is_greenscreen: t.presenter.type === "clip" && t.presenter.is_greenscreen,
925
- background: t.presenter.type === "clip" && t.presenter.background,
926
- "stream-type": r
927
- },
928
- "done",
929
- [P.StreamVideoDone]
930
- ));
931
- }
932
- function At(e, t, a, r, o) {
933
- N.get() <= 0 || (e === w.Start ? r.linkTrack(
934
- "agent-video",
935
- { event: "start", latency: N.get(!0), "stream-type": o },
936
- "start",
937
- [P.StreamVideoCreated]
938
- ) : e === w.Stop && r.linkTrack(
939
- "agent-video",
940
- {
941
- event: "stop",
942
- is_greenscreen: t.presenter.type === "clip" && t.presenter.is_greenscreen,
943
- background: t.presenter.type === "clip" && t.presenter.background,
944
- "stream-type": o,
945
- ...a
946
- },
947
- "done",
948
- [P.StreamVideoDone]
949
- ));
950
- }
951
- function ge(e, t, a) {
952
- return N.reset(), new Promise(async (r, o) => {
953
- try {
954
- let i, c = !1;
955
- i = await Dt(e, Et(e, t), {
956
- ...t,
957
- analytics: a,
958
- callbacks: {
959
- ...t.callbacks,
960
- onConnectionStateChange: (n) => {
961
- var s, d;
962
- (d = (s = t.callbacks).onConnectionStateChange) == null || d.call(s, n), n === I.Connected && (i ? r(i) : c = !0);
963
- },
964
- onVideoStateChange: (n, s) => {
965
- var d, l;
966
- (l = (d = t.callbacks).onVideoStateChange) == null || l.call(d, n), Mt(
967
- n,
968
- e,
969
- s,
970
- a,
971
- i.streamType
972
- );
973
- },
974
- onAgentActivityStateChange: (n) => {
975
- var s, d;
976
- (d = (s = t.callbacks).onAgentActivityStateChange) == null || d.call(s, n), n === X.Talking ? ie.update() : ie.reset(), Tt(
977
- n === X.Talking ? w.Start : w.Stop,
978
- e,
979
- a,
980
- i.streamType
981
- );
982
- }
983
- }
984
- }), c && r(i);
985
- } catch (i) {
986
- o(i);
987
- }
988
- });
989
- }
990
- async function jt(e, t, a, r, o) {
991
- var l, h, y, A;
992
- const i = async () => {
993
- var B;
994
- if (le(e.presenter.type)) {
995
- const b = await se(
996
- e,
997
- a,
998
- r,
999
- t.mode,
1000
- t.persistentChat,
1001
- o
1002
- ), L = await ge(
1003
- e,
1004
- { ...t, chatId: (B = b.chat) == null ? void 0 : B.id },
1005
- r
1006
- );
1007
- return { chatResult: b, streamingManager: L };
1008
- } else {
1009
- const b = se(
1010
- e,
1011
- a,
1012
- r,
1013
- t.mode,
1014
- t.persistentChat,
1015
- o
1016
- ), L = ge(e, t, r), [$, C] = await Promise.all([b, L]);
1017
- return { chatResult: $, streamingManager: C };
1018
- }
1019
- }, { chatResult: c, streamingManager: n } = await i(), { chat: s, chatMode: d } = c;
1020
- return d && d !== t.mode && (t.mode = d, (h = (l = t.callbacks).onModeChange) == null || h.call(l, d), d !== _.Functional) ? ((A = (y = t.callbacks).onError) == null || A.call(y, new Ee(d)), n == null || n.disconnect(), { chat: s }) : { chat: s, streamingManager: n };
1021
- }
1022
- async function Lt(e, t) {
1023
- var C, K, H;
1024
- let a = !0, r = null;
1025
- const o = t.mixpanelKey || Ne, i = t.wsURL || Fe, c = t.baseURL || te, n = {
1026
- messages: [],
1027
- chatMode: t.mode || _.Functional
1028
- }, s = Qe({
1029
- token: o,
1030
- agentId: e,
1031
- isEnabled: t.enableAnalitics,
1032
- externalId: t.externalId,
1033
- mixpanelAdditionalProperties: t.mixpanelAdditionalProperties
1034
- });
1035
- s.track("agent-sdk", { event: "init" });
1036
- const d = He(t.auth, c, t.callbacks.onError, t.externalId), l = await d.getById(e), h = le(l.presenter.type);
1037
- s.enrich(qe(l));
1038
- const { onMessage: y, clearQueue: A } = st(
1039
- s,
1040
- n,
1041
- t,
1042
- l,
1043
- () => {
1044
- var u;
1045
- return (u = n.socketManager) == null ? void 0 : u.disconnect();
1046
- }
1047
- );
1048
- n.messages = Ze(t.initialMessages), (K = (C = t.callbacks).onNewMessage) == null || K.call(C, [...n.messages], "answer");
1049
- const B = (u) => {
1050
- r = u;
1051
- };
1052
- s.track("agent-sdk", { event: "loaded", ...Ve(l) });
1053
- async function b(u) {
1054
- var S, x, z, D, E, J, R;
1055
- (x = (S = t.callbacks).onConnectionStateChange) == null || x.call(S, I.Connecting), N.reset(), u && !a && (delete n.chat, (D = (z = t.callbacks).onNewMessage) == null || D.call(z, [...n.messages], "answer"));
1056
- const k = t.mode === _.DirectPlayback || h ? Promise.resolve(void 0) : nt(
1057
- t.auth,
1058
- i,
1059
- { onMessage: y, onError: t.callbacks.onError },
1060
- t.externalId
1061
- ), v = ne(
1062
- () => jt(
1063
- l,
1064
- { ...t, callbacks: { ...t.callbacks, onVideoIdChange: B } },
1065
- d,
1066
- s,
1067
- n.chat
1068
- ),
1069
- {
1070
- limit: 3,
1071
- timeout: xe,
1072
- timeoutErrorMessage: "Timeout initializing the stream",
1073
- // Retry on all errors except for connection errors and rate limit errors, these are already handled in client level.
1074
- shouldRetryFn: (M) => (M == null ? void 0 : M.message) !== "Could not connect" && M.status !== 429,
1075
- delayMs: 1e3
1076
- }
1077
- ).catch((M) => {
1078
- var U, F;
1079
- throw $(_.Maintenance), (F = (U = t.callbacks).onConnectionStateChange) == null || F.call(U, I.Fail), M;
1080
- }), [T, { streamingManager: g, chat: p }] = await Promise.all([k, v]);
1081
- 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({
1082
- chatId: p == null ? void 0 : p.id,
1083
- streamId: g == null ? void 0 : g.streamId,
1084
- mode: n.chatMode
1085
- }), $((p == null ? void 0 : p.chat_mode) ?? t.mode ?? _.Functional);
1086
- }
1087
- async function L() {
1088
- var u, k, v, T;
1089
- (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);
1090
- }
1091
- async function $(u) {
1092
- var k, v;
1093
- u !== n.chatMode && (s.track("agent-mode-change", { mode: u }), n.chatMode = u, n.chatMode !== _.Functional && await L(), (v = (k = t.callbacks).onModeChange) == null || v.call(k, u));
1094
- }
1095
- return {
1096
- agent: l,
1097
- getStreamType: () => {
1098
- var u;
1099
- return (u = n.streamingManager) == null ? void 0 : u.streamType;
1100
- },
1101
- getIsInterruptAvailable: () => {
1102
- var u;
1103
- return ((u = n.streamingManager) == null ? void 0 : u.interruptAvailable) ?? !1;
1104
- },
1105
- getIsTriggersAvailable: () => {
1106
- var u;
1107
- return ((u = n.streamingManager) == null ? void 0 : u.triggersAvailable) ?? !1;
1108
- },
1109
- starterMessages: ((H = l.knowledge) == null ? void 0 : H.starter_message) || [],
1110
- getSTTToken: () => d.getSTTToken(l.id),
1111
- changeMode: $,
1112
- enrichAnalytics: s.enrich,
1113
- async connect() {
1114
- await b(!0), s.track("agent-chat", {
1115
- event: "connect",
1116
- mode: n.chatMode
1117
- });
1118
- },
1119
- async reconnect() {
1120
- await L(), await b(!1), s.track("agent-chat", {
1121
- event: "reconnect",
1122
- mode: n.chatMode
1123
- });
1124
- },
1125
- async disconnect() {
1126
- await L(), s.track("agent-chat", {
1127
- event: "disconnect",
1128
- mode: n.chatMode
1129
- });
1130
- },
1131
- async chat(u) {
1132
- var g, p, S, x, z;
1133
- const k = () => {
1134
- if (ve(t.mode))
1135
- throw new V(`${t.mode} is enabled, chat is disabled`);
1136
- if (u.length >= 800)
1137
- throw new V("Message cannot be more than 800 characters");
1138
- if (u.length === 0)
1139
- throw new V("Message cannot be empty");
1140
- if (n.chatMode === _.Maintenance)
1141
- throw new V("Chat is in maintenance mode");
1142
- if (![_.TextOnly, _.Playground].includes(n.chatMode)) {
1143
- if (!n.streamingManager)
1144
- throw new V("Streaming manager is not initialized");
1145
- if (!n.chat)
1146
- throw new V("Chat is not initialized");
1147
- }
1148
- }, v = async () => {
1149
- var D, E;
1150
- if (!n.chat) {
1151
- const J = await se(
1152
- l,
1153
- d,
1154
- s,
1155
- n.chatMode,
1156
- t.persistentChat
1157
- );
1158
- if (!J.chat)
1159
- throw new Ie(n.chatMode, !!t.persistentChat);
1160
- n.chat = J.chat, (E = (D = t.callbacks).onNewChat) == null || E.call(D, n.chat.id);
1161
- }
1162
- return n.chat.id;
1163
- }, T = async (D, E) => ne(h ? async () => {
1164
- var R, M;
1165
- return await ((M = (R = n.streamingManager) == null ? void 0 : R.sendTextMessage) == null ? void 0 : M.call(R, u)), Promise.resolve({
1166
- result: "This is a mock message until the data channel is implemented."
1167
- });
1168
- } : async () => {
1169
- var R, M;
1170
- return d.chat(
1171
- l.id,
1172
- E,
1173
- {
1174
- chatMode: n.chatMode,
1175
- streamId: (R = n.streamingManager) == null ? void 0 : R.streamId,
1176
- sessionId: (M = n.streamingManager) == null ? void 0 : M.sessionId,
1177
- messages: D.map(({ matches: U, ...F }) => F)
1178
- },
1179
- {
1180
- ...Ce(n.chatMode),
1181
- skipErrorHandler: !0
1182
- }
1183
- );
1184
- }, {
1185
- limit: 2,
1186
- shouldRetryFn: (R) => {
1187
- var F, Y, f, m;
1188
- const M = (F = R == null ? void 0 : R.message) == null ? void 0 : F.includes("missing or invalid session_id");
1189
- return !((Y = R == null ? void 0 : R.message) == null ? void 0 : Y.includes("Stream Error")) && !M ? ((m = (f = t.callbacks).onError) == null || m.call(f, R), !1) : !0;
1190
- },
1191
- onRetry: async () => {
1192
- await L(), await b(!1);
1193
- }
1194
- });
1195
- try {
1196
- A(), k(), n.messages.push({
1197
- id: O(),
1198
- role: "user",
1199
- content: u,
1200
- created_at: new Date(N.update()).toISOString()
1201
- }), (p = (g = t.callbacks).onNewMessage) == null || p.call(g, [...n.messages], "user");
1202
- const D = await v(), E = await T([...n.messages], D);
1203
- return n.messages.push({
1204
- id: O(),
1205
- role: "assistant",
1206
- content: E.result || "",
1207
- created_at: (/* @__PURE__ */ new Date()).toISOString(),
1208
- context: E.context,
1209
- matches: E.matches
1210
- }), s.track("agent-message-send", {
1211
- event: "success",
1212
- messages: n.messages.length + 1
1213
- }), E.result && ((x = (S = t.callbacks).onNewMessage) == null || x.call(S, [...n.messages], "answer"), s.track("agent-message-received", {
1214
- latency: N.get(!0),
1215
- messages: n.messages.length
1216
- })), E;
1217
- } catch (D) {
1218
- throw ((z = n.messages[n.messages.length - 1]) == null ? void 0 : z.role) === "assistant" && n.messages.pop(), s.track("agent-message-send", {
1219
- event: "error",
1220
- messages: n.messages.length
1221
- }), D;
1222
- }
1223
- },
1224
- rate(u, k, v) {
1225
- var p, S, x, z;
1226
- const T = n.messages.find((D) => D.id === u);
1227
- if (n.chat) {
1228
- if (!T)
1229
- throw new Error("Message not found");
1230
- } else throw new Error("Chat is not initialized");
1231
- const g = ((p = T.matches) == null ? void 0 : p.map((D) => [D.document_id, D.id])) ?? [];
1232
- return s.track("agent-rate", {
1233
- event: v ? "update" : "create",
1234
- thumb: k === 1 ? "up" : "down",
1235
- knowledge_id: ((S = l.knowledge) == null ? void 0 : S.id) ?? "",
1236
- matches: g,
1237
- score: k
1238
- }), v ? d.updateRating(l.id, n.chat.id, v, {
1239
- knowledge_id: ((x = l.knowledge) == null ? void 0 : x.id) ?? "",
1240
- message_id: u,
1241
- matches: g,
1242
- score: k
1243
- }) : d.createRating(l.id, n.chat.id, {
1244
- knowledge_id: ((z = l.knowledge) == null ? void 0 : z.id) ?? "",
1245
- message_id: u,
1246
- matches: g,
1247
- score: k
1248
- });
1249
- },
1250
- deleteRate(u) {
1251
- if (!n.chat)
1252
- throw new Error("Chat is not initialized");
1253
- return s.track("agent-rate-delete", { type: "text" }), d.deleteRating(l.id, n.chat.id, u);
1254
- },
1255
- async speak(u) {
1256
- var g, p, S;
1257
- function k() {
1258
- if (typeof u == "string") {
1259
- if (!l.presenter.voice)
1260
- throw new Error("Presenter voice is not initialized");
1261
- return {
1262
- type: "text",
1263
- provider: l.presenter.voice,
1264
- input: u,
1265
- ssml: !1
1266
- };
1267
- }
1268
- if (u.type === "text" && !u.provider) {
1269
- if (!l.presenter.voice)
1270
- throw new Error("Presenter voice is not initialized");
1271
- return {
1272
- type: "text",
1273
- provider: l.presenter.voice,
1274
- input: u.input,
1275
- ssml: u.ssml
1276
- };
1277
- }
1278
- return u;
1279
- }
1280
- const v = k();
1281
- if (s.track("agent-speak", v), N.update(), n.messages && v.type === "text" && (n.messages.push({
1282
- id: O(),
1283
- role: "assistant",
1284
- content: v.input,
1285
- created_at: (/* @__PURE__ */ new Date()).toISOString()
1286
- }), (p = (g = t.callbacks).onNewMessage) == null || p.call(g, [...n.messages], "answer")), Je(n.chatMode))
1287
- return {
1288
- duration: 0,
1289
- video_id: "",
1290
- status: "success"
1291
- };
1292
- if (!n.streamingManager)
1293
- throw new Error("Please connect to the agent first");
1294
- return n.streamingManager.speak({
1295
- script: v,
1296
- metadata: { chat_id: (S = n.chat) == null ? void 0 : S.id, agent_id: l.id }
1297
- });
1298
- },
1299
- async interrupt({ type: u }) {
1300
- var v, T, g;
1301
- Ge(n.streamingManager, (v = n.streamingManager) == null ? void 0 : v.streamType, r);
1302
- const k = n.messages[n.messages.length - 1];
1303
- s.track("agent-video-interrupt", {
1304
- type: u || "click",
1305
- video_duration_to_interrupt: ie.get(!0),
1306
- message_duration_to_interrupt: N.get(!0)
1307
- }), k.interrupted = !0, (g = (T = t.callbacks).onNewMessage) == null || g.call(T, [...n.messages], "answer"), et(n.streamingManager, r);
1308
- }
1309
- };
1310
- }
1311
- export {
1312
- X as A,
1313
- I as C,
1314
- Le as D,
1315
- Pe as K,
1316
- Te as P,
1317
- je as R,
1318
- W as S,
1319
- de as T,
1320
- _e as U,
1321
- V,
1322
- Me as W,
1323
- ct as a,
1324
- G as b,
1325
- ke as c,
1326
- te as d,
1327
- w as e,
1328
- P as f,
1329
- Ie as g,
1330
- Ee as h,
1331
- Lt as i,
1332
- Ae as j,
1333
- _ as k,
1334
- q as l,
1335
- be as m,
1336
- he as n,
1337
- Pt as o,
1338
- Be as p,
1339
- $e as q
1340
- };