@mastra/react 0.2.6-alpha.0 → 0.2.7-alpha.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 (23) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/dist/{chunk-REDZDNFN-TfJ4yMVk.js → chunk-REDZDNFN-B3BKm5Q3.js} +2 -2
  3. package/dist/{chunk-REDZDNFN-TfJ4yMVk.js.map → chunk-REDZDNFN-B3BKm5Q3.js.map} +1 -1
  4. package/dist/{chunk-REDZDNFN-C4VwKzrd.cjs → chunk-REDZDNFN-B6_m0Vw5.cjs} +2 -2
  5. package/dist/{chunk-REDZDNFN-C4VwKzrd.cjs.map → chunk-REDZDNFN-B6_m0Vw5.cjs.map} +1 -1
  6. package/dist/{index-CU6GBOIY.cjs → index-0ViTRi6s.cjs} +1449 -1345
  7. package/dist/index-0ViTRi6s.cjs.map +1 -0
  8. package/dist/{index-DKjW1068.js → index-D3vBmpgO.js} +1449 -1345
  9. package/dist/index-D3vBmpgO.js.map +1 -0
  10. package/dist/index.cjs +1 -1
  11. package/dist/index.js +1 -1
  12. package/dist/src/lib/ai-sdk/types.d.ts +9 -0
  13. package/dist/{token-6GSAFR2W-XRCSVUPZ-C2rqLNj8.cjs → token-6GSAFR2W-XRCSVUPZ-DHFPWxwn.cjs} +3 -3
  14. package/dist/{token-6GSAFR2W-XRCSVUPZ-C2rqLNj8.cjs.map → token-6GSAFR2W-XRCSVUPZ-DHFPWxwn.cjs.map} +1 -1
  15. package/dist/{token-6GSAFR2W-XRCSVUPZ-Cgcu7avO.js → token-6GSAFR2W-XRCSVUPZ-PJRK45Cx.js} +3 -3
  16. package/dist/{token-6GSAFR2W-XRCSVUPZ-Cgcu7avO.js.map → token-6GSAFR2W-XRCSVUPZ-PJRK45Cx.js.map} +1 -1
  17. package/dist/{token-util-NEHG7TUY-U7CX7GS4-C59wA2lQ.cjs → token-util-NEHG7TUY-U7CX7GS4-B0wfFQ5e.cjs} +2 -2
  18. package/dist/{token-util-NEHG7TUY-U7CX7GS4-C59wA2lQ.cjs.map → token-util-NEHG7TUY-U7CX7GS4-B0wfFQ5e.cjs.map} +1 -1
  19. package/dist/{token-util-NEHG7TUY-U7CX7GS4-jJSXEovt.js → token-util-NEHG7TUY-U7CX7GS4-C_BDhp1r.js} +2 -2
  20. package/dist/{token-util-NEHG7TUY-U7CX7GS4-jJSXEovt.js.map → token-util-NEHG7TUY-U7CX7GS4-C_BDhp1r.js.map} +1 -1
  21. package/package.json +3 -3
  22. package/dist/index-CU6GBOIY.cjs.map +0 -1
  23. package/dist/index-DKjW1068.js.map +0 -1
@@ -51,1163 +51,347 @@ const MastraReactProvider = ({ children, baseUrl, headers, apiPrefix }) => {
51
51
  return /* @__PURE__ */ jsxRuntime.jsx(MastraClientProvider, { baseUrl, headers, apiPrefix, children });
52
52
  };
53
53
 
