@d-id/client-sdk 1.0.19-beta.100 → 1.0.19-beta.102
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 +350 -327
- package/dist/index.umd.cjs +1 -1
- package/dist/src/api/agents.d.ts +1 -4
- package/dist/src/consts.d.ts +1 -0
- package/dist/src/types/entities/agents/manager.d.ts +0 -6
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
|
-
var
|
|
2
|
-
const
|
|
3
|
-
function
|
|
1
|
+
var te = /* @__PURE__ */ ((e) => (e.TRIAL = "trial", e.BASIC = "basic", e.ENTERPRISE = "enterprise", e.LITE = "lite", e.ADVANCED = "advanced", e))(te || {}), ne = /* @__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))(ne || {}), re = /* @__PURE__ */ ((e) => (e.Unrated = "Unrated", e.Positive = "Positive", e.Negative = "Negative", e))(re || {}), S = /* @__PURE__ */ ((e) => (e.Functional = "Functional", e.TextOnly = "TextOnly", e.Maintenance = "Maintenance", e.Playground = "Playground", e))(S || {}), K = /* @__PURE__ */ ((e) => (e.Embed = "embed", e.Query = "query", e.Partial = "partial", e.Answer = "answer", e.Complete = "done", e))(K || {}), ae = /* @__PURE__ */ ((e) => (e.KnowledgeProcessing = "knowledge/processing", e.KnowledgeIndexing = "knowledge/indexing", e.KnowledgeFailed = "knowledge/error", e.KnowledgeDone = "knowledge/done", e))(ae || {}), ie = /* @__PURE__ */ ((e) => (e.Knowledge = "knowledge", e.Document = "document", e.Record = "record", e))(ie || {}), se = /* @__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))(se || {}), _ = /* @__PURE__ */ ((e) => (e.Clip = "clip", e.Talk = "talk", e))(_ || {}), O = /* @__PURE__ */ ((e) => (e.Start = "START", e.Stop = "STOP", e))(O || {}), E = /* @__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))(E || {}), I = /* @__PURE__ */ ((e) => (e[e.New = 0] = "New", e[e.Fail = 1] = "Fail", e[e.Connected = 2] = "Connected", e[e.Connecting = 3] = "Connecting", e[e.Terminating = 4] = "Terminating", e))(I || {}), oe = /* @__PURE__ */ ((e) => (e.Amazon = "amazon", e.Microsoft = "microsoft", e.Afflorithmics = "afflorithmics", e.Elevenlabs = "elevenlabs", e))(oe || {}), ce = /* @__PURE__ */ ((e) => (e.Public = "public", e.Premium = "premium", e.Private = "private", e))(ce || {});
|
|
2
|
+
const z = "https://api.d-id.com", de = "wss://notifications.d-id.com", le = "79f81a83a67430be2bc0fd61042b8faa", U = () => Math.random().toString(16).slice(2);
|
|
3
|
+
function Y() {
|
|
4
4
|
let e = window.localStorage.getItem("did_external_key_id");
|
|
5
5
|
return e || (e = Math.random().toString(16).slice(2), window.localStorage.setItem("did_external_key_id", e)), e;
|
|
6
6
|
}
|
|
7
|
-
let
|
|
8
|
-
function
|
|
7
|
+
let ge = U();
|
|
8
|
+
function Z(e) {
|
|
9
9
|
if (e.type === "bearer")
|
|
10
10
|
return `Bearer ${e.token}`;
|
|
11
11
|
if (e.type === "basic")
|
|
12
12
|
return `Basic ${btoa(`${e.username}:${e.password}`)}`;
|
|
13
13
|
if (e.type === "key")
|
|
14
|
-
return `Client-Key ${e.clientKey}.${
|
|
14
|
+
return `Client-Key ${e.clientKey}.${Y()}_${ge}`;
|
|
15
15
|
throw new Error(`Unknown auth type: ${e}`);
|
|
16
16
|
}
|
|
17
|
-
function W(e, s =
|
|
17
|
+
function W(e, s = z, t) {
|
|
18
18
|
const r = async (a, n) => {
|
|
19
19
|
const i = await fetch(s + (a != null && a.startsWith("/") ? a : `/${a}`), {
|
|
20
20
|
...n,
|
|
21
21
|
headers: {
|
|
22
22
|
...n == null ? void 0 : n.headers,
|
|
23
|
-
Authorization:
|
|
23
|
+
Authorization: Z(e),
|
|
24
24
|
"Content-Type": "application/json"
|
|
25
25
|
}
|
|
26
26
|
});
|
|
@@ -64,7 +64,7 @@ function W(e, s = L, t) {
|
|
|
64
64
|
}
|
|
65
65
|
};
|
|
66
66
|
}
|
|
67
|
-
function
|
|
67
|
+
function G(e, s = z, t) {
|
|
68
68
|
const r = W(e, `${s}/agents`, t);
|
|
69
69
|
return {
|
|
70
70
|
create(a, n) {
|
|
@@ -88,22 +88,19 @@ function Y(e, s = L, t) {
|
|
|
88
88
|
chat(a, n, i, o) {
|
|
89
89
|
return r.post(`/${a}/chat/${n}`, i, o);
|
|
90
90
|
},
|
|
91
|
-
getChatMode(a, n, i) {
|
|
92
|
-
return r.get(`/${a}/chat/${n}/mode`, i);
|
|
93
|
-
},
|
|
94
91
|
createRating(a, n, i, o) {
|
|
95
92
|
return r.post(`/${a}/chat/${n}/ratings`, i, o);
|
|
96
93
|
},
|
|
97
|
-
updateRating(a, n, i, o,
|
|
98
|
-
return r.patch(`/${a}/chat/${n}/ratings/${i}`, o,
|
|
94
|
+
updateRating(a, n, i, o, l) {
|
|
95
|
+
return r.patch(`/${a}/chat/${n}/ratings/${i}`, o, l);
|
|
99
96
|
},
|
|
100
97
|
deleteRating(a, n, i, o) {
|
|
101
98
|
return r.delete(`/${a}/chat/${n}/ratings/${i}`, o);
|
|
102
99
|
}
|
|
103
100
|
};
|
|
104
101
|
}
|
|
105
|
-
const
|
|
106
|
-
function
|
|
102
|
+
const ue = (e) => new Promise((s) => setTimeout(s, e));
|
|
103
|
+
function me(e) {
|
|
107
104
|
return new Promise((s, t) => {
|
|
108
105
|
const {
|
|
109
106
|
callbacks: r,
|
|
@@ -112,33 +109,33 @@ function ge(e) {
|
|
|
112
109
|
} = e, {
|
|
113
110
|
onMessage: i = null,
|
|
114
111
|
onOpen: o = null,
|
|
115
|
-
onClose:
|
|
116
|
-
onError:
|
|
117
|
-
} = r || {},
|
|
118
|
-
|
|
119
|
-
console.error(
|
|
120
|
-
},
|
|
121
|
-
o == null || o(
|
|
112
|
+
onClose: l = null,
|
|
113
|
+
onError: u = null
|
|
114
|
+
} = r || {}, f = new WebSocket(`${a}?authorization=${Z(n)}`);
|
|
115
|
+
f.onmessage = i, f.onclose = l, f.onerror = (p) => {
|
|
116
|
+
console.error(p), u == null || u("Websocket failed to connect", p), t(p);
|
|
117
|
+
}, f.onopen = (p) => {
|
|
118
|
+
o == null || o(p), s(f);
|
|
122
119
|
};
|
|
123
120
|
});
|
|
124
121
|
}
|
|
125
|
-
async function
|
|
122
|
+
async function he(e) {
|
|
126
123
|
const {
|
|
127
124
|
retries: s = 1
|
|
128
125
|
} = e;
|
|
129
126
|
let t = null;
|
|
130
127
|
for (let r = 0; (t == null ? void 0 : t.readyState) !== WebSocket.OPEN; r++)
|
|
131
128
|
try {
|
|
132
|
-
t = await
|
|
129
|
+
t = await me(e);
|
|
133
130
|
} catch (a) {
|
|
134
131
|
if (r === s)
|
|
135
132
|
throw a;
|
|
136
|
-
await
|
|
133
|
+
await ue(r * 500);
|
|
137
134
|
}
|
|
138
135
|
return t;
|
|
139
136
|
}
|
|
140
|
-
async function
|
|
141
|
-
const r = t != null && t.onMessage ? [t.onMessage] : [], a = await
|
|
137
|
+
async function q(e, s, t) {
|
|
138
|
+
const r = t != null && t.onMessage ? [t.onMessage] : [], a = await he({
|
|
142
139
|
auth: e,
|
|
143
140
|
host: s,
|
|
144
141
|
callbacks: {
|
|
@@ -155,7 +152,8 @@ async function j(e, s, t) {
|
|
|
155
152
|
subscribeToEvents: (n) => r.push(n)
|
|
156
153
|
};
|
|
157
154
|
}
|
|
158
|
-
|
|
155
|
+
const X = "X-Playground-Chat";
|
|
156
|
+
function we(e, s, t, r) {
|
|
159
157
|
const a = W(e, `${s}/agents/${t}`, r);
|
|
160
158
|
return {
|
|
161
159
|
createStream(n) {
|
|
@@ -164,39 +162,39 @@ function me(e, s, t, r) {
|
|
|
164
162
|
presenter_id: n.presenter_id,
|
|
165
163
|
compatibility_mode: n.compatibility_mode,
|
|
166
164
|
stream_warmup: n.stream_warmup,
|
|
167
|
-
type:
|
|
165
|
+
type: _.Clip
|
|
168
166
|
});
|
|
169
167
|
},
|
|
170
168
|
startConnection(n, i, o) {
|
|
171
169
|
return a.post(`/streams/${n}/sdp`, {
|
|
172
170
|
session_id: o,
|
|
173
171
|
answer: i,
|
|
174
|
-
type:
|
|
172
|
+
type: _.Clip
|
|
175
173
|
});
|
|
176
174
|
},
|
|
177
175
|
addIceCandidate(n, i, o) {
|
|
178
176
|
return a.post(`/streams/${n}/ice`, {
|
|
179
177
|
session_id: o,
|
|
180
178
|
...i,
|
|
181
|
-
type:
|
|
179
|
+
type: _.Clip
|
|
182
180
|
});
|
|
183
181
|
},
|
|
184
182
|
sendStreamRequest(n, i, o) {
|
|
185
183
|
return a.post(`/streams/${n}`, {
|
|
186
184
|
session_id: i,
|
|
187
185
|
...o,
|
|
188
|
-
type:
|
|
186
|
+
type: _.Clip
|
|
189
187
|
});
|
|
190
188
|
},
|
|
191
189
|
close(n, i) {
|
|
192
190
|
return a.delete(`/streams/${n}`, {
|
|
193
191
|
session_id: i,
|
|
194
|
-
type:
|
|
192
|
+
type: _.Clip
|
|
195
193
|
});
|
|
196
194
|
}
|
|
197
195
|
};
|
|
198
196
|
}
|
|
199
|
-
function
|
|
197
|
+
function fe(e, s, t, r) {
|
|
200
198
|
const a = W(e, `${s}/agents/${t}`, r);
|
|
201
199
|
return {
|
|
202
200
|
createStream(n, i) {
|
|
@@ -208,56 +206,56 @@ function he(e, s, t, r) {
|
|
|
208
206
|
compatibility_mode: n.compatibility_mode,
|
|
209
207
|
stream_warmup: n.stream_warmup,
|
|
210
208
|
output_resolution: n.output_resolution,
|
|
211
|
-
type:
|
|
209
|
+
type: _.Talk
|
|
212
210
|
}, i);
|
|
213
211
|
},
|
|
214
|
-
startConnection(n, i, o,
|
|
212
|
+
startConnection(n, i, o, l) {
|
|
215
213
|
return a.post(`/streams/${n}/sdp`, {
|
|
216
214
|
session_id: o,
|
|
217
215
|
answer: i,
|
|
218
|
-
type:
|
|
219
|
-
},
|
|
216
|
+
type: _.Talk
|
|
217
|
+
}, l);
|
|
220
218
|
},
|
|
221
|
-
addIceCandidate(n, i, o,
|
|
219
|
+
addIceCandidate(n, i, o, l) {
|
|
222
220
|
return a.post(`/streams/${n}/ice`, {
|
|
223
221
|
session_id: o,
|
|
224
222
|
...i,
|
|
225
|
-
type:
|
|
226
|
-
},
|
|
223
|
+
type: _.Talk
|
|
224
|
+
}, l);
|
|
227
225
|
},
|
|
228
|
-
sendStreamRequest(n, i, o,
|
|
226
|
+
sendStreamRequest(n, i, o, l) {
|
|
229
227
|
return a.post(`/streams/${n}`, {
|
|
230
228
|
session_id: i,
|
|
231
229
|
...o,
|
|
232
|
-
type:
|
|
233
|
-
},
|
|
230
|
+
type: _.Talk
|
|
231
|
+
}, l);
|
|
234
232
|
},
|
|
235
233
|
close(n, i, o) {
|
|
236
234
|
return a.delete(`/streams/${n}`, {
|
|
237
235
|
session_id: i,
|
|
238
|
-
type:
|
|
236
|
+
type: _.Talk
|
|
239
237
|
}, o);
|
|
240
238
|
}
|
|
241
239
|
};
|
|
242
240
|
}
|
|
243
|
-
let
|
|
244
|
-
const T = (e, s) =>
|
|
245
|
-
function
|
|
241
|
+
let ee = !1;
|
|
242
|
+
const T = (e, s) => ee && console.log(e, s), pe = (window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection).bind(window);
|
|
243
|
+
function Q(e) {
|
|
246
244
|
switch (e) {
|
|
247
245
|
case "connected":
|
|
248
|
-
return
|
|
246
|
+
return I.Connected;
|
|
249
247
|
case "checking":
|
|
250
|
-
return
|
|
248
|
+
return I.Connecting;
|
|
251
249
|
case "failed":
|
|
252
|
-
return
|
|
250
|
+
return I.Fail;
|
|
253
251
|
case "new":
|
|
254
252
|
case "closed":
|
|
255
253
|
case "disconnected":
|
|
256
254
|
default:
|
|
257
|
-
return
|
|
255
|
+
return I.New;
|
|
258
256
|
}
|
|
259
257
|
}
|
|
260
|
-
function
|
|
258
|
+
function ve() {
|
|
261
259
|
let e = 0;
|
|
262
260
|
return (s) => {
|
|
263
261
|
for (const t of s.values())
|
|
@@ -268,113 +266,113 @@ function fe() {
|
|
|
268
266
|
return !1;
|
|
269
267
|
};
|
|
270
268
|
}
|
|
271
|
-
function
|
|
269
|
+
function ye(e, s) {
|
|
272
270
|
const r = Math.max(Math.ceil(10), 1);
|
|
273
271
|
let a = 0, n = !1;
|
|
274
|
-
const i =
|
|
272
|
+
const i = ve();
|
|
275
273
|
return setInterval(async () => {
|
|
276
274
|
const o = await e.getStats();
|
|
277
|
-
i(o) ? (a = 0, n || (s == null || s(
|
|
275
|
+
i(o) ? (a = 0, n || (s == null || s(O.Start), n = !0)) : n && (a++, a >= r && (s == null || s(O.Stop), n = !1));
|
|
278
276
|
}, 100);
|
|
279
277
|
}
|
|
280
|
-
async function
|
|
278
|
+
async function Me(e, s, {
|
|
281
279
|
debug: t = !1,
|
|
282
280
|
callbacks: r,
|
|
283
281
|
auth: a,
|
|
284
282
|
analytics: n,
|
|
285
|
-
baseURL: i =
|
|
283
|
+
baseURL: i = z
|
|
286
284
|
}) {
|
|
287
|
-
|
|
285
|
+
ee = t;
|
|
288
286
|
let o;
|
|
289
287
|
const {
|
|
290
|
-
startConnection:
|
|
291
|
-
sendStreamRequest:
|
|
292
|
-
close:
|
|
293
|
-
createStream:
|
|
294
|
-
addIceCandidate:
|
|
295
|
-
} = s.videoType ===
|
|
296
|
-
id:
|
|
297
|
-
offer:
|
|
298
|
-
ice_servers:
|
|
299
|
-
session_id:
|
|
300
|
-
} = await
|
|
301
|
-
iceServers:
|
|
302
|
-
}),
|
|
303
|
-
if (
|
|
288
|
+
startConnection: l,
|
|
289
|
+
sendStreamRequest: u,
|
|
290
|
+
close: f,
|
|
291
|
+
createStream: p,
|
|
292
|
+
addIceCandidate: k
|
|
293
|
+
} = s.videoType === _.Clip ? we(a, i, e, r.onError) : fe(a, i, e, r.onError), {
|
|
294
|
+
id: M,
|
|
295
|
+
offer: L,
|
|
296
|
+
ice_servers: b,
|
|
297
|
+
session_id: $
|
|
298
|
+
} = await p(s), v = new pe({
|
|
299
|
+
iceServers: b
|
|
300
|
+
}), F = v.createDataChannel("JanusDataChannel");
|
|
301
|
+
if (!$)
|
|
304
302
|
throw new Error("Could not create session_id");
|
|
305
|
-
const
|
|
306
|
-
|
|
307
|
-
T("peerConnection.onicecandidate",
|
|
308
|
-
candidate:
|
|
309
|
-
sdpMid:
|
|
310
|
-
sdpMLineIndex:
|
|
311
|
-
},
|
|
303
|
+
const d = ye(v, r.onVideoStateChange);
|
|
304
|
+
v.onicecandidate = (c) => {
|
|
305
|
+
T("peerConnection.onicecandidate", c), c.candidate && c.candidate.sdpMid && c.candidate.sdpMLineIndex !== null ? k(M, {
|
|
306
|
+
candidate: c.candidate.candidate,
|
|
307
|
+
sdpMid: c.candidate.sdpMid,
|
|
308
|
+
sdpMLineIndex: c.candidate.sdpMLineIndex
|
|
309
|
+
}, $) : k(M, {
|
|
312
310
|
candidate: null
|
|
313
|
-
},
|
|
314
|
-
},
|
|
315
|
-
var
|
|
316
|
-
T("peerConnection.oniceconnectionstatechange => " +
|
|
317
|
-
const
|
|
318
|
-
|
|
319
|
-
var
|
|
320
|
-
(
|
|
321
|
-
}, 5e3) : (clearTimeout(o), (
|
|
322
|
-
},
|
|
323
|
-
var
|
|
324
|
-
T("peerConnection.ontrack",
|
|
325
|
-
},
|
|
326
|
-
var
|
|
327
|
-
if (
|
|
328
|
-
const [
|
|
329
|
-
|
|
311
|
+
}, $);
|
|
312
|
+
}, v.oniceconnectionstatechange = () => {
|
|
313
|
+
var m;
|
|
314
|
+
T("peerConnection.oniceconnectionstatechange => " + v.iceConnectionState);
|
|
315
|
+
const c = Q(v.iceConnectionState);
|
|
316
|
+
c === I.Connected ? o = setTimeout(() => {
|
|
317
|
+
var h;
|
|
318
|
+
(h = r.onConnectionStateChange) == null || h.call(r, I.Connected);
|
|
319
|
+
}, 5e3) : (clearTimeout(o), (m = r.onConnectionStateChange) == null || m.call(r, c));
|
|
320
|
+
}, v.ontrack = (c) => {
|
|
321
|
+
var m;
|
|
322
|
+
T("peerConnection.ontrack", c), (m = r.onSrcObjectReady) == null || m.call(r, c.streams[0]);
|
|
323
|
+
}, F.onmessage = (c) => {
|
|
324
|
+
var m;
|
|
325
|
+
if (F.readyState === "open") {
|
|
326
|
+
const [h, y] = c.data.split(":");
|
|
327
|
+
h === E.StreamReady && (clearTimeout(o), (m = r.onConnectionStateChange) == null || m.call(r, I.Connected));
|
|
330
328
|
}
|
|
331
|
-
}, await
|
|
332
|
-
const
|
|
333
|
-
return T("create answer OK"), await
|
|
329
|
+
}, await v.setRemoteDescription(L), T("set remote description OK");
|
|
330
|
+
const g = await v.createAnswer();
|
|
331
|
+
return T("create answer OK"), await v.setLocalDescription(g), T("set local description OK"), await l(M, g, $), T("start connection OK"), {
|
|
334
332
|
/**
|
|
335
333
|
* Method to send request to server to get clip or talk depend on you payload
|
|
336
334
|
* @param payload
|
|
337
335
|
*/
|
|
338
|
-
speak(
|
|
339
|
-
return
|
|
336
|
+
speak(c) {
|
|
337
|
+
return u(M, $, c);
|
|
340
338
|
},
|
|
341
339
|
/**
|
|
342
340
|
* Method to close RTC connection
|
|
343
341
|
*/
|
|
344
342
|
async disconnect() {
|
|
345
|
-
var
|
|
346
|
-
if (
|
|
347
|
-
if (
|
|
348
|
-
if (
|
|
349
|
-
(
|
|
343
|
+
var c, m, h;
|
|
344
|
+
if (M) {
|
|
345
|
+
if (v) {
|
|
346
|
+
if (Q(v.iceConnectionState) === I.New) {
|
|
347
|
+
(c = r.onVideoStateChange) == null || c.call(r, O.Stop), clearInterval(d);
|
|
350
348
|
return;
|
|
351
349
|
}
|
|
352
|
-
|
|
350
|
+
v.close(), v.oniceconnectionstatechange = null, v.onnegotiationneeded = null, v.onicecandidate = null, v.ontrack = null;
|
|
353
351
|
}
|
|
354
352
|
try {
|
|
355
|
-
await
|
|
353
|
+
await f(M, $).catch((y) => {
|
|
356
354
|
});
|
|
357
|
-
} catch (
|
|
358
|
-
T("Error on close stream connection",
|
|
355
|
+
} catch (y) {
|
|
356
|
+
T("Error on close stream connection", y);
|
|
359
357
|
}
|
|
360
|
-
(
|
|
358
|
+
(m = r.onConnectionStateChange) == null || m.call(r, I.New), (h = r.onVideoStateChange) == null || h.call(r, O.Stop), clearInterval(d);
|
|
361
359
|
}
|
|
362
360
|
},
|
|
363
361
|
/**
|
|
364
362
|
* Session identifier information, should be returned in the body of all streaming requests
|
|
365
363
|
*/
|
|
366
|
-
sessionId:
|
|
364
|
+
sessionId: $,
|
|
367
365
|
/**
|
|
368
366
|
* Id of current RTC stream
|
|
369
367
|
*/
|
|
370
|
-
streamId:
|
|
368
|
+
streamId: M
|
|
371
369
|
};
|
|
372
370
|
}
|
|
373
|
-
let
|
|
374
|
-
function
|
|
371
|
+
let B = {};
|
|
372
|
+
function Ce(e) {
|
|
375
373
|
const s = window != null && window.hasOwnProperty("DID_AGENTS_API") ? "agents-ui" : "agents-sdk", t = {
|
|
376
374
|
token: e.token || "testKey",
|
|
377
|
-
distinct_id: e.distinctId ||
|
|
375
|
+
distinct_id: e.distinctId || Y(),
|
|
378
376
|
isEnabled: e.isEnabled ?? !0,
|
|
379
377
|
agentId: e.agent.id,
|
|
380
378
|
agentType: e.agent.presenter.type,
|
|
@@ -411,32 +409,32 @@ function ye(e) {
|
|
|
411
409
|
return fetch("https://api-js.mixpanel.com/track/?verbose=1&ip=1", n).then((i) => i.json()).catch((i) => console.error(i));
|
|
412
410
|
},
|
|
413
411
|
linkTrack(r, a, n, i) {
|
|
414
|
-
|
|
412
|
+
B[r] || (B[r] = {
|
|
415
413
|
events: {},
|
|
416
414
|
resolvedDependencies: []
|
|
417
415
|
}), i.includes(n) || i.push(n);
|
|
418
|
-
const o =
|
|
416
|
+
const o = B[r];
|
|
419
417
|
if (o.events[n] = {
|
|
420
418
|
props: a
|
|
421
|
-
}, o.resolvedDependencies.push(n), i.every((
|
|
422
|
-
const
|
|
423
|
-
...
|
|
424
|
-
...o.events[
|
|
425
|
-
} :
|
|
426
|
-
this.track(r,
|
|
427
|
-
delete o.events[
|
|
419
|
+
}, o.resolvedDependencies.push(n), i.every((u) => o.resolvedDependencies.includes(u))) {
|
|
420
|
+
const u = i.reduce((f, p) => o.events[p] ? {
|
|
421
|
+
...f,
|
|
422
|
+
...o.events[p].props
|
|
423
|
+
} : f, {});
|
|
424
|
+
this.track(r, u), o.resolvedDependencies = o.resolvedDependencies.filter((f) => !i.includes(f)), i.forEach((f) => {
|
|
425
|
+
delete o.events[f];
|
|
428
426
|
});
|
|
429
427
|
}
|
|
430
428
|
}
|
|
431
429
|
};
|
|
432
430
|
}
|
|
433
|
-
function
|
|
431
|
+
function _e(e) {
|
|
434
432
|
var r, a, n, i, o;
|
|
435
433
|
const s = () => /Mobi|Android/i.test(navigator.userAgent) ? "Mobile" : "Desktop";
|
|
436
434
|
return {
|
|
437
435
|
$os: `${(() => {
|
|
438
|
-
const
|
|
439
|
-
return
|
|
436
|
+
const l = navigator.platform;
|
|
437
|
+
return l.toLowerCase().includes("win") ? "Windows" : l.toLowerCase().includes("mac") ? "Mac OS X" : l.toLowerCase().includes("linux") ? "Linux" : "Unknown";
|
|
440
438
|
})()}`,
|
|
441
439
|
isMobile: `${s() == "Mobile"}`,
|
|
442
440
|
browser: navigator.userAgent,
|
|
@@ -448,22 +446,22 @@ function Me(e) {
|
|
|
448
446
|
}
|
|
449
447
|
};
|
|
450
448
|
}
|
|
451
|
-
const
|
|
452
|
-
let
|
|
453
|
-
function
|
|
449
|
+
const Se = 1080;
|
|
450
|
+
let D = 0;
|
|
451
|
+
function Ie(e, s) {
|
|
454
452
|
if (e.presenter) {
|
|
455
|
-
if (e.presenter.type ===
|
|
453
|
+
if (e.presenter.type === _.Clip)
|
|
456
454
|
return {
|
|
457
|
-
videoType:
|
|
455
|
+
videoType: _.Clip,
|
|
458
456
|
driver_id: e.presenter.driver_id,
|
|
459
457
|
presenter_id: e.presenter.presenter_id,
|
|
460
458
|
stream_warmup: !0
|
|
461
459
|
};
|
|
462
460
|
} else
|
|
463
461
|
throw new Error("Presenter is not initialized");
|
|
464
|
-
const t = s || (e.presenter.stitch ?
|
|
462
|
+
const t = s || (e.presenter.stitch ? Se : void 0);
|
|
465
463
|
return {
|
|
466
|
-
videoType:
|
|
464
|
+
videoType: _.Talk,
|
|
467
465
|
source_url: e.presenter.source_url,
|
|
468
466
|
stream_warmup: !0,
|
|
469
467
|
...t && {
|
|
@@ -471,55 +469,63 @@ function _e(e, s) {
|
|
|
471
469
|
}
|
|
472
470
|
};
|
|
473
471
|
}
|
|
474
|
-
function
|
|
475
|
-
return
|
|
472
|
+
function ke(e, s, t, r, a) {
|
|
473
|
+
return D = 0, new Promise(async (n, i) => {
|
|
476
474
|
let o = a;
|
|
477
|
-
const
|
|
475
|
+
const l = await Me(e.id, Ie(e, s.outputResolution), {
|
|
478
476
|
...s,
|
|
479
477
|
analytics: r,
|
|
480
478
|
callbacks: {
|
|
481
479
|
...s.callbacks,
|
|
482
|
-
onConnectionStateChange: async (
|
|
483
|
-
var
|
|
484
|
-
if (
|
|
485
|
-
|
|
480
|
+
onConnectionStateChange: async (u) => {
|
|
481
|
+
var f, p;
|
|
482
|
+
if (u === I.Connected) {
|
|
483
|
+
if (!o)
|
|
486
484
|
try {
|
|
487
|
-
o
|
|
485
|
+
o = await t.newChat(e.id), r.track("agent-chat", {
|
|
488
486
|
event: "created",
|
|
489
487
|
chat_id: o.id,
|
|
490
488
|
agent_id: e.id
|
|
491
|
-
})
|
|
489
|
+
}), l && n({
|
|
492
490
|
chat: o,
|
|
493
|
-
streamingManager:
|
|
491
|
+
streamingManager: l
|
|
494
492
|
});
|
|
495
|
-
} catch (
|
|
496
|
-
console.error(
|
|
493
|
+
} catch (k) {
|
|
494
|
+
console.error(k);
|
|
495
|
+
let M;
|
|
496
|
+
try {
|
|
497
|
+
M = JSON.parse(k.message);
|
|
498
|
+
} catch (L) {
|
|
499
|
+
console.error("Error parsing the error message:", L);
|
|
500
|
+
}
|
|
501
|
+
(M == null ? void 0 : M.kind) === "InsufficientCreditsError" && i("InsufficientCreditsError"), i("Cannot create new chat");
|
|
497
502
|
}
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
503
|
+
l && o && n({
|
|
504
|
+
chat: o,
|
|
505
|
+
streamingManager: l
|
|
506
|
+
});
|
|
507
|
+
} else
|
|
508
|
+
u === I.Fail && i(new Error("Cannot create connection"));
|
|
509
|
+
(p = (f = s.callbacks).onConnectionStateChange) == null || p.call(f, u);
|
|
504
510
|
},
|
|
505
|
-
onVideoStateChange(
|
|
506
|
-
var
|
|
507
|
-
if ((
|
|
508
|
-
const
|
|
511
|
+
onVideoStateChange(u) {
|
|
512
|
+
var f, p;
|
|
513
|
+
if ((p = (f = s.callbacks).onVideoStateChange) == null || p.call(f, u), D > 0 && u === O.Start) {
|
|
514
|
+
const k = "start";
|
|
509
515
|
r.linkTrack("agent-video", {
|
|
510
|
-
event:
|
|
511
|
-
latency: Date.now() -
|
|
512
|
-
},
|
|
516
|
+
event: k,
|
|
517
|
+
latency: Date.now() - D
|
|
518
|
+
}, k, [E.StreamVideoCreated]);
|
|
513
519
|
}
|
|
514
520
|
}
|
|
515
521
|
}
|
|
516
522
|
}).catch(i);
|
|
517
523
|
});
|
|
518
524
|
}
|
|
519
|
-
function
|
|
520
|
-
return
|
|
525
|
+
function Ae(e, s, t) {
|
|
526
|
+
return G(s, t || z).getById(e);
|
|
521
527
|
}
|
|
522
|
-
function
|
|
528
|
+
function H(e) {
|
|
523
529
|
let s = "";
|
|
524
530
|
if (e.greetings && e.greetings.length > 0) {
|
|
525
531
|
const t = Math.floor(Math.random() * e.greetings.length);
|
|
@@ -528,250 +534,267 @@ function B(e) {
|
|
|
528
534
|
s = `Hi! I'm ${e.preview_name || "My Agent"}. How can I help you?`;
|
|
529
535
|
return [{
|
|
530
536
|
content: s,
|
|
531
|
-
id:
|
|
537
|
+
id: U(),
|
|
532
538
|
role: "assistant",
|
|
533
539
|
created_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
534
540
|
}];
|
|
535
541
|
}
|
|
536
|
-
async function
|
|
537
|
-
var
|
|
542
|
+
async function Re(e, s) {
|
|
543
|
+
var $, v, F;
|
|
538
544
|
const t = {
|
|
539
545
|
messages: [],
|
|
540
|
-
chatMode: s.mode ||
|
|
546
|
+
chatMode: s.mode || S.Functional
|
|
541
547
|
};
|
|
542
548
|
let r = -1;
|
|
543
|
-
const a = s.wsURL ||
|
|
544
|
-
t.messages =
|
|
545
|
-
const
|
|
549
|
+
const a = s.wsURL || de, n = s.baseURL || z, i = s.mixpanelKey || le, o = G(s.auth, n, s.callbacks.onError), l = await o.getById(e);
|
|
550
|
+
t.messages = H(l), (v = ($ = s.callbacks).onNewMessage) == null || v.call($, t.messages);
|
|
551
|
+
const u = Ce({
|
|
546
552
|
token: i,
|
|
547
|
-
agent:
|
|
553
|
+
agent: l,
|
|
548
554
|
...s
|
|
549
555
|
});
|
|
550
|
-
|
|
556
|
+
u.track("agent-sdk", {
|
|
551
557
|
event: "loaded",
|
|
552
|
-
...
|
|
558
|
+
..._e(l)
|
|
553
559
|
});
|
|
554
|
-
const
|
|
555
|
-
onMessage: (d,
|
|
556
|
-
var
|
|
557
|
-
if ("content" in
|
|
560
|
+
const f = {
|
|
561
|
+
onMessage: (d, g) => {
|
|
562
|
+
var c, m, h, y, A, R;
|
|
563
|
+
if ("content" in g) {
|
|
558
564
|
const {
|
|
559
|
-
content:
|
|
560
|
-
} =
|
|
561
|
-
(
|
|
565
|
+
content: C
|
|
566
|
+
} = g, w = t.messages[t.messages.length - 1];
|
|
567
|
+
(w == null ? void 0 : w.role) === "assistant" && (r < t.messages.length && (w.content = d === K.Partial ? w.content + C : C), d === K.Answer && (r = t.messages.length)), d === K.Answer && u.track("agent-message-received", {
|
|
562
568
|
messages: t.messages.length
|
|
563
|
-
}), (
|
|
569
|
+
}), (m = (c = s.callbacks).onNewMessage) == null || m.call(c, t.messages);
|
|
564
570
|
} else {
|
|
565
|
-
if (d = d, d ===
|
|
571
|
+
if (d = d, d === E.StreamVideoCreated) {
|
|
566
572
|
const {
|
|
567
|
-
event:
|
|
568
|
-
...
|
|
569
|
-
} =
|
|
570
|
-
|
|
571
|
-
...
|
|
572
|
-
template: (h =
|
|
573
|
-
},
|
|
574
|
-
...
|
|
575
|
-
},
|
|
576
|
-
} else if ([
|
|
577
|
-
const
|
|
578
|
-
...
|
|
579
|
-
event:
|
|
573
|
+
event: C,
|
|
574
|
+
...w
|
|
575
|
+
} = g;
|
|
576
|
+
w.llm = {
|
|
577
|
+
...w.llm,
|
|
578
|
+
template: (h = l.llm) == null ? void 0 : h.template
|
|
579
|
+
}, u.linkTrack("agent-video", {
|
|
580
|
+
...w
|
|
581
|
+
}, E.StreamVideoCreated, ["start"]);
|
|
582
|
+
} else if ([E.StreamVideoDone, E.StreamVideoError, E.StreamVideoRejected].includes(d)) {
|
|
583
|
+
const C = d.split("/")[1], w = {
|
|
584
|
+
...g,
|
|
585
|
+
event: C
|
|
580
586
|
};
|
|
581
|
-
|
|
582
|
-
...
|
|
583
|
-
template: (
|
|
584
|
-
},
|
|
585
|
-
...
|
|
586
|
-
event:
|
|
587
|
+
w.llm = {
|
|
588
|
+
...w.llm,
|
|
589
|
+
template: (y = l.llm) == null ? void 0 : y.template
|
|
590
|
+
}, u.track("agent-video", {
|
|
591
|
+
...w,
|
|
592
|
+
event: C
|
|
587
593
|
});
|
|
588
594
|
}
|
|
589
|
-
[
|
|
590
|
-
data:
|
|
595
|
+
[E.StreamFailed, E.StreamVideoError, E.StreamVideoRejected].includes(d) && ((R = (A = s.callbacks).onError) == null || R.call(A, new Error(`Stream failed with event ${d}`), {
|
|
596
|
+
data: g
|
|
591
597
|
}));
|
|
592
598
|
}
|
|
593
599
|
}
|
|
594
600
|
};
|
|
595
|
-
async function
|
|
596
|
-
var h,
|
|
597
|
-
|
|
598
|
-
const d = await
|
|
599
|
-
streamingManager:
|
|
600
|
-
chat:
|
|
601
|
-
} = await
|
|
602
|
-
r = -1, t.messages.length === 0 && (t.messages =
|
|
603
|
-
const
|
|
604
|
-
|
|
601
|
+
async function p() {
|
|
602
|
+
var h, y, A, R, C, w;
|
|
603
|
+
D = 0;
|
|
604
|
+
const d = await q(s.auth, a, f), {
|
|
605
|
+
streamingManager: g,
|
|
606
|
+
chat: c
|
|
607
|
+
} = await b();
|
|
608
|
+
r = -1, t.messages.length === 0 && (t.messages = H(l), (y = (h = s.callbacks).onNewMessage) == null || y.call(h, t.messages)), c != null && c.id && c.id !== ((A = t.chat) == null ? void 0 : A.id) && ((C = (R = s.callbacks).onNewChat) == null || C.call(R, c == null ? void 0 : c.id)), t.streamingManager = g, t.socketManager = d, t.chat = c;
|
|
609
|
+
const m = ((w = t.chat) == null ? void 0 : w.chatMode) || S.Functional;
|
|
610
|
+
M(m), u.track("agent-chat", {
|
|
605
611
|
event: "connect",
|
|
606
|
-
chatId:
|
|
607
|
-
agentId:
|
|
612
|
+
chatId: c.id,
|
|
613
|
+
agentId: l.id
|
|
608
614
|
});
|
|
609
615
|
}
|
|
610
|
-
async function
|
|
611
|
-
var d,
|
|
612
|
-
(d = t.socketManager) == null || d.disconnect(), await ((
|
|
616
|
+
async function k() {
|
|
617
|
+
var d, g, c, m, h;
|
|
618
|
+
(d = t.socketManager) == null || d.disconnect(), await ((g = t.streamingManager) == null ? void 0 : g.disconnect()), delete t.streamingManager, delete t.socketManager, t.messages = H(l), (m = (c = s.callbacks).onNewMessage) == null || m.call(c, t.messages), u.track("agent-chat", {
|
|
613
619
|
event: "disconnect",
|
|
614
620
|
chatId: (h = t.chat) == null ? void 0 : h.id,
|
|
615
|
-
agentId:
|
|
621
|
+
agentId: l.id
|
|
616
622
|
});
|
|
617
623
|
}
|
|
618
|
-
async function
|
|
619
|
-
var
|
|
620
|
-
d !== t.chatMode && (
|
|
624
|
+
async function M(d) {
|
|
625
|
+
var g, c;
|
|
626
|
+
d !== t.chatMode && (u.track("agent-mode-change", {
|
|
621
627
|
mode: d
|
|
622
|
-
}), t.chatMode = d, t.chatMode !==
|
|
628
|
+
}), t.chatMode = d, t.chatMode !== S.Functional && await k(), (c = (g = s.callbacks).onModeChange) == null || c.call(g, d));
|
|
623
629
|
}
|
|
624
|
-
async function
|
|
630
|
+
async function L() {
|
|
625
631
|
if (!t.chat)
|
|
626
|
-
return
|
|
632
|
+
return p();
|
|
627
633
|
const {
|
|
628
634
|
streamingManager: d,
|
|
629
|
-
chat:
|
|
630
|
-
} = await
|
|
631
|
-
t.streamingManager = d,
|
|
635
|
+
chat: g
|
|
636
|
+
} = await b();
|
|
637
|
+
t.streamingManager = d, M(t.chat.chatMode || S.Functional), u.track("agent-chat", {
|
|
632
638
|
event: "reconnect",
|
|
633
|
-
chatId:
|
|
634
|
-
agentId:
|
|
639
|
+
chatId: g.id,
|
|
640
|
+
agentId: l.id
|
|
635
641
|
});
|
|
636
642
|
}
|
|
643
|
+
async function b() {
|
|
644
|
+
let d, g;
|
|
645
|
+
try {
|
|
646
|
+
const c = await ke(l, s, o, u, t.chat);
|
|
647
|
+
d = c.streamingManager, g = c.chat;
|
|
648
|
+
} catch (c) {
|
|
649
|
+
throw M(S.Maintenance), c;
|
|
650
|
+
}
|
|
651
|
+
return {
|
|
652
|
+
streamingManager: d,
|
|
653
|
+
chat: g
|
|
654
|
+
};
|
|
655
|
+
}
|
|
637
656
|
return {
|
|
638
|
-
agent:
|
|
639
|
-
starterMessages: ((
|
|
640
|
-
connect:
|
|
641
|
-
disconnect:
|
|
642
|
-
changeMode:
|
|
657
|
+
agent: l,
|
|
658
|
+
starterMessages: ((F = l.knowledge) == null ? void 0 : F.starter_message) || [],
|
|
659
|
+
connect: p,
|
|
660
|
+
disconnect: k,
|
|
661
|
+
changeMode: M,
|
|
643
662
|
async reconnect() {
|
|
644
|
-
var h,
|
|
663
|
+
var h, y;
|
|
645
664
|
if (!t.chat)
|
|
646
|
-
return
|
|
647
|
-
(h = t.socketManager) == null || h.disconnect(), await ((
|
|
648
|
-
const d = await
|
|
649
|
-
streamingManager:
|
|
650
|
-
chat:
|
|
651
|
-
} = await
|
|
652
|
-
t.streamingManager =
|
|
653
|
-
const
|
|
654
|
-
|
|
665
|
+
return p();
|
|
666
|
+
(h = t.socketManager) == null || h.disconnect(), await ((y = t.streamingManager) == null ? void 0 : y.disconnect());
|
|
667
|
+
const d = await q(s.auth, a, f), {
|
|
668
|
+
streamingManager: g,
|
|
669
|
+
chat: c
|
|
670
|
+
} = await b();
|
|
671
|
+
t.streamingManager = g, t.socketManager = d;
|
|
672
|
+
const m = t.chat.chatMode || S.Functional;
|
|
673
|
+
M(m), u.track("agent-chat", {
|
|
655
674
|
event: "reconnect",
|
|
656
|
-
chatId:
|
|
657
|
-
agentId:
|
|
675
|
+
chatId: c.id,
|
|
676
|
+
agentId: l.id
|
|
658
677
|
});
|
|
659
678
|
},
|
|
660
679
|
async chat(d) {
|
|
661
|
-
var
|
|
662
|
-
const
|
|
680
|
+
var c, m, h, y, A, R, C, w, J;
|
|
681
|
+
const g = U();
|
|
663
682
|
try {
|
|
664
|
-
if (
|
|
683
|
+
if (D = Date.now(), d.length >= 800)
|
|
665
684
|
throw new Error("Message cannot be more than 800 characters");
|
|
666
685
|
if (d.length === 0)
|
|
667
686
|
throw new Error("Message cannot be empty");
|
|
668
|
-
if (t.chatMode ===
|
|
687
|
+
if (t.chatMode === S.Maintenance)
|
|
669
688
|
throw new Error("Chat is in maintenance mode");
|
|
670
|
-
if (![
|
|
689
|
+
if (![S.TextOnly, S.Playground].includes(t.chatMode))
|
|
671
690
|
if (t.streamingManager) {
|
|
672
691
|
if (!t.chat)
|
|
673
692
|
throw new Error("Chat is not initialized");
|
|
674
693
|
} else
|
|
675
694
|
throw new Error("Streaming manager is not initialized");
|
|
676
|
-
t.messages.push({
|
|
677
|
-
id:
|
|
695
|
+
if (t.messages.push({
|
|
696
|
+
id: U(),
|
|
678
697
|
role: "user",
|
|
679
698
|
content: d,
|
|
680
|
-
created_at: new Date(
|
|
681
|
-
}), (
|
|
682
|
-
|
|
683
|
-
|
|
699
|
+
created_at: new Date(D).toISOString()
|
|
700
|
+
}), (m = (c = s.callbacks).onNewMessage) == null || m.call(c, t.messages), !t.chat) {
|
|
701
|
+
const N = {};
|
|
702
|
+
t.chatMode === S.Playground && (N.headers = {
|
|
703
|
+
[X]: "true"
|
|
704
|
+
}), t.chat = await o.newChat(l.id, N);
|
|
705
|
+
}
|
|
706
|
+
const P = {
|
|
707
|
+
id: g,
|
|
684
708
|
role: "assistant",
|
|
685
709
|
content: "",
|
|
686
710
|
created_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
687
711
|
matches: []
|
|
688
712
|
};
|
|
689
|
-
t.messages.push(
|
|
690
|
-
const
|
|
713
|
+
t.messages.push(P);
|
|
714
|
+
const j = t.messages.slice(0, -1);
|
|
691
715
|
let x;
|
|
716
|
+
const V = {};
|
|
717
|
+
t.chatMode === S.Playground && (V.headers = {
|
|
718
|
+
[X]: "true"
|
|
719
|
+
});
|
|
692
720
|
try {
|
|
693
|
-
x = await o.chat(
|
|
721
|
+
x = await o.chat(l.id, t.chat.id, {
|
|
694
722
|
sessionId: (h = t.streamingManager) == null ? void 0 : h.sessionId,
|
|
695
|
-
streamId: (
|
|
696
|
-
messages:
|
|
723
|
+
streamId: (y = t.streamingManager) == null ? void 0 : y.streamId,
|
|
724
|
+
messages: j,
|
|
697
725
|
chatMode: t.chatMode
|
|
698
|
-
});
|
|
699
|
-
} catch (
|
|
700
|
-
if ((
|
|
701
|
-
console.log("Invalid stream, try reconnect with new stream id"), await
|
|
726
|
+
}, V);
|
|
727
|
+
} catch (N) {
|
|
728
|
+
if ((A = N == null ? void 0 : N.message) != null && A.includes("missing or invalid session_id"))
|
|
729
|
+
console.log("Invalid stream, try reconnect with new stream id"), await L(), x = await o.chat(l.id, t.chat.id, {
|
|
702
730
|
sessionId: (R = t.streamingManager) == null ? void 0 : R.sessionId,
|
|
703
|
-
streamId: (
|
|
704
|
-
messages:
|
|
731
|
+
streamId: (C = t.streamingManager) == null ? void 0 : C.streamId,
|
|
732
|
+
messages: j,
|
|
705
733
|
chatMode: t.chatMode
|
|
706
|
-
});
|
|
734
|
+
}, V);
|
|
707
735
|
else
|
|
708
|
-
throw
|
|
736
|
+
throw N;
|
|
709
737
|
}
|
|
710
|
-
return
|
|
738
|
+
return u.track("agent-message-send", {
|
|
711
739
|
event: "success",
|
|
712
740
|
messages: t.messages.length + 1
|
|
713
|
-
}),
|
|
714
|
-
latency: Date.now() -
|
|
741
|
+
}), P.context = x.context, x.result && (P.content = x.result, P.matches = x.matches, u.track("agent-message-received", {
|
|
742
|
+
latency: Date.now() - D,
|
|
715
743
|
messages: t.messages.length
|
|
716
|
-
}), (
|
|
717
|
-
} catch (
|
|
718
|
-
throw t.messages[t.messages.length - 1].id ===
|
|
744
|
+
}), (J = (w = s.callbacks).onNewMessage) == null || J.call(w, t.messages)), x;
|
|
745
|
+
} catch (P) {
|
|
746
|
+
throw t.messages[t.messages.length - 1].id === g && t.messages.pop(), u.track("agent-message-send", {
|
|
719
747
|
event: "error",
|
|
720
748
|
messages: t.messages.length
|
|
721
|
-
}),
|
|
749
|
+
}), P;
|
|
722
750
|
}
|
|
723
751
|
},
|
|
724
|
-
rate(d,
|
|
725
|
-
var
|
|
726
|
-
const
|
|
752
|
+
rate(d, g, c) {
|
|
753
|
+
var y, A, R, C;
|
|
754
|
+
const m = t.messages.find((w) => w.id === d);
|
|
727
755
|
if (t.chat) {
|
|
728
|
-
if (!
|
|
756
|
+
if (!m)
|
|
729
757
|
throw new Error("Message not found");
|
|
730
758
|
} else
|
|
731
759
|
throw new Error("Chat is not initialized");
|
|
732
|
-
const h = ((
|
|
733
|
-
return
|
|
734
|
-
event:
|
|
735
|
-
thumb:
|
|
736
|
-
knowledge_id: ((
|
|
760
|
+
const h = ((y = m.matches) == null ? void 0 : y.map((w) => [w.document_id, w.id])) ?? [];
|
|
761
|
+
return u.track("agent-rate", {
|
|
762
|
+
event: c ? "update" : "create",
|
|
763
|
+
thumb: g === 1 ? "up" : "down",
|
|
764
|
+
knowledge_id: ((A = l.knowledge) == null ? void 0 : A.id) ?? "",
|
|
737
765
|
matches: h,
|
|
738
|
-
score:
|
|
739
|
-
}),
|
|
740
|
-
knowledge_id: ((R =
|
|
766
|
+
score: g
|
|
767
|
+
}), c ? o.updateRating(l.id, t.chat.id, c, {
|
|
768
|
+
knowledge_id: ((R = l.knowledge) == null ? void 0 : R.id) ?? "",
|
|
741
769
|
message_id: d,
|
|
742
770
|
matches: h,
|
|
743
|
-
score:
|
|
744
|
-
}) : o.createRating(
|
|
745
|
-
knowledge_id: ((
|
|
771
|
+
score: g
|
|
772
|
+
}) : o.createRating(l.id, t.chat.id, {
|
|
773
|
+
knowledge_id: ((C = l.knowledge) == null ? void 0 : C.id) ?? "",
|
|
746
774
|
message_id: d,
|
|
747
775
|
matches: h,
|
|
748
|
-
score:
|
|
776
|
+
score: g
|
|
749
777
|
});
|
|
750
778
|
},
|
|
751
|
-
getChatmode() {
|
|
752
|
-
if (!t.chat)
|
|
753
|
-
throw new Error("Chat is not initialized");
|
|
754
|
-
return o.getChatMode(c.id, t.chat.id);
|
|
755
|
-
},
|
|
756
779
|
deleteRate(d) {
|
|
757
|
-
var
|
|
780
|
+
var g;
|
|
758
781
|
if (!t.chat)
|
|
759
782
|
throw new Error("Chat is not initialized");
|
|
760
|
-
return
|
|
783
|
+
return u.track("agent-rate-delete", {
|
|
761
784
|
type: "text",
|
|
762
|
-
chat_id: (
|
|
785
|
+
chat_id: (g = t.chat) == null ? void 0 : g.id,
|
|
763
786
|
id: d
|
|
764
|
-
}), o.deleteRating(
|
|
787
|
+
}), o.deleteRating(l.id, t.chat.id, d);
|
|
765
788
|
},
|
|
766
789
|
speak(d) {
|
|
767
790
|
if (!t.streamingManager)
|
|
768
791
|
throw new Error("Streaming manager is not initialized");
|
|
769
|
-
function
|
|
770
|
-
if (
|
|
792
|
+
function g() {
|
|
793
|
+
if (l.presenter) {
|
|
771
794
|
if (d.type === "text")
|
|
772
795
|
return {
|
|
773
796
|
type: "text",
|
|
774
|
-
provider: d.provider ? d.provider :
|
|
797
|
+
provider: d.provider ? d.provider : l.presenter.voice,
|
|
775
798
|
input: d.input,
|
|
776
799
|
ssml: d.ssml || !1
|
|
777
800
|
};
|
|
@@ -784,28 +807,28 @@ async function Ie(e, s) {
|
|
|
784
807
|
throw new Error("Presenter is not initialized");
|
|
785
808
|
throw new Error("Invalid payload");
|
|
786
809
|
}
|
|
787
|
-
const
|
|
788
|
-
return
|
|
789
|
-
script:
|
|
810
|
+
const c = g();
|
|
811
|
+
return u.track("agent-speak", c), t.streamingManager.speak({
|
|
812
|
+
script: c
|
|
790
813
|
});
|
|
791
814
|
}
|
|
792
815
|
};
|
|
793
816
|
}
|
|
794
817
|
export {
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
818
|
+
S as ChatMode,
|
|
819
|
+
K as ChatProgress,
|
|
820
|
+
I as ConnectionState,
|
|
821
|
+
se as DocumentType,
|
|
822
|
+
ie as KnowledgeType,
|
|
823
|
+
ne as PlanGroup,
|
|
824
|
+
oe as Providers,
|
|
825
|
+
re as RateState,
|
|
826
|
+
E as StreamEvents,
|
|
827
|
+
O as StreamingState,
|
|
828
|
+
ae as Subject,
|
|
829
|
+
te as UserPlan,
|
|
830
|
+
_ as VideoType,
|
|
831
|
+
ce as VoiceAccess,
|
|
832
|
+
Re as createAgentManager,
|
|
833
|
+
Ae as getAgent
|
|
811
834
|
};
|
package/dist/index.umd.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(function(p,b){typeof exports=="object"&&typeof module<"u"?b(exports):typeof define=="function"&&define.amd?define(["exports"],b):(p=typeof globalThis<"u"?globalThis:p||self,b(p.index={}))})(this,function(p){"use strict";var b=(e=>(e.TRIAL="trial",e.BASIC="basic",e.ENTERPRISE="enterprise",e.LITE="lite",e.ADVANCED="advanced",e))(b||{}),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||{}),q=(e=>(e.Unrated="Unrated",e.Positive="Positive",e.Negative="Negative",e))(q||{}),$=(e=>(e.Functional="Functional",e.TextOnly="TextOnly",e.Maintenance="Maintenance",e.Playground="Playground",e))($||{}),x=(e=>(e.Embed="embed",e.Query="query",e.Partial="partial",e.Answer="answer",e.Complete="done",e))(x||{}),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||{}),Y=(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))(Y||{}),C=(e=>(e.Clip="clip",e.Talk="talk",e))(C||{}),P=(e=>(e.Start="START",e.Stop="STOP",e))(P||{}),A=(e=>(e.ChatAnswer="chat/answer",e.ChatPartial="chat/partial",e.StreamDone="stream/done",e.StreamStarted="stream/started",e.StreamFailed="stream/error",e.StreamReady="stream/ready",e.StreamCreated="stream/created",e.StreamVideoCreated="stream-video/started",e.StreamVideoDone="stream-video/done",e.StreamVideoError="stream-video/error",e.StreamVideoRejected="stream-video/rejected",e))(A||{}),k=(e=>(e[e.New=0]="New",e[e.Fail=1]="Fail",e[e.Connected=2]="Connected",e[e.Connecting=3]="Connecting",e[e.Terminating=4]="Terminating",e))(k||{}),Z=(e=>(e.Amazon="amazon",e.Microsoft="microsoft",e.Afflorithmics="afflorithmics",e.Elevenlabs="elevenlabs",e))(Z||{}),G=(e=>(e.Public="public",e.Premium="premium",e.Private="private",e))(G||{});const z="https://api.d-id.com",ce="wss://notifications.d-id.com",de="79f81a83a67430be2bc0fd61042b8faa",F=()=>Math.random().toString(16).slice(2);function ee(){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 le=F();function te(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}.${ee()}_${le}`;throw new Error(`Unknown auth type: ${e}`)}function U(e,s=z,t){const r=async(a,n)=>{const i=await fetch(s+(a!=null&&a.startsWith("/")?a:`/${a}`),{...n,headers:{...n==null?void 0:n.headers,Authorization:te(e),"Content-Type":"application/json"}});if(!i.ok){let o=await i.text().catch(()=>"Failed to fetch");throw t&&t(new Error(o),{url:a,options:n,headers:i.headers}),new Error(o)}return i.json()};return{get(a,n){return r(a,{...n,method:"GET"})},post(a,n,i){return r(a,{...i,body:JSON.stringify(n),method:"POST"})},delete(a,n,i){return r(a,{...i,body:JSON.stringify(n),method:"DELETE"})},patch(a,n,i){return r(a,{...i,body:JSON.stringify(n),method:"PATCH"})}}}function ne(e,s=z,t){const r=U(e,`${s}/agents`,t);return{create(a,n){return r.post("/",a,n)},getAgents(a,n){return r.get(`/${a?`?tag=${a}`:""}`,n).then(i=>i??[])},getById(a,n){return r.get(`/${a}`,n)},delete(a,n){return r.delete(`/${a}`,void 0,n)},update(a,n,i){return r.patch(`/${a}`,n,i)},newChat(a,n){return r.post(`/${a}/chat`,void 0,n)},chat(a,n,i,o){return r.post(`/${a}/chat/${n}`,i,o)},getChatMode(a,n,i){return r.get(`/${a}/chat/${n}/mode`,i)},createRating(a,n,i,o){return r.post(`/${a}/chat/${n}/ratings`,i,o)},updateRating(a,n,i,o,c){return r.patch(`/${a}/chat/${n}/ratings/${i}`,o,c)},deleteRating(a,n,i,o){return r.delete(`/${a}/chat/${n}/ratings/${i}`,o)}}}const ge=e=>new Promise(s=>setTimeout(s,e));function ue(e){return new Promise((s,t)=>{const{callbacks:r,host:a,auth:n}=e,{onMessage:i=null,onOpen:o=null,onClose:c=null,onError:g=null}=r||{},w=new WebSocket(`${a}?authorization=${te(n)}`);w.onmessage=i,w.onclose=c,w.onerror=y=>{console.error(y),g==null||g("Websocket failed to connect",y),t(y)},w.onopen=y=>{o==null||o(y),s(w)}})}async function me(e){const{retries:s=1}=e;let t=null;for(let r=0;(t==null?void 0:t.readyState)!==WebSocket.OPEN;r++)try{t=await ue(e)}catch(a){if(r===s)throw a;await ge(r*500)}return t}async function re(e,s,t){const r=t!=null&&t.onMessage?[t.onMessage]:[],a=await me({auth:e,host:s,callbacks:{onError:t==null?void 0:t.onError,onMessage:n=>{const i=JSON.parse(n.data);r.forEach(o=>o(i.event,i))}}});return{socket:a,disconnect:()=>a.close(),subscribeToEvents:n=>r.push(n)}}function he(e,s,t,r){const a=U(e,`${s}/agents/${t}`,r);return{createStream(n){return a.post("/streams",{driver_id:n.driver_id,presenter_id:n.presenter_id,compatibility_mode:n.compatibility_mode,stream_warmup:n.stream_warmup,type:C.Clip})},startConnection(n,i,o){return a.post(`/streams/${n}/sdp`,{session_id:o,answer:i,type:C.Clip})},addIceCandidate(n,i,o){return a.post(`/streams/${n}/ice`,{session_id:o,...i,type:C.Clip})},sendStreamRequest(n,i,o){return a.post(`/streams/${n}`,{session_id:i,...o,type:C.Clip})},close(n,i){return a.delete(`/streams/${n}`,{session_id:i,type:C.Clip})}}}function we(e,s,t,r){const a=U(e,`${s}/agents/${t}`,r);return{createStream(n,i){return a.post("/streams",{source_url:n.source_url,driver_url:n.driver_url,face:n.face,config:n.config,compatibility_mode:n.compatibility_mode,stream_warmup:n.stream_warmup,output_resolution:n.output_resolution,type:C.Talk},i)},startConnection(n,i,o,c){return a.post(`/streams/${n}/sdp`,{session_id:o,answer:i,type:C.Talk},c)},addIceCandidate(n,i,o,c){return a.post(`/streams/${n}/ice`,{session_id:o,...i,type:C.Talk},c)},sendStreamRequest(n,i,o,c){return a.post(`/streams/${n}`,{session_id:i,...o,type:C.Talk},c)},close(n,i,o){return a.delete(`/streams/${n}`,{session_id:i,type:C.Talk},o)}}}let ae=!1;const N=(e,s)=>ae&&console.log(e,s),fe=(window.RTCPeerConnection||window.webkitRTCPeerConnection||window.mozRTCPeerConnection).bind(window);function ie(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 pe(){let e=0;return s=>{for(const t of s.values())if(t&&t.type==="inbound-rtp"&&t.kind==="video"){const r=t.bytesReceived,a=r-e>0;return e=r,a}return!1}}function ve(e,s){const r=Math.max(Math.ceil(10),1);let a=0,n=!1;const i=pe();return setInterval(async()=>{const o=await e.getStats();i(o)?(a=0,n||(s==null||s(P.Start),n=!0)):n&&(a++,a>=r&&(s==null||s(P.Stop),n=!1))},100)}async function ye(e,s,{debug:t=!1,callbacks:r,auth:a,analytics:n,baseURL:i=z}){ae=t;let o;const{startConnection:c,sendStreamRequest:g,close:w,createStream:y,addIceCandidate:_}=s.videoType===C.Clip?he(a,i,e,r.onError):we(a,i,e,r.onError),{id:R,offer:H,ice_servers:K,session_id:T}=await y(s),M=new fe({iceServers:K}),d=M.createDataChannel("JanusDataChannel");if(!T)throw new Error("Could not create session_id");const u=ve(M,r.onVideoStateChange);M.onicecandidate=l=>{N("peerConnection.onicecandidate",l),l.candidate&&l.candidate.sdpMid&&l.candidate.sdpMLineIndex!==null?_(R,{candidate:l.candidate.candidate,sdpMid:l.candidate.sdpMid,sdpMLineIndex:l.candidate.sdpMLineIndex},T):_(R,{candidate:null},T)},M.oniceconnectionstatechange=()=>{var h;N("peerConnection.oniceconnectionstatechange => "+M.iceConnectionState);const l=ie(M.iceConnectionState);l===k.Connected?o=setTimeout(()=>{var f;(f=r.onConnectionStateChange)==null||f.call(r,k.Connected)},5e3):(clearTimeout(o),(h=r.onConnectionStateChange)==null||h.call(r,l))},M.ontrack=l=>{var h;N("peerConnection.ontrack",l),(h=r.onSrcObjectReady)==null||h.call(r,l.streams[0])},d.onmessage=l=>{var h;if(d.readyState==="open"){const[f,S]=l.data.split(":");f===A.StreamReady&&(clearTimeout(o),(h=r.onConnectionStateChange)==null||h.call(r,k.Connected))}},await M.setRemoteDescription(H),N("set remote description OK");const m=await M.createAnswer();return N("create answer OK"),await M.setLocalDescription(m),N("set local description OK"),await c(R,m,T),N("start connection OK"),{speak(l){return g(R,T,l)},async disconnect(){var l,h,f;if(R){if(M){if(ie(M.iceConnectionState)===k.New){(l=r.onVideoStateChange)==null||l.call(r,P.Stop),clearInterval(u);return}M.close(),M.oniceconnectionstatechange=null,M.onnegotiationneeded=null,M.onicecandidate=null,M.ontrack=null}try{await w(R,T).catch(S=>{})}catch(S){N("Error on close stream connection",S)}(h=r.onConnectionStateChange)==null||h.call(r,k.New),(f=r.onVideoStateChange)==null||f.call(r,P.Stop),clearInterval(u)}},sessionId:T,streamId:R}}let B={};function Me(e){const s=window!=null&&window.hasOwnProperty("DID_AGENTS_API")?"agents-ui":"agents-sdk",t={token:e.token||"testKey",distinct_id:e.distinctId||ee(),isEnabled:e.isEnabled??!0,agentId:e.agent.id,agentType:e.agent.presenter.type,owner_id:e.agent.owner_id??""};return{...t,getRandom:()=>Math.random().toString(16).slice(2),track(r,a){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:r,properties:{...a,...t,source:s,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(i=>i.json()).catch(i=>console.error(i))},linkTrack(r,a,n,i){B[r]||(B[r]={events:{},resolvedDependencies:[]}),i.includes(n)||i.push(n);const o=B[r];if(o.events[n]={props:a},o.resolvedDependencies.push(n),i.every(g=>o.resolvedDependencies.includes(g))){const g=i.reduce((w,y)=>o.events[y]?{...w,...o.events[y].props}:w,{});this.track(r,g),o.resolvedDependencies=o.resolvedDependencies.filter(w=>!i.includes(w)),i.forEach(w=>{delete o.events[w]})}}}}function Ce(e){var r,a,n,i,o;const s=()=>/Mobi|Android/i.test(navigator.userAgent)?"Mobile":"Desktop";return{$os:`${(()=>{const c=navigator.platform;return c.toLowerCase().includes("win")?"Windows":c.toLowerCase().includes("mac")?"Mac OS X":c.toLowerCase().includes("linux")?"Linux":"Unknown"})()}`,isMobile:`${s()=="Mobile"}`,browser:navigator.userAgent,origin:window.location.origin,agentType:(r=e.presenter)==null?void 0:r.type,agentVoice:{voiceId:(n=(a=e.presenter)==null?void 0:a.voice)==null?void 0:n.voice_id,provider:(o=(i=e.presenter)==null?void 0:i.voice)==null?void 0:o.type}}}const Se=1080;let D=0;function _e(e,s){if(e.presenter){if(e.presenter.type===C.Clip)return{videoType:C.Clip,driver_id:e.presenter.driver_id,presenter_id:e.presenter.presenter_id,stream_warmup:!0}}else throw new Error("Presenter is not initialized");const t=s||(e.presenter.stitch?Se:void 0);return{videoType:C.Talk,source_url:e.presenter.source_url,stream_warmup:!0,...t&&{output_resolution:t}}}function W(e,s,t,r,a){return D=0,new Promise(async(n,i)=>{let o=a;const c=await ye(e.id,_e(e,s.outputResolution),{...s,analytics:r,callbacks:{...s.callbacks,onConnectionStateChange:async g=>{var w,y;if(g===k.Connected)try{try{o||(o=await t.newChat(e.id),r.track("agent-chat",{event:"created",chat_id:o.id,agent_id:e.id})),c&&n({chat:o,streamingManager:c})}catch(_){console.error(_),(_==null?void 0:_.kind)==="InsufficientCreditsError"&&(s.mode,$.TextOnly),i("Cannot create new chat")}}catch(_){console.error(_),i("Cannot create new chat")}else g===k.Fail&&i(new Error("Cannot create connection"));(y=(w=s.callbacks).onConnectionStateChange)==null||y.call(w,g)},onVideoStateChange(g){var w,y;if((y=(w=s.callbacks).onVideoStateChange)==null||y.call(w,g),D>0&&g===P.Start){const _="start";r.linkTrack("agent-video",{event:_,latency:Date.now()-D},_,[A.StreamVideoCreated])}}}}).catch(i)})}function Ie(e,s,t){return ne(s,t||z).getById(e)}function j(e){let s="";if(e.greetings&&e.greetings.length>0){const t=Math.floor(Math.random()*e.greetings.length);s=e.greetings[t]}else s=`Hi! I'm ${e.preview_name||"My Agent"}. How can I help you?`;return[{content:s,id:F(),role:"assistant",created_at:new Date().toISOString()}]}async function ke(e,s){var K,T,M;const t={messages:[],chatMode:s.mode||$.Functional};let r=-1;const a=s.wsURL||ce,n=s.baseURL||z,i=s.mixpanelKey||de,o=ne(s.auth,n,s.callbacks.onError),c=await o.getById(e);t.messages=j(c),(T=(K=s.callbacks).onNewMessage)==null||T.call(K,t.messages);const g=Me({token:i,agent:c,...s});g.track("agent-sdk",{event:"loaded",...Ce(c)});const w={onMessage:(d,u)=>{var m,l,h,f,S,E;if("content"in u){const{content:I}=u,v=t.messages[t.messages.length-1];(v==null?void 0:v.role)==="assistant"&&(r<t.messages.length&&(v.content=d===x.Partial?v.content+I:I),d===x.Answer&&(r=t.messages.length)),d===x.Answer&&g.track("agent-message-received",{messages:t.messages.length}),(l=(m=s.callbacks).onNewMessage)==null||l.call(m,t.messages)}else{if(d=d,d===A.StreamVideoCreated){const{event:I,...v}=u;v.llm={...v.llm,template:(h=c.llm)==null?void 0:h.template},g.linkTrack("agent-video",{...v},A.StreamVideoCreated,["start"])}else if([A.StreamVideoDone,A.StreamVideoError,A.StreamVideoRejected].includes(d)){const I=d.split("/")[1],v={...u,event:I};v.llm={...v.llm,template:(f=c.llm)==null?void 0:f.template},g.track("agent-video",{...v,event:I})}[A.StreamFailed,A.StreamVideoError,A.StreamVideoRejected].includes(d)&&((E=(S=s.callbacks).onError)==null||E.call(S,new Error(`Stream failed with event ${d}`),{data:u}))}}};async function y(){var h,f,S,E,I;D=0;const d=await re(s.auth,a,w),{streamingManager:u,chat:m}=await W(c,s,o,g,t.chat);r=-1,t.messages.length===0&&(t.messages=j(c),(f=(h=s.callbacks).onNewMessage)==null||f.call(h,t.messages)),m!=null&&m.id&&m.id!==((S=t.chat)==null?void 0:S.id)&&((I=(E=s.callbacks).onNewChat)==null||I.call(E,m==null?void 0:m.id)),t.streamingManager=u,t.socketManager=d,t.chat=m;const l=t.chat.chatMode||$.Functional;R(l),g.track("agent-chat",{event:"connect",chatId:m.id,agentId:c.id})}async function _(){var d,u,m,l,h;(d=t.socketManager)==null||d.disconnect(),await((u=t.streamingManager)==null?void 0:u.disconnect()),delete t.streamingManager,delete t.socketManager,t.messages=j(c),(l=(m=s.callbacks).onNewMessage)==null||l.call(m,t.messages),g.track("agent-chat",{event:"disconnect",chatId:(h=t.chat)==null?void 0:h.id,agentId:c.id})}async function R(d){var u,m;d!==t.chatMode&&(g.track("agent-mode-change",{mode:d}),t.chatMode=d,t.chatMode!==$.Functional&&await _(),(m=(u=s.callbacks).onModeChange)==null||m.call(u,d))}async function H(){if(!t.chat)return y();const{streamingManager:d,chat:u}=await W(c,s,o,g,t.chat);t.streamingManager=d,R(t.chat.chatMode||$.Functional),g.track("agent-chat",{event:"reconnect",chatId:u.id,agentId:c.id})}return{agent:c,starterMessages:((M=c.knowledge)==null?void 0:M.starter_message)||[],connect:y,disconnect:_,changeMode:R,async reconnect(){var h,f;if(!t.chat)return y();(h=t.socketManager)==null||h.disconnect(),await((f=t.streamingManager)==null?void 0:f.disconnect());const d=await re(s.auth,a,w),{streamingManager:u,chat:m}=await W(c,s,o,g,t.chat);t.streamingManager=u,t.socketManager=d;const l=t.chat.chatMode||$.Functional;R(l),g.track("agent-chat",{event:"reconnect",chatId:m.id,agentId:c.id})},async chat(d){var m,l,h,f,S,E,I,v,se;const u=F();try{if(D=Date.now(),d.length>=800)throw new Error("Message cannot be more than 800 characters");if(d.length===0)throw new Error("Message cannot be empty");if(t.chatMode===$.Maintenance)throw new Error("Chat is in maintenance mode");if(![$.TextOnly,$.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:F(),role:"user",content:d,created_at:new Date(D).toISOString()}),(l=(m=s.callbacks).onNewMessage)==null||l.call(m,t.messages),t.chat||(t.chat=await o.newChat(c.id));const L={id:u,role:"assistant",content:"",created_at:new Date().toISOString(),matches:[]};t.messages.push(L);const oe=t.messages.slice(0,-1);let O;try{O=await o.chat(c.id,t.chat.id,{sessionId:(h=t.streamingManager)==null?void 0:h.sessionId,streamId:(f=t.streamingManager)==null?void 0:f.streamId,messages:oe,chatMode:t.chatMode})}catch(V){if((S=V==null?void 0:V.message)!=null&&S.includes("missing or invalid session_id"))console.log("Invalid stream, try reconnect with new stream id"),await H(),O=await o.chat(c.id,t.chat.id,{sessionId:(E=t.streamingManager)==null?void 0:E.sessionId,streamId:(I=t.streamingManager)==null?void 0:I.streamId,messages:oe,chatMode:t.chatMode});else throw V}return g.track("agent-message-send",{event:"success",messages:t.messages.length+1}),L.context=O.context,O.result&&(L.content=O.result,L.matches=O.matches,g.track("agent-message-received",{latency:Date.now()-D,messages:t.messages.length}),(se=(v=s.callbacks).onNewMessage)==null||se.call(v,t.messages)),O}catch(L){throw t.messages[t.messages.length-1].id===u&&t.messages.pop(),g.track("agent-message-send",{event:"error",messages:t.messages.length}),L}},rate(d,u,m){var f,S,E,I;const l=t.messages.find(v=>v.id===d);if(t.chat){if(!l)throw new Error("Message not found")}else throw new Error("Chat is not initialized");const h=((f=l.matches)==null?void 0:f.map(v=>[v.document_id,v.id]))??[];return g.track("agent-rate",{event:m?"update":"create",thumb:u===1?"up":"down",knowledge_id:((S=c.knowledge)==null?void 0:S.id)??"",matches:h,score:u}),m?o.updateRating(c.id,t.chat.id,m,{knowledge_id:((E=c.knowledge)==null?void 0:E.id)??"",message_id:d,matches:h,score:u}):o.createRating(c.id,t.chat.id,{knowledge_id:((I=c.knowledge)==null?void 0:I.id)??"",message_id:d,matches:h,score:u})},getChatmode(){if(!t.chat)throw new Error("Chat is not initialized");return o.getChatMode(c.id,t.chat.id)},deleteRate(d){var u;if(!t.chat)throw new Error("Chat is not initialized");return g.track("agent-rate-delete",{type:"text",chat_id:(u=t.chat)==null?void 0:u.id,id:d}),o.deleteRating(c.id,t.chat.id,d)},speak(d){if(!t.streamingManager)throw new Error("Streaming manager is not initialized");function u(){if(c.presenter){if(d.type==="text")return{type:"text",provider:d.provider?d.provider:c.presenter.voice,input:d.input,ssml:d.ssml||!1};if(d.type==="audio")return{type:"audio",audio_url:d.audio_url}}else throw new Error("Presenter is not initialized");throw new Error("Invalid payload")}const m=u();return g.track("agent-speak",m),t.streamingManager.speak({script:m})}}}p.ChatMode=$,p.ChatProgress=x,p.ConnectionState=k,p.DocumentType=Y,p.KnowledgeType=X,p.PlanGroup=J,p.Providers=Z,p.RateState=q,p.StreamEvents=A,p.StreamingState=P,p.Subject=Q,p.UserPlan=b,p.VideoType=C,p.VoiceAccess=G,p.createAgentManager=ke,p.getAgent=Ie,Object.defineProperty(p,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
(function(p,b){typeof exports=="object"&&typeof module<"u"?b(exports):typeof define=="function"&&define.amd?define(["exports"],b):(p=typeof globalThis<"u"?globalThis:p||self,b(p.index={}))})(this,function(p){"use strict";var b=(e=>(e.TRIAL="trial",e.BASIC="basic",e.ENTERPRISE="enterprise",e.LITE="lite",e.ADVANCED="advanced",e))(b||{}),q=(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))(q||{}),X=(e=>(e.Unrated="Unrated",e.Positive="Positive",e.Negative="Negative",e))(X||{}),I=(e=>(e.Functional="Functional",e.TextOnly="TextOnly",e.Maintenance="Maintenance",e.Playground="Playground",e))(I||{}),F=(e=>(e.Embed="embed",e.Query="query",e.Partial="partial",e.Answer="answer",e.Complete="done",e))(F||{}),Q=(e=>(e.KnowledgeProcessing="knowledge/processing",e.KnowledgeIndexing="knowledge/indexing",e.KnowledgeFailed="knowledge/error",e.KnowledgeDone="knowledge/done",e))(Q||{}),Y=(e=>(e.Knowledge="knowledge",e.Document="document",e.Record="record",e))(Y||{}),Z=(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))(Z||{}),S=(e=>(e.Clip="clip",e.Talk="talk",e))(S||{}),N=(e=>(e.Start="START",e.Stop="STOP",e))(N||{}),A=(e=>(e.ChatAnswer="chat/answer",e.ChatPartial="chat/partial",e.StreamDone="stream/done",e.StreamStarted="stream/started",e.StreamFailed="stream/error",e.StreamReady="stream/ready",e.StreamCreated="stream/created",e.StreamVideoCreated="stream-video/started",e.StreamVideoDone="stream-video/done",e.StreamVideoError="stream-video/error",e.StreamVideoRejected="stream-video/rejected",e))(A||{}),k=(e=>(e[e.New=0]="New",e[e.Fail=1]="Fail",e[e.Connected=2]="Connected",e[e.Connecting=3]="Connecting",e[e.Terminating=4]="Terminating",e))(k||{}),G=(e=>(e.Amazon="amazon",e.Microsoft="microsoft",e.Afflorithmics="afflorithmics",e.Elevenlabs="elevenlabs",e))(G||{}),ee=(e=>(e.Public="public",e.Premium="premium",e.Private="private",e))(ee||{});const z="https://api.d-id.com",le="wss://notifications.d-id.com",ge="79f81a83a67430be2bc0fd61042b8faa",B=()=>Math.random().toString(16).slice(2);function te(){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 ue=B();function ne(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}.${te()}_${ue}`;throw new Error(`Unknown auth type: ${e}`)}function j(e,s=z,t){const r=async(a,n)=>{const i=await fetch(s+(a!=null&&a.startsWith("/")?a:`/${a}`),{...n,headers:{...n==null?void 0:n.headers,Authorization:ne(e),"Content-Type":"application/json"}});if(!i.ok){let o=await i.text().catch(()=>"Failed to fetch");throw t&&t(new Error(o),{url:a,options:n,headers:i.headers}),new Error(o)}return i.json()};return{get(a,n){return r(a,{...n,method:"GET"})},post(a,n,i){return r(a,{...i,body:JSON.stringify(n),method:"POST"})},delete(a,n,i){return r(a,{...i,body:JSON.stringify(n),method:"DELETE"})},patch(a,n,i){return r(a,{...i,body:JSON.stringify(n),method:"PATCH"})}}}function re(e,s=z,t){const r=j(e,`${s}/agents`,t);return{create(a,n){return r.post("/",a,n)},getAgents(a,n){return r.get(`/${a?`?tag=${a}`:""}`,n).then(i=>i??[])},getById(a,n){return r.get(`/${a}`,n)},delete(a,n){return r.delete(`/${a}`,void 0,n)},update(a,n,i){return r.patch(`/${a}`,n,i)},newChat(a,n){return r.post(`/${a}/chat`,void 0,n)},chat(a,n,i,o){return r.post(`/${a}/chat/${n}`,i,o)},createRating(a,n,i,o){return r.post(`/${a}/chat/${n}/ratings`,i,o)},updateRating(a,n,i,o,l){return r.patch(`/${a}/chat/${n}/ratings/${i}`,o,l)},deleteRating(a,n,i,o){return r.delete(`/${a}/chat/${n}/ratings/${i}`,o)}}}const me=e=>new Promise(s=>setTimeout(s,e));function he(e){return new Promise((s,t)=>{const{callbacks:r,host:a,auth:n}=e,{onMessage:i=null,onOpen:o=null,onClose:l=null,onError:u=null}=r||{},f=new WebSocket(`${a}?authorization=${ne(n)}`);f.onmessage=i,f.onclose=l,f.onerror=y=>{console.error(y),u==null||u("Websocket failed to connect",y),t(y)},f.onopen=y=>{o==null||o(y),s(f)}})}async function we(e){const{retries:s=1}=e;let t=null;for(let r=0;(t==null?void 0:t.readyState)!==WebSocket.OPEN;r++)try{t=await he(e)}catch(a){if(r===s)throw a;await me(r*500)}return t}async function ae(e,s,t){const r=t!=null&&t.onMessage?[t.onMessage]:[],a=await we({auth:e,host:s,callbacks:{onError:t==null?void 0:t.onError,onMessage:n=>{const i=JSON.parse(n.data);r.forEach(o=>o(i.event,i))}}});return{socket:a,disconnect:()=>a.close(),subscribeToEvents:n=>r.push(n)}}const ie="X-Playground-Chat";function fe(e,s,t,r){const a=j(e,`${s}/agents/${t}`,r);return{createStream(n){return a.post("/streams",{driver_id:n.driver_id,presenter_id:n.presenter_id,compatibility_mode:n.compatibility_mode,stream_warmup:n.stream_warmup,type:S.Clip})},startConnection(n,i,o){return a.post(`/streams/${n}/sdp`,{session_id:o,answer:i,type:S.Clip})},addIceCandidate(n,i,o){return a.post(`/streams/${n}/ice`,{session_id:o,...i,type:S.Clip})},sendStreamRequest(n,i,o){return a.post(`/streams/${n}`,{session_id:i,...o,type:S.Clip})},close(n,i){return a.delete(`/streams/${n}`,{session_id:i,type:S.Clip})}}}function pe(e,s,t,r){const a=j(e,`${s}/agents/${t}`,r);return{createStream(n,i){return a.post("/streams",{source_url:n.source_url,driver_url:n.driver_url,face:n.face,config:n.config,compatibility_mode:n.compatibility_mode,stream_warmup:n.stream_warmup,output_resolution:n.output_resolution,type:S.Talk},i)},startConnection(n,i,o,l){return a.post(`/streams/${n}/sdp`,{session_id:o,answer:i,type:S.Talk},l)},addIceCandidate(n,i,o,l){return a.post(`/streams/${n}/ice`,{session_id:o,...i,type:S.Talk},l)},sendStreamRequest(n,i,o,l){return a.post(`/streams/${n}`,{session_id:i,...o,type:S.Talk},l)},close(n,i,o){return a.delete(`/streams/${n}`,{session_id:i,type:S.Talk},o)}}}let se=!1;const P=(e,s)=>se&&console.log(e,s),ye=(window.RTCPeerConnection||window.webkitRTCPeerConnection||window.mozRTCPeerConnection).bind(window);function oe(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 ve(){let e=0;return s=>{for(const t of s.values())if(t&&t.type==="inbound-rtp"&&t.kind==="video"){const r=t.bytesReceived,a=r-e>0;return e=r,a}return!1}}function Me(e,s){const r=Math.max(Math.ceil(10),1);let a=0,n=!1;const i=ve();return setInterval(async()=>{const o=await e.getStats();i(o)?(a=0,n||(s==null||s(N.Start),n=!0)):n&&(a++,a>=r&&(s==null||s(N.Stop),n=!1))},100)}async function Ce(e,s,{debug:t=!1,callbacks:r,auth:a,analytics:n,baseURL:i=z}){se=t;let o;const{startConnection:l,sendStreamRequest:u,close:f,createStream:y,addIceCandidate:R}=s.videoType===S.Clip?fe(a,i,e,r.onError):pe(a,i,e,r.onError),{id:C,offer:K,ice_servers:U,session_id:T}=await y(s),v=new ye({iceServers:U}),V=v.createDataChannel("JanusDataChannel");if(!T)throw new Error("Could not create session_id");const d=Me(v,r.onVideoStateChange);v.onicecandidate=c=>{P("peerConnection.onicecandidate",c),c.candidate&&c.candidate.sdpMid&&c.candidate.sdpMLineIndex!==null?R(C,{candidate:c.candidate.candidate,sdpMid:c.candidate.sdpMid,sdpMLineIndex:c.candidate.sdpMLineIndex},T):R(C,{candidate:null},T)},v.oniceconnectionstatechange=()=>{var m;P("peerConnection.oniceconnectionstatechange => "+v.iceConnectionState);const c=oe(v.iceConnectionState);c===k.Connected?o=setTimeout(()=>{var h;(h=r.onConnectionStateChange)==null||h.call(r,k.Connected)},5e3):(clearTimeout(o),(m=r.onConnectionStateChange)==null||m.call(r,c))},v.ontrack=c=>{var m;P("peerConnection.ontrack",c),(m=r.onSrcObjectReady)==null||m.call(r,c.streams[0])},V.onmessage=c=>{var m;if(V.readyState==="open"){const[h,M]=c.data.split(":");h===A.StreamReady&&(clearTimeout(o),(m=r.onConnectionStateChange)==null||m.call(r,k.Connected))}},await v.setRemoteDescription(K),P("set remote description OK");const g=await v.createAnswer();return P("create answer OK"),await v.setLocalDescription(g),P("set local description OK"),await l(C,g,T),P("start connection OK"),{speak(c){return u(C,T,c)},async disconnect(){var c,m,h;if(C){if(v){if(oe(v.iceConnectionState)===k.New){(c=r.onVideoStateChange)==null||c.call(r,N.Stop),clearInterval(d);return}v.close(),v.oniceconnectionstatechange=null,v.onnegotiationneeded=null,v.onicecandidate=null,v.ontrack=null}try{await f(C,T).catch(M=>{})}catch(M){P("Error on close stream connection",M)}(m=r.onConnectionStateChange)==null||m.call(r,k.New),(h=r.onVideoStateChange)==null||h.call(r,N.Stop),clearInterval(d)}},sessionId:T,streamId:C}}let H={};function Se(e){const s=window!=null&&window.hasOwnProperty("DID_AGENTS_API")?"agents-ui":"agents-sdk",t={token:e.token||"testKey",distinct_id:e.distinctId||te(),isEnabled:e.isEnabled??!0,agentId:e.agent.id,agentType:e.agent.presenter.type,owner_id:e.agent.owner_id??""};return{...t,getRandom:()=>Math.random().toString(16).slice(2),track(r,a){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:r,properties:{...a,...t,source:s,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(i=>i.json()).catch(i=>console.error(i))},linkTrack(r,a,n,i){H[r]||(H[r]={events:{},resolvedDependencies:[]}),i.includes(n)||i.push(n);const o=H[r];if(o.events[n]={props:a},o.resolvedDependencies.push(n),i.every(u=>o.resolvedDependencies.includes(u))){const u=i.reduce((f,y)=>o.events[y]?{...f,...o.events[y].props}:f,{});this.track(r,u),o.resolvedDependencies=o.resolvedDependencies.filter(f=>!i.includes(f)),i.forEach(f=>{delete o.events[f]})}}}}function _e(e){var r,a,n,i,o;const s=()=>/Mobi|Android/i.test(navigator.userAgent)?"Mobile":"Desktop";return{$os:`${(()=>{const l=navigator.platform;return l.toLowerCase().includes("win")?"Windows":l.toLowerCase().includes("mac")?"Mac OS X":l.toLowerCase().includes("linux")?"Linux":"Unknown"})()}`,isMobile:`${s()=="Mobile"}`,browser:navigator.userAgent,origin:window.location.origin,agentType:(r=e.presenter)==null?void 0:r.type,agentVoice:{voiceId:(n=(a=e.presenter)==null?void 0:a.voice)==null?void 0:n.voice_id,provider:(o=(i=e.presenter)==null?void 0:i.voice)==null?void 0:o.type}}}const Ie=1080;let D=0;function ke(e,s){if(e.presenter){if(e.presenter.type===S.Clip)return{videoType:S.Clip,driver_id:e.presenter.driver_id,presenter_id:e.presenter.presenter_id,stream_warmup:!0}}else throw new Error("Presenter is not initialized");const t=s||(e.presenter.stitch?Ie:void 0);return{videoType:S.Talk,source_url:e.presenter.source_url,stream_warmup:!0,...t&&{output_resolution:t}}}function Ae(e,s,t,r,a){return D=0,new Promise(async(n,i)=>{let o=a;const l=await Ce(e.id,ke(e,s.outputResolution),{...s,analytics:r,callbacks:{...s.callbacks,onConnectionStateChange:async u=>{var f,y;if(u===k.Connected){if(!o)try{o=await t.newChat(e.id),r.track("agent-chat",{event:"created",chat_id:o.id,agent_id:e.id}),l&&n({chat:o,streamingManager:l})}catch(R){console.error(R);let C;try{C=JSON.parse(R.message)}catch(K){console.error("Error parsing the error message:",K)}(C==null?void 0:C.kind)==="InsufficientCreditsError"&&i("InsufficientCreditsError"),i("Cannot create new chat")}l&&o&&n({chat:o,streamingManager:l})}else u===k.Fail&&i(new Error("Cannot create connection"));(y=(f=s.callbacks).onConnectionStateChange)==null||y.call(f,u)},onVideoStateChange(u){var f,y;if((y=(f=s.callbacks).onVideoStateChange)==null||y.call(f,u),D>0&&u===N.Start){const R="start";r.linkTrack("agent-video",{event:R,latency:Date.now()-D},R,[A.StreamVideoCreated])}}}}).catch(i)})}function Re(e,s,t){return re(s,t||z).getById(e)}function W(e){let s="";if(e.greetings&&e.greetings.length>0){const t=Math.floor(Math.random()*e.greetings.length);s=e.greetings[t]}else s=`Hi! I'm ${e.preview_name||"My Agent"}. How can I help you?`;return[{content:s,id:B(),role:"assistant",created_at:new Date().toISOString()}]}async function Ee(e,s){var T,v,V;const t={messages:[],chatMode:s.mode||I.Functional};let r=-1;const a=s.wsURL||le,n=s.baseURL||z,i=s.mixpanelKey||ge,o=re(s.auth,n,s.callbacks.onError),l=await o.getById(e);t.messages=W(l),(v=(T=s.callbacks).onNewMessage)==null||v.call(T,t.messages);const u=Se({token:i,agent:l,...s});u.track("agent-sdk",{event:"loaded",..._e(l)});const f={onMessage:(d,g)=>{var c,m,h,M,E,$;if("content"in g){const{content:_}=g,w=t.messages[t.messages.length-1];(w==null?void 0:w.role)==="assistant"&&(r<t.messages.length&&(w.content=d===F.Partial?w.content+_:_),d===F.Answer&&(r=t.messages.length)),d===F.Answer&&u.track("agent-message-received",{messages:t.messages.length}),(m=(c=s.callbacks).onNewMessage)==null||m.call(c,t.messages)}else{if(d=d,d===A.StreamVideoCreated){const{event:_,...w}=g;w.llm={...w.llm,template:(h=l.llm)==null?void 0:h.template},u.linkTrack("agent-video",{...w},A.StreamVideoCreated,["start"])}else if([A.StreamVideoDone,A.StreamVideoError,A.StreamVideoRejected].includes(d)){const _=d.split("/")[1],w={...g,event:_};w.llm={...w.llm,template:(M=l.llm)==null?void 0:M.template},u.track("agent-video",{...w,event:_})}[A.StreamFailed,A.StreamVideoError,A.StreamVideoRejected].includes(d)&&(($=(E=s.callbacks).onError)==null||$.call(E,new Error(`Stream failed with event ${d}`),{data:g}))}}};async function y(){var h,M,E,$,_,w;D=0;const d=await ae(s.auth,a,f),{streamingManager:g,chat:c}=await U();r=-1,t.messages.length===0&&(t.messages=W(l),(M=(h=s.callbacks).onNewMessage)==null||M.call(h,t.messages)),c!=null&&c.id&&c.id!==((E=t.chat)==null?void 0:E.id)&&((_=($=s.callbacks).onNewChat)==null||_.call($,c==null?void 0:c.id)),t.streamingManager=g,t.socketManager=d,t.chat=c;const m=((w=t.chat)==null?void 0:w.chatMode)||I.Functional;C(m),u.track("agent-chat",{event:"connect",chatId:c.id,agentId:l.id})}async function R(){var d,g,c,m,h;(d=t.socketManager)==null||d.disconnect(),await((g=t.streamingManager)==null?void 0:g.disconnect()),delete t.streamingManager,delete t.socketManager,t.messages=W(l),(m=(c=s.callbacks).onNewMessage)==null||m.call(c,t.messages),u.track("agent-chat",{event:"disconnect",chatId:(h=t.chat)==null?void 0:h.id,agentId:l.id})}async function C(d){var g,c;d!==t.chatMode&&(u.track("agent-mode-change",{mode:d}),t.chatMode=d,t.chatMode!==I.Functional&&await R(),(c=(g=s.callbacks).onModeChange)==null||c.call(g,d))}async function K(){if(!t.chat)return y();const{streamingManager:d,chat:g}=await U();t.streamingManager=d,C(t.chat.chatMode||I.Functional),u.track("agent-chat",{event:"reconnect",chatId:g.id,agentId:l.id})}async function U(){let d,g;try{const c=await Ae(l,s,o,u,t.chat);d=c.streamingManager,g=c.chat}catch(c){throw C(I.Maintenance),c}return{streamingManager:d,chat:g}}return{agent:l,starterMessages:((V=l.knowledge)==null?void 0:V.starter_message)||[],connect:y,disconnect:R,changeMode:C,async reconnect(){var h,M;if(!t.chat)return y();(h=t.socketManager)==null||h.disconnect(),await((M=t.streamingManager)==null?void 0:M.disconnect());const d=await ae(s.auth,a,f),{streamingManager:g,chat:c}=await U();t.streamingManager=g,t.socketManager=d;const m=t.chat.chatMode||I.Functional;C(m),u.track("agent-chat",{event:"reconnect",chatId:c.id,agentId:l.id})},async chat(d){var c,m,h,M,E,$,_,w,ce;const g=B();try{if(D=Date.now(),d.length>=800)throw new Error("Message cannot be more than 800 characters");if(d.length===0)throw new Error("Message cannot be empty");if(t.chatMode===I.Maintenance)throw new Error("Chat is in maintenance mode");if(![I.TextOnly,I.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");if(t.messages.push({id:B(),role:"user",content:d,created_at:new Date(D).toISOString()}),(m=(c=s.callbacks).onNewMessage)==null||m.call(c,t.messages),!t.chat){const L={};t.chatMode===I.Playground&&(L.headers={[ie]:"true"}),t.chat=await o.newChat(l.id,L)}const x={id:g,role:"assistant",content:"",created_at:new Date().toISOString(),matches:[]};t.messages.push(x);const de=t.messages.slice(0,-1);let O;const J={};t.chatMode===I.Playground&&(J.headers={[ie]:"true"});try{O=await o.chat(l.id,t.chat.id,{sessionId:(h=t.streamingManager)==null?void 0:h.sessionId,streamId:(M=t.streamingManager)==null?void 0:M.streamId,messages:de,chatMode:t.chatMode},J)}catch(L){if((E=L==null?void 0:L.message)!=null&&E.includes("missing or invalid session_id"))console.log("Invalid stream, try reconnect with new stream id"),await K(),O=await o.chat(l.id,t.chat.id,{sessionId:($=t.streamingManager)==null?void 0:$.sessionId,streamId:(_=t.streamingManager)==null?void 0:_.streamId,messages:de,chatMode:t.chatMode},J);else throw L}return u.track("agent-message-send",{event:"success",messages:t.messages.length+1}),x.context=O.context,O.result&&(x.content=O.result,x.matches=O.matches,u.track("agent-message-received",{latency:Date.now()-D,messages:t.messages.length}),(ce=(w=s.callbacks).onNewMessage)==null||ce.call(w,t.messages)),O}catch(x){throw t.messages[t.messages.length-1].id===g&&t.messages.pop(),u.track("agent-message-send",{event:"error",messages:t.messages.length}),x}},rate(d,g,c){var M,E,$,_;const m=t.messages.find(w=>w.id===d);if(t.chat){if(!m)throw new Error("Message not found")}else throw new Error("Chat is not initialized");const h=((M=m.matches)==null?void 0:M.map(w=>[w.document_id,w.id]))??[];return u.track("agent-rate",{event:c?"update":"create",thumb:g===1?"up":"down",knowledge_id:((E=l.knowledge)==null?void 0:E.id)??"",matches:h,score:g}),c?o.updateRating(l.id,t.chat.id,c,{knowledge_id:(($=l.knowledge)==null?void 0:$.id)??"",message_id:d,matches:h,score:g}):o.createRating(l.id,t.chat.id,{knowledge_id:((_=l.knowledge)==null?void 0:_.id)??"",message_id:d,matches:h,score:g})},deleteRate(d){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:d}),o.deleteRating(l.id,t.chat.id,d)},speak(d){if(!t.streamingManager)throw new Error("Streaming manager is not initialized");function g(){if(l.presenter){if(d.type==="text")return{type:"text",provider:d.provider?d.provider:l.presenter.voice,input:d.input,ssml:d.ssml||!1};if(d.type==="audio")return{type:"audio",audio_url:d.audio_url}}else throw new Error("Presenter is not initialized");throw new Error("Invalid payload")}const c=g();return u.track("agent-speak",c),t.streamingManager.speak({script:c})}}}p.ChatMode=I,p.ChatProgress=F,p.ConnectionState=k,p.DocumentType=Z,p.KnowledgeType=Y,p.PlanGroup=q,p.Providers=G,p.RateState=X,p.StreamEvents=A,p.StreamingState=N,p.Subject=Q,p.UserPlan=b,p.VideoType=S,p.VoiceAccess=ee,p.createAgentManager=Ee,p.getAgent=Re,Object.defineProperty(p,Symbol.toStringTag,{value:"Module"})});
|
package/dist/src/api/agents.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Agent, AgentPayload, Auth, Chat,
|
|
1
|
+
import { Agent, AgentPayload, Auth, Chat, ChatPayload, ChatResponse, RatingEntity, RatingPayload } from '../types/index';
|
|
2
2
|
export declare function createAgentsApi(auth: Auth, host?: string, onError?: (error: Error, errorData: object) => void): {
|
|
3
3
|
create(payload: AgentPayload, options?: RequestInit): Promise<Agent>;
|
|
4
4
|
getAgents(tag?: string, options?: RequestInit): Promise<Agent[]>;
|
|
@@ -7,9 +7,6 @@ export declare function createAgentsApi(auth: Auth, host?: string, onError?: (er
|
|
|
7
7
|
update(id: string, payload: AgentPayload, options?: RequestInit): Promise<Agent>;
|
|
8
8
|
newChat(agentId: string, options?: RequestInit): Promise<Chat>;
|
|
9
9
|
chat(agentId: string, chatId: string, payload: ChatPayload, options?: RequestInit): Promise<ChatResponse>;
|
|
10
|
-
getChatMode(agentId: string, chatId: string, options?: RequestInit): Promise<{
|
|
11
|
-
chatMode: ChatMode;
|
|
12
|
-
}>;
|
|
13
10
|
createRating(agentId: string, chatId: string, payload: RatingPayload, options?: RequestInit): Promise<RatingEntity>;
|
|
14
11
|
updateRating(agentId: string, chatId: string, ratingId: string, payload: Partial<RatingPayload>, options?: RequestInit): Promise<RatingEntity>;
|
|
15
12
|
deleteRating(agentId: string, chatId: string, ratingId: string, options?: RequestInit): Promise<RatingEntity>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare const PLAYGROUND_HEADER = "X-Playground-Chat";
|
|
@@ -140,11 +140,5 @@ export interface AgentManager {
|
|
|
140
140
|
* @param mode - ChatMode
|
|
141
141
|
*/
|
|
142
142
|
changeMode(mode: ChatMode): void;
|
|
143
|
-
/**
|
|
144
|
-
* Method to fetch the mode of the chat, dependend on the credit and chat history checks
|
|
145
|
-
*/
|
|
146
|
-
getChatmode: () => Promise<{
|
|
147
|
-
chatMode: string;
|
|
148
|
-
}>;
|
|
149
143
|
}
|
|
150
144
|
export {};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@d-id/client-sdk",
|
|
3
3
|
"private": false,
|
|
4
|
-
"version": "1.0.19-beta.
|
|
4
|
+
"version": "1.0.19-beta.102",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"description": "d-id client sdk",
|
|
7
7
|
"repository": {
|
|
@@ -44,4 +44,4 @@
|
|
|
44
44
|
"vite": "^5.1.4",
|
|
45
45
|
"vite-plugin-dts": "^3.7.3"
|
|
46
46
|
}
|
|
47
|
-
}
|
|
47
|
+
}
|