@d-id/client-sdk 1.2.3 → 1.2.4-staging.353

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.
@@ -0,0 +1,1803 @@
1
+ var it = Object.defineProperty;
2
+ var st = (e, t, n) => t in e ? it(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
3
+ var K = (e, t, n) => st(e, typeof t != "symbol" ? t + "" : t, n);
4
+ class G extends Error {
5
+ constructor(t, n = "Error", i) {
6
+ super(t), this.kind = n, this.originalError = i, Object.setPrototypeOf(this, new.target.prototype);
7
+ }
8
+ toJson() {
9
+ const t = this.originalError instanceof Error ? this.originalError.message.slice(0, 256) : void 0;
10
+ return {
11
+ kind: this.kind,
12
+ message: this.message,
13
+ ...t && t !== this.message ? { cause: t } : {}
14
+ };
15
+ }
16
+ }
17
+ function bn(e) {
18
+ return e instanceof Error && typeof e.kind == "string";
19
+ }
20
+ class ot extends G {
21
+ constructor(t, n) {
22
+ super(`Failed to create ${n ? "persistent" : ""} chat, mode: ${t}`, "ChatCreationFailed");
23
+ }
24
+ }
25
+ class ct extends G {
26
+ constructor(t) {
27
+ super(`Chat mode downgraded to ${t}`, "ChatModeDowngraded");
28
+ }
29
+ }
30
+ function dt(e) {
31
+ try {
32
+ const t = JSON.parse(e);
33
+ if (t && typeof t == "object" && typeof t.kind == "string")
34
+ return t;
35
+ } catch {
36
+ }
37
+ }
38
+ class Oe extends G {
39
+ constructor(n, i, c = {}) {
40
+ const o = dt(i);
41
+ super(((o == null ? void 0 : o.description) ?? i).slice(0, 256), (o == null ? void 0 : o.kind) ?? "HttpError");
42
+ K(this, "status");
43
+ K(this, "url");
44
+ K(this, "method");
45
+ this.status = n, this.url = c.url, this.method = c.method;
46
+ }
47
+ toJson() {
48
+ return {
49
+ ...super.toJson(),
50
+ httpStatus: this.status,
51
+ ...this.url ? { endpoint: this.url } : {},
52
+ ...this.method ? { method: this.method } : {}
53
+ };
54
+ }
55
+ }
56
+ class lt extends G {
57
+ constructor(n, i = {}) {
58
+ super("Network request failed", "NetworkError", n);
59
+ K(this, "endpoint");
60
+ K(this, "method");
61
+ K(this, "durationMs");
62
+ K(this, "online");
63
+ K(this, "visibility");
64
+ this.endpoint = i.url, this.method = i.method, this.durationMs = i.durationMs, this.online = i.online, this.visibility = i.visibility;
65
+ }
66
+ toJson() {
67
+ return {
68
+ ...super.toJson(),
69
+ ...this.endpoint ? { endpoint: this.endpoint } : {},
70
+ ...this.method ? { method: this.method } : {},
71
+ ...this.durationMs !== void 0 ? { durationMs: this.durationMs } : {},
72
+ ...this.online !== void 0 ? { online: this.online } : {},
73
+ ...this.visibility ? { visibility: this.visibility } : {}
74
+ };
75
+ }
76
+ }
77
+ class Ke extends G {
78
+ constructor(t, n) {
79
+ super(t, "StreamError", n);
80
+ }
81
+ }
82
+ class $ extends G {
83
+ constructor(t, n) {
84
+ super(t, "ValidationError"), this.key = n;
85
+ }
86
+ }
87
+ class ut extends G {
88
+ constructor(t) {
89
+ super(t, "WSError");
90
+ }
91
+ }
92
+ var ft = /* @__PURE__ */ ((e) => (e.TRIAL = "trial", e.BASIC = "basic", e.ENTERPRISE = "enterprise", e.LITE = "lite", e.ADVANCED = "advanced", e))(ft || {}), mt = /* @__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))(mt || {}), gt = /* @__PURE__ */ ((e) => (e.Created = "created", e.Started = "started", e.Done = "done", e.Error = "error", e.Rejected = "rejected", e.Ready = "ready", e))(gt || {}), ht = /* @__PURE__ */ ((e) => (e.Unrated = "Unrated", e.Positive = "Positive", e.Negative = "Negative", e))(ht || {}), b = /* @__PURE__ */ ((e) => (e.Functional = "Functional", e.TextOnly = "TextOnly", e.Maintenance = "Maintenance", e.Playground = "Playground", e.DirectPlayback = "DirectPlayback", e.Off = "Off", e))(b || {}), z = /* @__PURE__ */ ((e) => (e.Embed = "embed", e.Query = "query", e.Partial = "partial", e.Answer = "answer", e.Transcribe = "transcribe", e.Complete = "done", e))(z || {}), pt = /* @__PURE__ */ ((e) => (e.KnowledgeProcessing = "knowledge/processing", e.KnowledgeIndexing = "knowledge/indexing", e.KnowledgeFailed = "knowledge/error", e.KnowledgeDone = "knowledge/done", e))(pt || {}), wt = /* @__PURE__ */ ((e) => (e.Knowledge = "knowledge", e.Document = "document", e.Record = "record", e))(wt || {}), yt = /* @__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))(yt || {}), We = /* @__PURE__ */ ((e) => (e.Clip = "clip", e.Talk = "talk", e.Expressive = "expressive", e))(We || {});
93
+ const An = (e) => {
94
+ switch (e) {
95
+ case "clip":
96
+ return "clip";
97
+ case "talk":
98
+ return "talk";
99
+ case "expressive":
100
+ return "expressive";
101
+ default:
102
+ throw new Error(`Unknown video type: ${e}`);
103
+ }
104
+ };
105
+ var S = /* @__PURE__ */ ((e) => (e.Start = "START", e.Stop = "STOP", e))(S || {}), re = /* @__PURE__ */ ((e) => (e.Strong = "STRONG", e.Weak = "WEAK", e.Unknown = "UNKNOWN", e))(re || {}), ie = /* @__PURE__ */ ((e) => (e.Idle = "IDLE", e.Loading = "LOADING", e.Talking = "TALKING", e.ToolActive = "TOOL_ACTIVE", e))(ie || {}), x = /* @__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.ToolCallStarted = "tool-call/started", e.ToolCallDone = "tool-call/done", e.ToolCallError = "tool-call/error", e))(x || {}), A = /* @__PURE__ */ ((e) => (e.New = "new", e.Fail = "fail", e.Connected = "connected", e.Connecting = "connecting", e.Closed = "closed", e.Completed = "completed", e.Disconnecting = "disconnecting", e.Disconnected = "disconnected", e))(A || {}), W = /* @__PURE__ */ ((e) => (e.Legacy = "legacy", e.Fluent = "fluent", e))(W || {}), Se = /* @__PURE__ */ ((e) => (e.Livekit = "livekit", e))(Se || {}), vt = /* @__PURE__ */ ((e) => (e.Amazon = "amazon", e.AzureOpenAi = "azure-openai", e.Microsoft = "microsoft", e.Afflorithmics = "afflorithmics", e.Elevenlabs = "elevenlabs", e))(vt || {}), Ct = /* @__PURE__ */ ((e) => (e.Public = "public", e.Premium = "premium", e.Private = "private", e))(Ct || {});
106
+ const xn = (...e) => {
107
+ }, He = (e) => new Promise((t) => setTimeout(t, e)), ee = (e = 16) => {
108
+ const t = new Uint8Array(e);
109
+ return window.crypto.getRandomValues(t), Array.from(t, (n) => n.toString(16).padStart(2, "0")).join("").slice(0, 13);
110
+ };
111
+ function pe(e) {
112
+ if (e !== void 0)
113
+ return window.localStorage.setItem("did_external_key_id", e), e;
114
+ let t = window.localStorage.getItem("did_external_key_id");
115
+ if (!t) {
116
+ let n = ee();
117
+ window.localStorage.setItem("did_external_key_id", n), t = n;
118
+ }
119
+ return t;
120
+ }
121
+ let qe = ee();
122
+ function St() {
123
+ qe = ee();
124
+ }
125
+ function Xe(e, t) {
126
+ if (e.type === "bearer")
127
+ return `Bearer ${e.token}`;
128
+ if (e.type === "basic")
129
+ return `Basic ${"token" in e ? e.token : btoa(`${e.username}:${e.password}`)}`;
130
+ if (e.type === "key")
131
+ return `Client-Key ${e.clientKey}.${pe(t)}_${qe}`;
132
+ throw new Error(`Unknown auth type: ${e}`);
133
+ }
134
+ const kt = 45 * 1e3, Mt = "X-Playground-Chat", Ee = 2e3, fe = "https://api.d-id.com", Rt = "wss://notifications.d-id.com", Dt = "79f81a83a67430be2bc0fd61042b8faa", Ge = (e) => e.type === "clip" && e.presenter_id.startsWith("v2_") ? "clip_v2" : e.type, It = (e) => {
135
+ switch (e.type) {
136
+ case "expressive":
137
+ return "v4";
138
+ case "clip":
139
+ return "v3-pro";
140
+ case "talk":
141
+ return "v2";
142
+ }
143
+ }, Et = (e) => e.type === "talk" ? e.source_url : e.presenter_id, ke = (e) => e === We.Expressive, Tt = (e) => [b.TextOnly, b.Playground, b.Maintenance].includes(e), Qe = (e) => e && [b.DirectPlayback, b.Off].includes(e), Te = /\[!\[([^\[\]]*)\]\(([^)\s]+)\)\]\(([^)\s]+)\)/g, _e = /!\[([^\[\]]*)\]\(([^)\s]+)\)/g, _t = [".mp4", ".webm", ".mkv", ".mov", ".m4v", ".ogv"];
144
+ function bt(e) {
145
+ const t = e.split("?")[0].split("#")[0].toLowerCase();
146
+ return _t.some((n) => t.endsWith(n));
147
+ }
148
+ const be = new RegExp("(?<!!)\\[([^\\[\\]]+)\\]\\(([^)\\s]+)\\)", "g"), Ae = /<a\s+href="([^"]*)"[^>]*?>([^<]*)<\/a>/gi;
149
+ function At(e) {
150
+ if (e.length === 0)
151
+ return [];
152
+ const t = [];
153
+ let n;
154
+ for (Te.lastIndex = 0; (n = Te.exec(e)) !== null; )
155
+ t.push({
156
+ index: n.index,
157
+ length: n[0].length,
158
+ part: { type: "video", src: n[3], alt: n[1], thumbnail: n[2] }
159
+ });
160
+ for (_e.lastIndex = 0; (n = _e.exec(e)) !== null; )
161
+ if (!t.some((s) => n.index >= s.index && n.index < s.index + s.length)) {
162
+ const s = n[2], r = n[1];
163
+ let a;
164
+ bt(s) ? a = { type: "video", src: s, alt: r } : (a = { type: "image", src: s, alt: r }, s.toLowerCase().endsWith(".gif") && (a.mimeType = "image/gif")), t.push({ index: n.index, length: n[0].length, part: a });
165
+ }
166
+ for (be.lastIndex = 0; (n = be.exec(e)) !== null; )
167
+ t.some((s) => n.index >= s.index && n.index < s.index + s.length) || t.push({
168
+ index: n.index,
169
+ length: n[0].length,
170
+ part: { type: "link", href: n[2], label: n[1] }
171
+ });
172
+ for (Ae.lastIndex = 0; (n = Ae.exec(e)) !== null; )
173
+ t.some((s) => n.index >= s.index && n.index < s.index + s.length) || t.push({
174
+ index: n.index,
175
+ length: n[0].length,
176
+ part: { type: "link", href: n[1], label: n[2] }
177
+ });
178
+ if (t.length === 0)
179
+ return [{ type: "text", text: e }];
180
+ t.sort((o, s) => o.index - s.index);
181
+ const i = [];
182
+ let c = 0;
183
+ for (const o of t)
184
+ o.index > c && i.push({ type: "text", text: e.slice(c, o.index) }), i.push(o.part), c = o.index + o.length;
185
+ return c < e.length && i.push({ type: "text", text: e.slice(c) }), i;
186
+ }
187
+ let xe = "", me = [];
188
+ function ae(e) {
189
+ return e === xe || (xe = e, me = At(e)), me;
190
+ }
191
+ function xt(e, t) {
192
+ let n;
193
+ return {
194
+ promise: new Promise((c, o) => {
195
+ n = setTimeout(() => o(new Error(t)), e);
196
+ }),
197
+ clear: () => clearTimeout(n)
198
+ };
199
+ }
200
+ async function we(e, t) {
201
+ const n = {
202
+ limit: (t == null ? void 0 : t.limit) ?? 3,
203
+ delayMs: (t == null ? void 0 : t.delayMs) ?? 0,
204
+ timeout: (t == null ? void 0 : t.timeout) ?? 3e4,
205
+ timeoutErrorMessage: (t == null ? void 0 : t.timeoutErrorMessage) || "Timeout error",
206
+ shouldRetryFn: (t == null ? void 0 : t.shouldRetryFn) ?? (() => !0),
207
+ onRetry: (t == null ? void 0 : t.onRetry) ?? (() => {
208
+ })
209
+ };
210
+ let i;
211
+ for (let c = 1; c <= n.limit; c++)
212
+ try {
213
+ if (!n.timeout)
214
+ return await e();
215
+ const { promise: o, clear: s } = xt(n.timeout, n.timeoutErrorMessage), r = e().finally(s);
216
+ return await Promise.race([r, o]);
217
+ } catch (o) {
218
+ if (i = o, !n.shouldRetryFn(o) || c >= n.limit)
219
+ throw o;
220
+ await He(n.delayMs), n.onRetry(o);
221
+ }
222
+ throw i;
223
+ }
224
+ const Pt = (e) => we(e, {
225
+ limit: 3,
226
+ delayMs: 1e3,
227
+ timeout: 0,
228
+ shouldRetryFn: (t) => t.status === 429
229
+ });
230
+ function Ye(e, t = fe, n, i) {
231
+ const c = async (o, s) => {
232
+ const { skipErrorHandler: r, ...a } = s || {}, d = a.method ?? "GET", m = performance.now();
233
+ let u;
234
+ try {
235
+ u = await Pt(
236
+ () => fetch(t + (o != null && o.startsWith("/") ? o : `/${o}`), {
237
+ ...a,
238
+ headers: {
239
+ ...a.headers,
240
+ Authorization: Xe(e, i),
241
+ "Content-Type": "application/json"
242
+ }
243
+ })
244
+ );
245
+ } catch (f) {
246
+ if ((f == null ? void 0 : f.name) === "AbortError")
247
+ throw f;
248
+ const v = new lt(f, {
249
+ url: o,
250
+ method: d,
251
+ durationMs: Math.round(performance.now() - m),
252
+ online: typeof navigator < "u" ? navigator.onLine : void 0,
253
+ visibility: typeof document < "u" ? document.visibilityState : void 0
254
+ });
255
+ throw r || n == null || n(v, { url: o, options: a }), v;
256
+ }
257
+ if (!u.ok) {
258
+ const f = await u.text().catch(() => `Failed to fetch with status ${u.status}`), w = new Oe(u.status, f, { url: o, method: d });
259
+ throw r || n == null || n(w, { url: o, options: a, headers: u.headers }), w;
260
+ }
261
+ return u.json();
262
+ };
263
+ return {
264
+ get(o, s) {
265
+ return c(o, { ...s, method: "GET" });
266
+ },
267
+ post(o, s, r) {
268
+ return c(o, { ...r, body: JSON.stringify(s), method: "POST" });
269
+ },
270
+ delete(o, s, r) {
271
+ return c(o, { ...r, body: JSON.stringify(s), method: "DELETE" });
272
+ },
273
+ patch(o, s, r) {
274
+ return c(o, { ...r, body: JSON.stringify(s), method: "PATCH" });
275
+ }
276
+ };
277
+ }
278
+ function Lt(e, t = fe, n, i) {
279
+ const c = Ye(e, `${t}/agents`, n, i);
280
+ return {
281
+ create(o, s) {
282
+ return c.post("/", o, s);
283
+ },
284
+ getAgents(o, s) {
285
+ return c.get(`/${o ? `?tag=${o}` : ""}`, s).then((r) => r ?? []);
286
+ },
287
+ getById(o, s) {
288
+ return c.get(`/${o}`, s);
289
+ },
290
+ delete(o, s) {
291
+ return c.delete(`/${o}`, void 0, s);
292
+ },
293
+ update(o, s, r) {
294
+ return c.patch(`/${o}`, s, r);
295
+ },
296
+ newChat(o, s, r) {
297
+ return c.post(`/${o}/chat`, s, r);
298
+ },
299
+ chat(o, s, r, a) {
300
+ return c.post(`/${o}/chat/${s}`, r, a);
301
+ },
302
+ createRating(o, s, r, a) {
303
+ return c.post(`/${o}/chat/${s}/ratings`, r, a);
304
+ },
305
+ updateRating(o, s, r, a, d) {
306
+ return c.patch(`/${o}/chat/${s}/ratings/${r}`, a, d);
307
+ },
308
+ deleteRating(o, s, r, a) {
309
+ return c.delete(`/${o}/chat/${s}/ratings/${r}`, a);
310
+ },
311
+ getSTTToken(o, s) {
312
+ return c.get(`/${o}/stt-token`, s);
313
+ }
314
+ };
315
+ }
316
+ function jt(e) {
317
+ var c, o, s, r;
318
+ const t = () => /Mobi|Android/i.test(navigator.userAgent) ? "Mobile" : "Desktop", n = () => {
319
+ const a = navigator.platform;
320
+ return a.toLowerCase().includes("win") ? "Windows" : a.toLowerCase().includes("mac") ? "Mac OS X" : a.toLowerCase().includes("linux") ? "Linux" : "Unknown";
321
+ }, i = e.presenter;
322
+ return {
323
+ $os: `${n()}`,
324
+ isMobile: `${t() == "Mobile"}`,
325
+ browser: navigator.userAgent,
326
+ origin: window.location.origin,
327
+ agentType: Ge(i),
328
+ agentVoice: {
329
+ voiceId: (o = (c = e.presenter) == null ? void 0 : c.voice) == null ? void 0 : o.voice_id,
330
+ provider: (r = (s = e.presenter) == null ? void 0 : s.voice) == null ? void 0 : r.type
331
+ }
332
+ };
333
+ }
334
+ function Bt(e) {
335
+ var n, i, c, o, s, r;
336
+ const t = (n = e.llm) == null ? void 0 : n.prompt_customization;
337
+ return {
338
+ agentType: Ge(e.presenter),
339
+ presenterType: It(e.presenter),
340
+ presenter: Et(e.presenter),
341
+ owner_id: e.owner_id ?? "",
342
+ promptVersion: (i = e.llm) == null ? void 0 : i.prompt_version,
343
+ behavior: {
344
+ role: t == null ? void 0 : t.role,
345
+ personality: t == null ? void 0 : t.personality,
346
+ instructions: (c = e.llm) == null ? void 0 : c.instructions
347
+ },
348
+ temperature: (o = e.llm) == null ? void 0 : o.temperature,
349
+ knowledgeSource: t == null ? void 0 : t.knowledge_source,
350
+ starterQuestionsCount: (r = (s = e.knowledge) == null ? void 0 : s.starter_message) == null ? void 0 : r.length,
351
+ topicsToAvoid: t == null ? void 0 : t.topics_to_avoid,
352
+ maxResponseLength: t == null ? void 0 : t.max_response_length,
353
+ agentId: e.id,
354
+ access: e.access,
355
+ agentName: e.preview_name,
356
+ ...e.access === "public" ? { from: "agent-template" } : {}
357
+ };
358
+ }
359
+ const $t = (e) => {
360
+ try {
361
+ return String((e == null ? void 0 : e.message) ?? e ?? "").slice(0, 256);
362
+ } catch {
363
+ return "Unknown error";
364
+ }
365
+ }, zt = (e) => e.reduce((t, n) => t + n, 0), Pe = (e) => zt(e) / e.length, Le = (e) => Math.min(...e), je = (e) => Math.max(...e), le = (e, t = 0) => {
366
+ const n = 10 ** t;
367
+ return Math.round(e * n) / n;
368
+ }, Nt = (e, t) => {
369
+ const n = [...e].sort((i, c) => i - c);
370
+ return n[Math.min(n.length - 1, Math.floor(t * (n.length - 1)))];
371
+ }, Ft = (e) => Nt(e, 0.5), Vt = (e, t) => {
372
+ try {
373
+ return e();
374
+ } catch {
375
+ return t;
376
+ }
377
+ };
378
+ function Ut(e, t, n) {
379
+ var a, d, m;
380
+ const { event: i, ...c } = e, { template: o } = (t == null ? void 0 : t.llm) || {}, { language: s } = ((a = t == null ? void 0 : t.presenter) == null ? void 0 : a.voice) || {};
381
+ return {
382
+ ...c,
383
+ llm: { ...c.llm, template: o },
384
+ script: { ...c.script, provider: { ...(d = c == null ? void 0 : c.script) == null ? void 0 : d.provider, language: s } },
385
+ stitch: (t == null ? void 0 : t.presenter.type) === "talk" ? (m = t == null ? void 0 : t.presenter) == null ? void 0 : m.stitch : void 0,
386
+ ...n
387
+ };
388
+ }
389
+ function Be(e) {
390
+ "requestIdleCallback" in window ? requestIdleCallback(e, { timeout: 2e3 }) : setTimeout(e, 0);
391
+ }
392
+ function ge(e) {
393
+ return e instanceof G ? e.toJson() : { kind: "UnknownError", message: $t(e) || "UnknownError" };
394
+ }
395
+ const Jt = "1.2.4-staging.353", Ot = "https://api-js.mixpanel.com/track/?verbose=1&ip=1", Ze = 50, Z = [];
396
+ let he = !1;
397
+ async function et(e) {
398
+ const t = await fetch(Ot, {
399
+ method: "POST",
400
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
401
+ body: new URLSearchParams({ data: JSON.stringify(e) })
402
+ });
403
+ if (!t.ok)
404
+ throw new Error(`Mixpanel responded with ${t.status}`);
405
+ }
406
+ function Kt(e) {
407
+ Z.push(e), Z.splice(Ze);
408
+ }
409
+ function ye() {
410
+ if (he || !Z.length)
411
+ return;
412
+ he = !0;
413
+ const e = Z.splice(0, Z.length);
414
+ et(e).catch(() => {
415
+ Z.unshift(...e), Z.splice(Ze);
416
+ }).finally(() => {
417
+ he = !1;
418
+ });
419
+ }
420
+ typeof window < "u" && typeof window.addEventListener == "function" && (window.addEventListener("online", ye), typeof document < "u" && document.addEventListener("visibilitychange", () => {
421
+ document.visibilityState === "visible" && ye();
422
+ }));
423
+ function Wt(e) {
424
+ const t = window != null && window.hasOwnProperty("DID_AGENTS_API") ? "agents-ui" : "agents-sdk", n = {};
425
+ return {
426
+ token: e.token || "testKey",
427
+ distinct_id: pe(e.externalId),
428
+ agentId: e.agentId,
429
+ additionalProperties: {
430
+ id: pe(e.externalId),
431
+ ...e.mixpanelAdditionalProperties || {}
432
+ },
433
+ isEnabled: e.isEnabled ?? !0,
434
+ getRandom: ee,
435
+ enrich(i) {
436
+ this.additionalProperties = { ...this.additionalProperties, ...i };
437
+ },
438
+ async track(i, c, o) {
439
+ if (!this.isEnabled)
440
+ return Promise.resolve();
441
+ const { audioPath: s, ...r } = c || {}, a = o || Date.now(), d = {
442
+ event: i,
443
+ properties: {
444
+ ...this.additionalProperties,
445
+ ...r,
446
+ agentId: this.agentId,
447
+ source: t,
448
+ emittedBy: "agents-sdk",
449
+ sdkVersion: Jt,
450
+ token: this.token,
451
+ time: a,
452
+ $insert_id: this.getRandom(),
453
+ origin: window.location.href,
454
+ "Screen Height": window.screen.height || window.innerHeight,
455
+ "Screen Width": window.screen.width || window.innerWidth,
456
+ "User Agent": navigator.userAgent
457
+ }
458
+ };
459
+ return ye(), et([d]).catch(() => Kt(d)), Promise.resolve();
460
+ },
461
+ linkTrack(i, c, o, s) {
462
+ n[i] || (n[i] = { events: {}, resolvedDependencies: [] }), s.includes(o) || s.push(o);
463
+ const r = n[i];
464
+ if (r.events[o] = { props: c }, r.resolvedDependencies.push(o), s.every(
465
+ (d) => r.resolvedDependencies.includes(d)
466
+ )) {
467
+ const d = s.reduce((m, u) => r.events[u] ? { ...m, ...r.events[u].props } : m, {});
468
+ this.track(i, d), r.resolvedDependencies = r.resolvedDependencies.filter(
469
+ (m) => !s.includes(m)
470
+ ), s.forEach((m) => {
471
+ delete r.events[m];
472
+ });
473
+ }
474
+ }
475
+ };
476
+ }
477
+ function Me() {
478
+ let e = 0;
479
+ return {
480
+ reset: () => e = 0,
481
+ update: () => e = Date.now(),
482
+ get: (t = !1) => t ? Date.now() - e : e
483
+ };
484
+ }
485
+ const X = Me(), ve = Me(), $e = Me();
486
+ function tt(e) {
487
+ return e === b.Playground ? { headers: { [Mt]: "true" } } : {};
488
+ }
489
+ async function nt(e, t, n, i, c = !1, o) {
490
+ return !o && !Qe(i) && (o = await t.newChat(e.id, { persist: c }, tt(i)), n.track("agent-chat", {
491
+ event: "created",
492
+ chatId: o.id,
493
+ mode: i
494
+ })), { chat: o, chatMode: (o == null ? void 0 : o.chat_mode) ?? i };
495
+ }
496
+ function Ht(e) {
497
+ return e && e.length > 0 ? e : [];
498
+ }
499
+ function qt(e) {
500
+ return new Promise((t, n) => {
501
+ const { callbacks: i, host: c, auth: o, externalId: s } = e, { onMessage: r = null, onOpen: a = null, onClose: d = null, onError: m = null } = i || {}, u = new WebSocket(`${c}?authorization=${encodeURIComponent(Xe(o, s))}`);
502
+ u.onmessage = r, u.onclose = d, u.onerror = (f) => {
503
+ console.error(f), m == null || m("Websocket failed to connect", f), n(f);
504
+ }, u.onopen = (f) => {
505
+ a == null || a(f), t(u);
506
+ };
507
+ });
508
+ }
509
+ async function Xt(e) {
510
+ const { retries: t = 1 } = e;
511
+ let n = null;
512
+ for (let i = 0; (n == null ? void 0 : n.readyState) !== WebSocket.OPEN; i++)
513
+ try {
514
+ n = await qt(e);
515
+ } catch (c) {
516
+ if (i === t)
517
+ throw c;
518
+ await He(i * 500);
519
+ }
520
+ return n;
521
+ }
522
+ async function Gt(e, t, n, i) {
523
+ const c = n != null && n.onMessage ? [n.onMessage] : [], o = await Xt({
524
+ auth: e,
525
+ host: t,
526
+ externalId: i,
527
+ callbacks: {
528
+ onError: (s) => {
529
+ var r;
530
+ return (r = n.onError) == null ? void 0 : r.call(n, new ut(s));
531
+ },
532
+ onMessage(s) {
533
+ const r = JSON.parse(s.data);
534
+ c.forEach((a) => a(r.event, r));
535
+ }
536
+ }
537
+ });
538
+ return {
539
+ socket: o,
540
+ disconnect: () => o.close(),
541
+ subscribeToEvents: (s) => c.push(s)
542
+ };
543
+ }
544
+ function ze(e) {
545
+ if (e.answer !== void 0)
546
+ return e.answer;
547
+ let t = 0, n = "";
548
+ for (; t in e; )
549
+ n += e[t++];
550
+ return n;
551
+ }
552
+ function Qt(e, t, n) {
553
+ if (!e.content)
554
+ return;
555
+ const i = {
556
+ id: e.id || `user-${Date.now()}`,
557
+ role: e.role,
558
+ content: e.content,
559
+ parts: ae(e.content),
560
+ created_at: e.created_at || (/* @__PURE__ */ new Date()).toISOString(),
561
+ transcribed: !0
562
+ };
563
+ t.messages.push(i), n == null || n([...t.messages], "user");
564
+ }
565
+ function Yt(e, t, n, i, c, o, s) {
566
+ if (e === z.Transcribe && t.content) {
567
+ Qt(t, i, c);
568
+ return;
569
+ }
570
+ if (!(e === z.Partial || e === z.Answer))
571
+ return;
572
+ const r = i.messages[i.messages.length - 1];
573
+ if (e === z.Answer && (r == null ? void 0 : r.role) === "user" && s === "partial")
574
+ return;
575
+ const d = s === "answer";
576
+ let m;
577
+ if ((r == null ? void 0 : r.role) === "assistant" && !d)
578
+ m = r;
579
+ else if (!r || r.role === "user" || d)
580
+ d && o(), m = {
581
+ id: t.id || `assistant-${Date.now()}`,
582
+ role: t.role || "assistant",
583
+ content: t.content || "",
584
+ parts: [],
585
+ created_at: t.created_at || (/* @__PURE__ */ new Date()).toISOString()
586
+ }, i.messages.push(m);
587
+ else
588
+ return;
589
+ const { content: u, sequence: f } = t;
590
+ if (e === z.Partial)
591
+ n[f] = u;
592
+ else {
593
+ const v = ze(n);
594
+ !!(u && u.length < v.length) && (m.interrupted = !0), n.answer = u;
595
+ }
596
+ const w = ze(n);
597
+ (m.content !== w || e === z.Answer) && (m.content = w, m.parts = ae(w), c == null || c([...i.messages], e));
598
+ }
599
+ function Zt(e, t, n, i, c) {
600
+ const o = {}, s = () => {
601
+ for (const d of Object.keys(o))
602
+ delete o[d];
603
+ };
604
+ let r = null;
605
+ const a = (d, m) => {
606
+ var u, f;
607
+ m === "user" && s(), (f = (u = n.callbacks).onNewMessage) == null || f.call(u, d, m);
608
+ };
609
+ return {
610
+ clearQueue: s,
611
+ onMessage: (d, m) => {
612
+ var u, f;
613
+ if ("content" in m) {
614
+ const w = d === x.ChatAnswer ? z.Answer : d === x.ChatAudioTranscribed ? z.Transcribe : d;
615
+ Yt(
616
+ w,
617
+ m,
618
+ o,
619
+ t,
620
+ a,
621
+ s,
622
+ r
623
+ ), w === z.Partial ? r = "partial" : w === z.Answer && (r = "answer", s()), w === z.Answer && e.track("agent-message-received", {
624
+ content: m.content,
625
+ messages: t.messages.length,
626
+ mode: t.chatMode
627
+ });
628
+ } else {
629
+ const w = x, v = [w.StreamVideoDone, w.StreamVideoError, w.StreamVideoRejected], j = [w.StreamFailed, w.StreamVideoError, w.StreamVideoRejected], I = Ut(m, i, { mode: t.chatMode });
630
+ if (d = d, d === w.StreamVideoCreated && (e.linkTrack("agent-video", I, w.StreamVideoCreated, ["start"]), m.sentiment)) {
631
+ const T = t.messages[t.messages.length - 1];
632
+ if ((T == null ? void 0 : T.role) === "assistant") {
633
+ const P = { ...T, sentiment: m.sentiment };
634
+ t.messages[t.messages.length - 1] = P, a == null || a([...t.messages], r ?? "answer");
635
+ }
636
+ }
637
+ if (v.includes(d)) {
638
+ const T = d.split("/")[1];
639
+ j.includes(d) ? e.track("agent-video", { ...I, event: T }) : e.linkTrack("agent-video", { ...I, event: T }, d, ["done"]);
640
+ }
641
+ j.includes(d) && ((f = (u = n.callbacks).onError) == null || f.call(u, new Ke(`Stream failed with event ${d}`), { data: m })), m.event === w.StreamDone && c();
642
+ }
643
+ }
644
+ };
645
+ }
646
+ function en(e, t, n, i) {
647
+ const c = Ye(e, `${t}/agents/${n}`, i);
648
+ return {
649
+ createStream(o, s) {
650
+ return c.post("/streams", o, { signal: s });
651
+ },
652
+ startConnection(o, s, r, a) {
653
+ return c.post(
654
+ `/streams/${o}/sdp`,
655
+ {
656
+ session_id: r,
657
+ answer: s
658
+ },
659
+ { signal: a }
660
+ );
661
+ },
662
+ addIceCandidate(o, s, r, a) {
663
+ return c.post(
664
+ `/streams/${o}/ice`,
665
+ {
666
+ session_id: r,
667
+ ...s
668
+ },
669
+ { signal: a }
670
+ );
671
+ },
672
+ sendStreamRequest(o, s, r) {
673
+ return c.post(`/streams/${o}`, {
674
+ session_id: s,
675
+ ...r
676
+ });
677
+ },
678
+ close(o, s) {
679
+ return c.delete(`/streams/${o}`, { session_id: s });
680
+ }
681
+ };
682
+ }
683
+ const tn = (e, t) => (n, i) => e && console.log(`[${t}] ${n}`, i ?? ""), nn = 45;
684
+ function rn(e) {
685
+ const t = e.map((a) => a.av).filter((a) => !!a && a.audioPlayout > 0 && a.videoPlayout > 0);
686
+ if (t.length < 2)
687
+ return null;
688
+ const n = t[0].localTs, i = t[t.length - 1].localTs - n, c = t.map((a) => a.audioPlayout - a.videoPlayout), o = c.filter(
689
+ (a) => a > nn || a < -100
690
+ ), s = t.filter((a) => a.localTs - n >= Math.min(5e3, i / 2)), r = (s.length ? s : t).map((a) => a.audioPlayout - a.videoPlayout);
691
+ return {
692
+ sampleCount: t.length,
693
+ durationMs: le(i),
694
+ desyncDurationMs: le(i * (o.length / c.length)),
695
+ maxOffsetMs: le(c.reduce((a, d) => Math.abs(d) > Math.abs(a) ? d : a)),
696
+ residualOffsetMs: le(Ft(r))
697
+ };
698
+ }
699
+ function an(e, t, n) {
700
+ const i = (t.timestamp - e.timestamp) / 1e3;
701
+ return {
702
+ duration: i,
703
+ bytesReceived: t.bytesReceived - e.bytesReceived,
704
+ bitrate: Math.round((t.bytesReceived - e.bytesReceived) * 8 / i),
705
+ packetsReceived: t.packetsReceived - e.packetsReceived,
706
+ packetsLost: t.packetsLost - e.packetsLost,
707
+ framesDropped: t.framesDropped - e.framesDropped,
708
+ framesDecoded: t.framesDecoded - e.framesDecoded,
709
+ jitter: t.jitter,
710
+ avgJitterDelayInInterval: (t.jitterBufferDelay - e.jitterBufferDelay) / (t.jitterBufferEmittedCount - e.jitterBufferEmittedCount),
711
+ jitterBufferEmittedCount: t.jitterBufferEmittedCount - e.jitterBufferEmittedCount,
712
+ jitterBufferDelay: (t.jitterBufferDelay - e.jitterBufferDelay) / i,
713
+ framesPerSecond: t.framesPerSecond,
714
+ freezeCount: t.freezeCount - e.freezeCount,
715
+ freezeDuration: t.freezeDuration - e.freezeDuration,
716
+ lowFpsCount: n
717
+ };
718
+ }
719
+ function sn(e) {
720
+ return e.filter(
721
+ (t) => t.freezeCount > 0 || t.framesPerSecond < 21 || t.framesDropped > 0 || t.packetsLost > 0
722
+ ).map((t) => {
723
+ const { timestamp: n, ...i } = t, c = [];
724
+ return t.freezeCount > 0 && c.push("freeze"), t.framesPerSecond < 21 && c.push("low fps"), t.framesDropped > 0 && c.push("frames dropped"), t.packetsLost > 0 && c.push("packet loss"), {
725
+ ...i,
726
+ causes: c
727
+ };
728
+ });
729
+ }
730
+ function on(e) {
731
+ var a;
732
+ let t = "", n = 0, i = null, c = null;
733
+ const o = /* @__PURE__ */ new Map();
734
+ for (const d of e.values())
735
+ if (d)
736
+ if (d.type === "codec" && ((a = d.mimeType) != null && a.startsWith("video")))
737
+ o.set(d.id, d.mimeType.split("/")[1]);
738
+ else if (d.type === "candidate-pair") {
739
+ const m = d, u = m.currentRoundTripTime ?? 0;
740
+ u > 0 && (m.nominated === !0 || n === 0) && (n = u);
741
+ } else d.type === "inbound-rtp" && d.kind === "video" ? i = d : d.type === "inbound-rtp" && d.kind === "audio" && (c = d);
742
+ if (!i)
743
+ return {};
744
+ const s = i;
745
+ s.codecId && o.has(s.codecId) ? t = o.get(s.codecId) : o.size > 0 && (t = o.values().next().value ?? "");
746
+ const r = {
747
+ codec: t,
748
+ rtt: n,
749
+ timestamp: s.timestamp,
750
+ bytesReceived: s.bytesReceived,
751
+ packetsReceived: s.packetsReceived,
752
+ packetsLost: s.packetsLost,
753
+ framesDropped: s.framesDropped,
754
+ framesDecoded: s.framesDecoded,
755
+ jitter: s.jitter,
756
+ jitterBufferDelay: s.jitterBufferDelay,
757
+ jitterBufferEmittedCount: s.jitterBufferEmittedCount,
758
+ avgJitterDelayInInterval: s.jitterBufferDelay / s.jitterBufferEmittedCount,
759
+ frameWidth: s.frameWidth,
760
+ frameHeight: s.frameHeight,
761
+ framesPerSecond: s.framesPerSecond,
762
+ freezeCount: s.freezeCount,
763
+ freezeDuration: s.totalFreezesDuration
764
+ };
765
+ return c && (r.av = {
766
+ audioPlayout: c.estimatedPlayoutTimestamp ?? 0,
767
+ videoPlayout: s.estimatedPlayoutTimestamp ?? 0,
768
+ localTs: s.timestamp
769
+ }), r;
770
+ }
771
+ function Ne(e, t, n) {
772
+ const i = e.map((a, d) => d === 0 ? n ? {
773
+ timestamp: a.timestamp,
774
+ duration: 0,
775
+ rtt: a.rtt,
776
+ bytesReceived: a.bytesReceived - n.bytesReceived,
777
+ bitrate: (a.bytesReceived - n.bytesReceived) * 8 / (t / 1e3),
778
+ packetsReceived: a.packetsReceived - n.packetsReceived,
779
+ packetsLost: a.packetsLost - n.packetsLost,
780
+ framesDropped: a.framesDropped - n.framesDropped,
781
+ framesDecoded: a.framesDecoded - n.framesDecoded,
782
+ jitter: a.jitter,
783
+ jitterBufferDelay: a.jitterBufferDelay - n.jitterBufferDelay,
784
+ jitterBufferEmittedCount: a.jitterBufferEmittedCount - n.jitterBufferEmittedCount,
785
+ avgJitterDelayInInterval: (a.jitterBufferDelay - n.jitterBufferDelay) / (a.jitterBufferEmittedCount - n.jitterBufferEmittedCount),
786
+ framesPerSecond: a.framesPerSecond,
787
+ freezeCount: a.freezeCount - n.freezeCount,
788
+ freezeDuration: a.freezeDuration - n.freezeDuration
789
+ } : {
790
+ timestamp: a.timestamp,
791
+ rtt: a.rtt,
792
+ duration: 0,
793
+ bytesReceived: a.bytesReceived,
794
+ bitrate: a.bytesReceived * 8 / (t / 1e3),
795
+ packetsReceived: a.packetsReceived,
796
+ packetsLost: a.packetsLost,
797
+ framesDropped: a.framesDropped,
798
+ framesDecoded: a.framesDecoded,
799
+ jitter: a.jitter,
800
+ jitterBufferDelay: a.jitterBufferDelay,
801
+ jitterBufferEmittedCount: a.jitterBufferEmittedCount,
802
+ avgJitterDelayInInterval: a.jitterBufferDelay / a.jitterBufferEmittedCount,
803
+ framesPerSecond: a.framesPerSecond,
804
+ freezeCount: a.freezeCount,
805
+ freezeDuration: a.freezeDuration
806
+ } : {
807
+ timestamp: a.timestamp,
808
+ duration: t * d / 1e3,
809
+ rtt: a.rtt,
810
+ bytesReceived: a.bytesReceived - e[d - 1].bytesReceived,
811
+ bitrate: (a.bytesReceived - e[d - 1].bytesReceived) * 8 / (t / 1e3),
812
+ packetsReceived: a.packetsReceived - e[d - 1].packetsReceived,
813
+ packetsLost: a.packetsLost - e[d - 1].packetsLost,
814
+ framesDropped: a.framesDropped - e[d - 1].framesDropped,
815
+ framesDecoded: a.framesDecoded - e[d - 1].framesDecoded,
816
+ jitter: a.jitter,
817
+ jitterBufferDelay: a.jitterBufferDelay - e[d - 1].jitterBufferDelay,
818
+ jitterBufferEmittedCount: a.jitterBufferEmittedCount - e[d - 1].jitterBufferEmittedCount,
819
+ avgJitterDelayInInterval: (a.jitterBufferDelay - e[d - 1].jitterBufferDelay) / (a.jitterBufferEmittedCount - e[d - 1].jitterBufferEmittedCount),
820
+ framesPerSecond: a.framesPerSecond,
821
+ freezeCount: a.freezeCount - e[d - 1].freezeCount,
822
+ freezeDuration: a.freezeDuration - e[d - 1].freezeDuration
823
+ }), c = sn(i), o = c.reduce((a, d) => a + (d.causes.includes("low fps") ? 1 : 0), 0), s = i.filter((a) => !!a.avgJitterDelayInInterval).map((a) => a.avgJitterDelayInInterval), r = i.filter((a) => !!a.rtt).map((a) => a.rtt);
824
+ return {
825
+ webRTCStats: {
826
+ anomalies: c,
827
+ avSync: Vt(() => rn(e), null),
828
+ minRtt: Le(r),
829
+ avgRtt: Pe(r),
830
+ maxRtt: je(r),
831
+ aggregateReport: an(e[0], e[e.length - 1], o),
832
+ minJitterDelayInInterval: Le(s),
833
+ maxJitterDelayInInterval: je(s),
834
+ avgJitterDelayInInterval: Pe(s)
835
+ },
836
+ codec: e[0].codec,
837
+ resolution: `${e[0].frameWidth}x${e[0].frameHeight}`
838
+ };
839
+ }
840
+ function rt(e, t) {
841
+ for (const n of e.values())
842
+ if ((n == null ? void 0 : n.type) === "inbound-rtp" && n.kind === t)
843
+ return n;
844
+ return null;
845
+ }
846
+ const ne = 10;
847
+ function Pn(e, t) {
848
+ let n = !1, i = !1, c = null, o = 0, s = 0, r = {};
849
+ async function a() {
850
+ if (n) {
851
+ try {
852
+ const d = await e();
853
+ if (!d) {
854
+ c = setTimeout(a, ne);
855
+ return;
856
+ }
857
+ const m = rt(d, "audio");
858
+ if (!m) {
859
+ c = setTimeout(a, ne);
860
+ return;
861
+ }
862
+ const u = m.totalAudioEnergy ?? 0, f = m.totalSamplesReceived ?? 0;
863
+ if (!i) {
864
+ o = u, s = f, i = !0, c = setTimeout(a, ne);
865
+ return;
866
+ }
867
+ const w = u - o, v = f - s;
868
+ if (o = u, s = f, v > 0 && w > 0) {
869
+ n = !1, t(r);
870
+ return;
871
+ }
872
+ } catch {
873
+ }
874
+ n && (c = setTimeout(a, ne));
875
+ }
876
+ }
877
+ return {
878
+ arm(d = {}) {
879
+ r = d, n = !0, i = !1, performance.now(), c !== null && clearTimeout(c), c = setTimeout(a, ne);
880
+ },
881
+ destroy() {
882
+ n = !1, c !== null && (clearTimeout(c), c = null);
883
+ }
884
+ };
885
+ }
886
+ const ue = 100, cn = Math.max(Math.ceil(400 / ue), 1), dn = 0.25, ln = 0.28;
887
+ function un() {
888
+ let e = 0, t, n, i = 0;
889
+ return (c) => {
890
+ const o = rt(c, "video");
891
+ if (!o)
892
+ return { isReceiving: !1, avgJitterDelayInInterval: i };
893
+ const s = o.jitterBufferDelay, r = o.jitterBufferEmittedCount;
894
+ if (n && r > n) {
895
+ const m = s - t, u = r - n;
896
+ i = m / u;
897
+ }
898
+ t = s, n = r;
899
+ const a = o.framesDecoded, d = a - e > 0;
900
+ return e = a, { isReceiving: d, avgJitterDelayInInterval: i, freezeCount: o.freezeCount };
901
+ };
902
+ }
903
+ function fn(e, t, n, i, c) {
904
+ let o = null, s = [], r, a = 0, d = !1, m = re.Unknown, u = re.Unknown, f = 0, w = 0;
905
+ const v = un();
906
+ async function j() {
907
+ const I = await e();
908
+ if (!I)
909
+ return;
910
+ const { isReceiving: T, avgJitterDelayInInterval: P, freezeCount: E } = v(I), Q = on(I);
911
+ if (T)
912
+ a = 0, f = E - w, u = P < dn ? re.Strong : P > ln && f > 1 ? re.Weak : m, u !== m && (c == null || c(u), m = u, w += f, f = 0), d || (i == null || i(S.Start), r = s[s.length - 1], s = [], d = !0), s.push(Q);
913
+ else if (d && (a++, a >= cn)) {
914
+ const H = Ne(s, ue, r);
915
+ i == null || i(S.Stop, H), t() || n(), w = E, d = !1;
916
+ }
917
+ }
918
+ return {
919
+ start: () => {
920
+ o || (o = setInterval(j, ue));
921
+ },
922
+ stop: () => {
923
+ o && (clearInterval(o), o = null);
924
+ },
925
+ getReport: () => Ne(s, ue, r)
926
+ };
927
+ }
928
+ const mn = (window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection).bind(window);
929
+ function Fe(e) {
930
+ switch (e) {
931
+ case "connected":
932
+ return A.Connected;
933
+ case "checking":
934
+ return A.Connecting;
935
+ case "failed":
936
+ return A.Fail;
937
+ case "new":
938
+ return A.New;
939
+ case "closed":
940
+ return A.Closed;
941
+ case "disconnected":
942
+ return A.Disconnected;
943
+ case "completed":
944
+ return A.Completed;
945
+ default:
946
+ return A.New;
947
+ }
948
+ }
949
+ const gn = (e) => (t) => {
950
+ const [n, i = ""] = t.split(/:(.+)/);
951
+ try {
952
+ const c = JSON.parse(i);
953
+ return e("parsed data channel message", { subject: n, data: c }), { subject: n, data: c };
954
+ } catch (c) {
955
+ return e("Failed to parse data channel message, returning data as string", { subject: n, rawData: i, error: c }), { subject: n, data: i };
956
+ }
957
+ };
958
+ function hn({
959
+ statsSignal: e,
960
+ dataChannelSignal: t,
961
+ onVideoStateChange: n,
962
+ report: i,
963
+ log: c
964
+ }) {
965
+ e === S.Start && t === S.Start ? (c("CALLBACK: onVideoStateChange(Start)"), n == null || n(S.Start)) : e === S.Stop && t === S.Stop && (c("CALLBACK: onVideoStateChange(Stop)"), n == null || n(S.Stop, i));
966
+ }
967
+ function pn({
968
+ statsSignal: e,
969
+ dataChannelSignal: t,
970
+ onVideoStateChange: n,
971
+ onAgentActivityStateChange: i,
972
+ report: c,
973
+ log: o
974
+ }) {
975
+ e === S.Start ? (o("CALLBACK: onVideoStateChange(Start)"), n == null || n(S.Start)) : e === S.Stop && (o("CALLBACK: onVideoStateChange(Stop)"), n == null || n(S.Stop, c)), t === S.Start ? i == null || i(ie.Talking) : t === S.Stop && (i == null || i(ie.Idle));
976
+ }
977
+ function Ve({
978
+ statsSignal: e,
979
+ dataChannelSignal: t,
980
+ onVideoStateChange: n,
981
+ onAgentActivityStateChange: i,
982
+ streamType: c,
983
+ report: o,
984
+ log: s
985
+ }) {
986
+ c === W.Legacy ? hn({ statsSignal: e, dataChannelSignal: t, onVideoStateChange: n, report: o, log: s }) : c === W.Fluent && pn({
987
+ statsSignal: e,
988
+ dataChannelSignal: t,
989
+ onVideoStateChange: n,
990
+ onAgentActivityStateChange: i,
991
+ report: o,
992
+ log: s
993
+ });
994
+ }
995
+ async function wn(e, t, { debug: n = !1, callbacks: i, auth: c, baseURL: o = fe, analytics: s }, r) {
996
+ var F;
997
+ const a = tn(n, "WebRTCStreamingManager"), d = gn(a);
998
+ let m = !1, u = !1, f = S.Stop, w = S.Stop;
999
+ const { startConnection: v, sendStreamRequest: j, close: I, createStream: T, addIceCandidate: P } = en(
1000
+ c,
1001
+ o,
1002
+ e,
1003
+ i.onError
1004
+ ), {
1005
+ id: E,
1006
+ offer: Q,
1007
+ ice_servers: H,
1008
+ session_id: V,
1009
+ fluent: se,
1010
+ interrupt_enabled: Y
1011
+ } = await T(t, r);
1012
+ (F = i.onStreamCreated) == null || F.call(i, { stream_id: E, session_id: V, agent_id: e });
1013
+ const R = new mn({ iceServers: H }), q = R.createDataChannel("JanusDataChannel");
1014
+ if (!V)
1015
+ throw new Error("Could not create session_id");
1016
+ const U = se ? W.Fluent : W.Legacy;
1017
+ s.enrich({
1018
+ "stream-type": U
1019
+ });
1020
+ const oe = t.stream_warmup && !se, ce = () => m, te = () => {
1021
+ var g;
1022
+ m = !0, u && (a("CALLBACK: onConnectionStateChange(Connected)"), (g = i.onConnectionStateChange) == null || g.call(i, A.Connected));
1023
+ }, l = fn(
1024
+ () => R.getStats(),
1025
+ ce,
1026
+ te,
1027
+ (g, h) => Ve({
1028
+ statsSignal: w = g,
1029
+ dataChannelSignal: U === W.Legacy ? f : void 0,
1030
+ onVideoStateChange: i.onVideoStateChange,
1031
+ onAgentActivityStateChange: i.onAgentActivityStateChange,
1032
+ report: h,
1033
+ streamType: U,
1034
+ log: a
1035
+ }),
1036
+ (g) => {
1037
+ var h;
1038
+ return (h = i.onConnectivityStateChange) == null ? void 0 : h.call(i, g);
1039
+ }
1040
+ );
1041
+ l.start(), R.onicecandidate = (g) => {
1042
+ var h;
1043
+ a("peerConnection.onicecandidate", g);
1044
+ try {
1045
+ g.candidate && g.candidate.sdpMid && g.candidate.sdpMLineIndex !== null ? P(
1046
+ E,
1047
+ {
1048
+ candidate: g.candidate.candidate,
1049
+ sdpMid: g.candidate.sdpMid,
1050
+ sdpMLineIndex: g.candidate.sdpMLineIndex
1051
+ },
1052
+ V,
1053
+ r
1054
+ ) : P(E, { candidate: null }, V, r);
1055
+ } catch (D) {
1056
+ (h = i.onError) == null || h.call(i, D, { streamId: E });
1057
+ }
1058
+ }, q.onopen = () => {
1059
+ u = !0, (!oe || m) && te();
1060
+ };
1061
+ let p = null;
1062
+ const y = (g) => {
1063
+ var h;
1064
+ p = g, (h = i.onVideoIdChange) == null || h.call(i, g);
1065
+ };
1066
+ function C(g, h) {
1067
+ if (g === x.StreamStarted && typeof h == "object" && "metadata" in h) {
1068
+ const D = h.metadata;
1069
+ y(D.videoId);
1070
+ }
1071
+ g === x.StreamDone && y(null), f = g === x.StreamStarted ? S.Start : S.Stop, Ve({
1072
+ statsSignal: U === W.Legacy ? w : void 0,
1073
+ dataChannelSignal: f,
1074
+ onVideoStateChange: i.onVideoStateChange,
1075
+ onAgentActivityStateChange: i.onAgentActivityStateChange,
1076
+ streamType: U,
1077
+ log: a
1078
+ });
1079
+ }
1080
+ function k(g, h) {
1081
+ var B;
1082
+ const D = typeof h == "string" ? h : h == null ? void 0 : h.metadata;
1083
+ D && s.enrich({ streamMetadata: D }), (B = i.onStreamReady) == null || B.call(i);
1084
+ }
1085
+ const M = {
1086
+ [x.StreamStarted]: C,
1087
+ [x.StreamDone]: C,
1088
+ [x.StreamReady]: k
1089
+ };
1090
+ q.onmessage = (g) => {
1091
+ var B;
1092
+ const { subject: h, data: D } = d(g.data);
1093
+ (B = M[h]) == null || B.call(M, h, D);
1094
+ }, R.oniceconnectionstatechange = () => {
1095
+ var h;
1096
+ a("peerConnection.oniceconnectionstatechange => " + R.iceConnectionState);
1097
+ const g = Fe(R.iceConnectionState);
1098
+ g !== A.Connected && ((h = i.onConnectionStateChange) == null || h.call(i, g, `webrtc:ice-${R.iceConnectionState}`));
1099
+ }, R.ontrack = (g) => {
1100
+ var h;
1101
+ a("peerConnection.ontrack", g), a("CALLBACK: onSrcObjectReady"), (h = i.onSrcObjectReady) == null || h.call(i, g.streams[0]);
1102
+ }, await R.setRemoteDescription(Q), a("set remote description OK");
1103
+ const L = await R.createAnswer();
1104
+ a("create answer OK"), await R.setLocalDescription(L), a("set local description OK"), await v(E, L, V, r), a("start connection OK");
1105
+ function N(g) {
1106
+ var h, D;
1107
+ if (!m || q.readyState !== "open") {
1108
+ a("Data channel is not ready for sending messages"), (h = i.onError) == null || h.call(i, new Ke("Data channel is not ready for sending messages"), {
1109
+ streamId: E
1110
+ });
1111
+ return;
1112
+ }
1113
+ try {
1114
+ q.send(g);
1115
+ } catch (B) {
1116
+ a("Error sending data channel message", B), (D = i.onError) == null || D.call(i, B, { streamId: E });
1117
+ }
1118
+ }
1119
+ return {
1120
+ /**
1121
+ * Method to send request to server to get clip or talk depend on you payload
1122
+ * @param payload
1123
+ */
1124
+ speak(g) {
1125
+ return j(E, V, g);
1126
+ },
1127
+ /**
1128
+ * Method to close RTC connection
1129
+ */
1130
+ async disconnect() {
1131
+ var g;
1132
+ if (E) {
1133
+ const h = Fe(R.iceConnectionState);
1134
+ if (R) {
1135
+ if (h === A.New) {
1136
+ l.stop();
1137
+ return;
1138
+ }
1139
+ R.close(), R.oniceconnectionstatechange = null, R.onnegotiationneeded = null, R.onicecandidate = null, R.ontrack = null;
1140
+ }
1141
+ try {
1142
+ h === A.Connected && await I(E, V).catch((D) => {
1143
+ });
1144
+ } catch (D) {
1145
+ a("Error on close stream connection", D);
1146
+ }
1147
+ (g = i.onAgentActivityStateChange) == null || g.call(i, ie.Idle), l.stop();
1148
+ }
1149
+ },
1150
+ sendDataChannelMessage: N,
1151
+ /**
1152
+ * Session identifier information, should be returned in the body of all streaming requests
1153
+ */
1154
+ sessionId: V,
1155
+ /**
1156
+ * Id of current RTC stream
1157
+ */
1158
+ streamId: E,
1159
+ streamType: U,
1160
+ interruptAvailable: Y ?? !1,
1161
+ isInterruptible: !0,
1162
+ interrupt(g) {
1163
+ if (!Y)
1164
+ throw new Error("Interrupt is not enabled for this stream");
1165
+ if (U !== W.Fluent)
1166
+ throw new Error("Interrupt only available for Fluent streams");
1167
+ if (!p)
1168
+ throw new Error("No active video to interrupt");
1169
+ const h = {
1170
+ type: x.StreamInterrupt,
1171
+ videoId: p,
1172
+ timestamp: Date.now()
1173
+ };
1174
+ N(JSON.stringify(h));
1175
+ }
1176
+ };
1177
+ }
1178
+ var Ce = /* @__PURE__ */ ((e) => (e.V1 = "v1", e.V2 = "v2", e))(Ce || {});
1179
+ async function yn(e, t, n, i) {
1180
+ const c = e.id;
1181
+ switch (t.version) {
1182
+ case "v1": {
1183
+ const { version: o, ...s } = t;
1184
+ return wn(c, s, n, i);
1185
+ }
1186
+ case "v2": {
1187
+ const { version: o, ...s } = t;
1188
+ switch (s.transport.provider) {
1189
+ case Se.Livekit:
1190
+ const { createLiveKitStreamingManager: r } = await import("./livekit-manager-CQ-HE9cP.js");
1191
+ return r(c, s, n);
1192
+ default:
1193
+ throw new Error(`Unsupported transport provider: ${s.transport.provider}`);
1194
+ }
1195
+ }
1196
+ default:
1197
+ throw new Error(`Invalid stream version: ${t.version}`);
1198
+ }
1199
+ }
1200
+ const vn = "cht";
1201
+ function Cn() {
1202
+ return {
1203
+ transport: {
1204
+ provider: Se.Livekit
1205
+ }
1206
+ };
1207
+ }
1208
+ function Sn(e) {
1209
+ var c, o;
1210
+ const { streamOptions: t } = e ?? {}, n = ((c = e == null ? void 0 : e.mixpanelAdditionalProperties) == null ? void 0 : c.plan) !== void 0 ? {
1211
+ plan: (o = e.mixpanelAdditionalProperties) == null ? void 0 : o.plan
1212
+ } : void 0;
1213
+ return { ...{
1214
+ output_resolution: t == null ? void 0 : t.outputResolution,
1215
+ session_timeout: t == null ? void 0 : t.sessionTimeout,
1216
+ stream_warmup: t == null ? void 0 : t.streamWarmup,
1217
+ compatibility_mode: t == null ? void 0 : t.compatibilityMode,
1218
+ fluent: t == null ? void 0 : t.fluent
1219
+ }, ...n && { end_user_data: n } };
1220
+ }
1221
+ function kn(e, t) {
1222
+ return ke(e.presenter.type) ? { version: Ce.V2, ...Cn() } : { version: Ce.V1, ...Sn(t) };
1223
+ }
1224
+ function Mn(e, t, n) {
1225
+ n.track("agent-connection-state-change", { state: e, ...t && { reason: t } });
1226
+ }
1227
+ function Rn(e, t, n, i, c) {
1228
+ c === W.Fluent ? Dn(e, t, n, i, c) : In(e, t, n, i, c);
1229
+ }
1230
+ function Dn(e, t, n, i, c) {
1231
+ e === S.Start ? i.track("stream-session", { event: "start", "stream-type": c }) : e === S.Stop && i.track("stream-session", {
1232
+ event: "stop",
1233
+ is_greenscreen: t.presenter.type === "clip" && t.presenter.is_greenscreen,
1234
+ background: t.presenter.type === "clip" && t.presenter.background,
1235
+ "stream-type": c,
1236
+ ...n
1237
+ });
1238
+ }
1239
+ function Ue(e, t, n, i, c) {
1240
+ e === S.Start ? n.linkTrack("agent-video", { event: "start", ...c, "stream-type": i }, "start", [
1241
+ x.StreamVideoCreated
1242
+ ]) : e === S.Stop && n.linkTrack(
1243
+ "agent-video",
1244
+ {
1245
+ event: "stop",
1246
+ is_greenscreen: t.presenter.type === "clip" && t.presenter.is_greenscreen,
1247
+ background: t.presenter.type === "clip" && t.presenter.background,
1248
+ "stream-type": i
1249
+ },
1250
+ "done",
1251
+ [x.StreamVideoDone]
1252
+ );
1253
+ }
1254
+ function In(e, t, n, i, c) {
1255
+ e === S.Start ? i.linkTrack(
1256
+ "agent-video",
1257
+ { event: "start", latency: X.get(!0), "stream-type": c },
1258
+ "start",
1259
+ [x.StreamVideoCreated]
1260
+ ) : e === S.Stop && i.linkTrack(
1261
+ "agent-video",
1262
+ {
1263
+ event: "stop",
1264
+ is_greenscreen: t.presenter.type === "clip" && t.presenter.is_greenscreen,
1265
+ background: t.presenter.type === "clip" && t.presenter.background,
1266
+ "stream-type": c,
1267
+ ...n
1268
+ },
1269
+ "done",
1270
+ [x.StreamVideoDone]
1271
+ );
1272
+ }
1273
+ function En(e, t, n) {
1274
+ const i = {
1275
+ call_id: t.call_id,
1276
+ name: t.name
1277
+ };
1278
+ if (e === x.ToolCallStarted) {
1279
+ n.track("agent-tool-call", { ...i, event: "started" });
1280
+ return;
1281
+ }
1282
+ const c = t;
1283
+ n.track("agent-tool-call", {
1284
+ ...i,
1285
+ event: e === x.ToolCallDone ? "done" : "error",
1286
+ duration_ms: c.duration_ms,
1287
+ extra_keys: c.extra ? Object.keys(c.extra).length : 0
1288
+ });
1289
+ }
1290
+ function Je(e, t, n, i) {
1291
+ return X.reset(), $e.update(), new Promise(async (c, o) => {
1292
+ try {
1293
+ let s, r = !1;
1294
+ const a = kn(e, t);
1295
+ n.enrich({
1296
+ "stream-version": a.version.toString()
1297
+ });
1298
+ let d = null;
1299
+ const m = e.presenter.type === "expressive";
1300
+ s = await yn(
1301
+ e,
1302
+ a,
1303
+ {
1304
+ ...t,
1305
+ analytics: n,
1306
+ callbacks: {
1307
+ ...t.callbacks,
1308
+ onConnectionStateChange: (u, f) => {
1309
+ var w, v;
1310
+ (v = (w = t.callbacks).onConnectionStateChange) == null || v.call(w, u), Mn(u, f, n), u === A.Connected && (s ? c(s) : r = !0);
1311
+ },
1312
+ onVideoStateChange: (u, f) => {
1313
+ var w, v;
1314
+ (v = (w = t.callbacks).onVideoStateChange) == null || v.call(w, u), Rn(
1315
+ u,
1316
+ e,
1317
+ f,
1318
+ n,
1319
+ s.streamType
1320
+ );
1321
+ },
1322
+ onAgentActivityStateChange: (u) => {
1323
+ var f, w;
1324
+ (w = (f = t.callbacks).onAgentActivityStateChange) == null || w.call(f, u), u === ie.Talking ? (ve.update(), d = (v) => {
1325
+ Ue(
1326
+ S.Start,
1327
+ e,
1328
+ n,
1329
+ s.streamType,
1330
+ v
1331
+ ), d = null;
1332
+ }, m || d({ latency: X.get(!0) })) : (ve.reset(), d = null, Ue(
1333
+ S.Stop,
1334
+ e,
1335
+ n,
1336
+ s.streamType
1337
+ ));
1338
+ },
1339
+ onFirstAudioDetected: (u) => {
1340
+ d == null || d(u);
1341
+ },
1342
+ onStreamReady: () => {
1343
+ const u = $e.get(!0);
1344
+ n.track("agent-chat", { event: "ready", latency: u });
1345
+ },
1346
+ onToolEvent: ((u, f) => {
1347
+ var w, v;
1348
+ (v = (w = t.callbacks).onToolEvent) == null || v.call(w, u, f), En(u, f, n);
1349
+ })
1350
+ }
1351
+ },
1352
+ i
1353
+ ), r && c(s);
1354
+ } catch (s) {
1355
+ o(s);
1356
+ }
1357
+ });
1358
+ }
1359
+ async function Tn(e, t, n, i, c) {
1360
+ var m, u, f, w;
1361
+ const o = async () => {
1362
+ if (ke(e.presenter.type)) {
1363
+ const v = await Je(e, t, i), j = `${vn}_${v.sessionId}`, I = (/* @__PURE__ */ new Date()).toISOString();
1364
+ return { chatResult: {
1365
+ chatMode: b.Functional,
1366
+ chat: {
1367
+ id: j,
1368
+ agent_id: e.id,
1369
+ owner_id: e.owner_id ?? "",
1370
+ created: I,
1371
+ modified: I,
1372
+ agent_id__created_at: I,
1373
+ agent_id__modified_at: I,
1374
+ chat_mode: b.Functional,
1375
+ messages: []
1376
+ }
1377
+ }, streamingManager: v };
1378
+ } else {
1379
+ const v = new AbortController(), j = v.signal;
1380
+ let I;
1381
+ try {
1382
+ const T = nt(
1383
+ e,
1384
+ n,
1385
+ i,
1386
+ t.mode,
1387
+ t.persistentChat,
1388
+ c
1389
+ ), P = Je(e, t, i, j).then((H) => (I = H, H)), [E, Q] = await Promise.all([T, P]);
1390
+ return { chatResult: E, streamingManager: Q };
1391
+ } catch (T) {
1392
+ throw v.abort(), I && await I.disconnect().catch(() => {
1393
+ }), T;
1394
+ }
1395
+ }
1396
+ }, { chatResult: s, streamingManager: r } = await o(), { chat: a, chatMode: d } = s;
1397
+ return d && t.mode !== void 0 && d !== t.mode && (t.mode = d, (u = (m = t.callbacks).onModeChange) == null || u.call(m, d), d !== b.Functional) ? ((w = (f = t.callbacks).onError) == null || w.call(f, new ct(d)), r == null || r.disconnect(), { chat: a }) : { chat: a, streamingManager: r };
1398
+ }
1399
+ async function Ln(e, t) {
1400
+ var U, oe, ce, te;
1401
+ let n = !0;
1402
+ const i = t.mixpanelKey || Dt, c = t.wsURL || Rt, o = t.baseURL || fe, s = t.mode || b.Functional, r = {
1403
+ messages: [],
1404
+ chatMode: s
1405
+ }, a = Wt({
1406
+ token: i,
1407
+ agentId: e,
1408
+ isEnabled: t.enableAnalitics,
1409
+ externalId: t.externalId,
1410
+ mixpanelAdditionalProperties: t.mixpanelAdditionalProperties
1411
+ }), d = Date.now();
1412
+ Be(() => {
1413
+ a.track("agent-sdk", { event: "init" }, d);
1414
+ });
1415
+ const m = t.callbacks.onError;
1416
+ t.callbacks.onError = (l, p) => {
1417
+ a.track("agent-error", { error: ge(l) }), m == null || m(l, p);
1418
+ };
1419
+ const u = Lt(t.auth, o, t.callbacks.onError, t.externalId), f = await u.getById(e);
1420
+ t.debug = t.debug || ((U = f == null ? void 0 : f.advanced_settings) == null ? void 0 : U.ui_debug_mode);
1421
+ const w = ke(f.presenter.type);
1422
+ a.enrich(Bt(f));
1423
+ const { onMessage: v, clearQueue: j } = Zt(a, r, t, f, () => {
1424
+ var l, p, y;
1425
+ (l = r.socketManager) == null || l.disconnect(), (y = (p = t.callbacks).onConnectionStateChange) == null || y.call(p, A.Disconnected);
1426
+ });
1427
+ r.messages = Ht(t.initialMessages), (ce = (oe = t.callbacks).onNewMessage) == null || ce.call(oe, [...r.messages], "answer");
1428
+ const I = (l) => {
1429
+ a.enrich({ videoId: l });
1430
+ }, T = ({ type: l }) => {
1431
+ var y, C, k, M;
1432
+ if (!((y = r.streamingManager) != null && y.interruptAvailable) || !((C = r.streamingManager) != null && C.isInterruptible)) return;
1433
+ const p = r.messages[r.messages.length - 1];
1434
+ a.track("agent-video-interrupt", {
1435
+ type: l || "click",
1436
+ video_duration_to_interrupt: ve.get(!0),
1437
+ message_duration_to_interrupt: X.get(!0)
1438
+ }), p.interrupted = !0, (M = (k = t.callbacks).onNewMessage) == null || M.call(k, [...r.messages], "answer"), r.streamingManager.interrupt(l);
1439
+ }, P = /* @__PURE__ */ new Map();
1440
+ function E(l) {
1441
+ return async (p) => {
1442
+ const y = P.get(l);
1443
+ if (!y)
1444
+ throw new Error(`No handler registered for client tool: ${l}`);
1445
+ try {
1446
+ const C = JSON.parse(p.payload);
1447
+ return await y(C);
1448
+ } catch (C) {
1449
+ throw new Error(`Client tool "${l}" failed: ${C.message}`);
1450
+ }
1451
+ };
1452
+ }
1453
+ function Q() {
1454
+ var l, p, y, C;
1455
+ for (const [k] of P)
1456
+ (p = (l = r.streamingManager) == null ? void 0 : l.unregisterRpcMethod) == null || p.call(l, k), (C = (y = r.streamingManager) == null ? void 0 : y.registerRpcMethod) == null || C.call(y, k, E(k));
1457
+ }
1458
+ function H(l, p) {
1459
+ var C, k;
1460
+ const y = !P.has(l);
1461
+ P.set(l, p), y && ((k = (C = r.streamingManager) == null ? void 0 : C.registerRpcMethod) == null || k.call(C, l, E(l)));
1462
+ }
1463
+ function V(l) {
1464
+ var p, y;
1465
+ P.delete(l), (y = (p = r.streamingManager) == null ? void 0 : p.unregisterRpcMethod) == null || y.call(p, l);
1466
+ }
1467
+ const se = Date.now();
1468
+ Be(() => {
1469
+ a.track("agent-sdk", { event: "loaded", ...jt(f) }, se);
1470
+ });
1471
+ async function Y(l) {
1472
+ var L, N, F, g, h, D, B;
1473
+ St(), (N = (L = t.callbacks).onConnectionStateChange) == null || N.call(L, A.Connecting), X.reset(), l && !n && (delete r.chat, (g = (F = t.callbacks).onNewMessage) == null || g.call(F, [...r.messages], "answer"));
1474
+ const p = s === b.DirectPlayback || w ? Promise.resolve(void 0) : Gt(
1475
+ t.auth,
1476
+ c,
1477
+ { onMessage: v, onError: t.callbacks.onError },
1478
+ t.externalId
1479
+ ), y = we(
1480
+ () => Tn(
1481
+ f,
1482
+ {
1483
+ ...t,
1484
+ mode: s,
1485
+ callbacks: {
1486
+ ...t.callbacks,
1487
+ onVideoIdChange: I,
1488
+ onMessage: v
1489
+ }
1490
+ },
1491
+ u,
1492
+ a,
1493
+ r.chat
1494
+ ),
1495
+ {
1496
+ limit: 3,
1497
+ timeout: kt,
1498
+ timeoutErrorMessage: "Timeout initializing the stream",
1499
+ shouldRetryFn: (O) => (O == null ? void 0 : O.message) !== "Could not connect" && !(O instanceof Oe && (O.status === 429 || O.kind === "InsufficientCreditsError")),
1500
+ delayMs: 1e3
1501
+ }
1502
+ ).catch((O) => {
1503
+ var _, J;
1504
+ throw q(b.Maintenance), (J = (_ = t.callbacks).onConnectionStateChange) == null || J.call(_, A.Fail), O;
1505
+ }), [C, { streamingManager: k, chat: M }] = await Promise.all([p, y]);
1506
+ M && M.id !== ((h = r.chat) == null ? void 0 : h.id) && ((B = (D = t.callbacks).onNewChat) == null || B.call(D, M.id)), r.streamingManager = k, r.socketManager = C, r.chat = M, Q(), n = !1, a.enrich({
1507
+ chatId: M == null ? void 0 : M.id,
1508
+ streamId: k == null ? void 0 : k.streamId,
1509
+ mode: r.chatMode
1510
+ }), q((M == null ? void 0 : M.chat_mode) ?? s);
1511
+ }
1512
+ async function R() {
1513
+ var l, p, y, C;
1514
+ (l = r.socketManager) == null || l.disconnect(), await ((p = r.streamingManager) == null ? void 0 : p.disconnect()), delete r.streamingManager, delete r.socketManager, (C = (y = t.callbacks).onConnectionStateChange) == null || C.call(y, A.Disconnected);
1515
+ }
1516
+ async function q(l) {
1517
+ var p, y;
1518
+ l !== r.chatMode && (a.track("agent-mode-change", { mode: l }), r.chatMode = l, r.chatMode !== b.Functional && await R(), (y = (p = t.callbacks).onModeChange) == null || y.call(p, l));
1519
+ }
1520
+ return {
1521
+ agent: f,
1522
+ getStreamType: () => {
1523
+ var l;
1524
+ return (l = r.streamingManager) == null ? void 0 : l.streamType;
1525
+ },
1526
+ getIsInterruptAvailable: () => {
1527
+ var l;
1528
+ return ((l = r.streamingManager) == null ? void 0 : l.interruptAvailable) ?? !1;
1529
+ },
1530
+ starterMessages: ((te = f.knowledge) == null ? void 0 : te.starter_message) || [],
1531
+ getSTTToken: () => u.getSTTToken(f.id),
1532
+ changeMode: q,
1533
+ enrichAnalytics: a.enrich,
1534
+ async connect() {
1535
+ await Y(!0), a.track("agent-chat", {
1536
+ event: "connect",
1537
+ mode: r.chatMode
1538
+ });
1539
+ },
1540
+ async reconnect() {
1541
+ const l = r.streamingManager;
1542
+ let p;
1543
+ if (w && (l != null && l.reconnect))
1544
+ try {
1545
+ await l.reconnect();
1546
+ } catch (y) {
1547
+ p = ge(y).kind, await R(), await Y(!1);
1548
+ }
1549
+ else
1550
+ await R(), await Y(!1);
1551
+ a.track("agent-chat", {
1552
+ event: "reconnect",
1553
+ mode: r.chatMode,
1554
+ success: !0,
1555
+ ...p && { fallbackReason: p }
1556
+ });
1557
+ },
1558
+ async disconnect() {
1559
+ await R(), a.track("agent-chat", {
1560
+ event: "disconnect",
1561
+ mode: r.chatMode
1562
+ });
1563
+ },
1564
+ publishMicrophoneStream(l) {
1565
+ var p;
1566
+ return (p = r.streamingManager) != null && p.publishMicrophoneStream ? r.streamingManager.publishMicrophoneStream(l) : Promise.reject(new Error("publishMicrophoneStream is not available for this streaming manager"));
1567
+ },
1568
+ unpublishMicrophoneStream() {
1569
+ var l;
1570
+ return (l = r.streamingManager) != null && l.unpublishMicrophoneStream ? r.streamingManager.unpublishMicrophoneStream() : Promise.resolve();
1571
+ },
1572
+ replaceMicrophoneTrack(l) {
1573
+ var p;
1574
+ return (p = r.streamingManager) != null && p.replaceMicrophoneTrack ? r.streamingManager.replaceMicrophoneTrack(l) : Promise.reject(new Error("replaceMicrophoneTrack is not available for this streaming manager"));
1575
+ },
1576
+ publishCameraStream(l) {
1577
+ var p;
1578
+ return (p = r.streamingManager) != null && p.publishCameraStream ? r.streamingManager.publishCameraStream(l) : Promise.reject(new Error("publishCameraStream is not available for this streaming manager"));
1579
+ },
1580
+ unpublishCameraStream() {
1581
+ var l;
1582
+ return (l = r.streamingManager) != null && l.unpublishCameraStream ? r.streamingManager.unpublishCameraStream() : Promise.resolve();
1583
+ },
1584
+ async chat(l) {
1585
+ var k, M, L, N, F;
1586
+ const p = () => {
1587
+ if (Qe(s))
1588
+ throw new $(`${s} is enabled, chat is disabled`);
1589
+ if (l.length >= Ee)
1590
+ throw new $(`Message cannot be more than ${Ee} characters`);
1591
+ if (l.length === 0)
1592
+ throw new $("Message cannot be empty");
1593
+ if (r.chatMode === b.Maintenance)
1594
+ throw new $("Chat is in maintenance mode");
1595
+ if (![b.TextOnly, b.Playground].includes(r.chatMode)) {
1596
+ if (!r.streamingManager)
1597
+ throw new $("Streaming manager is not initialized");
1598
+ if (!r.chat)
1599
+ throw new $("Chat is not initialized");
1600
+ }
1601
+ }, y = async () => {
1602
+ var g, h;
1603
+ if (!r.chat) {
1604
+ const D = await nt(
1605
+ f,
1606
+ u,
1607
+ a,
1608
+ r.chatMode,
1609
+ t.persistentChat
1610
+ );
1611
+ if (!D.chat)
1612
+ throw new ot(r.chatMode, !!t.persistentChat);
1613
+ r.chat = D.chat, (h = (g = t.callbacks).onNewChat) == null || h.call(g, r.chat.id);
1614
+ }
1615
+ return r.chat.id;
1616
+ }, C = async (g, h) => {
1617
+ const D = r.chatMode === b.Playground;
1618
+ return we(w && !D ? async () => {
1619
+ var _, J;
1620
+ return await ((J = (_ = r.streamingManager) == null ? void 0 : _.sendTextMessage) == null ? void 0 : J.call(_, l)), Promise.resolve({});
1621
+ } : async () => {
1622
+ var _, J;
1623
+ return u.chat(
1624
+ f.id,
1625
+ h,
1626
+ {
1627
+ chatMode: r.chatMode,
1628
+ streamId: (_ = r.streamingManager) == null ? void 0 : _.streamId,
1629
+ sessionId: (J = r.streamingManager) == null ? void 0 : J.sessionId,
1630
+ messages: g.map(({ matches: at, ...de }) => de)
1631
+ },
1632
+ {
1633
+ ...tt(r.chatMode),
1634
+ skipErrorHandler: !0
1635
+ }
1636
+ );
1637
+ }, {
1638
+ limit: 2,
1639
+ shouldRetryFn: (_) => {
1640
+ var de, Re, De, Ie;
1641
+ const J = (de = _ == null ? void 0 : _.message) == null ? void 0 : de.includes("missing or invalid session_id");
1642
+ return !((Re = _ == null ? void 0 : _.message) == null ? void 0 : Re.includes("Stream Error")) && !J ? ((Ie = (De = t.callbacks).onError) == null || Ie.call(De, _), !1) : !0;
1643
+ },
1644
+ onRetry: async () => {
1645
+ await R(), await Y(!1);
1646
+ }
1647
+ });
1648
+ };
1649
+ try {
1650
+ j(), p(), r.messages.push({
1651
+ id: ee(),
1652
+ role: "user",
1653
+ content: l,
1654
+ parts: ae(l),
1655
+ created_at: new Date(X.update()).toISOString()
1656
+ }), (M = (k = t.callbacks).onNewMessage) == null || M.call(k, [...r.messages], "user");
1657
+ const g = await y(), h = await C([...r.messages], g);
1658
+ return h.result && r.messages.push({
1659
+ id: ee(),
1660
+ role: "assistant",
1661
+ content: h.result,
1662
+ parts: ae(h.result),
1663
+ created_at: (/* @__PURE__ */ new Date()).toISOString(),
1664
+ context: h.context,
1665
+ matches: h.matches
1666
+ }), a.track("agent-message-send", {
1667
+ event: "success",
1668
+ messages: r.messages.length + 1
1669
+ }), h.result && ((N = (L = t.callbacks).onNewMessage) == null || N.call(L, [...r.messages], "answer"), a.track("agent-message-received", {
1670
+ latency: X.get(!0),
1671
+ messages: r.messages.length
1672
+ })), h;
1673
+ } catch (g) {
1674
+ throw ((F = r.messages[r.messages.length - 1]) == null ? void 0 : F.role) === "assistant" && r.messages.pop(), a.track("agent-message-send", {
1675
+ event: "error",
1676
+ messages: r.messages.length,
1677
+ error: ge(g)
1678
+ }), g;
1679
+ }
1680
+ },
1681
+ rate(l, p, y) {
1682
+ var M, L, N, F;
1683
+ const C = r.messages.find((g) => g.id === l);
1684
+ if (r.chat) {
1685
+ if (!C)
1686
+ throw new $("Message not found");
1687
+ } else throw new $("Chat is not initialized");
1688
+ const k = ((M = C.matches) == null ? void 0 : M.map((g) => [g.document_id, g.id])) ?? [];
1689
+ return a.track("agent-rate", {
1690
+ event: y ? "update" : "create",
1691
+ thumb: p === 1 ? "up" : "down",
1692
+ knowledge_id: ((L = f.knowledge) == null ? void 0 : L.id) ?? "",
1693
+ matches: k,
1694
+ score: p
1695
+ }), y ? u.updateRating(f.id, r.chat.id, y, {
1696
+ knowledge_id: ((N = f.knowledge) == null ? void 0 : N.id) ?? "",
1697
+ message_id: l,
1698
+ matches: k,
1699
+ score: p
1700
+ }) : u.createRating(f.id, r.chat.id, {
1701
+ knowledge_id: ((F = f.knowledge) == null ? void 0 : F.id) ?? "",
1702
+ message_id: l,
1703
+ matches: k,
1704
+ score: p
1705
+ });
1706
+ },
1707
+ deleteRate(l) {
1708
+ if (!r.chat)
1709
+ throw new $("Chat is not initialized");
1710
+ return a.track("agent-rate-delete", { type: "text" }), u.deleteRating(f.id, r.chat.id, l);
1711
+ },
1712
+ async speak(l) {
1713
+ var k, M, L;
1714
+ function p() {
1715
+ if (typeof l == "string") {
1716
+ if (!f.presenter.voice)
1717
+ throw new $("Presenter voice is not initialized");
1718
+ return {
1719
+ type: "text",
1720
+ provider: f.presenter.voice,
1721
+ input: l,
1722
+ ssml: !1
1723
+ };
1724
+ }
1725
+ if (l.type === "text" && !l.provider) {
1726
+ if (!f.presenter.voice)
1727
+ throw new $("Presenter voice is not initialized");
1728
+ return {
1729
+ type: "text",
1730
+ provider: f.presenter.voice,
1731
+ input: l.input,
1732
+ ssml: l.ssml
1733
+ };
1734
+ }
1735
+ return l;
1736
+ }
1737
+ const y = p();
1738
+ if (a.track("agent-speak", y), X.update(), r.messages && y.type === "text" && (r.messages.push({
1739
+ id: ee(),
1740
+ role: "assistant",
1741
+ content: y.input,
1742
+ parts: ae(y.input),
1743
+ created_at: (/* @__PURE__ */ new Date()).toISOString()
1744
+ }), (M = (k = t.callbacks).onNewMessage) == null || M.call(k, [...r.messages], "answer")), Tt(r.chatMode))
1745
+ return {
1746
+ duration: 0,
1747
+ video_id: "",
1748
+ status: "success"
1749
+ };
1750
+ if (!r.streamingManager)
1751
+ throw new $("Please connect to the agent first");
1752
+ return r.streamingManager.speak({
1753
+ script: y,
1754
+ metadata: { chat_id: (L = r.chat) == null ? void 0 : L.id, agent_id: f.id }
1755
+ });
1756
+ },
1757
+ interrupt: T,
1758
+ registerClientTool: H,
1759
+ unregisterClientTool: V
1760
+ };
1761
+ }
1762
+ export {
1763
+ ie as A,
1764
+ G as B,
1765
+ z as C,
1766
+ yt as D,
1767
+ Oe as H,
1768
+ wt as K,
1769
+ lt as N,
1770
+ mt as P,
1771
+ ht as R,
1772
+ x as S,
1773
+ Se as T,
1774
+ ft as U,
1775
+ $ as V,
1776
+ ut as W,
1777
+ tn as a,
1778
+ W as b,
1779
+ Ye as c,
1780
+ fe as d,
1781
+ Ke as e,
1782
+ A as f,
1783
+ re as g,
1784
+ fn as h,
1785
+ Pn as i,
1786
+ S as j,
1787
+ gt as k,
1788
+ X as l,
1789
+ ot as m,
1790
+ xn as n,
1791
+ b as o,
1792
+ ct as p,
1793
+ vt as q,
1794
+ Jt as r,
1795
+ pt as s,
1796
+ ge as t,
1797
+ We as u,
1798
+ Ct as v,
1799
+ Ln as w,
1800
+ bn as x,
1801
+ An as y,
1802
+ At as z
1803
+ };