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

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