@d-id/client-sdk 1.1.0-beta.10 → 1.1.0-beta.12

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,525 +1,323 @@
1
- var __defProp = Object.defineProperty;
2
- var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
3
- var __publicField = (obj, key, value) => {
4
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
5
- return value;
6
- };
7
- class BaseError extends Error {
1
+ var me = Object.defineProperty;
2
+ var ge = (e, t, a) => t in e ? me(e, t, { enumerable: !0, configurable: !0, writable: !0, value: a }) : e[t] = a;
3
+ var q = (e, t, a) => (ge(e, typeof t != "symbol" ? t + "" : t, a), a);
4
+ class Q extends Error {
8
5
  constructor({
9
- kind,
10
- description,
11
- error
6
+ kind: a,
7
+ description: r,
8
+ error: o
12
9
  }) {
13
10
  super(JSON.stringify({
14
- kind,
15
- description
11
+ kind: a,
12
+ description: r
16
13
  }));
17
- __publicField(this, "kind");
18
- __publicField(this, "description");
19
- __publicField(this, "error");
20
- this.kind = kind;
21
- this.description = description;
22
- this.error = error;
14
+ q(this, "kind");
15
+ q(this, "description");
16
+ q(this, "error");
17
+ this.kind = a, this.description = r, this.error = o;
23
18
  }
24
19
  }
25
- class ChatCreationFailed extends BaseError {
26
- constructor(mode, persistent) {
20
+ class he extends Q {
21
+ constructor(t, a) {
27
22
  super({
28
23
  kind: "ChatCreationFailed",
29
- description: `Failed to create ${persistent ? "persistent" : ""} chat, mode: ${mode}`
24
+ description: `Failed to create ${a ? "persistent" : ""} chat, mode: ${t}`
30
25
  });
31
26
  }
32
27
  }
33
- class ChatModeDowngraded extends BaseError {
34
- constructor(mode) {
28
+ class we extends Q {
29
+ constructor(t) {
35
30
  super({
36
31
  kind: "ChatModeDowngraded",
37
- description: `Chat mode downgraded to ${mode}`
32
+ description: `Chat mode downgraded to ${t}`
38
33
  });
39
34
  }
40
35
  }
41
- class ValidationError extends BaseError {
42
- constructor(message, key) {
36
+ class W extends Q {
37
+ constructor(a, r) {
43
38
  super({
44
39
  kind: "ValidationError",
45
- description: message
40
+ description: a
46
41
  });
47
- __publicField(this, "key");
48
- this.key = key;
42
+ q(this, "key");
43
+ this.key = r;
49
44
  }
50
45
  }
51
- class WsError extends BaseError {
52
- constructor(message) {
46
+ class pe extends Q {
47
+ constructor(t) {
53
48
  super({
54
49
  kind: "WSError",
55
- description: message
50
+ description: t
56
51
  });
57
52
  }
58
53
  }
59
- var UserPlan = /* @__PURE__ */ ((UserPlan2) => {
60
- UserPlan2["TRIAL"] = "trial";
61
- UserPlan2["BASIC"] = "basic";
62
- UserPlan2["ENTERPRISE"] = "enterprise";
63
- UserPlan2["LITE"] = "lite";
64
- UserPlan2["ADVANCED"] = "advanced";
65
- return UserPlan2;
66
- })(UserPlan || {});
67
- var PlanGroup = /* @__PURE__ */ ((PlanGroup2) => {
68
- PlanGroup2["TRIAL"] = "deid-trial";
69
- PlanGroup2["PRO"] = "deid-pro";
70
- PlanGroup2["ENTERPRISE"] = "deid-enterprise";
71
- PlanGroup2["LITE"] = "deid-lite";
72
- PlanGroup2["ADVANCED"] = "deid-advanced";
73
- PlanGroup2["BUILD"] = "deid-api-build";
74
- PlanGroup2["LAUNCH"] = "deid-api-launch";
75
- PlanGroup2["SCALE"] = "deid-api-scale";
76
- return PlanGroup2;
77
- })(PlanGroup || {});
78
- var AgentStatus = /* @__PURE__ */ ((AgentStatus2) => {
79
- AgentStatus2["Created"] = "created";
80
- AgentStatus2["Started"] = "started";
81
- AgentStatus2["Done"] = "done";
82
- AgentStatus2["Error"] = "error";
83
- AgentStatus2["Rejected"] = "rejected";
84
- AgentStatus2["Ready"] = "ready";
85
- return AgentStatus2;
86
- })(AgentStatus || {});
87
- var RateState = /* @__PURE__ */ ((RateState2) => {
88
- RateState2["Unrated"] = "Unrated";
89
- RateState2["Positive"] = "Positive";
90
- RateState2["Negative"] = "Negative";
91
- return RateState2;
92
- })(RateState || {});
93
- var ChatMode = /* @__PURE__ */ ((ChatMode2) => {
94
- ChatMode2["Functional"] = "Functional";
95
- ChatMode2["TextOnly"] = "TextOnly";
96
- ChatMode2["Maintenance"] = "Maintenance";
97
- ChatMode2["Playground"] = "Playground";
98
- ChatMode2["DirectPlayback"] = "DirectPlayback";
99
- return ChatMode2;
100
- })(ChatMode || {});
101
- var ChatProgress = /* @__PURE__ */ ((ChatProgress2) => {
102
- ChatProgress2["Embed"] = "embed";
103
- ChatProgress2["Query"] = "query";
104
- ChatProgress2["Partial"] = "partial";
105
- ChatProgress2["Answer"] = "answer";
106
- ChatProgress2["Complete"] = "done";
107
- return ChatProgress2;
108
- })(ChatProgress || {});
109
- var Subject = /* @__PURE__ */ ((Subject2) => {
110
- Subject2["KnowledgeProcessing"] = "knowledge/processing";
111
- Subject2["KnowledgeIndexing"] = "knowledge/indexing";
112
- Subject2["KnowledgeFailed"] = "knowledge/error";
113
- Subject2["KnowledgeDone"] = "knowledge/done";
114
- return Subject2;
115
- })(Subject || {});
116
- var KnowledgeType = /* @__PURE__ */ ((KnowledgeType2) => {
117
- KnowledgeType2["Knowledge"] = "knowledge";
118
- KnowledgeType2["Document"] = "document";
119
- KnowledgeType2["Record"] = "record";
120
- return KnowledgeType2;
121
- })(KnowledgeType || {});
122
- var DocumentType = /* @__PURE__ */ ((DocumentType2) => {
123
- DocumentType2["Pdf"] = "pdf";
124
- DocumentType2["Text"] = "text";
125
- DocumentType2["Html"] = "html";
126
- DocumentType2["Word"] = "word";
127
- DocumentType2["Json"] = "json";
128
- DocumentType2["Markdown"] = "markdown";
129
- DocumentType2["Csv"] = "csv";
130
- DocumentType2["Excel"] = "excel";
131
- DocumentType2["Powerpoint"] = "powerpoint";
132
- DocumentType2["Archive"] = "archive";
133
- DocumentType2["Image"] = "image";
134
- DocumentType2["Audio"] = "audio";
135
- DocumentType2["Video"] = "video";
136
- return DocumentType2;
137
- })(DocumentType || {});
138
- var VideoType = /* @__PURE__ */ ((VideoType2) => {
139
- VideoType2["Clip"] = "clip";
140
- VideoType2["Talk"] = "talk";
141
- return VideoType2;
142
- })(VideoType || {});
143
- const mapVideoType = (type) => {
144
- switch (type) {
54
+ var ye = /* @__PURE__ */ ((e) => (e.TRIAL = "trial", e.BASIC = "basic", e.ENTERPRISE = "enterprise", e.LITE = "lite", e.ADVANCED = "advanced", e))(ye || {}), ve = /* @__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))(ve || {}), ke = /* @__PURE__ */ ((e) => (e.Created = "created", e.Started = "started", e.Done = "done", e.Error = "error", e.Rejected = "rejected", e.Ready = "ready", e))(ke || {}), De = /* @__PURE__ */ ((e) => (e.Unrated = "Unrated", e.Positive = "Positive", e.Negative = "Negative", e))(De || {}), b = /* @__PURE__ */ ((e) => (e.Functional = "Functional", e.TextOnly = "TextOnly", e.Maintenance = "Maintenance", e.Playground = "Playground", e.DirectPlayback = "DirectPlayback", e))(b || {}), U = /* @__PURE__ */ ((e) => (e.Embed = "embed", e.Query = "query", e.Partial = "partial", e.Answer = "answer", e.Complete = "done", e))(U || {}), Re = /* @__PURE__ */ ((e) => (e.KnowledgeProcessing = "knowledge/processing", e.KnowledgeIndexing = "knowledge/indexing", e.KnowledgeFailed = "knowledge/error", e.KnowledgeDone = "knowledge/done", e))(Re || {}), Ce = /* @__PURE__ */ ((e) => (e.Knowledge = "knowledge", e.Document = "document", e.Record = "record", e))(Ce || {}), 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 || {}), ae = /* @__PURE__ */ ((e) => (e.Clip = "clip", e.Talk = "talk", e))(ae || {});
55
+ const Ee = (e) => {
56
+ switch (e) {
145
57
  case "clip":
146
58
  return "clip";
147
59
  case "talk":
148
60
  return "talk";
149
61
  default:
150
- throw new Error(`Unknown video type: ${type}`);
62
+ throw new Error(`Unknown video type: ${e}`);
151
63
  }
152
64
  };
153
- var StreamingState = /* @__PURE__ */ ((StreamingState2) => {
154
- StreamingState2["Start"] = "START";
155
- StreamingState2["Stop"] = "STOP";
156
- return StreamingState2;
157
- })(StreamingState || {});
158
- var ConnectivityState = /* @__PURE__ */ ((ConnectivityState2) => {
159
- ConnectivityState2["Strong"] = "STRONG";
160
- ConnectivityState2["Weak"] = "WEAK";
161
- ConnectivityState2["Unknown"] = "UNKNOWN";
162
- return ConnectivityState2;
163
- })(ConnectivityState || {});
164
- var AgentActivityState = /* @__PURE__ */ ((AgentActivityState2) => {
165
- AgentActivityState2["Idle"] = "IDLE";
166
- AgentActivityState2["Talking"] = "TALKING";
167
- return AgentActivityState2;
168
- })(AgentActivityState || {});
169
- const DataChannelSignalMap = {
170
- "stream/started": "START",
171
- "stream/done": "STOP"
172
- /* Stop */
173
- };
174
- var StreamEvents = /* @__PURE__ */ ((StreamEvents2) => {
175
- StreamEvents2["ChatAnswer"] = "chat/answer";
176
- StreamEvents2["ChatPartial"] = "chat/partial";
177
- StreamEvents2["StreamDone"] = "stream/done";
178
- StreamEvents2["StreamStarted"] = "stream/started";
179
- StreamEvents2["StreamFailed"] = "stream/error";
180
- StreamEvents2["StreamReady"] = "stream/ready";
181
- StreamEvents2["StreamCreated"] = "stream/created";
182
- StreamEvents2["StreamVideoCreated"] = "stream-video/started";
183
- StreamEvents2["StreamVideoDone"] = "stream-video/done";
184
- StreamEvents2["StreamVideoError"] = "stream-video/error";
185
- StreamEvents2["StreamVideoRejected"] = "stream-video/rejected";
186
- return StreamEvents2;
187
- })(StreamEvents || {});
188
- var ConnectionState = /* @__PURE__ */ ((ConnectionState2) => {
189
- ConnectionState2["New"] = "new";
190
- ConnectionState2["Fail"] = "fail";
191
- ConnectionState2["Connected"] = "connected";
192
- ConnectionState2["Connecting"] = "connecting";
193
- ConnectionState2["Closed"] = "closed";
194
- ConnectionState2["Completed"] = "completed";
195
- ConnectionState2["Disconnected"] = "disconnected";
196
- return ConnectionState2;
197
- })(ConnectionState || {});
198
- var StreamType = /* @__PURE__ */ ((StreamType2) => {
199
- StreamType2["Legacy"] = "legacy";
200
- StreamType2["Fluent"] = "fluent";
201
- return StreamType2;
202
- })(StreamType || {});
203
- var Providers = /* @__PURE__ */ ((Providers2) => {
204
- Providers2["Amazon"] = "amazon";
205
- Providers2["Microsoft"] = "microsoft";
206
- Providers2["Afflorithmics"] = "afflorithmics";
207
- Providers2["Elevenlabs"] = "elevenlabs";
208
- return Providers2;
209
- })(Providers || {});
210
- var VoiceAccess = /* @__PURE__ */ ((VoiceAccess2) => {
211
- VoiceAccess2["Public"] = "public";
212
- VoiceAccess2["Premium"] = "premium";
213
- VoiceAccess2["Private"] = "private";
214
- return VoiceAccess2;
215
- })(VoiceAccess || {});
216
- const CONNECTION_RETRY_TIMEOUT_MS = 45 * 1e3;
217
- const PLAYGROUND_HEADER = "X-Playground-Chat";
218
- const didApiUrl = "https://api-dev.d-id.com";
219
- const didSocketApiUrl = "wss://notifications-dev.d-id.com";
220
- const mixpanelKey = "79f81a83a67430be2bc0fd61042b8faa";
221
- const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
222
- const getRandom = (length = 16) => {
223
- const arr = new Uint8Array(length);
224
- window.crypto.getRandomValues(arr);
225
- return Array.from(arr, (byte) => byte.toString(16).padStart(2, "0")).join("").slice(0, 13);
226
- };
227
- const isTextualChat = (chatMode) => [ChatMode.TextOnly, ChatMode.Playground, ChatMode.Maintenance].includes(chatMode);
228
- function createRacePromise(timeout, timeoutErrorMessage) {
229
- let timeId;
230
- const promise = new Promise((_, reject) => {
231
- timeId = setTimeout(() => reject(new Error(timeoutErrorMessage)), timeout);
232
- });
65
+ var p = /* @__PURE__ */ ((e) => (e.Start = "START", e.Stop = "STOP", e))(p || {}), V = /* @__PURE__ */ ((e) => (e.Strong = "STRONG", e.Weak = "WEAK", e.Unknown = "UNKNOWN", e))(V || {}), X = /* @__PURE__ */ ((e) => (e.Idle = "IDLE", e.Talking = "TALKING", e))(X || {}), N = /* @__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))(N || {}), M = /* @__PURE__ */ ((e) => (e.New = "new", e.Fail = "fail", e.Connected = "connected", e.Connecting = "connecting", e.Closed = "closed", e.Completed = "completed", e.Disconnected = "disconnected", e))(M || {}), J = /* @__PURE__ */ ((e) => (e.Legacy = "legacy", e.Fluent = "fluent", e))(J || {}), _e = /* @__PURE__ */ ((e) => (e.Amazon = "amazon", e.Microsoft = "microsoft", e.Afflorithmics = "afflorithmics", e.Elevenlabs = "elevenlabs", e))(_e || {}), Me = /* @__PURE__ */ ((e) => (e.Public = "public", e.Premium = "premium", e.Private = "private", e))(Me || {});
66
+ const Ie = 45 * 1e3, be = "X-Playground-Chat", Y = "https://api.d-id.com", Te = "wss://notifications.d-id.com", je = "79f81a83a67430be2bc0fd61042b8faa", ie = (e) => new Promise((t) => setTimeout(t, e)), K = (e = 16) => {
67
+ const t = new Uint8Array(e);
68
+ return window.crypto.getRandomValues(t), Array.from(t, (a) => a.toString(16).padStart(2, "0")).join("").slice(0, 13);
69
+ }, Pe = (e) => [b.TextOnly, b.Playground, b.Maintenance].includes(e);
70
+ function Ae(e, t) {
71
+ let a;
233
72
  return {
234
- promise,
235
- clear: () => clearTimeout(timeId)
73
+ promise: new Promise((o, s) => {
74
+ a = setTimeout(() => s(new Error(t)), e);
75
+ }),
76
+ clear: () => clearTimeout(a)
236
77
  };
237
78
  }
238
- async function retryOperation(operation, userOptions) {
239
- const options = {
240
- limit: (userOptions == null ? void 0 : userOptions.limit) ?? 3,
241
- delayMs: (userOptions == null ? void 0 : userOptions.delayMs) ?? 0,
242
- timeout: (userOptions == null ? void 0 : userOptions.timeout) ?? 3e4,
243
- timeoutErrorMessage: (userOptions == null ? void 0 : userOptions.timeoutErrorMessage) || "Timeout error",
244
- shouldRetryFn: (userOptions == null ? void 0 : userOptions.shouldRetryFn) ?? (() => true),
245
- onRetry: (userOptions == null ? void 0 : userOptions.onRetry) ?? (() => {
79
+ async function G(e, t) {
80
+ const a = {
81
+ limit: (t == null ? void 0 : t.limit) ?? 3,
82
+ delayMs: (t == null ? void 0 : t.delayMs) ?? 0,
83
+ timeout: (t == null ? void 0 : t.timeout) ?? 3e4,
84
+ timeoutErrorMessage: (t == null ? void 0 : t.timeoutErrorMessage) || "Timeout error",
85
+ shouldRetryFn: (t == null ? void 0 : t.shouldRetryFn) ?? (() => !0),
86
+ onRetry: (t == null ? void 0 : t.onRetry) ?? (() => {
246
87
  })
247
88
  };
248
- let lastError;
249
- for (let attempt = 1; attempt <= options.limit; attempt++) {
89
+ let r;
90
+ for (let o = 1; o <= a.limit; o++)
250
91
  try {
251
- if (!options.timeout) {
252
- return await operation();
253
- }
92
+ if (!a.timeout)
93
+ return await e();
254
94
  const {
255
- promise,
256
- clear
257
- } = createRacePromise(options.timeout, options.timeoutErrorMessage);
258
- const operationPromise = operation().finally(clear);
259
- return await Promise.race([operationPromise, promise]);
260
- } catch (error) {
261
- lastError = error;
262
- if (!options.shouldRetryFn(error) || attempt >= options.limit) {
263
- throw error;
264
- }
265
- await sleep(options.delayMs);
266
- options.onRetry(error);
95
+ promise: s,
96
+ clear: n
97
+ } = Ae(a.timeout, a.timeoutErrorMessage), c = e().finally(n);
98
+ return await Promise.race([c, s]);
99
+ } catch (s) {
100
+ if (r = s, !a.shouldRetryFn(s) || o >= a.limit)
101
+ throw s;
102
+ await ie(a.delayMs), a.onRetry(s);
267
103
  }
268
- }
269
- throw lastError;
104
+ throw r;
270
105
  }
271
- function getExternalId() {
272
- let key = window.localStorage.getItem("did_external_key_id");
273
- if (!key) {
274
- let newKey = getRandom();
275
- window.localStorage.setItem("did_external_key_id", newKey);
276
- key = newKey;
106
+ function se() {
107
+ let e = window.localStorage.getItem("did_external_key_id");
108
+ if (!e) {
109
+ let t = K();
110
+ window.localStorage.setItem("did_external_key_id", t), e = t;
277
111
  }
278
- return key;
112
+ return e;
279
113
  }
280
- let sessionKey = getRandom();
281
- function getAuthHeader(auth) {
282
- if (auth.type === "bearer") {
283
- return `Bearer ${auth.token}`;
284
- } else if (auth.type === "basic") {
285
- return `Basic ${btoa(`${auth.username}:${auth.password}`)}`;
286
- } else if (auth.type === "key") {
287
- return `Client-Key ${auth.clientKey}.${getExternalId()}_${sessionKey}`;
288
- } else {
289
- throw new Error(`Unknown auth type: ${auth}`);
290
- }
114
+ let Be = K();
115
+ function oe(e) {
116
+ if (e.type === "bearer")
117
+ return `Bearer ${e.token}`;
118
+ if (e.type === "basic")
119
+ return `Basic ${btoa(`${e.username}:${e.password}`)}`;
120
+ if (e.type === "key")
121
+ return `Client-Key ${e.clientKey}.${se()}_${Be}`;
122
+ throw new Error(`Unknown auth type: ${e}`);
291
123
  }
292
- const retryHttpTooManyRequests = (operation) => retryOperation(operation, {
124
+ const $e = (e) => G(e, {
293
125
  limit: 3,
294
126
  delayMs: 1e3,
295
127
  timeout: 0,
296
- shouldRetryFn: (error) => error.status === 429
128
+ shouldRetryFn: (t) => t.status === 429
297
129
  });
298
- function createClient(auth, host = didApiUrl, onError) {
299
- const client = async (url, options) => {
130
+ function ee(e, t = Y, a) {
131
+ const r = async (o, s) => {
300
132
  const {
301
- skipErrorHandler,
302
- ...fetchOptions
303
- } = options || {};
304
- const request = await retryHttpTooManyRequests(() => fetch(host + ((url == null ? void 0 : url.startsWith("/")) ? url : `/${url}`), {
305
- ...fetchOptions,
133
+ skipErrorHandler: n,
134
+ ...c
135
+ } = s || {}, i = await $e(() => fetch(t + (o != null && o.startsWith("/") ? o : `/${o}`), {
136
+ ...c,
306
137
  headers: {
307
- ...fetchOptions.headers,
308
- Authorization: getAuthHeader(auth),
138
+ ...c.headers,
139
+ Authorization: oe(e),
309
140
  "Content-Type": "application/json"
310
141
  }
311
142
  }));
312
- if (!request.ok) {
313
- let errorText = await request.text().catch(() => `Failed to fetch with status ${request.status}`);
314
- const error = new Error(errorText);
315
- if (onError && !skipErrorHandler) {
316
- onError(error, {
317
- url,
318
- options: fetchOptions,
319
- headers: request.headers
320
- });
321
- }
322
- throw error;
143
+ if (!i.ok) {
144
+ let d = await i.text().catch(() => `Failed to fetch with status ${i.status}`);
145
+ const u = new Error(d);
146
+ throw a && !n && a(u, {
147
+ url: o,
148
+ options: c,
149
+ headers: i.headers
150
+ }), u;
323
151
  }
324
- return request.json();
152
+ return i.json();
325
153
  };
326
154
  return {
327
- get(url, options) {
328
- return client(url, {
329
- ...options,
155
+ get(o, s) {
156
+ return r(o, {
157
+ ...s,
330
158
  method: "GET"
331
159
  });
332
160
  },
333
- post(url, body, options) {
334
- return client(url, {
335
- ...options,
336
- body: JSON.stringify(body),
161
+ post(o, s, n) {
162
+ return r(o, {
163
+ ...n,
164
+ body: JSON.stringify(s),
337
165
  method: "POST"
338
166
  });
339
167
  },
340
- delete(url, body, options) {
341
- return client(url, {
342
- ...options,
343
- body: JSON.stringify(body),
168
+ delete(o, s, n) {
169
+ return r(o, {
170
+ ...n,
171
+ body: JSON.stringify(s),
344
172
  method: "DELETE"
345
173
  });
346
174
  },
347
- patch(url, body, options) {
348
- return client(url, {
349
- ...options,
350
- body: JSON.stringify(body),
175
+ patch(o, s, n) {
176
+ return r(o, {
177
+ ...n,
178
+ body: JSON.stringify(s),
351
179
  method: "PATCH"
352
180
  });
353
181
  }
354
182
  };
355
183
  }
356
- function createAgentsApi(auth, host = didApiUrl, onError) {
357
- const client = createClient(auth, `${host}/agents`, onError);
184
+ function ce(e, t = Y, a) {
185
+ const r = ee(e, `${t}/agents`, a);
358
186
  return {
359
- create(payload, options) {
360
- return client.post(`/`, payload, options);
187
+ create(o, s) {
188
+ return r.post("/", o, s);
361
189
  },
362
- getAgents(tag, options) {
363
- return client.get(`/${tag ? `?tag=${tag}` : ""}`, options).then((agents) => agents ?? []);
190
+ getAgents(o, s) {
191
+ return r.get(`/${o ? `?tag=${o}` : ""}`, s).then((n) => n ?? []);
364
192
  },
365
- getById(id, options) {
366
- return client.get(`/${id}`, options);
193
+ getById(o, s) {
194
+ return r.get(`/${o}`, s);
367
195
  },
368
- delete(id, options) {
369
- return client.delete(`/${id}`, void 0, options);
196
+ delete(o, s) {
197
+ return r.delete(`/${o}`, void 0, s);
370
198
  },
371
- update(id, payload, options) {
372
- return client.patch(`/${id}`, payload, options);
199
+ update(o, s, n) {
200
+ return r.patch(`/${o}`, s, n);
373
201
  },
374
- newChat(agentId, payload, options) {
375
- return client.post(`/${agentId}/chat`, payload, options);
202
+ newChat(o, s, n) {
203
+ return r.post(`/${o}/chat`, s, n);
376
204
  },
377
- chat(agentId, chatId, payload, options) {
378
- return client.post(`/${agentId}/chat/${chatId}`, payload, options);
205
+ chat(o, s, n, c) {
206
+ return r.post(`/${o}/chat/${s}`, n, c);
379
207
  },
380
- createRating(agentId, chatId, payload, options) {
381
- return client.post(`/${agentId}/chat/${chatId}/ratings`, payload, options);
208
+ createRating(o, s, n, c) {
209
+ return r.post(`/${o}/chat/${s}/ratings`, n, c);
382
210
  },
383
- updateRating(agentId, chatId, ratingId, payload, options) {
384
- return client.patch(`/${agentId}/chat/${chatId}/ratings/${ratingId}`, payload, options);
211
+ updateRating(o, s, n, c, i) {
212
+ return r.patch(`/${o}/chat/${s}/ratings/${n}`, c, i);
385
213
  },
386
- deleteRating(agentId, chatId, ratingId, options) {
387
- return client.delete(`/${agentId}/chat/${chatId}/ratings/${ratingId}`, options);
214
+ deleteRating(o, s, n, c) {
215
+ return r.delete(`/${o}/chat/${s}/ratings/${n}`, c);
388
216
  },
389
- getSTTToken(agentId, options) {
390
- return client.get(`/${agentId}/stt-token`, options);
217
+ getSTTToken(o, s) {
218
+ return r.get(`/${o}/stt-token`, s);
391
219
  }
392
220
  };
393
221
  }
394
- const getAgentType = (presenter) => presenter.type === "clip" && presenter.presenter_id.startsWith("v2_") ? "clip_v2" : presenter.type;
395
- function getAnalyticsInfo(agent) {
396
- var _a, _b, _c, _d;
397
- const mobileOrDesktop = () => {
398
- return /Mobi|Android/i.test(navigator.userAgent) ? "Mobile" : "Desktop";
399
- };
400
- const getUserOS = () => {
401
- const platform = navigator.platform;
402
- if (platform.toLowerCase().includes("win")) {
403
- return "Windows";
404
- } else if (platform.toLowerCase().includes("mac")) {
405
- return "Mac OS X";
406
- } else if (platform.toLowerCase().includes("linux")) {
407
- return "Linux";
408
- } else {
409
- return "Unknown";
410
- }
411
- };
412
- const presenter = agent.presenter;
222
+ const de = (e) => e.type === "clip" && e.presenter_id.startsWith("v2_") ? "clip_v2" : e.type;
223
+ function Le(e) {
224
+ var o, s, n, c;
225
+ const t = () => /Mobi|Android/i.test(navigator.userAgent) ? "Mobile" : "Desktop", a = () => {
226
+ const i = navigator.platform;
227
+ return i.toLowerCase().includes("win") ? "Windows" : i.toLowerCase().includes("mac") ? "Mac OS X" : i.toLowerCase().includes("linux") ? "Linux" : "Unknown";
228
+ }, r = e.presenter;
413
229
  return {
414
- $os: `${getUserOS()}`,
415
- isMobile: `${mobileOrDesktop() == "Mobile"}`,
230
+ $os: `${a()}`,
231
+ isMobile: `${t() == "Mobile"}`,
416
232
  browser: navigator.userAgent,
417
233
  origin: window.location.origin,
418
- agentType: getAgentType(presenter),
234
+ agentType: de(r),
419
235
  agentVoice: {
420
- voiceId: (_b = (_a = agent.presenter) == null ? void 0 : _a.voice) == null ? void 0 : _b.voice_id,
421
- provider: (_d = (_c = agent.presenter) == null ? void 0 : _c.voice) == null ? void 0 : _d.type
236
+ voiceId: (s = (o = e.presenter) == null ? void 0 : o.voice) == null ? void 0 : s.voice_id,
237
+ provider: (c = (n = e.presenter) == null ? void 0 : n.voice) == null ? void 0 : c.type
422
238
  }
423
239
  };
424
240
  }
425
- const sumFunc = (numbers) => numbers.reduce((total, aNumber) => total + aNumber, 0);
426
- const average = (numbers) => sumFunc(numbers) / numbers.length;
427
- function getStreamAnalyticsProps(data, agent, additionalProps) {
428
- var _a, _b, _c;
429
- const {
430
- event,
431
- ...baseProps
432
- } = data;
241
+ const ze = (e) => e.reduce((t, a) => t + a, 0), te = (e) => ze(e) / e.length;
242
+ function xe(e, t, a) {
243
+ var i, d, u;
433
244
  const {
434
- template
435
- } = (agent == null ? void 0 : agent.llm) || {};
436
- const {
437
- language
438
- } = ((_a = agent == null ? void 0 : agent.presenter) == null ? void 0 : _a.voice) || {};
439
- const props = {
440
- ...baseProps,
245
+ event: r,
246
+ ...o
247
+ } = e, {
248
+ template: s
249
+ } = (t == null ? void 0 : t.llm) || {}, {
250
+ language: n
251
+ } = ((i = t == null ? void 0 : t.presenter) == null ? void 0 : i.voice) || {};
252
+ return {
253
+ ...o,
441
254
  llm: {
442
- ...baseProps.llm,
443
- template
255
+ ...o.llm,
256
+ template: s
444
257
  },
445
258
  script: {
446
- ...baseProps.script,
259
+ ...o.script,
447
260
  provider: {
448
- ...(_b = baseProps == null ? void 0 : baseProps.script) == null ? void 0 : _b.provider,
449
- language
261
+ ...(d = o == null ? void 0 : o.script) == null ? void 0 : d.provider,
262
+ language: n
450
263
  }
451
264
  },
452
- stitch: (agent == null ? void 0 : agent.presenter.type) === "talk" ? (_c = agent == null ? void 0 : agent.presenter) == null ? void 0 : _c.stitch : void 0,
453
- ...additionalProps
265
+ stitch: (t == null ? void 0 : t.presenter.type) === "talk" ? (u = t == null ? void 0 : t.presenter) == null ? void 0 : u.stitch : void 0,
266
+ ...a
454
267
  };
455
- return props;
456
268
  }
457
- let mixpanelEvents = {};
458
- const mixpanelUrl = "https://api-js.mixpanel.com/track/?verbose=1&ip=1";
459
- function initializeAnalytics(config) {
460
- var _a, _b, _c, _d, _e, _f;
461
- const source = (window == null ? void 0 : window.hasOwnProperty("DID_AGENTS_API")) ? "agents-ui" : "agents-sdk";
462
- const presenter = config.agent.presenter;
463
- const promptCustomization = (_a = config.agent.llm) == null ? void 0 : _a.prompt_customization;
464
- const analyticProps = {
465
- token: config.token || "testKey",
466
- distinct_id: config.distinctId || getExternalId(),
467
- agentId: config.agent.id,
468
- agentType: getAgentType(presenter),
469
- owner_id: config.agent.owner_id ?? "",
470
- promptVersion: (_b = config.agent.llm) == null ? void 0 : _b.prompt_version,
269
+ let Z = {};
270
+ const Fe = "https://api-js.mixpanel.com/track/?verbose=1&ip=1";
271
+ function Ne(e) {
272
+ var s, n, c, i, d, u;
273
+ const t = window != null && window.hasOwnProperty("DID_AGENTS_API") ? "agents-ui" : "agents-sdk", a = e.agent.presenter, r = (s = e.agent.llm) == null ? void 0 : s.prompt_customization, o = {
274
+ token: e.token || "testKey",
275
+ distinct_id: e.distinctId || se(),
276
+ agentId: e.agent.id,
277
+ agentType: de(a),
278
+ owner_id: e.agent.owner_id ?? "",
279
+ promptVersion: (n = e.agent.llm) == null ? void 0 : n.prompt_version,
471
280
  behavior: {
472
- role: promptCustomization == null ? void 0 : promptCustomization.role,
473
- personality: promptCustomization == null ? void 0 : promptCustomization.personality,
474
- instructions: (_c = config.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: (c = e.agent.llm) == null ? void 0 : c.instructions
475
284
  },
476
- temperature: (_d = config.agent.llm) == null ? void 0 : _d.temperature,
477
- knowledgeSource: promptCustomization == null ? void 0 : promptCustomization.knowledge_source,
478
- starterQuestionsCount: (_f = (_e = config.agent.knowledge) == null ? void 0 : _e.starter_message) == null ? void 0 : _f.length,
479
- topicsToAvoid: promptCustomization == null ? void 0 : promptCustomization.topics_to_avoid,
480
- maxResponseLength: promptCustomization == null ? void 0 : promptCustomization.max_response_length
285
+ temperature: (i = e.agent.llm) == null ? void 0 : i.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
481
290
  };
482
291
  return {
483
- ...analyticProps,
292
+ ...o,
484
293
  additionalProperties: {},
485
- isEnabled: config.isEnabled ?? true,
486
- getRandom,
487
- enrich(properties) {
488
- const props = {};
489
- if (properties && typeof properties !== "object") {
490
- throw new Error("properties must be a flat json object");
491
- }
492
- for (let prop in properties) {
493
- if (typeof properties[prop] === "string" || typeof properties[prop] === "number") {
494
- props[prop] = properties[prop];
495
- }
496
- }
294
+ isEnabled: e.isEnabled ?? !0,
295
+ getRandom: K,
296
+ enrich(h) {
497
297
  this.additionalProperties = {
498
298
  ...this.additionalProperties,
499
- ...props
299
+ ...h
500
300
  };
501
301
  },
502
- async track(event, props) {
503
- if (!this.isEnabled) {
302
+ async track(h, _) {
303
+ if (!this.isEnabled)
504
304
  return Promise.resolve();
505
- }
506
305
  const {
507
- audioPath,
508
- ...sendProps
509
- } = props || {};
510
- const options = {
306
+ audioPath: k,
307
+ ...D
308
+ } = _ || {}, R = {
511
309
  method: "POST",
512
310
  headers: {
513
311
  "Content-Type": "application/x-www-form-urlencoded"
514
312
  },
515
313
  body: new URLSearchParams({
516
314
  data: JSON.stringify([{
517
- event,
315
+ event: h,
518
316
  properties: {
519
317
  ...this.additionalProperties,
520
- ...sendProps,
521
- ...analyticProps,
522
- source,
318
+ ...D,
319
+ ...o,
320
+ source: t,
523
321
  time: Date.now(),
524
322
  $insert_id: this.getRandom(),
525
323
  origin: window.location.href,
@@ -531,1317 +329,1040 @@ function initializeAnalytics(config) {
531
329
  })
532
330
  };
533
331
  try {
534
- return await fetch(mixpanelUrl, options).then((res) => res.json());
535
- } catch (err) {
536
- return console.error(err);
332
+ return await fetch(Fe, R).then((S) => S.json());
333
+ } catch (S) {
334
+ return console.error(S);
537
335
  }
538
336
  },
539
- linkTrack(mixpanelEvent, props, event, dependencies) {
540
- if (!mixpanelEvents[mixpanelEvent]) {
541
- mixpanelEvents[mixpanelEvent] = {
542
- events: {},
543
- resolvedDependencies: []
544
- };
545
- }
546
- if (!dependencies.includes(event)) {
547
- dependencies.push(event);
548
- }
549
- const linkedEvent = mixpanelEvents[mixpanelEvent];
550
- linkedEvent.events[event] = {
551
- props
552
- };
553
- linkedEvent.resolvedDependencies.push(event);
554
- const allDependenciesResolved = dependencies.every((value) => linkedEvent.resolvedDependencies.includes(value));
555
- if (allDependenciesResolved) {
556
- const aggregatedProps = dependencies.reduce((acc, curr) => {
557
- if (linkedEvent.events[curr]) {
558
- return {
559
- ...acc,
560
- ...linkedEvent.events[curr].props
561
- };
562
- }
563
- return acc;
564
- }, {});
565
- this.track(mixpanelEvent, aggregatedProps);
566
- linkedEvent.resolvedDependencies = linkedEvent.resolvedDependencies.filter((event2) => !dependencies.includes(event2));
567
- dependencies.forEach((event2) => {
568
- delete linkedEvent.events[event2];
337
+ linkTrack(h, _, k, D) {
338
+ Z[h] || (Z[h] = {
339
+ events: {},
340
+ resolvedDependencies: []
341
+ }), D.includes(k) || D.push(k);
342
+ const R = Z[h];
343
+ if (R.events[k] = {
344
+ props: _
345
+ }, R.resolvedDependencies.push(k), D.every((B) => R.resolvedDependencies.includes(B))) {
346
+ const B = D.reduce((l, m) => R.events[m] ? {
347
+ ...l,
348
+ ...R.events[m].props
349
+ } : l, {});
350
+ this.track(h, B), R.resolvedDependencies = R.resolvedDependencies.filter((l) => !D.includes(l)), D.forEach((l) => {
351
+ delete R.events[l];
569
352
  });
570
353
  }
571
354
  }
572
355
  };
573
356
  }
574
- function createTimestampTracker() {
575
- let timestamp = 0;
357
+ function Je() {
358
+ let e = 0;
576
359
  return {
577
- reset: () => timestamp = 0,
578
- update: () => timestamp = Date.now(),
579
- get: (delta = false) => delta ? Date.now() - timestamp : timestamp
360
+ reset: () => e = 0,
361
+ update: () => e = Date.now(),
362
+ get: (t = !1) => t ? Date.now() - e : e
580
363
  };
581
364
  }
582
- const timestampTracker = createTimestampTracker();
583
- function getRequestHeaders(chatMode) {
584
- return chatMode === ChatMode.Playground ? {
365
+ const F = Je();
366
+ function le(e) {
367
+ return e === b.Playground ? {
585
368
  headers: {
586
- [PLAYGROUND_HEADER]: "true"
369
+ [be]: "true"
587
370
  }
588
371
  } : {};
589
372
  }
590
- async function createChat(agent, agentsApi, analytics, chatMode, persist = false, chat) {
373
+ async function ue(e, t, a, r, o = !1, s) {
591
374
  try {
592
- if (!chat && chatMode !== ChatMode.DirectPlayback) {
593
- chat = await agentsApi.newChat(agent.id, {
594
- persist
595
- }, getRequestHeaders(chatMode));
596
- analytics.track("agent-chat", {
597
- event: "created",
598
- chat_id: chat.id,
599
- agent_id: agent.id,
600
- mode: chatMode
601
- });
602
- }
603
- return {
604
- chat,
605
- chatMode: (chat == null ? void 0 : chat.chat_mode) ?? chatMode
375
+ return !s && r !== b.DirectPlayback && (s = await t.newChat(e.id, {
376
+ persist: o
377
+ }, le(r)), a.track("agent-chat", {
378
+ event: "created",
379
+ chat_id: s.id,
380
+ agent_id: e.id,
381
+ mode: r
382
+ })), {
383
+ chat: s,
384
+ chatMode: (s == null ? void 0 : s.chat_mode) ?? r
606
385
  };
607
- } catch (error) {
386
+ } catch (n) {
608
387
  try {
609
- const parsedError = JSON.parse(error.message);
610
- if ((parsedError == null ? void 0 : parsedError.kind) === "InsufficientCreditsError") {
388
+ const c = JSON.parse(n.message);
389
+ if ((c == null ? void 0 : c.kind) === "InsufficientCreditsError")
611
390
  throw new Error("InsufficientCreditsError");
612
- }
613
- } catch (e) {
614
- console.error("Error parsing the error message:", e);
391
+ } catch (c) {
392
+ console.error("Error parsing the error message:", c);
615
393
  }
616
394
  throw new Error("Cannot create new chat");
617
395
  }
618
396
  }
619
- function getInitialMessages(initialMessages) {
620
- if (initialMessages && initialMessages.length > 0) {
621
- return initialMessages;
622
- }
623
- return [];
397
+ function We(e) {
398
+ return e && e.length > 0 ? e : [];
624
399
  }
625
- function connect(options) {
626
- return new Promise((resolve, reject) => {
627
- const {
628
- callbacks,
629
- host,
630
- auth
631
- } = options;
400
+ function Ue(e) {
401
+ return new Promise((t, a) => {
632
402
  const {
633
- onMessage = null,
634
- onOpen = null,
635
- onClose = null,
636
- onError = null
637
- } = callbacks || {};
638
- const socket = new WebSocket(`${host}?authorization=${getAuthHeader(auth)}`);
639
- socket.onmessage = onMessage;
640
- socket.onclose = onClose;
641
- socket.onerror = (e) => {
642
- console.error(e);
643
- onError == null ? void 0 : onError("Websocket failed to connect", e);
644
- reject(e);
645
- };
646
- socket.onopen = (e) => {
647
- onOpen == null ? void 0 : onOpen(e);
648
- resolve(socket);
403
+ callbacks: r,
404
+ host: o,
405
+ auth: s
406
+ } = e, {
407
+ onMessage: n = null,
408
+ onOpen: c = null,
409
+ onClose: i = null,
410
+ onError: d = null
411
+ } = r || {}, u = new WebSocket(`${o}?authorization=${oe(s)}`);
412
+ u.onmessage = n, u.onclose = i, u.onerror = (h) => {
413
+ console.error(h), d == null || d("Websocket failed to connect", h), a(h);
414
+ }, u.onopen = (h) => {
415
+ c == null || c(h), t(u);
649
416
  };
650
417
  });
651
418
  }
652
- async function connectWithRetries(options) {
419
+ async function Ke(e) {
653
420
  const {
654
- retries = 1
655
- } = options;
656
- let socket = null;
657
- for (let attempt = 0; (socket == null ? void 0 : socket.readyState) !== WebSocket.OPEN; attempt++) {
421
+ retries: t = 1
422
+ } = e;
423
+ let a = null;
424
+ for (let r = 0; (a == null ? void 0 : a.readyState) !== WebSocket.OPEN; r++)
658
425
  try {
659
- socket = await connect(options);
660
- } catch (e) {
661
- if (attempt === retries) {
662
- throw e;
663
- }
664
- await sleep(attempt * 500);
426
+ a = await Ue(e);
427
+ } catch (o) {
428
+ if (r === t)
429
+ throw o;
430
+ await ie(r * 500);
665
431
  }
666
- }
667
- return socket;
432
+ return a;
668
433
  }
669
- async function createSocketManager(auth, host, callbacks) {
670
- const messageCallbacks = (callbacks == null ? void 0 : callbacks.onMessage) ? [callbacks.onMessage] : [];
671
- const socket = await connectWithRetries({
672
- auth,
673
- host,
434
+ async function He(e, t, a) {
435
+ const r = a != null && a.onMessage ? [a.onMessage] : [], o = await Ke({
436
+ auth: e,
437
+ host: t,
674
438
  callbacks: {
675
- onError: (error) => {
676
- var _a;
677
- return (_a = callbacks.onError) == null ? void 0 : _a.call(callbacks, new WsError(error));
439
+ onError: (s) => {
440
+ var n;
441
+ return (n = a.onError) == null ? void 0 : n.call(a, new pe(s));
678
442
  },
679
- onMessage(event) {
680
- const parsedData = JSON.parse(event.data);
681
- messageCallbacks.forEach((callback) => callback(parsedData.event, parsedData));
443
+ onMessage(s) {
444
+ const n = JSON.parse(s.data);
445
+ r.forEach((c) => c(n.event, n));
682
446
  }
683
447
  }
684
448
  });
685
449
  return {
686
- socket,
687
- disconnect: () => socket.close(),
688
- subscribeToEvents: (callback) => messageCallbacks.push(callback)
450
+ socket: o,
451
+ disconnect: () => o.close(),
452
+ subscribeToEvents: (s) => r.push(s)
689
453
  };
690
454
  }
691
- function getMessageContent(chatEventQueue) {
692
- if (chatEventQueue["answer"] !== void 0) {
693
- return chatEventQueue["answer"];
694
- }
695
- let currentSequence = 0;
696
- let content = "";
697
- while (currentSequence in chatEventQueue) {
698
- content += chatEventQueue[currentSequence++];
699
- }
700
- return content;
455
+ function qe(e) {
456
+ if (e.answer !== void 0)
457
+ return e.answer;
458
+ let t = 0, a = "";
459
+ for (; t in e; )
460
+ a += e[t++];
461
+ return a;
701
462
  }
702
- function processChatEvent(event, data, chatEventQueue, items, onNewMessage) {
703
- const lastMessage = items.messages[items.messages.length - 1];
704
- if (!(event === ChatProgress.Partial || event === ChatProgress.Answer) || (lastMessage == null ? void 0 : lastMessage.role) !== "assistant") {
463
+ function Ve(e, t, a, r, o) {
464
+ const s = r.messages[r.messages.length - 1];
465
+ if (!(e === U.Partial || e === U.Answer) || (s == null ? void 0 : s.role) !== "assistant")
705
466
  return;
706
- }
707
467
  const {
708
- content,
709
- sequence
710
- } = data;
711
- if (event === ChatProgress.Partial) {
712
- chatEventQueue[sequence] = content;
713
- } else {
714
- chatEventQueue["answer"] = content;
715
- }
716
- const messageContent = getMessageContent(chatEventQueue);
717
- if (lastMessage.content !== messageContent || event === ChatProgress.Answer) {
718
- lastMessage.content = messageContent;
719
- onNewMessage == null ? void 0 : onNewMessage([...items.messages], event);
720
- }
468
+ content: n,
469
+ sequence: c
470
+ } = t;
471
+ e === U.Partial ? a[c] = n : a.answer = n;
472
+ const i = qe(a);
473
+ (s.content !== i || e === U.Answer) && (s.content = i, o == null || o([...r.messages], e));
721
474
  }
722
- function createMessageEventQueue(analytics, items, options, agentEntity, onStreamDone) {
723
- let chatEventQueue = {};
475
+ function Xe(e, t, a, r, o) {
476
+ let s = {};
724
477
  return {
725
- clearQueue: () => chatEventQueue = {},
726
- onMessage: (event, data) => {
727
- var _a, _b;
728
- if ("content" in data) {
729
- processChatEvent(event, data, chatEventQueue, items, options.callbacks.onNewMessage);
730
- if (event === ChatProgress.Answer) {
731
- analytics.track("agent-message-received", {
732
- messages: items.messages.length,
733
- mode: items.chatMode
734
- });
735
- }
736
- } else {
737
- const SEvent = StreamEvents;
738
- const completedEvents = [SEvent.StreamVideoDone, SEvent.StreamVideoError, SEvent.StreamVideoRejected];
739
- const failedEvents = [SEvent.StreamFailed, SEvent.StreamVideoError, SEvent.StreamVideoRejected];
740
- const props = getStreamAnalyticsProps(data, agentEntity, {
741
- mode: items.chatMode
478
+ clearQueue: () => s = {},
479
+ onMessage: (n, c) => {
480
+ var i, d;
481
+ if ("content" in c)
482
+ Ve(n, c, s, t, a.callbacks.onNewMessage), n === U.Answer && e.track("agent-message-received", {
483
+ messages: t.messages.length,
484
+ mode: t.chatMode
742
485
  });
743
- event = event;
744
- if (event === SEvent.StreamVideoCreated) {
745
- analytics.linkTrack("agent-video", props, SEvent.StreamVideoCreated, ["start"]);
746
- } else if (completedEvents.includes(event)) {
747
- const streamEvent = event.split("/")[1];
748
- if (failedEvents.includes(event)) {
749
- analytics.track("agent-video", {
750
- ...props,
751
- event: streamEvent
752
- });
753
- } else {
754
- analytics.linkTrack("agent-video", {
755
- ...props,
756
- event: streamEvent
757
- }, event, ["done"]);
758
- }
759
- }
760
- if (failedEvents.includes(event)) {
761
- (_b = (_a = options.callbacks).onError) == null ? void 0 : _b.call(_a, new Error(`Stream failed with event ${event}`), {
762
- data
763
- });
764
- }
765
- if (data.event === SEvent.StreamDone) {
766
- onStreamDone();
486
+ else {
487
+ const u = N, h = [u.StreamVideoDone, u.StreamVideoError, u.StreamVideoRejected], _ = [u.StreamFailed, u.StreamVideoError, u.StreamVideoRejected], k = xe(c, r, {
488
+ mode: t.chatMode
489
+ });
490
+ if (n = n, n === u.StreamVideoCreated)
491
+ e.linkTrack("agent-video", k, u.StreamVideoCreated, ["start"]);
492
+ else if (h.includes(n)) {
493
+ const D = n.split("/")[1];
494
+ _.includes(n) ? e.track("agent-video", {
495
+ ...k,
496
+ event: D
497
+ }) : e.linkTrack("agent-video", {
498
+ ...k,
499
+ event: D
500
+ }, n, ["done"]);
767
501
  }
502
+ _.includes(n) && ((d = (i = a.callbacks).onError) == null || d.call(i, new Error(`Stream failed with event ${n}`), {
503
+ data: c
504
+ })), c.event === u.StreamDone && o();
768
505
  }
769
506
  }
770
507
  };
771
508
  }
772
- function createClipApi(auth, host, agentId, onError) {
773
- const client = createClient(auth, `${host}/agents/${agentId}`, onError);
509
+ function Ye(e, t, a, r) {
510
+ const o = ee(e, `${t}/agents/${a}`, r);
774
511
  return {
775
- createStream(options) {
776
- return client.post("/streams", {
777
- output_resolution: options.output_resolution,
778
- compatibility_mode: options.compatibility_mode,
779
- stream_warmup: options.stream_warmup,
780
- session_timeout: options.session_timeout,
781
- fluent: options.fluent
512
+ createStream(s) {
513
+ return o.post("/streams", {
514
+ output_resolution: s.output_resolution,
515
+ compatibility_mode: s.compatibility_mode,
516
+ stream_warmup: s.stream_warmup,
517
+ session_timeout: s.session_timeout,
518
+ fluent: s.fluent
782
519
  });
783
520
  },
784
- startConnection(streamId, answer, sessionId) {
785
- return client.post(`/streams/${streamId}/sdp`, {
786
- session_id: sessionId,
787
- answer
521
+ startConnection(s, n, c) {
522
+ return o.post(`/streams/${s}/sdp`, {
523
+ session_id: c,
524
+ answer: n
788
525
  });
789
526
  },
790
- addIceCandidate(streamId, candidate, sessionId) {
791
- return client.post(`/streams/${streamId}/ice`, {
792
- session_id: sessionId,
793
- ...candidate
527
+ addIceCandidate(s, n, c) {
528
+ return o.post(`/streams/${s}/ice`, {
529
+ session_id: c,
530
+ ...n
794
531
  });
795
532
  },
796
- sendStreamRequest(streamId, sessionId, payload) {
797
- return client.post(`/streams/${streamId}`, {
798
- session_id: sessionId,
799
- ...payload
533
+ sendStreamRequest(s, n, c) {
534
+ return o.post(`/streams/${s}`, {
535
+ session_id: n,
536
+ ...c
800
537
  });
801
538
  },
802
- close(streamId, sessionId) {
803
- return client.delete(`/streams/${streamId}`, {
804
- session_id: sessionId
539
+ close(s, n) {
540
+ return o.delete(`/streams/${s}`, {
541
+ session_id: n
805
542
  });
806
543
  }
807
544
  };
808
545
  }
809
- function createTalkApi(auth, host, agentId, onError) {
810
- const client = createClient(auth, `${host}/agents/${agentId}`, onError);
546
+ function Qe(e, t, a, r) {
547
+ const o = ee(e, `${t}/agents/${a}`, r);
811
548
  return {
812
- createStream(streamOptions, options) {
813
- return client.post("/streams", {
814
- driver_url: streamOptions.driver_url,
815
- face: streamOptions.face,
816
- config: streamOptions.config,
817
- output_resolution: streamOptions.output_resolution,
818
- compatibility_mode: streamOptions.compatibility_mode,
819
- stream_warmup: streamOptions.stream_warmup,
820
- session_timeout: streamOptions.session_timeout,
821
- fluent: streamOptions.fluent
822
- }, options);
549
+ createStream(s, n) {
550
+ return o.post("/streams", {
551
+ driver_url: s.driver_url,
552
+ face: s.face,
553
+ config: s.config,
554
+ output_resolution: s.output_resolution,
555
+ compatibility_mode: s.compatibility_mode,
556
+ stream_warmup: s.stream_warmup,
557
+ session_timeout: s.session_timeout,
558
+ fluent: s.fluent
559
+ }, n);
823
560
  },
824
- startConnection(streamId, answer, sessionId, options) {
825
- return client.post(`/streams/${streamId}/sdp`, {
826
- session_id: sessionId,
827
- answer
828
- }, options);
561
+ startConnection(s, n, c, i) {
562
+ return o.post(`/streams/${s}/sdp`, {
563
+ session_id: c,
564
+ answer: n
565
+ }, i);
829
566
  },
830
- addIceCandidate(streamId, candidate, sessionId, options) {
831
- return client.post(`/streams/${streamId}/ice`, {
832
- session_id: sessionId,
833
- ...candidate
834
- }, options);
567
+ addIceCandidate(s, n, c, i) {
568
+ return o.post(`/streams/${s}/ice`, {
569
+ session_id: c,
570
+ ...n
571
+ }, i);
835
572
  },
836
- sendStreamRequest(streamId, sessionId, payload, options) {
837
- return client.post(`/streams/${streamId}`, {
838
- session_id: sessionId,
839
- ...payload
840
- }, options);
573
+ sendStreamRequest(s, n, c, i) {
574
+ return o.post(`/streams/${s}`, {
575
+ session_id: n,
576
+ ...c
577
+ }, i);
841
578
  },
842
- close(streamId, sessionId, options) {
843
- return client.delete(`/streams/${streamId}`, {
844
- session_id: sessionId
845
- }, options);
579
+ close(s, n, c) {
580
+ return o.delete(`/streams/${s}`, {
581
+ session_id: n
582
+ }, c);
846
583
  }
847
584
  };
848
585
  }
849
- function createAggregateReport(start, end, lowFpsCount) {
850
- const duration = (end.timestamp - start.timestamp) / 1e3;
586
+ function Ze(e, t, a) {
587
+ const r = (t.timestamp - e.timestamp) / 1e3;
851
588
  return {
852
- duration,
853
- bytesReceived: end.bytesReceived - start.bytesReceived,
854
- bitrate: Math.round((end.bytesReceived - start.bytesReceived) * 8 / duration),
855
- packetsReceived: end.packetsReceived - start.packetsReceived,
856
- packetsLost: end.packetsLost - start.packetsLost,
857
- framesDropped: end.framesDropped - start.framesDropped,
858
- framesDecoded: end.framesDecoded - start.framesDecoded,
859
- jitter: end.jitter,
860
- avgJitterDelayInInterval: (end.jitterBufferDelay - start.jitterBufferDelay) / (end.jitterBufferEmittedCount - start.jitterBufferEmittedCount),
861
- jitterBufferEmittedCount: end.jitterBufferEmittedCount - start.jitterBufferEmittedCount,
862
- jitterBufferDelay: (end.jitterBufferDelay - start.jitterBufferDelay) / duration,
863
- framesPerSecond: end.framesPerSecond,
864
- freezeCount: end.freezeCount - start.freezeCount,
865
- freezeDuration: end.freezeDuration - start.freezeDuration,
866
- lowFpsCount
589
+ duration: r,
590
+ bytesReceived: t.bytesReceived - e.bytesReceived,
591
+ bitrate: Math.round((t.bytesReceived - e.bytesReceived) * 8 / r),
592
+ packetsReceived: t.packetsReceived - e.packetsReceived,
593
+ packetsLost: t.packetsLost - e.packetsLost,
594
+ framesDropped: t.framesDropped - e.framesDropped,
595
+ framesDecoded: t.framesDecoded - e.framesDecoded,
596
+ jitter: t.jitter,
597
+ avgJitterDelayInInterval: (t.jitterBufferDelay - e.jitterBufferDelay) / (t.jitterBufferEmittedCount - e.jitterBufferEmittedCount),
598
+ jitterBufferEmittedCount: t.jitterBufferEmittedCount - e.jitterBufferEmittedCount,
599
+ jitterBufferDelay: (t.jitterBufferDelay - e.jitterBufferDelay) / r,
600
+ framesPerSecond: t.framesPerSecond,
601
+ freezeCount: t.freezeCount - e.freezeCount,
602
+ freezeDuration: t.freezeDuration - e.freezeDuration,
603
+ lowFpsCount: a
867
604
  };
868
605
  }
869
- function extractAnomalies(stats) {
870
- return stats.filter((report) => report.freezeCount > 0 || report.framesPerSecond < 21 || report.framesDropped > 0 || report.packetsLost > 0).map((report) => {
606
+ function Ge(e) {
607
+ return e.filter((t) => t.freezeCount > 0 || t.framesPerSecond < 21 || t.framesDropped > 0 || t.packetsLost > 0).map((t) => {
871
608
  const {
872
- timestamp,
873
- ...updatedReport
874
- } = report;
875
- const causes = [];
876
- if (report.freezeCount > 0) {
877
- causes.push("freeze");
878
- }
879
- if (report.framesPerSecond < 21) {
880
- causes.push("low fps");
881
- }
882
- if (report.framesDropped > 0) {
883
- causes.push("frames dropped");
884
- }
885
- if (report.packetsLost > 0) {
886
- causes.push("packet loss");
887
- }
888
- return {
889
- ...updatedReport,
890
- causes
609
+ timestamp: a,
610
+ ...r
611
+ } = t, o = [];
612
+ 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"), {
613
+ ...r,
614
+ causes: o
891
615
  };
892
616
  });
893
617
  }
894
- function formatStats(stats) {
895
- let codec = "";
896
- let currRtt = 0;
897
- for (const report of stats.values()) {
898
- if (report && report.type === "codec" && report.mimeType.startsWith("video")) {
899
- codec = report.mimeType.split("/")[1];
900
- }
901
- if (report && report.type === "candidate-pair") {
902
- currRtt = report.currentRoundTripTime;
903
- }
904
- if (report && report.type === "inbound-rtp" && report.kind === "video") {
618
+ function Oe(e) {
619
+ let t = "", a = 0;
620
+ for (const r of e.values())
621
+ 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")
905
622
  return {
906
- codec,
907
- rtt: currRtt,
908
- timestamp: report.timestamp,
909
- bytesReceived: report.bytesReceived,
910
- packetsReceived: report.packetsReceived,
911
- packetsLost: report.packetsLost,
912
- framesDropped: report.framesDropped,
913
- framesDecoded: report.framesDecoded,
914
- jitter: report.jitter,
915
- jitterBufferDelay: report.jitterBufferDelay,
916
- jitterBufferEmittedCount: report.jitterBufferEmittedCount,
917
- avgJitterDelayInInterval: report.jitterBufferDelay / report.jitterBufferEmittedCount,
918
- frameWidth: report.frameWidth,
919
- frameHeight: report.frameHeight,
920
- framesPerSecond: report.framesPerSecond,
921
- freezeCount: report.freezeCount,
922
- freezeDuration: report.totalFreezesDuration
623
+ codec: t,
624
+ rtt: a,
625
+ timestamp: r.timestamp,
626
+ bytesReceived: r.bytesReceived,
627
+ packetsReceived: r.packetsReceived,
628
+ packetsLost: r.packetsLost,
629
+ framesDropped: r.framesDropped,
630
+ framesDecoded: r.framesDecoded,
631
+ jitter: r.jitter,
632
+ jitterBufferDelay: r.jitterBufferDelay,
633
+ jitterBufferEmittedCount: r.jitterBufferEmittedCount,
634
+ avgJitterDelayInInterval: r.jitterBufferDelay / r.jitterBufferEmittedCount,
635
+ frameWidth: r.frameWidth,
636
+ frameHeight: r.frameHeight,
637
+ framesPerSecond: r.framesPerSecond,
638
+ freezeCount: r.freezeCount,
639
+ freezeDuration: r.totalFreezesDuration
923
640
  };
924
- }
925
- }
926
641
  return {};
927
642
  }
928
- function createVideoStatsReport(stats, interval2, previousStats) {
929
- const differentialReport = stats.map((report, index) => {
930
- if (index === 0) {
931
- if (!previousStats) {
932
- return {
933
- timestamp: report.timestamp,
934
- rtt: report.rtt,
935
- duration: 0,
936
- bytesReceived: report.bytesReceived,
937
- bitrate: report.bytesReceived * 8 / (interval2 / 1e3),
938
- packetsReceived: report.packetsReceived,
939
- packetsLost: report.packetsLost,
940
- framesDropped: report.framesDropped,
941
- framesDecoded: report.framesDecoded,
942
- jitter: report.jitter,
943
- jitterBufferDelay: report.jitterBufferDelay,
944
- jitterBufferEmittedCount: report.jitterBufferEmittedCount,
945
- avgJitterDelayInInterval: report.jitterBufferDelay / report.jitterBufferEmittedCount,
946
- framesPerSecond: report.framesPerSecond,
947
- freezeCount: report.freezeCount,
948
- freezeDuration: report.freezeDuration
949
- };
950
- }
951
- return {
952
- timestamp: report.timestamp,
953
- duration: 0,
954
- rtt: report.rtt,
955
- bytesReceived: report.bytesReceived - previousStats.bytesReceived,
956
- bitrate: (report.bytesReceived - previousStats.bytesReceived) * 8 / (interval2 / 1e3),
957
- packetsReceived: report.packetsReceived - previousStats.packetsReceived,
958
- packetsLost: report.packetsLost - previousStats.packetsLost,
959
- framesDropped: report.framesDropped - previousStats.framesDropped,
960
- framesDecoded: report.framesDecoded - previousStats.framesDecoded,
961
- jitter: report.jitter,
962
- jitterBufferDelay: report.jitterBufferDelay - previousStats.jitterBufferDelay,
963
- jitterBufferEmittedCount: report.jitterBufferEmittedCount - previousStats.jitterBufferEmittedCount,
964
- avgJitterDelayInInterval: (report.jitterBufferDelay - previousStats.jitterBufferDelay) / (report.jitterBufferEmittedCount - previousStats.jitterBufferEmittedCount),
965
- framesPerSecond: report.framesPerSecond,
966
- freezeCount: report.freezeCount - previousStats.freezeCount,
967
- freezeDuration: report.freezeDuration - previousStats.freezeDuration
968
- };
969
- }
970
- return {
971
- timestamp: report.timestamp,
972
- duration: interval2 * index / 1e3,
973
- rtt: report.rtt,
974
- bytesReceived: report.bytesReceived - stats[index - 1].bytesReceived,
975
- bitrate: (report.bytesReceived - stats[index - 1].bytesReceived) * 8 / (interval2 / 1e3),
976
- packetsReceived: report.packetsReceived - stats[index - 1].packetsReceived,
977
- packetsLost: report.packetsLost - stats[index - 1].packetsLost,
978
- framesDropped: report.framesDropped - stats[index - 1].framesDropped,
979
- framesDecoded: report.framesDecoded - stats[index - 1].framesDecoded,
980
- jitter: report.jitter,
981
- jitterBufferDelay: report.jitterBufferDelay - stats[index - 1].jitterBufferDelay,
982
- jitterBufferEmittedCount: report.jitterBufferEmittedCount - stats[index - 1].jitterBufferEmittedCount,
983
- avgJitterDelayInInterval: (report.jitterBufferDelay - stats[index - 1].jitterBufferDelay) / (report.jitterBufferEmittedCount - stats[index - 1].jitterBufferEmittedCount),
984
- framesPerSecond: report.framesPerSecond,
985
- freezeCount: report.freezeCount - stats[index - 1].freezeCount,
986
- freezeDuration: report.freezeDuration - stats[index - 1].freezeDuration
987
- };
988
- });
989
- const anomalies = extractAnomalies(differentialReport);
990
- const lowFpsCount = anomalies.reduce((acc, report) => acc + (report.causes.includes("low fps") ? 1 : 0), 0);
991
- const avgJittersSamples = differentialReport.filter((stat) => !!stat.avgJitterDelayInInterval).map((stat) => stat.avgJitterDelayInInterval);
992
- const avgRttSamples = differentialReport.filter((stat) => !!stat.rtt).map((stat) => stat.rtt);
643
+ function et(e, t, a) {
644
+ const r = e.map((i, d) => d === 0 ? a ? {
645
+ timestamp: i.timestamp,
646
+ duration: 0,
647
+ rtt: i.rtt,
648
+ bytesReceived: i.bytesReceived - a.bytesReceived,
649
+ bitrate: (i.bytesReceived - a.bytesReceived) * 8 / (t / 1e3),
650
+ packetsReceived: i.packetsReceived - a.packetsReceived,
651
+ packetsLost: i.packetsLost - a.packetsLost,
652
+ framesDropped: i.framesDropped - a.framesDropped,
653
+ framesDecoded: i.framesDecoded - a.framesDecoded,
654
+ jitter: i.jitter,
655
+ jitterBufferDelay: i.jitterBufferDelay - a.jitterBufferDelay,
656
+ jitterBufferEmittedCount: i.jitterBufferEmittedCount - a.jitterBufferEmittedCount,
657
+ avgJitterDelayInInterval: (i.jitterBufferDelay - a.jitterBufferDelay) / (i.jitterBufferEmittedCount - a.jitterBufferEmittedCount),
658
+ framesPerSecond: i.framesPerSecond,
659
+ freezeCount: i.freezeCount - a.freezeCount,
660
+ freezeDuration: i.freezeDuration - a.freezeDuration
661
+ } : {
662
+ timestamp: i.timestamp,
663
+ rtt: i.rtt,
664
+ duration: 0,
665
+ bytesReceived: i.bytesReceived,
666
+ bitrate: i.bytesReceived * 8 / (t / 1e3),
667
+ packetsReceived: i.packetsReceived,
668
+ packetsLost: i.packetsLost,
669
+ framesDropped: i.framesDropped,
670
+ framesDecoded: i.framesDecoded,
671
+ jitter: i.jitter,
672
+ jitterBufferDelay: i.jitterBufferDelay,
673
+ jitterBufferEmittedCount: i.jitterBufferEmittedCount,
674
+ avgJitterDelayInInterval: i.jitterBufferDelay / i.jitterBufferEmittedCount,
675
+ framesPerSecond: i.framesPerSecond,
676
+ freezeCount: i.freezeCount,
677
+ freezeDuration: i.freezeDuration
678
+ } : {
679
+ timestamp: i.timestamp,
680
+ duration: t * d / 1e3,
681
+ rtt: i.rtt,
682
+ bytesReceived: i.bytesReceived - e[d - 1].bytesReceived,
683
+ bitrate: (i.bytesReceived - e[d - 1].bytesReceived) * 8 / (t / 1e3),
684
+ packetsReceived: i.packetsReceived - e[d - 1].packetsReceived,
685
+ packetsLost: i.packetsLost - e[d - 1].packetsLost,
686
+ framesDropped: i.framesDropped - e[d - 1].framesDropped,
687
+ framesDecoded: i.framesDecoded - e[d - 1].framesDecoded,
688
+ jitter: i.jitter,
689
+ jitterBufferDelay: i.jitterBufferDelay - e[d - 1].jitterBufferDelay,
690
+ jitterBufferEmittedCount: i.jitterBufferEmittedCount - e[d - 1].jitterBufferEmittedCount,
691
+ avgJitterDelayInInterval: (i.jitterBufferDelay - e[d - 1].jitterBufferDelay) / (i.jitterBufferEmittedCount - e[d - 1].jitterBufferEmittedCount),
692
+ framesPerSecond: i.framesPerSecond,
693
+ freezeCount: i.freezeCount - e[d - 1].freezeCount,
694
+ freezeDuration: i.freezeDuration - e[d - 1].freezeDuration
695
+ }), o = Ge(r), s = o.reduce((i, d) => i + (d.causes.includes("low fps") ? 1 : 0), 0), n = r.filter((i) => !!i.avgJitterDelayInInterval).map((i) => i.avgJitterDelayInInterval), c = r.filter((i) => !!i.rtt).map((i) => i.rtt);
993
696
  return {
994
697
  webRTCStats: {
995
- anomalies,
996
- minRtt: Math.min(...avgRttSamples),
997
- avgRtt: average(avgRttSamples),
998
- maxRtt: Math.max(...avgRttSamples),
999
- aggregateReport: createAggregateReport(stats[0], stats[stats.length - 1], lowFpsCount),
1000
- minJitterDelayInInterval: Math.min(...avgJittersSamples),
1001
- maxJitterDelayInInterval: Math.max(...avgJittersSamples),
1002
- avgJitterDelayInInterval: average(avgJittersSamples)
698
+ anomalies: o,
699
+ minRtt: Math.min(...c),
700
+ avgRtt: te(c),
701
+ maxRtt: Math.max(...c),
702
+ aggregateReport: Ze(e[0], e[e.length - 1], s),
703
+ minJitterDelayInInterval: Math.min(...n),
704
+ maxJitterDelayInInterval: Math.max(...n),
705
+ avgJitterDelayInInterval: te(n)
1003
706
  },
1004
- codec: stats[0].codec,
1005
- resolution: `${stats[0].frameWidth}x${stats[0].frameHeight}`
707
+ codec: e[0].codec,
708
+ resolution: `${e[0].frameWidth}x${e[0].frameHeight}`
1006
709
  };
1007
710
  }
1008
- const interval = 100;
1009
- const notReceivingIntervalsThreshold = Math.max(Math.ceil(400 / interval), 1);
1010
- const LOW_JITTER_TRESHOLD = 0.25;
1011
- const HIGH_JITTER_TRESHOLD = 0.28;
1012
- function createVideoStatsAnalyzer() {
1013
- let lastFramesReceived = 0;
1014
- let prevDelay;
1015
- let prevCount;
1016
- let avgJitterDelayInInterval = 0;
1017
- return (stats) => {
1018
- for (const report of stats.values()) {
1019
- if (report && report.type === "inbound-rtp" && report.kind === "video") {
1020
- const delay = report.jitterBufferDelay;
1021
- const count = report.jitterBufferEmittedCount;
1022
- if (prevCount && count > prevCount) {
1023
- const deltaDelay = delay - prevDelay;
1024
- const deltaCount = count - prevCount;
1025
- avgJitterDelayInInterval = deltaDelay / deltaCount;
711
+ const O = 100, tt = Math.max(Math.ceil(400 / O), 1), rt = 0.25, nt = 0.28;
712
+ function at() {
713
+ let e = 0, t, a, r = 0;
714
+ return (o) => {
715
+ for (const s of o.values())
716
+ if (s && s.type === "inbound-rtp" && s.kind === "video") {
717
+ const n = s.jitterBufferDelay, c = s.jitterBufferEmittedCount;
718
+ if (a && c > a) {
719
+ const u = n - t, h = c - a;
720
+ r = u / h;
1026
721
  }
1027
- prevDelay = delay;
1028
- prevCount = count;
1029
- const currFramesReceived = report.framesDecoded;
1030
- const isReceiving = currFramesReceived - lastFramesReceived > 0;
1031
- lastFramesReceived = currFramesReceived;
1032
- return {
1033
- isReceiving,
1034
- avgJitterDelayInInterval,
1035
- freezeCount: report.freezeCount
722
+ t = n, a = c;
723
+ const i = s.framesDecoded, d = i - e > 0;
724
+ return e = i, {
725
+ isReceiving: d,
726
+ avgJitterDelayInInterval: r,
727
+ freezeCount: s.freezeCount
1036
728
  };
1037
729
  }
1038
- }
1039
730
  return {
1040
- isReceiving: false,
1041
- avgJitterDelayInInterval
731
+ isReceiving: !1,
732
+ avgJitterDelayInInterval: r
1042
733
  };
1043
734
  };
1044
735
  }
1045
- function pollStats(peerConnection, getIsConnected, onConnected, onVideoStateChange, onConnectivityStateChange, warmup = false) {
1046
- let allStats = [];
1047
- let previousStats;
1048
- let notReceivingNumIntervals = 0;
1049
- let isStreaming = false;
1050
- let prevLowConnState = ConnectivityState.Unknown;
1051
- let currLowConnState = ConnectivityState.Unknown;
1052
- let currFreezeCount = 0;
1053
- let prevFreezeCount = 0;
1054
- const isReceivingVideoBytes = createVideoStatsAnalyzer();
736
+ function it(e, t, a, r, o, s = !1) {
737
+ let n = [], c, i = 0, d = !1, u = V.Unknown, h = V.Unknown, _ = 0, k = 0;
738
+ const D = at();
1055
739
  return setInterval(async () => {
1056
- const stats = await peerConnection.getStats();
1057
- const {
1058
- isReceiving,
1059
- avgJitterDelayInInterval,
1060
- freezeCount
1061
- } = isReceivingVideoBytes(stats);
1062
- const slimStats = formatStats(stats);
1063
- if (isReceiving) {
1064
- notReceivingNumIntervals = 0;
1065
- currFreezeCount = freezeCount - prevFreezeCount;
1066
- currLowConnState = avgJitterDelayInInterval < LOW_JITTER_TRESHOLD ? ConnectivityState.Strong : avgJitterDelayInInterval > HIGH_JITTER_TRESHOLD && currFreezeCount > 1 ? ConnectivityState.Weak : prevLowConnState;
1067
- if (currLowConnState !== prevLowConnState) {
1068
- onConnectivityStateChange == null ? void 0 : onConnectivityStateChange(currLowConnState);
1069
- prevLowConnState = currLowConnState;
1070
- prevFreezeCount += currFreezeCount;
1071
- currFreezeCount = 0;
1072
- }
1073
- if (!isStreaming) {
1074
- onVideoStateChange == null ? void 0 : onVideoStateChange(StreamingState.Start);
1075
- previousStats = allStats[allStats.length - 1];
1076
- allStats = [];
1077
- isStreaming = true;
1078
- }
1079
- allStats.push(slimStats);
1080
- } else if (isStreaming) {
1081
- notReceivingNumIntervals++;
1082
- if (notReceivingNumIntervals >= notReceivingIntervalsThreshold) {
1083
- const statsReport = createVideoStatsReport(allStats, interval, previousStats);
1084
- onVideoStateChange == null ? void 0 : onVideoStateChange(StreamingState.Stop, statsReport);
1085
- if (!getIsConnected()) {
1086
- onConnected();
1087
- }
1088
- prevFreezeCount = freezeCount;
1089
- isStreaming = false;
1090
- }
740
+ const R = await e.getStats(), {
741
+ isReceiving: S,
742
+ avgJitterDelayInInterval: B,
743
+ freezeCount: l
744
+ } = D(R), m = Oe(R);
745
+ if (S)
746
+ i = 0, _ = l - k, h = B < rt ? V.Strong : B > nt && _ > 1 ? V.Weak : u, h !== u && (o == null || o(h), u = h, k += _, _ = 0), d || (r == null || r(p.Start), c = n[n.length - 1], n = [], d = !0), n.push(m);
747
+ else if (d && (i++, i >= tt)) {
748
+ const y = et(n, O, c);
749
+ r == null || r(p.Stop, y), t() || a(), k = l, d = !1;
1091
750
  }
1092
- }, interval);
751
+ }, O);
1093
752
  }
1094
- let _debug = false;
1095
- const log = (message, extra) => _debug && console.log(message, extra);
1096
- const actualRTCPC = (window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection).bind(window);
1097
- function mapConnectionState(state) {
1098
- switch (state) {
753
+ let fe = !1;
754
+ const x = (e, t) => fe && console.log(e, t), st = (window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection).bind(window);
755
+ function re(e) {
756
+ switch (e) {
1099
757
  case "connected":
1100
- return ConnectionState.Connected;
758
+ return M.Connected;
1101
759
  case "checking":
1102
- return ConnectionState.Connecting;
760
+ return M.Connecting;
1103
761
  case "failed":
1104
- return ConnectionState.Fail;
762
+ return M.Fail;
1105
763
  case "new":
1106
- return ConnectionState.New;
764
+ return M.New;
1107
765
  case "closed":
1108
- return ConnectionState.Closed;
766
+ return M.Closed;
1109
767
  case "disconnected":
1110
- return ConnectionState.Disconnected;
768
+ return M.Disconnected;
1111
769
  case "completed":
1112
- return ConnectionState.Completed;
770
+ return M.Completed;
1113
771
  default:
1114
- return ConnectionState.New;
772
+ return M.New;
1115
773
  }
1116
774
  }
1117
- function handleLegacyStreamState({
1118
- statsSignal,
1119
- dataChannelSignal,
1120
- onVideoStateChange,
1121
- report
1122
- }) {
1123
- if (statsSignal === StreamingState.Start && dataChannelSignal === StreamingState.Start) {
1124
- onVideoStateChange == null ? void 0 : onVideoStateChange(StreamingState.Start);
1125
- } else if (statsSignal === StreamingState.Stop && dataChannelSignal === StreamingState.Stop) {
1126
- onVideoStateChange == null ? void 0 : onVideoStateChange(StreamingState.Stop, report);
775
+ function ot(e) {
776
+ const [t, a = ""] = e.split(/:(.+)/);
777
+ try {
778
+ const r = JSON.parse(a);
779
+ return x("parsed data channel message", {
780
+ subject: t,
781
+ data: r
782
+ }), {
783
+ subject: t,
784
+ data: r
785
+ };
786
+ } catch (r) {
787
+ return x("Failed to parse data channel message, returning data as string", {
788
+ subject: t,
789
+ rawData: a,
790
+ error: r
791
+ }), {
792
+ subject: t,
793
+ data: a
794
+ };
1127
795
  }
1128
796
  }
1129
- function handleFluentStreamState({
1130
- statsSignal,
1131
- dataChannelSignal,
1132
- onVideoStateChange,
1133
- onAgentActivityStateChange,
1134
- report
797
+ function ct({
798
+ statsSignal: e,
799
+ dataChannelSignal: t,
800
+ onVideoStateChange: a,
801
+ report: r
1135
802
  }) {
1136
- if (statsSignal === StreamingState.Start) {
1137
- onVideoStateChange == null ? void 0 : onVideoStateChange(StreamingState.Start);
1138
- } else if (statsSignal === StreamingState.Stop) {
1139
- onVideoStateChange == null ? void 0 : onVideoStateChange(StreamingState.Stop, report);
1140
- }
1141
- if (dataChannelSignal === StreamingState.Start) {
1142
- onAgentActivityStateChange == null ? void 0 : onAgentActivityStateChange(AgentActivityState.Talking);
1143
- } else if (dataChannelSignal === StreamingState.Stop) {
1144
- onAgentActivityStateChange == null ? void 0 : onAgentActivityStateChange(AgentActivityState.Idle);
1145
- }
803
+ e === p.Start && t === p.Start ? a == null || a(p.Start) : e === p.Stop && t === p.Stop && (a == null || a(p.Stop, r));
1146
804
  }
1147
- function handleStreamState({
1148
- statsSignal,
1149
- dataChannelSignal,
1150
- onVideoStateChange,
1151
- onAgentActivityStateChange,
1152
- streamType,
1153
- report
805
+ function dt({
806
+ statsSignal: e,
807
+ dataChannelSignal: t,
808
+ onVideoStateChange: a,
809
+ onAgentActivityStateChange: r,
810
+ report: o
1154
811
  }) {
1155
- if (streamType === StreamType.Legacy) {
1156
- handleLegacyStreamState({
1157
- statsSignal,
1158
- dataChannelSignal,
1159
- onVideoStateChange,
1160
- report
1161
- });
1162
- } else if (streamType === StreamType.Fluent) {
1163
- handleFluentStreamState({
1164
- statsSignal,
1165
- dataChannelSignal,
1166
- onVideoStateChange,
1167
- onAgentActivityStateChange,
1168
- report
1169
- });
1170
- }
812
+ e === p.Start ? a == null || a(p.Start) : e === p.Stop && (a == null || a(p.Stop, o)), t === p.Start ? r == null || r(X.Talking) : t === p.Stop && (r == null || r(X.Idle));
1171
813
  }
1172
- async function createStreamingManager(agentId, agent, {
1173
- debug = false,
1174
- callbacks,
1175
- auth,
1176
- baseURL = didApiUrl,
1177
- analytics
814
+ function ne({
815
+ statsSignal: e,
816
+ dataChannelSignal: t,
817
+ onVideoStateChange: a,
818
+ onAgentActivityStateChange: r,
819
+ streamType: o,
820
+ report: s
1178
821
  }) {
1179
- _debug = debug;
1180
- let isConnected = false;
1181
- let isDatachannelOpen = false;
1182
- let dataChannelSignal = StreamingState.Stop;
1183
- let statsSignal = StreamingState.Stop;
1184
- const {
1185
- startConnection,
1186
- sendStreamRequest,
1187
- close,
1188
- createStream,
1189
- addIceCandidate
1190
- } = agent.videoType === VideoType.Clip ? createClipApi(auth, baseURL, agentId, callbacks.onError) : createTalkApi(auth, baseURL, agentId, callbacks.onError);
1191
- const {
1192
- id: streamIdFromServer,
1193
- offer,
1194
- ice_servers,
1195
- session_id,
1196
- fluent
1197
- } = await createStream(agent);
1198
- const peerConnection = new actualRTCPC({
1199
- iceServers: ice_servers
822
+ o === J.Legacy ? ct({
823
+ statsSignal: e,
824
+ dataChannelSignal: t,
825
+ onVideoStateChange: a,
826
+ report: s
827
+ }) : o === J.Fluent && dt({
828
+ statsSignal: e,
829
+ dataChannelSignal: t,
830
+ onVideoStateChange: a,
831
+ onAgentActivityStateChange: r,
832
+ report: s
1200
833
  });
1201
- const pcDataChannel = peerConnection.createDataChannel("JanusDataChannel");
1202
- if (!session_id) {
834
+ }
835
+ async function lt(e, t, {
836
+ debug: a = !1,
837
+ callbacks: r,
838
+ auth: o,
839
+ baseURL: s = Y,
840
+ analytics: n
841
+ }) {
842
+ fe = a;
843
+ let c = !1, i = !1, d = p.Stop, u = p.Stop;
844
+ const {
845
+ startConnection: h,
846
+ sendStreamRequest: _,
847
+ close: k,
848
+ createStream: D,
849
+ addIceCandidate: R
850
+ } = t.videoType === ae.Clip ? Ye(o, s, e, r.onError) : Qe(o, s, e, r.onError), {
851
+ id: S,
852
+ offer: B,
853
+ ice_servers: l,
854
+ session_id: m,
855
+ fluent: y
856
+ } = await D(t), w = new st({
857
+ iceServers: l
858
+ }), T = w.createDataChannel("JanusDataChannel");
859
+ if (!m)
1203
860
  throw new Error("Could not create session_id");
1204
- }
1205
- const streamType = fluent ? StreamType.Fluent : StreamType.Legacy;
1206
- analytics.enrich({
1207
- "stream-type": streamType
861
+ const v = y ? J.Fluent : J.Legacy;
862
+ n.enrich({
863
+ "stream-type": v
1208
864
  });
1209
- const warmup = agent.stream_warmup && !fluent;
1210
- const getIsConnected = () => isConnected;
1211
- const onConnected = () => {
1212
- var _a;
1213
- isConnected = true;
1214
- if (isDatachannelOpen) {
1215
- (_a = callbacks.onConnectionStateChange) == null ? void 0 : _a.call(callbacks, ConnectionState.Connected);
1216
- }
1217
- };
1218
- const videoStatsInterval = pollStats(peerConnection, getIsConnected, onConnected, (state, report) => handleStreamState({
1219
- statsSignal: statsSignal = state,
1220
- dataChannelSignal: streamType === StreamType.Legacy ? dataChannelSignal : void 0,
1221
- onVideoStateChange: callbacks.onVideoStateChange,
1222
- onAgentActivityStateChange: callbacks.onAgentActivityStateChange,
1223
- report,
1224
- streamType
1225
- }), (state) => {
1226
- var _a;
1227
- return (_a = callbacks.onConnectivityStateChange) == null ? void 0 : _a.call(callbacks, state);
1228
- }, warmup);
1229
- peerConnection.onicecandidate = (event) => {
1230
- var _a;
1231
- log("peerConnection.onicecandidate", event);
865
+ const j = t.stream_warmup && !y, P = () => c, $ = () => {
866
+ var f;
867
+ c = !0, i && ((f = r.onConnectionStateChange) == null || f.call(r, M.Connected));
868
+ }, C = it(w, P, $, (f, g) => ne({
869
+ statsSignal: u = f,
870
+ dataChannelSignal: v === J.Legacy ? d : void 0,
871
+ onVideoStateChange: r.onVideoStateChange,
872
+ onAgentActivityStateChange: r.onAgentActivityStateChange,
873
+ report: g,
874
+ streamType: v
875
+ }), (f) => {
876
+ var g;
877
+ return (g = r.onConnectivityStateChange) == null ? void 0 : g.call(r, f);
878
+ }, j);
879
+ w.onicecandidate = (f) => {
880
+ var g;
881
+ x("peerConnection.onicecandidate", f);
1232
882
  try {
1233
- if (event.candidate && event.candidate.sdpMid && event.candidate.sdpMLineIndex !== null) {
1234
- addIceCandidate(streamIdFromServer, {
1235
- candidate: event.candidate.candidate,
1236
- sdpMid: event.candidate.sdpMid,
1237
- sdpMLineIndex: event.candidate.sdpMLineIndex
1238
- }, session_id);
1239
- } else {
1240
- addIceCandidate(streamIdFromServer, {
1241
- candidate: null
1242
- }, session_id);
1243
- }
1244
- } catch (e) {
1245
- (_a = callbacks.onError) == null ? void 0 : _a.call(callbacks, e, {
1246
- streamId: streamIdFromServer
1247
- });
1248
- }
1249
- };
1250
- pcDataChannel.onopen = () => {
1251
- isDatachannelOpen = true;
1252
- if (!warmup || isConnected) {
1253
- onConnected();
1254
- }
1255
- };
1256
- pcDataChannel.onmessage = (event) => {
1257
- if (event.data in DataChannelSignalMap) {
1258
- dataChannelSignal = DataChannelSignalMap[event.data];
1259
- handleStreamState({
1260
- statsSignal: streamType === StreamType.Legacy ? statsSignal : void 0,
1261
- dataChannelSignal,
1262
- onVideoStateChange: callbacks.onVideoStateChange,
1263
- onAgentActivityStateChange: callbacks.onAgentActivityStateChange,
1264
- streamType
883
+ f.candidate && f.candidate.sdpMid && f.candidate.sdpMLineIndex !== null ? R(S, {
884
+ candidate: f.candidate.candidate,
885
+ sdpMid: f.candidate.sdpMid,
886
+ sdpMLineIndex: f.candidate.sdpMLineIndex
887
+ }, m) : R(S, {
888
+ candidate: null
889
+ }, m);
890
+ } catch (A) {
891
+ (g = r.onError) == null || g.call(r, A, {
892
+ streamId: S
1265
893
  });
1266
894
  }
895
+ }, T.onopen = () => {
896
+ i = !0, (!j || c) && $();
1267
897
  };
1268
- peerConnection.oniceconnectionstatechange = () => {
1269
- var _a;
1270
- log("peerConnection.oniceconnectionstatechange => " + peerConnection.iceConnectionState);
1271
- const newState = mapConnectionState(peerConnection.iceConnectionState);
1272
- if (newState !== ConnectionState.Connected) {
1273
- (_a = callbacks.onConnectionStateChange) == null ? void 0 : _a.call(callbacks, newState);
1274
- }
1275
- };
1276
- peerConnection.ontrack = (event) => {
1277
- var _a;
1278
- log("peerConnection.ontrack", event);
1279
- (_a = callbacks.onSrcObjectReady) == null ? void 0 : _a.call(callbacks, event.streams[0]);
898
+ function I(f) {
899
+ d = f === N.StreamStarted ? p.Start : p.Stop, ne({
900
+ statsSignal: v === J.Legacy ? u : void 0,
901
+ dataChannelSignal: d,
902
+ onVideoStateChange: r.onVideoStateChange,
903
+ onAgentActivityStateChange: r.onAgentActivityStateChange,
904
+ streamType: v
905
+ });
906
+ }
907
+ function E(f, g) {
908
+ const A = typeof g == "string" ? g : g == null ? void 0 : g.metadata;
909
+ A && n.enrich({
910
+ streamMetadata: A
911
+ }), n.track("agent-chat", {
912
+ event: "ready"
913
+ });
914
+ }
915
+ const L = {
916
+ [N.StreamStarted]: I,
917
+ [N.StreamDone]: I,
918
+ [N.StreamReady]: E
1280
919
  };
1281
- await peerConnection.setRemoteDescription(offer);
1282
- log("set remote description OK");
1283
- const sessionClientAnswer = await peerConnection.createAnswer();
1284
- log("create answer OK");
1285
- await peerConnection.setLocalDescription(sessionClientAnswer);
1286
- log("set local description OK");
1287
- await startConnection(streamIdFromServer, sessionClientAnswer, session_id);
1288
- log("start connection OK");
1289
- return {
920
+ T.onmessage = (f) => {
921
+ var H;
922
+ const {
923
+ subject: g,
924
+ data: A
925
+ } = ot(f.data);
926
+ (H = L[g]) == null || H.call(L, g, A);
927
+ }, w.oniceconnectionstatechange = () => {
928
+ var g;
929
+ x("peerConnection.oniceconnectionstatechange => " + w.iceConnectionState);
930
+ const f = re(w.iceConnectionState);
931
+ f !== M.Connected && ((g = r.onConnectionStateChange) == null || g.call(r, f));
932
+ }, w.ontrack = (f) => {
933
+ var g;
934
+ x("peerConnection.ontrack", f), (g = r.onSrcObjectReady) == null || g.call(r, f.streams[0]);
935
+ }, await w.setRemoteDescription(B), x("set remote description OK");
936
+ const z = await w.createAnswer();
937
+ return x("create answer OK"), await w.setLocalDescription(z), x("set local description OK"), await h(S, z, m), x("start connection OK"), {
1290
938
  /**
1291
939
  * Method to send request to server to get clip or talk depend on you payload
1292
940
  * @param payload
1293
941
  */
1294
- speak(payload) {
1295
- return sendStreamRequest(streamIdFromServer, session_id, payload);
942
+ speak(f) {
943
+ return _(S, m, f);
1296
944
  },
1297
945
  /**
1298
946
  * Method to close RTC connection
1299
947
  */
1300
948
  async disconnect() {
1301
- var _a;
1302
- if (streamIdFromServer) {
1303
- const state = mapConnectionState(peerConnection.iceConnectionState);
1304
- if (peerConnection) {
1305
- if (state === ConnectionState.New) {
1306
- clearInterval(videoStatsInterval);
949
+ var f;
950
+ if (S) {
951
+ const g = re(w.iceConnectionState);
952
+ if (w) {
953
+ if (g === M.New) {
954
+ clearInterval(C);
1307
955
  return;
1308
956
  }
1309
- peerConnection.close();
1310
- peerConnection.oniceconnectionstatechange = null;
1311
- peerConnection.onnegotiationneeded = null;
1312
- peerConnection.onicecandidate = null;
1313
- peerConnection.ontrack = null;
957
+ w.close(), w.oniceconnectionstatechange = null, w.onnegotiationneeded = null, w.onicecandidate = null, w.ontrack = null;
1314
958
  }
1315
959
  try {
1316
- if (state === ConnectionState.Connected) {
1317
- await close(streamIdFromServer, session_id).catch((_) => {
1318
- });
1319
- }
1320
- } catch (e) {
1321
- log("Error on close stream connection", e);
960
+ g === M.Connected && await k(S, m).catch((A) => {
961
+ });
962
+ } catch (A) {
963
+ x("Error on close stream connection", A);
1322
964
  }
1323
- (_a = callbacks.onAgentActivityStateChange) == null ? void 0 : _a.call(callbacks, AgentActivityState.Idle);
1324
- clearInterval(videoStatsInterval);
965
+ (f = r.onAgentActivityStateChange) == null || f.call(r, X.Idle), clearInterval(C);
1325
966
  }
1326
967
  },
1327
968
  /**
1328
969
  * Session identifier information, should be returned in the body of all streaming requests
1329
970
  */
1330
- sessionId: session_id,
971
+ sessionId: m,
1331
972
  /**
1332
973
  * Id of current RTC stream
1333
974
  */
1334
- streamId: streamIdFromServer,
1335
- streamType
975
+ streamId: S,
976
+ streamType: v
1336
977
  };
1337
978
  }
1338
- function getAgentStreamArgs(agent, options) {
979
+ function ut(e, t) {
1339
980
  const {
1340
- streamOptions
1341
- } = options ?? {};
981
+ streamOptions: a
982
+ } = t ?? {};
1342
983
  return {
1343
- videoType: mapVideoType(agent.presenter.type),
1344
- output_resolution: streamOptions == null ? void 0 : streamOptions.outputResolution,
1345
- session_timeout: streamOptions == null ? void 0 : streamOptions.sessionTimeout,
1346
- stream_warmup: streamOptions == null ? void 0 : streamOptions.streamWarmup,
1347
- compatibility_mode: streamOptions == null ? void 0 : streamOptions.compatibilityMode,
1348
- fluent: streamOptions == null ? void 0 : streamOptions.fluent
984
+ videoType: Ee(e.presenter.type),
985
+ output_resolution: a == null ? void 0 : a.outputResolution,
986
+ session_timeout: a == null ? void 0 : a.sessionTimeout,
987
+ stream_warmup: a == null ? void 0 : a.streamWarmup,
988
+ compatibility_mode: a == null ? void 0 : a.compatibilityMode,
989
+ fluent: a == null ? void 0 : a.fluent
1349
990
  };
1350
991
  }
1351
- function trackVideoStateChangeAnalytics(state, agent, statsReport, analytics, streamType) {
1352
- if (streamType === StreamType.Fluent) {
1353
- trackVideoStreamAnalytics(state, agent, statsReport, analytics, streamType);
1354
- } else {
1355
- trackLegacyVideoAnalytics(state, agent, statsReport, analytics, streamType);
1356
- }
992
+ function ft(e, t, a, r, o) {
993
+ o === J.Fluent ? mt(e, t, a, r, o) : ht(e, t, a, r, o);
1357
994
  }
1358
- function trackVideoStreamAnalytics(state, agent, statsReport, analytics, streamType) {
1359
- if (state === StreamingState.Start) {
1360
- analytics.track("stream-session", {
1361
- event: "start",
1362
- "stream-type": streamType
1363
- });
1364
- } else if (state === StreamingState.Stop) {
1365
- analytics.track("stream-session", {
1366
- event: "stop",
1367
- is_greenscreen: agent.presenter.type === "clip" && agent.presenter.is_greenscreen,
1368
- background: agent.presenter.type === "clip" && agent.presenter.background,
1369
- "stream-type": streamType,
1370
- ...statsReport
1371
- });
1372
- }
995
+ function mt(e, t, a, r, o) {
996
+ e === p.Start ? r.track("stream-session", {
997
+ event: "start",
998
+ "stream-type": o
999
+ }) : e === p.Stop && r.track("stream-session", {
1000
+ event: "stop",
1001
+ is_greenscreen: t.presenter.type === "clip" && t.presenter.is_greenscreen,
1002
+ background: t.presenter.type === "clip" && t.presenter.background,
1003
+ "stream-type": o,
1004
+ ...a
1005
+ });
1373
1006
  }
1374
- function trackAgentActivityAnalytics(state, agent, analytics, streamType) {
1375
- if (timestampTracker.get() <= 0)
1376
- return;
1377
- if (state === StreamingState.Start) {
1378
- analytics.linkTrack("agent-video", {
1379
- event: "start",
1380
- latency: timestampTracker.get(true),
1381
- "stream-type": streamType
1382
- }, "start", [StreamEvents.StreamVideoCreated]);
1383
- } else if (state === StreamingState.Stop) {
1384
- analytics.linkTrack("agent-video", {
1385
- event: "stop",
1386
- is_greenscreen: agent.presenter.type === "clip" && agent.presenter.is_greenscreen,
1387
- background: agent.presenter.type === "clip" && agent.presenter.background,
1388
- "stream-type": streamType
1389
- }, "done", [StreamEvents.StreamVideoDone]);
1390
- }
1007
+ function gt(e, t, a, r) {
1008
+ F.get() <= 0 || (e === p.Start ? a.linkTrack("agent-video", {
1009
+ event: "start",
1010
+ latency: F.get(!0),
1011
+ "stream-type": r
1012
+ }, "start", [N.StreamVideoCreated]) : e === p.Stop && a.linkTrack("agent-video", {
1013
+ event: "stop",
1014
+ is_greenscreen: t.presenter.type === "clip" && t.presenter.is_greenscreen,
1015
+ background: t.presenter.type === "clip" && t.presenter.background,
1016
+ "stream-type": r
1017
+ }, "done", [N.StreamVideoDone]));
1391
1018
  }
1392
- function trackLegacyVideoAnalytics(state, agent, statsReport, analytics, streamType) {
1393
- if (timestampTracker.get() <= 0)
1394
- return;
1395
- if (state === StreamingState.Start) {
1396
- analytics.linkTrack("agent-video", {
1397
- event: "start",
1398
- latency: timestampTracker.get(true),
1399
- "stream-type": streamType
1400
- }, "start", [StreamEvents.StreamVideoCreated]);
1401
- } else if (state === StreamingState.Stop) {
1402
- analytics.linkTrack("agent-video", {
1403
- event: "stop",
1404
- is_greenscreen: agent.presenter.type === "clip" && agent.presenter.is_greenscreen,
1405
- background: agent.presenter.type === "clip" && agent.presenter.background,
1406
- "stream-type": streamType,
1407
- ...statsReport
1408
- }, "done", [StreamEvents.StreamVideoDone]);
1409
- }
1019
+ function ht(e, t, a, r, o) {
1020
+ F.get() <= 0 || (e === p.Start ? r.linkTrack("agent-video", {
1021
+ event: "start",
1022
+ latency: F.get(!0),
1023
+ "stream-type": o
1024
+ }, "start", [N.StreamVideoCreated]) : e === p.Stop && r.linkTrack("agent-video", {
1025
+ event: "stop",
1026
+ is_greenscreen: t.presenter.type === "clip" && t.presenter.is_greenscreen,
1027
+ background: t.presenter.type === "clip" && t.presenter.background,
1028
+ "stream-type": o,
1029
+ ...a
1030
+ }, "done", [N.StreamVideoDone]));
1410
1031
  }
1411
- function connectToManager(agent, options, analytics) {
1412
- timestampTracker.reset();
1413
- return new Promise(async (resolve, reject) => {
1032
+ function wt(e, t, a) {
1033
+ return F.reset(), new Promise(async (r, o) => {
1414
1034
  try {
1415
- const streamingManager = await createStreamingManager(agent.id, getAgentStreamArgs(agent, options), {
1416
- ...options,
1417
- analytics,
1035
+ const s = await lt(e.id, ut(e, t), {
1036
+ ...t,
1037
+ analytics: a,
1418
1038
  callbacks: {
1419
- ...options.callbacks,
1420
- onConnectionStateChange: (state) => {
1421
- var _a, _b;
1422
- (_b = (_a = options.callbacks).onConnectionStateChange) == null ? void 0 : _b.call(_a, state);
1423
- if (state === ConnectionState.Connected) {
1424
- resolve(streamingManager);
1425
- }
1039
+ ...t.callbacks,
1040
+ onConnectionStateChange: (n) => {
1041
+ var c, i;
1042
+ (i = (c = t.callbacks).onConnectionStateChange) == null || i.call(c, n), n === M.Connected && r(s);
1426
1043
  },
1427
- onVideoStateChange: (state, statsReport) => {
1428
- var _a, _b;
1429
- (_b = (_a = options.callbacks).onVideoStateChange) == null ? void 0 : _b.call(_a, state);
1430
- trackVideoStateChangeAnalytics(state, agent, statsReport, analytics, streamingManager.streamType);
1044
+ onVideoStateChange: (n, c) => {
1045
+ var i, d;
1046
+ (d = (i = t.callbacks).onVideoStateChange) == null || d.call(i, n), ft(n, e, c, a, s.streamType);
1431
1047
  },
1432
- onAgentActivityStateChange: (state) => {
1433
- var _a, _b;
1434
- (_b = (_a = options.callbacks).onAgentActivityStateChange) == null ? void 0 : _b.call(_a, state);
1435
- trackAgentActivityAnalytics(state === AgentActivityState.Talking ? StreamingState.Start : StreamingState.Stop, agent, analytics, streamingManager.streamType);
1048
+ onAgentActivityStateChange: (n) => {
1049
+ var c, i;
1050
+ (i = (c = t.callbacks).onAgentActivityStateChange) == null || i.call(c, n), gt(n === X.Talking ? p.Start : p.Stop, e, a, s.streamType);
1436
1051
  }
1437
1052
  }
1438
1053
  });
1439
- } catch (error) {
1440
- reject(error);
1054
+ } catch (s) {
1055
+ o(s);
1441
1056
  }
1442
1057
  });
1443
1058
  }
1444
- async function initializeStreamAndChat(agent, options, agentsApi, analytics, chat) {
1445
- var _a, _b, _c, _d;
1059
+ async function pt(e, t, a, r, o) {
1060
+ var i, d, u, h;
1446
1061
  const {
1447
- chat: newChat,
1448
- chatMode
1449
- } = await createChat(agent, agentsApi, analytics, options.mode, options.persistentChat, chat);
1450
- if (chatMode && chatMode !== options.mode) {
1451
- options.mode = chatMode;
1452
- (_b = (_a = options.callbacks).onModeChange) == null ? void 0 : _b.call(_a, chatMode);
1453
- if (chatMode === ChatMode.TextOnly) {
1454
- (_d = (_c = options.callbacks).onError) == null ? void 0 : _d.call(_c, new ChatModeDowngraded(chatMode));
1455
- return {
1456
- chat: newChat
1457
- };
1458
- }
1459
- }
1460
- const streamingManager = await connectToManager(agent, options, analytics);
1062
+ chat: s,
1063
+ chatMode: n
1064
+ } = await ue(e, a, r, t.mode, t.persistentChat, o);
1065
+ if (n && n !== t.mode && (t.mode = n, (d = (i = t.callbacks).onModeChange) == null || d.call(i, n), n === b.TextOnly))
1066
+ return (h = (u = t.callbacks).onError) == null || h.call(u, new we(n)), {
1067
+ chat: s
1068
+ };
1069
+ const c = await wt(e, t, r);
1461
1070
  return {
1462
- chat: newChat,
1463
- streamingManager
1071
+ chat: s,
1072
+ streamingManager: c
1464
1073
  };
1465
1074
  }
1466
- async function createAgentManager(agent, options) {
1467
- var _a, _b, _c;
1468
- let firstConnection = true;
1469
- const mxKey = options.mixpanelKey || mixpanelKey;
1470
- const wsURL = options.wsURL || didSocketApiUrl;
1471
- const baseURL = options.baseURL || didApiUrl;
1472
- const items = {
1075
+ async function vt(e, t) {
1076
+ var R, S, B;
1077
+ let a = !0;
1078
+ const r = t.mixpanelKey || je, o = t.wsURL || Te, s = t.baseURL || Y, n = {
1473
1079
  messages: [],
1474
- chatMode: options.mode || ChatMode.Functional
1475
- };
1476
- const agentsApi = createAgentsApi(options.auth, baseURL, options.callbacks.onError);
1477
- const agentEntity = await agentsApi.getById(agent);
1478
- const analytics = initializeAnalytics({
1479
- token: mxKey,
1480
- agent: agentEntity,
1481
- isEnabled: options.enableAnalitics,
1482
- distinctId: options.distinctId
1483
- });
1484
- const {
1485
- onMessage,
1486
- clearQueue
1487
- } = createMessageEventQueue(analytics, items, options, agentEntity, () => {
1488
- var _a2;
1489
- return (_a2 = items.socketManager) == null ? void 0 : _a2.disconnect();
1080
+ chatMode: t.mode || b.Functional
1081
+ }, c = ce(t.auth, s, t.callbacks.onError), i = await c.getById(e), d = Ne({
1082
+ token: r,
1083
+ agent: i,
1084
+ isEnabled: t.enableAnalitics,
1085
+ distinctId: t.distinctId
1086
+ }), {
1087
+ onMessage: u,
1088
+ clearQueue: h
1089
+ } = Xe(d, n, t, i, () => {
1090
+ var l;
1091
+ return (l = n.socketManager) == null ? void 0 : l.disconnect();
1490
1092
  });
1491
- items.messages = getInitialMessages(options.initialMessages);
1492
- (_b = (_a = options.callbacks).onNewMessage) == null ? void 0 : _b.call(_a, [...items.messages], "answer");
1493
- analytics.track("agent-sdk", {
1093
+ n.messages = We(t.initialMessages), (S = (R = t.callbacks).onNewMessage) == null || S.call(R, [...n.messages], "answer"), d.track("agent-sdk", {
1494
1094
  event: "loaded",
1495
- ...getAnalyticsInfo(agentEntity)
1095
+ ...Le(i)
1496
1096
  });
1497
- async function connect2(newChat) {
1498
- var _a2, _b2, _c2, _d, _e, _f, _g;
1499
- (_b2 = (_a2 = options.callbacks).onConnectionStateChange) == null ? void 0 : _b2.call(_a2, ConnectionState.Connecting);
1500
- timestampTracker.reset();
1501
- if (newChat && !firstConnection) {
1502
- delete items.chat;
1503
- (_d = (_c2 = options.callbacks).onNewMessage) == null ? void 0 : _d.call(_c2, [...items.messages], "answer");
1504
- }
1505
- const websocketPromise = options.mode === ChatMode.DirectPlayback ? Promise.resolve(void 0) : createSocketManager(options.auth, wsURL, {
1506
- onMessage,
1507
- onError: options.callbacks.onError
1508
- });
1509
- const initPromise = retryOperation(() => {
1510
- return initializeStreamAndChat(agentEntity, options, agentsApi, analytics, items.chat);
1511
- }, {
1097
+ async function _(l) {
1098
+ var j, P, $, C, I, E, L;
1099
+ (P = (j = t.callbacks).onConnectionStateChange) == null || P.call(j, M.Connecting), F.reset(), l && !a && (delete n.chat, (C = ($ = t.callbacks).onNewMessage) == null || C.call($, [...n.messages], "answer"));
1100
+ const m = t.mode === b.DirectPlayback ? Promise.resolve(void 0) : He(t.auth, o, {
1101
+ onMessage: u,
1102
+ onError: t.callbacks.onError
1103
+ }), y = G(() => pt(i, t, c, d, n.chat), {
1512
1104
  limit: 3,
1513
- timeout: CONNECTION_RETRY_TIMEOUT_MS,
1105
+ timeout: Ie,
1514
1106
  timeoutErrorMessage: "Timeout initializing the stream",
1515
1107
  // Retry on all errors except for connection errors and rate limit errors, these are already handled in client level.
1516
- shouldRetryFn: (error) => (error == null ? void 0 : error.message) !== "Could not connect" && error.status !== 429,
1108
+ shouldRetryFn: (z) => (z == null ? void 0 : z.message) !== "Could not connect" && z.status !== 429,
1517
1109
  delayMs: 1e3
1518
- }).catch((e) => {
1519
- var _a3, _b3;
1520
- changeMode(ChatMode.Maintenance);
1521
- (_b3 = (_a3 = options.callbacks).onConnectionStateChange) == null ? void 0 : _b3.call(_a3, ConnectionState.Fail);
1522
- throw e;
1523
- });
1524
- const [socketManager, {
1525
- streamingManager,
1526
- chat
1527
- }] = await Promise.all([websocketPromise, initPromise]);
1528
- if (chat && chat.id !== ((_e = items.chat) == null ? void 0 : _e.id)) {
1529
- (_g = (_f = options.callbacks).onNewChat) == null ? void 0 : _g.call(_f, chat.id);
1530
- }
1531
- items.streamingManager = streamingManager;
1532
- items.socketManager = socketManager;
1533
- items.chat = chat;
1534
- firstConnection = false;
1535
- changeMode((chat == null ? void 0 : chat.chat_mode) ?? options.mode ?? ChatMode.Functional);
1110
+ }).catch((z) => {
1111
+ var f, g;
1112
+ throw D(b.Maintenance), (g = (f = t.callbacks).onConnectionStateChange) == null || g.call(f, M.Fail), z;
1113
+ }), [w, {
1114
+ streamingManager: T,
1115
+ chat: v
1116
+ }] = await Promise.all([m, y]);
1117
+ v && v.id !== ((I = n.chat) == null ? void 0 : I.id) && ((L = (E = t.callbacks).onNewChat) == null || L.call(E, v.id)), n.streamingManager = T, n.socketManager = w, n.chat = v, a = !1, D((v == null ? void 0 : v.chat_mode) ?? t.mode ?? b.Functional);
1536
1118
  }
1537
- async function disconnect() {
1538
- var _a2, _b2, _c2, _d;
1539
- (_a2 = items.socketManager) == null ? void 0 : _a2.disconnect();
1540
- await ((_b2 = items.streamingManager) == null ? void 0 : _b2.disconnect());
1541
- delete items.streamingManager;
1542
- delete items.socketManager;
1543
- (_d = (_c2 = options.callbacks).onConnectionStateChange) == null ? void 0 : _d.call(_c2, ConnectionState.Disconnected);
1119
+ async function k() {
1120
+ var l, m, y, w;
1121
+ (l = n.socketManager) == null || l.disconnect(), await ((m = n.streamingManager) == null ? void 0 : m.disconnect()), delete n.streamingManager, delete n.socketManager, (w = (y = t.callbacks).onConnectionStateChange) == null || w.call(y, M.Disconnected);
1544
1122
  }
1545
- async function changeMode(mode) {
1546
- var _a2, _b2;
1547
- if (mode !== items.chatMode) {
1548
- analytics.track("agent-mode-change", {
1549
- mode
1550
- });
1551
- items.chatMode = mode;
1552
- if (items.chatMode !== ChatMode.Functional) {
1553
- await disconnect();
1554
- }
1555
- (_b2 = (_a2 = options.callbacks).onModeChange) == null ? void 0 : _b2.call(_a2, mode);
1556
- }
1123
+ async function D(l) {
1124
+ var m, y;
1125
+ l !== n.chatMode && (d.track("agent-mode-change", {
1126
+ mode: l
1127
+ }), n.chatMode = l, n.chatMode !== b.Functional && await k(), (y = (m = t.callbacks).onModeChange) == null || y.call(m, l));
1557
1128
  }
1558
1129
  return {
1559
- agent: agentEntity,
1130
+ agent: i,
1560
1131
  getStreamType: () => {
1561
- var _a2;
1562
- return (_a2 = items.streamingManager) == null ? void 0 : _a2.streamType;
1132
+ var l;
1133
+ return (l = n.streamingManager) == null ? void 0 : l.streamType;
1563
1134
  },
1564
- starterMessages: ((_c = agentEntity.knowledge) == null ? void 0 : _c.starter_message) || [],
1565
- getSTTToken: () => agentsApi.getSTTToken(agentEntity.id),
1566
- changeMode,
1567
- enrichAnalytics: analytics.enrich,
1135
+ starterMessages: ((B = i.knowledge) == null ? void 0 : B.starter_message) || [],
1136
+ getSTTToken: () => c.getSTTToken(i.id),
1137
+ changeMode: D,
1138
+ enrichAnalytics: d.enrich,
1568
1139
  async connect() {
1569
- var _a2;
1570
- await connect2(true);
1571
- analytics.track("agent-chat", {
1140
+ var l;
1141
+ await _(!0), d.track("agent-chat", {
1572
1142
  event: "connect",
1573
- chatId: (_a2 = items.chat) == null ? void 0 : _a2.id,
1574
- agentId: agentEntity.id,
1575
- mode: items.chatMode
1143
+ chatId: (l = n.chat) == null ? void 0 : l.id,
1144
+ agentId: i.id,
1145
+ mode: n.chatMode
1576
1146
  });
1577
1147
  },
1578
1148
  async reconnect() {
1579
- var _a2;
1580
- await disconnect();
1581
- await connect2(false);
1582
- analytics.track("agent-chat", {
1149
+ var l;
1150
+ await k(), await _(!1), d.track("agent-chat", {
1583
1151
  event: "reconnect",
1584
- chatId: (_a2 = items.chat) == null ? void 0 : _a2.id,
1585
- agentId: agentEntity.id,
1586
- mode: items.chatMode
1152
+ chatId: (l = n.chat) == null ? void 0 : l.id,
1153
+ agentId: i.id,
1154
+ mode: n.chatMode
1587
1155
  });
1588
1156
  },
1589
1157
  async disconnect() {
1590
- var _a2;
1591
- await disconnect();
1592
- analytics.track("agent-chat", {
1158
+ var l;
1159
+ await k(), d.track("agent-chat", {
1593
1160
  event: "disconnect",
1594
- chatId: (_a2 = items.chat) == null ? void 0 : _a2.id,
1595
- agentId: agentEntity.id,
1596
- mode: items.chatMode
1161
+ chatId: (l = n.chat) == null ? void 0 : l.id,
1162
+ agentId: i.id,
1163
+ mode: n.chatMode
1597
1164
  });
1598
1165
  },
1599
- async chat(userMessage) {
1600
- var _a2, _b2, _c2, _d, _e;
1601
- const validateChatRequest = () => {
1602
- if (options.mode === ChatMode.DirectPlayback) {
1603
- throw new ValidationError("Direct playback is enabled, chat is disabled");
1604
- } else if (userMessage.length >= 800) {
1605
- throw new ValidationError("Message cannot be more than 800 characters");
1606
- } else if (userMessage.length === 0) {
1607
- throw new ValidationError("Message cannot be empty");
1608
- } else if (items.chatMode === ChatMode.Maintenance) {
1609
- throw new ValidationError("Chat is in maintenance mode");
1610
- } else if (![ChatMode.TextOnly, ChatMode.Playground].includes(items.chatMode)) {
1611
- if (!items.streamingManager) {
1612
- throw new ValidationError("Streaming manager is not initialized");
1613
- }
1614
- if (!items.chat) {
1615
- throw new ValidationError("Chat is not initialized");
1616
- }
1166
+ async chat(l) {
1167
+ var T, v, j, P, $;
1168
+ const m = () => {
1169
+ if (t.mode === b.DirectPlayback)
1170
+ throw new W("Direct playback is enabled, chat is disabled");
1171
+ if (l.length >= 800)
1172
+ throw new W("Message cannot be more than 800 characters");
1173
+ if (l.length === 0)
1174
+ throw new W("Message cannot be empty");
1175
+ if (n.chatMode === b.Maintenance)
1176
+ throw new W("Chat is in maintenance mode");
1177
+ if (![b.TextOnly, b.Playground].includes(n.chatMode)) {
1178
+ if (!n.streamingManager)
1179
+ throw new W("Streaming manager is not initialized");
1180
+ if (!n.chat)
1181
+ throw new W("Chat is not initialized");
1617
1182
  }
1618
- };
1619
- const initializeChat = async () => {
1620
- var _a3, _b3;
1621
- if (!items.chat) {
1622
- const newChat = await createChat(agentEntity, agentsApi, analytics, items.chatMode, options.persistentChat);
1623
- if (!newChat.chat) {
1624
- throw new ChatCreationFailed(items.chatMode, !!options.persistentChat);
1625
- }
1626
- items.chat = newChat.chat;
1627
- (_b3 = (_a3 = options.callbacks).onNewChat) == null ? void 0 : _b3.call(_a3, items.chat.id);
1183
+ }, y = async () => {
1184
+ var C, I;
1185
+ if (!n.chat) {
1186
+ const E = await ue(i, c, d, n.chatMode, t.persistentChat);
1187
+ if (!E.chat)
1188
+ throw new he(n.chatMode, !!t.persistentChat);
1189
+ n.chat = E.chat, (I = (C = t.callbacks).onNewChat) == null || I.call(C, n.chat.id);
1628
1190
  }
1629
- return items.chat.id;
1630
- };
1631
- const sendChatRequest = async (messages, chatId) => {
1632
- return retryOperation(() => {
1633
- var _a3, _b3;
1634
- return agentsApi.chat(agentEntity.id, chatId, {
1635
- chatMode: items.chatMode,
1636
- streamId: (_a3 = items.streamingManager) == null ? void 0 : _a3.streamId,
1637
- sessionId: (_b3 = items.streamingManager) == null ? void 0 : _b3.sessionId,
1638
- messages: messages.map(({
1639
- matches,
1640
- ...message
1641
- }) => message)
1642
- }, {
1643
- ...getRequestHeaders(items.chatMode),
1644
- skipErrorHandler: true
1645
- });
1191
+ return n.chat.id;
1192
+ }, w = async (C, I) => G(() => {
1193
+ var E, L;
1194
+ return c.chat(i.id, I, {
1195
+ chatMode: n.chatMode,
1196
+ streamId: (E = n.streamingManager) == null ? void 0 : E.streamId,
1197
+ sessionId: (L = n.streamingManager) == null ? void 0 : L.sessionId,
1198
+ messages: C.map(({
1199
+ matches: z,
1200
+ ...f
1201
+ }) => f)
1646
1202
  }, {
1647
- limit: 2,
1648
- shouldRetryFn: (error) => {
1649
- var _a3, _b3, _c3, _d2;
1650
- const isInvalidSessionId = (_a3 = error == null ? void 0 : error.message) == null ? void 0 : _a3.includes("missing or invalid session_id");
1651
- const isStreamError = (_b3 = error == null ? void 0 : error.message) == null ? void 0 : _b3.includes("Stream Error");
1652
- if (!isStreamError && !isInvalidSessionId) {
1653
- (_d2 = (_c3 = options.callbacks).onError) == null ? void 0 : _d2.call(_c3, error);
1654
- return false;
1655
- }
1656
- return true;
1657
- },
1658
- onRetry: async () => {
1659
- await disconnect();
1660
- await connect2(false);
1661
- }
1203
+ ...le(n.chatMode),
1204
+ skipErrorHandler: !0
1662
1205
  });
1663
- };
1206
+ }, {
1207
+ limit: 2,
1208
+ shouldRetryFn: (E) => {
1209
+ var f, g, A, H;
1210
+ const L = (f = E == null ? void 0 : E.message) == null ? void 0 : f.includes("missing or invalid session_id");
1211
+ return !((g = E == null ? void 0 : E.message) == null ? void 0 : g.includes("Stream Error")) && !L ? ((H = (A = t.callbacks).onError) == null || H.call(A, E), !1) : !0;
1212
+ },
1213
+ onRetry: async () => {
1214
+ await k(), await _(!1);
1215
+ }
1216
+ });
1664
1217
  try {
1665
- clearQueue();
1666
- validateChatRequest();
1667
- items.messages.push({
1668
- id: getRandom(),
1218
+ h(), m(), n.messages.push({
1219
+ id: K(),
1669
1220
  role: "user",
1670
- content: userMessage,
1671
- created_at: new Date(timestampTracker.update()).toISOString()
1672
- });
1673
- (_b2 = (_a2 = options.callbacks).onNewMessage) == null ? void 0 : _b2.call(_a2, [...items.messages], "user");
1674
- const chatId = await initializeChat();
1675
- const response = await sendChatRequest([...items.messages], chatId);
1676
- items.messages.push({
1677
- id: getRandom(),
1221
+ content: l,
1222
+ created_at: new Date(F.update()).toISOString()
1223
+ }), (v = (T = t.callbacks).onNewMessage) == null || v.call(T, [...n.messages], "user");
1224
+ const C = await y(), I = await w([...n.messages], C);
1225
+ return n.messages.push({
1226
+ id: K(),
1678
1227
  role: "assistant",
1679
- content: response.result || "",
1228
+ content: I.result || "",
1680
1229
  created_at: (/* @__PURE__ */ new Date()).toISOString(),
1681
- context: response.context,
1682
- matches: response.matches
1683
- });
1684
- analytics.track("agent-message-send", {
1230
+ context: I.context,
1231
+ matches: I.matches
1232
+ }), d.track("agent-message-send", {
1685
1233
  event: "success",
1686
- mode: items.chatMode,
1687
- messages: items.messages.length + 1
1688
- });
1689
- if (response.result) {
1690
- (_d = (_c2 = options.callbacks).onNewMessage) == null ? void 0 : _d.call(_c2, [...items.messages], "answer");
1691
- analytics.track("agent-message-received", {
1692
- latency: timestampTracker.get(true),
1693
- mode: items.chatMode,
1694
- messages: items.messages.length
1695
- });
1696
- }
1697
- return response;
1698
- } catch (e) {
1699
- if (((_e = items.messages[items.messages.length - 1]) == null ? void 0 : _e.role) === "assistant") {
1700
- items.messages.pop();
1701
- }
1702
- analytics.track("agent-message-send", {
1234
+ mode: n.chatMode,
1235
+ messages: n.messages.length + 1
1236
+ }), I.result && ((P = (j = t.callbacks).onNewMessage) == null || P.call(j, [...n.messages], "answer"), d.track("agent-message-received", {
1237
+ latency: F.get(!0),
1238
+ mode: n.chatMode,
1239
+ messages: n.messages.length
1240
+ })), I;
1241
+ } catch (C) {
1242
+ throw (($ = n.messages[n.messages.length - 1]) == null ? void 0 : $.role) === "assistant" && n.messages.pop(), d.track("agent-message-send", {
1703
1243
  event: "error",
1704
- mode: items.chatMode,
1705
- messages: items.messages.length
1706
- });
1707
- throw e;
1244
+ mode: n.chatMode,
1245
+ messages: n.messages.length
1246
+ }), C;
1708
1247
  }
1709
1248
  },
1710
- rate(messageId, score, rateId) {
1711
- var _a2, _b2, _c2, _d;
1712
- const message = items.messages.find((message2) => message2.id === messageId);
1713
- if (!items.chat) {
1249
+ rate(l, m, y) {
1250
+ var v, j, P, $;
1251
+ const w = n.messages.find((C) => C.id === l);
1252
+ if (n.chat) {
1253
+ if (!w)
1254
+ throw new Error("Message not found");
1255
+ } else
1714
1256
  throw new Error("Chat is not initialized");
1715
- } else if (!message) {
1716
- throw new Error("Message not found");
1717
- }
1718
- const matches = ((_a2 = message.matches) == null ? void 0 : _a2.map((match) => [match.document_id, match.id])) ?? [];
1719
- analytics.track("agent-rate", {
1720
- event: rateId ? "update" : "create",
1721
- thumb: score === 1 ? "up" : "down",
1722
- knowledge_id: ((_b2 = agentEntity.knowledge) == null ? void 0 : _b2.id) ?? "",
1723
- mode: items.chatMode,
1724
- matches,
1725
- score
1726
- });
1727
- if (rateId) {
1728
- return agentsApi.updateRating(agentEntity.id, items.chat.id, rateId, {
1729
- knowledge_id: ((_c2 = agentEntity.knowledge) == null ? void 0 : _c2.id) ?? "",
1730
- message_id: messageId,
1731
- matches,
1732
- score
1733
- });
1734
- }
1735
- return agentsApi.createRating(agentEntity.id, items.chat.id, {
1736
- knowledge_id: ((_d = agentEntity.knowledge) == null ? void 0 : _d.id) ?? "",
1737
- message_id: messageId,
1738
- matches,
1739
- score
1257
+ const T = ((v = w.matches) == null ? void 0 : v.map((C) => [C.document_id, C.id])) ?? [];
1258
+ return d.track("agent-rate", {
1259
+ event: y ? "update" : "create",
1260
+ thumb: m === 1 ? "up" : "down",
1261
+ knowledge_id: ((j = i.knowledge) == null ? void 0 : j.id) ?? "",
1262
+ mode: n.chatMode,
1263
+ matches: T,
1264
+ score: m
1265
+ }), y ? c.updateRating(i.id, n.chat.id, y, {
1266
+ knowledge_id: ((P = i.knowledge) == null ? void 0 : P.id) ?? "",
1267
+ message_id: l,
1268
+ matches: T,
1269
+ score: m
1270
+ }) : c.createRating(i.id, n.chat.id, {
1271
+ knowledge_id: (($ = i.knowledge) == null ? void 0 : $.id) ?? "",
1272
+ message_id: l,
1273
+ matches: T,
1274
+ score: m
1740
1275
  });
1741
1276
  },
1742
- deleteRate(id) {
1743
- var _a2;
1744
- if (!items.chat) {
1277
+ deleteRate(l) {
1278
+ var m;
1279
+ if (!n.chat)
1745
1280
  throw new Error("Chat is not initialized");
1746
- }
1747
- analytics.track("agent-rate-delete", {
1281
+ return d.track("agent-rate-delete", {
1748
1282
  type: "text",
1749
- chat_id: (_a2 = items.chat) == null ? void 0 : _a2.id,
1750
- id,
1751
- mode: items.chatMode
1752
- });
1753
- return agentsApi.deleteRating(agentEntity.id, items.chat.id, id);
1283
+ chat_id: (m = n.chat) == null ? void 0 : m.id,
1284
+ id: l,
1285
+ mode: n.chatMode
1286
+ }), c.deleteRating(i.id, n.chat.id, l);
1754
1287
  },
1755
- async speak(payload) {
1756
- var _a2, _b2, _c2, _d;
1757
- if (!items.streamingManager) {
1288
+ async speak(l) {
1289
+ var T, v, j, P;
1290
+ if (!n.streamingManager)
1758
1291
  throw new Error("Please connect to the agent first");
1759
- }
1760
- function getScript() {
1761
- if (typeof payload === "string") {
1762
- if (!agentEntity.presenter.voice) {
1292
+ function m() {
1293
+ if (typeof l == "string") {
1294
+ if (!i.presenter.voice)
1763
1295
  throw new Error("Presenter voice is not initialized");
1764
- }
1765
1296
  return {
1766
1297
  type: "text",
1767
- provider: agentEntity.presenter.voice,
1768
- input: payload,
1769
- ssml: false
1298
+ provider: i.presenter.voice,
1299
+ input: l,
1300
+ ssml: !1
1770
1301
  };
1771
1302
  }
1772
- if (payload.type === "text" && !payload.provider) {
1773
- if (!agentEntity.presenter.voice) {
1303
+ if (l.type === "text" && !l.provider) {
1304
+ if (!i.presenter.voice)
1774
1305
  throw new Error("Presenter voice is not initialized");
1775
- }
1776
1306
  return {
1777
1307
  type: "text",
1778
- provider: agentEntity.presenter.voice,
1779
- input: payload.input,
1780
- ssml: payload.ssml
1308
+ provider: i.presenter.voice,
1309
+ input: l.input,
1310
+ ssml: l.ssml
1781
1311
  };
1782
1312
  }
1783
- return payload;
1784
- }
1785
- const script = getScript();
1786
- analytics.track("agent-speak", script);
1787
- timestampTracker.update();
1788
- if (((_a2 = items.chat) == null ? void 0 : _a2.id) && script.type === "text") {
1789
- items.messages.push({
1790
- id: getRandom(),
1791
- role: "assistant",
1792
- content: script.input,
1793
- created_at: new Date(timestampTracker.get(true)).toISOString()
1794
- });
1795
- (_c2 = (_b2 = options.callbacks).onNewMessage) == null ? void 0 : _c2.call(_b2, [...items.messages], "answer");
1313
+ return l;
1796
1314
  }
1797
- const isTextual = isTextualChat(items.chatMode);
1798
- if (items.chat && isTextual) {
1799
- return {
1800
- duration: 0,
1801
- status: "success"
1802
- };
1803
- }
1804
- return items.streamingManager.speak({
1805
- script,
1315
+ const y = m();
1316
+ d.track("agent-speak", y), F.update(), (T = n.chat) != null && T.id && y.type === "text" && (n.messages.push({
1317
+ id: K(),
1318
+ role: "assistant",
1319
+ content: y.input,
1320
+ created_at: new Date(F.get(!0)).toISOString()
1321
+ }), (j = (v = t.callbacks).onNewMessage) == null || j.call(v, [...n.messages], "answer"));
1322
+ const w = Pe(n.chatMode);
1323
+ return n.chat && w ? {
1324
+ duration: 0,
1325
+ status: "success"
1326
+ } : n.streamingManager.speak({
1327
+ script: y,
1806
1328
  metadata: {
1807
- chat_id: (_d = items.chat) == null ? void 0 : _d.id,
1808
- agent_id: agentEntity.id
1329
+ chat_id: (P = n.chat) == null ? void 0 : P.id,
1330
+ agent_id: i.id
1809
1331
  }
1810
1332
  });
1811
1333
  }
1812
1334
  };
1813
1335
  }
1814
- function getAgent(agentId, auth, baseURL) {
1336
+ function kt(e, t, a) {
1815
1337
  const {
1816
- getById
1817
- } = createAgentsApi(auth, baseURL || didApiUrl);
1818
- return getById(agentId);
1338
+ getById: r
1339
+ } = ce(t, a || Y);
1340
+ return r(e);
1819
1341
  }
1820
1342
  export {
1821
- AgentActivityState,
1822
- AgentStatus,
1823
- ChatCreationFailed,
1824
- ChatMode,
1825
- ChatModeDowngraded,
1826
- ChatProgress,
1827
- ConnectionState,
1828
- ConnectivityState,
1829
- DataChannelSignalMap,
1830
- DocumentType,
1831
- KnowledgeType,
1832
- PlanGroup,
1833
- Providers,
1834
- RateState,
1835
- StreamEvents,
1836
- StreamType,
1837
- StreamingState,
1838
- Subject,
1839
- UserPlan,
1840
- ValidationError,
1841
- VideoType,
1842
- VoiceAccess,
1843
- WsError,
1844
- createAgentManager,
1845
- getAgent,
1846
- mapVideoType
1343
+ X as AgentActivityState,
1344
+ ke as AgentStatus,
1345
+ he as ChatCreationFailed,
1346
+ b as ChatMode,
1347
+ we as ChatModeDowngraded,
1348
+ U as ChatProgress,
1349
+ M as ConnectionState,
1350
+ V as ConnectivityState,
1351
+ Se as DocumentType,
1352
+ Ce as KnowledgeType,
1353
+ ve as PlanGroup,
1354
+ _e as Providers,
1355
+ De as RateState,
1356
+ N as StreamEvents,
1357
+ J as StreamType,
1358
+ p as StreamingState,
1359
+ Re as Subject,
1360
+ ye as UserPlan,
1361
+ W as ValidationError,
1362
+ ae as VideoType,
1363
+ Me as VoiceAccess,
1364
+ pe as WsError,
1365
+ vt as createAgentManager,
1366
+ kt as getAgent,
1367
+ Ee as mapVideoType
1847
1368
  };