@d-id/client-sdk 1.2.3 → 1.2.4

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