@d-id/client-sdk 1.1.24 → 1.1.26-staging.116

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