@d-id/client-sdk 1.0.19-beta.149 → 1.0.19-beta.150

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