@d-id/client-sdk 1.1.0-beta.7 → 1.1.1-staging.2

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