@d-id/client-sdk 1.1.0-beta.3 → 1.1.0-beta.5

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