@d-id/client-sdk 1.0.19-beta.105 → 1.0.19-beta.106
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 +146 -141
- package/dist/index.umd.cjs +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -25,12 +25,12 @@ function B(e, a = O, t) {
|
|
|
25
25
|
}
|
|
26
26
|
});
|
|
27
27
|
if (!s.ok) {
|
|
28
|
-
let
|
|
29
|
-
throw t && t(new Error(
|
|
28
|
+
let c = await s.text().catch(() => "Failed to fetch");
|
|
29
|
+
throw t && t(new Error(c), {
|
|
30
30
|
url: r,
|
|
31
31
|
options: n,
|
|
32
32
|
headers: s.headers
|
|
33
|
-
}), new Error(
|
|
33
|
+
}), new Error(c);
|
|
34
34
|
}
|
|
35
35
|
return s.json();
|
|
36
36
|
};
|
|
@@ -85,17 +85,17 @@ function q(e, a = O, t) {
|
|
|
85
85
|
newChat(r, n) {
|
|
86
86
|
return i.post(`/${r}/chat`, void 0, n);
|
|
87
87
|
},
|
|
88
|
-
chat(r, n, s,
|
|
89
|
-
return i.post(`/${r}/chat/${n}`, s,
|
|
88
|
+
chat(r, n, s, c) {
|
|
89
|
+
return i.post(`/${r}/chat/${n}`, s, c);
|
|
90
90
|
},
|
|
91
|
-
createRating(r, n, s,
|
|
92
|
-
return i.post(`/${r}/chat/${n}/ratings`, s,
|
|
91
|
+
createRating(r, n, s, c) {
|
|
92
|
+
return i.post(`/${r}/chat/${n}/ratings`, s, c);
|
|
93
93
|
},
|
|
94
|
-
updateRating(r, n, s,
|
|
95
|
-
return i.patch(`/${r}/chat/${n}/ratings/${s}`,
|
|
94
|
+
updateRating(r, n, s, c, d) {
|
|
95
|
+
return i.patch(`/${r}/chat/${n}/ratings/${s}`, c, d);
|
|
96
96
|
},
|
|
97
|
-
deleteRating(r, n, s,
|
|
98
|
-
return i.delete(`/${r}/chat/${n}/ratings/${s}`,
|
|
97
|
+
deleteRating(r, n, s, c) {
|
|
98
|
+
return i.delete(`/${r}/chat/${n}/ratings/${s}`, c);
|
|
99
99
|
}
|
|
100
100
|
};
|
|
101
101
|
}
|
|
@@ -108,14 +108,14 @@ function le(e) {
|
|
|
108
108
|
auth: n
|
|
109
109
|
} = e, {
|
|
110
110
|
onMessage: s = null,
|
|
111
|
-
onOpen:
|
|
111
|
+
onOpen: c = null,
|
|
112
112
|
onClose: d = null,
|
|
113
113
|
onError: l = null
|
|
114
114
|
} = i || {}, w = new WebSocket(`${r}?authorization=${j(n)}`);
|
|
115
115
|
w.onmessage = s, w.onclose = d, w.onerror = (y) => {
|
|
116
116
|
console.error(y), l == null || l("Websocket failed to connect", y), t(y);
|
|
117
117
|
}, w.onopen = (y) => {
|
|
118
|
-
|
|
118
|
+
c == null || c(y), a(w);
|
|
119
119
|
};
|
|
120
120
|
});
|
|
121
121
|
}
|
|
@@ -134,7 +134,7 @@ async function ge(e) {
|
|
|
134
134
|
}
|
|
135
135
|
return t;
|
|
136
136
|
}
|
|
137
|
-
async function
|
|
137
|
+
async function me(e, a, t) {
|
|
138
138
|
const i = t != null && t.onMessage ? [t.onMessage] : [], r = await ge({
|
|
139
139
|
auth: e,
|
|
140
140
|
host: a,
|
|
@@ -142,7 +142,7 @@ async function ue(e, a, t) {
|
|
|
142
142
|
onError: t == null ? void 0 : t.onError,
|
|
143
143
|
onMessage: (n) => {
|
|
144
144
|
const s = JSON.parse(n.data);
|
|
145
|
-
i.forEach((
|
|
145
|
+
i.forEach((c) => c(s.event, s));
|
|
146
146
|
}
|
|
147
147
|
}
|
|
148
148
|
});
|
|
@@ -152,7 +152,7 @@ async function ue(e, a, t) {
|
|
|
152
152
|
subscribeToEvents: (n) => i.push(n)
|
|
153
153
|
};
|
|
154
154
|
}
|
|
155
|
-
const
|
|
155
|
+
const ue = "X-Playground-Chat";
|
|
156
156
|
function we(e, a, t, i) {
|
|
157
157
|
const r = B(e, `${a}/agents/${t}`, i);
|
|
158
158
|
return {
|
|
@@ -166,24 +166,24 @@ function we(e, a, t, i) {
|
|
|
166
166
|
type: _.Clip
|
|
167
167
|
});
|
|
168
168
|
},
|
|
169
|
-
startConnection(n, s,
|
|
169
|
+
startConnection(n, s, c) {
|
|
170
170
|
return r.post(`/streams/${n}/sdp`, {
|
|
171
|
-
session_id:
|
|
171
|
+
session_id: c,
|
|
172
172
|
answer: s,
|
|
173
173
|
type: _.Clip
|
|
174
174
|
});
|
|
175
175
|
},
|
|
176
|
-
addIceCandidate(n, s,
|
|
176
|
+
addIceCandidate(n, s, c) {
|
|
177
177
|
return r.post(`/streams/${n}/ice`, {
|
|
178
|
-
session_id:
|
|
178
|
+
session_id: c,
|
|
179
179
|
...s,
|
|
180
180
|
type: _.Clip
|
|
181
181
|
});
|
|
182
182
|
},
|
|
183
|
-
sendStreamRequest(n, s,
|
|
183
|
+
sendStreamRequest(n, s, c) {
|
|
184
184
|
return r.post(`/streams/${n}`, {
|
|
185
185
|
session_id: s,
|
|
186
|
-
...
|
|
186
|
+
...c,
|
|
187
187
|
type: _.Clip
|
|
188
188
|
});
|
|
189
189
|
},
|
|
@@ -211,32 +211,32 @@ function he(e, a, t, i) {
|
|
|
211
211
|
type: _.Talk
|
|
212
212
|
}, s);
|
|
213
213
|
},
|
|
214
|
-
startConnection(n, s,
|
|
214
|
+
startConnection(n, s, c, d) {
|
|
215
215
|
return r.post(`/streams/${n}/sdp`, {
|
|
216
|
-
session_id:
|
|
216
|
+
session_id: c,
|
|
217
217
|
answer: s,
|
|
218
218
|
type: _.Talk
|
|
219
219
|
}, d);
|
|
220
220
|
},
|
|
221
|
-
addIceCandidate(n, s,
|
|
221
|
+
addIceCandidate(n, s, c, d) {
|
|
222
222
|
return r.post(`/streams/${n}/ice`, {
|
|
223
|
-
session_id:
|
|
223
|
+
session_id: c,
|
|
224
224
|
...s,
|
|
225
225
|
type: _.Talk
|
|
226
226
|
}, d);
|
|
227
227
|
},
|
|
228
|
-
sendStreamRequest(n, s,
|
|
228
|
+
sendStreamRequest(n, s, c, d) {
|
|
229
229
|
return r.post(`/streams/${n}`, {
|
|
230
230
|
session_id: s,
|
|
231
|
-
...
|
|
231
|
+
...c,
|
|
232
232
|
type: _.Talk
|
|
233
233
|
}, d);
|
|
234
234
|
},
|
|
235
|
-
close(n, s,
|
|
235
|
+
close(n, s, c) {
|
|
236
236
|
return r.delete(`/streams/${n}`, {
|
|
237
237
|
session_id: s,
|
|
238
238
|
type: _.Talk
|
|
239
|
-
},
|
|
239
|
+
}, c);
|
|
240
240
|
}
|
|
241
241
|
};
|
|
242
242
|
}
|
|
@@ -273,8 +273,8 @@ function ye(e, a) {
|
|
|
273
273
|
let r = 0, n = !1;
|
|
274
274
|
const s = pe();
|
|
275
275
|
return setInterval(async () => {
|
|
276
|
-
const
|
|
277
|
-
s(
|
|
276
|
+
const c = await e.getStats();
|
|
277
|
+
s(c) ? (r = 0, n || (a == null || a(b.Start), n = !0)) : n && (r++, r >= i && (a == null || a(b.Stop), n = !1));
|
|
278
278
|
}, 100);
|
|
279
279
|
}
|
|
280
280
|
async function ve(e, a, {
|
|
@@ -285,7 +285,7 @@ async function ve(e, a, {
|
|
|
285
285
|
baseURL: s = O
|
|
286
286
|
}) {
|
|
287
287
|
X = t;
|
|
288
|
-
let
|
|
288
|
+
let c;
|
|
289
289
|
const {
|
|
290
290
|
startConnection: d,
|
|
291
291
|
sendStreamRequest: l,
|
|
@@ -297,13 +297,13 @@ async function ve(e, a, {
|
|
|
297
297
|
offer: L,
|
|
298
298
|
ice_servers: z,
|
|
299
299
|
session_id: R
|
|
300
|
-
} = await y(a),
|
|
300
|
+
} = await y(a), o = new fe({
|
|
301
301
|
iceServers: z
|
|
302
|
-
}),
|
|
302
|
+
}), m = o.createDataChannel("JanusDataChannel");
|
|
303
303
|
if (!R)
|
|
304
304
|
throw new Error("Could not create session_id");
|
|
305
|
-
const f = ye(
|
|
306
|
-
|
|
305
|
+
const f = ye(o, i.onVideoStateChange);
|
|
306
|
+
o.onicecandidate = (g) => {
|
|
307
307
|
T("peerConnection.onicecandidate", g), g.candidate && g.candidate.sdpMid && g.candidate.sdpMLineIndex !== null ? x(I, {
|
|
308
308
|
candidate: g.candidate.candidate,
|
|
309
309
|
sdpMid: g.candidate.sdpMid,
|
|
@@ -311,26 +311,26 @@ async function ve(e, a, {
|
|
|
311
311
|
}, R) : x(I, {
|
|
312
312
|
candidate: null
|
|
313
313
|
}, R);
|
|
314
|
-
},
|
|
315
|
-
var
|
|
316
|
-
T("peerConnection.oniceconnectionstatechange => " +
|
|
317
|
-
const g = H(
|
|
318
|
-
g === E.Connected ?
|
|
314
|
+
}, o.oniceconnectionstatechange = () => {
|
|
315
|
+
var u;
|
|
316
|
+
T("peerConnection.oniceconnectionstatechange => " + o.iceConnectionState);
|
|
317
|
+
const g = H(o.iceConnectionState);
|
|
318
|
+
g === E.Connected ? c = setTimeout(() => {
|
|
319
319
|
var p;
|
|
320
320
|
(p = i.onConnectionStateChange) == null || p.call(i, E.Connected);
|
|
321
|
-
}, 5e3) : (clearTimeout(
|
|
322
|
-
},
|
|
323
|
-
var
|
|
324
|
-
T("peerConnection.ontrack", g), (
|
|
325
|
-
},
|
|
326
|
-
var
|
|
327
|
-
if (
|
|
321
|
+
}, 5e3) : (clearTimeout(c), (u = i.onConnectionStateChange) == null || u.call(i, g));
|
|
322
|
+
}, o.ontrack = (g) => {
|
|
323
|
+
var u;
|
|
324
|
+
T("peerConnection.ontrack", g), (u = i.onSrcObjectReady) == null || u.call(i, g.streams[0]);
|
|
325
|
+
}, m.onmessage = (g) => {
|
|
326
|
+
var u;
|
|
327
|
+
if (m.readyState === "open") {
|
|
328
328
|
const [p, v] = g.data.split(":");
|
|
329
|
-
p === U.StreamReady && (clearTimeout(
|
|
329
|
+
p === U.StreamReady && (clearTimeout(c), (u = i.onConnectionStateChange) == null || u.call(i, E.Connected));
|
|
330
330
|
}
|
|
331
|
-
}, await
|
|
332
|
-
const S = await
|
|
333
|
-
return T("create answer OK"), await
|
|
331
|
+
}, await o.setRemoteDescription(L), T("set remote description OK");
|
|
332
|
+
const S = await o.createAnswer();
|
|
333
|
+
return T("create answer OK"), await o.setLocalDescription(S), T("set local description OK"), await d(I, S, R), T("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
|
|
@@ -342,14 +342,14 @@ async function ve(e, a, {
|
|
|
342
342
|
* Method to close RTC connection
|
|
343
343
|
*/
|
|
344
344
|
async disconnect() {
|
|
345
|
-
var g,
|
|
345
|
+
var g, u, p;
|
|
346
346
|
if (I) {
|
|
347
|
-
if (
|
|
348
|
-
if (H(
|
|
347
|
+
if (o) {
|
|
348
|
+
if (H(o.iceConnectionState) === E.New) {
|
|
349
349
|
(g = i.onVideoStateChange) == null || g.call(i, b.Stop), clearInterval(f);
|
|
350
350
|
return;
|
|
351
351
|
}
|
|
352
|
-
|
|
352
|
+
o.close(), o.oniceconnectionstatechange = null, o.onnegotiationneeded = null, o.onicecandidate = null, o.ontrack = null;
|
|
353
353
|
}
|
|
354
354
|
try {
|
|
355
355
|
await w(I, R).catch((v) => {
|
|
@@ -357,7 +357,7 @@ async function ve(e, a, {
|
|
|
357
357
|
} catch (v) {
|
|
358
358
|
T("Error on close stream connection", v);
|
|
359
359
|
}
|
|
360
|
-
(
|
|
360
|
+
(u = i.onConnectionStateChange) == null || u.call(i, E.New), (p = i.onVideoStateChange) == null || p.call(i, b.Stop), clearInterval(f);
|
|
361
361
|
}
|
|
362
362
|
},
|
|
363
363
|
/**
|
|
@@ -415,23 +415,23 @@ function Ce(e) {
|
|
|
415
415
|
events: {},
|
|
416
416
|
resolvedDependencies: []
|
|
417
417
|
}), s.includes(n) || s.push(n);
|
|
418
|
-
const
|
|
419
|
-
if (
|
|
418
|
+
const c = V[i];
|
|
419
|
+
if (c.events[n] = {
|
|
420
420
|
props: r
|
|
421
|
-
},
|
|
422
|
-
const l = s.reduce((w, y) =>
|
|
421
|
+
}, c.resolvedDependencies.push(n), s.every((l) => c.resolvedDependencies.includes(l))) {
|
|
422
|
+
const l = s.reduce((w, y) => c.events[y] ? {
|
|
423
423
|
...w,
|
|
424
|
-
...
|
|
424
|
+
...c.events[y].props
|
|
425
425
|
} : w, {});
|
|
426
|
-
this.track(i, l),
|
|
427
|
-
delete
|
|
426
|
+
this.track(i, l), c.resolvedDependencies = c.resolvedDependencies.filter((w) => !s.includes(w)), s.forEach((w) => {
|
|
427
|
+
delete c.events[w];
|
|
428
428
|
});
|
|
429
429
|
}
|
|
430
430
|
}
|
|
431
431
|
};
|
|
432
432
|
}
|
|
433
433
|
function _e(e) {
|
|
434
|
-
var i, r, n, s,
|
|
434
|
+
var i, r, n, s, c;
|
|
435
435
|
const a = () => /Mobi|Android/i.test(navigator.userAgent) ? "Mobile" : "Desktop";
|
|
436
436
|
return {
|
|
437
437
|
$os: `${(() => {
|
|
@@ -444,7 +444,7 @@ function _e(e) {
|
|
|
444
444
|
agentType: (i = e.presenter) == null ? void 0 : i.type,
|
|
445
445
|
agentVoice: {
|
|
446
446
|
voiceId: (n = (r = e.presenter) == null ? void 0 : r.voice) == null ? void 0 : n.voice_id,
|
|
447
|
-
provider: (
|
|
447
|
+
provider: (c = (s = e.presenter) == null ? void 0 : s.voice) == null ? void 0 : c.type
|
|
448
448
|
}
|
|
449
449
|
};
|
|
450
450
|
}
|
|
@@ -473,7 +473,7 @@ function Me(e, a) {
|
|
|
473
473
|
}
|
|
474
474
|
function Q(e) {
|
|
475
475
|
return e === k.Playground ? {
|
|
476
|
-
[
|
|
476
|
+
[ue]: "true"
|
|
477
477
|
} : {};
|
|
478
478
|
}
|
|
479
479
|
async function Y(e, a, t, i) {
|
|
@@ -499,7 +499,7 @@ async function Y(e, a, t, i) {
|
|
|
499
499
|
function ke(e, a, t, i, r) {
|
|
500
500
|
return new Promise(async (n, s) => {
|
|
501
501
|
N = 0;
|
|
502
|
-
const
|
|
502
|
+
const c = await ve(e.id, Me(e, a), {
|
|
503
503
|
...a,
|
|
504
504
|
analytics: i,
|
|
505
505
|
callbacks: {
|
|
@@ -508,9 +508,9 @@ function ke(e, a, t, i, r) {
|
|
|
508
508
|
var l, w;
|
|
509
509
|
d === E.Connected && (!r && a.mode !== k.DirectPlayback && (r = await Y(e.id, t, i, a.mode).catch((y) => {
|
|
510
510
|
s(y);
|
|
511
|
-
})),
|
|
511
|
+
})), c ? n({
|
|
512
512
|
chat: r,
|
|
513
|
-
streamingManager:
|
|
513
|
+
streamingManager: c
|
|
514
514
|
}) : r && s(new Error("Something went wrong while initializing the manager"))), (w = (l = a.callbacks).onConnectionStateChange) == null || w.call(l, d);
|
|
515
515
|
},
|
|
516
516
|
onVideoStateChange(d) {
|
|
@@ -545,7 +545,7 @@ async function Ee(e, a) {
|
|
|
545
545
|
chatMode: a.mode || k.Functional
|
|
546
546
|
};
|
|
547
547
|
let i = -1;
|
|
548
|
-
const r = a.baseURL || O, n = a.wsURL || se, s = a.mixpanelKey || oe,
|
|
548
|
+
const r = a.baseURL || O, n = a.wsURL || se, s = a.mixpanelKey || oe, c = q(a.auth, r, a.callbacks.onError), d = await c.getById(e);
|
|
549
549
|
t.messages = W(d), (z = (L = a.callbacks).onNewMessage) == null || z.call(L, t.messages, "answer");
|
|
550
550
|
const l = Ce({
|
|
551
551
|
token: s,
|
|
@@ -557,33 +557,33 @@ async function Ee(e, a) {
|
|
|
557
557
|
..._e(d)
|
|
558
558
|
});
|
|
559
559
|
const w = {
|
|
560
|
-
onMessage: (
|
|
561
|
-
var f, S, g,
|
|
562
|
-
if ("content" in
|
|
560
|
+
onMessage: (o, m) => {
|
|
561
|
+
var f, S, g, u, p, v, C;
|
|
562
|
+
if ("content" in m) {
|
|
563
563
|
const {
|
|
564
564
|
content: h
|
|
565
|
-
} =
|
|
566
|
-
(M == null ? void 0 : M.role) === "assistant" && (i < t.messages.length && (M.content =
|
|
565
|
+
} = m, M = t.messages[t.messages.length - 1];
|
|
566
|
+
(M == null ? void 0 : M.role) === "assistant" && (i < t.messages.length && (M.content = o === K.Partial ? M.content + h : h), o === K.Answer && (i = t.messages.length, l.track("agent-message-received", {
|
|
567
567
|
messages: t.messages.length
|
|
568
|
-
}))), (S = (f = a.callbacks).onNewMessage) == null || S.call(f, t.messages,
|
|
568
|
+
}))), (S = (f = a.callbacks).onNewMessage) == null || S.call(f, t.messages, o === K.Answer ? "answer" : "partial");
|
|
569
569
|
} else {
|
|
570
570
|
const h = U, M = [h.StreamVideoDone, h.StreamVideoError, h.StreamVideoRejected], $ = [h.StreamFailed, h.StreamVideoError, h.StreamVideoRejected];
|
|
571
|
-
|
|
571
|
+
o = o;
|
|
572
572
|
const D = (g = d.llm) == null ? void 0 : g.template;
|
|
573
|
-
if (
|
|
573
|
+
if (o === h.StreamVideoCreated) {
|
|
574
574
|
const {
|
|
575
575
|
event: P,
|
|
576
576
|
...A
|
|
577
|
-
} =
|
|
577
|
+
} = m;
|
|
578
578
|
A.llm = {
|
|
579
579
|
...A.llm,
|
|
580
580
|
template: D
|
|
581
581
|
}, l.linkTrack("agent-video", {
|
|
582
582
|
...A
|
|
583
583
|
}, h.StreamVideoCreated, ["start"]);
|
|
584
|
-
} else if (M.includes(
|
|
585
|
-
const P =
|
|
586
|
-
...
|
|
584
|
+
} else if (M.includes(o)) {
|
|
585
|
+
const P = o.split("/")[1], A = {
|
|
586
|
+
...m,
|
|
587
587
|
event: P
|
|
588
588
|
};
|
|
589
589
|
A.llm = {
|
|
@@ -594,68 +594,73 @@ async function Ee(e, a) {
|
|
|
594
594
|
event: P
|
|
595
595
|
});
|
|
596
596
|
}
|
|
597
|
-
$.includes(
|
|
598
|
-
data:
|
|
599
|
-
})),
|
|
597
|
+
$.includes(o) && ((p = (u = a.callbacks).onError) == null || p.call(u, new Error(`Stream failed with event ${o}`), {
|
|
598
|
+
data: m
|
|
599
|
+
})), m.event === h.StreamDone && ((C = (v = a.callbacks).onConnectionStateChange) == null || C.call(v, E.New));
|
|
600
600
|
}
|
|
601
601
|
}
|
|
602
602
|
};
|
|
603
|
-
async function y(
|
|
603
|
+
async function y(o) {
|
|
604
604
|
var p, v, C, h, M;
|
|
605
|
-
N = 0, i = -1,
|
|
606
|
-
const
|
|
605
|
+
N = 0, i = -1, o && (delete t.chat, t.messages = W(d), (v = (p = a.callbacks).onNewMessage) == null || v.call(p, t.messages, "answer"));
|
|
606
|
+
const m = a.mode === k.DirectPlayback ? Promise.resolve(void 0) : me(a.auth, n, w), f = ke(d, a, c, l, t.chat).catch(($) => {
|
|
607
607
|
throw I(k.Maintenance), $;
|
|
608
608
|
}), [S, {
|
|
609
609
|
streamingManager: g,
|
|
610
|
-
chat:
|
|
611
|
-
}] = await Promise.all([
|
|
612
|
-
|
|
610
|
+
chat: u
|
|
611
|
+
}] = await Promise.all([m, f]);
|
|
612
|
+
u && u.id !== ((C = t.chat) == null ? void 0 : C.id) && ((M = (h = a.callbacks).onNewChat) == null || M.call(h, u.id)), t.streamingManager = g, t.socketManager = S, t.chat = u, I((u == null ? void 0 : u.chat_mode) ?? a.mode ?? k.Functional);
|
|
613
613
|
}
|
|
614
614
|
async function x() {
|
|
615
|
-
var
|
|
616
|
-
(
|
|
615
|
+
var o, m;
|
|
616
|
+
(o = t.socketManager) == null || o.disconnect(), await ((m = t.streamingManager) == null ? void 0 : m.disconnect()), delete t.streamingManager, delete t.socketManager;
|
|
617
617
|
}
|
|
618
|
-
async function I(
|
|
619
|
-
var
|
|
620
|
-
|
|
621
|
-
mode:
|
|
622
|
-
}), t.chatMode =
|
|
618
|
+
async function I(o) {
|
|
619
|
+
var m, f;
|
|
620
|
+
o !== t.chatMode && (l.track("agent-mode-change", {
|
|
621
|
+
mode: o
|
|
622
|
+
}), t.chatMode = o, t.chatMode !== k.Functional && await x(), (f = (m = a.callbacks).onModeChange) == null || f.call(m, o));
|
|
623
623
|
}
|
|
624
624
|
return {
|
|
625
625
|
agent: d,
|
|
626
626
|
starterMessages: ((R = d.knowledge) == null ? void 0 : R.starter_message) || [],
|
|
627
627
|
changeMode: I,
|
|
628
628
|
async connect() {
|
|
629
|
+
var o;
|
|
629
630
|
await y(!0), l.track("agent-chat", {
|
|
630
631
|
event: "connect",
|
|
631
|
-
chatId: t.chat.id,
|
|
632
|
-
agentId: d.id
|
|
632
|
+
chatId: (o = t.chat) == null ? void 0 : o.id,
|
|
633
|
+
agentId: d.id,
|
|
634
|
+
mode: t.chatMode
|
|
633
635
|
});
|
|
634
636
|
},
|
|
635
637
|
async reconnect() {
|
|
638
|
+
var o;
|
|
636
639
|
await x(), await y(!1), l.track("agent-chat", {
|
|
637
640
|
event: "reconnect",
|
|
638
|
-
chatId: t.chat.id,
|
|
639
|
-
agentId: d.id
|
|
641
|
+
chatId: (o = t.chat) == null ? void 0 : o.id,
|
|
642
|
+
agentId: d.id,
|
|
643
|
+
mode: t.chatMode
|
|
640
644
|
});
|
|
641
645
|
},
|
|
642
646
|
async disconnect() {
|
|
643
|
-
var
|
|
647
|
+
var o;
|
|
644
648
|
await x(), l.track("agent-chat", {
|
|
645
649
|
event: "disconnect",
|
|
646
|
-
chatId: (
|
|
647
|
-
agentId: d.id
|
|
650
|
+
chatId: (o = t.chat) == null ? void 0 : o.id,
|
|
651
|
+
agentId: d.id,
|
|
652
|
+
mode: t.chatMode
|
|
648
653
|
});
|
|
649
654
|
},
|
|
650
|
-
async chat(
|
|
651
|
-
var f, S, g,
|
|
652
|
-
const
|
|
655
|
+
async chat(o) {
|
|
656
|
+
var f, S, g, u, p, v;
|
|
657
|
+
const m = F();
|
|
653
658
|
try {
|
|
654
659
|
if (N = Date.now(), a.mode === k.DirectPlayback)
|
|
655
660
|
throw new Error("Direct playback is enabled, chat is disabled");
|
|
656
|
-
if (
|
|
661
|
+
if (o.length >= 800)
|
|
657
662
|
throw new Error("Message cannot be more than 800 characters");
|
|
658
|
-
if (
|
|
663
|
+
if (o.length === 0)
|
|
659
664
|
throw new Error("Message cannot be empty");
|
|
660
665
|
if (t.chatMode === k.Maintenance)
|
|
661
666
|
throw new Error("Chat is in maintenance mode");
|
|
@@ -665,14 +670,14 @@ async function Ee(e, a) {
|
|
|
665
670
|
throw new Error("Chat is not initialized");
|
|
666
671
|
} else
|
|
667
672
|
throw new Error("Streaming manager is not initialized");
|
|
668
|
-
t.chat || (t.chat = await Y(d.id,
|
|
673
|
+
t.chat || (t.chat = await Y(d.id, c, l, t.chatMode), (S = (f = a.callbacks).onNewChat) == null || S.call(f, t.chat.id)), t.messages.push({
|
|
669
674
|
id: F(),
|
|
670
675
|
role: "user",
|
|
671
|
-
content:
|
|
676
|
+
content: o,
|
|
672
677
|
created_at: new Date(N).toISOString()
|
|
673
|
-
}), (
|
|
678
|
+
}), (u = (g = a.callbacks).onNewMessage) == null || u.call(g, t.messages, "user");
|
|
674
679
|
const C = {
|
|
675
|
-
id:
|
|
680
|
+
id: m,
|
|
676
681
|
role: "assistant",
|
|
677
682
|
content: "",
|
|
678
683
|
created_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
@@ -681,7 +686,7 @@ async function Ee(e, a) {
|
|
|
681
686
|
t.messages.push(C);
|
|
682
687
|
const M = (D) => {
|
|
683
688
|
var P, A;
|
|
684
|
-
return
|
|
689
|
+
return c.chat(d.id, D, {
|
|
685
690
|
sessionId: (P = t.streamingManager) == null ? void 0 : P.sessionId,
|
|
686
691
|
streamId: (A = t.streamingManager) == null ? void 0 : A.streamId,
|
|
687
692
|
chatMode: t.chatMode,
|
|
@@ -701,66 +706,66 @@ async function Ee(e, a) {
|
|
|
701
706
|
messages: t.messages.length
|
|
702
707
|
}), (v = (p = a.callbacks).onNewMessage) == null || v.call(p, t.messages, "answer")), $;
|
|
703
708
|
} catch (C) {
|
|
704
|
-
throw t.messages[t.messages.length - 1].id ===
|
|
709
|
+
throw t.messages[t.messages.length - 1].id === m && t.messages.pop(), l.track("agent-message-send", {
|
|
705
710
|
event: "error",
|
|
706
711
|
messages: t.messages.length
|
|
707
712
|
}), C;
|
|
708
713
|
}
|
|
709
714
|
},
|
|
710
|
-
rate(
|
|
711
|
-
var
|
|
712
|
-
const S = t.messages.find((h) => h.id ===
|
|
715
|
+
rate(o, m, f) {
|
|
716
|
+
var u, p, v, C;
|
|
717
|
+
const S = t.messages.find((h) => h.id === o);
|
|
713
718
|
if (t.chat) {
|
|
714
719
|
if (!S)
|
|
715
720
|
throw new Error("Message not found");
|
|
716
721
|
} else
|
|
717
722
|
throw new Error("Chat is not initialized");
|
|
718
|
-
const g = ((
|
|
723
|
+
const g = ((u = S.matches) == null ? void 0 : u.map((h) => [h.document_id, h.id])) ?? [];
|
|
719
724
|
return l.track("agent-rate", {
|
|
720
725
|
event: f ? "update" : "create",
|
|
721
|
-
thumb:
|
|
726
|
+
thumb: m === 1 ? "up" : "down",
|
|
722
727
|
knowledge_id: ((p = d.knowledge) == null ? void 0 : p.id) ?? "",
|
|
723
728
|
matches: g,
|
|
724
|
-
score:
|
|
725
|
-
}), f ?
|
|
729
|
+
score: m
|
|
730
|
+
}), f ? c.updateRating(d.id, t.chat.id, f, {
|
|
726
731
|
knowledge_id: ((v = d.knowledge) == null ? void 0 : v.id) ?? "",
|
|
727
|
-
message_id:
|
|
732
|
+
message_id: o,
|
|
728
733
|
matches: g,
|
|
729
|
-
score:
|
|
730
|
-
}) :
|
|
734
|
+
score: m
|
|
735
|
+
}) : c.createRating(d.id, t.chat.id, {
|
|
731
736
|
knowledge_id: ((C = d.knowledge) == null ? void 0 : C.id) ?? "",
|
|
732
|
-
message_id:
|
|
737
|
+
message_id: o,
|
|
733
738
|
matches: g,
|
|
734
|
-
score:
|
|
739
|
+
score: m
|
|
735
740
|
});
|
|
736
741
|
},
|
|
737
|
-
deleteRate(
|
|
738
|
-
var
|
|
742
|
+
deleteRate(o) {
|
|
743
|
+
var m;
|
|
739
744
|
if (!t.chat)
|
|
740
745
|
throw new Error("Chat is not initialized");
|
|
741
746
|
return l.track("agent-rate-delete", {
|
|
742
747
|
type: "text",
|
|
743
|
-
chat_id: (
|
|
744
|
-
id:
|
|
745
|
-
}),
|
|
748
|
+
chat_id: (m = t.chat) == null ? void 0 : m.id,
|
|
749
|
+
id: o
|
|
750
|
+
}), c.deleteRating(d.id, t.chat.id, o);
|
|
746
751
|
},
|
|
747
|
-
speak(
|
|
752
|
+
speak(o) {
|
|
748
753
|
if (!t.streamingManager)
|
|
749
754
|
throw new Error("Please connect to the agent first");
|
|
750
|
-
function
|
|
751
|
-
if (typeof
|
|
755
|
+
function m() {
|
|
756
|
+
if (typeof o == "string") {
|
|
752
757
|
if (!d.presenter)
|
|
753
758
|
throw new Error("Presenter is not initialized");
|
|
754
759
|
return {
|
|
755
760
|
type: "text",
|
|
756
761
|
provider: d.presenter.voice,
|
|
757
|
-
input:
|
|
762
|
+
input: o,
|
|
758
763
|
ssml: !1
|
|
759
764
|
};
|
|
760
765
|
}
|
|
761
|
-
return
|
|
766
|
+
return o;
|
|
762
767
|
}
|
|
763
|
-
const f =
|
|
768
|
+
const f = m();
|
|
764
769
|
return l.track("agent-speak", f), t.streamingManager.speak({
|
|
765
770
|
script: f
|
|
766
771
|
});
|
package/dist/index.umd.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
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||{}),W=(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))(W||{}),J=(e=>(e.Unrated="Unrated",e.Positive="Positive",e.Negative="Negative",e))(J||{}),M=(e=>(e.Functional="Functional",e.TextOnly="TextOnly",e.Maintenance="Maintenance",e.Playground="Playground",e.DirectPlayback="DirectPlayback",e))(M||{}),z=(e=>(e.Embed="embed",e.Query="query",e.Partial="partial",e.Answer="answer",e.Complete="done",e))(z||{}),q=(e=>(e.KnowledgeProcessing="knowledge/processing",e.KnowledgeIndexing="knowledge/indexing",e.KnowledgeFailed="knowledge/error",e.KnowledgeDone="knowledge/done",e))(q||{}),X=(e=>(e.Knowledge="knowledge",e.Document="document",e.Record="record",e))(X||{}),Q=(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))(Q||{}),v=(e=>(e.Clip="clip",e.Talk="talk",e))(v||{}),N=(e=>(e.Start="START",e.Stop="STOP",e))(N||{}),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||{}),k=(e=>(e.New="new",e.Fail="fail",e.Connected="connected",e.Connecting="connecting",e.Terminating="terminating",e))(k||{}),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 U="https://api.d-id.com",oe="wss://notifications.d-id.com",ce="79f81a83a67430be2bc0fd61042b8faa",V=()=>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=V();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 B(e,a=U,t){const i=async(r,n)=>{const s=await fetch(a+(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 i(r,{...n,method:"GET"})},post(r,n,s){return i(r,{...s,body:JSON.stringify(n),method:"POST"})},delete(r,n,s){return i(r,{...s,body:JSON.stringify(n),method:"DELETE"})},patch(r,n,s){return i(r,{...s,body:JSON.stringify(n),method:"PATCH"})}}}function te(e,a=U,t){const i=B(e,`${a}/agents`,t);return{create(r,n){return i.post("/",r,n)},getAgents(r,n){return i.get(`/${r?`?tag=${r}`:""}`,n).then(s=>s??[])},getById(r,n){return i.get(`/${r}`,n)},delete(r,n){return i.delete(`/${r}`,void 0,n)},update(r,n,s){return i.patch(`/${r}`,n,s)},newChat(r,n){return i.post(`/${r}/chat`,void 0,n)},chat(r,n,s,o){return i.post(`/${r}/chat/${n}`,s,o)},createRating(r,n,s,o){return i.post(`/${r}/chat/${n}/ratings`,s,o)},updateRating(r,n,s,o,d){return i.patch(`/${r}/chat/${n}/ratings/${s}`,o,d)},deleteRating(r,n,s,o){return i.delete(`/${r}/chat/${n}/ratings/${s}`,o)}}}const le=e=>new Promise(a=>setTimeout(a,e));function ge(e){return new Promise((a,t)=>{const{callbacks:i,host:r,auth:n}=e,{onMessage:s=null,onOpen:o=null,onClose:d=null,onError:l=null}=i||{},w=new WebSocket(`${r}?authorization=${ee(n)}`);w.onmessage=s,w.onclose=d,w.onerror=C=>{console.error(C),l==null||l("Websocket failed to connect",C),t(C)},w.onopen=C=>{o==null||o(C),a(w)}})}async function ue(e){const{retries:a=1}=e;let t=null;for(let i=0;(t==null?void 0:t.readyState)!==WebSocket.OPEN;i++)try{t=await ge(e)}catch(r){if(i===a)throw r;await le(i*500)}return t}async function me(e,a,t){const i=t!=null&&t.onMessage?[t.onMessage]:[],r=await ue({auth:e,host:a,callbacks:{onError:t==null?void 0:t.onError,onMessage:n=>{const s=JSON.parse(n.data);i.forEach(o=>o(s.event,s))}}});return{socket:r,disconnect:()=>r.close(),subscribeToEvents:n=>i.push(n)}}const we="X-Playground-Chat";function he(e,a,t,i){const r=B(e,`${a}/agents/${t}`,i);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,session_timeout:n.session_timeout,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 fe(e,a,t,i){const r=B(e,`${a}/agents/${t}`,i);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,session_timeout:n.session_timeout,type:v.Talk},s)},startConnection(n,s,o,d){return r.post(`/streams/${n}/sdp`,{session_id:o,answer:s,type:v.Talk},d)},addIceCandidate(n,s,o,d){return r.post(`/streams/${n}/ice`,{session_id:o,...s,type:v.Talk},d)},sendStreamRequest(n,s,o,d){return r.post(`/streams/${n}`,{session_id:s,...o,type:v.Talk},d)},close(n,s,o){return r.delete(`/streams/${n}`,{session_id:s,type:v.Talk},o)}}}let ne=!1;const b=(e,a)=>ne&&console.log(e,a),pe=(window.RTCPeerConnection||window.webkitRTCPeerConnection||window.mozRTCPeerConnection).bind(window);function re(e){switch(e){case"connected":return k.Connected;case"checking":return k.Connecting;case"failed":return k.Fail;case"new":case"closed":case"disconnected":default:return k.New}}function ye(){let e=0;return a=>{for(const t of a.values())if(t&&t.type==="inbound-rtp"&&t.kind==="video"){const i=t.bytesReceived,r=i-e>0;return e=i,r}return!1}}function ve(e,a){const i=Math.max(Math.ceil(10),1);let r=0,n=!1;const s=ye();return setInterval(async()=>{const o=await e.getStats();s(o)?(r=0,n||(a==null||a(N.Start),n=!0)):n&&(r++,r>=i&&(a==null||a(N.Stop),n=!1))},100)}async function Ce(e,a,{debug:t=!1,callbacks:i,auth:r,analytics:n,baseURL:s=U}){ne=t;let o;const{startConnection:d,sendStreamRequest:l,close:w,createStream:C,addIceCandidate:L}=a.videoType===v.Clip?he(r,s,e,i.onError):fe(r,s,e,i.onError),{id:R,offer:F,ice_servers:j,session_id:A}=await C(a),c=new pe({iceServers:j}),u=c.createDataChannel("JanusDataChannel");if(!A)throw new Error("Could not create session_id");const p=ve(c,i.onVideoStateChange);c.onicecandidate=g=>{b("peerConnection.onicecandidate",g),g.candidate&&g.candidate.sdpMid&&g.candidate.sdpMLineIndex!==null?L(R,{candidate:g.candidate.candidate,sdpMid:g.candidate.sdpMid,sdpMLineIndex:g.candidate.sdpMLineIndex},A):L(R,{candidate:null},A)},c.oniceconnectionstatechange=()=>{var m;b("peerConnection.oniceconnectionstatechange => "+c.iceConnectionState);const g=re(c.iceConnectionState);g===k.Connected?o=setTimeout(()=>{var y;(y=i.onConnectionStateChange)==null||y.call(i,k.Connected)},5e3):(clearTimeout(o),(m=i.onConnectionStateChange)==null||m.call(i,g))},c.ontrack=g=>{var m;b("peerConnection.ontrack",g),(m=i.onSrcObjectReady)==null||m.call(i,g.streams[0])},u.onmessage=g=>{var m;if(u.readyState==="open"){const[y,S]=g.data.split(":");y===K.StreamReady&&(clearTimeout(o),(m=i.onConnectionStateChange)==null||m.call(i,k.Connected))}},await c.setRemoteDescription(F),b("set remote description OK");const E=await c.createAnswer();return b("create answer OK"),await c.setLocalDescription(E),b("set local description OK"),await d(R,E,A),b("start connection OK"),{speak(g){return l(R,A,g)},async disconnect(){var g,m,y;if(R){if(c){if(re(c.iceConnectionState)===k.New){(g=i.onVideoStateChange)==null||g.call(i,N.Stop),clearInterval(p);return}c.close(),c.oniceconnectionstatechange=null,c.onnegotiationneeded=null,c.onicecandidate=null,c.ontrack=null}try{await w(R,A).catch(S=>{})}catch(S){b("Error on close stream connection",S)}(m=i.onConnectionStateChange)==null||m.call(i,k.New),(y=i.onVideoStateChange)==null||y.call(i,N.Stop),clearInterval(p)}},sessionId:A,streamId:R}}let H={};function Se(e){const a=window!=null&&window.hasOwnProperty("DID_AGENTS_API")?"agents-ui":"agents-sdk",t={token:e.token||"testKey",distinct_id:e.distinctId||G(),agentId:e.agent.id,agentType:e.agent.presenter.type,owner_id:e.agent.owner_id??""};return{...t,isEnabled:e.isEnabled??!0,getRandom:()=>Math.random().toString(16).slice(2),track(i,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:i,properties:{...r,...t,source:a,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))},linkTrack(i,r,n,s){H[i]||(H[i]={events:{},resolvedDependencies:[]}),s.includes(n)||s.push(n);const o=H[i];if(o.events[n]={props:r},o.resolvedDependencies.push(n),s.every(l=>o.resolvedDependencies.includes(l))){const l=s.reduce((w,C)=>o.events[C]?{...w,...o.events[C].props}:w,{});this.track(i,l),o.resolvedDependencies=o.resolvedDependencies.filter(w=>!s.includes(w)),s.forEach(w=>{delete o.events[w]})}}}}function _e(e){var i,r,n,s,o;const a=()=>/Mobi|Android/i.test(navigator.userAgent)?"Mobile":"Desktop";return{$os:`${(()=>{const d=navigator.platform;return d.toLowerCase().includes("win")?"Windows":d.toLowerCase().includes("mac")?"Mac OS X":d.toLowerCase().includes("linux")?"Linux":"Unknown"})()}`,isMobile:`${a()=="Mobile"}`,browser:navigator.userAgent,origin:window.location.origin,agentType:(i=e.presenter)==null?void 0:i.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 Me=1080;let O=0;function ke(e,a){var t,i,r;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");return{videoType:v.Talk,source_url:e.presenter.source_url,session_timeout:(t=a==null?void 0:a.streamOptions)==null?void 0:t.session_timeout,stream_warmup:((i=a==null?void 0:a.streamOptions)==null?void 0:i.stream_warmup)??!0,compatibility_mode:(r=a==null?void 0:a.streamOptions)==null?void 0:r.compatibility_mode,output_resolution:(a==null?void 0:a.outputResolution)||(e.presenter.stitch?Me:void 0)}}function ae(e){return e===M.Playground?{[we]:"true"}:{}}async function ie(e,a,t,i){try{const r=await a.newChat(e,ae(i));return t.track("agent-chat",{event:"created",chat_id:r.id,agent_id:e}),r}catch(r){try{console.error(r);const n=JSON.parse(r.message);if((n==null?void 0:n.kind)==="InsufficientCreditsError")throw new Error("InsufficientCreditsError")}catch(n){console.error("Error parsing the error message:",n)}throw new Error("Cannot create new chat")}}function Ee(e,a,t,i,r){return new Promise(async(n,s)=>{O=0;const o=await Ce(e.id,ke(e,a),{...a,analytics:i,callbacks:{...a.callbacks,onConnectionStateChange:async d=>{var l,w;d===k.Connected&&(!r&&a.mode!==M.DirectPlayback&&(r=await ie(e.id,t,i,a.mode).catch(C=>{s(C)})),o?n({chat:r,streamingManager:o}):r&&s(new Error("Something went wrong while initializing the manager"))),(w=(l=a.callbacks).onConnectionStateChange)==null||w.call(l,d)},onVideoStateChange(d){var l,w;(w=(l=a.callbacks).onVideoStateChange)==null||w.call(l,d),O>0&&d===N.Start&&i.linkTrack("agent-video",{event:"start",latency:Date.now()-O},"start",[K.StreamVideoCreated])}}}).catch(s)})}function se(e){let a="";if(e.greetings&&e.greetings.length>0){const t=Math.floor(Math.random()*e.greetings.length);a=e.greetings[t]}else a=`Hi! I'm ${e.preview_name||"My Agent"}. How can I help you?`;return[{content:a,id:V(),role:"assistant",created_at:new Date().toISOString()}]}async function Ie(e,a){var F,j,A;const t={messages:[],chatMode:a.mode||M.Functional};let i=-1;const r=a.baseURL||U,n=a.wsURL||oe,s=a.mixpanelKey||ce,o=te(a.auth,r,a.callbacks.onError),d=await o.getById(e);t.messages=se(d),(j=(F=a.callbacks).onNewMessage)==null||j.call(F,t.messages,"answer");const l=Se({token:s,agent:d,...a});l.track("agent-sdk",{event:"loaded",..._e(d)});const w={onMessage:(c,u)=>{var p,E,g,m,y,S,_;if("content"in u){const{content:h}=u,I=t.messages[t.messages.length-1];(I==null?void 0:I.role)==="assistant"&&(i<t.messages.length&&(I.content=c===z.Partial?I.content+h:h),c===z.Answer&&(i=t.messages.length,l.track("agent-message-received",{messages:t.messages.length}))),(E=(p=a.callbacks).onNewMessage)==null||E.call(p,t.messages,c===z.Answer?"answer":"partial")}else{const h=K,I=[h.StreamVideoDone,h.StreamVideoError,h.StreamVideoRejected],T=[h.StreamFailed,h.StreamVideoError,h.StreamVideoRejected];c=c;const P=(g=d.llm)==null?void 0:g.template;if(c===h.StreamVideoCreated){const{event:D,...$}=u;$.llm={...$.llm,template:P},l.linkTrack("agent-video",{...$},h.StreamVideoCreated,["start"])}else if(I.includes(c)){const D=c.split("/")[1],$={...u,event:D};$.llm={...$.llm,template:P},l.track("agent-video",{...$,event:D})}T.includes(c)&&((y=(m=a.callbacks).onError)==null||y.call(m,new Error(`Stream failed with event ${c}`),{data:u})),u.event===h.StreamDone&&((_=(S=a.callbacks).onConnectionStateChange)==null||_.call(S,k.New))}}};async function C(c){var y,S,_,h,I;O=0,i=-1,c&&(delete t.chat,t.messages=se(d),(S=(y=a.callbacks).onNewMessage)==null||S.call(y,t.messages,"answer"));const u=a.mode===M.DirectPlayback?Promise.resolve(void 0):me(a.auth,n,w),p=Ee(d,a,o,l,t.chat).catch(T=>{throw R(M.Maintenance),T}),[E,{streamingManager:g,chat:m}]=await Promise.all([u,p]);m&&m.id!==((_=t.chat)==null?void 0:_.id)&&((I=(h=a.callbacks).onNewChat)==null||I.call(h,m.id)),t.streamingManager=g,t.socketManager=E,t.chat=m,R((m==null?void 0:m.chat_mode)??a.mode??M.Functional)}async function L(){var c,u;(c=t.socketManager)==null||c.disconnect(),await((u=t.streamingManager)==null?void 0:u.disconnect()),delete t.streamingManager,delete t.socketManager}async function R(c){var u,p;c!==t.chatMode&&(l.track("agent-mode-change",{mode:c}),t.chatMode=c,t.chatMode!==M.Functional&&await L(),(p=(u=a.callbacks).onModeChange)==null||p.call(u,c))}return{agent:d,starterMessages:((A=d.knowledge)==null?void 0:A.starter_message)||[],changeMode:R,async connect(){await C(!0),l.track("agent-chat",{event:"connect",chatId:t.chat.id,agentId:d.id})},async reconnect(){await L(),await C(!1),l.track("agent-chat",{event:"reconnect",chatId:t.chat.id,agentId:d.id})},async disconnect(){var c;await L(),l.track("agent-chat",{event:"disconnect",chatId:(c=t.chat)==null?void 0:c.id,agentId:d.id})},async chat(c){var p,E,g,m,y,S;const u=V();try{if(O=Date.now(),a.mode===M.DirectPlayback)throw new Error("Direct playback is enabled, chat is disabled");if(c.length>=800)throw new Error("Message cannot be more than 800 characters");if(c.length===0)throw new Error("Message cannot be empty");if(t.chatMode===M.Maintenance)throw new Error("Chat is in maintenance mode");if(![M.TextOnly,M.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.chat||(t.chat=await ie(d.id,o,l,t.chatMode),(E=(p=a.callbacks).onNewChat)==null||E.call(p,t.chat.id)),t.messages.push({id:V(),role:"user",content:c,created_at:new Date(O).toISOString()}),(m=(g=a.callbacks).onNewMessage)==null||m.call(g,t.messages,"user");const _={id:u,role:"assistant",content:"",created_at:new Date().toISOString(),matches:[]},h=[...t.messages];t.messages.push(_);const I=P=>{var D,$;return o.chat(d.id,P,{sessionId:(D=t.streamingManager)==null?void 0:D.sessionId,streamId:($=t.streamingManager)==null?void 0:$.streamId,chatMode:t.chatMode,messages:h},ae(t.chatMode))},T=await I(t.chat.id).catch(async P=>{var D;if(!((D=P==null?void 0:P.message)!=null&&D.includes("missing or invalid session_id")))throw P;return await L(),await C(!1),I(t.chat.id)});return l.track("agent-message-send",{event:"success",messages:t.messages.length+1}),T.result&&(_.content=T.result,_.matches=T.matches,_.context=T.context,l.track("agent-message-received",{latency:Date.now()-O,messages:t.messages.length}),(S=(y=a.callbacks).onNewMessage)==null||S.call(y,t.messages,"answer")),T}catch(_){throw t.messages[t.messages.length-1].id===u&&t.messages.pop(),l.track("agent-message-send",{event:"error",messages:t.messages.length}),_}},rate(c,u,p){var m,y,S,_;const E=t.messages.find(h=>h.id===c);if(t.chat){if(!E)throw new Error("Message not found")}else throw new Error("Chat is not initialized");const g=((m=E.matches)==null?void 0:m.map(h=>[h.document_id,h.id]))??[];return l.track("agent-rate",{event:p?"update":"create",thumb:u===1?"up":"down",knowledge_id:((y=d.knowledge)==null?void 0:y.id)??"",matches:g,score:u}),p?o.updateRating(d.id,t.chat.id,p,{knowledge_id:((S=d.knowledge)==null?void 0:S.id)??"",message_id:c,matches:g,score:u}):o.createRating(d.id,t.chat.id,{knowledge_id:((_=d.knowledge)==null?void 0:_.id)??"",message_id:c,matches:g,score:u})},deleteRate(c){var u;if(!t.chat)throw new Error("Chat is not initialized");return l.track("agent-rate-delete",{type:"text",chat_id:(u=t.chat)==null?void 0:u.id,id:c}),o.deleteRating(d.id,t.chat.id,c)},speak(c){if(!t.streamingManager)throw new Error("Please connect to the agent first");function u(){if(typeof c=="string"){if(!d.presenter)throw new Error("Presenter is not initialized");return{type:"text",provider:d.presenter.voice,input:c,ssml:!1}}return c}const p=u();return l.track("agent-speak",p),t.streamingManager.speak({script:p})}}}function Re(e,a,t){const{getById:i}=te(a,t||U);return i(e)}f.ChatMode=M,f.ChatProgress=z,f.ConnectionState=k,f.DocumentType=Q,f.KnowledgeType=X,f.PlanGroup=W,f.Providers=Y,f.RateState=J,f.StreamEvents=K,f.StreamingState=N,f.Subject=q,f.UserPlan=x,f.VideoType=v,f.VoiceAccess=Z,f.createAgentManager=Ie,f.getAgent=Re,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||{}),W=(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))(W||{}),J=(e=>(e.Unrated="Unrated",e.Positive="Positive",e.Negative="Negative",e))(J||{}),M=(e=>(e.Functional="Functional",e.TextOnly="TextOnly",e.Maintenance="Maintenance",e.Playground="Playground",e.DirectPlayback="DirectPlayback",e))(M||{}),z=(e=>(e.Embed="embed",e.Query="query",e.Partial="partial",e.Answer="answer",e.Complete="done",e))(z||{}),q=(e=>(e.KnowledgeProcessing="knowledge/processing",e.KnowledgeIndexing="knowledge/indexing",e.KnowledgeFailed="knowledge/error",e.KnowledgeDone="knowledge/done",e))(q||{}),X=(e=>(e.Knowledge="knowledge",e.Document="document",e.Record="record",e))(X||{}),Q=(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))(Q||{}),v=(e=>(e.Clip="clip",e.Talk="talk",e))(v||{}),N=(e=>(e.Start="START",e.Stop="STOP",e))(N||{}),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||{}),k=(e=>(e.New="new",e.Fail="fail",e.Connected="connected",e.Connecting="connecting",e.Terminating="terminating",e))(k||{}),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 U="https://api.d-id.com",oe="wss://notifications.d-id.com",ce="79f81a83a67430be2bc0fd61042b8faa",V=()=>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=V();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 B(e,a=U,t){const i=async(r,n)=>{const s=await fetch(a+(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 c=await s.text().catch(()=>"Failed to fetch");throw t&&t(new Error(c),{url:r,options:n,headers:s.headers}),new Error(c)}return s.json()};return{get(r,n){return i(r,{...n,method:"GET"})},post(r,n,s){return i(r,{...s,body:JSON.stringify(n),method:"POST"})},delete(r,n,s){return i(r,{...s,body:JSON.stringify(n),method:"DELETE"})},patch(r,n,s){return i(r,{...s,body:JSON.stringify(n),method:"PATCH"})}}}function te(e,a=U,t){const i=B(e,`${a}/agents`,t);return{create(r,n){return i.post("/",r,n)},getAgents(r,n){return i.get(`/${r?`?tag=${r}`:""}`,n).then(s=>s??[])},getById(r,n){return i.get(`/${r}`,n)},delete(r,n){return i.delete(`/${r}`,void 0,n)},update(r,n,s){return i.patch(`/${r}`,n,s)},newChat(r,n){return i.post(`/${r}/chat`,void 0,n)},chat(r,n,s,c){return i.post(`/${r}/chat/${n}`,s,c)},createRating(r,n,s,c){return i.post(`/${r}/chat/${n}/ratings`,s,c)},updateRating(r,n,s,c,d){return i.patch(`/${r}/chat/${n}/ratings/${s}`,c,d)},deleteRating(r,n,s,c){return i.delete(`/${r}/chat/${n}/ratings/${s}`,c)}}}const le=e=>new Promise(a=>setTimeout(a,e));function ge(e){return new Promise((a,t)=>{const{callbacks:i,host:r,auth:n}=e,{onMessage:s=null,onOpen:c=null,onClose:d=null,onError:l=null}=i||{},w=new WebSocket(`${r}?authorization=${ee(n)}`);w.onmessage=s,w.onclose=d,w.onerror=C=>{console.error(C),l==null||l("Websocket failed to connect",C),t(C)},w.onopen=C=>{c==null||c(C),a(w)}})}async function ue(e){const{retries:a=1}=e;let t=null;for(let i=0;(t==null?void 0:t.readyState)!==WebSocket.OPEN;i++)try{t=await ge(e)}catch(r){if(i===a)throw r;await le(i*500)}return t}async function me(e,a,t){const i=t!=null&&t.onMessage?[t.onMessage]:[],r=await ue({auth:e,host:a,callbacks:{onError:t==null?void 0:t.onError,onMessage:n=>{const s=JSON.parse(n.data);i.forEach(c=>c(s.event,s))}}});return{socket:r,disconnect:()=>r.close(),subscribeToEvents:n=>i.push(n)}}const we="X-Playground-Chat";function he(e,a,t,i){const r=B(e,`${a}/agents/${t}`,i);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,session_timeout:n.session_timeout,type:v.Clip})},startConnection(n,s,c){return r.post(`/streams/${n}/sdp`,{session_id:c,answer:s,type:v.Clip})},addIceCandidate(n,s,c){return r.post(`/streams/${n}/ice`,{session_id:c,...s,type:v.Clip})},sendStreamRequest(n,s,c){return r.post(`/streams/${n}`,{session_id:s,...c,type:v.Clip})},close(n,s){return r.delete(`/streams/${n}`,{session_id:s,type:v.Clip})}}}function fe(e,a,t,i){const r=B(e,`${a}/agents/${t}`,i);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,session_timeout:n.session_timeout,type:v.Talk},s)},startConnection(n,s,c,d){return r.post(`/streams/${n}/sdp`,{session_id:c,answer:s,type:v.Talk},d)},addIceCandidate(n,s,c,d){return r.post(`/streams/${n}/ice`,{session_id:c,...s,type:v.Talk},d)},sendStreamRequest(n,s,c,d){return r.post(`/streams/${n}`,{session_id:s,...c,type:v.Talk},d)},close(n,s,c){return r.delete(`/streams/${n}`,{session_id:s,type:v.Talk},c)}}}let ne=!1;const b=(e,a)=>ne&&console.log(e,a),pe=(window.RTCPeerConnection||window.webkitRTCPeerConnection||window.mozRTCPeerConnection).bind(window);function re(e){switch(e){case"connected":return k.Connected;case"checking":return k.Connecting;case"failed":return k.Fail;case"new":case"closed":case"disconnected":default:return k.New}}function ye(){let e=0;return a=>{for(const t of a.values())if(t&&t.type==="inbound-rtp"&&t.kind==="video"){const i=t.bytesReceived,r=i-e>0;return e=i,r}return!1}}function ve(e,a){const i=Math.max(Math.ceil(10),1);let r=0,n=!1;const s=ye();return setInterval(async()=>{const c=await e.getStats();s(c)?(r=0,n||(a==null||a(N.Start),n=!0)):n&&(r++,r>=i&&(a==null||a(N.Stop),n=!1))},100)}async function Ce(e,a,{debug:t=!1,callbacks:i,auth:r,analytics:n,baseURL:s=U}){ne=t;let c;const{startConnection:d,sendStreamRequest:l,close:w,createStream:C,addIceCandidate:L}=a.videoType===v.Clip?he(r,s,e,i.onError):fe(r,s,e,i.onError),{id:R,offer:F,ice_servers:j,session_id:A}=await C(a),o=new pe({iceServers:j}),u=o.createDataChannel("JanusDataChannel");if(!A)throw new Error("Could not create session_id");const p=ve(o,i.onVideoStateChange);o.onicecandidate=g=>{b("peerConnection.onicecandidate",g),g.candidate&&g.candidate.sdpMid&&g.candidate.sdpMLineIndex!==null?L(R,{candidate:g.candidate.candidate,sdpMid:g.candidate.sdpMid,sdpMLineIndex:g.candidate.sdpMLineIndex},A):L(R,{candidate:null},A)},o.oniceconnectionstatechange=()=>{var m;b("peerConnection.oniceconnectionstatechange => "+o.iceConnectionState);const g=re(o.iceConnectionState);g===k.Connected?c=setTimeout(()=>{var y;(y=i.onConnectionStateChange)==null||y.call(i,k.Connected)},5e3):(clearTimeout(c),(m=i.onConnectionStateChange)==null||m.call(i,g))},o.ontrack=g=>{var m;b("peerConnection.ontrack",g),(m=i.onSrcObjectReady)==null||m.call(i,g.streams[0])},u.onmessage=g=>{var m;if(u.readyState==="open"){const[y,S]=g.data.split(":");y===K.StreamReady&&(clearTimeout(c),(m=i.onConnectionStateChange)==null||m.call(i,k.Connected))}},await o.setRemoteDescription(F),b("set remote description OK");const E=await o.createAnswer();return b("create answer OK"),await o.setLocalDescription(E),b("set local description OK"),await d(R,E,A),b("start connection OK"),{speak(g){return l(R,A,g)},async disconnect(){var g,m,y;if(R){if(o){if(re(o.iceConnectionState)===k.New){(g=i.onVideoStateChange)==null||g.call(i,N.Stop),clearInterval(p);return}o.close(),o.oniceconnectionstatechange=null,o.onnegotiationneeded=null,o.onicecandidate=null,o.ontrack=null}try{await w(R,A).catch(S=>{})}catch(S){b("Error on close stream connection",S)}(m=i.onConnectionStateChange)==null||m.call(i,k.New),(y=i.onVideoStateChange)==null||y.call(i,N.Stop),clearInterval(p)}},sessionId:A,streamId:R}}let H={};function Se(e){const a=window!=null&&window.hasOwnProperty("DID_AGENTS_API")?"agents-ui":"agents-sdk",t={token:e.token||"testKey",distinct_id:e.distinctId||G(),agentId:e.agent.id,agentType:e.agent.presenter.type,owner_id:e.agent.owner_id??""};return{...t,isEnabled:e.isEnabled??!0,getRandom:()=>Math.random().toString(16).slice(2),track(i,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:i,properties:{...r,...t,source:a,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))},linkTrack(i,r,n,s){H[i]||(H[i]={events:{},resolvedDependencies:[]}),s.includes(n)||s.push(n);const c=H[i];if(c.events[n]={props:r},c.resolvedDependencies.push(n),s.every(l=>c.resolvedDependencies.includes(l))){const l=s.reduce((w,C)=>c.events[C]?{...w,...c.events[C].props}:w,{});this.track(i,l),c.resolvedDependencies=c.resolvedDependencies.filter(w=>!s.includes(w)),s.forEach(w=>{delete c.events[w]})}}}}function _e(e){var i,r,n,s,c;const a=()=>/Mobi|Android/i.test(navigator.userAgent)?"Mobile":"Desktop";return{$os:`${(()=>{const d=navigator.platform;return d.toLowerCase().includes("win")?"Windows":d.toLowerCase().includes("mac")?"Mac OS X":d.toLowerCase().includes("linux")?"Linux":"Unknown"})()}`,isMobile:`${a()=="Mobile"}`,browser:navigator.userAgent,origin:window.location.origin,agentType:(i=e.presenter)==null?void 0:i.type,agentVoice:{voiceId:(n=(r=e.presenter)==null?void 0:r.voice)==null?void 0:n.voice_id,provider:(c=(s=e.presenter)==null?void 0:s.voice)==null?void 0:c.type}}}const Me=1080;let O=0;function ke(e,a){var t,i,r;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");return{videoType:v.Talk,source_url:e.presenter.source_url,session_timeout:(t=a==null?void 0:a.streamOptions)==null?void 0:t.session_timeout,stream_warmup:((i=a==null?void 0:a.streamOptions)==null?void 0:i.stream_warmup)??!0,compatibility_mode:(r=a==null?void 0:a.streamOptions)==null?void 0:r.compatibility_mode,output_resolution:(a==null?void 0:a.outputResolution)||(e.presenter.stitch?Me:void 0)}}function ae(e){return e===M.Playground?{[we]:"true"}:{}}async function ie(e,a,t,i){try{const r=await a.newChat(e,ae(i));return t.track("agent-chat",{event:"created",chat_id:r.id,agent_id:e}),r}catch(r){try{console.error(r);const n=JSON.parse(r.message);if((n==null?void 0:n.kind)==="InsufficientCreditsError")throw new Error("InsufficientCreditsError")}catch(n){console.error("Error parsing the error message:",n)}throw new Error("Cannot create new chat")}}function Ee(e,a,t,i,r){return new Promise(async(n,s)=>{O=0;const c=await Ce(e.id,ke(e,a),{...a,analytics:i,callbacks:{...a.callbacks,onConnectionStateChange:async d=>{var l,w;d===k.Connected&&(!r&&a.mode!==M.DirectPlayback&&(r=await ie(e.id,t,i,a.mode).catch(C=>{s(C)})),c?n({chat:r,streamingManager:c}):r&&s(new Error("Something went wrong while initializing the manager"))),(w=(l=a.callbacks).onConnectionStateChange)==null||w.call(l,d)},onVideoStateChange(d){var l,w;(w=(l=a.callbacks).onVideoStateChange)==null||w.call(l,d),O>0&&d===N.Start&&i.linkTrack("agent-video",{event:"start",latency:Date.now()-O},"start",[K.StreamVideoCreated])}}}).catch(s)})}function se(e){let a="";if(e.greetings&&e.greetings.length>0){const t=Math.floor(Math.random()*e.greetings.length);a=e.greetings[t]}else a=`Hi! I'm ${e.preview_name||"My Agent"}. How can I help you?`;return[{content:a,id:V(),role:"assistant",created_at:new Date().toISOString()}]}async function Ie(e,a){var F,j,A;const t={messages:[],chatMode:a.mode||M.Functional};let i=-1;const r=a.baseURL||U,n=a.wsURL||oe,s=a.mixpanelKey||ce,c=te(a.auth,r,a.callbacks.onError),d=await c.getById(e);t.messages=se(d),(j=(F=a.callbacks).onNewMessage)==null||j.call(F,t.messages,"answer");const l=Se({token:s,agent:d,...a});l.track("agent-sdk",{event:"loaded",..._e(d)});const w={onMessage:(o,u)=>{var p,E,g,m,y,S,_;if("content"in u){const{content:h}=u,I=t.messages[t.messages.length-1];(I==null?void 0:I.role)==="assistant"&&(i<t.messages.length&&(I.content=o===z.Partial?I.content+h:h),o===z.Answer&&(i=t.messages.length,l.track("agent-message-received",{messages:t.messages.length}))),(E=(p=a.callbacks).onNewMessage)==null||E.call(p,t.messages,o===z.Answer?"answer":"partial")}else{const h=K,I=[h.StreamVideoDone,h.StreamVideoError,h.StreamVideoRejected],T=[h.StreamFailed,h.StreamVideoError,h.StreamVideoRejected];o=o;const P=(g=d.llm)==null?void 0:g.template;if(o===h.StreamVideoCreated){const{event:D,...$}=u;$.llm={...$.llm,template:P},l.linkTrack("agent-video",{...$},h.StreamVideoCreated,["start"])}else if(I.includes(o)){const D=o.split("/")[1],$={...u,event:D};$.llm={...$.llm,template:P},l.track("agent-video",{...$,event:D})}T.includes(o)&&((y=(m=a.callbacks).onError)==null||y.call(m,new Error(`Stream failed with event ${o}`),{data:u})),u.event===h.StreamDone&&((_=(S=a.callbacks).onConnectionStateChange)==null||_.call(S,k.New))}}};async function C(o){var y,S,_,h,I;O=0,i=-1,o&&(delete t.chat,t.messages=se(d),(S=(y=a.callbacks).onNewMessage)==null||S.call(y,t.messages,"answer"));const u=a.mode===M.DirectPlayback?Promise.resolve(void 0):me(a.auth,n,w),p=Ee(d,a,c,l,t.chat).catch(T=>{throw R(M.Maintenance),T}),[E,{streamingManager:g,chat:m}]=await Promise.all([u,p]);m&&m.id!==((_=t.chat)==null?void 0:_.id)&&((I=(h=a.callbacks).onNewChat)==null||I.call(h,m.id)),t.streamingManager=g,t.socketManager=E,t.chat=m,R((m==null?void 0:m.chat_mode)??a.mode??M.Functional)}async function L(){var o,u;(o=t.socketManager)==null||o.disconnect(),await((u=t.streamingManager)==null?void 0:u.disconnect()),delete t.streamingManager,delete t.socketManager}async function R(o){var u,p;o!==t.chatMode&&(l.track("agent-mode-change",{mode:o}),t.chatMode=o,t.chatMode!==M.Functional&&await L(),(p=(u=a.callbacks).onModeChange)==null||p.call(u,o))}return{agent:d,starterMessages:((A=d.knowledge)==null?void 0:A.starter_message)||[],changeMode:R,async connect(){var o;await C(!0),l.track("agent-chat",{event:"connect",chatId:(o=t.chat)==null?void 0:o.id,agentId:d.id,mode:t.chatMode})},async reconnect(){var o;await L(),await C(!1),l.track("agent-chat",{event:"reconnect",chatId:(o=t.chat)==null?void 0:o.id,agentId:d.id,mode:t.chatMode})},async disconnect(){var o;await L(),l.track("agent-chat",{event:"disconnect",chatId:(o=t.chat)==null?void 0:o.id,agentId:d.id,mode:t.chatMode})},async chat(o){var p,E,g,m,y,S;const u=V();try{if(O=Date.now(),a.mode===M.DirectPlayback)throw new Error("Direct playback is enabled, chat is disabled");if(o.length>=800)throw new Error("Message cannot be more than 800 characters");if(o.length===0)throw new Error("Message cannot be empty");if(t.chatMode===M.Maintenance)throw new Error("Chat is in maintenance mode");if(![M.TextOnly,M.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.chat||(t.chat=await ie(d.id,c,l,t.chatMode),(E=(p=a.callbacks).onNewChat)==null||E.call(p,t.chat.id)),t.messages.push({id:V(),role:"user",content:o,created_at:new Date(O).toISOString()}),(m=(g=a.callbacks).onNewMessage)==null||m.call(g,t.messages,"user");const _={id:u,role:"assistant",content:"",created_at:new Date().toISOString(),matches:[]},h=[...t.messages];t.messages.push(_);const I=P=>{var D,$;return c.chat(d.id,P,{sessionId:(D=t.streamingManager)==null?void 0:D.sessionId,streamId:($=t.streamingManager)==null?void 0:$.streamId,chatMode:t.chatMode,messages:h},ae(t.chatMode))},T=await I(t.chat.id).catch(async P=>{var D;if(!((D=P==null?void 0:P.message)!=null&&D.includes("missing or invalid session_id")))throw P;return await L(),await C(!1),I(t.chat.id)});return l.track("agent-message-send",{event:"success",messages:t.messages.length+1}),T.result&&(_.content=T.result,_.matches=T.matches,_.context=T.context,l.track("agent-message-received",{latency:Date.now()-O,messages:t.messages.length}),(S=(y=a.callbacks).onNewMessage)==null||S.call(y,t.messages,"answer")),T}catch(_){throw t.messages[t.messages.length-1].id===u&&t.messages.pop(),l.track("agent-message-send",{event:"error",messages:t.messages.length}),_}},rate(o,u,p){var m,y,S,_;const E=t.messages.find(h=>h.id===o);if(t.chat){if(!E)throw new Error("Message not found")}else throw new Error("Chat is not initialized");const g=((m=E.matches)==null?void 0:m.map(h=>[h.document_id,h.id]))??[];return l.track("agent-rate",{event:p?"update":"create",thumb:u===1?"up":"down",knowledge_id:((y=d.knowledge)==null?void 0:y.id)??"",matches:g,score:u}),p?c.updateRating(d.id,t.chat.id,p,{knowledge_id:((S=d.knowledge)==null?void 0:S.id)??"",message_id:o,matches:g,score:u}):c.createRating(d.id,t.chat.id,{knowledge_id:((_=d.knowledge)==null?void 0:_.id)??"",message_id:o,matches:g,score:u})},deleteRate(o){var u;if(!t.chat)throw new Error("Chat is not initialized");return l.track("agent-rate-delete",{type:"text",chat_id:(u=t.chat)==null?void 0:u.id,id:o}),c.deleteRating(d.id,t.chat.id,o)},speak(o){if(!t.streamingManager)throw new Error("Please connect to the agent first");function u(){if(typeof o=="string"){if(!d.presenter)throw new Error("Presenter is not initialized");return{type:"text",provider:d.presenter.voice,input:o,ssml:!1}}return o}const p=u();return l.track("agent-speak",p),t.streamingManager.speak({script:p})}}}function Re(e,a,t){const{getById:i}=te(a,t||U);return i(e)}f.ChatMode=M,f.ChatProgress=z,f.ConnectionState=k,f.DocumentType=Q,f.KnowledgeType=X,f.PlanGroup=W,f.Providers=Y,f.RateState=J,f.StreamEvents=K,f.StreamingState=N,f.Subject=q,f.UserPlan=x,f.VideoType=v,f.VoiceAccess=Z,f.createAgentManager=Ie,f.getAgent=Re,Object.defineProperty(f,Symbol.toStringTag,{value:"Module"})});
|