@d-id/client-sdk 1.0.19-beta.87 → 1.0.19-beta.88
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 +269 -266
- package/dist/index.umd.cjs +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1,26 +1,26 @@
|
|
|
1
|
-
var
|
|
2
|
-
const T = "https://api.d-id.com",
|
|
3
|
-
function
|
|
1
|
+
var J = /* @__PURE__ */ ((e) => (e.TRIAL = "trial", e.BASIC = "basic", e.ENTERPRISE = "enterprise", e.LITE = "lite", e.ADVANCED = "advanced", e))(J || {}), q = /* @__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))(q || {}), V = /* @__PURE__ */ ((e) => (e.Unrated = "Unrated", e.Positive = "Positive", e.Negative = "Negative", e))(V || {}), A = /* @__PURE__ */ ((e) => (e.Functional = "Functional", e.TextOnly = "TextOnly", e.Maintenance = "Maintenance", e.Playground = "Playground", e))(A || {}), x = /* @__PURE__ */ ((e) => (e.Embed = "embed", e.Query = "query", e.Partial = "partial", e.Answer = "answer", e.Complete = "done", e))(x || {}), Q = /* @__PURE__ */ ((e) => (e.KnowledgeProcessing = "knowledge/processing", e.KnowledgeIndexing = "knowledge/indexing", e.KnowledgeFailed = "knowledge/error", e.KnowledgeDone = "knowledge/done", e))(Q || {}), X = /* @__PURE__ */ ((e) => (e.Knowledge = "knowledge", e.Document = "document", e.Record = "record", e))(X || {}), Y = /* @__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))(Y || {}), y = /* @__PURE__ */ ((e) => (e.Clip = "clip", e.Talk = "talk", e))(y || {}), N = /* @__PURE__ */ ((e) => (e.Start = "START", e.Stop = "STOP", e))(N || {}), L = /* @__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))(L || {}), S = /* @__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))(S || {}), Z = /* @__PURE__ */ ((e) => (e.Amazon = "amazon", e.Microsoft = "microsoft", e.Afflorithmics = "afflorithmics", e.Elevenlabs = "elevenlabs", e))(Z || {}), G = /* @__PURE__ */ ((e) => (e.Public = "public", e.Premium = "premium", e.Private = "private", e))(G || {});
|
|
2
|
+
const T = "https://api.d-id.com", ee = "wss://notifications.d-id.com", te = "79f81a83a67430be2bc0fd61042b8faa", O = () => Math.random().toString(16).slice(2);
|
|
3
|
+
function D() {
|
|
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 ne = O();
|
|
8
|
+
function j(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}.${D()}_${ne}`;
|
|
15
15
|
throw new Error(`Unknown auth type: ${e}`);
|
|
16
16
|
}
|
|
17
|
-
function
|
|
17
|
+
function z(e, r = T) {
|
|
18
18
|
const t = async (n, a) => {
|
|
19
19
|
const i = await fetch(r + (n != null && n.startsWith("/") ? n : `/${n}`), {
|
|
20
20
|
...a,
|
|
21
21
|
headers: {
|
|
22
22
|
...a == null ? void 0 : a.headers,
|
|
23
|
-
Authorization:
|
|
23
|
+
Authorization: j(e),
|
|
24
24
|
"Content-Type": "application/json"
|
|
25
25
|
}
|
|
26
26
|
});
|
|
@@ -60,8 +60,8 @@ function F(e, r = T) {
|
|
|
60
60
|
}
|
|
61
61
|
};
|
|
62
62
|
}
|
|
63
|
-
function
|
|
64
|
-
const t =
|
|
63
|
+
function U(e, r = T) {
|
|
64
|
+
const t = z(e, `${r}/agents`);
|
|
65
65
|
return {
|
|
66
66
|
create(n, a) {
|
|
67
67
|
return t.post("/", n, a);
|
|
@@ -87,16 +87,16 @@ function D(e, r = T) {
|
|
|
87
87
|
createRating(n, a, i, o) {
|
|
88
88
|
return t.post(`/${n}/chat/${a}/ratings`, i, o);
|
|
89
89
|
},
|
|
90
|
-
updateRating(n, a, i, o,
|
|
91
|
-
return t.patch(`/${n}/chat/${a}/ratings/${i}`, o,
|
|
90
|
+
updateRating(n, a, i, o, c) {
|
|
91
|
+
return t.patch(`/${n}/chat/${a}/ratings/${i}`, o, c);
|
|
92
92
|
},
|
|
93
93
|
deleteRating(n, a, i, o) {
|
|
94
94
|
return t.delete(`/${n}/chat/${a}/ratings/${i}`, o);
|
|
95
95
|
}
|
|
96
96
|
};
|
|
97
97
|
}
|
|
98
|
-
const
|
|
99
|
-
function
|
|
98
|
+
const ae = (e) => new Promise((r) => setTimeout(r, e));
|
|
99
|
+
function re(e) {
|
|
100
100
|
return new Promise((r, t) => {
|
|
101
101
|
const {
|
|
102
102
|
callbacks: n,
|
|
@@ -104,41 +104,41 @@ function ne(e) {
|
|
|
104
104
|
auth: i
|
|
105
105
|
} = e, {
|
|
106
106
|
onMessage: o = null,
|
|
107
|
-
onOpen:
|
|
107
|
+
onOpen: c = null,
|
|
108
108
|
onClose: g = null,
|
|
109
|
-
onError:
|
|
110
|
-
} = n || {},
|
|
111
|
-
|
|
112
|
-
console.error(
|
|
113
|
-
},
|
|
114
|
-
|
|
109
|
+
onError: u = null
|
|
110
|
+
} = n || {}, h = new WebSocket(`${a}?authorization=${j(i)}`);
|
|
111
|
+
h.onmessage = o, h.onclose = g, h.onerror = (p) => {
|
|
112
|
+
console.error(p), u == null || u("Websocket failed to connect", p), t(p);
|
|
113
|
+
}, h.onopen = (p) => {
|
|
114
|
+
c == null || c(p), r(h);
|
|
115
115
|
};
|
|
116
116
|
});
|
|
117
117
|
}
|
|
118
|
-
async function
|
|
118
|
+
async function ie(e) {
|
|
119
119
|
const {
|
|
120
120
|
retries: r = 1
|
|
121
121
|
} = e;
|
|
122
122
|
let t = null;
|
|
123
123
|
for (let n = 0; (t == null ? void 0 : t.readyState) !== WebSocket.OPEN; n++)
|
|
124
124
|
try {
|
|
125
|
-
t = await
|
|
125
|
+
t = await re(e);
|
|
126
126
|
} catch (a) {
|
|
127
127
|
if (n === r)
|
|
128
128
|
throw a;
|
|
129
|
-
await
|
|
129
|
+
await ae(n * 500);
|
|
130
130
|
}
|
|
131
131
|
return t;
|
|
132
132
|
}
|
|
133
|
-
async function
|
|
134
|
-
const n = t != null && t.onMessage ? [t.onMessage] : [], a = await
|
|
133
|
+
async function H(e, r, t) {
|
|
134
|
+
const n = t != null && t.onMessage ? [t.onMessage] : [], a = await ie({
|
|
135
135
|
auth: e,
|
|
136
136
|
host: r,
|
|
137
137
|
callbacks: {
|
|
138
138
|
onError: t == null ? void 0 : t.onError,
|
|
139
139
|
onMessage: (i) => {
|
|
140
140
|
const o = JSON.parse(i.data);
|
|
141
|
-
n.forEach((
|
|
141
|
+
n.forEach((c) => c(o.event, o));
|
|
142
142
|
}
|
|
143
143
|
}
|
|
144
144
|
});
|
|
@@ -148,8 +148,8 @@ async function W(e, r, t) {
|
|
|
148
148
|
subscribeToEvents: (i) => n.push(i)
|
|
149
149
|
};
|
|
150
150
|
}
|
|
151
|
-
function
|
|
152
|
-
const n =
|
|
151
|
+
function se(e, r, t) {
|
|
152
|
+
const n = z(e, `${r}/agents/${t}`);
|
|
153
153
|
return {
|
|
154
154
|
createStream(a) {
|
|
155
155
|
return n.post("/streams", {
|
|
@@ -157,40 +157,40 @@ function re(e, r, t) {
|
|
|
157
157
|
presenter_id: a.presenter_id,
|
|
158
158
|
compatibility_mode: a.compatibility_mode,
|
|
159
159
|
stream_warmup: a.stream_warmup,
|
|
160
|
-
type:
|
|
160
|
+
type: y.Clip
|
|
161
161
|
});
|
|
162
162
|
},
|
|
163
163
|
startConnection(a, i, o) {
|
|
164
164
|
return n.post(`/streams/${a}/sdp`, {
|
|
165
165
|
session_id: o,
|
|
166
166
|
answer: i,
|
|
167
|
-
type:
|
|
167
|
+
type: y.Clip
|
|
168
168
|
});
|
|
169
169
|
},
|
|
170
170
|
addIceCandidate(a, i, o) {
|
|
171
171
|
return n.post(`/streams/${a}/ice`, {
|
|
172
172
|
session_id: o,
|
|
173
173
|
...i,
|
|
174
|
-
type:
|
|
174
|
+
type: y.Clip
|
|
175
175
|
});
|
|
176
176
|
},
|
|
177
177
|
sendStreamRequest(a, i, o) {
|
|
178
178
|
return n.post(`/streams/${a}`, {
|
|
179
179
|
session_id: i,
|
|
180
180
|
...o,
|
|
181
|
-
type:
|
|
181
|
+
type: y.Clip
|
|
182
182
|
});
|
|
183
183
|
},
|
|
184
184
|
close(a, i) {
|
|
185
185
|
return n.delete(`/streams/${a}`, {
|
|
186
186
|
session_id: i,
|
|
187
|
-
type:
|
|
187
|
+
type: y.Clip
|
|
188
188
|
});
|
|
189
189
|
}
|
|
190
190
|
};
|
|
191
191
|
}
|
|
192
|
-
function
|
|
193
|
-
const n =
|
|
192
|
+
function oe(e, r, t) {
|
|
193
|
+
const n = z(e, `${r}/agents/${t}`);
|
|
194
194
|
return {
|
|
195
195
|
createStream(a, i) {
|
|
196
196
|
return n.post("/streams", {
|
|
@@ -201,39 +201,39 @@ function ie(e, r, t) {
|
|
|
201
201
|
compatibility_mode: a.compatibility_mode,
|
|
202
202
|
stream_warmup: a.stream_warmup,
|
|
203
203
|
stream_resolution: a.stream_resolution,
|
|
204
|
-
type:
|
|
204
|
+
type: y.Talk
|
|
205
205
|
}, i);
|
|
206
206
|
},
|
|
207
|
-
startConnection(a, i, o,
|
|
207
|
+
startConnection(a, i, o, c) {
|
|
208
208
|
return n.post(`/streams/${a}/sdp`, {
|
|
209
209
|
session_id: o,
|
|
210
210
|
answer: i,
|
|
211
|
-
type:
|
|
212
|
-
},
|
|
211
|
+
type: y.Talk
|
|
212
|
+
}, c);
|
|
213
213
|
},
|
|
214
|
-
addIceCandidate(a, i, o,
|
|
214
|
+
addIceCandidate(a, i, o, c) {
|
|
215
215
|
return n.post(`/streams/${a}/ice`, {
|
|
216
216
|
session_id: o,
|
|
217
217
|
...i,
|
|
218
|
-
type:
|
|
219
|
-
},
|
|
218
|
+
type: y.Talk
|
|
219
|
+
}, c);
|
|
220
220
|
},
|
|
221
|
-
sendStreamRequest(a, i, o,
|
|
221
|
+
sendStreamRequest(a, i, o, c) {
|
|
222
222
|
return n.post(`/streams/${a}`, {
|
|
223
223
|
session_id: i,
|
|
224
224
|
...o,
|
|
225
|
-
type:
|
|
226
|
-
},
|
|
225
|
+
type: y.Talk
|
|
226
|
+
}, c);
|
|
227
227
|
},
|
|
228
228
|
close(a, i, o) {
|
|
229
229
|
return n.delete(`/streams/${a}`, {
|
|
230
230
|
session_id: i,
|
|
231
|
-
type:
|
|
231
|
+
type: y.Talk
|
|
232
232
|
}, o);
|
|
233
233
|
}
|
|
234
234
|
};
|
|
235
235
|
}
|
|
236
|
-
function
|
|
236
|
+
function ce(e, r) {
|
|
237
237
|
return e.map((t, n) => n === 0 ? r ? {
|
|
238
238
|
index: n,
|
|
239
239
|
timestamp: t.timestamp,
|
|
@@ -266,138 +266,141 @@ function se(e, r) {
|
|
|
266
266
|
framesPerSecond: t.framesPerSecond
|
|
267
267
|
});
|
|
268
268
|
}
|
|
269
|
-
let
|
|
270
|
-
const
|
|
271
|
-
function
|
|
269
|
+
let B = !1;
|
|
270
|
+
const $ = (e, r) => B && console.log(e, r), de = (window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection).bind(window);
|
|
271
|
+
function ge(e) {
|
|
272
272
|
switch (e) {
|
|
273
273
|
case "connected":
|
|
274
|
-
return
|
|
274
|
+
return S.Connected;
|
|
275
275
|
case "checking":
|
|
276
|
-
return
|
|
276
|
+
return S.Connecting;
|
|
277
277
|
case "failed":
|
|
278
|
-
return
|
|
278
|
+
return S.Fail;
|
|
279
279
|
case "new":
|
|
280
280
|
case "closed":
|
|
281
281
|
case "disconnected":
|
|
282
282
|
default:
|
|
283
|
-
return
|
|
283
|
+
return S.New;
|
|
284
284
|
}
|
|
285
285
|
}
|
|
286
|
-
function
|
|
287
|
-
let
|
|
286
|
+
function le(e, r, t) {
|
|
287
|
+
let n = [], a = 0, i = 0, o = 0, c;
|
|
288
288
|
return setInterval(() => {
|
|
289
|
-
e.getStats().then((
|
|
290
|
-
|
|
291
|
-
if (
|
|
292
|
-
if (
|
|
293
|
-
const p =
|
|
294
|
-
let
|
|
295
|
-
if (
|
|
296
|
-
if (
|
|
297
|
-
|
|
289
|
+
e.getStats().then((u) => {
|
|
290
|
+
u.forEach((h) => {
|
|
291
|
+
if (h.type === "inbound-rtp" && h.kind === "video") {
|
|
292
|
+
if (i = n.length - 1, h && n[i]) {
|
|
293
|
+
const p = h.bytesReceived, k = n[i].bytesReceived, C = c;
|
|
294
|
+
let _;
|
|
295
|
+
if (c = p - k > 0, o = c ? 0 : ++o, C !== c)
|
|
296
|
+
if (c)
|
|
297
|
+
a = n.length, r == null || r(N.Start, _);
|
|
298
298
|
else {
|
|
299
|
-
const E =
|
|
300
|
-
|
|
299
|
+
const E = n.slice(a), M = a === 0 ? void 0 : n[a - 1];
|
|
300
|
+
_ = ce(E, M), _ = _.sort((s, m) => m.packetsLost - s.packetsLost).slice(0, 5);
|
|
301
301
|
}
|
|
302
|
-
!
|
|
302
|
+
!c && o === 1 && t.track("agent-video", {
|
|
303
|
+
event: "stats",
|
|
304
|
+
rtc: _
|
|
305
|
+
}), !c && o === 2 && (r == null || r(N.Stop, _));
|
|
303
306
|
}
|
|
304
|
-
|
|
307
|
+
n.push(h);
|
|
305
308
|
}
|
|
306
309
|
});
|
|
307
310
|
});
|
|
308
311
|
}, 500);
|
|
309
312
|
}
|
|
310
|
-
async function
|
|
313
|
+
async function me(e, r, {
|
|
311
314
|
debug: t = !1,
|
|
312
315
|
callbacks: n,
|
|
313
316
|
auth: a,
|
|
314
317
|
analytics: i,
|
|
315
318
|
baseURL: o = T
|
|
316
319
|
}) {
|
|
317
|
-
|
|
318
|
-
let
|
|
320
|
+
B = t;
|
|
321
|
+
let c;
|
|
319
322
|
const {
|
|
320
323
|
startConnection: g,
|
|
321
|
-
sendStreamRequest:
|
|
322
|
-
close:
|
|
323
|
-
createStream:
|
|
324
|
+
sendStreamRequest: u,
|
|
325
|
+
close: h,
|
|
326
|
+
createStream: p,
|
|
324
327
|
addIceCandidate: k
|
|
325
|
-
} = r.videoType ===
|
|
326
|
-
id:
|
|
327
|
-
offer:
|
|
328
|
-
ice_servers:
|
|
329
|
-
session_id:
|
|
330
|
-
} = await
|
|
331
|
-
iceServers:
|
|
332
|
-
}),
|
|
333
|
-
if (!
|
|
328
|
+
} = r.videoType === y.Clip ? se(a, o, e) : oe(a, o, e), {
|
|
329
|
+
id: C,
|
|
330
|
+
offer: _,
|
|
331
|
+
ice_servers: E,
|
|
332
|
+
session_id: M
|
|
333
|
+
} = await p(r), s = new de({
|
|
334
|
+
iceServers: E
|
|
335
|
+
}), m = s.createDataChannel("JanusDataChannel");
|
|
336
|
+
if (!M)
|
|
334
337
|
throw new Error("Could not create session_id");
|
|
335
|
-
const
|
|
336
|
-
s.onicecandidate = (
|
|
337
|
-
|
|
338
|
-
candidate:
|
|
339
|
-
sdpMid:
|
|
340
|
-
sdpMLineIndex:
|
|
341
|
-
},
|
|
338
|
+
const l = le(s, n.onVideoStateChange, i);
|
|
339
|
+
s.onicecandidate = (d) => {
|
|
340
|
+
$("peerConnection.onicecandidate", d), d.candidate && d.candidate.sdpMid && d.candidate.sdpMLineIndex !== null ? k(C, {
|
|
341
|
+
candidate: d.candidate.candidate,
|
|
342
|
+
sdpMid: d.candidate.sdpMid,
|
|
343
|
+
sdpMLineIndex: d.candidate.sdpMLineIndex
|
|
344
|
+
}, M) : k(C, {
|
|
342
345
|
candidate: null
|
|
343
|
-
},
|
|
346
|
+
}, M);
|
|
344
347
|
}, s.oniceconnectionstatechange = () => {
|
|
345
348
|
var w;
|
|
346
|
-
|
|
347
|
-
const
|
|
348
|
-
|
|
349
|
-
var
|
|
350
|
-
(
|
|
351
|
-
}, 5e3) : (clearTimeout(
|
|
352
|
-
}, s.ontrack = (
|
|
349
|
+
$("peerConnection.oniceconnectionstatechange => " + s.iceConnectionState);
|
|
350
|
+
const d = ge(s.iceConnectionState);
|
|
351
|
+
d === S.Connected ? c = setTimeout(() => {
|
|
352
|
+
var v;
|
|
353
|
+
(v = n.onConnectionStateChange) == null || v.call(n, S.Connected);
|
|
354
|
+
}, 5e3) : (clearTimeout(c), (w = n.onConnectionStateChange) == null || w.call(n, d));
|
|
355
|
+
}, s.ontrack = (d) => {
|
|
353
356
|
var w;
|
|
354
|
-
|
|
355
|
-
},
|
|
357
|
+
$("peerConnection.ontrack", d), (w = n.onSrcObjectReady) == null || w.call(n, d.streams[0]);
|
|
358
|
+
}, m.onmessage = (d) => {
|
|
356
359
|
var w;
|
|
357
|
-
if (
|
|
358
|
-
const [
|
|
359
|
-
|
|
360
|
+
if (m.readyState === "open") {
|
|
361
|
+
const [v, R] = d.data.split(":");
|
|
362
|
+
v === L.StreamReady && (clearTimeout(c), (w = n.onConnectionStateChange) == null || w.call(n, S.Connected));
|
|
360
363
|
}
|
|
361
|
-
}, await s.setRemoteDescription(
|
|
362
|
-
const
|
|
363
|
-
return
|
|
364
|
+
}, await s.setRemoteDescription(_), $("set remote description OK");
|
|
365
|
+
const f = await s.createAnswer();
|
|
366
|
+
return $("create answer OK"), await s.setLocalDescription(f), $("set local description OK"), await g(C, f, M), $("start connection OK"), {
|
|
364
367
|
/**
|
|
365
368
|
* Method to send request to server to get clip or talk depend on you payload
|
|
366
369
|
* @param payload
|
|
367
370
|
*/
|
|
368
|
-
speak(
|
|
369
|
-
return
|
|
371
|
+
speak(d) {
|
|
372
|
+
return u(C, M, d);
|
|
370
373
|
},
|
|
371
374
|
/**
|
|
372
375
|
* Method to close RTC connection
|
|
373
376
|
*/
|
|
374
377
|
async disconnect() {
|
|
375
|
-
var
|
|
376
|
-
if (
|
|
378
|
+
var d, w;
|
|
379
|
+
if (C) {
|
|
377
380
|
s && (s.close(), s.oniceconnectionstatechange = null, s.onnegotiationneeded = null, s.onicecandidate = null, s.ontrack = null);
|
|
378
381
|
try {
|
|
379
|
-
await
|
|
382
|
+
await h(C, M).catch((v) => {
|
|
380
383
|
});
|
|
381
|
-
} catch (
|
|
382
|
-
|
|
384
|
+
} catch (v) {
|
|
385
|
+
$("Error on close stream connection", v);
|
|
383
386
|
}
|
|
384
|
-
(
|
|
387
|
+
(d = n.onConnectionStateChange) == null || d.call(n, S.New), (w = n.onVideoStateChange) == null || w.call(n, N.Stop), clearInterval(l);
|
|
385
388
|
}
|
|
386
389
|
},
|
|
387
390
|
/**
|
|
388
391
|
* Session identifier information, should be returned in the body of all streaming requests
|
|
389
392
|
*/
|
|
390
|
-
sessionId:
|
|
393
|
+
sessionId: M,
|
|
391
394
|
/**
|
|
392
395
|
* Id of current RTC stream
|
|
393
396
|
*/
|
|
394
|
-
streamId:
|
|
397
|
+
streamId: C
|
|
395
398
|
};
|
|
396
399
|
}
|
|
397
|
-
function
|
|
400
|
+
function ue(e) {
|
|
398
401
|
const r = {
|
|
399
402
|
token: e.token || "testKey",
|
|
400
|
-
distinct_id: e.distinctId ||
|
|
403
|
+
distinct_id: e.distinctId || D(),
|
|
401
404
|
isEnabled: e.isEnabled ?? !0,
|
|
402
405
|
agentId: e.agent.id,
|
|
403
406
|
owner_id: e.agent.owner_id ?? ""
|
|
@@ -433,8 +436,8 @@ function le(e) {
|
|
|
433
436
|
}
|
|
434
437
|
};
|
|
435
438
|
}
|
|
436
|
-
function
|
|
437
|
-
var n, a, i, o,
|
|
439
|
+
function we(e) {
|
|
440
|
+
var n, a, i, o, c;
|
|
438
441
|
const r = () => /Mobi|Android/i.test(navigator.userAgent) ? "Mobile" : "Desktop";
|
|
439
442
|
return {
|
|
440
443
|
$os: `${(() => {
|
|
@@ -447,15 +450,15 @@ function me(e) {
|
|
|
447
450
|
agentType: (n = e.presenter) == null ? void 0 : n.type,
|
|
448
451
|
agentVoice: {
|
|
449
452
|
voiceId: (i = (a = e.presenter) == null ? void 0 : a.voice) == null ? void 0 : i.voice_id,
|
|
450
|
-
provider: (
|
|
453
|
+
provider: (c = (o = e.presenter) == null ? void 0 : o.voice) == null ? void 0 : c.type
|
|
451
454
|
}
|
|
452
455
|
};
|
|
453
456
|
}
|
|
454
|
-
function
|
|
457
|
+
function he(e) {
|
|
455
458
|
if (e.presenter) {
|
|
456
|
-
if (e.presenter.type ===
|
|
459
|
+
if (e.presenter.type === y.Clip)
|
|
457
460
|
return {
|
|
458
|
-
videoType:
|
|
461
|
+
videoType: y.Clip,
|
|
459
462
|
driver_id: e.presenter.driver_id,
|
|
460
463
|
presenter_id: e.presenter.presenter_id,
|
|
461
464
|
stream_warmup: !0
|
|
@@ -463,53 +466,50 @@ function ue(e) {
|
|
|
463
466
|
} else
|
|
464
467
|
throw new Error("Presenter is not initialized");
|
|
465
468
|
return {
|
|
466
|
-
videoType:
|
|
469
|
+
videoType: y.Talk,
|
|
467
470
|
source_url: e.presenter.source_url,
|
|
468
|
-
stream_warmup: !0
|
|
469
|
-
...e.presenter.stitch && {
|
|
470
|
-
stream_resolution: 1080
|
|
471
|
-
}
|
|
471
|
+
stream_warmup: !0
|
|
472
472
|
};
|
|
473
473
|
}
|
|
474
|
-
function
|
|
474
|
+
function K(e, r, t, n, a) {
|
|
475
475
|
return new Promise(async (i, o) => {
|
|
476
|
-
let
|
|
477
|
-
const g = await
|
|
476
|
+
let c = a;
|
|
477
|
+
const g = await me(e.id, he(e), {
|
|
478
478
|
...r,
|
|
479
479
|
analytics: n,
|
|
480
480
|
callbacks: {
|
|
481
481
|
...r.callbacks,
|
|
482
|
-
onConnectionStateChange: async (
|
|
483
|
-
var
|
|
484
|
-
if (
|
|
482
|
+
onConnectionStateChange: async (u) => {
|
|
483
|
+
var h, p;
|
|
484
|
+
if (u === S.Connected)
|
|
485
485
|
try {
|
|
486
|
-
|
|
486
|
+
c || (c = await t.newChat(e.id), n.track("agent-chat", {
|
|
487
487
|
event: "created",
|
|
488
|
-
chat_id:
|
|
488
|
+
chat_id: c.id,
|
|
489
489
|
agent_id: e.id
|
|
490
490
|
})), g && i({
|
|
491
|
-
chat:
|
|
491
|
+
chat: c,
|
|
492
492
|
streamingManager: g
|
|
493
493
|
});
|
|
494
494
|
} catch (k) {
|
|
495
495
|
console.error(k), o("Cannot create new chat");
|
|
496
496
|
}
|
|
497
497
|
else
|
|
498
|
-
|
|
499
|
-
(
|
|
498
|
+
u === S.Fail && o(new Error("Cannot create connection"));
|
|
499
|
+
(p = (h = r.callbacks).onConnectionStateChange) == null || p.call(h, u);
|
|
500
500
|
},
|
|
501
|
-
onVideoStateChange(
|
|
502
|
-
var
|
|
503
|
-
(k = (
|
|
501
|
+
onVideoStateChange(u, h) {
|
|
502
|
+
var p, k;
|
|
503
|
+
(k = (p = r.callbacks).onVideoStateChange) == null || k.call(p, u, h);
|
|
504
504
|
}
|
|
505
505
|
}
|
|
506
506
|
}).catch(o);
|
|
507
507
|
});
|
|
508
508
|
}
|
|
509
|
-
function
|
|
510
|
-
return
|
|
509
|
+
function fe(e, r, t) {
|
|
510
|
+
return U(r, t || T).getById(e);
|
|
511
511
|
}
|
|
512
|
-
function
|
|
512
|
+
function W(e) {
|
|
513
513
|
let r = "";
|
|
514
514
|
if (e.greetings && e.greetings.length > 0) {
|
|
515
515
|
const t = Math.floor(Math.random() * e.greetings.length);
|
|
@@ -518,185 +518,188 @@ function O(e) {
|
|
|
518
518
|
r = `Hi! I'm ${e.preview_name}, welcome to agents. How can I help you?`;
|
|
519
519
|
return [{
|
|
520
520
|
content: r,
|
|
521
|
-
id:
|
|
521
|
+
id: O(),
|
|
522
522
|
role: "assistant",
|
|
523
523
|
created_at: (/* @__PURE__ */ new Date()).toISOString()
|
|
524
524
|
}];
|
|
525
525
|
}
|
|
526
|
-
async function
|
|
527
|
-
var
|
|
526
|
+
async function pe(e, r) {
|
|
527
|
+
var _, E, M;
|
|
528
528
|
const t = {
|
|
529
529
|
messages: [],
|
|
530
|
-
chatMode: r.mode ||
|
|
530
|
+
chatMode: r.mode || A.Functional
|
|
531
531
|
};
|
|
532
532
|
let n = -1;
|
|
533
|
-
const a = r.wsURL ||
|
|
534
|
-
t.messages =
|
|
535
|
-
const
|
|
533
|
+
const a = r.wsURL || ee, i = r.baseURL || T, o = r.mixpanelKey || te, c = U(r.auth, i), g = await c.getById(e);
|
|
534
|
+
t.messages = W(g), (E = (_ = r.callbacks).onNewMessage) == null || E.call(_, t.messages);
|
|
535
|
+
const u = ue({
|
|
536
536
|
token: o,
|
|
537
537
|
agent: g,
|
|
538
538
|
...r
|
|
539
539
|
});
|
|
540
|
-
|
|
540
|
+
u.track("agent-sdk", {
|
|
541
541
|
event: "loaded",
|
|
542
|
-
...
|
|
542
|
+
...we(g)
|
|
543
543
|
});
|
|
544
|
-
const
|
|
545
|
-
onMessage: (s,
|
|
546
|
-
var
|
|
547
|
-
if ("content" in
|
|
544
|
+
const h = {
|
|
545
|
+
onMessage: (s, m) => {
|
|
546
|
+
var l, f;
|
|
547
|
+
if ("content" in m) {
|
|
548
548
|
const {
|
|
549
|
-
content:
|
|
550
|
-
} =
|
|
551
|
-
(w == null ? void 0 : w.role) === "assistant" && (n < t.messages.length && (w.content = s ===
|
|
549
|
+
content: d
|
|
550
|
+
} = m, w = t.messages[t.messages.length - 1];
|
|
551
|
+
(w == null ? void 0 : w.role) === "assistant" && (n < t.messages.length && (w.content = s === x.Partial ? w.content + d : d), s === x.Answer && (n = t.messages.length)), s === x.Answer && u.track("agent-message-received", {
|
|
552
552
|
messages: t.messages.length
|
|
553
|
-
}), (
|
|
554
|
-
} else if ([
|
|
555
|
-
const
|
|
556
|
-
|
|
557
|
-
...
|
|
558
|
-
event:
|
|
553
|
+
}), (f = (l = r.callbacks).onNewMessage) == null || f.call(l, t.messages);
|
|
554
|
+
} else if ([L.StreamVideoCreated, L.StreamVideoDone, L.StreamVideoError, L.StreamVideoRejected].includes(s)) {
|
|
555
|
+
const d = s.split("/")[1];
|
|
556
|
+
u.track("agent-video", {
|
|
557
|
+
...m,
|
|
558
|
+
event: d
|
|
559
559
|
});
|
|
560
560
|
}
|
|
561
561
|
}
|
|
562
562
|
};
|
|
563
|
-
async function
|
|
564
|
-
var
|
|
565
|
-
const s = await
|
|
566
|
-
streamingManager:
|
|
567
|
-
chat:
|
|
568
|
-
} = await
|
|
569
|
-
n = -1, t.messages.length === 0 && (t.messages =
|
|
563
|
+
async function p() {
|
|
564
|
+
var f, d, w, v, R;
|
|
565
|
+
const s = await H(r.auth, a, h), {
|
|
566
|
+
streamingManager: m,
|
|
567
|
+
chat: l
|
|
568
|
+
} = await K(g, r, c, u, t.chat);
|
|
569
|
+
n = -1, t.messages.length === 0 && (t.messages = W(g), (d = (f = r.callbacks).onNewMessage) == null || d.call(f, t.messages)), l != null && l.id && l.id !== ((w = t.chat) == null ? void 0 : w.id) && ((R = (v = r.callbacks).onNewChat) == null || R.call(v, l == null ? void 0 : l.id)), t.streamingManager = m, t.socketManager = s, t.chat = l, C(A.Functional), u.track("agent-chat", {
|
|
570
570
|
event: "connect",
|
|
571
|
-
chatId:
|
|
571
|
+
chatId: l.id,
|
|
572
572
|
agentId: g.id
|
|
573
573
|
});
|
|
574
574
|
}
|
|
575
575
|
async function k() {
|
|
576
|
-
var s,
|
|
577
|
-
(s = t.socketManager) == null || s.disconnect(), await ((
|
|
576
|
+
var s, m, l, f, d;
|
|
577
|
+
(s = t.socketManager) == null || s.disconnect(), await ((m = t.streamingManager) == null ? void 0 : m.disconnect()), delete t.streamingManager, delete t.socketManager, t.messages = W(g), (f = (l = r.callbacks).onNewMessage) == null || f.call(l, t.messages), u.track("agent-chat", {
|
|
578
578
|
event: "disconnect",
|
|
579
|
-
chatId: (
|
|
579
|
+
chatId: (d = t.chat) == null ? void 0 : d.id,
|
|
580
580
|
agentId: g.id
|
|
581
581
|
});
|
|
582
582
|
}
|
|
583
|
-
async function
|
|
584
|
-
var
|
|
585
|
-
s !== t.chatMode && (
|
|
583
|
+
async function C(s) {
|
|
584
|
+
var m, l;
|
|
585
|
+
s !== t.chatMode && (u.track("agent-mode-change", {
|
|
586
586
|
mode: s
|
|
587
|
-
}), t.chatMode = s, t.chatMode !==
|
|
587
|
+
}), t.chatMode = s, t.chatMode !== A.Functional && await k(), (l = (m = r.callbacks).onModeChange) == null || l.call(m, s));
|
|
588
588
|
}
|
|
589
589
|
return {
|
|
590
590
|
agent: g,
|
|
591
|
-
starterMessages: ((
|
|
592
|
-
connect:
|
|
591
|
+
starterMessages: ((M = g.knowledge) == null ? void 0 : M.starter_message) || [],
|
|
592
|
+
connect: p,
|
|
593
593
|
disconnect: k,
|
|
594
|
-
changeMode:
|
|
594
|
+
changeMode: C,
|
|
595
595
|
async reconnect() {
|
|
596
|
-
var
|
|
596
|
+
var f, d;
|
|
597
597
|
if (!t.chat)
|
|
598
|
-
return
|
|
599
|
-
(
|
|
600
|
-
const s = await
|
|
601
|
-
streamingManager:
|
|
602
|
-
chat:
|
|
603
|
-
} = await
|
|
604
|
-
t.streamingManager =
|
|
598
|
+
return p();
|
|
599
|
+
(f = t.socketManager) == null || f.disconnect(), await ((d = t.streamingManager) == null ? void 0 : d.disconnect());
|
|
600
|
+
const s = await H(r.auth, a, h), {
|
|
601
|
+
streamingManager: m,
|
|
602
|
+
chat: l
|
|
603
|
+
} = await K(g, r, c, u, t.chat);
|
|
604
|
+
t.streamingManager = m, t.socketManager = s, C(A.Functional), u.track("agent-chat", {
|
|
605
605
|
event: "reconnect",
|
|
606
|
-
chatId:
|
|
606
|
+
chatId: l.id,
|
|
607
607
|
agentId: g.id
|
|
608
608
|
});
|
|
609
609
|
},
|
|
610
|
-
async chat(s,
|
|
611
|
-
var
|
|
610
|
+
async chat(s, m = !1) {
|
|
611
|
+
var f, d, w, v, R, b;
|
|
612
|
+
const l = O();
|
|
612
613
|
try {
|
|
613
|
-
const
|
|
614
|
+
const I = Date.now();
|
|
614
615
|
if (s.length >= 800)
|
|
615
616
|
throw new Error("Message cannot be more than 800 characters");
|
|
616
617
|
if (s.length === 0)
|
|
617
618
|
throw new Error("Message cannot be empty");
|
|
618
|
-
if (t.chatMode ===
|
|
619
|
+
if (t.chatMode === A.Maintenance)
|
|
619
620
|
throw new Error("Chat is in maintenance mode");
|
|
620
|
-
if (![
|
|
621
|
+
if (![A.TextOnly, A.Playground].includes(t.chatMode)) {
|
|
621
622
|
if (!t.streamingManager)
|
|
622
623
|
throw new Error("Streaming manager is not initialized");
|
|
623
624
|
if (!t.chat)
|
|
624
625
|
throw new Error("Chat is not initialized");
|
|
625
626
|
}
|
|
626
627
|
t.messages.push({
|
|
627
|
-
id:
|
|
628
|
+
id: O(),
|
|
628
629
|
role: "user",
|
|
629
630
|
content: s,
|
|
630
|
-
created_at: new Date(
|
|
631
|
-
}), (
|
|
632
|
-
const
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
631
|
+
created_at: new Date(I).toISOString()
|
|
632
|
+
}), (d = (f = r.callbacks).onNewMessage) == null || d.call(f, t.messages), t.chat || (t.chat = await c.newChat(g.id));
|
|
633
|
+
const F = {
|
|
634
|
+
id: l,
|
|
635
|
+
role: "assistant",
|
|
636
|
+
content: "",
|
|
637
|
+
created_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
638
|
+
matches: []
|
|
639
|
+
};
|
|
640
|
+
t.messages.push(F);
|
|
641
|
+
const P = await c.chat(g.id, t.chat.id, {
|
|
642
|
+
sessionId: (w = t.streamingManager) == null ? void 0 : w.sessionId,
|
|
643
|
+
streamId: (v = t.streamingManager) == null ? void 0 : v.streamId,
|
|
644
|
+
messages: t.messages.slice(0, -1),
|
|
636
645
|
chatMode: t.chatMode,
|
|
637
|
-
append_chat:
|
|
646
|
+
append_chat: m
|
|
638
647
|
});
|
|
639
|
-
return
|
|
648
|
+
return u.track("agent-message-send", {
|
|
640
649
|
event: "success",
|
|
641
650
|
messages: t.messages.length + 1
|
|
642
|
-
}),
|
|
643
|
-
|
|
644
|
-
role: "assistant",
|
|
645
|
-
content: R.result || "",
|
|
646
|
-
created_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
647
|
-
matches: R.matches
|
|
648
|
-
}), R.result && (l.track("agent-message-received", {
|
|
649
|
-
latency: Date.now() - A,
|
|
651
|
+
}), P.result && (F.content = P.result, F.matches = P.matches, u.track("agent-message-received", {
|
|
652
|
+
latency: Date.now() - I,
|
|
650
653
|
messages: t.messages.length
|
|
651
|
-
}), (
|
|
652
|
-
} catch (
|
|
653
|
-
throw l.track("agent-message-send", {
|
|
654
|
+
}), (b = (R = r.callbacks).onNewMessage) == null || b.call(R, t.messages)), P;
|
|
655
|
+
} catch (I) {
|
|
656
|
+
throw t.messages[t.messages.length - 1].id === l && t.messages.pop(), u.track("agent-message-send", {
|
|
654
657
|
event: "error",
|
|
655
658
|
messages: t.messages.length
|
|
656
|
-
}),
|
|
659
|
+
}), I;
|
|
657
660
|
}
|
|
658
661
|
},
|
|
659
|
-
rate(s,
|
|
660
|
-
var w,
|
|
661
|
-
const
|
|
662
|
+
rate(s, m, l) {
|
|
663
|
+
var w, v, R, b;
|
|
664
|
+
const f = t.messages.find((I) => I.id === s);
|
|
662
665
|
if (t.chat) {
|
|
663
|
-
if (!
|
|
666
|
+
if (!f)
|
|
664
667
|
throw new Error("Message not found");
|
|
665
668
|
} else
|
|
666
669
|
throw new Error("Chat is not initialized");
|
|
667
|
-
const
|
|
668
|
-
return
|
|
669
|
-
event:
|
|
670
|
-
thumb:
|
|
671
|
-
knowledge_id: ((
|
|
672
|
-
matches:
|
|
673
|
-
score:
|
|
674
|
-
}),
|
|
675
|
-
knowledge_id: ((
|
|
670
|
+
const d = ((w = f.matches) == null ? void 0 : w.map((I) => [I.document_id, I.id])) ?? [];
|
|
671
|
+
return u.track("agent-rate", {
|
|
672
|
+
event: l ? "update" : "create",
|
|
673
|
+
thumb: m === 1 ? "up" : "down",
|
|
674
|
+
knowledge_id: ((v = g.knowledge) == null ? void 0 : v.id) ?? "",
|
|
675
|
+
matches: d,
|
|
676
|
+
score: m
|
|
677
|
+
}), l ? c.updateRating(g.id, t.chat.id, l, {
|
|
678
|
+
knowledge_id: ((R = g.knowledge) == null ? void 0 : R.id) ?? "",
|
|
676
679
|
message_id: s,
|
|
677
|
-
matches:
|
|
678
|
-
score:
|
|
679
|
-
}) :
|
|
680
|
-
knowledge_id: ((
|
|
680
|
+
matches: d,
|
|
681
|
+
score: m
|
|
682
|
+
}) : c.createRating(g.id, t.chat.id, {
|
|
683
|
+
knowledge_id: ((b = g.knowledge) == null ? void 0 : b.id) ?? "",
|
|
681
684
|
message_id: s,
|
|
682
|
-
matches:
|
|
683
|
-
score:
|
|
685
|
+
matches: d,
|
|
686
|
+
score: m
|
|
684
687
|
});
|
|
685
688
|
},
|
|
686
689
|
deleteRate(s) {
|
|
687
|
-
var
|
|
690
|
+
var m;
|
|
688
691
|
if (!t.chat)
|
|
689
692
|
throw new Error("Chat is not initialized");
|
|
690
|
-
return
|
|
693
|
+
return u.track("agent-rate-delete", {
|
|
691
694
|
type: "text",
|
|
692
|
-
chat_id: (
|
|
695
|
+
chat_id: (m = t.chat) == null ? void 0 : m.id,
|
|
693
696
|
id: s
|
|
694
|
-
}),
|
|
697
|
+
}), c.deleteRating(g.id, t.chat.id, s);
|
|
695
698
|
},
|
|
696
699
|
speak(s) {
|
|
697
700
|
if (!t.streamingManager)
|
|
698
701
|
throw new Error("Streaming manager is not initialized");
|
|
699
|
-
function
|
|
702
|
+
function m() {
|
|
700
703
|
if (g.presenter) {
|
|
701
704
|
if (s.type === "text")
|
|
702
705
|
return {
|
|
@@ -714,28 +717,28 @@ async function he(e, r) {
|
|
|
714
717
|
throw new Error("Presenter is not initialized");
|
|
715
718
|
throw new Error("Invalid payload");
|
|
716
719
|
}
|
|
717
|
-
const
|
|
718
|
-
return
|
|
719
|
-
script:
|
|
720
|
+
const l = m();
|
|
721
|
+
return u.track("agent-speak", l), t.streamingManager.speak({
|
|
722
|
+
script: l
|
|
720
723
|
});
|
|
721
724
|
}
|
|
722
725
|
};
|
|
723
726
|
}
|
|
724
727
|
export {
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
728
|
+
A as ChatMode,
|
|
729
|
+
x as ChatProgress,
|
|
730
|
+
S as ConnectionState,
|
|
731
|
+
Y as DocumentType,
|
|
732
|
+
X as KnowledgeType,
|
|
733
|
+
q as PlanGroup,
|
|
734
|
+
Z as Providers,
|
|
735
|
+
V as RateState,
|
|
736
|
+
L as StreamEvents,
|
|
737
|
+
N as StreamingState,
|
|
738
|
+
Q as Subject,
|
|
739
|
+
J as UserPlan,
|
|
740
|
+
y as VideoType,
|
|
741
|
+
G as VoiceAccess,
|
|
742
|
+
pe as createAgentManager,
|
|
743
|
+
fe as getAgent
|
|
741
744
|
};
|
package/dist/index.umd.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(function(w,T){typeof exports=="object"&&typeof module<"u"?T(exports):typeof define=="function"&&define.amd?define(["exports"],T):(w=typeof globalThis<"u"?globalThis:w||self,T(w.index={}))})(this,function(w){"use strict";var T=(e=>(e.TRIAL="trial",e.BASIC="basic",e.ENTERPRISE="enterprise",e.LITE="lite",e.ADVANCED="advanced",e))(T||{}),z=(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))(z||{}),D=(e=>(e.Unrated="Unrated",e.Positive="Positive",e.Negative="Negative",e))(D||{}),R=(e=>(e.Functional="Functional",e.TextOnly="TextOnly",e.Maintenance="Maintenance",e.Playground="Playground",e))(R||{}),N=(e=>(e.Embed="embed",e.Query="query",e.Partial="partial",e.Answer="answer",e.Complete="done",e))(N||{}),H=(e=>(e.KnowledgeProcessing="knowledge/processing",e.KnowledgeIndexing="knowledge/indexing",e.KnowledgeFailed="knowledge/error",e.KnowledgeDone="knowledge/done",e))(H||{}),x=(e=>(e.Knowledge="knowledge",e.Document="document",e.Record="record",e))(x||{}),U=(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))(U||{}),C=(e=>(e.Clip="clip",e.Talk="talk",e))(C||{}),O=(e=>(e.Start="START",e.Stop="STOP",e))(O||{}),E=(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||{}),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||{}),B=(e=>(e.Amazon="amazon",e.Microsoft="microsoft",e.Afflorithmics="afflorithmics",e.Elevenlabs="elevenlabs",e))(B||{}),J=(e=>(e.Public="public",e.Premium="premium",e.Private="private",e))(J||{});const F="https://api.d-id.com",G="wss://notifications.d-id.com",ee="79f81a83a67430be2bc0fd61042b8faa",K=()=>Math.random().toString(16).slice(2);function V(){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 te=K();function q(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}.${V()}_${te}`;throw new Error(`Unknown auth type: ${e}`)}function W(e,i=F){const t=async(n,a)=>{const r=await fetch(i+(n!=null&&n.startsWith("/")?n:`/${n}`),{...a,headers:{...a==null?void 0:a.headers,Authorization:q(e),"Content-Type":"application/json"}});if(!r.ok){let o=await r.text().catch(()=>"Failed to fetch");throw new Error(o)}return r.json()};return{get(n,a){return t(n,{...a,method:"GET"})},post(n,a,r){return t(n,{...r,body:JSON.stringify(a),method:"POST"})},delete(n,a,r){return t(n,{...r,body:JSON.stringify(a),method:"DELETE"})},patch(n,a,r){return t(n,{...r,body:JSON.stringify(a),method:"PATCH"})}}}function Q(e,i=F){const t=W(e,`${i}/agents`);return{create(n,a){return t.post("/",n,a)},getAgents(n,a){return t.get(`/${n?`?tag=${n}`:""}`,a).then(r=>r??[])},getById(n,a){return t.get(`/${n}`,a)},delete(n,a){return t.delete(`/${n}`,void 0,a)},update(n,a,r){return t.patch(`/${n}`,a,r)},newChat(n,a){return t.post(`/${n}/chat`,void 0,a)},chat(n,a,r,o){return t.post(`/${n}/chat/${a}`,r,o)},createRating(n,a,r,o){return t.post(`/${n}/chat/${a}/ratings`,r,o)},updateRating(n,a,r,o,d){return t.patch(`/${n}/chat/${a}/ratings/${r}`,o,d)},deleteRating(n,a,r,o){return t.delete(`/${n}/chat/${a}/ratings/${r}`,o)}}}const ne=e=>new Promise(i=>setTimeout(i,e));function ae(e){return new Promise((i,t)=>{const{callbacks:n,host:a,auth:r}=e,{onMessage:o=null,onOpen:d=null,onClose:g=null,onError:l=null}=n||{},y=new WebSocket(`${a}?authorization=${q(r)}`);y.onmessage=o,y.onclose=g,y.onerror=p=>{console.error(p),l==null||l("Websocket failed to connect",p),t(p)},y.onopen=p=>{d==null||d(p),i(y)}})}async function ie(e){const{retries:i=1}=e;let t=null;for(let n=0;(t==null?void 0:t.readyState)!==WebSocket.OPEN;n++)try{t=await ae(e)}catch(a){if(n===i)throw a;await ne(n*500)}return t}async function X(e,i,t){const n=t!=null&&t.onMessage?[t.onMessage]:[],a=await ie({auth:e,host:i,callbacks:{onError:t==null?void 0:t.onError,onMessage:r=>{const o=JSON.parse(r.data);n.forEach(d=>d(o.event,o))}}});return{socket:a,disconnect:()=>a.close(),subscribeToEvents:r=>n.push(r)}}function re(e,i,t){const n=W(e,`${i}/agents/${t}`);return{createStream(a){return n.post("/streams",{driver_id:a.driver_id,presenter_id:a.presenter_id,compatibility_mode:a.compatibility_mode,stream_warmup:a.stream_warmup,type:C.Clip})},startConnection(a,r,o){return n.post(`/streams/${a}/sdp`,{session_id:o,answer:r,type:C.Clip})},addIceCandidate(a,r,o){return n.post(`/streams/${a}/ice`,{session_id:o,...r,type:C.Clip})},sendStreamRequest(a,r,o){return n.post(`/streams/${a}`,{session_id:r,...o,type:C.Clip})},close(a,r){return n.delete(`/streams/${a}`,{session_id:r,type:C.Clip})}}}function se(e,i,t){const n=W(e,`${i}/agents/${t}`);return{createStream(a,r){return n.post("/streams",{source_url:a.source_url,driver_url:a.driver_url,face:a.face,config:a.config,compatibility_mode:a.compatibility_mode,stream_warmup:a.stream_warmup,stream_resolution:a.stream_resolution,type:C.Talk},r)},startConnection(a,r,o,d){return n.post(`/streams/${a}/sdp`,{session_id:o,answer:r,type:C.Talk},d)},addIceCandidate(a,r,o,d){return n.post(`/streams/${a}/ice`,{session_id:o,...r,type:C.Talk},d)},sendStreamRequest(a,r,o,d){return n.post(`/streams/${a}`,{session_id:r,...o,type:C.Talk},d)},close(a,r,o){return n.delete(`/streams/${a}`,{session_id:r,type:C.Talk},o)}}}function oe(e,i){return e.map((t,n)=>n===0?i?{index:n,timestamp:t.timestamp,bytesReceived:t.bytesReceived-i.bytesReceived,packetsReceived:t.packetsReceived-i.packetsReceived,packetsLost:t.packetsLost-i.packetsLost,jitter:t.jitter,frameWidth:t.frameWidth,frameHeight:t.frameHeight,framesPerSecond:t.framesPerSecond}:{index:n,timestamp:t.timestamp,bytesReceived:t.bytesReceived,packetsReceived:t.packetsReceived,packetsLost:t.packetsLost,jitter:t.jitter,frameWidth:t.frameWidth,frameHeight:t.frameHeight,framesPerSecond:t.framesPerSecond}:{index:n,timestamp:t.timestamp,bytesReceived:t.bytesReceived-e[n-1].bytesReceived,packetsReceived:t.packetsReceived-e[n-1].packetsReceived,packetsLost:t.packetsLost-e[n-1].packetsLost,jitter:t.jitter,frameWidth:t.frameWidth,frameHeight:t.frameHeight,framesPerSecond:t.framesPerSecond})}let Y=!1;const $=(e,i)=>Y&&console.log(e,i),ce=(window.RTCPeerConnection||window.webkitRTCPeerConnection||window.mozRTCPeerConnection).bind(window);function de(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 ge(e,i){let t=[],n=0,a=0,r=0,o;return setInterval(()=>{e.getStats().then(g=>{g.forEach(l=>{if(l.type==="inbound-rtp"&&l.kind==="video"){if(a=t.length-1,l&&t[a]){const y=l.bytesReceived,p=t[a].bytesReceived,M=o;let v;if(o=y-p>0,r=o?0:++r,M!==o)if(o)n=t.length,i==null||i(O.Start,v);else{const P=t.slice(n),L=n===0?void 0:t[n-1];v=oe(P,L),v=v.sort((_,s)=>s.packetsLost-_.packetsLost).slice(0,5)}!o&&r===2&&(i==null||i(O.Stop,v))}t.push(l)}})})},500)}async function le(e,i,{debug:t=!1,callbacks:n,auth:a,analytics:r,baseURL:o=F}){Y=t;let d;const{startConnection:g,sendStreamRequest:l,close:y,createStream:p,addIceCandidate:M}=i.videoType===C.Clip?re(a,o,e):se(a,o,e),{id:v,offer:P,ice_servers:L,session_id:_}=await p(i),s=new ce({iceServers:L}),u=s.createDataChannel("JanusDataChannel");if(!_)throw new Error("Could not create session_id");const m=ge(s,n.onVideoStateChange);s.onicecandidate=c=>{$("peerConnection.onicecandidate",c),c.candidate&&c.candidate.sdpMid&&c.candidate.sdpMLineIndex!==null?M(v,{candidate:c.candidate.candidate,sdpMid:c.candidate.sdpMid,sdpMLineIndex:c.candidate.sdpMLineIndex},_):M(v,{candidate:null},_)},s.oniceconnectionstatechange=()=>{var h;$("peerConnection.oniceconnectionstatechange => "+s.iceConnectionState);const c=de(s.iceConnectionState);c===k.Connected?d=setTimeout(()=>{var S;(S=n.onConnectionStateChange)==null||S.call(n,k.Connected)},5e3):(clearTimeout(d),(h=n.onConnectionStateChange)==null||h.call(n,c))},s.ontrack=c=>{var h;$("peerConnection.ontrack",c),(h=n.onSrcObjectReady)==null||h.call(n,c.streams[0])},u.onmessage=c=>{var h;if(u.readyState==="open"){const[S,I]=c.data.split(":");S===E.StreamReady&&(clearTimeout(d),(h=n.onConnectionStateChange)==null||h.call(n,k.Connected))}},await s.setRemoteDescription(P),$("set remote description OK");const f=await s.createAnswer();return $("create answer OK"),await s.setLocalDescription(f),$("set local description OK"),await g(v,f,_),$("start connection OK"),{speak(c){return l(v,_,c)},async disconnect(){var c,h;if(v){s&&(s.close(),s.oniceconnectionstatechange=null,s.onnegotiationneeded=null,s.onicecandidate=null,s.ontrack=null);try{await y(v,_).catch(S=>{})}catch(S){$("Error on close stream connection",S)}(c=n.onConnectionStateChange)==null||c.call(n,k.New),(h=n.onVideoStateChange)==null||h.call(n,O.Stop),clearInterval(m)}},sessionId:_,streamId:v}}function me(e){const i={token:e.token||"testKey",distinct_id:e.distinctId||V(),isEnabled:e.isEnabled??!0,agentId:e.agent.id,owner_id:e.agent.owner_id??""};return{...i,getRandom:()=>Math.random().toString(16).slice(2),track(t,n){if(!this.isEnabled)return Promise.reject("MixPanel analytics is disabled on creation");const a={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({data:JSON.stringify([{event:t,properties:{...n,...i,time:Date.now(),$insert_id:this.getRandom(),origin:window.location.href,"Screen Height":window.screen.height||window.innerWidth,"Screen Width":window.screen.width||window.innerHeight,"User Agent":navigator.userAgent}}])})};return fetch("https://api-js.mixpanel.com/track/?verbose=1&ip=1",a).then(r=>r.json()).catch(r=>console.error(r))}}}function ue(e){var n,a,r,o,d;const i=()=>/Mobi|Android/i.test(navigator.userAgent)?"Mobile":"Desktop";return{$os:`${(()=>{const g=navigator.platform;return g.toLowerCase().includes("win")?"Windows":g.toLowerCase().includes("mac")?"Mac OS X":g.toLowerCase().includes("linux")?"Linux":"Unknown"})()}`,isMobile:`${i()=="Mobile"}`,browser:navigator.userAgent,origin:window.location.origin,agentType:(n=e.presenter)==null?void 0:n.type,agentVoice:{voiceId:(r=(a=e.presenter)==null?void 0:a.voice)==null?void 0:r.voice_id,provider:(d=(o=e.presenter)==null?void 0:o.voice)==null?void 0:d.type}}}function he(e){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");return{videoType:C.Talk,source_url:e.presenter.source_url,stream_warmup:!0,...e.presenter.stitch&&{stream_resolution:1080}}}function Z(e,i,t,n,a){return new Promise(async(r,o)=>{let d=a;const g=await le(e.id,he(e),{...i,analytics:n,callbacks:{...i.callbacks,onConnectionStateChange:async l=>{var y,p;if(l===k.Connected)try{d||(d=await t.newChat(e.id),n.track("agent-chat",{event:"created",chat_id:d.id,agent_id:e.id})),g&&r({chat:d,streamingManager:g})}catch(M){console.error(M),o("Cannot create new chat")}else l===k.Fail&&o(new Error("Cannot create connection"));(p=(y=i.callbacks).onConnectionStateChange)==null||p.call(y,l)},onVideoStateChange(l,y){var p,M;(M=(p=i.callbacks).onVideoStateChange)==null||M.call(p,l,y)}}}).catch(o)})}function we(e,i,t){return Q(i,t||F).getById(e)}function j(e){let i="";if(e.greetings&&e.greetings.length>0){const t=Math.floor(Math.random()*e.greetings.length);i=e.greetings[t]}else i=`Hi! I'm ${e.preview_name}, welcome to agents. How can I help you?`;return[{content:i,id:K(),role:"assistant",created_at:new Date().toISOString()}]}async function fe(e,i){var P,L,_;const t={messages:[],chatMode:i.mode||R.Functional};let n=-1;const a=i.wsURL||G,r=i.baseURL||F,o=i.mixpanelKey||ee,d=Q(i.auth,r),g=await d.getById(e);t.messages=j(g),(L=(P=i.callbacks).onNewMessage)==null||L.call(P,t.messages);const l=me({token:o,agent:g,...i});l.track("agent-sdk",{event:"loaded",...ue(g)});const y={onMessage:(s,u)=>{var m,f;if("content"in u){const{content:c}=u,h=t.messages[t.messages.length-1];(h==null?void 0:h.role)==="assistant"&&(n<t.messages.length&&(h.content=s===N.Partial?h.content+c:c),s===N.Answer&&(n=t.messages.length)),s===N.Answer&&l.track("agent-message-received",{messages:t.messages.length}),(f=(m=i.callbacks).onNewMessage)==null||f.call(m,t.messages)}else if([E.StreamVideoCreated,E.StreamVideoDone,E.StreamVideoError,E.StreamVideoRejected].includes(s)){const c=s.split("/")[1];l.track("agent-video",{...u,event:c})}}};async function p(){var f,c,h,S,I;const s=await X(i.auth,a,y),{streamingManager:u,chat:m}=await Z(g,i,d,l,t.chat);n=-1,t.messages.length===0&&(t.messages=j(g),(c=(f=i.callbacks).onNewMessage)==null||c.call(f,t.messages)),m!=null&&m.id&&m.id!==((h=t.chat)==null?void 0:h.id)&&((I=(S=i.callbacks).onNewChat)==null||I.call(S,m==null?void 0:m.id)),t.streamingManager=u,t.socketManager=s,t.chat=m,v(R.Functional),l.track("agent-chat",{event:"connect",chatId:m.id,agentId:g.id})}async function M(){var s,u,m,f,c;(s=t.socketManager)==null||s.disconnect(),await((u=t.streamingManager)==null?void 0:u.disconnect()),delete t.streamingManager,delete t.socketManager,t.messages=j(g),(f=(m=i.callbacks).onNewMessage)==null||f.call(m,t.messages),l.track("agent-chat",{event:"disconnect",chatId:(c=t.chat)==null?void 0:c.id,agentId:g.id})}async function v(s){var u,m;s!==t.chatMode&&(l.track("agent-mode-change",{mode:s}),t.chatMode=s,t.chatMode!==R.Functional&&await M(),(m=(u=i.callbacks).onModeChange)==null||m.call(u,s))}return{agent:g,starterMessages:((_=g.knowledge)==null?void 0:_.starter_message)||[],connect:p,disconnect:M,changeMode:v,async reconnect(){var f,c;if(!t.chat)return p();(f=t.socketManager)==null||f.disconnect(),await((c=t.streamingManager)==null?void 0:c.disconnect());const s=await X(i.auth,a,y),{streamingManager:u,chat:m}=await Z(g,i,d,l,t.chat);t.streamingManager=u,t.socketManager=s,v(R.Functional),l.track("agent-chat",{event:"reconnect",chatId:m.id,agentId:g.id})},async chat(s,u=!1){var m,f,c,h,S,I;try{const b=Date.now();if(s.length>=800)throw new Error("Message cannot be more than 800 characters");if(s.length===0)throw new Error("Message cannot be empty");if(t.chatMode===R.Maintenance)throw new Error("Chat is in maintenance mode");if(![R.TextOnly,R.Playground].includes(t.chatMode)){if(!t.streamingManager)throw new Error("Streaming manager is not initialized");if(!t.chat)throw new Error("Chat is not initialized")}t.messages.push({id:K(),role:"user",content:s,created_at:new Date(b).toISOString()}),(f=(m=i.callbacks).onNewMessage)==null||f.call(m,t.messages),t.chat||(t.chat=await d.newChat(g.id));const A=await d.chat(g.id,t.chat.id,{sessionId:(c=t.streamingManager)==null?void 0:c.sessionId,streamId:(h=t.streamingManager)==null?void 0:h.streamId,messages:t.messages,chatMode:t.chatMode,append_chat:u});return l.track("agent-message-send",{event:"success",messages:t.messages.length+1}),t.messages.push({id:K(),role:"assistant",content:A.result||"",created_at:new Date().toISOString(),matches:A.matches}),A.result&&(l.track("agent-message-received",{latency:Date.now()-b,messages:t.messages.length}),(I=(S=i.callbacks).onNewMessage)==null||I.call(S,t.messages)),A}catch(b){throw l.track("agent-message-send",{event:"error",messages:t.messages.length}),b}},rate(s,u,m){var h,S,I,b;const f=t.messages.find(A=>A.id===s);if(t.chat){if(!f)throw new Error("Message not found")}else throw new Error("Chat is not initialized");const c=((h=f.matches)==null?void 0:h.map(A=>[A.document_id,A.id]))??[];return l.track("agent-rate",{event:m?"update":"create",thumb:u===1?"up":"down",knowledge_id:((S=g.knowledge)==null?void 0:S.id)??"",matches:c,score:u}),m?d.updateRating(g.id,t.chat.id,m,{knowledge_id:((I=g.knowledge)==null?void 0:I.id)??"",message_id:s,matches:c,score:u}):d.createRating(g.id,t.chat.id,{knowledge_id:((b=g.knowledge)==null?void 0:b.id)??"",message_id:s,matches:c,score:u})},deleteRate(s){var u;if(!t.chat)throw new Error("Chat is not initialized");return l.track("agent-rate-delete",{type:"text",chat_id:(u=t.chat)==null?void 0:u.id,id:s}),d.deleteRating(g.id,t.chat.id,s)},speak(s){if(!t.streamingManager)throw new Error("Streaming manager is not initialized");function u(){if(g.presenter){if(s.type==="text")return{type:"text",provider:s.provider?s.provider:g.presenter.voice,input:s.input,ssml:s.ssml||!1};if(s.type==="audio")return{type:"audio",audio_url:s.audio_url}}else throw new Error("Presenter is not initialized");throw new Error("Invalid payload")}const m=u();return l.track("agent-speak",m),t.streamingManager.speak({script:m})}}}w.ChatMode=R,w.ChatProgress=N,w.ConnectionState=k,w.DocumentType=U,w.KnowledgeType=x,w.PlanGroup=z,w.Providers=B,w.RateState=D,w.StreamEvents=E,w.StreamingState=O,w.Subject=H,w.UserPlan=T,w.VideoType=C,w.VoiceAccess=J,w.createAgentManager=fe,w.getAgent=we,Object.defineProperty(w,Symbol.toStringTag,{value:"Module"})});
|
|
1
|
+
(function(w,T){typeof exports=="object"&&typeof module<"u"?T(exports):typeof define=="function"&&define.amd?define(["exports"],T):(w=typeof globalThis<"u"?globalThis:w||self,T(w.index={}))})(this,function(w){"use strict";var T=(e=>(e.TRIAL="trial",e.BASIC="basic",e.ENTERPRISE="enterprise",e.LITE="lite",e.ADVANCED="advanced",e))(T||{}),H=(e=>(e.TRIAL="deid-trial",e.PRO="deid-pro",e.ENTERPRISE="deid-enterprise",e.LITE="deid-lite",e.ADVANCED="deid-advanced",e.BUILD="deid-api-build",e.LAUNCH="deid-api-launch",e.SCALE="deid-api-scale",e))(H||{}),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||{}),L=(e=>(e.Embed="embed",e.Query="query",e.Partial="partial",e.Answer="answer",e.Complete="done",e))(L||{}),U=(e=>(e.KnowledgeProcessing="knowledge/processing",e.KnowledgeIndexing="knowledge/indexing",e.KnowledgeFailed="knowledge/error",e.KnowledgeDone="knowledge/done",e))(U||{}),B=(e=>(e.Knowledge="knowledge",e.Document="document",e.Record="record",e))(B||{}),J=(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))(J||{}),y=(e=>(e.Clip="clip",e.Talk="talk",e))(y||{}),N=(e=>(e.Start="START",e.Stop="STOP",e))(N||{}),b=(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))(b||{}),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||{}),V=(e=>(e.Amazon="amazon",e.Microsoft="microsoft",e.Afflorithmics="afflorithmics",e.Elevenlabs="elevenlabs",e))(V||{}),q=(e=>(e.Public="public",e.Premium="premium",e.Private="private",e))(q||{});const O="https://api.d-id.com",te="wss://notifications.d-id.com",ne="79f81a83a67430be2bc0fd61042b8faa",K=()=>Math.random().toString(16).slice(2);function Q(){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 ae=K();function X(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}.${Q()}_${ae}`;throw new Error(`Unknown auth type: ${e}`)}function j(e,i=O){const t=async(n,a)=>{const r=await fetch(i+(n!=null&&n.startsWith("/")?n:`/${n}`),{...a,headers:{...a==null?void 0:a.headers,Authorization:X(e),"Content-Type":"application/json"}});if(!r.ok){let o=await r.text().catch(()=>"Failed to fetch");throw new Error(o)}return r.json()};return{get(n,a){return t(n,{...a,method:"GET"})},post(n,a,r){return t(n,{...r,body:JSON.stringify(a),method:"POST"})},delete(n,a,r){return t(n,{...r,body:JSON.stringify(a),method:"DELETE"})},patch(n,a,r){return t(n,{...r,body:JSON.stringify(a),method:"PATCH"})}}}function Y(e,i=O){const t=j(e,`${i}/agents`);return{create(n,a){return t.post("/",n,a)},getAgents(n,a){return t.get(`/${n?`?tag=${n}`:""}`,a).then(r=>r??[])},getById(n,a){return t.get(`/${n}`,a)},delete(n,a){return t.delete(`/${n}`,void 0,a)},update(n,a,r){return t.patch(`/${n}`,a,r)},newChat(n,a){return t.post(`/${n}/chat`,void 0,a)},chat(n,a,r,o){return t.post(`/${n}/chat/${a}`,r,o)},createRating(n,a,r,o){return t.post(`/${n}/chat/${a}/ratings`,r,o)},updateRating(n,a,r,o,c){return t.patch(`/${n}/chat/${a}/ratings/${r}`,o,c)},deleteRating(n,a,r,o){return t.delete(`/${n}/chat/${a}/ratings/${r}`,o)}}}const ie=e=>new Promise(i=>setTimeout(i,e));function re(e){return new Promise((i,t)=>{const{callbacks:n,host:a,auth:r}=e,{onMessage:o=null,onOpen:c=null,onClose:g=null,onError:u=null}=n||{},f=new WebSocket(`${a}?authorization=${X(r)}`);f.onmessage=o,f.onclose=g,f.onerror=v=>{console.error(v),u==null||u("Websocket failed to connect",v),t(v)},f.onopen=v=>{c==null||c(v),i(f)}})}async function se(e){const{retries:i=1}=e;let t=null;for(let n=0;(t==null?void 0:t.readyState)!==WebSocket.OPEN;n++)try{t=await re(e)}catch(a){if(n===i)throw a;await ie(n*500)}return t}async function Z(e,i,t){const n=t!=null&&t.onMessage?[t.onMessage]:[],a=await se({auth:e,host:i,callbacks:{onError:t==null?void 0:t.onError,onMessage:r=>{const o=JSON.parse(r.data);n.forEach(c=>c(o.event,o))}}});return{socket:a,disconnect:()=>a.close(),subscribeToEvents:r=>n.push(r)}}function oe(e,i,t){const n=j(e,`${i}/agents/${t}`);return{createStream(a){return n.post("/streams",{driver_id:a.driver_id,presenter_id:a.presenter_id,compatibility_mode:a.compatibility_mode,stream_warmup:a.stream_warmup,type:y.Clip})},startConnection(a,r,o){return n.post(`/streams/${a}/sdp`,{session_id:o,answer:r,type:y.Clip})},addIceCandidate(a,r,o){return n.post(`/streams/${a}/ice`,{session_id:o,...r,type:y.Clip})},sendStreamRequest(a,r,o){return n.post(`/streams/${a}`,{session_id:r,...o,type:y.Clip})},close(a,r){return n.delete(`/streams/${a}`,{session_id:r,type:y.Clip})}}}function ce(e,i,t){const n=j(e,`${i}/agents/${t}`);return{createStream(a,r){return n.post("/streams",{source_url:a.source_url,driver_url:a.driver_url,face:a.face,config:a.config,compatibility_mode:a.compatibility_mode,stream_warmup:a.stream_warmup,stream_resolution:a.stream_resolution,type:y.Talk},r)},startConnection(a,r,o,c){return n.post(`/streams/${a}/sdp`,{session_id:o,answer:r,type:y.Talk},c)},addIceCandidate(a,r,o,c){return n.post(`/streams/${a}/ice`,{session_id:o,...r,type:y.Talk},c)},sendStreamRequest(a,r,o,c){return n.post(`/streams/${a}`,{session_id:r,...o,type:y.Talk},c)},close(a,r,o){return n.delete(`/streams/${a}`,{session_id:r,type:y.Talk},o)}}}function de(e,i){return e.map((t,n)=>n===0?i?{index:n,timestamp:t.timestamp,bytesReceived:t.bytesReceived-i.bytesReceived,packetsReceived:t.packetsReceived-i.packetsReceived,packetsLost:t.packetsLost-i.packetsLost,jitter:t.jitter,frameWidth:t.frameWidth,frameHeight:t.frameHeight,framesPerSecond:t.framesPerSecond}:{index:n,timestamp:t.timestamp,bytesReceived:t.bytesReceived,packetsReceived:t.packetsReceived,packetsLost:t.packetsLost,jitter:t.jitter,frameWidth:t.frameWidth,frameHeight:t.frameHeight,framesPerSecond:t.framesPerSecond}:{index:n,timestamp:t.timestamp,bytesReceived:t.bytesReceived-e[n-1].bytesReceived,packetsReceived:t.packetsReceived-e[n-1].packetsReceived,packetsLost:t.packetsLost-e[n-1].packetsLost,jitter:t.jitter,frameWidth:t.frameWidth,frameHeight:t.frameHeight,framesPerSecond:t.framesPerSecond})}let G=!1;const E=(e,i)=>G&&console.log(e,i),ge=(window.RTCPeerConnection||window.webkitRTCPeerConnection||window.mozRTCPeerConnection).bind(window);function le(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 me(e,i,t){let n=[],a=0,r=0,o=0,c;return setInterval(()=>{e.getStats().then(u=>{u.forEach(f=>{if(f.type==="inbound-rtp"&&f.kind==="video"){if(r=n.length-1,f&&n[r]){const v=f.bytesReceived,M=n[r].bytesReceived,S=c;let R;if(c=v-M>0,o=c?0:++o,S!==c)if(c)a=n.length,i==null||i(N.Start,R);else{const P=n.slice(a),_=a===0?void 0:n[a-1];R=de(P,_),R=R.sort((s,m)=>m.packetsLost-s.packetsLost).slice(0,5)}!c&&o===1&&t.track("agent-video",{event:"stats",rtc:R}),!c&&o===2&&(i==null||i(N.Stop,R))}n.push(f)}})})},500)}async function ue(e,i,{debug:t=!1,callbacks:n,auth:a,analytics:r,baseURL:o=O}){G=t;let c;const{startConnection:g,sendStreamRequest:u,close:f,createStream:v,addIceCandidate:M}=i.videoType===y.Clip?oe(a,o,e):ce(a,o,e),{id:S,offer:R,ice_servers:P,session_id:_}=await v(i),s=new ge({iceServers:P}),m=s.createDataChannel("JanusDataChannel");if(!_)throw new Error("Could not create session_id");const l=me(s,n.onVideoStateChange,r);s.onicecandidate=d=>{E("peerConnection.onicecandidate",d),d.candidate&&d.candidate.sdpMid&&d.candidate.sdpMLineIndex!==null?M(S,{candidate:d.candidate.candidate,sdpMid:d.candidate.sdpMid,sdpMLineIndex:d.candidate.sdpMLineIndex},_):M(S,{candidate:null},_)},s.oniceconnectionstatechange=()=>{var h;E("peerConnection.oniceconnectionstatechange => "+s.iceConnectionState);const d=le(s.iceConnectionState);d===k.Connected?c=setTimeout(()=>{var C;(C=n.onConnectionStateChange)==null||C.call(n,k.Connected)},5e3):(clearTimeout(c),(h=n.onConnectionStateChange)==null||h.call(n,d))},s.ontrack=d=>{var h;E("peerConnection.ontrack",d),(h=n.onSrcObjectReady)==null||h.call(n,d.streams[0])},m.onmessage=d=>{var h;if(m.readyState==="open"){const[C,A]=d.data.split(":");C===b.StreamReady&&(clearTimeout(c),(h=n.onConnectionStateChange)==null||h.call(n,k.Connected))}},await s.setRemoteDescription(R),E("set remote description OK");const p=await s.createAnswer();return E("create answer OK"),await s.setLocalDescription(p),E("set local description OK"),await g(S,p,_),E("start connection OK"),{speak(d){return u(S,_,d)},async disconnect(){var d,h;if(S){s&&(s.close(),s.oniceconnectionstatechange=null,s.onnegotiationneeded=null,s.onicecandidate=null,s.ontrack=null);try{await f(S,_).catch(C=>{})}catch(C){E("Error on close stream connection",C)}(d=n.onConnectionStateChange)==null||d.call(n,k.New),(h=n.onVideoStateChange)==null||h.call(n,N.Stop),clearInterval(l)}},sessionId:_,streamId:S}}function he(e){const i={token:e.token||"testKey",distinct_id:e.distinctId||Q(),isEnabled:e.isEnabled??!0,agentId:e.agent.id,owner_id:e.agent.owner_id??""};return{...i,getRandom:()=>Math.random().toString(16).slice(2),track(t,n){if(!this.isEnabled)return Promise.reject("MixPanel analytics is disabled on creation");const a={method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({data:JSON.stringify([{event:t,properties:{...n,...i,time:Date.now(),$insert_id:this.getRandom(),origin:window.location.href,"Screen Height":window.screen.height||window.innerWidth,"Screen Width":window.screen.width||window.innerHeight,"User Agent":navigator.userAgent}}])})};return fetch("https://api-js.mixpanel.com/track/?verbose=1&ip=1",a).then(r=>r.json()).catch(r=>console.error(r))}}}function we(e){var n,a,r,o,c;const i=()=>/Mobi|Android/i.test(navigator.userAgent)?"Mobile":"Desktop";return{$os:`${(()=>{const g=navigator.platform;return g.toLowerCase().includes("win")?"Windows":g.toLowerCase().includes("mac")?"Mac OS X":g.toLowerCase().includes("linux")?"Linux":"Unknown"})()}`,isMobile:`${i()=="Mobile"}`,browser:navigator.userAgent,origin:window.location.origin,agentType:(n=e.presenter)==null?void 0:n.type,agentVoice:{voiceId:(r=(a=e.presenter)==null?void 0:a.voice)==null?void 0:r.voice_id,provider:(c=(o=e.presenter)==null?void 0:o.voice)==null?void 0:c.type}}}function fe(e){if(e.presenter){if(e.presenter.type===y.Clip)return{videoType:y.Clip,driver_id:e.presenter.driver_id,presenter_id:e.presenter.presenter_id,stream_warmup:!0}}else throw new Error("Presenter is not initialized");return{videoType:y.Talk,source_url:e.presenter.source_url,stream_warmup:!0}}function ee(e,i,t,n,a){return new Promise(async(r,o)=>{let c=a;const g=await ue(e.id,fe(e),{...i,analytics:n,callbacks:{...i.callbacks,onConnectionStateChange:async u=>{var f,v;if(u===k.Connected)try{c||(c=await t.newChat(e.id),n.track("agent-chat",{event:"created",chat_id:c.id,agent_id:e.id})),g&&r({chat:c,streamingManager:g})}catch(M){console.error(M),o("Cannot create new chat")}else u===k.Fail&&o(new Error("Cannot create connection"));(v=(f=i.callbacks).onConnectionStateChange)==null||v.call(f,u)},onVideoStateChange(u,f){var v,M;(M=(v=i.callbacks).onVideoStateChange)==null||M.call(v,u,f)}}}).catch(o)})}function pe(e,i,t){return Y(i,t||O).getById(e)}function z(e){let i="";if(e.greetings&&e.greetings.length>0){const t=Math.floor(Math.random()*e.greetings.length);i=e.greetings[t]}else i=`Hi! I'm ${e.preview_name}, welcome to agents. How can I help you?`;return[{content:i,id:K(),role:"assistant",created_at:new Date().toISOString()}]}async function ve(e,i){var R,P,_;const t={messages:[],chatMode:i.mode||I.Functional};let n=-1;const a=i.wsURL||te,r=i.baseURL||O,o=i.mixpanelKey||ne,c=Y(i.auth,r),g=await c.getById(e);t.messages=z(g),(P=(R=i.callbacks).onNewMessage)==null||P.call(R,t.messages);const u=he({token:o,agent:g,...i});u.track("agent-sdk",{event:"loaded",...we(g)});const f={onMessage:(s,m)=>{var l,p;if("content"in m){const{content:d}=m,h=t.messages[t.messages.length-1];(h==null?void 0:h.role)==="assistant"&&(n<t.messages.length&&(h.content=s===L.Partial?h.content+d:d),s===L.Answer&&(n=t.messages.length)),s===L.Answer&&u.track("agent-message-received",{messages:t.messages.length}),(p=(l=i.callbacks).onNewMessage)==null||p.call(l,t.messages)}else if([b.StreamVideoCreated,b.StreamVideoDone,b.StreamVideoError,b.StreamVideoRejected].includes(s)){const d=s.split("/")[1];u.track("agent-video",{...m,event:d})}}};async function v(){var p,d,h,C,A;const s=await Z(i.auth,a,f),{streamingManager:m,chat:l}=await ee(g,i,c,u,t.chat);n=-1,t.messages.length===0&&(t.messages=z(g),(d=(p=i.callbacks).onNewMessage)==null||d.call(p,t.messages)),l!=null&&l.id&&l.id!==((h=t.chat)==null?void 0:h.id)&&((A=(C=i.callbacks).onNewChat)==null||A.call(C,l==null?void 0:l.id)),t.streamingManager=m,t.socketManager=s,t.chat=l,S(I.Functional),u.track("agent-chat",{event:"connect",chatId:l.id,agentId:g.id})}async function M(){var s,m,l,p,d;(s=t.socketManager)==null||s.disconnect(),await((m=t.streamingManager)==null?void 0:m.disconnect()),delete t.streamingManager,delete t.socketManager,t.messages=z(g),(p=(l=i.callbacks).onNewMessage)==null||p.call(l,t.messages),u.track("agent-chat",{event:"disconnect",chatId:(d=t.chat)==null?void 0:d.id,agentId:g.id})}async function S(s){var m,l;s!==t.chatMode&&(u.track("agent-mode-change",{mode:s}),t.chatMode=s,t.chatMode!==I.Functional&&await M(),(l=(m=i.callbacks).onModeChange)==null||l.call(m,s))}return{agent:g,starterMessages:((_=g.knowledge)==null?void 0:_.starter_message)||[],connect:v,disconnect:M,changeMode:S,async reconnect(){var p,d;if(!t.chat)return v();(p=t.socketManager)==null||p.disconnect(),await((d=t.streamingManager)==null?void 0:d.disconnect());const s=await Z(i.auth,a,f),{streamingManager:m,chat:l}=await ee(g,i,c,u,t.chat);t.streamingManager=m,t.socketManager=s,S(I.Functional),u.track("agent-chat",{event:"reconnect",chatId:l.id,agentId:g.id})},async chat(s,m=!1){var p,d,h,C,A,F;const l=K();try{const $=Date.now();if(s.length>=800)throw new Error("Message cannot be more than 800 characters");if(s.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)throw new Error("Streaming manager is not initialized");if(!t.chat)throw new Error("Chat is not initialized")}t.messages.push({id:K(),role:"user",content:s,created_at:new Date($).toISOString()}),(d=(p=i.callbacks).onNewMessage)==null||d.call(p,t.messages),t.chat||(t.chat=await c.newChat(g.id));const D={id:l,role:"assistant",content:"",created_at:new Date().toISOString(),matches:[]};t.messages.push(D);const W=await c.chat(g.id,t.chat.id,{sessionId:(h=t.streamingManager)==null?void 0:h.sessionId,streamId:(C=t.streamingManager)==null?void 0:C.streamId,messages:t.messages.slice(0,-1),chatMode:t.chatMode,append_chat:m});return u.track("agent-message-send",{event:"success",messages:t.messages.length+1}),W.result&&(D.content=W.result,D.matches=W.matches,u.track("agent-message-received",{latency:Date.now()-$,messages:t.messages.length}),(F=(A=i.callbacks).onNewMessage)==null||F.call(A,t.messages)),W}catch($){throw t.messages[t.messages.length-1].id===l&&t.messages.pop(),u.track("agent-message-send",{event:"error",messages:t.messages.length}),$}},rate(s,m,l){var h,C,A,F;const p=t.messages.find($=>$.id===s);if(t.chat){if(!p)throw new Error("Message not found")}else throw new Error("Chat is not initialized");const d=((h=p.matches)==null?void 0:h.map($=>[$.document_id,$.id]))??[];return u.track("agent-rate",{event:l?"update":"create",thumb:m===1?"up":"down",knowledge_id:((C=g.knowledge)==null?void 0:C.id)??"",matches:d,score:m}),l?c.updateRating(g.id,t.chat.id,l,{knowledge_id:((A=g.knowledge)==null?void 0:A.id)??"",message_id:s,matches:d,score:m}):c.createRating(g.id,t.chat.id,{knowledge_id:((F=g.knowledge)==null?void 0:F.id)??"",message_id:s,matches:d,score:m})},deleteRate(s){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:s}),c.deleteRating(g.id,t.chat.id,s)},speak(s){if(!t.streamingManager)throw new Error("Streaming manager is not initialized");function m(){if(g.presenter){if(s.type==="text")return{type:"text",provider:s.provider?s.provider:g.presenter.voice,input:s.input,ssml:s.ssml||!1};if(s.type==="audio")return{type:"audio",audio_url:s.audio_url}}else throw new Error("Presenter is not initialized");throw new Error("Invalid payload")}const l=m();return u.track("agent-speak",l),t.streamingManager.speak({script:l})}}}w.ChatMode=I,w.ChatProgress=L,w.ConnectionState=k,w.DocumentType=J,w.KnowledgeType=B,w.PlanGroup=H,w.Providers=V,w.RateState=x,w.StreamEvents=b,w.StreamingState=N,w.Subject=U,w.UserPlan=T,w.VideoType=y,w.VoiceAccess=q,w.createAgentManager=ve,w.getAgent=pe,Object.defineProperty(w,Symbol.toStringTag,{value:"Module"})});
|