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

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