@d-id/client-sdk 1.1.0-beta.4 → 1.1.0-beta.50

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