@d-id/client-sdk 1.1.46 → 1.1.47

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