@d-id/client-sdk 1.0.19-beta.136 → 1.0.19-beta.138

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