@d-id/client-sdk 3.0.0-staging.414 → 3.0.0-staging.415

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 (120) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +2 -0
  3. package/dist/index-D0K-5SID.js +2037 -0
  4. package/dist/index.d.ts +3270 -0
  5. package/dist/index.js +1 -1
  6. package/dist/index.umd.cjs +13 -13
  7. package/dist/{index-DBWnR72S.js → livekit-client.esm-QkbCKsng.js} +6234 -8269
  8. package/dist/livekit-manager-CU_yynQK.js +557 -0
  9. package/package.json +33 -9
  10. package/dist/livekit-manager-BM3JMzT5.js +0 -531
  11. package/dist/src/api/agents.d.ts +0 -18
  12. package/dist/src/api/apiClient.d.ts +0 -11
  13. package/dist/src/api/apiClient.test.d.ts +0 -1
  14. package/dist/src/api/knowledge.d.ts +0 -15
  15. package/dist/src/api/streams/index.d.ts +0 -1
  16. package/dist/src/api/streams/streamApi.d.ts +0 -3
  17. package/dist/src/api/streams/streamApi.test.d.ts +0 -1
  18. package/dist/src/api/streams/streamsApiV2.d.ts +0 -5
  19. package/dist/src/auth/get-auth-header.d.ts +0 -5
  20. package/dist/src/auth/get-auth-header.test.d.ts +0 -1
  21. package/dist/src/config/consts.d.ts +0 -3
  22. package/dist/src/config/environment.d.ts +0 -5
  23. package/dist/src/errors/base-error.d.ts +0 -182
  24. package/dist/src/errors/chat/chat-creation-failed.d.ts +0 -30
  25. package/dist/src/errors/chat/chat-mode-downgraded.d.ts +0 -35
  26. package/dist/src/errors/errors.test.d.ts +0 -1
  27. package/dist/src/errors/http-error.d.ts +0 -74
  28. package/dist/src/errors/index.d.ts +0 -9
  29. package/dist/src/errors/network-error.d.ts +0 -72
  30. package/dist/src/errors/request-meta.d.ts +0 -12
  31. package/dist/src/errors/stream-error.d.ts +0 -37
  32. package/dist/src/errors/validation-error.d.ts +0 -67
  33. package/dist/src/errors/ws-error.d.ts +0 -34
  34. package/dist/src/index.d.ts +0 -20
  35. package/dist/src/public-api.test.d.ts +0 -1
  36. package/dist/src/services/agent-manager/connect-to-manager.d.ts +0 -19
  37. package/dist/src/services/agent-manager/connect-to-manager.test.d.ts +0 -1
  38. package/dist/src/services/agent-manager/index.d.ts +0 -64
  39. package/dist/src/services/agent-manager/index.test.d.ts +0 -1
  40. package/dist/src/services/analytics/mixpanel.d.ts +0 -22
  41. package/dist/src/services/analytics/mixpanel.test.d.ts +0 -1
  42. package/dist/src/services/analytics/timestamp-tracker.d.ts +0 -15
  43. package/dist/src/services/chat/index.d.ts +0 -10
  44. package/dist/src/services/chat/index.test.d.ts +0 -1
  45. package/dist/src/services/chat/intial-messages.d.ts +0 -3
  46. package/dist/src/services/chat/intial-messages.test.d.ts +0 -1
  47. package/dist/src/services/socket-manager/index.d.ts +0 -12
  48. package/dist/src/services/socket-manager/message-queue.d.ts +0 -12
  49. package/dist/src/services/socket-manager/message-queue.test.d.ts +0 -1
  50. package/dist/src/services/streaming-manager/advanced.test.d.ts +0 -1
  51. package/dist/src/services/streaming-manager/business-flows.test.d.ts +0 -5
  52. package/dist/src/services/streaming-manager/common.d.ts +0 -101
  53. package/dist/src/services/streaming-manager/data-channel-handlers.d.ts +0 -3
  54. package/dist/src/services/streaming-manager/disconnect.test.d.ts +0 -5
  55. package/dist/src/services/streaming-manager/edge-cases.test.d.ts +0 -1
  56. package/dist/src/services/streaming-manager/factory.d.ts +0 -13
  57. package/dist/src/services/streaming-manager/factory.test.d.ts +0 -1
  58. package/dist/src/services/streaming-manager/index.d.ts +0 -5
  59. package/dist/src/services/streaming-manager/livekit-manager.d.ts +0 -10
  60. package/dist/src/services/streaming-manager/livekit-manager.test.d.ts +0 -1
  61. package/dist/src/services/streaming-manager/stats/av-sync.d.ts +0 -3
  62. package/dist/src/services/streaming-manager/stats/av-sync.test.d.ts +0 -1
  63. package/dist/src/services/streaming-manager/stats/poll.d.ts +0 -16
  64. package/dist/src/services/streaming-manager/stats/report.d.ts +0 -19
  65. package/dist/src/services/streaming-manager/stats/report.test.d.ts +0 -1
  66. package/dist/src/services/streaming-manager/webrtc-core.test.d.ts +0 -1
  67. package/dist/src/services/streaming-manager/webrtc-manager.d.ts +0 -12
  68. package/dist/src/services/streaming-manager/webrtc-utils.test.d.ts +0 -5
  69. package/dist/src/test-utils/factories/agent-manager.factory.d.ts +0 -3
  70. package/dist/src/test-utils/factories/agent.factory.d.ts +0 -4
  71. package/dist/src/test-utils/factories/agents-api.factory.d.ts +0 -1
  72. package/dist/src/test-utils/factories/analytics.factory.d.ts +0 -1
  73. package/dist/src/test-utils/factories/chat.factory.d.ts +0 -1
  74. package/dist/src/test-utils/factories/index.d.ts +0 -8
  75. package/dist/src/test-utils/factories/socket-manager.factory.d.ts +0 -1
  76. package/dist/src/test-utils/factories/stream-api.factory.d.ts +0 -1
  77. package/dist/src/test-utils/factories/streaming-manager.factory.d.ts +0 -4
  78. package/dist/src/types/auth.d.ts +0 -95
  79. package/dist/src/types/entities/agents/agent.d.ts +0 -202
  80. package/dist/src/types/entities/agents/chat.d.ts +0 -476
  81. package/dist/src/types/entities/agents/index.d.ts +0 -3
  82. package/dist/src/types/entities/agents/manager.d.ts +0 -897
  83. package/dist/src/types/entities/avatar.d.ts +0 -21
  84. package/dist/src/types/entities/index.d.ts +0 -3
  85. package/dist/src/types/entities/knowledge/document.d.ts +0 -31
  86. package/dist/src/types/entities/knowledge/index.d.ts +0 -4
  87. package/dist/src/types/entities/knowledge/knowledge.d.ts +0 -56
  88. package/dist/src/types/entities/knowledge/record.d.ts +0 -24
  89. package/dist/src/types/entities/knowledge/retrival.d.ts +0 -9
  90. package/dist/src/types/face-rect.d.ts +0 -6
  91. package/dist/src/types/index.d.ts +0 -6
  92. package/dist/src/types/stream/api/clip.d.ts +0 -122
  93. package/dist/src/types/stream/api/index.d.ts +0 -2
  94. package/dist/src/types/stream/api/talk.d.ts +0 -77
  95. package/dist/src/types/stream/data-channel.d.ts +0 -16
  96. package/dist/src/types/stream/index.d.ts +0 -4
  97. package/dist/src/types/stream/rtc.d.ts +0 -125
  98. package/dist/src/types/stream/stream.d.ts +0 -856
  99. package/dist/src/types/stream/streams-v2.d.ts +0 -28
  100. package/dist/src/types/stream-script.d.ts +0 -138
  101. package/dist/src/types/voice/stt.d.ts +0 -16
  102. package/dist/src/types/voice/tts.d.ts +0 -238
  103. package/dist/src/utils/agent.d.ts +0 -8
  104. package/dist/src/utils/analytics.d.ts +0 -31
  105. package/dist/src/utils/analytics.test.d.ts +0 -1
  106. package/dist/src/utils/chat.d.ts +0 -4
  107. package/dist/src/utils/content-parser.d.ts +0 -35
  108. package/dist/src/utils/content-parser.test.d.ts +0 -1
  109. package/dist/src/utils/defer.d.ts +0 -7
  110. package/dist/src/utils/error-analytics.d.ts +0 -4
  111. package/dist/src/utils/error-analytics.test.d.ts +0 -1
  112. package/dist/src/utils/index.d.ts +0 -3
  113. package/dist/src/utils/retry-operation.d.ts +0 -38
  114. package/dist/src/utils/stream-end.d.ts +0 -5
  115. package/dist/src/utils/stream-end.test.d.ts +0 -1
  116. package/dist/src/utils/tool-calls.d.ts +0 -27
  117. package/dist/src/utils/tool-calls.test.d.ts +0 -1
  118. package/dist/src/utils/user-context.d.ts +0 -15
  119. package/dist/src/utils/user-context.test.d.ts +0 -1
  120. package/dist/src/version.d.ts +0 -7
