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

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 he = Object.defineProperty;
2
+ var we = (e, t, a) => t in e ? he(e, t, { enumerable: !0, configurable: !0, writable: !0, value: a }) : e[t] = a;
3
+ var U = (e, t, a) => (we(e, typeof t != "symbol" ? t + "" : t, a), a);
4
+ class Q extends Error {
8
5
  constructor({
9
- kind,
10
- description,
11
- error
6
+ kind: a,
7
+ description: n,
8
+ error: o
12
9
  }) {
13
10
  super(JSON.stringify({
14
- kind,
15
- description
11
+ kind: a,
12
+ description: n
16
13
  }));
17
- __publicField(this, "kind");
18
- __publicField(this, "description");
19
- __publicField(this, "error");
20
- this.kind = kind;
21
- this.description = description;
22
- this.error = error;
14
+ U(this, "kind");
15
+ U(this, "description");
16
+ U(this, "error");
17
+ this.kind = a, this.description = n, this.error = o;
23
18
  }
24
19
  }
25
- class ChatCreationFailed extends BaseError {
26
- constructor(mode, persistent) {
20
+ class pe extends Q {
21
+ constructor(t, a) {
27
22
  super({
28
23
  kind: "ChatCreationFailed",
29
- description: `Failed to create ${persistent ? "persistent" : ""} chat, mode: ${mode}`
24
+ description: `Failed to create ${a ? "persistent" : ""} chat, mode: ${t}`
30
25
  });
31
26
  }
32
27
  }
33
- class ChatModeDowngraded extends BaseError {
34
- constructor(mode) {
28
+ class ye extends Q {
29
+ constructor(t) {
35
30
  super({
36
31
  kind: "ChatModeDowngraded",
37
- description: `Chat mode downgraded to ${mode}`
32
+ description: `Chat mode downgraded to ${t}`
38
33
  });
39
34
  }
40
35
  }
41
- class ValidationError extends BaseError {
42
- constructor(message, key) {
36
+ class x extends Q {
37
+ constructor(a, n) {
43
38
  super({
44
39
  kind: "ValidationError",
45
- description: message
40
+ description: a
46
41
  });
47
- __publicField(this, "key");
48
- this.key = key;
42
+ U(this, "key");
43
+ this.key = n;
49
44
  }
50
45
  }
51
- class WsError extends BaseError {
52
- constructor(message) {
46
+ class ve extends Q {
47
+ constructor(t) {
53
48
  super({
54
49
  kind: "WSError",
55
- description: message
50
+ description: t
56
51
  });
57
52
  }
58
53
  }
59
- var UserPlan = /* @__PURE__ */ ((UserPlan2) => {
60
- UserPlan2["TRIAL"] = "trial";
61
- UserPlan2["BASIC"] = "basic";
62
- UserPlan2["ENTERPRISE"] = "enterprise";
63
- UserPlan2["LITE"] = "lite";
64
- UserPlan2["ADVANCED"] = "advanced";
65
- return UserPlan2;
66
- })(UserPlan || {});
67
- var PlanGroup = /* @__PURE__ */ ((PlanGroup2) => {
68
- PlanGroup2["TRIAL"] = "deid-trial";
69
- PlanGroup2["PRO"] = "deid-pro";
70
- PlanGroup2["ENTERPRISE"] = "deid-enterprise";
71
- PlanGroup2["LITE"] = "deid-lite";
72
- PlanGroup2["ADVANCED"] = "deid-advanced";
73
- PlanGroup2["BUILD"] = "deid-api-build";
74
- PlanGroup2["LAUNCH"] = "deid-api-launch";
75
- PlanGroup2["SCALE"] = "deid-api-scale";
76
- return PlanGroup2;
77
- })(PlanGroup || {});
78
- var AgentStatus = /* @__PURE__ */ ((AgentStatus2) => {
79
- AgentStatus2["Created"] = "created";
80
- AgentStatus2["Started"] = "started";
81
- AgentStatus2["Done"] = "done";
82
- AgentStatus2["Error"] = "error";
83
- AgentStatus2["Rejected"] = "rejected";
84
- AgentStatus2["Ready"] = "ready";
85
- return AgentStatus2;
86
- })(AgentStatus || {});
87
- var RateState = /* @__PURE__ */ ((RateState2) => {
88
- RateState2["Unrated"] = "Unrated";
89
- RateState2["Positive"] = "Positive";
90
- RateState2["Negative"] = "Negative";
91
- return RateState2;
92
- })(RateState || {});
93
- var ChatMode = /* @__PURE__ */ ((ChatMode2) => {
94
- ChatMode2["Functional"] = "Functional";
95
- ChatMode2["TextOnly"] = "TextOnly";
96
- ChatMode2["Maintenance"] = "Maintenance";
97
- ChatMode2["Playground"] = "Playground";
98
- ChatMode2["DirectPlayback"] = "DirectPlayback";
99
- return ChatMode2;
100
- })(ChatMode || {});
101
- var ChatProgress = /* @__PURE__ */ ((ChatProgress2) => {
102
- ChatProgress2["Embed"] = "embed";
103
- ChatProgress2["Query"] = "query";
104
- ChatProgress2["Partial"] = "partial";
105
- ChatProgress2["Answer"] = "answer";
106
- ChatProgress2["Complete"] = "done";
107
- return ChatProgress2;
108
- })(ChatProgress || {});
109
- var Subject = /* @__PURE__ */ ((Subject2) => {
110
- Subject2["KnowledgeProcessing"] = "knowledge/processing";
111
- Subject2["KnowledgeIndexing"] = "knowledge/indexing";
112
- Subject2["KnowledgeFailed"] = "knowledge/error";
113
- Subject2["KnowledgeDone"] = "knowledge/done";
114
- return Subject2;
115
- })(Subject || {});
116
- var KnowledgeType = /* @__PURE__ */ ((KnowledgeType2) => {
117
- KnowledgeType2["Knowledge"] = "knowledge";
118
- KnowledgeType2["Document"] = "document";
119
- KnowledgeType2["Record"] = "record";
120
- return KnowledgeType2;
121
- })(KnowledgeType || {});
122
- var DocumentType = /* @__PURE__ */ ((DocumentType2) => {
123
- DocumentType2["Pdf"] = "pdf";
124
- DocumentType2["Text"] = "text";
125
- DocumentType2["Html"] = "html";
126
- DocumentType2["Word"] = "word";
127
- DocumentType2["Json"] = "json";
128
- DocumentType2["Markdown"] = "markdown";
129
- DocumentType2["Csv"] = "csv";
130
- DocumentType2["Excel"] = "excel";
131
- DocumentType2["Powerpoint"] = "powerpoint";
132
- DocumentType2["Archive"] = "archive";
133
- DocumentType2["Image"] = "image";
134
- DocumentType2["Audio"] = "audio";
135
- DocumentType2["Video"] = "video";
136
- return DocumentType2;
137
- })(DocumentType || {});
138
- var VideoType = /* @__PURE__ */ ((VideoType2) => {
139
- VideoType2["Clip"] = "clip";
140
- VideoType2["Talk"] = "talk";
141
- return VideoType2;
142
- })(VideoType || {});
143
- const mapVideoType = (type) => {
144
- switch (type) {
54
+ var ke = /* @__PURE__ */ ((e) => (e.TRIAL = "trial", e.BASIC = "basic", e.ENTERPRISE = "enterprise", e.LITE = "lite", e.ADVANCED = "advanced", e))(ke || {}), De = /* @__PURE__ */ ((e) => (e.TRIAL = "deid-trial", e.PRO = "deid-pro", e.ENTERPRISE = "deid-enterprise", e.LITE = "deid-lite", e.ADVANCED = "deid-advanced", e.BUILD = "deid-api-build", e.LAUNCH = "deid-api-launch", e.SCALE = "deid-api-scale", e))(De || {}), Ce = /* @__PURE__ */ ((e) => (e.Created = "created", e.Started = "started", e.Done = "done", e.Error = "error", e.Rejected = "rejected", e.Ready = "ready", e))(Ce || {}), Re = /* @__PURE__ */ ((e) => (e.Unrated = "Unrated", e.Positive = "Positive", e.Negative = "Negative", e))(Re || {}), T = /* @__PURE__ */ ((e) => (e.Functional = "Functional", e.TextOnly = "TextOnly", e.Maintenance = "Maintenance", e.Playground = "Playground", e.DirectPlayback = "DirectPlayback", e))(T || {}), J = /* @__PURE__ */ ((e) => (e.Embed = "embed", e.Query = "query", e.Partial = "partial", e.Answer = "answer", e.Complete = "done", e))(J || {}), Ee = /* @__PURE__ */ ((e) => (e.KnowledgeProcessing = "knowledge/processing", e.KnowledgeIndexing = "knowledge/indexing", e.KnowledgeFailed = "knowledge/error", e.KnowledgeDone = "knowledge/done", e))(Ee || {}), _e = /* @__PURE__ */ ((e) => (e.Knowledge = "knowledge", e.Document = "document", e.Record = "record", e))(_e || {}), Me = /* @__PURE__ */ ((e) => (e.Pdf = "pdf", e.Text = "text", e.Html = "html", e.Word = "word", e.Json = "json", e.Markdown = "markdown", e.Csv = "csv", e.Excel = "excel", e.Powerpoint = "powerpoint", e.Archive = "archive", e.Image = "image", e.Audio = "audio", e.Video = "video", e))(Me || {}), oe = /* @__PURE__ */ ((e) => (e.Clip = "clip", e.Talk = "talk", e))(oe || {});
55
+ const Se = (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 k = /* @__PURE__ */ ((e) => (e.Start = "START", e.Stop = "STOP", e))(k || {}), W = /* @__PURE__ */ ((e) => (e.Strong = "STRONG", e.Weak = "WEAK", e.Unknown = "UNKNOWN", e))(W || {}), q = /* @__PURE__ */ ((e) => (e.Idle = "IDLE", e.Talking = "TALKING", e))(q || {});
66
+ const ne = {
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 || {}), _ = /* @__PURE__ */ ((e) => (e.New = "new", e.Fail = "fail", e.Connected = "connected", e.Connecting = "connecting", e.Closed = "closed", e.Completed = "completed", e.Disconnected = "disconnected", e))(_ || {}), N = /* @__PURE__ */ ((e) => (e.Legacy = "legacy", e.Fluent = "fluent", e))(N || {}), Ie = /* @__PURE__ */ ((e) => (e.Amazon = "amazon", e.Microsoft = "microsoft", e.Afflorithmics = "afflorithmics", e.Elevenlabs = "elevenlabs", e))(Ie || {}), Te = /* @__PURE__ */ ((e) => (e.Public = "public", e.Premium = "premium", e.Private = "private", e))(Te || {});
72
+ const je = 45 * 1e3, be = "X-Playground-Chat", K = "https://api.d-id.com", Pe = "wss://notifications.d-id.com", Be = "79f81a83a67430be2bc0fd61042b8faa", ce = (e) => new Promise((t) => setTimeout(t, e)), Y = () => Math.random().toString(16).slice(2);
73
+ function $e(e, t) {
74
+ let a;
228
75
  return {
229
- promise,
230
- clear: () => clearTimeout(timeId)
76
+ promise: new Promise((o, s) => {
77
+ a = setTimeout(() => s(new Error(t)), e);
78
+ }),
79
+ clear: () => clearTimeout(a)
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 G(e, t) {
83
+ const a = {
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 n;
93
+ for (let o = 1; o <= a.limit; o++)
245
94
  try {
246
- if (!options.timeout) {
247
- return await operation();
248
- }
95
+ if (!a.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
+ } = $e(a.timeout, a.timeoutErrorMessage), i = e().finally(r);
101
+ return await Promise.race([i, s]);
102
+ } catch (s) {
103
+ if (n = s, !a.shouldRetryFn(s) || o >= a.limit)
104
+ throw s;
105
+ await ce(a.delayMs), a.onRetry(s);
262
106
  }
263
- }
264
- throw lastError;
107
+ throw n;
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 de() {
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 Le = Y();
114
+ function le(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}.${de()}_${Le}`;
121
+ throw new Error(`Unknown auth type: ${e}`);
285
122
  }
286
- const retryHttpTooManyRequests = (operation) => retryOperation(operation, {
123
+ const Ae = (e) => G(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 O(e, t = K, a) {
130
+ const n = 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 Ae(() => 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: le(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 m = await c.text().catch(() => `Failed to fetch with status ${c.status}`);
144
+ const l = new Error(m);
145
+ throw a && !r && a(l, {
146
+ url: o,
147
+ options: i,
148
+ headers: c.headers
149
+ }), l;
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 n(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 n(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 n(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 n(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 ue(e, t = K, a) {
184
+ const n = O(e, `${t}/agents`, a);
352
185
  return {
353
- create(payload, options) {
354
- return client.post(`/`, payload, options);
186
+ create(o, s) {
187
+ return n.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 n.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 n.get(`/${o}`, s);
361
194
  },
362
- delete(id, options) {
363
- return client.delete(`/${id}`, void 0, options);
195
+ delete(o, s) {
196
+ return n.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 n.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 n.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 n.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 n.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 n.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 n.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 n.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 ee = (e) => e.type === "clip" && e.presenter_id.startsWith("v2_") ? "clip_v2" : e.type;
222
+ function ze(e) {
223
+ var o, s, r, i;
224
+ const t = () => /Mobi|Android/i.test(navigator.userAgent) ? "Mobile" : "Desktop", a = () => {
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
+ }, n = e.presenter;
407
228
  return {
408
- $os: `${getUserOS()}`,
409
- isMobile: `${mobileOrDesktop() == "Mobile"}`,
229
+ $os: `${a()}`,
230
+ isMobile: `${t() == "Mobile"}`,
410
231
  browser: navigator.userAgent,
411
232
  origin: window.location.origin,
412
- agentType: getAgentType(presenter),
233
+ agentType: ee(n),
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 Ne = (e) => e.reduce((t, a) => t + a, 0), Fe = (e) => Ne(e) / e.length;
241
+ function xe(e, t, a) {
242
+ var c, m, l;
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: n,
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
+ ...(m = o == null ? void 0 : o.script) == null ? void 0 : m.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" ? (l = t == null ? void 0 : t.presenter) == null ? void 0 : l.stitch : void 0,
265
+ ...a
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 V = {};
269
+ const Je = "https://api-js.mixpanel.com/track/?verbose=1&ip=1";
270
+ function We(e) {
271
+ var s, r, i, c, m, l;
272
+ const t = window != null && window.hasOwnProperty("DID_AGENTS_API") ? "agents-ui" : "agents-sdk", a = e.agent.presenter, n = (s = e.agent.llm) == null ? void 0 : s.prompt_customization, o = {
273
+ token: e.token || "testKey",
274
+ distinct_id: e.distinctId || de(),
275
+ agentId: e.agent.id,
276
+ agentType: ee(a),
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: n == null ? void 0 : n.role,
281
+ personality: n == null ? void 0 : n.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: n == null ? void 0 : n.knowledge_source,
286
+ starterQuestionsCount: (l = (m = e.agent.knowledge) == null ? void 0 : m.starter_message) == null ? void 0 : l.length,
287
+ topicsToAvoid: n == null ? void 0 : n.topics_to_avoid,
288
+ maxResponseLength: n == null ? void 0 : n.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(g) {
296
+ const D = {};
297
+ if (g && typeof g != "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 p in g)
300
+ (typeof g[p] == "string" || typeof g[p] == "number") && (D[p] = g[p]);
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(g, 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: p,
311
+ ...y
312
+ } = D || {}, v = {
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: g,
512
320
  properties: {
513
321
  ...this.additionalProperties,
514
- ...sendProps,
515
- ...analyticProps,
516
- source,
322
+ ...y,
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,954 @@ 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(Je, v).then((C) => C.json());
337
+ } catch (C) {
338
+ return console.error(C);
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(g, D, p, y) {
342
+ V[g] || (V[g] = {
343
+ events: {},
344
+ resolvedDependencies: []
345
+ }), y.includes(p) || y.push(p);
346
+ const v = V[g];
347
+ if (v.events[p] = {
348
+ props: D
349
+ }, v.resolvedDependencies.push(p), y.every(($) => v.resolvedDependencies.includes($))) {
350
+ const $ = y.reduce((I, d) => v.events[d] ? {
351
+ ...I,
352
+ ...v.events[d].props
353
+ } : I, {});
354
+ this.track(g, $), v.resolvedDependencies = v.resolvedDependencies.filter((I) => !y.includes(I)), y.forEach((I) => {
355
+ delete v.events[I];
563
356
  });
564
357
  }
565
358
  }
566
359
  };
567
360
  }
568
- function createTimestampTracker() {
569
- let timestamp = 0;
361
+ function He() {
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 F = He();
370
+ function fe(e) {
371
+ return e === T.Playground ? {
579
372
  headers: {
580
- [PLAYGROUND_HEADER]: "true"
373
+ [be]: "true"
581
374
  }
582
375
  } : {};
583
376
  }
584
- async function createChat(agent, agentsApi, analytics, chatMode, persist = false, chat) {
377
+ async function me(e, t, a, n, 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 && n !== T.DirectPlayback && (s = await t.newChat(e.id, {
380
+ persist: o
381
+ }, fe(n)), a.track("agent-chat", {
382
+ event: "created",
383
+ chat_id: s.id,
384
+ agent_id: e.id,
385
+ mode: n
386
+ })), {
387
+ chat: s,
388
+ chatMode: (s == null ? void 0 : s.chat_mode) ?? n
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
+ var a;
403
+ const t = ((a = e.greetings) == null ? void 0 : a.filter((n) => n.length > 0)) ?? [];
404
+ return t.length > 0 ? t[Math.floor(Math.random() * t.length)] : `Hi! I'm ${e.preview_name || "My Agent"}. How can I help you?`;
620
405
  }
621
- function getInitialMessages(content, initialMessages) {
622
- if (initialMessages && initialMessages.length > 0) {
623
- return initialMessages;
624
- }
625
- return [{
626
- content,
627
- id: getRandom(),
406
+ function ae(e, t) {
407
+ return t && t.length > 0 ? t : [{
408
+ content: e,
409
+ id: Y(),
628
410
  role: "assistant",
629
411
  created_at: (/* @__PURE__ */ new Date()).toISOString()
630
412
  }];
631
413
  }
632
- function connect(options) {
633
- return new Promise((resolve, reject) => {
414
+ function Ke(e) {
415
+ return new Promise((t, a) => {
634
416
  const {
635
- callbacks,
636
- host,
637
- auth
638
- } = options;
639
- 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);
417
+ callbacks: n,
418
+ host: o,
419
+ auth: s
420
+ } = e, {
421
+ onMessage: r = null,
422
+ onOpen: i = null,
423
+ onClose: c = null,
424
+ onError: m = null
425
+ } = n || {}, l = new WebSocket(`${o}?authorization=${le(s)}`);
426
+ l.onmessage = r, l.onclose = c, l.onerror = (g) => {
427
+ console.error(g), m == null || m("Websocket failed to connect", g), a(g);
428
+ }, l.onopen = (g) => {
429
+ i == null || i(g), t(l);
656
430
  };
657
431
  });
658
432
  }
659
- async function connectWithRetries(options) {
433
+ async function qe(e) {
660
434
  const {
661
- retries = 1
662
- } = options;
663
- let socket = null;
664
- for (let attempt = 0; (socket == null ? void 0 : socket.readyState) !== WebSocket.OPEN; attempt++) {
435
+ retries: t = 1
436
+ } = e;
437
+ let a = null;
438
+ for (let n = 0; (a == null ? void 0 : a.readyState) !== WebSocket.OPEN; n++)
665
439
  try {
666
- socket = await connect(options);
667
- } catch (e) {
668
- if (attempt === retries) {
669
- throw e;
670
- }
671
- await sleep(attempt * 500);
440
+ a = await Ke(e);
441
+ } catch (o) {
442
+ if (n === t)
443
+ throw o;
444
+ await ce(n * 500);
672
445
  }
673
- }
674
- return socket;
446
+ return a;
675
447
  }
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,
448
+ async function Xe(e, t, a) {
449
+ const n = a != null && a.onMessage ? [a.onMessage] : [], o = await qe({
450
+ auth: e,
451
+ host: t,
681
452
  callbacks: {
682
- onError: (error) => {
683
- var _a;
684
- return (_a = callbacks.onError) == null ? void 0 : _a.call(callbacks, new WsError(error));
453
+ onError: (s) => {
454
+ var r;
455
+ return (r = a.onError) == null ? void 0 : r.call(a, new ve(s));
685
456
  },
686
- onMessage(event) {
687
- const parsedData = JSON.parse(event.data);
688
- messageCallbacks.forEach((callback) => callback(parsedData.event, parsedData));
457
+ onMessage(s) {
458
+ const r = JSON.parse(s.data);
459
+ n.forEach((i) => i(r.event, r));
689
460
  }
690
461
  }
691
462
  });
692
463
  return {
693
- socket,
694
- disconnect: () => socket.close(),
695
- subscribeToEvents: (callback) => messageCallbacks.push(callback)
464
+ socket: o,
465
+ disconnect: () => o.close(),
466
+ subscribeToEvents: (s) => n.push(s)
696
467
  };
697
468
  }
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;
469
+ function Ye(e) {
470
+ if (e.answer !== void 0)
471
+ return e.answer;
472
+ let t = 0, a = "";
473
+ for (; t in e; )
474
+ a += e[t++];
475
+ return a;
708
476
  }
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") {
477
+ function Qe(e, t, a, n, o) {
478
+ const s = n.messages[n.messages.length - 1];
479
+ if (!(e === J.Partial || e === J.Answer) || (s == null ? void 0 : s.role) !== "assistant")
712
480
  return;
713
- }
714
481
  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
- }
482
+ content: r,
483
+ sequence: i
484
+ } = t;
485
+ e === J.Partial ? a[i] = r : a.answer = r;
486
+ const c = Ye(a);
487
+ (s.content !== c || e === J.Answer) && (s.content = c, o == null || o([...n.messages], e));
728
488
  }
729
- function createMessageEventQueue(analytics, items, options, agentEntity, onStreamDone) {
730
- let chatEventQueue = {};
489
+ function Ve(e, t, a, n, o) {
490
+ let s = {};
731
491
  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
492
+ clearQueue: () => s = {},
493
+ onMessage: (r, i) => {
494
+ var c, m;
495
+ if ("content" in i)
496
+ Qe(r, i, s, t, a.callbacks.onNewMessage), r === J.Answer && e.track("agent-message-received", {
497
+ messages: t.messages.length,
498
+ mode: t.chatMode
749
499
  });
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();
500
+ else {
501
+ const l = X, g = [l.StreamVideoDone, l.StreamVideoError, l.StreamVideoRejected], D = [l.StreamFailed, l.StreamVideoError, l.StreamVideoRejected], p = xe(i, n, {
502
+ mode: t.chatMode
503
+ });
504
+ if (r = r, r === l.StreamVideoCreated)
505
+ e.linkTrack("agent-video", p, l.StreamVideoCreated, ["start"]);
506
+ else if (g.includes(r)) {
507
+ const y = r.split("/")[1];
508
+ D.includes(r) ? e.track("agent-video", {
509
+ ...p,
510
+ event: y
511
+ }) : e.linkTrack("agent-video", {
512
+ ...p,
513
+ event: y
514
+ }, r, ["done"]);
774
515
  }
516
+ D.includes(r) && ((m = (c = a.callbacks).onError) == null || m.call(c, new Error(`Stream failed with event ${r}`), {
517
+ data: i
518
+ })), i.event === l.StreamDone && o();
775
519
  }
776
520
  }
777
521
  };
778
522
  }
779
- function createClipApi(auth, host, agentId, onError) {
780
- const client = createClient(auth, `${host}/agents/${agentId}`, onError);
523
+ function Ge(e, t, a, n) {
524
+ const o = O(e, `${t}/agents/${a}`, n);
781
525
  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
526
+ createStream(s) {
527
+ return o.post("/streams", {
528
+ output_resolution: s.output_resolution,
529
+ compatibility_mode: s.compatibility_mode,
530
+ stream_warmup: s.stream_warmup,
531
+ session_timeout: s.session_timeout,
532
+ stream_greeting: s.stream_greeting
789
533
  });
790
534
  },
791
- startConnection(streamId, answer, sessionId) {
792
- return client.post(`/streams/${streamId}/sdp`, {
793
- session_id: sessionId,
794
- answer
535
+ startConnection(s, r, i) {
536
+ return o.post(`/streams/${s}/sdp`, {
537
+ session_id: i,
538
+ answer: r
795
539
  });
796
540
  },
797
- addIceCandidate(streamId, candidate, sessionId) {
798
- return client.post(`/streams/${streamId}/ice`, {
799
- session_id: sessionId,
800
- ...candidate
541
+ addIceCandidate(s, r, i) {
542
+ return o.post(`/streams/${s}/ice`, {
543
+ session_id: i,
544
+ ...r
801
545
  });
802
546
  },
803
- sendStreamRequest(streamId, sessionId, payload) {
804
- return client.post(`/streams/${streamId}`, {
805
- session_id: sessionId,
806
- ...payload
547
+ sendStreamRequest(s, r, i) {
548
+ return o.post(`/streams/${s}`, {
549
+ session_id: r,
550
+ ...i
807
551
  });
808
552
  },
809
- close(streamId, sessionId) {
810
- return client.delete(`/streams/${streamId}`, {
811
- session_id: sessionId
553
+ close(s, r) {
554
+ return o.delete(`/streams/${s}`, {
555
+ session_id: r
812
556
  });
813
557
  }
814
558
  };
815
559
  }
816
- function createTalkApi(auth, host, agentId, onError) {
817
- const client = createClient(auth, `${host}/agents/${agentId}`, onError);
560
+ function Ze(e, t, a, n) {
561
+ const o = O(e, `${t}/agents/${a}`, n);
818
562
  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);
563
+ createStream(s, r) {
564
+ return o.post("/streams", {
565
+ driver_url: s.driver_url,
566
+ face: s.face,
567
+ config: s.config,
568
+ output_resolution: s.output_resolution,
569
+ compatibility_mode: s.compatibility_mode,
570
+ stream_warmup: s.stream_warmup,
571
+ session_timeout: s.session_timeout,
572
+ stream_greeting: s.stream_greeting
573
+ }, r);
830
574
  },
831
- startConnection(streamId, answer, sessionId, options) {
832
- return client.post(`/streams/${streamId}/sdp`, {
833
- session_id: sessionId,
834
- answer
835
- }, options);
575
+ startConnection(s, r, i, c) {
576
+ return o.post(`/streams/${s}/sdp`, {
577
+ session_id: i,
578
+ answer: r
579
+ }, c);
836
580
  },
837
- addIceCandidate(streamId, candidate, sessionId, options) {
838
- return client.post(`/streams/${streamId}/ice`, {
839
- session_id: sessionId,
840
- ...candidate
841
- }, options);
581
+ addIceCandidate(s, r, i, c) {
582
+ return o.post(`/streams/${s}/ice`, {
583
+ session_id: i,
584
+ ...r
585
+ }, c);
842
586
  },
843
- sendStreamRequest(streamId, sessionId, payload, options) {
844
- return client.post(`/streams/${streamId}`, {
845
- session_id: sessionId,
846
- ...payload
847
- }, options);
587
+ sendStreamRequest(s, r, i, c) {
588
+ return o.post(`/streams/${s}`, {
589
+ session_id: r,
590
+ ...i
591
+ }, c);
848
592
  },
849
- close(streamId, sessionId, options) {
850
- return client.delete(`/streams/${streamId}`, {
851
- session_id: sessionId
852
- }, options);
593
+ close(s, r, i) {
594
+ return o.delete(`/streams/${s}`, {
595
+ session_id: r
596
+ }, i);
853
597
  }
854
598
  };
855
599
  }
856
- function createAggregateReport(start, end, lowFpsCount) {
857
- const duration = (end.timestamp - start.timestamp) / 1e3;
600
+ function Oe(e, t, a) {
601
+ const n = (t.timestamp - e.timestamp) / 1e3;
858
602
  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
603
+ duration: n,
604
+ bytesReceived: t.bytesReceived - e.bytesReceived,
605
+ bitrate: Math.round((t.bytesReceived - e.bytesReceived) * 8 / n),
606
+ packetsReceived: t.packetsReceived - e.packetsReceived,
607
+ packetsLost: t.packetsLost - e.packetsLost,
608
+ framesDropped: t.framesDropped - e.framesDropped,
609
+ framesDecoded: t.framesDecoded - e.framesDecoded,
610
+ jitter: t.jitter,
611
+ avgJitterDelayInInterval: (t.jitterBufferDelay - e.jitterBufferDelay) / (t.jitterBufferEmittedCount - e.jitterBufferEmittedCount),
612
+ jitterBufferEmittedCount: t.jitterBufferEmittedCount - e.jitterBufferEmittedCount,
613
+ jitterBufferDelay: (t.jitterBufferDelay - e.jitterBufferDelay) / n,
614
+ framesPerSecond: t.framesPerSecond,
615
+ freezeCount: t.freezeCount - e.freezeCount,
616
+ freezeDuration: t.freezeDuration - e.freezeDuration,
617
+ lowFpsCount: a
874
618
  };
875
619
  }
876
- function extractAnomalies(stats) {
877
- return stats.filter((report) => report.freezeCount > 0 || report.framesPerSecond < 21 || report.framesDropped > 0 || report.packetsLost > 0).map((report) => {
620
+ function et(e) {
621
+ return e.filter((t) => t.freezeCount > 0 || t.framesPerSecond < 21 || t.framesDropped > 0 || t.packetsLost > 0).map((t) => {
878
622
  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
623
+ timestamp: a,
624
+ ...n
625
+ } = t, o = [];
626
+ 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"), {
627
+ ...n,
628
+ causes: o
898
629
  };
899
630
  });
900
631
  }
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") {
632
+ function tt(e) {
633
+ let t = "";
634
+ for (const a of e.values())
635
+ if (a && a.type === "codec" && a.mimeType.startsWith("video") && (t = a.mimeType.split("/")[1]), a && a.type === "inbound-rtp" && a.kind === "video")
908
636
  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
637
+ codec: t,
638
+ timestamp: a.timestamp,
639
+ bytesReceived: a.bytesReceived,
640
+ packetsReceived: a.packetsReceived,
641
+ packetsLost: a.packetsLost,
642
+ framesDropped: a.framesDropped,
643
+ framesDecoded: a.framesDecoded,
644
+ jitter: a.jitter,
645
+ jitterBufferDelay: a.jitterBufferDelay,
646
+ jitterBufferEmittedCount: a.jitterBufferEmittedCount,
647
+ avgJitterDelayInInterval: a.jitterBufferDelay / a.jitterBufferEmittedCount,
648
+ frameWidth: a.frameWidth,
649
+ frameHeight: a.frameHeight,
650
+ framesPerSecond: a.framesPerSecond,
651
+ freezeCount: a.freezeCount,
652
+ freezeDuration: a.totalFreezesDuration
925
653
  };
926
- }
927
- }
928
654
  return {};
929
655
  }
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);
656
+ function rt(e, t, a) {
657
+ const n = e.map((i, c) => c === 0 ? a ? {
658
+ timestamp: i.timestamp,
659
+ duration: 0,
660
+ bytesReceived: i.bytesReceived - a.bytesReceived,
661
+ bitrate: (i.bytesReceived - a.bytesReceived) * 8 / (t / 1e3),
662
+ packetsReceived: i.packetsReceived - a.packetsReceived,
663
+ packetsLost: i.packetsLost - a.packetsLost,
664
+ framesDropped: i.framesDropped - a.framesDropped,
665
+ framesDecoded: i.framesDecoded - a.framesDecoded,
666
+ jitter: i.jitter,
667
+ jitterBufferDelay: i.jitterBufferDelay - a.jitterBufferDelay,
668
+ jitterBufferEmittedCount: i.jitterBufferEmittedCount - a.jitterBufferEmittedCount,
669
+ avgJitterDelayInInterval: (i.jitterBufferDelay - a.jitterBufferDelay) / (i.jitterBufferEmittedCount - a.jitterBufferEmittedCount),
670
+ framesPerSecond: i.framesPerSecond,
671
+ freezeCount: i.freezeCount - a.freezeCount,
672
+ freezeDuration: i.freezeDuration - a.freezeDuration
673
+ } : {
674
+ timestamp: i.timestamp,
675
+ duration: 0,
676
+ bytesReceived: i.bytesReceived,
677
+ bitrate: i.bytesReceived * 8 / (t / 1e3),
678
+ packetsReceived: i.packetsReceived,
679
+ packetsLost: i.packetsLost,
680
+ framesDropped: i.framesDropped,
681
+ framesDecoded: i.framesDecoded,
682
+ jitter: i.jitter,
683
+ jitterBufferDelay: i.jitterBufferDelay,
684
+ jitterBufferEmittedCount: i.jitterBufferEmittedCount,
685
+ avgJitterDelayInInterval: i.jitterBufferDelay / i.jitterBufferEmittedCount,
686
+ framesPerSecond: i.framesPerSecond,
687
+ freezeCount: i.freezeCount,
688
+ freezeDuration: i.freezeDuration
689
+ } : {
690
+ timestamp: i.timestamp,
691
+ duration: t * c / 1e3,
692
+ bytesReceived: i.bytesReceived - e[c - 1].bytesReceived,
693
+ bitrate: (i.bytesReceived - e[c - 1].bytesReceived) * 8 / (t / 1e3),
694
+ packetsReceived: i.packetsReceived - e[c - 1].packetsReceived,
695
+ packetsLost: i.packetsLost - e[c - 1].packetsLost,
696
+ framesDropped: i.framesDropped - e[c - 1].framesDropped,
697
+ framesDecoded: i.framesDecoded - e[c - 1].framesDecoded,
698
+ jitter: i.jitter,
699
+ jitterBufferDelay: i.jitterBufferDelay - e[c - 1].jitterBufferDelay,
700
+ jitterBufferEmittedCount: i.jitterBufferEmittedCount - e[c - 1].jitterBufferEmittedCount,
701
+ avgJitterDelayInInterval: (i.jitterBufferDelay - e[c - 1].jitterBufferDelay) / (i.jitterBufferEmittedCount - e[c - 1].jitterBufferEmittedCount),
702
+ framesPerSecond: i.framesPerSecond,
703
+ freezeCount: i.freezeCount - e[c - 1].freezeCount,
704
+ freezeDuration: i.freezeDuration - e[c - 1].freezeDuration
705
+ }), o = et(n), s = o.reduce((i, c) => i + (c.causes.includes("low fps") ? 1 : 0), 0), r = n.map((i) => i.avgJitterDelayInInterval);
991
706
  return {
992
707
  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)
708
+ anomalies: o,
709
+ aggregateReport: Oe(e[0], e[e.length - 1], s),
710
+ minJitterDelayInInterval: Math.min(...r),
711
+ maxJitterDelayInInterval: Math.max(...r),
712
+ avgJitterDelayInInterval: Fe(r)
998
713
  },
999
- codec: stats[0].codec,
1000
- resolution: `${stats[0].frameWidth}x${stats[0].frameHeight}`
714
+ codec: e[0].codec,
715
+ resolution: `${e[0].frameWidth}x${e[0].frameHeight}`
1001
716
  };
1002
717
  }
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;
718
+ const Z = 100, nt = Math.max(Math.ceil(400 / Z), 1), at = 0.25, it = 0.28;
719
+ function st() {
720
+ let e = 0, t, a, n = 0;
721
+ return (o) => {
722
+ for (const s of o.values())
723
+ if (s && s.type === "inbound-rtp" && s.kind === "video") {
724
+ const r = s.jitterBufferDelay, i = s.jitterBufferEmittedCount;
725
+ if (a && i > a) {
726
+ const l = r - t, g = i - a;
727
+ n = l / g;
1021
728
  }
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
729
+ t = r, a = i;
730
+ const c = s.framesDecoded, m = c - e > 0;
731
+ return e = c, {
732
+ isReceiving: m,
733
+ avgJitterDelayInInterval: n,
734
+ freezeCount: s.freezeCount
1031
735
  };
1032
736
  }
1033
- }
1034
737
  return {
1035
- isReceiving: false,
1036
- avgJitterDelayInInterval
738
+ isReceiving: !1,
739
+ avgJitterDelayInInterval: n
1037
740
  };
1038
741
  };
1039
742
  }
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();
743
+ function ot(e, t, a, n, o, s = !1, r = !1) {
744
+ const i = s ? 1 : 0;
745
+ let c = [], m, l = 0, g = !1, D = 0, p = W.Unknown, y = W.Unknown, v = 0, C = 0;
746
+ const $ = st();
1052
747
  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
- }
748
+ const I = await e.getStats(), {
749
+ isReceiving: d,
750
+ avgJitterDelayInInterval: w,
751
+ freezeCount: f
752
+ } = $(I), E = tt(I);
753
+ if (d)
754
+ l = 0, v = f - C, y = w < at ? W.Strong : w > it && v > 1 ? W.Weak : p, y !== p && (o == null || o(y), p = y, C += v, v = 0), g || (n == null || n(k.Start), r && D >= i && !t() && a(), m = c[c.length - 1], c = [], D++, g = !0), c.push(E);
755
+ else if (g && (l++, l >= nt)) {
756
+ const M = rt(c, Z, m);
757
+ n == null || n(k.Stop, M), !r && !t() && a(), g = !1;
1091
758
  }
1092
- }, interval);
759
+ }, Z);
1093
760
  }
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) {
761
+ let ge = !1;
762
+ const z = (e, t) => ge && console.log(e, t), ct = (window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection).bind(window);
763
+ function ie(e) {
764
+ switch (e) {
1099
765
  case "connected":
1100
- return ConnectionState.Connected;
766
+ return _.Connected;
1101
767
  case "checking":
1102
- return ConnectionState.Connecting;
768
+ return _.Connecting;
1103
769
  case "failed":
1104
- return ConnectionState.Fail;
770
+ return _.Fail;
1105
771
  case "new":
1106
- return ConnectionState.New;
772
+ return _.New;
1107
773
  case "closed":
1108
- return ConnectionState.Closed;
774
+ return _.Closed;
1109
775
  case "disconnected":
1110
- return ConnectionState.Disconnected;
776
+ return _.Disconnected;
1111
777
  case "completed":
1112
- return ConnectionState.Completed;
778
+ return _.Completed;
1113
779
  default:
1114
- return ConnectionState.New;
780
+ return _.New;
1115
781
  }
1116
782
  }
1117
- function handleLegacyStreamState({
1118
- statsSignal,
1119
- dataChannelSignal,
1120
- onVideoStateChange,
1121
- report
783
+ function dt({
784
+ statsSignal: e,
785
+ dataChannelSignal: t,
786
+ onVideoStateChange: a,
787
+ report: n
1122
788
  }) {
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
- }
789
+ e === k.Start && t === k.Start ? a == null || a(k.Start) : e === k.Stop && t === k.Stop && (a == null || a(k.Stop, n));
1128
790
  }
1129
- function handleFluentStreamState({
1130
- statsSignal,
1131
- dataChannelSignal,
1132
- onVideoStateChange,
1133
- onAgentActivityStateChange,
1134
- report
791
+ function lt({
792
+ statsSignal: e,
793
+ dataChannelSignal: t,
794
+ onVideoStateChange: a,
795
+ onAgentActivityStateChange: n,
796
+ report: o
1135
797
  }) {
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
- }
798
+ e === k.Start ? a == null || a(k.Start) : e === k.Stop && (a == null || a(k.Stop, o)), t === k.Start ? n == null || n(q.Talking) : t === k.Stop && (n == null || n(q.Idle));
1146
799
  }
1147
- function handleStreamState({
1148
- statsSignal,
1149
- dataChannelSignal,
1150
- onVideoStateChange,
1151
- onAgentActivityStateChange,
1152
- streamType,
1153
- report
800
+ function se({
801
+ statsSignal: e,
802
+ dataChannelSignal: t,
803
+ onVideoStateChange: a,
804
+ onAgentActivityStateChange: n,
805
+ streamType: o,
806
+ report: s
1154
807
  }) {
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
- }
808
+ o === N.Legacy ? dt({
809
+ statsSignal: e,
810
+ dataChannelSignal: t,
811
+ onVideoStateChange: a,
812
+ report: s
813
+ }) : o === N.Fluent && lt({
814
+ statsSignal: e,
815
+ dataChannelSignal: t,
816
+ onVideoStateChange: a,
817
+ onAgentActivityStateChange: n,
818
+ report: s
819
+ });
1171
820
  }
1172
- async function createStreamingManager(agentId, agent, {
1173
- debug = false,
1174
- callbacks,
1175
- auth,
1176
- baseURL = didApiUrl
821
+ async function ut(e, t, {
822
+ debug: a = !1,
823
+ callbacks: n,
824
+ auth: o,
825
+ baseURL: s = K
1177
826
  }) {
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;
827
+ ge = a;
828
+ let r = !1, i = !1, c = k.Stop, m = k.Stop, l = W.Unknown;
1184
829
  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) {
830
+ startConnection: g,
831
+ sendStreamRequest: D,
832
+ close: p,
833
+ createStream: y,
834
+ addIceCandidate: v
835
+ } = t.videoType === oe.Clip ? Ge(o, s, e, n.onError) : Ze(o, s, e, n.onError), {
836
+ id: C,
837
+ offer: $,
838
+ ice_servers: I,
839
+ session_id: d,
840
+ fluent: w
841
+ } = await y(t), f = new ct({
842
+ iceServers: I
843
+ }), E = f.createDataChannel("JanusDataChannel");
844
+ if (!d)
1203
845
  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);
846
+ const M = w ? N.Fluent : N.Legacy, S = t.stream_warmup && !w, L = () => r, b = () => {
847
+ var u;
848
+ r = !0, i && ((u = n.onConnectionStateChange) == null || u.call(n, _.Connected));
849
+ }, P = ot(f, L, b, (u, h) => se({
850
+ statsSignal: m = u,
851
+ dataChannelSignal: M === N.Legacy ? c : void 0,
852
+ onVideoStateChange: n.onVideoStateChange,
853
+ onAgentActivityStateChange: n.onAgentActivityStateChange,
854
+ report: h,
855
+ streamType: M
856
+ }), (u) => {
857
+ var h;
858
+ return (h = n.onConnectivityStateChange) == null ? void 0 : h.call(n, l);
859
+ }, S, !!t.stream_greeting);
860
+ f.onicecandidate = (u) => {
861
+ var h;
862
+ z("peerConnection.onicecandidate", u);
1229
863
  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
864
+ u.candidate && u.candidate.sdpMid && u.candidate.sdpMLineIndex !== null ? v(C, {
865
+ candidate: u.candidate.candidate,
866
+ sdpMid: u.candidate.sdpMid,
867
+ sdpMLineIndex: u.candidate.sdpMLineIndex
868
+ }, d) : v(C, {
869
+ candidate: null
870
+ }, d);
871
+ } catch (j) {
872
+ (h = n.onError) == null || h.call(n, j, {
873
+ streamId: C
1244
874
  });
1245
875
  }
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 {
876
+ }, E.onopen = () => {
877
+ i = !0, (!S && !t.stream_greeting || r) && b();
878
+ }, E.onmessage = (u) => {
879
+ u.data in ne && (c = ne[u.data], se({
880
+ statsSignal: M === N.Legacy ? m : void 0,
881
+ dataChannelSignal: c,
882
+ onVideoStateChange: n.onVideoStateChange,
883
+ onAgentActivityStateChange: n.onAgentActivityStateChange,
884
+ streamType: M
885
+ }));
886
+ }, f.oniceconnectionstatechange = () => {
887
+ var h;
888
+ z("peerConnection.oniceconnectionstatechange => " + f.iceConnectionState);
889
+ const u = ie(f.iceConnectionState);
890
+ u !== _.Connected && ((h = n.onConnectionStateChange) == null || h.call(n, u));
891
+ }, f.ontrack = (u) => {
892
+ var h;
893
+ z("peerConnection.ontrack", u), (h = n.onSrcObjectReady) == null || h.call(n, u.streams[0]);
894
+ }, await f.setRemoteDescription($), z("set remote description OK");
895
+ const R = await f.createAnswer();
896
+ return z("create answer OK"), await f.setLocalDescription(R), z("set local description OK"), await g(C, R, d), z("start connection OK"), {
1287
897
  /**
1288
898
  * Method to send request to server to get clip or talk depend on you payload
1289
899
  * @param payload
1290
900
  */
1291
- speak(payload) {
1292
- return sendStreamRequest(streamIdFromServer, session_id, payload);
901
+ speak(u) {
902
+ return D(C, d, u);
1293
903
  },
1294
904
  /**
1295
905
  * Method to close RTC connection
1296
906
  */
1297
907
  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);
908
+ var u, h, j;
909
+ if (C) {
910
+ const B = ie(f.iceConnectionState);
911
+ if (f) {
912
+ if (B === _.New) {
913
+ (u = n.onVideoStateChange) == null || u.call(n, k.Stop), clearInterval(P);
1305
914
  return;
1306
915
  }
1307
- peerConnection.close();
1308
- peerConnection.oniceconnectionstatechange = null;
1309
- peerConnection.onnegotiationneeded = null;
1310
- peerConnection.onicecandidate = null;
1311
- peerConnection.ontrack = null;
916
+ f.close(), f.oniceconnectionstatechange = null, f.onnegotiationneeded = null, f.onicecandidate = null, f.ontrack = null;
1312
917
  }
1313
918
  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);
919
+ B === _.Connected && await p(C, d).catch((A) => {
920
+ });
921
+ } catch (A) {
922
+ z("Error on close stream connection", A);
1320
923
  }
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);
924
+ (h = n.onVideoStateChange) == null || h.call(n, k.Stop), (j = n.onAgentActivityStateChange) == null || j.call(n, q.Idle), clearInterval(P);
1324
925
  }
1325
926
  },
1326
927
  /**
1327
928
  * Session identifier information, should be returned in the body of all streaming requests
1328
929
  */
1329
- sessionId: session_id,
930
+ sessionId: d,
1330
931
  /**
1331
932
  * Id of current RTC stream
1332
933
  */
1333
- streamId: streamIdFromServer,
1334
- streamType
934
+ streamId: C,
935
+ streamType: M
1335
936
  };
1336
937
  }
1337
- function getAgentStreamArgs(agent, options, greeting) {
1338
- var _a;
938
+ function ft(e, t, a) {
939
+ var o;
1339
940
  const {
1340
- streamOptions
1341
- } = options ?? {};
941
+ streamOptions: n
942
+ } = t ?? {};
1342
943
  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
944
+ videoType: Se(e.presenter.type),
945
+ output_resolution: n == null ? void 0 : n.outputResolution,
946
+ session_timeout: n == null ? void 0 : n.sessionTimeout,
947
+ stream_warmup: n == null ? void 0 : n.streamWarmup,
948
+ compatibility_mode: n == null ? void 0 : n.compatibilityMode,
949
+ stream_greeting: ee(e.presenter) !== "clip" && ((o = t == null ? void 0 : t.streamOptions) != null && o.streamGreeting) ? a : void 0
1349
950
  };
1350
951
  }
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
- }
952
+ function mt(e, t, a, n) {
953
+ F.get() > 0 && (e === k.Start ? n.linkTrack("agent-video", {
954
+ event: "start",
955
+ latency: F.get(!0)
956
+ }, "start", [X.StreamVideoCreated]) : e === k.Stop && n.linkTrack("agent-video", {
957
+ event: "stop",
958
+ is_greenscreen: t.presenter.type === "clip" && t.presenter.is_greenscreen,
959
+ background: t.presenter.type === "clip" && t.presenter.background,
960
+ ...a
961
+ }, "done", [X.StreamVideoDone]));
1367
962
  }
1368
- function connectToManager(agent, options, analytics, greeting) {
1369
- timestampTracker.reset();
1370
- return new Promise(async (resolve, reject) => {
963
+ function gt(e, t, a, n) {
964
+ return F.reset(), new Promise(async (o, s) => {
1371
965
  try {
1372
- const streamingManager = await createStreamingManager(agent.id, getAgentStreamArgs(agent, options, greeting), {
1373
- ...options,
1374
- analytics,
966
+ const r = await ut(e.id, ft(e, t, n), {
967
+ ...t,
968
+ analytics: a,
1375
969
  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
- }
970
+ ...t.callbacks,
971
+ onConnectionStateChange: (i) => {
972
+ var c, m;
973
+ (m = (c = t.callbacks).onConnectionStateChange) == null || m.call(c, i), i === _.Connected && o(r);
1383
974
  },
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);
975
+ onVideoStateChange: (i, c) => {
976
+ var m, l;
977
+ (l = (m = t.callbacks).onVideoStateChange) == null || l.call(m, i), mt(i, e, c, a);
1388
978
  }
1389
979
  }
1390
980
  });
1391
- } catch (error) {
1392
- reject(error);
981
+ } catch (r) {
982
+ s(r);
1393
983
  }
1394
984
  });
1395
985
  }
1396
- async function initializeStreamAndChat(agent, options, agentsApi, analytics, chat, greeting) {
1397
- var _a, _b, _c, _d;
986
+ async function ht(e, t, a, n, o, s) {
987
+ var m, l, g, D;
1398
988
  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);
989
+ chat: r,
990
+ chatMode: i
991
+ } = await me(e, a, n, t.mode, t.persistentChat, o);
992
+ if (i && i !== t.mode && (t.mode = i, (l = (m = t.callbacks).onModeChange) == null || l.call(m, i), i === T.TextOnly))
993
+ return (D = (g = t.callbacks).onError) == null || D.call(g, new ye(i)), {
994
+ chat: r
995
+ };
996
+ const c = await gt(e, t, n, s);
1413
997
  return {
1414
- chat: newChat,
1415
- streamingManager
998
+ chat: r,
999
+ streamingManager: c
1416
1000
  };
1417
1001
  }
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 = {
1002
+ async function pt(e, t) {
1003
+ var C, $, I;
1004
+ let a = !0;
1005
+ const n = t.mixpanelKey || Be, o = t.wsURL || Pe, s = t.baseURL || K, r = {
1425
1006
  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();
1007
+ chatMode: t.mode || T.Functional
1008
+ }, i = ue(t.auth, s, t.callbacks.onError), c = await i.getById(e), m = Ue(c), l = We({
1009
+ token: n,
1010
+ agent: c,
1011
+ isEnabled: t.enableAnalitics,
1012
+ distinctId: t.distinctId
1013
+ }), {
1014
+ onMessage: g,
1015
+ clearQueue: D
1016
+ } = Ve(l, r, t, c, () => {
1017
+ var d;
1018
+ return (d = r.socketManager) == null ? void 0 : d.disconnect();
1443
1019
  });
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", {
1020
+ r.messages = ae(m, t.initialMessages), ($ = (C = t.callbacks).onNewMessage) == null || $.call(C, [...r.messages], "answer"), l.track("agent-sdk", {
1447
1021
  event: "loaded",
1448
- ...getAnalyticsInfo(agentEntity)
1022
+ ...ze(c)
1449
1023
  });
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
- }, {
1024
+ async function p(d) {
1025
+ var L, b, P, R, u, h, j;
1026
+ (b = (L = t.callbacks).onConnectionStateChange) == null || b.call(L, _.Connecting), F.reset(), d && !a && (delete r.chat, r.messages = ae(m), (R = (P = t.callbacks).onNewMessage) == null || R.call(P, [...r.messages], "answer"));
1027
+ const w = t.mode === T.DirectPlayback ? Promise.resolve(void 0) : Xe(t.auth, o, {
1028
+ onMessage: g,
1029
+ onError: t.callbacks.onError
1030
+ }), f = G(() => ht(c, t, i, l, r.chat, d ? m : void 0), {
1466
1031
  limit: 3,
1467
- timeout: CONNECTION_RETRY_TIMEOUT_MS,
1032
+ timeout: je,
1468
1033
  timeoutErrorMessage: "Timeout initializing the stream",
1469
1034
  // 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,
1035
+ shouldRetryFn: (B) => (B == null ? void 0 : B.message) !== "Could not connect" && B.status !== 429,
1471
1036
  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);
1037
+ }).catch((B) => {
1038
+ var A, H;
1039
+ throw v(T.Maintenance), (H = (A = t.callbacks).onConnectionStateChange) == null || H.call(A, _.Fail), B;
1040
+ }), [E, {
1041
+ streamingManager: M,
1042
+ chat: S
1043
+ }] = await Promise.all([w, f]);
1044
+ S && S.id !== ((u = r.chat) == null ? void 0 : u.id) && ((j = (h = t.callbacks).onNewChat) == null || j.call(h, S.id)), r.streamingManager = M, r.socketManager = E, r.chat = S, a = !1, v((S == null ? void 0 : S.chat_mode) ?? t.mode ?? T.Functional);
1490
1045
  }
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);
1046
+ async function y() {
1047
+ var d, w, f, E;
1048
+ (d = r.socketManager) == null || d.disconnect(), await ((w = r.streamingManager) == null ? void 0 : w.disconnect()), delete r.streamingManager, delete r.socketManager, (E = (f = t.callbacks).onConnectionStateChange) == null || E.call(f, _.Disconnected);
1498
1049
  }
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
- }
1050
+ async function v(d) {
1051
+ var w, f;
1052
+ d !== r.chatMode && (l.track("agent-mode-change", {
1053
+ mode: d
1054
+ }), r.chatMode = d, r.chatMode !== T.Functional && await y(), (f = (w = t.callbacks).onModeChange) == null || f.call(w, d));
1511
1055
  }
1512
1056
  return {
1513
- agent: agentEntity,
1057
+ agent: c,
1514
1058
  getStreamType: () => {
1515
- var _a2;
1516
- return ((_a2 = items.streamingManager) == null ? void 0 : _a2.streamType) || StreamType.Legacy;
1059
+ var d;
1060
+ return (d = r.streamingManager) == null ? void 0 : d.streamType;
1517
1061
  },
1518
- starterMessages: ((_c = agentEntity.knowledge) == null ? void 0 : _c.starter_message) || [],
1519
- getSTTToken: () => agentsApi.getSTTToken(agentEntity.id),
1520
- changeMode,
1521
- enrichAnalytics: analytics.enrich,
1062
+ starterMessages: ((I = c.knowledge) == null ? void 0 : I.starter_message) || [],
1063
+ getSTTToken: () => i.getSTTToken(c.id),
1064
+ changeMode: v,
1065
+ enrichAnalytics: l.enrich,
1522
1066
  async connect() {
1523
- var _a2;
1524
- await connect2(true);
1525
- analytics.track("agent-chat", {
1067
+ var d;
1068
+ await p(!0), l.track("agent-chat", {
1526
1069
  event: "connect",
1527
- chatId: (_a2 = items.chat) == null ? void 0 : _a2.id,
1528
- agentId: agentEntity.id,
1529
- mode: items.chatMode
1070
+ chatId: (d = r.chat) == null ? void 0 : d.id,
1071
+ agentId: c.id,
1072
+ mode: r.chatMode
1530
1073
  });
1531
1074
  },
1532
1075
  async reconnect() {
1533
- var _a2;
1534
- await disconnect();
1535
- await connect2(false);
1536
- analytics.track("agent-chat", {
1076
+ var d;
1077
+ await y(), await p(!1), l.track("agent-chat", {
1537
1078
  event: "reconnect",
1538
- chatId: (_a2 = items.chat) == null ? void 0 : _a2.id,
1539
- agentId: agentEntity.id,
1540
- mode: items.chatMode
1079
+ chatId: (d = r.chat) == null ? void 0 : d.id,
1080
+ agentId: c.id,
1081
+ mode: r.chatMode
1541
1082
  });
1542
1083
  },
1543
1084
  async disconnect() {
1544
- var _a2;
1545
- await disconnect();
1546
- analytics.track("agent-chat", {
1085
+ var d;
1086
+ await y(), l.track("agent-chat", {
1547
1087
  event: "disconnect",
1548
- chatId: (_a2 = items.chat) == null ? void 0 : _a2.id,
1549
- agentId: agentEntity.id,
1550
- mode: items.chatMode
1088
+ chatId: (d = r.chat) == null ? void 0 : d.id,
1089
+ agentId: c.id,
1090
+ mode: r.chatMode
1551
1091
  });
1552
1092
  },
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
- }
1093
+ async chat(d) {
1094
+ var M, S, L, b, P;
1095
+ const w = () => {
1096
+ if (t.mode === T.DirectPlayback)
1097
+ throw new x("Direct playback is enabled, chat is disabled");
1098
+ if (d.length >= 800)
1099
+ throw new x("Message cannot be more than 800 characters");
1100
+ if (d.length === 0)
1101
+ throw new x("Message cannot be empty");
1102
+ if (r.chatMode === T.Maintenance)
1103
+ throw new x("Chat is in maintenance mode");
1104
+ if (![T.TextOnly, T.Playground].includes(r.chatMode)) {
1105
+ if (!r.streamingManager)
1106
+ throw new x("Streaming manager is not initialized");
1107
+ if (!r.chat)
1108
+ throw new x("Chat is not initialized");
1571
1109
  }
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);
1110
+ }, f = async () => {
1111
+ var R, u;
1112
+ if (!r.chat) {
1113
+ const h = await me(c, i, l, r.chatMode, t.persistentChat);
1114
+ if (!h.chat)
1115
+ throw new pe(r.chatMode, !!t.persistentChat);
1116
+ r.chat = h.chat, (u = (R = t.callbacks).onNewChat) == null || u.call(R, r.chat.id);
1582
1117
  }
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
- });
1118
+ return r.chat.id;
1119
+ }, E = async (R, u) => G(() => {
1120
+ var h, j;
1121
+ return i.chat(c.id, u, {
1122
+ chatMode: r.chatMode,
1123
+ streamId: (h = r.streamingManager) == null ? void 0 : h.streamId,
1124
+ sessionId: (j = r.streamingManager) == null ? void 0 : j.sessionId,
1125
+ messages: R.map(({
1126
+ matches: B,
1127
+ ...A
1128
+ }) => A)
1600
1129
  }, {
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
- }
1130
+ ...fe(r.chatMode),
1131
+ skipErrorHandler: !0
1616
1132
  });
1617
- };
1133
+ }, {
1134
+ limit: 2,
1135
+ shouldRetryFn: (h) => {
1136
+ var A, H, te, re;
1137
+ const j = (A = h == null ? void 0 : h.message) == null ? void 0 : A.includes("missing or invalid session_id");
1138
+ return !((H = h == null ? void 0 : h.message) == null ? void 0 : H.includes("Stream Error")) && !j ? ((re = (te = t.callbacks).onError) == null || re.call(te, h), !1) : !0;
1139
+ },
1140
+ onRetry: async () => {
1141
+ await y(), await p(!1);
1142
+ }
1143
+ });
1618
1144
  try {
1619
- clearQueue();
1620
- validateChatRequest();
1621
- items.messages.push({
1622
- id: getRandom(),
1145
+ D(), w(), r.messages.push({
1146
+ id: Y(),
1623
1147
  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(),
1148
+ content: d,
1149
+ created_at: new Date(F.update()).toISOString()
1150
+ }), (S = (M = t.callbacks).onNewMessage) == null || S.call(M, [...r.messages], "user");
1151
+ const R = await f(), u = await E([...r.messages], R);
1152
+ return r.messages.push({
1153
+ id: Y(),
1632
1154
  role: "assistant",
1633
- content: response.result || "",
1155
+ content: u.result || "",
1634
1156
  created_at: (/* @__PURE__ */ new Date()).toISOString(),
1635
- context: response.context,
1636
- matches: response.matches
1637
- });
1638
- analytics.track("agent-message-send", {
1157
+ context: u.context,
1158
+ matches: u.matches
1159
+ }), l.track("agent-message-send", {
1639
1160
  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", {
1161
+ mode: r.chatMode,
1162
+ messages: r.messages.length + 1
1163
+ }), u.result && ((b = (L = t.callbacks).onNewMessage) == null || b.call(L, [...r.messages], "answer"), l.track("agent-message-received", {
1164
+ latency: F.get(!0),
1165
+ mode: r.chatMode,
1166
+ messages: r.messages.length
1167
+ })), u;
1168
+ } catch (R) {
1169
+ throw ((P = r.messages[r.messages.length - 1]) == null ? void 0 : P.role) === "assistant" && r.messages.pop(), l.track("agent-message-send", {
1657
1170
  event: "error",
1658
- mode: items.chatMode,
1659
- messages: items.messages.length
1660
- });
1661
- throw e;
1171
+ mode: r.chatMode,
1172
+ messages: r.messages.length
1173
+ }), R;
1662
1174
  }
1663
1175
  },
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) {
1176
+ rate(d, w, f) {
1177
+ var S, L, b, P;
1178
+ const E = r.messages.find((R) => R.id === d);
1179
+ if (r.chat) {
1180
+ if (!E)
1181
+ throw new Error("Message not found");
1182
+ } else
1668
1183
  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
1184
+ const M = ((S = E.matches) == null ? void 0 : S.map((R) => [R.document_id, R.id])) ?? [];
1185
+ return l.track("agent-rate", {
1186
+ event: f ? "update" : "create",
1187
+ thumb: w === 1 ? "up" : "down",
1188
+ knowledge_id: ((L = c.knowledge) == null ? void 0 : L.id) ?? "",
1189
+ mode: r.chatMode,
1190
+ matches: M,
1191
+ score: w
1192
+ }), f ? i.updateRating(c.id, r.chat.id, f, {
1193
+ knowledge_id: ((b = c.knowledge) == null ? void 0 : b.id) ?? "",
1194
+ message_id: d,
1195
+ matches: M,
1196
+ score: w
1197
+ }) : i.createRating(c.id, r.chat.id, {
1198
+ knowledge_id: ((P = c.knowledge) == null ? void 0 : P.id) ?? "",
1199
+ message_id: d,
1200
+ matches: M,
1201
+ score: w
1694
1202
  });
1695
1203
  },
1696
- deleteRate(id) {
1697
- var _a2;
1698
- if (!items.chat) {
1204
+ deleteRate(d) {
1205
+ var w;
1206
+ if (!r.chat)
1699
1207
  throw new Error("Chat is not initialized");
1700
- }
1701
- analytics.track("agent-rate-delete", {
1208
+ return l.track("agent-rate-delete", {
1702
1209
  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);
1210
+ chat_id: (w = r.chat) == null ? void 0 : w.id,
1211
+ id: d,
1212
+ mode: r.chatMode
1213
+ }), i.deleteRating(c.id, r.chat.id, d);
1708
1214
  },
1709
- speak(payload) {
1710
- var _a2;
1711
- if (!items.streamingManager) {
1215
+ speak(d) {
1216
+ var E;
1217
+ if (!r.streamingManager)
1712
1218
  throw new Error("Please connect to the agent first");
1713
- }
1714
- function getScript() {
1715
- if (typeof payload === "string") {
1716
- if (!agentEntity.presenter.voice) {
1219
+ function w() {
1220
+ if (typeof d == "string") {
1221
+ if (!c.presenter.voice)
1717
1222
  throw new Error("Presenter voice is not initialized");
1718
- }
1719
1223
  return {
1720
1224
  type: "text",
1721
- provider: agentEntity.presenter.voice,
1722
- input: payload,
1723
- ssml: false
1225
+ provider: c.presenter.voice,
1226
+ input: d,
1227
+ ssml: !1
1724
1228
  };
1725
1229
  }
1726
- if (payload.type === "text" && !payload.provider) {
1727
- if (!agentEntity.presenter.voice) {
1230
+ if (d.type === "text" && !d.provider) {
1231
+ if (!c.presenter.voice)
1728
1232
  throw new Error("Presenter voice is not initialized");
1729
- }
1730
1233
  return {
1731
1234
  type: "text",
1732
- provider: agentEntity.presenter.voice,
1733
- input: payload.input,
1734
- ssml: payload.ssml
1235
+ provider: c.presenter.voice,
1236
+ input: d.input,
1237
+ ssml: d.ssml
1735
1238
  };
1736
1239
  }
1737
- return payload;
1240
+ return d;
1738
1241
  }
1739
- const script = getScript();
1740
- analytics.track("agent-speak", script);
1741
- timestampTracker.update();
1742
- return items.streamingManager.speak({
1743
- script,
1242
+ const f = w();
1243
+ return l.track("agent-speak", f), F.update(), r.streamingManager.speak({
1244
+ script: f,
1744
1245
  metadata: {
1745
- chat_id: (_a2 = items.chat) == null ? void 0 : _a2.id,
1746
- agent_id: agentEntity.id
1246
+ chat_id: (E = r.chat) == null ? void 0 : E.id,
1247
+ agent_id: c.id
1747
1248
  }
1748
1249
  });
1749
1250
  }
1750
1251
  };
1751
1252
  }
1752
- function getAgent(agentId, auth, baseURL) {
1253
+ function yt(e, t, a) {
1753
1254
  const {
1754
- getById
1755
- } = createAgentsApi(auth, baseURL || didApiUrl);
1756
- return getById(agentId);
1255
+ getById: n
1256
+ } = ue(t, a || K);
1257
+ return n(e);
1757
1258
  }
1758
1259
  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
1260
+ q as AgentActivityState,
1261
+ Ce as AgentStatus,
1262
+ pe as ChatCreationFailed,
1263
+ T as ChatMode,
1264
+ ye as ChatModeDowngraded,
1265
+ J as ChatProgress,
1266
+ _ as ConnectionState,
1267
+ W as ConnectivityState,
1268
+ ne as DataChannelSignalMap,
1269
+ Me as DocumentType,
1270
+ _e as KnowledgeType,
1271
+ De as PlanGroup,
1272
+ Ie as Providers,
1273
+ Re as RateState,
1274
+ X as StreamEvents,
1275
+ N as StreamType,
1276
+ k as StreamingState,
1277
+ Ee as Subject,
1278
+ ke as UserPlan,
1279
+ x as ValidationError,
1280
+ oe as VideoType,
1281
+ Te as VoiceAccess,
1282
+ ve as WsError,
1283
+ pt as createAgentManager,
1284
+ yt as getAgent,
1285
+ Se as mapVideoType
1785
1286
  };