@d-id/client-sdk 1.1.11 → 1.1.12-staging.49

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.
Files changed (62) hide show
  1. package/dist/index.js +546 -670
  2. package/dist/index.umd.cjs +1 -1
  3. package/dist/src/api/agents.d.ts +1 -0
  4. package/dist/src/api/apiClient.d.ts +4 -3
  5. package/dist/src/api/knowledge.d.ts +1 -0
  6. package/dist/src/api/streams/streamApi.d.ts +1 -0
  7. package/dist/src/api/streams/streamsApiV2.d.ts +5 -0
  8. package/dist/src/auth/get-auth-header.d.ts +1 -0
  9. package/dist/src/errors/chat/chat-creation-failed.d.ts +1 -0
  10. package/dist/src/errors/chat/chat-mode-downgraded.d.ts +1 -0
  11. package/dist/src/errors/validation-error.d.ts +1 -0
  12. package/dist/src/errors/ws-error.d.ts +1 -0
  13. package/dist/src/services/agent-manager/connect-to-manager.d.ts +1 -0
  14. package/dist/src/services/agent-manager/connect-to-manager.test.d.ts +1 -0
  15. package/dist/src/services/agent-manager/index.d.ts +1 -0
  16. package/dist/src/services/agent-manager/index.test.d.ts +1 -0
  17. package/dist/src/services/analytics/mixpanel.d.ts +1 -0
  18. package/dist/src/services/chat/index.d.ts +2 -2
  19. package/dist/src/services/chat/intial-messages.d.ts +1 -0
  20. package/dist/src/services/interrupt/index.d.ts +1 -0
  21. package/dist/src/services/socket-manager/index.d.ts +1 -0
  22. package/dist/src/services/socket-manager/message-queue.d.ts +1 -0
  23. package/dist/src/services/streaming-manager/advanced.test.d.ts +5 -0
  24. package/dist/src/services/streaming-manager/business-flows.test.d.ts +5 -0
  25. package/dist/src/services/streaming-manager/common.d.ts +43 -0
  26. package/dist/src/services/streaming-manager/disconnect.test.d.ts +5 -0
  27. package/dist/src/services/streaming-manager/edge-cases.test.d.ts +5 -0
  28. package/dist/src/services/streaming-manager/factory.d.ts +3 -0
  29. package/dist/src/services/streaming-manager/factory.test.d.ts +1 -0
  30. package/dist/src/services/streaming-manager/index.d.ts +3 -27
  31. package/dist/src/services/streaming-manager/livekit-manager.d.ts +5 -0
  32. package/dist/src/services/streaming-manager/stats/poll.d.ts +1 -1
  33. package/dist/src/services/streaming-manager/stats/report.d.ts +1 -0
  34. package/dist/src/services/streaming-manager/webrtc-core.test.d.ts +5 -0
  35. package/dist/src/services/streaming-manager/webrtc-manager.d.ts +12 -0
  36. package/dist/src/services/streaming-manager/webrtc-utils.test.d.ts +5 -0
  37. package/dist/src/test-utils/factories/agent-manager.factory.d.ts +3 -0
  38. package/dist/src/test-utils/factories/agent.factory.d.ts +4 -0
  39. package/dist/src/test-utils/factories/agents-api.factory.d.ts +1 -0
  40. package/dist/src/test-utils/factories/analytics.factory.d.ts +1 -0
  41. package/dist/src/test-utils/factories/chat.factory.d.ts +1 -0
  42. package/dist/src/test-utils/factories/index.d.ts +8 -0
  43. package/dist/src/test-utils/factories/socket-manager.factory.d.ts +1 -0
  44. package/dist/src/test-utils/factories/stream-api.factory.d.ts +1 -0
  45. package/dist/src/test-utils/factories/streaming-manager.factory.d.ts +4 -0
  46. package/dist/src/types/entities/agents/agent.d.ts +1 -0
  47. package/dist/src/types/entities/agents/manager.d.ts +7 -1
  48. package/dist/src/types/entities/agents/presenter.d.ts +6 -2
  49. package/dist/src/types/entities/knowledge/document.d.ts +1 -0
  50. package/dist/src/types/entities/knowledge/record.d.ts +1 -0
  51. package/dist/src/types/entities/video.d.ts +2 -1
  52. package/dist/src/types/stream/api/clip.d.ts +1 -0
  53. package/dist/src/types/stream/api/talk.d.ts +1 -0
  54. package/dist/src/types/stream/index.d.ts +1 -0
  55. package/dist/src/types/stream/rtc.d.ts +1 -0
  56. package/dist/src/types/stream/stream.d.ts +1 -0
  57. package/dist/src/types/stream/streams-v2.d.ts +12 -0
  58. package/dist/src/types/stream-script.d.ts +1 -0
  59. package/dist/src/utils/agent.d.ts +2 -1
  60. package/dist/src/utils/analytics.d.ts +3 -2
  61. package/dist/src/utils/chat.d.ts +1 -0
  62. package/package.json +21 -2
