@d-id/client-sdk 1.1.0-beta.1 → 1.1.0-beta.11

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