@d-id/client-sdk 1.1.0-beta.5 → 1.1.0-beta.51

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,31 +1,31 @@
1
- var ge = Object.defineProperty;
2
- var he = (e, t, n) => t in e ? ge(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
3
- var U = (e, t, n) => (he(e, typeof t != "symbol" ? t + "" : t, n), n);
4
- class Y extends Error {
1
+ var ve = Object.defineProperty;
2
+ var ke = (e, t, a) => t in e ? ve(e, t, { enumerable: !0, configurable: !0, writable: !0, value: a }) : e[t] = a;
3
+ var Y = (e, t, a) => (ke(e, typeof t != "symbol" ? t + "" : t, a), a);
4
+ class Z extends Error {
5
5
  constructor({
6
- kind: n,
7
- description: a,
8
- error: o
6
+ kind: a,
7
+ description: r,
8
+ error: s
9
9
  }) {
10
10
  super(JSON.stringify({
11
- kind: n,
12
- description: a
11
+ kind: a,
12
+ description: r
13
13
  }));
14
- U(this, "kind");
15
- U(this, "description");
16
- U(this, "error");
17
- this.kind = n, this.description = a, this.error = o;
14
+ Y(this, "kind");
15
+ Y(this, "description");
16
+ Y(this, "error");
17
+ this.kind = a, this.description = r, this.error = s;
18
18
  }
19
19
  }
20
- class we extends Y {
21
- constructor(t, n) {
20
+ class De extends Z {
21
+ constructor(t, a) {
22
22
  super({
23
23
  kind: "ChatCreationFailed",
24
- description: `Failed to create ${n ? "persistent" : ""} chat, mode: ${t}`
24
+ description: `Failed to create ${a ? "persistent" : ""} chat, mode: ${t}`
25
25
  });
26
26
  }
27
27
  }
28
- class pe extends Y {
28
+ class Ce extends Z {
29
29
  constructor(t) {
30
30
  super({
31
31
  kind: "ChatModeDowngraded",
@@ -33,17 +33,17 @@ class pe extends Y {
33
33
  });
34
34
  }
35
35
  }
36
- class x extends Y {
37
- constructor(n, a) {
36
+ class K extends Z {
37
+ constructor(a, r) {
38
38
  super({
39
39
  kind: "ValidationError",
40
- description: n
40
+ description: a
41
41
  });
42
- U(this, "key");
43
- this.key = a;
42
+ Y(this, "key");
43
+ this.key = r;
44
44
  }
45
45
  }
46
- class ye extends Y {
46
+ class Re extends Z {
47
47
  constructor(t) {
48
48
  super({
49
49
  kind: "WSError",
@@ -51,8 +51,8 @@ class ye extends Y {
51
51
  });
52
52
  }
53
53
  }
54
- var ve = /* @__PURE__ */ ((e) => (e.TRIAL = "trial", e.BASIC = "basic", e.ENTERPRISE = "enterprise", e.LITE = "lite", e.ADVANCED = "advanced", e))(ve || {}), ke = /* @__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))(ke || {}), De = /* @__PURE__ */ ((e) => (e.Created = "created", e.Started = "started", e.Done = "done", e.Error = "error", e.Rejected = "rejected", e.Ready = "ready", e))(De || {}), Ce = /* @__PURE__ */ ((e) => (e.Unrated = "Unrated", e.Positive = "Positive", e.Negative = "Negative", e))(Ce || {}), b = /* @__PURE__ */ ((e) => (e.Functional = "Functional", e.TextOnly = "TextOnly", e.Maintenance = "Maintenance", e.Playground = "Playground", e.DirectPlayback = "DirectPlayback", e))(b || {}), J = /* @__PURE__ */ ((e) => (e.Embed = "embed", e.Query = "query", e.Partial = "partial", e.Answer = "answer", e.Complete = "done", e))(J || {}), Re = /* @__PURE__ */ ((e) => (e.KnowledgeProcessing = "knowledge/processing", e.KnowledgeIndexing = "knowledge/indexing", e.KnowledgeFailed = "knowledge/error", e.KnowledgeDone = "knowledge/done", e))(Re || {}), Ee = /* @__PURE__ */ ((e) => (e.Knowledge = "knowledge", e.Document = "document", e.Record = "record", e))(Ee || {}), Se = /* @__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))(Se || {}), ie = /* @__PURE__ */ ((e) => (e.Clip = "clip", e.Talk = "talk", e))(ie || {});
55
- const Me = (e) => {
54
+ var Se = /* @__PURE__ */ ((e) => (e.TRIAL = "trial", e.BASIC = "basic", e.ENTERPRISE = "enterprise", e.LITE = "lite", e.ADVANCED = "advanced", e))(Se || {}), _e = /* @__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))(_e || {}), Ee = /* @__PURE__ */ ((e) => (e.Created = "created", e.Started = "started", e.Done = "done", e.Error = "error", e.Rejected = "rejected", e.Ready = "ready", e))(Ee || {}), Ie = /* @__PURE__ */ ((e) => (e.Unrated = "Unrated", e.Positive = "Positive", e.Negative = "Negative", e))(Ie || {}), A = /* @__PURE__ */ ((e) => (e.Functional = "Functional", e.TextOnly = "TextOnly", e.Maintenance = "Maintenance", e.Playground = "Playground", e.DirectPlayback = "DirectPlayback", e.Off = "Off", e))(A || {}), H = /* @__PURE__ */ ((e) => (e.Embed = "embed", e.Query = "query", e.Partial = "partial", e.Answer = "answer", e.Complete = "done", e))(H || {}), Me = /* @__PURE__ */ ((e) => (e.KnowledgeProcessing = "knowledge/processing", e.KnowledgeIndexing = "knowledge/indexing", e.KnowledgeFailed = "knowledge/error", e.KnowledgeDone = "knowledge/done", e))(Me || {}), Te = /* @__PURE__ */ ((e) => (e.Knowledge = "knowledge", e.Document = "document", e.Record = "record", e))(Te || {}), je = /* @__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))(je || {}), de = /* @__PURE__ */ ((e) => (e.Clip = "clip", e.Talk = "talk", e))(de || {});
55
+ const be = (e) => {
56
56
  switch (e) {
57
57
  case "clip":
58
58
  return "clip";
@@ -62,25 +62,22 @@ const Me = (e) => {
62
62
  throw new Error(`Unknown video type: ${e}`);
63
63
  }
64
64
  };
65
- var v = /* @__PURE__ */ ((e) => (e.Start = "START", e.Stop = "STOP", e))(v || {}), W = /* @__PURE__ */ ((e) => (e.Strong = "STRONG", e.Weak = "WEAK", e.Unknown = "UNKNOWN", e))(W || {}), H = /* @__PURE__ */ ((e) => (e.Idle = "IDLE", e.Talking = "TALKING", e))(H || {});
66
- const te = {
67
- "stream/started": "START",
68
- "stream/done": "STOP"
69
- /* Stop */
70
- };
71
- var X = /* @__PURE__ */ ((e) => (e.ChatAnswer = "chat/answer", e.ChatPartial = "chat/partial", e.StreamDone = "stream/done", e.StreamStarted = "stream/started", e.StreamFailed = "stream/error", e.StreamReady = "stream/ready", e.StreamCreated = "stream/created", e.StreamVideoCreated = "stream-video/started", e.StreamVideoDone = "stream-video/done", e.StreamVideoError = "stream-video/error", e.StreamVideoRejected = "stream-video/rejected", e))(X || {}), M = /* @__PURE__ */ ((e) => (e.New = "new", e.Fail = "fail", e.Connected = "connected", e.Connecting = "connecting", e.Closed = "closed", e.Completed = "completed", e.Disconnected = "disconnected", e))(M || {}), F = /* @__PURE__ */ ((e) => (e.Legacy = "legacy", e.Fluent = "fluent", e))(F || {}), _e = /* @__PURE__ */ ((e) => (e.Amazon = "amazon", e.Microsoft = "microsoft", e.Afflorithmics = "afflorithmics", e.Elevenlabs = "elevenlabs", e))(_e || {}), Ie = /* @__PURE__ */ ((e) => (e.Public = "public", e.Premium = "premium", e.Private = "private", e))(Ie || {});
72
- const Te = 45 * 1e3, je = "X-Playground-Chat", K = "https://api.d-id.com", be = "wss://notifications.d-id.com", Pe = "79f81a83a67430be2bc0fd61042b8faa", se = (e) => new Promise((t) => setTimeout(t, e)), q = () => Math.random().toString(16).slice(2);
73
- function Be(e, t) {
74
- let n;
65
+ var p = /* @__PURE__ */ ((e) => (e.Start = "START", e.Stop = "STOP", e))(p || {}), Q = /* @__PURE__ */ ((e) => (e.Strong = "STRONG", e.Weak = "WEAK", e.Unknown = "UNKNOWN", e))(Q || {}), V = /* @__PURE__ */ ((e) => (e.Idle = "IDLE", e.Talking = "TALKING", e))(V || {}), J = /* @__PURE__ */ ((e) => (e.ChatAnswer = "chat/answer", e.ChatPartial = "chat/partial", 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))(J || {}), T = /* @__PURE__ */ ((e) => (e.New = "new", e.Fail = "fail", e.Connected = "connected", e.Connecting = "connecting", e.Closed = "closed", e.Completed = "completed", e.Disconnected = "disconnected", e))(T || {}), U = /* @__PURE__ */ ((e) => (e.Legacy = "legacy", e.Fluent = "fluent", e))(U || {}), Ae = /* @__PURE__ */ ((e) => (e.Amazon = "amazon", e.Microsoft = "microsoft", e.Afflorithmics = "afflorithmics", e.Elevenlabs = "elevenlabs", e))(Ae || {}), Pe = /* @__PURE__ */ ((e) => (e.Public = "public", e.Premium = "premium", e.Private = "private", e))(Pe || {});
66
+ const $e = 45 * 1e3, Be = "X-Playground-Chat", O = "https://api.d-id.com", Le = "wss://notifications.d-id.com", ze = "79f81a83a67430be2bc0fd61042b8faa", ue = (e) => new Promise((t) => setTimeout(t, e)), q = (e = 16) => {
67
+ const t = new Uint8Array(e);
68
+ return window.crypto.getRandomValues(t), Array.from(t, (a) => a.toString(16).padStart(2, "0")).join("").slice(0, 13);
69
+ }, Ne = (e) => [A.TextOnly, A.Playground, A.Maintenance].includes(e), ee = (e) => e && [A.DirectPlayback, A.Off].includes(e);
70
+ function xe(e, t) {
71
+ let a;
75
72
  return {
76
- promise: new Promise((o, s) => {
77
- n = setTimeout(() => s(new Error(t)), e);
73
+ promise: new Promise((s, i) => {
74
+ a = setTimeout(() => i(new Error(t)), e);
78
75
  }),
79
- clear: () => clearTimeout(n)
76
+ clear: () => clearTimeout(a)
80
77
  };
81
78
  }
82
- async function V(e, t) {
83
- const n = {
79
+ async function te(e, t) {
80
+ const a = {
84
81
  limit: (t == null ? void 0 : t.limit) ?? 3,
85
82
  delayMs: (t == null ? void 0 : t.delayMs) ?? 0,
86
83
  timeout: (t == null ? void 0 : t.timeout) ?? 3e4,
@@ -89,238 +86,237 @@ async function V(e, t) {
89
86
  onRetry: (t == null ? void 0 : t.onRetry) ?? (() => {
90
87
  })
91
88
  };
92
- let a;
93
- for (let o = 1; o <= n.limit; o++)
89
+ let r;
90
+ for (let s = 1; s <= a.limit; s++)
94
91
  try {
95
- if (!n.timeout)
92
+ if (!a.timeout)
96
93
  return await e();
97
94
  const {
98
- promise: s,
99
- clear: r
100
- } = Be(n.timeout, n.timeoutErrorMessage), i = e().finally(r);
101
- return await Promise.race([i, s]);
102
- } catch (s) {
103
- if (a = s, !n.shouldRetryFn(s) || o >= n.limit)
104
- throw s;
105
- await se(n.delayMs), n.onRetry(s);
95
+ promise: i,
96
+ clear: c
97
+ } = xe(a.timeout, a.timeoutErrorMessage), n = e().finally(c);
98
+ return await Promise.race([n, i]);
99
+ } catch (i) {
100
+ if (r = i, !a.shouldRetryFn(i) || s >= a.limit)
101
+ throw i;
102
+ await ue(a.delayMs), a.onRetry(i);
106
103
  }
107
- throw a;
104
+ throw r;
108
105
  }
109
- function oe() {
106
+ function le() {
110
107
  let e = window.localStorage.getItem("did_external_key_id");
111
- return e || (e = Math.random().toString(16).slice(2), window.localStorage.setItem("did_external_key_id", e)), e;
108
+ if (!e) {
109
+ let t = q();
110
+ window.localStorage.setItem("did_external_key_id", t), e = t;
111
+ }
112
+ return e;
112
113
  }
113
- let $e = q();
114
- function ce(e) {
114
+ let Fe = q();
115
+ function fe(e) {
115
116
  if (e.type === "bearer")
116
117
  return `Bearer ${e.token}`;
117
118
  if (e.type === "basic")
118
119
  return `Basic ${btoa(`${e.username}:${e.password}`)}`;
119
120
  if (e.type === "key")
120
- return `Client-Key ${e.clientKey}.${oe()}_${$e}`;
121
+ return `Client-Key ${e.clientKey}.${le()}_${Fe}`;
121
122
  throw new Error(`Unknown auth type: ${e}`);
122
123
  }
123
- const Le = (e) => V(e, {
124
+ const Je = (e) => te(e, {
124
125
  limit: 3,
125
126
  delayMs: 1e3,
126
127
  timeout: 0,
127
128
  shouldRetryFn: (t) => t.status === 429
128
129
  });
129
- function G(e, t = K, n) {
130
- const a = async (o, s) => {
130
+ function ae(e, t = O, a) {
131
+ const r = async (s, i) => {
131
132
  const {
132
- skipErrorHandler: r,
133
- ...i
134
- } = s || {}, c = await Le(() => fetch(t + (o != null && o.startsWith("/") ? o : `/${o}`), {
135
- ...i,
133
+ skipErrorHandler: c,
134
+ ...n
135
+ } = i || {}, o = await Je(() => fetch(t + (s != null && s.startsWith("/") ? s : `/${s}`), {
136
+ ...n,
136
137
  headers: {
137
- ...i.headers,
138
- Authorization: ce(e),
138
+ ...n.headers,
139
+ Authorization: fe(e),
139
140
  "Content-Type": "application/json"
140
141
  }
141
142
  }));
142
- if (!c.ok) {
143
- let l = await c.text().catch(() => `Failed to fetch with status ${c.status}`);
144
- const f = new Error(l);
145
- throw n && !r && n(f, {
146
- url: o,
147
- options: i,
148
- headers: c.headers
149
- }), f;
143
+ if (!o.ok) {
144
+ let d = await o.text().catch(() => `Failed to fetch with status ${o.status}`);
145
+ const l = new Error(d);
146
+ throw a && !c && a(l, {
147
+ url: s,
148
+ options: n,
149
+ headers: o.headers
150
+ }), l;
150
151
  }
151
- return c.json();
152
+ return o.json();
152
153
  };
153
154
  return {
154
- get(o, s) {
155
- return a(o, {
156
- ...s,
155
+ get(s, i) {
156
+ return r(s, {
157
+ ...i,
157
158
  method: "GET"
158
159
  });
159
160
  },
160
- post(o, s, r) {
161
- return a(o, {
162
- ...r,
163
- body: JSON.stringify(s),
161
+ post(s, i, c) {
162
+ return r(s, {
163
+ ...c,
164
+ body: JSON.stringify(i),
164
165
  method: "POST"
165
166
  });
166
167
  },
167
- delete(o, s, r) {
168
- return a(o, {
169
- ...r,
170
- body: JSON.stringify(s),
168
+ delete(s, i, c) {
169
+ return r(s, {
170
+ ...c,
171
+ body: JSON.stringify(i),
171
172
  method: "DELETE"
172
173
  });
173
174
  },
174
- patch(o, s, r) {
175
- return a(o, {
176
- ...r,
177
- body: JSON.stringify(s),
175
+ patch(s, i, c) {
176
+ return r(s, {
177
+ ...c,
178
+ body: JSON.stringify(i),
178
179
  method: "PATCH"
179
180
  });
180
181
  }
181
182
  };
182
183
  }
183
- function de(e, t = K, n) {
184
- const a = G(e, `${t}/agents`, n);
184
+ function me(e, t = O, a) {
185
+ const r = ae(e, `${t}/agents`, a);
185
186
  return {
186
- create(o, s) {
187
- return a.post("/", o, s);
187
+ create(s, i) {
188
+ return r.post("/", s, i);
188
189
  },
189
- getAgents(o, s) {
190
- return a.get(`/${o ? `?tag=${o}` : ""}`, s).then((r) => r ?? []);
190
+ getAgents(s, i) {
191
+ return r.get(`/${s ? `?tag=${s}` : ""}`, i).then((c) => c ?? []);
191
192
  },
192
- getById(o, s) {
193
- return a.get(`/${o}`, s);
193
+ getById(s, i) {
194
+ return r.get(`/${s}`, i);
194
195
  },
195
- delete(o, s) {
196
- return a.delete(`/${o}`, void 0, s);
196
+ delete(s, i) {
197
+ return r.delete(`/${s}`, void 0, i);
197
198
  },
198
- update(o, s, r) {
199
- return a.patch(`/${o}`, s, r);
199
+ update(s, i, c) {
200
+ return r.patch(`/${s}`, i, c);
200
201
  },
201
- newChat(o, s, r) {
202
- return a.post(`/${o}/chat`, s, r);
202
+ newChat(s, i, c) {
203
+ return r.post(`/${s}/chat`, i, c);
203
204
  },
204
- chat(o, s, r, i) {
205
- return a.post(`/${o}/chat/${s}`, r, i);
205
+ chat(s, i, c, n) {
206
+ return r.post(`/${s}/chat/${i}`, c, n);
206
207
  },
207
- createRating(o, s, r, i) {
208
- return a.post(`/${o}/chat/${s}/ratings`, r, i);
208
+ createRating(s, i, c, n) {
209
+ return r.post(`/${s}/chat/${i}/ratings`, c, n);
209
210
  },
210
- updateRating(o, s, r, i, c) {
211
- return a.patch(`/${o}/chat/${s}/ratings/${r}`, i, c);
211
+ updateRating(s, i, c, n, o) {
212
+ return r.patch(`/${s}/chat/${i}/ratings/${c}`, n, o);
212
213
  },
213
- deleteRating(o, s, r, i) {
214
- return a.delete(`/${o}/chat/${s}/ratings/${r}`, i);
214
+ deleteRating(s, i, c, n) {
215
+ return r.delete(`/${s}/chat/${i}/ratings/${c}`, n);
215
216
  },
216
- getSTTToken(o, s) {
217
- return a.get(`/${o}/stt-token`, s);
217
+ getSTTToken(s, i) {
218
+ return r.get(`/${s}/stt-token`, i);
218
219
  }
219
220
  };
220
221
  }
221
- const le = (e) => e.type === "clip" && e.presenter_id.startsWith("v2_") ? "clip_v2" : e.type;
222
- function Ae(e) {
223
- var o, s, r, i;
224
- const t = () => /Mobi|Android/i.test(navigator.userAgent) ? "Mobile" : "Desktop", n = () => {
225
- const c = navigator.platform;
226
- return c.toLowerCase().includes("win") ? "Windows" : c.toLowerCase().includes("mac") ? "Mac OS X" : c.toLowerCase().includes("linux") ? "Linux" : "Unknown";
227
- }, a = e.presenter;
222
+ const ge = (e) => e.type === "clip" && e.presenter_id.startsWith("v2_") ? "clip_v2" : e.type;
223
+ function We(e) {
224
+ var s, i, c, n;
225
+ const t = () => /Mobi|Android/i.test(navigator.userAgent) ? "Mobile" : "Desktop", a = () => {
226
+ const o = navigator.platform;
227
+ return o.toLowerCase().includes("win") ? "Windows" : o.toLowerCase().includes("mac") ? "Mac OS X" : o.toLowerCase().includes("linux") ? "Linux" : "Unknown";
228
+ }, r = e.presenter;
228
229
  return {
229
- $os: `${n()}`,
230
+ $os: `${a()}`,
230
231
  isMobile: `${t() == "Mobile"}`,
231
232
  browser: navigator.userAgent,
232
233
  origin: window.location.origin,
233
- agentType: le(a),
234
+ agentType: ge(r),
234
235
  agentVoice: {
235
- voiceId: (s = (o = e.presenter) == null ? void 0 : o.voice) == null ? void 0 : s.voice_id,
236
- provider: (i = (r = e.presenter) == null ? void 0 : r.voice) == null ? void 0 : i.type
236
+ voiceId: (i = (s = e.presenter) == null ? void 0 : s.voice) == null ? void 0 : i.voice_id,
237
+ provider: (n = (c = e.presenter) == null ? void 0 : c.voice) == null ? void 0 : n.type
237
238
  }
238
239
  };
239
240
  }
240
- const ze = (e) => e.reduce((t, n) => t + n, 0), Ne = (e) => ze(e) / e.length;
241
- function Fe(e, t, n) {
242
- var c, l, f;
241
+ const Ue = (e) => e.reduce((t, a) => t + a, 0), ie = (e) => Ue(e) / e.length;
242
+ function Ke(e, t, a) {
243
+ var o, d, l;
243
244
  const {
244
- event: a,
245
- ...o
245
+ event: r,
246
+ ...s
246
247
  } = e, {
247
- template: s
248
+ template: i
248
249
  } = (t == null ? void 0 : t.llm) || {}, {
249
- language: r
250
- } = ((c = t == null ? void 0 : t.presenter) == null ? void 0 : c.voice) || {};
250
+ language: c
251
+ } = ((o = t == null ? void 0 : t.presenter) == null ? void 0 : o.voice) || {};
251
252
  return {
252
- ...o,
253
+ ...s,
253
254
  llm: {
254
- ...o.llm,
255
- template: s
255
+ ...s.llm,
256
+ template: i
256
257
  },
257
258
  script: {
258
- ...o.script,
259
+ ...s.script,
259
260
  provider: {
260
- ...(l = o == null ? void 0 : o.script) == null ? void 0 : l.provider,
261
- language: r
261
+ ...(d = s == null ? void 0 : s.script) == null ? void 0 : d.provider,
262
+ language: c
262
263
  }
263
264
  },
264
- stitch: (t == null ? void 0 : t.presenter.type) === "talk" ? (f = t == null ? void 0 : t.presenter) == null ? void 0 : f.stitch : void 0,
265
- ...n
265
+ stitch: (t == null ? void 0 : t.presenter.type) === "talk" ? (l = t == null ? void 0 : t.presenter) == null ? void 0 : l.stitch : void 0,
266
+ ...a
266
267
  };
267
268
  }
268
- let Q = {};
269
- const xe = "https://api-js.mixpanel.com/track/?verbose=1&ip=1";
270
- function Je(e) {
271
- var s, r, i, c, l, f;
272
- const t = window != null && window.hasOwnProperty("DID_AGENTS_API") ? "agents-ui" : "agents-sdk", n = e.agent.presenter, a = (s = e.agent.llm) == null ? void 0 : s.prompt_customization, o = {
269
+ let G = {};
270
+ const He = "https://api-js.mixpanel.com/track/?verbose=1&ip=1";
271
+ function qe(e) {
272
+ var i, c, n, o, d, l;
273
+ const t = window != null && window.hasOwnProperty("DID_AGENTS_API") ? "agents-ui" : "agents-sdk", a = e.agent.presenter, r = (i = e.agent.llm) == null ? void 0 : i.prompt_customization, s = {
273
274
  token: e.token || "testKey",
274
- distinct_id: e.distinctId || oe(),
275
+ distinct_id: e.distinctId || le(),
275
276
  agentId: e.agent.id,
276
- agentType: le(n),
277
+ agentType: ge(a),
277
278
  owner_id: e.agent.owner_id ?? "",
278
- promptVersion: (r = e.agent.llm) == null ? void 0 : r.prompt_version,
279
+ promptVersion: (c = e.agent.llm) == null ? void 0 : c.prompt_version,
279
280
  behavior: {
280
- role: a == null ? void 0 : a.role,
281
- personality: a == null ? void 0 : a.personality,
282
- instructions: (i = e.agent.llm) == null ? void 0 : i.instructions
281
+ role: r == null ? void 0 : r.role,
282
+ personality: r == null ? void 0 : r.personality,
283
+ instructions: (n = e.agent.llm) == null ? void 0 : n.instructions
283
284
  },
284
- temperature: (c = e.agent.llm) == null ? void 0 : c.temperature,
285
- knowledgeSource: a == null ? void 0 : a.knowledge_source,
286
- starterQuestionsCount: (f = (l = e.agent.knowledge) == null ? void 0 : l.starter_message) == null ? void 0 : f.length,
287
- topicsToAvoid: a == null ? void 0 : a.topics_to_avoid,
288
- maxResponseLength: a == null ? void 0 : a.max_response_length
285
+ temperature: (o = e.agent.llm) == null ? void 0 : o.temperature,
286
+ knowledgeSource: r == null ? void 0 : r.knowledge_source,
287
+ starterQuestionsCount: (l = (d = e.agent.knowledge) == null ? void 0 : d.starter_message) == null ? void 0 : l.length,
288
+ topicsToAvoid: r == null ? void 0 : r.topics_to_avoid,
289
+ maxResponseLength: r == null ? void 0 : r.max_response_length
289
290
  };
290
291
  return {
291
- ...o,
292
+ ...s,
292
293
  additionalProperties: {},
293
294
  isEnabled: e.isEnabled ?? !0,
294
- getRandom: () => Math.random().toString(16).slice(2),
295
- enrich(m) {
296
- const D = {};
297
- if (m && typeof m != "object")
298
- throw new Error("properties must be a flat json object");
299
- for (let w in m)
300
- (typeof m[w] == "string" || typeof m[w] == "number") && (D[w] = m[w]);
295
+ getRandom: q,
296
+ enrich(w) {
301
297
  this.additionalProperties = {
302
298
  ...this.additionalProperties,
303
- ...D
299
+ ...w
304
300
  };
305
301
  },
306
- async track(m, D) {
302
+ async track(w, j) {
307
303
  if (!this.isEnabled)
308
304
  return Promise.resolve();
309
305
  const {
310
- audioPath: w,
311
- ...C
312
- } = D || {}, R = {
306
+ audioPath: R,
307
+ ...D
308
+ } = j || {}, C = {
313
309
  method: "POST",
314
310
  headers: {
315
311
  "Content-Type": "application/x-www-form-urlencoded"
316
312
  },
317
313
  body: new URLSearchParams({
318
314
  data: JSON.stringify([{
319
- event: m,
315
+ event: w,
320
316
  properties: {
321
317
  ...this.additionalProperties,
322
- ...C,
323
- ...o,
318
+ ...D,
319
+ ...s,
324
320
  source: t,
325
321
  time: Date.now(),
326
322
  $insert_id: this.getRandom(),
@@ -333,32 +329,32 @@ function Je(e) {
333
329
  })
334
330
  };
335
331
  try {
336
- return await fetch(xe, R).then((S) => S.json());
337
- } catch (S) {
338
- return console.error(S);
332
+ return await fetch(He, C).then((k) => k.json());
333
+ } catch (k) {
334
+ return console.error(k);
339
335
  }
340
336
  },
341
- linkTrack(m, D, w, C) {
342
- Q[m] || (Q[m] = {
337
+ linkTrack(w, j, R, D) {
338
+ G[w] || (G[w] = {
343
339
  events: {},
344
340
  resolvedDependencies: []
345
- }), C.includes(w) || C.push(w);
346
- const R = Q[m];
347
- if (R.events[w] = {
348
- props: D
349
- }, R.resolvedDependencies.push(w), C.every((P) => R.resolvedDependencies.includes(P))) {
350
- const P = C.reduce((d, g) => R.events[g] ? {
351
- ...d,
352
- ...R.events[g].props
353
- } : d, {});
354
- this.track(m, P), R.resolvedDependencies = R.resolvedDependencies.filter((d) => !C.includes(d)), C.forEach((d) => {
355
- delete R.events[d];
341
+ }), D.includes(R) || D.push(R);
342
+ const C = G[w];
343
+ if (C.events[R] = {
344
+ props: j
345
+ }, C.resolvedDependencies.push(R), D.every((L) => C.resolvedDependencies.includes(L))) {
346
+ const L = D.reduce((P, u) => C.events[u] ? {
347
+ ...P,
348
+ ...C.events[u].props
349
+ } : P, {});
350
+ this.track(w, L), C.resolvedDependencies = C.resolvedDependencies.filter((P) => !D.includes(P)), D.forEach((P) => {
351
+ delete C.events[P];
356
352
  });
357
353
  }
358
354
  }
359
355
  };
360
356
  }
361
- function We() {
357
+ function he() {
362
358
  let e = 0;
363
359
  return {
364
360
  reset: () => e = 0,
@@ -366,233 +362,251 @@ function We() {
366
362
  get: (t = !1) => t ? Date.now() - e : e
367
363
  };
368
364
  }
369
- const N = We();
370
- function ue(e) {
371
- return e === b.Playground ? {
365
+ const F = he(), re = he();
366
+ function we(e) {
367
+ return e === A.Playground ? {
372
368
  headers: {
373
- [je]: "true"
369
+ [Be]: "true"
374
370
  }
375
371
  } : {};
376
372
  }
377
- async function fe(e, t, n, a, o = !1, s) {
373
+ async function pe(e, t, a, r, s = !1, i) {
378
374
  try {
379
- return !s && a !== b.DirectPlayback && (s = await t.newChat(e.id, {
380
- persist: o
381
- }, ue(a)), n.track("agent-chat", {
375
+ return !i && !ee(r) && (i = await t.newChat(e.id, {
376
+ persist: s
377
+ }, we(r)), a.track("agent-chat", {
382
378
  event: "created",
383
- chat_id: s.id,
379
+ chat_id: i.id,
384
380
  agent_id: e.id,
385
- mode: a
381
+ mode: r
386
382
  })), {
387
- chat: s,
388
- chatMode: (s == null ? void 0 : s.chat_mode) ?? a
383
+ chat: i,
384
+ chatMode: (i == null ? void 0 : i.chat_mode) ?? r
389
385
  };
390
- } catch (r) {
386
+ } catch (c) {
391
387
  try {
392
- const i = JSON.parse(r.message);
393
- if ((i == null ? void 0 : i.kind) === "InsufficientCreditsError")
388
+ const n = JSON.parse(c.message);
389
+ if ((n == null ? void 0 : n.kind) === "InsufficientCreditsError")
394
390
  throw new Error("InsufficientCreditsError");
395
- } catch (i) {
396
- console.error("Error parsing the error message:", i);
391
+ } catch (n) {
392
+ console.error("Error parsing the error message:", n);
397
393
  }
398
394
  throw new Error("Cannot create new chat");
399
395
  }
400
396
  }
401
- function Ue(e) {
397
+ function Ve(e) {
402
398
  return e && e.length > 0 ? e : [];
403
399
  }
404
- function He(e) {
405
- return new Promise((t, n) => {
400
+ function Xe(e, t, a, r, s) {
401
+ if (!e || !t)
402
+ throw new Error("Please connect to the agent first");
403
+ if (!e.interruptAvailable)
404
+ throw new Error("Interrupt is not enabled for this stream");
405
+ if (a !== U.Fluent)
406
+ throw new Error("Interrupt only available for Fluent streams");
407
+ if (!r && !s)
408
+ throw new Error("No active video to interrupt");
409
+ }
410
+ async function se(e, t) {
411
+ const a = {
412
+ type: J.StreamInterrupt,
413
+ videoId: t,
414
+ timestamp: Date.now()
415
+ };
416
+ e.sendDataChannelMessage(JSON.stringify(a));
417
+ }
418
+ function Ye(e) {
419
+ return new Promise((t, a) => {
406
420
  const {
407
- callbacks: a,
408
- host: o,
409
- auth: s
421
+ callbacks: r,
422
+ host: s,
423
+ auth: i
410
424
  } = e, {
411
- onMessage: r = null,
412
- onOpen: i = null,
413
- onClose: c = null,
414
- onError: l = null
415
- } = a || {}, f = new WebSocket(`${o}?authorization=${ce(s)}`);
416
- f.onmessage = r, f.onclose = c, f.onerror = (m) => {
417
- console.error(m), l == null || l("Websocket failed to connect", m), n(m);
418
- }, f.onopen = (m) => {
419
- i == null || i(m), t(f);
425
+ onMessage: c = null,
426
+ onOpen: n = null,
427
+ onClose: o = null,
428
+ onError: d = null
429
+ } = r || {}, l = new WebSocket(`${s}?authorization=${fe(i)}`);
430
+ l.onmessage = c, l.onclose = o, l.onerror = (w) => {
431
+ console.error(w), d == null || d("Websocket failed to connect", w), a(w);
432
+ }, l.onopen = (w) => {
433
+ n == null || n(w), t(l);
420
434
  };
421
435
  });
422
436
  }
423
- async function Ke(e) {
437
+ async function Qe(e) {
424
438
  const {
425
439
  retries: t = 1
426
440
  } = e;
427
- let n = null;
428
- for (let a = 0; (n == null ? void 0 : n.readyState) !== WebSocket.OPEN; a++)
441
+ let a = null;
442
+ for (let r = 0; (a == null ? void 0 : a.readyState) !== WebSocket.OPEN; r++)
429
443
  try {
430
- n = await He(e);
431
- } catch (o) {
432
- if (a === t)
433
- throw o;
434
- await se(a * 500);
444
+ a = await Ye(e);
445
+ } catch (s) {
446
+ if (r === t)
447
+ throw s;
448
+ await ue(r * 500);
435
449
  }
436
- return n;
450
+ return a;
437
451
  }
438
- async function qe(e, t, n) {
439
- const a = n != null && n.onMessage ? [n.onMessage] : [], o = await Ke({
452
+ async function Oe(e, t, a) {
453
+ const r = a != null && a.onMessage ? [a.onMessage] : [], s = await Qe({
440
454
  auth: e,
441
455
  host: t,
442
456
  callbacks: {
443
- onError: (s) => {
444
- var r;
445
- return (r = n.onError) == null ? void 0 : r.call(n, new ye(s));
457
+ onError: (i) => {
458
+ var c;
459
+ return (c = a.onError) == null ? void 0 : c.call(a, new Re(i));
446
460
  },
447
- onMessage(s) {
448
- const r = JSON.parse(s.data);
449
- a.forEach((i) => i(r.event, r));
461
+ onMessage(i) {
462
+ const c = JSON.parse(i.data);
463
+ r.forEach((n) => n(c.event, c));
450
464
  }
451
465
  }
452
466
  });
453
467
  return {
454
- socket: o,
455
- disconnect: () => o.close(),
456
- subscribeToEvents: (s) => a.push(s)
468
+ socket: s,
469
+ disconnect: () => s.close(),
470
+ subscribeToEvents: (i) => r.push(i)
457
471
  };
458
472
  }
459
- function Xe(e) {
473
+ function Ze(e) {
460
474
  if (e.answer !== void 0)
461
475
  return e.answer;
462
- let t = 0, n = "";
476
+ let t = 0, a = "";
463
477
  for (; t in e; )
464
- n += e[t++];
465
- return n;
478
+ a += e[t++];
479
+ return a;
466
480
  }
467
- function Ye(e, t, n, a, o) {
468
- const s = a.messages[a.messages.length - 1];
469
- if (!(e === J.Partial || e === J.Answer) || (s == null ? void 0 : s.role) !== "assistant")
481
+ function Ge(e, t, a, r, s) {
482
+ const i = r.messages[r.messages.length - 1];
483
+ if (!(e === H.Partial || e === H.Answer) || (i == null ? void 0 : i.role) !== "assistant")
470
484
  return;
471
485
  const {
472
- content: r,
473
- sequence: i
486
+ content: c,
487
+ sequence: n
474
488
  } = t;
475
- e === J.Partial ? n[i] = r : n.answer = r;
476
- const c = Xe(n);
477
- (s.content !== c || e === J.Answer) && (s.content = c, o == null || o([...a.messages], e));
489
+ e === H.Partial ? a[n] = c : a.answer = c;
490
+ const o = Ze(a);
491
+ (i.content !== o || e === H.Answer) && (i.content = o, s == null || s([...r.messages], e));
478
492
  }
479
- function Qe(e, t, n, a, o) {
480
- let s = {};
493
+ function et(e, t, a, r, s) {
494
+ let i = {};
481
495
  return {
482
- clearQueue: () => s = {},
483
- onMessage: (r, i) => {
484
- var c, l;
485
- if ("content" in i)
486
- Ye(r, i, s, t, n.callbacks.onNewMessage), r === J.Answer && e.track("agent-message-received", {
496
+ clearQueue: () => i = {},
497
+ onMessage: (c, n) => {
498
+ var o, d;
499
+ if ("content" in n)
500
+ Ge(c, n, i, t, a.callbacks.onNewMessage), c === H.Answer && e.track("agent-message-received", {
487
501
  messages: t.messages.length,
488
502
  mode: t.chatMode
489
503
  });
490
504
  else {
491
- const f = X, m = [f.StreamVideoDone, f.StreamVideoError, f.StreamVideoRejected], D = [f.StreamFailed, f.StreamVideoError, f.StreamVideoRejected], w = Fe(i, a, {
505
+ const l = J, w = [l.StreamVideoDone, l.StreamVideoError, l.StreamVideoRejected], j = [l.StreamFailed, l.StreamVideoError, l.StreamVideoRejected], R = Ke(n, r, {
492
506
  mode: t.chatMode
493
507
  });
494
- if (r = r, r === f.StreamVideoCreated)
495
- e.linkTrack("agent-video", w, f.StreamVideoCreated, ["start"]);
496
- else if (m.includes(r)) {
497
- const C = r.split("/")[1];
498
- D.includes(r) ? e.track("agent-video", {
499
- ...w,
500
- event: C
508
+ if (c = c, c === l.StreamVideoCreated)
509
+ e.linkTrack("agent-video", R, l.StreamVideoCreated, ["start"]);
510
+ else if (w.includes(c)) {
511
+ const D = c.split("/")[1];
512
+ j.includes(c) ? e.track("agent-video", {
513
+ ...R,
514
+ event: D
501
515
  }) : e.linkTrack("agent-video", {
502
- ...w,
503
- event: C
504
- }, r, ["done"]);
516
+ ...R,
517
+ event: D
518
+ }, c, ["done"]);
505
519
  }
506
- D.includes(r) && ((l = (c = n.callbacks).onError) == null || l.call(c, new Error(`Stream failed with event ${r}`), {
507
- data: i
508
- })), i.event === f.StreamDone && o();
520
+ j.includes(c) && ((d = (o = a.callbacks).onError) == null || d.call(o, new Error(`Stream failed with event ${c}`), {
521
+ data: n
522
+ })), n.event === l.StreamDone && s();
509
523
  }
510
524
  }
511
525
  };
512
526
  }
513
- function Ve(e, t, n, a) {
514
- const o = G(e, `${t}/agents/${n}`, a);
527
+ function tt(e, t, a, r) {
528
+ const s = ae(e, `${t}/agents/${a}`, r);
515
529
  return {
516
- createStream(s) {
517
- return o.post("/streams", {
518
- output_resolution: s.output_resolution,
519
- compatibility_mode: s.compatibility_mode,
520
- stream_warmup: s.stream_warmup,
521
- session_timeout: s.session_timeout,
522
- fluent: s.fluent
530
+ createStream(i) {
531
+ return s.post("/streams", {
532
+ output_resolution: i.output_resolution,
533
+ compatibility_mode: i.compatibility_mode,
534
+ stream_warmup: i.stream_warmup,
535
+ session_timeout: i.session_timeout,
536
+ fluent: i.fluent
523
537
  });
524
538
  },
525
- startConnection(s, r, i) {
526
- return o.post(`/streams/${s}/sdp`, {
527
- session_id: i,
528
- answer: r
539
+ startConnection(i, c, n) {
540
+ return s.post(`/streams/${i}/sdp`, {
541
+ session_id: n,
542
+ answer: c
529
543
  });
530
544
  },
531
- addIceCandidate(s, r, i) {
532
- return o.post(`/streams/${s}/ice`, {
533
- session_id: i,
534
- ...r
545
+ addIceCandidate(i, c, n) {
546
+ return s.post(`/streams/${i}/ice`, {
547
+ session_id: n,
548
+ ...c
535
549
  });
536
550
  },
537
- sendStreamRequest(s, r, i) {
538
- return o.post(`/streams/${s}`, {
539
- session_id: r,
540
- ...i
551
+ sendStreamRequest(i, c, n) {
552
+ return s.post(`/streams/${i}`, {
553
+ session_id: c,
554
+ ...n
541
555
  });
542
556
  },
543
- close(s, r) {
544
- return o.delete(`/streams/${s}`, {
545
- session_id: r
557
+ close(i, c) {
558
+ return s.delete(`/streams/${i}`, {
559
+ session_id: c
546
560
  });
547
561
  }
548
562
  };
549
563
  }
550
- function Ze(e, t, n, a) {
551
- const o = G(e, `${t}/agents/${n}`, a);
564
+ function rt(e, t, a, r) {
565
+ const s = ae(e, `${t}/agents/${a}`, r);
552
566
  return {
553
- createStream(s, r) {
554
- return o.post("/streams", {
555
- driver_url: s.driver_url,
556
- face: s.face,
557
- config: s.config,
558
- output_resolution: s.output_resolution,
559
- compatibility_mode: s.compatibility_mode,
560
- stream_warmup: s.stream_warmup,
561
- session_timeout: s.session_timeout,
562
- fluent: s.fluent
563
- }, r);
564
- },
565
- startConnection(s, r, i, c) {
566
- return o.post(`/streams/${s}/sdp`, {
567
- session_id: i,
568
- answer: r
567
+ createStream(i, c) {
568
+ return s.post("/streams", {
569
+ driver_url: i.driver_url,
570
+ face: i.face,
571
+ config: i.config,
572
+ output_resolution: i.output_resolution,
573
+ compatibility_mode: i.compatibility_mode,
574
+ stream_warmup: i.stream_warmup,
575
+ session_timeout: i.session_timeout,
576
+ fluent: i.fluent
569
577
  }, c);
570
578
  },
571
- addIceCandidate(s, r, i, c) {
572
- return o.post(`/streams/${s}/ice`, {
573
- session_id: i,
574
- ...r
575
- }, c);
579
+ startConnection(i, c, n, o) {
580
+ return s.post(`/streams/${i}/sdp`, {
581
+ session_id: n,
582
+ answer: c
583
+ }, o);
576
584
  },
577
- sendStreamRequest(s, r, i, c) {
578
- return o.post(`/streams/${s}`, {
579
- session_id: r,
580
- ...i
581
- }, c);
585
+ addIceCandidate(i, c, n, o) {
586
+ return s.post(`/streams/${i}/ice`, {
587
+ session_id: n,
588
+ ...c
589
+ }, o);
582
590
  },
583
- close(s, r, i) {
584
- return o.delete(`/streams/${s}`, {
585
- session_id: r
586
- }, i);
591
+ sendStreamRequest(i, c, n, o) {
592
+ return s.post(`/streams/${i}`, {
593
+ session_id: c,
594
+ ...n
595
+ }, o);
596
+ },
597
+ close(i, c, n) {
598
+ return s.delete(`/streams/${i}`, {
599
+ session_id: c
600
+ }, n);
587
601
  }
588
602
  };
589
603
  }
590
- function Ge(e, t, n) {
591
- const a = (t.timestamp - e.timestamp) / 1e3;
604
+ function nt(e, t, a) {
605
+ const r = (t.timestamp - e.timestamp) / 1e3;
592
606
  return {
593
- duration: a,
607
+ duration: r,
594
608
  bytesReceived: t.bytesReceived - e.bytesReceived,
595
- bitrate: Math.round((t.bytesReceived - e.bytesReceived) * 8 / a),
609
+ bitrate: Math.round((t.bytesReceived - e.bytesReceived) * 8 / r),
596
610
  packetsReceived: t.packetsReceived - e.packetsReceived,
597
611
  packetsLost: t.packetsLost - e.packetsLost,
598
612
  framesDropped: t.framesDropped - e.framesDropped,
@@ -600,686 +614,827 @@ function Ge(e, t, n) {
600
614
  jitter: t.jitter,
601
615
  avgJitterDelayInInterval: (t.jitterBufferDelay - e.jitterBufferDelay) / (t.jitterBufferEmittedCount - e.jitterBufferEmittedCount),
602
616
  jitterBufferEmittedCount: t.jitterBufferEmittedCount - e.jitterBufferEmittedCount,
603
- jitterBufferDelay: (t.jitterBufferDelay - e.jitterBufferDelay) / a,
617
+ jitterBufferDelay: (t.jitterBufferDelay - e.jitterBufferDelay) / r,
604
618
  framesPerSecond: t.framesPerSecond,
605
619
  freezeCount: t.freezeCount - e.freezeCount,
606
620
  freezeDuration: t.freezeDuration - e.freezeDuration,
607
- lowFpsCount: n
621
+ lowFpsCount: a
608
622
  };
609
623
  }
610
- function Oe(e) {
624
+ function at(e) {
611
625
  return e.filter((t) => t.freezeCount > 0 || t.framesPerSecond < 21 || t.framesDropped > 0 || t.packetsLost > 0).map((t) => {
612
626
  const {
613
- timestamp: n,
614
- ...a
615
- } = t, o = [];
616
- return t.freezeCount > 0 && o.push("freeze"), t.framesPerSecond < 21 && o.push("low fps"), t.framesDropped > 0 && o.push("frames dropped"), t.packetsLost > 0 && o.push("packet loss"), {
617
- ...a,
618
- causes: o
627
+ timestamp: a,
628
+ ...r
629
+ } = t, s = [];
630
+ return t.freezeCount > 0 && s.push("freeze"), t.framesPerSecond < 21 && s.push("low fps"), t.framesDropped > 0 && s.push("frames dropped"), t.packetsLost > 0 && s.push("packet loss"), {
631
+ ...r,
632
+ causes: s
619
633
  };
620
634
  });
621
635
  }
622
- function et(e) {
623
- let t = "";
624
- for (const n of e.values())
625
- if (n && n.type === "codec" && n.mimeType.startsWith("video") && (t = n.mimeType.split("/")[1]), n && n.type === "inbound-rtp" && n.kind === "video")
636
+ function it(e) {
637
+ let t = "", a = 0;
638
+ for (const r of e.values())
639
+ if (r && r.type === "codec" && r.mimeType.startsWith("video") && (t = r.mimeType.split("/")[1]), r && r.type === "candidate-pair" && (a = r.currentRoundTripTime), r && r.type === "inbound-rtp" && r.kind === "video")
626
640
  return {
627
641
  codec: t,
628
- timestamp: n.timestamp,
629
- bytesReceived: n.bytesReceived,
630
- packetsReceived: n.packetsReceived,
631
- packetsLost: n.packetsLost,
632
- framesDropped: n.framesDropped,
633
- framesDecoded: n.framesDecoded,
634
- jitter: n.jitter,
635
- jitterBufferDelay: n.jitterBufferDelay,
636
- jitterBufferEmittedCount: n.jitterBufferEmittedCount,
637
- avgJitterDelayInInterval: n.jitterBufferDelay / n.jitterBufferEmittedCount,
638
- frameWidth: n.frameWidth,
639
- frameHeight: n.frameHeight,
640
- framesPerSecond: n.framesPerSecond,
641
- freezeCount: n.freezeCount,
642
- freezeDuration: n.totalFreezesDuration
642
+ rtt: a,
643
+ timestamp: r.timestamp,
644
+ bytesReceived: r.bytesReceived,
645
+ packetsReceived: r.packetsReceived,
646
+ packetsLost: r.packetsLost,
647
+ framesDropped: r.framesDropped,
648
+ framesDecoded: r.framesDecoded,
649
+ jitter: r.jitter,
650
+ jitterBufferDelay: r.jitterBufferDelay,
651
+ jitterBufferEmittedCount: r.jitterBufferEmittedCount,
652
+ avgJitterDelayInInterval: r.jitterBufferDelay / r.jitterBufferEmittedCount,
653
+ frameWidth: r.frameWidth,
654
+ frameHeight: r.frameHeight,
655
+ framesPerSecond: r.framesPerSecond,
656
+ freezeCount: r.freezeCount,
657
+ freezeDuration: r.totalFreezesDuration
643
658
  };
644
659
  return {};
645
660
  }
646
- function tt(e, t, n) {
647
- const a = e.map((i, c) => c === 0 ? n ? {
648
- timestamp: i.timestamp,
661
+ function st(e, t, a) {
662
+ const r = e.map((o, d) => d === 0 ? a ? {
663
+ timestamp: o.timestamp,
649
664
  duration: 0,
650
- bytesReceived: i.bytesReceived - n.bytesReceived,
651
- bitrate: (i.bytesReceived - n.bytesReceived) * 8 / (t / 1e3),
652
- packetsReceived: i.packetsReceived - n.packetsReceived,
653
- packetsLost: i.packetsLost - n.packetsLost,
654
- framesDropped: i.framesDropped - n.framesDropped,
655
- framesDecoded: i.framesDecoded - n.framesDecoded,
656
- jitter: i.jitter,
657
- jitterBufferDelay: i.jitterBufferDelay - n.jitterBufferDelay,
658
- jitterBufferEmittedCount: i.jitterBufferEmittedCount - n.jitterBufferEmittedCount,
659
- avgJitterDelayInInterval: (i.jitterBufferDelay - n.jitterBufferDelay) / (i.jitterBufferEmittedCount - n.jitterBufferEmittedCount),
660
- framesPerSecond: i.framesPerSecond,
661
- freezeCount: i.freezeCount - n.freezeCount,
662
- freezeDuration: i.freezeDuration - n.freezeDuration
665
+ rtt: o.rtt,
666
+ bytesReceived: o.bytesReceived - a.bytesReceived,
667
+ bitrate: (o.bytesReceived - a.bytesReceived) * 8 / (t / 1e3),
668
+ packetsReceived: o.packetsReceived - a.packetsReceived,
669
+ packetsLost: o.packetsLost - a.packetsLost,
670
+ framesDropped: o.framesDropped - a.framesDropped,
671
+ framesDecoded: o.framesDecoded - a.framesDecoded,
672
+ jitter: o.jitter,
673
+ jitterBufferDelay: o.jitterBufferDelay - a.jitterBufferDelay,
674
+ jitterBufferEmittedCount: o.jitterBufferEmittedCount - a.jitterBufferEmittedCount,
675
+ avgJitterDelayInInterval: (o.jitterBufferDelay - a.jitterBufferDelay) / (o.jitterBufferEmittedCount - a.jitterBufferEmittedCount),
676
+ framesPerSecond: o.framesPerSecond,
677
+ freezeCount: o.freezeCount - a.freezeCount,
678
+ freezeDuration: o.freezeDuration - a.freezeDuration
663
679
  } : {
664
- timestamp: i.timestamp,
680
+ timestamp: o.timestamp,
681
+ rtt: o.rtt,
665
682
  duration: 0,
666
- bytesReceived: i.bytesReceived,
667
- bitrate: i.bytesReceived * 8 / (t / 1e3),
668
- packetsReceived: i.packetsReceived,
669
- packetsLost: i.packetsLost,
670
- framesDropped: i.framesDropped,
671
- framesDecoded: i.framesDecoded,
672
- jitter: i.jitter,
673
- jitterBufferDelay: i.jitterBufferDelay,
674
- jitterBufferEmittedCount: i.jitterBufferEmittedCount,
675
- avgJitterDelayInInterval: i.jitterBufferDelay / i.jitterBufferEmittedCount,
676
- framesPerSecond: i.framesPerSecond,
677
- freezeCount: i.freezeCount,
678
- freezeDuration: i.freezeDuration
683
+ bytesReceived: o.bytesReceived,
684
+ bitrate: o.bytesReceived * 8 / (t / 1e3),
685
+ packetsReceived: o.packetsReceived,
686
+ packetsLost: o.packetsLost,
687
+ framesDropped: o.framesDropped,
688
+ framesDecoded: o.framesDecoded,
689
+ jitter: o.jitter,
690
+ jitterBufferDelay: o.jitterBufferDelay,
691
+ jitterBufferEmittedCount: o.jitterBufferEmittedCount,
692
+ avgJitterDelayInInterval: o.jitterBufferDelay / o.jitterBufferEmittedCount,
693
+ framesPerSecond: o.framesPerSecond,
694
+ freezeCount: o.freezeCount,
695
+ freezeDuration: o.freezeDuration
679
696
  } : {
680
- timestamp: i.timestamp,
681
- duration: t * c / 1e3,
682
- bytesReceived: i.bytesReceived - e[c - 1].bytesReceived,
683
- bitrate: (i.bytesReceived - e[c - 1].bytesReceived) * 8 / (t / 1e3),
684
- packetsReceived: i.packetsReceived - e[c - 1].packetsReceived,
685
- packetsLost: i.packetsLost - e[c - 1].packetsLost,
686
- framesDropped: i.framesDropped - e[c - 1].framesDropped,
687
- framesDecoded: i.framesDecoded - e[c - 1].framesDecoded,
688
- jitter: i.jitter,
689
- jitterBufferDelay: i.jitterBufferDelay - e[c - 1].jitterBufferDelay,
690
- jitterBufferEmittedCount: i.jitterBufferEmittedCount - e[c - 1].jitterBufferEmittedCount,
691
- avgJitterDelayInInterval: (i.jitterBufferDelay - e[c - 1].jitterBufferDelay) / (i.jitterBufferEmittedCount - e[c - 1].jitterBufferEmittedCount),
692
- framesPerSecond: i.framesPerSecond,
693
- freezeCount: i.freezeCount - e[c - 1].freezeCount,
694
- freezeDuration: i.freezeDuration - e[c - 1].freezeDuration
695
- }), o = Oe(a), s = o.reduce((i, c) => i + (c.causes.includes("low fps") ? 1 : 0), 0), r = a.map((i) => i.avgJitterDelayInInterval);
697
+ timestamp: o.timestamp,
698
+ duration: t * d / 1e3,
699
+ rtt: o.rtt,
700
+ bytesReceived: o.bytesReceived - e[d - 1].bytesReceived,
701
+ bitrate: (o.bytesReceived - e[d - 1].bytesReceived) * 8 / (t / 1e3),
702
+ packetsReceived: o.packetsReceived - e[d - 1].packetsReceived,
703
+ packetsLost: o.packetsLost - e[d - 1].packetsLost,
704
+ framesDropped: o.framesDropped - e[d - 1].framesDropped,
705
+ framesDecoded: o.framesDecoded - e[d - 1].framesDecoded,
706
+ jitter: o.jitter,
707
+ jitterBufferDelay: o.jitterBufferDelay - e[d - 1].jitterBufferDelay,
708
+ jitterBufferEmittedCount: o.jitterBufferEmittedCount - e[d - 1].jitterBufferEmittedCount,
709
+ avgJitterDelayInInterval: (o.jitterBufferDelay - e[d - 1].jitterBufferDelay) / (o.jitterBufferEmittedCount - e[d - 1].jitterBufferEmittedCount),
710
+ framesPerSecond: o.framesPerSecond,
711
+ freezeCount: o.freezeCount - e[d - 1].freezeCount,
712
+ freezeDuration: o.freezeDuration - e[d - 1].freezeDuration
713
+ }), s = at(r), i = s.reduce((o, d) => o + (d.causes.includes("low fps") ? 1 : 0), 0), c = r.filter((o) => !!o.avgJitterDelayInInterval).map((o) => o.avgJitterDelayInInterval), n = r.filter((o) => !!o.rtt).map((o) => o.rtt);
696
714
  return {
697
715
  webRTCStats: {
698
- anomalies: o,
699
- aggregateReport: Ge(e[0], e[e.length - 1], s),
700
- minJitterDelayInInterval: Math.min(...r),
701
- maxJitterDelayInInterval: Math.max(...r),
702
- avgJitterDelayInInterval: Ne(r)
716
+ anomalies: s,
717
+ minRtt: Math.min(...n),
718
+ avgRtt: ie(n),
719
+ maxRtt: Math.max(...n),
720
+ aggregateReport: nt(e[0], e[e.length - 1], i),
721
+ minJitterDelayInInterval: Math.min(...c),
722
+ maxJitterDelayInInterval: Math.max(...c),
723
+ avgJitterDelayInInterval: ie(c)
703
724
  },
704
725
  codec: e[0].codec,
705
726
  resolution: `${e[0].frameWidth}x${e[0].frameHeight}`
706
727
  };
707
728
  }
708
- const Z = 100, rt = Math.max(Math.ceil(400 / Z), 1), nt = 0.25, at = 0.28;
709
- function it() {
710
- let e = 0, t, n, a = 0;
711
- return (o) => {
712
- for (const s of o.values())
713
- if (s && s.type === "inbound-rtp" && s.kind === "video") {
714
- const r = s.jitterBufferDelay, i = s.jitterBufferEmittedCount;
715
- if (n && i > n) {
716
- const f = r - t, m = i - n;
717
- a = f / m;
729
+ const ne = 100, ot = Math.max(Math.ceil(400 / ne), 1), ct = 0.25, dt = 0.28;
730
+ function ut() {
731
+ let e = 0, t, a, r = 0;
732
+ return (s) => {
733
+ for (const i of s.values())
734
+ if (i && i.type === "inbound-rtp" && i.kind === "video") {
735
+ const c = i.jitterBufferDelay, n = i.jitterBufferEmittedCount;
736
+ if (a && n > a) {
737
+ const l = c - t, w = n - a;
738
+ r = l / w;
718
739
  }
719
- t = r, n = i;
720
- const c = s.framesDecoded, l = c - e > 0;
721
- return e = c, {
722
- isReceiving: l,
723
- avgJitterDelayInInterval: a,
724
- freezeCount: s.freezeCount
740
+ t = c, a = n;
741
+ const o = i.framesDecoded, d = o - e > 0;
742
+ return e = o, {
743
+ isReceiving: d,
744
+ avgJitterDelayInInterval: r,
745
+ freezeCount: i.freezeCount
725
746
  };
726
747
  }
727
748
  return {
728
749
  isReceiving: !1,
729
- avgJitterDelayInInterval: a
750
+ avgJitterDelayInInterval: r
730
751
  };
731
752
  };
732
753
  }
733
- function st(e, t, n, a, o, s = !1) {
734
- let r = [], i, c = 0, l = !1, f = W.Unknown, m = W.Unknown, D = 0, w = 0;
735
- const C = it();
754
+ function lt(e, t, a, r, s, i = !1) {
755
+ let c = [], n, o = 0, d = !1, l = Q.Unknown, w = Q.Unknown, j = 0, R = 0;
756
+ const D = ut();
736
757
  return setInterval(async () => {
737
- const R = await e.getStats(), {
738
- isReceiving: S,
739
- avgJitterDelayInInterval: P,
740
- freezeCount: d
741
- } = C(R), g = et(R);
742
- if (S)
743
- c = 0, D = d - w, m = P < nt ? W.Strong : P > at && D > 1 ? W.Weak : f, m !== f && (o == null || o(m), f = m, w += D, D = 0), l || (a == null || a(v.Start), i = r[r.length - 1], r = [], l = !0), r.push(g);
744
- else if (l && (c++, c >= rt)) {
745
- const y = tt(r, Z, i);
746
- a == null || a(v.Stop, y), t() || n(), l = !1;
758
+ const C = await e.getStats(), {
759
+ isReceiving: k,
760
+ avgJitterDelayInInterval: L,
761
+ freezeCount: P
762
+ } = D(C), u = it(C);
763
+ if (k)
764
+ o = 0, j = P - R, w = L < ct ? Q.Strong : L > dt && j > 1 ? Q.Weak : l, w !== l && (s == null || s(w), l = w, R += j, j = 0), d || (r == null || r(p.Start), n = c[c.length - 1], c = [], d = !0), c.push(u);
765
+ else if (d && (o++, o >= ot)) {
766
+ const m = st(c, ne, n);
767
+ r == null || r(p.Stop, m), t() || a(), R = P, d = !1;
747
768
  }
748
- }, Z);
769
+ }, ne);
749
770
  }
750
- let me = !1;
751
- const z = (e, t) => me && console.log(e, t), ot = (window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection).bind(window);
752
- function re(e) {
771
+ let ye = !1;
772
+ const B = (e, t) => ye && console.log(e, t), ft = (window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection).bind(window);
773
+ function oe(e) {
753
774
  switch (e) {
754
775
  case "connected":
755
- return M.Connected;
776
+ return T.Connected;
756
777
  case "checking":
757
- return M.Connecting;
778
+ return T.Connecting;
758
779
  case "failed":
759
- return M.Fail;
780
+ return T.Fail;
760
781
  case "new":
761
- return M.New;
782
+ return T.New;
762
783
  case "closed":
763
- return M.Closed;
784
+ return T.Closed;
764
785
  case "disconnected":
765
- return M.Disconnected;
786
+ return T.Disconnected;
766
787
  case "completed":
767
- return M.Completed;
788
+ return T.Completed;
768
789
  default:
769
- return M.New;
790
+ return T.New;
770
791
  }
771
792
  }
772
- function ct({
793
+ function mt(e) {
794
+ const [t, a = ""] = e.split(/:(.+)/);
795
+ try {
796
+ const r = JSON.parse(a);
797
+ return B("parsed data channel message", {
798
+ subject: t,
799
+ data: r
800
+ }), {
801
+ subject: t,
802
+ data: r
803
+ };
804
+ } catch (r) {
805
+ return B("Failed to parse data channel message, returning data as string", {
806
+ subject: t,
807
+ rawData: a,
808
+ error: r
809
+ }), {
810
+ subject: t,
811
+ data: a
812
+ };
813
+ }
814
+ }
815
+ function gt({
773
816
  statsSignal: e,
774
817
  dataChannelSignal: t,
775
- onVideoStateChange: n,
776
- report: a
818
+ onVideoStateChange: a,
819
+ report: r
777
820
  }) {
778
- e === v.Start && t === v.Start ? n == null || n(v.Start) : e === v.Stop && t === v.Stop && (n == null || n(v.Stop, a));
821
+ e === p.Start && t === p.Start ? a == null || a(p.Start) : e === p.Stop && t === p.Stop && (a == null || a(p.Stop, r));
779
822
  }
780
- function dt({
823
+ function ht({
781
824
  statsSignal: e,
782
825
  dataChannelSignal: t,
783
- onVideoStateChange: n,
784
- onAgentActivityStateChange: a,
785
- report: o
826
+ onVideoStateChange: a,
827
+ onAgentActivityStateChange: r,
828
+ report: s
786
829
  }) {
787
- e === v.Start ? n == null || n(v.Start) : e === v.Stop && (n == null || n(v.Stop, o)), t === v.Start ? a == null || a(H.Talking) : t === v.Stop && (a == null || a(H.Idle));
830
+ e === p.Start ? a == null || a(p.Start) : e === p.Stop && (a == null || a(p.Stop, s)), t === p.Start ? r == null || r(V.Talking) : t === p.Stop && (r == null || r(V.Idle));
788
831
  }
789
- function ne({
832
+ function ce({
790
833
  statsSignal: e,
791
834
  dataChannelSignal: t,
792
- onVideoStateChange: n,
793
- onAgentActivityStateChange: a,
794
- streamType: o,
795
- report: s
835
+ onVideoStateChange: a,
836
+ onAgentActivityStateChange: r,
837
+ streamType: s,
838
+ report: i
796
839
  }) {
797
- o === F.Legacy ? ct({
840
+ s === U.Legacy ? gt({
798
841
  statsSignal: e,
799
842
  dataChannelSignal: t,
800
- onVideoStateChange: n,
801
- report: s
802
- }) : o === F.Fluent && dt({
843
+ onVideoStateChange: a,
844
+ report: i
845
+ }) : s === U.Fluent && ht({
803
846
  statsSignal: e,
804
847
  dataChannelSignal: t,
805
- onVideoStateChange: n,
806
- onAgentActivityStateChange: a,
807
- report: s
848
+ onVideoStateChange: a,
849
+ onAgentActivityStateChange: r,
850
+ report: i
808
851
  });
809
852
  }
810
- async function lt(e, t, {
811
- debug: n = !1,
812
- callbacks: a,
813
- auth: o,
814
- baseURL: s = K
853
+ async function wt(e, t, {
854
+ debug: a = !1,
855
+ callbacks: r,
856
+ auth: s,
857
+ baseURL: i = O,
858
+ analytics: c
815
859
  }) {
816
- me = n;
817
- let r = !1, i = !1, c = v.Stop, l = v.Stop, f = W.Unknown;
860
+ var W;
861
+ ye = a;
862
+ let n = !1, o = !1, d = p.Stop, l = p.Stop;
818
863
  const {
819
- startConnection: m,
820
- sendStreamRequest: D,
821
- close: w,
822
- createStream: C,
823
- addIceCandidate: R
824
- } = t.videoType === ie.Clip ? Ve(o, s, e, a.onError) : Ze(o, s, e, a.onError), {
825
- id: S,
826
- offer: P,
827
- ice_servers: d,
828
- session_id: g,
829
- fluent: y
830
- } = await C(t), h = new ot({
831
- iceServers: d
832
- }), I = h.createDataChannel("JanusDataChannel");
833
- if (!g)
864
+ startConnection: w,
865
+ sendStreamRequest: j,
866
+ close: R,
867
+ createStream: D,
868
+ addIceCandidate: C
869
+ } = t.videoType === de.Clip ? tt(s, i, e, r.onError) : rt(s, i, e, r.onError), {
870
+ id: k,
871
+ offer: L,
872
+ ice_servers: P,
873
+ session_id: u,
874
+ fluent: m,
875
+ interrupt_enabled: v
876
+ } = await D(t);
877
+ (W = r.onStreamCreated) == null || W.call(r, {
878
+ stream_id: k,
879
+ session_id: u,
880
+ agent_id: e
881
+ });
882
+ const g = new ft({
883
+ iceServers: P
884
+ }), S = g.createDataChannel("JanusDataChannel");
885
+ if (!u)
834
886
  throw new Error("Could not create session_id");
835
- const k = y ? F.Fluent : F.Legacy, T = t.stream_warmup && !y, $ = () => r, B = () => {
836
- var u;
837
- r = !0, i && ((u = a.onConnectionStateChange) == null || u.call(a, M.Connected));
838
- }, E = st(h, $, B, (u, p) => ne({
839
- statsSignal: l = u,
840
- dataChannelSignal: k === F.Legacy ? c : void 0,
841
- onVideoStateChange: a.onVideoStateChange,
842
- onAgentActivityStateChange: a.onAgentActivityStateChange,
843
- report: p,
844
- streamType: k
845
- }), (u) => {
846
- var p;
847
- return (p = a.onConnectivityStateChange) == null ? void 0 : p.call(a, f);
848
- }, T);
849
- h.onicecandidate = (u) => {
850
- var p;
851
- z("peerConnection.onicecandidate", u);
887
+ const y = m ? U.Fluent : U.Legacy;
888
+ c.enrich({
889
+ "stream-type": y
890
+ });
891
+ const M = t.stream_warmup && !m, $ = () => n, z = () => {
892
+ var f;
893
+ n = !0, o && ((f = r.onConnectionStateChange) == null || f.call(r, T.Connected));
894
+ }, _ = lt(g, $, z, (f, h) => ce({
895
+ statsSignal: l = f,
896
+ dataChannelSignal: y === U.Legacy ? d : void 0,
897
+ onVideoStateChange: r.onVideoStateChange,
898
+ onAgentActivityStateChange: r.onAgentActivityStateChange,
899
+ report: h,
900
+ streamType: y
901
+ }), (f) => {
902
+ var h;
903
+ return (h = r.onConnectivityStateChange) == null ? void 0 : h.call(r, f);
904
+ }, M);
905
+ g.onicecandidate = (f) => {
906
+ var h;
907
+ B("peerConnection.onicecandidate", f);
852
908
  try {
853
- u.candidate && u.candidate.sdpMid && u.candidate.sdpMLineIndex !== null ? R(S, {
854
- candidate: u.candidate.candidate,
855
- sdpMid: u.candidate.sdpMid,
856
- sdpMLineIndex: u.candidate.sdpMLineIndex
857
- }, g) : R(S, {
909
+ f.candidate && f.candidate.sdpMid && f.candidate.sdpMLineIndex !== null ? C(k, {
910
+ candidate: f.candidate.candidate,
911
+ sdpMid: f.candidate.sdpMid,
912
+ sdpMLineIndex: f.candidate.sdpMLineIndex
913
+ }, u) : C(k, {
858
914
  candidate: null
859
- }, g);
860
- } catch (j) {
861
- (p = a.onError) == null || p.call(a, j, {
862
- streamId: S
915
+ }, u);
916
+ } catch (b) {
917
+ (h = r.onError) == null || h.call(r, b, {
918
+ streamId: k
863
919
  });
864
920
  }
865
- }, I.onopen = () => {
866
- i = !0, (!T || r) && B();
867
- }, I.onmessage = (u) => {
868
- u.data in te && (c = te[u.data], ne({
869
- statsSignal: k === F.Legacy ? l : void 0,
870
- dataChannelSignal: c,
871
- onVideoStateChange: a.onVideoStateChange,
872
- onAgentActivityStateChange: a.onAgentActivityStateChange,
873
- streamType: k
874
- }));
875
- }, h.oniceconnectionstatechange = () => {
876
- var p;
877
- z("peerConnection.oniceconnectionstatechange => " + h.iceConnectionState);
878
- const u = re(h.iceConnectionState);
879
- u !== M.Connected && ((p = a.onConnectionStateChange) == null || p.call(a, u));
880
- }, h.ontrack = (u) => {
881
- var p;
882
- z("peerConnection.ontrack", u), (p = a.onSrcObjectReady) == null || p.call(a, u.streams[0]);
883
- }, await h.setRemoteDescription(P), z("set remote description OK");
884
- const _ = await h.createAnswer();
885
- return z("create answer OK"), await h.setLocalDescription(_), z("set local description OK"), await m(S, _, g), z("start connection OK"), {
921
+ }, S.onopen = () => {
922
+ o = !0, (!M || n) && z();
923
+ };
924
+ function E(f) {
925
+ d = f === J.StreamStarted ? p.Start : p.Stop, ce({
926
+ statsSignal: y === U.Legacy ? l : void 0,
927
+ dataChannelSignal: d,
928
+ onVideoStateChange: r.onVideoStateChange,
929
+ onAgentActivityStateChange: r.onAgentActivityStateChange,
930
+ streamType: y
931
+ });
932
+ }
933
+ function I(f, h) {
934
+ const b = typeof h == "string" ? h : h == null ? void 0 : h.metadata;
935
+ b && c.enrich({
936
+ streamMetadata: b
937
+ }), c.track("agent-chat", {
938
+ event: "ready"
939
+ });
940
+ }
941
+ const N = {
942
+ [J.StreamStarted]: E,
943
+ [J.StreamDone]: E,
944
+ [J.StreamReady]: I
945
+ };
946
+ S.onmessage = (f) => {
947
+ var X;
948
+ const {
949
+ subject: h,
950
+ data: b
951
+ } = mt(f.data);
952
+ (X = N[h]) == null || X.call(N, h, b);
953
+ }, g.oniceconnectionstatechange = () => {
954
+ var h;
955
+ B("peerConnection.oniceconnectionstatechange => " + g.iceConnectionState);
956
+ const f = oe(g.iceConnectionState);
957
+ f !== T.Connected && ((h = r.onConnectionStateChange) == null || h.call(r, f));
958
+ }, g.ontrack = (f) => {
959
+ var h;
960
+ B("peerConnection.ontrack", f), (h = r.onSrcObjectReady) == null || h.call(r, f.streams[0]);
961
+ }, await g.setRemoteDescription(L), B("set remote description OK");
962
+ const x = await g.createAnswer();
963
+ return B("create answer OK"), await g.setLocalDescription(x), B("set local description OK"), await w(k, x, u), B("start connection OK"), {
886
964
  /**
887
965
  * Method to send request to server to get clip or talk depend on you payload
888
966
  * @param payload
889
967
  */
890
- speak(u) {
891
- return D(S, g, u);
968
+ speak(f) {
969
+ return j(k, u, f);
892
970
  },
893
971
  /**
894
972
  * Method to close RTC connection
895
973
  */
896
974
  async disconnect() {
897
- var u, p, j;
898
- if (S) {
899
- const L = re(h.iceConnectionState);
900
- if (h) {
901
- if (L === M.New) {
902
- (u = a.onVideoStateChange) == null || u.call(a, v.Stop), clearInterval(E);
975
+ var f;
976
+ if (k) {
977
+ const h = oe(g.iceConnectionState);
978
+ if (g) {
979
+ if (h === T.New) {
980
+ clearInterval(_);
903
981
  return;
904
982
  }
905
- h.close(), h.oniceconnectionstatechange = null, h.onnegotiationneeded = null, h.onicecandidate = null, h.ontrack = null;
983
+ g.close(), g.oniceconnectionstatechange = null, g.onnegotiationneeded = null, g.onicecandidate = null, g.ontrack = null;
906
984
  }
907
985
  try {
908
- L === M.Connected && await w(S, g).catch((A) => {
986
+ h === T.Connected && await R(k, u).catch((b) => {
909
987
  });
910
- } catch (A) {
911
- z("Error on close stream connection", A);
988
+ } catch (b) {
989
+ B("Error on close stream connection", b);
912
990
  }
913
- (p = a.onVideoStateChange) == null || p.call(a, v.Stop), (j = a.onAgentActivityStateChange) == null || j.call(a, H.Idle), clearInterval(E);
991
+ (f = r.onAgentActivityStateChange) == null || f.call(r, V.Idle), clearInterval(_);
992
+ }
993
+ },
994
+ /**
995
+ * Method to send data channel messages to the server
996
+ */
997
+ sendDataChannelMessage(f) {
998
+ var h, b;
999
+ if (!n || S.readyState !== "open") {
1000
+ B("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"), {
1001
+ streamId: k
1002
+ });
1003
+ return;
1004
+ }
1005
+ try {
1006
+ S.send(f);
1007
+ } catch (X) {
1008
+ B("Error sending data channel message", X), (b = r.onError) == null || b.call(r, X, {
1009
+ streamId: k
1010
+ });
914
1011
  }
915
1012
  },
916
1013
  /**
917
1014
  * Session identifier information, should be returned in the body of all streaming requests
918
1015
  */
919
- sessionId: g,
1016
+ sessionId: u,
920
1017
  /**
921
1018
  * Id of current RTC stream
922
1019
  */
923
- streamId: S,
924
- streamType: k
1020
+ streamId: k,
1021
+ streamType: y,
1022
+ interruptAvailable: v
925
1023
  };
926
1024
  }
927
- function ut(e, t) {
1025
+ function pt(e, t) {
928
1026
  const {
929
- streamOptions: n
1027
+ streamOptions: a
930
1028
  } = t ?? {};
931
1029
  return {
932
- videoType: Me(e.presenter.type),
933
- output_resolution: n == null ? void 0 : n.outputResolution,
934
- session_timeout: n == null ? void 0 : n.sessionTimeout,
935
- stream_warmup: n == null ? void 0 : n.streamWarmup,
936
- compatibility_mode: n == null ? void 0 : n.compatibilityMode,
937
- fluent: n == null ? void 0 : n.fluent
1030
+ videoType: be(e.presenter.type),
1031
+ output_resolution: a == null ? void 0 : a.outputResolution,
1032
+ session_timeout: a == null ? void 0 : a.sessionTimeout,
1033
+ stream_warmup: a == null ? void 0 : a.streamWarmup,
1034
+ compatibility_mode: a == null ? void 0 : a.compatibilityMode,
1035
+ fluent: a == null ? void 0 : a.fluent
938
1036
  };
939
1037
  }
940
- function ae(e, t, n, a, o) {
941
- N.get() > 0 && (e === v.Start ? a.linkTrack("agent-video", {
1038
+ function yt(e, t, a, r, s) {
1039
+ s === U.Fluent ? vt(e, t, a, r, s) : Dt(e, t, a, r, s);
1040
+ }
1041
+ function vt(e, t, a, r, s) {
1042
+ e === p.Start ? r.track("stream-session", {
942
1043
  event: "start",
943
- latency: N.get(!0),
944
- "stream-type": o
945
- }, "start", [X.StreamVideoCreated]) : e === v.Stop && a.linkTrack("agent-video", {
1044
+ "stream-type": s
1045
+ }) : e === p.Stop && r.track("stream-session", {
946
1046
  event: "stop",
947
1047
  is_greenscreen: t.presenter.type === "clip" && t.presenter.is_greenscreen,
948
1048
  background: t.presenter.type === "clip" && t.presenter.background,
949
- "stream-type": o,
950
- ...n
951
- }, "done", [X.StreamVideoDone]));
1049
+ "stream-type": s,
1050
+ ...a
1051
+ });
952
1052
  }
953
- function ft(e, t, n) {
954
- return N.reset(), new Promise(async (a, o) => {
1053
+ function kt(e, t, a, r) {
1054
+ F.get() <= 0 || (e === p.Start ? a.linkTrack("agent-video", {
1055
+ event: "start",
1056
+ latency: F.get(!0),
1057
+ "stream-type": r
1058
+ }, "start", [J.StreamVideoCreated]) : e === p.Stop && a.linkTrack("agent-video", {
1059
+ event: "stop",
1060
+ is_greenscreen: t.presenter.type === "clip" && t.presenter.is_greenscreen,
1061
+ background: t.presenter.type === "clip" && t.presenter.background,
1062
+ "stream-type": r
1063
+ }, "done", [J.StreamVideoDone]));
1064
+ }
1065
+ function Dt(e, t, a, r, s) {
1066
+ F.get() <= 0 || (e === p.Start ? r.linkTrack("agent-video", {
1067
+ event: "start",
1068
+ latency: F.get(!0),
1069
+ "stream-type": s
1070
+ }, "start", [J.StreamVideoCreated]) : e === p.Stop && r.linkTrack("agent-video", {
1071
+ event: "stop",
1072
+ is_greenscreen: t.presenter.type === "clip" && t.presenter.is_greenscreen,
1073
+ background: t.presenter.type === "clip" && t.presenter.background,
1074
+ "stream-type": s,
1075
+ ...a
1076
+ }, "done", [J.StreamVideoDone]));
1077
+ }
1078
+ function Ct(e, t, a) {
1079
+ return F.reset(), new Promise(async (r, s) => {
955
1080
  try {
956
- const s = await lt(e.id, ut(e, t), {
1081
+ const i = await wt(e.id, pt(e, t), {
957
1082
  ...t,
958
- analytics: n,
1083
+ analytics: a,
959
1084
  callbacks: {
960
1085
  ...t.callbacks,
961
- onConnectionStateChange: (r) => {
962
- var i, c;
963
- (c = (i = t.callbacks).onConnectionStateChange) == null || c.call(i, r), r === M.Connected && a(s);
1086
+ onConnectionStateChange: (c) => {
1087
+ var n, o;
1088
+ (o = (n = t.callbacks).onConnectionStateChange) == null || o.call(n, c), c === T.Connected && r(i);
964
1089
  },
965
- onVideoStateChange: (r, i) => {
966
- var c, l;
967
- (l = (c = t.callbacks).onVideoStateChange) == null || l.call(c, r), ae(r, e, i, n, s.streamType);
1090
+ onVideoStateChange: (c, n) => {
1091
+ var o, d;
1092
+ (d = (o = t.callbacks).onVideoStateChange) == null || d.call(o, c), yt(c, e, n, a, i.streamType);
968
1093
  },
969
- onAgentActivityStateChange: (r) => {
970
- var i, c;
971
- (c = (i = t.callbacks).onAgentActivityStateChange) == null || c.call(i, r), ae(r === H.Talking ? v.Start : v.Stop, e, void 0, n, s.streamType);
1094
+ onAgentActivityStateChange: (c) => {
1095
+ var n, o;
1096
+ (o = (n = t.callbacks).onAgentActivityStateChange) == null || o.call(n, c), c === V.Talking ? re.update() : re.reset(), kt(c === V.Talking ? p.Start : p.Stop, e, a, i.streamType);
972
1097
  }
973
1098
  }
974
1099
  });
975
- } catch (s) {
976
- o(s);
1100
+ } catch (i) {
1101
+ s(i);
977
1102
  }
978
1103
  });
979
1104
  }
980
- async function mt(e, t, n, a, o) {
981
- var c, l, f, m;
1105
+ async function Rt(e, t, a, r, s) {
1106
+ var o, d, l, w;
982
1107
  const {
983
- chat: s,
984
- chatMode: r
985
- } = await fe(e, n, a, t.mode, t.persistentChat, o);
986
- if (r && r !== t.mode && (t.mode = r, (l = (c = t.callbacks).onModeChange) == null || l.call(c, r), r === b.TextOnly))
987
- return (m = (f = t.callbacks).onError) == null || m.call(f, new pe(r)), {
988
- chat: s
1108
+ chat: i,
1109
+ chatMode: c
1110
+ } = await pe(e, a, r, t.mode, t.persistentChat, s);
1111
+ if (c && c !== t.mode && (t.mode = c, (d = (o = t.callbacks).onModeChange) == null || d.call(o, c), c === A.TextOnly))
1112
+ return (w = (l = t.callbacks).onError) == null || w.call(l, new Ce(c)), {
1113
+ chat: i
989
1114
  };
990
- const i = await ft(e, t, a);
1115
+ const n = await Ct(e, t, r);
991
1116
  return {
992
- chat: s,
993
- streamingManager: i
1117
+ chat: i,
1118
+ streamingManager: n
994
1119
  };
995
1120
  }
996
- async function ht(e, t) {
997
- var R, S, P;
998
- let n = !0;
999
- const a = t.mixpanelKey || Pe, o = t.wsURL || be, s = t.baseURL || K, r = {
1121
+ async function _t(e, t) {
1122
+ var k, L, P;
1123
+ let a = !0, r = !1;
1124
+ const s = t.mixpanelKey || ze, i = t.wsURL || Le, c = t.baseURL || O, n = {
1000
1125
  messages: [],
1001
- chatMode: t.mode || b.Functional
1002
- }, i = de(t.auth, s, t.callbacks.onError), c = await i.getById(e), l = Je({
1003
- token: a,
1004
- agent: c,
1126
+ chatMode: t.mode || A.Functional
1127
+ }, o = me(t.auth, c, t.callbacks.onError), d = await o.getById(e), l = qe({
1128
+ token: s,
1129
+ agent: d,
1005
1130
  isEnabled: t.enableAnalitics,
1006
1131
  distinctId: t.distinctId
1007
1132
  }), {
1008
- onMessage: f,
1009
- clearQueue: m
1010
- } = Qe(l, r, t, c, () => {
1011
- var d;
1012
- return (d = r.socketManager) == null ? void 0 : d.disconnect();
1133
+ onMessage: w,
1134
+ clearQueue: j
1135
+ } = et(l, n, t, d, () => {
1136
+ var u;
1137
+ return (u = n.socketManager) == null ? void 0 : u.disconnect();
1013
1138
  });
1014
- r.messages = Ue(t.initialMessages), (S = (R = t.callbacks).onNewMessage) == null || S.call(R, [...r.messages], "answer"), l.track("agent-sdk", {
1139
+ n.messages = Ve(t.initialMessages), (L = (k = t.callbacks).onNewMessage) == null || L.call(k, [...n.messages], "answer"), l.track("agent-sdk", {
1015
1140
  event: "loaded",
1016
- ...Ae(c)
1141
+ ...We(d)
1017
1142
  });
1018
- async function D(d) {
1019
- var T, $, B, E, _, u, p;
1020
- ($ = (T = t.callbacks).onConnectionStateChange) == null || $.call(T, M.Connecting), N.reset(), d && !n && (delete r.chat, (E = (B = t.callbacks).onNewMessage) == null || E.call(B, [...r.messages], "answer"));
1021
- const g = t.mode === b.DirectPlayback ? Promise.resolve(void 0) : qe(t.auth, o, {
1022
- onMessage: f,
1143
+ async function R(u) {
1144
+ var M, $, z, _, E, I, N;
1145
+ ($ = (M = t.callbacks).onConnectionStateChange) == null || $.call(M, T.Connecting), F.reset(), r = !1, u && !a && (delete n.chat, (_ = (z = t.callbacks).onNewMessage) == null || _.call(z, [...n.messages], "answer"));
1146
+ const m = ee(t.mode) ? Promise.resolve(void 0) : Oe(t.auth, i, {
1147
+ onMessage: w,
1023
1148
  onError: t.callbacks.onError
1024
- }), y = V(() => mt(c, t, i, l, r.chat), {
1149
+ }), v = te(() => Rt(d, t, o, l, n.chat), {
1025
1150
  limit: 3,
1026
- timeout: Te,
1151
+ timeout: $e,
1027
1152
  timeoutErrorMessage: "Timeout initializing the stream",
1028
1153
  // Retry on all errors except for connection errors and rate limit errors, these are already handled in client level.
1029
- shouldRetryFn: (j) => (j == null ? void 0 : j.message) !== "Could not connect" && j.status !== 429,
1154
+ shouldRetryFn: (x) => (x == null ? void 0 : x.message) !== "Could not connect" && x.status !== 429,
1030
1155
  delayMs: 1e3
1031
- }).catch((j) => {
1032
- var L, A;
1033
- throw C(b.Maintenance), (A = (L = t.callbacks).onConnectionStateChange) == null || A.call(L, M.Fail), j;
1034
- }), [h, {
1035
- streamingManager: I,
1036
- chat: k
1037
- }] = await Promise.all([g, y]);
1038
- k && k.id !== ((_ = r.chat) == null ? void 0 : _.id) && ((p = (u = t.callbacks).onNewChat) == null || p.call(u, k.id)), r.streamingManager = I, r.socketManager = h, r.chat = k, n = !1, C((k == null ? void 0 : k.chat_mode) ?? t.mode ?? b.Functional);
1156
+ }).catch((x) => {
1157
+ var W, f;
1158
+ throw C(A.Maintenance), (f = (W = t.callbacks).onConnectionStateChange) == null || f.call(W, T.Fail), x;
1159
+ }), [g, {
1160
+ streamingManager: S,
1161
+ chat: y
1162
+ }] = await Promise.all([m, v]);
1163
+ y && y.id !== ((E = n.chat) == null ? void 0 : E.id) && ((N = (I = t.callbacks).onNewChat) == null || N.call(I, y.id)), n.streamingManager = S, n.socketManager = g, n.chat = y, a = !1, C((y == null ? void 0 : y.chat_mode) ?? t.mode ?? A.Functional);
1039
1164
  }
1040
- async function w() {
1041
- var d, g, y, h;
1042
- (d = r.socketManager) == null || d.disconnect(), await ((g = r.streamingManager) == null ? void 0 : g.disconnect()), delete r.streamingManager, delete r.socketManager, (h = (y = t.callbacks).onConnectionStateChange) == null || h.call(y, M.Disconnected);
1165
+ async function D() {
1166
+ var u, m, v, g;
1167
+ (u = n.socketManager) == null || u.disconnect(), await ((m = n.streamingManager) == null ? void 0 : m.disconnect()), r = !1, delete n.streamingManager, delete n.socketManager, (g = (v = t.callbacks).onConnectionStateChange) == null || g.call(v, T.Disconnected);
1043
1168
  }
1044
- async function C(d) {
1045
- var g, y;
1046
- d !== r.chatMode && (l.track("agent-mode-change", {
1047
- mode: d
1048
- }), r.chatMode = d, r.chatMode !== b.Functional && await w(), (y = (g = t.callbacks).onModeChange) == null || y.call(g, d));
1169
+ async function C(u) {
1170
+ var m, v;
1171
+ u !== n.chatMode && (l.track("agent-mode-change", {
1172
+ mode: u
1173
+ }), n.chatMode = u, n.chatMode !== A.Functional && await D(), (v = (m = t.callbacks).onModeChange) == null || v.call(m, u));
1049
1174
  }
1050
1175
  return {
1051
- agent: c,
1176
+ agent: d,
1052
1177
  getStreamType: () => {
1053
- var d;
1054
- return (d = r.streamingManager) == null ? void 0 : d.streamType;
1178
+ var u;
1179
+ return (u = n.streamingManager) == null ? void 0 : u.streamType;
1055
1180
  },
1056
- starterMessages: ((P = c.knowledge) == null ? void 0 : P.starter_message) || [],
1057
- getSTTToken: () => i.getSTTToken(c.id),
1181
+ getIsInterruptAvailable: () => {
1182
+ var u;
1183
+ return ((u = n.streamingManager) == null ? void 0 : u.interruptAvailable) ?? !1;
1184
+ },
1185
+ starterMessages: ((P = d.knowledge) == null ? void 0 : P.starter_message) || [],
1186
+ getSTTToken: () => o.getSTTToken(d.id),
1058
1187
  changeMode: C,
1059
1188
  enrichAnalytics: l.enrich,
1060
1189
  async connect() {
1061
- var d;
1062
- await D(!0), l.track("agent-chat", {
1190
+ var u;
1191
+ await R(!0), l.track("agent-chat", {
1063
1192
  event: "connect",
1064
- chatId: (d = r.chat) == null ? void 0 : d.id,
1065
- agentId: c.id,
1066
- mode: r.chatMode
1193
+ chatId: (u = n.chat) == null ? void 0 : u.id,
1194
+ agentId: d.id,
1195
+ mode: n.chatMode
1067
1196
  });
1068
1197
  },
1069
1198
  async reconnect() {
1070
- var d;
1071
- await w(), await D(!1), l.track("agent-chat", {
1199
+ var u;
1200
+ await D(), await R(!1), l.track("agent-chat", {
1072
1201
  event: "reconnect",
1073
- chatId: (d = r.chat) == null ? void 0 : d.id,
1074
- agentId: c.id,
1075
- mode: r.chatMode
1202
+ chatId: (u = n.chat) == null ? void 0 : u.id,
1203
+ agentId: d.id,
1204
+ mode: n.chatMode
1076
1205
  });
1077
1206
  },
1078
1207
  async disconnect() {
1079
- var d;
1080
- await w(), l.track("agent-chat", {
1208
+ var u;
1209
+ await D(), l.track("agent-chat", {
1081
1210
  event: "disconnect",
1082
- chatId: (d = r.chat) == null ? void 0 : d.id,
1083
- agentId: c.id,
1084
- mode: r.chatMode
1211
+ chatId: (u = n.chat) == null ? void 0 : u.id,
1212
+ agentId: d.id,
1213
+ mode: n.chatMode
1085
1214
  });
1086
1215
  },
1087
- async chat(d) {
1088
- var I, k, T, $, B;
1089
- const g = () => {
1090
- if (t.mode === b.DirectPlayback)
1091
- throw new x("Direct playback is enabled, chat is disabled");
1092
- if (d.length >= 800)
1093
- throw new x("Message cannot be more than 800 characters");
1094
- if (d.length === 0)
1095
- throw new x("Message cannot be empty");
1096
- if (r.chatMode === b.Maintenance)
1097
- throw new x("Chat is in maintenance mode");
1098
- if (![b.TextOnly, b.Playground].includes(r.chatMode)) {
1099
- if (!r.streamingManager)
1100
- throw new x("Streaming manager is not initialized");
1101
- if (!r.chat)
1102
- throw new x("Chat is not initialized");
1216
+ async chat(u) {
1217
+ var S, y, M, $, z;
1218
+ const m = () => {
1219
+ if (ee(t.mode))
1220
+ throw new K(`${t.mode} is enabled, chat is disabled`);
1221
+ if (u.length >= 800)
1222
+ throw new K("Message cannot be more than 800 characters");
1223
+ if (u.length === 0)
1224
+ throw new K("Message cannot be empty");
1225
+ if (n.chatMode === A.Maintenance)
1226
+ throw new K("Chat is in maintenance mode");
1227
+ if (![A.TextOnly, A.Playground].includes(n.chatMode)) {
1228
+ if (!n.streamingManager)
1229
+ throw new K("Streaming manager is not initialized");
1230
+ if (!n.chat)
1231
+ throw new K("Chat is not initialized");
1103
1232
  }
1104
- }, y = async () => {
1105
- var E, _;
1106
- if (!r.chat) {
1107
- const u = await fe(c, i, l, r.chatMode, t.persistentChat);
1108
- if (!u.chat)
1109
- throw new we(r.chatMode, !!t.persistentChat);
1110
- r.chat = u.chat, (_ = (E = t.callbacks).onNewChat) == null || _.call(E, r.chat.id);
1233
+ }, v = async () => {
1234
+ var _, E;
1235
+ if (!n.chat) {
1236
+ const I = await pe(d, o, l, n.chatMode, t.persistentChat);
1237
+ if (!I.chat)
1238
+ throw new De(n.chatMode, !!t.persistentChat);
1239
+ n.chat = I.chat, (E = (_ = t.callbacks).onNewChat) == null || E.call(_, n.chat.id);
1111
1240
  }
1112
- return r.chat.id;
1113
- }, h = async (E, _) => V(() => {
1114
- var u, p;
1115
- return i.chat(c.id, _, {
1116
- chatMode: r.chatMode,
1117
- streamId: (u = r.streamingManager) == null ? void 0 : u.streamId,
1118
- sessionId: (p = r.streamingManager) == null ? void 0 : p.sessionId,
1119
- messages: E.map(({
1120
- matches: j,
1121
- ...L
1122
- }) => L)
1241
+ return n.chat.id;
1242
+ }, g = async (_, E) => te(() => {
1243
+ var I, N;
1244
+ return o.chat(d.id, E, {
1245
+ chatMode: n.chatMode,
1246
+ streamId: (I = n.streamingManager) == null ? void 0 : I.streamId,
1247
+ sessionId: (N = n.streamingManager) == null ? void 0 : N.sessionId,
1248
+ messages: _.map(({
1249
+ matches: x,
1250
+ ...W
1251
+ }) => W)
1123
1252
  }, {
1124
- ...ue(r.chatMode),
1253
+ ...we(n.chatMode),
1125
1254
  skipErrorHandler: !0
1126
1255
  });
1127
1256
  }, {
1128
1257
  limit: 2,
1129
- shouldRetryFn: (u) => {
1130
- var L, A, O, ee;
1131
- const p = (L = u == null ? void 0 : u.message) == null ? void 0 : L.includes("missing or invalid session_id");
1132
- return !((A = u == null ? void 0 : u.message) == null ? void 0 : A.includes("Stream Error")) && !p ? ((ee = (O = t.callbacks).onError) == null || ee.call(O, u), !1) : !0;
1258
+ shouldRetryFn: (I) => {
1259
+ var W, f, h, b;
1260
+ const N = (W = I == null ? void 0 : I.message) == null ? void 0 : W.includes("missing or invalid session_id");
1261
+ return !((f = I == null ? void 0 : I.message) == null ? void 0 : f.includes("Stream Error")) && !N ? ((b = (h = t.callbacks).onError) == null || b.call(h, I), !1) : !0;
1133
1262
  },
1134
1263
  onRetry: async () => {
1135
- await w(), await D(!1);
1264
+ await D(), await R(!1);
1136
1265
  }
1137
1266
  });
1138
1267
  try {
1139
- m(), g(), r.messages.push({
1268
+ j(), m(), n.messages.push({
1140
1269
  id: q(),
1141
1270
  role: "user",
1142
- content: d,
1143
- created_at: new Date(N.update()).toISOString()
1144
- }), (k = (I = t.callbacks).onNewMessage) == null || k.call(I, [...r.messages], "user");
1145
- const E = await y(), _ = await h([...r.messages], E);
1146
- return r.messages.push({
1271
+ content: u,
1272
+ created_at: new Date(F.update()).toISOString()
1273
+ }), (y = (S = t.callbacks).onNewMessage) == null || y.call(S, [...n.messages], "user");
1274
+ const _ = await v(), E = await g([...n.messages], _);
1275
+ return n.messages.push({
1147
1276
  id: q(),
1148
1277
  role: "assistant",
1149
- content: _.result || "",
1278
+ content: E.result || "",
1150
1279
  created_at: (/* @__PURE__ */ new Date()).toISOString(),
1151
- context: _.context,
1152
- matches: _.matches
1153
- }), l.track("agent-message-send", {
1280
+ context: E.context,
1281
+ matches: E.matches,
1282
+ videoId: E.videoId
1283
+ }), r && E.videoId && n.streamingManager && (r = !1, n.messages[n.messages.length - 1].interrupted = !0, await se(n.streamingManager, E.videoId)), l.track("agent-message-send", {
1154
1284
  event: "success",
1155
- mode: r.chatMode,
1156
- messages: r.messages.length + 1
1157
- }), _.result && (($ = (T = t.callbacks).onNewMessage) == null || $.call(T, [...r.messages], "answer"), l.track("agent-message-received", {
1158
- latency: N.get(!0),
1159
- mode: r.chatMode,
1160
- messages: r.messages.length
1161
- })), _;
1162
- } catch (E) {
1163
- throw ((B = r.messages[r.messages.length - 1]) == null ? void 0 : B.role) === "assistant" && r.messages.pop(), l.track("agent-message-send", {
1285
+ mode: n.chatMode,
1286
+ messages: n.messages.length + 1
1287
+ }), E.result && (($ = (M = t.callbacks).onNewMessage) == null || $.call(M, [...n.messages], "answer"), l.track("agent-message-received", {
1288
+ latency: F.get(!0),
1289
+ mode: n.chatMode,
1290
+ messages: n.messages.length
1291
+ })), E;
1292
+ } catch (_) {
1293
+ throw r = !1, ((z = n.messages[n.messages.length - 1]) == null ? void 0 : z.role) === "assistant" && n.messages.pop(), l.track("agent-message-send", {
1164
1294
  event: "error",
1165
- mode: r.chatMode,
1166
- messages: r.messages.length
1167
- }), E;
1295
+ mode: n.chatMode,
1296
+ messages: n.messages.length
1297
+ }), _;
1168
1298
  }
1169
1299
  },
1170
- rate(d, g, y) {
1171
- var k, T, $, B;
1172
- const h = r.messages.find((E) => E.id === d);
1173
- if (r.chat) {
1174
- if (!h)
1300
+ rate(u, m, v) {
1301
+ var y, M, $, z;
1302
+ const g = n.messages.find((_) => _.id === u);
1303
+ if (n.chat) {
1304
+ if (!g)
1175
1305
  throw new Error("Message not found");
1176
1306
  } else
1177
1307
  throw new Error("Chat is not initialized");
1178
- const I = ((k = h.matches) == null ? void 0 : k.map((E) => [E.document_id, E.id])) ?? [];
1308
+ const S = ((y = g.matches) == null ? void 0 : y.map((_) => [_.document_id, _.id])) ?? [];
1179
1309
  return l.track("agent-rate", {
1180
- event: y ? "update" : "create",
1181
- thumb: g === 1 ? "up" : "down",
1182
- knowledge_id: ((T = c.knowledge) == null ? void 0 : T.id) ?? "",
1183
- mode: r.chatMode,
1184
- matches: I,
1185
- score: g
1186
- }), y ? i.updateRating(c.id, r.chat.id, y, {
1187
- knowledge_id: (($ = c.knowledge) == null ? void 0 : $.id) ?? "",
1188
- message_id: d,
1189
- matches: I,
1190
- score: g
1191
- }) : i.createRating(c.id, r.chat.id, {
1192
- knowledge_id: ((B = c.knowledge) == null ? void 0 : B.id) ?? "",
1193
- message_id: d,
1194
- matches: I,
1195
- score: g
1310
+ event: v ? "update" : "create",
1311
+ thumb: m === 1 ? "up" : "down",
1312
+ knowledge_id: ((M = d.knowledge) == null ? void 0 : M.id) ?? "",
1313
+ mode: n.chatMode,
1314
+ matches: S,
1315
+ score: m
1316
+ }), v ? o.updateRating(d.id, n.chat.id, v, {
1317
+ knowledge_id: (($ = d.knowledge) == null ? void 0 : $.id) ?? "",
1318
+ message_id: u,
1319
+ matches: S,
1320
+ score: m
1321
+ }) : o.createRating(d.id, n.chat.id, {
1322
+ knowledge_id: ((z = d.knowledge) == null ? void 0 : z.id) ?? "",
1323
+ message_id: u,
1324
+ matches: S,
1325
+ score: m
1196
1326
  });
1197
1327
  },
1198
- deleteRate(d) {
1199
- var g;
1200
- if (!r.chat)
1328
+ deleteRate(u) {
1329
+ var m;
1330
+ if (!n.chat)
1201
1331
  throw new Error("Chat is not initialized");
1202
1332
  return l.track("agent-rate-delete", {
1203
1333
  type: "text",
1204
- chat_id: (g = r.chat) == null ? void 0 : g.id,
1205
- id: d,
1206
- mode: r.chatMode
1207
- }), i.deleteRating(c.id, r.chat.id, d);
1334
+ chat_id: (m = n.chat) == null ? void 0 : m.id,
1335
+ id: u,
1336
+ mode: n.chatMode
1337
+ }), o.deleteRating(d.id, n.chat.id, u);
1208
1338
  },
1209
- speak(d) {
1210
- var h, I, k, T;
1211
- if (!r.streamingManager)
1212
- throw new Error("Please connect to the agent first");
1213
- function g() {
1214
- if (typeof d == "string") {
1215
- if (!c.presenter.voice)
1339
+ async speak(u) {
1340
+ var S, y, M;
1341
+ function m() {
1342
+ if (typeof u == "string") {
1343
+ if (!d.presenter.voice)
1216
1344
  throw new Error("Presenter voice is not initialized");
1217
1345
  return {
1218
1346
  type: "text",
1219
- provider: c.presenter.voice,
1220
- input: d,
1347
+ provider: d.presenter.voice,
1348
+ input: u,
1221
1349
  ssml: !1
1222
1350
  };
1223
1351
  }
1224
- if (d.type === "text" && !d.provider) {
1225
- if (!c.presenter.voice)
1352
+ if (u.type === "text" && !u.provider) {
1353
+ if (!d.presenter.voice)
1226
1354
  throw new Error("Presenter voice is not initialized");
1227
1355
  return {
1228
1356
  type: "text",
1229
- provider: c.presenter.voice,
1230
- input: d.input,
1231
- ssml: d.ssml
1357
+ provider: d.presenter.voice,
1358
+ input: u.input,
1359
+ ssml: u.ssml
1232
1360
  };
1233
1361
  }
1234
- return d;
1362
+ return u;
1235
1363
  }
1236
- const y = g();
1237
- return l.track("agent-speak", y), N.update(), (h = r.chat) != null && h.id && y.type === "text" && (r.messages.push({
1364
+ const v = m();
1365
+ if (l.track("agent-speak", v), F.update(), n.messages && v.type === "text" && (n.messages.push({
1238
1366
  id: q(),
1239
1367
  role: "assistant",
1240
- content: y.input,
1241
- created_at: new Date(N.get(!0)).toISOString()
1242
- }), (k = (I = t.callbacks).onNewMessage) == null || k.call(I, [...r.messages], "answer")), r.streamingManager.speak({
1243
- script: y,
1368
+ content: v.input,
1369
+ created_at: new Date(F.get(!0)).toISOString()
1370
+ }), (y = (S = t.callbacks).onNewMessage) == null || y.call(S, [...n.messages], "answer")), Ne(n.chatMode))
1371
+ return {
1372
+ duration: 0,
1373
+ status: "success"
1374
+ };
1375
+ if (!n.streamingManager)
1376
+ throw new Error("Please connect to the agent first");
1377
+ return n.streamingManager.speak({
1378
+ script: v,
1244
1379
  metadata: {
1245
- chat_id: (T = r.chat) == null ? void 0 : T.id,
1246
- agent_id: c.id
1380
+ chat_id: (M = n.chat) == null ? void 0 : M.id,
1381
+ agent_id: d.id
1247
1382
  }
1248
1383
  });
1384
+ },
1385
+ async interrupt({
1386
+ type: u
1387
+ }) {
1388
+ var g, S, y, M, $;
1389
+ const m = n.messages[n.messages.length - 1], v = (m == null ? void 0 : m.role) === "user";
1390
+ if (Xe(n.streamingManager, n.chat, (g = n.streamingManager) == null ? void 0 : g.streamType, v, !!(m != null && m.videoId)), l.track("agent-video-interrupt", {
1391
+ type: u || "click",
1392
+ stream_id: (S = n.streamingManager) == null ? void 0 : S.streamId,
1393
+ agent_id: d.id,
1394
+ owner_id: d.owner_id,
1395
+ video_duration_to_interrupt: re.get(!0),
1396
+ message_duration_to_interrupt: F.get(!0),
1397
+ chat_id: (y = n.chat) == null ? void 0 : y.id,
1398
+ mode: n.chatMode,
1399
+ queued_interrupt: v
1400
+ }), v) {
1401
+ r = !0;
1402
+ return;
1403
+ }
1404
+ m.interrupted = !0, ($ = (M = t.callbacks).onNewMessage) == null || $.call(M, [...n.messages], "answer"), se(n.streamingManager, m.videoId);
1249
1405
  }
1250
1406
  };
1251
1407
  }
1252
- function wt(e, t, n) {
1408
+ function Et(e, t, a) {
1253
1409
  const {
1254
- getById: a
1255
- } = de(t, n || K);
1256
- return a(e);
1410
+ getById: r
1411
+ } = me(t, a || O);
1412
+ return r(e);
1257
1413
  }
1258
1414
  export {
1259
- H as AgentActivityState,
1260
- De as AgentStatus,
1261
- we as ChatCreationFailed,
1262
- b as ChatMode,
1263
- pe as ChatModeDowngraded,
1264
- J as ChatProgress,
1265
- M as ConnectionState,
1266
- W as ConnectivityState,
1267
- te as DataChannelSignalMap,
1268
- Se as DocumentType,
1269
- Ee as KnowledgeType,
1270
- ke as PlanGroup,
1271
- _e as Providers,
1272
- Ce as RateState,
1273
- X as StreamEvents,
1274
- F as StreamType,
1275
- v as StreamingState,
1276
- Re as Subject,
1277
- ve as UserPlan,
1278
- x as ValidationError,
1279
- ie as VideoType,
1280
- Ie as VoiceAccess,
1281
- ye as WsError,
1282
- ht as createAgentManager,
1283
- wt as getAgent,
1284
- Me as mapVideoType
1415
+ V as AgentActivityState,
1416
+ Ee as AgentStatus,
1417
+ De as ChatCreationFailed,
1418
+ A as ChatMode,
1419
+ Ce as ChatModeDowngraded,
1420
+ H as ChatProgress,
1421
+ T as ConnectionState,
1422
+ Q as ConnectivityState,
1423
+ je as DocumentType,
1424
+ Te as KnowledgeType,
1425
+ _e as PlanGroup,
1426
+ Ae as Providers,
1427
+ Ie as RateState,
1428
+ J as StreamEvents,
1429
+ U as StreamType,
1430
+ p as StreamingState,
1431
+ Me as Subject,
1432
+ Se as UserPlan,
1433
+ K as ValidationError,
1434
+ de as VideoType,
1435
+ Pe as VoiceAccess,
1436
+ Re as WsError,
1437
+ _t as createAgentManager,
1438
+ Et as getAgent,
1439
+ be as mapVideoType
1285
1440
  };