package/dist/index.js CHANGED
@@ -1,23 +1,16 @@
1
- var ye = Object.defineProperty;
2
- var ve = (e, t, n) => t in e ? ye(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
3
- var Y = (e, t, n) => (ve(e, typeof t != "symbol" ? t + "" : t, n), n);
4
- class G extends Error {
5
- constructor({
6
- kind: n,
7
- description: r,
8
- error: s
9
- }) {
10
- super(JSON.stringify({
11
- kind: n,
12
- description: r
13
- }));
14
- Y(this, "kind");
15
- Y(this, "description");
16
- Y(this, "error");
1
+ var ke = Object.defineProperty;
2
+ var De = (e, t, n) => t in e ? ke(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
3
+ var Z = (e, t, n) => De(e, typeof t != "symbol" ? t + "" : t, n);
4
+ class te extends Error {
5
+ constructor({ kind: n, description: r, error: s }) {
6
+ super(JSON.stringify({ kind: n, description: r }));
7
+ Z(this, "kind");
8
+ Z(this, "description");
9
+ Z(this, "error");
17
10
  this.kind = n, this.description = r, this.error = s;
18
11
  }
19
12
  }
20
- class ke extends G {
13
+ class Ce extends te {
21
14
  constructor(t, n) {
22
15
  super({
23
16
  kind: "ChatCreationFailed",
@@ -25,34 +18,25 @@ class ke extends G {
25
18
  });
26
19
  }
27
20
  }
28
- class De extends G {
21
+ class Re extends te {
29
22
  constructor(t) {
30
- super({
31
- kind: "ChatModeDowngraded",
32
- description: `Chat mode downgraded to ${t}`
33
- });
23
+ super({ kind: "ChatModeDowngraded", description: `Chat mode downgraded to ${t}` });
34
24
  }
35
25
  }
36
- class H extends G {
26
+ class H extends te {
37
27
  constructor(n, r) {
38
- super({
39
- kind: "ValidationError",
40
- description: n
41
- });
42
- Y(this, "key");
28
+ super({ kind: "ValidationError", description: n });
29
+ Z(this, "key");
43
30
  this.key = r;
44
31
  }
45
32
  }
46
- class Ce extends G {
33
+ class Se extends te {
47
34
  constructor(t) {
48
- super({
49
- kind: "WSError",
50
- description: t
51
- });
35
+ super({ kind: "WSError", description: t });
52
36
  }
53
37
  }
54
- var Re = /* @__PURE__ */ ((e) => (e.TRIAL = "trial", e.BASIC = "basic", e.ENTERPRISE = "enterprise", e.LITE = "lite", e.ADVANCED = "advanced", e))(Re || {}), Se = /* @__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))(Se || {}), Ie = /* @__PURE__ */ ((e) => (e.Created = "created", e.Started = "started", e.Done = "done", e.Error = "error", e.Rejected = "rejected", e.Ready = "ready", e))(Ie || {}), Ee = /* @__PURE__ */ ((e) => (e.Unrated = "Unrated", e.Positive = "Positive", e.Negative = "Negative", e))(Ee || {}), M = /* @__PURE__ */ ((e) => (e.Functional = "Functional", e.TextOnly = "TextOnly", e.Maintenance = "Maintenance", e.Playground = "Playground", e.DirectPlayback = "DirectPlayback", e.Off = "Off", e))(M || {}), q = /* @__PURE__ */ ((e) => (e.Embed = "embed", e.Query = "query", e.Partial = "partial", e.Answer = "answer", e.Complete = "done", e))(q || {}), Me = /* @__PURE__ */ ((e) => (e.KnowledgeProcessing = "knowledge/processing", e.KnowledgeIndexing = "knowledge/indexing", e.KnowledgeFailed = "knowledge/error", e.KnowledgeDone = "knowledge/done", e))(Me || {}), _e = /* @__PURE__ */ ((e) => (e.Knowledge = "knowledge", e.Document = "document", e.Record = "record", e))(_e || {}), Te = /* @__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))(Te || {}), je = /* @__PURE__ */ ((e) => (e.Clip = "clip", e.Talk = "talk", e))(je || {});
55
- const It = (e) => {
38
+ var Ie = /* @__PURE__ */ ((e) => (e.TRIAL = "trial", e.BASIC = "basic", e.ENTERPRISE = "enterprise", e.LITE = "lite", e.ADVANCED = "advanced", e))(Ie || {}), Ee = /* @__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))(Ee || {}), Me = /* @__PURE__ */ ((e) => (e.Created = "created", e.Started = "started", e.Done = "done", e.Error = "error", e.Rejected = "rejected", e.Ready = "ready", e))(Me || {}), _e = /* @__PURE__ */ ((e) => (e.Unrated = "Unrated", e.Positive = "Positive", e.Negative = "Negative", e))(_e || {}), E = /* @__PURE__ */ ((e) => (e.Functional = "Functional", e.TextOnly = "TextOnly", e.Maintenance = "Maintenance", e.Playground = "Playground", e.DirectPlayback = "DirectPlayback", e.Off = "Off", e))(E || {}), q = /* @__PURE__ */ ((e) => (e.Embed = "embed", e.Query = "query", e.Partial = "partial", e.Answer = "answer", e.Complete = "done", e))(q || {}), Te = /* @__PURE__ */ ((e) => (e.KnowledgeProcessing = "knowledge/processing", e.KnowledgeIndexing = "knowledge/indexing", e.KnowledgeFailed = "knowledge/error", e.KnowledgeDone = "knowledge/done", e))(Te || {}), je = /* @__PURE__ */ ((e) => (e.Knowledge = "knowledge", e.Document = "document", e.Record = "record", e))(je || {}), Ae = /* @__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))(Ae || {}), de = /* @__PURE__ */ ((e) => (e.Clip = "clip", e.Talk = "talk", e.Expressive = "expressive", e))(de || {});
39
+ const jt = (e) => {
56
40
  switch (e) {
57
41
  case "clip":
58
42
  return "clip";
@@ -62,12 +46,12 @@ const It = (e) => {
62
46
  throw new Error(`Unknown video type: ${e}`);
63
47
  }
64
48
  };
65
- var h = /* @__PURE__ */ ((e) => (e.Start = "START", e.Stop = "STOP", e))(h || {}), Q = /* @__PURE__ */ ((e) => (e.Strong = "STRONG", e.Weak = "WEAK", e.Unknown = "UNKNOWN", e))(Q || {}), O = /* @__PURE__ */ ((e) => (e.Idle = "IDLE", e.Talking = "TALKING", e))(O || {}), A = /* @__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.StreamInterrupt = "stream/interrupt", e.StreamVideoCreated = "stream-video/started", e.StreamVideoDone = "stream-video/done", e.StreamVideoError = "stream-video/error", e.StreamVideoRejected = "stream-video/rejected", e))(A || {}), I = /* @__PURE__ */ ((e) => (e.New = "new", e.Fail = "fail", e.Connected = "connected", e.Connecting = "connecting", e.Closed = "closed", e.Completed = "completed", e.Disconnected = "disconnected", e))(I || {}), W = /* @__PURE__ */ ((e) => (e.Legacy = "legacy", e.Fluent = "fluent", e))(W || {}), Pe = /* @__PURE__ */ ((e) => (e.Amazon = "amazon", e.Microsoft = "microsoft", e.Afflorithmics = "afflorithmics", e.Elevenlabs = "elevenlabs", e))(Pe || {}), be = /* @__PURE__ */ ((e) => (e.Public = "public", e.Premium = "premium", e.Private = "private", e))(be || {});
66
- const Ae = 45 * 1e3, Be = "X-Playground-Chat", Z = "https://api.d-id.com", Le = "wss://notifications.d-id.com", $e = "79f81a83a67430be2bc0fd61042b8faa", oe = (e) => new Promise((t) => setTimeout(t, e)), V = (e = 16) => {
49
+ var w = /* @__PURE__ */ ((e) => (e.Start = "START", e.Stop = "STOP", e))(w || {}), G = /* @__PURE__ */ ((e) => (e.Strong = "STRONG", e.Weak = "WEAK", e.Unknown = "UNKNOWN", e))(G || {}), O = /* @__PURE__ */ ((e) => (e.Idle = "IDLE", e.Talking = "TALKING", e))(O || {}), P = /* @__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.StreamInterrupt = "stream/interrupt", e.StreamVideoCreated = "stream-video/started", e.StreamVideoDone = "stream-video/done", e.StreamVideoError = "stream-video/error", e.StreamVideoRejected = "stream-video/rejected", e))(P || {}), R = /* @__PURE__ */ ((e) => (e.New = "new", e.Fail = "fail", e.Connected = "connected", e.Connecting = "connecting", e.Closed = "closed", e.Completed = "completed", e.Disconnected = "disconnected", e))(R || {}), J = /* @__PURE__ */ ((e) => (e.Legacy = "legacy", e.Fluent = "fluent", e))(J || {}), be = /* @__PURE__ */ ((e) => (e.Livekit = "livekit", e))(be || {}), Pe = /* @__PURE__ */ ((e) => (e.Amazon = "amazon", e.Microsoft = "microsoft", e.Afflorithmics = "afflorithmics", e.Elevenlabs = "elevenlabs", e))(Pe || {}), Le = /* @__PURE__ */ ((e) => (e.Public = "public", e.Premium = "premium", e.Private = "private", e))(Le || {});
50
+ const Be = 45 * 1e3, $e = "X-Playground-Chat", ee = "https://api.d-id.com", xe = "wss://notifications.d-id.com", ze = "79f81a83a67430be2bc0fd61042b8faa", le = (e) => new Promise((t) => setTimeout(t, e)), V = (e = 16) => {
67
51
  const t = new Uint8Array(e);
68
52
  return window.crypto.getRandomValues(t), Array.from(t, (n) => n.toString(16).padStart(2, "0")).join("").slice(0, 13);
69
- }, ze = (e) => [M.TextOnly, M.Playground, M.Maintenance].includes(e), ce = (e) => e && [M.DirectPlayback, M.Off].includes(e);
70
- function Fe(e, t) {
53
+ }, Fe = (e) => [E.TextOnly, E.Playground, E.Maintenance].includes(e), ue = (e) => e && [E.DirectPlayback, E.Off].includes(e);
54
+ function Ne(e, t) {
71
55
  let n;
72
56
  return {
73
57
  promise: new Promise((s, o) => {
@@ -76,7 +60,7 @@ function Fe(e, t) {
76
60
  clear: () => clearTimeout(n)
77
61
  };
78
62
  }
79
- async function te(e, t) {
63
+ async function ne(e, t) {
80
64
  const n = {
81
65
  limit: (t == null ? void 0 : t.limit) ?? 3,
82
66
  delayMs: (t == null ? void 0 : t.delayMs) ?? 0,
@@ -91,19 +75,16 @@ async function te(e, t) {
91
75
  try {
92
76
  if (!n.timeout)
93
77
  return await e();
94
- const {
95
- promise: o,
96
- clear: c
97
- } = Fe(n.timeout, n.timeoutErrorMessage), a = e().finally(c);
78
+ const { promise: o, clear: c } = Ne(n.timeout, n.timeoutErrorMessage), a = e().finally(c);
98
79
  return await Promise.race([a, o]);
99
80
  } catch (o) {
100
81
  if (r = o, !n.shouldRetryFn(o) || s >= n.limit)
101
82
  throw o;
102
- await oe(n.delayMs), n.onRetry(o);
83
+ await le(n.delayMs), n.onRetry(o);
103
84
  }
104
85
  throw r;
105
86
  }
106
- function de() {
87
+ function fe() {
107
88
  let e = window.localStorage.getItem("did_external_key_id");
108
89
  if (!e) {
109
90
  let t = V();
@@ -111,78 +92,58 @@ function de() {
111
92
  }
112
93
  return e;
113
94
  }
114
- let Ne = V();
115
- function le(e) {
95
+ let Je = V();
96
+ function me(e) {
116
97
  if (e.type === "bearer")
117
98
  return `Bearer ${e.token}`;
118
99
  if (e.type === "basic")
119
100
  return `Basic ${btoa(`${e.username}:${e.password}`)}`;
120
101
  if (e.type === "key")
121
- return `Client-Key ${e.clientKey}.${de()}_${Ne}`;
102
+ return `Client-Key ${e.clientKey}.${fe()}_${Je}`;
122
103
  throw new Error(`Unknown auth type: ${e}`);
123
104
  }
124
- const xe = (e) => te(e, {
105
+ const We = (e) => ne(e, {
125
106
  limit: 3,
126
107
  delayMs: 1e3,
127
108
  timeout: 0,
128
109
  shouldRetryFn: (t) => t.status === 429
129
110
  });
130
- function ue(e, t = Z, n) {
111
+ function ge(e, t = ee, n) {
131
112
  const r = async (s, o) => {
132
- const {
133
- skipErrorHandler: c,
134
- ...a
135
- } = o || {}, i = await xe(() => fetch(t + (s != null && s.startsWith("/") ? s : `/${s}`), {
136
- ...a,
137
- headers: {
138
- ...a.headers,
139
- Authorization: le(e),
140
- "Content-Type": "application/json"
141
- }
142
- }));
113
+ const { skipErrorHandler: c, ...a } = o || {}, i = await We(
114
+ () => fetch(t + (s != null && s.startsWith("/") ? s : `/${s}`), {
115
+ ...a,
116
+ headers: {
117
+ ...a.headers,
118
+ Authorization: me(e),
119
+ "Content-Type": "application/json"
120
+ }
121
+ })
122
+ );
143
123
  if (!i.ok) {
144
124
  let d = await i.text().catch(() => `Failed to fetch with status ${i.status}`);
145
125
  const l = new Error(d);
146
- throw n && !c && n(l, {
147
- url: s,
148
- options: a,
149
- headers: i.headers
150
- }), l;
126
+ throw n && !c && n(l, { url: s, options: a, headers: i.headers }), l;
151
127
  }
152
128
  return i.json();
153
129
  };
154
130
  return {
155
131
  get(s, o) {
156
- return r(s, {
157
- ...o,
158
- method: "GET"
159
- });
132
+ return r(s, { ...o, method: "GET" });
160
133
  },
161
134
  post(s, o, c) {
162
- return r(s, {
163
- ...c,
164
- body: JSON.stringify(o),
165
- method: "POST"
166
- });
135
+ return r(s, { ...c, body: JSON.stringify(o), method: "POST" });
167
136
  },
168
137
  delete(s, o, c) {
169
- return r(s, {
170
- ...c,
171
- body: JSON.stringify(o),
172
- method: "DELETE"
173
- });
138
+ return r(s, { ...c, body: JSON.stringify(o), method: "DELETE" });
174
139
  },
175
140
  patch(s, o, c) {
176
- return r(s, {
177
- ...c,
178
- body: JSON.stringify(o),
179
- method: "PATCH"
180
- });
141
+ return r(s, { ...c, body: JSON.stringify(o), method: "PATCH" });
181
142
  }
182
143
  };
183
144
  }
184
- function fe(e, t = Z, n) {
185
- const r = ue(e, `${t}/agents`, n);
145
+ function he(e, t = ee, n) {
146
+ const r = ge(e, `${t}/agents`, n);
186
147
  return {
187
148
  create(s, o) {
188
149
  return r.post("/", s, o);
@@ -219,8 +180,8 @@ function fe(e, t = Z, n) {
219
180
  }
220
181
  };
221
182
  }
222
- const me = (e) => e.type === "clip" && e.presenter_id.startsWith("v2_") ? "clip_v2" : e.type;
223
- function Je(e) {
183
+ const we = (e) => e.type === "clip" && e.presenter_id.startsWith("v2_") ? "clip_v2" : e.type;
184
+ function Ue(e) {
224
185
  var s, o, c, a;
225
186
  const t = () => /Mobi|Android/i.test(navigator.userAgent) ? "Mobile" : "Desktop", n = () => {
226
187
  const i = navigator.platform;
@@ -231,18 +192,18 @@ function Je(e) {
231
192
  isMobile: `${t() == "Mobile"}`,
232
193
  browser: navigator.userAgent,
233
194
  origin: window.location.origin,
234
- agentType: me(r),
195
+ agentType: we(r),
235
196
  agentVoice: {
236
197
  voiceId: (o = (s = e.presenter) == null ? void 0 : s.voice) == null ? void 0 : o.voice_id,
237
198
  provider: (a = (c = e.presenter) == null ? void 0 : c.voice) == null ? void 0 : a.type
238
199
  }
239
200
  };
240
201
  }
241
- function We(e) {
202
+ function Ke(e) {
242
203
  var n, r, s, o, c, a;
243
204
  const t = (n = e.llm) == null ? void 0 : n.prompt_customization;
244
205
  return {
245
- agentType: me(e.presenter),
206
+ agentType: we(e.presenter),
246
207
  owner_id: e.owner_id ?? "",
247
208
  promptVersion: (r = e.llm) == null ? void 0 : r.prompt_version,
248
209
  behavior: {
@@ -258,113 +219,90 @@ function We(e) {
258
219
  agentId: e.id,
259
220
  access: e.access,
260
221
  name: e.preview_name,
261
- ...e.access === "public" ? {
262
- from: "agent-template"
263
- } : {}
222
+ ...e.access === "public" ? { from: "agent-template" } : {}
264
223
  };
265
224
  }
266
- const Ue = (e) => e.reduce((t, n) => t + n, 0), ae = (e) => Ue(e) / e.length;
267
- function Ke(e, t, n) {
225
+ const He = (e) => e.reduce((t, n) => t + n, 0), se = (e) => He(e) / e.length;
226
+ function qe(e, t, n) {
268
227
  var i, d, l;
269
- const {
270
- event: r,
271
- ...s
272
- } = e, {
273
- template: o
274
- } = (t == null ? void 0 : t.llm) || {}, {
275
- language: c
276
- } = ((i = t == null ? void 0 : t.presenter) == null ? void 0 : i.voice) || {};
228
+ const { event: r, ...s } = e, { template: o } = (t == null ? void 0 : t.llm) || {}, { language: c } = ((i = t == null ? void 0 : t.presenter) == null ? void 0 : i.voice) || {};
277
229
  return {
278
230
  ...s,
279
- llm: {
280
- ...s.llm,
281
- template: o
282
- },
283
- script: {
284
- ...s.script,
285
- provider: {
286
- ...(d = s == null ? void 0 : s.script) == null ? void 0 : d.provider,
287
- language: c
288
- }
289
- },
231
+ llm: { ...s.llm, template: o },
232
+ script: { ...s.script, provider: { ...(d = s == null ? void 0 : s.script) == null ? void 0 : d.provider, language: c } },
290
233
  stitch: (t == null ? void 0 : t.presenter.type) === "talk" ? (l = t == null ? void 0 : t.presenter) == null ? void 0 : l.stitch : void 0,
291
234
  ...n
292
235
  };
293
236
  }
294
- let ee = {};
295
- const He = "https://api-js.mixpanel.com/track/?verbose=1&ip=1";
296
- function qe(e) {
237
+ let re = {};
238
+ const Ve = "https://api-js.mixpanel.com/track/?verbose=1&ip=1";
239
+ function Oe(e) {
297
240
  const t = window != null && window.hasOwnProperty("DID_AGENTS_API") ? "agents-ui" : "agents-sdk";
298
241
  return {
299
242
  token: e.token || "testKey",
300
- distinct_id: e.distinctId || de(),
243
+ distinct_id: e.distinctId || fe(),
301
244
  agentId: e.agentId,
302
- additionalProperties: {},
245
+ additionalProperties: {
246
+ id: e.distinctId,
247
+ ...e.mixpanelAdditionalProperties || {}
248
+ },
303
249
  isEnabled: e.isEnabled ?? !0,
304
250
  getRandom: V,
305
251
  enrich(n) {
306
- this.additionalProperties = {
307
- ...this.additionalProperties,
308
- ...n
309
- };
252
+ this.additionalProperties = { ...this.additionalProperties, ...n };
310
253
  },
311
254
  async track(n, r) {
312
255
  if (!this.isEnabled)
313
256
  return Promise.resolve();
314
- const {
315
- audioPath: s,
316
- ...o
317
- } = r || {}, c = {
257
+ const { audioPath: s, ...o } = r || {}, c = {
318
258
  method: "POST",
319
259
  headers: {
320
260
  "Content-Type": "application/x-www-form-urlencoded"
321
261
  },
322
262
  body: new URLSearchParams({
323
- data: JSON.stringify([{
324
- event: n,
325
- properties: {
326
- ...this.additionalProperties,
327
- ...o,
328
- agentId: this.agentId,
329
- source: t,
330
- token: this.token,
331
- time: Date.now(),
332
- $insert_id: this.getRandom(),
333
- origin: window.location.href,
334
- "Screen Height": window.screen.height || window.innerWidth,
335
- "Screen Width": window.screen.width || window.innerHeight,
336
- "User Agent": navigator.userAgent
263
+ data: JSON.stringify([
264
+ {
265
+ event: n,
266
+ properties: {
267
+ ...this.additionalProperties,
268
+ ...o,
269
+ agentId: this.agentId,
270
+ source: t,
271
+ token: this.token,
272
+ time: Date.now(),
273
+ $insert_id: this.getRandom(),
274
+ origin: window.location.href,
275
+ "Screen Height": window.screen.height || window.innerWidth,
276
+ "Screen Width": window.screen.width || window.innerHeight,
277
+ "User Agent": navigator.userAgent
278
+ }
337
279
  }
338
- }])
280
+ ])
339
281
  })
340
282
  };
341
283
  try {
342
- return await fetch(He, c).then((a) => a.json());
284
+ return await fetch(Ve, c).then((a) => a.json());
343
285
  } catch (a) {
344
286
  return console.error(a);
345
287
  }
346
288
  },
347
289
  linkTrack(n, r, s, o) {
348
- ee[n] || (ee[n] = {
349
- events: {},
350
- resolvedDependencies: []
351
- }), o.includes(s) || o.push(s);
352
- const c = ee[n];
353
- if (c.events[s] = {
354
- props: r
355
- }, c.resolvedDependencies.push(s), o.every((i) => c.resolvedDependencies.includes(i))) {
356
- const i = o.reduce((d, l) => c.events[l] ? {
357
- ...d,
358
- ...c.events[l].props
359
- } : d, {});
360
- this.track(n, i), c.resolvedDependencies = c.resolvedDependencies.filter((d) => !o.includes(d)), o.forEach((d) => {
290
+ re[n] || (re[n] = { events: {}, resolvedDependencies: [] }), o.includes(s) || o.push(s);
291
+ const c = re[n];
292
+ if (c.events[s] = { props: r }, c.resolvedDependencies.push(s), o.every(
293
+ (i) => c.resolvedDependencies.includes(i)
294
+ )) {
295
+ const i = o.reduce((d, l) => c.events[l] ? { ...d, ...c.events[l].props } : d, {});
296
+ this.track(n, i), c.resolvedDependencies = c.resolvedDependencies.filter(
297
+ (d) => !o.includes(d)
298
+ ), o.forEach((d) => {
361
299
  delete c.events[d];
362
300
  });
363
301
  }
364
302
  }
365
303
  };
366
304
  }
367
- function ge() {
305
+ function pe() {
368
306
  let e = 0;
369
307
  return {
370
308
  reset: () => e = 0,
@@ -372,26 +310,17 @@ function ge() {
372
310
  get: (t = !1) => t ? Date.now() - e : e
373
311
  };
374
312
  }
375
- const N = ge(), re = ge();
376
- function he(e) {
377
- return e === M.Playground ? {
378
- headers: {
379
- [Be]: "true"
380
- }
381
- } : {};
313
+ const $ = pe(), ae = pe();
314
+ function ye(e) {
315
+ return e === E.Playground ? { headers: { [$e]: "true" } } : {};
382
316
  }
383
- async function we(e, t, n, r, s = !1, o) {
317
+ async function ve(e, t, n, r, s = !1, o) {
384
318
  try {
385
- return !o && !ce(r) && (o = await t.newChat(e.id, {
386
- persist: s
387
- }, he(r)), n.track("agent-chat", {
319
+ return !o && !ue(r) && (o = await t.newChat(e.id, { persist: s }, ye(r)), n.track("agent-chat", {
388
320
  event: "created",
389
321
  chatId: o.id,
390
322
  mode: r
391
- })), {
392
- chat: o,
393
- chatMode: (o == null ? void 0 : o.chat_mode) ?? r
394
- };
323
+ })), { chat: o, chatMode: (o == null ? void 0 : o.chat_mode) ?? r };
395
324
  } catch (c) {
396
325
  try {
397
326
  const a = JSON.parse(c.message);
@@ -403,39 +332,30 @@ async function we(e, t, n, r, s = !1, o) {
403
332
  throw new Error("Cannot create new chat");
404
333
  }
405
334
  }
406
- function Ve(e) {
335
+ function Xe(e) {
407
336
  return e && e.length > 0 ? e : [];
408
337
  }
409
- function Oe(e, t, n) {
338
+ function Ye(e, t, n) {
410
339
  if (!e)
411
340
  throw new Error("Please connect to the agent first");
412
341
  if (!e.interruptAvailable)
413
342
  throw new Error("Interrupt is not enabled for this stream");
414
- if (t !== W.Fluent)
343
+ if (t !== J.Fluent)
415
344
  throw new Error("Interrupt only available for Fluent streams");
416
345
  if (!n)
417
346
  throw new Error("No active video to interrupt");
418
347
  }
419
- async function Xe(e, t) {
348
+ async function Qe(e, t) {
420
349
  const n = {
421
- type: A.StreamInterrupt,
350
+ type: P.StreamInterrupt,
422
351
  videoId: t,
423
352
  timestamp: Date.now()
424
353
  };
425
354
  e.sendDataChannelMessage(JSON.stringify(n));
426
355
  }
427
- function Ye(e) {
356
+ function Ze(e) {
428
357
  return new Promise((t, n) => {
429
- const {
430
- callbacks: r,
431
- host: s,
432
- auth: o
433
- } = e, {
434
- onMessage: c = null,
435
- onOpen: a = null,
436
- onClose: i = null,
437
- onError: d = null
438
- } = r || {}, l = new WebSocket(`${s}?authorization=${le(o)}`);
358
+ const { callbacks: r, host: s, auth: o } = e, { onMessage: c = null, onOpen: a = null, onClose: i = null, onError: d = null } = r || {}, l = new WebSocket(`${s}?authorization=${me(o)}`);
439
359
  l.onmessage = c, l.onclose = i, l.onerror = (y) => {
440
360
  console.error(y), d == null || d("Websocket failed to connect", y), n(y);
441
361
  }, l.onopen = (y) => {
@@ -443,29 +363,27 @@ function Ye(e) {
443
363
  };
444
364
  });
445
365
  }
446
- async function Qe(e) {
447
- const {
448
- retries: t = 1
449
- } = e;
366
+ async function Ge(e) {
367
+ const { retries: t = 1 } = e;
450
368
  let n = null;
451
369
  for (let r = 0; (n == null ? void 0 : n.readyState) !== WebSocket.OPEN; r++)
452
370
  try {
453
- n = await Ye(e);
371
+ n = await Ze(e);
454
372
  } catch (s) {
455
373
  if (r === t)
456
374
  throw s;
457
- await oe(r * 500);
375
+ await le(r * 500);
458
376
  }
459
377
  return n;
460
378
  }
461
- async function Ze(e, t, n) {
462
- const r = n != null && n.onMessage ? [n.onMessage] : [], s = await Qe({
379
+ async function et(e, t, n) {
380
+ const r = n != null && n.onMessage ? [n.onMessage] : [], s = await Ge({
463
381
  auth: e,
464
382
  host: t,
465
383
  callbacks: {
466
384
  onError: (o) => {
467
385
  var c;
468
- return (c = n.onError) == null ? void 0 : c.call(n, new Ce(o));
386
+ return (c = n.onError) == null ? void 0 : c.call(n, new Se(o));
469
387
  },
470
388
  onMessage(o) {
471
389
  const c = JSON.parse(o.data);
@@ -479,7 +397,7 @@ async function Ze(e, t, n) {
479
397
  subscribeToEvents: (o) => r.push(o)
480
398
  };
481
399
  }
482
- function Ge(e) {
400
+ function tt(e) {
483
401
  if (e.answer !== void 0)
484
402
  return e.answer;
485
403
  let t = 0, n = "";
@@ -487,54 +405,41 @@ function Ge(e) {
487
405
  n += e[t++];
488
406
  return n;
489
407
  }
490
- function et(e, t, n, r, s) {
408
+ function rt(e, t, n, r, s) {
491
409
  const o = r.messages[r.messages.length - 1];
492
410
  if (!(e === q.Partial || e === q.Answer) || (o == null ? void 0 : o.role) !== "assistant")
493
411
  return;
494
- const {
495
- content: c,
496
- sequence: a
497
- } = t;
412
+ const { content: c, sequence: a } = t;
498
413
  e === q.Partial ? n[a] = c : n.answer = c;
499
- const i = Ge(n);
414
+ const i = tt(n);
500
415
  (o.content !== i || e === q.Answer) && (o.content = i, s == null || s([...r.messages], e));
501
416
  }
502
- function tt(e, t, n, r, s) {
417
+ function nt(e, t, n, r, s) {
503
418
  let o = {};
504
419
  return {
505
420
  clearQueue: () => o = {},
506
421
  onMessage: (c, a) => {
507
422
  var i, d;
508
423
  if ("content" in a)
509
- et(c, a, o, t, n.callbacks.onNewMessage), c === q.Answer && e.track("agent-message-received", {
424
+ rt(c, a, o, t, n.callbacks.onNewMessage), c === q.Answer && e.track("agent-message-received", {
510
425
  messages: t.messages.length,
511
426
  mode: t.chatMode
512
427
  });
513
428
  else {
514
- const l = A, y = [l.StreamVideoDone, l.StreamVideoError, l.StreamVideoRejected], _ = [l.StreamFailed, l.StreamVideoError, l.StreamVideoRejected], T = Ke(a, r, {
515
- mode: t.chatMode
516
- });
429
+ const l = P, y = [l.StreamVideoDone, l.StreamVideoError, l.StreamVideoRejected], M = [l.StreamFailed, l.StreamVideoError, l.StreamVideoRejected], j = qe(a, r, { mode: t.chatMode });
517
430
  if (c = c, c === l.StreamVideoCreated)
518
- e.linkTrack("agent-video", T, l.StreamVideoCreated, ["start"]);
431
+ e.linkTrack("agent-video", j, l.StreamVideoCreated, ["start"]);
519
432
  else if (y.includes(c)) {
520
- const j = c.split("/")[1];
521
- _.includes(c) ? e.track("agent-video", {
522
- ...T,
523
- event: j
524
- }) : e.linkTrack("agent-video", {
525
- ...T,
526
- event: j
527
- }, c, ["done"]);
433
+ const b = c.split("/")[1];
434
+ M.includes(c) ? e.track("agent-video", { ...j, event: b }) : e.linkTrack("agent-video", { ...j, event: b }, c, ["done"]);
528
435
  }
529
- _.includes(c) && ((d = (i = n.callbacks).onError) == null || d.call(i, new Error(`Stream failed with event ${c}`), {
530
- data: a
531
- })), a.event === l.StreamDone && s();
436
+ M.includes(c) && ((d = (i = n.callbacks).onError) == null || d.call(i, new Error(`Stream failed with event ${c}`), { data: a })), a.event === l.StreamDone && s();
532
437
  }
533
438
  }
534
439
  };
535
440
  }
536
- function rt(e, t, n, r) {
537
- const s = ue(e, `${t}/agents/${n}`, r);
441
+ function at(e, t, n, r) {
442
+ const s = ge(e, `${t}/agents/${n}`, r);
538
443
  return {
539
444
  createStream(o) {
540
445
  return s.post("/streams", o);
@@ -558,13 +463,12 @@ function rt(e, t, n, r) {
558
463
  });
559
464
  },
560
465
  close(o, c) {
561
- return s.delete(`/streams/${o}`, {
562
- session_id: c
563
- });
466
+ return s.delete(`/streams/${o}`, { session_id: c });
564
467
  }
565
468
  };
566
469
  }
567
- function nt(e, t, n) {
470
+ const it = (e, t) => (n, r) => e && console.log(`[${t}] ${n}`, r ?? "");
471
+ function st(e, t, n) {
568
472
  const r = (t.timestamp - e.timestamp) / 1e3;
569
473
  return {
570
474
  duration: r,
@@ -584,19 +488,18 @@ function nt(e, t, n) {
584
488
  lowFpsCount: n
585
489
  };
586
490
  }
587
- function at(e) {
588
- return e.filter((t) => t.freezeCount > 0 || t.framesPerSecond < 21 || t.framesDropped > 0 || t.packetsLost > 0).map((t) => {
589
- const {
590
- timestamp: n,
591
- ...r
592
- } = t, s = [];
491
+ function ot(e) {
492
+ return e.filter(
493
+ (t) => t.freezeCount > 0 || t.framesPerSecond < 21 || t.framesDropped > 0 || t.packetsLost > 0
494
+ ).map((t) => {
495
+ const { timestamp: n, ...r } = t, s = [];
593
496
  return t.freezeCount > 0 && s.push("freeze"), t.framesPerSecond < 21 && s.push("low fps"), t.framesDropped > 0 && s.push("frames dropped"), t.packetsLost > 0 && s.push("packet loss"), {
594
497
  ...r,
595
498
  causes: s
596
499
  };
597
500
  });
598
501
  }
599
- function it(e) {
502
+ function ct(e) {
600
503
  let t = "", n = 0;
601
504
  for (const r of e.values())
602
505
  if (r && r.type === "codec" && r.mimeType.startsWith("video") && (t = r.mimeType.split("/")[1]), r && r.type === "candidate-pair" && (n = r.currentRoundTripTime), r && r.type === "inbound-rtp" && r.kind === "video")
@@ -621,7 +524,7 @@ function it(e) {
621
524
  };
622
525
  return {};
623
526
  }
624
- function st(e, t, n) {
527
+ function dt(e, t, n) {
625
528
  const r = e.map((i, d) => d === 0 ? n ? {
626
529
  timestamp: i.timestamp,
627
530
  duration: 0,
@@ -673,24 +576,24 @@ function st(e, t, n) {
673
576
  framesPerSecond: i.framesPerSecond,
674
577
  freezeCount: i.freezeCount - e[d - 1].freezeCount,
675
578
  freezeDuration: i.freezeDuration - e[d - 1].freezeDuration
676
- }), s = at(r), o = s.reduce((i, d) => i + (d.causes.includes("low fps") ? 1 : 0), 0), c = r.filter((i) => !!i.avgJitterDelayInInterval).map((i) => i.avgJitterDelayInInterval), a = r.filter((i) => !!i.rtt).map((i) => i.rtt);
579
+ }), s = ot(r), o = s.reduce((i, d) => i + (d.causes.includes("low fps") ? 1 : 0), 0), c = r.filter((i) => !!i.avgJitterDelayInInterval).map((i) => i.avgJitterDelayInInterval), a = r.filter((i) => !!i.rtt).map((i) => i.rtt);
677
580
  return {
678
581
  webRTCStats: {
679
582
  anomalies: s,
680
583
  minRtt: Math.min(...a),
681
- avgRtt: ae(a),
584
+ avgRtt: se(a),
682
585
  maxRtt: Math.max(...a),
683
- aggregateReport: nt(e[0], e[e.length - 1], o),
586
+ aggregateReport: st(e[0], e[e.length - 1], o),
684
587
  minJitterDelayInInterval: Math.min(...c),
685
588
  maxJitterDelayInInterval: Math.max(...c),
686
- avgJitterDelayInInterval: ae(c)
589
+ avgJitterDelayInInterval: se(c)
687
590
  },
688
591
  codec: e[0].codec,
689
592
  resolution: `${e[0].frameWidth}x${e[0].frameHeight}`
690
593
  };
691
594
  }
692
- const ne = 100, ot = Math.max(Math.ceil(400 / ne), 1), ct = 0.25, dt = 0.28;
693
- function lt() {
595
+ const ie = 100, lt = Math.max(Math.ceil(400 / ie), 1), ut = 0.25, ft = 0.28;
596
+ function mt() {
694
597
  let e = 0, t, n, r = 0;
695
598
  return (s) => {
696
599
  for (const o of s.values())
@@ -702,97 +605,72 @@ function lt() {
702
605
  }
703
606
  t = c, n = a;
704
607
  const i = o.framesDecoded, d = i - e > 0;
705
- return e = i, {
706
- isReceiving: d,
707
- avgJitterDelayInInterval: r,
708
- freezeCount: o.freezeCount
709
- };
608
+ return e = i, { isReceiving: d, avgJitterDelayInInterval: r, freezeCount: o.freezeCount };
710
609
  }
711
- return {
712
- isReceiving: !1,
713
- avgJitterDelayInInterval: r
714
- };
610
+ return { isReceiving: !1, avgJitterDelayInInterval: r };
715
611
  };
716
612
  }
717
- function ut(e, t, n, r, s, o = !1) {
718
- let c = [], a, i = 0, d = !1, l = Q.Unknown, y = Q.Unknown, _ = 0, T = 0;
719
- const j = lt();
613
+ function gt(e, t, n, r, s, o = !1) {
614
+ let c = [], a, i = 0, d = !1, l = G.Unknown, y = G.Unknown, M = 0, j = 0;
615
+ const b = mt();
720
616
  return setInterval(async () => {
721
- const x = await e.getStats(), {
722
- isReceiving: R,
723
- avgJitterDelayInInterval: U,
724
- freezeCount: K
725
- } = j(x), P = it(x);
726
- if (R)
727
- i = 0, _ = K - T, y = U < ct ? Q.Strong : U > dt && _ > 1 ? Q.Weak : l, y !== l && (s == null || s(y), l = y, T += _, _ = 0), d || (r == null || r(h.Start), a = c[c.length - 1], c = [], d = !0), c.push(P);
728
- else if (d && (i++, i >= ot)) {
729
- const u = st(c, ne, a);
730
- r == null || r(h.Stop, u), t() || n(), T = K, d = !1;
617
+ const z = await e.getStats(), { isReceiving: U, avgJitterDelayInInterval: W, freezeCount: C } = b(z), K = ct(z);
618
+ if (U)
619
+ i = 0, M = C - j, y = W < ut ? G.Strong : W > ft && M > 1 ? G.Weak : l, y !== l && (s == null || s(y), l = y, j += M, M = 0), d || (r == null || r(w.Start), a = c[c.length - 1], c = [], d = !0), c.push(K);
620
+ else if (d && (i++, i >= lt)) {
621
+ const u = dt(c, ie, a);
622
+ r == null || r(w.Stop, u), t() || n(), j = C, d = !1;
731
623
  }
732
- }, ne);
624
+ }, ie);
733
625
  }
734
- let pe = !1;
735
- const B = (e, t) => pe && console.log(e, t), ft = (window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection).bind(window);
736
- function ie(e) {
626
+ const ht = (window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection).bind(window);
627
+ function oe(e) {
737
628
  switch (e) {
738
629
  case "connected":
739
- return I.Connected;
630
+ return R.Connected;
740
631
  case "checking":
741
- return I.Connecting;
632
+ return R.Connecting;
742
633
  case "failed":
743
- return I.Fail;
634
+ return R.Fail;
744
635
  case "new":
745
- return I.New;
636
+ return R.New;
746
637
  case "closed":
747
- return I.Closed;
638
+ return R.Closed;
748
639
  case "disconnected":
749
- return I.Disconnected;
640
+ return R.Disconnected;
750
641
  case "completed":
751
- return I.Completed;
642
+ return R.Completed;
752
643
  default:
753
- return I.New;
644
+ return R.New;
754
645
  }
755
646
  }
756
- function mt(e) {
757
- const [t, n = ""] = e.split(/:(.+)/);
647
+ const wt = (e) => (t) => {
648
+ const [n, r = ""] = t.split(/:(.+)/);
758
649
  try {
759
- const r = JSON.parse(n);
760
- return B("parsed data channel message", {
761
- subject: t,
762
- data: r
763
- }), {
764
- subject: t,
765
- data: r
766
- };
767
- } catch (r) {
768
- return B("Failed to parse data channel message, returning data as string", {
769
- subject: t,
770
- rawData: n,
771
- error: r
772
- }), {
773
- subject: t,
774
- data: n
775
- };
650
+ const s = JSON.parse(r);
651
+ return e("parsed data channel message", { subject: n, data: s }), { subject: n, data: s };
652
+ } catch (s) {
653
+ return e("Failed to parse data channel message, returning data as string", { subject: n, rawData: r, error: s }), { subject: n, data: r };
776
654
  }
777
- }
778
- function gt({
655
+ };
656
+ function pt({
779
657
  statsSignal: e,
780
658
  dataChannelSignal: t,
781
659
  onVideoStateChange: n,
782
660
  report: r
783
661
  }) {
784
- e === h.Start && t === h.Start ? n == null || n(h.Start) : e === h.Stop && t === h.Stop && (n == null || n(h.Stop, r));
662
+ e === w.Start && t === w.Start ? n == null || n(w.Start) : e === w.Stop && t === w.Stop && (n == null || n(w.Stop, r));
785
663
  }
786
- function ht({
664
+ function yt({
787
665
  statsSignal: e,
788
666
  dataChannelSignal: t,
789
667
  onVideoStateChange: n,
790
668
  onAgentActivityStateChange: r,
791
669
  report: s
792
670
  }) {
793
- e === h.Start ? n == null || n(h.Start) : e === h.Stop && (n == null || n(h.Stop, s)), t === h.Start ? r == null || r(O.Talking) : t === h.Stop && (r == null || r(O.Idle));
671
+ e === w.Start ? n == null || n(w.Start) : e === w.Stop && (n == null || n(w.Stop, s)), t === w.Start ? r == null || r(O.Talking) : t === w.Stop && (r == null || r(O.Idle));
794
672
  }
795
- function se({
673
+ function ce({
796
674
  statsSignal: e,
797
675
  dataChannelSignal: t,
798
676
  onVideoStateChange: n,
@@ -800,12 +678,7 @@ function se({
800
678
  streamType: s,
801
679
  report: o
802
680
  }) {
803
- s === W.Legacy ? gt({
804
- statsSignal: e,
805
- dataChannelSignal: t,
806
- onVideoStateChange: n,
807
- report: o
808
- }) : s === W.Fluent && ht({
681
+ s === J.Legacy ? pt({ statsSignal: e, dataChannelSignal: t, onVideoStateChange: n, report: o }) : s === J.Fluent && yt({
809
682
  statsSignal: e,
810
683
  dataChannelSignal: t,
811
684
  onVideoStateChange: n,
@@ -813,190 +686,180 @@ function se({
813
686
  report: o
814
687
  });
815
688
  }
816
- async function wt(e, t, {
817
- debug: n = !1,
818
- callbacks: r,
819
- auth: s,
820
- baseURL: o = Z,
821
- analytics: c
822
- }) {
823
- var J;
824
- pe = n;
825
- let a = !1, i = !1, d = h.Stop, l = h.Stop;
826
- const {
827
- startConnection: y,
828
- sendStreamRequest: _,
829
- close: T,
830
- createStream: j,
831
- addIceCandidate: x
832
- } = rt(s, o, e, r.onError), {
833
- id: R,
834
- offer: U,
835
- ice_servers: K,
836
- session_id: P,
837
- fluent: u,
838
- interrupt_enabled: v
839
- } = await j(t);
840
- (J = r.onStreamCreated) == null || J.call(r, {
841
- stream_id: R,
842
- session_id: P,
843
- agent_id: e
844
- });
845
- const m = new ft({
846
- iceServers: K
847
- }), D = m.createDataChannel("JanusDataChannel");
848
- if (!P)
689
+ async function vt(e, t, { debug: n = !1, callbacks: r, auth: s, baseURL: o = ee, analytics: c }) {
690
+ var Y;
691
+ const a = it(n, "WebRTCStreamingManager"), i = wt(a);
692
+ let d = !1, l = !1, y = w.Stop, M = w.Stop;
693
+ const { startConnection: j, sendStreamRequest: b, close: z, createStream: U, addIceCandidate: W } = at(
694
+ s,
695
+ o,
696
+ e,
697
+ r.onError
698
+ ), {
699
+ id: C,
700
+ offer: K,
701
+ ice_servers: u,
702
+ session_id: h,
703
+ fluent: p,
704
+ interrupt_enabled: _,
705
+ triggers_enabled: v
706
+ } = await U(t);
707
+ (Y = r.onStreamCreated) == null || Y.call(r, { stream_id: C, session_id: h, agent_id: e });
708
+ const f = new ht({ iceServers: u }), S = f.createDataChannel("JanusDataChannel");
709
+ if (!h)
849
710
  throw new Error("Could not create session_id");
850
- const w = u ? W.Fluent : W.Legacy;
711
+ const T = p ? J.Fluent : J.Legacy;
851
712
  c.enrich({
852
- "stream-type": w
713
+ "stream-type": T
853
714
  });
854
- const p = t.stream_warmup && !u, b = () => a, L = () => {
855
- var f;
856
- a = !0, i && ((f = r.onConnectionStateChange) == null || f.call(r, I.Connected));
857
- }, $ = ut(m, b, L, (f, g) => se({
858
- statsSignal: l = f,
859
- dataChannelSignal: w === W.Legacy ? d : void 0,
860
- onVideoStateChange: r.onVideoStateChange,
861
- onAgentActivityStateChange: r.onAgentActivityStateChange,
862
- report: g,
863
- streamType: w
864
- }), (f) => {
865
- var g;
866
- return (g = r.onConnectivityStateChange) == null ? void 0 : g.call(r, f);
867
- }, p);
868
- m.onicecandidate = (f) => {
715
+ const L = t.stream_warmup && !p, D = () => d, I = () => {
716
+ var m;
717
+ d = !0, l && ((m = r.onConnectionStateChange) == null || m.call(r, R.Connected));
718
+ }, k = gt(
719
+ f,
720
+ D,
721
+ I,
722
+ (m, g) => ce({
723
+ statsSignal: M = m,
724
+ dataChannelSignal: T === J.Legacy ? y : void 0,
725
+ onVideoStateChange: r.onVideoStateChange,
726
+ onAgentActivityStateChange: r.onAgentActivityStateChange,
727
+ report: g,
728
+ streamType: T
729
+ }),
730
+ (m) => {
731
+ var g;
732
+ return (g = r.onConnectivityStateChange) == null ? void 0 : g.call(r, m);
733
+ },
734
+ L
735
+ );
736
+ f.onicecandidate = (m) => {
869
737
  var g;
870
- B("peerConnection.onicecandidate", f);
738
+ a("peerConnection.onicecandidate", m);
871
739
  try {
872
- f.candidate && f.candidate.sdpMid && f.candidate.sdpMLineIndex !== null ? x(R, {
873
- candidate: f.candidate.candidate,
874
- sdpMid: f.candidate.sdpMid,
875
- sdpMLineIndex: f.candidate.sdpMLineIndex
876
- }, P) : x(R, {
877
- candidate: null
878
- }, P);
879
- } catch (S) {
880
- (g = r.onError) == null || g.call(r, S, {
881
- streamId: R
882
- });
740
+ m.candidate && m.candidate.sdpMid && m.candidate.sdpMLineIndex !== null ? W(
741
+ C,
742
+ {
743
+ candidate: m.candidate.candidate,
744
+ sdpMid: m.candidate.sdpMid,
745
+ sdpMLineIndex: m.candidate.sdpMLineIndex
746
+ },
747
+ h
748
+ ) : W(C, { candidate: null }, h);
749
+ } catch (A) {
750
+ (g = r.onError) == null || g.call(r, A, { streamId: C });
883
751
  }
884
- }, D.onopen = () => {
885
- i = !0, (!p || a) && L();
752
+ }, S.onopen = () => {
753
+ l = !0, (!L || d) && I();
886
754
  };
887
- const k = (f) => {
755
+ const x = (m) => {
888
756
  var g;
889
- (g = r.onVideoIdChange) == null || g.call(r, f);
757
+ (g = r.onVideoIdChange) == null || g.call(r, m);
890
758
  };
891
- function E(f, g) {
892
- if (f === A.StreamStarted && typeof g == "object" && "metadata" in g) {
893
- const S = g.metadata;
894
- k(S.videoId);
759
+ function B(m, g) {
760
+ if (m === P.StreamStarted && typeof g == "object" && "metadata" in g) {
761
+ const A = g.metadata;
762
+ x(A.videoId);
895
763
  }
896
- f === A.StreamDone && k(null), d = f === A.StreamStarted ? h.Start : h.Stop, se({
897
- statsSignal: w === W.Legacy ? l : void 0,
898
- dataChannelSignal: d,
764
+ m === P.StreamDone && x(null), y = m === P.StreamStarted ? w.Start : w.Stop, ce({
765
+ statsSignal: T === J.Legacy ? M : void 0,
766
+ dataChannelSignal: y,
899
767
  onVideoStateChange: r.onVideoStateChange,
900
768
  onAgentActivityStateChange: r.onAgentActivityStateChange,
901
- streamType: w
769
+ streamType: T
902
770
  });
903
771
  }
904
- function C(f, g) {
905
- const S = typeof g == "string" ? g : g == null ? void 0 : g.metadata;
906
- S && c.enrich({
907
- streamMetadata: S
908
- }), c.track("agent-chat", {
909
- event: "ready"
910
- });
772
+ function F(m, g) {
773
+ const A = typeof g == "string" ? g : g == null ? void 0 : g.metadata;
774
+ A && c.enrich({ streamMetadata: A }), c.track("agent-chat", { event: "ready" });
911
775
  }
912
- const z = {
913
- [A.StreamStarted]: E,
914
- [A.StreamDone]: E,
915
- [A.StreamReady]: C
776
+ const N = {
777
+ [P.StreamStarted]: B,
778
+ [P.StreamDone]: B,
779
+ [P.StreamReady]: F
916
780
  };
917
- D.onmessage = (f) => {
918
- var X;
919
- const {
920
- subject: g,
921
- data: S
922
- } = mt(f.data);
923
- (X = z[g]) == null || X.call(z, g, S);
924
- }, m.oniceconnectionstatechange = () => {
781
+ S.onmessage = (m) => {
782
+ var Q;
783
+ const { subject: g, data: A } = i(m.data);
784
+ (Q = N[g]) == null || Q.call(N, g, A);
785
+ }, f.oniceconnectionstatechange = () => {
925
786
  var g;
926
- B("peerConnection.oniceconnectionstatechange => " + m.iceConnectionState);
927
- const f = ie(m.iceConnectionState);
928
- f !== I.Connected && ((g = r.onConnectionStateChange) == null || g.call(r, f));
929
- }, m.ontrack = (f) => {
787
+ a("peerConnection.oniceconnectionstatechange => " + f.iceConnectionState);
788
+ const m = oe(f.iceConnectionState);
789
+ m !== R.Connected && ((g = r.onConnectionStateChange) == null || g.call(r, m));
790
+ }, f.ontrack = (m) => {
930
791
  var g;
931
- B("peerConnection.ontrack", f), (g = r.onSrcObjectReady) == null || g.call(r, f.streams[0]);
932
- }, await m.setRemoteDescription(U), B("set remote description OK");
933
- const F = await m.createAnswer();
934
- return B("create answer OK"), await m.setLocalDescription(F), B("set local description OK"), await y(R, F, P), B("start connection OK"), {
792
+ a("peerConnection.ontrack", m), (g = r.onSrcObjectReady) == null || g.call(r, m.streams[0]);
793
+ }, await f.setRemoteDescription(K), a("set remote description OK");
794
+ const X = await f.createAnswer();
795
+ return a("create answer OK"), await f.setLocalDescription(X), a("set local description OK"), await j(C, X, h), a("start connection OK"), {
935
796
  /**
936
797
  * Method to send request to server to get clip or talk depend on you payload
937
798
  * @param payload
938
799
  */
939
- speak(f) {
940
- return _(R, P, f);
800
+ speak(m) {
801
+ return b(C, h, m);
941
802
  },
942
803
  /**
943
804
  * Method to close RTC connection
944
805
  */
945
806
  async disconnect() {
946
- var f;
947
- if (R) {
948
- const g = ie(m.iceConnectionState);
949
- if (m) {
950
- if (g === I.New) {
951
- clearInterval($);
807
+ var m;
808
+ if (C) {
809
+ const g = oe(f.iceConnectionState);
810
+ if (f) {
811
+ if (g === R.New) {
812
+ clearInterval(k);
952
813
  return;
953
814
  }
954
- m.close(), m.oniceconnectionstatechange = null, m.onnegotiationneeded = null, m.onicecandidate = null, m.ontrack = null;
815
+ f.close(), f.oniceconnectionstatechange = null, f.onnegotiationneeded = null, f.onicecandidate = null, f.ontrack = null;
955
816
  }
956
817
  try {
957
- g === I.Connected && await T(R, P).catch((S) => {
818
+ g === R.Connected && await z(C, h).catch((A) => {
958
819
  });
959
- } catch (S) {
960
- B("Error on close stream connection", S);
820
+ } catch (A) {
821
+ a("Error on close stream connection", A);
961
822
  }
962
- (f = r.onAgentActivityStateChange) == null || f.call(r, O.Idle), clearInterval($);
823
+ (m = r.onAgentActivityStateChange) == null || m.call(r, O.Idle), clearInterval(k);
963
824
  }
964
825
  },
965
826
  /**
966
827
  * Method to send data channel messages to the server
967
828
  */
968
- sendDataChannelMessage(f) {
969
- var g, S;
970
- if (!a || D.readyState !== "open") {
971
- B("Data channel is not ready for sending messages"), (g = r.onError) == null || g.call(r, new Error("Data channel is not ready for sending messages"), {
972
- streamId: R
829
+ sendDataChannelMessage(m) {
830
+ var g, A;
831
+ if (!d || S.readyState !== "open") {
832
+ a("Data channel is not ready for sending messages"), (g = r.onError) == null || g.call(r, new Error("Data channel is not ready for sending messages"), {
833
+ streamId: C
973
834
  });
974
835
  return;
975
836
  }
976
837
  try {
977
- D.send(f);
978
- } catch (X) {
979
- B("Error sending data channel message", X), (S = r.onError) == null || S.call(r, X, {
980
- streamId: R
981
- });
838
+ S.send(m);
839
+ } catch (Q) {
840
+ a("Error sending data channel message", Q), (A = r.onError) == null || A.call(r, Q, { streamId: C });
982
841
  }
983
842
  },
984
843
  /**
985
844
  * Session identifier information, should be returned in the body of all streaming requests
986
845
  */
987
- sessionId: P,
846
+ sessionId: h,
988
847
  /**
989
848
  * Id of current RTC stream
990
849
  */
991
- streamId: R,
992
- streamType: w,
993
- interruptAvailable: v
850
+ streamId: C,
851
+ streamType: T,
852
+ interruptAvailable: _ ?? !1,
853
+ triggersAvailable: v ?? !1
994
854
  };
995
855
  }
996
- function pt(e) {
997
- const {
998
- streamOptions: t
999
- } = e ?? {};
856
+ const kt = (e) => e.presenter.type === de.Expressive;
857
+ async function Dt(e, t, n) {
858
+ const r = e.id;
859
+ return kt(e) ? {} : vt(r, t, n);
860
+ }
861
+ function Ct(e) {
862
+ const { streamOptions: t } = e ?? {};
1000
863
  return {
1001
864
  output_resolution: t == null ? void 0 : t.outputResolution,
1002
865
  session_timeout: t == null ? void 0 : t.sessionTimeout,
@@ -1005,14 +868,11 @@ function pt(e) {
1005
868
  fluent: t == null ? void 0 : t.fluent
1006
869
  };
1007
870
  }
1008
- function yt(e, t, n, r, s) {
1009
- s === W.Fluent ? vt(e, t, n, r, s) : Dt(e, t, n, r, s);
871
+ function Rt(e, t, n, r, s) {
872
+ s === J.Fluent ? St(e, t, n, r, s) : Et(e, t, n, r, s);
1010
873
  }
1011
- function vt(e, t, n, r, s) {
1012
- e === h.Start ? r.track("stream-session", {
1013
- event: "start",
1014
- "stream-type": s
1015
- }) : e === h.Stop && r.track("stream-session", {
874
+ function St(e, t, n, r, s) {
875
+ e === w.Start ? r.track("stream-session", { event: "start", "stream-type": s }) : e === w.Stop && r.track("stream-session", {
1016
876
  event: "stop",
1017
877
  is_greenscreen: t.presenter.type === "clip" && t.presenter.is_greenscreen,
1018
878
  background: t.presenter.type === "clip" && t.presenter.background,
@@ -1020,50 +880,74 @@ function vt(e, t, n, r, s) {
1020
880
  ...n
1021
881
  });
1022
882
  }
1023
- function kt(e, t, n, r) {
1024
- N.get() <= 0 || (e === h.Start ? n.linkTrack("agent-video", {
1025
- event: "start",
1026
- latency: N.get(!0),
1027
- "stream-type": r
1028
- }, "start", [A.StreamVideoCreated]) : e === h.Stop && n.linkTrack("agent-video", {
1029
- event: "stop",
1030
- is_greenscreen: t.presenter.type === "clip" && t.presenter.is_greenscreen,
1031
- background: t.presenter.type === "clip" && t.presenter.background,
1032
- "stream-type": r
1033
- }, "done", [A.StreamVideoDone]));
883
+ function It(e, t, n, r) {
884
+ $.get() <= 0 || (e === w.Start ? n.linkTrack(
885
+ "agent-video",
886
+ { event: "start", latency: $.get(!0), "stream-type": r },
887
+ "start",
888
+ [P.StreamVideoCreated]
889
+ ) : e === w.Stop && n.linkTrack(
890
+ "agent-video",
891
+ {
892
+ event: "stop",
893
+ is_greenscreen: t.presenter.type === "clip" && t.presenter.is_greenscreen,
894
+ background: t.presenter.type === "clip" && t.presenter.background,
895
+ "stream-type": r
896
+ },
897
+ "done",
898
+ [P.StreamVideoDone]
899
+ ));
1034
900
  }
1035
- function Dt(e, t, n, r, s) {
1036
- N.get() <= 0 || (e === h.Start ? r.linkTrack("agent-video", {
1037
- event: "start",
1038
- latency: N.get(!0),
1039
- "stream-type": s
1040
- }, "start", [A.StreamVideoCreated]) : e === h.Stop && r.linkTrack("agent-video", {
1041
- event: "stop",
1042
- is_greenscreen: t.presenter.type === "clip" && t.presenter.is_greenscreen,
1043
- background: t.presenter.type === "clip" && t.presenter.background,
1044
- "stream-type": s,
1045
- ...n
1046
- }, "done", [A.StreamVideoDone]));
901
+ function Et(e, t, n, r, s) {
902
+ $.get() <= 0 || (e === w.Start ? r.linkTrack(
903
+ "agent-video",
904
+ { event: "start", latency: $.get(!0), "stream-type": s },
905
+ "start",
906
+ [P.StreamVideoCreated]
907
+ ) : e === w.Stop && r.linkTrack(
908
+ "agent-video",
909
+ {
910
+ event: "stop",
911
+ is_greenscreen: t.presenter.type === "clip" && t.presenter.is_greenscreen,
912
+ background: t.presenter.type === "clip" && t.presenter.background,
913
+ "stream-type": s,
914
+ ...n
915
+ },
916
+ "done",
917
+ [P.StreamVideoDone]
918
+ ));
1047
919
  }
1048
- function Ct(e, t, n) {
1049
- return N.reset(), new Promise(async (r, s) => {
920
+ function Mt(e, t, n) {
921
+ return $.reset(), new Promise(async (r, s) => {
1050
922
  try {
1051
- const o = await wt(e.id, pt(t), {
923
+ let o;
924
+ o = await Dt(e, Ct(t), {
1052
925
  ...t,
1053
926
  analytics: n,
1054
927
  callbacks: {
1055
928
  ...t.callbacks,
1056
929
  onConnectionStateChange: (c) => {
1057
930
  var a, i;
1058
- (i = (a = t.callbacks).onConnectionStateChange) == null || i.call(a, c), c === I.Connected && r(o);
931
+ (i = (a = t.callbacks).onConnectionStateChange) == null || i.call(a, c), c === R.Connected && r(o);
1059
932
  },
1060
933
  onVideoStateChange: (c, a) => {
1061
934
  var i, d;
1062
- (d = (i = t.callbacks).onVideoStateChange) == null || d.call(i, c), yt(c, e, a, n, o.streamType);
935
+ (d = (i = t.callbacks).onVideoStateChange) == null || d.call(i, c), Rt(
936
+ c,
937
+ e,
938
+ a,
939
+ n,
940
+ o.streamType
941
+ );
1063
942
  },
1064
943
  onAgentActivityStateChange: (c) => {
1065
944
  var a, i;
1066
- (i = (a = t.callbacks).onAgentActivityStateChange) == null || i.call(a, c), c === O.Talking ? re.update() : re.reset(), kt(c === O.Talking ? h.Start : h.Stop, e, n, o.streamType);
945
+ (i = (a = t.callbacks).onAgentActivityStateChange) == null || i.call(a, c), c === O.Talking ? ae.update() : ae.reset(), It(
946
+ c === O.Talking ? w.Start : w.Stop,
947
+ e,
948
+ n,
949
+ o.streamType
950
+ );
1067
951
  }
1068
952
  }
1069
953
  });
@@ -1072,92 +956,78 @@ function Ct(e, t, n) {
1072
956
  }
1073
957
  });
1074
958
  }
1075
- async function Rt(e, t, n, r, s) {
1076
- var y, _, T, j;
1077
- const o = we(e, n, r, t.mode, t.persistentChat, s), c = Ct(e, t, r), [a, i] = await Promise.all([o, c]), {
1078
- chat: d,
1079
- chatMode: l
1080
- } = a;
1081
- return l && l !== t.mode && (t.mode = l, (_ = (y = t.callbacks).onModeChange) == null || _.call(y, l), l !== M.Functional) ? ((j = (T = t.callbacks).onError) == null || j.call(T, new De(l)), i == null || i.disconnect(), {
1082
- chat: d
1083
- }) : {
1084
- chat: d,
1085
- streamingManager: i
1086
- };
959
+ async function _t(e, t, n, r, s) {
960
+ var y, M, j, b;
961
+ const o = ve(e, n, r, t.mode, t.persistentChat, s), c = Mt(e, t, r), [a, i] = await Promise.all([o, c]), { chat: d, chatMode: l } = a;
962
+ return l && l !== t.mode && (t.mode = l, (M = (y = t.callbacks).onModeChange) == null || M.call(y, l), l !== E.Functional) ? ((b = (j = t.callbacks).onError) == null || b.call(j, new Re(l)), i == null || i.disconnect(), { chat: d }) : { chat: d, streamingManager: i };
1087
963
  }
1088
- async function Et(e, t) {
1089
- var U, K, P;
964
+ async function At(e, t) {
965
+ var W, C, K;
1090
966
  let n = !0, r = null;
1091
- const s = t.mixpanelKey || $e, o = t.wsURL || Le, c = t.baseURL || Z, a = {
967
+ const s = t.mixpanelKey || ze, o = t.wsURL || xe, c = t.baseURL || ee, a = {
1092
968
  messages: [],
1093
- chatMode: t.mode || M.Functional
1094
- }, i = qe({
969
+ chatMode: t.mode || E.Functional
970
+ }, i = Oe({
1095
971
  token: s,
1096
972
  agentId: e,
1097
973
  isEnabled: t.enableAnalitics,
1098
- distinctId: t.distinctId
1099
- });
1100
- i.track("agent-sdk", {
1101
- event: "init"
974
+ distinctId: t.distinctId,
975
+ mixpanelAdditionalProperties: t.mixpanelAdditionalProperties
1102
976
  });
1103
- const d = fe(t.auth, c, t.callbacks.onError), l = await d.getById(e);
1104
- i.enrich(We(l));
1105
- const {
1106
- onMessage: y,
1107
- clearQueue: _
1108
- } = tt(i, a, t, l, () => {
1109
- var u;
1110
- return (u = a.socketManager) == null ? void 0 : u.disconnect();
1111
- });
1112
- a.messages = Ve(t.initialMessages), (K = (U = t.callbacks).onNewMessage) == null || K.call(U, [...a.messages], "answer");
1113
- const T = (u) => {
977
+ i.track("agent-sdk", { event: "init" });
978
+ const d = he(t.auth, c, t.callbacks.onError), l = await d.getById(e);
979
+ i.enrich(Ke(l));
980
+ const { onMessage: y, clearQueue: M } = nt(
981
+ i,
982
+ a,
983
+ t,
984
+ l,
985
+ () => {
986
+ var u;
987
+ return (u = a.socketManager) == null ? void 0 : u.disconnect();
988
+ }
989
+ );
990
+ a.messages = Xe(t.initialMessages), (C = (W = t.callbacks).onNewMessage) == null || C.call(W, [...a.messages], "answer");
991
+ const j = (u) => {
1114
992
  r = u;
1115
993
  };
1116
- i.track("agent-sdk", {
1117
- event: "loaded",
1118
- ...Je(l)
1119
- });
1120
- async function j(u) {
1121
- var b, L, $, k, E, C, z;
1122
- (L = (b = t.callbacks).onConnectionStateChange) == null || L.call(b, I.Connecting), N.reset(), u && !n && (delete a.chat, (k = ($ = t.callbacks).onNewMessage) == null || k.call($, [...a.messages], "answer"));
1123
- const v = t.mode === M.DirectPlayback ? Promise.resolve(void 0) : Ze(t.auth, o, {
1124
- onMessage: y,
1125
- onError: t.callbacks.onError
1126
- }), m = te(() => Rt(l, {
1127
- ...t,
1128
- callbacks: {
1129
- ...t.callbacks,
1130
- onVideoIdChange: T
994
+ i.track("agent-sdk", { event: "loaded", ...Ue(l) });
995
+ async function b(u) {
996
+ var S, T, L, D, I, k, x;
997
+ (T = (S = t.callbacks).onConnectionStateChange) == null || T.call(S, R.Connecting), $.reset(), u && !n && (delete a.chat, (D = (L = t.callbacks).onNewMessage) == null || D.call(L, [...a.messages], "answer"));
998
+ const h = t.mode === E.DirectPlayback ? Promise.resolve(void 0) : et(t.auth, o, { onMessage: y, onError: t.callbacks.onError }), p = ne(
999
+ () => _t(
1000
+ l,
1001
+ { ...t, callbacks: { ...t.callbacks, onVideoIdChange: j } },
1002
+ d,
1003
+ i,
1004
+ a.chat
1005
+ ),
1006
+ {
1007
+ limit: 3,
1008
+ timeout: Be,
1009
+ timeoutErrorMessage: "Timeout initializing the stream",
1010
+ // Retry on all errors except for connection errors and rate limit errors, these are already handled in client level.
1011
+ shouldRetryFn: (B) => (B == null ? void 0 : B.message) !== "Could not connect" && B.status !== 429,
1012
+ delayMs: 1e3
1131
1013
  }
1132
- }, d, i, a.chat), {
1133
- limit: 3,
1134
- timeout: Ae,
1135
- timeoutErrorMessage: "Timeout initializing the stream",
1136
- // Retry on all errors except for connection errors and rate limit errors, these are already handled in client level.
1137
- shouldRetryFn: (F) => (F == null ? void 0 : F.message) !== "Could not connect" && F.status !== 429,
1138
- delayMs: 1e3
1139
- }).catch((F) => {
1140
- var J, f;
1141
- throw R(M.Maintenance), (f = (J = t.callbacks).onConnectionStateChange) == null || f.call(J, I.Fail), F;
1142
- }), [D, {
1143
- streamingManager: w,
1144
- chat: p
1145
- }] = await Promise.all([v, m]);
1146
- p && p.id !== ((E = a.chat) == null ? void 0 : E.id) && ((z = (C = t.callbacks).onNewChat) == null || z.call(C, p.id)), a.streamingManager = w, a.socketManager = D, a.chat = p, n = !1, i.enrich({
1147
- chatId: p == null ? void 0 : p.id,
1148
- streamId: w == null ? void 0 : w.streamId,
1014
+ ).catch((B) => {
1015
+ var F, N;
1016
+ throw U(E.Maintenance), (N = (F = t.callbacks).onConnectionStateChange) == null || N.call(F, R.Fail), B;
1017
+ }), [_, { streamingManager: v, chat: f }] = await Promise.all([h, p]);
1018
+ f && f.id !== ((I = a.chat) == null ? void 0 : I.id) && ((x = (k = t.callbacks).onNewChat) == null || x.call(k, f.id)), a.streamingManager = v, a.socketManager = _, a.chat = f, n = !1, i.enrich({
1019
+ chatId: f == null ? void 0 : f.id,
1020
+ streamId: v == null ? void 0 : v.streamId,
1149
1021
  mode: a.chatMode
1150
- }), R((p == null ? void 0 : p.chat_mode) ?? t.mode ?? M.Functional);
1022
+ }), U((f == null ? void 0 : f.chat_mode) ?? t.mode ?? E.Functional);
1151
1023
  }
1152
- async function x() {
1153
- var u, v, m, D;
1154
- (u = a.socketManager) == null || u.disconnect(), await ((v = a.streamingManager) == null ? void 0 : v.disconnect()), delete a.streamingManager, delete a.socketManager, (D = (m = t.callbacks).onConnectionStateChange) == null || D.call(m, I.Disconnected);
1024
+ async function z() {
1025
+ var u, h, p, _;
1026
+ (u = a.socketManager) == null || u.disconnect(), await ((h = a.streamingManager) == null ? void 0 : h.disconnect()), delete a.streamingManager, delete a.socketManager, (_ = (p = t.callbacks).onConnectionStateChange) == null || _.call(p, R.Disconnected);
1155
1027
  }
1156
- async function R(u) {
1157
- var v, m;
1158
- u !== a.chatMode && (i.track("agent-mode-change", {
1159
- mode: u
1160
- }), a.chatMode = u, a.chatMode !== M.Functional && await x(), (m = (v = t.callbacks).onModeChange) == null || m.call(v, u));
1028
+ async function U(u) {
1029
+ var h, p;
1030
+ u !== a.chatMode && (i.track("agent-mode-change", { mode: u }), a.chatMode = u, a.chatMode !== E.Functional && await z(), (p = (h = t.callbacks).onModeChange) == null || p.call(h, u));
1161
1031
  }
1162
1032
  return {
1163
1033
  agent: l,
@@ -1169,145 +1039,157 @@ async function Et(e, t) {
1169
1039
  var u;
1170
1040
  return ((u = a.streamingManager) == null ? void 0 : u.interruptAvailable) ?? !1;
1171
1041
  },
1172
- starterMessages: ((P = l.knowledge) == null ? void 0 : P.starter_message) || [],
1042
+ getIsTriggersAvailable: () => {
1043
+ var u;
1044
+ return ((u = a.streamingManager) == null ? void 0 : u.triggersAvailable) ?? !1;
1045
+ },
1046
+ starterMessages: ((K = l.knowledge) == null ? void 0 : K.starter_message) || [],
1173
1047
  getSTTToken: () => d.getSTTToken(l.id),
1174
- changeMode: R,
1048
+ changeMode: U,
1175
1049
  enrichAnalytics: i.enrich,
1176
1050
  async connect() {
1177
- await j(!0), i.track("agent-chat", {
1051
+ await b(!0), i.track("agent-chat", {
1178
1052
  event: "connect",
1179
1053
  mode: a.chatMode
1180
1054
  });
1181
1055
  },
1182
1056
  async reconnect() {
1183
- await x(), await j(!1), i.track("agent-chat", {
1057
+ await z(), await b(!1), i.track("agent-chat", {
1184
1058
  event: "reconnect",
1185
1059
  mode: a.chatMode
1186
1060
  });
1187
1061
  },
1188
1062
  async disconnect() {
1189
- await x(), i.track("agent-chat", {
1063
+ await z(), i.track("agent-chat", {
1190
1064
  event: "disconnect",
1191
1065
  mode: a.chatMode
1192
1066
  });
1193
1067
  },
1194
1068
  async chat(u) {
1195
- var w, p, b, L, $;
1196
- const v = () => {
1197
- if (ce(t.mode))
1069
+ var v, f, S, T, L;
1070
+ const h = () => {
1071
+ if (ue(t.mode))
1198
1072
  throw new H(`${t.mode} is enabled, chat is disabled`);
1199
1073
  if (u.length >= 800)
1200
1074
  throw new H("Message cannot be more than 800 characters");
1201
1075
  if (u.length === 0)
1202
1076
  throw new H("Message cannot be empty");
1203
- if (a.chatMode === M.Maintenance)
1077
+ if (a.chatMode === E.Maintenance)
1204
1078
  throw new H("Chat is in maintenance mode");
1205
- if (![M.TextOnly, M.Playground].includes(a.chatMode)) {
1079
+ if (![E.TextOnly, E.Playground].includes(a.chatMode)) {
1206
1080
  if (!a.streamingManager)
1207
1081
  throw new H("Streaming manager is not initialized");
1208
1082
  if (!a.chat)
1209
1083
  throw new H("Chat is not initialized");
1210
1084
  }
1211
- }, m = async () => {
1212
- var k, E;
1085
+ }, p = async () => {
1086
+ var D, I;
1213
1087
  if (!a.chat) {
1214
- const C = await we(l, d, i, a.chatMode, t.persistentChat);
1215
- if (!C.chat)
1216
- throw new ke(a.chatMode, !!t.persistentChat);
1217
- a.chat = C.chat, (E = (k = t.callbacks).onNewChat) == null || E.call(k, a.chat.id);
1088
+ const k = await ve(
1089
+ l,
1090
+ d,
1091
+ i,
1092
+ a.chatMode,
1093
+ t.persistentChat
1094
+ );
1095
+ if (!k.chat)
1096
+ throw new Ce(a.chatMode, !!t.persistentChat);
1097
+ a.chat = k.chat, (I = (D = t.callbacks).onNewChat) == null || I.call(D, a.chat.id);
1218
1098
  }
1219
1099
  return a.chat.id;
1220
- }, D = async (k, E) => te(() => {
1221
- var C, z;
1222
- return d.chat(l.id, E, {
1223
- chatMode: a.chatMode,
1224
- streamId: (C = a.streamingManager) == null ? void 0 : C.streamId,
1225
- sessionId: (z = a.streamingManager) == null ? void 0 : z.sessionId,
1226
- messages: k.map(({
1227
- matches: F,
1228
- ...J
1229
- }) => J)
1230
- }, {
1231
- ...he(a.chatMode),
1232
- skipErrorHandler: !0
1233
- });
1234
- }, {
1235
- limit: 2,
1236
- shouldRetryFn: (C) => {
1237
- var J, f, g, S;
1238
- const z = (J = C == null ? void 0 : C.message) == null ? void 0 : J.includes("missing or invalid session_id");
1239
- return !((f = C == null ? void 0 : C.message) == null ? void 0 : f.includes("Stream Error")) && !z ? ((S = (g = t.callbacks).onError) == null || S.call(g, C), !1) : !0;
1100
+ }, _ = async (D, I) => ne(
1101
+ () => {
1102
+ var k, x;
1103
+ return d.chat(
1104
+ l.id,
1105
+ I,
1106
+ {
1107
+ chatMode: a.chatMode,
1108
+ streamId: (k = a.streamingManager) == null ? void 0 : k.streamId,
1109
+ sessionId: (x = a.streamingManager) == null ? void 0 : x.sessionId,
1110
+ messages: D.map(({ matches: B, ...F }) => F)
1111
+ },
1112
+ {
1113
+ ...ye(a.chatMode),
1114
+ skipErrorHandler: !0
1115
+ }
1116
+ );
1240
1117
  },
1241
- onRetry: async () => {
1242
- await x(), await j(!1);
1118
+ {
1119
+ limit: 2,
1120
+ shouldRetryFn: (k) => {
1121
+ var F, N, X, Y;
1122
+ const x = (F = k == null ? void 0 : k.message) == null ? void 0 : F.includes("missing or invalid session_id");
1123
+ return !((N = k == null ? void 0 : k.message) == null ? void 0 : N.includes("Stream Error")) && !x ? ((Y = (X = t.callbacks).onError) == null || Y.call(X, k), !1) : !0;
1124
+ },
1125
+ onRetry: async () => {
1126
+ await z(), await b(!1);
1127
+ }
1243
1128
  }
1244
- });
1129
+ );
1245
1130
  try {
1246
- _(), v(), a.messages.push({
1131
+ M(), h(), a.messages.push({
1247
1132
  id: V(),
1248
1133
  role: "user",
1249
1134
  content: u,
1250
- created_at: new Date(N.update()).toISOString()
1251
- }), (p = (w = t.callbacks).onNewMessage) == null || p.call(w, [...a.messages], "user");
1252
- const k = await m(), E = await D([...a.messages], k);
1135
+ created_at: new Date($.update()).toISOString()
1136
+ }), (f = (v = t.callbacks).onNewMessage) == null || f.call(v, [...a.messages], "user");
1137
+ const D = await p(), I = await _([...a.messages], D);
1253
1138
  return a.messages.push({
1254
1139
  id: V(),
1255
1140
  role: "assistant",
1256
- content: E.result || "",
1141
+ content: I.result || "",
1257
1142
  created_at: (/* @__PURE__ */ new Date()).toISOString(),
1258
- context: E.context,
1259
- matches: E.matches
1143
+ context: I.context,
1144
+ matches: I.matches
1260
1145
  }), i.track("agent-message-send", {
1261
1146
  event: "success",
1262
1147
  messages: a.messages.length + 1
1263
- }), E.result && ((L = (b = t.callbacks).onNewMessage) == null || L.call(b, [...a.messages], "answer"), i.track("agent-message-received", {
1264
- latency: N.get(!0),
1148
+ }), I.result && ((T = (S = t.callbacks).onNewMessage) == null || T.call(S, [...a.messages], "answer"), i.track("agent-message-received", {
1149
+ latency: $.get(!0),
1265
1150
  messages: a.messages.length
1266
- })), E;
1267
- } catch (k) {
1268
- throw (($ = a.messages[a.messages.length - 1]) == null ? void 0 : $.role) === "assistant" && a.messages.pop(), i.track("agent-message-send", {
1151
+ })), I;
1152
+ } catch (D) {
1153
+ throw ((L = a.messages[a.messages.length - 1]) == null ? void 0 : L.role) === "assistant" && a.messages.pop(), i.track("agent-message-send", {
1269
1154
  event: "error",
1270
1155
  messages: a.messages.length
1271
- }), k;
1156
+ }), D;
1272
1157
  }
1273
1158
  },
1274
- rate(u, v, m) {
1275
- var p, b, L, $;
1276
- const D = a.messages.find((k) => k.id === u);
1159
+ rate(u, h, p) {
1160
+ var f, S, T, L;
1161
+ const _ = a.messages.find((D) => D.id === u);
1277
1162
  if (a.chat) {
1278
- if (!D)
1163
+ if (!_)
1279
1164
  throw new Error("Message not found");
1280
- } else
1281
- throw new Error("Chat is not initialized");
1282
- const w = ((p = D.matches) == null ? void 0 : p.map((k) => [k.document_id, k.id])) ?? [];
1165
+ } else throw new Error("Chat is not initialized");
1166
+ const v = ((f = _.matches) == null ? void 0 : f.map((D) => [D.document_id, D.id])) ?? [];
1283
1167
  return i.track("agent-rate", {
1284
- event: m ? "update" : "create",
1285
- thumb: v === 1 ? "up" : "down",
1286
- knowledge_id: ((b = l.knowledge) == null ? void 0 : b.id) ?? "",
1287
- matches: w,
1288
- score: v
1289
- }), m ? d.updateRating(l.id, a.chat.id, m, {
1290
- knowledge_id: ((L = l.knowledge) == null ? void 0 : L.id) ?? "",
1168
+ event: p ? "update" : "create",
1169
+ thumb: h === 1 ? "up" : "down",
1170
+ knowledge_id: ((S = l.knowledge) == null ? void 0 : S.id) ?? "",
1171
+ matches: v,
1172
+ score: h
1173
+ }), p ? d.updateRating(l.id, a.chat.id, p, {
1174
+ knowledge_id: ((T = l.knowledge) == null ? void 0 : T.id) ?? "",
1291
1175
  message_id: u,
1292
- matches: w,
1293
- score: v
1176
+ matches: v,
1177
+ score: h
1294
1178
  }) : d.createRating(l.id, a.chat.id, {
1295
- knowledge_id: (($ = l.knowledge) == null ? void 0 : $.id) ?? "",
1179
+ knowledge_id: ((L = l.knowledge) == null ? void 0 : L.id) ?? "",
1296
1180
  message_id: u,
1297
- matches: w,
1298
- score: v
1181
+ matches: v,
1182
+ score: h
1299
1183
  });
1300
1184
  },
1301
1185
  deleteRate(u) {
1302
1186
  if (!a.chat)
1303
1187
  throw new Error("Chat is not initialized");
1304
- return i.track("agent-rate-delete", {
1305
- type: "text"
1306
- }), d.deleteRating(l.id, a.chat.id, u);
1188
+ return i.track("agent-rate-delete", { type: "text" }), d.deleteRating(l.id, a.chat.id, u);
1307
1189
  },
1308
1190
  async speak(u) {
1309
- var w, p, b;
1310
- function v() {
1191
+ var v, f, S;
1192
+ function h() {
1311
1193
  if (typeof u == "string") {
1312
1194
  if (!l.presenter.voice)
1313
1195
  throw new Error("Presenter voice is not initialized");
@@ -1330,13 +1212,13 @@ async function Et(e, t) {
1330
1212
  }
1331
1213
  return u;
1332
1214
  }
1333
- const m = v();
1334
- if (i.track("agent-speak", m), N.update(), a.messages && m.type === "text" && (a.messages.push({
1215
+ const p = h();
1216
+ if (i.track("agent-speak", p), $.update(), a.messages && p.type === "text" && (a.messages.push({
1335
1217
  id: V(),
1336
1218
  role: "assistant",
1337
- content: m.input,
1338
- created_at: new Date(N.get(!0)).toISOString()
1339
- }), (p = (w = t.callbacks).onNewMessage) == null || p.call(w, [...a.messages], "answer")), ze(a.chatMode))
1219
+ content: p.input,
1220
+ created_at: new Date($.get(!0)).toISOString()
1221
+ }), (f = (v = t.callbacks).onNewMessage) == null || f.call(v, [...a.messages], "answer")), Fe(a.chatMode))
1340
1222
  return {
1341
1223
  duration: 0,
1342
1224
  video_id: "",
@@ -1345,57 +1227,51 @@ async function Et(e, t) {
1345
1227
  if (!a.streamingManager)
1346
1228
  throw new Error("Please connect to the agent first");
1347
1229
  return a.streamingManager.speak({
1348
- script: m,
1349
- metadata: {
1350
- chat_id: (b = a.chat) == null ? void 0 : b.id,
1351
- agent_id: l.id
1352
- }
1230
+ script: p,
1231
+ metadata: { chat_id: (S = a.chat) == null ? void 0 : S.id, agent_id: l.id }
1353
1232
  });
1354
1233
  },
1355
- async interrupt({
1356
- type: u
1357
- }) {
1358
- var m, D, w;
1359
- Oe(a.streamingManager, (m = a.streamingManager) == null ? void 0 : m.streamType, r);
1360
- const v = a.messages[a.messages.length - 1];
1234
+ async interrupt({ type: u }) {
1235
+ var p, _, v;
1236
+ Ye(a.streamingManager, (p = a.streamingManager) == null ? void 0 : p.streamType, r);
1237
+ const h = a.messages[a.messages.length - 1];
1361
1238
  i.track("agent-video-interrupt", {
1362
1239
  type: u || "click",
1363
- video_duration_to_interrupt: re.get(!0),
1364
- message_duration_to_interrupt: N.get(!0)
1365
- }), v.interrupted = !0, (w = (D = t.callbacks).onNewMessage) == null || w.call(D, [...a.messages], "answer"), Xe(a.streamingManager, r);
1240
+ video_duration_to_interrupt: ae.get(!0),
1241
+ message_duration_to_interrupt: $.get(!0)
1242
+ }), h.interrupted = !0, (v = (_ = t.callbacks).onNewMessage) == null || v.call(_, [...a.messages], "answer"), Qe(a.streamingManager, r);
1366
1243
  }
1367
1244
  };
1368
1245
  }
1369
- function Mt(e, t, n) {
1370
- const {
1371
- getById: r
1372
- } = fe(t, n || Z);
1246
+ function bt(e, t, n) {
1247
+ const { getById: r } = he(t, n || ee);
1373
1248
  return r(e);
1374
1249
  }
1375
1250
  export {
1376
1251
  O as AgentActivityState,
1377
- Ie as AgentStatus,
1378
- ke as ChatCreationFailed,
1379
- M as ChatMode,
1380
- De as ChatModeDowngraded,
1252
+ Me as AgentStatus,
1253
+ Ce as ChatCreationFailed,
1254
+ E as ChatMode,
1255
+ Re as ChatModeDowngraded,
1381
1256
  q as ChatProgress,
1382
- I as ConnectionState,
1383
- Q as ConnectivityState,
1384
- Te as DocumentType,
1385
- _e as KnowledgeType,
1386
- Se as PlanGroup,
1257
+ R as ConnectionState,
1258
+ G as ConnectivityState,
1259
+ Ae as DocumentType,
1260
+ je as KnowledgeType,
1261
+ Ee as PlanGroup,
1387
1262
  Pe as Providers,
1388
- Ee as RateState,
1389
- A as StreamEvents,
1390
- W as StreamType,
1391
- h as StreamingState,
1392
- Me as Subject,
1393
- Re as UserPlan,
1263
+ _e as RateState,
1264
+ P as StreamEvents,
1265
+ J as StreamType,
1266
+ w as StreamingState,
1267
+ Te as Subject,
1268
+ be as Transport,
1269
+ Ie as UserPlan,
1394
1270
  H as ValidationError,
1395
- je as VideoType,
1396
- be as VoiceAccess,
1397
- Ce as WsError,
1398
- Et as createAgentManager,
1399
- Mt as getAgent,
1400
- It as mapVideoType
1271
+ de as VideoType,
1272
+ Le as VoiceAccess,
1273
+ Se as WsError,
1274
+ At as createAgentManager,
1275
+ bt as getAgent,
1276
+ jt as mapVideoType
1401
1277
  };