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

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