@opencx/widget-react-headless 4.0.62 → 5.0.0-beta.1

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 (99) hide show
  1. package/README.md +17 -0
  2. package/dist/index.cjs +23 -1
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.js +4748 -182
  5. package/dist/index.js.map +1 -1
  6. package/dist/package.json.d.ts +53 -0
  7. package/dist/src/ComponentRegistry.d.ts.map +1 -1
  8. package/dist/src/WidgetProvider.d.ts +9 -2
  9. package/dist/src/WidgetProvider.d.ts.map +1 -1
  10. package/dist/src/__tests__/ComponentRegistry.spec.d.ts +2 -0
  11. package/dist/src/__tests__/ComponentRegistry.spec.d.ts.map +1 -0
  12. package/dist/src/__tests__/WidgetProvider.capabilities.spec.d.ts +2 -0
  13. package/dist/src/__tests__/WidgetProvider.capabilities.spec.d.ts.map +1 -0
  14. package/dist/src/__tests__/WidgetProvider.initialization.spec.d.ts +2 -0
  15. package/dist/src/__tests__/WidgetProvider.initialization.spec.d.ts.map +1 -0
  16. package/dist/src/agent-chat/AgentChatContext.d.ts +58 -0
  17. package/dist/src/agent-chat/AgentChatContext.d.ts.map +1 -0
  18. package/dist/src/agent-chat/__tests__/WidgetProvider.agent-chat.spec.d.ts +2 -0
  19. package/dist/src/agent-chat/__tests__/WidgetProvider.agent-chat.spec.d.ts.map +1 -0
  20. package/dist/src/agent-chat/__tests__/agent-chat-queue.spec.d.ts +2 -0
  21. package/dist/src/agent-chat/__tests__/agent-chat-queue.spec.d.ts.map +1 -0
  22. package/dist/src/agent-chat/__tests__/agent-chat-stream.spec.d.ts +2 -0
  23. package/dist/src/agent-chat/__tests__/agent-chat-stream.spec.d.ts.map +1 -0
  24. package/dist/src/agent-chat/__tests__/agent-chat-transport.spec.d.ts +2 -0
  25. package/dist/src/agent-chat/__tests__/agent-chat-transport.spec.d.ts.map +1 -0
  26. package/dist/src/agent-chat/__tests__/agent-turn-sources.spec.d.ts +2 -0
  27. package/dist/src/agent-chat/__tests__/agent-turn-sources.spec.d.ts.map +1 -0
  28. package/dist/src/agent-chat/__tests__/ask-questions.spec.d.ts +2 -0
  29. package/dist/src/agent-chat/__tests__/ask-questions.spec.d.ts.map +1 -0
  30. package/dist/src/agent-chat/__tests__/pending-clarification.spec.d.ts +2 -0
  31. package/dist/src/agent-chat/__tests__/pending-clarification.spec.d.ts.map +1 -0
  32. package/dist/src/agent-chat/__tests__/stop-agent-chat-turn.spec.d.ts +2 -0
  33. package/dist/src/agent-chat/__tests__/stop-agent-chat-turn.spec.d.ts.map +1 -0
  34. package/dist/src/agent-chat/__tests__/use-agent-chat.client-context.spec.d.ts +2 -0
  35. package/dist/src/agent-chat/__tests__/use-agent-chat.client-context.spec.d.ts.map +1 -0
  36. package/dist/src/agent-chat/__tests__/use-agent-chat.drain-order.spec.d.ts +2 -0
  37. package/dist/src/agent-chat/__tests__/use-agent-chat.drain-order.spec.d.ts.map +1 -0
  38. package/dist/src/agent-chat/__tests__/use-agent-chat.failed-turn.spec.d.ts +2 -0
  39. package/dist/src/agent-chat/__tests__/use-agent-chat.failed-turn.spec.d.ts.map +1 -0
  40. package/dist/src/agent-chat/__tests__/use-agent-chat.feature-narrowing.spec.d.ts +2 -0
  41. package/dist/src/agent-chat/__tests__/use-agent-chat.feature-narrowing.spec.d.ts.map +1 -0
  42. package/dist/src/agent-chat/__tests__/use-agent-chat.send-features.spec.d.ts +2 -0
  43. package/dist/src/agent-chat/__tests__/use-agent-chat.send-features.spec.d.ts.map +1 -0
  44. package/dist/src/agent-chat/__tests__/use-agent-chat.steer.spec.d.ts +2 -0
  45. package/dist/src/agent-chat/__tests__/use-agent-chat.steer.spec.d.ts.map +1 -0
  46. package/dist/src/agent-chat/__tests__/use-agent-chat.stop-partial.spec.d.ts +2 -0
  47. package/dist/src/agent-chat/__tests__/use-agent-chat.stop-partial.spec.d.ts.map +1 -0
  48. package/dist/src/agent-chat/__tests__/use-agent-chat.stream-handoff.spec.d.ts +2 -0
  49. package/dist/src/agent-chat/__tests__/use-agent-chat.stream-handoff.spec.d.ts.map +1 -0
  50. package/dist/src/agent-chat/__tests__/use-agent-chat.turn-retention.spec.d.ts +2 -0
  51. package/dist/src/agent-chat/__tests__/use-agent-chat.turn-retention.spec.d.ts.map +1 -0
  52. package/dist/src/agent-chat/__tests__/use-chat-post-finish-data-part.spec.d.ts +2 -0
  53. package/dist/src/agent-chat/__tests__/use-chat-post-finish-data-part.spec.d.ts.map +1 -0
  54. package/dist/src/agent-chat/agent-chat-queue.d.ts +29 -0
  55. package/dist/src/agent-chat/agent-chat-queue.d.ts.map +1 -0
  56. package/dist/src/agent-chat/agent-chat-stream.d.ts +74 -0
  57. package/dist/src/agent-chat/agent-chat-stream.d.ts.map +1 -0
  58. package/dist/src/agent-chat/agent-chat-transport.d.ts +29 -0
  59. package/dist/src/agent-chat/agent-chat-transport.d.ts.map +1 -0
  60. package/dist/src/agent-chat/agent-turn-sources.d.ts +23 -0
  61. package/dist/src/agent-chat/agent-turn-sources.d.ts.map +1 -0
  62. package/dist/src/agent-chat/ask-questions.d.ts +51 -0
  63. package/dist/src/agent-chat/ask-questions.d.ts.map +1 -0
  64. package/dist/src/agent-chat/pending-clarification.d.ts +27 -0
  65. package/dist/src/agent-chat/pending-clarification.d.ts.map +1 -0
  66. package/dist/src/agent-chat/steer-into-live-turn.d.ts +35 -0
  67. package/dist/src/agent-chat/steer-into-live-turn.d.ts.map +1 -0
  68. package/dist/src/agent-chat/stop-agent-chat-turn.d.ts +12 -0
  69. package/dist/src/agent-chat/stop-agent-chat-turn.d.ts.map +1 -0
  70. package/dist/src/agent-chat/useAgentChat.d.ts +54 -0
  71. package/dist/src/agent-chat/useAgentChat.d.ts.map +1 -0
  72. package/dist/src/hooks/__tests__/use-display-mode.spec.d.ts +2 -0
  73. package/dist/src/hooks/__tests__/use-display-mode.spec.d.ts.map +1 -0
  74. package/dist/src/hooks/__tests__/use-widget-layout.spec.d.ts +2 -0
  75. package/dist/src/hooks/__tests__/use-widget-layout.spec.d.ts.map +1 -0
  76. package/dist/src/hooks/__tests__/useHostLocation.spec.d.ts +2 -0
  77. package/dist/src/hooks/__tests__/useHostLocation.spec.d.ts.map +1 -0
  78. package/dist/src/hooks/useBot.d.ts +8 -0
  79. package/dist/src/hooks/useBot.d.ts.map +1 -0
  80. package/dist/src/hooks/useCsat.d.ts +1 -1
  81. package/dist/src/hooks/useCsat.d.ts.map +1 -1
  82. package/dist/src/hooks/useDictation.d.ts +22 -0
  83. package/dist/src/hooks/useDictation.d.ts.map +1 -0
  84. package/dist/src/hooks/useDisplayMode.d.ts +7 -0
  85. package/dist/src/hooks/useDisplayMode.d.ts.map +1 -0
  86. package/dist/src/hooks/useHostLocation.d.ts +17 -0
  87. package/dist/src/hooks/useHostLocation.d.ts.map +1 -0
  88. package/dist/src/hooks/useIsAwaitingBotReply.d.ts.map +1 -1
  89. package/dist/src/hooks/useMessages.d.ts +3 -6
  90. package/dist/src/hooks/useMessages.d.ts.map +1 -1
  91. package/dist/src/hooks/useModes.d.ts +5 -12
  92. package/dist/src/hooks/useModes.d.ts.map +1 -1
  93. package/dist/src/hooks/useSessions.d.ts.map +1 -1
  94. package/dist/src/hooks/useUploadFiles.d.ts +1 -1
  95. package/dist/src/hooks/useWidgetLayout.d.ts +60 -0
  96. package/dist/src/hooks/useWidgetLayout.d.ts.map +1 -0
  97. package/dist/src/index.d.ts +10 -0
  98. package/dist/src/index.d.ts.map +1 -1
  99. package/package.json +9 -3
