@d-id/client-sdk 1.0.19-beta.125 → 1.0.19-beta.126
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 +181 -181
- package/dist/index.umd.cjs +1 -1
- package/dist/src/types/entities/agents/manager.d.ts +1 -0
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
var
|
|
2
|
-
const
|
|
1
|
+
var ne = /* @__PURE__ */ ((e) => (e.TRIAL = "trial", e.BASIC = "basic", e.ENTERPRISE = "enterprise", e.LITE = "lite", e.ADVANCED = "advanced", e))(ne || {}), re = /* @__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))(re || {}), ae = /* @__PURE__ */ ((e) => (e.Created = "created", e.Started = "started", e.Done = "done", e.Error = "error", e.Rejected = "rejected", e.Ready = "ready", e))(ae || {}), ie = /* @__PURE__ */ ((e) => (e.Unrated = "Unrated", e.Positive = "Positive", e.Negative = "Negative", e))(ie || {}), M = /* @__PURE__ */ ((e) => (e.Functional = "Functional", e.TextOnly = "TextOnly", e.Maintenance = "Maintenance", e.Playground = "Playground", e.DirectPlayback = "DirectPlayback", e))(M || {}), x = /* @__PURE__ */ ((e) => (e.Embed = "embed", e.Query = "query", e.Partial = "partial", e.Answer = "answer", e.Complete = "done", e))(x || {}), se = /* @__PURE__ */ ((e) => (e.KnowledgeProcessing = "knowledge/processing", e.KnowledgeIndexing = "knowledge/indexing", e.KnowledgeFailed = "knowledge/error", e.KnowledgeDone = "knowledge/done", e))(se || {}), oe = /* @__PURE__ */ ((e) => (e.Knowledge = "knowledge", e.Document = "document", e.Record = "record", e))(oe || {}), ce = /* @__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))(ce || {}), J = /* @__PURE__ */ ((e) => (e.Clip = "clip", e.Talk = "talk", e))(J || {});
|
|
2
|
+
const de = (e) => {
|
|
3
3
|
switch (e) {
|
|
4
4
|
case "clip":
|
|
5
5
|
return "clip";
|
|
@@ -9,29 +9,29 @@ const ce = (e) => {
|
|
|
9
9
|
throw new Error(`Unknown video type: ${e}`);
|
|
10
10
|
}
|
|
11
11
|
};
|
|
12
|
-
var T = /* @__PURE__ */ ((e) => (e.Start = "START", e.Stop = "STOP", e))(T || {}),
|
|
13
|
-
const
|
|
14
|
-
function
|
|
12
|
+
var T = /* @__PURE__ */ ((e) => (e.Start = "START", e.Stop = "STOP", e))(T || {}), F = /* @__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))(F || {}), y = /* @__PURE__ */ ((e) => (e.New = "new", e.Fail = "fail", e.Connected = "connected", e.Connecting = "connecting", e.Closed = "closed", e.Completed = "completed", e.Disconnected = "disconnected", e))(y || {}), le = /* @__PURE__ */ ((e) => (e.Amazon = "amazon", e.Microsoft = "microsoft", e.Afflorithmics = "afflorithmics", e.Elevenlabs = "elevenlabs", e))(le || {}), ge = /* @__PURE__ */ ((e) => (e.Public = "public", e.Premium = "premium", e.Private = "private", e))(ge || {}), B = { BASE_URL: "/", MODE: "dev", DEV: !1, PROD: !0, SSR: !1 };
|
|
13
|
+
const V = B.VITE_DID_API_URL, me = B.VITE_WS_ENDPOINT, ue = B.VITE_MIXPANEL_KEY, K = () => Math.random().toString(16).slice(2);
|
|
14
|
+
function X() {
|
|
15
15
|
let e = window.localStorage.getItem("did_external_key_id");
|
|
16
16
|
return e || (e = Math.random().toString(16).slice(2), window.localStorage.setItem("did_external_key_id", e)), e;
|
|
17
17
|
}
|
|
18
|
-
let
|
|
19
|
-
function
|
|
18
|
+
let we = K();
|
|
19
|
+
function Y(e) {
|
|
20
20
|
if (e.type === "bearer")
|
|
21
21
|
return `Bearer ${e.token}`;
|
|
22
22
|
if (e.type === "basic")
|
|
23
23
|
return `Basic ${btoa(`${e.username}:${e.password}`)}`;
|
|
24
24
|
if (e.type === "key")
|
|
25
|
-
return `Client-Key ${e.clientKey}.${
|
|
25
|
+
return `Client-Key ${e.clientKey}.${X()}_${we}`;
|
|
26
26
|
throw new Error(`Unknown auth type: ${e}`);
|
|
27
27
|
}
|
|
28
|
-
function
|
|
28
|
+
function H(e, n = V, s) {
|
|
29
29
|
const a = async (t, r) => {
|
|
30
30
|
const i = await fetch(n + (t != null && t.startsWith("/") ? t : `/${t}`), {
|
|
31
31
|
...r,
|
|
32
32
|
headers: {
|
|
33
33
|
...r == null ? void 0 : r.headers,
|
|
34
|
-
Authorization:
|
|
34
|
+
Authorization: Y(e),
|
|
35
35
|
"Content-Type": "application/json"
|
|
36
36
|
}
|
|
37
37
|
});
|
|
@@ -75,8 +75,8 @@ function B(e, n = z, s) {
|
|
|
75
75
|
}
|
|
76
76
|
};
|
|
77
77
|
}
|
|
78
|
-
function
|
|
79
|
-
const a =
|
|
78
|
+
function Z(e, n = V, s) {
|
|
79
|
+
const a = H(e, `${n}/agents`, s);
|
|
80
80
|
return {
|
|
81
81
|
create(t, r) {
|
|
82
82
|
return a.post("/", t, r);
|
|
@@ -110,8 +110,8 @@ function Y(e, n = z, s) {
|
|
|
110
110
|
}
|
|
111
111
|
};
|
|
112
112
|
}
|
|
113
|
-
const
|
|
114
|
-
function
|
|
113
|
+
const he = (e) => new Promise((n) => setTimeout(n, e));
|
|
114
|
+
function fe(e) {
|
|
115
115
|
return new Promise((n, s) => {
|
|
116
116
|
const {
|
|
117
117
|
callbacks: a,
|
|
@@ -122,31 +122,31 @@ function he(e) {
|
|
|
122
122
|
onOpen: o = null,
|
|
123
123
|
onClose: l = null,
|
|
124
124
|
onError: d = null
|
|
125
|
-
} = a || {},
|
|
126
|
-
|
|
125
|
+
} = a || {}, m = new WebSocket(`${t}?authorization=${Y(r)}`);
|
|
126
|
+
m.onmessage = i, m.onclose = l, m.onerror = (h) => {
|
|
127
127
|
console.error(h), d == null || d("Websocket failed to connect", h), s(h);
|
|
128
|
-
},
|
|
129
|
-
o == null || o(h), n(
|
|
128
|
+
}, m.onopen = (h) => {
|
|
129
|
+
o == null || o(h), n(m);
|
|
130
130
|
};
|
|
131
131
|
});
|
|
132
132
|
}
|
|
133
|
-
async function
|
|
133
|
+
async function pe(e) {
|
|
134
134
|
const {
|
|
135
135
|
retries: n = 1
|
|
136
136
|
} = e;
|
|
137
137
|
let s = null;
|
|
138
138
|
for (let a = 0; (s == null ? void 0 : s.readyState) !== WebSocket.OPEN; a++)
|
|
139
139
|
try {
|
|
140
|
-
s = await
|
|
140
|
+
s = await fe(e);
|
|
141
141
|
} catch (t) {
|
|
142
142
|
if (a === n)
|
|
143
143
|
throw t;
|
|
144
|
-
await
|
|
144
|
+
await he(a * 500);
|
|
145
145
|
}
|
|
146
146
|
return s;
|
|
147
147
|
}
|
|
148
|
-
async function
|
|
149
|
-
const a = s != null && s.onMessage ? [s.onMessage] : [], t = await
|
|
148
|
+
async function ve(e, n, s) {
|
|
149
|
+
const a = s != null && s.onMessage ? [s.onMessage] : [], t = await pe({
|
|
150
150
|
auth: e,
|
|
151
151
|
host: n,
|
|
152
152
|
callbacks: {
|
|
@@ -163,9 +163,9 @@ async function pe(e, n, s) {
|
|
|
163
163
|
subscribeToEvents: (r) => a.push(r)
|
|
164
164
|
};
|
|
165
165
|
}
|
|
166
|
-
const
|
|
167
|
-
function
|
|
168
|
-
const t =
|
|
166
|
+
const ye = "X-Playground-Chat";
|
|
167
|
+
function Ce(e, n, s, a) {
|
|
168
|
+
const t = H(e, `${n}/agents/${s}`, a);
|
|
169
169
|
return {
|
|
170
170
|
createStream(r) {
|
|
171
171
|
return t.post("/streams", {
|
|
@@ -200,8 +200,8 @@ function ye(e, n, s, a) {
|
|
|
200
200
|
}
|
|
201
201
|
};
|
|
202
202
|
}
|
|
203
|
-
function
|
|
204
|
-
const t =
|
|
203
|
+
function _e(e, n, s, a) {
|
|
204
|
+
const t = H(e, `${n}/agents/${s}`, a);
|
|
205
205
|
return {
|
|
206
206
|
createStream(r, i) {
|
|
207
207
|
return t.post("/streams", {
|
|
@@ -239,9 +239,9 @@ function Ce(e, n, s, a) {
|
|
|
239
239
|
}
|
|
240
240
|
};
|
|
241
241
|
}
|
|
242
|
-
let
|
|
243
|
-
const b = (e, n) =>
|
|
244
|
-
function
|
|
242
|
+
let Q = !0;
|
|
243
|
+
const b = (e, n) => Q && console.log(e, n), Me = (window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection).bind(window);
|
|
244
|
+
function j(e) {
|
|
245
245
|
switch (e) {
|
|
246
246
|
case "connected":
|
|
247
247
|
return y.Connected;
|
|
@@ -261,7 +261,7 @@ function H(e) {
|
|
|
261
261
|
return y.New;
|
|
262
262
|
}
|
|
263
263
|
}
|
|
264
|
-
function
|
|
264
|
+
function Se() {
|
|
265
265
|
let e = 0;
|
|
266
266
|
return (n) => {
|
|
267
267
|
for (const s of n.values())
|
|
@@ -272,60 +272,60 @@ function ke() {
|
|
|
272
272
|
return !1;
|
|
273
273
|
};
|
|
274
274
|
}
|
|
275
|
-
function
|
|
275
|
+
function ke(e, n) {
|
|
276
276
|
const a = Math.max(Math.ceil(10), 1);
|
|
277
277
|
let t = 0, r = !1;
|
|
278
|
-
const i =
|
|
278
|
+
const i = Se();
|
|
279
279
|
return setInterval(async () => {
|
|
280
280
|
const o = await e.getStats();
|
|
281
|
-
i(o) ? (t = 0, r || (n == null || n(T.Start), r = !0)) : r && (t++, t >= a && (n == null || n(T.Stop), r = !1));
|
|
281
|
+
i(o) ? (console.log("Receiving video bytes"), t = 0, r || (n == null || n(T.Start), r = !0)) : r && (t++, t >= a && (n == null || n(T.Stop), r = !1));
|
|
282
282
|
}, 100);
|
|
283
283
|
}
|
|
284
|
-
async function
|
|
284
|
+
async function Ee(e, n, {
|
|
285
285
|
debug: s = !1,
|
|
286
286
|
callbacks: a,
|
|
287
287
|
auth: t,
|
|
288
|
-
baseURL: r =
|
|
288
|
+
baseURL: r = V,
|
|
289
289
|
warmup: i
|
|
290
290
|
}) {
|
|
291
|
-
|
|
291
|
+
Q = s;
|
|
292
292
|
let o;
|
|
293
293
|
const {
|
|
294
294
|
startConnection: l,
|
|
295
295
|
sendStreamRequest: d,
|
|
296
|
-
close:
|
|
296
|
+
close: m,
|
|
297
297
|
createStream: h,
|
|
298
|
-
addIceCandidate:
|
|
299
|
-
} = n.videoType ===
|
|
298
|
+
addIceCandidate: S
|
|
299
|
+
} = n.videoType === J.Clip ? Ce(t, r, e, a.onError) : _e(t, r, e, a.onError), {
|
|
300
300
|
id: _,
|
|
301
301
|
offer: O,
|
|
302
|
-
ice_servers:
|
|
302
|
+
ice_servers: z,
|
|
303
303
|
session_id: E
|
|
304
|
-
} = await h(n), p = new
|
|
305
|
-
iceServers:
|
|
304
|
+
} = await h(n), p = new Me({
|
|
305
|
+
iceServers: z
|
|
306
306
|
});
|
|
307
307
|
if (!E)
|
|
308
308
|
throw new Error("Could not create session_id");
|
|
309
|
-
const c =
|
|
310
|
-
p.onicecandidate = (
|
|
311
|
-
b("peerConnection.onicecandidate",
|
|
312
|
-
candidate:
|
|
313
|
-
sdpMid:
|
|
314
|
-
sdpMLineIndex:
|
|
315
|
-
}, E) :
|
|
309
|
+
const c = ke(p, a.onVideoStateChange);
|
|
310
|
+
p.onicecandidate = (g) => {
|
|
311
|
+
b("peerConnection.onicecandidate", g), g.candidate && g.candidate.sdpMid && g.candidate.sdpMLineIndex !== null ? S(_, {
|
|
312
|
+
candidate: g.candidate.candidate,
|
|
313
|
+
sdpMid: g.candidate.sdpMid,
|
|
314
|
+
sdpMLineIndex: g.candidate.sdpMLineIndex
|
|
315
|
+
}, E) : S(_, {
|
|
316
316
|
candidate: null
|
|
317
317
|
}, E);
|
|
318
318
|
}, p.oniceconnectionstatechange = () => {
|
|
319
319
|
var f;
|
|
320
|
-
|
|
321
|
-
const
|
|
322
|
-
|
|
320
|
+
console.log("peerConnection.oniceconnectionstatechange => " + p.iceConnectionState);
|
|
321
|
+
const g = j(p.iceConnectionState);
|
|
322
|
+
g === y.Connected ? (console.log("connected"), o = setTimeout(() => {
|
|
323
323
|
var w;
|
|
324
324
|
return (w = a.onConnectionStateChange) == null ? void 0 : w.call(a, y.Connected);
|
|
325
|
-
},
|
|
326
|
-
}, p.ontrack = (
|
|
325
|
+
}, 0)) : (clearTimeout(o), (f = a.onConnectionStateChange) == null || f.call(a, g));
|
|
326
|
+
}, p.ontrack = (g) => {
|
|
327
327
|
var f;
|
|
328
|
-
|
|
328
|
+
console.log("peerConnection.ontrack", g), (f = a.onSrcObjectReady) == null || f.call(a, g.streams[0]);
|
|
329
329
|
}, await p.setRemoteDescription(O), b("set remote description OK");
|
|
330
330
|
const u = await p.createAnswer();
|
|
331
331
|
return b("create answer OK"), await p.setLocalDescription(u), b("set local description OK"), await l(_, u, E), b("start connection OK"), {
|
|
@@ -333,25 +333,25 @@ async function Se(e, n, {
|
|
|
333
333
|
* Method to send request to server to get clip or talk depend on you payload
|
|
334
334
|
* @param payload
|
|
335
335
|
*/
|
|
336
|
-
speak(
|
|
337
|
-
return d(_, E,
|
|
336
|
+
speak(g) {
|
|
337
|
+
return d(_, E, g);
|
|
338
338
|
},
|
|
339
339
|
/**
|
|
340
340
|
* Method to close RTC connection
|
|
341
341
|
*/
|
|
342
342
|
async disconnect() {
|
|
343
|
-
var
|
|
343
|
+
var g, f;
|
|
344
344
|
if (_) {
|
|
345
|
-
const w =
|
|
345
|
+
const w = j(p.iceConnectionState);
|
|
346
346
|
if (p) {
|
|
347
347
|
if (w === y.New) {
|
|
348
|
-
(
|
|
348
|
+
(g = a.onVideoStateChange) == null || g.call(a, T.Stop), clearInterval(c);
|
|
349
349
|
return;
|
|
350
350
|
}
|
|
351
351
|
p.close(), p.oniceconnectionstatechange = null, p.onnegotiationneeded = null, p.onicecandidate = null, p.ontrack = null;
|
|
352
352
|
}
|
|
353
353
|
try {
|
|
354
|
-
w === y.Connected && await
|
|
354
|
+
w === y.Connected && await m(_, E).catch((v) => {
|
|
355
355
|
});
|
|
356
356
|
} catch (v) {
|
|
357
357
|
b("Error on close stream connection", v);
|
|
@@ -369,11 +369,11 @@ async function Se(e, n, {
|
|
|
369
369
|
streamId: _
|
|
370
370
|
};
|
|
371
371
|
}
|
|
372
|
-
let
|
|
373
|
-
function
|
|
372
|
+
let W = {};
|
|
373
|
+
function Ie(e) {
|
|
374
374
|
const n = window != null && window.hasOwnProperty("DID_AGENTS_API") ? "agents-ui" : "agents-sdk", s = e.agent.presenter, a = {
|
|
375
375
|
token: e.token || "testKey",
|
|
376
|
-
distinct_id: e.distinctId ||
|
|
376
|
+
distinct_id: e.distinctId || X(),
|
|
377
377
|
agentId: e.agent.id,
|
|
378
378
|
agentType: s.type === "clip" && s.presenter_id.startsWith("v2_") ? "clip_v2" : s.type,
|
|
379
379
|
owner_id: e.agent.owner_id ?? ""
|
|
@@ -413,26 +413,26 @@ function Ee(e) {
|
|
|
413
413
|
return fetch("https://api-js.mixpanel.com/track/?verbose=1&ip=1", l).then((d) => d.json()).catch((d) => console.error(d));
|
|
414
414
|
},
|
|
415
415
|
linkTrack(t, r, i, o) {
|
|
416
|
-
|
|
416
|
+
W[t] || (W[t] = {
|
|
417
417
|
events: {},
|
|
418
418
|
resolvedDependencies: []
|
|
419
419
|
}), o.includes(i) || o.push(i);
|
|
420
|
-
const l =
|
|
420
|
+
const l = W[t];
|
|
421
421
|
if (l.events[i] = {
|
|
422
422
|
props: r
|
|
423
|
-
}, l.resolvedDependencies.push(i), o.every((
|
|
424
|
-
const
|
|
423
|
+
}, l.resolvedDependencies.push(i), o.every((m) => l.resolvedDependencies.includes(m))) {
|
|
424
|
+
const m = o.reduce((h, S) => l.events[S] ? {
|
|
425
425
|
...h,
|
|
426
|
-
...l.events[
|
|
426
|
+
...l.events[S].props
|
|
427
427
|
} : h, {});
|
|
428
|
-
this.track(t,
|
|
428
|
+
this.track(t, m), l.resolvedDependencies = l.resolvedDependencies.filter((h) => !o.includes(h)), o.forEach((h) => {
|
|
429
429
|
delete l.events[h];
|
|
430
430
|
});
|
|
431
431
|
}
|
|
432
432
|
}
|
|
433
433
|
};
|
|
434
434
|
}
|
|
435
|
-
function
|
|
435
|
+
function Re(e) {
|
|
436
436
|
var t, r, i, o;
|
|
437
437
|
const n = () => /Mobi|Android/i.test(navigator.userAgent) ? "Mobile" : "Desktop", s = () => {
|
|
438
438
|
const l = navigator.platform;
|
|
@@ -450,8 +450,8 @@ function Ie(e) {
|
|
|
450
450
|
}
|
|
451
451
|
};
|
|
452
452
|
}
|
|
453
|
-
function
|
|
454
|
-
var d,
|
|
453
|
+
function $e(e, n, s) {
|
|
454
|
+
var d, m;
|
|
455
455
|
const {
|
|
456
456
|
event: a,
|
|
457
457
|
...t
|
|
@@ -471,7 +471,7 @@ function Re(e, n, s) {
|
|
|
471
471
|
script: {
|
|
472
472
|
...t.script,
|
|
473
473
|
provider: {
|
|
474
|
-
...(
|
|
474
|
+
...(m = t == null ? void 0 : t.script) == null ? void 0 : m.provider,
|
|
475
475
|
language: i
|
|
476
476
|
}
|
|
477
477
|
},
|
|
@@ -480,77 +480,77 @@ function Re(e, n, s) {
|
|
|
480
480
|
};
|
|
481
481
|
}
|
|
482
482
|
let D = 0;
|
|
483
|
-
function
|
|
483
|
+
function Ae(e, n) {
|
|
484
484
|
var s, a, t, r;
|
|
485
485
|
return {
|
|
486
|
-
videoType:
|
|
486
|
+
videoType: de(e.presenter.type),
|
|
487
487
|
output_resolution: (s = n == null ? void 0 : n.streamOptions) == null ? void 0 : s.outputResolution,
|
|
488
488
|
session_timeout: (a = n == null ? void 0 : n.streamOptions) == null ? void 0 : a.sessionTimeout,
|
|
489
489
|
stream_warmup: (t = n == null ? void 0 : n.streamOptions) == null ? void 0 : t.streamWarmup,
|
|
490
490
|
compatibility_mode: (r = n == null ? void 0 : n.streamOptions) == null ? void 0 : r.compatibilityMode
|
|
491
491
|
};
|
|
492
492
|
}
|
|
493
|
-
function
|
|
494
|
-
return e ===
|
|
493
|
+
function G(e) {
|
|
494
|
+
return e === M.Playground ? {
|
|
495
495
|
headers: {
|
|
496
|
-
[
|
|
496
|
+
[ye]: "true"
|
|
497
497
|
}
|
|
498
498
|
} : {};
|
|
499
499
|
}
|
|
500
|
-
async function
|
|
500
|
+
async function ee(e, n, s, a, t) {
|
|
501
501
|
try {
|
|
502
|
-
const
|
|
503
|
-
persist: !
|
|
504
|
-
},
|
|
502
|
+
const r = await n.newChat(e, {
|
|
503
|
+
persist: t ?? !1
|
|
504
|
+
}, G(a));
|
|
505
505
|
return s.track("agent-chat", {
|
|
506
506
|
event: "created",
|
|
507
|
-
chat_id:
|
|
507
|
+
chat_id: r.id,
|
|
508
508
|
agent_id: e,
|
|
509
509
|
mode: a
|
|
510
|
-
}),
|
|
511
|
-
} catch (
|
|
510
|
+
}), r;
|
|
511
|
+
} catch (r) {
|
|
512
512
|
try {
|
|
513
|
-
console.error(
|
|
514
|
-
const
|
|
515
|
-
if ((
|
|
513
|
+
console.error(r);
|
|
514
|
+
const i = JSON.parse(r.message);
|
|
515
|
+
if ((i == null ? void 0 : i.kind) === "InsufficientCreditsError")
|
|
516
516
|
throw new Error("InsufficientCreditsError");
|
|
517
|
-
} catch (
|
|
518
|
-
console.error("Error parsing the error message:",
|
|
517
|
+
} catch (i) {
|
|
518
|
+
console.error("Error parsing the error message:", i);
|
|
519
519
|
}
|
|
520
520
|
throw new Error("Cannot create new chat");
|
|
521
521
|
}
|
|
522
522
|
}
|
|
523
|
-
function
|
|
523
|
+
function Pe(e, n, s, a, t) {
|
|
524
524
|
return new Promise(async (r, i) => {
|
|
525
525
|
var l;
|
|
526
526
|
D = 0;
|
|
527
|
-
const o = await
|
|
527
|
+
const o = await Ee(e.id, Ae(e, n), {
|
|
528
528
|
...n,
|
|
529
529
|
analytics: a,
|
|
530
530
|
warmup: (l = n.streamOptions) == null ? void 0 : l.streamWarmup,
|
|
531
531
|
callbacks: {
|
|
532
532
|
...n.callbacks,
|
|
533
533
|
onConnectionStateChange: async (d) => {
|
|
534
|
-
var
|
|
535
|
-
d === y.Connected && (!t && n.mode !==
|
|
536
|
-
i(
|
|
534
|
+
var m, h;
|
|
535
|
+
d === y.Connected && (!t && n.mode !== M.DirectPlayback && (t = await ee(e.id, s, a, n.mode, n.persistentChat).catch((S) => {
|
|
536
|
+
i(S);
|
|
537
537
|
})), o ? r({
|
|
538
538
|
chat: t,
|
|
539
539
|
streamingManager: o
|
|
540
|
-
}) : t && i(new Error("Something went wrong while initializing the manager"))), (h = (
|
|
540
|
+
}) : t && i(new Error("Something went wrong while initializing the manager"))), (h = (m = n.callbacks).onConnectionStateChange) == null || h.call(m, d);
|
|
541
541
|
},
|
|
542
542
|
onVideoStateChange(d) {
|
|
543
|
-
var
|
|
544
|
-
(h = (
|
|
543
|
+
var m, h;
|
|
544
|
+
(h = (m = n.callbacks).onVideoStateChange) == null || h.call(m, d), D > 0 && d === T.Start && a.linkTrack("agent-video", {
|
|
545
545
|
event: "start",
|
|
546
546
|
latency: Date.now() - D
|
|
547
|
-
}, "start", [
|
|
547
|
+
}, "start", [F.StreamVideoCreated]);
|
|
548
548
|
}
|
|
549
549
|
}
|
|
550
550
|
}).catch(i);
|
|
551
551
|
});
|
|
552
552
|
}
|
|
553
|
-
function
|
|
553
|
+
function q(e, n) {
|
|
554
554
|
if (n && n.length > 0)
|
|
555
555
|
return n;
|
|
556
556
|
let s = "";
|
|
@@ -561,12 +561,12 @@ function j(e, n) {
|
|
|
561
561
|
s = `Hi! I'm ${e.preview_name || "My Agent"}. How can I help you?`;
|
|
562
562
|
return [{
|
|
563
563
|
content: s,
|
|
564
|
-
id:
|
|
564
|
+
id: K(),
|
|
565
565
|
role: "assistant",
|
|
566
566
|
created_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
567
567
|
}];
|
|
568
568
|
}
|
|
569
|
-
function
|
|
569
|
+
function De(e) {
|
|
570
570
|
if (e.answer !== void 0)
|
|
571
571
|
return e.answer;
|
|
572
572
|
let n = 0, s = "";
|
|
@@ -574,7 +574,7 @@ function be(e) {
|
|
|
574
574
|
s += e[n], n++;
|
|
575
575
|
return s;
|
|
576
576
|
}
|
|
577
|
-
function
|
|
577
|
+
function be(e, n, s, a, t) {
|
|
578
578
|
if (!(e === x.Partial || e === x.Answer))
|
|
579
579
|
return;
|
|
580
580
|
const r = a.messages[a.messages.length - 1];
|
|
@@ -585,74 +585,74 @@ function Pe(e, n, s, a, t) {
|
|
|
585
585
|
sequence: o
|
|
586
586
|
} = n;
|
|
587
587
|
e === x.Partial ? s[o] = i : s.answer = i;
|
|
588
|
-
const l =
|
|
588
|
+
const l = De(s);
|
|
589
589
|
(r.content !== l || e === x.Answer) && (r.content = l, t == null || t([...a.messages], e));
|
|
590
590
|
}
|
|
591
|
-
async function
|
|
592
|
-
var
|
|
591
|
+
async function xe(e, n) {
|
|
592
|
+
var z, E, p;
|
|
593
593
|
let s = {}, a = !0;
|
|
594
594
|
const t = {
|
|
595
595
|
messages: [],
|
|
596
|
-
chatMode: n.mode ||
|
|
597
|
-
}, r = n.baseURL ||
|
|
598
|
-
t.messages =
|
|
599
|
-
const
|
|
596
|
+
chatMode: n.mode || M.Functional
|
|
597
|
+
}, r = n.baseURL || V, i = n.wsURL || me, o = n.mixpanelKey || ue, l = Z(n.auth, r, n.callbacks.onError), d = await l.getById(e);
|
|
598
|
+
t.messages = q(d, n.initialMessages), (E = (z = n.callbacks).onNewMessage) == null || E.call(z, [...t.messages], "answer");
|
|
599
|
+
const m = Ie({
|
|
600
600
|
token: o,
|
|
601
601
|
agent: d,
|
|
602
602
|
...n
|
|
603
603
|
});
|
|
604
|
-
|
|
604
|
+
m.track("agent-sdk", {
|
|
605
605
|
event: "loaded",
|
|
606
|
-
...
|
|
606
|
+
...Re(d)
|
|
607
607
|
});
|
|
608
608
|
const h = {
|
|
609
609
|
onMessage: (c, u) => {
|
|
610
|
-
var
|
|
610
|
+
var g, f;
|
|
611
611
|
if ("content" in u)
|
|
612
|
-
|
|
612
|
+
be(c, u, s, t, n.callbacks.onNewMessage), c === x.Answer && m.track("agent-message-received", {
|
|
613
613
|
messages: t.messages.length,
|
|
614
614
|
mode: t.chatMode
|
|
615
615
|
});
|
|
616
616
|
else {
|
|
617
|
-
const w =
|
|
617
|
+
const w = F, v = [w.StreamVideoDone, w.StreamVideoError, w.StreamVideoRejected], I = [w.StreamFailed, w.StreamVideoError, w.StreamVideoRejected], k = $e(u, d, {
|
|
618
618
|
mode: t.chatMode
|
|
619
619
|
});
|
|
620
620
|
if (c = c, c === w.StreamVideoCreated)
|
|
621
|
-
|
|
621
|
+
m.linkTrack("agent-video", k, w.StreamVideoCreated, ["start"]);
|
|
622
622
|
else if (v.includes(c)) {
|
|
623
623
|
const C = c.split("/")[1];
|
|
624
|
-
|
|
625
|
-
...
|
|
624
|
+
m.track("agent-video", {
|
|
625
|
+
...k,
|
|
626
626
|
event: C
|
|
627
627
|
});
|
|
628
628
|
}
|
|
629
|
-
I.includes(c) && ((f = (
|
|
629
|
+
I.includes(c) && ((f = (g = n.callbacks).onError) == null || f.call(g, new Error(`Stream failed with event ${c}`), {
|
|
630
630
|
data: u
|
|
631
631
|
})), u.event === w.StreamDone && _();
|
|
632
632
|
}
|
|
633
633
|
}
|
|
634
634
|
};
|
|
635
|
-
async function
|
|
636
|
-
var I,
|
|
637
|
-
(
|
|
638
|
-
const u = n.mode ===
|
|
639
|
-
var L,
|
|
640
|
-
throw O(
|
|
635
|
+
async function S(c) {
|
|
636
|
+
var I, k, C, R, N, A, $;
|
|
637
|
+
(k = (I = n.callbacks).onConnectionStateChange) == null || k.call(I, y.Connecting), D = 0, c && !a && (delete t.chat, t.messages = q(d), (R = (C = n.callbacks).onNewMessage) == null || R.call(C, [...t.messages], "answer"));
|
|
638
|
+
const u = n.mode === M.DirectPlayback ? Promise.resolve(void 0) : ve(n.auth, i, h), g = Pe(d, n, l, m, t.chat).catch((P) => {
|
|
639
|
+
var L, U;
|
|
640
|
+
throw O(M.Maintenance), (U = (L = n.callbacks).onConnectionStateChange) == null || U.call(L, y.Fail), P;
|
|
641
641
|
}), [f, {
|
|
642
642
|
streamingManager: w,
|
|
643
643
|
chat: v
|
|
644
|
-
}] = await Promise.all([u,
|
|
645
|
-
v && v.id !== ((N = t.chat) == null ? void 0 : N.id) && (($ = (A = n.callbacks).onNewChat) == null || $.call(A, v.id)), t.streamingManager = w, t.socketManager = f, t.chat = v, a = !1, O((v == null ? void 0 : v.chat_mode) ?? n.mode ??
|
|
644
|
+
}] = await Promise.all([u, g]);
|
|
645
|
+
v && v.id !== ((N = t.chat) == null ? void 0 : N.id) && (($ = (A = n.callbacks).onNewChat) == null || $.call(A, v.id)), t.streamingManager = w, t.socketManager = f, t.chat = v, a = !1, O((v == null ? void 0 : v.chat_mode) ?? n.mode ?? M.Functional);
|
|
646
646
|
}
|
|
647
647
|
async function _() {
|
|
648
|
-
var c, u,
|
|
649
|
-
(c = t.socketManager) == null || c.disconnect(), await ((u = t.streamingManager) == null ? void 0 : u.disconnect()), delete t.streamingManager, delete t.socketManager, (f = (
|
|
648
|
+
var c, u, g, f;
|
|
649
|
+
(c = t.socketManager) == null || c.disconnect(), await ((u = t.streamingManager) == null ? void 0 : u.disconnect()), delete t.streamingManager, delete t.socketManager, (f = (g = n.callbacks).onConnectionStateChange) == null || f.call(g, y.Disconnected);
|
|
650
650
|
}
|
|
651
651
|
async function O(c) {
|
|
652
|
-
var u,
|
|
653
|
-
c !== t.chatMode && (
|
|
652
|
+
var u, g;
|
|
653
|
+
c !== t.chatMode && (m.track("agent-mode-change", {
|
|
654
654
|
mode: c
|
|
655
|
-
}), t.chatMode = c, t.chatMode !==
|
|
655
|
+
}), t.chatMode = c, t.chatMode !== M.Functional && await _(), (g = (u = n.callbacks).onModeChange) == null || g.call(u, c));
|
|
656
656
|
}
|
|
657
657
|
return {
|
|
658
658
|
agent: d,
|
|
@@ -660,7 +660,7 @@ async function De(e, n) {
|
|
|
660
660
|
changeMode: O,
|
|
661
661
|
async connect() {
|
|
662
662
|
var c;
|
|
663
|
-
await
|
|
663
|
+
await S(!0), m.track("agent-chat", {
|
|
664
664
|
event: "connect",
|
|
665
665
|
chatId: (c = t.chat) == null ? void 0 : c.id,
|
|
666
666
|
agentId: d.id,
|
|
@@ -669,7 +669,7 @@ async function De(e, n) {
|
|
|
669
669
|
},
|
|
670
670
|
async reconnect() {
|
|
671
671
|
var c;
|
|
672
|
-
await _(), await
|
|
672
|
+
await _(), await S(!1), m.track("agent-chat", {
|
|
673
673
|
event: "reconnect",
|
|
674
674
|
chatId: (c = t.chat) == null ? void 0 : c.id,
|
|
675
675
|
agentId: d.id,
|
|
@@ -678,7 +678,7 @@ async function De(e, n) {
|
|
|
678
678
|
},
|
|
679
679
|
async disconnect() {
|
|
680
680
|
var c;
|
|
681
|
-
await _(),
|
|
681
|
+
await _(), m.track("agent-chat", {
|
|
682
682
|
event: "disconnect",
|
|
683
683
|
chatId: (c = t.chat) == null ? void 0 : c.id,
|
|
684
684
|
agentId: d.id,
|
|
@@ -686,30 +686,30 @@ async function De(e, n) {
|
|
|
686
686
|
});
|
|
687
687
|
},
|
|
688
688
|
async chat(c) {
|
|
689
|
-
var
|
|
690
|
-
const u =
|
|
689
|
+
var g, f, w, v, I, k;
|
|
690
|
+
const u = K();
|
|
691
691
|
s = {};
|
|
692
692
|
try {
|
|
693
|
-
if (D = Date.now(), n.mode ===
|
|
693
|
+
if (D = Date.now(), n.mode === M.DirectPlayback)
|
|
694
694
|
throw new Error("Direct playback is enabled, chat is disabled");
|
|
695
695
|
if (c.length >= 800)
|
|
696
696
|
throw new Error("Message cannot be more than 800 characters");
|
|
697
697
|
if (c.length === 0)
|
|
698
698
|
throw new Error("Message cannot be empty");
|
|
699
|
-
if (t.chatMode ===
|
|
699
|
+
if (t.chatMode === M.Maintenance)
|
|
700
700
|
throw new Error("Chat is in maintenance mode");
|
|
701
|
-
if (![
|
|
701
|
+
if (![M.TextOnly, M.Playground].includes(t.chatMode))
|
|
702
702
|
if (t.streamingManager) {
|
|
703
703
|
if (!t.chat)
|
|
704
704
|
throw new Error("Chat is not initialized");
|
|
705
705
|
} else
|
|
706
706
|
throw new Error("Streaming manager is not initialized");
|
|
707
707
|
t.messages.push({
|
|
708
|
-
id:
|
|
708
|
+
id: K(),
|
|
709
709
|
role: "user",
|
|
710
710
|
content: c,
|
|
711
711
|
created_at: new Date(D).toISOString()
|
|
712
|
-
}), (f = (
|
|
712
|
+
}), (f = (g = n.callbacks).onNewMessage) == null || f.call(g, [...t.messages], "user"), t.chat || (t.chat = await ee(d.id, l, m, t.chatMode, n.persistentChat), (v = (w = n.callbacks).onNewChat) == null || v.call(w, t.chat.id));
|
|
713
713
|
const C = {
|
|
714
714
|
id: u,
|
|
715
715
|
role: "assistant",
|
|
@@ -725,35 +725,35 @@ async function De(e, n) {
|
|
|
725
725
|
streamId: (L = t.streamingManager) == null ? void 0 : L.streamId,
|
|
726
726
|
chatMode: t.chatMode,
|
|
727
727
|
messages: R.map(({
|
|
728
|
-
matches:
|
|
729
|
-
...
|
|
730
|
-
}) =>
|
|
731
|
-
},
|
|
728
|
+
matches: U,
|
|
729
|
+
...te
|
|
730
|
+
}) => te)
|
|
731
|
+
}, G(t.chatMode));
|
|
732
732
|
}, A = await N(t.chat.id).catch(async ($) => {
|
|
733
733
|
var P;
|
|
734
734
|
if (!((P = $ == null ? void 0 : $.message) != null && P.includes("missing or invalid session_id")))
|
|
735
735
|
throw $;
|
|
736
|
-
return await _(), await
|
|
736
|
+
return await _(), await S(!1), N(t.chat.id);
|
|
737
737
|
});
|
|
738
|
-
return
|
|
738
|
+
return m.track("agent-message-send", {
|
|
739
739
|
event: "success",
|
|
740
740
|
mode: t.chatMode,
|
|
741
741
|
messages: t.messages.length + 1
|
|
742
|
-
}), C.context = A.context, C.matches = A.matches, A.result && (C.content = A.result,
|
|
742
|
+
}), C.context = A.context, C.matches = A.matches, A.result && (C.content = A.result, m.track("agent-message-received", {
|
|
743
743
|
latency: Date.now() - D,
|
|
744
744
|
mode: t.chatMode,
|
|
745
745
|
messages: t.messages.length
|
|
746
|
-
}), (
|
|
746
|
+
}), (k = (I = n.callbacks).onNewMessage) == null || k.call(I, [...t.messages], "answer")), A;
|
|
747
747
|
} catch (C) {
|
|
748
|
-
throw t.messages[t.messages.length - 1].id === u && t.messages.pop(),
|
|
748
|
+
throw t.messages[t.messages.length - 1].id === u && t.messages.pop(), m.track("agent-message-send", {
|
|
749
749
|
event: "error",
|
|
750
750
|
mode: t.chatMode,
|
|
751
751
|
messages: t.messages.length
|
|
752
752
|
}), C;
|
|
753
753
|
}
|
|
754
754
|
},
|
|
755
|
-
rate(c, u,
|
|
756
|
-
var v, I,
|
|
755
|
+
rate(c, u, g) {
|
|
756
|
+
var v, I, k, C;
|
|
757
757
|
const f = t.messages.find((R) => R.id === c);
|
|
758
758
|
if (t.chat) {
|
|
759
759
|
if (!f)
|
|
@@ -761,15 +761,15 @@ async function De(e, n) {
|
|
|
761
761
|
} else
|
|
762
762
|
throw new Error("Chat is not initialized");
|
|
763
763
|
const w = ((v = f.matches) == null ? void 0 : v.map((R) => [R.document_id, R.id])) ?? [];
|
|
764
|
-
return
|
|
765
|
-
event:
|
|
764
|
+
return m.track("agent-rate", {
|
|
765
|
+
event: g ? "update" : "create",
|
|
766
766
|
thumb: u === 1 ? "up" : "down",
|
|
767
767
|
knowledge_id: ((I = d.knowledge) == null ? void 0 : I.id) ?? "",
|
|
768
768
|
mode: t.chatMode,
|
|
769
769
|
matches: w,
|
|
770
770
|
score: u
|
|
771
|
-
}),
|
|
772
|
-
knowledge_id: ((
|
|
771
|
+
}), g ? l.updateRating(d.id, t.chat.id, g, {
|
|
772
|
+
knowledge_id: ((k = d.knowledge) == null ? void 0 : k.id) ?? "",
|
|
773
773
|
message_id: c,
|
|
774
774
|
matches: w,
|
|
775
775
|
score: u
|
|
@@ -784,7 +784,7 @@ async function De(e, n) {
|
|
|
784
784
|
var u;
|
|
785
785
|
if (!t.chat)
|
|
786
786
|
throw new Error("Chat is not initialized");
|
|
787
|
-
return
|
|
787
|
+
return m.track("agent-rate-delete", {
|
|
788
788
|
type: "text",
|
|
789
789
|
chat_id: (u = t.chat) == null ? void 0 : u.id,
|
|
790
790
|
id: c,
|
|
@@ -817,36 +817,36 @@ async function De(e, n) {
|
|
|
817
817
|
}
|
|
818
818
|
return c;
|
|
819
819
|
}
|
|
820
|
-
const
|
|
821
|
-
return
|
|
822
|
-
script:
|
|
820
|
+
const g = u();
|
|
821
|
+
return m.track("agent-speak", g), t.streamingManager.speak({
|
|
822
|
+
script: g
|
|
823
823
|
});
|
|
824
824
|
}
|
|
825
825
|
};
|
|
826
826
|
}
|
|
827
|
-
function
|
|
827
|
+
function Te(e, n, s) {
|
|
828
828
|
const {
|
|
829
829
|
getById: a
|
|
830
|
-
} =
|
|
830
|
+
} = Z(n, s || V);
|
|
831
831
|
return a(e);
|
|
832
832
|
}
|
|
833
833
|
export {
|
|
834
|
-
|
|
835
|
-
|
|
834
|
+
ae as AgentStatus,
|
|
835
|
+
M as ChatMode,
|
|
836
836
|
x as ChatProgress,
|
|
837
837
|
y as ConnectionState,
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
838
|
+
ce as DocumentType,
|
|
839
|
+
oe as KnowledgeType,
|
|
840
|
+
re as PlanGroup,
|
|
841
|
+
le as Providers,
|
|
842
|
+
ie as RateState,
|
|
843
|
+
F as StreamEvents,
|
|
844
844
|
T as StreamingState,
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
845
|
+
se as Subject,
|
|
846
|
+
ne as UserPlan,
|
|
847
|
+
J as VideoType,
|
|
848
|
+
ge as VoiceAccess,
|
|
849
|
+
xe as createAgentManager,
|
|
850
|
+
Te as getAgent,
|
|
851
|
+
de as mapVideoType
|
|
852
852
|
};
|
package/dist/index.umd.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(function(w,L){typeof exports=="object"&&typeof module<"u"?L(exports):typeof define=="function"&&define.amd?define(["exports"],L):(w=typeof globalThis<"u"?globalThis:w||self,L(w.index={}))})(this,function(w){"use strict";var L=(e=>(e.TRIAL="trial",e.BASIC="basic",e.ENTERPRISE="enterprise",e.LITE="lite",e.ADVANCED="advanced",e))(L||{}),J=(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))(J||{}),X=(e=>(e.Created="created",e.Started="started",e.Done="done",e.Error="error",e.Rejected="rejected",e.Ready="ready",e))(X||{}),Y=(e=>(e.Unrated="Unrated",e.Positive="Positive",e.Negative="Negative",e))(Y||{}),M=(e=>(e.Functional="Functional",e.TextOnly="TextOnly",e.Maintenance="Maintenance",e.Playground="Playground",e.DirectPlayback="DirectPlayback",e))(M||{}),D=(e=>(e.Embed="embed",e.Query="query",e.Partial="partial",e.Answer="answer",e.Complete="done",e))(D||{}),Z=(e=>(e.KnowledgeProcessing="knowledge/processing",e.KnowledgeIndexing="knowledge/indexing",e.KnowledgeFailed="knowledge/error",e.KnowledgeDone="knowledge/done",e))(Z||{}),G=(e=>(e.Knowledge="knowledge",e.Document="document",e.Record="record",e))(G||{}),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||{}),j=(e=>(e.Clip="clip",e.Talk="talk",e))(j||{});const ee=e=>{switch(e){case"clip":return"clip";case"talk":return"talk";default:throw new Error(`Unknown video type: ${e}`)}};var T=(e=>(e.Start="START",e.Stop="STOP",e))(T||{}),F=(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))(F||{}),v=(e=>(e.New="new",e.Fail="fail",e.Connected="connected",e.Connecting="connecting",e.Closed="closed",e.Completed="completed",e.Disconnected="disconnected",e))(v||{}),te=(e=>(e.Amazon="amazon",e.Microsoft="microsoft",e.Afflorithmics="afflorithmics",e.Elevenlabs="elevenlabs",e))(te||{}),ne=(e=>(e.Public="public",e.Premium="premium",e.Private="private",e))(ne||{});const x="https://api.d-id.com",me="wss://notifications.d-id.com",ue="79f81a83a67430be2bc0fd61042b8faa",U=()=>Math.random().toString(16).slice(2);function re(){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 ge=U();function ae(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}.${re()}_${ge}`;throw new Error(`Unknown auth type: ${e}`)}function B(e,n=x,s){const a=async(t,r)=>{const i=await fetch(n+(t!=null&&t.startsWith("/")?t:`/${t}`),{...r,headers:{...r==null?void 0:r.headers,Authorization:ae(e),"Content-Type":"application/json"}});if(!i.ok){let o=await i.text().catch(()=>"Failed to fetch");throw s&&s(new Error(o),{url:t,options:r,headers:i.headers}),new Error(o)}return i.json()};return{get(t,r){return a(t,{...r,method:"GET"})},post(t,r,i){return a(t,{...i,body:JSON.stringify(r),method:"POST"})},delete(t,r,i){return a(t,{...i,body:JSON.stringify(r),method:"DELETE"})},patch(t,r,i){return a(t,{...i,body:JSON.stringify(r),method:"PATCH"})}}}function ie(e,n=x,s){const a=B(e,`${n}/agents`,s);return{create(t,r){return a.post("/",t,r)},getAgents(t,r){return a.get(`/${t?`?tag=${t}`:""}`,r).then(i=>i??[])},getById(t,r){return a.get(`/${t}`,r)},delete(t,r){return a.delete(`/${t}`,void 0,r)},update(t,r,i){return a.patch(`/${t}`,r,i)},newChat(t,r,i){return a.post(`/${t}/chat`,r,i)},chat(t,r,i,o){return a.post(`/${t}/chat/${r}`,i,o)},createRating(t,r,i,o){return a.post(`/${t}/chat/${r}/ratings`,i,o)},updateRating(t,r,i,o,l){return a.patch(`/${t}/chat/${r}/ratings/${i}`,o,l)},deleteRating(t,r,i,o){return a.delete(`/${t}/chat/${r}/ratings/${i}`,o)}}}const he=e=>new Promise(n=>setTimeout(n,e));function we(e){return new Promise((n,s)=>{const{callbacks:a,host:t,auth:r}=e,{onMessage:i=null,onOpen:o=null,onClose:l=null,onError:d=null}=a||{},u=new WebSocket(`${t}?authorization=${ae(r)}`);u.onmessage=i,u.onclose=l,u.onerror=f=>{console.error(f),d==null||d("Websocket failed to connect",f),s(f)},u.onopen=f=>{o==null||o(f),n(u)}})}async function fe(e){const{retries:n=1}=e;let s=null;for(let a=0;(s==null?void 0:s.readyState)!==WebSocket.OPEN;a++)try{s=await we(e)}catch(t){if(a===n)throw t;await he(a*500)}return s}async function pe(e,n,s){const a=s!=null&&s.onMessage?[s.onMessage]:[],t=await fe({auth:e,host:n,callbacks:{onError:s==null?void 0:s.onError,onMessage:r=>{const i=JSON.parse(r.data);a.forEach(o=>o(i.event,i))}}});return{socket:t,disconnect:()=>t.close(),subscribeToEvents:r=>a.push(r)}}const ye="X-Playground-Chat";function ve(e,n,s,a){const t=B(e,`${n}/agents/${s}`,a);return{createStream(r){return t.post("/streams",{output_resolution:r.output_resolution,compatibility_mode:r.compatibility_mode,stream_warmup:r.stream_warmup,session_timeout:r.session_timeout})},startConnection(r,i,o){return t.post(`/streams/${r}/sdp`,{session_id:o,answer:i})},addIceCandidate(r,i,o){return t.post(`/streams/${r}/ice`,{session_id:o,...i})},sendStreamRequest(r,i,o){return t.post(`/streams/${r}`,{session_id:i,...o})},close(r,i){return t.delete(`/streams/${r}`,{session_id:i})}}}function Ce(e,n,s,a){const t=B(e,`${n}/agents/${s}`,a);return{createStream(r,i){return t.post("/streams",{driver_url:r.driver_url,face:r.face,config:r.config,output_resolution:r.output_resolution,compatibility_mode:r.compatibility_mode,stream_warmup:r.stream_warmup,session_timeout:r.session_timeout},i)},startConnection(r,i,o,l){return t.post(`/streams/${r}/sdp`,{session_id:o,answer:i},l)},addIceCandidate(r,i,o,l){return t.post(`/streams/${r}/ice`,{session_id:o,...i},l)},sendStreamRequest(r,i,o,l){return t.post(`/streams/${r}`,{session_id:i,...o},l)},close(r,i,o){return t.delete(`/streams/${r}`,{session_id:i},o)}}}let se=!1;const b=(e,n)=>se&&console.log(e,n),Se=(window.RTCPeerConnection||window.webkitRTCPeerConnection||window.mozRTCPeerConnection).bind(window);function oe(e){switch(e){case"connected":return v.Connected;case"checking":return v.Connecting;case"failed":return v.Fail;case"new":return v.New;case"closed":return v.Closed;case"disconnected":return v.Disconnected;case"completed":return v.Completed;default:return v.New}}function Me(){let e=0;return n=>{for(const s of n.values())if(s&&s.type==="inbound-rtp"&&s.kind==="video"){const a=s.bytesReceived,t=a-e>0;return e=a,t}return!1}}function _e(e,n){const a=Math.max(Math.ceil(10),1);let t=0,r=!1;const i=Me();return setInterval(async()=>{const o=await e.getStats();i(o)?(t=0,r||(n==null||n(T.Start),r=!0)):r&&(t++,t>=a&&(n==null||n(T.Stop),r=!1))},100)}async function ke(e,n,{debug:s=!1,callbacks:a,auth:t,baseURL:r=x,warmup:i}){se=s;let o;const{startConnection:l,sendStreamRequest:d,close:u,createStream:f,addIceCandidate:k}=n.videoType===j.Clip?ve(t,r,e,a.onError):Ce(t,r,e,a.onError),{id:_,offer:z,ice_servers:W,session_id:R}=await f(n),y=new Se({iceServers:W});if(!R)throw new Error("Could not create session_id");const c=_e(y,a.onVideoStateChange);y.onicecandidate=m=>{b("peerConnection.onicecandidate",m),m.candidate&&m.candidate.sdpMid&&m.candidate.sdpMLineIndex!==null?k(_,{candidate:m.candidate.candidate,sdpMid:m.candidate.sdpMid,sdpMLineIndex:m.candidate.sdpMLineIndex},R):k(_,{candidate:null},R)},y.oniceconnectionstatechange=()=>{var p;b("peerConnection.oniceconnectionstatechange => "+y.iceConnectionState);const m=oe(y.iceConnectionState);m===v.Connected?o=setTimeout(()=>{var h;return(h=a.onConnectionStateChange)==null?void 0:h.call(a,v.Connected)},i?5e3:0):(clearTimeout(o),(p=a.onConnectionStateChange)==null||p.call(a,m))},y.ontrack=m=>{var p;b("peerConnection.ontrack",m),(p=a.onSrcObjectReady)==null||p.call(a,m.streams[0])},await y.setRemoteDescription(z),b("set remote description OK");const g=await y.createAnswer();return b("create answer OK"),await y.setLocalDescription(g),b("set local description OK"),await l(_,g,R),b("start connection OK"),{speak(m){return d(_,R,m)},async disconnect(){var m,p;if(_){const h=oe(y.iceConnectionState);if(y){if(h===v.New){(m=a.onVideoStateChange)==null||m.call(a,T.Stop),clearInterval(c);return}y.close(),y.oniceconnectionstatechange=null,y.onnegotiationneeded=null,y.onicecandidate=null,y.ontrack=null}try{h===v.Connected&&await u(_,R).catch(C=>{})}catch(C){b("Error on close stream connection",C)}(p=a.onVideoStateChange)==null||p.call(a,T.Stop),clearInterval(c)}},sessionId:R,streamId:_}}let H={};function Ee(e){const n=window!=null&&window.hasOwnProperty("DID_AGENTS_API")?"agents-ui":"agents-sdk",s=e.agent.presenter,a={token:e.token||"testKey",distinct_id:e.distinctId||re(),agentId:e.agent.id,agentType:s.type==="clip"&&s.presenter_id.startsWith("v2_")?"clip_v2":s.type,owner_id:e.agent.owner_id??""};return{...a,isEnabled:e.isEnabled??!0,getRandom:()=>Math.random().toString(16).slice(2),track(t,r){if(!this.isEnabled)return Promise.reject("MixPanel analytics is disabled on creation");const{audioPath:i,...o}=r||{},l={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({data:JSON.stringify([{event:t,properties:{...o,...a,source:n,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",l).then(d=>d.json()).catch(d=>console.error(d))},linkTrack(t,r,i,o){H[t]||(H[t]={events:{},resolvedDependencies:[]}),o.includes(i)||o.push(i);const l=H[t];if(l.events[i]={props:r},l.resolvedDependencies.push(i),o.every(u=>l.resolvedDependencies.includes(u))){const u=o.reduce((f,k)=>l.events[k]?{...f,...l.events[k].props}:f,{});this.track(t,u),l.resolvedDependencies=l.resolvedDependencies.filter(f=>!o.includes(f)),o.forEach(f=>{delete l.events[f]})}}}}function Re(e){var t,r,i,o;const n=()=>/Mobi|Android/i.test(navigator.userAgent)?"Mobile":"Desktop",s=()=>{const l=navigator.platform;return l.toLowerCase().includes("win")?"Windows":l.toLowerCase().includes("mac")?"Mac OS X":l.toLowerCase().includes("linux")?"Linux":"Unknown"},a=e.presenter;return{$os:`${s()}`,isMobile:`${n()=="Mobile"}`,browser:navigator.userAgent,origin:window.location.origin,agentType:a.type==="clip"&&a.presenter_id.startsWith("v2_")?"clip_v2":a.type,agentVoice:{voiceId:(r=(t=e.presenter)==null?void 0:t.voice)==null?void 0:r.voice_id,provider:(o=(i=e.presenter)==null?void 0:i.voice)==null?void 0:o.type}}}function Ie(e,n,s){var d,u;const{event:a,...t}=e,{template:r}=(n==null?void 0:n.llm)||{},{language:i}=((d=n==null?void 0:n.presenter)==null?void 0:d.voice)||{},{stitch:o}=(n==null?void 0:n.presenter)||{};return{...t,llm:{...t.llm,template:r},script:{...t.script,provider:{...(u=t==null?void 0:t.script)==null?void 0:u.provider,language:i}},stitch:o,...s}}let O=0;function Ae(e,n){var s,a,t,r;return{videoType:ee(e.presenter.type),output_resolution:(s=n==null?void 0:n.streamOptions)==null?void 0:s.outputResolution,session_timeout:(a=n==null?void 0:n.streamOptions)==null?void 0:a.sessionTimeout,stream_warmup:(t=n==null?void 0:n.streamOptions)==null?void 0:t.streamWarmup,compatibility_mode:(r=n==null?void 0:n.streamOptions)==null?void 0:r.compatibilityMode}}function ce(e){return e===M.Playground?{headers:{[ye]:"true"}}:{}}async function de(e,n,s,a){try{const t=await n.newChat(e,{persist:!0},ce(a));return s.track("agent-chat",{event:"created",chat_id:t.id,agent_id:e,mode:a}),t}catch(t){try{console.error(t);const r=JSON.parse(t.message);if((r==null?void 0:r.kind)==="InsufficientCreditsError")throw new Error("InsufficientCreditsError")}catch(r){console.error("Error parsing the error message:",r)}throw new Error("Cannot create new chat")}}function $e(e,n,s,a,t){return new Promise(async(r,i)=>{var l;O=0;const o=await ke(e.id,Ae(e,n),{...n,analytics:a,warmup:(l=n.streamOptions)==null?void 0:l.streamWarmup,callbacks:{...n.callbacks,onConnectionStateChange:async d=>{var u,f;d===v.Connected&&(!t&&n.mode!==M.DirectPlayback&&(t=await de(e.id,s,a,n.mode).catch(k=>{i(k)})),o?r({chat:t,streamingManager:o}):t&&i(new Error("Something went wrong while initializing the manager"))),(f=(u=n.callbacks).onConnectionStateChange)==null||f.call(u,d)},onVideoStateChange(d){var u,f;(f=(u=n.callbacks).onVideoStateChange)==null||f.call(u,d),O>0&&d===T.Start&&a.linkTrack("agent-video",{event:"start",latency:Date.now()-O},"start",[F.StreamVideoCreated])}}}).catch(i)})}function le(e,n){if(n&&n.length>0)return n;let s="";if(e.greetings&&e.greetings.length>0){const a=Math.floor(Math.random()*e.greetings.length);s=e.greetings[a]}else s=`Hi! I'm ${e.preview_name||"My Agent"}. How can I help you?`;return[{content:s,id:U(),role:"assistant",created_at:new Date().toISOString()}]}function be(e){if(e.answer!==void 0)return e.answer;let n=0,s="";for(;n in e;)s+=e[n],n++;return s}function Pe(e,n,s,a,t){if(!(e===D.Partial||e===D.Answer))return;const r=a.messages[a.messages.length-1];if((r==null?void 0:r.role)!=="assistant")return;const{content:i,sequence:o}=n;e===D.Partial?s[o]=i:s.answer=i;const l=be(s);(r.content!==l||e===D.Answer)&&(r.content=l,t==null||t([...a.messages],e))}async function De(e,n){var W,R,y;let s={},a=!0;const t={messages:[],chatMode:n.mode||M.Functional},r=n.baseURL||x,i=n.wsURL||me,o=n.mixpanelKey||ue,l=ie(n.auth,r,n.callbacks.onError),d=await l.getById(e);t.messages=le(d,n.initialMessages),(R=(W=n.callbacks).onNewMessage)==null||R.call(W,[...t.messages],"answer");const u=Ee({token:o,agent:d,...n});u.track("agent-sdk",{event:"loaded",...Re(d)});const f={onMessage:(c,g)=>{var m,p;if("content"in g)Pe(c,g,s,t,n.callbacks.onNewMessage),c===D.Answer&&u.track("agent-message-received",{messages:t.messages.length,mode:t.chatMode});else{const h=F,C=[h.StreamVideoDone,h.StreamVideoError,h.StreamVideoRejected],I=[h.StreamFailed,h.StreamVideoError,h.StreamVideoRejected],E=Ie(g,d,{mode:t.chatMode});if(c=c,c===h.StreamVideoCreated)u.linkTrack("agent-video",E,h.StreamVideoCreated,["start"]);else if(C.includes(c)){const S=c.split("/")[1];u.track("agent-video",{...E,event:S})}I.includes(c)&&((p=(m=n.callbacks).onError)==null||p.call(m,new Error(`Stream failed with event ${c}`),{data:g})),g.event===h.StreamDone&&_()}}};async function k(c){var I,E,S,A,K,P,$;(E=(I=n.callbacks).onConnectionStateChange)==null||E.call(I,v.Connecting),O=0,c&&!a&&(delete t.chat,t.messages=le(d),(A=(S=n.callbacks).onNewMessage)==null||A.call(S,[...t.messages],"answer"));const g=n.mode===M.DirectPlayback?Promise.resolve(void 0):pe(n.auth,i,f),m=$e(d,n,l,u,t.chat).catch(N=>{var V,q;throw z(M.Maintenance),(q=(V=n.callbacks).onConnectionStateChange)==null||q.call(V,v.Fail),N}),[p,{streamingManager:h,chat:C}]=await Promise.all([g,m]);C&&C.id!==((K=t.chat)==null?void 0:K.id)&&(($=(P=n.callbacks).onNewChat)==null||$.call(P,C.id)),t.streamingManager=h,t.socketManager=p,t.chat=C,a=!1,z((C==null?void 0:C.chat_mode)??n.mode??M.Functional)}async function _(){var c,g,m,p;(c=t.socketManager)==null||c.disconnect(),await((g=t.streamingManager)==null?void 0:g.disconnect()),delete t.streamingManager,delete t.socketManager,(p=(m=n.callbacks).onConnectionStateChange)==null||p.call(m,v.Disconnected)}async function z(c){var g,m;c!==t.chatMode&&(u.track("agent-mode-change",{mode:c}),t.chatMode=c,t.chatMode!==M.Functional&&await _(),(m=(g=n.callbacks).onModeChange)==null||m.call(g,c))}return{agent:d,starterMessages:((y=d.knowledge)==null?void 0:y.starter_message)||[],changeMode:z,async connect(){var c;await k(!0),u.track("agent-chat",{event:"connect",chatId:(c=t.chat)==null?void 0:c.id,agentId:d.id,mode:t.chatMode})},async reconnect(){var c;await _(),await k(!1),u.track("agent-chat",{event:"reconnect",chatId:(c=t.chat)==null?void 0:c.id,agentId:d.id,mode:t.chatMode})},async disconnect(){var c;await _(),u.track("agent-chat",{event:"disconnect",chatId:(c=t.chat)==null?void 0:c.id,agentId:d.id,mode:t.chatMode})},async chat(c){var m,p,h,C,I,E;const g=U();s={};try{if(O=Date.now(),n.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.messages.push({id:U(),role:"user",content:c,created_at:new Date(O).toISOString()}),(p=(m=n.callbacks).onNewMessage)==null||p.call(m,[...t.messages],"user"),t.chat||(t.chat=await de(d.id,l,u,t.chatMode),(C=(h=n.callbacks).onNewChat)==null||C.call(h,t.chat.id));const S={id:g,role:"assistant",content:"",created_at:new Date().toISOString(),matches:[]},A=[...t.messages];t.messages.push(S);const K=$=>{var N,V;return l.chat(d.id,$,{sessionId:(N=t.streamingManager)==null?void 0:N.sessionId,streamId:(V=t.streamingManager)==null?void 0:V.streamId,chatMode:t.chatMode,messages:A.map(({matches:q,...Oe})=>Oe)},ce(t.chatMode))},P=await K(t.chat.id).catch(async $=>{var N;if(!((N=$==null?void 0:$.message)!=null&&N.includes("missing or invalid session_id")))throw $;return await _(),await k(!1),K(t.chat.id)});return u.track("agent-message-send",{event:"success",mode:t.chatMode,messages:t.messages.length+1}),S.context=P.context,S.matches=P.matches,P.result&&(S.content=P.result,u.track("agent-message-received",{latency:Date.now()-O,mode:t.chatMode,messages:t.messages.length}),(E=(I=n.callbacks).onNewMessage)==null||E.call(I,[...t.messages],"answer")),P}catch(S){throw t.messages[t.messages.length-1].id===g&&t.messages.pop(),u.track("agent-message-send",{event:"error",mode:t.chatMode,messages:t.messages.length}),S}},rate(c,g,m){var C,I,E,S;const p=t.messages.find(A=>A.id===c);if(t.chat){if(!p)throw new Error("Message not found")}else throw new Error("Chat is not initialized");const h=((C=p.matches)==null?void 0:C.map(A=>[A.document_id,A.id]))??[];return u.track("agent-rate",{event:m?"update":"create",thumb:g===1?"up":"down",knowledge_id:((I=d.knowledge)==null?void 0:I.id)??"",mode:t.chatMode,matches:h,score:g}),m?l.updateRating(d.id,t.chat.id,m,{knowledge_id:((E=d.knowledge)==null?void 0:E.id)??"",message_id:c,matches:h,score:g}):l.createRating(d.id,t.chat.id,{knowledge_id:((S=d.knowledge)==null?void 0:S.id)??"",message_id:c,matches:h,score:g})},deleteRate(c){var g;if(!t.chat)throw new Error("Chat is not initialized");return u.track("agent-rate-delete",{type:"text",chat_id:(g=t.chat)==null?void 0:g.id,id:c,mode:t.chatMode}),l.deleteRating(d.id,t.chat.id,c)},speak(c){if(!t.streamingManager)throw new Error("Please connect to the agent first");function g(){if(typeof c=="string"){if(!d.presenter.voice)throw new Error("Presenter voice is not initialized");return{type:"text",provider:d.presenter.voice,input:c,ssml:!1}}if(c.type==="text"&&!c.provider){if(!d.presenter.voice)throw new Error("Presenter voice is not initialized");return{type:"text",provider:d.presenter.voice,input:c.input,ssml:c.ssml}}return c}const m=g();return u.track("agent-speak",m),t.streamingManager.speak({script:m})}}}function Te(e,n,s){const{getById:a}=ie(n,s||x);return a(e)}w.AgentStatus=X,w.ChatMode=M,w.ChatProgress=D,w.ConnectionState=v,w.DocumentType=Q,w.KnowledgeType=G,w.PlanGroup=J,w.Providers=te,w.RateState=Y,w.StreamEvents=F,w.StreamingState=T,w.Subject=Z,w.UserPlan=L,w.VideoType=j,w.VoiceAccess=ne,w.createAgentManager=De,w.getAgent=Te,w.mapVideoType=ee,Object.defineProperty(w,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
(function(w,N){typeof exports=="object"&&typeof module<"u"?N(exports):typeof define=="function"&&define.amd?define(["exports"],N):(w=typeof globalThis<"u"?globalThis:w||self,N(w.index={}))})(this,function(w){"use strict";var N=(e=>(e.TRIAL="trial",e.BASIC="basic",e.ENTERPRISE="enterprise",e.LITE="lite",e.ADVANCED="advanced",e))(N||{}),X=(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))(X||{}),Y=(e=>(e.Created="created",e.Started="started",e.Done="done",e.Error="error",e.Rejected="rejected",e.Ready="ready",e))(Y||{}),Z=(e=>(e.Unrated="Unrated",e.Positive="Positive",e.Negative="Negative",e))(Z||{}),S=(e=>(e.Functional="Functional",e.TextOnly="TextOnly",e.Maintenance="Maintenance",e.Playground="Playground",e.DirectPlayback="DirectPlayback",e))(S||{}),b=(e=>(e.Embed="embed",e.Query="query",e.Partial="partial",e.Answer="answer",e.Complete="done",e))(b||{}),G=(e=>(e.KnowledgeProcessing="knowledge/processing",e.KnowledgeIndexing="knowledge/indexing",e.KnowledgeFailed="knowledge/error",e.KnowledgeDone="knowledge/done",e))(G||{}),Q=(e=>(e.Knowledge="knowledge",e.Document="document",e.Record="record",e))(Q||{}),ee=(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))(ee||{}),j=(e=>(e.Clip="clip",e.Talk="talk",e))(j||{});const te=e=>{switch(e){case"clip":return"clip";case"talk":return"talk";default:throw new Error(`Unknown video type: ${e}`)}};var D=(e=>(e.Start="START",e.Stop="STOP",e))(D||{}),U=(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))(U||{}),y=(e=>(e.New="new",e.Fail="fail",e.Connected="connected",e.Connecting="connecting",e.Closed="closed",e.Completed="completed",e.Disconnected="disconnected",e))(y||{}),ne=(e=>(e.Amazon="amazon",e.Microsoft="microsoft",e.Afflorithmics="afflorithmics",e.Elevenlabs="elevenlabs",e))(ne||{}),re=(e=>(e.Public="public",e.Premium="premium",e.Private="private",e))(re||{}),B={BASE_URL:"/",MODE:"dev",DEV:!1,PROD:!0,SSR:!1};const V=B.VITE_DID_API_URL,ue=B.VITE_WS_ENDPOINT,me=B.VITE_MIXPANEL_KEY,W=()=>Math.random().toString(16).slice(2);function ae(){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 he=W();function ie(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}.${ae()}_${he}`;throw new Error(`Unknown auth type: ${e}`)}function H(e,n=V,s){const a=async(t,r)=>{const i=await fetch(n+(t!=null&&t.startsWith("/")?t:`/${t}`),{...r,headers:{...r==null?void 0:r.headers,Authorization:ie(e),"Content-Type":"application/json"}});if(!i.ok){let o=await i.text().catch(()=>"Failed to fetch");throw s&&s(new Error(o),{url:t,options:r,headers:i.headers}),new Error(o)}return i.json()};return{get(t,r){return a(t,{...r,method:"GET"})},post(t,r,i){return a(t,{...i,body:JSON.stringify(r),method:"POST"})},delete(t,r,i){return a(t,{...i,body:JSON.stringify(r),method:"DELETE"})},patch(t,r,i){return a(t,{...i,body:JSON.stringify(r),method:"PATCH"})}}}function se(e,n=V,s){const a=H(e,`${n}/agents`,s);return{create(t,r){return a.post("/",t,r)},getAgents(t,r){return a.get(`/${t?`?tag=${t}`:""}`,r).then(i=>i??[])},getById(t,r){return a.get(`/${t}`,r)},delete(t,r){return a.delete(`/${t}`,void 0,r)},update(t,r,i){return a.patch(`/${t}`,r,i)},newChat(t,r,i){return a.post(`/${t}/chat`,r,i)},chat(t,r,i,o){return a.post(`/${t}/chat/${r}`,i,o)},createRating(t,r,i,o){return a.post(`/${t}/chat/${r}/ratings`,i,o)},updateRating(t,r,i,o,l){return a.patch(`/${t}/chat/${r}/ratings/${i}`,o,l)},deleteRating(t,r,i,o){return a.delete(`/${t}/chat/${r}/ratings/${i}`,o)}}}const we=e=>new Promise(n=>setTimeout(n,e));function fe(e){return new Promise((n,s)=>{const{callbacks:a,host:t,auth:r}=e,{onMessage:i=null,onOpen:o=null,onClose:l=null,onError:d=null}=a||{},u=new WebSocket(`${t}?authorization=${ie(r)}`);u.onmessage=i,u.onclose=l,u.onerror=f=>{console.error(f),d==null||d("Websocket failed to connect",f),s(f)},u.onopen=f=>{o==null||o(f),n(u)}})}async function pe(e){const{retries:n=1}=e;let s=null;for(let a=0;(s==null?void 0:s.readyState)!==WebSocket.OPEN;a++)try{s=await fe(e)}catch(t){if(a===n)throw t;await we(a*500)}return s}async function ve(e,n,s){const a=s!=null&&s.onMessage?[s.onMessage]:[],t=await pe({auth:e,host:n,callbacks:{onError:s==null?void 0:s.onError,onMessage:r=>{const i=JSON.parse(r.data);a.forEach(o=>o(i.event,i))}}});return{socket:t,disconnect:()=>t.close(),subscribeToEvents:r=>a.push(r)}}const ye="X-Playground-Chat";function Ce(e,n,s,a){const t=H(e,`${n}/agents/${s}`,a);return{createStream(r){return t.post("/streams",{output_resolution:r.output_resolution,compatibility_mode:r.compatibility_mode,stream_warmup:r.stream_warmup,session_timeout:r.session_timeout})},startConnection(r,i,o){return t.post(`/streams/${r}/sdp`,{session_id:o,answer:i})},addIceCandidate(r,i,o){return t.post(`/streams/${r}/ice`,{session_id:o,...i})},sendStreamRequest(r,i,o){return t.post(`/streams/${r}`,{session_id:i,...o})},close(r,i){return t.delete(`/streams/${r}`,{session_id:i})}}}function _e(e,n,s,a){const t=H(e,`${n}/agents/${s}`,a);return{createStream(r,i){return t.post("/streams",{driver_url:r.driver_url,face:r.face,config:r.config,output_resolution:r.output_resolution,compatibility_mode:r.compatibility_mode,stream_warmup:r.stream_warmup,session_timeout:r.session_timeout},i)},startConnection(r,i,o,l){return t.post(`/streams/${r}/sdp`,{session_id:o,answer:i},l)},addIceCandidate(r,i,o,l){return t.post(`/streams/${r}/ice`,{session_id:o,...i},l)},sendStreamRequest(r,i,o,l){return t.post(`/streams/${r}`,{session_id:i,...o},l)},close(r,i,o){return t.delete(`/streams/${r}`,{session_id:i},o)}}}let oe=!0;const L=(e,n)=>oe&&console.log(e,n),Se=(window.RTCPeerConnection||window.webkitRTCPeerConnection||window.mozRTCPeerConnection).bind(window);function ce(e){switch(e){case"connected":return y.Connected;case"checking":return y.Connecting;case"failed":return y.Fail;case"new":return y.New;case"closed":return y.Closed;case"disconnected":return y.Disconnected;case"completed":return y.Completed;default:return y.New}}function Me(){let e=0;return n=>{for(const s of n.values())if(s&&s.type==="inbound-rtp"&&s.kind==="video"){const a=s.bytesReceived,t=a-e>0;return e=a,t}return!1}}function ke(e,n){const a=Math.max(Math.ceil(10),1);let t=0,r=!1;const i=Me();return setInterval(async()=>{const o=await e.getStats();i(o)?(console.log("Receiving video bytes"),t=0,r||(n==null||n(D.Start),r=!0)):r&&(t++,t>=a&&(n==null||n(D.Stop),r=!1))},100)}async function Ee(e,n,{debug:s=!1,callbacks:a,auth:t,baseURL:r=V,warmup:i}){oe=s;let o;const{startConnection:l,sendStreamRequest:d,close:u,createStream:f,addIceCandidate:k}=n.videoType===j.Clip?Ce(t,r,e,a.onError):_e(t,r,e,a.onError),{id:M,offer:x,ice_servers:F,session_id:I}=await f(n),v=new Se({iceServers:F});if(!I)throw new Error("Could not create session_id");const c=ke(v,a.onVideoStateChange);v.onicecandidate=g=>{L("peerConnection.onicecandidate",g),g.candidate&&g.candidate.sdpMid&&g.candidate.sdpMLineIndex!==null?k(M,{candidate:g.candidate.candidate,sdpMid:g.candidate.sdpMid,sdpMLineIndex:g.candidate.sdpMLineIndex},I):k(M,{candidate:null},I)},v.oniceconnectionstatechange=()=>{var p;console.log("peerConnection.oniceconnectionstatechange => "+v.iceConnectionState);const g=ce(v.iceConnectionState);g===y.Connected?(console.log("connected"),o=setTimeout(()=>{var h;return(h=a.onConnectionStateChange)==null?void 0:h.call(a,y.Connected)},0)):(clearTimeout(o),(p=a.onConnectionStateChange)==null||p.call(a,g))},v.ontrack=g=>{var p;console.log("peerConnection.ontrack",g),(p=a.onSrcObjectReady)==null||p.call(a,g.streams[0])},await v.setRemoteDescription(x),L("set remote description OK");const m=await v.createAnswer();return L("create answer OK"),await v.setLocalDescription(m),L("set local description OK"),await l(M,m,I),L("start connection OK"),{speak(g){return d(M,I,g)},async disconnect(){var g,p;if(M){const h=ce(v.iceConnectionState);if(v){if(h===y.New){(g=a.onVideoStateChange)==null||g.call(a,D.Stop),clearInterval(c);return}v.close(),v.oniceconnectionstatechange=null,v.onnegotiationneeded=null,v.onicecandidate=null,v.ontrack=null}try{h===y.Connected&&await u(M,I).catch(C=>{})}catch(C){L("Error on close stream connection",C)}(p=a.onVideoStateChange)==null||p.call(a,D.Stop),clearInterval(c)}},sessionId:I,streamId:M}}let q={};function Ie(e){const n=window!=null&&window.hasOwnProperty("DID_AGENTS_API")?"agents-ui":"agents-sdk",s=e.agent.presenter,a={token:e.token||"testKey",distinct_id:e.distinctId||ae(),agentId:e.agent.id,agentType:s.type==="clip"&&s.presenter_id.startsWith("v2_")?"clip_v2":s.type,owner_id:e.agent.owner_id??""};return{...a,isEnabled:e.isEnabled??!0,getRandom:()=>Math.random().toString(16).slice(2),track(t,r){if(!this.isEnabled)return Promise.reject("MixPanel analytics is disabled on creation");const{audioPath:i,...o}=r||{},l={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({data:JSON.stringify([{event:t,properties:{...o,...a,source:n,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",l).then(d=>d.json()).catch(d=>console.error(d))},linkTrack(t,r,i,o){q[t]||(q[t]={events:{},resolvedDependencies:[]}),o.includes(i)||o.push(i);const l=q[t];if(l.events[i]={props:r},l.resolvedDependencies.push(i),o.every(u=>l.resolvedDependencies.includes(u))){const u=o.reduce((f,k)=>l.events[k]?{...f,...l.events[k].props}:f,{});this.track(t,u),l.resolvedDependencies=l.resolvedDependencies.filter(f=>!o.includes(f)),o.forEach(f=>{delete l.events[f]})}}}}function Re(e){var t,r,i,o;const n=()=>/Mobi|Android/i.test(navigator.userAgent)?"Mobile":"Desktop",s=()=>{const l=navigator.platform;return l.toLowerCase().includes("win")?"Windows":l.toLowerCase().includes("mac")?"Mac OS X":l.toLowerCase().includes("linux")?"Linux":"Unknown"},a=e.presenter;return{$os:`${s()}`,isMobile:`${n()=="Mobile"}`,browser:navigator.userAgent,origin:window.location.origin,agentType:a.type==="clip"&&a.presenter_id.startsWith("v2_")?"clip_v2":a.type,agentVoice:{voiceId:(r=(t=e.presenter)==null?void 0:t.voice)==null?void 0:r.voice_id,provider:(o=(i=e.presenter)==null?void 0:i.voice)==null?void 0:o.type}}}function Ae(e,n,s){var d,u;const{event:a,...t}=e,{template:r}=(n==null?void 0:n.llm)||{},{language:i}=((d=n==null?void 0:n.presenter)==null?void 0:d.voice)||{},{stitch:o}=(n==null?void 0:n.presenter)||{};return{...t,llm:{...t.llm,template:r},script:{...t.script,provider:{...(u=t==null?void 0:t.script)==null?void 0:u.provider,language:i}},stitch:o,...s}}let T=0;function $e(e,n){var s,a,t,r;return{videoType:te(e.presenter.type),output_resolution:(s=n==null?void 0:n.streamOptions)==null?void 0:s.outputResolution,session_timeout:(a=n==null?void 0:n.streamOptions)==null?void 0:a.sessionTimeout,stream_warmup:(t=n==null?void 0:n.streamOptions)==null?void 0:t.streamWarmup,compatibility_mode:(r=n==null?void 0:n.streamOptions)==null?void 0:r.compatibilityMode}}function de(e){return e===S.Playground?{headers:{[ye]:"true"}}:{}}async function le(e,n,s,a,t){try{const r=await n.newChat(e,{persist:t??!1},de(a));return s.track("agent-chat",{event:"created",chat_id:r.id,agent_id:e,mode:a}),r}catch(r){try{console.error(r);const i=JSON.parse(r.message);if((i==null?void 0:i.kind)==="InsufficientCreditsError")throw new Error("InsufficientCreditsError")}catch(i){console.error("Error parsing the error message:",i)}throw new Error("Cannot create new chat")}}function Pe(e,n,s,a,t){return new Promise(async(r,i)=>{var l;T=0;const o=await Ee(e.id,$e(e,n),{...n,analytics:a,warmup:(l=n.streamOptions)==null?void 0:l.streamWarmup,callbacks:{...n.callbacks,onConnectionStateChange:async d=>{var u,f;d===y.Connected&&(!t&&n.mode!==S.DirectPlayback&&(t=await le(e.id,s,a,n.mode,n.persistentChat).catch(k=>{i(k)})),o?r({chat:t,streamingManager:o}):t&&i(new Error("Something went wrong while initializing the manager"))),(f=(u=n.callbacks).onConnectionStateChange)==null||f.call(u,d)},onVideoStateChange(d){var u,f;(f=(u=n.callbacks).onVideoStateChange)==null||f.call(u,d),T>0&&d===D.Start&&a.linkTrack("agent-video",{event:"start",latency:Date.now()-T},"start",[U.StreamVideoCreated])}}}).catch(i)})}function ge(e,n){if(n&&n.length>0)return n;let s="";if(e.greetings&&e.greetings.length>0){const a=Math.floor(Math.random()*e.greetings.length);s=e.greetings[a]}else s=`Hi! I'm ${e.preview_name||"My Agent"}. How can I help you?`;return[{content:s,id:W(),role:"assistant",created_at:new Date().toISOString()}]}function be(e){if(e.answer!==void 0)return e.answer;let n=0,s="";for(;n in e;)s+=e[n],n++;return s}function De(e,n,s,a,t){if(!(e===b.Partial||e===b.Answer))return;const r=a.messages[a.messages.length-1];if((r==null?void 0:r.role)!=="assistant")return;const{content:i,sequence:o}=n;e===b.Partial?s[o]=i:s.answer=i;const l=be(s);(r.content!==l||e===b.Answer)&&(r.content=l,t==null||t([...a.messages],e))}async function Te(e,n){var F,I,v;let s={},a=!0;const t={messages:[],chatMode:n.mode||S.Functional},r=n.baseURL||V,i=n.wsURL||ue,o=n.mixpanelKey||me,l=se(n.auth,r,n.callbacks.onError),d=await l.getById(e);t.messages=ge(d,n.initialMessages),(I=(F=n.callbacks).onNewMessage)==null||I.call(F,[...t.messages],"answer");const u=Ie({token:o,agent:d,...n});u.track("agent-sdk",{event:"loaded",...Re(d)});const f={onMessage:(c,m)=>{var g,p;if("content"in m)De(c,m,s,t,n.callbacks.onNewMessage),c===b.Answer&&u.track("agent-message-received",{messages:t.messages.length,mode:t.chatMode});else{const h=U,C=[h.StreamVideoDone,h.StreamVideoError,h.StreamVideoRejected],R=[h.StreamFailed,h.StreamVideoError,h.StreamVideoRejected],E=Ae(m,d,{mode:t.chatMode});if(c=c,c===h.StreamVideoCreated)u.linkTrack("agent-video",E,h.StreamVideoCreated,["start"]);else if(C.includes(c)){const _=c.split("/")[1];u.track("agent-video",{...E,event:_})}R.includes(c)&&((p=(g=n.callbacks).onError)==null||p.call(g,new Error(`Stream failed with event ${c}`),{data:m})),m.event===h.StreamDone&&M()}}};async function k(c){var R,E,_,A,K,P,$;(E=(R=n.callbacks).onConnectionStateChange)==null||E.call(R,y.Connecting),T=0,c&&!a&&(delete t.chat,t.messages=ge(d),(A=(_=n.callbacks).onNewMessage)==null||A.call(_,[...t.messages],"answer"));const m=n.mode===S.DirectPlayback?Promise.resolve(void 0):ve(n.auth,i,f),g=Pe(d,n,l,u,t.chat).catch(O=>{var z,J;throw x(S.Maintenance),(J=(z=n.callbacks).onConnectionStateChange)==null||J.call(z,y.Fail),O}),[p,{streamingManager:h,chat:C}]=await Promise.all([m,g]);C&&C.id!==((K=t.chat)==null?void 0:K.id)&&(($=(P=n.callbacks).onNewChat)==null||$.call(P,C.id)),t.streamingManager=h,t.socketManager=p,t.chat=C,a=!1,x((C==null?void 0:C.chat_mode)??n.mode??S.Functional)}async function M(){var c,m,g,p;(c=t.socketManager)==null||c.disconnect(),await((m=t.streamingManager)==null?void 0:m.disconnect()),delete t.streamingManager,delete t.socketManager,(p=(g=n.callbacks).onConnectionStateChange)==null||p.call(g,y.Disconnected)}async function x(c){var m,g;c!==t.chatMode&&(u.track("agent-mode-change",{mode:c}),t.chatMode=c,t.chatMode!==S.Functional&&await M(),(g=(m=n.callbacks).onModeChange)==null||g.call(m,c))}return{agent:d,starterMessages:((v=d.knowledge)==null?void 0:v.starter_message)||[],changeMode:x,async connect(){var c;await k(!0),u.track("agent-chat",{event:"connect",chatId:(c=t.chat)==null?void 0:c.id,agentId:d.id,mode:t.chatMode})},async reconnect(){var c;await M(),await k(!1),u.track("agent-chat",{event:"reconnect",chatId:(c=t.chat)==null?void 0:c.id,agentId:d.id,mode:t.chatMode})},async disconnect(){var c;await M(),u.track("agent-chat",{event:"disconnect",chatId:(c=t.chat)==null?void 0:c.id,agentId:d.id,mode:t.chatMode})},async chat(c){var g,p,h,C,R,E;const m=W();s={};try{if(T=Date.now(),n.mode===S.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===S.Maintenance)throw new Error("Chat is in maintenance mode");if(![S.TextOnly,S.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:W(),role:"user",content:c,created_at:new Date(T).toISOString()}),(p=(g=n.callbacks).onNewMessage)==null||p.call(g,[...t.messages],"user"),t.chat||(t.chat=await le(d.id,l,u,t.chatMode,n.persistentChat),(C=(h=n.callbacks).onNewChat)==null||C.call(h,t.chat.id));const _={id:m,role:"assistant",content:"",created_at:new Date().toISOString(),matches:[]},A=[...t.messages];t.messages.push(_);const K=$=>{var O,z;return l.chat(d.id,$,{sessionId:(O=t.streamingManager)==null?void 0:O.sessionId,streamId:(z=t.streamingManager)==null?void 0:z.streamId,chatMode:t.chatMode,messages:A.map(({matches:J,...Ne})=>Ne)},de(t.chatMode))},P=await K(t.chat.id).catch(async $=>{var O;if(!((O=$==null?void 0:$.message)!=null&&O.includes("missing or invalid session_id")))throw $;return await M(),await k(!1),K(t.chat.id)});return u.track("agent-message-send",{event:"success",mode:t.chatMode,messages:t.messages.length+1}),_.context=P.context,_.matches=P.matches,P.result&&(_.content=P.result,u.track("agent-message-received",{latency:Date.now()-T,mode:t.chatMode,messages:t.messages.length}),(E=(R=n.callbacks).onNewMessage)==null||E.call(R,[...t.messages],"answer")),P}catch(_){throw t.messages[t.messages.length-1].id===m&&t.messages.pop(),u.track("agent-message-send",{event:"error",mode:t.chatMode,messages:t.messages.length}),_}},rate(c,m,g){var C,R,E,_;const p=t.messages.find(A=>A.id===c);if(t.chat){if(!p)throw new Error("Message not found")}else throw new Error("Chat is not initialized");const h=((C=p.matches)==null?void 0:C.map(A=>[A.document_id,A.id]))??[];return u.track("agent-rate",{event:g?"update":"create",thumb:m===1?"up":"down",knowledge_id:((R=d.knowledge)==null?void 0:R.id)??"",mode:t.chatMode,matches:h,score:m}),g?l.updateRating(d.id,t.chat.id,g,{knowledge_id:((E=d.knowledge)==null?void 0:E.id)??"",message_id:c,matches:h,score:m}):l.createRating(d.id,t.chat.id,{knowledge_id:((_=d.knowledge)==null?void 0:_.id)??"",message_id:c,matches:h,score:m})},deleteRate(c){var m;if(!t.chat)throw new Error("Chat is not initialized");return u.track("agent-rate-delete",{type:"text",chat_id:(m=t.chat)==null?void 0:m.id,id:c,mode:t.chatMode}),l.deleteRating(d.id,t.chat.id,c)},speak(c){if(!t.streamingManager)throw new Error("Please connect to the agent first");function m(){if(typeof c=="string"){if(!d.presenter.voice)throw new Error("Presenter voice is not initialized");return{type:"text",provider:d.presenter.voice,input:c,ssml:!1}}if(c.type==="text"&&!c.provider){if(!d.presenter.voice)throw new Error("Presenter voice is not initialized");return{type:"text",provider:d.presenter.voice,input:c.input,ssml:c.ssml}}return c}const g=m();return u.track("agent-speak",g),t.streamingManager.speak({script:g})}}}function Oe(e,n,s){const{getById:a}=se(n,s||V);return a(e)}w.AgentStatus=Y,w.ChatMode=S,w.ChatProgress=b,w.ConnectionState=y,w.DocumentType=ee,w.KnowledgeType=Q,w.PlanGroup=X,w.Providers=ne,w.RateState=Z,w.StreamEvents=U,w.StreamingState=D,w.Subject=G,w.UserPlan=N,w.VideoType=j,w.VoiceAccess=re,w.createAgentManager=Te,w.getAgent=Oe,w.mapVideoType=te,Object.defineProperty(w,Symbol.toStringTag,{value:"Module"})});
|