@d-id/client-sdk 1.1.53 → 1.1.54-staging.242

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