package/dist/index.js CHANGED
@@ -1,273 +1,4802 @@
1
- import E, { createContext as v, useRef as y, useState as b, useMemo as m, useEffect as C, useContext as F, useSyncExternalStore as k } from "react";
2
- import { WidgetCtx as T } from "@opencx/widget-core";
3
- import { v4 as W } from "uuid";
4
- const O = "4.0.62";
5
- class P {
1
+ import V, { useSyncExternalStore as Oe, useRef as j, useCallback as U, useEffect as $, useMemo as X, useState as Z, createContext as Ue, useContext as qe } from "react";
2
+ import { isAgentStreamKeepalive as Zt, isRecord as Rr, isTurnSteeredPart as Or, buildSendMessageBody as Pr, log as q, genUuid as yt, WidgetCtx as Nr, resolveSidebarMode as jr, resolveSidebarSide as Dr, normalizeCompanionLayouts as Lr, resolveCompanionDefaultLayout as Fr } from "@opencx/widget-core";
3
+ import * as bt from "zod/v4";
4
+ import { z as s } from "zod/v4";
5
+ import { ZodFirstPartyTypeKind as C } from "zod/v3";
6
+ import "react/jsx-runtime";
7
+ import { z } from "zod";
8
+ import { v4 as kr } from "uuid";
9
+ const $r = "5.0.0-beta.1";
10
+ class Ur {
6
11
  constructor(t) {
7
12
  this.components = [];
8
- const { components: n } = t;
9
- if (n && n.forEach((o) => this.register(o)), this.components.length === 0)
13
+ const { components: r } = t;
14
+ if (r && r.forEach((a) => this.register(a)), this.components.length === 0)
10
15
  throw new Error("No components registered");
11
16
  if (!this.get("fallback"))
12
17
  throw new Error("No fallback component registered");
13
18
  }
14
- // TODO test that this registers or replaces the component
15
19
  register(t) {
16
- const n = this.components.findIndex((o) => o.key === t.key);
17
- return n !== -1 ? this.components[n] = t : this.components.push(t), this;
20
+ const r = this.components.findIndex(
21
+ (a) => a.key.toUpperCase() === t.key.toUpperCase()
22
+ );
23
+ return r !== -1 ? this.components[r] = t : this.components.push(t), this;
24
+ }
25
+ get(t) {
26
+ const r = this.components.find(
27
+ (a) => a.key.toUpperCase() === t.toUpperCase()
28
+ );
29
+ return r || null;
30
+ }
31
+ getComponent(t) {
32
+ var r;
33
+ return (r = this.get(t)) == null ? void 0 : r.component;
34
+ }
35
+ }
36
+ function de(e) {
37
+ return Oe(e.subscribe, e.get, e.get);
38
+ }
39
+ function qr({
40
+ turnSources: e,
41
+ liveItems: t,
42
+ isStreaming: r,
43
+ lastMessageIsFromUser: a
44
+ }) {
45
+ var o;
46
+ if (r || a) return null;
47
+ const n = t.length > 0 ? t : (o = e.at(-1)) == null ? void 0 : o.items;
48
+ return n ? Zr(n) : null;
49
+ }
50
+ function Zr(e) {
51
+ for (let t = e.length - 1; t >= 0; t--) {
52
+ const r = e[t];
53
+ if ((r == null ? void 0 : r.kind) === "questions") return r.request;
54
+ }
55
+ return null;
56
+ }
57
+ var zt = "vercel.ai.error", zr = Symbol.for(zt), Et, St, re = class Bt extends (St = Error, Et = zr, St) {
58
+ /**
59
+ * Creates an AI SDK Error.
60
+ *
61
+ * @param {Object} params - The parameters for creating the error.
62
+ * @param {string} params.name - The name of the error.
63
+ * @param {string} params.message - The error message.
64
+ * @param {unknown} [params.cause] - The underlying cause of the error.
65
+ */
66
+ constructor({
67
+ name: t,
68
+ message: r,
69
+ cause: a
70
+ }) {
71
+ super(r), this[Et] = !0, this.name = t, this.cause = a;
72
+ }
73
+ /**
74
+ * Checks if the given error is an AI SDK Error.
75
+ * @param {unknown} error - The error to check.
76
+ * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
77
+ */
78
+ static isInstance(t) {
79
+ return Bt.hasMarker(t, zt);
80
+ }
81
+ static hasMarker(t, r) {
82
+ const a = Symbol.for(r);
83
+ return t != null && typeof t == "object" && a in t && typeof t[a] == "boolean" && t[a] === !0;
84
+ }
85
+ };
86
+ function Wt(e) {
87
+ return e == null ? "unknown error" : typeof e == "string" ? e : e instanceof Error ? e.toString() : JSON.stringify(e);
88
+ }
89
+ var Vt = "AI_InvalidArgumentError", Jt = `vercel.ai.error.${Vt}`, Br = Symbol.for(Jt), It, _t, Wr = class extends (_t = re, It = Br, _t) {
90
+ constructor({
91
+ message: e,
92
+ cause: t,
93
+ argument: r
94
+ }) {
95
+ super({ name: Vt, message: e, cause: t }), this[It] = !0, this.argument = r;
96
+ }
97
+ static isInstance(e) {
98
+ return re.hasMarker(e, Jt);
99
+ }
100
+ }, Kt = "AI_JSONParseError", Yt = `vercel.ai.error.${Kt}`, Vr = Symbol.for(Yt), wt, Mt, Tt = class extends (Mt = re, wt = Vr, Mt) {
101
+ constructor({ text: e, cause: t }) {
102
+ super({
103
+ name: Kt,
104
+ message: `JSON parsing failed: Text: ${e}.
105
+ Error message: ${Wt(t)}`,
106
+ cause: t
107
+ }), this[wt] = !0, this.text = e;
108
+ }
109
+ static isInstance(e) {
110
+ return re.hasMarker(e, Yt);
111
+ }
112
+ }, Ht = "AI_TypeValidationError", Gt = `vercel.ai.error.${Ht}`, Jr = Symbol.for(Gt), At, Ct, we = class et extends (Ct = re, At = Jr, Ct) {
113
+ constructor({
114
+ value: t,
115
+ cause: r,
116
+ context: a
117
+ }) {
118
+ let n = "Type validation failed";
119
+ if (a != null && a.field && (n += ` for ${a.field}`), a != null && a.entityName || a != null && a.entityId) {
120
+ n += " (";
121
+ const o = [];
122
+ a.entityName && o.push(a.entityName), a.entityId && o.push(`id: "${a.entityId}"`), n += o.join(", "), n += ")";
123
+ }
124
+ super({
125
+ name: Ht,
126
+ message: `${n}: Value: ${JSON.stringify(t)}.
127
+ Error message: ${Wt(r)}`,
128
+ cause: r
129
+ }), this[At] = !0, this.value = t, this.context = a;
130
+ }
131
+ static isInstance(t) {
132
+ return re.hasMarker(t, Gt);
133
+ }
134
+ /**
135
+ * Wraps an error into a TypeValidationError.
136
+ * If the cause is already a TypeValidationError with the same value and context, it returns the cause.
137
+ * Otherwise, it creates a new TypeValidationError.
138
+ *
139
+ * @param {Object} params - The parameters for wrapping the error.
140
+ * @param {unknown} params.value - The value that failed validation.
141
+ * @param {unknown} params.cause - The original error or cause of the validation failure.
142
+ * @param {TypeValidationContext} params.context - Optional context about what is being validated.
143
+ * @returns {TypeValidationError} A TypeValidationError instance.
144
+ */
145
+ static wrap({
146
+ value: t,
147
+ cause: r,
148
+ context: a
149
+ }) {
150
+ var n, o, u;
151
+ return et.isInstance(r) && r.value === t && ((n = r.context) == null ? void 0 : n.field) === (a == null ? void 0 : a.field) && ((o = r.context) == null ? void 0 : o.entityName) === (a == null ? void 0 : a.entityName) && ((u = r.context) == null ? void 0 : u.entityId) === (a == null ? void 0 : a.entityId) ? r : new et({ value: t, cause: r, context: a });
152
+ }
153
+ };
154
+ class Ke extends Error {
155
+ constructor(t, r) {
156
+ super(t), this.name = "ParseError", this.type = r.type, this.field = r.field, this.value = r.value, this.line = r.line;
157
+ }
158
+ }
159
+ const xt = 10, Kr = 13, fe = 32;
160
+ function Ye(e) {
161
+ }
162
+ function Yr(e) {
163
+ if (typeof e == "function")
164
+ throw new TypeError(
165
+ "`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?"
166
+ );
167
+ const { onEvent: t = Ye, onError: r = Ye, onRetry: a = Ye, onComment: n, maxBufferSize: o } = e, u = [];
168
+ let i = 0, g = !0, c, l = "", p = 0, v, h = !1;
169
+ function A(f) {
170
+ if (h)
171
+ throw new Error(
172
+ "Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing."
173
+ );
174
+ if (g && (g = !1, f.charCodeAt(0) === 239 && f.charCodeAt(1) === 187 && f.charCodeAt(2) === 191 && (f = f.slice(3))), u.length === 0) {
175
+ const y = S(f);
176
+ y !== "" && (u.push(y), i = y.length), M();
177
+ return;
178
+ }
179
+ if (f.indexOf(`
180
+ `) === -1 && f.indexOf("\r") === -1) {
181
+ u.push(f), i += f.length, M();
182
+ return;
183
+ }
184
+ u.push(f);
185
+ const m = u.join("");
186
+ u.length = 0, i = 0;
187
+ const b = S(m);
188
+ b !== "" && (u.push(b), i = b.length), M();
189
+ }
190
+ function M() {
191
+ o !== void 0 && (i + l.length <= o || (h = !0, u.length = 0, i = 0, c = void 0, l = "", p = 0, v = void 0, r(
192
+ new Ke(`Buffered data exceeded max buffer size of ${o} characters`, {
193
+ type: "max-buffer-size-exceeded"
194
+ })
195
+ )));
196
+ }
197
+ function S(f) {
198
+ let m = 0;
199
+ if (f.indexOf("\r") === -1) {
200
+ let b = f.indexOf(`
201
+ `, m);
202
+ for (; b !== -1; ) {
203
+ if (m === b) {
204
+ p > 0 && t({ id: c, event: v, data: l }), c = void 0, l = "", p = 0, v = void 0, m = b + 1, b = f.indexOf(`
205
+ `, m);
206
+ continue;
207
+ }
208
+ const y = f.charCodeAt(m);
209
+ if (Rt(f, m, y)) {
210
+ const w = f.charCodeAt(m + 5) === fe ? m + 6 : m + 5, D = f.slice(w, b);
211
+ if (p === 0 && f.charCodeAt(b + 1) === xt) {
212
+ t({ id: c, event: v, data: D }), c = void 0, l = "", v = void 0, m = b + 2, b = f.indexOf(`
213
+ `, m);
214
+ continue;
215
+ }
216
+ l = p === 0 ? D : `${l}
217
+ ${D}`, p++;
218
+ } else Ot(f, m, y) ? v = f.slice(
219
+ f.charCodeAt(m + 6) === fe ? m + 7 : m + 6,
220
+ b
221
+ ) || void 0 : I(f, m, b);
222
+ m = b + 1, b = f.indexOf(`
223
+ `, m);
224
+ }
225
+ return f.slice(m);
226
+ }
227
+ for (; m < f.length; ) {
228
+ const b = f.indexOf("\r", m), y = f.indexOf(`
229
+ `, m);
230
+ let w = -1;
231
+ if (b !== -1 && y !== -1 ? w = b < y ? b : y : b !== -1 ? b === f.length - 1 ? w = -1 : w = b : y !== -1 && (w = y), w === -1)
232
+ break;
233
+ I(f, m, w), m = w + 1, f.charCodeAt(m - 1) === Kr && f.charCodeAt(m) === xt && m++;
234
+ }
235
+ return f.slice(m);
236
+ }
237
+ function I(f, m, b) {
238
+ if (m === b) {
239
+ R();
240
+ return;
241
+ }
242
+ const y = f.charCodeAt(m);
243
+ if (Rt(f, m, y)) {
244
+ const Y = f.charCodeAt(m + 5) === fe ? m + 6 : m + 5, ee = f.slice(Y, b);
245
+ l = p === 0 ? ee : `${l}
246
+ ${ee}`, p++;
247
+ return;
248
+ }
249
+ if (Ot(f, m, y)) {
250
+ v = f.slice(f.charCodeAt(m + 6) === fe ? m + 7 : m + 6, b) || void 0;
251
+ return;
252
+ }
253
+ if (y === 105 && f.charCodeAt(m + 1) === 100 && f.charCodeAt(m + 2) === 58) {
254
+ const Y = f.slice(f.charCodeAt(m + 3) === fe ? m + 4 : m + 3, b);
255
+ c = Y.includes("\0") ? void 0 : Y;
256
+ return;
257
+ }
258
+ if (y === 58) {
259
+ if (n) {
260
+ const Y = f.slice(m, b);
261
+ n(Y.slice(f.charCodeAt(m + 1) === fe ? 2 : 1));
262
+ }
263
+ return;
264
+ }
265
+ const w = f.slice(m, b), D = w.indexOf(":");
266
+ if (D === -1) {
267
+ _(w, "", w);
268
+ return;
269
+ }
270
+ const se = w.slice(0, D), Be = w.charCodeAt(D + 1) === fe ? 2 : 1, We = w.slice(D + Be);
271
+ _(se, We, w);
272
+ }
273
+ function _(f, m, b) {
274
+ switch (f) {
275
+ case "event":
276
+ v = m || void 0;
277
+ break;
278
+ case "data":
279
+ l = p === 0 ? m : `${l}
280
+ ${m}`, p++;
281
+ break;
282
+ case "id":
283
+ c = m.includes("\0") ? void 0 : m;
284
+ break;
285
+ case "retry":
286
+ /^\d+$/.test(m) ? a(parseInt(m, 10)) : r(
287
+ new Ke(`Invalid \`retry\` value: "${m}"`, {
288
+ type: "invalid-retry",
289
+ value: m,
290
+ line: b
291
+ })
292
+ );
293
+ break;
294
+ default:
295
+ r(
296
+ new Ke(
297
+ `Unknown field "${f.length > 20 ? `${f.slice(0, 20)}…` : f}"`,
298
+ { type: "unknown-field", field: f, value: m, line: b }
299
+ )
300
+ );
301
+ break;
302
+ }
303
+ }
304
+ function R() {
305
+ p > 0 && t({
306
+ id: c,
307
+ event: v,
308
+ data: l
309
+ }), c = void 0, l = "", p = 0, v = void 0;
310
+ }
311
+ function d(f = {}) {
312
+ if (f.consume && u.length > 0) {
313
+ const m = u.join("");
314
+ I(m, 0, m.length);
315
+ }
316
+ g = !0, c = void 0, l = "", p = 0, v = void 0, u.length = 0, i = 0, h = !1;
317
+ }
318
+ return { feed: A, reset: d };
319
+ }
320
+ function Rt(e, t, r) {
321
+ return r === 100 && e.charCodeAt(t + 1) === 97 && e.charCodeAt(t + 2) === 116 && e.charCodeAt(t + 3) === 97 && e.charCodeAt(t + 4) === 58;
322
+ }
323
+ function Ot(e, t, r) {
324
+ return r === 101 && e.charCodeAt(t + 1) === 118 && e.charCodeAt(t + 2) === 101 && e.charCodeAt(t + 3) === 110 && e.charCodeAt(t + 4) === 116 && e.charCodeAt(t + 5) === 58;
325
+ }
326
+ class Hr extends TransformStream {
327
+ constructor({ onError: t, onRetry: r, onComment: a, maxBufferSize: n } = {}) {
328
+ let o;
329
+ super({
330
+ start(u) {
331
+ o = Yr({
332
+ onEvent: (i) => {
333
+ u.enqueue(i);
334
+ },
335
+ onError(i) {
336
+ typeof t == "function" && t(i), (t === "terminate" || i.type === "max-buffer-size-exceeded") && u.error(i);
337
+ },
338
+ onRetry: r,
339
+ onComment: a,
340
+ maxBufferSize: n
341
+ });
342
+ },
343
+ transform(u) {
344
+ o.feed(u);
345
+ }
346
+ });
347
+ }
348
+ }
349
+ new TextDecoder();
350
+ var J = ({
351
+ prefix: e,
352
+ size: t = 16,
353
+ alphabet: r = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz",
354
+ separator: a = "-"
355
+ } = {}) => {
356
+ const n = () => {
357
+ const o = r.length, u = new Array(t);
358
+ for (let i = 0; i < t; i++)
359
+ u[i] = r[Math.random() * o | 0];
360
+ return u.join("");
361
+ };
362
+ if (e == null)
363
+ return n;
364
+ if (r.includes(a))
365
+ throw new Wr({
366
+ argument: "separator",
367
+ message: `The separator "${a}" must not be part of the alphabet "${r}".`
368
+ });
369
+ return () => `${e}${a}${n()}`;
370
+ }, Gr = J();
371
+ function Ee(e) {
372
+ if (e == null)
373
+ return {};
374
+ const t = {};
375
+ if (e instanceof Headers)
376
+ e.forEach((r, a) => {
377
+ t[a.toLowerCase()] = r;
378
+ });
379
+ else {
380
+ Array.isArray(e) || (e = Object.entries(e));
381
+ for (const [r, a] of e)
382
+ a != null && (t[r.toLowerCase()] = a);
383
+ }
384
+ return t;
385
+ }
386
+ function Qr(e) {
387
+ var t, r;
388
+ return (r = (t = globalThis.Buffer) == null ? void 0 : t.isBuffer(e)) != null ? r : !1;
389
+ }
390
+ var Xr = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/, ea = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/;
391
+ function Pt(e) {
392
+ const t = JSON.parse(e);
393
+ return t === null || typeof t != "object" || Xr.test(e) === !1 && ea.test(e) === !1 ? t : ta(t);
394
+ }
395
+ function ta(e) {
396
+ let t = [e];
397
+ for (; t.length; ) {
398
+ const r = t;
399
+ t = [];
400
+ for (const a of r) {
401
+ if (Object.prototype.hasOwnProperty.call(a, "__proto__"))
402
+ throw new SyntaxError("Object contains forbidden prototype property");
403
+ if (Object.prototype.hasOwnProperty.call(a, "constructor") && a.constructor !== null && typeof a.constructor == "object" && Object.prototype.hasOwnProperty.call(a.constructor, "prototype"))
404
+ throw new SyntaxError("Object contains forbidden prototype property");
405
+ for (const n in a) {
406
+ const o = a[n];
407
+ o && typeof o == "object" && t.push(o);
408
+ }
409
+ }
410
+ }
411
+ return e;
412
+ }
413
+ function ra(e) {
414
+ const { stackTraceLimit: t } = Error;
415
+ try {
416
+ Error.stackTraceLimit = 0;
417
+ } catch {
418
+ return Pt(e);
419
+ }
420
+ try {
421
+ return Pt(e);
422
+ } finally {
423
+ Error.stackTraceLimit = t;
424
+ }
425
+ }
426
+ function lt(e) {
427
+ if (e.type === "object" || Array.isArray(e.type) && e.type.includes("object")) {
428
+ e.additionalProperties = !1;
429
+ const { properties: r } = e;
430
+ if (r != null)
431
+ for (const a of Object.keys(r))
432
+ r[a] = me(r[a]);
433
+ }
434
+ e.items != null && (e.items = Array.isArray(e.items) ? e.items.map(me) : me(e.items)), e.anyOf != null && (e.anyOf = e.anyOf.map(me)), e.allOf != null && (e.allOf = e.allOf.map(me)), e.oneOf != null && (e.oneOf = e.oneOf.map(me));
435
+ const { definitions: t } = e;
436
+ if (t != null)
437
+ for (const r of Object.keys(t))
438
+ t[r] = me(t[r]);
439
+ return e;
440
+ }
441
+ function me(e) {
442
+ return typeof e == "boolean" ? e : lt(e);
443
+ }
444
+ var aa = /* @__PURE__ */ Symbol(
445
+ "Let zodToJsonSchema decide on which parser to use"
446
+ ), Nt = {
447
+ name: void 0,
448
+ $refStrategy: "root",
449
+ basePath: ["#"],
450
+ effectStrategy: "input",
451
+ pipeStrategy: "all",
452
+ dateStrategy: "format:date-time",
453
+ mapStrategy: "entries",
454
+ removeAdditionalStrategy: "passthrough",
455
+ allowedAdditionalProperties: !0,
456
+ rejectedAdditionalProperties: !1,
457
+ definitionPath: "definitions",
458
+ strictUnions: !1,
459
+ definitions: {},
460
+ errorMessages: !1,
461
+ patternStrategy: "escape",
462
+ applyRegexFlags: !1,
463
+ emailStrategy: "format:email",
464
+ base64Strategy: "contentEncoding:base64",
465
+ nameStrategy: "ref"
466
+ }, sa = (e) => typeof e == "string" ? {
467
+ ...Nt,
468
+ name: e
469
+ } : {
470
+ ...Nt,
471
+ ...e
472
+ };
473
+ function B() {
474
+ return {};
475
+ }
476
+ function na(e, t) {
477
+ var r, a, n;
478
+ const o = {
479
+ type: "array"
480
+ };
481
+ return (r = e.type) != null && r._def && ((n = (a = e.type) == null ? void 0 : a._def) == null ? void 0 : n.typeName) !== C.ZodAny && (o.items = P(e.type._def, {
482
+ ...t,
483
+ currentPath: [...t.currentPath, "items"]
484
+ })), e.minLength && (o.minItems = e.minLength.value), e.maxLength && (o.maxItems = e.maxLength.value), e.exactLength && (o.minItems = e.exactLength.value, o.maxItems = e.exactLength.value), o;
485
+ }
486
+ function ia(e) {
487
+ const t = {
488
+ type: "integer",
489
+ format: "int64"
490
+ };
491
+ if (!e.checks) return t;
492
+ for (const r of e.checks)
493
+ switch (r.kind) {
494
+ case "min":
495
+ r.inclusive ? t.minimum = r.value : t.exclusiveMinimum = r.value;
496
+ break;
497
+ case "max":
498
+ r.inclusive ? t.maximum = r.value : t.exclusiveMaximum = r.value;
499
+ break;
500
+ case "multipleOf":
501
+ t.multipleOf = r.value;
502
+ break;
503
+ }
504
+ return t;
505
+ }
506
+ function oa() {
507
+ return { type: "boolean" };
508
+ }
509
+ function Qt(e, t) {
510
+ return P(e.type._def, t);
511
+ }
512
+ var la = (e, t) => P(e.innerType._def, t);
513
+ function Xt(e, t, r) {
514
+ const a = r ?? t.dateStrategy;
515
+ if (Array.isArray(a))
516
+ return {
517
+ anyOf: a.map((n) => Xt(e, t, n))
518
+ };
519
+ switch (a) {
520
+ case "string":
521
+ case "format:date-time":
522
+ return {
523
+ type: "string",
524
+ format: "date-time"
525
+ };
526
+ case "format:date":
527
+ return {
528
+ type: "string",
529
+ format: "date"
530
+ };
531
+ case "integer":
532
+ return ua(e);
533
+ }
534
+ }
535
+ var ua = (e) => {
536
+ const t = {
537
+ type: "integer",
538
+ format: "unix-time"
539
+ };
540
+ for (const r of e.checks)
541
+ switch (r.kind) {
542
+ case "min":
543
+ t.minimum = r.value;
544
+ break;
545
+ case "max":
546
+ t.maximum = r.value;
547
+ break;
548
+ }
549
+ return t;
550
+ };
551
+ function ca(e, t) {
552
+ return {
553
+ ...P(e.innerType._def, t),
554
+ default: e.defaultValue()
555
+ };
556
+ }
557
+ function da(e, t) {
558
+ return t.effectStrategy === "input" ? P(e.schema._def, t) : B();
559
+ }
560
+ function pa(e) {
561
+ return {
562
+ type: "string",
563
+ enum: Array.from(e.values)
564
+ };
565
+ }
566
+ var fa = (e) => "type" in e && e.type === "string" ? !1 : "allOf" in e;
567
+ function ma(e, t) {
568
+ const r = [
569
+ P(e.left._def, {
570
+ ...t,
571
+ currentPath: [...t.currentPath, "allOf", "0"]
572
+ }),
573
+ P(e.right._def, {
574
+ ...t,
575
+ currentPath: [...t.currentPath, "allOf", "1"]
576
+ })
577
+ ].filter((n) => !!n), a = [];
578
+ return r.forEach((n) => {
579
+ if (fa(n))
580
+ a.push(...n.allOf);
581
+ else {
582
+ let o = n;
583
+ if ("additionalProperties" in n && n.additionalProperties === !1) {
584
+ const { additionalProperties: u, ...i } = n;
585
+ o = i;
586
+ }
587
+ a.push(o);
588
+ }
589
+ }), a.length ? { allOf: a } : void 0;
590
+ }
591
+ function ga(e) {
592
+ const t = typeof e.value;
593
+ return t !== "bigint" && t !== "number" && t !== "boolean" && t !== "string" ? {
594
+ type: Array.isArray(e.value) ? "array" : "object"
595
+ } : {
596
+ type: t === "bigint" ? "integer" : t,
597
+ const: e.value
598
+ };
599
+ }
600
+ var He = void 0, G = {
601
+ /**
602
+ * `c` was changed to `[cC]` to replicate /i flag
603
+ */
604
+ cuid: /^[cC][^\s-]{8,}$/,
605
+ cuid2: /^[0-9a-z]+$/,
606
+ ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/,
607
+ /**
608
+ * `a-z` was added to replicate /i flag
609
+ */
610
+ email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,
611
+ /**
612
+ * Constructed a valid Unicode RegExp
613
+ *
614
+ * Lazily instantiate since this type of regex isn't supported
615
+ * in all envs (e.g. React Native).
616
+ *
617
+ * See:
618
+ * https://github.com/colinhacks/zod/issues/2433
619
+ * Fix in Zod:
620
+ * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b
621
+ */
622
+ emoji: () => (He === void 0 && (He = RegExp(
623
+ "^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",
624
+ "u"
625
+ )), He),
626
+ /**
627
+ * Unused
628
+ */
629
+ uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,
630
+ /**
631
+ * Unused
632
+ */
633
+ ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,
634
+ ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,
635
+ /**
636
+ * Unused
637
+ */
638
+ ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,
639
+ ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,
640
+ base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,
641
+ base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,
642
+ nanoid: /^[a-zA-Z0-9_-]{21}$/,
643
+ jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/
644
+ };
645
+ function er(e, t) {
646
+ const r = {
647
+ type: "string"
648
+ };
649
+ if (e.checks)
650
+ for (const a of e.checks)
651
+ switch (a.kind) {
652
+ case "min":
653
+ r.minLength = typeof r.minLength == "number" ? Math.max(r.minLength, a.value) : a.value;
654
+ break;
655
+ case "max":
656
+ r.maxLength = typeof r.maxLength == "number" ? Math.min(r.maxLength, a.value) : a.value;
657
+ break;
658
+ case "email":
659
+ switch (t.emailStrategy) {
660
+ case "format:email":
661
+ Q(r, "email", a.message, t);
662
+ break;
663
+ case "format:idn-email":
664
+ Q(r, "idn-email", a.message, t);
665
+ break;
666
+ case "pattern:zod":
667
+ k(r, G.email, a.message, t);
668
+ break;
669
+ }
670
+ break;
671
+ case "url":
672
+ Q(r, "uri", a.message, t);
673
+ break;
674
+ case "uuid":
675
+ Q(r, "uuid", a.message, t);
676
+ break;
677
+ case "regex":
678
+ k(r, a.regex, a.message, t);
679
+ break;
680
+ case "cuid":
681
+ k(r, G.cuid, a.message, t);
682
+ break;
683
+ case "cuid2":
684
+ k(r, G.cuid2, a.message, t);
685
+ break;
686
+ case "startsWith":
687
+ k(
688
+ r,
689
+ RegExp(`^${Ge(a.value, t)}`),
690
+ a.message,
691
+ t
692
+ );
693
+ break;
694
+ case "endsWith":
695
+ k(
696
+ r,
697
+ RegExp(`${Ge(a.value, t)}$`),
698
+ a.message,
699
+ t
700
+ );
701
+ break;
702
+ case "datetime":
703
+ Q(r, "date-time", a.message, t);
704
+ break;
705
+ case "date":
706
+ Q(r, "date", a.message, t);
707
+ break;
708
+ case "time":
709
+ Q(r, "time", a.message, t);
710
+ break;
711
+ case "duration":
712
+ Q(r, "duration", a.message, t);
713
+ break;
714
+ case "length":
715
+ r.minLength = typeof r.minLength == "number" ? Math.max(r.minLength, a.value) : a.value, r.maxLength = typeof r.maxLength == "number" ? Math.min(r.maxLength, a.value) : a.value;
716
+ break;
717
+ case "includes": {
718
+ k(
719
+ r,
720
+ RegExp(Ge(a.value, t)),
721
+ a.message,
722
+ t
723
+ );
724
+ break;
725
+ }
726
+ case "ip": {
727
+ a.version !== "v6" && Q(r, "ipv4", a.message, t), a.version !== "v4" && Q(r, "ipv6", a.message, t);
728
+ break;
729
+ }
730
+ case "base64url":
731
+ k(r, G.base64url, a.message, t);
732
+ break;
733
+ case "jwt":
734
+ k(r, G.jwt, a.message, t);
735
+ break;
736
+ case "cidr": {
737
+ a.version !== "v6" && k(r, G.ipv4Cidr, a.message, t), a.version !== "v4" && k(r, G.ipv6Cidr, a.message, t);
738
+ break;
739
+ }
740
+ case "emoji":
741
+ k(r, G.emoji(), a.message, t);
742
+ break;
743
+ case "ulid": {
744
+ k(r, G.ulid, a.message, t);
745
+ break;
746
+ }
747
+ case "base64": {
748
+ switch (t.base64Strategy) {
749
+ case "format:binary": {
750
+ Q(r, "binary", a.message, t);
751
+ break;
752
+ }
753
+ case "contentEncoding:base64": {
754
+ r.contentEncoding = "base64";
755
+ break;
756
+ }
757
+ case "pattern:zod": {
758
+ k(r, G.base64, a.message, t);
759
+ break;
760
+ }
761
+ }
762
+ break;
763
+ }
764
+ case "nanoid":
765
+ k(r, G.nanoid, a.message, t);
766
+ }
767
+ return r;
768
+ }
769
+ function Ge(e, t) {
770
+ return t.patternStrategy === "escape" ? ha(e) : e;
771
+ }
772
+ var va = new Set(
773
+ "ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"
774
+ );
775
+ function ha(e) {
776
+ let t = "";
777
+ for (let r = 0; r < e.length; r++)
778
+ va.has(e[r]) || (t += "\\"), t += e[r];
779
+ return t;
780
+ }
781
+ function Q(e, t, r, a) {
782
+ var n;
783
+ e.format || (n = e.anyOf) != null && n.some((o) => o.format) ? (e.anyOf || (e.anyOf = []), e.format && (e.anyOf.push({
784
+ format: e.format
785
+ }), delete e.format), e.anyOf.push({
786
+ format: t,
787
+ ...r && a.errorMessages && { errorMessage: { format: r } }
788
+ })) : e.format = t;
789
+ }
790
+ function k(e, t, r, a) {
791
+ var n;
792
+ e.pattern || (n = e.allOf) != null && n.some((o) => o.pattern) ? (e.allOf || (e.allOf = []), e.pattern && (e.allOf.push({
793
+ pattern: e.pattern
794
+ }), delete e.pattern), e.allOf.push({
795
+ pattern: jt(t, a),
796
+ ...r && a.errorMessages && { errorMessage: { pattern: r } }
797
+ })) : e.pattern = jt(t, a);
798
+ }
799
+ function jt(e, t) {
800
+ var r;
801
+ if (!t.applyRegexFlags || !e.flags)
802
+ return e.source;
803
+ const a = {
804
+ i: e.flags.includes("i"),
805
+ // Case-insensitive
806
+ m: e.flags.includes("m"),
807
+ // `^` and `$` matches adjacent to newline characters
808
+ s: e.flags.includes("s")
809
+ // `.` matches newlines
810
+ }, n = a.i ? e.source.toLowerCase() : e.source;
811
+ let o = "", u = !1, i = !1, g = !1;
812
+ for (let c = 0; c < n.length; c++) {
813
+ if (u) {
814
+ o += n[c], u = !1;
815
+ continue;
816
+ }
817
+ if (a.i) {
818
+ if (i) {
819
+ if (n[c].match(/[a-z]/)) {
820
+ g ? (o += n[c], o += `${n[c - 2]}-${n[c]}`.toUpperCase(), g = !1) : n[c + 1] === "-" && ((r = n[c + 2]) != null && r.match(/[a-z]/)) ? (o += n[c], g = !0) : o += `${n[c]}${n[c].toUpperCase()}`;
821
+ continue;
822
+ }
823
+ } else if (n[c].match(/[a-z]/)) {
824
+ o += `[${n[c]}${n[c].toUpperCase()}]`;
825
+ continue;
826
+ }
827
+ }
828
+ if (a.m) {
829
+ if (n[c] === "^") {
830
+ o += `(^|(?<=[\r
831
+ ]))`;
832
+ continue;
833
+ } else if (n[c] === "$") {
834
+ o += `($|(?=[\r
835
+ ]))`;
836
+ continue;
837
+ }
838
+ }
839
+ if (a.s && n[c] === ".") {
840
+ o += i ? `${n[c]}\r
841
+ ` : `[${n[c]}\r
842
+ ]`;
843
+ continue;
844
+ }
845
+ o += n[c], n[c] === "\\" ? u = !0 : i && n[c] === "]" ? i = !1 : !i && n[c] === "[" && (i = !0);
846
+ }
847
+ try {
848
+ new RegExp(o);
849
+ } catch {
850
+ return console.warn(
851
+ `Could not convert regex pattern at ${t.currentPath.join(
852
+ "/"
853
+ )} to a flag-independent form! Falling back to the flag-ignorant source`
854
+ ), e.source;
855
+ }
856
+ return o;
857
+ }
858
+ function tr(e, t) {
859
+ var r, a, n, o, u, i;
860
+ const g = {
861
+ type: "object",
862
+ additionalProperties: (r = P(e.valueType._def, {
863
+ ...t,
864
+ currentPath: [...t.currentPath, "additionalProperties"]
865
+ })) != null ? r : t.allowedAdditionalProperties
866
+ };
867
+ if (((a = e.keyType) == null ? void 0 : a._def.typeName) === C.ZodString && ((n = e.keyType._def.checks) != null && n.length)) {
868
+ const { type: c, ...l } = er(e.keyType._def, t);
869
+ return {
870
+ ...g,
871
+ propertyNames: l
872
+ };
873
+ } else {
874
+ if (((o = e.keyType) == null ? void 0 : o._def.typeName) === C.ZodEnum)
875
+ return {
876
+ ...g,
877
+ propertyNames: {
878
+ enum: e.keyType._def.values
879
+ }
880
+ };
881
+ if (((u = e.keyType) == null ? void 0 : u._def.typeName) === C.ZodBranded && e.keyType._def.type._def.typeName === C.ZodString && ((i = e.keyType._def.type._def.checks) != null && i.length)) {
882
+ const { type: c, ...l } = Qt(
883
+ e.keyType._def,
884
+ t
885
+ );
886
+ return {
887
+ ...g,
888
+ propertyNames: l
889
+ };
890
+ }
891
+ }
892
+ return g;
893
+ }
894
+ function ya(e, t) {
895
+ if (t.mapStrategy === "record")
896
+ return tr(e, t);
897
+ const r = P(e.keyType._def, {
898
+ ...t,
899
+ currentPath: [...t.currentPath, "items", "items", "0"]
900
+ }) || B(), a = P(e.valueType._def, {
901
+ ...t,
902
+ currentPath: [...t.currentPath, "items", "items", "1"]
903
+ }) || B();
904
+ return {
905
+ type: "array",
906
+ maxItems: 125,
907
+ items: {
908
+ type: "array",
909
+ items: [r, a],
910
+ minItems: 2,
911
+ maxItems: 2
912
+ }
913
+ };
914
+ }
915
+ function ba(e) {
916
+ const t = e.values, a = Object.keys(e.values).filter((o) => typeof t[t[o]] != "number").map((o) => t[o]), n = Array.from(
917
+ new Set(a.map((o) => typeof o))
918
+ );
919
+ return {
920
+ type: n.length === 1 ? n[0] === "string" ? "string" : "number" : ["string", "number"],
921
+ enum: a
922
+ };
923
+ }
924
+ function Ea() {
925
+ return { not: B() };
926
+ }
927
+ function Sa() {
928
+ return {
929
+ type: "null"
930
+ };
931
+ }
932
+ var tt = {
933
+ ZodString: "string",
934
+ ZodNumber: "number",
935
+ ZodBigInt: "integer",
936
+ ZodBoolean: "boolean",
937
+ ZodNull: "null"
938
+ };
939
+ function Ia(e, t) {
940
+ const r = e.options instanceof Map ? Array.from(e.options.values()) : e.options;
941
+ if (r.every(
942
+ (a) => a._def.typeName in tt && (!a._def.checks || !a._def.checks.length)
943
+ )) {
944
+ const a = r.reduce((n, o) => {
945
+ const u = tt[o._def.typeName];
946
+ return u && !n.includes(u) ? [...n, u] : n;
947
+ }, []);
948
+ return {
949
+ type: a.length > 1 ? a : a[0]
950
+ };
951
+ } else if (r.every((a) => a._def.typeName === "ZodLiteral" && !a.description)) {
952
+ const a = r.reduce(
953
+ (n, o) => {
954
+ const u = typeof o._def.value;
955
+ switch (u) {
956
+ case "string":
957
+ case "number":
958
+ case "boolean":
959
+ return [...n, u];
960
+ case "bigint":
961
+ return [...n, "integer"];
962
+ case "object":
963
+ if (o._def.value === null) return [...n, "null"];
964
+ case "symbol":
965
+ case "undefined":
966
+ case "function":
967
+ default:
968
+ return n;
969
+ }
970
+ },
971
+ []
972
+ );
973
+ if (a.length === r.length) {
974
+ const n = a.filter((o, u, i) => i.indexOf(o) === u);
975
+ return {
976
+ type: n.length > 1 ? n : n[0],
977
+ enum: r.reduce(
978
+ (o, u) => o.includes(u._def.value) ? o : [...o, u._def.value],
979
+ []
980
+ )
981
+ };
982
+ }
983
+ } else if (r.every((a) => a._def.typeName === "ZodEnum"))
984
+ return {
985
+ type: "string",
986
+ enum: r.reduce(
987
+ (a, n) => [
988
+ ...a,
989
+ ...n._def.values.filter((o) => !a.includes(o))
990
+ ],
991
+ []
992
+ )
993
+ };
994
+ return _a(e, t);
995
+ }
996
+ var _a = (e, t) => {
997
+ const r = (e.options instanceof Map ? Array.from(e.options.values()) : e.options).map(
998
+ (a, n) => P(a._def, {
999
+ ...t,
1000
+ currentPath: [...t.currentPath, "anyOf", `${n}`]
1001
+ })
1002
+ ).filter(
1003
+ (a) => !!a && (!t.strictUnions || typeof a == "object" && Object.keys(a).length > 0)
1004
+ );
1005
+ return r.length ? { anyOf: r } : void 0;
1006
+ };
1007
+ function wa(e, t) {
1008
+ if (["ZodString", "ZodNumber", "ZodBigInt", "ZodBoolean", "ZodNull"].includes(
1009
+ e.innerType._def.typeName
1010
+ ) && (!e.innerType._def.checks || !e.innerType._def.checks.length))
1011
+ return {
1012
+ type: [
1013
+ tt[e.innerType._def.typeName],
1014
+ "null"
1015
+ ]
1016
+ };
1017
+ const r = P(e.innerType._def, {
1018
+ ...t,
1019
+ currentPath: [...t.currentPath, "anyOf", "0"]
1020
+ });
1021
+ return r && { anyOf: [r, { type: "null" }] };
1022
+ }
1023
+ function Ma(e) {
1024
+ const t = {
1025
+ type: "number"
1026
+ };
1027
+ if (!e.checks) return t;
1028
+ for (const r of e.checks)
1029
+ switch (r.kind) {
1030
+ case "int":
1031
+ t.type = "integer";
1032
+ break;
1033
+ case "min":
1034
+ r.inclusive ? t.minimum = r.value : t.exclusiveMinimum = r.value;
1035
+ break;
1036
+ case "max":
1037
+ r.inclusive ? t.maximum = r.value : t.exclusiveMaximum = r.value;
1038
+ break;
1039
+ case "multipleOf":
1040
+ t.multipleOf = r.value;
1041
+ break;
1042
+ }
1043
+ return t;
1044
+ }
1045
+ function Ta(e, t) {
1046
+ const r = {
1047
+ type: "object",
1048
+ properties: {}
1049
+ }, a = [], n = e.shape();
1050
+ for (const u in n) {
1051
+ let i = n[u];
1052
+ if (i === void 0 || i._def === void 0)
1053
+ continue;
1054
+ const g = Ca(i), c = P(i._def, {
1055
+ ...t,
1056
+ currentPath: [...t.currentPath, "properties", u],
1057
+ propertyPath: [...t.currentPath, "properties", u]
1058
+ });
1059
+ c !== void 0 && (r.properties[u] = c, g || a.push(u));
1060
+ }
1061
+ a.length && (r.required = a);
1062
+ const o = Aa(e, t);
1063
+ return o !== void 0 && (r.additionalProperties = o), r;
1064
+ }
1065
+ function Aa(e, t) {
1066
+ if (e.catchall._def.typeName !== "ZodNever")
1067
+ return P(e.catchall._def, {
1068
+ ...t,
1069
+ currentPath: [...t.currentPath, "additionalProperties"]
1070
+ });
1071
+ switch (e.unknownKeys) {
1072
+ case "passthrough":
1073
+ return t.allowedAdditionalProperties;
1074
+ case "strict":
1075
+ return t.rejectedAdditionalProperties;
1076
+ case "strip":
1077
+ return t.removeAdditionalStrategy === "strict" ? t.allowedAdditionalProperties : t.rejectedAdditionalProperties;
1078
+ }
1079
+ }
1080
+ function Ca(e) {
1081
+ try {
1082
+ return e.isOptional();
1083
+ } catch {
1084
+ return !0;
1085
+ }
1086
+ }
1087
+ var xa = (e, t) => {
1088
+ var r;
1089
+ if (t.currentPath.toString() === ((r = t.propertyPath) == null ? void 0 : r.toString()))
1090
+ return P(e.innerType._def, t);
1091
+ const a = P(e.innerType._def, {
1092
+ ...t,
1093
+ currentPath: [...t.currentPath, "anyOf", "1"]
1094
+ });
1095
+ return a ? { anyOf: [{ not: B() }, a] } : B();
1096
+ }, Ra = (e, t) => {
1097
+ if (t.pipeStrategy === "input")
1098
+ return P(e.in._def, t);
1099
+ if (t.pipeStrategy === "output")
1100
+ return P(e.out._def, t);
1101
+ const r = P(e.in._def, {
1102
+ ...t,
1103
+ currentPath: [...t.currentPath, "allOf", "0"]
1104
+ }), a = P(e.out._def, {
1105
+ ...t,
1106
+ currentPath: [...t.currentPath, "allOf", r ? "1" : "0"]
1107
+ });
1108
+ return {
1109
+ allOf: [r, a].filter(
1110
+ (n) => n !== void 0
1111
+ )
1112
+ };
1113
+ };
1114
+ function Oa(e, t) {
1115
+ return P(e.type._def, t);
1116
+ }
1117
+ function Pa(e, t) {
1118
+ const a = {
1119
+ type: "array",
1120
+ uniqueItems: !0,
1121
+ items: P(e.valueType._def, {
1122
+ ...t,
1123
+ currentPath: [...t.currentPath, "items"]
1124
+ })
1125
+ };
1126
+ return e.minSize && (a.minItems = e.minSize.value), e.maxSize && (a.maxItems = e.maxSize.value), a;
1127
+ }
1128
+ function Na(e, t) {
1129
+ return e.rest ? {
1130
+ type: "array",
1131
+ minItems: e.items.length,
1132
+ items: e.items.map(
1133
+ (r, a) => P(r._def, {
1134
+ ...t,
1135
+ currentPath: [...t.currentPath, "items", `${a}`]
1136
+ })
1137
+ ).reduce(
1138
+ (r, a) => a === void 0 ? r : [...r, a],
1139
+ []
1140
+ ),
1141
+ additionalItems: P(e.rest._def, {
1142
+ ...t,
1143
+ currentPath: [...t.currentPath, "additionalItems"]
1144
+ })
1145
+ } : {
1146
+ type: "array",
1147
+ minItems: e.items.length,
1148
+ maxItems: e.items.length,
1149
+ items: e.items.map(
1150
+ (r, a) => P(r._def, {
1151
+ ...t,
1152
+ currentPath: [...t.currentPath, "items", `${a}`]
1153
+ })
1154
+ ).reduce(
1155
+ (r, a) => a === void 0 ? r : [...r, a],
1156
+ []
1157
+ )
1158
+ };
1159
+ }
1160
+ function ja() {
1161
+ return {
1162
+ not: B()
1163
+ };
1164
+ }
1165
+ function Da() {
1166
+ return B();
1167
+ }
1168
+ var La = (e, t) => P(e.innerType._def, t), Fa = (e, t, r) => {
1169
+ switch (t) {
1170
+ case C.ZodString:
1171
+ return er(e, r);
1172
+ case C.ZodNumber:
1173
+ return Ma(e);
1174
+ case C.ZodObject:
1175
+ return Ta(e, r);
1176
+ case C.ZodBigInt:
1177
+ return ia(e);
1178
+ case C.ZodBoolean:
1179
+ return oa();
1180
+ case C.ZodDate:
1181
+ return Xt(e, r);
1182
+ case C.ZodUndefined:
1183
+ return ja();
1184
+ case C.ZodNull:
1185
+ return Sa();
1186
+ case C.ZodArray:
1187
+ return na(e, r);
1188
+ case C.ZodUnion:
1189
+ case C.ZodDiscriminatedUnion:
1190
+ return Ia(e, r);
1191
+ case C.ZodIntersection:
1192
+ return ma(e, r);
1193
+ case C.ZodTuple:
1194
+ return Na(e, r);
1195
+ case C.ZodRecord:
1196
+ return tr(e, r);
1197
+ case C.ZodLiteral:
1198
+ return ga(e);
1199
+ case C.ZodEnum:
1200
+ return pa(e);
1201
+ case C.ZodNativeEnum:
1202
+ return ba(e);
1203
+ case C.ZodNullable:
1204
+ return wa(e, r);
1205
+ case C.ZodOptional:
1206
+ return xa(e, r);
1207
+ case C.ZodMap:
1208
+ return ya(e, r);
1209
+ case C.ZodSet:
1210
+ return Pa(e, r);
1211
+ case C.ZodLazy:
1212
+ return () => e.getter()._def;
1213
+ case C.ZodPromise:
1214
+ return Oa(e, r);
1215
+ case C.ZodNaN:
1216
+ case C.ZodNever:
1217
+ return Ea();
1218
+ case C.ZodEffects:
1219
+ return da(e, r);
1220
+ case C.ZodAny:
1221
+ return B();
1222
+ case C.ZodUnknown:
1223
+ return Da();
1224
+ case C.ZodDefault:
1225
+ return ca(e, r);
1226
+ case C.ZodBranded:
1227
+ return Qt(e, r);
1228
+ case C.ZodReadonly:
1229
+ return La(e, r);
1230
+ case C.ZodCatch:
1231
+ return la(e, r);
1232
+ case C.ZodPipeline:
1233
+ return Ra(e, r);
1234
+ case C.ZodFunction:
1235
+ case C.ZodVoid:
1236
+ case C.ZodSymbol:
1237
+ return;
1238
+ default:
1239
+ return /* @__PURE__ */ ((a) => {
1240
+ })();
1241
+ }
1242
+ }, ka = (e, t) => {
1243
+ let r = 0;
1244
+ for (; r < e.length && r < t.length && e[r] === t[r]; r++)
1245
+ ;
1246
+ return [(e.length - r).toString(), ...t.slice(r)].join("/");
1247
+ };
1248
+ function P(e, t, r = !1) {
1249
+ var a;
1250
+ const n = t.seen.get(e);
1251
+ if (t.override) {
1252
+ const g = (a = t.override) == null ? void 0 : a.call(
1253
+ t,
1254
+ e,
1255
+ t,
1256
+ n,
1257
+ r
1258
+ );
1259
+ if (g !== aa)
1260
+ return g;
1261
+ }
1262
+ if (n && !r) {
1263
+ const g = $a(n, t);
1264
+ if (g !== void 0)
1265
+ return g;
1266
+ }
1267
+ const o = { def: e, path: t.currentPath, jsonSchema: void 0 };
1268
+ t.seen.set(e, o);
1269
+ const u = Fa(e, e.typeName, t), i = typeof u == "function" ? P(u(), t) : u;
1270
+ if (i && Ua(e, t, i), t.postProcess) {
1271
+ const g = t.postProcess(i, e, t);
1272
+ return o.jsonSchema = i, g;
1273
+ }
1274
+ return o.jsonSchema = i, i;
1275
+ }
1276
+ var $a = (e, t) => {
1277
+ switch (t.$refStrategy) {
1278
+ case "root":
1279
+ return { $ref: e.path.join("/") };
1280
+ case "relative":
1281
+ return { $ref: ka(t.currentPath, e.path) };
1282
+ case "none":
1283
+ case "seen":
1284
+ return e.path.length < t.currentPath.length && e.path.every((r, a) => t.currentPath[a] === r) ? (console.warn(
1285
+ `Recursive reference detected at ${t.currentPath.join(
1286
+ "/"
1287
+ )}! Defaulting to any`
1288
+ ), B()) : t.$refStrategy === "seen" ? B() : void 0;
1289
+ }
1290
+ }, Ua = (e, t, r) => (e.description && (r.description = e.description), r), qa = (e) => {
1291
+ const t = sa(e), r = t.name !== void 0 ? [...t.basePath, t.definitionPath, t.name] : t.basePath;
1292
+ return {
1293
+ ...t,
1294
+ currentPath: r,
1295
+ propertyPath: void 0,
1296
+ seen: new Map(
1297
+ Object.entries(t.definitions).map(([a, n]) => [
1298
+ n._def,
1299
+ {
1300
+ def: n._def,
1301
+ path: [...t.basePath, t.definitionPath, a],
1302
+ // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now.
1303
+ jsonSchema: void 0
1304
+ }
1305
+ ])
1306
+ )
1307
+ };
1308
+ }, Za = (e, t) => {
1309
+ var r;
1310
+ const a = qa(t);
1311
+ let n = typeof t == "object" && t.definitions ? Object.entries(t.definitions).reduce(
1312
+ (c, [l, p]) => {
1313
+ var v;
1314
+ return {
1315
+ ...c,
1316
+ [l]: (v = P(
1317
+ p._def,
1318
+ {
1319
+ ...a,
1320
+ currentPath: [...a.basePath, a.definitionPath, l]
1321
+ },
1322
+ !0
1323
+ )) != null ? v : B()
1324
+ };
1325
+ },
1326
+ {}
1327
+ ) : void 0;
1328
+ const o = typeof t == "string" ? t : (t == null ? void 0 : t.nameStrategy) === "title" || t == null ? void 0 : t.name, u = (r = P(
1329
+ e._def,
1330
+ o === void 0 ? a : {
1331
+ ...a,
1332
+ currentPath: [...a.basePath, a.definitionPath, o]
1333
+ },
1334
+ !1
1335
+ )) != null ? r : B(), i = typeof t == "object" && t.name !== void 0 && t.nameStrategy === "title" ? t.name : void 0;
1336
+ i !== void 0 && (u.title = i);
1337
+ const g = o === void 0 ? n ? {
1338
+ ...u,
1339
+ [a.definitionPath]: n
1340
+ } : u : {
1341
+ $ref: [
1342
+ ...a.$refStrategy === "relative" ? [] : a.basePath,
1343
+ a.definitionPath,
1344
+ o
1345
+ ].join("/"),
1346
+ [a.definitionPath]: {
1347
+ ...n,
1348
+ [o]: u
1349
+ }
1350
+ };
1351
+ return g.$schema = "http://json-schema.org/draft-07/schema#", g;
1352
+ }, rt = /* @__PURE__ */ Symbol.for("vercel.ai.schema");
1353
+ function za(e) {
1354
+ let t;
1355
+ return () => (t == null && (t = e()), t);
1356
+ }
1357
+ function Ze(e, {
1358
+ validate: t
1359
+ } = {}) {
1360
+ return {
1361
+ [rt]: !0,
1362
+ _type: void 0,
1363
+ // should never be used directly
1364
+ get jsonSchema() {
1365
+ return typeof e == "function" && (e = e()), e;
1366
+ },
1367
+ validate: t
1368
+ };
1369
+ }
1370
+ function Ba(e) {
1371
+ return typeof e == "object" && e !== null && rt in e && e[rt] === !0 && "jsonSchema" in e && "validate" in e;
1372
+ }
1373
+ function ut(e) {
1374
+ return e == null ? Ze({
1375
+ type: "object",
1376
+ properties: {},
1377
+ additionalProperties: !1
1378
+ }) : Ba(e) ? e : "~standard" in e ? e["~standard"].vendor === "zod" ? rr(e) : Wa(e) : e();
1379
+ }
1380
+ function Wa(e) {
1381
+ return Ze(
1382
+ () => {
1383
+ if (!Va(e))
1384
+ throw new Error(
1385
+ `Standard schema vendor '${e["~standard"].vendor}' does not support JSON Schema conversion.`
1386
+ );
1387
+ return lt(
1388
+ e["~standard"].jsonSchema.input({
1389
+ target: "draft-07"
1390
+ })
1391
+ );
1392
+ },
1393
+ {
1394
+ validate: async (t) => {
1395
+ const r = await e["~standard"].validate(t);
1396
+ return "value" in r ? { success: !0, value: r.value } : {
1397
+ success: !1,
1398
+ error: new we({
1399
+ value: t,
1400
+ cause: r.issues
1401
+ })
1402
+ };
1403
+ }
1404
+ }
1405
+ );
1406
+ }
1407
+ function Va(e) {
1408
+ return e["~standard"].jsonSchema != null;
1409
+ }
1410
+ function Ja(e, t) {
1411
+ var r;
1412
+ const a = (r = void 0) != null ? r : !1;
1413
+ return Ze(
1414
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
1415
+ () => Za(e, {
1416
+ $refStrategy: a ? "root" : "none"
1417
+ }),
1418
+ {
1419
+ validate: async (n) => {
1420
+ const o = await e.safeParseAsync(n);
1421
+ return o.success ? { success: !0, value: o.data } : { success: !1, error: o.error };
1422
+ }
1423
+ }
1424
+ );
1425
+ }
1426
+ function Ka(e, t) {
1427
+ var r;
1428
+ const a = (r = void 0) != null ? r : !1;
1429
+ return Ze(
1430
+ // defer json schema creation to avoid unnecessary computation when only validation is needed
1431
+ () => lt(
1432
+ bt.toJSONSchema(e, {
1433
+ target: "draft-7",
1434
+ io: "input",
1435
+ reused: a ? "ref" : "inline"
1436
+ })
1437
+ ),
1438
+ {
1439
+ validate: async (n) => {
1440
+ const o = await bt.safeParseAsync(e, n);
1441
+ return o.success ? { success: !0, value: o.data } : { success: !1, error: o.error };
1442
+ }
1443
+ }
1444
+ );
1445
+ }
1446
+ function Ya(e) {
1447
+ return "_zod" in e;
1448
+ }
1449
+ function rr(e, t) {
1450
+ return Ya(e) ? Ka(e) : Ja(e);
1451
+ }
1452
+ async function Dt({
1453
+ value: e,
1454
+ schema: t,
1455
+ context: r
1456
+ }) {
1457
+ const a = await Ne({ value: e, schema: t, context: r });
1458
+ if (!a.success)
1459
+ throw we.wrap({ value: e, cause: a.error, context: r });
1460
+ return a.value;
1461
+ }
1462
+ async function Ne({
1463
+ value: e,
1464
+ schema: t,
1465
+ context: r
1466
+ }) {
1467
+ const a = ut(t);
1468
+ try {
1469
+ if (a.validate == null)
1470
+ return { success: !0, value: e, rawValue: e };
1471
+ const n = await a.validate(e);
1472
+ return n.success ? { success: !0, value: n.value, rawValue: e } : {
1473
+ success: !1,
1474
+ error: we.wrap({ value: e, cause: n.error, context: r }),
1475
+ rawValue: e
1476
+ };
1477
+ } catch (n) {
1478
+ return {
1479
+ success: !1,
1480
+ error: we.wrap({ value: e, cause: n, context: r }),
1481
+ rawValue: e
1482
+ };
1483
+ }
1484
+ }
1485
+ async function ve({
1486
+ text: e,
1487
+ schema: t
1488
+ }) {
1489
+ try {
1490
+ const r = ra(e);
1491
+ return t == null ? { success: !0, value: r, rawValue: r } : await Ne({ value: r, schema: t });
1492
+ } catch (r) {
1493
+ return {
1494
+ success: !1,
1495
+ error: Tt.isInstance(r) ? r : new Tt({ text: e, cause: r }),
1496
+ rawValue: void 0
1497
+ };
1498
+ }
1499
+ }
1500
+ function Ha({
1501
+ stream: e,
1502
+ schema: t
1503
+ }) {
1504
+ return e.pipeThrough(new TextDecoderStream()).pipeThrough(new Hr()).pipeThrough(
1505
+ new TransformStream({
1506
+ async transform({ data: r }, a) {
1507
+ r !== "[DONE]" && a.enqueue(await ve({ text: r, schema: t }));
1508
+ }
1509
+ })
1510
+ );
1511
+ }
1512
+ async function ue(e) {
1513
+ return typeof e == "function" && (e = e()), Promise.resolve(e);
1514
+ }
1515
+ new TextDecoder();
1516
+ function Ga(e) {
1517
+ return e && e.__esModule && Object.prototype.hasOwnProperty.call(e, "default") ? e.default : e;
1518
+ }
1519
+ var Qa = Object.defineProperty, Xa = (e, t) => {
1520
+ for (var r in t)
1521
+ Qa(e, r, { get: t[r], enumerable: !0 });
1522
+ }, ar = "AI_NoObjectGeneratedError", sr = `vercel.ai.error.${ar}`, es = Symbol.for(sr), nr, ce = class extends re {
1523
+ constructor({
1524
+ message: e = "No object generated.",
1525
+ cause: t,
1526
+ text: r,
1527
+ response: a,
1528
+ usage: n,
1529
+ finishReason: o
1530
+ }) {
1531
+ super({ name: ar, message: e, cause: t }), this[nr] = !0, this.text = r, this.response = a, this.usage = n, this.finishReason = o;
1532
+ }
1533
+ static isInstance(e) {
1534
+ return re.hasMarker(e, sr);
1535
+ }
1536
+ };
1537
+ nr = es;
1538
+ var ir = "AI_UIMessageStreamError", or = `vercel.ai.error.${ir}`, ts = Symbol.for(or), lr, ge = class extends re {
1539
+ constructor({
1540
+ chunkType: e,
1541
+ chunkId: t,
1542
+ message: r
1543
+ }) {
1544
+ super({ name: ir, message: r }), this[lr] = !0, this.chunkType = e, this.chunkId = t;
1545
+ }
1546
+ static isInstance(e) {
1547
+ return re.hasMarker(e, or);
1548
+ }
1549
+ };
1550
+ lr = ts;
1551
+ var he = s.lazy(
1552
+ () => s.union([
1553
+ s.null(),
1554
+ s.string(),
1555
+ s.number(),
1556
+ s.boolean(),
1557
+ s.record(s.string(), he.optional()),
1558
+ s.array(he)
1559
+ ])
1560
+ ), T = s.record(
1561
+ s.string(),
1562
+ s.record(s.string(), he.optional())
1563
+ ), je = s.union([
1564
+ s.string(),
1565
+ s.instanceof(Uint8Array),
1566
+ s.instanceof(ArrayBuffer),
1567
+ s.custom(Qr, { message: "Must be a Buffer" })
1568
+ ]), ct = s.record(s.string(), s.string()), ur = s.object({
1569
+ type: s.literal("text"),
1570
+ text: s.string(),
1571
+ providerOptions: T.optional()
1572
+ }), rs = s.object({
1573
+ type: s.literal("image"),
1574
+ image: s.union([
1575
+ je,
1576
+ s.instanceof(URL),
1577
+ ct
1578
+ ]),
1579
+ mediaType: s.string().optional(),
1580
+ providerOptions: T.optional()
1581
+ }), cr = s.discriminatedUnion("type", [
1582
+ s.object({ type: s.literal("data"), data: je }),
1583
+ s.object({ type: s.literal("url"), url: s.instanceof(URL) }),
1584
+ s.object({
1585
+ type: s.literal("reference"),
1586
+ reference: ct
1587
+ }),
1588
+ s.object({ type: s.literal("text"), text: s.string() })
1589
+ ]), as = s.discriminatedUnion("type", [
1590
+ s.object({ type: s.literal("data"), data: je }),
1591
+ s.object({ type: s.literal("url"), url: s.instanceof(URL) })
1592
+ ]), dr = s.object({
1593
+ type: s.literal("file"),
1594
+ data: s.union([
1595
+ cr,
1596
+ je,
1597
+ s.instanceof(URL),
1598
+ ct
1599
+ ]),
1600
+ filename: s.string().optional(),
1601
+ mediaType: s.string(),
1602
+ providerOptions: T.optional()
1603
+ }), ss = s.object({
1604
+ type: s.literal("reasoning"),
1605
+ text: s.string(),
1606
+ providerOptions: T.optional()
1607
+ }), ns = s.object({
1608
+ type: s.literal("custom"),
1609
+ kind: s.string().transform((e) => e),
1610
+ providerOptions: T.optional()
1611
+ }), is = s.object({
1612
+ type: s.literal("reasoning-file"),
1613
+ data: s.union([
1614
+ as,
1615
+ je,
1616
+ s.instanceof(URL)
1617
+ ]),
1618
+ mediaType: s.string(),
1619
+ providerOptions: T.optional()
1620
+ }), os = s.object({
1621
+ type: s.literal("tool-call"),
1622
+ toolCallId: s.string(),
1623
+ toolName: s.string(),
1624
+ input: s.unknown(),
1625
+ providerOptions: T.optional(),
1626
+ providerExecuted: s.boolean().optional()
1627
+ }), ls = s.discriminatedUnion(
1628
+ "type",
1629
+ [
1630
+ s.object({
1631
+ type: s.literal("text"),
1632
+ value: s.string(),
1633
+ providerOptions: T.optional()
1634
+ }),
1635
+ s.object({
1636
+ type: s.literal("json"),
1637
+ value: he,
1638
+ providerOptions: T.optional()
1639
+ }),
1640
+ s.object({
1641
+ type: s.literal("execution-denied"),
1642
+ reason: s.string().optional(),
1643
+ providerOptions: T.optional()
1644
+ }),
1645
+ s.object({
1646
+ type: s.literal("error-text"),
1647
+ value: s.string(),
1648
+ providerOptions: T.optional()
1649
+ }),
1650
+ s.object({
1651
+ type: s.literal("error-json"),
1652
+ value: he,
1653
+ providerOptions: T.optional()
1654
+ }),
1655
+ s.object({
1656
+ type: s.literal("content"),
1657
+ value: s.array(
1658
+ s.union([
1659
+ s.object({
1660
+ type: s.literal("text"),
1661
+ text: s.string(),
1662
+ providerOptions: T.optional()
1663
+ }),
1664
+ s.object({
1665
+ type: s.literal("file"),
1666
+ data: cr,
1667
+ mediaType: s.string(),
1668
+ filename: s.string().optional(),
1669
+ providerOptions: T.optional()
1670
+ }),
1671
+ s.object({
1672
+ // Deprecated.
1673
+ type: s.literal("file-data"),
1674
+ data: s.string(),
1675
+ mediaType: s.string(),
1676
+ filename: s.string().optional(),
1677
+ providerOptions: T.optional()
1678
+ }),
1679
+ s.object({
1680
+ // Deprecated.
1681
+ type: s.literal("file-url"),
1682
+ url: s.string(),
1683
+ mediaType: s.string().optional(),
1684
+ providerOptions: T.optional()
1685
+ }),
1686
+ s.object({
1687
+ // Deprecated.
1688
+ type: s.literal("file-id"),
1689
+ fileId: s.union([s.string(), s.record(s.string(), s.string())]),
1690
+ providerOptions: T.optional()
1691
+ }),
1692
+ s.object({
1693
+ // Deprecated.
1694
+ type: s.literal("file-reference"),
1695
+ providerReference: s.record(s.string(), s.string()),
1696
+ providerOptions: T.optional()
1697
+ }),
1698
+ s.object({
1699
+ // Deprecated.
1700
+ type: s.literal("image-data"),
1701
+ data: s.string(),
1702
+ mediaType: s.string(),
1703
+ providerOptions: T.optional()
1704
+ }),
1705
+ s.object({
1706
+ // Deprecated.
1707
+ type: s.literal("image-url"),
1708
+ url: s.string(),
1709
+ providerOptions: T.optional()
1710
+ }),
1711
+ s.object({
1712
+ // Deprecated.
1713
+ type: s.literal("image-file-id"),
1714
+ fileId: s.union([s.string(), s.record(s.string(), s.string())]),
1715
+ providerOptions: T.optional()
1716
+ }),
1717
+ s.object({
1718
+ // Deprecated.
1719
+ type: s.literal("image-file-reference"),
1720
+ providerReference: s.record(s.string(), s.string()),
1721
+ providerOptions: T.optional()
1722
+ }),
1723
+ s.object({
1724
+ type: s.literal("custom"),
1725
+ providerOptions: T.optional()
1726
+ })
1727
+ ])
1728
+ )
1729
+ })
1730
+ ]
1731
+ ), pr = s.object({
1732
+ type: s.literal("tool-result"),
1733
+ toolCallId: s.string(),
1734
+ toolName: s.string(),
1735
+ output: ls,
1736
+ providerOptions: T.optional()
1737
+ }), us = s.object({
1738
+ type: s.literal("tool-approval-request"),
1739
+ approvalId: s.string(),
1740
+ toolCallId: s.string()
1741
+ }), cs = s.object({
1742
+ type: s.literal("tool-approval-response"),
1743
+ approvalId: s.string(),
1744
+ approved: s.boolean(),
1745
+ reason: s.string().optional()
1746
+ }), ds = s.object(
1747
+ {
1748
+ role: s.literal("system"),
1749
+ content: s.string(),
1750
+ providerOptions: T.optional()
1751
+ }
1752
+ ), ps = s.object({
1753
+ role: s.literal("user"),
1754
+ content: s.union([
1755
+ s.string(),
1756
+ s.array(s.union([ur, rs, dr]))
1757
+ ]),
1758
+ providerOptions: T.optional()
1759
+ }), fs = s.object({
1760
+ role: s.literal("assistant"),
1761
+ content: s.union([
1762
+ s.string(),
1763
+ s.array(
1764
+ s.union([
1765
+ ur,
1766
+ ns,
1767
+ dr,
1768
+ ss,
1769
+ is,
1770
+ os,
1771
+ pr,
1772
+ us
1773
+ ])
1774
+ )
1775
+ ]),
1776
+ providerOptions: T.optional()
1777
+ }), ms = s.object({
1778
+ role: s.literal("tool"),
1779
+ content: s.array(s.union([pr, cs])),
1780
+ providerOptions: T.optional()
1781
+ });
1782
+ s.union([
1783
+ ds,
1784
+ ps,
1785
+ fs,
1786
+ ms
1787
+ ]);
1788
+ function fr(e, t) {
1789
+ if (e === void 0 && t === void 0)
1790
+ return;
1791
+ if (e === void 0)
1792
+ return t;
1793
+ if (t === void 0)
1794
+ return e;
1795
+ const r = { ...e };
1796
+ for (const a in t)
1797
+ if (!(a === "__proto__" || a === "constructor" || a === "prototype") && Object.prototype.hasOwnProperty.call(t, a)) {
1798
+ const n = t[a];
1799
+ if (n === void 0)
1800
+ continue;
1801
+ const o = a in e ? e[a] : void 0, u = n !== null && typeof n == "object" && !Array.isArray(n) && !(n instanceof Date) && !(n instanceof RegExp), i = o != null && typeof o == "object" && !Array.isArray(o) && !(o instanceof Date) && !(o instanceof RegExp);
1802
+ u && i ? r[a] = fr(
1803
+ o,
1804
+ n
1805
+ ) : r[a] = n;
1806
+ }
1807
+ return r;
1808
+ }
1809
+ var gs = {};
1810
+ Xa(gs, {
1811
+ array: () => bs,
1812
+ choice: () => Es,
1813
+ json: () => Ss,
1814
+ object: () => ys,
1815
+ text: () => hs
1816
+ });
1817
+ function vs(e) {
1818
+ const t = ["ROOT"];
1819
+ let r = -1, a = null, n = 0;
1820
+ function o(l) {
1821
+ return l >= "0" && l <= "9" || l >= "A" && l <= "F" || l >= "a" && l <= "f";
1822
+ }
1823
+ function u(l, p, v) {
1824
+ switch (l) {
1825
+ case '"': {
1826
+ r = p, t.pop(), t.push(v), t.push("INSIDE_STRING");
1827
+ break;
1828
+ }
1829
+ case "f":
1830
+ case "t":
1831
+ case "n": {
1832
+ r = p, a = p, t.pop(), t.push(v), t.push("INSIDE_LITERAL");
1833
+ break;
1834
+ }
1835
+ case "-": {
1836
+ t.pop(), t.push(v), t.push("INSIDE_NUMBER");
1837
+ break;
1838
+ }
1839
+ case "0":
1840
+ case "1":
1841
+ case "2":
1842
+ case "3":
1843
+ case "4":
1844
+ case "5":
1845
+ case "6":
1846
+ case "7":
1847
+ case "8":
1848
+ case "9": {
1849
+ r = p, t.pop(), t.push(v), t.push("INSIDE_NUMBER");
1850
+ break;
1851
+ }
1852
+ case "{": {
1853
+ r = p, t.pop(), t.push(v), t.push("INSIDE_OBJECT_START");
1854
+ break;
1855
+ }
1856
+ case "[": {
1857
+ r = p, t.pop(), t.push(v), t.push("INSIDE_ARRAY_START");
1858
+ break;
1859
+ }
1860
+ }
1861
+ }
1862
+ function i(l, p) {
1863
+ switch (l) {
1864
+ case ",": {
1865
+ t.pop(), t.push("INSIDE_OBJECT_AFTER_COMMA");
1866
+ break;
1867
+ }
1868
+ case "}": {
1869
+ r = p, t.pop();
1870
+ break;
1871
+ }
1872
+ }
1873
+ }
1874
+ function g(l, p) {
1875
+ switch (l) {
1876
+ case ",": {
1877
+ t.pop(), t.push("INSIDE_ARRAY_AFTER_COMMA");
1878
+ break;
1879
+ }
1880
+ case "]": {
1881
+ r = p, t.pop();
1882
+ break;
1883
+ }
1884
+ }
1885
+ }
1886
+ for (let l = 0; l < e.length; l++) {
1887
+ const p = e[l];
1888
+ switch (t[t.length - 1]) {
1889
+ case "ROOT":
1890
+ u(p, l, "FINISH");
1891
+ break;
1892
+ case "INSIDE_OBJECT_START": {
1893
+ switch (p) {
1894
+ case '"': {
1895
+ t.pop(), t.push("INSIDE_OBJECT_KEY");
1896
+ break;
1897
+ }
1898
+ case "}": {
1899
+ r = l, t.pop();
1900
+ break;
1901
+ }
1902
+ }
1903
+ break;
1904
+ }
1905
+ case "INSIDE_OBJECT_AFTER_COMMA": {
1906
+ switch (p) {
1907
+ case '"': {
1908
+ t.pop(), t.push("INSIDE_OBJECT_KEY");
1909
+ break;
1910
+ }
1911
+ }
1912
+ break;
1913
+ }
1914
+ case "INSIDE_OBJECT_KEY": {
1915
+ switch (p) {
1916
+ case '"': {
1917
+ t.pop(), t.push("INSIDE_OBJECT_AFTER_KEY");
1918
+ break;
1919
+ }
1920
+ }
1921
+ break;
1922
+ }
1923
+ case "INSIDE_OBJECT_AFTER_KEY": {
1924
+ switch (p) {
1925
+ case ":": {
1926
+ t.pop(), t.push("INSIDE_OBJECT_BEFORE_VALUE");
1927
+ break;
1928
+ }
1929
+ }
1930
+ break;
1931
+ }
1932
+ case "INSIDE_OBJECT_BEFORE_VALUE": {
1933
+ u(p, l, "INSIDE_OBJECT_AFTER_VALUE");
1934
+ break;
1935
+ }
1936
+ case "INSIDE_OBJECT_AFTER_VALUE": {
1937
+ i(p, l);
1938
+ break;
1939
+ }
1940
+ case "INSIDE_STRING": {
1941
+ switch (p) {
1942
+ case '"': {
1943
+ t.pop(), r = l;
1944
+ break;
1945
+ }
1946
+ case "\\": {
1947
+ t.push("INSIDE_STRING_ESCAPE");
1948
+ break;
1949
+ }
1950
+ default:
1951
+ r = l;
1952
+ }
1953
+ break;
1954
+ }
1955
+ case "INSIDE_ARRAY_START": {
1956
+ switch (p) {
1957
+ case "]": {
1958
+ r = l, t.pop();
1959
+ break;
1960
+ }
1961
+ default: {
1962
+ r = l, u(p, l, "INSIDE_ARRAY_AFTER_VALUE");
1963
+ break;
1964
+ }
1965
+ }
1966
+ break;
1967
+ }
1968
+ case "INSIDE_ARRAY_AFTER_VALUE": {
1969
+ switch (p) {
1970
+ case ",": {
1971
+ t.pop(), t.push("INSIDE_ARRAY_AFTER_COMMA");
1972
+ break;
1973
+ }
1974
+ case "]": {
1975
+ r = l, t.pop();
1976
+ break;
1977
+ }
1978
+ default: {
1979
+ r = l;
1980
+ break;
1981
+ }
1982
+ }
1983
+ break;
1984
+ }
1985
+ case "INSIDE_ARRAY_AFTER_COMMA": {
1986
+ u(p, l, "INSIDE_ARRAY_AFTER_VALUE");
1987
+ break;
1988
+ }
1989
+ case "INSIDE_STRING_ESCAPE": {
1990
+ t.pop(), p === "u" ? (n = 0, t.push("INSIDE_STRING_UNICODE_ESCAPE")) : r = l;
1991
+ break;
1992
+ }
1993
+ case "INSIDE_STRING_UNICODE_ESCAPE": {
1994
+ o(p) && (n++, n === 4 && (t.pop(), r = l));
1995
+ break;
1996
+ }
1997
+ case "INSIDE_NUMBER": {
1998
+ switch (p) {
1999
+ case "0":
2000
+ case "1":
2001
+ case "2":
2002
+ case "3":
2003
+ case "4":
2004
+ case "5":
2005
+ case "6":
2006
+ case "7":
2007
+ case "8":
2008
+ case "9": {
2009
+ r = l;
2010
+ break;
2011
+ }
2012
+ case "e":
2013
+ case "E":
2014
+ case "-":
2015
+ case ".":
2016
+ break;
2017
+ case ",": {
2018
+ t.pop(), t[t.length - 1] === "INSIDE_ARRAY_AFTER_VALUE" && g(p, l), t[t.length - 1] === "INSIDE_OBJECT_AFTER_VALUE" && i(p, l);
2019
+ break;
2020
+ }
2021
+ case "}": {
2022
+ t.pop(), t[t.length - 1] === "INSIDE_OBJECT_AFTER_VALUE" && i(p, l);
2023
+ break;
2024
+ }
2025
+ case "]": {
2026
+ t.pop(), t[t.length - 1] === "INSIDE_ARRAY_AFTER_VALUE" && g(p, l);
2027
+ break;
2028
+ }
2029
+ default: {
2030
+ t.pop();
2031
+ break;
2032
+ }
2033
+ }
2034
+ break;
2035
+ }
2036
+ case "INSIDE_LITERAL": {
2037
+ const h = e.substring(a, l + 1);
2038
+ !"false".startsWith(h) && !"true".startsWith(h) && !"null".startsWith(h) ? (t.pop(), t[t.length - 1] === "INSIDE_OBJECT_AFTER_VALUE" ? i(p, l) : t[t.length - 1] === "INSIDE_ARRAY_AFTER_VALUE" && g(p, l)) : r = l;
2039
+ break;
2040
+ }
2041
+ }
2042
+ }
2043
+ let c = e.slice(0, r + 1);
2044
+ for (let l = t.length - 1; l >= 0; l--)
2045
+ switch (t[l]) {
2046
+ case "INSIDE_STRING": {
2047
+ c += '"';
2048
+ break;
2049
+ }
2050
+ case "INSIDE_OBJECT_KEY":
2051
+ case "INSIDE_OBJECT_AFTER_KEY":
2052
+ case "INSIDE_OBJECT_AFTER_COMMA":
2053
+ case "INSIDE_OBJECT_START":
2054
+ case "INSIDE_OBJECT_BEFORE_VALUE":
2055
+ case "INSIDE_OBJECT_AFTER_VALUE": {
2056
+ c += "}";
2057
+ break;
2058
+ }
2059
+ case "INSIDE_ARRAY_START":
2060
+ case "INSIDE_ARRAY_AFTER_COMMA":
2061
+ case "INSIDE_ARRAY_AFTER_VALUE": {
2062
+ c += "]";
2063
+ break;
2064
+ }
2065
+ case "INSIDE_LITERAL": {
2066
+ const v = e.substring(a, e.length);
2067
+ "true".startsWith(v) ? c += "true".slice(v.length) : "false".startsWith(v) ? c += "false".slice(v.length) : "null".startsWith(v) && (c += "null".slice(v.length));
2068
+ }
2069
+ }
2070
+ return c;
2071
+ }
2072
+ async function De(e) {
2073
+ if (e === void 0)
2074
+ return { value: void 0, state: "undefined-input" };
2075
+ let t = await ve({ text: e });
2076
+ return t.success ? { value: t.value, state: "successful-parse" } : (t = await ve({ text: vs(e) }), t.success ? { value: t.value, state: "repaired-parse" } : { value: void 0, state: "failed-parse" });
2077
+ }
2078
+ var hs = () => ({
2079
+ name: "text",
2080
+ responseFormat: Promise.resolve({ type: "text" }),
2081
+ async parseCompleteOutput({ text: e }) {
2082
+ return e;
2083
+ },
2084
+ async parsePartialOutput({ text: e }) {
2085
+ return { partial: e };
2086
+ },
2087
+ createElementStreamTransform() {
18
2088
  }
19
- get(t) {
20
- const n = this.components.find(
21
- (o) => o.key.toUpperCase() === t.toUpperCase()
2089
+ }), ys = ({
2090
+ schema: e,
2091
+ name: t,
2092
+ description: r
2093
+ }) => {
2094
+ const a = ut(e);
2095
+ return {
2096
+ name: "object",
2097
+ responseFormat: ue(a.jsonSchema).then((n) => ({
2098
+ type: "json",
2099
+ schema: n,
2100
+ ...t != null && { name: t },
2101
+ ...r != null && { description: r }
2102
+ })),
2103
+ async parseCompleteOutput({ text: n }, o) {
2104
+ const u = await ve({ text: n });
2105
+ if (!u.success)
2106
+ throw new ce({
2107
+ message: "No object generated: could not parse the response.",
2108
+ cause: u.error,
2109
+ text: n,
2110
+ response: o.response,
2111
+ usage: o.usage,
2112
+ finishReason: o.finishReason
2113
+ });
2114
+ const i = await Ne({
2115
+ value: u.value,
2116
+ schema: a
2117
+ });
2118
+ if (!i.success)
2119
+ throw new ce({
2120
+ message: "No object generated: response did not match schema.",
2121
+ cause: i.error,
2122
+ text: n,
2123
+ response: o.response,
2124
+ usage: o.usage,
2125
+ finishReason: o.finishReason
2126
+ });
2127
+ return i.value;
2128
+ },
2129
+ async parsePartialOutput({ text: n }) {
2130
+ const o = await De(n);
2131
+ switch (o.state) {
2132
+ case "failed-parse":
2133
+ case "undefined-input":
2134
+ return;
2135
+ case "repaired-parse":
2136
+ case "successful-parse":
2137
+ return {
2138
+ // Note: currently no validation of partial results:
2139
+ partial: o.value
2140
+ };
2141
+ }
2142
+ },
2143
+ createElementStreamTransform() {
2144
+ }
2145
+ };
2146
+ }, bs = ({
2147
+ element: e,
2148
+ name: t,
2149
+ description: r
2150
+ }) => {
2151
+ const a = ut(e);
2152
+ return {
2153
+ name: "array",
2154
+ // JSON schema that describes an array of elements:
2155
+ responseFormat: ue(a.jsonSchema).then((n) => {
2156
+ const { $schema: o, ...u } = n;
2157
+ return {
2158
+ type: "json",
2159
+ schema: {
2160
+ $schema: "http://json-schema.org/draft-07/schema#",
2161
+ type: "object",
2162
+ properties: {
2163
+ elements: { type: "array", items: u }
2164
+ },
2165
+ required: ["elements"],
2166
+ additionalProperties: !1
2167
+ },
2168
+ ...t != null && { name: t },
2169
+ ...r != null && { description: r }
2170
+ };
2171
+ }),
2172
+ async parseCompleteOutput({ text: n }, o) {
2173
+ const u = await ve({ text: n });
2174
+ if (!u.success)
2175
+ throw new ce({
2176
+ message: "No object generated: could not parse the response.",
2177
+ cause: u.error,
2178
+ text: n,
2179
+ response: o.response,
2180
+ usage: o.usage,
2181
+ finishReason: o.finishReason
2182
+ });
2183
+ const i = u.value;
2184
+ if (i == null || typeof i != "object" || !("elements" in i) || !Array.isArray(i.elements))
2185
+ throw new ce({
2186
+ message: "No object generated: response did not match schema.",
2187
+ cause: new we({
2188
+ value: i,
2189
+ cause: "response must be an object with an elements array"
2190
+ }),
2191
+ text: n,
2192
+ response: o.response,
2193
+ usage: o.usage,
2194
+ finishReason: o.finishReason
2195
+ });
2196
+ const g = [];
2197
+ for (const c of i.elements) {
2198
+ const l = await Ne({
2199
+ value: c,
2200
+ schema: a
2201
+ });
2202
+ if (!l.success)
2203
+ throw new ce({
2204
+ message: "No object generated: response did not match schema.",
2205
+ cause: l.error,
2206
+ text: n,
2207
+ response: o.response,
2208
+ usage: o.usage,
2209
+ finishReason: o.finishReason
2210
+ });
2211
+ g.push(l.value);
2212
+ }
2213
+ return g;
2214
+ },
2215
+ async parsePartialOutput({ text: n }) {
2216
+ const o = await De(n);
2217
+ switch (o.state) {
2218
+ case "failed-parse":
2219
+ case "undefined-input":
2220
+ return;
2221
+ case "repaired-parse":
2222
+ case "successful-parse": {
2223
+ const u = o.value;
2224
+ if (u == null || typeof u != "object" || !("elements" in u) || !Array.isArray(u.elements))
2225
+ return;
2226
+ const i = o.state === "repaired-parse" && u.elements.length > 0 ? u.elements.slice(0, -1) : u.elements, g = [];
2227
+ for (const c of i) {
2228
+ const l = await Ne({
2229
+ value: c,
2230
+ schema: a
2231
+ });
2232
+ l.success && g.push(l.value);
2233
+ }
2234
+ return { partial: g };
2235
+ }
2236
+ }
2237
+ },
2238
+ createElementStreamTransform() {
2239
+ let n = 0;
2240
+ return new TransformStream({
2241
+ transform({ partialOutput: o }, u) {
2242
+ if (o != null)
2243
+ for (; n < o.length; n++)
2244
+ u.enqueue(o[n]);
2245
+ }
2246
+ });
2247
+ }
2248
+ };
2249
+ }, Es = ({
2250
+ options: e,
2251
+ name: t,
2252
+ description: r
2253
+ }) => ({
2254
+ name: "choice",
2255
+ // JSON schema that describes an enumeration:
2256
+ responseFormat: Promise.resolve({
2257
+ type: "json",
2258
+ schema: {
2259
+ $schema: "http://json-schema.org/draft-07/schema#",
2260
+ type: "object",
2261
+ properties: {
2262
+ result: { type: "string", enum: e }
2263
+ },
2264
+ required: ["result"],
2265
+ additionalProperties: !1
2266
+ },
2267
+ ...t != null && { name: t },
2268
+ ...r != null && { description: r }
2269
+ }),
2270
+ async parseCompleteOutput({ text: a }, n) {
2271
+ const o = await ve({ text: a });
2272
+ if (!o.success)
2273
+ throw new ce({
2274
+ message: "No object generated: could not parse the response.",
2275
+ cause: o.error,
2276
+ text: a,
2277
+ response: n.response,
2278
+ usage: n.usage,
2279
+ finishReason: n.finishReason
2280
+ });
2281
+ const u = o.value;
2282
+ if (u == null || typeof u != "object" || !("result" in u) || typeof u.result != "string" || !e.includes(u.result))
2283
+ throw new ce({
2284
+ message: "No object generated: response did not match schema.",
2285
+ cause: new we({
2286
+ value: u,
2287
+ cause: "response must be an object that contains a choice value."
2288
+ }),
2289
+ text: a,
2290
+ response: n.response,
2291
+ usage: n.usage,
2292
+ finishReason: n.finishReason
2293
+ });
2294
+ return u.result;
2295
+ },
2296
+ async parsePartialOutput({ text: a }) {
2297
+ const n = await De(a);
2298
+ switch (n.state) {
2299
+ case "failed-parse":
2300
+ case "undefined-input":
2301
+ return;
2302
+ case "repaired-parse":
2303
+ case "successful-parse": {
2304
+ const o = n.value;
2305
+ if (o == null || typeof o != "object" || !("result" in o) || typeof o.result != "string")
2306
+ return;
2307
+ const u = e.filter(
2308
+ (i) => i.startsWith(o.result)
2309
+ );
2310
+ return n.state === "successful-parse" ? u.includes(o.result) ? { partial: o.result } : void 0 : u.length === 1 ? { partial: u[0] } : void 0;
2311
+ }
2312
+ }
2313
+ },
2314
+ createElementStreamTransform() {
2315
+ }
2316
+ }), Ss = ({
2317
+ name: e,
2318
+ description: t
2319
+ } = {}) => ({
2320
+ name: "json",
2321
+ responseFormat: Promise.resolve({
2322
+ type: "json",
2323
+ ...e != null && { name: e },
2324
+ ...t != null && { description: t }
2325
+ }),
2326
+ async parseCompleteOutput({ text: r }, a) {
2327
+ const n = await ve({ text: r });
2328
+ if (!n.success)
2329
+ throw new ce({
2330
+ message: "No object generated: could not parse the response.",
2331
+ cause: n.error,
2332
+ text: r,
2333
+ response: a.response,
2334
+ usage: a.usage,
2335
+ finishReason: a.finishReason
2336
+ });
2337
+ return n.value;
2338
+ },
2339
+ async parsePartialOutput({ text: r }) {
2340
+ const a = await De(r);
2341
+ switch (a.state) {
2342
+ case "failed-parse":
2343
+ case "undefined-input":
2344
+ return;
2345
+ case "repaired-parse":
2346
+ case "successful-parse":
2347
+ return a.value === void 0 ? void 0 : { partial: a.value };
2348
+ }
2349
+ },
2350
+ createElementStreamTransform() {
2351
+ }
2352
+ });
2353
+ new TextEncoder();
2354
+ new TextEncoder();
2355
+ J({
2356
+ prefix: "aitxt",
2357
+ size: 24
2358
+ });
2359
+ J({
2360
+ prefix: "call",
2361
+ size: 24
2362
+ });
2363
+ (class extends TransformStream {
2364
+ constructor() {
2365
+ super({
2366
+ transform(e, t) {
2367
+ t.enqueue(`data: ${JSON.stringify(e)}
2368
+
2369
+ `);
2370
+ },
2371
+ flush(e) {
2372
+ e.enqueue(`data: [DONE]
2373
+
2374
+ `);
2375
+ }
2376
+ });
2377
+ }
2378
+ });
2379
+ var Ae = s.record(
2380
+ s.string(),
2381
+ he.optional()
2382
+ ), Is = za(
2383
+ () => rr(
2384
+ s.union([
2385
+ s.strictObject({
2386
+ type: s.literal("text-start"),
2387
+ id: s.string(),
2388
+ providerMetadata: T.optional()
2389
+ }),
2390
+ s.strictObject({
2391
+ type: s.literal("text-delta"),
2392
+ id: s.string(),
2393
+ delta: s.string(),
2394
+ providerMetadata: T.optional()
2395
+ }),
2396
+ s.strictObject({
2397
+ type: s.literal("text-end"),
2398
+ id: s.string(),
2399
+ providerMetadata: T.optional()
2400
+ }),
2401
+ s.strictObject({
2402
+ type: s.literal("error"),
2403
+ errorText: s.string()
2404
+ }),
2405
+ s.strictObject({
2406
+ type: s.literal("tool-input-start"),
2407
+ toolCallId: s.string(),
2408
+ toolName: s.string(),
2409
+ providerExecuted: s.boolean().optional(),
2410
+ providerMetadata: T.optional(),
2411
+ toolMetadata: Ae.optional(),
2412
+ dynamic: s.boolean().optional(),
2413
+ title: s.string().optional()
2414
+ }),
2415
+ s.strictObject({
2416
+ type: s.literal("tool-input-delta"),
2417
+ toolCallId: s.string(),
2418
+ inputTextDelta: s.string()
2419
+ }),
2420
+ s.strictObject({
2421
+ type: s.literal("tool-input-available"),
2422
+ toolCallId: s.string(),
2423
+ toolName: s.string(),
2424
+ input: s.unknown(),
2425
+ providerExecuted: s.boolean().optional(),
2426
+ providerMetadata: T.optional(),
2427
+ toolMetadata: Ae.optional(),
2428
+ dynamic: s.boolean().optional(),
2429
+ title: s.string().optional()
2430
+ }),
2431
+ s.strictObject({
2432
+ type: s.literal("tool-input-error"),
2433
+ toolCallId: s.string(),
2434
+ toolName: s.string(),
2435
+ input: s.unknown(),
2436
+ providerExecuted: s.boolean().optional(),
2437
+ providerMetadata: T.optional(),
2438
+ toolMetadata: Ae.optional(),
2439
+ dynamic: s.boolean().optional(),
2440
+ errorText: s.string(),
2441
+ title: s.string().optional()
2442
+ }),
2443
+ s.strictObject({
2444
+ type: s.literal("tool-approval-request"),
2445
+ approvalId: s.string(),
2446
+ toolCallId: s.string(),
2447
+ isAutomatic: s.boolean().optional(),
2448
+ signature: s.string().optional()
2449
+ }),
2450
+ s.strictObject({
2451
+ type: s.literal("tool-approval-response"),
2452
+ approvalId: s.string(),
2453
+ approved: s.boolean(),
2454
+ reason: s.string().optional(),
2455
+ providerExecuted: s.boolean().optional(),
2456
+ providerMetadata: T.optional()
2457
+ }),
2458
+ s.strictObject({
2459
+ type: s.literal("tool-output-available"),
2460
+ toolCallId: s.string(),
2461
+ output: s.unknown(),
2462
+ providerExecuted: s.boolean().optional(),
2463
+ providerMetadata: T.optional(),
2464
+ toolMetadata: Ae.optional(),
2465
+ dynamic: s.boolean().optional(),
2466
+ preliminary: s.boolean().optional()
2467
+ }),
2468
+ s.strictObject({
2469
+ type: s.literal("tool-output-error"),
2470
+ toolCallId: s.string(),
2471
+ errorText: s.string(),
2472
+ providerExecuted: s.boolean().optional(),
2473
+ providerMetadata: T.optional(),
2474
+ toolMetadata: Ae.optional(),
2475
+ dynamic: s.boolean().optional()
2476
+ }),
2477
+ s.strictObject({
2478
+ type: s.literal("tool-output-denied"),
2479
+ toolCallId: s.string()
2480
+ }),
2481
+ s.strictObject({
2482
+ type: s.literal("reasoning-start"),
2483
+ id: s.string(),
2484
+ providerMetadata: T.optional()
2485
+ }),
2486
+ s.strictObject({
2487
+ type: s.literal("reasoning-delta"),
2488
+ id: s.string(),
2489
+ delta: s.string(),
2490
+ providerMetadata: T.optional()
2491
+ }),
2492
+ s.strictObject({
2493
+ type: s.literal("reasoning-end"),
2494
+ id: s.string(),
2495
+ providerMetadata: T.optional()
2496
+ }),
2497
+ s.strictObject({
2498
+ type: s.literal("custom"),
2499
+ kind: s.string().transform((e) => e),
2500
+ providerMetadata: T.optional()
2501
+ }),
2502
+ s.strictObject({
2503
+ type: s.literal("source-url"),
2504
+ sourceId: s.string(),
2505
+ url: s.string(),
2506
+ title: s.string().optional(),
2507
+ providerMetadata: T.optional()
2508
+ }),
2509
+ s.strictObject({
2510
+ type: s.literal("source-document"),
2511
+ sourceId: s.string(),
2512
+ mediaType: s.string(),
2513
+ title: s.string(),
2514
+ filename: s.string().optional(),
2515
+ providerMetadata: T.optional()
2516
+ }),
2517
+ s.strictObject({
2518
+ type: s.literal("file"),
2519
+ url: s.string(),
2520
+ mediaType: s.string(),
2521
+ providerMetadata: T.optional()
2522
+ }),
2523
+ s.strictObject({
2524
+ type: s.literal("reasoning-file"),
2525
+ url: s.string(),
2526
+ mediaType: s.string(),
2527
+ providerMetadata: T.optional()
2528
+ }),
2529
+ s.strictObject({
2530
+ type: s.custom(
2531
+ (e) => typeof e == "string" && e.startsWith("data-"),
2532
+ { message: 'Type must start with "data-"' }
2533
+ ),
2534
+ id: s.string().optional(),
2535
+ data: s.unknown(),
2536
+ transient: s.boolean().optional()
2537
+ }),
2538
+ s.strictObject({
2539
+ type: s.literal("start-step")
2540
+ }),
2541
+ s.strictObject({
2542
+ type: s.literal("finish-step")
2543
+ }),
2544
+ s.strictObject({
2545
+ type: s.literal("start"),
2546
+ messageId: s.string().optional(),
2547
+ messageMetadata: s.unknown().optional()
2548
+ }),
2549
+ s.strictObject({
2550
+ type: s.literal("finish"),
2551
+ finishReason: s.enum([
2552
+ "stop",
2553
+ "length",
2554
+ "content-filter",
2555
+ "tool-calls",
2556
+ "error",
2557
+ "other"
2558
+ ]).optional(),
2559
+ messageMetadata: s.unknown().optional()
2560
+ }),
2561
+ s.strictObject({
2562
+ type: s.literal("abort"),
2563
+ reason: s.string().optional()
2564
+ }),
2565
+ s.strictObject({
2566
+ type: s.literal("message-metadata"),
2567
+ messageMetadata: s.unknown()
2568
+ })
2569
+ ])
2570
+ )
2571
+ );
2572
+ function _s(e) {
2573
+ return e.type.startsWith("data-");
2574
+ }
2575
+ function Pe() {
2576
+ return /* @__PURE__ */ Object.create(null);
2577
+ }
2578
+ function at(e) {
2579
+ return e.type.startsWith("tool-");
2580
+ }
2581
+ function mr(e) {
2582
+ return e.type === "dynamic-tool";
2583
+ }
2584
+ function _e(e) {
2585
+ return at(e) || mr(e);
2586
+ }
2587
+ function st(e) {
2588
+ return e.type.split("-").slice(1).join("-");
2589
+ }
2590
+ function ws(e) {
2591
+ return mr(e) ? e.toolName : st(e);
2592
+ }
2593
+ function Ms({
2594
+ lastMessage: e,
2595
+ messageId: t
2596
+ }) {
2597
+ return {
2598
+ message: (e == null ? void 0 : e.role) === "assistant" ? e : {
2599
+ id: t,
2600
+ metadata: void 0,
2601
+ role: "assistant",
2602
+ parts: []
2603
+ },
2604
+ activeTextParts: Pe(),
2605
+ activeReasoningParts: Pe(),
2606
+ partialToolCalls: Pe()
2607
+ };
2608
+ }
2609
+ function Ts({
2610
+ stream: e,
2611
+ messageMetadataSchema: t,
2612
+ dataPartSchemas: r,
2613
+ runUpdateMessageJob: a,
2614
+ onError: n,
2615
+ onToolCall: o,
2616
+ onData: u
2617
+ }) {
2618
+ return e.pipeThrough(
2619
+ new TransformStream({
2620
+ async transform(i, g) {
2621
+ await a(async ({ state: c, write: l }) => {
2622
+ var p, v, h, A;
2623
+ function M(d) {
2624
+ const m = c.message.parts.filter(_e).find(
2625
+ (b) => b.toolCallId === d
2626
+ );
2627
+ if (m == null)
2628
+ throw new ge({
2629
+ chunkType: "tool-invocation",
2630
+ chunkId: d,
2631
+ message: `No tool invocation found for tool call ID "${d}".`
2632
+ });
2633
+ return m;
2634
+ }
2635
+ function S(d) {
2636
+ const m = c.message.parts.filter(_e).find(
2637
+ (b) => {
2638
+ var y;
2639
+ return ((y = b.approval) == null ? void 0 : y.id) === d;
2640
+ }
2641
+ );
2642
+ if (m == null)
2643
+ throw new ge({
2644
+ chunkType: "tool-approval-response",
2645
+ chunkId: d,
2646
+ message: `No tool invocation found for approval ID "${d}".`
2647
+ });
2648
+ return m;
2649
+ }
2650
+ function I(d) {
2651
+ var f;
2652
+ const m = c.message.parts.find(
2653
+ (w) => at(w) && w.toolCallId === d.toolCallId
2654
+ ), b = d, y = m;
2655
+ if (m != null) {
2656
+ m.state = d.state, y.input = b.input, y.output = b.output, y.errorText = b.errorText, y.rawInput = b.rawInput, y.preliminary = b.preliminary, d.title !== void 0 && (y.title = d.title), d.toolMetadata !== void 0 && (y.toolMetadata = d.toolMetadata), y.providerExecuted = (f = b.providerExecuted) != null ? f : m.providerExecuted;
2657
+ const w = b.providerMetadata;
2658
+ if (w != null)
2659
+ if (d.state === "output-available" || d.state === "output-error") {
2660
+ const D = m;
2661
+ D.resultProviderMetadata = w;
2662
+ } else
2663
+ m.callProviderMetadata = w;
2664
+ } else
2665
+ c.message.parts.push({
2666
+ type: `tool-${d.toolName}`,
2667
+ toolCallId: d.toolCallId,
2668
+ state: d.state,
2669
+ title: d.title,
2670
+ ...d.toolMetadata !== void 0 ? { toolMetadata: d.toolMetadata } : {},
2671
+ input: b.input,
2672
+ output: b.output,
2673
+ rawInput: b.rawInput,
2674
+ errorText: b.errorText,
2675
+ providerExecuted: b.providerExecuted,
2676
+ preliminary: b.preliminary,
2677
+ ...b.providerMetadata != null && (d.state === "output-available" || d.state === "output-error") ? { resultProviderMetadata: b.providerMetadata } : {},
2678
+ ...b.providerMetadata != null && !(d.state === "output-available" || d.state === "output-error") ? { callProviderMetadata: b.providerMetadata } : {}
2679
+ });
2680
+ }
2681
+ function _(d) {
2682
+ var f, m;
2683
+ const b = c.message.parts.find(
2684
+ (D) => D.type === "dynamic-tool" && D.toolCallId === d.toolCallId
2685
+ ), y = d, w = b;
2686
+ if (b != null) {
2687
+ b.state = d.state, w.toolName = d.toolName, w.input = y.input, w.output = y.output, w.errorText = y.errorText, w.rawInput = (f = y.rawInput) != null ? f : w.rawInput, w.preliminary = y.preliminary, d.title !== void 0 && (w.title = d.title), d.toolMetadata !== void 0 && (w.toolMetadata = d.toolMetadata), w.providerExecuted = (m = y.providerExecuted) != null ? m : b.providerExecuted;
2688
+ const D = y.providerMetadata;
2689
+ if (D != null)
2690
+ if (d.state === "output-available" || d.state === "output-error") {
2691
+ const se = b;
2692
+ se.resultProviderMetadata = D;
2693
+ } else
2694
+ b.callProviderMetadata = D;
2695
+ } else
2696
+ c.message.parts.push({
2697
+ type: "dynamic-tool",
2698
+ toolName: d.toolName,
2699
+ toolCallId: d.toolCallId,
2700
+ state: d.state,
2701
+ input: y.input,
2702
+ output: y.output,
2703
+ errorText: y.errorText,
2704
+ preliminary: y.preliminary,
2705
+ providerExecuted: y.providerExecuted,
2706
+ title: d.title,
2707
+ ...d.toolMetadata !== void 0 ? { toolMetadata: d.toolMetadata } : {},
2708
+ ...y.providerMetadata != null && (d.state === "output-available" || d.state === "output-error") ? { resultProviderMetadata: y.providerMetadata } : {},
2709
+ ...y.providerMetadata != null && !(d.state === "output-available" || d.state === "output-error") ? { callProviderMetadata: y.providerMetadata } : {}
2710
+ });
2711
+ }
2712
+ async function R(d) {
2713
+ if (d != null) {
2714
+ const f = c.message.metadata != null ? fr(c.message.metadata, d) : d;
2715
+ t != null && await Dt({
2716
+ value: f,
2717
+ schema: t,
2718
+ context: {
2719
+ field: "message.metadata",
2720
+ entityId: c.message.id
2721
+ }
2722
+ }), c.message.metadata = f;
2723
+ }
2724
+ }
2725
+ switch (i.type) {
2726
+ case "text-start": {
2727
+ const d = {
2728
+ type: "text",
2729
+ text: "",
2730
+ providerMetadata: i.providerMetadata,
2731
+ state: "streaming"
2732
+ };
2733
+ c.activeTextParts[i.id] = d, c.message.parts.push(d), l();
2734
+ break;
2735
+ }
2736
+ case "text-delta": {
2737
+ const d = c.activeTextParts[i.id];
2738
+ if (d == null)
2739
+ throw new ge({
2740
+ chunkType: "text-delta",
2741
+ chunkId: i.id,
2742
+ message: `Received text-delta for missing text part with ID "${i.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`
2743
+ });
2744
+ d.text += i.delta, d.providerMetadata = (p = i.providerMetadata) != null ? p : d.providerMetadata, l();
2745
+ break;
2746
+ }
2747
+ case "text-end": {
2748
+ const d = c.activeTextParts[i.id];
2749
+ if (d == null)
2750
+ throw new ge({
2751
+ chunkType: "text-end",
2752
+ chunkId: i.id,
2753
+ message: `Received text-end for missing text part with ID "${i.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`
2754
+ });
2755
+ d.state = "done", d.providerMetadata = (v = i.providerMetadata) != null ? v : d.providerMetadata, delete c.activeTextParts[i.id], l();
2756
+ break;
2757
+ }
2758
+ case "custom": {
2759
+ const d = {
2760
+ type: "custom",
2761
+ kind: i.kind,
2762
+ providerMetadata: i.providerMetadata
2763
+ };
2764
+ c.message.parts.push(d), l();
2765
+ break;
2766
+ }
2767
+ case "reasoning-start": {
2768
+ const d = {
2769
+ type: "reasoning",
2770
+ text: "",
2771
+ providerMetadata: i.providerMetadata,
2772
+ state: "streaming"
2773
+ };
2774
+ c.activeReasoningParts[i.id] = d, c.message.parts.push(d), l();
2775
+ break;
2776
+ }
2777
+ case "reasoning-delta": {
2778
+ const d = c.activeReasoningParts[i.id];
2779
+ if (d == null)
2780
+ throw new ge({
2781
+ chunkType: "reasoning-delta",
2782
+ chunkId: i.id,
2783
+ message: `Received reasoning-delta for missing reasoning part with ID "${i.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`
2784
+ });
2785
+ d.text += i.delta, d.providerMetadata = (h = i.providerMetadata) != null ? h : d.providerMetadata, l();
2786
+ break;
2787
+ }
2788
+ case "reasoning-end": {
2789
+ const d = c.activeReasoningParts[i.id];
2790
+ if (d == null)
2791
+ throw new ge({
2792
+ chunkType: "reasoning-end",
2793
+ chunkId: i.id,
2794
+ message: `Received reasoning-end for missing reasoning part with ID "${i.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`
2795
+ });
2796
+ d.providerMetadata = (A = i.providerMetadata) != null ? A : d.providerMetadata, d.state = "done", delete c.activeReasoningParts[i.id], l();
2797
+ break;
2798
+ }
2799
+ case "file":
2800
+ case "reasoning-file": {
2801
+ c.message.parts.push({
2802
+ type: i.type,
2803
+ mediaType: i.mediaType,
2804
+ url: i.url,
2805
+ ...i.providerMetadata != null ? { providerMetadata: i.providerMetadata } : {}
2806
+ }), l();
2807
+ break;
2808
+ }
2809
+ case "source-url": {
2810
+ c.message.parts.push({
2811
+ type: "source-url",
2812
+ sourceId: i.sourceId,
2813
+ url: i.url,
2814
+ title: i.title,
2815
+ providerMetadata: i.providerMetadata
2816
+ }), l();
2817
+ break;
2818
+ }
2819
+ case "source-document": {
2820
+ c.message.parts.push({
2821
+ type: "source-document",
2822
+ sourceId: i.sourceId,
2823
+ mediaType: i.mediaType,
2824
+ title: i.title,
2825
+ filename: i.filename,
2826
+ providerMetadata: i.providerMetadata
2827
+ }), l();
2828
+ break;
2829
+ }
2830
+ case "tool-input-start": {
2831
+ const d = c.message.parts.filter(at);
2832
+ c.partialToolCalls[i.toolCallId] = {
2833
+ text: "",
2834
+ toolName: i.toolName,
2835
+ index: d.length,
2836
+ dynamic: i.dynamic,
2837
+ title: i.title,
2838
+ toolMetadata: i.toolMetadata
2839
+ }, i.dynamic ? _({
2840
+ toolCallId: i.toolCallId,
2841
+ toolName: i.toolName,
2842
+ state: "input-streaming",
2843
+ input: void 0,
2844
+ providerExecuted: i.providerExecuted,
2845
+ title: i.title,
2846
+ toolMetadata: i.toolMetadata,
2847
+ providerMetadata: i.providerMetadata
2848
+ }) : I({
2849
+ toolCallId: i.toolCallId,
2850
+ toolName: i.toolName,
2851
+ state: "input-streaming",
2852
+ input: void 0,
2853
+ providerExecuted: i.providerExecuted,
2854
+ title: i.title,
2855
+ toolMetadata: i.toolMetadata,
2856
+ providerMetadata: i.providerMetadata
2857
+ }), l();
2858
+ break;
2859
+ }
2860
+ case "tool-input-delta": {
2861
+ const d = c.partialToolCalls[i.toolCallId];
2862
+ if (d == null)
2863
+ throw new ge({
2864
+ chunkType: "tool-input-delta",
2865
+ chunkId: i.toolCallId,
2866
+ message: `Received tool-input-delta for missing tool call with ID "${i.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`
2867
+ });
2868
+ d.text += i.inputTextDelta;
2869
+ const { value: f } = await De(
2870
+ d.text
2871
+ );
2872
+ d.dynamic ? _({
2873
+ toolCallId: i.toolCallId,
2874
+ toolName: d.toolName,
2875
+ state: "input-streaming",
2876
+ input: f,
2877
+ title: d.title,
2878
+ toolMetadata: d.toolMetadata
2879
+ }) : I({
2880
+ toolCallId: i.toolCallId,
2881
+ toolName: d.toolName,
2882
+ state: "input-streaming",
2883
+ input: f,
2884
+ title: d.title,
2885
+ toolMetadata: d.toolMetadata
2886
+ }), l();
2887
+ break;
2888
+ }
2889
+ case "tool-input-available": {
2890
+ i.dynamic ? _({
2891
+ toolCallId: i.toolCallId,
2892
+ toolName: i.toolName,
2893
+ state: "input-available",
2894
+ input: i.input,
2895
+ providerExecuted: i.providerExecuted,
2896
+ providerMetadata: i.providerMetadata,
2897
+ title: i.title,
2898
+ toolMetadata: i.toolMetadata
2899
+ }) : I({
2900
+ toolCallId: i.toolCallId,
2901
+ toolName: i.toolName,
2902
+ state: "input-available",
2903
+ input: i.input,
2904
+ providerExecuted: i.providerExecuted,
2905
+ providerMetadata: i.providerMetadata,
2906
+ title: i.title,
2907
+ toolMetadata: i.toolMetadata
2908
+ }), l(), o && !i.providerExecuted && await o({
2909
+ toolCall: i
2910
+ });
2911
+ break;
2912
+ }
2913
+ case "tool-input-error": {
2914
+ const d = c.message.parts.filter(_e).find((m) => m.toolCallId === i.toolCallId);
2915
+ (d != null ? d.type === "dynamic-tool" : !!i.dynamic) ? _({
2916
+ toolCallId: i.toolCallId,
2917
+ toolName: i.toolName,
2918
+ state: "output-error",
2919
+ input: i.input,
2920
+ errorText: i.errorText,
2921
+ providerExecuted: i.providerExecuted,
2922
+ providerMetadata: i.providerMetadata,
2923
+ toolMetadata: i.toolMetadata
2924
+ }) : I({
2925
+ toolCallId: i.toolCallId,
2926
+ toolName: i.toolName,
2927
+ state: "output-error",
2928
+ input: void 0,
2929
+ rawInput: i.input,
2930
+ errorText: i.errorText,
2931
+ providerExecuted: i.providerExecuted,
2932
+ providerMetadata: i.providerMetadata,
2933
+ toolMetadata: i.toolMetadata
2934
+ }), l();
2935
+ break;
2936
+ }
2937
+ case "tool-approval-request": {
2938
+ const d = M(i.toolCallId);
2939
+ d.state = "approval-requested", d.approval = {
2940
+ id: i.approvalId,
2941
+ ...i.isAutomatic === !0 ? { isAutomatic: !0 } : {},
2942
+ ...i.signature != null ? { signature: i.signature } : {}
2943
+ }, l();
2944
+ break;
2945
+ }
2946
+ case "tool-approval-response": {
2947
+ const d = S(
2948
+ i.approvalId
2949
+ ), f = d.approval == null ? { id: i.approvalId } : d.approval;
2950
+ d.state = "approval-responded", d.approval = {
2951
+ id: i.approvalId,
2952
+ approved: i.approved,
2953
+ ...i.reason != null ? { reason: i.reason } : {},
2954
+ ...f.isAutomatic === !0 ? { isAutomatic: !0 } : {},
2955
+ ...f.signature != null ? { signature: f.signature } : {}
2956
+ }, i.providerExecuted != null && (d.providerExecuted = i.providerExecuted), i.providerMetadata != null && (d.callProviderMetadata = i.providerMetadata), l();
2957
+ break;
2958
+ }
2959
+ case "tool-output-denied": {
2960
+ const d = M(i.toolCallId);
2961
+ d.state = "output-denied", l();
2962
+ break;
2963
+ }
2964
+ case "tool-output-available": {
2965
+ const d = M(i.toolCallId);
2966
+ d.type === "dynamic-tool" ? _({
2967
+ toolCallId: i.toolCallId,
2968
+ toolName: d.toolName,
2969
+ state: "output-available",
2970
+ input: d.input,
2971
+ output: i.output,
2972
+ preliminary: i.preliminary,
2973
+ providerExecuted: i.providerExecuted,
2974
+ providerMetadata: i.providerMetadata,
2975
+ title: d.title,
2976
+ toolMetadata: d.toolMetadata
2977
+ }) : I({
2978
+ toolCallId: i.toolCallId,
2979
+ toolName: st(d),
2980
+ state: "output-available",
2981
+ input: d.input,
2982
+ output: i.output,
2983
+ providerExecuted: i.providerExecuted,
2984
+ preliminary: i.preliminary,
2985
+ providerMetadata: i.providerMetadata,
2986
+ title: d.title,
2987
+ toolMetadata: d.toolMetadata
2988
+ }), l();
2989
+ break;
2990
+ }
2991
+ case "tool-output-error": {
2992
+ const d = M(i.toolCallId);
2993
+ d.type === "dynamic-tool" ? _({
2994
+ toolCallId: i.toolCallId,
2995
+ toolName: d.toolName,
2996
+ state: "output-error",
2997
+ input: d.input,
2998
+ errorText: i.errorText,
2999
+ providerExecuted: i.providerExecuted,
3000
+ providerMetadata: i.providerMetadata,
3001
+ title: d.title,
3002
+ toolMetadata: d.toolMetadata
3003
+ }) : I({
3004
+ toolCallId: i.toolCallId,
3005
+ toolName: st(d),
3006
+ state: "output-error",
3007
+ input: d.input,
3008
+ rawInput: d.rawInput,
3009
+ errorText: i.errorText,
3010
+ providerExecuted: i.providerExecuted,
3011
+ providerMetadata: i.providerMetadata,
3012
+ title: d.title,
3013
+ toolMetadata: d.toolMetadata
3014
+ }), l();
3015
+ break;
3016
+ }
3017
+ case "start-step": {
3018
+ c.message.parts.push({ type: "step-start" });
3019
+ break;
3020
+ }
3021
+ case "finish-step": {
3022
+ c.activeTextParts = Pe(), c.activeReasoningParts = Pe();
3023
+ break;
3024
+ }
3025
+ case "start": {
3026
+ i.messageId != null && (c.message.id = i.messageId), await R(i.messageMetadata), (i.messageId != null || i.messageMetadata != null) && l();
3027
+ break;
3028
+ }
3029
+ case "finish": {
3030
+ i.finishReason != null && (c.finishReason = i.finishReason), await R(i.messageMetadata), i.messageMetadata != null && l();
3031
+ break;
3032
+ }
3033
+ case "message-metadata": {
3034
+ await R(i.messageMetadata), i.messageMetadata != null && l();
3035
+ break;
3036
+ }
3037
+ case "error": {
3038
+ n == null || n(new Error(i.errorText));
3039
+ break;
3040
+ }
3041
+ default:
3042
+ if (_s(i)) {
3043
+ if ((r == null ? void 0 : r[i.type]) != null) {
3044
+ const m = c.message.parts.findIndex(
3045
+ (y) => "id" in y && "data" in y && y.id === i.id && y.type === i.type
3046
+ ), b = m >= 0 ? m : c.message.parts.length;
3047
+ await Dt({
3048
+ value: i.data,
3049
+ schema: r[i.type],
3050
+ context: {
3051
+ field: `message.parts[${b}].data`,
3052
+ entityName: i.type,
3053
+ entityId: i.id
3054
+ }
3055
+ });
3056
+ }
3057
+ const d = i;
3058
+ if (d.transient) {
3059
+ u == null || u(d);
3060
+ break;
3061
+ }
3062
+ const f = d.id != null ? c.message.parts.find(
3063
+ (m) => d.type === m.type && d.id === m.id
3064
+ ) : void 0;
3065
+ f != null ? f.data = d.data : c.message.parts.push(d), u == null || u(d), l();
3066
+ }
3067
+ }
3068
+ g.enqueue(i);
3069
+ });
3070
+ }
3071
+ })
3072
+ );
3073
+ }
3074
+ async function As({
3075
+ stream: e,
3076
+ onError: t
3077
+ }) {
3078
+ const r = e.getReader();
3079
+ try {
3080
+ for (; ; ) {
3081
+ const { done: a } = await r.read();
3082
+ if (a)
3083
+ break;
3084
+ }
3085
+ } catch (a) {
3086
+ t == null || t(a);
3087
+ } finally {
3088
+ r.releaseLock();
3089
+ }
3090
+ }
3091
+ J({
3092
+ prefix: "aitxt",
3093
+ size: 24
3094
+ });
3095
+ J({
3096
+ prefix: "call",
3097
+ size: 24
3098
+ });
3099
+ J({
3100
+ prefix: "aitxt",
3101
+ size: 24
3102
+ });
3103
+ J({
3104
+ prefix: "call",
3105
+ size: 24
3106
+ });
3107
+ s.record(
3108
+ s.string(),
3109
+ he.optional()
3110
+ );
3111
+ s.record(s.string(), s.string());
3112
+ J({
3113
+ prefix: "call",
3114
+ size: 24
3115
+ });
3116
+ J({
3117
+ prefix: "call",
3118
+ size: 24
3119
+ });
3120
+ J({ prefix: "aiobj", size: 24 });
3121
+ var Cs = class {
3122
+ constructor() {
3123
+ this.queue = [], this.isProcessing = !1;
3124
+ }
3125
+ async processQueue() {
3126
+ if (!this.isProcessing) {
3127
+ for (this.isProcessing = !0; this.queue.length > 0; )
3128
+ await this.queue[0](), this.queue.shift();
3129
+ this.isProcessing = !1;
3130
+ }
3131
+ }
3132
+ async run(e) {
3133
+ return new Promise((t, r) => {
3134
+ this.queue.push(async () => {
3135
+ try {
3136
+ await e(), t();
3137
+ } catch (a) {
3138
+ r(a);
3139
+ }
3140
+ }), this.processQueue();
3141
+ });
3142
+ }
3143
+ };
3144
+ J({ prefix: "aiobj", size: 24 });
3145
+ J({
3146
+ prefix: "call",
3147
+ size: 24
3148
+ });
3149
+ async function xs(e) {
3150
+ if (e == null)
3151
+ return [];
3152
+ if (!globalThis.FileList || !(e instanceof globalThis.FileList))
3153
+ throw new Error("FileList is not supported in the current environment");
3154
+ return Promise.all(
3155
+ Array.from(e).map(async (t) => {
3156
+ const { name: r, type: a } = t, n = await new Promise((o, u) => {
3157
+ const i = new FileReader();
3158
+ i.onload = (g) => {
3159
+ var c;
3160
+ o((c = g.target) == null ? void 0 : c.result);
3161
+ }, i.onerror = (g) => u(g), i.readAsDataURL(t);
3162
+ });
3163
+ return {
3164
+ type: "file",
3165
+ mediaType: a,
3166
+ filename: r,
3167
+ url: n
3168
+ };
3169
+ })
3170
+ );
3171
+ }
3172
+ var Rs = class {
3173
+ constructor({
3174
+ api: e = "/api/chat",
3175
+ credentials: t,
3176
+ headers: r,
3177
+ body: a,
3178
+ fetch: n,
3179
+ prepareSendMessagesRequest: o,
3180
+ prepareReconnectToStreamRequest: u
3181
+ }) {
3182
+ this.api = e, this.credentials = t, this.headers = r, this.body = a, this.fetch = n, this.prepareSendMessagesRequest = o, this.prepareReconnectToStreamRequest = u;
3183
+ }
3184
+ async sendMessages({
3185
+ abortSignal: e,
3186
+ ...t
3187
+ }) {
3188
+ var r, a, n, o, u;
3189
+ const i = await ue(this.body), g = await ue(this.headers), c = await ue(this.credentials), l = {
3190
+ ...Ee(g),
3191
+ ...Ee(t.headers)
3192
+ }, p = await ((r = this.prepareSendMessagesRequest) == null ? void 0 : r.call(this, {
3193
+ api: this.api,
3194
+ id: t.chatId,
3195
+ messages: t.messages,
3196
+ body: { ...i, ...t.body },
3197
+ headers: l,
3198
+ credentials: c,
3199
+ requestMetadata: t.metadata,
3200
+ trigger: t.trigger,
3201
+ messageId: t.messageId
3202
+ })), v = (a = p == null ? void 0 : p.api) != null ? a : this.api, h = (p == null ? void 0 : p.headers) !== void 0 ? Ee(p.headers) : l, A = (p == null ? void 0 : p.body) !== void 0 ? p.body : {
3203
+ ...i,
3204
+ ...t.body,
3205
+ id: t.chatId,
3206
+ messages: t.messages,
3207
+ trigger: t.trigger,
3208
+ messageId: t.messageId
3209
+ }, M = (n = p == null ? void 0 : p.credentials) != null ? n : c, I = await ((o = this.fetch) != null ? o : globalThis.fetch)(v, {
3210
+ method: "POST",
3211
+ headers: {
3212
+ "Content-Type": "application/json",
3213
+ ...h
3214
+ },
3215
+ body: JSON.stringify(A),
3216
+ credentials: M,
3217
+ signal: e
3218
+ });
3219
+ if (!I.ok)
3220
+ throw new Error(
3221
+ (u = await I.text()) != null ? u : "Failed to fetch the chat response."
3222
+ );
3223
+ if (!I.body)
3224
+ throw new Error("The response body is empty.");
3225
+ return this.processResponseStream(I.body);
3226
+ }
3227
+ async reconnectToStream(e) {
3228
+ var t, r, a, n, o;
3229
+ const u = await ue(this.body), i = await ue(this.headers), g = await ue(this.credentials), c = {
3230
+ ...Ee(i),
3231
+ ...Ee(e.headers)
3232
+ }, l = await ((t = this.prepareReconnectToStreamRequest) == null ? void 0 : t.call(this, {
3233
+ api: this.api,
3234
+ id: e.chatId,
3235
+ body: { ...u, ...e.body },
3236
+ headers: c,
3237
+ credentials: g,
3238
+ requestMetadata: e.metadata
3239
+ })), p = (r = l == null ? void 0 : l.api) != null ? r : `${this.api}/${e.chatId}/stream`, v = (l == null ? void 0 : l.headers) !== void 0 ? Ee(l.headers) : c, h = (a = l == null ? void 0 : l.credentials) != null ? a : g, M = await ((n = this.fetch) != null ? n : globalThis.fetch)(p, {
3240
+ method: "GET",
3241
+ headers: v,
3242
+ credentials: h
3243
+ });
3244
+ if (M.status === 204)
3245
+ return null;
3246
+ if (!M.ok)
3247
+ throw new Error(
3248
+ (o = await M.text()) != null ? o : "Failed to fetch the chat response."
3249
+ );
3250
+ if (!M.body)
3251
+ throw new Error("The response body is empty.");
3252
+ return this.processResponseStream(M.body);
3253
+ }
3254
+ }, dt = class extends Rs {
3255
+ constructor(e = {}) {
3256
+ super(e);
3257
+ }
3258
+ processResponseStream(e) {
3259
+ return Ha({
3260
+ stream: e,
3261
+ schema: Is
3262
+ }).pipeThrough(
3263
+ new TransformStream({
3264
+ async transform(t, r) {
3265
+ if (!t.success)
3266
+ throw t.error;
3267
+ r.enqueue(t.value);
3268
+ }
3269
+ })
22
3270
  );
23
- return n || null;
24
3271
  }
25
- getComponent(t) {
26
- var n;
27
- return (n = this.get(t)) == null ? void 0 : n.component;
3272
+ }, Os = class {
3273
+ constructor({
3274
+ generateId: e = Gr,
3275
+ id: t = e(),
3276
+ transport: r = new dt(),
3277
+ messageMetadataSchema: a,
3278
+ dataPartSchemas: n,
3279
+ state: o,
3280
+ onError: u,
3281
+ onToolCall: i,
3282
+ onFinish: g,
3283
+ onData: c,
3284
+ sendAutomaticallyWhen: l
3285
+ }) {
3286
+ this.activeResponse = void 0, this.jobExecutor = new Cs(), this.sendMessage = async (p, v) => {
3287
+ var h, A, M, S;
3288
+ if (p == null) {
3289
+ await this.makeRequest({
3290
+ trigger: "submit-message",
3291
+ messageId: (h = this.lastMessage) == null ? void 0 : h.id,
3292
+ ...v
3293
+ });
3294
+ return;
3295
+ }
3296
+ let I;
3297
+ if ("text" in p || "files" in p ? I = {
3298
+ parts: [
3299
+ ...Array.isArray(p.files) ? p.files : await xs(p.files),
3300
+ ..."text" in p && p.text != null ? [{ type: "text", text: p.text }] : []
3301
+ ]
3302
+ } : I = p, p.messageId != null) {
3303
+ const _ = this.state.messages.findIndex(
3304
+ (R) => R.id === p.messageId
3305
+ );
3306
+ if (_ === -1)
3307
+ throw new Error(`message with id ${p.messageId} not found`);
3308
+ if (this.state.messages[_].role !== "user")
3309
+ throw new Error(
3310
+ `message with id ${p.messageId} is not a user message`
3311
+ );
3312
+ this.state.messages = this.state.messages.slice(0, _ + 1), this.state.replaceMessage(_, {
3313
+ ...I,
3314
+ id: p.messageId,
3315
+ role: (A = I.role) != null ? A : "user",
3316
+ metadata: p.metadata
3317
+ });
3318
+ } else
3319
+ this.state.pushMessage({
3320
+ ...I,
3321
+ id: (M = I.id) != null ? M : this.generateId(),
3322
+ role: (S = I.role) != null ? S : "user",
3323
+ metadata: p.metadata
3324
+ });
3325
+ await this.makeRequest({
3326
+ trigger: "submit-message",
3327
+ messageId: p.messageId,
3328
+ ...v
3329
+ });
3330
+ }, this.regenerate = async ({
3331
+ messageId: p,
3332
+ ...v
3333
+ } = {}) => {
3334
+ const h = p == null ? this.state.messages.length - 1 : this.state.messages.findIndex((A) => A.id === p);
3335
+ if (h === -1)
3336
+ throw new Error(`message ${p} not found`);
3337
+ this.state.messages = this.state.messages.slice(
3338
+ 0,
3339
+ // if the message is a user message, we need to include it in the request:
3340
+ this.messages[h].role === "assistant" ? h : h + 1
3341
+ ), await this.makeRequest({
3342
+ trigger: "regenerate-message",
3343
+ messageId: p,
3344
+ ...v
3345
+ });
3346
+ }, this.resumeStream = async (p = {}) => {
3347
+ await this.makeRequest({ trigger: "resume-stream", ...p });
3348
+ }, this.clearError = () => {
3349
+ this.status === "error" && (this.state.error = void 0, this.setStatus({ status: "ready" }));
3350
+ }, this.addToolApprovalResponse = async ({
3351
+ id: p,
3352
+ approved: v,
3353
+ reason: h,
3354
+ options: A
3355
+ }) => this.jobExecutor.run(async () => {
3356
+ const M = this.state.messages, S = M[M.length - 1], I = (_) => _e(_) && _.state === "approval-requested" && _.approval.id === p ? {
3357
+ ..._,
3358
+ state: "approval-responded",
3359
+ approval: { ..._.approval, id: p, approved: v, reason: h }
3360
+ } : _;
3361
+ this.state.replaceMessage(M.length - 1, {
3362
+ ...S,
3363
+ parts: S.parts.map(I)
3364
+ }), this.activeResponse && (this.activeResponse.state.message.parts = this.activeResponse.state.message.parts.map(I)), this.status !== "streaming" && this.status !== "submitted" && this.sendAutomaticallyWhen && this.shouldSendAutomatically().then((_) => {
3365
+ var R;
3366
+ _ && this.makeRequest({
3367
+ trigger: "submit-message",
3368
+ messageId: (R = this.lastMessage) == null ? void 0 : R.id,
3369
+ ...A
3370
+ });
3371
+ });
3372
+ }), this.addToolOutput = async ({
3373
+ state: p = "output-available",
3374
+ toolCallId: v,
3375
+ output: h,
3376
+ errorText: A,
3377
+ options: M
3378
+ }) => this.jobExecutor.run(async () => {
3379
+ const S = this.state.messages, I = S[S.length - 1], _ = (R) => _e(R) && R.toolCallId === v ? { ...R, state: p, output: h, errorText: A } : R;
3380
+ this.state.replaceMessage(S.length - 1, {
3381
+ ...I,
3382
+ parts: I.parts.map(_)
3383
+ }), this.activeResponse && (this.activeResponse.state.message.parts = this.activeResponse.state.message.parts.map(_)), this.status !== "streaming" && this.status !== "submitted" && this.sendAutomaticallyWhen && this.shouldSendAutomatically().then((R) => {
3384
+ var d;
3385
+ R && this.makeRequest({
3386
+ trigger: "submit-message",
3387
+ messageId: (d = this.lastMessage) == null ? void 0 : d.id,
3388
+ ...M
3389
+ });
3390
+ });
3391
+ }), this.addToolResult = this.addToolOutput, this.stop = async () => {
3392
+ var p;
3393
+ this.status !== "streaming" && this.status !== "submitted" || (p = this.activeResponse) != null && p.abortController && this.activeResponse.abortController.abort();
3394
+ }, this.id = t, this.transport = r, this.generateId = e, this.messageMetadataSchema = a, this.dataPartSchemas = n, this.state = o, this.onError = u, this.onToolCall = i, this.onFinish = g, this.onData = c, this.sendAutomaticallyWhen = l;
3395
+ }
3396
+ /**
3397
+ * Hook status:
3398
+ *
3399
+ * - `submitted`: The message has been sent to the API and we're awaiting the start of the response stream.
3400
+ * - `streaming`: The response is actively streaming in from the API, receiving chunks of data.
3401
+ * - `ready`: The full response has been received and processed; a new user message can be submitted.
3402
+ * - `error`: An error occurred during the API request, preventing successful completion.
3403
+ */
3404
+ get status() {
3405
+ return this.state.status;
3406
+ }
3407
+ setStatus({
3408
+ status: e,
3409
+ error: t
3410
+ }) {
3411
+ this.status !== e && (this.state.status = e, this.state.error = t);
3412
+ }
3413
+ get error() {
3414
+ return this.state.error;
3415
+ }
3416
+ get messages() {
3417
+ return this.state.messages;
3418
+ }
3419
+ get lastMessage() {
3420
+ return this.state.messages[this.state.messages.length - 1];
3421
+ }
3422
+ set messages(e) {
3423
+ this.state.messages = e;
3424
+ }
3425
+ async shouldSendAutomatically() {
3426
+ if (!this.sendAutomaticallyWhen)
3427
+ return !1;
3428
+ const e = this.sendAutomaticallyWhen({
3429
+ messages: this.state.messages
3430
+ });
3431
+ return e && typeof e == "object" && "then" in e ? await e : e;
3432
+ }
3433
+ async makeRequest({
3434
+ trigger: e,
3435
+ metadata: t,
3436
+ headers: r,
3437
+ body: a,
3438
+ messageId: n
3439
+ }) {
3440
+ var o, u;
3441
+ let i;
3442
+ if (e === "resume-stream")
3443
+ try {
3444
+ const h = await this.transport.reconnectToStream({
3445
+ chatId: this.id,
3446
+ metadata: t,
3447
+ headers: r,
3448
+ body: a
3449
+ });
3450
+ if (h == null)
3451
+ return;
3452
+ i = h;
3453
+ } catch (h) {
3454
+ this.onError && h instanceof Error && this.onError(h), this.setStatus({ status: "error", error: h });
3455
+ return;
3456
+ }
3457
+ this.setStatus({ status: "submitted", error: void 0 });
3458
+ const g = this.lastMessage;
3459
+ let c = !1, l = !1, p = !1, v;
3460
+ try {
3461
+ const h = {
3462
+ state: Ms({
3463
+ lastMessage: this.state.snapshot(g),
3464
+ messageId: this.generateId()
3465
+ }),
3466
+ abortController: new AbortController()
3467
+ };
3468
+ v = h, h.abortController.signal.addEventListener("abort", () => {
3469
+ c = !0;
3470
+ }), this.activeResponse = h;
3471
+ let A;
3472
+ e === "resume-stream" ? A = i : A = await this.transport.sendMessages({
3473
+ chatId: this.id,
3474
+ messages: this.state.messages,
3475
+ abortSignal: h.abortController.signal,
3476
+ metadata: t,
3477
+ headers: r,
3478
+ body: a,
3479
+ trigger: e,
3480
+ messageId: n
3481
+ });
3482
+ const M = (S) => (
3483
+ // serialize the job execution to avoid race conditions:
3484
+ this.jobExecutor.run(
3485
+ () => S({
3486
+ state: h.state,
3487
+ write: () => {
3488
+ var I;
3489
+ this.setStatus({ status: "streaming" }), h.state.message.id === ((I = this.lastMessage) == null ? void 0 : I.id) ? this.state.replaceMessage(
3490
+ this.state.messages.length - 1,
3491
+ h.state.message
3492
+ ) : this.state.pushMessage(h.state.message);
3493
+ }
3494
+ })
3495
+ )
3496
+ );
3497
+ await As({
3498
+ stream: Ts({
3499
+ stream: A,
3500
+ onToolCall: this.onToolCall,
3501
+ onData: this.onData,
3502
+ messageMetadataSchema: this.messageMetadataSchema,
3503
+ dataPartSchemas: this.dataPartSchemas,
3504
+ runUpdateMessageJob: M,
3505
+ onError: (S) => {
3506
+ throw S;
3507
+ }
3508
+ }),
3509
+ onError: (S) => {
3510
+ throw S;
3511
+ }
3512
+ }), this.setStatus({ status: "ready" });
3513
+ } catch (h) {
3514
+ if (c || h.name === "AbortError")
3515
+ return c = !0, this.setStatus({ status: "ready" }), null;
3516
+ p = !0, h instanceof TypeError && (h.message.toLowerCase().includes("fetch") || h.message.toLowerCase().includes("network")) && (l = !0), this.onError && h instanceof Error && this.onError(h), this.setStatus({ status: "error", error: h });
3517
+ } finally {
3518
+ try {
3519
+ v && ((o = this.onFinish) == null || o.call(this, {
3520
+ message: v.state.message,
3521
+ messages: this.state.messages,
3522
+ isAbort: c,
3523
+ isDisconnect: l,
3524
+ isError: p,
3525
+ finishReason: v.state.finishReason
3526
+ }));
3527
+ } catch (h) {
3528
+ console.error(h);
3529
+ }
3530
+ this.activeResponse === v && (this.activeResponse = void 0);
3531
+ }
3532
+ !p && await this.shouldSendAutomatically() && await this.makeRequest({
3533
+ trigger: "submit-message",
3534
+ messageId: (u = this.lastMessage) == null ? void 0 : u.id,
3535
+ metadata: t,
3536
+ headers: r,
3537
+ body: a
3538
+ });
3539
+ }
3540
+ };
3541
+ function Ps(e, t) {
3542
+ if (typeof e != "function")
3543
+ throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);
3544
+ let r, a = 0;
3545
+ return function(...o) {
3546
+ clearTimeout(r);
3547
+ const u = Date.now(), i = u - a, g = t - i;
3548
+ g <= 0 ? (a = u, e.apply(this, o)) : r = setTimeout(() => {
3549
+ a = Date.now(), e.apply(this, o);
3550
+ }, g);
3551
+ };
3552
+ }
3553
+ var Ns = Ps;
3554
+ const js = /* @__PURE__ */ Ga(Ns);
3555
+ var gr = (e, t, r) => {
3556
+ if (!t.has(e))
3557
+ throw TypeError("Cannot " + r);
3558
+ }, N = (e, t, r) => (gr(e, t, "read from private field"), r ? r.call(e) : t.get(e)), te = (e, t, r) => {
3559
+ if (t.has(e))
3560
+ throw TypeError("Cannot add the same private member more than once");
3561
+ t instanceof WeakSet ? t.add(e) : t.set(e, r);
3562
+ }, le = (e, t, r, a) => (gr(e, t, "write to private field"), t.set(e, r), r);
3563
+ function Ds(e, t) {
3564
+ return t != null ? js(e, t) : e;
3565
+ }
3566
+ var W, ke, $e, Ce, xe, Re, Se, nt, it, Ls = class {
3567
+ constructor(e = []) {
3568
+ te(this, W, void 0), te(this, ke, "ready"), te(this, $e, void 0), te(this, Ce, /* @__PURE__ */ new Set()), te(this, xe, /* @__PURE__ */ new Set()), te(this, Re, /* @__PURE__ */ new Set()), this.pushMessage = (t) => {
3569
+ le(this, W, N(this, W).concat(t)), N(this, Se).call(this);
3570
+ }, this.popMessage = () => {
3571
+ le(this, W, N(this, W).slice(0, -1)), N(this, Se).call(this);
3572
+ }, this.replaceMessage = (t, r) => {
3573
+ le(this, W, [
3574
+ ...N(this, W).slice(0, t),
3575
+ // We deep clone the message here to ensure the new React Compiler (currently in RC) detects deeply nested parts/metadata changes:
3576
+ this.snapshot(r),
3577
+ ...N(this, W).slice(t + 1)
3578
+ ]), N(this, Se).call(this);
3579
+ }, this.snapshot = (t) => structuredClone(t), this["~registerMessagesCallback"] = (t, r) => {
3580
+ const a = r ? Ds(t, r) : t;
3581
+ return N(this, Ce).add(a), () => {
3582
+ N(this, Ce).delete(a);
3583
+ };
3584
+ }, this["~registerStatusCallback"] = (t) => (N(this, xe).add(t), () => {
3585
+ N(this, xe).delete(t);
3586
+ }), this["~registerErrorCallback"] = (t) => (N(this, Re).add(t), () => {
3587
+ N(this, Re).delete(t);
3588
+ }), te(this, Se, () => {
3589
+ N(this, Ce).forEach((t) => t());
3590
+ }), te(this, nt, () => {
3591
+ N(this, xe).forEach((t) => t());
3592
+ }), te(this, it, () => {
3593
+ N(this, Re).forEach((t) => t());
3594
+ }), le(this, W, e);
3595
+ }
3596
+ get status() {
3597
+ return N(this, ke);
3598
+ }
3599
+ set status(e) {
3600
+ le(this, ke, e), N(this, nt).call(this);
3601
+ }
3602
+ get error() {
3603
+ return N(this, $e);
3604
+ }
3605
+ set error(e) {
3606
+ le(this, $e, e), N(this, it).call(this);
3607
+ }
3608
+ get messages() {
3609
+ return N(this, W);
3610
+ }
3611
+ set messages(e) {
3612
+ le(this, W, [...e]), N(this, Se).call(this);
3613
+ }
3614
+ };
3615
+ W = /* @__PURE__ */ new WeakMap();
3616
+ ke = /* @__PURE__ */ new WeakMap();
3617
+ $e = /* @__PURE__ */ new WeakMap();
3618
+ Ce = /* @__PURE__ */ new WeakMap();
3619
+ xe = /* @__PURE__ */ new WeakMap();
3620
+ Re = /* @__PURE__ */ new WeakMap();
3621
+ Se = /* @__PURE__ */ new WeakMap();
3622
+ nt = /* @__PURE__ */ new WeakMap();
3623
+ it = /* @__PURE__ */ new WeakMap();
3624
+ var Ie, Lt = class extends Os {
3625
+ constructor({ messages: e, ...t }) {
3626
+ const r = new Ls(e);
3627
+ super({ ...t, state: r }), te(this, Ie, void 0), this["~registerMessagesCallback"] = (a, n) => N(this, Ie)["~registerMessagesCallback"](a, n), this["~registerStatusCallback"] = (a) => N(this, Ie)["~registerStatusCallback"](a), this["~registerErrorCallback"] = (a) => N(this, Ie)["~registerErrorCallback"](a), le(this, Ie, r);
3628
+ }
3629
+ };
3630
+ Ie = /* @__PURE__ */ new WeakMap();
3631
+ function Fs({
3632
+ throttle: e,
3633
+ experimental_throttle: t,
3634
+ resume: r = !1,
3635
+ ...a
3636
+ } = {}) {
3637
+ const n = e ?? t, o = j({});
3638
+ "chat" in a || (o.current = {
3639
+ onToolCall: a.onToolCall,
3640
+ onData: a.onData,
3641
+ onFinish: a.onFinish,
3642
+ onError: a.onError,
3643
+ sendAutomaticallyWhen: a.sendAutomaticallyWhen,
3644
+ transport: a.transport
3645
+ });
3646
+ let u;
3647
+ const i = () => {
3648
+ var S;
3649
+ return (S = o.current.transport) != null ? S : u ?? (u = new dt());
3650
+ }, g = {
3651
+ ...a,
3652
+ transport: {
3653
+ sendMessages: (S) => i().sendMessages(S),
3654
+ reconnectToStream: (S) => i().reconnectToStream(S)
3655
+ },
3656
+ onToolCall: (S) => {
3657
+ var I, _;
3658
+ return (_ = (I = o.current).onToolCall) == null ? void 0 : _.call(I, S);
3659
+ },
3660
+ onData: (S) => {
3661
+ var I, _;
3662
+ return (_ = (I = o.current).onData) == null ? void 0 : _.call(I, S);
3663
+ },
3664
+ onFinish: (S) => {
3665
+ var I, _;
3666
+ return (_ = (I = o.current).onFinish) == null ? void 0 : _.call(I, S);
3667
+ },
3668
+ onError: (S) => {
3669
+ var I, _;
3670
+ return (_ = (I = o.current).onError) == null ? void 0 : _.call(I, S);
3671
+ },
3672
+ sendAutomaticallyWhen: (S) => {
3673
+ var I, _, R;
3674
+ return (R = (_ = (I = o.current).sendAutomaticallyWhen) == null ? void 0 : _.call(I, S)) != null ? R : !1;
3675
+ }
3676
+ }, c = j(
3677
+ "chat" in a ? a.chat : new Lt(g)
3678
+ );
3679
+ ("chat" in a && a.chat !== c.current || "id" in a && a.id != null && c.current.id !== a.id) && (c.current = "chat" in a ? a.chat : new Lt(g));
3680
+ const p = U(
3681
+ (S) => c.current["~registerMessagesCallback"](S, n),
3682
+ // `chatRef.current.id` is required to trigger re-subscription when the chat ID changes
3683
+ // eslint-disable-next-line react-hooks/exhaustive-deps
3684
+ [n, c.current.id]
3685
+ ), v = Oe(
3686
+ p,
3687
+ () => c.current.messages,
3688
+ () => c.current.messages
3689
+ ), h = Oe(
3690
+ c.current["~registerStatusCallback"],
3691
+ () => c.current.status,
3692
+ () => c.current.status
3693
+ ), A = Oe(
3694
+ c.current["~registerErrorCallback"],
3695
+ () => c.current.error,
3696
+ () => c.current.error
3697
+ ), M = U(
3698
+ (S) => {
3699
+ typeof S == "function" && (S = S(c.current.messages)), c.current.messages = S;
3700
+ },
3701
+ [c]
3702
+ );
3703
+ return $(() => {
3704
+ r && c.current.resumeStream();
3705
+ }, [r, c]), {
3706
+ id: c.current.id,
3707
+ messages: v,
3708
+ setMessages: M,
3709
+ sendMessage: c.current.sendMessage,
3710
+ regenerate: c.current.regenerate,
3711
+ clearError: c.current.clearError,
3712
+ stop: c.current.stop,
3713
+ error: A,
3714
+ resumeStream: c.current.resumeStream,
3715
+ status: h,
3716
+ /**
3717
+ * @deprecated Use `addToolOutput` instead.
3718
+ */
3719
+ addToolResult: c.current.addToolOutput,
3720
+ addToolOutput: c.current.addToolOutput,
3721
+ addToolApprovalResponse: c.current.addToolApprovalResponse
3722
+ };
3723
+ }
3724
+ class Ft {
3725
+ constructor(t) {
3726
+ this.buffer = [], this.cap = Math.max(1, Math.floor(t));
3727
+ }
3728
+ get size() {
3729
+ return this.buffer.length;
3730
+ }
3731
+ /** Read-only snapshot of pending items, oldest first. */
3732
+ get items() {
3733
+ return this.buffer;
3734
+ }
3735
+ /**
3736
+ * Append an item when capacity permits. Returns `false` without mutating
3737
+ * the accepted FIFO backlog when full.
3738
+ */
3739
+ enqueue(t) {
3740
+ return this.buffer.length >= this.cap ? !1 : (this.buffer.push(t), !0);
3741
+ }
3742
+ /** Remove and return the next item (FIFO), or `null` when empty. */
3743
+ dequeueNext() {
3744
+ return this.buffer.shift() ?? null;
3745
+ }
3746
+ /**
3747
+ * Remove and return the first item matching `predicate`, or `null` when
3748
+ * nothing matches. Used by the queue pill's per-message remove button.
3749
+ */
3750
+ removeWhere(t) {
3751
+ const r = this.buffer.findIndex(t);
3752
+ if (r === -1) return null;
3753
+ const [a] = this.buffer.splice(r, 1);
3754
+ return a ?? null;
3755
+ }
3756
+ }
3757
+ const ks = z.union([
3758
+ z.string(),
3759
+ z.looseObject({ id: z.string().optional(), label: z.string() })
3760
+ ]), $s = z.looseObject({
3761
+ id: z.string().optional(),
3762
+ prompt: z.string(),
3763
+ selection: z.enum(["single", "multiple"]).default("single"),
3764
+ options: z.array(ks).min(1)
3765
+ }), Us = z.looseObject({
3766
+ request_id: z.string().optional(),
3767
+ questions: z.array($s).min(1)
3768
+ });
3769
+ function qs(e) {
3770
+ return !!(e != null && e.includes("ask_questions"));
3771
+ }
3772
+ const Zs = [
3773
+ /\bi[’'ʼ‘]?ll\s+(type|describe|enter|write|tell)\b/i,
3774
+ /\b(type|describe|enter|write|tell)\s+(it|my\s+own|manually)\b/i,
3775
+ /^\s*(other|custom|none\s+of\s+the\s+above|something\s+else)\s*\.?\s*$/i
3776
+ ];
3777
+ function zs(e) {
3778
+ return Zs.some((t) => t.test(e));
3779
+ }
3780
+ function Bs(e, t) {
3781
+ return {
3782
+ request_id: e.request_id ?? t ?? "req-clarification",
3783
+ questions: e.questions.map((r, a) => ({
3784
+ id: r.id ?? `q${a}`,
3785
+ prompt: r.prompt,
3786
+ selection: r.selection,
3787
+ options: r.options.map(
3788
+ (n, o) => typeof n == "string" ? { id: `q${a}-o${o}`, label: n } : {
3789
+ id: n.id ?? `q${a}-o${o}`,
3790
+ label: n.label
3791
+ }
3792
+ ).filter((n) => !zs(n.label))
3793
+ }))
3794
+ };
3795
+ }
3796
+ function Qe(e) {
3797
+ try {
3798
+ return JSON.parse(e);
3799
+ } catch {
3800
+ return null;
3801
+ }
3802
+ }
3803
+ function Ws(e) {
3804
+ if (e == null) return null;
3805
+ if (typeof e == "string") return Qe(e);
3806
+ if (Array.isArray(e)) {
3807
+ for (const t of e)
3808
+ if (t && typeof t == "object" && "text" in t) {
3809
+ const r = t.text;
3810
+ if (typeof r == "string") return Qe(r);
3811
+ }
3812
+ return null;
3813
+ }
3814
+ if (typeof e == "object") {
3815
+ if ("text" in e) {
3816
+ const t = e.text;
3817
+ if (typeof t == "string") return Qe(t);
3818
+ }
3819
+ return e;
3820
+ }
3821
+ return null;
3822
+ }
3823
+ function kt(e, t) {
3824
+ const r = Ws(e);
3825
+ if (r == null) return null;
3826
+ const a = Us.safeParse(r);
3827
+ return a.success ? Bs(a.data, t) : null;
3828
+ }
3829
+ function _n(e, t) {
3830
+ const r = [];
3831
+ for (const a of e.questions) {
3832
+ const n = t.get(a.id);
3833
+ n === void 0 || n.trim() === "" || r.push(`Q: ${a.prompt}
3834
+ A: ${n.trim()}`);
3835
+ }
3836
+ return r.join(`
3837
+
3838
+ `);
3839
+ }
3840
+ const $t = "data-spec";
3841
+ function ot(e) {
3842
+ const t = [], r = (o) => {
3843
+ const u = t.at(-1);
3844
+ (u == null ? void 0 : u.kind) === "steps" ? u.steps.push(o) : t.push({ kind: "steps", steps: [o] });
3845
+ }, a = (o) => o === "output-available" || o === "output-error";
3846
+ let n = null;
3847
+ for (const o of e)
3848
+ if (!Zt(o)) {
3849
+ if (Js(o)) {
3850
+ const u = Ks(o);
3851
+ u && t.push(u);
3852
+ continue;
3853
+ }
3854
+ if (o.type === $t)
3855
+ n || (n = { kind: "spec", parts: [] }, t.push(n)), n.parts.push({ type: $t, data: o.data });
3856
+ else if (o.type === "text") {
3857
+ const u = typeof o.text == "string" ? o.text : "";
3858
+ u.trim().length > 0 && t.push({ kind: "text", text: u });
3859
+ } else o.type === "reasoning" ? r({
3860
+ kind: "reasoning",
3861
+ label: typeof o.text == "string" ? o.text : "",
3862
+ done: o.state !== "streaming"
3863
+ }) : o.type === "dynamic-tool" ? r({
3864
+ kind: "tool",
3865
+ label: typeof o.toolName == "string" ? o.toolName : "tool",
3866
+ done: a(o.state),
3867
+ ...Ut(o)
3868
+ }) : o.type.startsWith("tool-") && r({
3869
+ kind: "tool",
3870
+ label: o.type.slice(5),
3871
+ done: a(o.state),
3872
+ ...Ut(o)
3873
+ });
3874
+ }
3875
+ return t;
3876
+ }
3877
+ function Vs(e) {
3878
+ return e.type === "dynamic-tool" ? typeof e.toolName == "string" ? e.toolName : void 0 : e.type.startsWith("tool-") ? e.type.slice(5) : void 0;
3879
+ }
3880
+ function Js(e) {
3881
+ return qs(Vs(e));
3882
+ }
3883
+ function Ks(e) {
3884
+ const t = typeof e.toolCallId == "string" ? e.toolCallId : void 0, r = kt(e.output, t) ?? kt(e.input, t);
3885
+ return r ? { kind: "questions", request: r } : null;
3886
+ }
3887
+ function Ut(e) {
3888
+ return {
3889
+ ...e.input === void 0 ? {} : { input: e.input },
3890
+ ...e.output === void 0 ? {} : { output: e.output }
3891
+ };
3892
+ }
3893
+ function Ys(e) {
3894
+ return ({ id: t }) => ({
3895
+ api: e.reconnectApi(t),
3896
+ headers: e.headers()
3897
+ });
3898
+ }
3899
+ function Hs(e) {
3900
+ return new dt({
3901
+ api: e.api,
3902
+ headers: () => e.headers(),
3903
+ // Every send carries its full body; a send without one is a programming
3904
+ // error, and an empty body would be rejected server-side just as loudly.
3905
+ prepareSendMessagesRequest: ({ body: t }) => ({ body: t ?? {} }),
3906
+ prepareReconnectToStreamRequest: Ys(e)
3907
+ });
3908
+ }
3909
+ function Gs({
3910
+ existing: e,
3911
+ fetched: t
3912
+ }) {
3913
+ const r = new Map(
3914
+ e.map((u) => [u.turnId, u])
3915
+ ), a = /* @__PURE__ */ new Set(), n = [];
3916
+ for (const u of t.turns) {
3917
+ if (a.add(u.turn_id), u.message_uuids.length === 0) continue;
3918
+ const i = r.get(u.turn_id);
3919
+ if (i) {
3920
+ Qs(i.rowIds, u.message_uuids) ? n.push(i) : n.push({ ...i, rowIds: u.message_uuids });
3921
+ continue;
3922
+ }
3923
+ if (u.ui_parts !== null) {
3924
+ const g = ot(u.ui_parts);
3925
+ if (g.length === 0) continue;
3926
+ n.push({
3927
+ key: `turn-${u.turn_id}`,
3928
+ turnId: u.turn_id,
3929
+ rowIds: u.message_uuids,
3930
+ items: g
3931
+ });
3932
+ }
3933
+ }
3934
+ for (const u of e)
3935
+ a.has(u.turnId) || n.push(u);
3936
+ return n.length === e.length && n.every((u, i) => u === e[i]) ? e : n;
3937
+ }
3938
+ const Qs = (e, t) => e.length === t.length && e.every((r, a) => r === t[a]), Xs = (e) => Array.isArray(e) && e.every((t) => typeof t == "string");
3939
+ function en(e) {
3940
+ for (const t of e) {
3941
+ if (t.type !== "data-turn-settled") continue;
3942
+ const r = t.data;
3943
+ return !Rr(r) || typeof r.turn_id != "string" || !Xs(r.message_uuids) ? null : { turnId: r.turn_id, rowIds: r.message_uuids };
3944
+ }
3945
+ return null;
3946
+ }
3947
+ async function tn(e) {
3948
+ const t = e.getReader();
3949
+ try {
3950
+ for (; ; ) {
3951
+ const { value: r, done: a } = await t.read();
3952
+ if (a || r === void 0) return { kind: "silent" };
3953
+ if (!Zt(r))
3954
+ return Or(r) ? { kind: "steered" } : r.type === "error" ? { kind: "failed", errorText: r.errorText } : { kind: "turn" };
3955
+ }
3956
+ } finally {
3957
+ await t.cancel().catch(() => {
3958
+ });
3959
+ }
3960
+ }
3961
+ async function rn({
3962
+ api: e,
3963
+ sessionId: t,
3964
+ chatStop: r
3965
+ }) {
3966
+ try {
3967
+ await r();
3968
+ } finally {
3969
+ t && await e.stopStream(t);
28
3970
  }
29
3971
  }
30
- const U = v(null);
31
- function B({
3972
+ const qt = 20, an = "highlight_element";
3973
+ function sn({
3974
+ widgetCtx: e,
3975
+ config: t,
3976
+ sessionId: r,
3977
+ persistedMessages: a
3978
+ }) {
3979
+ const { api: n, messageCtx: o } = e, u = j(t);
3980
+ u.current = t;
3981
+ const { pageContext: i, clientTools: g } = e.features, c = X(
3982
+ () => Hs({
3983
+ ...n.getStreamTransportOptions(),
3984
+ headers: () => n.getStreamTransportOptions().headers
3985
+ }),
3986
+ [n]
3987
+ ), {
3988
+ status: l,
3989
+ messages: p,
3990
+ sendMessage: v,
3991
+ stop: h,
3992
+ error: A,
3993
+ clearError: M,
3994
+ resumeStream: S
3995
+ } = Fs({
3996
+ id: r ?? void 0,
3997
+ // Reattach to a still-live turn (reload, tab switch) — but only once a
3998
+ // session actually exists. A fresh visitor has nothing to resume, and the
3999
+ // engine mounts with the shell, so probing unconditionally would fire a
4000
+ // spurious reconnect request on every page load.
4001
+ resume: r !== null,
4002
+ transport: c,
4003
+ // Batch token updates: without it every streamed token re-renders the
4004
+ // whole chat surface (transcript + composer), which stutters on long
4005
+ // replies inside customer pages.
4006
+ throttle: 50,
4007
+ onError: (E) => q.error("agent chat stream error", E)
4008
+ }), I = j(p);
4009
+ I.current = p;
4010
+ const _ = j(new Ft(qt)), R = j("idle"), d = j(Promise.resolve()), f = j(0), [m, b] = Z(0), [y, w] = Z(!1), [D, se] = Z([]), [Be, We] = Z(null), Y = j(null), ee = U((E) => {
4011
+ Y.current = E, We(E);
4012
+ }, []), Me = j(null), ye = j(null), be = j(l), ft = j(r), Ve = j(null), Je = j(null), mt = j(h), pe = j(l);
4013
+ pe.current = l;
4014
+ const Le = U((E, x) => {
4015
+ const O = en(E.parts);
4016
+ if (!O || O.rowIds.length === 0) return;
4017
+ const L = ot(E.parts);
4018
+ L.length !== 0 && se(
4019
+ (F) => F.some((Te) => Te.turnId === O.turnId) ? F : [
4020
+ ...F,
4021
+ { key: x, turnId: O.turnId, rowIds: O.rowIds, items: L }
4022
+ ]
4023
+ );
4024
+ }, []), Fe = U(
4025
+ (E) => Pr({
4026
+ config: u.current,
4027
+ input: E.input,
4028
+ uuid: E.retryUuid ?? E.userMessage.id,
4029
+ sessionId: E.sessionId,
4030
+ content: E.userMessage.content,
4031
+ initialMessages: E.initialMessages,
4032
+ sendsPageContext: i
4033
+ }),
4034
+ [i]
4035
+ ), gt = U(
4036
+ async (E) => {
4037
+ const x = f.current, O = new AbortController();
4038
+ let L;
4039
+ try {
4040
+ const F = await c.sendMessages({
4041
+ trigger: "submit-message",
4042
+ chatId: E.sessionId,
4043
+ messageId: void 0,
4044
+ messages: [],
4045
+ abortSignal: O.signal,
4046
+ body: Fe(E)
4047
+ });
4048
+ L = await tn(F);
4049
+ } catch (F) {
4050
+ q.error("agent chat steer failed", F);
4051
+ return;
4052
+ } finally {
4053
+ O.abort();
4054
+ }
4055
+ if (x === f.current) {
4056
+ switch (L.kind) {
4057
+ case "steered":
4058
+ o.markUserMessageDelivered(E.userMessage.id);
4059
+ return;
4060
+ case "turn":
4061
+ ye.current = E;
4062
+ try {
4063
+ await h();
4064
+ } catch (F) {
4065
+ q.error("agent chat steer fallback: client stop failed", F);
4066
+ }
4067
+ if (x !== f.current) return;
4068
+ S();
4069
+ return;
4070
+ case "failed":
4071
+ q.error("agent chat steer: the turn failed", {
4072
+ errorText: L.errorText
4073
+ });
4074
+ break;
4075
+ case "silent":
4076
+ o.markUserMessageDelivered(E.userMessage.id);
4077
+ break;
4078
+ }
4079
+ e.reconcileAfterStream(E.sessionId).catch((F) => {
4080
+ q.error("agent chat post-steer reconcile failed", F);
4081
+ });
4082
+ }
4083
+ },
4084
+ [c, Fe, o, h, S, e]
4085
+ ), vt = j(gt);
4086
+ vt.current = gt, $(() => {
4087
+ const E = mt.current;
4088
+ mt.current = h;
4089
+ const x = ft.current;
4090
+ if (x === r) return;
4091
+ if (ft.current = r, x === null) {
4092
+ se([]);
4093
+ return;
4094
+ }
4095
+ const O = pe.current === "submitted" || pe.current === "streaming" || be.current === "submitted" || be.current === "streaming" || R.current === "in-flight";
4096
+ f.current += 1, d.current = Promise.resolve(), _.current = new Ft(qt), R.current = "idle", ye.current = null, Me.current = null, Je.current = null, Ve.current = l === "submitted" || l === "streaming" ? l : null, be.current = "ready", pe.current = "ready", M(), b((L) => L + 1), w(!1), se([]), ee(null), O && Promise.resolve().then(() => E()).catch((L) => {
4097
+ q.error("agent chat client stream cancel failed", L);
4098
+ });
4099
+ }, [r, l, h, M, ee]), $(() => {
4100
+ var F, Te;
4101
+ const E = Ve.current;
4102
+ if (E !== null && l === E) {
4103
+ be.current = "ready";
4104
+ return;
4105
+ }
4106
+ Ve.current = null;
4107
+ const x = be.current;
4108
+ if (be.current = l, (l === "submitted" || l === "streaming") && (x !== "submitted" && x !== "streaming" && Y.current === null && ee(`turn-resumed-${yt()}`), w(!0)), l === "streaming") {
4109
+ const H = (F = ye.current) == null ? void 0 : F.userMessage.id;
4110
+ H && o.markUserMessageDelivered(H);
4111
+ return;
4112
+ }
4113
+ if (l !== "ready" && l !== "error") return;
4114
+ if (x === "streaming" || x === "submitted") {
4115
+ R.current === "in-flight" && (R.current = "idle");
4116
+ const H = I.current.at(-1), ne = Y.current;
4117
+ if (Me.current = ne, ne !== null && H && H.role === "assistant" && Le(H, ne), l === "ready") {
4118
+ const ie = (Te = ye.current) == null ? void 0 : Te.userMessage.id;
4119
+ ie && o.markUserMessageDelivered(ie);
4120
+ }
4121
+ R.current === "stopping" || (r ? (R.current = "reconciling", e.reconcileAfterStream(r).catch((ie) => {
4122
+ q.error("agent chat post-turn reconcile failed", ie);
4123
+ }).finally(() => {
4124
+ R.current === "reconciling" && (R.current = "idle"), b((ie) => ie + 1);
4125
+ })) : w(!1));
4126
+ }
4127
+ if (R.current !== "idle" || !r) return;
4128
+ const L = _.current.dequeueNext();
4129
+ L && (R.current = "in-flight", ye.current = L, ee(`turn-${L.userMessage.id}`), o.appendUserMessageIfAbsent(L.userMessage), b((H) => H + 1), v(
4130
+ { text: L.userMessage.content },
4131
+ { body: Fe(L) }
4132
+ ));
4133
+ }, [
4134
+ l,
4135
+ r,
4136
+ m,
4137
+ v,
4138
+ o,
4139
+ e,
4140
+ Fe,
4141
+ Le,
4142
+ ee
4143
+ ]);
4144
+ const ht = U(
4145
+ (E) => {
4146
+ const x = f.current, O = d.current.then(
4147
+ async () => {
4148
+ if (x !== f.current) return;
4149
+ const L = R.current, F = pe.current === "streaming" && L !== "stopping" && L !== "reconciling" && _.current.size === 0, H = pe.current === "submitted" || pe.current === "streaming" || L !== "idle" || _.current.size > 0 ? nn(o.buildQueuedUserMessage(E)) : await o.stageUserTurn(E, { pending: !0 });
4150
+ if (!H || x !== f.current) return;
4151
+ const ne = { ...H, input: E };
4152
+ if (F) {
4153
+ o.appendUserMessageIfAbsent(ne.userMessage), o.notifySendAccepted(E), vt.current(ne);
4154
+ return;
4155
+ }
4156
+ if (!_.current.enqueue(ne)) {
4157
+ q.warn("agent chat queue full; rejecting newest send", {
4158
+ rejectedMessageId: ne.userMessage.id
4159
+ });
4160
+ return;
4161
+ }
4162
+ b((ie) => ie + 1), o.notifySendAccepted(E);
4163
+ }
4164
+ );
4165
+ return d.current = O.then(
4166
+ () => {
4167
+ },
4168
+ () => {
4169
+ }
4170
+ ), O;
4171
+ },
4172
+ [o]
4173
+ ), wr = U(() => {
4174
+ const E = ye.current;
4175
+ if (!E) return;
4176
+ if (!_.current.enqueue({
4177
+ ...E,
4178
+ retryUuid: yt()
4179
+ })) {
4180
+ q.warn("agent chat queue full; retry not enqueued");
4181
+ return;
4182
+ }
4183
+ M(), b((O) => O + 1);
4184
+ }, [M]), Mr = U((E) => {
4185
+ _.current.removeWhere(
4186
+ (O) => O.userMessage.id === E
4187
+ ) && b((O) => O + 1);
4188
+ }, []), Tr = U(() => {
4189
+ R.current = "stopping";
4190
+ const E = f.current;
4191
+ rn({ api: n, sessionId: r, chatStop: h }).catch((x) => {
4192
+ q.error("agent chat stop failed", x);
4193
+ }).then(() => {
4194
+ if (E === f.current) {
4195
+ if (!r) {
4196
+ w(!1);
4197
+ return;
4198
+ }
4199
+ return e.reconcileAfterStream(r).catch((x) => {
4200
+ q.error("agent chat post-stop reconcile failed", x);
4201
+ });
4202
+ }
4203
+ }).finally(() => {
4204
+ E === f.current && (R.current = "idle", b((x) => x + 1));
4205
+ });
4206
+ }, [n, r, h, e]);
4207
+ $(() => {
4208
+ const E = { send: ht };
4209
+ return o.registerAgentHandlers(E), () => o.unregisterAgentHandlers(E);
4210
+ }, [o, ht]), $(() => {
4211
+ if (!r || Je.current === r) return;
4212
+ Je.current = r;
4213
+ let E = !1;
4214
+ return (async () => {
4215
+ try {
4216
+ const x = await n.getAgentTurnMessages(r);
4217
+ if (!x || E) return;
4218
+ se((O) => Gs({ existing: O, fetched: x }));
4219
+ } catch (x) {
4220
+ q.error("agent chat turn sources fetch failed", x);
4221
+ }
4222
+ })(), () => {
4223
+ E = !0;
4224
+ };
4225
+ }, [r, n]);
4226
+ const Ar = X(() => {
4227
+ if (!g) return [];
4228
+ const E = p.at(-1);
4229
+ if (!E || E.role !== "assistant") return [];
4230
+ const x = [];
4231
+ for (const O of E.parts)
4232
+ _e(O) && ws(O) === an && (O.state !== "input-available" && O.state !== "output-available" || x.push({
4233
+ key: `${r ?? "pending"}:${O.toolCallId}`,
4234
+ type: "highlight-element",
4235
+ input: O.input
4236
+ }));
4237
+ return x;
4238
+ }, [p, r, g]), ae = l === "submitted" || l === "streaming";
4239
+ $(() => {
4240
+ if (ae) return;
4241
+ const E = Me.current;
4242
+ if (E === null) return;
4243
+ const x = p.at(-1);
4244
+ x && x.role === "assistant" && Le(x, E);
4245
+ }, [p, ae, Le]), $(() => {
4246
+ const E = () => {
4247
+ document.visibilityState === "visible" && r && (ae || A === void 0 && !y || S());
4248
+ };
4249
+ return document.addEventListener("visibilitychange", E), window.addEventListener("online", E), () => {
4250
+ document.removeEventListener("visibilitychange", E), window.removeEventListener("online", E);
4251
+ };
4252
+ }, [r, ae, y, A, S]), $(() => {
4253
+ if (!(ae || !y))
4254
+ for (let E = a.length - 1; E >= 0; E -= 1) {
4255
+ const x = a[E];
4256
+ if (x) {
4257
+ if (x.type === "USER") return;
4258
+ if (!(x.type !== "AI" && x.type !== "AGENT")) {
4259
+ w(!1), Y.current === Me.current && ee(null), Me.current = null;
4260
+ return;
4261
+ }
4262
+ }
4263
+ }
4264
+ }, [ae, y, a, ee]);
4265
+ const Cr = X(() => {
4266
+ if (!ae && !y) return [];
4267
+ const E = p.at(-1);
4268
+ return !E || E.role !== "assistant" ? [] : ot(E.parts);
4269
+ }, [p, ae, y]), xr = X(
4270
+ () => _.current.items.map((E) => E.userMessage),
4271
+ // eslint-disable-next-line react-hooks/exhaustive-deps -- queueRef is mutable; queueVersion is the signal
4272
+ [m]
4273
+ );
4274
+ return {
4275
+ isStreaming: ae,
4276
+ liveItems: Cr,
4277
+ /** Finished turns' render sources — see `TurnRenderSource`. */
4278
+ turnSources: D,
4279
+ /** The live turn's node key (stable through the retained promotion). */
4280
+ liveTurnKey: Be,
4281
+ /** The last turn failed — the transcript renders a visible error row. */
4282
+ turnFailed: A !== void 0,
4283
+ retryFailedTurn: wr,
4284
+ queuedUserMessages: xr,
4285
+ removeQueued: Mr,
4286
+ stop: Tr,
4287
+ pageEffects: Ar
4288
+ };
4289
+ }
4290
+ function nn(e) {
4291
+ return e ? { ...e, initialMessages: [] } : null;
4292
+ }
4293
+ const vr = {
4294
+ isStreaming: !1,
4295
+ liveItems: [],
4296
+ turnSources: [],
4297
+ liveTurnKey: null,
4298
+ turnFailed: !1,
4299
+ retryFailedTurn: () => {
4300
+ },
4301
+ queuedUserMessages: [],
4302
+ removeQueued: () => {
4303
+ },
4304
+ stop: () => {
4305
+ },
4306
+ pageEffects: [],
4307
+ pendingClarification: null
4308
+ }, pt = Ue(null);
4309
+ function on() {
4310
+ return qe(pt) ?? vr;
4311
+ }
4312
+ function ln({
4313
+ children: e,
4314
+ widgetCtx: t,
4315
+ config: r
4316
+ }) {
4317
+ var I, _;
4318
+ const a = de(t.sessionCtx.sessionState), n = de(t.messageCtx.state), {
4319
+ isStreaming: o,
4320
+ liveItems: u,
4321
+ turnSources: i,
4322
+ liveTurnKey: g,
4323
+ turnFailed: c,
4324
+ retryFailedTurn: l,
4325
+ queuedUserMessages: p,
4326
+ removeQueued: v,
4327
+ stop: h,
4328
+ pageEffects: A
4329
+ } = sn({
4330
+ widgetCtx: t,
4331
+ config: r,
4332
+ sessionId: ((I = a.session) == null ? void 0 : I.id) ?? null,
4333
+ persistedMessages: n.messages
4334
+ }), M = ((_ = n.messages.at(-1)) == null ? void 0 : _.type) === "USER", S = X(
4335
+ () => ({
4336
+ isStreaming: o,
4337
+ liveItems: u,
4338
+ turnSources: i,
4339
+ liveTurnKey: g,
4340
+ turnFailed: c,
4341
+ retryFailedTurn: l,
4342
+ queuedUserMessages: p,
4343
+ removeQueued: v,
4344
+ stop: h,
4345
+ pageEffects: A,
4346
+ pendingClarification: qr({
4347
+ turnSources: i,
4348
+ liveItems: u,
4349
+ isStreaming: o,
4350
+ lastMessageIsFromUser: M
4351
+ })
4352
+ }),
4353
+ [
4354
+ o,
4355
+ u,
4356
+ i,
4357
+ g,
4358
+ c,
4359
+ l,
4360
+ p,
4361
+ v,
4362
+ h,
4363
+ A,
4364
+ M
4365
+ ]
4366
+ );
4367
+ return /* @__PURE__ */ V.createElement(pt.Provider, { value: S }, e);
4368
+ }
4369
+ function un({
4370
+ children: e,
4371
+ widgetCtx: t,
4372
+ config: r
4373
+ }) {
4374
+ return t.streaming ? /* @__PURE__ */ V.createElement(ln, { widgetCtx: t, config: r }, e) : /* @__PURE__ */ V.createElement(pt.Provider, { value: vr }, e);
4375
+ }
4376
+ const hr = Ue(null);
4377
+ function wn({
32
4378
  options: e,
33
4379
  children: t,
34
- components: n,
35
- storage: o,
36
- loadingComponent: a
4380
+ components: r,
4381
+ storage: a,
4382
+ loadingComponent: n,
4383
+ errorComponent: o
37
4384
  }) {
38
- const i = y(null), l = y(!1), [u, g] = b(null), c = m(
39
- () => new P({
40
- components: n
4385
+ const u = j(e);
4386
+ u.current = e;
4387
+ const i = j(null), g = j(null), [c, l] = Z({ status: "loading" }), p = X(
4388
+ () => new Ur({
4389
+ components: r
41
4390
  }),
42
- [n]
4391
+ [r]
43
4392
  );
44
- return C(() => {
45
- l.current || (l.current = !0, T.initialize({ config: e, storage: o }).then(g).catch(console.error));
46
- }, []), u ? /* @__PURE__ */ E.createElement(
47
- U.Provider,
4393
+ if ($(() => {
4394
+ const h = g.current ?? (g.current = Nr.initialize({
4395
+ config: e,
4396
+ storage: a,
4397
+ getClientCapabilities: () => u.current.capabilities
4398
+ }));
4399
+ let A = !0;
4400
+ return h.then(
4401
+ (M) => {
4402
+ A && l({ status: "ready", widgetCtx: M });
4403
+ },
4404
+ (M) => {
4405
+ const S = M instanceof Error ? M : new Error("Widget initialization failed", { cause: M });
4406
+ q.error("widget initialization failed", S), A && l({ status: "error", error: S });
4407
+ }
4408
+ ), () => {
4409
+ A = !1;
4410
+ };
4411
+ }, []), c.status === "loading")
4412
+ return n ? /* @__PURE__ */ V.createElement(V.Fragment, null, n) : null;
4413
+ if (c.status === "error")
4414
+ return o ? /* @__PURE__ */ V.createElement(V.Fragment, null, o(c.error)) : null;
4415
+ const { widgetCtx: v } = c;
4416
+ return /* @__PURE__ */ V.createElement(
4417
+ hr.Provider,
48
4418
  {
49
4419
  value: {
50
- widgetCtx: u,
4420
+ widgetCtx: v,
51
4421
  config: e,
52
- components: n,
53
- componentStore: c,
54
- version: O,
4422
+ components: r,
4423
+ componentStore: p,
4424
+ version: $r,
55
4425
  contentIframeRef: i
56
4426
  }
57
4427
  },
58
- t
59
- ) : a || null;
4428
+ /* @__PURE__ */ V.createElement(un, { widgetCtx: v, config: e }, t)
4429
+ );
60
4430
  }
61
- function f() {
62
- const e = F(U);
4431
+ function K() {
4432
+ const e = qe(hr);
63
4433
  if (!e)
64
4434
  throw new Error("useWidget must be used within a WidgetProvider");
65
4435
  return e;
66
4436
  }
67
- function x() {
68
- const { config: e } = f();
4437
+ function Mn() {
4438
+ const { config: e, widgetCtx: t } = K(), { name: r, avatarUrl: a } = t.agent, n = e.bot;
4439
+ return X(
4440
+ () => ({
4441
+ isAi: !0,
4442
+ id: null,
4443
+ name: (n == null ? void 0 : n.name) ?? r,
4444
+ avatarUrl: (n == null ? void 0 : n.avatarUrl) ?? a,
4445
+ avatar: n == null ? void 0 : n.avatar
4446
+ }),
4447
+ [n == null ? void 0 : n.name, n == null ? void 0 : n.avatarUrl, n == null ? void 0 : n.avatar, r, a]
4448
+ );
4449
+ }
4450
+ function ze() {
4451
+ const { config: e } = K();
69
4452
  return e;
70
4453
  }
71
- function w(e) {
72
- return k(e.subscribe, e.get, e.get);
4454
+ function Tn() {
4455
+ const { config: e } = K();
4456
+ return e.displayMode ?? "popover";
73
4457
  }
74
- function D() {
75
- const { widgetCtx: e } = f();
4458
+ function An() {
4459
+ const { widgetCtx: e } = K();
76
4460
  return {
77
- contactState: w(e.contactCtx.state),
4461
+ contactState: de(e.contactCtx.state),
78
4462
  createUnverifiedContact: e.contactCtx.createUnverifiedContact
79
4463
  };
80
4464
  }
81
- function I() {
82
- const [e, t] = b("ltr");
83
- return C(() => {
84
- const n = () => {
4465
+ function cn() {
4466
+ const [e, t] = Z("ltr");
4467
+ return $(() => {
4468
+ const r = () => {
85
4469
  typeof document > "u" || t(
86
4470
  window.getComputedStyle((window.top || window).document.body).direction
87
4471
  );
88
4472
  };
89
- n();
90
- const o = new MutationObserver(n);
91
- return o.observe(document.documentElement, {
4473
+ r();
4474
+ const a = new MutationObserver(r);
4475
+ return a.observe(document.documentElement, {
92
4476
  attributes: !0,
93
4477
  attributeFilter: ["dir"]
94
- }), o.observe(document.body, {
4478
+ }), a.observe(document.body, {
95
4479
  attributes: !0,
96
4480
  attributeFilter: ["dir"]
97
- }), window.addEventListener("languagechange", n), () => {
98
- o.disconnect(), window.removeEventListener("languagechange", n);
4481
+ }), window.addEventListener("languagechange", r), () => {
4482
+ a.disconnect(), window.removeEventListener("languagechange", r);
99
4483
  };
100
4484
  }, []), { dir: e };
101
4485
  }
102
- function R() {
103
- const { widgetCtx: e } = f();
104
- return { messagesState: w(e.messageCtx.state), sendMessage: e.messageCtx.sendMessage };
4486
+ const dn = 500, Xe = "opencx:context-changed";
4487
+ function yr() {
4488
+ if (typeof window > "u") return null;
4489
+ try {
4490
+ const e = window.top ?? window;
4491
+ return e.location.href, e;
4492
+ } catch {
4493
+ return null;
4494
+ }
4495
+ }
4496
+ function pn(e) {
4497
+ const t = yr();
4498
+ if (!t) return () => {
4499
+ };
4500
+ const r = (n) => {
4501
+ (n == null ? void 0 : n.type) === Xe && (br += 1), e();
4502
+ };
4503
+ t.addEventListener("popstate", r), t.addEventListener("hashchange", r), t.addEventListener(Xe, r);
4504
+ const a = t.setInterval(r, dn);
4505
+ return () => {
4506
+ t.removeEventListener("popstate", r), t.removeEventListener("hashchange", r), t.removeEventListener(Xe, r), t.clearInterval(a);
4507
+ };
4508
+ }
4509
+ let br = 0;
4510
+ function fn() {
4511
+ var e;
4512
+ return `${br}|${((e = yr()) == null ? void 0 : e.location.href) ?? ""}`;
4513
+ }
4514
+ function Cn() {
4515
+ return Oe(pn, fn, () => "");
4516
+ }
4517
+ function Er() {
4518
+ const { widgetCtx: e } = K(), t = de(e.messageCtx.state), { isStreaming: r } = on();
4519
+ return {
4520
+ messagesState: r ? { ...t, isSendingMessage: !0, isSendingMessageToAI: !0 } : t,
4521
+ sendMessage: e.messageCtx.sendMessage,
4522
+ // Composer ↑/↓ recall. Owned by MessageCtx so it is scoped to this widget
4523
+ // instance and cleared with the conversation.
4524
+ rememberSentText: e.messageCtx.rememberSentText,
4525
+ getSentTextHistory: e.messageCtx.getSentTextHistory
4526
+ };
105
4527
  }
106
- function A() {
107
- const { widgetCtx: e } = f(), { oneOpenSessionAllowed: t } = x(), n = w(e.sessionCtx.sessionState), o = w(e.sessionCtx.sessionsState), { openSessions: a, closedSessions: i } = m(() => ({
108
- openSessions: o.data.filter((u) => u.isOpened === !0),
109
- closedSessions: o.data.filter((u) => u.isOpened === !1)
110
- }), [o.data]), l = m(() => t ? a.length === 0 : !0, [t, a.length]);
4528
+ function Sr() {
4529
+ const { widgetCtx: e } = K(), { oneOpenSessionAllowed: t } = ze(), r = de(e.sessionCtx.sessionState), a = de(e.sessionCtx.sessionsState), { openSessions: n, closedSessions: o } = X(() => ({
4530
+ openSessions: a.data.filter((i) => i.isOpened === !0),
4531
+ closedSessions: a.data.filter((i) => i.isOpened === !1)
4532
+ }), [a.data]), u = X(() => t ? n.length === 0 : !0, [t, n.length]);
111
4533
  return {
112
- sessionState: n,
113
- sessionsState: o,
4534
+ sessionState: r,
4535
+ sessionsState: a,
114
4536
  loadMoreSessions: e.sessionCtx.loadMoreSessions,
115
4537
  resolveSession: e.sessionCtx.resolveSession,
116
4538
  createStateCheckpoint: e.sessionCtx.createStateCheckpoint,
117
- openSessions: a,
118
- closedSessions: i,
119
- canCreateNewSession: l
4539
+ openSessions: n,
4540
+ closedSessions: o,
4541
+ canCreateNewSession: u
120
4542
  };
121
4543
  }
122
- function z() {
123
- var i, l, u;
124
- const { sessionState: e } = A(), { messagesState: t } = R(), n = ((i = e.session) == null ? void 0 : i.assignee.kind) === "ai", o = ((u = (l = t.messages) == null ? void 0 : l.at(-1)) == null ? void 0 : u.type) === "USER";
125
- return { isAwaitingBotReply: !!(t.isSendingMessageToAI || (n || e.isCreatingSession) && (t.isSendingMessage || o)) };
4544
+ function xn() {
4545
+ var o, u, i;
4546
+ const { sessionState: e } = Sr(), { messagesState: t } = Er(), r = ((o = e.session) == null ? void 0 : o.assignee.kind) === "ai", a = ((i = (u = t.messages) == null ? void 0 : u.at(-1)) == null ? void 0 : i.type) === "USER";
4547
+ return { isAwaitingBotReply: !!(t.isSendingMessageToAI || (r || e.isCreatingSession) && (t.isSendingMessage || a)) };
126
4548
  }
127
- function Y() {
128
- const { widgetCtx: e } = f();
4549
+ function Rn() {
4550
+ const { widgetCtx: e } = K();
129
4551
  return {
130
- routerState: w(e.routerCtx.state),
4552
+ routerState: de(e.routerCtx.state),
131
4553
  toSessionsScreen: e.routerCtx.toSessionsScreen,
132
4554
  toChatScreen: e.routerCtx.toChatScreen
133
4555
  };
134
4556
  }
135
- const p = /* @__PURE__ */ new Map();
136
- function _() {
137
- const [e, t] = b([]), {
138
- widgetCtx: { api: n }
139
- } = f();
140
- function o(s) {
141
- const r = s.map((d) => ({
142
- file: d,
143
- id: W(),
4557
+ const oe = /* @__PURE__ */ new Map();
4558
+ function On() {
4559
+ const [e, t] = Z([]), {
4560
+ widgetCtx: { api: r }
4561
+ } = K();
4562
+ function a(l) {
4563
+ const p = l.map((v) => ({
4564
+ file: v,
4565
+ id: kr(),
144
4566
  status: "pending",
145
4567
  progress: 0
146
4568
  }));
147
- t((d) => [...d, ...r]), r.forEach(l);
4569
+ t((v) => [...v, ...p]), p.forEach(u);
148
4570
  }
149
- function a(s, r) {
4571
+ function n(l, p) {
150
4572
  t(
151
- (d) => d.map((S) => S.id === s ? { ...S, ...r } : S)
4573
+ (v) => v.map((h) => h.id === l ? { ...h, ...p } : h)
152
4574
  );
153
4575
  }
154
- function i(s) {
155
- t((r) => r.filter((d) => d.id !== s));
4576
+ function o(l) {
4577
+ t((p) => p.filter((v) => v.id !== l));
156
4578
  }
157
- const l = async (s) => {
158
- const r = new AbortController();
159
- p.set(s.id, r);
4579
+ const u = async (l) => {
4580
+ const p = new AbortController();
4581
+ oe.set(l.id, p);
160
4582
  try {
161
4583
  t(
162
- (S) => S.map(
163
- (h) => h.id === s.id ? { ...h, status: "uploading", progress: 0 } : h
4584
+ (h) => h.map(
4585
+ (A) => A.id === l.id ? { ...A, status: "uploading", progress: 0 } : A
164
4586
  )
165
4587
  );
166
- const d = await n.uploadFile({
167
- file: s.file,
168
- abortSignal: r.signal,
169
- onProgress: (S) => {
170
- a(s.id, { progress: S });
4588
+ const v = await r.uploadFile({
4589
+ file: l.file,
4590
+ abortSignal: p.signal,
4591
+ onProgress: (h) => {
4592
+ n(l.id, { progress: h });
171
4593
  }
172
4594
  });
173
- a(s.id, {
4595
+ n(l.id, {
174
4596
  status: "success",
175
- fileUrl: d.fileUrl,
4597
+ fileUrl: v.fileUrl,
176
4598
  progress: 100
177
4599
  });
178
- } catch (d) {
179
- r.signal.aborted || a(s.id, {
4600
+ } catch (v) {
4601
+ p.signal.aborted || n(l.id, {
180
4602
  status: "error",
181
- error: d instanceof Error ? d.message : "Upload failed",
4603
+ error: v instanceof Error ? v.message : "Upload failed",
182
4604
  progress: 0
183
4605
  });
184
4606
  } finally {
185
- p.delete(s.id);
4607
+ oe.delete(l.id);
186
4608
  }
187
- }, u = (s) => {
188
- const r = p.get(s);
189
- r && (r.abort(), p.delete(s)), i(s);
190
- }, g = m(() => e.filter((s) => s.status === "success" && s.fileUrl), [e]);
4609
+ }, i = (l) => {
4610
+ const p = oe.get(l);
4611
+ p && (p.abort(), oe.delete(l)), o(l);
4612
+ }, g = X(() => e.filter((l) => l.status === "success" && l.fileUrl), [e]);
191
4613
  function c() {
192
- p.forEach((s) => s.abort()), p.clear(), t([]);
4614
+ oe.forEach((l) => l.abort()), oe.clear(), t([]);
193
4615
  }
194
- return C(() => () => {
195
- p.forEach((s) => s.abort()), p.clear();
4616
+ return $(() => () => {
4617
+ oe.forEach((l) => l.abort()), oe.clear();
196
4618
  }, []), {
197
4619
  allFiles: e,
198
- appendFiles: o,
199
- handleCancelUpload: u,
4620
+ appendFiles: a,
4621
+ handleCancelUpload: i,
200
4622
  successFiles: g,
201
4623
  emptyTheFiles: c,
202
- getFileById: (s) => e.find((r) => r.id === s),
203
- getUploadProgress: (s) => {
204
- var r;
205
- return ((r = e.find((d) => d.id === s)) == null ? void 0 : r.progress) ?? 0;
4624
+ getFileById: (l) => e.find((p) => p.id === l),
4625
+ getUploadProgress: (l) => {
4626
+ var p;
4627
+ return ((p = e.find((v) => v.id === l)) == null ? void 0 : p.progress) ?? 0;
206
4628
  },
207
- getUploadStatus: (s) => {
208
- var r;
209
- return (r = e.find((d) => d.id === s)) == null ? void 0 : r.status;
4629
+ getUploadStatus: (l) => {
4630
+ var p;
4631
+ return (p = e.find((v) => v.id === l)) == null ? void 0 : p.status;
210
4632
  },
211
- hasErrors: e.some((s) => s.status === "error"),
212
- isUploading: e.some((s) => s.status === "uploading")
213
- };
214
- }
215
- const M = v(null);
216
- function $({ children: e }) {
217
- const t = x(), [n, o] = b(() => t.inline ? !0 : t.isOpen ?? !1);
218
- return C(() => {
219
- o((a) => t.isOpen ?? a);
220
- }, [t.isOpen]), C(() => {
221
- const a = t.openAfterNSeconds;
222
- if (typeof a != "number" || isNaN(a))
4633
+ hasErrors: e.some((l) => l.status === "error"),
4634
+ isUploading: e.some((l) => l.status === "uploading")
4635
+ };
4636
+ }
4637
+ const Ir = Ue(null);
4638
+ function Pn({ children: e }) {
4639
+ const t = ze(), [r, a] = Z(() => t.inline ? !0 : t.isOpen ?? !1);
4640
+ return $(() => {
4641
+ a((n) => t.isOpen ?? n);
4642
+ }, [t.isOpen]), $(() => {
4643
+ const n = t.openAfterNSeconds;
4644
+ if (typeof n != "number" || isNaN(n))
223
4645
  return;
224
- const i = setTimeout(() => o(!0), a * 1e3);
225
- return () => clearTimeout(i);
226
- }, [t.openAfterNSeconds]), /* @__PURE__ */ E.createElement(M.Provider, { value: { isOpen: n, setIsOpen: o } }, e);
4646
+ const o = setTimeout(() => a(!0), n * 1e3);
4647
+ return () => clearTimeout(o);
4648
+ }, [t.openAfterNSeconds]), /* @__PURE__ */ V.createElement(Ir.Provider, { value: { isOpen: r, setIsOpen: a } }, e);
227
4649
  }
228
- function j() {
229
- const e = F(M);
4650
+ function Nn() {
4651
+ const e = qe(Ir);
230
4652
  if (!e)
231
4653
  throw new Error(
232
4654
  "useWidgetTrigger must be used within a WidgetTriggerProvider"
233
4655
  );
234
4656
  return e;
235
4657
  }
236
- function G() {
237
- var u, g;
238
- const { widgetCtx: e } = f(), { modesComponents: t } = x(), { sessionState: n } = A(), o = e.modes, a = (u = n.session) == null ? void 0 : u.modeId, i = o.find((c) => c.id === a), l = (g = t == null ? void 0 : t.find(
4658
+ function mn(e) {
4659
+ return e !== "fullscreen";
4660
+ }
4661
+ const _r = Ue(null);
4662
+ function jn({ children: e }) {
4663
+ var n, o;
4664
+ const { companion: t } = ze(), { dir: r } = cn(), { widgetCtx: a } = K();
4665
+ return /* @__PURE__ */ V.createElement(
4666
+ gn,
4667
+ {
4668
+ configuredDefaultLayout: t == null ? void 0 : t.defaultLayout,
4669
+ configuredLayouts: t == null ? void 0 : t.layouts,
4670
+ configuredSidebarSide: Dr((n = t == null ? void 0 : t.sidebar) == null ? void 0 : n.side, r),
4671
+ configuredSidebarMode: jr((o = t == null ? void 0 : t.sidebar) == null ? void 0 : o.mode),
4672
+ storage: a.storageCtx
4673
+ },
4674
+ e
4675
+ );
4676
+ }
4677
+ function gn({
4678
+ configuredDefaultLayout: e,
4679
+ configuredLayouts: t,
4680
+ configuredSidebarSide: r,
4681
+ configuredSidebarMode: a,
4682
+ storage: n,
4683
+ children: o
4684
+ }) {
4685
+ const u = Lr(t), i = Fr(
4686
+ e,
4687
+ u
4688
+ ), g = u.join("|"), [c, l] = Z(i), [p, v] = Z({
4689
+ defaultLayout: i,
4690
+ allowedLayoutsKey: g
4691
+ });
4692
+ (p.defaultLayout !== i || p.allowedLayoutsKey !== g) && (v({ defaultLayout: i, allowedLayoutsKey: g }), (p.defaultLayout !== i || !u.includes(c)) && l(i));
4693
+ const h = (y) => {
4694
+ l((w) => {
4695
+ const D = typeof y == "function" ? y(w) : y;
4696
+ return u.includes(D) ? D : w;
4697
+ });
4698
+ }, A = j(u);
4699
+ A.current = u;
4700
+ const M = (y) => {
4701
+ h(y), A.current.includes(y) && mn(y) && (n == null || n.setCompanionLayout(y).catch(() => {
4702
+ }));
4703
+ }, [S, I] = Z(r), [_, R] = Z(a), [d, f] = Z({
4704
+ side: r,
4705
+ mode: a
4706
+ });
4707
+ (d.side !== r || d.mode !== a) && (f({
4708
+ side: r,
4709
+ mode: a
4710
+ }), d.side !== r && I(r), d.mode !== a && R(a)), $(() => {
4711
+ if (!n) return;
4712
+ let y = !1;
4713
+ return n.getCompanionLayout().then((w) => {
4714
+ y || !w || A.current.includes(w) && l(w);
4715
+ }).catch(() => {
4716
+ }), n.getCompanionSidebarSide().then((w) => {
4717
+ !y && w && I(w);
4718
+ }).catch(() => {
4719
+ }), n.getCompanionSidebarMode().then((w) => {
4720
+ !y && w && R(w);
4721
+ }).catch(() => {
4722
+ }), () => {
4723
+ y = !0;
4724
+ };
4725
+ }, [n]);
4726
+ const m = U(
4727
+ (y) => {
4728
+ I(y), n == null || n.setCompanionSidebarSide(y).catch(() => {
4729
+ });
4730
+ },
4731
+ [n]
4732
+ ), b = U(
4733
+ (y) => {
4734
+ R(y), n == null || n.setCompanionSidebarMode(y).catch(() => {
4735
+ });
4736
+ },
4737
+ [n]
4738
+ );
4739
+ return /* @__PURE__ */ V.createElement(
4740
+ _r.Provider,
4741
+ {
4742
+ value: {
4743
+ layout: c,
4744
+ setLayout: h,
4745
+ setLayoutPreference: M,
4746
+ allowedLayouts: u,
4747
+ defaultLayout: i,
4748
+ sidebarSide: S,
4749
+ setSidebarSide: m,
4750
+ sidebarMode: _,
4751
+ setSidebarMode: b
4752
+ }
4753
+ },
4754
+ o
4755
+ );
4756
+ }
4757
+ function Dn() {
4758
+ const e = qe(_r);
4759
+ if (!e)
4760
+ throw new Error(
4761
+ "useWidgetLayout must be used within a WidgetLayoutProvider"
4762
+ );
4763
+ return e;
4764
+ }
4765
+ function Ln() {
4766
+ var i, g;
4767
+ const { widgetCtx: e } = K(), { modesComponents: t } = ze(), { sessionState: r } = Sr(), a = e.modes, n = (i = r.session) == null ? void 0 : i.modeId, o = a.find((c) => c.id === n), u = (g = t == null ? void 0 : t.find(
239
4768
  (c) => {
240
- var s, r;
4769
+ var l, p;
241
4770
  return [
242
- (i == null ? void 0 : i.id) || "",
243
- ((s = i == null ? void 0 : i.name) == null ? void 0 : s.toLowerCase()) || "",
244
- ((r = i == null ? void 0 : i.slug) == null ? void 0 : r.toLowerCase()) || ""
4771
+ (o == null ? void 0 : o.id) || "",
4772
+ ((l = o == null ? void 0 : o.name) == null ? void 0 : l.toLowerCase()) || "",
4773
+ ((p = o == null ? void 0 : o.slug) == null ? void 0 : p.toLowerCase()) || ""
245
4774
  ].includes(c.key.toLowerCase());
246
4775
  }
247
4776
  )) == null ? void 0 : g.component;
248
4777
  return {
249
- modes: o,
4778
+ modes: a,
250
4779
  modesComponents: t,
251
- activeModeId: a,
252
- activeMode: i,
253
- Component: l
4780
+ activeModeId: n,
4781
+ activeMode: o,
4782
+ Component: u
254
4783
  };
255
4784
  }
256
- function H() {
257
- const { widgetCtx: e } = f(), {
4785
+ function Fn() {
4786
+ const { widgetCtx: e } = K(), {
258
4787
  messagesState: { messages: t }
259
- } = R(), {
260
- csatRequestedMessage: n,
261
- isCsatRequested: o,
262
- csatSubmittedMessage: a,
263
- isCsatSubmitted: i,
264
- submittedScore: l,
265
- submittedFeedback: u
266
- } = m(() => {
4788
+ } = Er(), {
4789
+ csatRequestedMessage: r,
4790
+ isCsatRequested: a,
4791
+ csatSubmittedMessage: n,
4792
+ isCsatSubmitted: o,
4793
+ submittedScore: u,
4794
+ submittedFeedback: i
4795
+ } = X(() => {
267
4796
  const g = t.find(
268
- (s) => s.type === "SYSTEM" && s.subtype === "csat_requested"
4797
+ (l) => l.type === "SYSTEM" && l.subtype === "csat_requested"
269
4798
  ), c = t.findLast(
270
- (s) => s.type === "SYSTEM" && s.subtype === "csat_submitted"
4799
+ (l) => l.type === "SYSTEM" && l.subtype === "csat_submitted"
271
4800
  );
272
4801
  return {
273
4802
  csatRequestedMessage: g,
@@ -280,29 +4809,66 @@ function H() {
280
4809
  }, [t]);
281
4810
  return {
282
4811
  submitCsat: e.csatCtx.submitCsat,
283
- csatRequestedMessage: n,
284
- isCsatRequested: o,
285
- csatSubmittedMessage: a,
286
- isCsatSubmitted: i,
287
- submittedScore: l,
288
- submittedFeedback: u
4812
+ csatRequestedMessage: r,
4813
+ isCsatRequested: a,
4814
+ csatSubmittedMessage: n,
4815
+ isCsatSubmitted: o,
4816
+ submittedScore: u,
4817
+ submittedFeedback: i
4818
+ };
4819
+ }
4820
+ function kn(e) {
4821
+ const { widgetCtx: t } = K(), r = t.dictationCtx, a = de(r.state), n = j(e);
4822
+ n.current = e;
4823
+ const o = U(() => {
4824
+ r.start({
4825
+ getValue: () => n.current.getValue(),
4826
+ setValue: (i) => n.current.setValue(i),
4827
+ onSend: () => {
4828
+ var i, g;
4829
+ return (g = (i = n.current).onSend) == null ? void 0 : g.call(i);
4830
+ }
4831
+ });
4832
+ }, [r]), u = U(() => {
4833
+ r.isActive() ? r.stop() : o();
4834
+ }, [r, o]);
4835
+ return $(() => () => r.stop(), [r]), {
4836
+ enabled: t.features.dictation,
4837
+ status: a.status,
4838
+ error: a.error,
4839
+ isActive: a.status !== "idle",
4840
+ /** 0..1 mic level — read inside a rAF loop, not a render. */
4841
+ levelRef: r.levelRef,
4842
+ start: o,
4843
+ stop: r.stop,
4844
+ toggle: u,
4845
+ prewarm: r.prewarm
289
4846
  };
290
4847
  }
291
4848
  export {
292
- B as WidgetProvider,
293
- $ as WidgetTriggerProvider,
294
- x as useConfig,
295
- D as useContact,
296
- H as useCsat,
297
- I as useDocumentDir,
298
- z as useIsAwaitingBotReply,
299
- R as useMessages,
300
- G as useModes,
301
- w as usePrimitiveState,
302
- A as useSessions,
303
- _ as useUploadFiles,
304
- f as useWidget,
305
- Y as useWidgetRouter,
306
- j as useWidgetTrigger
4849
+ Xe as HOST_CONTEXT_CHANGED_EVENT,
4850
+ jn as WidgetLayoutProvider,
4851
+ wn as WidgetProvider,
4852
+ Pn as WidgetTriggerProvider,
4853
+ _n as formatAskQuestionsAnswers,
4854
+ on as useAgentChatUi,
4855
+ Mn as useBot,
4856
+ ze as useConfig,
4857
+ An as useContact,
4858
+ Fn as useCsat,
4859
+ kn as useDictation,
4860
+ Tn as useDisplayMode,
4861
+ cn as useDocumentDir,
4862
+ Cn as useHostLocation,
4863
+ xn as useIsAwaitingBotReply,
4864
+ Er as useMessages,
4865
+ Ln as useModes,
4866
+ de as usePrimitiveState,
4867
+ Sr as useSessions,
4868
+ On as useUploadFiles,
4869
+ K as useWidget,
4870
+ Dn as useWidgetLayout,
4871
+ Rn as useWidgetRouter,
4872
+ Nn as useWidgetTrigger
307
4873
  };
308
4874
  //# sourceMappingURL=index.js.map