@@ -0,0 +1,2037 @@
1
+ var vt = Object.defineProperty;
2
+ var St = (e, t, n) => t in e ? vt(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
3
+ var A = (e, t, n) => St(e, typeof t != "symbol" ? t + "" : t, n);
4
+ var ye = /* @__PURE__ */ ((e) => (e.Chat = "lk.chat", e.Speak = "did.speak", e.Interrupt = "did.interrupt", e.SttLanguage = "did.stt-language", e.Presentation = "did.presentation", e))(ye || {}), P = /* @__PURE__ */ ((e) => (e.Functional = "Functional", e.TextOnly = "TextOnly", e.Maintenance = "Maintenance", e.Playground = "Playground", e.DirectPlayback = "DirectPlayback", e.Off = "Off", e))(P || {}), N = /* @__PURE__ */ ((e) => (e.Embed = "embed", e.Query = "query", e.Partial = "partial", e.Answer = "answer", e.Transcribe = "transcribe", e.Complete = "done", e))(N || {}), ne = /* @__PURE__ */ ((e) => (e.Clip = "clip", e.Talk = "talk", e.Expressive = "expressive", e))(ne || {}), k = /* @__PURE__ */ ((e) => (e.Start = "START", e.Stop = "STOP", e))(k || {}), oe = /* @__PURE__ */ ((e) => (e.Strong = "STRONG", e.Weak = "WEAK", e.Unknown = "UNKNOWN", e))(oe || {}), le = /* @__PURE__ */ ((e) => (e.Idle = "IDLE", e.Loading = "LOADING", e.Talking = "TALKING", e.ToolActive = "TOOL_ACTIVE", e))(le || {}), I = /* @__PURE__ */ ((e) => (e.ChatAnswer = "chat/answer", e.ChatPartial = "chat/partial", e.ChatAudioTranscribed = "chat/audio-transcribed", e.StreamDone = "stream/done", e.StreamStarted = "stream/started", e.StreamFailed = "stream/error", e.StreamReady = "stream/ready", 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.ToolCallStarted = "tool-call/started", e.ToolCallDone = "tool-call/done", e.ToolCallError = "tool-call/error", e.TurnStarted = "turn/started", e.TurnEnded = "turn/ended", e))(I || {}), Ee = /* @__PURE__ */ ((e) => (e.Started = "tool-call/started", e.Done = "tool-call/done", e.Error = "tool-call/error", e))(Ee || {}), kt = /* @__PURE__ */ ((e) => (e.Presentation = "did.presentation", e))(kt || {}), x = /* @__PURE__ */ ((e) => (e.New = "new", e.Fail = "fail", e.Connected = "connected", e.Connecting = "connecting", e.Closed = "closed", e.Completed = "completed", e.Disconnecting = "disconnecting", e.Disconnected = "disconnected", e))(x || {}), J = /* @__PURE__ */ ((e) => (e.Legacy = "legacy", e.Fluent = "fluent", e))(J || {}), ce = /* @__PURE__ */ ((e) => (e.Ok = "ok", e.UnknownError = "unknown_error", e.NetworkIssue = "network_issue", e.MessageLimit = "message_limit", e.TimeLimit = "time_limit", e.Inactivity = "inactivity", e.EndedByAgent = "ended_by_agent", e))(ce || {}), Le = /* @__PURE__ */ ((e) => (e.Livekit = "livekit", e))(Le || {}), Ct = /* @__PURE__ */ ((e) => (e.Amazon = "amazon", e.AzureOpenAi = "azure-openai", e.Microsoft = "microsoft", e.Elevenlabs = "elevenlabs", e))(Ct || {}), Mt = /* @__PURE__ */ ((e) => (e.Public = "public", e.Premium = "premium", e.Private = "private", e))(Mt || {});
5
+ const Nn = (...e) => {
6
+ }, it = (e) => new Promise((t) => setTimeout(t, e)), Y = (e = 16) => {
7
+ const t = new Uint8Array(e);
8
+ return globalThis.crypto.getRandomValues(t), Array.from(t, (n) => n.toString(16).padStart(2, "0")).join("").slice(0, 13);
9
+ };
10
+ function Te(e) {
11
+ if (e !== void 0)
12
+ return window.localStorage.setItem("did_external_key_id", e), e;
13
+ let t = window.localStorage.getItem("did_external_key_id");
14
+ if (!t) {
15
+ let n = Y();
16
+ window.localStorage.setItem("did_external_key_id", n), t = n;
17
+ }
18
+ return t;
19
+ }
20
+ let ot;
21
+ function Me() {
22
+ return ot ?? (ot = Y());
23
+ }
24
+ function Dt() {
25
+ ot = Y();
26
+ }
27
+ function ct(e, t) {
28
+ if (e.type === "bearer")
29
+ return `Bearer ${e.token}~${Me()}`;
30
+ if (e.type === "basic")
31
+ return `Basic ${"token" in e ? e.token : btoa(`${e.username}:${e.password}`)}~${Me()}`;
32
+ if (e.type === "key")
33
+ return `Client-Key ${e.clientKey}.${Te(t)}_${Me()}`;
34
+ throw new Error(`Unknown auth type: ${e}`);
35
+ }
36
+ const Rt = 45 * 1e3, bt = "X-Playground-Chat", Fe = 2e3, ve = "https://api.d-id.com", It = "wss://notifications.d-id.com", Et = "79f81a83a67430be2bc0fd61042b8faa";
37
+ class K extends Error {
38
+ /**
39
+ * Creates an SDK error. The SDK builds these itself; applications normally only catch them.
40
+ *
41
+ * @param message - Human-readable description of the failure, used as the `Error` message.
42
+ * @param kind - Stable machine-readable code for the failure.
43
+ * @param originalError - The underlying error or value this one wraps, when there is one.
44
+ */
45
+ constructor(t, n = "Error", a) {
46
+ super(t), this.kind = n, this.originalError = a, Object.setPrototypeOf(this, new.target.prototype);
47
+ }
48
+ /**
49
+ * Serializes the error into the JSON-safe {@link ErrorJson} payload for logging or reporting.
50
+ *
51
+ * The payload always carries {@link BaseError.kind | kind} and the message. The cause's message
52
+ * is added only when {@link BaseError.originalError | originalError} is an `Error` and says
53
+ * something the message does not, truncated to 256 characters; any other cause is dropped.
54
+ * Subclasses extend the payload with the fields listed on their own pages.
55
+ *
56
+ * @returns The error as plain, JSON-serializable data.
57
+ * @example An HttpError from a request that was refused
58
+ * ```json
59
+ * {
60
+ * "kind": "InsufficientCreditsError",
61
+ * "message": "Account has insufficient credits",
62
+ * "httpStatus": 402,
63
+ * "endpoint": "/agt_x/chat/cht_y",
64
+ * "method": "POST"
65
+ * }
66
+ * ```
67
+ * @example A NetworkError from a request that never left the browser
68
+ * ```json
69
+ * {
70
+ * "kind": "NetworkError",
71
+ * "message": "Network request failed",
72
+ * "cause": "Failed to fetch",
73
+ * "endpoint": "/agt_x/chat/cht_y",
74
+ * "method": "POST",
75
+ * "durationMs": 12,
76
+ * "online": false,
77
+ * "visibility": "visible"
78
+ * }
79
+ * ```
80
+ */
81
+ toJson() {
82
+ const t = this.originalError instanceof Error ? this.originalError.message.slice(0, 256) : void 0;
83
+ return {
84
+ kind: this.kind,
85
+ message: this.message,
86
+ ...t && t !== this.message ? { cause: t } : {}
87
+ };
88
+ }
89
+ }
90
+ function Fn(e) {
91
+ return e instanceof Error && typeof e.kind == "string";
92
+ }
93
+ class Tt extends K {
94
+ /**
95
+ * Builds the error from the attempt that failed.
96
+ * @internal The SDK builds this itself; applications catch the error rather than construct it.
97
+ */
98
+ constructor(n, a) {
99
+ super(`Failed to create ${a ? "persistent " : ""}chat, mode: ${n}`, "ChatCreationFailed");
100
+ /**
101
+ * Always `'ChatCreationFailed'`. Branch on it to tell this failure from the other SDK errors.
102
+ */
103
+ A(this, "kind", "ChatCreationFailed");
104
+ }
105
+ }
106
+ class _t extends K {
107
+ /**
108
+ * Builds the error from the mode the session ended up in.
109
+ * @internal The SDK builds this itself; applications catch the error rather than construct it.
110
+ */
111
+ constructor(n) {
112
+ super(`Chat mode downgraded to ${n}`, "ChatModeDowngraded");
113
+ /**
114
+ * Always `'ChatModeDowngraded'`. Branch on it to tell this failure from the other SDK errors.
115
+ */
116
+ A(this, "kind", "ChatModeDowngraded");
117
+ }
118
+ }
119
+ function At(e) {
120
+ try {
121
+ const t = JSON.parse(e);
122
+ if (t && typeof t == "object" && typeof t.kind == "string")
123
+ return t;
124
+ } catch {
125
+ }
126
+ }
127
+ class dt extends K {
128
+ /**
129
+ * Builds the error from the failing response.
130
+ * @internal The SDK builds this itself; applications catch the error rather than construct it.
131
+ */
132
+ constructor(n, a, o = {}) {
133
+ const i = At(a);
134
+ super(((i == null ? void 0 : i.description) ?? a).slice(0, 256), "HttpError");
135
+ /**
136
+ * Always `'HttpError'`. Branch on it to tell this failure from the other SDK errors.
137
+ */
138
+ A(this, "kind", "HttpError");
139
+ /**
140
+ * The Agents API's own classification of the failure — the `kind` from D-ID's
141
+ * `{ kind, description }` error body — and `'HttpError'` when the response was not that
142
+ * envelope.
143
+ *
144
+ * An account out of credits comes back as `'InsufficientCreditsError'`, for instance. It is a
145
+ * plain `string` because the set is the API's, not the SDK's, and grows without an SDK release.
146
+ * Use {@link HttpError.status | status} for the transport-level branch, this for the API-level
147
+ * one, and {@link BaseError.kind | kind} to tell an `HttpError` from the SDK's other errors.
148
+ */
149
+ A(this, "code");
150
+ /**
151
+ * HTTP status code of the response, such as `401`, `404` or `500`.
152
+ */
153
+ A(this, "status");
154
+ /**
155
+ * Path of the request that failed, relative to the API client's base path — for example
156
+ * `/agt_x/chat/cht_y` for a message sent to a chat.
157
+ *
158
+ * Absent when the error was constructed without call context. {@link NetworkError.endpoint}
159
+ * is the same value on a transport failure.
160
+ */
161
+ A(this, "endpoint");
162
+ /**
163
+ * HTTP method of the request that failed, such as `GET` or `POST`.
164
+ *
165
+ * Absent when the error was constructed without call context.
166
+ */
167
+ A(this, "method");
168
+ this.code = (i == null ? void 0 : i.kind) ?? "HttpError", this.status = n, this.endpoint = o.endpoint, this.method = o.method;
169
+ }
170
+ /**
171
+ * Serializes the error, adding the failing call to what
172
+ * {@link BaseError.toJson | BaseError.toJson()} already returns.
173
+ *
174
+ * Adds {@link HttpError.code | code}, `httpStatus` from {@link HttpError.status | status}, and
175
+ * `endpoint` and `method` when the call context is known. The raw `status` property is
176
+ * serialized as `httpStatus`.
177
+ *
178
+ * @returns The error as plain, JSON-serializable data.
179
+ */
180
+ toJson() {
181
+ return {
182
+ ...super.toJson(),
183
+ code: this.code,
184
+ httpStatus: this.status,
185
+ ...this.endpoint ? { endpoint: this.endpoint } : {},
186
+ ...this.method ? { method: this.method } : {}
187
+ };
188
+ }
189
+ }
190
+ class Pt extends K {
191
+ /**
192
+ * Wraps a rejected `fetch` together with what was known about the call.
193
+ * @internal The SDK builds this itself; applications catch the error rather than construct it.
194
+ */
195
+ constructor(n, a = {}) {
196
+ super("Network request failed", "NetworkError", n);
197
+ /**
198
+ * Always `'NetworkError'`. Branch on it to tell this failure from the other SDK errors.
199
+ */
200
+ A(this, "kind", "NetworkError");
201
+ /**
202
+ * Path of the request that failed, relative to the API client's base path — for example
203
+ * `/agt_x/chat/cht_y`.
204
+ */
205
+ A(this, "endpoint");
206
+ /**
207
+ * HTTP method of the request that failed, such as `GET` or `POST`.
208
+ */
209
+ A(this, "method");
210
+ /**
211
+ * How long the request ran before it failed, in milliseconds.
212
+ *
213
+ * A value close to zero usually means the request never left the browser; a large one points
214
+ * at a connection that was established and then lost.
215
+ */
216
+ A(this, "durationMs");
217
+ /**
218
+ * The browser's `navigator.onLine` at the moment of the failure — `false` when the device
219
+ * reported itself offline.
220
+ */
221
+ A(this, "online");
222
+ /**
223
+ * The page's `document.visibilityState` at the moment of the failure.
224
+ *
225
+ * `'hidden'` means the tab was in the background, where browsers throttle or suspend network
226
+ * activity.
227
+ */
228
+ A(this, "visibility");
229
+ this.endpoint = a.endpoint, this.method = a.method, this.durationMs = a.durationMs, this.online = a.online, this.visibility = a.visibility;
230
+ }
231
+ /**
232
+ * Serializes the error, adding the captured context to what
233
+ * {@link BaseError.toJson | BaseError.toJson()} already returns.
234
+ *
235
+ * Each of `endpoint`, `method`, `durationMs`, `online` and `visibility` is included only when it
236
+ * was captured.
237
+ *
238
+ * @returns The error as plain, JSON-serializable data.
239
+ */
240
+ toJson() {
241
+ return {
242
+ ...super.toJson(),
243
+ ...this.endpoint ? { endpoint: this.endpoint } : {},
244
+ ...this.method ? { method: this.method } : {},
245
+ ...this.durationMs !== void 0 ? { durationMs: this.durationMs } : {},
246
+ ...this.online !== void 0 ? { online: this.online } : {},
247
+ ...this.visibility ? { visibility: this.visibility } : {}
248
+ };
249
+ }
250
+ }
251
+ class lt extends K {
252
+ /**
253
+ * Wraps a streaming failure.
254
+ * @internal The SDK builds this itself; applications catch the error rather than construct it.
255
+ */
256
+ constructor(n, a) {
257
+ super(n, "StreamError", a);
258
+ /**
259
+ * Always `'StreamError'`. Branch on it to tell this failure from the other SDK errors.
260
+ */
261
+ A(this, "kind", "StreamError");
262
+ }
263
+ }
264
+ class E extends K {
265
+ /**
266
+ * Builds a validation failure. The SDK does this itself before it performs a request.
267
+ *
268
+ * @param message - What was wrong with the call, such as `'Message cannot be empty'`.
269
+ * @param key - Name of the field the failure is about. The SDK's own validations leave it
270
+ * unset.
271
+ */
272
+ constructor(n, a) {
273
+ super(n, "ValidationError");
274
+ /**
275
+ * Always `'ValidationError'`. Branch on it to tell this failure from the other SDK errors.
276
+ */
277
+ A(this, "kind", "ValidationError");
278
+ this.key = a;
279
+ }
280
+ }
281
+ class xt extends K {
282
+ /**
283
+ * Wraps a web socket failure, built from the socket's `error` event.
284
+ * @internal The SDK builds this itself; applications catch the error rather than construct it.
285
+ */
286
+ constructor(n) {
287
+ super(n, "WSError");
288
+ /**
289
+ * Always `'WSError'` — note the capitalization, which does not match the class name.
290
+ */
291
+ A(this, "kind", "WSError");
292
+ }
293
+ }
294
+ const ut = (e) => e.type, Lt = (e) => {
295
+ switch (e.type) {
296
+ case ne.Expressive:
297
+ return "v4";
298
+ case ne.Clip:
299
+ return "v3-pro";
300
+ case ne.Talk:
301
+ return "v2";
302
+ }
303
+ }, je = (e) => e === ne.Expressive, jt = (e) => [P.TextOnly, P.Playground, P.Maintenance].includes(e), te = (e) => e && [P.DirectPlayback, P.Off].includes(e), Oe = /\[!\[([^\[\]]*)\]\(([^)\s]+)\)\]\(([^)\s]+)\)/g, Ve = /!\[([^\[\]]*)\]\(([^)\s]+)\)/g, Bt = [".mp4", ".webm", ".mkv", ".mov", ".m4v", ".ogv"];
304
+ function $t(e) {
305
+ const t = e.split("?")[0].split("#")[0].toLowerCase();
306
+ return Bt.some((n) => t.endsWith(n));
307
+ }
308
+ const Ue = new RegExp("(?<!!)\\[([^\\[\\]]+)\\]\\(([^)\\s]+)\\)", "g"), Je = /<a\s+href="([^"]*)"[^>]*?>([^<]*)<\/a>/gi;
309
+ function ft(e) {
310
+ if (e.length === 0)
311
+ return [];
312
+ const t = [];
313
+ let n;
314
+ for (Oe.lastIndex = 0; (n = Oe.exec(e)) !== null; )
315
+ t.push({
316
+ index: n.index,
317
+ length: n[0].length,
318
+ part: { type: "video", src: n[3], alt: n[1], thumbnail: n[2] }
319
+ });
320
+ for (Ve.lastIndex = 0; (n = Ve.exec(e)) !== null; )
321
+ if (!t.some((s) => n.index >= s.index && n.index < s.index + s.length)) {
322
+ const s = n[2], d = n[1];
323
+ let r;
324
+ $t(s) ? r = { type: "video", src: s, alt: d } : (r = { type: "image", src: s, alt: d }, s.toLowerCase().endsWith(".gif") && (r.mimeType = "image/gif")), t.push({ index: n.index, length: n[0].length, part: r });
325
+ }
326
+ for (Ue.lastIndex = 0; (n = Ue.exec(e)) !== null; )
327
+ t.some((s) => n.index >= s.index && n.index < s.index + s.length) || t.push({
328
+ index: n.index,
329
+ length: n[0].length,
330
+ part: { type: "link", href: n[2], label: n[1] }
331
+ });
332
+ for (Je.lastIndex = 0; (n = Je.exec(e)) !== null; )
333
+ t.some((s) => n.index >= s.index && n.index < s.index + s.length) || t.push({
334
+ index: n.index,
335
+ length: n[0].length,
336
+ part: { type: "link", href: n[1], label: n[2] }
337
+ });
338
+ if (t.length === 0)
339
+ return [{ type: "text", text: e }];
340
+ t.sort((i, s) => i.index - s.index);
341
+ const a = [];
342
+ let o = 0;
343
+ for (const i of t)
344
+ i.index > o && a.push({ type: "text", text: e.slice(o, i.index) }), a.push(i.part), o = i.index + i.length;
345
+ return o < e.length && a.push({ type: "text", text: e.slice(o) }), a;
346
+ }
347
+ let He = "", De = [];
348
+ function de(e) {
349
+ return e === He || (He = e, De = ft(e)), De;
350
+ }
351
+ function zt(e, t) {
352
+ let n;
353
+ return {
354
+ promise: new Promise((o, i) => {
355
+ n = setTimeout(() => i(new Error(t)), e);
356
+ }),
357
+ clear: () => clearTimeout(n)
358
+ };
359
+ }
360
+ async function _e(e, t) {
361
+ const n = {
362
+ limit: (t == null ? void 0 : t.limit) ?? 3,
363
+ delayMs: (t == null ? void 0 : t.delayMs) ?? 0,
364
+ timeout: (t == null ? void 0 : t.timeout) ?? 3e4,
365
+ timeoutErrorMessage: (t == null ? void 0 : t.timeoutErrorMessage) || "Timeout error",
366
+ shouldRetryFn: (t == null ? void 0 : t.shouldRetryFn) ?? (() => !0),
367
+ onRetry: (t == null ? void 0 : t.onRetry) ?? (() => {
368
+ })
369
+ };
370
+ let a;
371
+ for (let o = 1; o <= n.limit; o++)
372
+ try {
373
+ if (!n.timeout)
374
+ return await e();
375
+ const { promise: i, clear: s } = zt(n.timeout, n.timeoutErrorMessage), d = e().finally(s);
376
+ return await Promise.race([d, i]);
377
+ } catch (i) {
378
+ if (a = i, !n.shouldRetryFn(i) || o >= n.limit)
379
+ throw i;
380
+ await it(n.delayMs), n.onRetry(i);
381
+ }
382
+ throw a;
383
+ }
384
+ class We {
385
+ constructor(t) {
386
+ A(this, "status", 429);
387
+ this.response = t;
388
+ }
389
+ }
390
+ const Nt = (e) => _e(e, {
391
+ limit: 3,
392
+ delayMs: 1e3,
393
+ timeout: 0,
394
+ shouldRetryFn: (t) => t.status === 429
395
+ });
396
+ function mt(e, t = ve, n, a) {
397
+ const o = async (i, s) => {
398
+ const { skipErrorHandler: d, ...r } = s || {}, c = r.method ?? "GET", p = performance.now();
399
+ let u;
400
+ try {
401
+ u = await Nt(async () => {
402
+ const f = await fetch(t + (i != null && i.startsWith("/") ? i : `/${i}`), {
403
+ ...r,
404
+ headers: {
405
+ ...r.headers,
406
+ Authorization: ct(e, a),
407
+ "Content-Type": "application/json"
408
+ }
409
+ });
410
+ if (f.status === 429)
411
+ throw new We(f);
412
+ return f;
413
+ });
414
+ } catch (f) {
415
+ if (f instanceof We)
416
+ u = f.response;
417
+ else {
418
+ if ((f == null ? void 0 : f.name) === "AbortError")
419
+ throw f;
420
+ const y = new Pt(f, {
421
+ endpoint: i,
422
+ method: c,
423
+ durationMs: Math.round(performance.now() - p),
424
+ online: typeof navigator < "u" ? navigator.onLine : void 0,
425
+ visibility: typeof document < "u" ? document.visibilityState : void 0
426
+ });
427
+ throw d || n == null || n(y, { url: i, options: r }), y;
428
+ }
429
+ }
430
+ if (!u.ok) {
431
+ const f = await u.text().catch(() => `Failed to fetch with status ${u.status}`), g = new dt(u.status, f, { endpoint: i, method: c });
432
+ throw d || n == null || n(g, { url: i, options: r, headers: u.headers }), g;
433
+ }
434
+ return u.json();
435
+ };
436
+ return {
437
+ get(i, s) {
438
+ return o(i, { ...s, method: "GET" });
439
+ },
440
+ post(i, s, d) {
441
+ return o(i, { ...d, body: JSON.stringify(s), method: "POST" });
442
+ },
443
+ delete(i, s, d) {
444
+ return o(i, { ...d, body: JSON.stringify(s), method: "DELETE" });
445
+ },
446
+ patch(i, s, d) {
447
+ return o(i, { ...d, body: JSON.stringify(s), method: "PATCH" });
448
+ }
449
+ };
450
+ }
451
+ function Ft(e, t = ve, n, a) {
452
+ const o = mt(e, `${t}/agents`, n, a);
453
+ return {
454
+ getRuntimeById(i, s) {
455
+ return o.get(`/${i}/runtime`, s);
456
+ },
457
+ newChat(i, s, d) {
458
+ return o.post(`/${i}/chat`, s, d);
459
+ },
460
+ chat(i, s, d, r) {
461
+ return o.post(`/${i}/chat/${s}`, d, r);
462
+ },
463
+ createRating(i, s, d, r) {
464
+ return o.post(`/${i}/chat/${s}/ratings`, d, r);
465
+ },
466
+ updateRating(i, s, d, r, c) {
467
+ return o.patch(`/${i}/chat/${s}/ratings/${d}`, r, c);
468
+ },
469
+ deleteRating(i, s, d, r) {
470
+ return o.delete(`/${i}/chat/${s}/ratings/${d}`, r);
471
+ },
472
+ submitFeedback(i, s, d, r) {
473
+ return o.post(`/${i}/chat/${s}/feedback`, d, r);
474
+ },
475
+ getSttToken(i, s) {
476
+ return o.get(`/${i}/stt-token`, s);
477
+ }
478
+ };
479
+ }
480
+ function Ot(e) {
481
+ var o, i;
482
+ const t = () => /Mobi|Android/i.test(navigator.userAgent) ? "Mobile" : "Desktop", n = () => {
483
+ const s = navigator.platform;
484
+ return s.toLowerCase().includes("win") ? "Windows" : s.toLowerCase().includes("mac") ? "Mac OS X" : s.toLowerCase().includes("linux") ? "Linux" : "Unknown";
485
+ }, a = e.avatar;
486
+ return {
487
+ $os: `${n()}`,
488
+ isMobile: `${t() == "Mobile"}`,
489
+ browser: navigator.userAgent,
490
+ origin: window.location.origin,
491
+ agentType: ut(a),
492
+ agentVoice: {
493
+ language: (i = (o = e.avatar) == null ? void 0 : o.voice) == null ? void 0 : i.language
494
+ }
495
+ };
496
+ }
497
+ function Vt(e) {
498
+ var t;
499
+ return {
500
+ agentType: ut(e.avatar),
501
+ presenterType: Lt(e.avatar),
502
+ owner_id: e.owner_id ?? "",
503
+ starterQuestionsCount: (t = e.starter_message) == null ? void 0 : t.length,
504
+ agentId: e.id,
505
+ agentName: e.name
506
+ };
507
+ }
508
+ const Ut = (e) => {
509
+ try {
510
+ return String((e == null ? void 0 : e.message) ?? e ?? "").slice(0, 256);
511
+ } catch {
512
+ return "Unknown error";
513
+ }
514
+ }, Jt = (e) => e.reduce((t, n) => t + n, 0), Ke = (e) => Jt(e) / e.length, qe = (e) => Math.min(...e), Ge = (e) => Math.max(...e), pe = (e, t = 0) => {
515
+ const n = 10 ** t;
516
+ return Math.round(e * n) / n;
517
+ }, Ht = (e, t) => {
518
+ const n = [...e].sort((a, o) => a - o);
519
+ return n[Math.min(n.length - 1, Math.floor(t * (n.length - 1)))];
520
+ }, Wt = (e) => Ht(e, 0.5), Kt = (e, t) => {
521
+ try {
522
+ return e();
523
+ } catch {
524
+ return t;
525
+ }
526
+ };
527
+ function Xe(e, t, n) {
528
+ var d, r;
529
+ const { event: a, ...o } = e, { language: i } = ((d = t == null ? void 0 : t.avatar) == null ? void 0 : d.voice) || {};
530
+ return {
531
+ ...o,
532
+ script: { ...o.script, provider: { ...(r = o == null ? void 0 : o.script) == null ? void 0 : r.provider, language: i } },
533
+ ...n
534
+ };
535
+ }
536
+ function Qe(e) {
537
+ "requestIdleCallback" in window ? requestIdleCallback(e, { timeout: 2e3 }) : setTimeout(e, 0);
538
+ }
539
+ function Re(e) {
540
+ return e instanceof K ? e.toJson() : { kind: "UnknownError", message: Ut(e) || "UnknownError" };
541
+ }
542
+ const qt = "3.0.0-staging.415", Gt = "https://api-js.mixpanel.com/track/?verbose=1&ip=1", gt = 50, Q = [];
543
+ let be = !1;
544
+ async function ht(e) {
545
+ const t = await fetch(Gt, {
546
+ method: "POST",
547
+ headers: { "Content-Type": "application/x-www-form-urlencoded" },
548
+ body: new URLSearchParams({ data: JSON.stringify(e) })
549
+ });
550
+ if (!t.ok)
551
+ throw new Error(`Mixpanel responded with ${t.status}`);
552
+ }
553
+ function Xt(e) {
554
+ Q.push(e), Q.splice(gt);
555
+ }
556
+ function Ae() {
557
+ if (be || !Q.length)
558
+ return;
559
+ be = !0;
560
+ const e = Q.splice(0, Q.length);
561
+ ht(e).catch(() => {
562
+ Q.unshift(...e), Q.splice(gt);
563
+ }).finally(() => {
564
+ be = !1;
565
+ });
566
+ }
567
+ typeof window < "u" && typeof window.addEventListener == "function" && (window.addEventListener("online", Ae), typeof document < "u" && document.addEventListener("visibilitychange", () => {
568
+ document.visibilityState === "visible" && Ae();
569
+ }));
570
+ function Qt(e) {
571
+ const t = window != null && window.hasOwnProperty("DID_AGENTS_API") ? "agents-ui" : "agents-sdk", n = {};
572
+ return {
573
+ token: e.token || "testKey",
574
+ distinct_id: Te(e.externalId),
575
+ agentId: e.agentId,
576
+ additionalProperties: {
577
+ id: Te(e.externalId),
578
+ ...e.mixpanelAdditionalProperties || {}
579
+ },
580
+ isEnabled: e.isEnabled ?? !0,
581
+ getRandom: Y,
582
+ enrich(a) {
583
+ this.additionalProperties = { ...this.additionalProperties, ...a };
584
+ },
585
+ async track(a, o, i) {
586
+ if (!this.isEnabled)
587
+ return Promise.resolve();
588
+ const { audioPath: s, ...d } = o || {}, r = i || Date.now(), c = {
589
+ event: a,
590
+ properties: {
591
+ ...this.additionalProperties,
592
+ ...d,
593
+ agentId: this.agentId,
594
+ source: t,
595
+ emittedBy: "agents-sdk",
596
+ sdkVersion: qt,
597
+ token: this.token,
598
+ time: r,
599
+ $insert_id: this.getRandom(),
600
+ origin: window.location.href,
601
+ "Screen Height": window.screen.height || window.innerHeight,
602
+ "Screen Width": window.screen.width || window.innerWidth,
603
+ "User Agent": navigator.userAgent
604
+ }
605
+ };
606
+ return Ae(), ht([c]).catch(() => Xt(c)), Promise.resolve();
607
+ },
608
+ linkTrack(a, o, i, s) {
609
+ n[a] || (n[a] = { events: {}, resolvedDependencies: [] }), s.includes(i) || s.push(i);
610
+ const d = n[a];
611
+ if (d.events[i] = { props: o }, d.resolvedDependencies.push(i), s.every(
612
+ (c) => d.resolvedDependencies.includes(c)
613
+ )) {
614
+ const c = s.reduce((p, u) => d.events[u] ? { ...p, ...d.events[u].props } : p, {});
615
+ this.track(a, c), d.resolvedDependencies = d.resolvedDependencies.filter(
616
+ (p) => !s.includes(p)
617
+ ), s.forEach((p) => {
618
+ delete d.events[p];
619
+ });
620
+ }
621
+ }
622
+ };
623
+ }
624
+ function Be() {
625
+ let e = 0;
626
+ return {
627
+ reset: () => e = 0,
628
+ update: () => e = Date.now(),
629
+ get: (t = !1) => t ? Date.now() - e : e
630
+ };
631
+ }
632
+ const W = Be(), Pe = Be(), Ye = Be();
633
+ function pt(e) {
634
+ return e === P.Playground ? { headers: { [bt]: "true" } } : {};
635
+ }
636
+ async function wt(e, t, n, a, o = !1, i) {
637
+ return !i && !te(a) && (i = await t.newChat(e.id, { persist: o }, pt(a)), n.track("agent-chat", {
638
+ event: "created",
639
+ chatId: i.id,
640
+ mode: a
641
+ })), { chat: i, chatMode: (i == null ? void 0 : i.chat_mode) ?? a };
642
+ }
643
+ function Yt(e) {
644
+ return !e || e.length === 0 ? [] : e.map(
645
+ (t) => Array.isArray(t.parts) && t.parts.length > 0 ? t : { ...t, parts: ft(typeof t.content == "string" ? t.content : "") }
646
+ );
647
+ }
648
+ function Zt(e) {
649
+ return new Promise((t, n) => {
650
+ const { callbacks: a, host: o, auth: i, externalId: s } = e, { onMessage: d = null, onOpen: r = null, onClose: c = null, onError: p = null } = a || {}, u = new WebSocket(`${o}?authorization=${encodeURIComponent(ct(i, s))}`);
651
+ u.onmessage = d, u.onclose = c, u.onerror = (f) => {
652
+ console.error(f), p == null || p("Websocket failed to connect", f), n(f);
653
+ }, u.onopen = (f) => {
654
+ r == null || r(f), t(u);
655
+ };
656
+ });
657
+ }
658
+ async function en(e) {
659
+ const { retries: t = 1 } = e;
660
+ let n = null;
661
+ for (let a = 0; (n == null ? void 0 : n.readyState) !== WebSocket.OPEN; a++)
662
+ try {
663
+ n = await Zt(e);
664
+ } catch (o) {
665
+ if (a === t)
666
+ throw o;
667
+ await it(a * 500);
668
+ }
669
+ return n;
670
+ }
671
+ async function tn(e, t, n, a) {
672
+ const o = n != null && n.onMessage ? [n.onMessage] : [], i = await en({
673
+ auth: e,
674
+ host: t,
675
+ externalId: a,
676
+ callbacks: {
677
+ onError: (s) => {
678
+ var d;
679
+ return (d = n.onError) == null ? void 0 : d.call(n, new xt(s));
680
+ },
681
+ onMessage(s) {
682
+ const d = JSON.parse(s.data);
683
+ o.forEach((r) => r(d.event, d));
684
+ }
685
+ }
686
+ });
687
+ return {
688
+ socket: i,
689
+ disconnect: () => i.close(),
690
+ subscribeToEvents: (s) => o.push(s)
691
+ };
692
+ }
693
+ const nn = {
694
+ manual: ce.Ok,
695
+ inactivity: ce.Inactivity,
696
+ peer_disconnected: ce.NetworkIssue,
697
+ shutdown: ce.UnknownError
698
+ };
699
+ function rn(e) {
700
+ return nn[e.close_reason] ?? e.close_reason;
701
+ }
702
+ const an = [
703
+ I.StreamVideoDone,
704
+ I.StreamVideoError,
705
+ I.StreamVideoRejected
706
+ ], Ze = [I.StreamFailed, I.StreamVideoError, I.StreamVideoRejected];
707
+ function et(e) {
708
+ if (e.answer !== void 0)
709
+ return e.answer;
710
+ let t = 0, n = "";
711
+ for (; t in e; )
712
+ n += e[t++];
713
+ return n;
714
+ }
715
+ function sn(e, t, n) {
716
+ if (!e.content)
717
+ return;
718
+ const a = {
719
+ id: e.id || `user-${Date.now()}`,
720
+ role: e.role,
721
+ content: e.content,
722
+ parts: de(e.content),
723
+ createdAt: e.created_at || (/* @__PURE__ */ new Date()).toISOString(),
724
+ transcribed: !0
725
+ };
726
+ t.messages.push(a), n == null || n([...t.messages], "user");
727
+ }
728
+ function on(e, t, n, a, o, i, s) {
729
+ if (e === N.Transcribe && t.content) {
730
+ sn(t, a, o);
731
+ return;
732
+ }
733
+ if (!(e === N.Partial || e === N.Answer))
734
+ return;
735
+ const d = a.messages[a.messages.length - 1];
736
+ if (e === N.Answer && (d == null ? void 0 : d.role) === "user" && s === "partial")
737
+ return;
738
+ const c = s === "answer";
739
+ let p;
740
+ if ((d == null ? void 0 : d.role) === "assistant" && !c)
741
+ p = d;
742
+ else if (!d || d.role === "user" || c)
743
+ c && i(), p = {
744
+ id: t.id || `assistant-${Date.now()}`,
745
+ role: t.role || "assistant",
746
+ // Starts empty so the content-change check below fires for this message's first chat
747
+ // event. Seeding it with `data.content` made that check a no-op, so a message carried
748
+ // by a single partial (e.g. a worker `say` greeting) never reached `onNewMessage`.
749
+ content: "",
750
+ parts: [],
751
+ createdAt: t.created_at || (/* @__PURE__ */ new Date()).toISOString()
752
+ }, a.messages.push(p);
753
+ else
754
+ return;
755
+ const { content: u, sequence: f } = t;
756
+ if (e === N.Partial)
757
+ n[f] = u;
758
+ else {
759
+ const y = et(n);
760
+ !!(u && u.length < y.length) && (p.interrupted = !0), n.answer = u;
761
+ }
762
+ const g = et(n);
763
+ (p.content !== g || e === N.Answer) && (p.content = g, p.parts = de(g), o == null || o([...a.messages], e));
764
+ }
765
+ function cn(e, t, n, a, o) {
766
+ const i = {}, s = () => {
767
+ for (const c of Object.keys(i))
768
+ delete i[c];
769
+ };
770
+ let d = null;
771
+ const r = (c, p) => {
772
+ var u, f;
773
+ p === "user" && s(), (f = (u = n.callbacks).onNewMessage) == null || f.call(u, c, p);
774
+ };
775
+ return {
776
+ clearQueue: s,
777
+ onMessage: (c, p) => {
778
+ var u, f;
779
+ if ("content" in p) {
780
+ const g = c === I.ChatAnswer ? N.Answer : c === I.ChatAudioTranscribed ? N.Transcribe : c;
781
+ on(
782
+ g,
783
+ p,
784
+ i,
785
+ t,
786
+ r,
787
+ s,
788
+ d
789
+ ), g === N.Partial ? d = "partial" : g === N.Answer && (d = "answer", s()), g === N.Answer && e.track("agent-message-received", {
790
+ content: p.content,
791
+ messages: t.messages.length,
792
+ mode: t.chatMode
793
+ });
794
+ } else {
795
+ const g = I;
796
+ if (c = c, c === g.StreamVideoCreated) {
797
+ const y = Xe(p, a, { mode: t.chatMode });
798
+ if (e.linkTrack("agent-video", y, g.StreamVideoCreated, ["start"]), p.sentiment) {
799
+ const T = t.messages[t.messages.length - 1];
800
+ if ((T == null ? void 0 : T.role) === "assistant") {
801
+ const _ = { ...T, sentiment: p.sentiment };
802
+ t.messages[t.messages.length - 1] = _, r == null || r([...t.messages], d ?? "answer");
803
+ }
804
+ }
805
+ }
806
+ if (an.includes(c)) {
807
+ const y = c.split("/")[1], T = Xe(p, a, { mode: t.chatMode });
808
+ Ze.includes(c) ? e.track("agent-video", { ...T, event: y }) : e.linkTrack("agent-video", { ...T, event: y }, c, ["done"]);
809
+ }
810
+ Ze.includes(c) && ((f = (u = n.callbacks).onError) == null || f.call(u, new lt(`Stream failed with event ${c}`), { data: p })), p.event === g.StreamDone && o(rn(p));
811
+ }
812
+ }
813
+ };
814
+ }
815
+ function dn(e) {
816
+ return {
817
+ status: e.status,
818
+ sessionId: e.session_id,
819
+ duration: e.duration,
820
+ videoId: e.video_id
821
+ };
822
+ }
823
+ function ln(e, t, n, a) {
824
+ const o = mt(e, `${t}/agents/${n}`, a);
825
+ return {
826
+ createStream(i, s) {
827
+ return o.post("/streams", i, { signal: s });
828
+ },
829
+ startConnection(i, s, d, r) {
830
+ return o.post(
831
+ `/streams/${i}/sdp`,
832
+ {
833
+ session_id: d,
834
+ answer: s
835
+ },
836
+ { signal: r }
837
+ );
838
+ },
839
+ addIceCandidate(i, s, d, r) {
840
+ return o.post(
841
+ `/streams/${i}/ice`,
842
+ {
843
+ session_id: d,
844
+ ...s
845
+ },
846
+ { signal: r }
847
+ );
848
+ },
849
+ async sendStreamRequest(i, s, d) {
850
+ const r = await o.post(`/streams/${i}`, {
851
+ session_id: s,
852
+ ...d
853
+ });
854
+ return dn(r);
855
+ },
856
+ close(i, s) {
857
+ return o.delete(`/streams/${i}`, { session_id: s });
858
+ }
859
+ };
860
+ }
861
+ const un = (e, t) => (n, a) => e && console.log(`[${t}] ${n}`, a ?? ""), fn = 45;
862
+ function mn(e) {
863
+ const t = e.map((r) => r.av).filter((r) => !!r && r.audioPlayout > 0 && r.videoPlayout > 0);
864
+ if (t.length < 2)
865
+ return null;
866
+ const n = t[0].localTs, a = t[t.length - 1].localTs - n, o = t.map((r) => r.audioPlayout - r.videoPlayout), i = o.filter(
867
+ (r) => r > fn || r < -100
868
+ ), s = t.filter((r) => r.localTs - n >= Math.min(5e3, a / 2)), d = (s.length ? s : t).map((r) => r.audioPlayout - r.videoPlayout);
869
+ return {
870
+ sampleCount: t.length,
871
+ durationMs: pe(a),
872
+ desyncDurationMs: pe(a * (i.length / o.length)),
873
+ maxOffsetMs: pe(o.reduce((r, c) => Math.abs(c) > Math.abs(r) ? c : r)),
874
+ residualOffsetMs: pe(Wt(d))
875
+ };
876
+ }
877
+ function gn(e, t, n) {
878
+ const a = (t.timestamp - e.timestamp) / 1e3;
879
+ return {
880
+ duration: a,
881
+ bytesReceived: t.bytesReceived - e.bytesReceived,
882
+ bitrate: Math.round((t.bytesReceived - e.bytesReceived) * 8 / a),
883
+ packetsReceived: t.packetsReceived - e.packetsReceived,
884
+ packetsLost: t.packetsLost - e.packetsLost,
885
+ framesDropped: t.framesDropped - e.framesDropped,
886
+ framesDecoded: t.framesDecoded - e.framesDecoded,
887
+ jitter: t.jitter,
888
+ avgJitterDelayInInterval: (t.jitterBufferDelay - e.jitterBufferDelay) / (t.jitterBufferEmittedCount - e.jitterBufferEmittedCount),
889
+ jitterBufferEmittedCount: t.jitterBufferEmittedCount - e.jitterBufferEmittedCount,
890
+ jitterBufferDelay: (t.jitterBufferDelay - e.jitterBufferDelay) / a,
891
+ framesPerSecond: t.framesPerSecond,
892
+ freezeCount: t.freezeCount - e.freezeCount,
893
+ freezeDuration: t.freezeDuration - e.freezeDuration,
894
+ lowFpsCount: n
895
+ };
896
+ }
897
+ function hn(e) {
898
+ return e.filter(
899
+ (t) => t.freezeCount > 0 || t.framesPerSecond < 21 || t.framesDropped > 0 || t.packetsLost > 0
900
+ ).map((t) => {
901
+ const { timestamp: n, ...a } = t, o = [];
902
+ return t.freezeCount > 0 && o.push("freeze"), t.framesPerSecond < 21 && o.push("low fps"), t.framesDropped > 0 && o.push("frames dropped"), t.packetsLost > 0 && o.push("packet loss"), {
903
+ ...a,
904
+ causes: o
905
+ };
906
+ });
907
+ }
908
+ function pn(e) {
909
+ var r;
910
+ let t = "", n = 0, a = null, o = null;
911
+ const i = /* @__PURE__ */ new Map();
912
+ for (const c of e.values())
913
+ if (c)
914
+ if (c.type === "codec" && ((r = c.mimeType) != null && r.startsWith("video")))
915
+ i.set(c.id, c.mimeType.split("/")[1]);
916
+ else if (c.type === "candidate-pair") {
917
+ const p = c, u = p.currentRoundTripTime ?? 0;
918
+ u > 0 && (p.nominated === !0 || n === 0) && (n = u);
919
+ } else c.type === "inbound-rtp" && c.kind === "video" ? a = c : c.type === "inbound-rtp" && c.kind === "audio" && (o = c);
920
+ if (!a)
921
+ return {};
922
+ const s = a;
923
+ s.codecId && i.has(s.codecId) ? t = i.get(s.codecId) : i.size > 0 && (t = i.values().next().value ?? "");
924
+ const d = {
925
+ codec: t,
926
+ rtt: n,
927
+ timestamp: s.timestamp,
928
+ bytesReceived: s.bytesReceived,
929
+ packetsReceived: s.packetsReceived,
930
+ packetsLost: s.packetsLost,
931
+ framesDropped: s.framesDropped,
932
+ framesDecoded: s.framesDecoded,
933
+ jitter: s.jitter,
934
+ jitterBufferDelay: s.jitterBufferDelay,
935
+ jitterBufferEmittedCount: s.jitterBufferEmittedCount,
936
+ avgJitterDelayInInterval: s.jitterBufferDelay / s.jitterBufferEmittedCount,
937
+ frameWidth: s.frameWidth,
938
+ frameHeight: s.frameHeight,
939
+ framesPerSecond: s.framesPerSecond,
940
+ freezeCount: s.freezeCount,
941
+ freezeDuration: s.totalFreezesDuration
942
+ };
943
+ return o && (d.av = {
944
+ audioPlayout: o.estimatedPlayoutTimestamp ?? 0,
945
+ videoPlayout: s.estimatedPlayoutTimestamp ?? 0,
946
+ localTs: s.timestamp
947
+ }), d;
948
+ }
949
+ function tt(e, t, n) {
950
+ if (e.length === 0)
951
+ return null;
952
+ const a = e.map((r, c) => c === 0 ? n ? {
953
+ timestamp: r.timestamp,
954
+ duration: 0,
955
+ rtt: r.rtt,
956
+ bytesReceived: r.bytesReceived - n.bytesReceived,
957
+ bitrate: (r.bytesReceived - n.bytesReceived) * 8 / (t / 1e3),
958
+ packetsReceived: r.packetsReceived - n.packetsReceived,
959
+ packetsLost: r.packetsLost - n.packetsLost,
960
+ framesDropped: r.framesDropped - n.framesDropped,
961
+ framesDecoded: r.framesDecoded - n.framesDecoded,
962
+ jitter: r.jitter,
963
+ jitterBufferDelay: r.jitterBufferDelay - n.jitterBufferDelay,
964
+ jitterBufferEmittedCount: r.jitterBufferEmittedCount - n.jitterBufferEmittedCount,
965
+ avgJitterDelayInInterval: (r.jitterBufferDelay - n.jitterBufferDelay) / (r.jitterBufferEmittedCount - n.jitterBufferEmittedCount),
966
+ framesPerSecond: r.framesPerSecond,
967
+ freezeCount: r.freezeCount - n.freezeCount,
968
+ freezeDuration: r.freezeDuration - n.freezeDuration
969
+ } : {
970
+ timestamp: r.timestamp,
971
+ rtt: r.rtt,
972
+ duration: 0,
973
+ bytesReceived: r.bytesReceived,
974
+ bitrate: r.bytesReceived * 8 / (t / 1e3),
975
+ packetsReceived: r.packetsReceived,
976
+ packetsLost: r.packetsLost,
977
+ framesDropped: r.framesDropped,
978
+ framesDecoded: r.framesDecoded,
979
+ jitter: r.jitter,
980
+ jitterBufferDelay: r.jitterBufferDelay,
981
+ jitterBufferEmittedCount: r.jitterBufferEmittedCount,
982
+ avgJitterDelayInInterval: r.jitterBufferDelay / r.jitterBufferEmittedCount,
983
+ framesPerSecond: r.framesPerSecond,
984
+ freezeCount: r.freezeCount,
985
+ freezeDuration: r.freezeDuration
986
+ } : {
987
+ timestamp: r.timestamp,
988
+ duration: t * c / 1e3,
989
+ rtt: r.rtt,
990
+ bytesReceived: r.bytesReceived - e[c - 1].bytesReceived,
991
+ bitrate: (r.bytesReceived - e[c - 1].bytesReceived) * 8 / (t / 1e3),
992
+ packetsReceived: r.packetsReceived - e[c - 1].packetsReceived,
993
+ packetsLost: r.packetsLost - e[c - 1].packetsLost,
994
+ framesDropped: r.framesDropped - e[c - 1].framesDropped,
995
+ framesDecoded: r.framesDecoded - e[c - 1].framesDecoded,
996
+ jitter: r.jitter,
997
+ jitterBufferDelay: r.jitterBufferDelay - e[c - 1].jitterBufferDelay,
998
+ jitterBufferEmittedCount: r.jitterBufferEmittedCount - e[c - 1].jitterBufferEmittedCount,
999
+ avgJitterDelayInInterval: (r.jitterBufferDelay - e[c - 1].jitterBufferDelay) / (r.jitterBufferEmittedCount - e[c - 1].jitterBufferEmittedCount),
1000
+ framesPerSecond: r.framesPerSecond,
1001
+ freezeCount: r.freezeCount - e[c - 1].freezeCount,
1002
+ freezeDuration: r.freezeDuration - e[c - 1].freezeDuration
1003
+ }), o = hn(a), i = o.reduce((r, c) => r + (c.causes.includes("low fps") ? 1 : 0), 0), s = a.filter((r) => !!r.avgJitterDelayInInterval).map((r) => r.avgJitterDelayInInterval), d = a.filter((r) => !!r.rtt).map((r) => r.rtt);
1004
+ return {
1005
+ webRTCStats: {
1006
+ anomalies: o,
1007
+ avSync: Kt(() => mn(e), null),
1008
+ minRtt: qe(d),
1009
+ avgRtt: Ke(d),
1010
+ maxRtt: Ge(d),
1011
+ aggregateReport: gn(e[0], e[e.length - 1], i),
1012
+ minJitterDelayInInterval: qe(s),
1013
+ maxJitterDelayInInterval: Ge(s),
1014
+ avgJitterDelayInInterval: Ke(s)
1015
+ },
1016
+ codec: e[0].codec,
1017
+ resolution: `${e[0].frameWidth}x${e[0].frameHeight}`
1018
+ };
1019
+ }
1020
+ function yt(e, t) {
1021
+ for (const n of e.values())
1022
+ if ((n == null ? void 0 : n.type) === "inbound-rtp" && n.kind === t)
1023
+ return n;
1024
+ return null;
1025
+ }
1026
+ const ie = 10;
1027
+ function On(e, t) {
1028
+ let n = !1, a = !1, o = null, i = 0, s = 0, d = {};
1029
+ async function r() {
1030
+ if (n) {
1031
+ try {
1032
+ const c = await e();
1033
+ if (!c) {
1034
+ o = setTimeout(r, ie);
1035
+ return;
1036
+ }
1037
+ const p = yt(c, "audio");
1038
+ if (!p) {
1039
+ o = setTimeout(r, ie);
1040
+ return;
1041
+ }
1042
+ const u = p.totalAudioEnergy ?? 0, f = p.totalSamplesReceived ?? 0;
1043
+ if (!a) {
1044
+ i = u, s = f, a = !0, o = setTimeout(r, ie);
1045
+ return;
1046
+ }
1047
+ const g = u - i, y = f - s;
1048
+ if (i = u, s = f, y > 0 && g > 0) {
1049
+ n = !1, t(d);
1050
+ return;
1051
+ }
1052
+ } catch {
1053
+ }
1054
+ n && (o = setTimeout(r, ie));
1055
+ }
1056
+ }
1057
+ return {
1058
+ arm(c = {}) {
1059
+ d = c, n = !0, a = !1, performance.now(), o !== null && clearTimeout(o), o = setTimeout(r, ie);
1060
+ },
1061
+ destroy() {
1062
+ n = !1, o !== null && (clearTimeout(o), o = null);
1063
+ }
1064
+ };
1065
+ }
1066
+ const we = 100, wn = Math.max(Math.ceil(400 / we), 1), yn = 0.25, vn = 0.28;
1067
+ function Sn() {
1068
+ let e = 0, t, n, a = 0;
1069
+ return (o) => {
1070
+ const i = yt(o, "video");
1071
+ if (!i)
1072
+ return { isReceiving: !1, avgJitterDelayInInterval: a };
1073
+ const s = i.jitterBufferDelay, d = i.jitterBufferEmittedCount;
1074
+ if (n && d > n) {
1075
+ const p = s - t, u = d - n;
1076
+ a = p / u;
1077
+ }
1078
+ t = s, n = d;
1079
+ const r = i.framesDecoded, c = r - e > 0;
1080
+ return e = r, { isReceiving: c, avgJitterDelayInInterval: a, freezeCount: i.freezeCount };
1081
+ };
1082
+ }
1083
+ function kn(e, t, n, a, o) {
1084
+ let i = null, s = [], d, r = 0, c = !1, p = oe.Unknown, u = oe.Unknown, f = 0, g = 0;
1085
+ const y = Sn();
1086
+ async function T() {
1087
+ const _ = await e();
1088
+ if (!_)
1089
+ return;
1090
+ const { isReceiving: F, avgJitterDelayInInterval: V, freezeCount: b } = y(_), U = pn(_);
1091
+ if (F)
1092
+ r = 0, f = b - g, u = V < yn ? oe.Strong : V > vn && f > 1 ? oe.Weak : p, u !== p && (o == null || o(u), p = u, g += f, f = 0), c || (a == null || a(k.Start), d = s[s.length - 1], s = [], c = !0), s.push(U);
1093
+ else if (c && (r++, r >= wn)) {
1094
+ const H = tt(s, we, d);
1095
+ a == null || a(k.Stop, H ?? void 0), t() || n(), g = b, c = !1;
1096
+ }
1097
+ }
1098
+ return {
1099
+ start: () => {
1100
+ i || (i = setInterval(T, we));
1101
+ },
1102
+ stop: () => {
1103
+ i && (clearInterval(i), i = null);
1104
+ },
1105
+ getReport: () => tt(s, we, d)
1106
+ };
1107
+ }
1108
+ const Cn = () => {
1109
+ const e = globalThis, t = e.RTCPeerConnection || e.webkitRTCPeerConnection || e.mozRTCPeerConnection;
1110
+ if (!t)
1111
+ throw new Error("RTCPeerConnection is not available in this environment");
1112
+ return t.bind(e);
1113
+ };
1114
+ function nt(e) {
1115
+ switch (e) {
1116
+ case "connected":
1117
+ return x.Connected;
1118
+ case "checking":
1119
+ return x.Connecting;
1120
+ case "failed":
1121
+ return x.Fail;
1122
+ case "new":
1123
+ return x.New;
1124
+ case "closed":
1125
+ return x.Closed;
1126
+ case "disconnected":
1127
+ return x.Disconnected;
1128
+ case "completed":
1129
+ return x.Completed;
1130
+ default:
1131
+ return x.New;
1132
+ }
1133
+ }
1134
+ const Mn = (e) => (t) => {
1135
+ const [n, a = ""] = t.split(/:(.+)/);
1136
+ try {
1137
+ const o = JSON.parse(a);
1138
+ return e("parsed data channel message", { subject: n, data: o }), { subject: n, data: o };
1139
+ } catch (o) {
1140
+ return e("Failed to parse data channel message, returning data as string", { subject: n, rawData: a, error: o }), { subject: n, data: a };
1141
+ }
1142
+ };
1143
+ function Dn({
1144
+ statsSignal: e,
1145
+ dataChannelSignal: t,
1146
+ onVideoStateChange: n,
1147
+ report: a,
1148
+ log: o
1149
+ }) {
1150
+ e === k.Start && t === k.Start ? (o("CALLBACK: onVideoStateChange(Start)"), n == null || n(k.Start)) : e === k.Stop && t === k.Stop && (o("CALLBACK: onVideoStateChange(Stop)"), n == null || n(k.Stop, a));
1151
+ }
1152
+ function Rn({
1153
+ statsSignal: e,
1154
+ dataChannelSignal: t,
1155
+ onVideoStateChange: n,
1156
+ onAgentActivityStateChange: a,
1157
+ report: o,
1158
+ log: i
1159
+ }) {
1160
+ e === k.Start ? (i("CALLBACK: onVideoStateChange(Start)"), n == null || n(k.Start)) : e === k.Stop && (i("CALLBACK: onVideoStateChange(Stop)"), n == null || n(k.Stop, o)), t === k.Start ? a == null || a(le.Talking) : t === k.Stop && (a == null || a(le.Idle));
1161
+ }
1162
+ function rt({
1163
+ statsSignal: e,
1164
+ dataChannelSignal: t,
1165
+ onVideoStateChange: n,
1166
+ onAgentActivityStateChange: a,
1167
+ streamType: o,
1168
+ report: i,
1169
+ log: s
1170
+ }) {
1171
+ o === J.Legacy ? Dn({ statsSignal: e, dataChannelSignal: t, onVideoStateChange: n, report: i, log: s }) : o === J.Fluent && Rn({
1172
+ statsSignal: e,
1173
+ dataChannelSignal: t,
1174
+ onVideoStateChange: n,
1175
+ onAgentActivityStateChange: a,
1176
+ report: i,
1177
+ log: s
1178
+ });
1179
+ }
1180
+ async function bn(e, t, { debug: n = !1, callbacks: a, auth: o, baseURL: i = ve, analytics: s }, d) {
1181
+ var C;
1182
+ const r = un(n, "WebRTCStreamingManager"), c = Mn(r);
1183
+ let p = !1, u = !1, f = k.Stop, g = k.Stop;
1184
+ const { startConnection: y, sendStreamRequest: T, close: _, createStream: F, addIceCandidate: V } = ln(
1185
+ o,
1186
+ i,
1187
+ e,
1188
+ a.onError
1189
+ ), {
1190
+ id: b,
1191
+ offer: U,
1192
+ ice_servers: H,
1193
+ session_id: O,
1194
+ fluent: ue,
1195
+ interrupt_enabled: fe
1196
+ } = await F(t, d);
1197
+ if (!O)
1198
+ throw new Error("Could not create session_id");
1199
+ (C = a.onStreamCreated) == null || C.call(a, { streamId: b, sessionId: O, agentId: e });
1200
+ const j = (h) => {
1201
+ var w;
1202
+ return (w = a.onError) == null ? void 0 : w.call(a, h, { streamId: b });
1203
+ }, R = new (Cn())({ iceServers: H }), q = R.createDataChannel("JanusDataChannel"), z = ue ? J.Fluent : J.Legacy;
1204
+ s.enrich({
1205
+ "stream-type": z
1206
+ });
1207
+ const me = t.stream_warmup && !ue, Se = () => p, Z = () => {
1208
+ var h;
1209
+ p = !0, u && (r("CALLBACK: onConnectionStateChange(Connected)"), (h = a.onConnectionStateChange) == null || h.call(a, x.Connected));
1210
+ }, re = kn(
1211
+ () => R.getStats(),
1212
+ Se,
1213
+ Z,
1214
+ (h, w) => rt({
1215
+ statsSignal: g = h,
1216
+ dataChannelSignal: z === J.Legacy ? f : void 0,
1217
+ onVideoStateChange: a.onVideoStateChange,
1218
+ onAgentActivityStateChange: a.onAgentActivityStateChange,
1219
+ report: w,
1220
+ streamType: z,
1221
+ log: r
1222
+ }),
1223
+ (h) => {
1224
+ var w;
1225
+ return (w = a.onConnectivityStateChange) == null ? void 0 : w.call(a, h);
1226
+ }
1227
+ );
1228
+ re.start(), R.onicecandidate = (h) => {
1229
+ r("peerConnection.onicecandidate", h);
1230
+ try {
1231
+ h.candidate && h.candidate.sdpMid && h.candidate.sdpMLineIndex !== null ? V(
1232
+ b,
1233
+ {
1234
+ candidate: h.candidate.candidate,
1235
+ sdpMid: h.candidate.sdpMid,
1236
+ sdpMLineIndex: h.candidate.sdpMLineIndex
1237
+ },
1238
+ O,
1239
+ d
1240
+ ) : V(b, { candidate: null }, O, d);
1241
+ } catch (w) {
1242
+ j(w);
1243
+ }
1244
+ }, q.onopen = () => {
1245
+ u = !0, (!me || p) && Z();
1246
+ };
1247
+ let ee = null;
1248
+ const ae = (h) => {
1249
+ var w;
1250
+ ee = h, (w = a.onVideoIdChange) == null || w.call(a, h);
1251
+ };
1252
+ function se(h, w) {
1253
+ if (h === I.StreamStarted && typeof w == "object" && "metadata" in w) {
1254
+ const D = w.metadata;
1255
+ ae(D.videoId);
1256
+ }
1257
+ h === I.StreamDone && ae(null), f = h === I.StreamStarted ? k.Start : k.Stop, rt({
1258
+ statsSignal: z === J.Legacy ? g : void 0,
1259
+ dataChannelSignal: f,
1260
+ onVideoStateChange: a.onVideoStateChange,
1261
+ onAgentActivityStateChange: a.onAgentActivityStateChange,
1262
+ streamType: z,
1263
+ log: r
1264
+ });
1265
+ }
1266
+ function l(h, w) {
1267
+ var $;
1268
+ const D = typeof w == "string" ? w : w == null ? void 0 : w.metadata;
1269
+ D && s.enrich({ streamMetadata: D }), ($ = a.onStreamReady) == null || $.call(a);
1270
+ }
1271
+ const m = {
1272
+ [I.StreamStarted]: se,
1273
+ [I.StreamDone]: se,
1274
+ [I.StreamReady]: l
1275
+ };
1276
+ q.onmessage = (h) => {
1277
+ var $;
1278
+ const { subject: w, data: D } = c(h.data);
1279
+ ($ = m[w]) == null || $.call(m, w, D);
1280
+ }, R.oniceconnectionstatechange = () => {
1281
+ var w;
1282
+ r("peerConnection.oniceconnectionstatechange => " + R.iceConnectionState);
1283
+ const h = nt(R.iceConnectionState);
1284
+ h !== x.Connected && ((w = a.onConnectionStateChange) == null || w.call(a, h, `webrtc:ice-${R.iceConnectionState}`));
1285
+ }, R.ontrack = (h) => {
1286
+ var w;
1287
+ r("peerConnection.ontrack", h), r("CALLBACK: onSrcObjectReady"), (w = a.onSrcObjectReady) == null || w.call(a, h.streams[0]);
1288
+ }, await R.setRemoteDescription(U), r("set remote description OK");
1289
+ const v = await R.createAnswer();
1290
+ r("create answer OK"), await R.setLocalDescription(v), r("set local description OK"), await y(b, v, O, d), r("start connection OK");
1291
+ async function S(h, w) {
1292
+ if (!p || q.readyState !== "open") {
1293
+ r("Data channel is not ready for sending messages"), j(new lt("Data channel is not ready for sending messages"));
1294
+ return;
1295
+ }
1296
+ try {
1297
+ q.send(w);
1298
+ } catch (D) {
1299
+ r("Error sending data channel message", D), j(D);
1300
+ }
1301
+ }
1302
+ return {
1303
+ /**
1304
+ * Method to send request to server to get clip or talk depend on you payload
1305
+ * @param payload
1306
+ */
1307
+ speak(h) {
1308
+ return T(b, O, h);
1309
+ },
1310
+ /**
1311
+ * Method to close RTC connection
1312
+ */
1313
+ async disconnect() {
1314
+ var h;
1315
+ if (b) {
1316
+ const w = nt(R.iceConnectionState);
1317
+ if (R) {
1318
+ if (w === x.New) {
1319
+ re.stop();
1320
+ return;
1321
+ }
1322
+ R.close(), R.oniceconnectionstatechange = null, R.onnegotiationneeded = null, R.onicecandidate = null, R.ontrack = null;
1323
+ }
1324
+ try {
1325
+ w === x.Connected && await _(b, O).catch((D) => {
1326
+ });
1327
+ } catch (D) {
1328
+ r("Error on close stream connection", D);
1329
+ }
1330
+ (h = a.onAgentActivityStateChange) == null || h.call(a, le.Idle), re.stop();
1331
+ }
1332
+ },
1333
+ sendDataChannelMessage: S,
1334
+ /**
1335
+ * Session identifier information, should be returned in the body of all streaming requests
1336
+ */
1337
+ sessionId: O,
1338
+ /**
1339
+ * Id of current RTC stream
1340
+ */
1341
+ streamId: b,
1342
+ streamType: z,
1343
+ interruptAvailable: fe ?? !1,
1344
+ isInterruptible: !0,
1345
+ interrupt(h) {
1346
+ if (!fe || z !== J.Fluent || !ee || !p || q.readyState !== "open")
1347
+ return !1;
1348
+ const w = {
1349
+ type: I.StreamInterrupt,
1350
+ videoId: ee,
1351
+ timestamp: Date.now()
1352
+ };
1353
+ return S(ye.Interrupt, JSON.stringify(w)), !0;
1354
+ }
1355
+ };
1356
+ }
1357
+ var xe = /* @__PURE__ */ ((e) => (e.V1 = "v1", e.V2 = "v2", e))(xe || {});
1358
+ async function In(e, t, n, a) {
1359
+ const o = e.id;
1360
+ switch (t.version) {
1361
+ case "v1": {
1362
+ const { version: i, ...s } = t;
1363
+ return bn(o, s, n, a);
1364
+ }
1365
+ case "v2": {
1366
+ const { version: i, ...s } = t;
1367
+ switch (s.transport.provider) {
1368
+ case Le.Livekit:
1369
+ const { createLiveKitStreamingManager: d } = await import("./livekit-manager-CU_yynQK.js");
1370
+ return d(o, s, n);
1371
+ default:
1372
+ throw new Error(`Unsupported transport provider: ${s.transport.provider}`);
1373
+ }
1374
+ }
1375
+ default:
1376
+ throw new Error(`Invalid stream version: ${t.version}`);
1377
+ }
1378
+ }
1379
+ const En = "cht";
1380
+ function Tn(e) {
1381
+ return {
1382
+ transport: {
1383
+ provider: Le.Livekit
1384
+ },
1385
+ ...(e == null ? void 0 : e.persistentChat) !== void 0 && { chat_persist: e.persistentChat }
1386
+ };
1387
+ }
1388
+ function _n(e) {
1389
+ var o, i;
1390
+ const { streamOptions: t } = e ?? {}, n = ((o = e == null ? void 0 : e.mixpanelAdditionalProperties) == null ? void 0 : o.plan) !== void 0 ? {
1391
+ plan: (i = e.mixpanelAdditionalProperties) == null ? void 0 : i.plan
1392
+ } : void 0;
1393
+ return { ...{
1394
+ session_timeout: t == null ? void 0 : t.sessionTimeout,
1395
+ stream_warmup: t == null ? void 0 : t.streamWarmup,
1396
+ compatibility_mode: t == null ? void 0 : t.compatibilityMode,
1397
+ fluent: t == null ? void 0 : t.fluent
1398
+ }, ...n && { end_user_data: n } };
1399
+ }
1400
+ function An(e, t) {
1401
+ return je(e.avatar.type) ? { version: xe.V2, ...Tn(t) } : { version: xe.V1, ..._n(t) };
1402
+ }
1403
+ function Pn(e, t, n) {
1404
+ n.track("agent-connection-state-change", { state: e, ...t && { reason: t } });
1405
+ }
1406
+ function xn(e, t, n, a, o) {
1407
+ o === J.Fluent ? Ln(e, t, n, a, o) : jn(e, t, n, a, o);
1408
+ }
1409
+ function Ln(e, t, n, a, o) {
1410
+ e === k.Start ? a.track("stream-session", { event: "start", "stream-type": o }) : e === k.Stop && a.track("stream-session", {
1411
+ event: "stop",
1412
+ "stream-type": o,
1413
+ ...n
1414
+ });
1415
+ }
1416
+ function at(e, t, n, a, o) {
1417
+ e === k.Start ? n.linkTrack("agent-video", { event: "start", ...o, "stream-type": a }, "start", [
1418
+ I.StreamVideoCreated
1419
+ ]) : e === k.Stop && n.linkTrack(
1420
+ "agent-video",
1421
+ {
1422
+ event: "stop",
1423
+ "stream-type": a
1424
+ },
1425
+ "done",
1426
+ [I.StreamVideoDone]
1427
+ );
1428
+ }
1429
+ function jn(e, t, n, a, o) {
1430
+ e === k.Start ? a.linkTrack(
1431
+ "agent-video",
1432
+ { event: "start", latency: W.get(!0), "stream-type": o },
1433
+ "start",
1434
+ [I.StreamVideoCreated]
1435
+ ) : e === k.Stop && a.linkTrack(
1436
+ "agent-video",
1437
+ {
1438
+ event: "stop",
1439
+ "stream-type": o,
1440
+ ...n
1441
+ },
1442
+ "done",
1443
+ [I.StreamVideoDone]
1444
+ );
1445
+ }
1446
+ function Bn(e, t, n) {
1447
+ const a = {
1448
+ call_id: t.callId,
1449
+ name: t.name
1450
+ };
1451
+ if (e === Ee.Started) {
1452
+ n.track("agent-tool-call", { ...a, event: "started" });
1453
+ return;
1454
+ }
1455
+ const o = t;
1456
+ n.track("agent-tool-call", {
1457
+ ...a,
1458
+ event: e === Ee.Done ? "done" : "error",
1459
+ duration_ms: o.durationMs,
1460
+ extra_keys: o.extra ? Object.keys(o.extra).length : 0
1461
+ });
1462
+ }
1463
+ function st(e, t, n, a) {
1464
+ return W.reset(), Ye.update(), new Promise(async (o, i) => {
1465
+ try {
1466
+ let s, d = !1;
1467
+ const r = An(e, t);
1468
+ n.enrich({
1469
+ "stream-version": r.version.toString()
1470
+ });
1471
+ let c = null;
1472
+ const p = e.avatar.type === ne.Expressive;
1473
+ s = await In(
1474
+ e,
1475
+ r,
1476
+ {
1477
+ ...t,
1478
+ analytics: n,
1479
+ callbacks: {
1480
+ ...t.callbacks,
1481
+ onConnectionStateChange: (u, f) => {
1482
+ var g, y;
1483
+ (y = (g = t.callbacks).onConnectionStateChange) == null || y.call(g, u, f), Pn(u, f, n), u === x.Connected && (s ? o(s) : d = !0);
1484
+ },
1485
+ onVideoStateChange: (u, f) => {
1486
+ var g, y;
1487
+ (y = (g = t.callbacks).onVideoStateChange) == null || y.call(g, u), xn(
1488
+ u,
1489
+ e,
1490
+ f,
1491
+ n,
1492
+ s.streamType
1493
+ );
1494
+ },
1495
+ onAgentActivityStateChange: (u) => {
1496
+ var f, g;
1497
+ (g = (f = t.callbacks).onAgentActivityStateChange) == null || g.call(f, u), u === le.Talking ? (Pe.update(), c = (y) => {
1498
+ at(
1499
+ k.Start,
1500
+ e,
1501
+ n,
1502
+ s.streamType,
1503
+ y
1504
+ ), c = null;
1505
+ }, p || c({ latency: W.get(!0) })) : (Pe.reset(), c = null, at(
1506
+ k.Stop,
1507
+ e,
1508
+ n,
1509
+ s.streamType
1510
+ ));
1511
+ },
1512
+ onFirstAudioDetected: (u) => {
1513
+ c == null || c(u);
1514
+ },
1515
+ onStreamReady: () => {
1516
+ const u = Ye.get(!0);
1517
+ n.track("agent-chat", { event: "ready", latency: u });
1518
+ },
1519
+ onToolEvent: ((u, f) => {
1520
+ var g, y;
1521
+ (y = (g = t.callbacks).onToolEvent) == null || y.call(g, u, f), Bn(u, f, n);
1522
+ })
1523
+ }
1524
+ },
1525
+ a
1526
+ ), d && o(s);
1527
+ } catch (s) {
1528
+ i(s);
1529
+ }
1530
+ });
1531
+ }
1532
+ async function $n(e, t, n, a, o) {
1533
+ var p, u, f, g;
1534
+ const i = async () => {
1535
+ if (je(e.avatar.type)) {
1536
+ const y = await st(e, t, a), T = `${En}_${y.sessionId}`, _ = (/* @__PURE__ */ new Date()).toISOString();
1537
+ return { chatResult: {
1538
+ chatMode: P.Functional,
1539
+ chat: {
1540
+ id: T,
1541
+ agent_id: e.id,
1542
+ owner_id: e.owner_id ?? "",
1543
+ created: _,
1544
+ modified: _,
1545
+ agent_id__created_at: _,
1546
+ agent_id__modified_at: _,
1547
+ chat_mode: P.Functional,
1548
+ messages: []
1549
+ }
1550
+ }, streamingManager: y };
1551
+ } else {
1552
+ const y = new AbortController(), T = y.signal;
1553
+ let _;
1554
+ try {
1555
+ const F = wt(
1556
+ e,
1557
+ n,
1558
+ a,
1559
+ t.mode,
1560
+ t.persistentChat,
1561
+ o
1562
+ ), V = st(e, t, a, T).then((H) => (_ = H, H)), [b, U] = await Promise.all([F, V]);
1563
+ return { chatResult: b, streamingManager: U };
1564
+ } catch (F) {
1565
+ throw y.abort(), _ && await _.disconnect().catch(() => {
1566
+ }), F;
1567
+ }
1568
+ }
1569
+ }, { chatResult: s, streamingManager: d } = await i(), { chat: r, chatMode: c } = s;
1570
+ return c && t.mode !== void 0 && c !== t.mode && (t.mode = c, (u = (p = t.callbacks).onModeChange) == null || u.call(p, c), c !== P.Functional) ? ((g = (f = t.callbacks).onError) == null || g.call(f, new _t(c)), d == null || d.disconnect(), { chat: r }) : { chat: r, streamingManager: d };
1571
+ }
1572
+ const Ie = "ChatMode.Off and ChatMode.DirectPlayback are not supported for Expressive agents";
1573
+ async function Vn(e, t) {
1574
+ var ee, ae, se;
1575
+ const n = { ...t, callbacks: { ...t.callbacks } };
1576
+ let a = !0;
1577
+ const o = n.mixpanelKey || Et, i = n.wsURL || It, s = n.baseURL || ve, d = n.mode || P.Functional, r = {
1578
+ messages: [],
1579
+ chatMode: d
1580
+ }, c = Qt({
1581
+ token: o,
1582
+ agentId: e,
1583
+ isEnabled: n.enableAnalytics,
1584
+ externalId: n.externalId,
1585
+ mixpanelAdditionalProperties: n.mixpanelAdditionalProperties
1586
+ }), p = Date.now();
1587
+ Qe(() => {
1588
+ c.track("agent-sdk", { event: "init" }, p);
1589
+ });
1590
+ const u = n.callbacks.onError;
1591
+ n.callbacks.onError = (l, m) => {
1592
+ c.track("agent-error", { error: Re(l) }), u == null || u(l, m);
1593
+ };
1594
+ const f = Ft(
1595
+ n.auth,
1596
+ s,
1597
+ n.callbacks.onError,
1598
+ n.externalId
1599
+ ), g = await f.getRuntimeById(e);
1600
+ n.debug = n.debug || ((ee = g == null ? void 0 : g.advanced_settings) == null ? void 0 : ee.ui_debug_mode);
1601
+ const y = je(g.avatar.type);
1602
+ if (y && te(d))
1603
+ throw new E(Ie);
1604
+ y && import("./livekit-manager-CU_yynQK.js").then(({ preloadLiveKit: l }) => l()).catch(() => {
1605
+ }), c.enrich(Vt(g));
1606
+ const { onMessage: T, clearQueue: _ } = cn(c, r, n, g, (l) => {
1607
+ var m, v, S;
1608
+ (m = r.socketManager) == null || m.disconnect(), (S = (v = n.callbacks).onConnectionStateChange) == null || S.call(v, x.Disconnected, l);
1609
+ });
1610
+ r.messages = Yt(n.initialMessages), (se = (ae = n.callbacks).onNewMessage) == null || se.call(ae, [...r.messages], "answer");
1611
+ const F = (l) => c.enrich({ videoId: l }), V = ({ type: l }) => {
1612
+ var C, h;
1613
+ const m = r.streamingManager;
1614
+ if (!(m != null && m.interruptAvailable) || !m.isInterruptible || !m.interrupt(l))
1615
+ return;
1616
+ c.track("agent-video-interrupt", {
1617
+ type: l || "click",
1618
+ video_duration_to_interrupt: Pe.get(!0),
1619
+ message_duration_to_interrupt: W.get(!0)
1620
+ });
1621
+ const S = r.messages[r.messages.length - 1];
1622
+ S && (S.interrupted = !0, (h = (C = n.callbacks).onNewMessage) == null || h.call(C, [...r.messages], "answer"));
1623
+ }, b = /* @__PURE__ */ new Map();
1624
+ function U(l) {
1625
+ return async (m) => {
1626
+ const v = b.get(l);
1627
+ if (!v)
1628
+ throw new Error(`No handler registered for client tool: ${l}`);
1629
+ const S = JSON.parse(m.payload);
1630
+ return v(S);
1631
+ };
1632
+ }
1633
+ function H() {
1634
+ var l, m, v, S;
1635
+ for (const [C] of b)
1636
+ (m = (l = r.streamingManager) == null ? void 0 : l.unregisterRpcMethod) == null || m.call(l, C), (S = (v = r.streamingManager) == null ? void 0 : v.registerRpcMethod) == null || S.call(v, C, U(C));
1637
+ }
1638
+ function O(l, m) {
1639
+ var S, C;
1640
+ const v = !b.has(l);
1641
+ b.set(l, m), v && ((C = (S = r.streamingManager) == null ? void 0 : S.registerRpcMethod) == null || C.call(S, l, U(l)));
1642
+ }
1643
+ function ue(l) {
1644
+ var m, v;
1645
+ b.delete(l), (v = (m = r.streamingManager) == null ? void 0 : m.unregisterRpcMethod) == null || v.call(m, l);
1646
+ }
1647
+ const fe = Date.now();
1648
+ Qe(() => {
1649
+ c.track("agent-sdk", { event: "loaded", ...Ot(g) }, fe);
1650
+ });
1651
+ let j;
1652
+ function R(l) {
1653
+ return j || (j = q(l).finally(() => {
1654
+ j = void 0;
1655
+ }), j);
1656
+ }
1657
+ async function q(l) {
1658
+ var D, $, L, B, G, ke, Ce;
1659
+ Dt(), ($ = (D = n.callbacks).onConnectionStateChange) == null || $.call(D, x.Connecting), W.reset(), l && !a && (delete r.chat, (B = (L = n.callbacks).onNewMessage) == null || B.call(L, [...r.messages], "answer"));
1660
+ const m = me(r.chatMode) ? tn(
1661
+ n.auth,
1662
+ i,
1663
+ { onMessage: T, onError: n.callbacks.onError },
1664
+ n.externalId
1665
+ ) : Promise.resolve(void 0), v = _e(
1666
+ () => $n(
1667
+ g,
1668
+ {
1669
+ ...n,
1670
+ mode: r.chatMode,
1671
+ callbacks: {
1672
+ ...n.callbacks,
1673
+ onVideoIdChange: F,
1674
+ onMessage: T
1675
+ },
1676
+ rpcMethods: new Map([...b.keys()].map((M) => [M, U(M)]))
1677
+ },
1678
+ f,
1679
+ c,
1680
+ r.chat
1681
+ ),
1682
+ {
1683
+ limit: 3,
1684
+ timeout: Rt,
1685
+ timeoutErrorMessage: "Timeout initializing the stream",
1686
+ shouldRetryFn: (M) => (M == null ? void 0 : M.message) !== "Could not connect" && !(M instanceof dt && (M.status === 429 || M.code === "InsufficientCreditsError")),
1687
+ delayMs: 1e3
1688
+ }
1689
+ ).catch((M) => {
1690
+ var X, ge;
1691
+ throw Z(P.Maintenance), (ge = (X = n.callbacks).onConnectionStateChange) == null || ge.call(X, x.Fail), M;
1692
+ }), [S, { streamingManager: C, chat: h }] = await Promise.all([m, v]);
1693
+ h && h.id !== ((G = r.chat) == null ? void 0 : G.id) && ((Ce = (ke = n.callbacks).onNewChat) == null || Ce.call(ke, h.id)), r.streamingManager = C, r.socketManager = S, r.chat = h, H(), a = !1, c.enrich({
1694
+ chatId: h == null ? void 0 : h.id,
1695
+ streamId: C == null ? void 0 : C.streamId,
1696
+ mode: r.chatMode
1697
+ });
1698
+ const w = (h == null ? void 0 : h.chat_mode) ?? r.chatMode;
1699
+ if (y && te(w)) {
1700
+ console.warn(`[AgentManager] Ignoring chat mode "${w}": ${Ie}`);
1701
+ return;
1702
+ }
1703
+ await Z(w);
1704
+ }
1705
+ async function z() {
1706
+ var l, m, v, S;
1707
+ (l = r.socketManager) == null || l.disconnect(), await ((m = r.streamingManager) == null ? void 0 : m.disconnect()), delete r.streamingManager, delete r.socketManager, (S = (v = n.callbacks).onConnectionStateChange) == null || S.call(v, x.Disconnected);
1708
+ }
1709
+ function me(l) {
1710
+ return !y && l !== P.DirectPlayback;
1711
+ }
1712
+ function Se(l) {
1713
+ const m = !te(l);
1714
+ return (!me(l) || !!r.socketManager) && (!m || !!r.chat);
1715
+ }
1716
+ async function Z(l) {
1717
+ var m, v;
1718
+ l !== r.chatMode && (c.track("agent-mode-change", { mode: l }), r.chatMode = l, (l !== P.Functional || !Se(l)) && await z(), (v = (m = n.callbacks).onModeChange) == null || v.call(m, l));
1719
+ }
1720
+ async function re(l) {
1721
+ if (y && te(l))
1722
+ throw new E(Ie);
1723
+ await Z(l);
1724
+ }
1725
+ return {
1726
+ agent: g,
1727
+ getStreamType: () => {
1728
+ var l;
1729
+ return (l = r.streamingManager) == null ? void 0 : l.streamType;
1730
+ },
1731
+ isInterruptAvailable: () => {
1732
+ var l;
1733
+ return ((l = r.streamingManager) == null ? void 0 : l.interruptAvailable) ?? !1;
1734
+ },
1735
+ starterMessages: g.starter_message || [],
1736
+ getSttToken: () => f.getSttToken(g.id),
1737
+ changeMode: re,
1738
+ enrichAnalytics: c.enrich,
1739
+ async connect() {
1740
+ if (j)
1741
+ return j;
1742
+ if (r.streamingManager)
1743
+ throw new E("Already connected; call disconnect() first");
1744
+ await R(!0), c.track("agent-chat", {
1745
+ event: "connect",
1746
+ mode: r.chatMode
1747
+ });
1748
+ },
1749
+ async reconnect() {
1750
+ if (j)
1751
+ throw new E("A connect() is in flight; wait for it before calling reconnect()");
1752
+ const l = r.streamingManager;
1753
+ let m;
1754
+ if (y && (l != null && l.reconnect))
1755
+ try {
1756
+ await l.reconnect();
1757
+ } catch (v) {
1758
+ const S = Re(v);
1759
+ m = S.code ?? S.kind, await z(), await R(!1);
1760
+ }
1761
+ else
1762
+ await z(), await R(!1);
1763
+ c.track("agent-chat", {
1764
+ event: "reconnect",
1765
+ mode: r.chatMode,
1766
+ success: !0,
1767
+ ...m && { fallbackReason: m }
1768
+ });
1769
+ },
1770
+ async disconnect() {
1771
+ await (j == null ? void 0 : j.catch(() => {
1772
+ })), await z(), c.track("agent-chat", {
1773
+ event: "disconnect",
1774
+ mode: r.chatMode
1775
+ });
1776
+ },
1777
+ publishMicrophoneStream(l) {
1778
+ var m;
1779
+ return (m = r.streamingManager) != null && m.publishMicrophoneStream ? r.streamingManager.publishMicrophoneStream(l) : Promise.reject(
1780
+ new E(
1781
+ "publishMicrophoneStream is only available on Expressive (V4) agents, after connect()"
1782
+ )
1783
+ );
1784
+ },
1785
+ setSttLanguage(l) {
1786
+ return !y || !r.streamingManager ? Promise.reject(
1787
+ new E("setSttLanguage is only available on Expressive (V4) agents, after connect()")
1788
+ ) : (c.track("agent-stt-language-change", { language: l }), r.streamingManager.sendDataChannelMessage(
1789
+ ye.SttLanguage,
1790
+ JSON.stringify({ language: l })
1791
+ ));
1792
+ },
1793
+ sendDataChannelMessage(l, m) {
1794
+ return !y || !r.streamingManager ? Promise.reject(
1795
+ new E(
1796
+ "sendDataChannelMessage is only available on Expressive (V4) agents, after connect()"
1797
+ )
1798
+ ) : (c.track("agent-data-message", { topic: l }), r.streamingManager.sendDataChannelMessage(l, JSON.stringify(m)));
1799
+ },
1800
+ unpublishMicrophoneStream() {
1801
+ var l;
1802
+ return (l = r.streamingManager) != null && l.unpublishMicrophoneStream ? r.streamingManager.unpublishMicrophoneStream() : Promise.resolve();
1803
+ },
1804
+ replaceMicrophoneTrack(l) {
1805
+ var m;
1806
+ return (m = r.streamingManager) != null && m.replaceMicrophoneTrack ? r.streamingManager.replaceMicrophoneTrack(l) : Promise.reject(
1807
+ new E(
1808
+ "replaceMicrophoneTrack is only available on Expressive (V4) agents, after connect()"
1809
+ )
1810
+ );
1811
+ },
1812
+ publishCameraStream(l) {
1813
+ var m;
1814
+ return (m = r.streamingManager) != null && m.publishCameraStream ? r.streamingManager.publishCameraStream(l) : Promise.reject(
1815
+ new E(
1816
+ "publishCameraStream is only available on Expressive (V4) agents, after connect()"
1817
+ )
1818
+ );
1819
+ },
1820
+ unpublishCameraStream() {
1821
+ var l;
1822
+ return (l = r.streamingManager) != null && l.unpublishCameraStream ? r.streamingManager.unpublishCameraStream() : Promise.resolve();
1823
+ },
1824
+ async chat(l) {
1825
+ var C, h, w, D, $;
1826
+ const m = () => {
1827
+ if (te(r.chatMode))
1828
+ throw new E(`${r.chatMode} is enabled, chat is disabled`);
1829
+ if (l.length >= Fe)
1830
+ throw new E(`Message cannot be more than ${Fe} characters`);
1831
+ if (l.length === 0)
1832
+ throw new E("Message cannot be empty");
1833
+ if (r.chatMode === P.Maintenance)
1834
+ throw new E("Chat is in maintenance mode");
1835
+ if (![P.TextOnly, P.Playground].includes(r.chatMode)) {
1836
+ if (!r.streamingManager)
1837
+ throw new E("Streaming manager is not initialized");
1838
+ if (!r.chat)
1839
+ throw new E("Chat is not initialized");
1840
+ }
1841
+ }, v = async () => {
1842
+ var L, B;
1843
+ if (!r.chat) {
1844
+ const G = await wt(
1845
+ g,
1846
+ f,
1847
+ c,
1848
+ r.chatMode,
1849
+ n.persistentChat
1850
+ );
1851
+ if (!G.chat)
1852
+ throw new Tt(r.chatMode, !!n.persistentChat);
1853
+ r.chat = G.chat, (B = (L = n.callbacks).onNewChat) == null || B.call(L, r.chat.id);
1854
+ }
1855
+ return r.chat.id;
1856
+ }, S = async (L, B) => {
1857
+ const G = r.chatMode === P.Playground;
1858
+ return _e(y && !G ? async () => {
1859
+ var M;
1860
+ return await ((M = r.streamingManager) == null ? void 0 : M.sendDataChannelMessage(
1861
+ ye.Chat,
1862
+ l
1863
+ )), Promise.resolve({});
1864
+ } : async () => {
1865
+ var M, X;
1866
+ return f.chat(
1867
+ g.id,
1868
+ B,
1869
+ {
1870
+ chatMode: r.chatMode,
1871
+ streamId: (M = r.streamingManager) == null ? void 0 : M.streamId,
1872
+ sessionId: (X = r.streamingManager) == null ? void 0 : X.sessionId,
1873
+ messages: L.map(({ matches: ge, ...he }) => he)
1874
+ },
1875
+ {
1876
+ ...pt(r.chatMode),
1877
+ skipErrorHandler: !0
1878
+ }
1879
+ );
1880
+ }, {
1881
+ limit: 2,
1882
+ shouldRetryFn: (M) => {
1883
+ var he, $e, ze, Ne;
1884
+ const X = (he = M == null ? void 0 : M.message) == null ? void 0 : he.includes("missing or invalid session_id");
1885
+ return !(($e = M == null ? void 0 : M.message) == null ? void 0 : $e.includes("Stream Error")) && !X ? ((Ne = (ze = n.callbacks).onError) == null || Ne.call(ze, M), !1) : !0;
1886
+ },
1887
+ onRetry: async () => {
1888
+ await z(), await R(!1);
1889
+ }
1890
+ });
1891
+ };
1892
+ try {
1893
+ _(), m(), r.messages.push({
1894
+ id: Y(),
1895
+ role: "user",
1896
+ content: l,
1897
+ parts: de(l),
1898
+ createdAt: new Date(W.update()).toISOString()
1899
+ }), (h = (C = n.callbacks).onNewMessage) == null || h.call(C, [...r.messages], "user");
1900
+ const L = await v(), B = await S([...r.messages], L);
1901
+ return B.result && r.messages.push({
1902
+ id: Y(),
1903
+ role: "assistant",
1904
+ content: B.result,
1905
+ parts: de(B.result),
1906
+ createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1907
+ context: B.context,
1908
+ matches: B.matches
1909
+ }), c.track("agent-message-send", {
1910
+ event: "success",
1911
+ messages: r.messages.length + 1
1912
+ }), B.result && ((D = (w = n.callbacks).onNewMessage) == null || D.call(w, [...r.messages], "answer"), c.track("agent-message-received", {
1913
+ latency: W.get(!0),
1914
+ messages: r.messages.length
1915
+ })), B;
1916
+ } catch (L) {
1917
+ throw (($ = r.messages[r.messages.length - 1]) == null ? void 0 : $.role) === "assistant" && r.messages.pop(), c.track("agent-message-send", {
1918
+ event: "error",
1919
+ messages: r.messages.length,
1920
+ error: Re(L)
1921
+ }), L;
1922
+ }
1923
+ },
1924
+ async rate(l, m, v) {
1925
+ var h, w, D, $;
1926
+ const S = r.messages.find((L) => L.id === l);
1927
+ if (r.chat) {
1928
+ if (!S)
1929
+ throw new E("Message not found");
1930
+ } else throw new E("Chat is not initialized");
1931
+ const C = ((h = S.matches) == null ? void 0 : h.map((L) => [L.document_id, L.id])) ?? [];
1932
+ return c.track("agent-rate", {
1933
+ event: v ? "update" : "create",
1934
+ thumb: m === 1 ? "up" : "down",
1935
+ knowledge_id: ((w = g.knowledge) == null ? void 0 : w.id) ?? "",
1936
+ matches: C,
1937
+ score: m
1938
+ }), v ? f.updateRating(g.id, r.chat.id, v, {
1939
+ knowledge_id: ((D = g.knowledge) == null ? void 0 : D.id) ?? "",
1940
+ message_id: l,
1941
+ matches: C,
1942
+ score: m
1943
+ }) : f.createRating(g.id, r.chat.id, {
1944
+ knowledge_id: (($ = g.knowledge) == null ? void 0 : $.id) ?? "",
1945
+ message_id: l,
1946
+ matches: C,
1947
+ score: m
1948
+ });
1949
+ },
1950
+ async deleteRate(l) {
1951
+ if (!r.chat)
1952
+ throw new E("Chat is not initialized");
1953
+ return c.track("agent-rate-delete", { type: "text" }), f.deleteRating(g.id, r.chat.id, l);
1954
+ },
1955
+ async submitFeedback(l, m) {
1956
+ if (!r.chat)
1957
+ throw new E("Chat is not initialized");
1958
+ return c.track("agent-feedback", { rating: l, hasAnswer: !!m }), f.submitFeedback(g.id, r.chat.id, { rating: l, answer: m });
1959
+ },
1960
+ async speak(l) {
1961
+ var h, w, D;
1962
+ function m() {
1963
+ return typeof l == "string" ? {
1964
+ type: "text",
1965
+ input: l,
1966
+ ssml: !1
1967
+ } : l.type === "text" && !l.provider ? {
1968
+ type: "text",
1969
+ input: l.input,
1970
+ ssml: l.ssml,
1971
+ should_queue_speaks: l.should_queue_speaks,
1972
+ sentiment: l.sentiment
1973
+ } : l;
1974
+ }
1975
+ const v = m();
1976
+ c.track("agent-speak", v), W.update(), r.messages && v.type === "text" && (r.messages.push({
1977
+ id: Y(),
1978
+ role: "assistant",
1979
+ content: v.input,
1980
+ parts: de(v.input),
1981
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
1982
+ }), (w = (h = n.callbacks).onNewMessage) == null || w.call(h, [...r.messages], "answer"));
1983
+ const S = { duration: 0, videoId: "", status: "success" };
1984
+ if (jt(r.chatMode))
1985
+ return S;
1986
+ if (!r.streamingManager)
1987
+ throw new E("Please connect to the agent first");
1988
+ return await r.streamingManager.speak({
1989
+ script: v,
1990
+ metadata: { chat_id: (D = r.chat) == null ? void 0 : D.id, agent_id: g.id }
1991
+ }) ?? S;
1992
+ },
1993
+ interrupt: V,
1994
+ registerClientTool: O,
1995
+ unregisterClientTool: ue
1996
+ };
1997
+ }
1998
+ function Un(e) {
1999
+ return e.some((t) => t.executionMode === "blocking");
2000
+ }
2001
+ export {
2002
+ le as A,
2003
+ K as B,
2004
+ N as C,
2005
+ kt as D,
2006
+ dt as H,
2007
+ ye as I,
2008
+ Pt as N,
2009
+ Ct as P,
2010
+ I as S,
2011
+ Ee as T,
2012
+ E as V,
2013
+ xt as W,
2014
+ un as a,
2015
+ J as b,
2016
+ mt as c,
2017
+ ve as d,
2018
+ lt as e,
2019
+ x as f,
2020
+ oe as g,
2021
+ kn as h,
2022
+ On as i,
2023
+ k as j,
2024
+ ne as k,
2025
+ W as l,
2026
+ Tt as m,
2027
+ Nn as n,
2028
+ P as o,
2029
+ _t as p,
2030
+ ce as q,
2031
+ Mt as r,
2032
+ Vn as s,
2033
+ Re as t,
2034
+ Un as u,
2035
+ Fn as v,
2036
+ ft as w
2037
+ };