@d-id/client-sdk 1.0.19-beta.98 → 1.0.19-beta.99
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 +117 -113
- package/dist/index.umd.cjs +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
var Z = /* @__PURE__ */ ((e) => (e.TRIAL = "trial", e.BASIC = "basic", e.ENTERPRISE = "enterprise", e.LITE = "lite", e.ADVANCED = "advanced", e))(Z || {}), G = /* @__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))(G || {}), ee = /* @__PURE__ */ ((e) => (e.Unrated = "Unrated", e.Positive = "Positive", e.Negative = "Negative", e))(ee || {}),
|
|
1
|
+
var Z = /* @__PURE__ */ ((e) => (e.TRIAL = "trial", e.BASIC = "basic", e.ENTERPRISE = "enterprise", e.LITE = "lite", e.ADVANCED = "advanced", e))(Z || {}), G = /* @__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))(G || {}), ee = /* @__PURE__ */ ((e) => (e.Unrated = "Unrated", e.Positive = "Positive", e.Negative = "Negative", e))(ee || {}), $ = /* @__PURE__ */ ((e) => (e.Functional = "Functional", e.TextOnly = "TextOnly", e.Maintenance = "Maintenance", e.Playground = "Playground", e))($ || {}), D = /* @__PURE__ */ ((e) => (e.Embed = "embed", e.Query = "query", e.Partial = "partial", e.Answer = "answer", e.Complete = "done", e))(D || {}), te = /* @__PURE__ */ ((e) => (e.KnowledgeProcessing = "knowledge/processing", e.KnowledgeIndexing = "knowledge/indexing", e.KnowledgeFailed = "knowledge/error", e.KnowledgeDone = "knowledge/done", e))(te || {}), ne = /* @__PURE__ */ ((e) => (e.Knowledge = "knowledge", e.Document = "document", e.Record = "record", e))(ne || {}), re = /* @__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))(re || {}), v = /* @__PURE__ */ ((e) => (e.Clip = "clip", e.Talk = "talk", e))(v || {}), N = /* @__PURE__ */ ((e) => (e.Start = "START", e.Stop = "STOP", e))(N || {}), A = /* @__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))(A || {}), I = /* @__PURE__ */ ((e) => (e[e.New = 0] = "New", e[e.Fail = 1] = "Fail", e[e.Connected = 2] = "Connected", e[e.Connecting = 3] = "Connecting", e[e.Terminating = 4] = "Terminating", e))(I || {}), ae = /* @__PURE__ */ ((e) => (e.Amazon = "amazon", e.Microsoft = "microsoft", e.Afflorithmics = "afflorithmics", e.Elevenlabs = "elevenlabs", e))(ae || {}), ie = /* @__PURE__ */ ((e) => (e.Public = "public", e.Premium = "premium", e.Private = "private", e))(ie || {});
|
|
2
2
|
const L = "https://api.d-id.com", se = "wss://notifications.d-id.com", oe = "79f81a83a67430be2bc0fd61042b8faa", F = () => Math.random().toString(16).slice(2);
|
|
3
3
|
function q() {
|
|
4
4
|
let e = window.localStorage.getItem("did_external_key_id");
|
|
@@ -114,11 +114,11 @@ function ge(e) {
|
|
|
114
114
|
onOpen: o = null,
|
|
115
115
|
onClose: c = null,
|
|
116
116
|
onError: h = null
|
|
117
|
-
} = a || {},
|
|
118
|
-
|
|
119
|
-
console.error(
|
|
120
|
-
},
|
|
121
|
-
o == null || o(
|
|
117
|
+
} = a || {}, M = new WebSocket(`${r}?authorization=${Q(n)}`);
|
|
118
|
+
M.onmessage = s, M.onclose = c, M.onerror = (y) => {
|
|
119
|
+
console.error(y), h == null || h("Websocket failed to connect", y), t(y);
|
|
120
|
+
}, M.onopen = (y) => {
|
|
121
|
+
o == null || o(y), i(M);
|
|
122
122
|
};
|
|
123
123
|
});
|
|
124
124
|
}
|
|
@@ -164,34 +164,34 @@ function ue(e, i, t, a) {
|
|
|
164
164
|
presenter_id: n.presenter_id,
|
|
165
165
|
compatibility_mode: n.compatibility_mode,
|
|
166
166
|
stream_warmup: n.stream_warmup,
|
|
167
|
-
type:
|
|
167
|
+
type: v.Clip
|
|
168
168
|
});
|
|
169
169
|
},
|
|
170
170
|
startConnection(n, s, o) {
|
|
171
171
|
return r.post(`/streams/${n}/sdp`, {
|
|
172
172
|
session_id: o,
|
|
173
173
|
answer: s,
|
|
174
|
-
type:
|
|
174
|
+
type: v.Clip
|
|
175
175
|
});
|
|
176
176
|
},
|
|
177
177
|
addIceCandidate(n, s, o) {
|
|
178
178
|
return r.post(`/streams/${n}/ice`, {
|
|
179
179
|
session_id: o,
|
|
180
180
|
...s,
|
|
181
|
-
type:
|
|
181
|
+
type: v.Clip
|
|
182
182
|
});
|
|
183
183
|
},
|
|
184
184
|
sendStreamRequest(n, s, o) {
|
|
185
185
|
return r.post(`/streams/${n}`, {
|
|
186
186
|
session_id: s,
|
|
187
187
|
...o,
|
|
188
|
-
type:
|
|
188
|
+
type: v.Clip
|
|
189
189
|
});
|
|
190
190
|
},
|
|
191
191
|
close(n, s) {
|
|
192
192
|
return r.delete(`/streams/${n}`, {
|
|
193
193
|
session_id: s,
|
|
194
|
-
type:
|
|
194
|
+
type: v.Clip
|
|
195
195
|
});
|
|
196
196
|
}
|
|
197
197
|
};
|
|
@@ -208,53 +208,53 @@ function me(e, i, t, a) {
|
|
|
208
208
|
compatibility_mode: n.compatibility_mode,
|
|
209
209
|
stream_warmup: n.stream_warmup,
|
|
210
210
|
output_resolution: n.output_resolution,
|
|
211
|
-
type:
|
|
211
|
+
type: v.Talk
|
|
212
212
|
}, s);
|
|
213
213
|
},
|
|
214
214
|
startConnection(n, s, o, c) {
|
|
215
215
|
return r.post(`/streams/${n}/sdp`, {
|
|
216
216
|
session_id: o,
|
|
217
217
|
answer: s,
|
|
218
|
-
type:
|
|
218
|
+
type: v.Talk
|
|
219
219
|
}, c);
|
|
220
220
|
},
|
|
221
221
|
addIceCandidate(n, s, o, c) {
|
|
222
222
|
return r.post(`/streams/${n}/ice`, {
|
|
223
223
|
session_id: o,
|
|
224
224
|
...s,
|
|
225
|
-
type:
|
|
225
|
+
type: v.Talk
|
|
226
226
|
}, c);
|
|
227
227
|
},
|
|
228
228
|
sendStreamRequest(n, s, o, c) {
|
|
229
229
|
return r.post(`/streams/${n}`, {
|
|
230
230
|
session_id: s,
|
|
231
231
|
...o,
|
|
232
|
-
type:
|
|
232
|
+
type: v.Talk
|
|
233
233
|
}, c);
|
|
234
234
|
},
|
|
235
235
|
close(n, s, o) {
|
|
236
236
|
return r.delete(`/streams/${n}`, {
|
|
237
237
|
session_id: s,
|
|
238
|
-
type:
|
|
238
|
+
type: v.Talk
|
|
239
239
|
}, o);
|
|
240
240
|
}
|
|
241
241
|
};
|
|
242
242
|
}
|
|
243
243
|
let Y = !1;
|
|
244
|
-
const
|
|
244
|
+
const E = (e, i) => Y && console.log(e, i), he = (window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection).bind(window);
|
|
245
245
|
function j(e) {
|
|
246
246
|
switch (e) {
|
|
247
247
|
case "connected":
|
|
248
|
-
return
|
|
248
|
+
return I.Connected;
|
|
249
249
|
case "checking":
|
|
250
|
-
return
|
|
250
|
+
return I.Connecting;
|
|
251
251
|
case "failed":
|
|
252
|
-
return
|
|
252
|
+
return I.Fail;
|
|
253
253
|
case "new":
|
|
254
254
|
case "closed":
|
|
255
255
|
case "disconnected":
|
|
256
256
|
default:
|
|
257
|
-
return
|
|
257
|
+
return I.New;
|
|
258
258
|
}
|
|
259
259
|
}
|
|
260
260
|
function we() {
|
|
@@ -289,88 +289,88 @@ async function pe(e, i, {
|
|
|
289
289
|
const {
|
|
290
290
|
startConnection: c,
|
|
291
291
|
sendStreamRequest: h,
|
|
292
|
-
close:
|
|
293
|
-
createStream:
|
|
294
|
-
addIceCandidate:
|
|
295
|
-
} = i.videoType ===
|
|
296
|
-
id:
|
|
292
|
+
close: M,
|
|
293
|
+
createStream: y,
|
|
294
|
+
addIceCandidate: _
|
|
295
|
+
} = i.videoType === v.Clip ? ue(r, s, e, a.onError) : me(r, s, e, a.onError), {
|
|
296
|
+
id: S,
|
|
297
297
|
offer: K,
|
|
298
|
-
ice_servers:
|
|
299
|
-
session_id:
|
|
300
|
-
} = await
|
|
301
|
-
iceServers:
|
|
298
|
+
ice_servers: O,
|
|
299
|
+
session_id: k
|
|
300
|
+
} = await y(i), f = new he({
|
|
301
|
+
iceServers: O
|
|
302
302
|
}), d = f.createDataChannel("JanusDataChannel");
|
|
303
|
-
if (!
|
|
303
|
+
if (!k)
|
|
304
304
|
throw new Error("Could not create session_id");
|
|
305
305
|
const u = fe(f, a.onVideoStateChange);
|
|
306
306
|
f.onicecandidate = (g) => {
|
|
307
|
-
|
|
307
|
+
E("peerConnection.onicecandidate", g), g.candidate && g.candidate.sdpMid && g.candidate.sdpMLineIndex !== null ? _(S, {
|
|
308
308
|
candidate: g.candidate.candidate,
|
|
309
309
|
sdpMid: g.candidate.sdpMid,
|
|
310
310
|
sdpMLineIndex: g.candidate.sdpMLineIndex
|
|
311
|
-
},
|
|
311
|
+
}, k) : _(S, {
|
|
312
312
|
candidate: null
|
|
313
|
-
},
|
|
313
|
+
}, k);
|
|
314
314
|
}, f.oniceconnectionstatechange = () => {
|
|
315
315
|
var m;
|
|
316
|
-
|
|
316
|
+
E("peerConnection.oniceconnectionstatechange => " + f.iceConnectionState);
|
|
317
317
|
const g = j(f.iceConnectionState);
|
|
318
|
-
g ===
|
|
318
|
+
g === I.Connected ? o = setTimeout(() => {
|
|
319
319
|
var w;
|
|
320
|
-
(w = a.onConnectionStateChange) == null || w.call(a,
|
|
320
|
+
(w = a.onConnectionStateChange) == null || w.call(a, I.Connected);
|
|
321
321
|
}, 5e3) : (clearTimeout(o), (m = a.onConnectionStateChange) == null || m.call(a, g));
|
|
322
322
|
}, f.ontrack = (g) => {
|
|
323
323
|
var m;
|
|
324
|
-
|
|
324
|
+
E("peerConnection.ontrack", g), (m = a.onSrcObjectReady) == null || m.call(a, g.streams[0]);
|
|
325
325
|
}, d.onmessage = (g) => {
|
|
326
326
|
var m;
|
|
327
327
|
if (d.readyState === "open") {
|
|
328
328
|
const [w, p] = g.data.split(":");
|
|
329
|
-
w ===
|
|
329
|
+
w === A.StreamReady && (clearTimeout(o), (m = a.onConnectionStateChange) == null || m.call(a, I.Connected));
|
|
330
330
|
}
|
|
331
|
-
}, await f.setRemoteDescription(K),
|
|
331
|
+
}, await f.setRemoteDescription(K), E("set remote description OK");
|
|
332
332
|
const l = await f.createAnswer();
|
|
333
|
-
return
|
|
333
|
+
return E("create answer OK"), await f.setLocalDescription(l), E("set local description OK"), await c(S, l, k), E("start connection OK"), {
|
|
334
334
|
/**
|
|
335
335
|
* Method to send request to server to get clip or talk depend on you payload
|
|
336
336
|
* @param payload
|
|
337
337
|
*/
|
|
338
338
|
speak(g) {
|
|
339
|
-
return h(
|
|
339
|
+
return h(S, k, g);
|
|
340
340
|
},
|
|
341
341
|
/**
|
|
342
342
|
* Method to close RTC connection
|
|
343
343
|
*/
|
|
344
344
|
async disconnect() {
|
|
345
345
|
var g, m, w;
|
|
346
|
-
if (
|
|
346
|
+
if (S) {
|
|
347
347
|
if (f) {
|
|
348
|
-
if (j(f.iceConnectionState) ===
|
|
348
|
+
if (j(f.iceConnectionState) === I.New) {
|
|
349
349
|
(g = a.onVideoStateChange) == null || g.call(a, N.Stop), clearInterval(u);
|
|
350
350
|
return;
|
|
351
351
|
}
|
|
352
352
|
f.close(), f.oniceconnectionstatechange = null, f.onnegotiationneeded = null, f.onicecandidate = null, f.ontrack = null;
|
|
353
353
|
}
|
|
354
354
|
try {
|
|
355
|
-
await
|
|
355
|
+
await M(S, k).catch((p) => {
|
|
356
356
|
});
|
|
357
357
|
} catch (p) {
|
|
358
|
-
|
|
358
|
+
E("Error on close stream connection", p);
|
|
359
359
|
}
|
|
360
|
-
(m = a.onConnectionStateChange) == null || m.call(a,
|
|
360
|
+
(m = a.onConnectionStateChange) == null || m.call(a, I.New), (w = a.onVideoStateChange) == null || w.call(a, N.Stop), clearInterval(u);
|
|
361
361
|
}
|
|
362
362
|
},
|
|
363
363
|
/**
|
|
364
364
|
* Session identifier information, should be returned in the body of all streaming requests
|
|
365
365
|
*/
|
|
366
|
-
sessionId:
|
|
366
|
+
sessionId: k,
|
|
367
367
|
/**
|
|
368
368
|
* Id of current RTC stream
|
|
369
369
|
*/
|
|
370
|
-
streamId:
|
|
370
|
+
streamId: S
|
|
371
371
|
};
|
|
372
372
|
}
|
|
373
|
-
function
|
|
373
|
+
function ye(e) {
|
|
374
374
|
const i = window != null && window.hasOwnProperty("DID_AGENTS_API") ? "agents-ui" : "agents-sdk", t = {
|
|
375
375
|
token: e.token || "testKey",
|
|
376
376
|
distinct_id: e.distinctId || q(),
|
|
@@ -410,7 +410,7 @@ function Me(e) {
|
|
|
410
410
|
}
|
|
411
411
|
};
|
|
412
412
|
}
|
|
413
|
-
function
|
|
413
|
+
function Me(e) {
|
|
414
414
|
var a, r, n, s, o;
|
|
415
415
|
const i = () => /Mobi|Android/i.test(navigator.userAgent) ? "Mobile" : "Desktop";
|
|
416
416
|
return {
|
|
@@ -428,21 +428,21 @@ function ve(e) {
|
|
|
428
428
|
}
|
|
429
429
|
};
|
|
430
430
|
}
|
|
431
|
-
const
|
|
431
|
+
const ve = 1080;
|
|
432
432
|
function Ce(e, i) {
|
|
433
433
|
if (e.presenter) {
|
|
434
|
-
if (e.presenter.type ===
|
|
434
|
+
if (e.presenter.type === v.Clip)
|
|
435
435
|
return {
|
|
436
|
-
videoType:
|
|
436
|
+
videoType: v.Clip,
|
|
437
437
|
driver_id: e.presenter.driver_id,
|
|
438
438
|
presenter_id: e.presenter.presenter_id,
|
|
439
439
|
stream_warmup: !0
|
|
440
440
|
};
|
|
441
441
|
} else
|
|
442
442
|
throw new Error("Presenter is not initialized");
|
|
443
|
-
const t = i || (e.presenter.stitch ?
|
|
443
|
+
const t = i || (e.presenter.stitch ? ve : void 0);
|
|
444
444
|
return {
|
|
445
|
-
videoType:
|
|
445
|
+
videoType: v.Talk,
|
|
446
446
|
source_url: e.presenter.source_url,
|
|
447
447
|
stream_warmup: !0,
|
|
448
448
|
...t && {
|
|
@@ -459,27 +459,31 @@ function U(e, i, t, a, r) {
|
|
|
459
459
|
callbacks: {
|
|
460
460
|
...i.callbacks,
|
|
461
461
|
onConnectionStateChange: async (h) => {
|
|
462
|
-
var
|
|
463
|
-
if (h ===
|
|
462
|
+
var M, y;
|
|
463
|
+
if (h === I.Connected)
|
|
464
464
|
try {
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
465
|
+
try {
|
|
466
|
+
o || (o = await t.newChat(e.id), a.track("agent-chat", {
|
|
467
|
+
event: "created",
|
|
468
|
+
chat_id: o.id,
|
|
469
|
+
agent_id: e.id
|
|
470
|
+
})), c && n({
|
|
471
|
+
chat: o,
|
|
472
|
+
streamingManager: c
|
|
473
|
+
});
|
|
474
|
+
} catch (_) {
|
|
475
|
+
console.error(_), (_ == null ? void 0 : _.kind) === "InsufficientCreditsError" && (i.mode, $.TextOnly), s("Cannot create new chat");
|
|
476
|
+
}
|
|
477
|
+
} catch (_) {
|
|
478
|
+
console.error(_), s("Cannot create new chat");
|
|
475
479
|
}
|
|
476
480
|
else
|
|
477
|
-
h ===
|
|
478
|
-
(
|
|
481
|
+
h === I.Fail && s(new Error("Cannot create connection"));
|
|
482
|
+
(y = (M = i.callbacks).onConnectionStateChange) == null || y.call(M, h);
|
|
479
483
|
},
|
|
480
484
|
onVideoStateChange(h) {
|
|
481
|
-
var
|
|
482
|
-
(
|
|
485
|
+
var M, y;
|
|
486
|
+
(y = (M = i.callbacks).onVideoStateChange) == null || y.call(M, h);
|
|
483
487
|
}
|
|
484
488
|
}
|
|
485
489
|
}).catch(s);
|
|
@@ -503,24 +507,24 @@ function B(e) {
|
|
|
503
507
|
}];
|
|
504
508
|
}
|
|
505
509
|
async function Se(e, i) {
|
|
506
|
-
var
|
|
510
|
+
var O, k, f;
|
|
507
511
|
const t = {
|
|
508
512
|
messages: [],
|
|
509
|
-
chatMode: i.mode ||
|
|
513
|
+
chatMode: i.mode || $.Functional
|
|
510
514
|
};
|
|
511
515
|
let a = -1;
|
|
512
516
|
const r = i.wsURL || se, n = i.baseURL || L, s = i.mixpanelKey || oe, o = X(i.auth, n, i.callbacks.onError), c = await o.getById(e);
|
|
513
|
-
t.messages = B(c), (
|
|
514
|
-
const h =
|
|
517
|
+
t.messages = B(c), (k = (O = i.callbacks).onNewMessage) == null || k.call(O, t.messages);
|
|
518
|
+
const h = ye({
|
|
515
519
|
token: s,
|
|
516
520
|
agent: c,
|
|
517
521
|
...i
|
|
518
522
|
});
|
|
519
523
|
h.track("agent-sdk", {
|
|
520
524
|
event: "loaded",
|
|
521
|
-
...
|
|
525
|
+
...Me(c)
|
|
522
526
|
});
|
|
523
|
-
const
|
|
527
|
+
const M = {
|
|
524
528
|
onMessage: (d, u) => {
|
|
525
529
|
var l, g, m, w;
|
|
526
530
|
if ("content" in u) {
|
|
@@ -531,34 +535,34 @@ async function Se(e, i) {
|
|
|
531
535
|
messages: t.messages.length
|
|
532
536
|
}), (g = (l = i.callbacks).onNewMessage) == null || g.call(l, t.messages);
|
|
533
537
|
} else {
|
|
534
|
-
if ([
|
|
538
|
+
if ([A.StreamVideoCreated, A.StreamVideoDone, A.StreamVideoError, A.StreamVideoRejected].includes(d)) {
|
|
535
539
|
const p = d.split("/")[1];
|
|
536
540
|
h.track("agent-video", {
|
|
537
541
|
...u,
|
|
538
542
|
event: p
|
|
539
543
|
});
|
|
540
544
|
}
|
|
541
|
-
[
|
|
545
|
+
[A.StreamFailed, A.StreamVideoError, A.StreamVideoRejected].includes(d) && ((w = (m = i.callbacks).onError) == null || w.call(m, new Error(`Stream failed with event ${d}`), {
|
|
542
546
|
data: u
|
|
543
547
|
}));
|
|
544
548
|
}
|
|
545
549
|
}
|
|
546
550
|
};
|
|
547
|
-
async function
|
|
548
|
-
var m, w, p, C,
|
|
549
|
-
const d = await J(i.auth, r,
|
|
551
|
+
async function y() {
|
|
552
|
+
var m, w, p, C, R;
|
|
553
|
+
const d = await J(i.auth, r, M), {
|
|
550
554
|
streamingManager: u,
|
|
551
555
|
chat: l
|
|
552
556
|
} = await U(c, i, o, h, t.chat);
|
|
553
|
-
a = -1, t.messages.length === 0 && (t.messages = B(c), (w = (m = i.callbacks).onNewMessage) == null || w.call(m, t.messages)), l != null && l.id && l.id !== ((p = t.chat) == null ? void 0 : p.id) && ((
|
|
554
|
-
const g = t.chat.chatMode ||
|
|
555
|
-
|
|
557
|
+
a = -1, t.messages.length === 0 && (t.messages = B(c), (w = (m = i.callbacks).onNewMessage) == null || w.call(m, t.messages)), l != null && l.id && l.id !== ((p = t.chat) == null ? void 0 : p.id) && ((R = (C = i.callbacks).onNewChat) == null || R.call(C, l == null ? void 0 : l.id)), t.streamingManager = u, t.socketManager = d, t.chat = l;
|
|
558
|
+
const g = t.chat.chatMode || $.Functional;
|
|
559
|
+
S(g), h.track("agent-chat", {
|
|
556
560
|
event: "connect",
|
|
557
561
|
chatId: l.id,
|
|
558
562
|
agentId: c.id
|
|
559
563
|
});
|
|
560
564
|
}
|
|
561
|
-
async function
|
|
565
|
+
async function _() {
|
|
562
566
|
var d, u, l, g, m;
|
|
563
567
|
(d = t.socketManager) == null || d.disconnect(), await ((u = t.streamingManager) == null ? void 0 : u.disconnect()), delete t.streamingManager, delete t.socketManager, t.messages = B(c), (g = (l = i.callbacks).onNewMessage) == null || g.call(l, t.messages), h.track("agent-chat", {
|
|
564
568
|
event: "disconnect",
|
|
@@ -566,20 +570,20 @@ async function Se(e, i) {
|
|
|
566
570
|
agentId: c.id
|
|
567
571
|
});
|
|
568
572
|
}
|
|
569
|
-
async function
|
|
573
|
+
async function S(d) {
|
|
570
574
|
var u, l;
|
|
571
575
|
d !== t.chatMode && (h.track("agent-mode-change", {
|
|
572
576
|
mode: d
|
|
573
|
-
}), t.chatMode = d, t.chatMode !==
|
|
577
|
+
}), t.chatMode = d, t.chatMode !== $.Functional && await _(), (l = (u = i.callbacks).onModeChange) == null || l.call(u, d));
|
|
574
578
|
}
|
|
575
579
|
async function K() {
|
|
576
580
|
if (!t.chat)
|
|
577
|
-
return
|
|
581
|
+
return y();
|
|
578
582
|
const {
|
|
579
583
|
streamingManager: d,
|
|
580
584
|
chat: u
|
|
581
585
|
} = await U(c, i, o, h, t.chat);
|
|
582
|
-
t.streamingManager = d,
|
|
586
|
+
t.streamingManager = d, S(t.chat.chatMode || $.Functional), h.track("agent-chat", {
|
|
583
587
|
event: "reconnect",
|
|
584
588
|
chatId: u.id,
|
|
585
589
|
agentId: c.id
|
|
@@ -588,38 +592,38 @@ async function Se(e, i) {
|
|
|
588
592
|
return {
|
|
589
593
|
agent: c,
|
|
590
594
|
starterMessages: ((f = c.knowledge) == null ? void 0 : f.starter_message) || [],
|
|
591
|
-
connect:
|
|
592
|
-
disconnect:
|
|
593
|
-
changeMode:
|
|
595
|
+
connect: y,
|
|
596
|
+
disconnect: _,
|
|
597
|
+
changeMode: S,
|
|
594
598
|
async reconnect() {
|
|
595
599
|
var m, w;
|
|
596
600
|
if (!t.chat)
|
|
597
|
-
return
|
|
601
|
+
return y();
|
|
598
602
|
(m = t.socketManager) == null || m.disconnect(), await ((w = t.streamingManager) == null ? void 0 : w.disconnect());
|
|
599
|
-
const d = await J(i.auth, r,
|
|
603
|
+
const d = await J(i.auth, r, M), {
|
|
600
604
|
streamingManager: u,
|
|
601
605
|
chat: l
|
|
602
606
|
} = await U(c, i, o, h, t.chat);
|
|
603
607
|
t.streamingManager = u, t.socketManager = d;
|
|
604
|
-
const g = t.chat.chatMode ||
|
|
605
|
-
|
|
608
|
+
const g = t.chat.chatMode || $.Functional;
|
|
609
|
+
S(g), h.track("agent-chat", {
|
|
606
610
|
event: "reconnect",
|
|
607
611
|
chatId: l.id,
|
|
608
612
|
agentId: c.id
|
|
609
613
|
});
|
|
610
614
|
},
|
|
611
615
|
async chat(d) {
|
|
612
|
-
var l, g, m, w, p, C,
|
|
616
|
+
var l, g, m, w, p, C, R, x, W;
|
|
613
617
|
const u = F();
|
|
614
618
|
try {
|
|
615
|
-
const
|
|
619
|
+
const P = Date.now();
|
|
616
620
|
if (d.length >= 800)
|
|
617
621
|
throw new Error("Message cannot be more than 800 characters");
|
|
618
622
|
if (d.length === 0)
|
|
619
623
|
throw new Error("Message cannot be empty");
|
|
620
|
-
if (t.chatMode ===
|
|
624
|
+
if (t.chatMode === $.Maintenance)
|
|
621
625
|
throw new Error("Chat is in maintenance mode");
|
|
622
|
-
if (![
|
|
626
|
+
if (![$.TextOnly, $.Playground].includes(t.chatMode))
|
|
623
627
|
if (t.streamingManager) {
|
|
624
628
|
if (!t.chat)
|
|
625
629
|
throw new Error("Chat is not initialized");
|
|
@@ -629,7 +633,7 @@ async function Se(e, i) {
|
|
|
629
633
|
id: F(),
|
|
630
634
|
role: "user",
|
|
631
635
|
content: d,
|
|
632
|
-
created_at: new Date(
|
|
636
|
+
created_at: new Date(P).toISOString()
|
|
633
637
|
}), (g = (l = i.callbacks).onNewMessage) == null || g.call(l, t.messages), t.chat || (t.chat = await o.newChat(c.id));
|
|
634
638
|
const b = {
|
|
635
639
|
id: u,
|
|
@@ -652,7 +656,7 @@ async function Se(e, i) {
|
|
|
652
656
|
if ((p = z == null ? void 0 : z.message) != null && p.includes("missing or invalid session_id"))
|
|
653
657
|
console.log("Invalid stream, try reconnect with new stream id"), await K(), T = await o.chat(c.id, t.chat.id, {
|
|
654
658
|
sessionId: (C = t.streamingManager) == null ? void 0 : C.sessionId,
|
|
655
|
-
streamId: (
|
|
659
|
+
streamId: (R = t.streamingManager) == null ? void 0 : R.streamId,
|
|
656
660
|
messages: H,
|
|
657
661
|
chatMode: t.chatMode
|
|
658
662
|
});
|
|
@@ -663,18 +667,18 @@ async function Se(e, i) {
|
|
|
663
667
|
event: "success",
|
|
664
668
|
messages: t.messages.length + 1
|
|
665
669
|
}), b.context = T.context, T.result && (b.content = T.result, b.matches = T.matches, h.track("agent-message-received", {
|
|
666
|
-
latency: Date.now() -
|
|
670
|
+
latency: Date.now() - P,
|
|
667
671
|
messages: t.messages.length
|
|
668
672
|
}), (W = (x = i.callbacks).onNewMessage) == null || W.call(x, t.messages)), T;
|
|
669
|
-
} catch (
|
|
673
|
+
} catch (P) {
|
|
670
674
|
throw t.messages[t.messages.length - 1].id === u && t.messages.pop(), h.track("agent-message-send", {
|
|
671
675
|
event: "error",
|
|
672
676
|
messages: t.messages.length
|
|
673
|
-
}),
|
|
677
|
+
}), P;
|
|
674
678
|
}
|
|
675
679
|
},
|
|
676
680
|
rate(d, u, l) {
|
|
677
|
-
var w, p, C,
|
|
681
|
+
var w, p, C, R;
|
|
678
682
|
const g = t.messages.find((x) => x.id === d);
|
|
679
683
|
if (t.chat) {
|
|
680
684
|
if (!g)
|
|
@@ -694,7 +698,7 @@ async function Se(e, i) {
|
|
|
694
698
|
matches: m,
|
|
695
699
|
score: u
|
|
696
700
|
}) : o.createRating(c.id, t.chat.id, {
|
|
697
|
-
knowledge_id: ((
|
|
701
|
+
knowledge_id: ((R = c.knowledge) == null ? void 0 : R.id) ?? "",
|
|
698
702
|
message_id: d,
|
|
699
703
|
matches: m,
|
|
700
704
|
score: u
|
|
@@ -744,19 +748,19 @@ async function Se(e, i) {
|
|
|
744
748
|
};
|
|
745
749
|
}
|
|
746
750
|
export {
|
|
747
|
-
|
|
751
|
+
$ as ChatMode,
|
|
748
752
|
D as ChatProgress,
|
|
749
|
-
|
|
753
|
+
I as ConnectionState,
|
|
750
754
|
re as DocumentType,
|
|
751
755
|
ne as KnowledgeType,
|
|
752
756
|
G as PlanGroup,
|
|
753
757
|
ae as Providers,
|
|
754
758
|
ee as RateState,
|
|
755
|
-
|
|
759
|
+
A as StreamEvents,
|
|
756
760
|
N as StreamingState,
|
|
757
761
|
te as Subject,
|
|
758
762
|
Z as UserPlan,
|
|
759
|
-
|
|
763
|
+
v as VideoType,
|
|
760
764
|
ie as VoiceAccess,
|
|
761
765
|
Se as createAgentManager,
|
|
762
766
|
_e as getAgent
|
package/dist/index.umd.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(function(f,b){typeof exports=="object"&&typeof module<"u"?b(exports):typeof define=="function"&&define.amd?define(["exports"],b):(f=typeof globalThis<"u"?globalThis:f||self,b(f.index={}))})(this,function(f){"use strict";var b=(e=>(e.TRIAL="trial",e.BASIC="basic",e.ENTERPRISE="enterprise",e.LITE="lite",e.ADVANCED="advanced",e))(b||{}),H=(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))(H||{}),J=(e=>(e.Unrated="Unrated",e.Positive="Positive",e.Negative="Negative",e))(J||{}),A=(e=>(e.Functional="Functional",e.TextOnly="TextOnly",e.Maintenance="Maintenance",e.Playground="Playground",e))(A||{}),L=(e=>(e.Embed="embed",e.Query="query",e.Partial="partial",e.Answer="answer",e.Complete="done",e))(L||{}),q=(e=>(e.KnowledgeProcessing="knowledge/processing",e.KnowledgeIndexing="knowledge/indexing",e.KnowledgeFailed="knowledge/error",e.KnowledgeDone="knowledge/done",e))(q||{}),Q=(e=>(e.Knowledge="knowledge",e.Document="document",e.Record="record",e))(Q||{}),X=(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))(X||{}),v=(e=>(e.Clip="clip",e.Talk="talk",e))(v||{}),x=(e=>(e.Start="START",e.Stop="STOP",e))(x||{}),k=(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))(k||{}),_=(e=>(e[e.New=0]="New",e[e.Fail=1]="Fail",e[e.Connected=2]="Connected",e[e.Connecting=3]="Connecting",e[e.Terminating=4]="Terminating",e))(_||{}),Y=(e=>(e.Amazon="amazon",e.Microsoft="microsoft",e.Afflorithmics="afflorithmics",e.Elevenlabs="elevenlabs",e))(Y||{}),Z=(e=>(e.Public="public",e.Premium="premium",e.Private="private",e))(Z||{});const O="https://api.d-id.com",oe="wss://notifications.d-id.com",ce="79f81a83a67430be2bc0fd61042b8faa",D=()=>Math.random().toString(16).slice(2);function G(){let e=window.localStorage.getItem("did_external_key_id");return e||(e=Math.random().toString(16).slice(2),window.localStorage.setItem("did_external_key_id",e)),e}let de=D();function ee(e){if(e.type==="bearer")return`Bearer ${e.token}`;if(e.type==="basic")return`Basic ${btoa(`${e.username}:${e.password}`)}`;if(e.type==="key")return`Client-Key ${e.clientKey}.${G()}_${de}`;throw new Error(`Unknown auth type: ${e}`)}function V(e,i=O,t){const a=async(r,n)=>{const s=await fetch(i+(r!=null&&r.startsWith("/")?r:`/${r}`),{...n,headers:{...n==null?void 0:n.headers,Authorization:ee(e),"Content-Type":"application/json"}});if(!s.ok){let o=await s.text().catch(()=>"Failed to fetch");throw t&&t(new Error(o),{url:r,options:n,headers:s.headers}),new Error(o)}return s.json()};return{get(r,n){return a(r,{...n,method:"GET"})},post(r,n,s){return a(r,{...s,body:JSON.stringify(n),method:"POST"})},delete(r,n,s){return a(r,{...s,body:JSON.stringify(n),method:"DELETE"})},patch(r,n,s){return a(r,{...s,body:JSON.stringify(n),method:"PATCH"})}}}function te(e,i=O,t){const a=V(e,`${i}/agents`,t);return{create(r,n){return a.post("/",r,n)},getAgents(r,n){return a.get(`/${r?`?tag=${r}`:""}`,n).then(s=>s??[])},getById(r,n){return a.get(`/${r}`,n)},delete(r,n){return a.delete(`/${r}`,void 0,n)},update(r,n,s){return a.patch(`/${r}`,n,s)},newChat(r,n){return a.post(`/${r}/chat`,void 0,n)},chat(r,n,s,o){return a.post(`/${r}/chat/${n}`,s,o)},getChatMode(r,n,s){return a.get(`/${r}/chat/${n}/mode`,s)},createRating(r,n,s,o){return a.post(`/${r}/chat/${n}/ratings`,s,o)},updateRating(r,n,s,o,c){return a.patch(`/${r}/chat/${n}/ratings/${s}`,o,c)},deleteRating(r,n,s,o){return a.delete(`/${r}/chat/${n}/ratings/${s}`,o)}}}const ge=e=>new Promise(i=>setTimeout(i,e));function le(e){return new Promise((i,t)=>{const{callbacks:a,host:r,auth:n}=e,{onMessage:s=null,onOpen:o=null,onClose:c=null,onError:h=null}=a||{},C=new WebSocket(`${r}?authorization=${ee(n)}`);C.onmessage=s,C.onclose=c,C.onerror=M=>{console.error(M),h==null||h("Websocket failed to connect",M),t(M)},C.onopen=M=>{o==null||o(M),i(C)}})}async function ue(e){const{retries:i=1}=e;let t=null;for(let a=0;(t==null?void 0:t.readyState)!==WebSocket.OPEN;a++)try{t=await le(e)}catch(r){if(a===i)throw r;await ge(a*500)}return t}async function ne(e,i,t){const a=t!=null&&t.onMessage?[t.onMessage]:[],r=await ue({auth:e,host:i,callbacks:{onError:t==null?void 0:t.onError,onMessage:n=>{const s=JSON.parse(n.data);a.forEach(o=>o(s.event,s))}}});return{socket:r,disconnect:()=>r.close(),subscribeToEvents:n=>a.push(n)}}function me(e,i,t,a){const r=V(e,`${i}/agents/${t}`,a);return{createStream(n){return r.post("/streams",{driver_id:n.driver_id,presenter_id:n.presenter_id,compatibility_mode:n.compatibility_mode,stream_warmup:n.stream_warmup,type:v.Clip})},startConnection(n,s,o){return r.post(`/streams/${n}/sdp`,{session_id:o,answer:s,type:v.Clip})},addIceCandidate(n,s,o){return r.post(`/streams/${n}/ice`,{session_id:o,...s,type:v.Clip})},sendStreamRequest(n,s,o){return r.post(`/streams/${n}`,{session_id:s,...o,type:v.Clip})},close(n,s){return r.delete(`/streams/${n}`,{session_id:s,type:v.Clip})}}}function he(e,i,t,a){const r=V(e,`${i}/agents/${t}`,a);return{createStream(n,s){return r.post("/streams",{source_url:n.source_url,driver_url:n.driver_url,face:n.face,config:n.config,compatibility_mode:n.compatibility_mode,stream_warmup:n.stream_warmup,output_resolution:n.output_resolution,type:v.Talk},s)},startConnection(n,s,o,c){return r.post(`/streams/${n}/sdp`,{session_id:o,answer:s,type:v.Talk},c)},addIceCandidate(n,s,o,c){return r.post(`/streams/${n}/ice`,{session_id:o,...s,type:v.Talk},c)},sendStreamRequest(n,s,o,c){return r.post(`/streams/${n}`,{session_id:s,...o,type:v.Talk},c)},close(n,s,o){return r.delete(`/streams/${n}`,{session_id:s,type:v.Talk},o)}}}let re=!1;const R=(e,i)=>re&&console.log(e,i),we=(window.RTCPeerConnection||window.webkitRTCPeerConnection||window.mozRTCPeerConnection).bind(window);function ae(e){switch(e){case"connected":return _.Connected;case"checking":return _.Connecting;case"failed":return _.Fail;case"new":case"closed":case"disconnected":default:return _.New}}function fe(){let e=0;return i=>{for(const t of i.values())if(t&&t.type==="inbound-rtp"&&t.kind==="video"){const a=t.bytesReceived,r=a-e>0;return e=a,r}return!1}}function pe(e,i){const a=Math.max(Math.ceil(10),1);let r=0,n=!1;const s=fe();return setInterval(async()=>{const o=await e.getStats();s(o)?(r=0,n||(i==null||i(x.Start),n=!0)):n&&(r++,r>=a&&(i==null||i(x.Stop),n=!1))},100)}async function ye(e,i,{debug:t=!1,callbacks:a,auth:r,analytics:n,baseURL:s=O}){re=t;let o;const{startConnection:c,sendStreamRequest:h,close:C,createStream:M,addIceCandidate:T}=i.videoType===v.Clip?me(r,s,e,a.onError):he(r,s,e,a.onError),{id:I,offer:W,ice_servers:z,session_id:$}=await M(i),p=new we({iceServers:z}),d=p.createDataChannel("JanusDataChannel");if(!$)throw new Error("Could not create session_id");const u=pe(p,a.onVideoStateChange);p.onicecandidate=g=>{R("peerConnection.onicecandidate",g),g.candidate&&g.candidate.sdpMid&&g.candidate.sdpMLineIndex!==null?T(I,{candidate:g.candidate.candidate,sdpMid:g.candidate.sdpMid,sdpMLineIndex:g.candidate.sdpMLineIndex},$):T(I,{candidate:null},$)},p.oniceconnectionstatechange=()=>{var m;R("peerConnection.oniceconnectionstatechange => "+p.iceConnectionState);const g=ae(p.iceConnectionState);g===_.Connected?o=setTimeout(()=>{var w;(w=a.onConnectionStateChange)==null||w.call(a,_.Connected)},5e3):(clearTimeout(o),(m=a.onConnectionStateChange)==null||m.call(a,g))},p.ontrack=g=>{var m;R("peerConnection.ontrack",g),(m=a.onSrcObjectReady)==null||m.call(a,g.streams[0])},d.onmessage=g=>{var m;if(d.readyState==="open"){const[w,y]=g.data.split(":");w===k.StreamReady&&(clearTimeout(o),(m=a.onConnectionStateChange)==null||m.call(a,_.Connected))}},await p.setRemoteDescription(W),R("set remote description OK");const l=await p.createAnswer();return R("create answer OK"),await p.setLocalDescription(l),R("set local description OK"),await c(I,l,$),R("start connection OK"),{speak(g){return h(I,$,g)},async disconnect(){var g,m,w;if(I){if(p){if(ae(p.iceConnectionState)===_.New){(g=a.onVideoStateChange)==null||g.call(a,x.Stop),clearInterval(u);return}p.close(),p.oniceconnectionstatechange=null,p.onnegotiationneeded=null,p.onicecandidate=null,p.ontrack=null}try{await C(I,$).catch(y=>{})}catch(y){R("Error on close stream connection",y)}(m=a.onConnectionStateChange)==null||m.call(a,_.New),(w=a.onVideoStateChange)==null||w.call(a,x.Stop),clearInterval(u)}},sessionId:$,streamId:I}}function Me(e){const i=window!=null&&window.hasOwnProperty("DID_AGENTS_API")?"agents-ui":"agents-sdk",t={token:e.token||"testKey",distinct_id:e.distinctId||G(),isEnabled:e.isEnabled??!0,agentId:e.agent.id,owner_id:e.agent.owner_id??""};return{...t,getRandom:()=>Math.random().toString(16).slice(2),track(a,r){if(!this.isEnabled)return Promise.reject("MixPanel analytics is disabled on creation");const n={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({data:JSON.stringify([{event:a,properties:{...r,...t,source:i,time:Date.now(),$insert_id:this.getRandom(),origin:window.location.href,"Screen Height":window.screen.height||window.innerWidth,"Screen Width":window.screen.width||window.innerHeight,"User Agent":navigator.userAgent}}])})};return fetch("https://api-js.mixpanel.com/track/?verbose=1&ip=1",n).then(s=>s.json()).catch(s=>console.error(s))}}}function ve(e){var a,r,n,s,o;const i=()=>/Mobi|Android/i.test(navigator.userAgent)?"Mobile":"Desktop";return{$os:`${(()=>{const c=navigator.platform;return c.toLowerCase().includes("win")?"Windows":c.toLowerCase().includes("mac")?"Mac OS X":c.toLowerCase().includes("linux")?"Linux":"Unknown"})()}`,isMobile:`${i()=="Mobile"}`,browser:navigator.userAgent,origin:window.location.origin,agentType:(a=e.presenter)==null?void 0:a.type,agentVoice:{voiceId:(n=(r=e.presenter)==null?void 0:r.voice)==null?void 0:n.voice_id,provider:(o=(s=e.presenter)==null?void 0:s.voice)==null?void 0:o.type}}}const Ce=1080;function Se(e,i){if(e.presenter){if(e.presenter.type===v.Clip)return{videoType:v.Clip,driver_id:e.presenter.driver_id,presenter_id:e.presenter.presenter_id,stream_warmup:!0}}else throw new Error("Presenter is not initialized");const t=i||(e.presenter.stitch?Ce:void 0);return{videoType:v.Talk,source_url:e.presenter.source_url,stream_warmup:!0,...t&&{output_resolution:t}}}function B(e,i,t,a,r){return new Promise(async(n,s)=>{let o=r;const c=await ye(e.id,Se(e,i.outputResolution),{...i,analytics:a,callbacks:{...i.callbacks,onConnectionStateChange:async h=>{var C,M;if(h===_.Connected)try{o||(o=await t.newChat(e.id),a.track("agent-chat",{event:"created",chat_id:o.id,agent_id:e.id})),c&&n({chat:o,streamingManager:c})}catch(T){console.error(T),s("Cannot create new chat")}else h===_.Fail&&s(new Error("Cannot create connection"));(M=(C=i.callbacks).onConnectionStateChange)==null||M.call(C,h)},onVideoStateChange(h){var C,M;(M=(C=i.callbacks).onVideoStateChange)==null||M.call(C,h)}}}).catch(s)})}function _e(e,i,t){return te(i,t||O).getById(e)}function j(e){let i="";if(e.greetings&&e.greetings.length>0){const t=Math.floor(Math.random()*e.greetings.length);i=e.greetings[t]}else i=`Hi! I'm ${e.preview_name||"My Agent"}. How can I help you?`;return[{content:i,id:D(),role:"assistant",created_at:new Date().toISOString()}]}async function Ie(e,i){var z,$,p;const t={messages:[],chatMode:i.mode||A.Functional};let a=-1;const r=i.wsURL||oe,n=i.baseURL||O,s=i.mixpanelKey||ce,o=te(i.auth,n,i.callbacks.onError),c=await o.getById(e);t.messages=j(c),($=(z=i.callbacks).onNewMessage)==null||$.call(z,t.messages);const h=Me({token:s,agent:c,...i});h.track("agent-sdk",{event:"loaded",...ve(c)});const C={onMessage:(d,u)=>{var l,g,m,w;if("content"in u){const{content:y}=u,S=t.messages[t.messages.length-1];(S==null?void 0:S.role)==="assistant"&&(a<t.messages.length&&(S.content=d===L.Partial?S.content+y:y),d===L.Answer&&(a=t.messages.length)),d===L.Answer&&h.track("agent-message-received",{messages:t.messages.length}),(g=(l=i.callbacks).onNewMessage)==null||g.call(l,t.messages)}else{if([k.StreamVideoCreated,k.StreamVideoDone,k.StreamVideoError,k.StreamVideoRejected].includes(d)){const y=d.split("/")[1];h.track("agent-video",{...u,event:y})}[k.StreamFailed,k.StreamVideoError,k.StreamVideoRejected].includes(d)&&((w=(m=i.callbacks).onError)==null||w.call(m,new Error(`Stream failed with event ${d}`),{data:u}))}}};async function M(){var m,w,y,S,E;const d=await ne(i.auth,r,C),{streamingManager:u,chat:l}=await B(c,i,o,h,t.chat);a=-1,t.messages.length===0&&(t.messages=j(c),(w=(m=i.callbacks).onNewMessage)==null||w.call(m,t.messages)),l!=null&&l.id&&l.id!==((y=t.chat)==null?void 0:y.id)&&((E=(S=i.callbacks).onNewChat)==null||E.call(S,l==null?void 0:l.id)),t.streamingManager=u,t.socketManager=d,t.chat=l;const g=t.chat.chatMode||A.Functional;I(g),h.track("agent-chat",{event:"connect",chatId:l.id,agentId:c.id})}async function T(){var d,u,l,g,m;(d=t.socketManager)==null||d.disconnect(),await((u=t.streamingManager)==null?void 0:u.disconnect()),delete t.streamingManager,delete t.socketManager,t.messages=j(c),(g=(l=i.callbacks).onNewMessage)==null||g.call(l,t.messages),h.track("agent-chat",{event:"disconnect",chatId:(m=t.chat)==null?void 0:m.id,agentId:c.id})}async function I(d){var u,l;d!==t.chatMode&&(h.track("agent-mode-change",{mode:d}),t.chatMode=d,t.chatMode!==A.Functional&&await T(),(l=(u=i.callbacks).onModeChange)==null||l.call(u,d))}async function W(){if(!t.chat)return M();const{streamingManager:d,chat:u}=await B(c,i,o,h,t.chat);t.streamingManager=d,I(t.chat.chatMode||A.Functional),h.track("agent-chat",{event:"reconnect",chatId:u.id,agentId:c.id})}return{agent:c,starterMessages:((p=c.knowledge)==null?void 0:p.starter_message)||[],connect:M,disconnect:T,changeMode:I,async reconnect(){var m,w;if(!t.chat)return M();(m=t.socketManager)==null||m.disconnect(),await((w=t.streamingManager)==null?void 0:w.disconnect());const d=await ne(i.auth,r,C),{streamingManager:u,chat:l}=await B(c,i,o,h,t.chat);t.streamingManager=u,t.socketManager=d;const g=t.chat.chatMode||A.Functional;I(g),h.track("agent-chat",{event:"reconnect",chatId:l.id,agentId:c.id})},async chat(d){var l,g,m,w,y,S,E,N,ie;const u=D();try{const F=Date.now();if(d.length>=800)throw new Error("Message cannot be more than 800 characters");if(d.length===0)throw new Error("Message cannot be empty");if(t.chatMode===A.Maintenance)throw new Error("Chat is in maintenance mode");if(![A.TextOnly,A.Playground].includes(t.chatMode))if(t.streamingManager){if(!t.chat)throw new Error("Chat is not initialized")}else throw new Error("Streaming manager is not initialized");t.messages.push({id:D(),role:"user",content:d,created_at:new Date(F).toISOString()}),(g=(l=i.callbacks).onNewMessage)==null||g.call(l,t.messages),t.chat||(t.chat=await o.newChat(c.id));const K={id:u,role:"assistant",content:"",created_at:new Date().toISOString(),matches:[]};t.messages.push(K);const se=t.messages.slice(0,-1);let P;try{P=await o.chat(c.id,t.chat.id,{sessionId:(m=t.streamingManager)==null?void 0:m.sessionId,streamId:(w=t.streamingManager)==null?void 0:w.streamId,messages:se,chatMode:t.chatMode})}catch(U){if((y=U==null?void 0:U.message)!=null&&y.includes("missing or invalid session_id"))console.log("Invalid stream, try reconnect with new stream id"),await W(),P=await o.chat(c.id,t.chat.id,{sessionId:(S=t.streamingManager)==null?void 0:S.sessionId,streamId:(E=t.streamingManager)==null?void 0:E.streamId,messages:se,chatMode:t.chatMode});else throw U}return h.track("agent-message-send",{event:"success",messages:t.messages.length+1}),K.context=P.context,P.result&&(K.content=P.result,K.matches=P.matches,h.track("agent-message-received",{latency:Date.now()-F,messages:t.messages.length}),(ie=(N=i.callbacks).onNewMessage)==null||ie.call(N,t.messages)),P}catch(F){throw t.messages[t.messages.length-1].id===u&&t.messages.pop(),h.track("agent-message-send",{event:"error",messages:t.messages.length}),F}},rate(d,u,l){var w,y,S,E;const g=t.messages.find(N=>N.id===d);if(t.chat){if(!g)throw new Error("Message not found")}else throw new Error("Chat is not initialized");const m=((w=g.matches)==null?void 0:w.map(N=>[N.document_id,N.id]))??[];return h.track("agent-rate",{event:l?"update":"create",thumb:u===1?"up":"down",knowledge_id:((y=c.knowledge)==null?void 0:y.id)??"",matches:m,score:u}),l?o.updateRating(c.id,t.chat.id,l,{knowledge_id:((S=c.knowledge)==null?void 0:S.id)??"",message_id:d,matches:m,score:u}):o.createRating(c.id,t.chat.id,{knowledge_id:((E=c.knowledge)==null?void 0:E.id)??"",message_id:d,matches:m,score:u})},getChatmode(){if(!t.chat)throw new Error("Chat is not initialized");return o.getChatMode(c.id,t.chat.id)},deleteRate(d){var u;if(!t.chat)throw new Error("Chat is not initialized");return h.track("agent-rate-delete",{type:"text",chat_id:(u=t.chat)==null?void 0:u.id,id:d}),o.deleteRating(c.id,t.chat.id,d)},speak(d){if(!t.streamingManager)throw new Error("Streaming manager is not initialized");function u(){if(c.presenter){if(d.type==="text")return{type:"text",provider:d.provider?d.provider:c.presenter.voice,input:d.input,ssml:d.ssml||!1};if(d.type==="audio")return{type:"audio",audio_url:d.audio_url}}else throw new Error("Presenter is not initialized");throw new Error("Invalid payload")}const l=u();return h.track("agent-speak",l),t.streamingManager.speak({script:l})}}}f.ChatMode=A,f.ChatProgress=L,f.ConnectionState=_,f.DocumentType=X,f.KnowledgeType=Q,f.PlanGroup=H,f.Providers=Y,f.RateState=J,f.StreamEvents=k,f.StreamingState=x,f.Subject=q,f.UserPlan=b,f.VideoType=v,f.VoiceAccess=Z,f.createAgentManager=Ie,f.getAgent=_e,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
(function(f,x){typeof exports=="object"&&typeof module<"u"?x(exports):typeof define=="function"&&define.amd?define(["exports"],x):(f=typeof globalThis<"u"?globalThis:f||self,x(f.index={}))})(this,function(f){"use strict";var x=(e=>(e.TRIAL="trial",e.BASIC="basic",e.ENTERPRISE="enterprise",e.LITE="lite",e.ADVANCED="advanced",e))(x||{}),H=(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))(H||{}),J=(e=>(e.Unrated="Unrated",e.Positive="Positive",e.Negative="Negative",e))(J||{}),k=(e=>(e.Functional="Functional",e.TextOnly="TextOnly",e.Maintenance="Maintenance",e.Playground="Playground",e))(k||{}),b=(e=>(e.Embed="embed",e.Query="query",e.Partial="partial",e.Answer="answer",e.Complete="done",e))(b||{}),q=(e=>(e.KnowledgeProcessing="knowledge/processing",e.KnowledgeIndexing="knowledge/indexing",e.KnowledgeFailed="knowledge/error",e.KnowledgeDone="knowledge/done",e))(q||{}),Q=(e=>(e.Knowledge="knowledge",e.Document="document",e.Record="record",e))(Q||{}),X=(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))(X||{}),v=(e=>(e.Clip="clip",e.Talk="talk",e))(v||{}),O=(e=>(e.Start="START",e.Stop="STOP",e))(O||{}),$=(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))($||{}),_=(e=>(e[e.New=0]="New",e[e.Fail=1]="Fail",e[e.Connected=2]="Connected",e[e.Connecting=3]="Connecting",e[e.Terminating=4]="Terminating",e))(_||{}),Y=(e=>(e.Amazon="amazon",e.Microsoft="microsoft",e.Afflorithmics="afflorithmics",e.Elevenlabs="elevenlabs",e))(Y||{}),Z=(e=>(e.Public="public",e.Premium="premium",e.Private="private",e))(Z||{});const L="https://api.d-id.com",oe="wss://notifications.d-id.com",ce="79f81a83a67430be2bc0fd61042b8faa",D=()=>Math.random().toString(16).slice(2);function G(){let e=window.localStorage.getItem("did_external_key_id");return e||(e=Math.random().toString(16).slice(2),window.localStorage.setItem("did_external_key_id",e)),e}let de=D();function ee(e){if(e.type==="bearer")return`Bearer ${e.token}`;if(e.type==="basic")return`Basic ${btoa(`${e.username}:${e.password}`)}`;if(e.type==="key")return`Client-Key ${e.clientKey}.${G()}_${de}`;throw new Error(`Unknown auth type: ${e}`)}function V(e,i=L,t){const a=async(r,n)=>{const s=await fetch(i+(r!=null&&r.startsWith("/")?r:`/${r}`),{...n,headers:{...n==null?void 0:n.headers,Authorization:ee(e),"Content-Type":"application/json"}});if(!s.ok){let o=await s.text().catch(()=>"Failed to fetch");throw t&&t(new Error(o),{url:r,options:n,headers:s.headers}),new Error(o)}return s.json()};return{get(r,n){return a(r,{...n,method:"GET"})},post(r,n,s){return a(r,{...s,body:JSON.stringify(n),method:"POST"})},delete(r,n,s){return a(r,{...s,body:JSON.stringify(n),method:"DELETE"})},patch(r,n,s){return a(r,{...s,body:JSON.stringify(n),method:"PATCH"})}}}function te(e,i=L,t){const a=V(e,`${i}/agents`,t);return{create(r,n){return a.post("/",r,n)},getAgents(r,n){return a.get(`/${r?`?tag=${r}`:""}`,n).then(s=>s??[])},getById(r,n){return a.get(`/${r}`,n)},delete(r,n){return a.delete(`/${r}`,void 0,n)},update(r,n,s){return a.patch(`/${r}`,n,s)},newChat(r,n){return a.post(`/${r}/chat`,void 0,n)},chat(r,n,s,o){return a.post(`/${r}/chat/${n}`,s,o)},getChatMode(r,n,s){return a.get(`/${r}/chat/${n}/mode`,s)},createRating(r,n,s,o){return a.post(`/${r}/chat/${n}/ratings`,s,o)},updateRating(r,n,s,o,c){return a.patch(`/${r}/chat/${n}/ratings/${s}`,o,c)},deleteRating(r,n,s,o){return a.delete(`/${r}/chat/${n}/ratings/${s}`,o)}}}const ge=e=>new Promise(i=>setTimeout(i,e));function le(e){return new Promise((i,t)=>{const{callbacks:a,host:r,auth:n}=e,{onMessage:s=null,onOpen:o=null,onClose:c=null,onError:h=null}=a||{},C=new WebSocket(`${r}?authorization=${ee(n)}`);C.onmessage=s,C.onclose=c,C.onerror=M=>{console.error(M),h==null||h("Websocket failed to connect",M),t(M)},C.onopen=M=>{o==null||o(M),i(C)}})}async function ue(e){const{retries:i=1}=e;let t=null;for(let a=0;(t==null?void 0:t.readyState)!==WebSocket.OPEN;a++)try{t=await le(e)}catch(r){if(a===i)throw r;await ge(a*500)}return t}async function ne(e,i,t){const a=t!=null&&t.onMessage?[t.onMessage]:[],r=await ue({auth:e,host:i,callbacks:{onError:t==null?void 0:t.onError,onMessage:n=>{const s=JSON.parse(n.data);a.forEach(o=>o(s.event,s))}}});return{socket:r,disconnect:()=>r.close(),subscribeToEvents:n=>a.push(n)}}function me(e,i,t,a){const r=V(e,`${i}/agents/${t}`,a);return{createStream(n){return r.post("/streams",{driver_id:n.driver_id,presenter_id:n.presenter_id,compatibility_mode:n.compatibility_mode,stream_warmup:n.stream_warmup,type:v.Clip})},startConnection(n,s,o){return r.post(`/streams/${n}/sdp`,{session_id:o,answer:s,type:v.Clip})},addIceCandidate(n,s,o){return r.post(`/streams/${n}/ice`,{session_id:o,...s,type:v.Clip})},sendStreamRequest(n,s,o){return r.post(`/streams/${n}`,{session_id:s,...o,type:v.Clip})},close(n,s){return r.delete(`/streams/${n}`,{session_id:s,type:v.Clip})}}}function he(e,i,t,a){const r=V(e,`${i}/agents/${t}`,a);return{createStream(n,s){return r.post("/streams",{source_url:n.source_url,driver_url:n.driver_url,face:n.face,config:n.config,compatibility_mode:n.compatibility_mode,stream_warmup:n.stream_warmup,output_resolution:n.output_resolution,type:v.Talk},s)},startConnection(n,s,o,c){return r.post(`/streams/${n}/sdp`,{session_id:o,answer:s,type:v.Talk},c)},addIceCandidate(n,s,o,c){return r.post(`/streams/${n}/ice`,{session_id:o,...s,type:v.Talk},c)},sendStreamRequest(n,s,o,c){return r.post(`/streams/${n}`,{session_id:s,...o,type:v.Talk},c)},close(n,s,o){return r.delete(`/streams/${n}`,{session_id:s,type:v.Talk},o)}}}let re=!1;const E=(e,i)=>re&&console.log(e,i),we=(window.RTCPeerConnection||window.webkitRTCPeerConnection||window.mozRTCPeerConnection).bind(window);function ae(e){switch(e){case"connected":return _.Connected;case"checking":return _.Connecting;case"failed":return _.Fail;case"new":case"closed":case"disconnected":default:return _.New}}function fe(){let e=0;return i=>{for(const t of i.values())if(t&&t.type==="inbound-rtp"&&t.kind==="video"){const a=t.bytesReceived,r=a-e>0;return e=a,r}return!1}}function pe(e,i){const a=Math.max(Math.ceil(10),1);let r=0,n=!1;const s=fe();return setInterval(async()=>{const o=await e.getStats();s(o)?(r=0,n||(i==null||i(O.Start),n=!0)):n&&(r++,r>=a&&(i==null||i(O.Stop),n=!1))},100)}async function ye(e,i,{debug:t=!1,callbacks:a,auth:r,analytics:n,baseURL:s=L}){re=t;let o;const{startConnection:c,sendStreamRequest:h,close:C,createStream:M,addIceCandidate:I}=i.videoType===v.Clip?me(r,s,e,a.onError):he(r,s,e,a.onError),{id:A,offer:j,ice_servers:z,session_id:R}=await M(i),p=new we({iceServers:z}),d=p.createDataChannel("JanusDataChannel");if(!R)throw new Error("Could not create session_id");const u=pe(p,a.onVideoStateChange);p.onicecandidate=g=>{E("peerConnection.onicecandidate",g),g.candidate&&g.candidate.sdpMid&&g.candidate.sdpMLineIndex!==null?I(A,{candidate:g.candidate.candidate,sdpMid:g.candidate.sdpMid,sdpMLineIndex:g.candidate.sdpMLineIndex},R):I(A,{candidate:null},R)},p.oniceconnectionstatechange=()=>{var m;E("peerConnection.oniceconnectionstatechange => "+p.iceConnectionState);const g=ae(p.iceConnectionState);g===_.Connected?o=setTimeout(()=>{var w;(w=a.onConnectionStateChange)==null||w.call(a,_.Connected)},5e3):(clearTimeout(o),(m=a.onConnectionStateChange)==null||m.call(a,g))},p.ontrack=g=>{var m;E("peerConnection.ontrack",g),(m=a.onSrcObjectReady)==null||m.call(a,g.streams[0])},d.onmessage=g=>{var m;if(d.readyState==="open"){const[w,y]=g.data.split(":");w===$.StreamReady&&(clearTimeout(o),(m=a.onConnectionStateChange)==null||m.call(a,_.Connected))}},await p.setRemoteDescription(j),E("set remote description OK");const l=await p.createAnswer();return E("create answer OK"),await p.setLocalDescription(l),E("set local description OK"),await c(A,l,R),E("start connection OK"),{speak(g){return h(A,R,g)},async disconnect(){var g,m,w;if(A){if(p){if(ae(p.iceConnectionState)===_.New){(g=a.onVideoStateChange)==null||g.call(a,O.Stop),clearInterval(u);return}p.close(),p.oniceconnectionstatechange=null,p.onnegotiationneeded=null,p.onicecandidate=null,p.ontrack=null}try{await C(A,R).catch(y=>{})}catch(y){E("Error on close stream connection",y)}(m=a.onConnectionStateChange)==null||m.call(a,_.New),(w=a.onVideoStateChange)==null||w.call(a,O.Stop),clearInterval(u)}},sessionId:R,streamId:A}}function Me(e){const i=window!=null&&window.hasOwnProperty("DID_AGENTS_API")?"agents-ui":"agents-sdk",t={token:e.token||"testKey",distinct_id:e.distinctId||G(),isEnabled:e.isEnabled??!0,agentId:e.agent.id,owner_id:e.agent.owner_id??""};return{...t,getRandom:()=>Math.random().toString(16).slice(2),track(a,r){if(!this.isEnabled)return Promise.reject("MixPanel analytics is disabled on creation");const n={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({data:JSON.stringify([{event:a,properties:{...r,...t,source:i,time:Date.now(),$insert_id:this.getRandom(),origin:window.location.href,"Screen Height":window.screen.height||window.innerWidth,"Screen Width":window.screen.width||window.innerHeight,"User Agent":navigator.userAgent}}])})};return fetch("https://api-js.mixpanel.com/track/?verbose=1&ip=1",n).then(s=>s.json()).catch(s=>console.error(s))}}}function ve(e){var a,r,n,s,o;const i=()=>/Mobi|Android/i.test(navigator.userAgent)?"Mobile":"Desktop";return{$os:`${(()=>{const c=navigator.platform;return c.toLowerCase().includes("win")?"Windows":c.toLowerCase().includes("mac")?"Mac OS X":c.toLowerCase().includes("linux")?"Linux":"Unknown"})()}`,isMobile:`${i()=="Mobile"}`,browser:navigator.userAgent,origin:window.location.origin,agentType:(a=e.presenter)==null?void 0:a.type,agentVoice:{voiceId:(n=(r=e.presenter)==null?void 0:r.voice)==null?void 0:n.voice_id,provider:(o=(s=e.presenter)==null?void 0:s.voice)==null?void 0:o.type}}}const Ce=1080;function Se(e,i){if(e.presenter){if(e.presenter.type===v.Clip)return{videoType:v.Clip,driver_id:e.presenter.driver_id,presenter_id:e.presenter.presenter_id,stream_warmup:!0}}else throw new Error("Presenter is not initialized");const t=i||(e.presenter.stitch?Ce:void 0);return{videoType:v.Talk,source_url:e.presenter.source_url,stream_warmup:!0,...t&&{output_resolution:t}}}function B(e,i,t,a,r){return new Promise(async(n,s)=>{let o=r;const c=await ye(e.id,Se(e,i.outputResolution),{...i,analytics:a,callbacks:{...i.callbacks,onConnectionStateChange:async h=>{var C,M;if(h===_.Connected)try{try{o||(o=await t.newChat(e.id),a.track("agent-chat",{event:"created",chat_id:o.id,agent_id:e.id})),c&&n({chat:o,streamingManager:c})}catch(I){console.error(I),(I==null?void 0:I.kind)==="InsufficientCreditsError"&&(i.mode,k.TextOnly),s("Cannot create new chat")}}catch(I){console.error(I),s("Cannot create new chat")}else h===_.Fail&&s(new Error("Cannot create connection"));(M=(C=i.callbacks).onConnectionStateChange)==null||M.call(C,h)},onVideoStateChange(h){var C,M;(M=(C=i.callbacks).onVideoStateChange)==null||M.call(C,h)}}}).catch(s)})}function _e(e,i,t){return te(i,t||L).getById(e)}function W(e){let i="";if(e.greetings&&e.greetings.length>0){const t=Math.floor(Math.random()*e.greetings.length);i=e.greetings[t]}else i=`Hi! I'm ${e.preview_name||"My Agent"}. How can I help you?`;return[{content:i,id:D(),role:"assistant",created_at:new Date().toISOString()}]}async function Ie(e,i){var z,R,p;const t={messages:[],chatMode:i.mode||k.Functional};let a=-1;const r=i.wsURL||oe,n=i.baseURL||L,s=i.mixpanelKey||ce,o=te(i.auth,n,i.callbacks.onError),c=await o.getById(e);t.messages=W(c),(R=(z=i.callbacks).onNewMessage)==null||R.call(z,t.messages);const h=Me({token:s,agent:c,...i});h.track("agent-sdk",{event:"loaded",...ve(c)});const C={onMessage:(d,u)=>{var l,g,m,w;if("content"in u){const{content:y}=u,S=t.messages[t.messages.length-1];(S==null?void 0:S.role)==="assistant"&&(a<t.messages.length&&(S.content=d===b.Partial?S.content+y:y),d===b.Answer&&(a=t.messages.length)),d===b.Answer&&h.track("agent-message-received",{messages:t.messages.length}),(g=(l=i.callbacks).onNewMessage)==null||g.call(l,t.messages)}else{if([$.StreamVideoCreated,$.StreamVideoDone,$.StreamVideoError,$.StreamVideoRejected].includes(d)){const y=d.split("/")[1];h.track("agent-video",{...u,event:y})}[$.StreamFailed,$.StreamVideoError,$.StreamVideoRejected].includes(d)&&((w=(m=i.callbacks).onError)==null||w.call(m,new Error(`Stream failed with event ${d}`),{data:u}))}}};async function M(){var m,w,y,S,T;const d=await ne(i.auth,r,C),{streamingManager:u,chat:l}=await B(c,i,o,h,t.chat);a=-1,t.messages.length===0&&(t.messages=W(c),(w=(m=i.callbacks).onNewMessage)==null||w.call(m,t.messages)),l!=null&&l.id&&l.id!==((y=t.chat)==null?void 0:y.id)&&((T=(S=i.callbacks).onNewChat)==null||T.call(S,l==null?void 0:l.id)),t.streamingManager=u,t.socketManager=d,t.chat=l;const g=t.chat.chatMode||k.Functional;A(g),h.track("agent-chat",{event:"connect",chatId:l.id,agentId:c.id})}async function I(){var d,u,l,g,m;(d=t.socketManager)==null||d.disconnect(),await((u=t.streamingManager)==null?void 0:u.disconnect()),delete t.streamingManager,delete t.socketManager,t.messages=W(c),(g=(l=i.callbacks).onNewMessage)==null||g.call(l,t.messages),h.track("agent-chat",{event:"disconnect",chatId:(m=t.chat)==null?void 0:m.id,agentId:c.id})}async function A(d){var u,l;d!==t.chatMode&&(h.track("agent-mode-change",{mode:d}),t.chatMode=d,t.chatMode!==k.Functional&&await I(),(l=(u=i.callbacks).onModeChange)==null||l.call(u,d))}async function j(){if(!t.chat)return M();const{streamingManager:d,chat:u}=await B(c,i,o,h,t.chat);t.streamingManager=d,A(t.chat.chatMode||k.Functional),h.track("agent-chat",{event:"reconnect",chatId:u.id,agentId:c.id})}return{agent:c,starterMessages:((p=c.knowledge)==null?void 0:p.starter_message)||[],connect:M,disconnect:I,changeMode:A,async reconnect(){var m,w;if(!t.chat)return M();(m=t.socketManager)==null||m.disconnect(),await((w=t.streamingManager)==null?void 0:w.disconnect());const d=await ne(i.auth,r,C),{streamingManager:u,chat:l}=await B(c,i,o,h,t.chat);t.streamingManager=u,t.socketManager=d;const g=t.chat.chatMode||k.Functional;A(g),h.track("agent-chat",{event:"reconnect",chatId:l.id,agentId:c.id})},async chat(d){var l,g,m,w,y,S,T,N,ie;const u=D();try{const F=Date.now();if(d.length>=800)throw new Error("Message cannot be more than 800 characters");if(d.length===0)throw new Error("Message cannot be empty");if(t.chatMode===k.Maintenance)throw new Error("Chat is in maintenance mode");if(![k.TextOnly,k.Playground].includes(t.chatMode))if(t.streamingManager){if(!t.chat)throw new Error("Chat is not initialized")}else throw new Error("Streaming manager is not initialized");t.messages.push({id:D(),role:"user",content:d,created_at:new Date(F).toISOString()}),(g=(l=i.callbacks).onNewMessage)==null||g.call(l,t.messages),t.chat||(t.chat=await o.newChat(c.id));const K={id:u,role:"assistant",content:"",created_at:new Date().toISOString(),matches:[]};t.messages.push(K);const se=t.messages.slice(0,-1);let P;try{P=await o.chat(c.id,t.chat.id,{sessionId:(m=t.streamingManager)==null?void 0:m.sessionId,streamId:(w=t.streamingManager)==null?void 0:w.streamId,messages:se,chatMode:t.chatMode})}catch(U){if((y=U==null?void 0:U.message)!=null&&y.includes("missing or invalid session_id"))console.log("Invalid stream, try reconnect with new stream id"),await j(),P=await o.chat(c.id,t.chat.id,{sessionId:(S=t.streamingManager)==null?void 0:S.sessionId,streamId:(T=t.streamingManager)==null?void 0:T.streamId,messages:se,chatMode:t.chatMode});else throw U}return h.track("agent-message-send",{event:"success",messages:t.messages.length+1}),K.context=P.context,P.result&&(K.content=P.result,K.matches=P.matches,h.track("agent-message-received",{latency:Date.now()-F,messages:t.messages.length}),(ie=(N=i.callbacks).onNewMessage)==null||ie.call(N,t.messages)),P}catch(F){throw t.messages[t.messages.length-1].id===u&&t.messages.pop(),h.track("agent-message-send",{event:"error",messages:t.messages.length}),F}},rate(d,u,l){var w,y,S,T;const g=t.messages.find(N=>N.id===d);if(t.chat){if(!g)throw new Error("Message not found")}else throw new Error("Chat is not initialized");const m=((w=g.matches)==null?void 0:w.map(N=>[N.document_id,N.id]))??[];return h.track("agent-rate",{event:l?"update":"create",thumb:u===1?"up":"down",knowledge_id:((y=c.knowledge)==null?void 0:y.id)??"",matches:m,score:u}),l?o.updateRating(c.id,t.chat.id,l,{knowledge_id:((S=c.knowledge)==null?void 0:S.id)??"",message_id:d,matches:m,score:u}):o.createRating(c.id,t.chat.id,{knowledge_id:((T=c.knowledge)==null?void 0:T.id)??"",message_id:d,matches:m,score:u})},getChatmode(){if(!t.chat)throw new Error("Chat is not initialized");return o.getChatMode(c.id,t.chat.id)},deleteRate(d){var u;if(!t.chat)throw new Error("Chat is not initialized");return h.track("agent-rate-delete",{type:"text",chat_id:(u=t.chat)==null?void 0:u.id,id:d}),o.deleteRating(c.id,t.chat.id,d)},speak(d){if(!t.streamingManager)throw new Error("Streaming manager is not initialized");function u(){if(c.presenter){if(d.type==="text")return{type:"text",provider:d.provider?d.provider:c.presenter.voice,input:d.input,ssml:d.ssml||!1};if(d.type==="audio")return{type:"audio",audio_url:d.audio_url}}else throw new Error("Presenter is not initialized");throw new Error("Invalid payload")}const l=u();return h.track("agent-speak",l),t.streamingManager.speak({script:l})}}}f.ChatMode=k,f.ChatProgress=b,f.ConnectionState=_,f.DocumentType=X,f.KnowledgeType=Q,f.PlanGroup=H,f.Providers=Y,f.RateState=J,f.StreamEvents=$,f.StreamingState=O,f.Subject=q,f.UserPlan=x,f.VideoType=v,f.VoiceAccess=Z,f.createAgentManager=Ie,f.getAgent=_e,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})});
|