@d-id/client-sdk 1.2.6 → 1.2.7

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.
@@ -0,0 +1,440 @@
1
+ import { c as Ne, C as B, S as l, a as Ue, b as je, A as p, d as xe, l as le, e as Oe, t as Be, f as w, g as j, h as Je, i as ze, j as P, n as Qe } from "./index-BXPWkNzW.js";
2
+ function qe(C, M, f, i) {
3
+ const b = Ne(C, `${M}/v2/agents/${f}`, i);
4
+ return {
5
+ async createStream(h) {
6
+ return b.post("/sessions", h);
7
+ }
8
+ };
9
+ }
10
+ const We = {
11
+ [l.ChatAnswer]: B.Answer,
12
+ [l.ChatPartial]: B.Partial
13
+ }, pe = 2e4;
14
+ async function He() {
15
+ try {
16
+ return await import("./livekit-client.esm-DypJ_fOm.js");
17
+ } catch {
18
+ throw new Error(
19
+ "LiveKit client is required for this streaming manager. Please install it using: npm install livekit-client"
20
+ );
21
+ }
22
+ }
23
+ const Ge = {
24
+ excellent: j.Strong,
25
+ good: j.Strong,
26
+ poor: j.Weak,
27
+ lost: j.Unknown,
28
+ unknown: j.Unknown
29
+ }, V = (C = "Stream Error") => new Oe(C);
30
+ function he(C, M, f) {
31
+ var i, b;
32
+ throw M("Failed to connect to LiveKit room:", C), (i = f.onConnectionStateChange) == null || i.call(f, w.Fail, "internal:init-error"), (b = f.onError) == null || b.call(f, C, { sessionId: "" }), C;
33
+ }
34
+ async function Ye(C, M, f) {
35
+ var ae;
36
+ const i = Ue(f.debug || !1, "LiveKitStreamingManager"), { Room: b, RoomEvent: h, ConnectionState: I, Track: G } = await He(), { callbacks: e, auth: ge, baseURL: fe, analytics: X } = f;
37
+ let a = null, A = !1;
38
+ const Y = je.Fluent;
39
+ let R = null;
40
+ const L = { isPublishing: !1, publication: null }, J = { isPublishing: !1, publication: null };
41
+ let g = null, m = null, x = null, D = !1;
42
+ a = new b({
43
+ adaptiveStream: !1,
44
+ // Must be false to use mediaStreamTrack directly
45
+ dynacast: !0
46
+ });
47
+ let E = null, y = p.Idle, k = !0;
48
+ const F = /* @__PURE__ */ new Set(), me = qe(ge, fe || xe, C, e.onError);
49
+ let S, $, K, Z = !0;
50
+ try {
51
+ const n = await me.createStream({
52
+ transport: M.transport,
53
+ chat_persist: M.chat_persist ?? !0,
54
+ verbose: f.verbose ?? !1
55
+ }), { id: t, session_token: o, session_url: r, interrupt_enabled: s } = n;
56
+ (ae = e.onStreamCreated) == null || ae.call(e, { session_id: t, stream_id: t, agent_id: C }), S = t, $ = o, K = r, Z = s ?? !0, await a.prepareConnection(K, $);
57
+ } catch (n) {
58
+ he(n, i, e);
59
+ }
60
+ if (!K || !$ || !S)
61
+ return Promise.reject(new Error("Failed to initialize LiveKit stream"));
62
+ a.on(h.ConnectionStateChanged, Se).on(h.ConnectionQualityChanged, Te).on(h.ParticipantConnected, ye).on(h.ParticipantDisconnected, ve).on(h.TrackSubscribed, Ae).on(h.TrackUnsubscribed, Ee).on(h.DataReceived, Me).on(h.MediaDevicesError, be).on(h.TranscriptionReceived, Ce).on(h.EncryptionError, Ie).on(h.TrackSubscriptionFailed, ke);
63
+ function Ce(n, t) {
64
+ t != null && t.isLocal && (le.update(), y === p.Talking && (y = p.Idle));
65
+ }
66
+ try {
67
+ await a.connect(K, $), i("LiveKit room joined successfully"), E = setTimeout(() => {
68
+ var t;
69
+ i(
70
+ `Track subscription timeout - no track subscribed within ${pe / 1e3} seconds after connect`
71
+ ), E = null;
72
+ const n = V("Track subscription timeout");
73
+ X.track("connectivity-error", {
74
+ error: Be(n),
75
+ sessionId: S
76
+ }), (t = e.onError) == null || t.call(e, n, { sessionId: S }), H("internal:track-subscription-timeout");
77
+ }, pe);
78
+ } catch (n) {
79
+ he(n, i, e);
80
+ }
81
+ X.enrich({
82
+ "stream-type": Y
83
+ });
84
+ function Se(n) {
85
+ var t, o, r, s;
86
+ switch (i("Connection state changed:", n), n) {
87
+ case I.Connecting:
88
+ i("CALLBACK: onConnectionStateChange(Connecting)"), (t = e.onConnectionStateChange) == null || t.call(e, w.Connecting, "livekit:connecting");
89
+ break;
90
+ case I.Connected:
91
+ i("LiveKit room connected successfully"), A = !0;
92
+ break;
93
+ case I.Disconnected:
94
+ i("LiveKit room disconnected"), A = !1, D = !1, L.publication = null, J.publication = null, (o = e.onConnectionStateChange) == null || o.call(e, w.Disconnected, "livekit:disconnected");
95
+ break;
96
+ case I.Reconnecting:
97
+ i("LiveKit room reconnecting..."), (r = e.onConnectionStateChange) == null || r.call(e, w.Connecting, "livekit:reconnecting");
98
+ break;
99
+ case I.SignalReconnecting:
100
+ i("LiveKit room signal reconnecting..."), (s = e.onConnectionStateChange) == null || s.call(e, w.Connecting, "livekit:signal-reconnecting");
101
+ break;
102
+ }
103
+ }
104
+ function Te(n, t) {
105
+ var o;
106
+ i("Connection quality:", n), t != null && t.isLocal && ((o = e.onConnectivityStateChange) == null || o.call(e, Ge[n]));
107
+ }
108
+ function ye(n) {
109
+ i("Participant connected:", n.identity);
110
+ }
111
+ function ve(n) {
112
+ i("Participant disconnected:", n.identity), H("livekit:participant-disconnected");
113
+ }
114
+ function we() {
115
+ var n;
116
+ x !== P.Start && (i("CALLBACK: onVideoStateChange(Start)"), x = P.Start, (n = e.onVideoStateChange) == null || n.call(e, P.Start));
117
+ }
118
+ function ee(n) {
119
+ var t;
120
+ x !== P.Stop && (i("CALLBACK: onVideoStateChange(Stop)"), x = P.Stop, (t = e.onVideoStateChange) == null || t.call(e, P.Stop, n));
121
+ }
122
+ function Ae(n, t, o) {
123
+ var s, d, u;
124
+ i(`Track subscribed: ${n.kind} from ${o.identity}`);
125
+ const r = n.mediaStreamTrack;
126
+ if (!r) {
127
+ i(`No mediaStreamTrack available for ${n.kind}`);
128
+ return;
129
+ }
130
+ R ? (R.addTrack(r), i(`Added ${n.kind} track to shared MediaStream`)) : (R = new MediaStream([r]), i(`Created shared MediaStream with ${n.kind} track`)), n.kind === "audio" && (m = ze(
131
+ () => n.getRTCStatsReport(),
132
+ ({ sttLatency: c, serviceLatency: T }) => {
133
+ var ce, se, de;
134
+ const N = le.get(!0);
135
+ let U = 0;
136
+ if (c) {
137
+ const ue = ((se = (ce = g == null ? void 0 : g.getReport()) == null ? void 0 : ce.webRTCStats) == null ? void 0 : se.avgRtt) ?? 0;
138
+ U = ue > 0 ? Math.round(ue * 1e3) : 0;
139
+ }
140
+ const _ = N > 0 ? N + (c ?? 0) + U : void 0, v = _ !== void 0 && T !== void 0 ? _ - T : void 0;
141
+ (de = e.onFirstAudioDetected) == null || de.call(e, { latency: _, networkLatency: v });
142
+ }
143
+ )), n.kind === "video" && ((s = e.onStreamReady) == null || s.call(e), i("CALLBACK: onSrcObjectReady"), (d = e.onSrcObjectReady) == null || d.call(e, R), D || (D = !0, i("CALLBACK: onConnectionStateChange(Connected)"), (u = e.onConnectionStateChange) == null || u.call(e, w.Connected, "livekit:track-subscribed")), g = Je(
144
+ () => n.getRTCStatsReport(),
145
+ () => A,
146
+ Qe,
147
+ (c, T) => {
148
+ i(`Video state change: ${c}`), c === P.Start ? (E && (clearTimeout(E), E = null, i("Track subscription timeout cleared")), we()) : c === P.Stop && ee(T);
149
+ }
150
+ ), g.start());
151
+ }
152
+ function Ee(n, t, o) {
153
+ i(`Track unsubscribed: ${n.kind} from ${o.identity}`), n.kind === "audio" && (m == null || m.destroy(), m = null), n.kind === "video" && (ee(g == null ? void 0 : g.getReport()), g == null || g.stop(), g = null);
154
+ }
155
+ function ne(n, t) {
156
+ var r;
157
+ const o = We[n];
158
+ o && ((r = e.onMessage) == null || r.call(e, o, { event: o, ...t }));
159
+ }
160
+ function z(n, t) {
161
+ var o, r, s, d, u;
162
+ if (n === l.ToolCallStarted) {
163
+ const c = t;
164
+ k = c.interruptible !== !1, (o = e.onInterruptibleChange) == null || o.call(e, k), F.add(c.call_id), y = p.ToolActive, (r = e.onAgentActivityStateChange) == null || r.call(e, p.ToolActive), (s = e.onToolEvent) == null || s.call(e, l.ToolCallStarted, c);
165
+ return;
166
+ }
167
+ if (n === l.ToolCallDone) {
168
+ const c = t;
169
+ te(c.call_id), (d = e.onToolEvent) == null || d.call(e, l.ToolCallDone, c);
170
+ return;
171
+ }
172
+ if (n === l.ToolCallError) {
173
+ const c = t;
174
+ te(c.call_id), (u = e.onToolEvent) == null || u.call(e, l.ToolCallError, c);
175
+ }
176
+ }
177
+ function te(n) {
178
+ var t;
179
+ F.delete(n), F.size === 0 && y === p.ToolActive && (y = p.Idle, (t = e.onAgentActivityStateChange) == null || t.call(e, p.Idle));
180
+ }
181
+ function Pe(n, t) {
182
+ var o, r, s, d, u, c;
183
+ if (k = ((o = t.metadata) == null ? void 0 : o.interruptible) !== !1, (r = e.onInterruptibleChange) == null || r.call(e, k), n === l.StreamVideoCreated) {
184
+ y = p.Talking, (s = e.onAgentActivityStateChange) == null || s.call(e, p.Talking), m == null || m.arm({
185
+ sttLatency: (d = t == null ? void 0 : t.stt) == null ? void 0 : d.latency,
186
+ serviceLatency: t == null ? void 0 : t.serviceLatency
187
+ });
188
+ return;
189
+ }
190
+ if (F.size > 0) {
191
+ y !== p.ToolActive && (y = p.ToolActive, (u = e.onAgentActivityStateChange) == null || u.call(e, p.ToolActive));
192
+ return;
193
+ }
194
+ k && (y = p.Idle, (c = e.onAgentActivityStateChange) == null || c.call(e, p.Idle));
195
+ }
196
+ function O(n, t) {
197
+ var d, u, c, T;
198
+ const o = ((u = (d = g == null ? void 0 : g.getReport()) == null ? void 0 : d.webRTCStats) == null ? void 0 : u.avgRtt) ?? 0, r = o > 0 ? Math.round(o / 2 * 1e3) : 0, s = { ...t, downstreamNetworkLatency: r };
199
+ f.debug && ((c = t == null ? void 0 : t.metadata) != null && c.sentiment) && (s.sentiment = {
200
+ id: t.metadata.sentiment.id,
201
+ name: t.metadata.sentiment.sentiment
202
+ }), (T = e.onMessage) == null || T.call(e, n, s), Pe(n, t);
203
+ }
204
+ function Re(n, t) {
205
+ var o;
206
+ (o = e.onMessage) == null || o.call(e, B.Transcribe, { event: B.Transcribe, ...t }), queueMicrotask(() => {
207
+ var r;
208
+ (r = e.onAgentActivityStateChange) == null || r.call(e, p.Loading);
209
+ });
210
+ }
211
+ const Le = {
212
+ [l.ChatAnswer]: ne,
213
+ [l.ChatPartial]: ne,
214
+ [l.ToolCallStarted]: z,
215
+ [l.ToolCallDone]: z,
216
+ [l.ToolCallError]: z,
217
+ [l.StreamVideoCreated]: O,
218
+ [l.StreamVideoDone]: O,
219
+ [l.StreamVideoError]: O,
220
+ [l.StreamVideoRejected]: O,
221
+ [l.ChatAudioTranscribed]: Re
222
+ };
223
+ function Me(n, t, o, r) {
224
+ const s = new TextDecoder().decode(n);
225
+ try {
226
+ const d = JSON.parse(s), u = r || d.subject;
227
+ if (i("Data received:", { subject: u, data: d }), !u) return;
228
+ const c = Le[u];
229
+ c == null || c(u, d);
230
+ } catch (d) {
231
+ i("Failed to parse data channel message:", d);
232
+ }
233
+ }
234
+ function be(n) {
235
+ var t;
236
+ i("Media devices error:", n), (t = e.onError) == null || t.call(e, V(), { sessionId: S });
237
+ }
238
+ function Ie(n) {
239
+ var t;
240
+ i("Encryption error:", n), (t = e.onError) == null || t.call(e, V(), { sessionId: S });
241
+ }
242
+ function ke(n, t, o) {
243
+ i("Track subscription failed:", { trackSid: n, participant: t, reason: o });
244
+ }
245
+ function $e(n, t, o) {
246
+ for (const [r, s] of o)
247
+ if (s.source === t && s.track) {
248
+ const d = s.track.mediaStreamTrack;
249
+ if (d === n || (d == null ? void 0 : d.id) === n.id)
250
+ return s;
251
+ }
252
+ return null;
253
+ }
254
+ async function ie(n, t, o, r, s, d) {
255
+ var N, U, _;
256
+ if (!A || !a)
257
+ throw i(`Room is not connected, cannot publish ${r} stream`), new Error("Room is not connected");
258
+ if (n.isPublishing) {
259
+ i(`${r} publish already in progress, skipping`);
260
+ return;
261
+ }
262
+ const u = o(t);
263
+ if (u.length === 0)
264
+ throw new Error(`No ${r} track found in the provided MediaStream`);
265
+ const c = u[0], T = $e(c, r, s());
266
+ if (T) {
267
+ i(`${r} track is already published, skipping`, {
268
+ trackId: c.id,
269
+ publishedTrackId: (U = (N = T.track) == null ? void 0 : N.mediaStreamTrack) == null ? void 0 : U.id
270
+ }), n.publication = T;
271
+ return;
272
+ }
273
+ if ((_ = n.publication) != null && _.track) {
274
+ const v = n.publication.track.mediaStreamTrack;
275
+ v !== c && (v == null ? void 0 : v.id) !== c.id && (i(`Unpublishing existing ${r} track before publishing new one`), await d());
276
+ }
277
+ i(`Publishing ${r} track from provided MediaStream`, { trackId: c.id }), n.isPublishing = !0;
278
+ try {
279
+ n.publication = await a.localParticipant.publishTrack(c, { source: r }), i(`${r} track published successfully`, { trackSid: n.publication.trackSid });
280
+ } catch (v) {
281
+ throw i(`Failed to publish ${r} track:`, v), v;
282
+ } finally {
283
+ n.isPublishing = !1;
284
+ }
285
+ }
286
+ async function oe(n, t) {
287
+ if (!(!n.publication || !n.publication.track))
288
+ try {
289
+ a && (await a.localParticipant.unpublishTrack(n.publication.track, !1), i(`${t} track unpublished`));
290
+ } catch (o) {
291
+ i(`Error unpublishing ${t} track:`, o);
292
+ } finally {
293
+ n.publication = null;
294
+ }
295
+ }
296
+ async function Ke(n) {
297
+ return ie(
298
+ L,
299
+ n,
300
+ (t) => t.getAudioTracks(),
301
+ G.Source.Microphone,
302
+ () => a.localParticipant.audioTrackPublications,
303
+ Q
304
+ );
305
+ }
306
+ async function Q() {
307
+ return oe(L, "Microphone");
308
+ }
309
+ async function _e(n) {
310
+ if (!A || !a)
311
+ throw i("Cannot replace microphone track: room is not connected"), new Error("Room is not connected");
312
+ if (n.kind !== "audio")
313
+ throw i("Cannot replace microphone track: not an audio track", { kind: n.kind }), new Error("Microphone track must be an audio track");
314
+ if (L.isPublishing)
315
+ throw i("Cannot replace microphone track: publish in progress"), new Error("Microphone publish in progress");
316
+ const t = L.publication;
317
+ if (!t || !t.track)
318
+ throw i("Cannot replace microphone track: no publication to replace"), new Error("No microphone publication to replace");
319
+ try {
320
+ L.isPublishing = !0, await t.track.replaceTrack(n), i("Microphone track replaced", { trackId: n.id, trackSid: t.trackSid });
321
+ } finally {
322
+ L.isPublishing = !1;
323
+ }
324
+ }
325
+ async function Ve(n) {
326
+ return ie(
327
+ J,
328
+ n,
329
+ (t) => t.getVideoTracks(),
330
+ G.Source.Camera,
331
+ () => a.localParticipant.videoTrackPublications,
332
+ q
333
+ );
334
+ }
335
+ async function q() {
336
+ return oe(J, "Camera");
337
+ }
338
+ function De() {
339
+ R && (R.getTracks().forEach((n) => n.stop()), R = null);
340
+ }
341
+ async function W(n, t) {
342
+ var o, r;
343
+ if (!A || !a) {
344
+ i("Room is not connected for sending messages"), (o = e.onError) == null || o.call(e, V(), {
345
+ sessionId: S
346
+ });
347
+ return;
348
+ }
349
+ try {
350
+ await a.localParticipant.sendText(n, { topic: t }), i("Message sent successfully:", n);
351
+ } catch (s) {
352
+ i("Failed to send message:", s), (r = e.onError) == null || r.call(e, V(), { sessionId: S });
353
+ }
354
+ }
355
+ async function re(n) {
356
+ var t;
357
+ try {
358
+ const r = JSON.parse(n).topic;
359
+ return W("", r);
360
+ } catch (o) {
361
+ i("Failed to send data channel message:", o), (t = e.onError) == null || t.call(e, V(), { sessionId: S });
362
+ }
363
+ }
364
+ function Fe(n) {
365
+ return W(
366
+ n,
367
+ "lk.chat"
368
+ /* Chat */
369
+ );
370
+ }
371
+ async function H(n) {
372
+ var t, o;
373
+ E && (clearTimeout(E), E = null), m == null || m.destroy(), m = null, a && ((t = e.onConnectionStateChange) == null || t.call(e, w.Disconnecting, n), await Promise.all([Q(), q()]), await a.disconnect()), De(), A = !1, D = !1, F.clear(), (o = e.onAgentActivityStateChange) == null || o.call(e, p.Idle), y = p.Idle;
374
+ }
375
+ return {
376
+ speak(n) {
377
+ const t = typeof n == "string" ? n : JSON.stringify(n);
378
+ return W(
379
+ t,
380
+ "did.speak"
381
+ /* Speak */
382
+ );
383
+ },
384
+ disconnect: () => H("user:disconnect"),
385
+ async reconnect() {
386
+ var n, t;
387
+ if ((a == null ? void 0 : a.state) === I.Connected) {
388
+ i("Room is already connected");
389
+ return;
390
+ }
391
+ if (!a || !K || !$)
392
+ throw i("Cannot reconnect: missing room, URL or token"), new Error("Cannot reconnect: session not available");
393
+ i("Reconnecting to LiveKit room, state:", a.state), D = !1, (n = e.onConnectionStateChange) == null || n.call(e, w.Connecting, "user:reconnect");
394
+ try {
395
+ if (await a.connect(K, $), i("Room reconnected"), A = !0, a.remoteParticipants.size === 0) {
396
+ if (i("Waiting for agent to join..."), !await new Promise((r) => {
397
+ const s = setTimeout(() => {
398
+ a == null || a.off(h.ParticipantConnected, d), r(!1);
399
+ }, 5e3), d = () => {
400
+ clearTimeout(s), a == null || a.off(h.ParticipantConnected, d), r(!0);
401
+ };
402
+ a == null || a.on(h.ParticipantConnected, d);
403
+ }))
404
+ throw i("Agent did not join within timeout"), await a.disconnect(), new Error("Agent did not rejoin the room");
405
+ i("Agent joined, reconnection successful");
406
+ }
407
+ } catch (o) {
408
+ throw i("Failed to reconnect:", o), (t = e.onConnectionStateChange) == null || t.call(e, w.Fail, "user:reconnect-failed"), o;
409
+ }
410
+ },
411
+ sendDataChannelMessage: re,
412
+ sendTextMessage: Fe,
413
+ publishMicrophoneStream: Ke,
414
+ unpublishMicrophoneStream: Q,
415
+ replaceMicrophoneTrack: _e,
416
+ publishCameraStream: Ve,
417
+ unpublishCameraStream: q,
418
+ interrupt(n) {
419
+ n !== "text" && re(JSON.stringify({
420
+ topic: "did.interrupt"
421
+ /* Interrupt */
422
+ }));
423
+ },
424
+ registerRpcMethod(n, t) {
425
+ a == null || a.registerRpcMethod(n, t);
426
+ },
427
+ unregisterRpcMethod(n) {
428
+ a == null || a.unregisterRpcMethod(n);
429
+ },
430
+ sessionId: S,
431
+ streamId: S,
432
+ streamType: Y,
433
+ interruptAvailable: Z,
434
+ isInterruptible: k
435
+ };
436
+ }
437
+ export {
438
+ Ye as createLiveKitStreamingManager,
439
+ he as handleInitError
440
+ };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@d-id/client-sdk",
3
3
  "private": false,
4
- "version": "1.2.6",
4
+ "version": "1.2.7",
5
5
  "type": "module",
6
6
  "description": "d-id client sdk",
7
7
  "repository": {