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

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