@d-id/client-sdk 1.1.23-staging.107 → 1.1.23-staging.110

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