@d-id/client-sdk 1.0.19-beta.143 → 1.0.19-beta.145

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,4 +1,4 @@
1
- var re = /* @__PURE__ */ ((e) => (e.TRIAL = "trial", e.BASIC = "basic", e.ENTERPRISE = "enterprise", e.LITE = "lite", e.ADVANCED = "advanced", e))(re || {}), ae = /* @__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))(ae || {}), ie = /* @__PURE__ */ ((e) => (e.Created = "created", e.Started = "started", e.Done = "done", e.Error = "error", e.Rejected = "rejected", e.Ready = "ready", e))(ie || {}), se = /* @__PURE__ */ ((e) => (e.Unrated = "Unrated", e.Positive = "Positive", e.Negative = "Negative", e))(se || {}), I = /* @__PURE__ */ ((e) => (e.Functional = "Functional", e.TextOnly = "TextOnly", e.Maintenance = "Maintenance", e.Playground = "Playground", e.DirectPlayback = "DirectPlayback", e))(I || {}), L = /* @__PURE__ */ ((e) => (e.Embed = "embed", e.Query = "query", e.Partial = "partial", e.Answer = "answer", e.Complete = "done", e))(L || {}), oe = /* @__PURE__ */ ((e) => (e.KnowledgeProcessing = "knowledge/processing", e.KnowledgeIndexing = "knowledge/indexing", e.KnowledgeFailed = "knowledge/error", e.KnowledgeDone = "knowledge/done", e))(oe || {}), ce = /* @__PURE__ */ ((e) => (e.Knowledge = "knowledge", e.Document = "document", e.Record = "record", e))(ce || {}), de = /* @__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))(de || {}), O = /* @__PURE__ */ ((e) => (e.Clip = "clip", e.Talk = "talk", e))(O || {});
1
+ var re = /* @__PURE__ */ ((e) => (e.TRIAL = "trial", e.BASIC = "basic", e.ENTERPRISE = "enterprise", e.LITE = "lite", e.ADVANCED = "advanced", e))(re || {}), ae = /* @__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))(ae || {}), ie = /* @__PURE__ */ ((e) => (e.Created = "created", e.Started = "started", e.Done = "done", e.Error = "error", e.Rejected = "rejected", e.Ready = "ready", e))(ie || {}), se = /* @__PURE__ */ ((e) => (e.Unrated = "Unrated", e.Positive = "Positive", e.Negative = "Negative", e))(se || {}), E = /* @__PURE__ */ ((e) => (e.Functional = "Functional", e.TextOnly = "TextOnly", e.Maintenance = "Maintenance", e.Playground = "Playground", e.DirectPlayback = "DirectPlayback", e))(E || {}), N = /* @__PURE__ */ ((e) => (e.Embed = "embed", e.Query = "query", e.Partial = "partial", e.Answer = "answer", e.Complete = "done", e))(N || {}), oe = /* @__PURE__ */ ((e) => (e.KnowledgeProcessing = "knowledge/processing", e.KnowledgeIndexing = "knowledge/indexing", e.KnowledgeFailed = "knowledge/error", e.KnowledgeDone = "knowledge/done", e))(oe || {}), ce = /* @__PURE__ */ ((e) => (e.Knowledge = "knowledge", e.Document = "document", e.Record = "record", e))(ce || {}), de = /* @__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))(de || {}), O = /* @__PURE__ */ ((e) => (e.Clip = "clip", e.Talk = "talk", e))(O || {});
2
2
  const le = (e) => {
3
3
  switch (e) {
4
4
  case "clip":
@@ -9,8 +9,8 @@ const le = (e) => {
9
9
  throw new Error(`Unknown video type: ${e}`);
10
10
  }
11
11
  };
12
- var F = /* @__PURE__ */ ((e) => (e.Start = "START", e.Stop = "STOP", e))(F || {}), 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.StreamVideoCreated = "stream-video/started", e.StreamVideoDone = "stream-video/done", e.StreamVideoError = "stream-video/error", e.StreamVideoRejected = "stream-video/rejected", e))(j || {}), 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 || {}), me = /* @__PURE__ */ ((e) => (e.Amazon = "amazon", e.Microsoft = "microsoft", e.Afflorithmics = "afflorithmics", e.Elevenlabs = "elevenlabs", e))(me || {}), ge = /* @__PURE__ */ ((e) => (e.Public = "public", e.Premium = "premium", e.Private = "private", e))(ge || {});
13
- const U = "https://api.d-id.com", ue = "wss://notifications.d-id.com", he = "79f81a83a67430be2bc0fd61042b8faa";
12
+ var x = /* @__PURE__ */ ((e) => (e.Start = "START", e.Stop = "STOP", e))(x || {}), W = /* @__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))(W || {}), S = /* @__PURE__ */ ((e) => (e.New = "new", e.Fail = "fail", e.Connected = "connected", e.Connecting = "connecting", e.Closed = "closed", e.Completed = "completed", e.Disconnected = "disconnected", e))(S || {}), me = /* @__PURE__ */ ((e) => (e.Amazon = "amazon", e.Microsoft = "microsoft", e.Afflorithmics = "afflorithmics", e.Elevenlabs = "elevenlabs", e))(me || {}), ue = /* @__PURE__ */ ((e) => (e.Public = "public", e.Premium = "premium", e.Private = "private", e))(ue || {});
13
+ const H = "https://api.d-id.com", fe = "wss://notifications.d-id.com", ge = "79f81a83a67430be2bc0fd61042b8faa";
14
14
  async function X(e, n) {
15
15
  const s = {
16
16
  limit: (n == null ? void 0 : n.limit) ?? 3,
@@ -21,458 +21,562 @@ async function X(e, n) {
21
21
  return !0;
22
22
  }
23
23
  };
24
- let a;
24
+ let i;
25
25
  for (let t = 1; t <= s.limit; t++)
26
26
  try {
27
27
  if (!s.timeout)
28
28
  return await e();
29
- let r;
30
- const i = new Promise((l, d) => {
31
- r = setTimeout(() => d(new Error(s.timeoutErrorMessage)), s.timeout);
29
+ let a;
30
+ const r = new Promise((m, d) => {
31
+ a = setTimeout(() => d(new Error(s.timeoutErrorMessage)), s.timeout);
32
32
  });
33
- return await Promise.race([e().then((l) => (clearTimeout(r), l)), i]);
34
- } catch (r) {
35
- if (a = r, !s.shouldRetryFn(r) || t >= s.limit)
36
- throw r;
37
- s.delayMs > 0 && await new Promise((i) => setTimeout(i, s.delayMs));
33
+ return await Promise.race([e().then((m) => (clearTimeout(a), m)), r]);
34
+ } catch (a) {
35
+ if (i = a, !s.shouldRetryFn(a) || t >= s.limit)
36
+ throw a;
37
+ s.delayMs > 0 && await new Promise((r) => setTimeout(r, s.delayMs));
38
38
  }
39
- throw a;
39
+ throw i;
40
40
  }
41
- const V = () => Math.random().toString(16).slice(2);
41
+ const K = () => Math.random().toString(16).slice(2);
42
42
  function Y() {
43
43
  let e = window.localStorage.getItem("did_external_key_id");
44
44
  return e || (e = Math.random().toString(16).slice(2), window.localStorage.setItem("did_external_key_id", e)), e;
45
45
  }
46
- let we = V();
46
+ let he = K();
47
47
  function Z(e) {
48
48
  if (e.type === "bearer")
49
49
  return `Bearer ${e.token}`;
50
50
  if (e.type === "basic")
51
51
  return `Basic ${btoa(`${e.username}:${e.password}`)}`;
52
52
  if (e.type === "key")
53
- return `Client-Key ${e.clientKey}.${Y()}_${we}`;
53
+ return `Client-Key ${e.clientKey}.${Y()}_${he}`;
54
54
  throw new Error(`Unknown auth type: ${e}`);
55
55
  }
56
- const fe = (e) => X(e, {
56
+ const we = (e) => X(e, {
57
57
  limit: 3,
58
58
  delayMs: 1e3,
59
59
  timeout: 0,
60
60
  shouldRetryFn: (n) => n.status === 429
61
61
  });
62
- function q(e, n = U, s) {
63
- const a = async (t, r) => {
64
- const i = await fe(() => fetch(n + (t != null && t.startsWith("/") ? t : `/${t}`), {
65
- ...r,
62
+ function B(e, n = H, s) {
63
+ const i = async (t, a) => {
64
+ const r = await we(() => fetch(n + (t != null && t.startsWith("/") ? t : `/${t}`), {
65
+ ...a,
66
66
  headers: {
67
- ...r == null ? void 0 : r.headers,
67
+ ...a == null ? void 0 : a.headers,
68
68
  Authorization: Z(e),
69
69
  "Content-Type": "application/json"
70
70
  }
71
71
  }));
72
- if (!i.ok) {
73
- let o = await i.text().catch(() => "Failed to fetch");
72
+ if (!r.ok) {
73
+ let o = await r.text().catch(() => "Failed to fetch");
74
74
  throw s && s(new Error(o), {
75
75
  url: t,
76
- options: r,
77
- headers: i.headers
76
+ options: a,
77
+ headers: r.headers
78
78
  }), new Error(o);
79
79
  }
80
- return i.json();
80
+ return r.json();
81
81
  };
82
82
  return {
83
- get(t, r) {
84
- return a(t, {
85
- ...r,
83
+ get(t, a) {
84
+ return i(t, {
85
+ ...a,
86
86
  method: "GET"
87
87
  });
88
88
  },
89
- post(t, r, i) {
90
- return a(t, {
91
- ...i,
92
- body: JSON.stringify(r),
89
+ post(t, a, r) {
90
+ return i(t, {
91
+ ...r,
92
+ body: JSON.stringify(a),
93
93
  method: "POST"
94
94
  });
95
95
  },
96
- delete(t, r, i) {
97
- return a(t, {
98
- ...i,
99
- body: JSON.stringify(r),
96
+ delete(t, a, r) {
97
+ return i(t, {
98
+ ...r,
99
+ body: JSON.stringify(a),
100
100
  method: "DELETE"
101
101
  });
102
102
  },
103
- patch(t, r, i) {
104
- return a(t, {
105
- ...i,
106
- body: JSON.stringify(r),
103
+ patch(t, a, r) {
104
+ return i(t, {
105
+ ...r,
106
+ body: JSON.stringify(a),
107
107
  method: "PATCH"
108
108
  });
109
109
  }
110
110
  };
111
111
  }
112
- function G(e, n = U, s) {
113
- const a = q(e, `${n}/agents`, s);
112
+ function G(e, n = H, s) {
113
+ const i = B(e, `${n}/agents`, s);
114
114
  return {
115
- create(t, r) {
116
- return a.post("/", t, r);
115
+ create(t, a) {
116
+ return i.post("/", t, a);
117
117
  },
118
- getAgents(t, r) {
119
- return a.get(`/${t ? `?tag=${t}` : ""}`, r).then((i) => i ?? []);
118
+ getAgents(t, a) {
119
+ return i.get(`/${t ? `?tag=${t}` : ""}`, a).then((r) => r ?? []);
120
120
  },
121
- getById(t, r) {
122
- return a.get(`/${t}`, r);
121
+ getById(t, a) {
122
+ return i.get(`/${t}`, a);
123
123
  },
124
- delete(t, r) {
125
- return a.delete(`/${t}`, void 0, r);
124
+ delete(t, a) {
125
+ return i.delete(`/${t}`, void 0, a);
126
126
  },
127
- update(t, r, i) {
128
- return a.patch(`/${t}`, r, i);
127
+ update(t, a, r) {
128
+ return i.patch(`/${t}`, a, r);
129
129
  },
130
- newChat(t, r, i) {
131
- return a.post(`/${t}/chat`, r, i);
130
+ newChat(t, a, r) {
131
+ return i.post(`/${t}/chat`, a, r);
132
132
  },
133
- chat(t, r, i, o) {
134
- return a.post(`/${t}/chat/${r}`, i, o);
133
+ chat(t, a, r, o) {
134
+ return i.post(`/${t}/chat/${a}`, r, o);
135
135
  },
136
- createRating(t, r, i, o) {
137
- return a.post(`/${t}/chat/${r}/ratings`, i, o);
136
+ createRating(t, a, r, o) {
137
+ return i.post(`/${t}/chat/${a}/ratings`, r, o);
138
138
  },
139
- updateRating(t, r, i, o, l) {
140
- return a.patch(`/${t}/chat/${r}/ratings/${i}`, o, l);
139
+ updateRating(t, a, r, o, m) {
140
+ return i.patch(`/${t}/chat/${a}/ratings/${r}`, o, m);
141
141
  },
142
- deleteRating(t, r, i, o) {
143
- return a.delete(`/${t}/chat/${r}/ratings/${i}`, o);
142
+ deleteRating(t, a, r, o) {
143
+ return i.delete(`/${t}/chat/${a}/ratings/${r}`, o);
144
144
  },
145
- getSTTToken(t, r) {
146
- return a.get(`/${t}/stt-token`, r);
145
+ getSTTToken(t, a) {
146
+ return i.get(`/${t}/stt-token`, a);
147
147
  }
148
148
  };
149
149
  }
150
- const ye = (e) => new Promise((n) => setTimeout(n, e));
151
- function ve(e) {
150
+ const pe = (e) => new Promise((n) => setTimeout(n, e));
151
+ function ye(e) {
152
152
  return new Promise((n, s) => {
153
153
  const {
154
- callbacks: a,
154
+ callbacks: i,
155
155
  host: t,
156
- auth: r
156
+ auth: a
157
157
  } = e, {
158
- onMessage: i = null,
158
+ onMessage: r = null,
159
159
  onOpen: o = null,
160
- onClose: l = null,
160
+ onClose: m = null,
161
161
  onError: d = null
162
- } = a || {}, u = new WebSocket(`${t}?authorization=${Z(r)}`);
163
- u.onmessage = i, u.onclose = l, u.onerror = (g) => {
164
- console.error(g), d == null || d("Websocket failed to connect", g), s(g);
165
- }, u.onopen = (g) => {
166
- o == null || o(g), n(u);
162
+ } = i || {}, f = new WebSocket(`${t}?authorization=${Z(a)}`);
163
+ f.onmessage = r, f.onclose = m, f.onerror = (u) => {
164
+ console.error(u), d == null || d("Websocket failed to connect", u), s(u);
165
+ }, f.onopen = (u) => {
166
+ o == null || o(u), n(f);
167
167
  };
168
168
  });
169
169
  }
170
- async function pe(e) {
170
+ async function ve(e) {
171
171
  const {
172
172
  retries: n = 1
173
173
  } = e;
174
174
  let s = null;
175
- for (let a = 0; (s == null ? void 0 : s.readyState) !== WebSocket.OPEN; a++)
175
+ for (let i = 0; (s == null ? void 0 : s.readyState) !== WebSocket.OPEN; i++)
176
176
  try {
177
- s = await ve(e);
177
+ s = await ye(e);
178
178
  } catch (t) {
179
- if (a === n)
179
+ if (i === n)
180
180
  throw t;
181
- await ye(a * 500);
181
+ await pe(i * 500);
182
182
  }
183
183
  return s;
184
184
  }
185
- async function Ce(e, n, s) {
186
- const a = s != null && s.onMessage ? [s.onMessage] : [], t = await pe({
185
+ async function ke(e, n, s) {
186
+ const i = s != null && s.onMessage ? [s.onMessage] : [], t = await ve({
187
187
  auth: e,
188
188
  host: n,
189
189
  callbacks: {
190
190
  onError: s == null ? void 0 : s.onError,
191
- onMessage: (r) => {
192
- const i = JSON.parse(r.data);
193
- a.forEach((o) => o(i.event, i));
191
+ onMessage: (a) => {
192
+ const r = JSON.parse(a.data);
193
+ i.forEach((o) => o(r.event, r));
194
194
  }
195
195
  }
196
196
  });
197
197
  return {
198
198
  socket: t,
199
199
  disconnect: () => t.close(),
200
- subscribeToEvents: (r) => a.push(r)
200
+ subscribeToEvents: (a) => i.push(a)
201
201
  };
202
202
  }
203
- const _e = "X-Playground-Chat";
204
- function Me(e, n, s, a) {
205
- const t = q(e, `${n}/agents/${s}`, a);
203
+ const Ce = "X-Playground-Chat";
204
+ function Re(e, n, s, i) {
205
+ const t = B(e, `${n}/agents/${s}`, i);
206
206
  return {
207
- createStream(r) {
207
+ createStream(a) {
208
208
  return t.post("/streams", {
209
- output_resolution: r.output_resolution,
210
- compatibility_mode: r.compatibility_mode,
211
- stream_warmup: r.stream_warmup,
212
- session_timeout: r.session_timeout,
213
- stream_greeting: r.stream_greeting
209
+ output_resolution: a.output_resolution,
210
+ compatibility_mode: a.compatibility_mode,
211
+ stream_warmup: a.stream_warmup,
212
+ session_timeout: a.session_timeout,
213
+ stream_greeting: a.stream_greeting
214
214
  });
215
215
  },
216
- startConnection(r, i, o) {
217
- return t.post(`/streams/${r}/sdp`, {
216
+ startConnection(a, r, o) {
217
+ return t.post(`/streams/${a}/sdp`, {
218
218
  session_id: o,
219
- answer: i
219
+ answer: r
220
220
  });
221
221
  },
222
- addIceCandidate(r, i, o) {
223
- return t.post(`/streams/${r}/ice`, {
222
+ addIceCandidate(a, r, o) {
223
+ return t.post(`/streams/${a}/ice`, {
224
224
  session_id: o,
225
- ...i
225
+ ...r
226
226
  });
227
227
  },
228
- sendStreamRequest(r, i, o) {
229
- return t.post(`/streams/${r}`, {
230
- session_id: i,
228
+ sendStreamRequest(a, r, o) {
229
+ return t.post(`/streams/${a}`, {
230
+ session_id: r,
231
231
  ...o
232
232
  });
233
233
  },
234
- close(r, i) {
235
- return t.delete(`/streams/${r}`, {
236
- session_id: i
234
+ close(a, r) {
235
+ return t.delete(`/streams/${a}`, {
236
+ session_id: r
237
237
  });
238
238
  }
239
239
  };
240
240
  }
241
- function Se(e, n, s, a) {
242
- const t = q(e, `${n}/agents/${s}`, a);
241
+ function Se(e, n, s, i) {
242
+ const t = B(e, `${n}/agents/${s}`, i);
243
243
  return {
244
- createStream(r, i) {
244
+ createStream(a, r) {
245
245
  return t.post("/streams", {
246
- driver_url: r.driver_url,
247
- face: r.face,
248
- config: r.config,
249
- output_resolution: r.output_resolution,
250
- compatibility_mode: r.compatibility_mode,
251
- stream_warmup: r.stream_warmup,
252
- session_timeout: r.session_timeout,
253
- stream_greeting: r.stream_greeting
254
- }, i);
255
- },
256
- startConnection(r, i, o, l) {
257
- return t.post(`/streams/${r}/sdp`, {
246
+ driver_url: a.driver_url,
247
+ face: a.face,
248
+ config: a.config,
249
+ output_resolution: a.output_resolution,
250
+ compatibility_mode: a.compatibility_mode,
251
+ stream_warmup: a.stream_warmup,
252
+ session_timeout: a.session_timeout,
253
+ stream_greeting: a.stream_greeting
254
+ }, r);
255
+ },
256
+ startConnection(a, r, o, m) {
257
+ return t.post(`/streams/${a}/sdp`, {
258
258
  session_id: o,
259
- answer: i
260
- }, l);
259
+ answer: r
260
+ }, m);
261
261
  },
262
- addIceCandidate(r, i, o, l) {
263
- return t.post(`/streams/${r}/ice`, {
262
+ addIceCandidate(a, r, o, m) {
263
+ return t.post(`/streams/${a}/ice`, {
264
264
  session_id: o,
265
- ...i
266
- }, l);
265
+ ...r
266
+ }, m);
267
267
  },
268
- sendStreamRequest(r, i, o, l) {
269
- return t.post(`/streams/${r}`, {
270
- session_id: i,
268
+ sendStreamRequest(a, r, o, m) {
269
+ return t.post(`/streams/${a}`, {
270
+ session_id: r,
271
271
  ...o
272
- }, l);
272
+ }, m);
273
273
  },
274
- close(r, i, o) {
275
- return t.delete(`/streams/${r}`, {
276
- session_id: i
274
+ close(a, r, o) {
275
+ return t.delete(`/streams/${a}`, {
276
+ session_id: r
277
277
  }, o);
278
278
  }
279
279
  };
280
280
  }
281
+ function _e(e, n, s) {
282
+ return {
283
+ duration: (n.timestamp - e.timestamp) / 1e3,
284
+ bytesReceived: n.bytesReceived - e.bytesReceived,
285
+ bitrate: Math.round((n.bytesReceived - e.bytesReceived) * 8 / ((n.timestamp - e.timestamp) / 1e3)),
286
+ packetsReceived: n.packetsReceived - e.packetsReceived,
287
+ packetsLost: n.packetsLost - e.packetsLost,
288
+ framesDropped: n.framesDropped - e.framesDropped,
289
+ framesDecoded: n.framesDecoded - e.framesDecoded,
290
+ jitter: n.jitter,
291
+ framesPerSecond: n.framesPerSecond,
292
+ freezeCount: n.freezeCount - e.freezeCount,
293
+ freezeDuration: n.freezeDuration - e.freezeDuration,
294
+ lowFpsCount: s
295
+ };
296
+ }
297
+ function Me(e) {
298
+ return e.filter((n) => n.freezeCount > 0 || n.framesPerSecond < 21 || n.framesDropped > 0 || n.packetsLost > 0).map((n) => {
299
+ const {
300
+ timestamp: s,
301
+ ...i
302
+ } = n, t = [];
303
+ return n.freezeCount > 0 && t.push("freeze"), n.framesPerSecond < 21 && t.push("low fps"), n.framesDropped > 0 && t.push("frames dropped"), n.packetsLost > 0 && t.push("packet loss"), {
304
+ ...i,
305
+ causes: t
306
+ };
307
+ });
308
+ }
309
+ function De(e) {
310
+ let n = "";
311
+ for (const s of e.values())
312
+ if (s && s.type === "codec" && s.mimeType.startsWith("video") && (n = s.mimeType.split("/")[1]), s && s.type === "inbound-rtp" && s.kind === "video")
313
+ return {
314
+ codec: n,
315
+ timestamp: s.timestamp,
316
+ bytesReceived: s.bytesReceived,
317
+ packetsReceived: s.packetsReceived,
318
+ packetsLost: s.packetsLost,
319
+ framesDropped: s.framesDropped,
320
+ framesDecoded: s.framesDecoded,
321
+ jitter: s.jitter,
322
+ frameWidth: s.frameWidth,
323
+ frameHeight: s.frameHeight,
324
+ framesPerSecond: s.framesPerSecond,
325
+ freezeCount: s.freezeCount,
326
+ freezeDuration: s.totalFreezesDuration
327
+ };
328
+ return {};
329
+ }
330
+ function be(e, n, s) {
331
+ const i = e.map((r, o) => o === 0 ? s ? {
332
+ timestamp: r.timestamp,
333
+ duration: 0,
334
+ bytesReceived: r.bytesReceived - s.bytesReceived,
335
+ bitrate: (r.bytesReceived - s.bytesReceived) * 8 / (n / 1e3),
336
+ packetsReceived: r.packetsReceived - s.packetsReceived,
337
+ packetsLost: r.packetsLost - s.packetsLost,
338
+ framesDropped: r.framesDropped - s.framesDropped,
339
+ framesDecoded: r.framesDecoded - s.framesDecoded,
340
+ jitter: r.jitter,
341
+ framesPerSecond: r.framesPerSecond,
342
+ freezeCount: r.freezeCount - s.freezeCount,
343
+ freezeDuration: r.freezeDuration - s.freezeDuration
344
+ } : {
345
+ timestamp: r.timestamp,
346
+ duration: 0,
347
+ bytesReceived: r.bytesReceived,
348
+ bitrate: r.bytesReceived * 8 / (n / 1e3),
349
+ packetsReceived: r.packetsReceived,
350
+ packetsLost: r.packetsLost,
351
+ framesDropped: r.framesDropped,
352
+ framesDecoded: r.framesDecoded,
353
+ jitter: r.jitter,
354
+ framesPerSecond: r.framesPerSecond,
355
+ freezeCount: r.freezeCount,
356
+ freezeDuration: r.freezeDuration
357
+ } : {
358
+ timestamp: r.timestamp,
359
+ duration: n * o / 1e3,
360
+ bytesReceived: r.bytesReceived - e[o - 1].bytesReceived,
361
+ bitrate: (r.bytesReceived - e[o - 1].bytesReceived) * 8 / (n / 1e3),
362
+ packetsReceived: r.packetsReceived - e[o - 1].packetsReceived,
363
+ packetsLost: r.packetsLost - e[o - 1].packetsLost,
364
+ framesDropped: r.framesDropped - e[o - 1].framesDropped,
365
+ framesDecoded: r.framesDecoded - e[o - 1].framesDecoded,
366
+ jitter: r.jitter,
367
+ framesPerSecond: r.framesPerSecond,
368
+ freezeCount: r.freezeCount - e[o - 1].freezeCount,
369
+ freezeDuration: r.freezeDuration - e[o - 1].freezeDuration
370
+ }), t = Me(i), a = t.reduce((r, o) => r + (o.causes.includes("low fps") ? 1 : 0), 0);
371
+ return {
372
+ webRTCStats: {
373
+ anomalies: t,
374
+ aggregateReport: _e(e[0], e[e.length - 1], a)
375
+ },
376
+ codec: e[0].codec,
377
+ resolution: `${e[0].frameWidth}x${e[0].frameHeight}`
378
+ };
379
+ }
281
380
  let Q = !1;
282
- const x = (e, n) => Q && console.log(e, n), ke = (window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection).bind(window);
283
- function J(e) {
381
+ const L = (e, n) => Q && console.log(e, n), Ee = (window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection).bind(window);
382
+ function q(e) {
284
383
  switch (e) {
285
384
  case "connected":
286
- return M.Connected;
385
+ return S.Connected;
287
386
  case "checking":
288
- return M.Connecting;
387
+ return S.Connecting;
289
388
  case "failed":
290
- return M.Fail;
389
+ return S.Fail;
291
390
  case "new":
292
- return M.New;
391
+ return S.New;
293
392
  case "closed":
294
- return M.Closed;
393
+ return S.Closed;
295
394
  case "disconnected":
296
- return M.Disconnected;
395
+ return S.Disconnected;
297
396
  case "completed":
298
- return M.Completed;
397
+ return S.Completed;
299
398
  default:
300
- return M.New;
399
+ return S.New;
301
400
  }
302
401
  }
303
- function Ee() {
402
+ function Ie() {
304
403
  let e = 0;
305
404
  return (n) => {
306
405
  for (const s of n.values())
307
406
  if (s && s.type === "inbound-rtp" && s.kind === "video") {
308
- const a = s.bytesReceived, t = a - e > 0;
309
- return e = a, t;
407
+ const i = s.bytesReceived, t = i - e > 0;
408
+ return e = i, t;
310
409
  }
311
410
  return !1;
312
411
  };
313
412
  }
314
- function Re(e, n, s = !1, a, t) {
315
- const i = Math.max(Math.ceil(10), 1);
316
- let o = 0, l = !1;
317
- const d = s ? 1 : 0;
318
- let u = 0;
319
- const g = Ee();
413
+ function Pe(e, n, s = !1, i, t) {
414
+ const r = Math.max(Math.ceil(10), 1);
415
+ let o = [], m, d = 0, f = !1;
416
+ const u = s ? 1 : 0;
417
+ let g = 0;
418
+ const C = Ie();
320
419
  return setInterval(async () => {
321
- const h = await e.getStats();
322
- g(h) ? (o = 0, l || (n == null || n(F.Start), u >= d && !a() && t(), u++, l = !0)) : l && (o++, o >= i && (n == null || n(F.Stop), l = !1));
420
+ const y = await e.getStats(), v = C(y), h = De(y);
421
+ if (v)
422
+ d = 0, f || (n == null || n(x.Start), g >= u && !i() && t(), m = o[o.length - 1], o = [], g++, f = !0), o.push(h);
423
+ else if (f && (d++, d >= r)) {
424
+ const b = be(o, 100, m);
425
+ n == null || n(x.Stop, b), f = !1;
426
+ }
323
427
  }, 100);
324
428
  }
325
- async function Ie(e, n, {
429
+ async function $e(e, n, {
326
430
  debug: s = !1,
327
- callbacks: a,
431
+ callbacks: i,
328
432
  auth: t,
329
- baseURL: r = U,
330
- warmup: i
433
+ baseURL: a = H,
434
+ warmup: r
331
435
  }) {
332
436
  Q = s;
333
437
  const {
334
438
  startConnection: o,
335
- sendStreamRequest: l,
439
+ sendStreamRequest: m,
336
440
  close: d,
337
- createStream: u,
338
- addIceCandidate: g
339
- } = n.videoType === O.Clip ? Me(t, r, e, a.onError) : Se(t, r, e, a.onError), {
340
- id: h,
441
+ createStream: f,
442
+ addIceCandidate: u
443
+ } = n.videoType === O.Clip ? Re(t, a, e, i.onError) : Se(t, a, e, i.onError), {
444
+ id: g,
341
445
  offer: C,
342
- ice_servers: v,
343
- session_id: _
344
- } = await u(n), y = new ke({
345
- iceServers: v
346
- }), $ = y.createDataChannel("JanusDataChannel");
347
- if (!_)
446
+ ice_servers: y,
447
+ session_id: v
448
+ } = await f(n), h = new Ee({
449
+ iceServers: y
450
+ }), b = h.createDataChannel("JanusDataChannel");
451
+ if (!v)
348
452
  throw new Error("Could not create session_id");
349
453
  let P = !1;
350
454
  const c = () => P, w = () => {
351
- var m;
352
- P = !0, (m = a.onConnectionStateChange) == null || m.call(a, M.Connected);
353
- }, p = Re(y, a.onVideoStateChange, i, c, w);
354
- y.onicecandidate = (m) => {
355
- var f;
356
- x("peerConnection.onicecandidate", m);
455
+ var l;
456
+ P = !0, (l = i.onConnectionStateChange) == null || l.call(i, S.Connected);
457
+ }, k = Pe(h, i.onVideoStateChange, r, c, w);
458
+ h.onicecandidate = (l) => {
459
+ var p;
460
+ L("peerConnection.onicecandidate", l);
357
461
  try {
358
- m.candidate && m.candidate.sdpMid && m.candidate.sdpMLineIndex !== null ? g(h, {
359
- candidate: m.candidate.candidate,
360
- sdpMid: m.candidate.sdpMid,
361
- sdpMLineIndex: m.candidate.sdpMLineIndex
362
- }, _) : g(h, {
462
+ l.candidate && l.candidate.sdpMid && l.candidate.sdpMLineIndex !== null ? u(g, {
463
+ candidate: l.candidate.candidate,
464
+ sdpMid: l.candidate.sdpMid,
465
+ sdpMLineIndex: l.candidate.sdpMLineIndex
466
+ }, v) : u(g, {
363
467
  candidate: null
364
- }, _);
365
- } catch (k) {
366
- (f = a.onError) == null || f.call(a, k, {
367
- streamId: h
468
+ }, v);
469
+ } catch (R) {
470
+ (p = i.onError) == null || p.call(i, R, {
471
+ streamId: g
368
472
  });
369
473
  }
370
- }, $.onmessage = (m) => {
371
- if ($.readyState === "open") {
372
- const [f, k] = m.data.split(":");
373
- f === j.StreamReady && !P && w();
474
+ }, b.onmessage = (l) => {
475
+ if (b.readyState === "open") {
476
+ const [p, R] = l.data.split(":");
477
+ p === W.StreamReady && !P && w();
374
478
  }
375
- }, y.oniceconnectionstatechange = () => {
376
- var f;
377
- x("peerConnection.oniceconnectionstatechange => " + y.iceConnectionState);
378
- const m = J(y.iceConnectionState);
379
- m !== M.Connected && ((f = a.onConnectionStateChange) == null || f.call(a, m));
380
- }, y.ontrack = (m) => {
381
- var f;
382
- x("peerConnection.ontrack", m), (f = a.onSrcObjectReady) == null || f.call(a, m.streams[0]);
383
- }, await y.setRemoteDescription(C), x("set remote description OK");
384
- const S = await y.createAnswer();
385
- return x("create answer OK"), await y.setLocalDescription(S), x("set local description OK"), await o(h, S, _), x("start connection OK"), {
479
+ }, h.oniceconnectionstatechange = () => {
480
+ var p;
481
+ L("peerConnection.oniceconnectionstatechange => " + h.iceConnectionState);
482
+ const l = q(h.iceConnectionState);
483
+ l !== S.Connected && ((p = i.onConnectionStateChange) == null || p.call(i, l));
484
+ }, h.ontrack = (l) => {
485
+ var p;
486
+ L("peerConnection.ontrack", l), (p = i.onSrcObjectReady) == null || p.call(i, l.streams[0]);
487
+ }, await h.setRemoteDescription(C), L("set remote description OK");
488
+ const _ = await h.createAnswer();
489
+ return L("create answer OK"), await h.setLocalDescription(_), L("set local description OK"), await o(g, _, v), L("start connection OK"), {
386
490
  /**
387
491
  * Method to send request to server to get clip or talk depend on you payload
388
492
  * @param payload
389
493
  */
390
- speak(m) {
391
- return l(h, _, m);
494
+ speak(l) {
495
+ return m(g, v, l);
392
496
  },
393
497
  /**
394
498
  * Method to close RTC connection
395
499
  */
396
500
  async disconnect() {
397
- var m, f;
398
- if (h) {
399
- const k = J(y.iceConnectionState);
400
- if (y) {
401
- if (k === M.New) {
402
- (m = a.onVideoStateChange) == null || m.call(a, F.Stop), clearInterval(p);
501
+ var l, p;
502
+ if (g) {
503
+ const R = q(h.iceConnectionState);
504
+ if (h) {
505
+ if (R === S.New) {
506
+ (l = i.onVideoStateChange) == null || l.call(i, x.Stop), clearInterval(k);
403
507
  return;
404
508
  }
405
- y.close(), y.oniceconnectionstatechange = null, y.onnegotiationneeded = null, y.onicecandidate = null, y.ontrack = null;
509
+ h.close(), h.oniceconnectionstatechange = null, h.onnegotiationneeded = null, h.onicecandidate = null, h.ontrack = null;
406
510
  }
407
511
  try {
408
- k === M.Connected && await d(h, _).catch((E) => {
512
+ R === S.Connected && await d(g, v).catch((M) => {
409
513
  });
410
- } catch (E) {
411
- x("Error on close stream connection", E);
514
+ } catch (M) {
515
+ L("Error on close stream connection", M);
412
516
  }
413
- (f = a.onVideoStateChange) == null || f.call(a, F.Stop), clearInterval(p);
517
+ (p = i.onVideoStateChange) == null || p.call(i, x.Stop), clearInterval(k);
414
518
  }
415
519
  },
416
520
  /**
417
521
  * Session identifier information, should be returned in the body of all streaming requests
418
522
  */
419
- sessionId: _,
523
+ sessionId: v,
420
524
  /**
421
525
  * Id of current RTC stream
422
526
  */
423
- streamId: h
527
+ streamId: g
424
528
  };
425
529
  }
426
- let H = {};
427
- function $e(e) {
428
- var r, i, o, l, d;
429
- const n = window != null && window.hasOwnProperty("DID_AGENTS_API") ? "agents-ui" : "agents-sdk", s = e.agent.presenter, a = (r = e.agent.llm) == null ? void 0 : r.prompt_customization, t = {
530
+ let U = {};
531
+ function Ae(e) {
532
+ var a, r, o, m, d;
533
+ const n = window != null && window.hasOwnProperty("DID_AGENTS_API") ? "agents-ui" : "agents-sdk", s = e.agent.presenter, i = (a = e.agent.llm) == null ? void 0 : a.prompt_customization, t = {
430
534
  token: e.token || "testKey",
431
535
  distinct_id: e.distinctId || Y(),
432
536
  agentId: e.agent.id,
433
537
  agentType: s.type === "clip" && s.presenter_id.startsWith("v2_") ? "clip_v2" : s.type,
434
538
  owner_id: e.agent.owner_id ?? "",
435
539
  behavior: {
436
- role: a == null ? void 0 : a.role,
437
- personality: a == null ? void 0 : a.personality,
438
- instructions: (i = e.agent.llm) == null ? void 0 : i.instructions
540
+ role: i == null ? void 0 : i.role,
541
+ personality: i == null ? void 0 : i.personality,
542
+ instructions: (r = e.agent.llm) == null ? void 0 : r.instructions
439
543
  },
440
544
  temperature: (o = e.agent.llm) == null ? void 0 : o.temperature,
441
- knowledgeSource: a == null ? void 0 : a.knowledge_source,
442
- starterQuestionsCount: (d = (l = e.agent.knowledge) == null ? void 0 : l.starter_message) == null ? void 0 : d.length,
443
- topicsToAvoid: a == null ? void 0 : a.topics_to_avoid,
444
- maxResponseLength: a == null ? void 0 : a.max_response_length
545
+ knowledgeSource: i == null ? void 0 : i.knowledge_source,
546
+ starterQuestionsCount: (d = (m = e.agent.knowledge) == null ? void 0 : m.starter_message) == null ? void 0 : d.length,
547
+ topicsToAvoid: i == null ? void 0 : i.topics_to_avoid,
548
+ maxResponseLength: i == null ? void 0 : i.max_response_length
445
549
  };
446
550
  return {
447
551
  ...t,
448
552
  additionalProperties: {},
449
553
  isEnabled: e.isEnabled ?? !0,
450
554
  getRandom: () => Math.random().toString(16).slice(2),
451
- enrich(u) {
452
- const g = {};
453
- if (u && typeof u != "object")
555
+ enrich(f) {
556
+ const u = {};
557
+ if (f && typeof f != "object")
454
558
  throw new Error("properties must be a flat json object");
455
- for (let h in u)
456
- (typeof u[h] == "string" || typeof u[h] == "number") && (g[h] = u[h]);
559
+ for (let g in f)
560
+ (typeof f[g] == "string" || typeof f[g] == "number") && (u[g] = f[g]);
457
561
  this.additionalProperties = {
458
562
  ...this.additionalProperties,
459
- ...g
563
+ ...u
460
564
  };
461
565
  },
462
- track(u, g) {
566
+ track(f, u) {
463
567
  if (!this.isEnabled)
464
568
  return Promise.resolve();
465
569
  const {
466
- audioPath: h,
570
+ audioPath: g,
467
571
  ...C
468
- } = g || {}, v = {
572
+ } = u || {}, y = {
469
573
  method: "POST",
470
574
  headers: {
471
575
  "Content-Type": "application/x-www-form-urlencoded"
472
576
  },
473
577
  body: new URLSearchParams({
474
578
  data: JSON.stringify([{
475
- event: u,
579
+ event: f,
476
580
  properties: {
477
581
  ...this.additionalProperties,
478
582
  ...C,
@@ -488,55 +592,55 @@ function $e(e) {
488
592
  }])
489
593
  })
490
594
  };
491
- return fetch("https://api-js.mixpanel.com/track/?verbose=1&ip=1", v).then((_) => _.json()).catch((_) => console.error(_));
595
+ return fetch("https://api-js.mixpanel.com/track/?verbose=1&ip=1", y).then((v) => v.json()).catch((v) => console.error(v));
492
596
  },
493
- linkTrack(u, g, h, C) {
494
- H[u] || (H[u] = {
597
+ linkTrack(f, u, g, C) {
598
+ U[f] || (U[f] = {
495
599
  events: {},
496
600
  resolvedDependencies: []
497
- }), C.includes(h) || C.push(h);
498
- const v = H[u];
499
- if (v.events[h] = {
500
- props: g
501
- }, v.resolvedDependencies.push(h), C.every((y) => v.resolvedDependencies.includes(y))) {
502
- const y = C.reduce(($, P) => v.events[P] ? {
503
- ...$,
504
- ...v.events[P].props
505
- } : $, {});
506
- this.track(u, y), v.resolvedDependencies = v.resolvedDependencies.filter(($) => !C.includes($)), C.forEach(($) => {
507
- delete v.events[$];
601
+ }), C.includes(g) || C.push(g);
602
+ const y = U[f];
603
+ if (y.events[g] = {
604
+ props: u
605
+ }, y.resolvedDependencies.push(g), C.every((h) => y.resolvedDependencies.includes(h))) {
606
+ const h = C.reduce((b, P) => y.events[P] ? {
607
+ ...b,
608
+ ...y.events[P].props
609
+ } : b, {});
610
+ this.track(f, h), y.resolvedDependencies = y.resolvedDependencies.filter((b) => !C.includes(b)), C.forEach((b) => {
611
+ delete y.events[b];
508
612
  });
509
613
  }
510
614
  }
511
615
  };
512
616
  }
513
- function Ae(e) {
514
- var t, r, i, o;
617
+ function Te(e) {
618
+ var t, a, r, o;
515
619
  const n = () => /Mobi|Android/i.test(navigator.userAgent) ? "Mobile" : "Desktop", s = () => {
516
- const l = navigator.platform;
517
- return l.toLowerCase().includes("win") ? "Windows" : l.toLowerCase().includes("mac") ? "Mac OS X" : l.toLowerCase().includes("linux") ? "Linux" : "Unknown";
518
- }, a = e.presenter;
620
+ const m = navigator.platform;
621
+ return m.toLowerCase().includes("win") ? "Windows" : m.toLowerCase().includes("mac") ? "Mac OS X" : m.toLowerCase().includes("linux") ? "Linux" : "Unknown";
622
+ }, i = e.presenter;
519
623
  return {
520
624
  $os: `${s()}`,
521
625
  isMobile: `${n() == "Mobile"}`,
522
626
  browser: navigator.userAgent,
523
627
  origin: window.location.origin,
524
- agentType: a.type === "clip" && a.presenter_id.startsWith("v2_") ? "clip_v2" : a.type,
628
+ agentType: i.type === "clip" && i.presenter_id.startsWith("v2_") ? "clip_v2" : i.type,
525
629
  agentVoice: {
526
- voiceId: (r = (t = e.presenter) == null ? void 0 : t.voice) == null ? void 0 : r.voice_id,
527
- provider: (o = (i = e.presenter) == null ? void 0 : i.voice) == null ? void 0 : o.type
630
+ voiceId: (a = (t = e.presenter) == null ? void 0 : t.voice) == null ? void 0 : a.voice_id,
631
+ provider: (o = (r = e.presenter) == null ? void 0 : r.voice) == null ? void 0 : o.type
528
632
  }
529
633
  };
530
634
  }
531
- function Pe(e, n, s) {
532
- var d, u;
635
+ function Le(e, n, s) {
636
+ var d, f;
533
637
  const {
534
- event: a,
638
+ event: i,
535
639
  ...t
536
640
  } = e, {
537
- template: r
641
+ template: a
538
642
  } = (n == null ? void 0 : n.llm) || {}, {
539
- language: i
643
+ language: r
540
644
  } = ((d = n == null ? void 0 : n.presenter) == null ? void 0 : d.voice) || {}, {
541
645
  stitch: o
542
646
  } = (n == null ? void 0 : n.presenter) || {};
@@ -544,119 +648,124 @@ function Pe(e, n, s) {
544
648
  ...t,
545
649
  llm: {
546
650
  ...t.llm,
547
- template: r
651
+ template: a
548
652
  },
549
653
  script: {
550
654
  ...t.script,
551
655
  provider: {
552
- ...(u = t == null ? void 0 : t.script) == null ? void 0 : u.provider,
553
- language: i
656
+ ...(f = t == null ? void 0 : t.script) == null ? void 0 : f.provider,
657
+ language: r
554
658
  }
555
659
  },
556
660
  stitch: o,
557
661
  ...s
558
662
  };
559
663
  }
560
- let N = 0;
561
- const be = 20 * 1e3;
562
- function Te(e, n, s) {
563
- var a, t, r, i, o;
664
+ let z = 0;
665
+ const ze = 20 * 1e3;
666
+ function xe(e, n, s) {
667
+ var i, t, a, r, o;
564
668
  return {
565
669
  videoType: le(e.presenter.type),
566
- output_resolution: (a = n == null ? void 0 : n.streamOptions) == null ? void 0 : a.outputResolution,
670
+ output_resolution: (i = n == null ? void 0 : n.streamOptions) == null ? void 0 : i.outputResolution,
567
671
  session_timeout: (t = n == null ? void 0 : n.streamOptions) == null ? void 0 : t.sessionTimeout,
568
- stream_warmup: (r = n == null ? void 0 : n.streamOptions) == null ? void 0 : r.streamWarmup,
569
- compatibility_mode: (i = n == null ? void 0 : n.streamOptions) == null ? void 0 : i.compatibilityMode,
672
+ stream_warmup: (a = n == null ? void 0 : n.streamOptions) == null ? void 0 : a.streamWarmup,
673
+ compatibility_mode: (r = n == null ? void 0 : n.streamOptions) == null ? void 0 : r.compatibilityMode,
570
674
  stream_greeting: (o = n == null ? void 0 : n.streamOptions) != null && o.streamGreeting ? s : void 0
571
675
  };
572
676
  }
573
677
  function ee(e) {
574
- return e === I.Playground ? {
678
+ return e === E.Playground ? {
575
679
  headers: {
576
- [_e]: "true"
680
+ [Ce]: "true"
577
681
  }
578
682
  } : {};
579
683
  }
580
- async function te(e, n, s, a, t) {
684
+ async function te(e, n, s, i, t) {
581
685
  try {
582
- const r = await n.newChat(e, {
686
+ const a = await n.newChat(e, {
583
687
  persist: t ?? !1
584
- }, ee(a));
688
+ }, ee(i));
585
689
  return s.track("agent-chat", {
586
690
  event: "created",
587
- chat_id: r.id,
691
+ chat_id: a.id,
588
692
  agent_id: e,
589
- mode: a
590
- }), r;
591
- } catch (r) {
592
- let i;
693
+ mode: i
694
+ }), a;
695
+ } catch (a) {
696
+ let r;
593
697
  try {
594
- i = JSON.parse(r.message);
698
+ r = JSON.parse(a.message);
595
699
  } catch (o) {
596
700
  console.error("Error parsing the error message:", o);
597
701
  }
598
- throw (i == null ? void 0 : i.kind) === "InsufficientCreditsError" ? new Error("InsufficientCreditsError") : new Error("Cannot create new chat");
702
+ throw (r == null ? void 0 : r.kind) === "InsufficientCreditsError" ? new Error("InsufficientCreditsError") : new Error("Cannot create new chat");
599
703
  }
600
704
  }
601
- function De(e, n, s, a, t, r) {
602
- return new Promise(async (i, o) => {
603
- var d, u, g;
604
- if (N = 0, !t && n.mode !== I.DirectPlayback)
705
+ function Ne(e, n, s, i, t, a) {
706
+ return new Promise(async (r, o) => {
707
+ var d, f, u;
708
+ if (z = 0, !t && n.mode !== E.DirectPlayback)
605
709
  try {
606
- t = await te(e.id, s, a, n.mode, n.persistentChat);
607
- } catch (h) {
608
- return o(h);
710
+ t = await te(e.id, s, i, n.mode, n.persistentChat);
711
+ } catch (g) {
712
+ return o(g);
609
713
  }
610
- if ((t == null ? void 0 : t.chat_mode) === I.TextOnly)
611
- return (u = (d = n.callbacks) == null ? void 0 : d.onError) == null || u.call(d, new Error(JSON.stringify({
714
+ if ((t == null ? void 0 : t.chat_mode) === E.TextOnly)
715
+ return (f = (d = n.callbacks) == null ? void 0 : d.onError) == null || f.call(d, new Error(JSON.stringify({
612
716
  kind: "InsufficientCreditsError"
613
717
  })), {
614
718
  fromSdk: !0
615
- }), i({
719
+ }), r({
616
720
  chat: t
617
721
  });
618
- const l = await Ie(e.id, Te(e, n, r), {
722
+ const m = await $e(e.id, xe(e, n, a), {
619
723
  ...n,
620
- analytics: a,
621
- warmup: (g = n.streamOptions) == null ? void 0 : g.streamWarmup,
724
+ analytics: i,
725
+ warmup: (u = n.streamOptions) == null ? void 0 : u.streamWarmup,
622
726
  callbacks: {
623
727
  ...n.callbacks,
624
- onConnectionStateChange: async (h) => {
625
- var C, v, _, y;
626
- h === M.Connected ? l ? ((v = (C = n.callbacks).onConnectionStateChange) == null || v.call(C, h), i({
728
+ onConnectionStateChange: async (g) => {
729
+ var C, y, v, h;
730
+ g === S.Connected ? m ? ((y = (C = n.callbacks).onConnectionStateChange) == null || y.call(C, g), r({
627
731
  chat: t,
628
- streamingManager: l
629
- })) : t && o(new Error("Something went wrong while initializing the manager")) : (y = (_ = n.callbacks).onConnectionStateChange) == null || y.call(_, h);
732
+ streamingManager: m
733
+ })) : t && o(new Error("Something went wrong while initializing the manager")) : (h = (v = n.callbacks).onConnectionStateChange) == null || h.call(v, g);
630
734
  },
631
- onVideoStateChange(h) {
632
- var C, v;
633
- (v = (C = n.callbacks).onVideoStateChange) == null || v.call(C, h), N > 0 && h === F.Start && a.linkTrack("agent-video", {
735
+ onVideoStateChange(g, C) {
736
+ var y, v;
737
+ (v = (y = n.callbacks).onVideoStateChange) == null || v.call(y, g), z > 0 && (g === x.Start ? i.linkTrack("agent-video", {
634
738
  event: "start",
635
- latency: Date.now() - N
636
- }, "start", [j.StreamVideoCreated]);
739
+ latency: Date.now() - z
740
+ }, "start", [W.StreamVideoCreated]) : g === x.Stop && i.linkTrack("agent-video", {
741
+ event: "stop",
742
+ is_greenscreen: e.presenter.type === "clip" && e.presenter.is_greenscreen,
743
+ background: e.presenter.type === "clip" && e.presenter.background,
744
+ ...C
745
+ }, "done", [W.StreamVideoDone]));
637
746
  }
638
747
  }
639
748
  }).catch(o);
640
749
  });
641
750
  }
642
- function xe(e) {
751
+ function je(e) {
643
752
  var s;
644
- const n = (s = e.greetings) == null ? void 0 : s.filter((a) => a.length > 0);
753
+ const n = (s = e.greetings) == null ? void 0 : s.filter((i) => i.length > 0);
645
754
  if (n && n.length > 0) {
646
- const a = Math.floor(Math.random() * n.length);
647
- return n[a];
755
+ const i = Math.floor(Math.random() * n.length);
756
+ return n[i];
648
757
  } else
649
758
  return `Hi! I'm ${e.preview_name || "My Agent"}. How can I help you?`;
650
759
  }
651
- function z(e, n) {
760
+ function J(e, n) {
652
761
  return n && n.length > 0 ? n : [{
653
762
  content: e,
654
- id: V(),
763
+ id: K(),
655
764
  role: "assistant",
656
765
  created_at: (/* @__PURE__ */ new Date()).toISOString()
657
766
  }];
658
767
  }
659
- function Ne(e) {
768
+ function Fe(e) {
660
769
  if (e.answer !== void 0)
661
770
  return e.answer;
662
771
  let n = 0, s = "";
@@ -664,103 +773,106 @@ function Ne(e) {
664
773
  s += e[n], n++;
665
774
  return s;
666
775
  }
667
- function Le(e, n, s, a, t) {
668
- if (!(e === L.Partial || e === L.Answer))
776
+ function We(e, n, s, i, t) {
777
+ if (!(e === N.Partial || e === N.Answer))
669
778
  return;
670
- const r = a.messages[a.messages.length - 1];
671
- if ((r == null ? void 0 : r.role) !== "assistant")
779
+ const a = i.messages[i.messages.length - 1];
780
+ if ((a == null ? void 0 : a.role) !== "assistant")
672
781
  return;
673
782
  const {
674
- content: i,
783
+ content: r,
675
784
  sequence: o
676
785
  } = n;
677
- e === L.Partial ? s[o] = i : s.answer = i;
678
- const l = Ne(s);
679
- (r.content !== l || e === L.Answer) && (r.content = l, t == null || t([...a.messages], e));
786
+ e === N.Partial ? s[o] = r : s.answer = r;
787
+ const m = Fe(s);
788
+ (a.content !== m || e === N.Answer) && (a.content = m, t == null || t([...i.messages], e));
680
789
  }
681
- async function Fe(e, n) {
682
- var y, $, P;
683
- let s = {}, a = !0;
790
+ async function He(e, n) {
791
+ var h, b, P;
792
+ let s = {}, i = !0;
684
793
  const t = {
685
794
  messages: [],
686
- chatMode: n.mode || I.Functional
687
- }, r = n.baseURL || U, i = n.wsURL || ue, o = n.mixpanelKey || he, l = G(n.auth, r, n.callbacks.onError), d = await l.getById(e), u = xe(d);
688
- t.messages = z(u, n.initialMessages), ($ = (y = n.callbacks).onNewMessage) == null || $.call(y, [...t.messages], "answer");
689
- const g = $e({
795
+ chatMode: n.mode || E.Functional
796
+ }, a = n.baseURL || H, r = n.wsURL || fe, o = n.mixpanelKey || ge, m = G(n.auth, a, n.callbacks.onError), d = await m.getById(e), f = je(d);
797
+ t.messages = J(f, n.initialMessages), (b = (h = n.callbacks).onNewMessage) == null || b.call(h, [...t.messages], "answer");
798
+ const u = Ae({
690
799
  token: o,
691
800
  agent: d,
692
801
  isEnabled: n.enableAnalitics,
693
802
  distinctId: n.distinctId
694
803
  });
695
- g.track("agent-sdk", {
804
+ u.track("agent-sdk", {
696
805
  event: "loaded",
697
- ...Ae(d)
806
+ ...Te(d)
698
807
  });
699
- const h = {
808
+ const g = {
700
809
  onMessage: (c, w) => {
701
- var p, S;
810
+ var k, _;
702
811
  if ("content" in w)
703
- Le(c, w, s, t, n.callbacks.onNewMessage), c === L.Answer && g.track("agent-message-received", {
812
+ We(c, w, s, t, n.callbacks.onNewMessage), c === N.Answer && u.track("agent-message-received", {
704
813
  messages: t.messages.length,
705
814
  mode: t.chatMode
706
815
  });
707
816
  else {
708
- const m = j, f = [m.StreamVideoDone, m.StreamVideoError, m.StreamVideoRejected], k = [m.StreamFailed, m.StreamVideoError, m.StreamVideoRejected], E = Pe(w, d, {
817
+ const l = W, p = [l.StreamVideoDone, l.StreamVideoError, l.StreamVideoRejected], R = [l.StreamFailed, l.StreamVideoError, l.StreamVideoRejected], M = Le(w, d, {
709
818
  mode: t.chatMode
710
819
  });
711
- if (c = c, c === m.StreamVideoCreated)
712
- g.linkTrack("agent-video", E, m.StreamVideoCreated, ["start"]);
713
- else if (f.includes(c)) {
714
- const R = c.split("/")[1];
715
- g.track("agent-video", {
716
- ...E,
717
- event: R
718
- });
820
+ if (c = c, c === l.StreamVideoCreated)
821
+ u.linkTrack("agent-video", M, l.StreamVideoCreated, ["start"]);
822
+ else if (p.includes(c)) {
823
+ const D = c.split("/")[1];
824
+ R.includes(c) ? u.track("agent-video", {
825
+ ...M,
826
+ event: D
827
+ }) : u.linkTrack("agent-video", {
828
+ ...M,
829
+ event: D
830
+ }, c, ["done"]);
719
831
  }
720
- k.includes(c) && ((S = (p = n.callbacks).onError) == null || S.call(p, new Error(`Stream failed with event ${c}`), {
832
+ R.includes(c) && ((_ = (k = n.callbacks).onError) == null || _.call(k, new Error(`Stream failed with event ${c}`), {
721
833
  data: w
722
- })), w.event === m.StreamDone && v();
834
+ })), w.event === l.StreamDone && y();
723
835
  }
724
836
  }
725
837
  };
726
838
  async function C(c) {
727
- var k, E, R, b, K, D, T;
728
- (E = (k = n.callbacks).onConnectionStateChange) == null || E.call(k, M.Connecting), N = 0, c && !a && (delete t.chat, t.messages = z(u), (b = (R = n.callbacks).onNewMessage) == null || b.call(R, [...t.messages], "answer"));
729
- const w = n.mode === I.DirectPlayback ? Promise.resolve(void 0) : Ce(n.auth, i, h), p = X(() => De(d, n, l, g, t.chat, c ? u : void 0), {
839
+ var R, M, D, $, j, T, A;
840
+ (M = (R = n.callbacks).onConnectionStateChange) == null || M.call(R, S.Connecting), z = 0, c && !i && (delete t.chat, t.messages = J(f), ($ = (D = n.callbacks).onNewMessage) == null || $.call(D, [...t.messages], "answer"));
841
+ const w = n.mode === E.DirectPlayback ? Promise.resolve(void 0) : ke(n.auth, r, g), k = X(() => Ne(d, n, m, u, t.chat, c ? f : void 0), {
730
842
  limit: 3,
731
- timeout: be,
843
+ timeout: ze,
732
844
  timeoutErrorMessage: "Could not connect",
733
845
  // Retry on all errors except for connection errors and rate limit errors, these are already handled in client level.
734
- shouldRetryFn: (A) => (A == null ? void 0 : A.message) !== "Could not connect" && A.status !== 429,
846
+ shouldRetryFn: (I) => (I == null ? void 0 : I.message) !== "Could not connect" && I.status !== 429,
735
847
  delayMs: 1e3
736
- }).catch((A) => {
737
- var W, B;
738
- throw _(I.Maintenance), (B = (W = n.callbacks).onConnectionStateChange) == null || B.call(W, M.Fail), A;
739
- }), [S, {
740
- streamingManager: m,
741
- chat: f
742
- }] = await Promise.all([w, p]);
743
- f && f.id !== ((K = t.chat) == null ? void 0 : K.id) && ((T = (D = n.callbacks).onNewChat) == null || T.call(D, f.id)), t.streamingManager = m, t.socketManager = S, t.chat = f, a = !1, _((f == null ? void 0 : f.chat_mode) ?? n.mode ?? I.Functional);
848
+ }).catch((I) => {
849
+ var F, V;
850
+ throw v(E.Maintenance), (V = (F = n.callbacks).onConnectionStateChange) == null || V.call(F, S.Fail), I;
851
+ }), [_, {
852
+ streamingManager: l,
853
+ chat: p
854
+ }] = await Promise.all([w, k]);
855
+ p && p.id !== ((j = t.chat) == null ? void 0 : j.id) && ((A = (T = n.callbacks).onNewChat) == null || A.call(T, p.id)), t.streamingManager = l, t.socketManager = _, t.chat = p, i = !1, v((p == null ? void 0 : p.chat_mode) ?? n.mode ?? E.Functional);
744
856
  }
745
- async function v() {
746
- var c, w, p, S;
747
- (c = t.socketManager) == null || c.disconnect(), await ((w = t.streamingManager) == null ? void 0 : w.disconnect()), delete t.streamingManager, delete t.socketManager, (S = (p = n.callbacks).onConnectionStateChange) == null || S.call(p, M.Disconnected);
857
+ async function y() {
858
+ var c, w, k, _;
859
+ (c = t.socketManager) == null || c.disconnect(), await ((w = t.streamingManager) == null ? void 0 : w.disconnect()), delete t.streamingManager, delete t.socketManager, (_ = (k = n.callbacks).onConnectionStateChange) == null || _.call(k, S.Disconnected);
748
860
  }
749
- async function _(c) {
750
- var w, p;
751
- c !== t.chatMode && (g.track("agent-mode-change", {
861
+ async function v(c) {
862
+ var w, k;
863
+ c !== t.chatMode && (u.track("agent-mode-change", {
752
864
  mode: c
753
- }), t.chatMode = c, t.chatMode !== I.Functional && await v(), (p = (w = n.callbacks).onModeChange) == null || p.call(w, c));
865
+ }), t.chatMode = c, t.chatMode !== E.Functional && await y(), (k = (w = n.callbacks).onModeChange) == null || k.call(w, c));
754
866
  }
755
867
  return {
756
868
  agent: d,
757
869
  starterMessages: ((P = d.knowledge) == null ? void 0 : P.starter_message) || [],
758
- getSTTToken: () => l.getSTTToken(d.id),
759
- changeMode: _,
760
- enrichAnalytics: g.enrich,
870
+ getSTTToken: () => m.getSTTToken(d.id),
871
+ changeMode: v,
872
+ enrichAnalytics: u.enrich,
761
873
  async connect() {
762
874
  var c;
763
- await C(!0), g.track("agent-chat", {
875
+ await C(!0), u.track("agent-chat", {
764
876
  event: "connect",
765
877
  chatId: (c = t.chat) == null ? void 0 : c.id,
766
878
  agentId: d.id,
@@ -769,7 +881,7 @@ async function Fe(e, n) {
769
881
  },
770
882
  async reconnect() {
771
883
  var c;
772
- await v(), await C(!1), g.track("agent-chat", {
884
+ await y(), await C(!1), u.track("agent-chat", {
773
885
  event: "reconnect",
774
886
  chatId: (c = t.chat) == null ? void 0 : c.id,
775
887
  agentId: d.id,
@@ -778,7 +890,7 @@ async function Fe(e, n) {
778
890
  },
779
891
  async disconnect() {
780
892
  var c;
781
- await v(), g.track("agent-chat", {
893
+ await y(), u.track("agent-chat", {
782
894
  event: "disconnect",
783
895
  chatId: (c = t.chat) == null ? void 0 : c.id,
784
896
  agentId: d.id,
@@ -786,97 +898,97 @@ async function Fe(e, n) {
786
898
  });
787
899
  },
788
900
  async chat(c) {
789
- var p, S, m, f, k, E;
790
- const w = V();
901
+ var k, _, l, p, R, M;
902
+ const w = K();
791
903
  s = {};
792
904
  try {
793
- if (N = Date.now(), n.mode === I.DirectPlayback)
905
+ if (z = Date.now(), n.mode === E.DirectPlayback)
794
906
  throw new Error("Direct playback is enabled, chat is disabled");
795
907
  if (c.length >= 800)
796
908
  throw new Error("Message cannot be more than 800 characters");
797
909
  if (c.length === 0)
798
910
  throw new Error("Message cannot be empty");
799
- if (t.chatMode === I.Maintenance)
911
+ if (t.chatMode === E.Maintenance)
800
912
  throw new Error("Chat is in maintenance mode");
801
- if (![I.TextOnly, I.Playground].includes(t.chatMode))
913
+ if (![E.TextOnly, E.Playground].includes(t.chatMode))
802
914
  if (t.streamingManager) {
803
915
  if (!t.chat)
804
916
  throw new Error("Chat is not initialized");
805
917
  } else
806
918
  throw new Error("Streaming manager is not initialized");
807
919
  t.messages.push({
808
- id: V(),
920
+ id: K(),
809
921
  role: "user",
810
922
  content: c,
811
- created_at: new Date(N).toISOString()
812
- }), (S = (p = n.callbacks).onNewMessage) == null || S.call(p, [...t.messages], "user"), t.chat || (t.chat = await te(d.id, l, g, t.chatMode, n.persistentChat), (f = (m = n.callbacks).onNewChat) == null || f.call(m, t.chat.id));
813
- const R = {
923
+ created_at: new Date(z).toISOString()
924
+ }), (_ = (k = n.callbacks).onNewMessage) == null || _.call(k, [...t.messages], "user"), t.chat || (t.chat = await te(d.id, m, u, t.chatMode, n.persistentChat), (p = (l = n.callbacks).onNewChat) == null || p.call(l, t.chat.id));
925
+ const D = {
814
926
  id: w,
815
927
  role: "assistant",
816
928
  content: "",
817
929
  created_at: (/* @__PURE__ */ new Date()).toISOString(),
818
930
  matches: []
819
- }, b = [...t.messages];
820
- t.messages.push(R);
821
- const K = (T) => {
822
- var A, W;
823
- return l.chat(d.id, T, {
824
- sessionId: (A = t.streamingManager) == null ? void 0 : A.sessionId,
825
- streamId: (W = t.streamingManager) == null ? void 0 : W.streamId,
931
+ }, $ = [...t.messages];
932
+ t.messages.push(D);
933
+ const j = (A) => {
934
+ var I, F;
935
+ return m.chat(d.id, A, {
936
+ sessionId: (I = t.streamingManager) == null ? void 0 : I.sessionId,
937
+ streamId: (F = t.streamingManager) == null ? void 0 : F.streamId,
826
938
  chatMode: t.chatMode,
827
- messages: b.map(({
828
- matches: B,
939
+ messages: $.map(({
940
+ matches: V,
829
941
  ...ne
830
942
  }) => ne)
831
943
  }, ee(t.chatMode));
832
- }, D = await K(t.chat.id).catch(async (T) => {
833
- var A;
834
- if (!((A = T == null ? void 0 : T.message) != null && A.includes("missing or invalid session_id")))
835
- throw T;
836
- return await v(), await C(!1), K(t.chat.id);
944
+ }, T = await j(t.chat.id).catch(async (A) => {
945
+ var I;
946
+ if (!((I = A == null ? void 0 : A.message) != null && I.includes("missing or invalid session_id")))
947
+ throw A;
948
+ return await y(), await C(!1), j(t.chat.id);
837
949
  });
838
- return g.track("agent-message-send", {
950
+ return u.track("agent-message-send", {
839
951
  event: "success",
840
952
  mode: t.chatMode,
841
953
  messages: t.messages.length + 1
842
- }), R.context = D.context, R.matches = D.matches, D.result && (R.content = D.result, g.track("agent-message-received", {
843
- latency: Date.now() - N,
954
+ }), D.context = T.context, D.matches = T.matches, T.result && (D.content = T.result, u.track("agent-message-received", {
955
+ latency: Date.now() - z,
844
956
  mode: t.chatMode,
845
957
  messages: t.messages.length
846
- }), (E = (k = n.callbacks).onNewMessage) == null || E.call(k, [...t.messages], "answer")), D;
847
- } catch (R) {
848
- throw t.messages[t.messages.length - 1].id === w && t.messages.pop(), g.track("agent-message-send", {
958
+ }), (M = (R = n.callbacks).onNewMessage) == null || M.call(R, [...t.messages], "answer")), T;
959
+ } catch (D) {
960
+ throw t.messages[t.messages.length - 1].id === w && t.messages.pop(), u.track("agent-message-send", {
849
961
  event: "error",
850
962
  mode: t.chatMode,
851
963
  messages: t.messages.length
852
- }), R;
964
+ }), D;
853
965
  }
854
966
  },
855
- rate(c, w, p) {
856
- var f, k, E, R;
857
- const S = t.messages.find((b) => b.id === c);
967
+ rate(c, w, k) {
968
+ var p, R, M, D;
969
+ const _ = t.messages.find(($) => $.id === c);
858
970
  if (t.chat) {
859
- if (!S)
971
+ if (!_)
860
972
  throw new Error("Message not found");
861
973
  } else
862
974
  throw new Error("Chat is not initialized");
863
- const m = ((f = S.matches) == null ? void 0 : f.map((b) => [b.document_id, b.id])) ?? [];
864
- return g.track("agent-rate", {
865
- event: p ? "update" : "create",
975
+ const l = ((p = _.matches) == null ? void 0 : p.map(($) => [$.document_id, $.id])) ?? [];
976
+ return u.track("agent-rate", {
977
+ event: k ? "update" : "create",
866
978
  thumb: w === 1 ? "up" : "down",
867
- knowledge_id: ((k = d.knowledge) == null ? void 0 : k.id) ?? "",
979
+ knowledge_id: ((R = d.knowledge) == null ? void 0 : R.id) ?? "",
868
980
  mode: t.chatMode,
869
- matches: m,
981
+ matches: l,
870
982
  score: w
871
- }), p ? l.updateRating(d.id, t.chat.id, p, {
872
- knowledge_id: ((E = d.knowledge) == null ? void 0 : E.id) ?? "",
983
+ }), k ? m.updateRating(d.id, t.chat.id, k, {
984
+ knowledge_id: ((M = d.knowledge) == null ? void 0 : M.id) ?? "",
873
985
  message_id: c,
874
- matches: m,
986
+ matches: l,
875
987
  score: w
876
- }) : l.createRating(d.id, t.chat.id, {
877
- knowledge_id: ((R = d.knowledge) == null ? void 0 : R.id) ?? "",
988
+ }) : m.createRating(d.id, t.chat.id, {
989
+ knowledge_id: ((D = d.knowledge) == null ? void 0 : D.id) ?? "",
878
990
  message_id: c,
879
- matches: m,
991
+ matches: l,
880
992
  score: w
881
993
  });
882
994
  },
@@ -884,16 +996,17 @@ async function Fe(e, n) {
884
996
  var w;
885
997
  if (!t.chat)
886
998
  throw new Error("Chat is not initialized");
887
- return g.track("agent-rate-delete", {
999
+ return u.track("agent-rate-delete", {
888
1000
  type: "text",
889
1001
  chat_id: (w = t.chat) == null ? void 0 : w.id,
890
1002
  id: c,
891
1003
  mode: t.chatMode
892
- }), l.deleteRating(d.id, t.chat.id, c);
1004
+ }), m.deleteRating(d.id, t.chat.id, c);
893
1005
  },
894
1006
  speak(c) {
895
1007
  if (!t.streamingManager)
896
1008
  throw new Error("Please connect to the agent first");
1009
+ z = Date.now();
897
1010
  function w() {
898
1011
  if (typeof c == "string") {
899
1012
  if (!d.presenter.voice)
@@ -917,36 +1030,36 @@ async function Fe(e, n) {
917
1030
  }
918
1031
  return c;
919
1032
  }
920
- const p = w();
921
- return g.track("agent-speak", p), t.streamingManager.speak({
922
- script: p
1033
+ const k = w();
1034
+ return u.track("agent-speak", k), t.streamingManager.speak({
1035
+ script: k
923
1036
  });
924
1037
  }
925
1038
  };
926
1039
  }
927
1040
  function Ke(e, n, s) {
928
1041
  const {
929
- getById: a
930
- } = G(n, s || U);
931
- return a(e);
1042
+ getById: i
1043
+ } = G(n, s || H);
1044
+ return i(e);
932
1045
  }
933
1046
  export {
934
1047
  ie as AgentStatus,
935
- I as ChatMode,
936
- L as ChatProgress,
937
- M as ConnectionState,
1048
+ E as ChatMode,
1049
+ N as ChatProgress,
1050
+ S as ConnectionState,
938
1051
  de as DocumentType,
939
1052
  ce as KnowledgeType,
940
1053
  ae as PlanGroup,
941
1054
  me as Providers,
942
1055
  se as RateState,
943
- j as StreamEvents,
944
- F as StreamingState,
1056
+ W as StreamEvents,
1057
+ x as StreamingState,
945
1058
  oe as Subject,
946
1059
  re as UserPlan,
947
1060
  O as VideoType,
948
- ge as VoiceAccess,
949
- Fe as createAgentManager,
1061
+ ue as VoiceAccess,
1062
+ He as createAgentManager,
950
1063
  Ke as getAgent,
951
1064
  le as mapVideoType
952
1065
  };