54
- const mapWorkflowStreamChunkToWatchResult = (prev, chunk) => {
55
- if (chunk.type === "workflow-start") {
56
- return {
57
- input: prev?.input,
58
- status: "running",
59
- steps: prev?.steps || {}
60
- };
54
+ // src/request-context/index.ts
55
+ var RequestContext = class {
56
+ registry = /* @__PURE__ */ new Map();
57
+ constructor(iterable) {
58
+ this.registry = new Map(iterable);
61
59
  }
62
- if (chunk.type === "workflow-canceled") {
63
- return {
64
- ...prev,
65
- status: "canceled"
66
- };
60
+ /**
61
+ * set a value with strict typing if `Values` is a Record and the key exists in it.
62
+ */
63
+ set(key, value) {
64
+ this.registry.set(key, value);
67
65
  }
68
- if (chunk.type === "workflow-finish") {
69
- const finalStatus = chunk.payload.workflowStatus;
70
- const prevSteps = prev?.steps ?? {};
71
- const lastStep = Object.values(prevSteps).pop();
72
- return {
73
- ...prev,
74
- status: chunk.payload.workflowStatus,
75
- ...finalStatus === "success" && lastStep?.status === "success" ? { result: lastStep?.output } : finalStatus === "failed" && lastStep?.status === "failed" ? { error: lastStep?.error } : finalStatus === "tripwire" && chunk.payload.tripwire ? { tripwire: chunk.payload.tripwire } : {}
76
- };
66
+ /**
67
+ * Get a value with its type
68
+ */
69
+ get(key) {
70
+ return this.registry.get(key);
77
71
  }
78
- const { stepCallId, stepName, ...newPayload } = chunk.payload ?? {};
79
- const newSteps = {
80
- ...prev?.steps,
81
- [chunk.payload.id]: {
82
- ...prev?.steps?.[chunk.payload.id],
83
- ...newPayload
84
- }
85
- };
86
- if (chunk.type === "workflow-step-start") {
87
- return {
88
- ...prev,
89
- steps: newSteps
90
- };
72
+ /**
73
+ * Check if a key exists in the container
74
+ */
75
+ has(key) {
76
+ return this.registry.has(key);
91
77
  }
92
- if (chunk.type === "workflow-step-suspended") {
93
- const suspendedStepIds = Object.entries(newSteps).flatMap(
94
- ([stepId, stepResult]) => {
95
- if (stepResult?.status === "suspended") {
96
- const nestedPath = stepResult?.suspendPayload?.__workflow_meta?.path;
97
- return nestedPath ? [[stepId, ...nestedPath]] : [[stepId]];
98
- }
99
- return [];
100
- }
101
- );
102
- return {
103
- ...prev,
104
- status: "suspended",
105
- steps: newSteps,
106
- suspendPayload: chunk.payload.suspendPayload,
107
- suspended: suspendedStepIds
108
- };
78
+ /**
79
+ * Delete a value by key
80
+ */
81
+ delete(key) {
82
+ return this.registry.delete(key);
109
83
  }
110
- if (chunk.type === "workflow-step-waiting") {
111
- return {
112
- ...prev,
113
- status: "waiting",
114
- steps: newSteps
115
- };
84
+ /**
85
+ * Clear all values from the container
86
+ */
87
+ clear() {
88
+ this.registry.clear();
116
89
  }
117
- if (chunk.type === "workflow-step-progress") {
118
- const progressSteps = {
119
- ...prev?.steps,
120
- [chunk.payload.id]: {
121
- ...prev?.steps?.[chunk.payload.id],
122
- foreachProgress: {
123
- completedCount: chunk.payload.completedCount,
124
- totalCount: chunk.payload.totalCount,
125
- currentIndex: chunk.payload.currentIndex,
126
- iterationStatus: chunk.payload.iterationStatus,
127
- iterationOutput: chunk.payload.iterationOutput
128
- }
129
- }
130
- };
131
- return {
132
- ...prev,
133
- steps: progressSteps
134
- };
90
+ /**
91
+ * Get all keys in the container
92
+ */
93
+ keys() {
94
+ return this.registry.keys();
135
95
  }
136
- if (chunk.type === "workflow-step-result") {
137
- return {
138
- ...prev,
139
- steps: newSteps
140
- };
96
+ /**
97
+ * Get all values in the container
98
+ */
99
+ values() {
100
+ return this.registry.values();
141
101
  }
142
- return prev;
143
- };
144
- const toUIMessage = ({ chunk, conversation, metadata }) => {
145
- const result = [...conversation];
146
- if (chunk.type.startsWith("data-")) {
147
- const lastMessage = result[result.length - 1];
148
- if (!lastMessage || lastMessage.role !== "assistant") {
149
- const newMessage = {
150
- id: `data-${chunk.runId}-${Date.now()}`,
151
- role: "assistant",
152
- parts: [
153
- {
154
- type: chunk.type,
155
- data: "data" in chunk ? chunk.data : void 0
156
- }
157
- ],
158
- metadata
159
- };
160
- return [...result, newMessage];
161
- }
162
- const updatedMessage = {
163
- ...lastMessage,
164
- parts: [
165
- ...lastMessage.parts,
166
- {
167
- type: chunk.type,
168
- data: "data" in chunk ? chunk.data : void 0
169
- }
170
- ]
171
- };
172
- return [...result.slice(0, -1), updatedMessage];
102
+ /**
103
+ * Get all entries in the container.
104
+ * Returns a discriminated union of tuples for proper type narrowing when iterating.
105
+ */
106
+ entries() {
107
+ return this.registry.entries();
173
108
  }
174
- switch (chunk.type) {
175
- case "tripwire": {
176
- const newMessage = {
177
- id: `tripwire-${chunk.runId + Date.now()}`,
178
- role: "assistant",
179
- parts: [
180
- {
181
- type: "text",
182
- text: chunk.payload.reason
183
- }
184
- ],
185
- metadata: {
186
- ...metadata,
187
- status: "tripwire",
188
- tripwire: {
189
- retry: chunk.payload.retry,
190
- tripwirePayload: chunk.payload.metadata,
191
- processorId: chunk.payload.processorId
192
- }
193
- }
194
- };
195
- return [...result, newMessage];
196
- }
197
- case "start": {
198
- const newMessage = {
199
- id: typeof chunk.payload.messageId === "string" ? chunk.payload.messageId : `start-${chunk.runId + Date.now()}`,
200
- role: "assistant",
201
- parts: [],
202
- metadata
203
- };
204
- return [...result, newMessage];
109
+ /**
110
+ * Get the size of the container
111
+ */
112
+ size() {
113
+ return this.registry.size;
114
+ }
115
+ /**
116
+ * Execute a function for each entry in the container.
117
+ * The callback receives properly typed key-value pairs.
118
+ */
119
+ forEach(callbackfn) {
120
+ this.registry.forEach(callbackfn);
121
+ }
122
+ /**
123
+ * Custom JSON serialization method.
124
+ * Converts the internal Map to a plain object for proper JSON serialization.
125
+ * Non-serializable values (e.g., RPC proxies, functions, circular references)
126
+ * are skipped to prevent serialization errors when storing to database.
127
+ */
128
+ toJSON() {
129
+ const result = {};
130
+ for (const [key, value] of this.registry.entries()) {
131
+ if (this.isSerializable(value)) {
132
+ result[key] = value;
133
+ }
205
134
  }
206
- case "text-start": {
207
- const lastMessage = result[result.length - 1];
208
- if (!lastMessage || lastMessage.role !== "assistant") return result;
209
- const parts = [...lastMessage.parts];
210
- const textId = chunk.payload.id || `text-${Date.now()}`;
211
- const newTextPart = {
212
- type: "text",
213
- text: "",
214
- state: "streaming",
215
- textId,
216
- providerMetadata: chunk.payload.providerMetadata
217
- };
218
- parts.push(newTextPart);
219
- return [
220
- ...result.slice(0, -1),
221
- {
222
- ...lastMessage,
223
- parts
224
- }
225
- ];
135
+ return result;
136
+ }
137
+ /**
138
+ * Check if a value can be safely serialized to JSON.
139
+ */
140
+ isSerializable(value) {
141
+ if (value === null || value === void 0) return true;
142
+ if (typeof value === "function") return false;
143
+ if (typeof value === "symbol") return false;
144
+ if (typeof value !== "object") return true;
145
+ try {
146
+ JSON.stringify(value);
147
+ return true;
148
+ } catch {
149
+ return false;
226
150
  }
227
- case "text-delta": {
228
- const lastMessage = result[result.length - 1];
229
- if (!lastMessage || lastMessage.role !== "assistant") return result;
230
- const parts = [...lastMessage.parts];
231
- const textId = chunk.payload.id;
232
- let textPartIndex = textId ? parts.findLastIndex((part) => part.type === "text" && part.textId === textId) : -1;
233
- if (textPartIndex === -1) {
234
- textPartIndex = parts.findLastIndex(
235
- (part) => part.type === "text" && part.state === "streaming"
236
- );
237
- }
238
- if (textPartIndex === -1) {
239
- const newTextPart = {
240
- type: "text",
241
- text: chunk.payload.text,
242
- state: "streaming",
243
- textId,
244
- providerMetadata: chunk.payload.providerMetadata
245
- };
246
- parts.push(newTextPart);
247
- } else {
248
- const textPart = parts[textPartIndex];
249
- if (textPart.type === "text") {
250
- const extendedTextPart = textPart;
251
- const updatedTextPart = {
252
- ...extendedTextPart,
253
- text: extendedTextPart.text + chunk.payload.text,
254
- state: "streaming"
255
- };
256
- parts[textPartIndex] = updatedTextPart;
257
- }
258
- }
259
- return [
260
- ...result.slice(0, -1),
261
- {
262
- ...lastMessage,
263
- parts
264
- }
265
- ];
266
- }
267
- case "reasoning-delta": {
268
- const lastMessage = result[result.length - 1];
269
- if (!lastMessage || lastMessage.role !== "assistant") {
270
- const newMessage = {
271
- id: `reasoning-${chunk.runId + Date.now()}`,
272
- role: "assistant",
273
- parts: [
274
- {
275
- type: "reasoning",
276
- text: chunk.payload.text,
277
- state: "streaming",
278
- providerMetadata: chunk.payload.providerMetadata
279
- }
280
- ],
281
- metadata
282
- };
283
- return [...result, newMessage];
151
+ }
152
+ /**
153
+ * Get all values as a typed object for destructuring.
154
+ * Returns Record<string, any> when untyped, or the Values type when typed.
155
+ *
156
+ * @example
157
+ * ```typescript
158
+ * const ctx = new RequestContext<{ userId: string; apiKey: string }>();
159
+ * ctx.set('userId', 'user-123');
160
+ * ctx.set('apiKey', 'key-456');
161
+ * const { userId, apiKey } = ctx.all;
162
+ * ```
163
+ */
164
+ get all() {
165
+ return Object.fromEntries(this.registry);
166
+ }
167
+ };
168
+
169
+ function getDefaultExportFromCjs (x) {
170
+ return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
171
+ }
172
+
173
+ var __create$4 = Object.create;
174
+ var __defProp$6 = Object.defineProperty;
175
+ var __getOwnPropDesc$4 = Object.getOwnPropertyDescriptor;
176
+ var __getOwnPropNames$4 = Object.getOwnPropertyNames;
177
+ var __getProtoOf$4 = Object.getPrototypeOf;
178
+ var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
179
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
180
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
181
+ }) : x)(function(x) {
182
+ if (typeof require !== "undefined") return require.apply(this, arguments);
183
+ throw Error('Dynamic require of "' + x + '" is not supported');
184
+ });
185
+ var __commonJS$4 = (cb, mod) => function __require2() {
186
+ return mod || (0, cb[__getOwnPropNames$4(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
187
+ };
188
+ var __copyProps$4 = (to, from, except, desc) => {
189
+ if (from && typeof from === "object" || typeof from === "function") {
190
+ for (let key of __getOwnPropNames$4(from))
191
+ if (!__hasOwnProp$4.call(to, key) && key !== except)
192
+ __defProp$6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc$4(from, key)) || desc.enumerable });
193
+ }
194
+ return to;
195
+ };
196
+ var __toESM$3 = (mod, isNodeMode, target) => (target = mod != null ? __create$4(__getProtoOf$4(mod)) : {}, __copyProps$4(
197
+ // If the importer is in node compatibility mode or this is not an ESM
198
+ // file that has been converted to a CommonJS file using a Babel-
199
+ // compatible transform (i.e. "__esModule" has not been set), then set
200
+ // "default" to the CommonJS "module.exports" for node compatibility.
201
+ __defProp$6(target, "default", { value: mod, enumerable: true }) ,
202
+ mod
203
+ ));
204
+
205
+ // ../_vendored/ai_v5/dist/chunk-7D4SUZUM.js
206
+ var __create$3 = Object.create;
207
+ var __defProp$5 = Object.defineProperty;
208
+ var __getOwnPropDesc$3 = Object.getOwnPropertyDescriptor;
209
+ var __getOwnPropNames$3 = Object.getOwnPropertyNames;
210
+ var __getProtoOf$3 = Object.getPrototypeOf;
211
+ var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
212
+ var __require2 = /* @__PURE__ */ ((x) => typeof __require !== "undefined" ? __require : typeof Proxy !== "undefined" ? new Proxy(x, {
213
+ get: (a, b) => (typeof __require !== "undefined" ? __require : a)[b]
214
+ }) : x)(function(x) {
215
+ if (typeof __require !== "undefined") return __require.apply(this, arguments);
216
+ throw Error('Dynamic require of "' + x + '" is not supported');
217
+ });
218
+ var __commonJS$3 = (cb, mod) => function __require22() {
219
+ return mod || (0, cb[__getOwnPropNames$3(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
220
+ };
221
+ var __copyProps$3 = (to, from, except, desc) => {
222
+ if (from && typeof from === "object" || typeof from === "function") {
223
+ for (let key of __getOwnPropNames$3(from))
224
+ if (!__hasOwnProp$3.call(to, key) && key !== except)
225
+ __defProp$5(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc$3(from, key)) || desc.enumerable });
226
+ }
227
+ return to;
228
+ };
229
+ var __toESM$2 = (mod, isNodeMode, target) => (target = mod != null ? __create$3(__getProtoOf$3(mod)) : {}, __copyProps$3(
230
+ // If the importer is in node compatibility mode or this is not an ESM
231
+ // file that has been converted to a CommonJS file using a Babel-
232
+ // compatible transform (i.e. "__esModule" has not been set), then set
233
+ // "default" to the CommonJS "module.exports" for node compatibility.
234
+ __defProp$5(target, "default", { value: mod, enumerable: true }) ,
235
+ mod
236
+ ));
237
+
238
+ // ../_vendored/ai_v5/dist/chunk-TLQKI65U.js
239
+ var require_token_error = __commonJS$3({
240
+ "../../../node_modules/.pnpm/@vercel+oidc@3.0.5/node_modules/@vercel/oidc/dist/token-error.js"(exports$1, module) {
241
+ var __defProp2 = Object.defineProperty;
242
+ var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
243
+ var __getOwnPropNames2 = Object.getOwnPropertyNames;
244
+ var __hasOwnProp2 = Object.prototype.hasOwnProperty;
245
+ var __export = (target, all) => {
246
+ for (var name in all)
247
+ __defProp2(target, name, { get: all[name], enumerable: true });
248
+ };
249
+ var __copyProps2 = (to, from, except, desc) => {
250
+ if (from && typeof from === "object" || typeof from === "function") {
251
+ for (let key of __getOwnPropNames2(from))
252
+ if (!__hasOwnProp2.call(to, key) && key !== except)
253
+ __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
284
254
  }
285
- const parts = [...lastMessage.parts];
286
- let reasoningPartIndex = parts.findIndex((part) => part.type === "reasoning");
287
- if (reasoningPartIndex === -1) {
288
- parts.push({
289
- type: "reasoning",
290
- text: chunk.payload.text,
291
- state: "streaming",
292
- providerMetadata: chunk.payload.providerMetadata
293
- });
294
- } else {
295
- const reasoningPart = parts[reasoningPartIndex];
296
- if (reasoningPart.type === "reasoning") {
297
- parts[reasoningPartIndex] = {
298
- ...reasoningPart,
299
- text: reasoningPart.text + chunk.payload.text,
300
- state: "streaming"
301
- };
302
- }
255
+ return to;
256
+ };
257
+ var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
258
+ var token_error_exports = {};
259
+ __export(token_error_exports, {
260
+ VercelOidcTokenError: () => VercelOidcTokenError
261
+ });
262
+ module.exports = __toCommonJS(token_error_exports);
263
+ var VercelOidcTokenError = class extends Error {
264
+ constructor(message, cause) {
265
+ super(message);
266
+ this.name = "VercelOidcTokenError";
267
+ this.cause = cause;
303
268
  }
304
- return [
305
- ...result.slice(0, -1),
306
- {
307
- ...lastMessage,
308
- parts
269
+ toString() {
270
+ if (this.cause) {
271
+ return `${this.name}: ${this.message}: ${this.cause}`;
309
272
  }
310
- ];
311
- }
312
- case "tool-call": {
313
- const lastMessage = result[result.length - 1];
314
- if (!lastMessage || lastMessage.role !== "assistant") {
315
- const newMessage = {
316
- id: `tool-call-${chunk.runId + Date.now()}`,
317
- role: "assistant",
318
- parts: [
319
- {
320
- type: "dynamic-tool",
321
- toolName: chunk.payload.toolName,
322
- toolCallId: chunk.payload.toolCallId,
323
- state: "input-available",
324
- input: chunk.payload.args,
325
- callProviderMetadata: chunk.payload.providerMetadata
326
- }
327
- ],
328
- metadata
329
- };
330
- return [...result, newMessage];
331
- }
332
- const parts = [...lastMessage.parts];
333
- parts.push({
334
- type: "dynamic-tool",
335
- toolName: chunk.payload.toolName,
336
- toolCallId: chunk.payload.toolCallId,
337
- state: "input-available",
338
- input: chunk.payload.args,
339
- callProviderMetadata: chunk.payload.providerMetadata
340
- });
341
- return [
342
- ...result.slice(0, -1),
343
- {
344
- ...lastMessage,
345
- parts
346
- }
347
- ];
348
- }
349
- case "tool-error":
350
- case "tool-result": {
351
- const lastMessage = result[result.length - 1];
352
- if (!lastMessage || lastMessage.role !== "assistant") return result;
353
- const parts = [...lastMessage.parts];
354
- const toolPartIndex = parts.findIndex(
355
- (part) => (part.type === "dynamic-tool" || typeof part.type === "string" && part.type.startsWith("tool-")) && "toolCallId" in part && part.toolCallId === chunk.payload.toolCallId
356
- );
357
- if (toolPartIndex !== -1) {
358
- const toolPart = parts[toolPartIndex];
359
- if (toolPart.type === "dynamic-tool" || typeof toolPart.type === "string" && toolPart.type.startsWith("tool-")) {
360
- const toolName = "toolName" in toolPart && typeof toolPart.toolName === "string" ? toolPart.toolName : toolPart.type.startsWith("tool-") ? toolPart.type.substring(5) : "";
361
- const toolCallId = toolPart.toolCallId;
362
- if (chunk.type === "tool-result" && chunk.payload.isError || chunk.type === "tool-error") {
363
- const error = chunk.type === "tool-error" ? chunk.payload.error : chunk.payload.result;
364
- parts[toolPartIndex] = {
365
- type: "dynamic-tool",
366
- toolName,
367
- toolCallId,
368
- state: "output-error",
369
- input: toolPart.input,
370
- errorText: typeof error === "string" ? error : error instanceof Error ? error.message : error?.message ?? String(error),
371
- callProviderMetadata: chunk.payload.providerMetadata
372
- };
373
- } else {
374
- const isWorkflow = Boolean(chunk.payload.result?.result?.steps);
375
- const isAgent = chunk?.from === "AGENT";
376
- let output;
377
- if (isWorkflow) {
378
- output = chunk.payload.result?.result;
379
- } else if (isAgent) {
380
- output = parts[toolPartIndex].output ?? chunk.payload.result;
381
- } else {
382
- output = chunk.payload.result;
383
- }
384
- parts[toolPartIndex] = {
385
- type: "dynamic-tool",
386
- toolName,
387
- toolCallId,
388
- state: "output-available",
389
- input: toolPart.input,
390
- output,
391
- callProviderMetadata: chunk.payload.providerMetadata
392
- };
393
- }
394
- }
395
- }
396
- return [
397
- ...result.slice(0, -1),
398
- {
399
- ...lastMessage,
400
- parts
401
- }
402
- ];
403
- }
404
- case "tool-output": {
405
- const lastMessage = result[result.length - 1];
406
- if (!lastMessage || lastMessage.role !== "assistant") return result;
407
- const parts = [...lastMessage.parts];
408
- const toolPartIndex = parts.findIndex(
409
- (part) => (part.type === "dynamic-tool" || typeof part.type === "string" && part.type.startsWith("tool-")) && "toolCallId" in part && part.toolCallId === chunk.payload.toolCallId
410
- );
411
- if (toolPartIndex !== -1) {
412
- const toolPart = parts[toolPartIndex];
413
- if (toolPart.type === "dynamic-tool" || typeof toolPart.type === "string" && toolPart.type.startsWith("tool-")) {
414
- const toolName = "toolName" in toolPart && typeof toolPart.toolName === "string" ? toolPart.toolName : typeof toolPart.type === "string" && toolPart.type.startsWith("tool-") ? toolPart.type.substring(5) : "";
415
- const toolCallId = toolPart.toolCallId;
416
- const input = toolPart.input;
417
- if (chunk.payload.output?.type?.startsWith("workflow-")) {
418
- const existingWorkflowState = toolPart.output || {};
419
- const updatedWorkflowState = mapWorkflowStreamChunkToWatchResult(
420
- existingWorkflowState,
421
- chunk.payload.output
422
- );
423
- parts[toolPartIndex] = {
424
- type: "dynamic-tool",
425
- toolName,
426
- toolCallId,
427
- state: "input-streaming",
428
- input,
429
- output: updatedWorkflowState
430
- };
431
- } else if (chunk.payload.output?.from === "AGENT" || chunk.payload.output?.from === "USER" && chunk.payload.output?.payload?.output?.type?.startsWith("workflow-")) {
432
- return toUIMessageFromAgent(chunk.payload.output, conversation);
433
- } else {
434
- const currentOutput = toolPart.output || [];
435
- const existingOutput = Array.isArray(currentOutput) ? currentOutput : [];
436
- parts[toolPartIndex] = {
437
- type: "dynamic-tool",
438
- toolName,
439
- toolCallId,
440
- state: "input-streaming",
441
- input,
442
- output: [...existingOutput, chunk.payload.output]
443
- };
444
- }
445
- }
446
- }
447
- return [
448
- ...result.slice(0, -1),
449
- {
450
- ...lastMessage,
451
- parts
452
- }
453
- ];
454
- }
455
- case "source": {
456
- const lastMessage = result[result.length - 1];
457
- if (!lastMessage || lastMessage.role !== "assistant") return result;
458
- const parts = [...lastMessage.parts];
459
- if (chunk.payload.sourceType === "url") {
460
- parts.push({
461
- type: "source-url",
462
- sourceId: chunk.payload.id,
463
- url: chunk.payload.url || "",
464
- title: chunk.payload.title,
465
- providerMetadata: chunk.payload.providerMetadata
466
- });
467
- } else if (chunk.payload.sourceType === "document") {
468
- parts.push({
469
- type: "source-document",
470
- sourceId: chunk.payload.id,
471
- mediaType: chunk.payload.mimeType || "application/octet-stream",
472
- title: chunk.payload.title,
473
- filename: chunk.payload.filename,
474
- providerMetadata: chunk.payload.providerMetadata
475
- });
476
- }
477
- return [
478
- ...result.slice(0, -1),
479
- {
480
- ...lastMessage,
481
- parts
482
- }
483
- ];
484
- }
485
- case "file": {
486
- const lastMessage = result[result.length - 1];
487
- if (!lastMessage || lastMessage.role !== "assistant") return result;
488
- const parts = [...lastMessage.parts];
489
- let url;
490
- if (typeof chunk.payload.data === "string") {
491
- url = chunk.payload.base64 ? `data:${chunk.payload.mimeType};base64,${chunk.payload.data}` : `data:${chunk.payload.mimeType},${encodeURIComponent(chunk.payload.data)}`;
492
- } else {
493
- const base64 = btoa(String.fromCharCode(...chunk.payload.data));
494
- url = `data:${chunk.payload.mimeType};base64,${base64}`;
495
- }
496
- parts.push({
497
- type: "file",
498
- mediaType: chunk.payload.mimeType,
499
- url,
500
- providerMetadata: chunk.payload.providerMetadata
501
- });
502
- return [
503
- ...result.slice(0, -1),
504
- {
505
- ...lastMessage,
506
- parts
507
- }
508
- ];
509
- }
510
- case "tool-call-approval": {
511
- const lastMessage = result[result.length - 1];
512
- if (!lastMessage || lastMessage.role !== "assistant") return result;
513
- const lastRequireApprovalMetadata = lastMessage.metadata?.mode === "stream" ? lastMessage.metadata?.requireApprovalMetadata : {};
514
- return [
515
- ...result.slice(0, -1),
516
- {
517
- ...lastMessage,
518
- metadata: {
519
- ...lastMessage.metadata,
520
- mode: "stream",
521
- requireApprovalMetadata: {
522
- ...lastRequireApprovalMetadata,
523
- [chunk.payload.toolName]: {
524
- toolCallId: chunk.payload.toolCallId,
525
- toolName: chunk.payload.toolName,
526
- args: chunk.payload.args
527
- }
528
- }
529
- }
530
- }
531
- ];
532
- }
533
- case "tool-call-suspended": {
534
- const lastMessage = result[result.length - 1];
535
- if (!lastMessage || lastMessage.role !== "assistant") return result;
536
- const lastSuspendedTools = lastMessage.metadata?.mode === "stream" ? lastMessage.metadata?.suspendedTools : {};
537
- return [
538
- ...result.slice(0, -1),
539
- {
540
- ...lastMessage,
541
- metadata: {
542
- ...lastMessage.metadata,
543
- mode: "stream",
544
- suspendedTools: {
545
- ...lastSuspendedTools,
546
- [chunk.payload.toolName]: {
547
- toolCallId: chunk.payload.toolCallId,
548
- toolName: chunk.payload.toolName,
549
- args: chunk.payload.args,
550
- suspendPayload: chunk.payload.suspendPayload
551
- }
552
- }
553
- }
554
- }
555
- ];
556
- }
557
- case "finish": {
558
- const lastMessage = result[result.length - 1];
559
- if (!lastMessage || lastMessage.role !== "assistant") return result;
560
- const parts = lastMessage.parts.map((part) => {
561
- if (typeof part === "object" && part !== null && "type" in part && "state" in part && part.state === "streaming") {
562
- if (part.type === "text" || part.type === "reasoning") {
563
- return { ...part, state: "done" };
564
- }
565
- }
566
- return part;
567
- });
568
- return [
569
- ...result.slice(0, -1),
570
- {
571
- ...lastMessage,
572
- parts
573
- }
574
- ];
575
- }
576
- case "error": {
577
- const newMessage = {
578
- id: `error-${chunk.runId + Date.now()}`,
579
- role: "assistant",
580
- parts: [
581
- {
582
- type: "text",
583
- text: typeof chunk.payload.error === "string" ? chunk.payload.error : JSON.stringify(chunk.payload.error)
584
- }
585
- ],
586
- metadata: {
587
- ...metadata,
588
- status: "error"
589
- }
590
- };
591
- return [...result, newMessage];
592
- }
593
- // For all other chunk types, return conversation unchanged
594
- default:
595
- return result;
596
- }
597
- };
598
- const toUIMessageFromAgent = (chunk, conversation, metadata) => {
599
- const lastMessage = conversation[conversation.length - 1];
600
- if (!lastMessage || lastMessage.role !== "assistant") return conversation;
601
- const parts = [...lastMessage.parts];
602
- if (chunk.type === "text-delta") {
603
- const agentChunk = chunk.payload;
604
- const toolPartIndex = parts.findIndex((part) => part.type === "dynamic-tool");
605
- if (toolPartIndex === -1) return conversation;
606
- const toolPart = parts[toolPartIndex];
607
- const childMessages = toolPart?.output?.childMessages || [];
608
- const lastChildMessage = childMessages[childMessages.length - 1];
609
- const textMessage = { type: "text", content: (lastChildMessage?.content || "") + agentChunk.text };
610
- const nextMessages = lastChildMessage?.type === "text" ? [...childMessages.slice(0, -1), textMessage] : [...childMessages, textMessage];
611
- parts[toolPartIndex] = {
612
- ...toolPart,
613
- output: {
614
- childMessages: nextMessages
273
+ return `${this.name}: ${this.message}`;
615
274
  }
616
275
  };
617
- } else if (chunk.type === "tool-call") {
618
- const agentChunk = chunk.payload;
619
- const toolPartIndex = parts.findIndex((part) => part.type === "dynamic-tool");
620
- if (toolPartIndex === -1) return conversation;
621
- const toolPart = parts[toolPartIndex];
622
- const childMessages = toolPart?.output?.childMessages || [];
623
- parts[toolPartIndex] = {
624
- ...toolPart,
625
- output: {
626
- ...toolPart?.output,
627
- childMessages: [
628
- ...childMessages,
629
- {
630
- type: "tool",
631
- toolCallId: agentChunk.toolCallId,
632
- toolName: agentChunk.toolName,
633
- args: agentChunk.args
634
- }
635
- ]
636
- }
637
- };
638
- } else if (chunk.type === "tool-output") {
639
- const agentChunk = chunk.payload;
640
- const toolPartIndex = parts.findIndex((part) => part.type === "dynamic-tool");
641
- if (toolPartIndex === -1) return conversation;
642
- const toolPart = parts[toolPartIndex];
643
- if (agentChunk?.output?.type?.startsWith("workflow-")) {
644
- const childMessages = toolPart?.output?.childMessages || [];
645
- const lastToolIndex = childMessages.length - 1;
646
- const currentMessage = childMessages[lastToolIndex];
647
- const actualExistingWorkflowState = currentMessage?.toolOutput || {};
648
- const updatedWorkflowState = mapWorkflowStreamChunkToWatchResult(actualExistingWorkflowState, agentChunk.output);
649
- if (lastToolIndex >= 0 && childMessages[lastToolIndex]?.type === "tool") {
650
- parts[toolPartIndex] = {
651
- ...toolPart,
652
- output: {
653
- ...toolPart?.output,
654
- childMessages: [
655
- ...childMessages.slice(0, -1),
656
- {
657
- ...currentMessage,
658
- toolOutput: { ...updatedWorkflowState, runId: agentChunk.output.runId }
659
- }
660
- ]
661
- }
662
- };
663
- }
664
- }
665
- } else if (chunk.type === "tool-result") {
666
- const agentChunk = chunk.payload;
667
- const toolPartIndex = parts.findIndex((part) => part.type === "dynamic-tool");
668
- if (toolPartIndex === -1) return conversation;
669
- const toolPart = parts[toolPartIndex];
670
- const childMessages = toolPart?.output?.childMessages || [];
671
- const lastToolIndex = childMessages.length - 1;
672
- const isWorkflow = agentChunk?.toolName?.startsWith("workflow-");
673
- if (lastToolIndex >= 0 && childMessages[lastToolIndex]?.type === "tool") {
674
- parts[toolPartIndex] = {
675
- ...toolPart,
676
- output: {
677
- ...toolPart?.output,
678
- childMessages: [
679
- ...childMessages.slice(0, -1),
680
- {
681
- ...childMessages[lastToolIndex],
682
- toolOutput: isWorkflow ? { ...agentChunk.result?.result, runId: agentChunk.result?.runId } : agentChunk.result
683
- }
684
- ]
685
- }
686
- };
687
- }
688
276
  }
689
- return [
690
- ...conversation.slice(0, -1),
691
- {
692
- ...lastMessage,
693
- parts
694
- }
695
- ];
696
- };
277
+ });
697
278
 
698
- const toAssistantUIMessage = (message) => {
699
- const extendedMessage = message;
700
- const content = message.parts.map((part) => {
701
- if (part.type === "text") {
702
- return {
703
- type: "text",
704
- text: part.text,
705
- metadata: message.metadata
706
- };
707
- }
708
- if (part.type === "reasoning") {
709
- return {
710
- type: "reasoning",
711
- text: part.text,
712
- metadata: message.metadata
713
- };
714
- }
715
- if (part.type === "source-url") {
716
- return {
717
- type: "source",
718
- sourceType: "url",
719
- id: part.sourceId,
720
- url: part.url,
721
- title: part.title,
722
- metadata: message.metadata
723
- };
724
- }
725
- if (part.type === "source-document") {
726
- return {
727
- type: "file",
728
- filename: part.filename,
729
- mimeType: part.mediaType,
730
- data: "",
731
- // Source documents don't have inline data
732
- metadata: message.metadata
733
- };
734
- }
735
- if (part.type === "file") {
736
- const type = part.mediaType.includes("image/") ? "image" : "file";
737
- if (type === "file") {
738
- return {
739
- type,
740
- mimeType: part.mediaType,
741
- data: part.url,
742
- // Use URL as data source
743
- metadata: message.metadata
744
- };
745
- }
746
- if (type === "image") {
747
- return {
748
- type,
749
- image: part.url,
750
- metadata: message.metadata
751
- };
752
- }
753
- }
754
- if (part.type === "dynamic-tool") {
755
- const baseToolCall = {
756
- type: "tool-call",
757
- toolCallId: part.toolCallId,
758
- toolName: part.toolName,
759
- argsText: JSON.stringify(part.input),
760
- args: part.input,
761
- metadata: message.metadata
762
- };
763
- if (part.state === "output-error" && "errorText" in part) {
764
- return { ...baseToolCall, result: part.errorText, isError: true };
765
- }
766
- if ("output" in part) {
767
- return { ...baseToolCall, result: part.output };
768
- }
769
- return baseToolCall;
770
- }
771
- if (part.type.startsWith("tool-") && part.state !== "input-available") {
772
- const toolName2 = "toolName" in part && typeof part.toolName === "string" ? part.toolName : part.type.substring(5);
773
- const { suspendedToolRunId, ...cleanInput } = "input" in part ? part.input : {};
774
- const baseToolCall = {
775
- type: "tool-call",
776
- toolCallId: "toolCallId" in part && typeof part.toolCallId === "string" ? part.toolCallId : "",
777
- toolName: toolName2,
778
- argsText: JSON.stringify(cleanInput ?? {}),
779
- args: cleanInput ?? {},
780
- metadata: message.metadata
781
- };
782
- if ("output" in part) {
783
- return { ...baseToolCall, result: part.output };
784
- } else if ("error" in part) {
785
- return { ...baseToolCall, result: part.error, isError: true };
786
- }
787
- return baseToolCall;
788
- }
789
- const toolName = "toolName" in part && typeof part.toolName === "string" ? part.toolName : part.type.startsWith("tool-") ? part.type.substring(5) : "";
790
- const requireApprovalMetadata = extendedMessage.metadata?.requireApprovalMetadata;
791
- const suspendedTools = extendedMessage.metadata?.suspendedTools;
792
- const partToolCallId = "toolCallId" in part && typeof part.toolCallId === "string" ? part.toolCallId : void 0;
793
- const suspensionData = toolName ? requireApprovalMetadata?.[toolName] ?? suspendedTools?.[toolName] : void 0;
794
- if (suspensionData) {
795
- const { suspendedToolRunId, ...cleanInput } = "input" in part ? part.input : {};
796
- return {
797
- type: "tool-call",
798
- toolCallId: partToolCallId,
799
- toolName,
800
- argsText: JSON.stringify(cleanInput ?? {}),
801
- args: cleanInput,
802
- metadata: extendedMessage.metadata
803
- };
804
- }
805
- if (part.type.startsWith("data-")) {
806
- return {
807
- type: "data",
808
- name: part.type.substring(5),
809
- // Extract name from 'data-{name}'
810
- data: part.data,
811
- metadata: message.metadata
812
- };
813
- }
814
- return {
815
- type: "text",
816
- text: "",
817
- metadata: message.metadata
818
- };
819
- });
820
- let status;
821
- if (message.role === "assistant" && content.length > 0) {
822
- const hasStreamingParts = message.parts.some(
823
- (part) => part.type === "text" && "state" in part && part.state === "streaming" || part.type === "reasoning" && "state" in part && part.state === "streaming"
824
- );
825
- const hasToolCalls = message.parts.some((part) => part.type === "dynamic-tool" || part.type.startsWith("tool-"));
826
- const hasInputAvailableTools = message.parts.some(
827
- (part) => part.type === "dynamic-tool" && part.state === "input-available"
828
- );
829
- const hasErrorTools = message.parts.some(
830
- (part) => part.type === "dynamic-tool" && part.state === "output-error" || part.type.startsWith("tool-") && "error" in part
831
- );
832
- if (hasStreamingParts) {
833
- status = { type: "running" };
834
- } else if (hasInputAvailableTools && hasToolCalls) {
835
- status = { type: "requires-action", reason: "tool-calls" };
836
- } else if (hasErrorTools) {
837
- status = { type: "incomplete", reason: "error" };
838
- } else {
839
- status = { type: "complete", reason: "stop" };
840
- }
279
+ // ../_vendored/ai_v5/dist/chunk-VQ35X6XO.js
280
+ var marker$4 = "vercel.ai.error";
281
+ var symbol$4 = Symbol.for(marker$4);
282
+ var _a$4;
283
+ var _AISDKError$2 = class _AISDKError2 extends Error {
284
+ /**
285
+ * Creates an AI SDK Error.
286
+ *
287
+ * @param {Object} params - The parameters for creating the error.
288
+ * @param {string} params.name - The name of the error.
289
+ * @param {string} params.message - The error message.
290
+ * @param {unknown} [params.cause] - The underlying cause of the error.
291
+ */
292
+ constructor({
293
+ name: name14,
294
+ message,
295
+ cause
296
+ }) {
297
+ super(message);
298
+ this[_a$4] = true;
299
+ this.name = name14;
300
+ this.cause = cause;
301
+ }
302
+ /**
303
+ * Checks if the given error is an AI SDK Error.
304
+ * @param {unknown} error - The error to check.
305
+ * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
306
+ */
307
+ static isInstance(error) {
308
+ return _AISDKError2.hasMarker(error, marker$4);
309
+ }
310
+ static hasMarker(error, marker15) {
311
+ const markerSymbol = Symbol.for(marker15);
312
+ return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
841
313
  }
842
- const threadMessage = {
843
- role: message.role,
844
- content,
845
- id: message.id,
846
- createdAt: extendedMessage.createdAt,
847
- status,
848
- attachments: extendedMessage.experimental_attachments
849
- };
850
- return threadMessage;
851
314
  };
852
-
853
- const resolveInitialMessages = (messages) => {
854
- const messagesLength = messages.length;
855
- return messages.map((message, index) => {
856
- const networkPart = message.parts.find(
857
- (part) => typeof part === "object" && part !== null && "type" in part && part.type === "text" && "text" in part && typeof part.text === "string" && part.text.includes('"isNetwork":true')
858
- );
859
- if (networkPart && networkPart.type === "text") {
860
- try {
861
- const json = JSON.parse(networkPart.text);
862
- if (json.isNetwork === true) {
863
- const selectionReason = json.selectionReason || "";
864
- const primitiveType = json.primitiveType || "";
865
- const primitiveId = json.primitiveId || "";
866
- const finalResult = json.finalResult;
867
- const messages2 = finalResult?.messages || [];
868
- const childMessages = [];
869
- const toolResultMap = /* @__PURE__ */ new Map();
870
- for (const msg of messages2) {
871
- if (Array.isArray(msg.content)) {
872
- for (const part of msg.content) {
873
- if (typeof part === "object" && part.type === "tool-result") {
874
- toolResultMap.set(part.toolCallId, part);
875
- }
876
- }
877
- }
878
- }
879
- for (const msg of messages2) {
880
- if (msg.type === "tool-call" && Array.isArray(msg.content)) {
881
- for (const part of msg.content) {
882
- if (typeof part === "object" && part.type === "tool-call") {
883
- const toolCallContent = part;
884
- const toolResult = toolResultMap.get(toolCallContent.toolCallId);
885
- const isWorkflow = Boolean(toolResult?.result?.result?.steps);
886
- childMessages.push({
887
- type: "tool",
888
- toolCallId: toolCallContent.toolCallId,
889
- toolName: toolCallContent.toolName,
890
- args: toolCallContent.args,
891
- toolOutput: isWorkflow ? toolResult?.result?.result : toolResult?.result
892
- });
893
- }
894
- }
895
- }
896
- }
897
- if (finalResult && finalResult.text) {
898
- childMessages.push({
899
- type: "text",
900
- content: finalResult.text
901
- });
902
- }
903
- const result = primitiveType === "tool" ? finalResult?.result : {
904
- childMessages,
905
- result: finalResult?.text || ""
906
- };
907
- const nextMessage = {
908
- role: "assistant",
909
- parts: [
910
- {
911
- type: "dynamic-tool",
912
- toolCallId: primitiveId,
913
- toolName: primitiveId,
914
- state: "output-available",
915
- input: json.input,
916
- output: result
917
- }
918
- ],
919
- id: message.id,
920
- metadata: {
921
- ...message.metadata,
922
- mode: "network",
923
- selectionReason,
924
- agentInput: json.input,
925
- hasMoreMessages: index < messagesLength - 1,
926
- from: primitiveType === "agent" ? "AGENT" : primitiveType === "tool" ? "TOOL" : "WORKFLOW"
927
- }
928
- };
929
- return nextMessage;
930
- }
931
- } catch (error) {
932
- return message;
933
- }
934
- }
935
- const extendedMessage = message;
936
- const pendingToolApprovals = extendedMessage.metadata?.pendingToolApprovals;
937
- if (pendingToolApprovals && typeof pendingToolApprovals === "object") {
938
- return {
939
- ...message,
940
- metadata: {
941
- ...message.metadata,
942
- mode: "stream",
943
- requireApprovalMetadata: pendingToolApprovals
944
- }
945
- };
946
- }
947
- const suspendedTools = extendedMessage.metadata?.suspendedTools;
948
- if (suspendedTools && typeof suspendedTools === "object") {
949
- return {
950
- ...message,
951
- metadata: {
952
- ...message.metadata,
953
- mode: "stream",
954
- suspendedTools
955
- }
956
- };
957
- }
958
- return message;
959
- });
960
- };
961
- const resolveToChildMessages = (messages) => {
962
- const assistantMessage = messages.find((message) => message.role === "assistant");
963
- if (!assistantMessage) return [];
964
- const parts = assistantMessage.parts;
965
- let childMessages = [];
966
- for (const part of parts) {
967
- const toolPart = part;
968
- if (part.type.startsWith("tool-")) {
969
- const toolName = part.type.substring("tool-".length);
970
- const isWorkflow = toolName.startsWith("workflow-");
971
- childMessages.push({
972
- type: "tool",
973
- toolCallId: toolPart.toolCallId,
974
- toolName,
975
- args: toolPart.input,
976
- toolOutput: isWorkflow ? { ...toolPart.output?.result, runId: toolPart.output?.runId } : toolPart.output
977
- });
978
- }
979
- if (part.type === "text") {
980
- childMessages.push({
981
- type: "text",
982
- content: toolPart.text
983
- });
984
- }
315
+ _a$4 = symbol$4;
316
+ var AISDKError$3 = _AISDKError$2;
317
+ var name$1 = "AI_APICallError";
318
+ var marker2$1 = `vercel.ai.error.${name$1}`;
319
+ var symbol2$1 = Symbol.for(marker2$1);
320
+ var _a2$1;
321
+ var APICallError = class extends AISDKError$3 {
322
+ constructor({
323
+ message,
324
+ url,
325
+ requestBodyValues,
326
+ statusCode,
327
+ responseHeaders,
328
+ responseBody,
329
+ cause,
330
+ isRetryable = statusCode != null && (statusCode === 408 || // request timeout
331
+ statusCode === 409 || // conflict
332
+ statusCode === 429 || // too many requests
333
+ statusCode >= 500),
334
+ // server error
335
+ data
336
+ }) {
337
+ super({ name: name$1, message, cause });
338
+ this[_a2$1] = true;
339
+ this.url = url;
340
+ this.requestBodyValues = requestBodyValues;
341
+ this.statusCode = statusCode;
342
+ this.responseHeaders = responseHeaders;
343
+ this.responseBody = responseBody;
344
+ this.isRetryable = isRetryable;
345
+ this.data = data;
985
346
  }
986
- return childMessages;
987
- };
988
-
989
- var __create$4 = Object.create;
990
- var __defProp$6 = Object.defineProperty;
991
- var __getOwnPropDesc$4 = Object.getOwnPropertyDescriptor;
992
- var __getOwnPropNames$4 = Object.getOwnPropertyNames;
993
- var __getProtoOf$4 = Object.getPrototypeOf;
994
- var __hasOwnProp$4 = Object.prototype.hasOwnProperty;
995
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
996
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
997
- }) : x)(function(x) {
998
- if (typeof require !== "undefined") return require.apply(this, arguments);
999
- throw Error('Dynamic require of "' + x + '" is not supported');
1000
- });
1001
- var __commonJS$4 = (cb, mod) => function __require2() {
1002
- return mod || (0, cb[__getOwnPropNames$4(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
1003
- };
1004
- var __copyProps$4 = (to, from, except, desc) => {
1005
- if (from && typeof from === "object" || typeof from === "function") {
1006
- for (let key of __getOwnPropNames$4(from))
1007
- if (!__hasOwnProp$4.call(to, key) && key !== except)
1008
- __defProp$6(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc$4(from, key)) || desc.enumerable });
347
+ static isInstance(error) {
348
+ return AISDKError$3.hasMarker(error, marker2$1);
1009
349
  }
1010
- return to;
1011
350
  };
1012
- var __toESM$3 = (mod, isNodeMode, target) => (target = mod != null ? __create$4(__getProtoOf$4(mod)) : {}, __copyProps$4(
1013
- // If the importer is in node compatibility mode or this is not an ESM
1014
- // file that has been converted to a CommonJS file using a Babel-
1015
- // compatible transform (i.e. "__esModule" has not been set), then set
1016
- // "default" to the CommonJS "module.exports" for node compatibility.
1017
- __defProp$6(target, "default", { value: mod, enumerable: true }) ,
1018
- mod
1019
- ));
1020
-
1021
- // ../_vendored/ai_v5/dist/chunk-7D4SUZUM.js
1022
- var __create$3 = Object.create;
1023
- var __defProp$5 = Object.defineProperty;
1024
- var __getOwnPropDesc$3 = Object.getOwnPropertyDescriptor;
1025
- var __getOwnPropNames$3 = Object.getOwnPropertyNames;
1026
- var __getProtoOf$3 = Object.getPrototypeOf;
1027
- var __hasOwnProp$3 = Object.prototype.hasOwnProperty;
1028
- var __require2 = /* @__PURE__ */ ((x) => typeof __require !== "undefined" ? __require : typeof Proxy !== "undefined" ? new Proxy(x, {
1029
- get: (a, b) => (typeof __require !== "undefined" ? __require : a)[b]
1030
- }) : x)(function(x) {
1031
- if (typeof __require !== "undefined") return __require.apply(this, arguments);
1032
- throw Error('Dynamic require of "' + x + '" is not supported');
1033
- });
1034
- var __commonJS$3 = (cb, mod) => function __require22() {
1035
- return mod || (0, cb[__getOwnPropNames$3(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
351
+ _a2$1 = symbol2$1;
352
+ var name2$1 = "AI_EmptyResponseBodyError";
353
+ var marker3$1 = `vercel.ai.error.${name2$1}`;
354
+ var symbol3$1 = Symbol.for(marker3$1);
355
+ var _a3$1;
356
+ var EmptyResponseBodyError = class extends AISDKError$3 {
357
+ // used in isInstance
358
+ constructor({ message = "Empty response body" } = {}) {
359
+ super({ name: name2$1, message });
360
+ this[_a3$1] = true;
361
+ }
362
+ static isInstance(error) {
363
+ return AISDKError$3.hasMarker(error, marker3$1);
364
+ }
1036
365
  };
1037
- var __copyProps$3 = (to, from, except, desc) => {
1038
- if (from && typeof from === "object" || typeof from === "function") {
1039
- for (let key of __getOwnPropNames$3(from))
1040
- if (!__hasOwnProp$3.call(to, key) && key !== except)
1041
- __defProp$5(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc$3(from, key)) || desc.enumerable });
1042
- }
1043
- return to;
1044
- };
1045
- var __toESM$2 = (mod, isNodeMode, target) => (target = mod != null ? __create$3(__getProtoOf$3(mod)) : {}, __copyProps$3(
1046
- // If the importer is in node compatibility mode or this is not an ESM
1047
- // file that has been converted to a CommonJS file using a Babel-
1048
- // compatible transform (i.e. "__esModule" has not been set), then set
1049
- // "default" to the CommonJS "module.exports" for node compatibility.
1050
- __defProp$5(target, "default", { value: mod, enumerable: true }) ,
1051
- mod
1052
- ));
1053
-
1054
- // ../_vendored/ai_v5/dist/chunk-TLQKI65U.js
1055
- var require_token_error = __commonJS$3({
1056
- "../../../node_modules/.pnpm/@vercel+oidc@3.0.5/node_modules/@vercel/oidc/dist/token-error.js"(exports$1, module) {
1057
- var __defProp2 = Object.defineProperty;
1058
- var __getOwnPropDesc2 = Object.getOwnPropertyDescriptor;
1059
- var __getOwnPropNames2 = Object.getOwnPropertyNames;
1060
- var __hasOwnProp2 = Object.prototype.hasOwnProperty;
1061
- var __export = (target, all) => {
1062
- for (var name in all)
1063
- __defProp2(target, name, { get: all[name], enumerable: true });
1064
- };
1065
- var __copyProps2 = (to, from, except, desc) => {
1066
- if (from && typeof from === "object" || typeof from === "function") {
1067
- for (let key of __getOwnPropNames2(from))
1068
- if (!__hasOwnProp2.call(to, key) && key !== except)
1069
- __defProp2(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc2(from, key)) || desc.enumerable });
1070
- }
1071
- return to;
1072
- };
1073
- var __toCommonJS = (mod) => __copyProps2(__defProp2({}, "__esModule", { value: true }), mod);
1074
- var token_error_exports = {};
1075
- __export(token_error_exports, {
1076
- VercelOidcTokenError: () => VercelOidcTokenError
1077
- });
1078
- module.exports = __toCommonJS(token_error_exports);
1079
- var VercelOidcTokenError = class extends Error {
1080
- constructor(message, cause) {
1081
- super(message);
1082
- this.name = "VercelOidcTokenError";
1083
- this.cause = cause;
1084
- }
1085
- toString() {
1086
- if (this.cause) {
1087
- return `${this.name}: ${this.message}: ${this.cause}`;
1088
- }
1089
- return `${this.name}: ${this.message}`;
1090
- }
1091
- };
1092
- }
1093
- });
1094
-
1095
- // ../_vendored/ai_v5/dist/chunk-VQ35X6XO.js
1096
- var marker$4 = "vercel.ai.error";
1097
- var symbol$4 = Symbol.for(marker$4);
1098
- var _a$4;
1099
- var _AISDKError$2 = class _AISDKError2 extends Error {
1100
- /**
1101
- * Creates an AI SDK Error.
1102
- *
1103
- * @param {Object} params - The parameters for creating the error.
1104
- * @param {string} params.name - The name of the error.
1105
- * @param {string} params.message - The error message.
1106
- * @param {unknown} [params.cause] - The underlying cause of the error.
1107
- */
1108
- constructor({
1109
- name: name14,
1110
- message,
1111
- cause
1112
- }) {
1113
- super(message);
1114
- this[_a$4] = true;
1115
- this.name = name14;
1116
- this.cause = cause;
1117
- }
1118
- /**
1119
- * Checks if the given error is an AI SDK Error.
1120
- * @param {unknown} error - The error to check.
1121
- * @returns {boolean} True if the error is an AI SDK Error, false otherwise.
1122
- */
1123
- static isInstance(error) {
1124
- return _AISDKError2.hasMarker(error, marker$4);
1125
- }
1126
- static hasMarker(error, marker15) {
1127
- const markerSymbol = Symbol.for(marker15);
1128
- return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true;
1129
- }
1130
- };
1131
- _a$4 = symbol$4;
1132
- var AISDKError$3 = _AISDKError$2;
1133
- var name$1 = "AI_APICallError";
1134
- var marker2$1 = `vercel.ai.error.${name$1}`;
1135
- var symbol2$1 = Symbol.for(marker2$1);
1136
- var _a2$1;
1137
- var APICallError = class extends AISDKError$3 {
1138
- constructor({
1139
- message,
1140
- url,
1141
- requestBodyValues,
1142
- statusCode,
1143
- responseHeaders,
1144
- responseBody,
1145
- cause,
1146
- isRetryable = statusCode != null && (statusCode === 408 || // request timeout
1147
- statusCode === 409 || // conflict
1148
- statusCode === 429 || // too many requests
1149
- statusCode >= 500),
1150
- // server error
1151
- data
1152
- }) {
1153
- super({ name: name$1, message, cause });
1154
- this[_a2$1] = true;
1155
- this.url = url;
1156
- this.requestBodyValues = requestBodyValues;
1157
- this.statusCode = statusCode;
1158
- this.responseHeaders = responseHeaders;
1159
- this.responseBody = responseBody;
1160
- this.isRetryable = isRetryable;
1161
- this.data = data;
1162
- }
1163
- static isInstance(error) {
1164
- return AISDKError$3.hasMarker(error, marker2$1);
1165
- }
1166
- };
1167
- _a2$1 = symbol2$1;
1168
- var name2$1 = "AI_EmptyResponseBodyError";
1169
- var marker3$1 = `vercel.ai.error.${name2$1}`;
1170
- var symbol3$1 = Symbol.for(marker3$1);
1171
- var _a3$1;
1172
- var EmptyResponseBodyError = class extends AISDKError$3 {
1173
- // used in isInstance
1174
- constructor({ message = "Empty response body" } = {}) {
1175
- super({ name: name2$1, message });
1176
- this[_a3$1] = true;
1177
- }
1178
- static isInstance(error) {
1179
- return AISDKError$3.hasMarker(error, marker3$1);
1180
- }
1181
- };
1182
- _a3$1 = symbol3$1;
1183
- function getErrorMessage$2(error) {
1184
- if (error == null) {
1185
- return "unknown error";
1186
- }
1187
- if (typeof error === "string") {
1188
- return error;
1189
- }
1190
- if (error instanceof Error) {
1191
- return error.message;
1192
- }
1193
- return JSON.stringify(error);
1194
- }
1195
- var name3$4 = "AI_InvalidArgumentError";
1196
- var marker4$4 = `vercel.ai.error.${name3$4}`;
1197
- var symbol4$4 = Symbol.for(marker4$4);
1198
- var _a4$4;
1199
- var InvalidArgumentError$3 = class InvalidArgumentError extends AISDKError$3 {
1200
- constructor({
1201
- message,
1202
- cause,
1203
- argument
1204
- }) {
1205
- super({ name: name3$4, message, cause });
1206
- this[_a4$4] = true;
1207
- this.argument = argument;
1208
- }
1209
- static isInstance(error) {
1210
- return AISDKError$3.hasMarker(error, marker4$4);
366
+ _a3$1 = symbol3$1;
367
+ function getErrorMessage$2(error) {
368
+ if (error == null) {
369
+ return "unknown error";
370
+ }
371
+ if (typeof error === "string") {
372
+ return error;
373
+ }
374
+ if (error instanceof Error) {
375
+ return error.message;
376
+ }
377
+ return JSON.stringify(error);
378
+ }
379
+ var name3$4 = "AI_InvalidArgumentError";
380
+ var marker4$4 = `vercel.ai.error.${name3$4}`;
381
+ var symbol4$4 = Symbol.for(marker4$4);
382
+ var _a4$4;
383
+ var InvalidArgumentError$3 = class InvalidArgumentError extends AISDKError$3 {
384
+ constructor({
385
+ message,
386
+ cause,
387
+ argument
388
+ }) {
389
+ super({ name: name3$4, message, cause });
390
+ this[_a4$4] = true;
391
+ this.argument = argument;
392
+ }
393
+ static isInstance(error) {
394
+ return AISDKError$3.hasMarker(error, marker4$4);
1211
395
  }
1212
396
  };
1213
397
  _a4$4 = symbol4$4;
@@ -3169,8 +2353,8 @@ var require_get_vercel_oidc_token = __commonJS$3({
3169
2353
  }
3170
2354
  try {
3171
2355
  const [{ getTokenPayload, isExpired }, { refreshToken }] = await Promise.all([
3172
- await Promise.resolve().then(() => require('./token-util-NEHG7TUY-U7CX7GS4-C59wA2lQ.cjs')),
3173
- await Promise.resolve().then(() => require('./token-6GSAFR2W-XRCSVUPZ-C2rqLNj8.cjs'))
2356
+ await Promise.resolve().then(() => require('./token-util-NEHG7TUY-U7CX7GS4-B0wfFQ5e.cjs')),
2357
+ await Promise.resolve().then(() => require('./token-6GSAFR2W-XRCSVUPZ-DHFPWxwn.cjs'))
3174
2358
  ]);
3175
2359
  if (!token || isExpired(getTokenPayload(token))) {
3176
2360
  await refreshToken();
@@ -5766,140 +4950,21 @@ var MastraBaseError = class extends Error {
5766
4950
  var MastraError = class extends MastraBaseError {
5767
4951
  };
5768
4952
 
5769
- // src/request-context/index.ts
5770
- var RequestContext = class {
5771
- registry = /* @__PURE__ */ new Map();
5772
- constructor(iterable) {
5773
- this.registry = new Map(iterable);
5774
- }
5775
- /**
5776
- * set a value with strict typing if `Values` is a Record and the key exists in it.
5777
- */
5778
- set(key, value) {
5779
- this.registry.set(key, value);
5780
- }
5781
- /**
5782
- * Get a value with its type
5783
- */
5784
- get(key) {
5785
- return this.registry.get(key);
5786
- }
5787
- /**
5788
- * Check if a key exists in the container
5789
- */
5790
- has(key) {
5791
- return this.registry.has(key);
5792
- }
5793
- /**
5794
- * Delete a value by key
5795
- */
5796
- delete(key) {
5797
- return this.registry.delete(key);
5798
- }
5799
- /**
5800
- * Clear all values from the container
5801
- */
5802
- clear() {
5803
- this.registry.clear();
5804
- }
5805
- /**
5806
- * Get all keys in the container
5807
- */
5808
- keys() {
5809
- return this.registry.keys();
5810
- }
5811
- /**
5812
- * Get all values in the container
5813
- */
5814
- values() {
5815
- return this.registry.values();
5816
- }
5817
- /**
5818
- * Get all entries in the container.
5819
- * Returns a discriminated union of tuples for proper type narrowing when iterating.
5820
- */
5821
- entries() {
5822
- return this.registry.entries();
5823
- }
5824
- /**
5825
- * Get the size of the container
5826
- */
5827
- size() {
5828
- return this.registry.size;
5829
- }
5830
- /**
5831
- * Execute a function for each entry in the container.
5832
- * The callback receives properly typed key-value pairs.
5833
- */
5834
- forEach(callbackfn) {
5835
- this.registry.forEach(callbackfn);
5836
- }
5837
- /**
5838
- * Custom JSON serialization method.
5839
- * Converts the internal Map to a plain object for proper JSON serialization.
5840
- * Non-serializable values (e.g., RPC proxies, functions, circular references)
5841
- * are skipped to prevent serialization errors when storing to database.
5842
- */
5843
- toJSON() {
5844
- const result = {};
5845
- for (const [key, value] of this.registry.entries()) {
5846
- if (this.isSerializable(value)) {
5847
- result[key] = value;
5848
- }
5849
- }
5850
- return result;
5851
- }
5852
- /**
5853
- * Check if a value can be safely serialized to JSON.
5854
- */
5855
- isSerializable(value) {
5856
- if (value === null || value === void 0) return true;
5857
- if (typeof value === "function") return false;
5858
- if (typeof value === "symbol") return false;
5859
- if (typeof value !== "object") return true;
5860
- try {
5861
- JSON.stringify(value);
5862
- return true;
5863
- } catch {
5864
- return false;
5865
- }
5866
- }
5867
- /**
5868
- * Get all values as a typed object for destructuring.
5869
- * Returns Record<string, any> when untyped, or the Values type when typed.
5870
- *
5871
- * @example
5872
- * ```typescript
5873
- * const ctx = new RequestContext<{ userId: string; apiKey: string }>();
5874
- * ctx.set('userId', 'user-123');
5875
- * ctx.set('apiKey', 'key-456');
5876
- * const { userId, apiKey } = ctx.all;
5877
- * ```
5878
- */
5879
- get all() {
5880
- return Object.fromEntries(this.registry);
5881
- }
5882
- };
5883
-
5884
- function getDefaultExportFromCjs (x) {
5885
- return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
5886
- }
5887
-
5888
- // ../_vendored/ai_v4/dist/chunk-OPIPXJLE.js
5889
- var __create$2 = Object.create;
5890
- var __defProp$3 = Object.defineProperty;
5891
- var __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor;
5892
- var __getOwnPropNames$2 = Object.getOwnPropertyNames;
5893
- var __getProtoOf$2 = Object.getPrototypeOf;
5894
- var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
5895
- var __commonJS$2 = (cb, mod) => function __require22() {
5896
- return mod || (0, cb[__getOwnPropNames$2(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
5897
- };
5898
- var __copyProps$2 = (to, from, except, desc) => {
5899
- if (from && typeof from === "object" || typeof from === "function") {
5900
- for (let key of __getOwnPropNames$2(from))
5901
- if (!__hasOwnProp$2.call(to, key) && key !== except)
5902
- __defProp$3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc$2(from, key)) || desc.enumerable });
4953
+ // ../_vendored/ai_v4/dist/chunk-OPIPXJLE.js
4954
+ var __create$2 = Object.create;
4955
+ var __defProp$3 = Object.defineProperty;
4956
+ var __getOwnPropDesc$2 = Object.getOwnPropertyDescriptor;
4957
+ var __getOwnPropNames$2 = Object.getOwnPropertyNames;
4958
+ var __getProtoOf$2 = Object.getPrototypeOf;
4959
+ var __hasOwnProp$2 = Object.prototype.hasOwnProperty;
4960
+ var __commonJS$2 = (cb, mod) => function __require22() {
4961
+ return mod || (0, cb[__getOwnPropNames$2(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
4962
+ };
4963
+ var __copyProps$2 = (to, from, except, desc) => {
4964
+ if (from && typeof from === "object" || typeof from === "function") {
4965
+ for (let key of __getOwnPropNames$2(from))
4966
+ if (!__hasOwnProp$2.call(to, key) && key !== except)
4967
+ __defProp$3(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc$2(from, key)) || desc.enumerable });
5903
4968
  }
5904
4969
  return to;
5905
4970
  };
@@ -12015,6 +11080,9 @@ var MessageMerger = class _MessageMerger {
12015
11080
  static shouldMerge(latestMessage, incomingMessage, messageSource, isLatestFromMemory, agentNetworkAppend = false) {
12016
11081
  if (!latestMessage) return false;
12017
11082
  if (_MessageMerger.isSealed(latestMessage)) return false;
11083
+ if (incomingMessage.content.metadata?.completionResult || latestMessage.content.metadata?.completionResult || incomingMessage.content.metadata?.isTaskCompleteResult || latestMessage.content.metadata?.isTaskCompleteResult) {
11084
+ return false;
11085
+ }
12018
11086
  const shouldAppendToLastAssistantMessage = latestMessage.role === "assistant" && incomingMessage.role === "assistant" && latestMessage.threadId === incomingMessage.threadId && // If the message is from memory, don't append to the last assistant message
12019
11087
  messageSource !== "memory";
12020
11088
  const appendNetworkMessage = agentNetworkAppend ? !isLatestFromMemory : true;
@@ -13755,6 +12823,20 @@ var MessageList$1 = class MessageList {
13755
12823
  this.messages.push(messageV2);
13756
12824
  }
13757
12825
  } else {
12826
+ const isExistingFromMemory = this.memoryMessages.has(existingMessage);
12827
+ const shouldMergeIntoExisting = MessageMerger.shouldMerge(
12828
+ existingMessage,
12829
+ messageV2,
12830
+ messageSource,
12831
+ isExistingFromMemory,
12832
+ this._agentNetworkAppend
12833
+ );
12834
+ if (shouldMergeIntoExisting) {
12835
+ MessageMerger.merge(existingMessage, messageV2);
12836
+ this.pushMessageToSource(existingMessage, messageSource);
12837
+ this.messages.sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime());
12838
+ return this;
12839
+ }
13758
12840
  this.messages[existingIndex] = messageV2;
13759
12841
  }
13760
12842
  } else if (!exists) {
@@ -24422,7 +23504,9 @@ z10.object({
24422
23504
  }),
24423
23505
  stepResult: llmIterationStepResultSchema,
24424
23506
  processorRetryCount: z10.number().optional(),
24425
- processorRetryFeedback: z10.string().optional()
23507
+ processorRetryFeedback: z10.string().optional(),
23508
+ isTaskCompleteCheckFailed: z10.boolean().optional()
23509
+ //true if the isTaskComplete check failed and LLM has to run again
24426
23510
  });
24427
23511
  var toolCallInputSchema = z10.object({
24428
23512
  toolCallId: z10.string(),
@@ -24445,83 +23529,1102 @@ function formatCompletionFeedback(result, maxIterationReached) {
24445
23529
  if (result.timedOut) {
24446
23530
  lines.push("\u26A0\uFE0F Scoring timed out");
24447
23531
  }
24448
- lines.push("");
24449
- for (const scorer of result.scorers) {
24450
- lines.push(`###### ${scorer.scorerName} (${scorer.scorerId})`);
24451
- lines.push(`Score: ${scorer.score} ${scorer.passed ? "\u2705" : "\u274C"}`);
24452
- if (scorer.reason) {
24453
- lines.push(`Reason: ${scorer.reason}`);
23532
+ lines.push("");
23533
+ for (const scorer of result.scorers) {
23534
+ lines.push(`###### ${scorer.scorerName} (${scorer.scorerId})`);
23535
+ lines.push(`Score: ${scorer.score} ${scorer.passed ? "\u2705" : "\u274C"}`);
23536
+ if (scorer.reason) {
23537
+ lines.push(`Reason: ${scorer.reason}`);
23538
+ }
23539
+ lines.push("");
23540
+ }
23541
+ if (result.complete) {
23542
+ lines.push("\n\n\u2705 The task is complete.");
23543
+ } else if (maxIterationReached) {
23544
+ lines.push("\n\n\u26A0\uFE0F Max iterations reached.");
23545
+ } else {
23546
+ lines.push("\n\n\u{1F504} Will continue working on the task.");
23547
+ }
23548
+ return lines.join("\n");
23549
+ }
23550
+ z10.z.object({
23551
+ isComplete: z10.z.boolean().describe("Whether the task is complete"),
23552
+ completionReason: z10.z.string().describe("Explanation of why the task is or is not complete"),
23553
+ finalResult: z10.z.string().optional().describe("The final result text to return to the user. omit if primitive result is sufficient")
23554
+ });
23555
+ z10.z.object({
23556
+ finalResult: z10.z.string().optional().describe("The final result text to return to the user, omit if primitive result is sufficient")
23557
+ });
23558
+ function formatStreamCompletionFeedback(result, maxIterationReached) {
23559
+ const lines = [];
23560
+ lines.push("#### Completion Check Results");
23561
+ lines.push("");
23562
+ lines.push(`Overall: ${result.complete ? "\u2705 COMPLETE" : "\u274C NOT COMPLETE"}`);
23563
+ lines.push(`Duration: ${result.totalDuration}ms`);
23564
+ if (result.timedOut) {
23565
+ lines.push("\u26A0\uFE0F Scoring timed out");
23566
+ }
23567
+ lines.push("");
23568
+ for (const scorer of result.scorers) {
23569
+ lines.push(`**${scorer.scorerName}** (${scorer.scorerId})`);
23570
+ lines.push(`Score: ${scorer.score} ${scorer.passed ? "\u2705" : "\u274C"}`);
23571
+ if (scorer.reason) {
23572
+ lines.push(`Reason: ${scorer.reason}`);
23573
+ }
23574
+ lines.push("");
23575
+ }
23576
+ if (result.complete) {
23577
+ lines.push("\u2705 The task is complete.");
23578
+ } else if (maxIterationReached) {
23579
+ lines.push("\u26A0\uFE0F Max iterations reached.");
23580
+ } else {
23581
+ lines.push("\u{1F504} The task is not yet complete. Please continue working based on the feedback above.");
23582
+ }
23583
+ return lines.join("\n");
23584
+ }
23585
+ z10.enum(["agent", "workflow", "none", "tool"]);
23586
+
23587
+ // src/agent/agent-legacy.ts
23588
+ __toESM$3(require_fast_deep_equal());
23589
+
23590
+ // src/agent/workflows/prepare-stream/prepare-memory-step.ts
23591
+ __toESM$3(require_fast_deep_equal());
23592
+ var coreToolSchema = z10.z.object({
23593
+ id: z10.z.string().optional(),
23594
+ description: z10.z.string().optional(),
23595
+ parameters: z10.z.union([
23596
+ z10.z.record(z10.z.string(), z10.z.any()),
23597
+ // JSON Schema as object
23598
+ z10.z.any()
23599
+ // Zod schema or other schema types - validated at tool execution
23600
+ ]),
23601
+ outputSchema: z10.z.union([z10.z.record(z10.z.string(), z10.z.any()), z10.z.any()]).optional(),
23602
+ execute: z10.z.optional(z10.z.function(z10.z.tuple([z10.z.any(), z10.z.any()]), z10.z.promise(z10.z.any()))),
23603
+ toModelOutput: z10.z.optional(z10.z.function(z10.z.tuple([z10.z.any()]), z10.z.any())),
23604
+ type: z10.z.union([z10.z.literal("function"), z10.z.literal("provider-defined"), z10.z.undefined()]).optional(),
23605
+ args: z10.z.record(z10.z.string(), z10.z.any()).optional()
23606
+ });
23607
+ var storageThreadSchema = z10.z.object({
23608
+ id: z10.z.string(),
23609
+ title: z10.z.string().optional(),
23610
+ resourceId: z10.z.string(),
23611
+ createdAt: z10.z.date(),
23612
+ updatedAt: z10.z.date(),
23613
+ metadata: z10.z.record(z10.z.string(), z10.z.any()).optional()
23614
+ });
23615
+ z10.z.object({
23616
+ convertedTools: z10.z.record(z10.z.string(), coreToolSchema)
23617
+ });
23618
+ z10.z.object({
23619
+ threadExists: z10.z.boolean(),
23620
+ thread: storageThreadSchema.optional(),
23621
+ messageList: z10.z.instanceof(MessageList$1),
23622
+ /** Shared processor states map that persists across loop iterations for both input and output processors */
23623
+ processorStates: z10.z.instanceof(Map),
23624
+ /** Tripwire data when input processor triggered abort */
23625
+ tripwire: z10.z.object({
23626
+ reason: z10.z.string(),
23627
+ retry: z10.z.boolean().optional(),
23628
+ metadata: z10.z.unknown().optional(),
23629
+ processorId: z10.z.string().optional()
23630
+ }).optional()
23631
+ });
23632
+ var DEFAULT_CACHE_MAX_SIZE = 1e3;
23633
+ new L({
23634
+ max: DEFAULT_CACHE_MAX_SIZE
23635
+ });
23636
+
23637
+ const mapWorkflowStreamChunkToWatchResult = (prev, chunk) => {
23638
+ if (chunk.type === "workflow-start") {
23639
+ return {
23640
+ input: prev?.input,
23641
+ status: "running",
23642
+ steps: prev?.steps || {}
23643
+ };
23644
+ }
23645
+ if (chunk.type === "workflow-canceled") {
23646
+ return {
23647
+ ...prev,
23648
+ status: "canceled"
23649
+ };
23650
+ }
23651
+ if (chunk.type === "workflow-finish") {
23652
+ const finalStatus = chunk.payload.workflowStatus;
23653
+ const prevSteps = prev?.steps ?? {};
23654
+ const lastStep = Object.values(prevSteps).pop();
23655
+ return {
23656
+ ...prev,
23657
+ status: chunk.payload.workflowStatus,
23658
+ ...finalStatus === "success" && lastStep?.status === "success" ? { result: lastStep?.output } : finalStatus === "failed" && lastStep?.status === "failed" ? { error: lastStep?.error } : finalStatus === "tripwire" && chunk.payload.tripwire ? { tripwire: chunk.payload.tripwire } : {}
23659
+ };
23660
+ }
23661
+ const { stepCallId, stepName, ...newPayload } = chunk.payload ?? {};
23662
+ const newSteps = {
23663
+ ...prev?.steps,
23664
+ [chunk.payload.id]: {
23665
+ ...prev?.steps?.[chunk.payload.id],
23666
+ ...newPayload
23667
+ }
23668
+ };
23669
+ if (chunk.type === "workflow-step-start") {
23670
+ return {
23671
+ ...prev,
23672
+ steps: newSteps
23673
+ };
23674
+ }
23675
+ if (chunk.type === "workflow-step-suspended") {
23676
+ const suspendedStepIds = Object.entries(newSteps).flatMap(
23677
+ ([stepId, stepResult]) => {
23678
+ if (stepResult?.status === "suspended") {
23679
+ const nestedPath = stepResult?.suspendPayload?.__workflow_meta?.path;
23680
+ return nestedPath ? [[stepId, ...nestedPath]] : [[stepId]];
23681
+ }
23682
+ return [];
23683
+ }
23684
+ );
23685
+ return {
23686
+ ...prev,
23687
+ status: "suspended",
23688
+ steps: newSteps,
23689
+ suspendPayload: chunk.payload.suspendPayload,
23690
+ suspended: suspendedStepIds
23691
+ };
23692
+ }
23693
+ if (chunk.type === "workflow-step-waiting") {
23694
+ return {
23695
+ ...prev,
23696
+ status: "waiting",
23697
+ steps: newSteps
23698
+ };
23699
+ }
23700
+ if (chunk.type === "workflow-step-progress") {
23701
+ const progressSteps = {
23702
+ ...prev?.steps,
23703
+ [chunk.payload.id]: {
23704
+ ...prev?.steps?.[chunk.payload.id],
23705
+ foreachProgress: {
23706
+ completedCount: chunk.payload.completedCount,
23707
+ totalCount: chunk.payload.totalCount,
23708
+ currentIndex: chunk.payload.currentIndex,
23709
+ iterationStatus: chunk.payload.iterationStatus,
23710
+ iterationOutput: chunk.payload.iterationOutput
23711
+ }
23712
+ }
23713
+ };
23714
+ return {
23715
+ ...prev,
23716
+ steps: progressSteps
23717
+ };
23718
+ }
23719
+ if (chunk.type === "workflow-step-result") {
23720
+ return {
23721
+ ...prev,
23722
+ steps: newSteps
23723
+ };
23724
+ }
23725
+ return prev;
23726
+ };
23727
+ const toUIMessage = ({ chunk, conversation, metadata }) => {
23728
+ const result = [...conversation];
23729
+ if (chunk.type.startsWith("data-")) {
23730
+ const lastMessage = result[result.length - 1];
23731
+ if (!lastMessage || lastMessage.role !== "assistant") {
23732
+ const newMessage = {
23733
+ id: `data-${chunk.runId}-${Date.now()}`,
23734
+ role: "assistant",
23735
+ parts: [
23736
+ {
23737
+ type: chunk.type,
23738
+ data: "data" in chunk ? chunk.data : void 0
23739
+ }
23740
+ ],
23741
+ metadata
23742
+ };
23743
+ return [...result, newMessage];
23744
+ }
23745
+ const updatedMessage = {
23746
+ ...lastMessage,
23747
+ parts: [
23748
+ ...lastMessage.parts,
23749
+ {
23750
+ type: chunk.type,
23751
+ data: "data" in chunk ? chunk.data : void 0
23752
+ }
23753
+ ]
23754
+ };
23755
+ return [...result.slice(0, -1), updatedMessage];
23756
+ }
23757
+ switch (chunk.type) {
23758
+ case "tripwire": {
23759
+ const newMessage = {
23760
+ id: `tripwire-${chunk.runId + Date.now()}`,
23761
+ role: "assistant",
23762
+ parts: [
23763
+ {
23764
+ type: "text",
23765
+ text: chunk.payload.reason
23766
+ }
23767
+ ],
23768
+ metadata: {
23769
+ ...metadata,
23770
+ status: "tripwire",
23771
+ tripwire: {
23772
+ retry: chunk.payload.retry,
23773
+ tripwirePayload: chunk.payload.metadata,
23774
+ processorId: chunk.payload.processorId
23775
+ }
23776
+ }
23777
+ };
23778
+ return [...result, newMessage];
23779
+ }
23780
+ case "start": {
23781
+ const newMessage = {
23782
+ id: typeof chunk.payload.messageId === "string" ? chunk.payload.messageId : `start-${chunk.runId + Date.now()}`,
23783
+ role: "assistant",
23784
+ parts: [],
23785
+ metadata
23786
+ };
23787
+ return [...result, newMessage];
23788
+ }
23789
+ case "text-start": {
23790
+ const lastMessage = result[result.length - 1];
23791
+ if (!lastMessage || lastMessage.role !== "assistant") return result;
23792
+ const textId = chunk.payload.id || `text-${Date.now()}`;
23793
+ const newTextPart = {
23794
+ type: "text",
23795
+ text: "",
23796
+ state: "streaming",
23797
+ textId,
23798
+ providerMetadata: chunk.payload.providerMetadata
23799
+ };
23800
+ if (lastMessage.metadata?.completionResult) {
23801
+ const newMessage = {
23802
+ id: `start-${chunk.runId}-${Date.now()}`,
23803
+ role: "assistant",
23804
+ parts: [newTextPart],
23805
+ metadata
23806
+ };
23807
+ return [...result, newMessage];
23808
+ }
23809
+ const parts = [...lastMessage.parts];
23810
+ parts.push(newTextPart);
23811
+ return [
23812
+ ...result.slice(0, -1),
23813
+ {
23814
+ ...lastMessage,
23815
+ parts
23816
+ }
23817
+ ];
23818
+ }
23819
+ case "text-delta": {
23820
+ const lastMessage = result[result.length - 1];
23821
+ if (!lastMessage || lastMessage.role !== "assistant") return result;
23822
+ const parts = [...lastMessage.parts];
23823
+ const textId = chunk.payload.id;
23824
+ let textPartIndex = textId ? parts.findLastIndex((part) => part.type === "text" && part.textId === textId) : -1;
23825
+ if (textPartIndex === -1) {
23826
+ textPartIndex = parts.findLastIndex(
23827
+ (part) => part.type === "text" && part.state === "streaming"
23828
+ );
23829
+ }
23830
+ if (textPartIndex === -1) {
23831
+ const newTextPart = {
23832
+ type: "text",
23833
+ text: chunk.payload.text,
23834
+ state: "streaming",
23835
+ textId,
23836
+ providerMetadata: chunk.payload.providerMetadata
23837
+ };
23838
+ parts.push(newTextPart);
23839
+ } else {
23840
+ const textPart = parts[textPartIndex];
23841
+ if (textPart.type === "text") {
23842
+ const extendedTextPart = textPart;
23843
+ const updatedTextPart = {
23844
+ ...extendedTextPart,
23845
+ text: extendedTextPart.text + chunk.payload.text,
23846
+ state: "streaming"
23847
+ };
23848
+ parts[textPartIndex] = updatedTextPart;
23849
+ }
23850
+ }
23851
+ return [
23852
+ ...result.slice(0, -1),
23853
+ {
23854
+ ...lastMessage,
23855
+ parts
23856
+ }
23857
+ ];
23858
+ }
23859
+ case "reasoning-delta": {
23860
+ const lastMessage = result[result.length - 1];
23861
+ if (!lastMessage || lastMessage.role !== "assistant") {
23862
+ const newMessage = {
23863
+ id: `reasoning-${chunk.runId + Date.now()}`,
23864
+ role: "assistant",
23865
+ parts: [
23866
+ {
23867
+ type: "reasoning",
23868
+ text: chunk.payload.text,
23869
+ state: "streaming",
23870
+ providerMetadata: chunk.payload.providerMetadata
23871
+ }
23872
+ ],
23873
+ metadata
23874
+ };
23875
+ return [...result, newMessage];
23876
+ }
23877
+ const parts = [...lastMessage.parts];
23878
+ let reasoningPartIndex = parts.findIndex((part) => part.type === "reasoning");
23879
+ if (reasoningPartIndex === -1) {
23880
+ parts.push({
23881
+ type: "reasoning",
23882
+ text: chunk.payload.text,
23883
+ state: "streaming",
23884
+ providerMetadata: chunk.payload.providerMetadata
23885
+ });
23886
+ } else {
23887
+ const reasoningPart = parts[reasoningPartIndex];
23888
+ if (reasoningPart.type === "reasoning") {
23889
+ parts[reasoningPartIndex] = {
23890
+ ...reasoningPart,
23891
+ text: reasoningPart.text + chunk.payload.text,
23892
+ state: "streaming"
23893
+ };
23894
+ }
23895
+ }
23896
+ return [
23897
+ ...result.slice(0, -1),
23898
+ {
23899
+ ...lastMessage,
23900
+ parts
23901
+ }
23902
+ ];
23903
+ }
23904
+ case "tool-call": {
23905
+ const lastMessage = result[result.length - 1];
23906
+ if (!lastMessage || lastMessage.role !== "assistant") {
23907
+ const newMessage = {
23908
+ id: `tool-call-${chunk.runId + Date.now()}`,
23909
+ role: "assistant",
23910
+ parts: [
23911
+ {
23912
+ type: "dynamic-tool",
23913
+ toolName: chunk.payload.toolName,
23914
+ toolCallId: chunk.payload.toolCallId,
23915
+ state: "input-available",
23916
+ input: chunk.payload.args,
23917
+ callProviderMetadata: chunk.payload.providerMetadata
23918
+ }
23919
+ ],
23920
+ metadata
23921
+ };
23922
+ return [...result, newMessage];
23923
+ }
23924
+ const parts = [...lastMessage.parts];
23925
+ parts.push({
23926
+ type: "dynamic-tool",
23927
+ toolName: chunk.payload.toolName,
23928
+ toolCallId: chunk.payload.toolCallId,
23929
+ state: "input-available",
23930
+ input: chunk.payload.args,
23931
+ callProviderMetadata: chunk.payload.providerMetadata
23932
+ });
23933
+ return [
23934
+ ...result.slice(0, -1),
23935
+ {
23936
+ ...lastMessage,
23937
+ parts
23938
+ }
23939
+ ];
23940
+ }
23941
+ case "tool-error":
23942
+ case "tool-result": {
23943
+ const lastMessage = result[result.length - 1];
23944
+ if (!lastMessage || lastMessage.role !== "assistant") return result;
23945
+ const parts = [...lastMessage.parts];
23946
+ const toolPartIndex = parts.findIndex(
23947
+ (part) => (part.type === "dynamic-tool" || typeof part.type === "string" && part.type.startsWith("tool-")) && "toolCallId" in part && part.toolCallId === chunk.payload.toolCallId
23948
+ );
23949
+ if (toolPartIndex !== -1) {
23950
+ const toolPart = parts[toolPartIndex];
23951
+ if (toolPart.type === "dynamic-tool" || typeof toolPart.type === "string" && toolPart.type.startsWith("tool-")) {
23952
+ const toolName = "toolName" in toolPart && typeof toolPart.toolName === "string" ? toolPart.toolName : toolPart.type.startsWith("tool-") ? toolPart.type.substring(5) : "";
23953
+ const toolCallId = toolPart.toolCallId;
23954
+ if (chunk.type === "tool-result" && chunk.payload.isError || chunk.type === "tool-error") {
23955
+ const error = chunk.type === "tool-error" ? chunk.payload.error : chunk.payload.result;
23956
+ parts[toolPartIndex] = {
23957
+ type: "dynamic-tool",
23958
+ toolName,
23959
+ toolCallId,
23960
+ state: "output-error",
23961
+ input: toolPart.input,
23962
+ errorText: typeof error === "string" ? error : error instanceof Error ? error.message : error?.message ?? String(error),
23963
+ callProviderMetadata: chunk.payload.providerMetadata
23964
+ };
23965
+ } else {
23966
+ const isWorkflow = Boolean(chunk.payload.result?.result?.steps);
23967
+ const isAgent = chunk?.from === "AGENT";
23968
+ let output;
23969
+ if (isWorkflow) {
23970
+ output = chunk.payload.result?.result;
23971
+ } else if (isAgent) {
23972
+ output = parts[toolPartIndex].output ?? chunk.payload.result;
23973
+ } else {
23974
+ output = chunk.payload.result;
23975
+ }
23976
+ parts[toolPartIndex] = {
23977
+ type: "dynamic-tool",
23978
+ toolName,
23979
+ toolCallId,
23980
+ state: "output-available",
23981
+ input: toolPart.input,
23982
+ output,
23983
+ callProviderMetadata: chunk.payload.providerMetadata
23984
+ };
23985
+ }
23986
+ }
23987
+ }
23988
+ return [
23989
+ ...result.slice(0, -1),
23990
+ {
23991
+ ...lastMessage,
23992
+ parts
23993
+ }
23994
+ ];
23995
+ }
23996
+ case "tool-output": {
23997
+ const lastMessage = result[result.length - 1];
23998
+ if (!lastMessage || lastMessage.role !== "assistant") return result;
23999
+ const parts = [...lastMessage.parts];
24000
+ const toolPartIndex = parts.findIndex(
24001
+ (part) => (part.type === "dynamic-tool" || typeof part.type === "string" && part.type.startsWith("tool-")) && "toolCallId" in part && part.toolCallId === chunk.payload.toolCallId
24002
+ );
24003
+ if (toolPartIndex !== -1) {
24004
+ const toolPart = parts[toolPartIndex];
24005
+ if (toolPart.type === "dynamic-tool" || typeof toolPart.type === "string" && toolPart.type.startsWith("tool-")) {
24006
+ const toolName = "toolName" in toolPart && typeof toolPart.toolName === "string" ? toolPart.toolName : typeof toolPart.type === "string" && toolPart.type.startsWith("tool-") ? toolPart.type.substring(5) : "";
24007
+ const toolCallId = toolPart.toolCallId;
24008
+ const input = toolPart.input;
24009
+ if (chunk.payload.output?.type?.startsWith("workflow-")) {
24010
+ const existingWorkflowState = toolPart.output || {};
24011
+ const updatedWorkflowState = mapWorkflowStreamChunkToWatchResult(
24012
+ existingWorkflowState,
24013
+ chunk.payload.output
24014
+ );
24015
+ parts[toolPartIndex] = {
24016
+ type: "dynamic-tool",
24017
+ toolName,
24018
+ toolCallId,
24019
+ state: "input-streaming",
24020
+ input,
24021
+ output: updatedWorkflowState
24022
+ };
24023
+ } else if (chunk.payload.output?.from === "AGENT" || chunk.payload.output?.from === "USER" && chunk.payload.output?.payload?.output?.type?.startsWith("workflow-")) {
24024
+ return toUIMessageFromAgent(chunk.payload.output, conversation, metadata, toolCallId, toolName);
24025
+ } else {
24026
+ const currentOutput = toolPart.output || [];
24027
+ const existingOutput = Array.isArray(currentOutput) ? currentOutput : [];
24028
+ parts[toolPartIndex] = {
24029
+ type: "dynamic-tool",
24030
+ toolName,
24031
+ toolCallId,
24032
+ state: "input-streaming",
24033
+ input,
24034
+ output: [...existingOutput, chunk.payload.output]
24035
+ };
24036
+ }
24037
+ }
24038
+ }
24039
+ return [
24040
+ ...result.slice(0, -1),
24041
+ {
24042
+ ...lastMessage,
24043
+ parts
24044
+ }
24045
+ ];
24046
+ }
24047
+ case "is-task-complete": {
24048
+ if (chunk.payload.suppressFeedback) return result;
24049
+ const feedback = formatStreamCompletionFeedback(
24050
+ {
24051
+ complete: chunk.payload.passed,
24052
+ scorers: chunk.payload.results,
24053
+ totalDuration: chunk.payload.duration,
24054
+ timedOut: chunk.payload.timedOut,
24055
+ completionReason: chunk.payload.reason
24056
+ },
24057
+ chunk.payload.maxIterationReached
24058
+ );
24059
+ const newMessage = {
24060
+ id: `is-task-complete-${chunk.runId + Date.now()}`,
24061
+ role: "assistant",
24062
+ parts: [
24063
+ {
24064
+ type: "text",
24065
+ text: feedback
24066
+ }
24067
+ ],
24068
+ metadata: {
24069
+ ...metadata,
24070
+ completionResult: {
24071
+ passed: chunk.payload.passed
24072
+ }
24073
+ }
24074
+ };
24075
+ return [...result, newMessage];
24076
+ }
24077
+ case "source": {
24078
+ const lastMessage = result[result.length - 1];
24079
+ if (!lastMessage || lastMessage.role !== "assistant") return result;
24080
+ const parts = [...lastMessage.parts];
24081
+ if (chunk.payload.sourceType === "url") {
24082
+ parts.push({
24083
+ type: "source-url",
24084
+ sourceId: chunk.payload.id,
24085
+ url: chunk.payload.url || "",
24086
+ title: chunk.payload.title,
24087
+ providerMetadata: chunk.payload.providerMetadata
24088
+ });
24089
+ } else if (chunk.payload.sourceType === "document") {
24090
+ parts.push({
24091
+ type: "source-document",
24092
+ sourceId: chunk.payload.id,
24093
+ mediaType: chunk.payload.mimeType || "application/octet-stream",
24094
+ title: chunk.payload.title,
24095
+ filename: chunk.payload.filename,
24096
+ providerMetadata: chunk.payload.providerMetadata
24097
+ });
24098
+ }
24099
+ return [
24100
+ ...result.slice(0, -1),
24101
+ {
24102
+ ...lastMessage,
24103
+ parts
24104
+ }
24105
+ ];
24106
+ }
24107
+ case "file": {
24108
+ const lastMessage = result[result.length - 1];
24109
+ if (!lastMessage || lastMessage.role !== "assistant") return result;
24110
+ const parts = [...lastMessage.parts];
24111
+ let url;
24112
+ if (typeof chunk.payload.data === "string") {
24113
+ url = chunk.payload.base64 ? `data:${chunk.payload.mimeType};base64,${chunk.payload.data}` : `data:${chunk.payload.mimeType},${encodeURIComponent(chunk.payload.data)}`;
24114
+ } else {
24115
+ const base64 = btoa(String.fromCharCode(...chunk.payload.data));
24116
+ url = `data:${chunk.payload.mimeType};base64,${base64}`;
24117
+ }
24118
+ parts.push({
24119
+ type: "file",
24120
+ mediaType: chunk.payload.mimeType,
24121
+ url,
24122
+ providerMetadata: chunk.payload.providerMetadata
24123
+ });
24124
+ return [
24125
+ ...result.slice(0, -1),
24126
+ {
24127
+ ...lastMessage,
24128
+ parts
24129
+ }
24130
+ ];
24131
+ }
24132
+ case "tool-call-approval": {
24133
+ const lastMessage = result[result.length - 1];
24134
+ if (!lastMessage || lastMessage.role !== "assistant") return result;
24135
+ const lastRequireApprovalMetadata = lastMessage.metadata?.mode === "stream" ? lastMessage.metadata?.requireApprovalMetadata : {};
24136
+ return [
24137
+ ...result.slice(0, -1),
24138
+ {
24139
+ ...lastMessage,
24140
+ metadata: {
24141
+ ...lastMessage.metadata,
24142
+ mode: "stream",
24143
+ requireApprovalMetadata: {
24144
+ ...lastRequireApprovalMetadata,
24145
+ [chunk.payload.toolName]: {
24146
+ toolCallId: chunk.payload.toolCallId,
24147
+ toolName: chunk.payload.toolName,
24148
+ args: chunk.payload.args
24149
+ }
24150
+ }
24151
+ }
24152
+ }
24153
+ ];
24154
+ }
24155
+ case "tool-call-suspended": {
24156
+ const lastMessage = result[result.length - 1];
24157
+ if (!lastMessage || lastMessage.role !== "assistant") return result;
24158
+ const lastSuspendedTools = lastMessage.metadata?.mode === "stream" ? lastMessage.metadata?.suspendedTools : {};
24159
+ return [
24160
+ ...result.slice(0, -1),
24161
+ {
24162
+ ...lastMessage,
24163
+ metadata: {
24164
+ ...lastMessage.metadata,
24165
+ mode: "stream",
24166
+ suspendedTools: {
24167
+ ...lastSuspendedTools,
24168
+ [chunk.payload.toolName]: {
24169
+ toolCallId: chunk.payload.toolCallId,
24170
+ toolName: chunk.payload.toolName,
24171
+ args: chunk.payload.args,
24172
+ suspendPayload: chunk.payload.suspendPayload
24173
+ }
24174
+ }
24175
+ }
24176
+ }
24177
+ ];
24178
+ }
24179
+ case "finish": {
24180
+ const lastMessage = result[result.length - 1];
24181
+ if (!lastMessage || lastMessage.role !== "assistant") return result;
24182
+ const parts = lastMessage.parts.map((part) => {
24183
+ if (typeof part === "object" && part !== null && "type" in part && "state" in part && part.state === "streaming") {
24184
+ if (part.type === "text" || part.type === "reasoning") {
24185
+ return { ...part, state: "done" };
24186
+ }
24187
+ }
24188
+ return part;
24189
+ });
24190
+ return [
24191
+ ...result.slice(0, -1),
24192
+ {
24193
+ ...lastMessage,
24194
+ parts
24195
+ }
24196
+ ];
24197
+ }
24198
+ case "error": {
24199
+ const newMessage = {
24200
+ id: `error-${chunk.runId + Date.now()}`,
24201
+ role: "assistant",
24202
+ parts: [
24203
+ {
24204
+ type: "text",
24205
+ text: typeof chunk.payload.error === "string" ? chunk.payload.error : JSON.stringify(chunk.payload.error)
24206
+ }
24207
+ ],
24208
+ metadata: {
24209
+ ...metadata,
24210
+ status: "error"
24211
+ }
24212
+ };
24213
+ return [...result, newMessage];
24214
+ }
24215
+ // For all other chunk types, return conversation unchanged
24216
+ default:
24217
+ return result;
24218
+ }
24219
+ };
24220
+ const toUIMessageFromAgent = (chunk, conversation, metadata, parentToolCallId, parentToolName) => {
24221
+ const lastMessage = conversation[conversation.length - 1];
24222
+ if (!lastMessage || lastMessage.role !== "assistant") return conversation;
24223
+ const parts = [...lastMessage.parts];
24224
+ if (chunk.type === "text-delta") {
24225
+ const agentChunk = chunk.payload;
24226
+ const toolPartIndex = parts.findIndex(
24227
+ (part) => part.type === "dynamic-tool" && (parentToolCallId && part.toolCallId === parentToolCallId || parentToolName && part.toolName === parentToolName)
24228
+ );
24229
+ if (toolPartIndex === -1) return conversation;
24230
+ const toolPart = parts[toolPartIndex];
24231
+ const childMessages = toolPart?.output?.childMessages || [];
24232
+ const lastChildMessage = childMessages[childMessages.length - 1];
24233
+ const textMessage = { type: "text", content: (lastChildMessage?.content || "") + agentChunk.text };
24234
+ const nextMessages = lastChildMessage?.type === "text" ? [...childMessages.slice(0, -1), textMessage] : [...childMessages, textMessage];
24235
+ parts[toolPartIndex] = {
24236
+ ...toolPart,
24237
+ output: {
24238
+ childMessages: nextMessages
24239
+ }
24240
+ };
24241
+ } else if (chunk.type === "tool-call") {
24242
+ const agentChunk = chunk.payload;
24243
+ const toolPartIndex = parts.findIndex(
24244
+ (part) => part.type === "dynamic-tool" && (parentToolCallId && part.toolCallId === parentToolCallId || parentToolName && part.toolName === parentToolName)
24245
+ );
24246
+ if (toolPartIndex === -1) return conversation;
24247
+ const toolPart = parts[toolPartIndex];
24248
+ const childMessages = toolPart?.output?.childMessages || [];
24249
+ parts[toolPartIndex] = {
24250
+ ...toolPart,
24251
+ output: {
24252
+ ...toolPart?.output,
24253
+ childMessages: [
24254
+ ...childMessages,
24255
+ {
24256
+ type: "tool",
24257
+ toolCallId: agentChunk.toolCallId,
24258
+ toolName: agentChunk.toolName,
24259
+ args: agentChunk.args
24260
+ }
24261
+ ]
24262
+ }
24263
+ };
24264
+ } else if (chunk.type === "tool-output") {
24265
+ const agentChunk = chunk.payload;
24266
+ const toolPartIndex = parts.findIndex(
24267
+ (part) => part.type === "dynamic-tool" && (parentToolCallId && part.toolCallId === parentToolCallId || parentToolName && part.toolName === parentToolName)
24268
+ );
24269
+ if (toolPartIndex === -1) return conversation;
24270
+ const toolPart = parts[toolPartIndex];
24271
+ if (agentChunk?.output?.type?.startsWith("workflow-")) {
24272
+ const childMessages = toolPart?.output?.childMessages || [];
24273
+ const lastToolIndex = childMessages.length - 1;
24274
+ const currentMessage = childMessages[lastToolIndex];
24275
+ const actualExistingWorkflowState = currentMessage?.toolOutput || {};
24276
+ const updatedWorkflowState = mapWorkflowStreamChunkToWatchResult(actualExistingWorkflowState, agentChunk.output);
24277
+ if (lastToolIndex >= 0 && childMessages[lastToolIndex]?.type === "tool") {
24278
+ parts[toolPartIndex] = {
24279
+ ...toolPart,
24280
+ output: {
24281
+ ...toolPart?.output,
24282
+ childMessages: [
24283
+ ...childMessages.slice(0, -1),
24284
+ {
24285
+ ...currentMessage,
24286
+ toolOutput: { ...updatedWorkflowState, runId: agentChunk.output.runId }
24287
+ }
24288
+ ]
24289
+ }
24290
+ };
24291
+ }
24292
+ }
24293
+ } else if (chunk.type === "tool-result") {
24294
+ const agentChunk = chunk.payload;
24295
+ const toolPartIndex = parts.findIndex(
24296
+ (part) => part.type === "dynamic-tool" && (parentToolCallId && part.toolCallId === parentToolCallId || parentToolName && part.toolName === parentToolName)
24297
+ );
24298
+ if (toolPartIndex === -1) return conversation;
24299
+ const toolPart = parts[toolPartIndex];
24300
+ const childMessages = toolPart?.output?.childMessages || [];
24301
+ const lastToolIndex = childMessages.length - 1;
24302
+ const isWorkflow = agentChunk?.toolName?.startsWith("workflow-");
24303
+ if (lastToolIndex >= 0 && childMessages[lastToolIndex]?.type === "tool") {
24304
+ parts[toolPartIndex] = {
24305
+ ...toolPart,
24306
+ output: {
24307
+ ...toolPart?.output,
24308
+ childMessages: [
24309
+ ...childMessages.slice(0, -1),
24310
+ {
24311
+ ...childMessages[lastToolIndex],
24312
+ toolOutput: isWorkflow ? { ...agentChunk.result?.result, runId: agentChunk.result?.runId } : agentChunk.result
24313
+ }
24314
+ ]
24315
+ }
24316
+ };
24317
+ }
24318
+ }
24319
+ return [
24320
+ ...conversation.slice(0, -1),
24321
+ {
24322
+ ...lastMessage,
24323
+ parts
24324
+ }
24325
+ ];
24326
+ };
24327
+
24328
+ const toAssistantUIMessage = (message) => {
24329
+ const extendedMessage = message;
24330
+ const content = message.parts.map((part) => {
24331
+ if (part.type === "text") {
24332
+ return {
24333
+ type: "text",
24334
+ text: part.text,
24335
+ metadata: message.metadata
24336
+ };
24337
+ }
24338
+ if (part.type === "reasoning") {
24339
+ return {
24340
+ type: "reasoning",
24341
+ text: part.text,
24342
+ metadata: message.metadata
24343
+ };
24344
+ }
24345
+ if (part.type === "source-url") {
24346
+ return {
24347
+ type: "source",
24348
+ sourceType: "url",
24349
+ id: part.sourceId,
24350
+ url: part.url,
24351
+ title: part.title,
24352
+ metadata: message.metadata
24353
+ };
24354
+ }
24355
+ if (part.type === "source-document") {
24356
+ return {
24357
+ type: "file",
24358
+ filename: part.filename,
24359
+ mimeType: part.mediaType,
24360
+ data: "",
24361
+ // Source documents don't have inline data
24362
+ metadata: message.metadata
24363
+ };
24364
+ }
24365
+ if (part.type === "file") {
24366
+ const type = part.mediaType.includes("image/") ? "image" : "file";
24367
+ if (type === "file") {
24368
+ return {
24369
+ type,
24370
+ mimeType: part.mediaType,
24371
+ data: part.url,
24372
+ // Use URL as data source
24373
+ metadata: message.metadata
24374
+ };
24375
+ }
24376
+ if (type === "image") {
24377
+ return {
24378
+ type,
24379
+ image: part.url,
24380
+ metadata: message.metadata
24381
+ };
24382
+ }
24383
+ }
24384
+ if (part.type === "dynamic-tool") {
24385
+ const baseToolCall = {
24386
+ type: "tool-call",
24387
+ toolCallId: part.toolCallId,
24388
+ toolName: part.toolName,
24389
+ argsText: JSON.stringify(part.input),
24390
+ args: part.input,
24391
+ metadata: message.metadata
24392
+ };
24393
+ if (part.state === "output-error" && "errorText" in part) {
24394
+ return { ...baseToolCall, result: part.errorText, isError: true };
24395
+ }
24396
+ if ("output" in part) {
24397
+ return { ...baseToolCall, result: part.output };
24398
+ }
24399
+ return baseToolCall;
24400
+ }
24401
+ if (part.type.startsWith("tool-") && part.state !== "input-available") {
24402
+ const toolName2 = "toolName" in part && typeof part.toolName === "string" ? part.toolName : part.type.substring(5);
24403
+ const { suspendedToolRunId, ...cleanInput } = "input" in part ? part.input : {};
24404
+ const baseToolCall = {
24405
+ type: "tool-call",
24406
+ toolCallId: "toolCallId" in part && typeof part.toolCallId === "string" ? part.toolCallId : "",
24407
+ toolName: toolName2,
24408
+ argsText: JSON.stringify(cleanInput ?? {}),
24409
+ args: cleanInput ?? {},
24410
+ metadata: message.metadata
24411
+ };
24412
+ if ("output" in part) {
24413
+ return { ...baseToolCall, result: part.output };
24414
+ } else if ("error" in part) {
24415
+ return { ...baseToolCall, result: part.error, isError: true };
24416
+ }
24417
+ return baseToolCall;
24418
+ }
24419
+ const toolName = "toolName" in part && typeof part.toolName === "string" ? part.toolName : part.type.startsWith("tool-") ? part.type.substring(5) : "";
24420
+ const requireApprovalMetadata = extendedMessage.metadata?.requireApprovalMetadata;
24421
+ const suspendedTools = extendedMessage.metadata?.suspendedTools;
24422
+ const partToolCallId = "toolCallId" in part && typeof part.toolCallId === "string" ? part.toolCallId : void 0;
24423
+ const suspensionData = toolName ? requireApprovalMetadata?.[toolName] ?? suspendedTools?.[toolName] : void 0;
24424
+ if (suspensionData) {
24425
+ const { suspendedToolRunId, ...cleanInput } = "input" in part ? part.input : {};
24426
+ return {
24427
+ type: "tool-call",
24428
+ toolCallId: partToolCallId,
24429
+ toolName,
24430
+ argsText: JSON.stringify(cleanInput ?? {}),
24431
+ args: cleanInput,
24432
+ metadata: extendedMessage.metadata
24433
+ };
24434
+ }
24435
+ if (part.type.startsWith("data-")) {
24436
+ return {
24437
+ type: "data",
24438
+ name: part.type.substring(5),
24439
+ // Extract name from 'data-{name}'
24440
+ data: part.data,
24441
+ metadata: message.metadata
24442
+ };
24443
+ }
24444
+ return {
24445
+ type: "text",
24446
+ text: "",
24447
+ metadata: message.metadata
24448
+ };
24449
+ });
24450
+ let status;
24451
+ if (message.role === "assistant" && content.length > 0) {
24452
+ const hasStreamingParts = message.parts.some(
24453
+ (part) => part.type === "text" && "state" in part && part.state === "streaming" || part.type === "reasoning" && "state" in part && part.state === "streaming"
24454
+ );
24455
+ const hasToolCalls = message.parts.some((part) => part.type === "dynamic-tool" || part.type.startsWith("tool-"));
24456
+ const hasInputAvailableTools = message.parts.some(
24457
+ (part) => part.type === "dynamic-tool" && part.state === "input-available"
24458
+ );
24459
+ const hasErrorTools = message.parts.some(
24460
+ (part) => part.type === "dynamic-tool" && part.state === "output-error" || part.type.startsWith("tool-") && "error" in part
24461
+ );
24462
+ if (hasStreamingParts) {
24463
+ status = { type: "running" };
24464
+ } else if (hasInputAvailableTools && hasToolCalls) {
24465
+ status = { type: "requires-action", reason: "tool-calls" };
24466
+ } else if (hasErrorTools) {
24467
+ status = { type: "incomplete", reason: "error" };
24468
+ } else {
24469
+ status = { type: "complete", reason: "stop" };
24454
24470
  }
24455
- lines.push("");
24456
- }
24457
- if (result.complete) {
24458
- lines.push("\n\n\u2705 The task is complete.");
24459
- } else if (maxIterationReached) {
24460
- lines.push("\n\n\u26A0\uFE0F Max iterations reached.");
24461
- } else {
24462
- lines.push("\n\n\u{1F504} Will continue working on the task.");
24463
24471
  }
24464
- return lines.join("\n");
24465
- }
24466
- z10.z.object({
24467
- isComplete: z10.z.boolean().describe("Whether the task is complete"),
24468
- completionReason: z10.z.string().describe("Explanation of why the task is or is not complete"),
24469
- finalResult: z10.z.string().optional().describe("The final result text to return to the user. omit if primitive result is sufficient")
24470
- });
24471
- z10.z.object({
24472
- finalResult: z10.z.string().optional().describe("The final result text to return to the user, omit if primitive result is sufficient")
24473
- });
24474
- z10.enum(["agent", "workflow", "none", "tool"]);
24475
-
24476
- // src/agent/agent-legacy.ts
24477
- __toESM$3(require_fast_deep_equal());
24472
+ const threadMessage = {
24473
+ role: message.role,
24474
+ content,
24475
+ id: message.id,
24476
+ createdAt: extendedMessage.createdAt,
24477
+ status,
24478
+ attachments: extendedMessage.experimental_attachments
24479
+ };
24480
+ return threadMessage;
24481
+ };
24478
24482
 
24479
- // src/agent/workflows/prepare-stream/prepare-memory-step.ts
24480
- __toESM$3(require_fast_deep_equal());
24481
- var coreToolSchema = z10.z.object({
24482
- id: z10.z.string().optional(),
24483
- description: z10.z.string().optional(),
24484
- parameters: z10.z.union([
24485
- z10.z.record(z10.z.string(), z10.z.any()),
24486
- // JSON Schema as object
24487
- z10.z.any()
24488
- // Zod schema or other schema types - validated at tool execution
24489
- ]),
24490
- outputSchema: z10.z.union([z10.z.record(z10.z.string(), z10.z.any()), z10.z.any()]).optional(),
24491
- execute: z10.z.optional(z10.z.function(z10.z.tuple([z10.z.any(), z10.z.any()]), z10.z.promise(z10.z.any()))),
24492
- toModelOutput: z10.z.optional(z10.z.function(z10.z.tuple([z10.z.any()]), z10.z.any())),
24493
- type: z10.z.union([z10.z.literal("function"), z10.z.literal("provider-defined"), z10.z.undefined()]).optional(),
24494
- args: z10.z.record(z10.z.string(), z10.z.any()).optional()
24495
- });
24496
- var storageThreadSchema = z10.z.object({
24497
- id: z10.z.string(),
24498
- title: z10.z.string().optional(),
24499
- resourceId: z10.z.string(),
24500
- createdAt: z10.z.date(),
24501
- updatedAt: z10.z.date(),
24502
- metadata: z10.z.record(z10.z.string(), z10.z.any()).optional()
24503
- });
24504
- z10.z.object({
24505
- convertedTools: z10.z.record(z10.z.string(), coreToolSchema)
24506
- });
24507
- z10.z.object({
24508
- threadExists: z10.z.boolean(),
24509
- thread: storageThreadSchema.optional(),
24510
- messageList: z10.z.instanceof(MessageList$1),
24511
- /** Shared processor states map that persists across loop iterations for both input and output processors */
24512
- processorStates: z10.z.instanceof(Map),
24513
- /** Tripwire data when input processor triggered abort */
24514
- tripwire: z10.z.object({
24515
- reason: z10.z.string(),
24516
- retry: z10.z.boolean().optional(),
24517
- metadata: z10.z.unknown().optional(),
24518
- processorId: z10.z.string().optional()
24519
- }).optional()
24520
- });
24521
- var DEFAULT_CACHE_MAX_SIZE = 1e3;
24522
- new L({
24523
- max: DEFAULT_CACHE_MAX_SIZE
24524
- });
24483
+ const resolveInitialMessages = (messages) => {
24484
+ const messagesLength = messages.length;
24485
+ return messages.map((message, index) => {
24486
+ const networkPart = message.parts.find(
24487
+ (part) => typeof part === "object" && part !== null && "type" in part && part.type === "text" && "text" in part && typeof part.text === "string" && part.text.includes('"isNetwork":true')
24488
+ );
24489
+ if (networkPart && networkPart.type === "text") {
24490
+ try {
24491
+ const json = JSON.parse(networkPart.text);
24492
+ if (json.isNetwork === true) {
24493
+ const selectionReason = json.selectionReason || "";
24494
+ const primitiveType = json.primitiveType || "";
24495
+ const primitiveId = json.primitiveId || "";
24496
+ const finalResult = json.finalResult;
24497
+ const messages2 = finalResult?.messages || [];
24498
+ const childMessages = [];
24499
+ const toolResultMap = /* @__PURE__ */ new Map();
24500
+ for (const msg of messages2) {
24501
+ if (Array.isArray(msg.content)) {
24502
+ for (const part of msg.content) {
24503
+ if (typeof part === "object" && part.type === "tool-result") {
24504
+ toolResultMap.set(part.toolCallId, part);
24505
+ }
24506
+ }
24507
+ }
24508
+ }
24509
+ for (const msg of messages2) {
24510
+ if (msg.type === "tool-call" && Array.isArray(msg.content)) {
24511
+ for (const part of msg.content) {
24512
+ if (typeof part === "object" && part.type === "tool-call") {
24513
+ const toolCallContent = part;
24514
+ const toolResult = toolResultMap.get(toolCallContent.toolCallId);
24515
+ const isWorkflow = Boolean(toolResult?.result?.result?.steps);
24516
+ childMessages.push({
24517
+ type: "tool",
24518
+ toolCallId: toolCallContent.toolCallId,
24519
+ toolName: toolCallContent.toolName,
24520
+ args: toolCallContent.args,
24521
+ toolOutput: isWorkflow ? toolResult?.result?.result : toolResult?.result
24522
+ });
24523
+ }
24524
+ }
24525
+ }
24526
+ }
24527
+ if (finalResult && finalResult.text) {
24528
+ childMessages.push({
24529
+ type: "text",
24530
+ content: finalResult.text
24531
+ });
24532
+ }
24533
+ const result = primitiveType === "tool" ? finalResult?.result : {
24534
+ childMessages,
24535
+ result: finalResult?.text || ""
24536
+ };
24537
+ const nextMessage = {
24538
+ role: "assistant",
24539
+ parts: [
24540
+ {
24541
+ type: "dynamic-tool",
24542
+ toolCallId: primitiveId,
24543
+ toolName: primitiveId,
24544
+ state: "output-available",
24545
+ input: json.input,
24546
+ output: result
24547
+ }
24548
+ ],
24549
+ id: message.id,
24550
+ metadata: {
24551
+ ...message.metadata,
24552
+ mode: "network",
24553
+ selectionReason,
24554
+ agentInput: json.input,
24555
+ hasMoreMessages: index < messagesLength - 1,
24556
+ from: primitiveType === "agent" ? "AGENT" : primitiveType === "tool" ? "TOOL" : "WORKFLOW"
24557
+ }
24558
+ };
24559
+ return nextMessage;
24560
+ }
24561
+ } catch (error) {
24562
+ return message;
24563
+ }
24564
+ }
24565
+ const extendedMessage = message;
24566
+ const pendingToolApprovals = extendedMessage.metadata?.pendingToolApprovals;
24567
+ if (pendingToolApprovals && typeof pendingToolApprovals === "object") {
24568
+ return {
24569
+ ...message,
24570
+ metadata: {
24571
+ ...message.metadata,
24572
+ mode: "stream",
24573
+ requireApprovalMetadata: pendingToolApprovals
24574
+ }
24575
+ };
24576
+ }
24577
+ const suspendedTools = extendedMessage.metadata?.suspendedTools;
24578
+ if (suspendedTools && typeof suspendedTools === "object") {
24579
+ return {
24580
+ ...message,
24581
+ metadata: {
24582
+ ...message.metadata,
24583
+ mode: "stream",
24584
+ suspendedTools
24585
+ }
24586
+ };
24587
+ }
24588
+ return message;
24589
+ })?.filter((message) => {
24590
+ const completionModes = ["generate", "stream", "network"];
24591
+ if (message.role === "assistant" && completionModes.includes(message?.metadata?.mode)) {
24592
+ const meta = message.metadata;
24593
+ if (meta?.isTaskCompleteResult?.suppressFeedback || meta?.completionResult?.suppressFeedback) {
24594
+ return false;
24595
+ }
24596
+ return true;
24597
+ }
24598
+ return true;
24599
+ });
24600
+ };
24601
+ const resolveToChildMessages = (messages) => {
24602
+ const assistantMessage = messages.find((message) => message.role === "assistant");
24603
+ if (!assistantMessage) return [];
24604
+ const parts = assistantMessage.parts;
24605
+ let childMessages = [];
24606
+ for (const part of parts) {
24607
+ const toolPart = part;
24608
+ if (part.type.startsWith("tool-")) {
24609
+ const toolName = part.type.substring("tool-".length);
24610
+ const isWorkflow = toolName.startsWith("workflow-");
24611
+ childMessages.push({
24612
+ type: "tool",
24613
+ toolCallId: toolPart.toolCallId,
24614
+ toolName,
24615
+ args: toolPart.input,
24616
+ toolOutput: isWorkflow ? { ...toolPart.output?.result, runId: toolPart.output?.runId } : toolPart.output
24617
+ });
24618
+ }
24619
+ if (part.type === "text") {
24620
+ childMessages.push({
24621
+ type: "text",
24622
+ content: toolPart.text
24623
+ });
24624
+ }
24625
+ }
24626
+ return childMessages;
24627
+ };
24525
24628
 
24526
24629
  class AISdkNetworkTransformer {
24527
24630
  transform({ chunk, conversation, metadata }) {
@@ -24539,6 +24642,7 @@ class AISdkNetworkTransformer {
24539
24642
  return this.handleToolConversation(chunk, newConversation, metadata);
24540
24643
  }
24541
24644
  if (chunk.type === "network-validation-end") {
24645
+ if (chunk.payload.suppressFeedback) return newConversation;
24542
24646
  const feedback = formatCompletionFeedback(
24543
24647
  {
24544
24648
  complete: chunk.payload.passed,
@@ -26267,4 +26371,4 @@ exports.useCreateWorkflowRun = useCreateWorkflowRun;
26267
26371
  exports.useEntity = useEntity;
26268
26372
  exports.useMastraClient = useMastraClient;
26269
26373
  exports.useStreamWorkflow = useStreamWorkflow;
26270
- //# sourceMappingURL=index-CU6GBOIY.cjs.map
26374
+ //# sourceMappingURL=index-0ViTRi6s.cjs.map