@d-id/client-sdk 1.1.13-staging.51 → 1.1.13-staging.54

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