@d-id/client-sdk 1.1.21-staging.98 → 1.1.22

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