@mastra/react 0.0.0-structured-output-issue-20260302184919 → 0.0.0-structured-output-errors-20260409185629

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 (134) hide show
  1. package/CHANGELOG.md +687 -2
  2. package/LICENSE.md +15 -0
  3. package/dist/{src/agent → agent}/hooks.d.ts +12 -9
  4. package/dist/agent/hooks.d.ts.map +1 -0
  5. package/dist/{src/agent → agent}/types.d.ts +1 -0
  6. package/dist/agent/types.d.ts.map +1 -0
  7. package/dist/index.cjs +2874 -66
  8. package/dist/index.cjs.map +1 -1
  9. package/dist/index.d.ts +9 -2
  10. package/dist/index.d.ts.map +1 -0
  11. package/dist/index.js +2815 -1
  12. package/dist/index.js.map +1 -1
  13. package/dist/lib/ai-sdk/index.d.ts +5 -0
  14. package/dist/lib/ai-sdk/index.d.ts.map +1 -0
  15. package/dist/{src/lib → lib}/ai-sdk/memory/resolveInitialMessages.d.ts +2 -1
  16. package/dist/lib/ai-sdk/memory/resolveInitialMessages.d.ts.map +1 -0
  17. package/dist/{src/lib → lib}/ai-sdk/transformers/AISdkNetworkTransformer.d.ts +4 -3
  18. package/dist/lib/ai-sdk/transformers/AISdkNetworkTransformer.d.ts.map +1 -0
  19. package/dist/lib/ai-sdk/transformers/types.d.ts +11 -0
  20. package/dist/lib/ai-sdk/transformers/types.d.ts.map +1 -0
  21. package/dist/{src/lib → lib}/ai-sdk/types.d.ts +3 -2
  22. package/dist/lib/ai-sdk/types.d.ts.map +1 -0
  23. package/dist/lib/ai-sdk/utils/formatCompletionFeedback.d.ts +19 -0
  24. package/dist/lib/ai-sdk/utils/formatCompletionFeedback.d.ts.map +1 -0
  25. package/dist/{src/lib → lib}/ai-sdk/utils/fromCoreUserMessageToUIMessage.d.ts +3 -2
  26. package/dist/lib/ai-sdk/utils/fromCoreUserMessageToUIMessage.d.ts.map +1 -0
  27. package/dist/{src/lib → lib}/ai-sdk/utils/toAssistantUIMessage.d.ts +3 -2
  28. package/dist/lib/ai-sdk/utils/toAssistantUIMessage.d.ts.map +1 -0
  29. package/dist/{src/lib → lib}/ai-sdk/utils/toUIMessage.d.ts +4 -3
  30. package/dist/lib/ai-sdk/utils/toUIMessage.d.ts.map +1 -0
  31. package/dist/{src/lib → lib}/use-mutation.d.ts +1 -0
  32. package/dist/lib/use-mutation.d.ts.map +1 -0
  33. package/dist/mastra-client-context.d.ts +26 -0
  34. package/dist/mastra-client-context.d.ts.map +1 -0
  35. package/dist/mastra-react-provider.d.ts +5 -0
  36. package/dist/mastra-react-provider.d.ts.map +1 -0
  37. package/dist/react.css +184 -322
  38. package/dist/{src/ui → ui}/Code/Code.d.ts +2 -1
  39. package/dist/ui/Code/Code.d.ts.map +1 -0
  40. package/dist/ui/Code/highlight.d.ts +4 -0
  41. package/dist/ui/Code/highlight.d.ts.map +1 -0
  42. package/dist/ui/Code/index.d.ts +2 -0
  43. package/dist/ui/Code/index.d.ts.map +1 -0
  44. package/dist/{src/ui → ui}/Entity/Entity.d.ts +2 -1
  45. package/dist/ui/Entity/Entity.d.ts.map +1 -0
  46. package/dist/{src/ui → ui}/Entity/Entry.d.ts +2 -1
  47. package/dist/ui/Entity/Entry.d.ts.map +1 -0
  48. package/dist/{src/ui → ui}/Entity/ToolApproval.d.ts +1 -0
  49. package/dist/ui/Entity/ToolApproval.d.ts.map +1 -0
  50. package/dist/{src/ui → ui}/Entity/context.d.ts +4 -3
  51. package/dist/ui/Entity/context.d.ts.map +1 -0
  52. package/dist/ui/Entity/index.d.ts +5 -0
  53. package/dist/ui/Entity/index.d.ts.map +1 -0
  54. package/dist/{src/ui → ui}/Entity/types.d.ts +1 -0
  55. package/dist/ui/Entity/types.d.ts.map +1 -0
  56. package/dist/{src/ui → ui}/Icon/Icon.d.ts +2 -1
  57. package/dist/ui/Icon/Icon.d.ts.map +1 -0
  58. package/dist/ui/Icon/index.d.ts +2 -0
  59. package/dist/ui/Icon/index.d.ts.map +1 -0
  60. package/dist/{src/ui → ui}/IconButton/IconButton.d.ts +2 -1
  61. package/dist/ui/IconButton/IconButton.d.ts.map +1 -0
  62. package/dist/ui/IconButton/index.d.ts +2 -0
  63. package/dist/ui/IconButton/index.d.ts.map +1 -0
  64. package/dist/{src/ui → ui}/Icons/AgentIcon.d.ts +2 -1
  65. package/dist/ui/Icons/AgentIcon.d.ts.map +1 -0
  66. package/dist/{src/ui → ui}/Icons/ToolsIcon.d.ts +2 -1
  67. package/dist/ui/Icons/ToolsIcon.d.ts.map +1 -0
  68. package/dist/{src/ui → ui}/Icons/WorkflowIcon.d.ts +2 -1
  69. package/dist/ui/Icons/WorkflowIcon.d.ts.map +1 -0
  70. package/dist/ui/Icons/index.d.ts +4 -0
  71. package/dist/ui/Icons/index.d.ts.map +1 -0
  72. package/dist/{src/ui → ui}/Message/Message.d.ts +2 -1
  73. package/dist/ui/Message/Message.d.ts.map +1 -0
  74. package/dist/ui/Message/index.d.ts +2 -0
  75. package/dist/ui/Message/index.d.ts.map +1 -0
  76. package/dist/{src/ui → ui}/Tooltip/Tooltip.d.ts +2 -1
  77. package/dist/ui/Tooltip/Tooltip.d.ts.map +1 -0
  78. package/dist/ui/Tooltip/index.d.ts +2 -0
  79. package/dist/ui/Tooltip/index.d.ts.map +1 -0
  80. package/dist/ui/index.d.ts +8 -0
  81. package/dist/ui/index.d.ts.map +1 -0
  82. package/dist/{src/workflows → workflows}/hooks.d.ts +5 -4
  83. package/dist/workflows/hooks.d.ts.map +1 -0
  84. package/dist/workflows/index.d.ts +3 -0
  85. package/dist/workflows/index.d.ts.map +1 -0
  86. package/dist/{src/workflows → workflows}/types.d.ts +4 -3
  87. package/dist/workflows/types.d.ts.map +1 -0
  88. package/dist/{src/workflows → workflows}/use-stream-workflow.d.ts +6 -5
  89. package/dist/workflows/use-stream-workflow.d.ts.map +1 -0
  90. package/package.json +32 -28
  91. package/dist/chunk-REDZDNFN-8Zc7Z9Ng.cjs +0 -251
  92. package/dist/chunk-REDZDNFN-8Zc7Z9Ng.cjs.map +0 -1
  93. package/dist/chunk-REDZDNFN-ByJ-H6Es.js +0 -249
  94. package/dist/chunk-REDZDNFN-ByJ-H6Es.js.map +0 -1
  95. package/dist/index--xXlugUp.js +0 -26288
  96. package/dist/index--xXlugUp.js.map +0 -1
  97. package/dist/index-BaK_Y6TP.cjs +0 -185
  98. package/dist/index-BaK_Y6TP.cjs.map +0 -1
  99. package/dist/index-C1OzXW5i.js +0 -180
  100. package/dist/index-C1OzXW5i.js.map +0 -1
  101. package/dist/index-DlzF_2Lc.cjs +0 -26374
  102. package/dist/index-DlzF_2Lc.cjs.map +0 -1
  103. package/dist/src/index.d.ts +0 -7
  104. package/dist/src/lib/ai-sdk/index.d.ts +0 -4
  105. package/dist/src/lib/ai-sdk/memory/resolveInitialMessages.test.d.ts +0 -1
  106. package/dist/src/lib/ai-sdk/transformers/AISdkNetworkTransformer.test.d.ts +0 -1
  107. package/dist/src/lib/ai-sdk/transformers/types.d.ts +0 -10
  108. package/dist/src/lib/ai-sdk/utils/fromCoreUserMessageToUIMessage.test.d.ts +0 -1
  109. package/dist/src/lib/ai-sdk/utils/toAssistantUIMessage.test.d.ts +0 -1
  110. package/dist/src/lib/ai-sdk/utils/toUIMessage.test.d.ts +0 -1
  111. package/dist/src/mastra-client-context.d.ts +0 -12
  112. package/dist/src/mastra-react-provider.d.ts +0 -4
  113. package/dist/src/ui/Code/highlight.d.ts +0 -3
  114. package/dist/src/ui/Code/index.d.ts +0 -1
  115. package/dist/src/ui/Entity/Entity.stories.d.ts +0 -22
  116. package/dist/src/ui/Entity/index.d.ts +0 -4
  117. package/dist/src/ui/Icon/index.d.ts +0 -1
  118. package/dist/src/ui/IconButton/IconButton.stories.d.ts +0 -12
  119. package/dist/src/ui/IconButton/index.d.ts +0 -1
  120. package/dist/src/ui/Icons/index.d.ts +0 -3
  121. package/dist/src/ui/Message/Message.stories.d.ts +0 -13
  122. package/dist/src/ui/Message/index.d.ts +0 -1
  123. package/dist/src/ui/Tooltip/Tooltip.stories.d.ts +0 -12
  124. package/dist/src/ui/Tooltip/index.d.ts +0 -1
  125. package/dist/src/ui/index.d.ts +0 -7
  126. package/dist/src/workflows/index.d.ts +0 -2
  127. package/dist/token-6GSAFR2W-XRCSVUPZ-BJL0Ab9b.cjs +0 -64
  128. package/dist/token-6GSAFR2W-XRCSVUPZ-BJL0Ab9b.cjs.map +0 -1
  129. package/dist/token-6GSAFR2W-XRCSVUPZ-CDxnj2bf.js +0 -60
  130. package/dist/token-6GSAFR2W-XRCSVUPZ-CDxnj2bf.js.map +0 -1
  131. package/dist/token-util-NEHG7TUY-U7CX7GS4-Btt5t18D.cjs +0 -11
  132. package/dist/token-util-NEHG7TUY-U7CX7GS4-Btt5t18D.cjs.map +0 -1
  133. package/dist/token-util-NEHG7TUY-U7CX7GS4-C_eotjlG.js +0 -7
  134. package/dist/token-util-NEHG7TUY-U7CX7GS4-C_eotjlG.js.map +0 -1
package/dist/index.cjs CHANGED
@@ -1,73 +1,2881 @@
1
1
  'use strict';
2
2
 
3
- Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
3
+ var clientJs = require('@mastra/client-js');
4
+ var react = require('react');
5
+ var jsxRuntime = require('react/jsx-runtime');
6
+ var uuid = require('@lukeed/uuid');
7
+ var lucideReact = require('lucide-react');
8
+ var tailwindMerge = require('tailwind-merge');
9
+ var reactTooltip = require('@radix-ui/react-tooltip');
10
+ var hastUtilToJsxRuntime = require('hast-util-to-jsx-runtime');
11
+ var web = require('shiki/bundle/web');
4
12
 
5
- const index = require('./index-DlzF_2Lc.cjs');
13
+ // src/mastra-client-context.tsx
14
+ var MastraClientContext = react.createContext({});
15
+ var MastraClientProvider = ({
16
+ children,
17
+ baseUrl,
18
+ headers,
19
+ apiPrefix,
20
+ credentials = "include",
21
+ customFetch
22
+ }) => {
23
+ const client = createMastraClient(baseUrl, headers, apiPrefix, credentials, customFetch);
24
+ return /* @__PURE__ */ jsxRuntime.jsx(MastraClientContext.Provider, { value: client, children });
25
+ };
26
+ var useMastraClient = () => react.useContext(MastraClientContext);
27
+ var IPV4_LOOPBACK_RE = /^127\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
28
+ var isIPv4Loopback = (hostname) => {
29
+ const m = IPV4_LOOPBACK_RE.exec(hostname);
30
+ if (!m) return false;
31
+ return +m[1] <= 255 && +m[2] <= 255 && +m[3] <= 255;
32
+ };
33
+ var isLocalUrl = (url) => {
34
+ if (!url) return true;
35
+ try {
36
+ const { hostname } = new URL(url);
37
+ return hostname === "localhost" || hostname.endsWith(".localhost") || isIPv4Loopback(hostname) || hostname === "::1" || hostname === "[::1]";
38
+ } catch {
39
+ return false;
40
+ }
41
+ };
42
+ var createMastraClient = (baseUrl, mastraClientHeaders = {}, apiPrefix, credentials = "include", customFetch) => {
43
+ return new clientJs.MastraClient({
44
+ baseUrl: baseUrl || "",
45
+ headers: isLocalUrl(baseUrl) ? { ...mastraClientHeaders, "x-mastra-dev-playground": "true" } : mastraClientHeaders,
46
+ apiPrefix,
47
+ credentials,
48
+ fetch: customFetch
49
+ });
50
+ };
51
+ var MastraReactProvider = ({
52
+ children,
53
+ baseUrl,
54
+ headers,
55
+ apiPrefix,
56
+ credentials,
57
+ customFetch
58
+ }) => {
59
+ return /* @__PURE__ */ jsxRuntime.jsx(
60
+ MastraClientProvider,
61
+ {
62
+ baseUrl,
63
+ headers,
64
+ apiPrefix,
65
+ credentials,
66
+ customFetch,
67
+ children
68
+ }
69
+ );
70
+ };
6
71
 
72
+ // src/lib/ai-sdk/utils/formatCompletionFeedback.ts
73
+ var formatBaseCompletionFeedback = (result, maxIterationReached, formatScorerHeading, incompleteMessage) => {
74
+ const lines = [];
75
+ lines.push("#### Completion Check Results");
76
+ lines.push("");
77
+ lines.push(`Overall: ${result.complete ? "\u2705 COMPLETE" : "\u274C NOT COMPLETE"}`);
78
+ lines.push(`Duration: ${result.totalDuration}ms`);
79
+ if (result.timedOut) {
80
+ lines.push("\u26A0\uFE0F Scoring timed out");
81
+ }
82
+ lines.push("");
83
+ for (const scorer of result.scorers) {
84
+ lines.push(formatScorerHeading(scorer));
85
+ lines.push(`Score: ${scorer.score} ${scorer.passed ? "\u2705" : "\u274C"}`);
86
+ if (scorer.reason) {
87
+ lines.push(`Reason: ${scorer.reason}`);
88
+ }
89
+ lines.push("");
90
+ }
91
+ if (result.complete) {
92
+ lines.push("\u2705 The task is complete.");
93
+ } else if (maxIterationReached) {
94
+ lines.push("\u26A0\uFE0F Max iterations reached.");
95
+ } else {
96
+ lines.push(incompleteMessage);
97
+ }
98
+ return lines.join("\n");
99
+ };
100
+ var formatCompletionFeedback = (result, maxIterationReached) => {
101
+ return formatBaseCompletionFeedback(
102
+ result,
103
+ maxIterationReached,
104
+ (scorer) => `###### ${scorer.scorerName} (${scorer.scorerId})`,
105
+ "\u{1F504} Will continue working on the task."
106
+ );
107
+ };
108
+ var formatStreamCompletionFeedback = (result, maxIterationReached) => {
109
+ return formatBaseCompletionFeedback(
110
+ result,
111
+ maxIterationReached,
112
+ (scorer) => `**${scorer.scorerName}** (${scorer.scorerId})`,
113
+ "\u{1F504} The task is not yet complete. Please continue working based on the feedback above."
114
+ );
115
+ };
7
116
 
117
+ // src/lib/ai-sdk/utils/toUIMessage.ts
118
+ var mapWorkflowStreamChunkToWatchResult = (prev, chunk) => {
119
+ if (chunk.type === "workflow-start") {
120
+ return {
121
+ input: prev?.input,
122
+ status: "running",
123
+ steps: prev?.steps || {}
124
+ };
125
+ }
126
+ if (chunk.type === "workflow-canceled") {
127
+ return {
128
+ ...prev,
129
+ status: "canceled"
130
+ };
131
+ }
132
+ if (chunk.type === "workflow-finish") {
133
+ const finalStatus = chunk.payload.workflowStatus;
134
+ const prevSteps = prev?.steps ?? {};
135
+ const lastStep = Object.values(prevSteps).pop();
136
+ return {
137
+ ...prev,
138
+ status: chunk.payload.workflowStatus,
139
+ ...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 } : {}
140
+ };
141
+ }
142
+ const { stepCallId, stepName, ...newPayload } = chunk.payload ?? {};
143
+ const newSteps = {
144
+ ...prev?.steps,
145
+ [chunk.payload.id]: {
146
+ ...prev?.steps?.[chunk.payload.id],
147
+ ...newPayload
148
+ }
149
+ };
150
+ if (chunk.type === "workflow-step-start") {
151
+ return {
152
+ ...prev,
153
+ steps: newSteps
154
+ };
155
+ }
156
+ if (chunk.type === "workflow-step-suspended") {
157
+ const suspendedStepIds = Object.entries(newSteps).flatMap(
158
+ ([stepId, stepResult]) => {
159
+ if (stepResult?.status === "suspended") {
160
+ const nestedPath = stepResult?.suspendPayload?.__workflow_meta?.path;
161
+ return nestedPath ? [[stepId, ...nestedPath]] : [[stepId]];
162
+ }
163
+ return [];
164
+ }
165
+ );
166
+ return {
167
+ ...prev,
168
+ status: "suspended",
169
+ steps: newSteps,
170
+ suspendPayload: chunk.payload.suspendPayload,
171
+ suspended: suspendedStepIds
172
+ };
173
+ }
174
+ if (chunk.type === "workflow-step-waiting") {
175
+ return {
176
+ ...prev,
177
+ status: "waiting",
178
+ steps: newSteps
179
+ };
180
+ }
181
+ if (chunk.type === "workflow-step-progress") {
182
+ const progressSteps = {
183
+ ...prev?.steps,
184
+ [chunk.payload.id]: {
185
+ ...prev?.steps?.[chunk.payload.id],
186
+ foreachProgress: {
187
+ completedCount: chunk.payload.completedCount,
188
+ totalCount: chunk.payload.totalCount,
189
+ currentIndex: chunk.payload.currentIndex,
190
+ iterationStatus: chunk.payload.iterationStatus,
191
+ iterationOutput: chunk.payload.iterationOutput
192
+ }
193
+ }
194
+ };
195
+ return {
196
+ ...prev,
197
+ steps: progressSteps
198
+ };
199
+ }
200
+ if (chunk.type === "workflow-step-result") {
201
+ return {
202
+ ...prev,
203
+ steps: newSteps
204
+ };
205
+ }
206
+ return prev;
207
+ };
208
+ var toUIMessage = ({ chunk, conversation, metadata }) => {
209
+ const result = [...conversation];
210
+ if (chunk.type.startsWith("data-")) {
211
+ const lastMessage = result[result.length - 1];
212
+ if (!lastMessage || lastMessage.role !== "assistant") {
213
+ const newMessage = {
214
+ id: `data-${chunk.runId}-${Date.now()}`,
215
+ role: "assistant",
216
+ parts: [
217
+ {
218
+ type: chunk.type,
219
+ data: "data" in chunk ? chunk.data : void 0
220
+ }
221
+ ],
222
+ metadata
223
+ };
224
+ return [...result, newMessage];
225
+ }
226
+ const updatedMessage = {
227
+ ...lastMessage,
228
+ parts: [
229
+ ...lastMessage.parts,
230
+ {
231
+ type: chunk.type,
232
+ data: "data" in chunk ? chunk.data : void 0
233
+ }
234
+ ]
235
+ };
236
+ return [...result.slice(0, -1), updatedMessage];
237
+ }
238
+ switch (chunk.type) {
239
+ case "tripwire": {
240
+ const newMessage = {
241
+ id: `tripwire-${chunk.runId + Date.now()}`,
242
+ role: "assistant",
243
+ parts: [
244
+ {
245
+ type: "text",
246
+ text: chunk.payload.reason
247
+ }
248
+ ],
249
+ metadata: {
250
+ ...metadata,
251
+ status: "tripwire",
252
+ tripwire: {
253
+ retry: chunk.payload.retry,
254
+ tripwirePayload: chunk.payload.metadata,
255
+ processorId: chunk.payload.processorId
256
+ }
257
+ }
258
+ };
259
+ return [...result, newMessage];
260
+ }
261
+ case "start": {
262
+ const newMessage = {
263
+ id: typeof chunk.payload.messageId === "string" ? chunk.payload.messageId : `start-${chunk.runId + Date.now()}`,
264
+ role: "assistant",
265
+ parts: [],
266
+ metadata
267
+ };
268
+ return [...result, newMessage];
269
+ }
270
+ case "text-start": {
271
+ const lastMessage = result[result.length - 1];
272
+ if (!lastMessage || lastMessage.role !== "assistant") return result;
273
+ const textId = chunk.payload.id || `text-${Date.now()}`;
274
+ const newTextPart = {
275
+ type: "text",
276
+ text: "",
277
+ state: "streaming",
278
+ textId,
279
+ providerMetadata: chunk.payload.providerMetadata
280
+ };
281
+ if (lastMessage.metadata?.completionResult) {
282
+ const newMessage = {
283
+ id: `start-${chunk.runId}-${Date.now()}`,
284
+ role: "assistant",
285
+ parts: [newTextPart],
286
+ metadata
287
+ };
288
+ return [...result, newMessage];
289
+ }
290
+ const parts = [...lastMessage.parts];
291
+ parts.push(newTextPart);
292
+ return [
293
+ ...result.slice(0, -1),
294
+ {
295
+ ...lastMessage,
296
+ parts
297
+ }
298
+ ];
299
+ }
300
+ case "text-delta": {
301
+ const lastMessage = result[result.length - 1];
302
+ if (!lastMessage || lastMessage.role !== "assistant") return result;
303
+ const parts = [...lastMessage.parts];
304
+ const textId = chunk.payload.id;
305
+ let textPartIndex = textId ? parts.findLastIndex((part) => part.type === "text" && part.textId === textId) : -1;
306
+ if (textPartIndex === -1) {
307
+ textPartIndex = parts.findLastIndex(
308
+ (part) => part.type === "text" && part.state === "streaming"
309
+ );
310
+ }
311
+ if (textPartIndex === -1) {
312
+ const newTextPart = {
313
+ type: "text",
314
+ text: chunk.payload.text,
315
+ state: "streaming",
316
+ textId,
317
+ providerMetadata: chunk.payload.providerMetadata
318
+ };
319
+ parts.push(newTextPart);
320
+ } else {
321
+ const textPart = parts[textPartIndex];
322
+ if (textPart.type === "text") {
323
+ const extendedTextPart = textPart;
324
+ const updatedTextPart = {
325
+ ...extendedTextPart,
326
+ text: extendedTextPart.text + chunk.payload.text,
327
+ state: "streaming"
328
+ };
329
+ parts[textPartIndex] = updatedTextPart;
330
+ }
331
+ }
332
+ return [
333
+ ...result.slice(0, -1),
334
+ {
335
+ ...lastMessage,
336
+ parts
337
+ }
338
+ ];
339
+ }
340
+ case "reasoning-delta": {
341
+ const lastMessage = result[result.length - 1];
342
+ if (!lastMessage || lastMessage.role !== "assistant") {
343
+ const newMessage = {
344
+ id: `reasoning-${chunk.runId + Date.now()}`,
345
+ role: "assistant",
346
+ parts: [
347
+ {
348
+ type: "reasoning",
349
+ text: chunk.payload.text,
350
+ state: "streaming",
351
+ providerMetadata: chunk.payload.providerMetadata
352
+ }
353
+ ],
354
+ metadata
355
+ };
356
+ return [...result, newMessage];
357
+ }
358
+ const parts = [...lastMessage.parts];
359
+ let reasoningPartIndex = parts.findIndex((part) => part.type === "reasoning");
360
+ if (reasoningPartIndex === -1) {
361
+ parts.push({
362
+ type: "reasoning",
363
+ text: chunk.payload.text,
364
+ state: "streaming",
365
+ providerMetadata: chunk.payload.providerMetadata
366
+ });
367
+ } else {
368
+ const reasoningPart = parts[reasoningPartIndex];
369
+ if (reasoningPart.type === "reasoning") {
370
+ parts[reasoningPartIndex] = {
371
+ ...reasoningPart,
372
+ text: reasoningPart.text + chunk.payload.text,
373
+ state: "streaming"
374
+ };
375
+ }
376
+ }
377
+ return [
378
+ ...result.slice(0, -1),
379
+ {
380
+ ...lastMessage,
381
+ parts
382
+ }
383
+ ];
384
+ }
385
+ case "tool-call": {
386
+ const lastMessage = result[result.length - 1];
387
+ if (!lastMessage || lastMessage.role !== "assistant") {
388
+ const newMessage = {
389
+ id: `tool-call-${chunk.runId + Date.now()}`,
390
+ role: "assistant",
391
+ parts: [
392
+ {
393
+ type: "dynamic-tool",
394
+ toolName: chunk.payload.toolName,
395
+ toolCallId: chunk.payload.toolCallId,
396
+ state: "input-available",
397
+ input: chunk.payload.args,
398
+ callProviderMetadata: chunk.payload.providerMetadata
399
+ }
400
+ ],
401
+ metadata
402
+ };
403
+ return [...result, newMessage];
404
+ }
405
+ const parts = [...lastMessage.parts];
406
+ parts.push({
407
+ type: "dynamic-tool",
408
+ toolName: chunk.payload.toolName,
409
+ toolCallId: chunk.payload.toolCallId,
410
+ state: "input-available",
411
+ input: chunk.payload.args,
412
+ callProviderMetadata: chunk.payload.providerMetadata
413
+ });
414
+ return [
415
+ ...result.slice(0, -1),
416
+ {
417
+ ...lastMessage,
418
+ parts
419
+ }
420
+ ];
421
+ }
422
+ case "tool-error":
423
+ case "tool-result": {
424
+ const lastMessage = result[result.length - 1];
425
+ if (!lastMessage || lastMessage.role !== "assistant") return result;
426
+ const parts = [...lastMessage.parts];
427
+ const toolPartIndex = parts.findIndex(
428
+ (part) => (part.type === "dynamic-tool" || typeof part.type === "string" && part.type.startsWith("tool-")) && "toolCallId" in part && part.toolCallId === chunk.payload.toolCallId
429
+ );
430
+ if (toolPartIndex !== -1) {
431
+ const toolPart = parts[toolPartIndex];
432
+ if (toolPart.type === "dynamic-tool" || typeof toolPart.type === "string" && toolPart.type.startsWith("tool-")) {
433
+ const toolName = "toolName" in toolPart && typeof toolPart.toolName === "string" ? toolPart.toolName : toolPart.type.startsWith("tool-") ? toolPart.type.substring(5) : "";
434
+ const toolCallId = toolPart.toolCallId;
435
+ if (chunk.type === "tool-result" && chunk.payload.isError || chunk.type === "tool-error") {
436
+ const error = chunk.type === "tool-error" ? chunk.payload.error : chunk.payload.result;
437
+ parts[toolPartIndex] = {
438
+ type: "dynamic-tool",
439
+ toolName,
440
+ toolCallId,
441
+ state: "output-error",
442
+ input: toolPart.input,
443
+ errorText: typeof error === "string" ? error : error instanceof Error ? error.message : error?.message ?? String(error),
444
+ callProviderMetadata: chunk.payload.providerMetadata
445
+ };
446
+ } else {
447
+ const isWorkflow = Boolean(chunk.payload.result?.result?.steps);
448
+ const isAgent = chunk?.from === "AGENT";
449
+ let output;
450
+ if (isWorkflow) {
451
+ output = chunk.payload.result?.result;
452
+ } else if (isAgent) {
453
+ const existingOutput = parts[toolPartIndex].output;
454
+ output = existingOutput ? {
455
+ ...chunk.payload.result,
456
+ childMessages: existingOutput.childMessages?.length ? existingOutput.childMessages : chunk.payload.result?.childMessages
457
+ } : chunk.payload.result;
458
+ } else {
459
+ output = chunk.payload.result;
460
+ }
461
+ parts[toolPartIndex] = {
462
+ type: "dynamic-tool",
463
+ toolName,
464
+ toolCallId,
465
+ state: "output-available",
466
+ input: toolPart.input,
467
+ output,
468
+ callProviderMetadata: chunk.payload.providerMetadata
469
+ };
470
+ }
471
+ }
472
+ }
473
+ return [
474
+ ...result.slice(0, -1),
475
+ {
476
+ ...lastMessage,
477
+ parts
478
+ }
479
+ ];
480
+ }
481
+ case "tool-output": {
482
+ const lastMessage = result[result.length - 1];
483
+ if (!lastMessage || lastMessage.role !== "assistant") return result;
484
+ const parts = [...lastMessage.parts];
485
+ const toolPartIndex = parts.findIndex(
486
+ (part) => (part.type === "dynamic-tool" || typeof part.type === "string" && part.type.startsWith("tool-")) && "toolCallId" in part && part.toolCallId === chunk.payload.toolCallId
487
+ );
488
+ if (toolPartIndex !== -1) {
489
+ const toolPart = parts[toolPartIndex];
490
+ if (toolPart.type === "dynamic-tool" || typeof toolPart.type === "string" && toolPart.type.startsWith("tool-")) {
491
+ const toolName = "toolName" in toolPart && typeof toolPart.toolName === "string" ? toolPart.toolName : typeof toolPart.type === "string" && toolPart.type.startsWith("tool-") ? toolPart.type.substring(5) : "";
492
+ const toolCallId = toolPart.toolCallId;
493
+ const input = toolPart.input;
494
+ if (chunk.payload.output?.type?.startsWith("workflow-")) {
495
+ const existingWorkflowState = toolPart.output || {};
496
+ const updatedWorkflowState = mapWorkflowStreamChunkToWatchResult(
497
+ existingWorkflowState,
498
+ chunk.payload.output
499
+ );
500
+ parts[toolPartIndex] = {
501
+ type: "dynamic-tool",
502
+ toolName,
503
+ toolCallId,
504
+ state: "input-streaming",
505
+ input,
506
+ output: updatedWorkflowState
507
+ };
508
+ } else if (chunk.payload.output?.from === "AGENT" || chunk.payload.output?.from === "USER" && chunk.payload.output?.payload?.output?.type?.startsWith("workflow-")) {
509
+ return toUIMessageFromAgent(chunk.payload.output, conversation, metadata, toolCallId, toolName);
510
+ } else {
511
+ const currentOutput = toolPart.output || [];
512
+ const existingOutput = Array.isArray(currentOutput) ? currentOutput : [];
513
+ parts[toolPartIndex] = {
514
+ type: "dynamic-tool",
515
+ toolName,
516
+ toolCallId,
517
+ state: "input-streaming",
518
+ input,
519
+ output: [...existingOutput, chunk.payload.output]
520
+ };
521
+ }
522
+ }
523
+ }
524
+ return [
525
+ ...result.slice(0, -1),
526
+ {
527
+ ...lastMessage,
528
+ parts
529
+ }
530
+ ];
531
+ }
532
+ case "is-task-complete": {
533
+ if (chunk.payload.suppressFeedback) return result;
534
+ const feedback = formatStreamCompletionFeedback(
535
+ {
536
+ complete: chunk.payload.passed,
537
+ scorers: chunk.payload.results,
538
+ totalDuration: chunk.payload.duration,
539
+ timedOut: chunk.payload.timedOut},
540
+ chunk.payload.maxIterationReached
541
+ );
542
+ const newMessage = {
543
+ id: `is-task-complete-${chunk.runId + Date.now()}`,
544
+ role: "assistant",
545
+ parts: [
546
+ {
547
+ type: "text",
548
+ text: feedback
549
+ }
550
+ ],
551
+ metadata: {
552
+ ...metadata,
553
+ completionResult: {
554
+ passed: chunk.payload.passed
555
+ }
556
+ }
557
+ };
558
+ return [...result, newMessage];
559
+ }
560
+ case "source": {
561
+ const lastMessage = result[result.length - 1];
562
+ if (!lastMessage || lastMessage.role !== "assistant") return result;
563
+ const parts = [...lastMessage.parts];
564
+ if (chunk.payload.sourceType === "url") {
565
+ parts.push({
566
+ type: "source-url",
567
+ sourceId: chunk.payload.id,
568
+ url: chunk.payload.url || "",
569
+ title: chunk.payload.title,
570
+ providerMetadata: chunk.payload.providerMetadata
571
+ });
572
+ } else if (chunk.payload.sourceType === "document") {
573
+ parts.push({
574
+ type: "source-document",
575
+ sourceId: chunk.payload.id,
576
+ mediaType: chunk.payload.mimeType || "application/octet-stream",
577
+ title: chunk.payload.title,
578
+ filename: chunk.payload.filename,
579
+ providerMetadata: chunk.payload.providerMetadata
580
+ });
581
+ }
582
+ return [
583
+ ...result.slice(0, -1),
584
+ {
585
+ ...lastMessage,
586
+ parts
587
+ }
588
+ ];
589
+ }
590
+ case "file": {
591
+ const lastMessage = result[result.length - 1];
592
+ if (!lastMessage || lastMessage.role !== "assistant") return result;
593
+ const parts = [...lastMessage.parts];
594
+ let url;
595
+ if (typeof chunk.payload.data === "string") {
596
+ url = chunk.payload.base64 ? `data:${chunk.payload.mimeType};base64,${chunk.payload.data}` : `data:${chunk.payload.mimeType},${encodeURIComponent(chunk.payload.data)}`;
597
+ } else {
598
+ const base64 = btoa(String.fromCharCode(...chunk.payload.data));
599
+ url = `data:${chunk.payload.mimeType};base64,${base64}`;
600
+ }
601
+ parts.push({
602
+ type: "file",
603
+ mediaType: chunk.payload.mimeType,
604
+ url,
605
+ providerMetadata: chunk.payload.providerMetadata
606
+ });
607
+ return [
608
+ ...result.slice(0, -1),
609
+ {
610
+ ...lastMessage,
611
+ parts
612
+ }
613
+ ];
614
+ }
615
+ case "tool-call-approval": {
616
+ const lastMessage = result[result.length - 1];
617
+ if (!lastMessage || lastMessage.role !== "assistant") return result;
618
+ const lastRequireApprovalMetadata = lastMessage.metadata?.mode === "stream" ? lastMessage.metadata?.requireApprovalMetadata : {};
619
+ return [
620
+ ...result.slice(0, -1),
621
+ {
622
+ ...lastMessage,
623
+ metadata: {
624
+ ...lastMessage.metadata,
625
+ mode: "stream",
626
+ requireApprovalMetadata: {
627
+ ...lastRequireApprovalMetadata,
628
+ [chunk.payload.toolName]: {
629
+ toolCallId: chunk.payload.toolCallId,
630
+ toolName: chunk.payload.toolName,
631
+ args: chunk.payload.args
632
+ }
633
+ }
634
+ }
635
+ }
636
+ ];
637
+ }
638
+ case "tool-call-suspended": {
639
+ const lastMessage = result[result.length - 1];
640
+ if (!lastMessage || lastMessage.role !== "assistant") return result;
641
+ const lastSuspendedTools = lastMessage.metadata?.mode === "stream" ? lastMessage.metadata?.suspendedTools : {};
642
+ return [
643
+ ...result.slice(0, -1),
644
+ {
645
+ ...lastMessage,
646
+ metadata: {
647
+ ...lastMessage.metadata,
648
+ mode: "stream",
649
+ suspendedTools: {
650
+ ...lastSuspendedTools,
651
+ [chunk.payload.toolName]: {
652
+ toolCallId: chunk.payload.toolCallId,
653
+ toolName: chunk.payload.toolName,
654
+ args: chunk.payload.args,
655
+ suspendPayload: chunk.payload.suspendPayload
656
+ }
657
+ }
658
+ }
659
+ }
660
+ ];
661
+ }
662
+ case "finish": {
663
+ const lastMessage = result[result.length - 1];
664
+ if (!lastMessage || lastMessage.role !== "assistant") return result;
665
+ const parts = lastMessage.parts.map((part) => {
666
+ if (typeof part === "object" && part !== null && "type" in part && "state" in part && part.state === "streaming") {
667
+ if (part.type === "text" || part.type === "reasoning") {
668
+ return { ...part, state: "done" };
669
+ }
670
+ }
671
+ return part;
672
+ });
673
+ return [
674
+ ...result.slice(0, -1),
675
+ {
676
+ ...lastMessage,
677
+ parts
678
+ }
679
+ ];
680
+ }
681
+ case "error": {
682
+ const newMessage = {
683
+ id: `error-${chunk.runId + Date.now()}`,
684
+ role: "assistant",
685
+ parts: [
686
+ {
687
+ type: "text",
688
+ text: typeof chunk.payload.error === "string" ? chunk.payload.error : JSON.stringify(chunk.payload.error)
689
+ }
690
+ ],
691
+ metadata: {
692
+ ...metadata,
693
+ status: "error"
694
+ }
695
+ };
696
+ return [...result, newMessage];
697
+ }
698
+ // For all other chunk types, return conversation unchanged
699
+ default:
700
+ return result;
701
+ }
702
+ };
703
+ var toUIMessageFromAgent = (chunk, conversation, metadata, parentToolCallId, parentToolName) => {
704
+ const lastMessage = conversation[conversation.length - 1];
705
+ if (!lastMessage || lastMessage.role !== "assistant") return conversation;
706
+ const parts = [...lastMessage.parts];
707
+ if (chunk.type === "text-delta") {
708
+ const agentChunk = chunk.payload;
709
+ const toolPartIndex = parts.findIndex(
710
+ (part) => part.type === "dynamic-tool" && (parentToolCallId && part.toolCallId === parentToolCallId || parentToolName && part.toolName === parentToolName)
711
+ );
712
+ if (toolPartIndex === -1) return conversation;
713
+ const toolPart = parts[toolPartIndex];
714
+ const childMessages = toolPart?.output?.childMessages || [];
715
+ const lastChildMessage = childMessages[childMessages.length - 1];
716
+ const textMessage = { type: "text", content: (lastChildMessage?.content || "") + agentChunk.text };
717
+ const nextMessages = lastChildMessage?.type === "text" ? [...childMessages.slice(0, -1), textMessage] : [...childMessages, textMessage];
718
+ parts[toolPartIndex] = {
719
+ ...toolPart,
720
+ output: {
721
+ childMessages: nextMessages
722
+ }
723
+ };
724
+ } else if (chunk.type === "tool-call") {
725
+ const agentChunk = chunk.payload;
726
+ const toolPartIndex = parts.findIndex(
727
+ (part) => part.type === "dynamic-tool" && (parentToolCallId && part.toolCallId === parentToolCallId || parentToolName && part.toolName === parentToolName)
728
+ );
729
+ if (toolPartIndex === -1) return conversation;
730
+ const toolPart = parts[toolPartIndex];
731
+ const childMessages = toolPart?.output?.childMessages || [];
732
+ parts[toolPartIndex] = {
733
+ ...toolPart,
734
+ output: {
735
+ ...toolPart?.output,
736
+ childMessages: [
737
+ ...childMessages,
738
+ {
739
+ type: "tool",
740
+ toolCallId: agentChunk.toolCallId,
741
+ toolName: agentChunk.toolName,
742
+ args: agentChunk.args
743
+ }
744
+ ]
745
+ }
746
+ };
747
+ } else if (chunk.type === "tool-output") {
748
+ const agentChunk = chunk.payload;
749
+ const toolPartIndex = parts.findIndex(
750
+ (part) => part.type === "dynamic-tool" && (parentToolCallId && part.toolCallId === parentToolCallId || parentToolName && part.toolName === parentToolName)
751
+ );
752
+ if (toolPartIndex === -1) return conversation;
753
+ const toolPart = parts[toolPartIndex];
754
+ if (agentChunk?.output?.type?.startsWith("workflow-")) {
755
+ const childMessages = toolPart?.output?.childMessages || [];
756
+ const lastToolIndex = childMessages.length - 1;
757
+ const currentMessage = childMessages[lastToolIndex];
758
+ const actualExistingWorkflowState = currentMessage?.toolOutput || {};
759
+ const updatedWorkflowState = mapWorkflowStreamChunkToWatchResult(actualExistingWorkflowState, agentChunk.output);
760
+ if (lastToolIndex >= 0 && childMessages[lastToolIndex]?.type === "tool") {
761
+ parts[toolPartIndex] = {
762
+ ...toolPart,
763
+ output: {
764
+ ...toolPart?.output,
765
+ childMessages: [
766
+ ...childMessages.slice(0, -1),
767
+ {
768
+ ...currentMessage,
769
+ toolOutput: { ...updatedWorkflowState, runId: agentChunk.output.runId }
770
+ }
771
+ ]
772
+ }
773
+ };
774
+ }
775
+ }
776
+ } else if (chunk.type === "tool-result") {
777
+ const agentChunk = chunk.payload;
778
+ const toolPartIndex = parts.findIndex(
779
+ (part) => part.type === "dynamic-tool" && (parentToolCallId && part.toolCallId === parentToolCallId || parentToolName && part.toolName === parentToolName)
780
+ );
781
+ if (toolPartIndex === -1) return conversation;
782
+ const toolPart = parts[toolPartIndex];
783
+ const childMessages = toolPart?.output?.childMessages || [];
784
+ const lastToolIndex = childMessages.length - 1;
785
+ const isWorkflow = agentChunk?.toolName?.startsWith("workflow-");
786
+ if (lastToolIndex >= 0 && childMessages[lastToolIndex]?.type === "tool") {
787
+ parts[toolPartIndex] = {
788
+ ...toolPart,
789
+ output: {
790
+ ...toolPart?.output,
791
+ childMessages: [
792
+ ...childMessages.slice(0, -1),
793
+ {
794
+ ...childMessages[lastToolIndex],
795
+ toolOutput: isWorkflow ? { ...agentChunk.result?.result, runId: agentChunk.result?.runId } : agentChunk.result
796
+ }
797
+ ]
798
+ }
799
+ };
800
+ }
801
+ }
802
+ return [
803
+ ...conversation.slice(0, -1),
804
+ {
805
+ ...lastMessage,
806
+ parts
807
+ }
808
+ ];
809
+ };
8
810
 
9
- exports.AgentIcon = index.AgentIcon;
10
- exports.CodeBlock = index.CodeBlock;
11
- exports.CodeBlockClass = index.CodeBlockClass;
12
- exports.CodeCopyButton = index.CodeCopyButton;
13
- exports.Entity = index.Entity;
14
- exports.EntityCaret = index.EntityCaret;
15
- exports.EntityContent = index.EntityContent;
16
- exports.EntityContentClass = index.EntityContentClass;
17
- exports.EntityTrigger = index.EntityTrigger;
18
- exports.EntityTriggerClass = index.EntityTriggerClass;
19
- exports.EntityTriggerVariantClasses = index.EntityTriggerVariantClasses;
20
- exports.Entry = index.Entry;
21
- exports.EntryClass = index.EntryClass;
22
- exports.EntryTitle = index.EntryTitle;
23
- exports.EntryTitleClass = index.EntryTitleClass;
24
- exports.Icon = index.Icon;
25
- exports.IconButton = index.IconButton;
26
- exports.IconButtonClass = index.IconButtonClass;
27
- exports.IconSizes = index.IconSizes;
28
- exports.MastraReactProvider = index.MastraReactProvider;
29
- exports.Message = index.Message;
30
- exports.MessageActions = index.MessageActions;
31
- exports.MessageActionsClass = index.MessageActionsClass;
32
- exports.MessageClass = index.MessageClass;
33
- exports.MessageContent = index.MessageContent;
34
- exports.MessageContentClass = index.MessageContentClass;
35
- exports.MessageList = index.MessageList;
36
- exports.MessageListClass = index.MessageListClass;
37
- exports.MessageStreaming = index.MessageStreaming;
38
- exports.MessageStreamingClass = index.MessageStreamingClass;
39
- exports.MessageUsage = index.MessageUsage;
40
- exports.MessageUsageClass = index.MessageUsageClass;
41
- exports.MessageUsageEntry = index.MessageUsageEntry;
42
- exports.MessageUsageEntryClass = index.MessageUsageEntryClass;
43
- exports.MessageUsageValue = index.MessageUsageValue;
44
- exports.MessageUsageValueClass = index.MessageUsageValueClass;
45
- exports.MessageUsages = index.MessageUsages;
46
- exports.MessageUsagesClass = index.MessageUsagesClass;
47
- exports.ToolApproval = index.ToolApproval;
48
- exports.ToolApprovalActions = index.ToolApprovalActions;
49
- exports.ToolApprovalActionsClass = index.ToolApprovalActionsClass;
50
- exports.ToolApprovalClass = index.ToolApprovalClass;
51
- exports.ToolApprovalContent = index.ToolApprovalContent;
52
- exports.ToolApprovalContentClass = index.ToolApprovalContentClass;
53
- exports.ToolApprovalHeader = index.ToolApprovalHeader;
54
- exports.ToolApprovalHeaderClass = index.ToolApprovalHeaderClass;
55
- exports.ToolApprovalTitle = index.ToolApprovalTitle;
56
- exports.ToolApprovalTitleClass = index.ToolApprovalTitleClass;
57
- exports.ToolsIcon = index.ToolsIcon;
58
- exports.Tooltip = index.Tooltip;
59
- exports.TooltipContent = index.TooltipContent;
60
- exports.TooltipContentClass = index.TooltipContentClass;
61
- exports.TooltipTrigger = index.TooltipTrigger;
62
- exports.WorkflowIcon = index.WorkflowIcon;
63
- exports.mapWorkflowStreamChunkToWatchResult = index.mapWorkflowStreamChunkToWatchResult;
64
- exports.resolveToChildMessages = index.resolveToChildMessages;
65
- exports.toAssistantUIMessage = index.toAssistantUIMessage;
66
- exports.toUIMessage = index.toUIMessage;
67
- exports.useCancelWorkflowRun = index.useCancelWorkflowRun;
68
- exports.useChat = index.useChat;
69
- exports.useCreateWorkflowRun = index.useCreateWorkflowRun;
70
- exports.useEntity = index.useEntity;
71
- exports.useMastraClient = index.useMastraClient;
72
- exports.useStreamWorkflow = index.useStreamWorkflow;
811
+ // src/lib/ai-sdk/utils/toAssistantUIMessage.ts
812
+ var toAssistantUIMessage = (message) => {
813
+ const extendedMessage = message;
814
+ const content = message.parts.map((part) => {
815
+ if (part.type === "text") {
816
+ return {
817
+ type: "text",
818
+ text: part.text,
819
+ metadata: message.metadata
820
+ };
821
+ }
822
+ if (part.type === "reasoning") {
823
+ return {
824
+ type: "reasoning",
825
+ text: part.text,
826
+ metadata: message.metadata
827
+ };
828
+ }
829
+ if (part.type === "source-url") {
830
+ return {
831
+ type: "source",
832
+ sourceType: "url",
833
+ id: part.sourceId,
834
+ url: part.url,
835
+ title: part.title,
836
+ metadata: message.metadata
837
+ };
838
+ }
839
+ if (part.type === "source-document") {
840
+ return {
841
+ type: "file",
842
+ filename: part.filename,
843
+ mimeType: part.mediaType,
844
+ data: "",
845
+ // Source documents don't have inline data
846
+ metadata: message.metadata
847
+ };
848
+ }
849
+ if (part.type === "file") {
850
+ const type = part.mediaType.includes("image/") ? "image" : "file";
851
+ if (type === "file") {
852
+ return {
853
+ type,
854
+ mimeType: part.mediaType,
855
+ data: part.url,
856
+ // Use URL as data source
857
+ metadata: message.metadata
858
+ };
859
+ }
860
+ if (type === "image") {
861
+ return {
862
+ type,
863
+ image: part.url,
864
+ metadata: message.metadata
865
+ };
866
+ }
867
+ }
868
+ if (part.type === "dynamic-tool") {
869
+ const baseToolCall = {
870
+ type: "tool-call",
871
+ toolCallId: part.toolCallId,
872
+ toolName: part.toolName,
873
+ argsText: JSON.stringify(part.input),
874
+ args: part.input,
875
+ metadata: message.metadata
876
+ };
877
+ if (part.state === "output-error" && "errorText" in part) {
878
+ return { ...baseToolCall, result: part.errorText, isError: true };
879
+ }
880
+ if ("output" in part) {
881
+ return { ...baseToolCall, result: part.output };
882
+ }
883
+ return baseToolCall;
884
+ }
885
+ if (part.type.startsWith("tool-") && part.state !== "input-available") {
886
+ const toolName2 = "toolName" in part && typeof part.toolName === "string" ? part.toolName : part.type.substring(5);
887
+ const { suspendedToolRunId, ...cleanInput } = "input" in part ? part.input : {};
888
+ const baseToolCall = {
889
+ type: "tool-call",
890
+ toolCallId: "toolCallId" in part && typeof part.toolCallId === "string" ? part.toolCallId : "",
891
+ toolName: toolName2,
892
+ argsText: JSON.stringify(cleanInput ?? {}),
893
+ args: cleanInput ?? {},
894
+ metadata: message.metadata
895
+ };
896
+ if ("output" in part) {
897
+ return { ...baseToolCall, result: part.output };
898
+ } else if ("error" in part) {
899
+ return { ...baseToolCall, result: part.error, isError: true };
900
+ }
901
+ return baseToolCall;
902
+ }
903
+ const toolName = "toolName" in part && typeof part.toolName === "string" ? part.toolName : part.type.startsWith("tool-") ? part.type.substring(5) : "";
904
+ const requireApprovalMetadata = extendedMessage.metadata?.requireApprovalMetadata;
905
+ const suspendedTools = extendedMessage.metadata?.suspendedTools;
906
+ const partToolCallId = "toolCallId" in part && typeof part.toolCallId === "string" ? part.toolCallId : void 0;
907
+ const suspensionData = toolName ? requireApprovalMetadata?.[toolName] ?? suspendedTools?.[toolName] : void 0;
908
+ if (suspensionData) {
909
+ const { suspendedToolRunId, ...cleanInput } = "input" in part ? part.input : {};
910
+ return {
911
+ type: "tool-call",
912
+ toolCallId: partToolCallId,
913
+ toolName,
914
+ argsText: JSON.stringify(cleanInput ?? {}),
915
+ args: cleanInput,
916
+ metadata: extendedMessage.metadata
917
+ };
918
+ }
919
+ if (part.type.startsWith("data-")) {
920
+ return {
921
+ type: "data",
922
+ name: part.type.substring(5),
923
+ // Extract name from 'data-{name}'
924
+ data: part.data,
925
+ metadata: message.metadata
926
+ };
927
+ }
928
+ return {
929
+ type: "text",
930
+ text: "",
931
+ metadata: message.metadata
932
+ };
933
+ });
934
+ let status;
935
+ if (message.role === "assistant" && content.length > 0) {
936
+ const hasStreamingParts = message.parts.some(
937
+ (part) => part.type === "text" && "state" in part && part.state === "streaming" || part.type === "reasoning" && "state" in part && part.state === "streaming"
938
+ );
939
+ const hasToolCalls = message.parts.some((part) => part.type === "dynamic-tool" || part.type.startsWith("tool-"));
940
+ const hasInputAvailableTools = message.parts.some(
941
+ (part) => part.type === "dynamic-tool" && part.state === "input-available"
942
+ );
943
+ const hasErrorTools = message.parts.some(
944
+ (part) => part.type === "dynamic-tool" && part.state === "output-error" || part.type.startsWith("tool-") && "error" in part
945
+ );
946
+ if (hasStreamingParts) {
947
+ status = { type: "running" };
948
+ } else if (hasInputAvailableTools && hasToolCalls) {
949
+ status = { type: "requires-action", reason: "tool-calls" };
950
+ } else if (hasErrorTools) {
951
+ status = { type: "incomplete", reason: "error" };
952
+ } else {
953
+ status = { type: "complete", reason: "stop" };
954
+ }
955
+ }
956
+ const threadMessage = {
957
+ role: message.role,
958
+ content,
959
+ id: message.id,
960
+ createdAt: extendedMessage.createdAt,
961
+ status,
962
+ attachments: extendedMessage.experimental_attachments
963
+ };
964
+ return threadMessage;
965
+ };
966
+
967
+ // src/lib/ai-sdk/memory/resolveInitialMessages.ts
968
+ var resolveInitialMessages = (messages) => {
969
+ const messagesLength = messages.length;
970
+ return messages.map((message, index) => {
971
+ const networkPart = message.parts.find(
972
+ (part) => typeof part === "object" && part !== null && "type" in part && part.type === "text" && "text" in part && typeof part.text === "string" && part.text.includes('"isNetwork":true')
973
+ );
974
+ if (networkPart && networkPart.type === "text") {
975
+ try {
976
+ const json = JSON.parse(networkPart.text);
977
+ if (json.isNetwork === true) {
978
+ const selectionReason = json.selectionReason || "";
979
+ const primitiveType = json.primitiveType || "";
980
+ const primitiveId = json.primitiveId || "";
981
+ const finalResult = json.finalResult;
982
+ const messages2 = finalResult?.messages || [];
983
+ const childMessages = [];
984
+ const toolResultMap = /* @__PURE__ */ new Map();
985
+ for (const msg of messages2) {
986
+ if (Array.isArray(msg.content)) {
987
+ for (const part of msg.content) {
988
+ if (typeof part === "object" && part.type === "tool-result") {
989
+ toolResultMap.set(part.toolCallId, part);
990
+ }
991
+ }
992
+ }
993
+ }
994
+ for (const msg of messages2) {
995
+ if (msg.type === "tool-call" && Array.isArray(msg.content)) {
996
+ for (const part of msg.content) {
997
+ if (typeof part === "object" && part.type === "tool-call") {
998
+ const toolCallContent = part;
999
+ const toolResult = toolResultMap.get(toolCallContent.toolCallId);
1000
+ const isWorkflow = Boolean(toolResult?.result?.result?.steps);
1001
+ childMessages.push({
1002
+ type: "tool",
1003
+ toolCallId: toolCallContent.toolCallId,
1004
+ toolName: toolCallContent.toolName,
1005
+ args: toolCallContent.args,
1006
+ toolOutput: isWorkflow ? toolResult?.result?.result : toolResult?.result
1007
+ });
1008
+ }
1009
+ }
1010
+ }
1011
+ }
1012
+ if (finalResult && finalResult.text) {
1013
+ childMessages.push({
1014
+ type: "text",
1015
+ content: finalResult.text
1016
+ });
1017
+ }
1018
+ const result = primitiveType === "tool" ? finalResult?.result : {
1019
+ childMessages,
1020
+ result: finalResult?.text || ""
1021
+ };
1022
+ const nextMessage = {
1023
+ role: "assistant",
1024
+ parts: [
1025
+ {
1026
+ type: "dynamic-tool",
1027
+ toolCallId: primitiveId,
1028
+ toolName: primitiveId,
1029
+ state: "output-available",
1030
+ input: json.input,
1031
+ output: result
1032
+ }
1033
+ ],
1034
+ id: message.id,
1035
+ metadata: {
1036
+ ...message.metadata,
1037
+ mode: "network",
1038
+ selectionReason,
1039
+ agentInput: json.input,
1040
+ hasMoreMessages: index < messagesLength - 1,
1041
+ from: primitiveType === "agent" ? "AGENT" : primitiveType === "tool" ? "TOOL" : "WORKFLOW"
1042
+ }
1043
+ };
1044
+ return nextMessage;
1045
+ }
1046
+ } catch {
1047
+ return message;
1048
+ }
1049
+ }
1050
+ const extendedMessage = message;
1051
+ const pendingToolApprovals = extendedMessage.metadata?.pendingToolApprovals;
1052
+ if (pendingToolApprovals && typeof pendingToolApprovals === "object") {
1053
+ const stillPending = Object.fromEntries(
1054
+ Object.entries(pendingToolApprovals).filter(([_, approval]) => {
1055
+ if (!approval || typeof approval !== "object" || !("toolCallId" in approval)) {
1056
+ return false;
1057
+ }
1058
+ const toolCallId = approval.toolCallId;
1059
+ return !message.parts.some(
1060
+ (part) => part.toolCallId === toolCallId && (part.state === "output-available" || part.output != null)
1061
+ );
1062
+ })
1063
+ );
1064
+ return {
1065
+ ...message,
1066
+ metadata: {
1067
+ ...message.metadata,
1068
+ mode: "stream",
1069
+ ...Object.keys(stillPending).length > 0 ? { requireApprovalMetadata: stillPending } : {}
1070
+ }
1071
+ };
1072
+ }
1073
+ const suspendedTools = extendedMessage.metadata?.suspendedTools;
1074
+ if (suspendedTools && typeof suspendedTools === "object") {
1075
+ return {
1076
+ ...message,
1077
+ metadata: {
1078
+ ...message.metadata,
1079
+ mode: "stream",
1080
+ suspendedTools
1081
+ }
1082
+ };
1083
+ }
1084
+ return message;
1085
+ })?.filter((message) => {
1086
+ const completionModes = ["generate", "stream", "network"];
1087
+ if (message.role === "assistant" && completionModes.includes(message?.metadata?.mode)) {
1088
+ const meta = message.metadata;
1089
+ if (meta?.isTaskCompleteResult?.suppressFeedback || meta?.completionResult?.suppressFeedback) {
1090
+ return false;
1091
+ }
1092
+ return true;
1093
+ }
1094
+ return true;
1095
+ });
1096
+ };
1097
+ var resolveToChildMessages = (messages) => {
1098
+ const assistantMessage = messages.find((message) => message.role === "assistant");
1099
+ if (!assistantMessage) return [];
1100
+ const parts = assistantMessage.parts;
1101
+ let childMessages = [];
1102
+ for (const part of parts) {
1103
+ const toolPart = part;
1104
+ if (part.type.startsWith("tool-")) {
1105
+ const toolName = part.type.substring("tool-".length);
1106
+ const isWorkflow = toolName.startsWith("workflow-");
1107
+ childMessages.push({
1108
+ type: "tool",
1109
+ toolCallId: toolPart.toolCallId,
1110
+ toolName,
1111
+ args: toolPart.input,
1112
+ toolOutput: isWorkflow ? { ...toolPart.output?.result, runId: toolPart.output?.runId } : toolPart.output
1113
+ });
1114
+ }
1115
+ if (part.type === "text") {
1116
+ childMessages.push({
1117
+ type: "text",
1118
+ content: toolPart.text
1119
+ });
1120
+ }
1121
+ }
1122
+ return childMessages;
1123
+ };
1124
+
1125
+ // src/lib/ai-sdk/transformers/AISdkNetworkTransformer.ts
1126
+ var AISdkNetworkTransformer = class {
1127
+ transform({ chunk, conversation, metadata }) {
1128
+ const newConversation = [...conversation];
1129
+ if (chunk.type === "routing-agent-text-delta") {
1130
+ return this.handleRoutingAgentConversation(chunk, newConversation);
1131
+ }
1132
+ if (chunk.type.startsWith("agent-execution-")) {
1133
+ return this.handleAgentConversation(chunk, newConversation, metadata);
1134
+ }
1135
+ if (chunk.type.startsWith("workflow-execution-")) {
1136
+ return this.handleWorkflowConversation(chunk, newConversation, metadata);
1137
+ }
1138
+ if (chunk.type.startsWith("tool-execution-")) {
1139
+ return this.handleToolConversation(chunk, newConversation, metadata);
1140
+ }
1141
+ if (chunk.type === "network-validation-end") {
1142
+ if (chunk.payload.suppressFeedback) return newConversation;
1143
+ const feedback = formatCompletionFeedback(
1144
+ {
1145
+ complete: chunk.payload.passed,
1146
+ scorers: chunk.payload.results,
1147
+ totalDuration: chunk.payload.duration,
1148
+ timedOut: chunk.payload.timedOut},
1149
+ chunk.payload.maxIterationReached
1150
+ );
1151
+ const newMessage = {
1152
+ id: `network-validation-end-${chunk.payload.runId}-${Date.now()}`,
1153
+ role: "assistant",
1154
+ parts: [
1155
+ {
1156
+ type: "text",
1157
+ text: feedback
1158
+ }
1159
+ ],
1160
+ metadata: {
1161
+ ...metadata,
1162
+ mode: "network",
1163
+ completionResult: {
1164
+ passed: chunk.payload.passed
1165
+ }
1166
+ }
1167
+ };
1168
+ return [...newConversation, newMessage];
1169
+ }
1170
+ if (chunk.type === "network-execution-event-step-finish") {
1171
+ const lastMessage = newConversation[newConversation.length - 1];
1172
+ if (!lastMessage || lastMessage.role !== "assistant") return newConversation;
1173
+ const agentChunk = chunk.payload;
1174
+ const parts = [...lastMessage.parts];
1175
+ const textPartIndex = parts.findIndex((part) => part.type === "text");
1176
+ if (textPartIndex === -1) {
1177
+ parts.push({
1178
+ type: "text",
1179
+ text: agentChunk.result,
1180
+ state: "done"
1181
+ });
1182
+ return [
1183
+ ...newConversation.slice(0, -1),
1184
+ {
1185
+ ...lastMessage,
1186
+ parts
1187
+ }
1188
+ ];
1189
+ }
1190
+ const textPart = parts[textPartIndex];
1191
+ if (textPart.type === "text") {
1192
+ parts[textPartIndex] = {
1193
+ ...textPart,
1194
+ state: "done"
1195
+ };
1196
+ return [
1197
+ ...newConversation.slice(0, -1),
1198
+ {
1199
+ ...lastMessage,
1200
+ parts
1201
+ }
1202
+ ];
1203
+ }
1204
+ return newConversation;
1205
+ }
1206
+ return newConversation;
1207
+ }
1208
+ handleRoutingAgentConversation = (chunk, newConversation) => {
1209
+ const lastMessage = newConversation[newConversation.length - 1];
1210
+ if (!lastMessage || lastMessage.role !== "assistant") return newConversation;
1211
+ const agentChunk = chunk.payload;
1212
+ const parts = [...lastMessage.parts];
1213
+ const textPartIndex = parts.findIndex((part) => part.type === "text");
1214
+ if (textPartIndex === -1) {
1215
+ parts.push({
1216
+ type: "text",
1217
+ text: agentChunk.text,
1218
+ state: "streaming"
1219
+ });
1220
+ return [
1221
+ ...newConversation.slice(0, -1),
1222
+ {
1223
+ ...lastMessage,
1224
+ parts
1225
+ }
1226
+ ];
1227
+ }
1228
+ const textPart = parts[textPartIndex];
1229
+ if (textPart.type === "text") {
1230
+ parts[textPartIndex] = {
1231
+ ...textPart,
1232
+ text: textPart.text + agentChunk.text,
1233
+ state: "streaming"
1234
+ };
1235
+ return [
1236
+ ...newConversation.slice(0, -1),
1237
+ {
1238
+ ...lastMessage,
1239
+ parts
1240
+ }
1241
+ ];
1242
+ }
1243
+ return newConversation;
1244
+ };
1245
+ handleAgentConversation = (chunk, newConversation, metadata) => {
1246
+ if (chunk.type === "agent-execution-start") {
1247
+ const primitiveId = chunk.payload?.args?.primitiveId;
1248
+ const runId = chunk.payload.runId;
1249
+ if (!primitiveId || !runId) return newConversation;
1250
+ const newMessage = {
1251
+ id: `agent-execution-start-${runId}-${Date.now()}`,
1252
+ role: "assistant",
1253
+ parts: [
1254
+ {
1255
+ type: "dynamic-tool",
1256
+ toolName: primitiveId,
1257
+ toolCallId: runId,
1258
+ state: "input-available",
1259
+ input: chunk.payload.args
1260
+ }
1261
+ ],
1262
+ metadata: {
1263
+ ...metadata,
1264
+ selectionReason: chunk.payload?.args?.selectionReason || "",
1265
+ agentInput: chunk.payload?.args?.task,
1266
+ mode: "network",
1267
+ from: "AGENT"
1268
+ }
1269
+ };
1270
+ return [...newConversation, newMessage];
1271
+ }
1272
+ if (chunk.type === "agent-execution-approval") {
1273
+ const lastMessage = newConversation[newConversation.length - 1];
1274
+ if (!lastMessage || lastMessage.role !== "assistant") return newConversation;
1275
+ const lastRequireApprovalMetadata = lastMessage.metadata?.mode === "network" ? lastMessage.metadata?.requireApprovalMetadata : {};
1276
+ return [
1277
+ ...newConversation.slice(0, -1),
1278
+ {
1279
+ ...lastMessage,
1280
+ metadata: {
1281
+ ...lastMessage.metadata,
1282
+ mode: "network",
1283
+ requireApprovalMetadata: {
1284
+ ...lastRequireApprovalMetadata,
1285
+ [chunk.payload.toolName]: {
1286
+ toolCallId: chunk.payload.toolCallId,
1287
+ toolName: chunk.payload.toolName,
1288
+ args: chunk.payload.args,
1289
+ runId: chunk.payload.runId
1290
+ }
1291
+ }
1292
+ }
1293
+ }
1294
+ ];
1295
+ }
1296
+ if (chunk.type === "agent-execution-suspended") {
1297
+ const lastMessage = newConversation[newConversation.length - 1];
1298
+ if (!lastMessage || lastMessage.role !== "assistant") return newConversation;
1299
+ const lastSuspendedTools = lastMessage.metadata?.mode === "network" ? lastMessage.metadata?.suspendedTools : {};
1300
+ return [
1301
+ ...newConversation.slice(0, -1),
1302
+ {
1303
+ ...lastMessage,
1304
+ metadata: {
1305
+ ...lastMessage.metadata,
1306
+ mode: "network",
1307
+ suspendedTools: {
1308
+ ...lastSuspendedTools,
1309
+ [chunk.payload.toolName]: {
1310
+ toolCallId: chunk.payload.toolCallId,
1311
+ toolName: chunk.payload.toolName,
1312
+ args: chunk.payload.args,
1313
+ suspendPayload: chunk.payload.suspendPayload
1314
+ }
1315
+ }
1316
+ }
1317
+ }
1318
+ ];
1319
+ }
1320
+ if (chunk.type === "agent-execution-end") {
1321
+ const lastMessage = newConversation[newConversation.length - 1];
1322
+ if (!lastMessage || lastMessage.role !== "assistant") return newConversation;
1323
+ const parts = [...lastMessage.parts];
1324
+ const toolPartIndex = parts.findIndex((part) => part.type === "dynamic-tool");
1325
+ if (toolPartIndex !== -1) {
1326
+ const toolPart = parts[toolPartIndex];
1327
+ if (toolPart.type === "dynamic-tool") {
1328
+ const currentOutput = toolPart.output;
1329
+ parts[toolPartIndex] = {
1330
+ type: "dynamic-tool",
1331
+ toolName: toolPart.toolName,
1332
+ toolCallId: toolPart.toolCallId,
1333
+ state: "output-available",
1334
+ input: toolPart.input,
1335
+ output: {
1336
+ ...currentOutput,
1337
+ result: currentOutput?.result || chunk.payload?.result || ""
1338
+ }
1339
+ };
1340
+ }
1341
+ }
1342
+ return [
1343
+ ...newConversation.slice(0, -1),
1344
+ {
1345
+ ...lastMessage,
1346
+ parts
1347
+ }
1348
+ ];
1349
+ }
1350
+ if (chunk.type.startsWith("agent-execution-event-")) {
1351
+ const lastMessage = newConversation[newConversation.length - 1];
1352
+ if (!lastMessage || lastMessage.role !== "assistant") return newConversation;
1353
+ const agentChunk = chunk.payload;
1354
+ const parts = [...lastMessage.parts];
1355
+ const toolPartIndex = parts.findIndex((part) => part.type === "dynamic-tool");
1356
+ if (toolPartIndex === -1) return newConversation;
1357
+ const toolPart = parts[toolPartIndex];
1358
+ if (agentChunk.type === "text-delta") {
1359
+ const childMessages = toolPart?.output?.childMessages || [];
1360
+ const lastChildMessage = childMessages[childMessages.length - 1];
1361
+ const textMessage = { type: "text", content: (lastChildMessage?.content || "") + agentChunk.payload.text };
1362
+ const nextMessages = lastChildMessage?.type === "text" ? [...childMessages.slice(0, -1), textMessage] : [...childMessages, textMessage];
1363
+ parts[toolPartIndex] = {
1364
+ ...toolPart,
1365
+ output: {
1366
+ childMessages: nextMessages
1367
+ }
1368
+ };
1369
+ } else if (agentChunk.type === "tool-call") {
1370
+ const childMessages = toolPart?.output?.childMessages || [];
1371
+ parts[toolPartIndex] = {
1372
+ ...toolPart,
1373
+ output: {
1374
+ ...toolPart?.output,
1375
+ childMessages: [
1376
+ ...childMessages,
1377
+ {
1378
+ type: "tool",
1379
+ toolCallId: agentChunk.payload.toolCallId,
1380
+ toolName: agentChunk.payload.toolName,
1381
+ args: agentChunk.payload.args
1382
+ }
1383
+ ]
1384
+ }
1385
+ };
1386
+ } else if (agentChunk.type === "tool-output") {
1387
+ if (agentChunk.payload?.output?.type?.startsWith("workflow-")) {
1388
+ const childMessages = toolPart?.output?.childMessages || [];
1389
+ const lastToolIndex = childMessages.length - 1;
1390
+ const currentMessage = childMessages[lastToolIndex];
1391
+ const actualExistingWorkflowState = currentMessage?.toolOutput || {};
1392
+ const updatedWorkflowState = mapWorkflowStreamChunkToWatchResult(
1393
+ actualExistingWorkflowState,
1394
+ agentChunk.payload.output
1395
+ );
1396
+ if (lastToolIndex >= 0 && childMessages[lastToolIndex]?.type === "tool") {
1397
+ parts[toolPartIndex] = {
1398
+ ...toolPart,
1399
+ output: {
1400
+ ...toolPart?.output,
1401
+ childMessages: [
1402
+ ...childMessages.slice(0, -1),
1403
+ {
1404
+ ...currentMessage,
1405
+ toolOutput: updatedWorkflowState
1406
+ }
1407
+ ]
1408
+ }
1409
+ };
1410
+ }
1411
+ }
1412
+ } else if (agentChunk.type === "tool-result") {
1413
+ const childMessages = toolPart?.output?.childMessages || [];
1414
+ const lastToolIndex = childMessages.length - 1;
1415
+ const isWorkflow = Boolean(agentChunk.payload?.result?.result?.steps);
1416
+ if (lastToolIndex >= 0 && childMessages[lastToolIndex]?.type === "tool") {
1417
+ parts[toolPartIndex] = {
1418
+ ...toolPart,
1419
+ output: {
1420
+ ...toolPart?.output,
1421
+ childMessages: [
1422
+ ...childMessages.slice(0, -1),
1423
+ {
1424
+ ...childMessages[lastToolIndex],
1425
+ toolOutput: isWorkflow ? agentChunk.payload.result.result : agentChunk.payload.result
1426
+ }
1427
+ ]
1428
+ }
1429
+ };
1430
+ }
1431
+ }
1432
+ return [
1433
+ ...newConversation.slice(0, -1),
1434
+ {
1435
+ ...lastMessage,
1436
+ parts
1437
+ }
1438
+ ];
1439
+ }
1440
+ return newConversation;
1441
+ };
1442
+ handleWorkflowConversation = (chunk, newConversation, metadata) => {
1443
+ if (chunk.type === "workflow-execution-start") {
1444
+ const primitiveId = chunk.payload?.args?.primitiveId;
1445
+ const runId = chunk.payload.runId;
1446
+ if (!primitiveId || !runId) return newConversation;
1447
+ let agentInput;
1448
+ try {
1449
+ agentInput = JSON.parse(chunk?.payload?.args?.prompt);
1450
+ } catch {
1451
+ agentInput = chunk?.payload?.args?.prompt;
1452
+ }
1453
+ const newMessage = {
1454
+ id: `workflow-start-${runId}-${Date.now()}`,
1455
+ role: "assistant",
1456
+ parts: [
1457
+ {
1458
+ type: "dynamic-tool",
1459
+ toolName: primitiveId,
1460
+ toolCallId: runId,
1461
+ state: "input-available",
1462
+ input: chunk.payload.args
1463
+ }
1464
+ ],
1465
+ metadata: {
1466
+ ...metadata,
1467
+ selectionReason: chunk.payload?.args?.selectionReason || "",
1468
+ from: "WORKFLOW",
1469
+ mode: "network",
1470
+ agentInput
1471
+ }
1472
+ };
1473
+ return [...newConversation, newMessage];
1474
+ }
1475
+ if (chunk.type === "workflow-execution-suspended") {
1476
+ const lastMessage = newConversation[newConversation.length - 1];
1477
+ if (!lastMessage || lastMessage.role !== "assistant") return newConversation;
1478
+ const lastSuspendedTools = lastMessage.metadata?.mode === "network" ? lastMessage.metadata?.suspendedTools : {};
1479
+ return [
1480
+ ...newConversation.slice(0, -1),
1481
+ {
1482
+ ...lastMessage,
1483
+ metadata: {
1484
+ ...lastMessage.metadata,
1485
+ mode: "network",
1486
+ suspendedTools: {
1487
+ ...lastSuspendedTools,
1488
+ [chunk.payload.toolName]: {
1489
+ toolCallId: chunk.payload.toolCallId,
1490
+ toolName: chunk.payload.toolName,
1491
+ args: chunk.payload.args,
1492
+ suspendPayload: chunk.payload.suspendPayload
1493
+ }
1494
+ }
1495
+ }
1496
+ }
1497
+ ];
1498
+ }
1499
+ if (chunk.type.startsWith("workflow-execution-event-")) {
1500
+ const lastMessage = newConversation[newConversation.length - 1];
1501
+ if (!lastMessage || lastMessage.role !== "assistant") return newConversation;
1502
+ const parts = [...lastMessage.parts];
1503
+ const toolPartIndex = parts.findIndex((part) => part.type === "dynamic-tool");
1504
+ if (toolPartIndex === -1) return newConversation;
1505
+ const toolPart = parts[toolPartIndex];
1506
+ if (toolPart.type !== "dynamic-tool") return newConversation;
1507
+ const existingWorkflowState = toolPart.output || {};
1508
+ const updatedWorkflowState = mapWorkflowStreamChunkToWatchResult(existingWorkflowState, chunk.payload);
1509
+ parts[toolPartIndex] = {
1510
+ ...toolPart,
1511
+ output: updatedWorkflowState
1512
+ };
1513
+ return [
1514
+ ...newConversation.slice(0, -1),
1515
+ {
1516
+ ...lastMessage,
1517
+ parts
1518
+ }
1519
+ ];
1520
+ }
1521
+ return newConversation;
1522
+ };
1523
+ handleToolConversation = (chunk, newConversation, metadata) => {
1524
+ if (chunk.type === "tool-execution-start") {
1525
+ const { args: argsData } = chunk.payload;
1526
+ const lastMessage = newConversation[newConversation.length - 1];
1527
+ const nestedArgs = argsData.args || {};
1528
+ if (!lastMessage || lastMessage.role !== "assistant") {
1529
+ const newMessage = {
1530
+ id: `tool-start-${chunk.runId}-${Date.now()}`,
1531
+ role: "assistant",
1532
+ parts: [
1533
+ {
1534
+ type: "dynamic-tool",
1535
+ toolName: argsData.toolName || "unknown",
1536
+ toolCallId: argsData.toolCallId || "unknown",
1537
+ state: "input-available",
1538
+ input: nestedArgs
1539
+ }
1540
+ ],
1541
+ metadata: {
1542
+ ...metadata,
1543
+ selectionReason: metadata?.mode === "network" ? metadata.selectionReason || argsData.selectionReason : "",
1544
+ mode: "network",
1545
+ agentInput: nestedArgs
1546
+ }
1547
+ };
1548
+ return [...newConversation, newMessage];
1549
+ }
1550
+ const parts = [...lastMessage.parts];
1551
+ parts.push({
1552
+ type: "dynamic-tool",
1553
+ toolName: argsData.toolName || "unknown",
1554
+ toolCallId: argsData.toolCallId || "unknown",
1555
+ state: "input-available",
1556
+ input: nestedArgs
1557
+ });
1558
+ return [
1559
+ ...newConversation.slice(0, -1),
1560
+ {
1561
+ ...lastMessage,
1562
+ parts
1563
+ }
1564
+ ];
1565
+ }
1566
+ if (chunk.type === "tool-execution-approval") {
1567
+ const lastMessage = newConversation[newConversation.length - 1];
1568
+ if (!lastMessage || lastMessage.role !== "assistant") return newConversation;
1569
+ const lastRequireApprovalMetadata = lastMessage.metadata?.mode === "network" ? lastMessage.metadata?.requireApprovalMetadata : {};
1570
+ return [
1571
+ ...newConversation.slice(0, -1),
1572
+ {
1573
+ ...lastMessage,
1574
+ metadata: {
1575
+ ...lastMessage.metadata,
1576
+ mode: "network",
1577
+ requireApprovalMetadata: {
1578
+ ...lastRequireApprovalMetadata,
1579
+ [chunk.payload.toolName]: {
1580
+ toolCallId: chunk.payload.toolCallId,
1581
+ toolName: chunk.payload.toolName,
1582
+ args: chunk.payload.args,
1583
+ runId: chunk.payload.runId
1584
+ }
1585
+ }
1586
+ }
1587
+ }
1588
+ ];
1589
+ }
1590
+ if (chunk.type === "tool-execution-suspended") {
1591
+ const lastMessage = newConversation[newConversation.length - 1];
1592
+ if (!lastMessage || lastMessage.role !== "assistant") return newConversation;
1593
+ const lastSuspendedTools = lastMessage.metadata?.mode === "network" ? lastMessage.metadata?.suspendedTools : {};
1594
+ return [
1595
+ ...newConversation.slice(0, -1),
1596
+ {
1597
+ ...lastMessage,
1598
+ metadata: {
1599
+ ...lastMessage.metadata,
1600
+ mode: "network",
1601
+ suspendedTools: {
1602
+ ...lastSuspendedTools,
1603
+ [chunk.payload.toolName]: {
1604
+ toolCallId: chunk.payload.toolCallId,
1605
+ toolName: chunk.payload.toolName,
1606
+ args: chunk.payload.args,
1607
+ suspendPayload: chunk.payload.suspendPayload
1608
+ }
1609
+ }
1610
+ }
1611
+ }
1612
+ ];
1613
+ }
1614
+ if (chunk.type === "tool-execution-end") {
1615
+ const lastMessage = newConversation[newConversation.length - 1];
1616
+ if (!lastMessage || lastMessage.role !== "assistant") return newConversation;
1617
+ const parts = [...lastMessage.parts];
1618
+ const toolPartIndex = parts.findIndex(
1619
+ (part) => part.type === "dynamic-tool" && "toolCallId" in part && part.toolCallId === chunk.payload.toolCallId
1620
+ );
1621
+ if (toolPartIndex !== -1) {
1622
+ const toolPart = parts[toolPartIndex];
1623
+ if (toolPart.type === "dynamic-tool") {
1624
+ const currentOutput = toolPart.output;
1625
+ parts[toolPartIndex] = {
1626
+ type: "dynamic-tool",
1627
+ toolName: toolPart.toolName,
1628
+ toolCallId: toolPart.toolCallId,
1629
+ state: "output-available",
1630
+ input: toolPart.input,
1631
+ output: currentOutput?.result || chunk.payload?.result || ""
1632
+ };
1633
+ }
1634
+ }
1635
+ return [
1636
+ ...newConversation.slice(0, -1),
1637
+ {
1638
+ ...lastMessage,
1639
+ parts
1640
+ }
1641
+ ];
1642
+ }
1643
+ return newConversation;
1644
+ };
1645
+ };
1646
+
1647
+ // src/lib/ai-sdk/utils/fromCoreUserMessageToUIMessage.tsx
1648
+ var fromCoreUserMessageToUIMessage = (coreUserMessage) => {
1649
+ const id = `user-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
1650
+ const parts = typeof coreUserMessage.content === "string" ? [
1651
+ {
1652
+ type: "text",
1653
+ text: coreUserMessage.content
1654
+ }
1655
+ ] : coreUserMessage.content.map((part) => {
1656
+ switch (part.type) {
1657
+ case "text": {
1658
+ return {
1659
+ type: "text",
1660
+ text: part.text
1661
+ };
1662
+ }
1663
+ case "image": {
1664
+ const url = typeof part.image === "string" ? part.image : part.image instanceof URL ? part.image.toString() : "";
1665
+ return {
1666
+ type: "file",
1667
+ mediaType: part.mimeType ?? "image/*",
1668
+ url
1669
+ };
1670
+ }
1671
+ case "file": {
1672
+ const url = typeof part.data === "string" ? part.data : part.data instanceof URL ? part.data.toString() : "";
1673
+ return {
1674
+ type: "file",
1675
+ mediaType: part.mimeType,
1676
+ url,
1677
+ ...part.filename !== void 0 ? { filename: part.filename } : {}
1678
+ };
1679
+ }
1680
+ default: {
1681
+ const exhaustiveCheck = part;
1682
+ throw new Error(`Unhandled content part type: ${exhaustiveCheck.type}`);
1683
+ }
1684
+ }
1685
+ });
1686
+ return {
1687
+ id,
1688
+ role: "user",
1689
+ parts
1690
+ };
1691
+ };
1692
+
1693
+ // src/agent/hooks.ts
1694
+ var extractRunIdFromMessages = (messages) => {
1695
+ for (const message of messages) {
1696
+ const pendingToolApprovals = message.metadata?.pendingToolApprovals;
1697
+ if (pendingToolApprovals && typeof pendingToolApprovals === "object") {
1698
+ const suspensionData = Object.values(pendingToolApprovals)[0];
1699
+ if (suspensionData?.runId) {
1700
+ return suspensionData.runId;
1701
+ }
1702
+ }
1703
+ }
1704
+ return void 0;
1705
+ };
1706
+ var useChat = ({
1707
+ agentId,
1708
+ resourceId,
1709
+ initialMessages,
1710
+ requestContext: propsRequestContext
1711
+ }) => {
1712
+ const _currentRunId = react.useRef(void 0);
1713
+ const _onChunk = react.useRef(void 0);
1714
+ const _networkRunId = react.useRef(void 0);
1715
+ const _onNetworkChunk = react.useRef(void 0);
1716
+ const _requestContext = react.useRef(propsRequestContext);
1717
+ const [messages, setMessages] = react.useState([]);
1718
+ const [toolCallApprovals, setToolCallApprovals] = react.useState({});
1719
+ const [networkToolCallApprovals, setNetworkToolCallApprovals] = react.useState({});
1720
+ const baseClient = useMastraClient();
1721
+ const [isRunning, setIsRunning] = react.useState(false);
1722
+ react.useEffect(() => {
1723
+ const formattedMessages = resolveInitialMessages(initialMessages || []);
1724
+ setMessages(formattedMessages);
1725
+ _currentRunId.current = extractRunIdFromMessages(formattedMessages);
1726
+ }, [initialMessages]);
1727
+ react.useEffect(() => {
1728
+ _requestContext.current = propsRequestContext;
1729
+ }, [propsRequestContext]);
1730
+ const generate = async ({
1731
+ coreUserMessages,
1732
+ requestContext,
1733
+ threadId,
1734
+ modelSettings,
1735
+ signal,
1736
+ onFinish,
1737
+ tracingOptions
1738
+ }) => {
1739
+ const {
1740
+ frequencyPenalty,
1741
+ presencePenalty,
1742
+ maxRetries,
1743
+ maxTokens,
1744
+ temperature,
1745
+ topK,
1746
+ topP,
1747
+ instructions,
1748
+ providerOptions,
1749
+ maxSteps,
1750
+ requireToolApproval
1751
+ } = modelSettings || {};
1752
+ const resolvedRequestContext = requestContext ?? propsRequestContext;
1753
+ _requestContext.current = resolvedRequestContext;
1754
+ setIsRunning(true);
1755
+ const clientWithAbort = new clientJs.MastraClient({
1756
+ ...baseClient.options,
1757
+ abortSignal: signal
1758
+ });
1759
+ const agent = clientWithAbort.getAgent(agentId);
1760
+ const runId = uuid.v4();
1761
+ _currentRunId.current = runId;
1762
+ const response = await agent.generate(coreUserMessages, {
1763
+ runId,
1764
+ maxSteps,
1765
+ modelSettings: {
1766
+ frequencyPenalty,
1767
+ presencePenalty,
1768
+ maxRetries,
1769
+ maxOutputTokens: maxTokens,
1770
+ temperature,
1771
+ topK,
1772
+ topP
1773
+ },
1774
+ instructions,
1775
+ requestContext: resolvedRequestContext,
1776
+ ...threadId ? { memory: { thread: threadId, resource: resourceId || agentId } } : {},
1777
+ providerOptions,
1778
+ tracingOptions,
1779
+ requireToolApproval
1780
+ });
1781
+ if (response.finishReason === "suspended" && response.suspendPayload) {
1782
+ const { toolCallId, toolName, args } = response.suspendPayload;
1783
+ if (response.response?.uiMessages) {
1784
+ const mastraUIMessages = (response.response.uiMessages || []).map((message) => ({
1785
+ ...message,
1786
+ metadata: {
1787
+ mode: "generate",
1788
+ requireApprovalMetadata: {
1789
+ [toolName]: {
1790
+ toolCallId,
1791
+ toolName,
1792
+ args
1793
+ }
1794
+ }
1795
+ }
1796
+ }));
1797
+ setMessages((prev) => [...prev, ...mastraUIMessages]);
1798
+ }
1799
+ setIsRunning(false);
1800
+ return;
1801
+ }
1802
+ setIsRunning(false);
1803
+ if (response && "uiMessages" in response.response && response.response.uiMessages) {
1804
+ void onFinish?.(response.response.uiMessages);
1805
+ const mastraUIMessages = (response.response.uiMessages || []).map((message) => ({
1806
+ ...message,
1807
+ metadata: {
1808
+ mode: "generate"
1809
+ }
1810
+ }));
1811
+ setMessages((prev) => [...prev, ...mastraUIMessages]);
1812
+ }
1813
+ };
1814
+ const stream = async ({
1815
+ coreUserMessages,
1816
+ requestContext,
1817
+ threadId,
1818
+ onChunk,
1819
+ modelSettings,
1820
+ signal,
1821
+ tracingOptions
1822
+ }) => {
1823
+ const {
1824
+ frequencyPenalty,
1825
+ presencePenalty,
1826
+ maxRetries,
1827
+ maxTokens,
1828
+ temperature,
1829
+ topK,
1830
+ topP,
1831
+ instructions,
1832
+ providerOptions,
1833
+ maxSteps,
1834
+ requireToolApproval
1835
+ } = modelSettings || {};
1836
+ const resolvedRequestContext = requestContext ?? propsRequestContext;
1837
+ _requestContext.current = resolvedRequestContext;
1838
+ setIsRunning(true);
1839
+ const clientWithAbort = new clientJs.MastraClient({
1840
+ ...baseClient.options,
1841
+ abortSignal: signal
1842
+ });
1843
+ const agent = clientWithAbort.getAgent(agentId);
1844
+ const runId = uuid.v4();
1845
+ const response = await agent.stream(coreUserMessages, {
1846
+ runId,
1847
+ maxSteps,
1848
+ modelSettings: {
1849
+ frequencyPenalty,
1850
+ presencePenalty,
1851
+ maxRetries,
1852
+ maxOutputTokens: maxTokens,
1853
+ temperature,
1854
+ topK,
1855
+ topP
1856
+ },
1857
+ instructions,
1858
+ requestContext: resolvedRequestContext,
1859
+ ...threadId ? { memory: { thread: threadId, resource: resourceId || agentId } } : {},
1860
+ providerOptions,
1861
+ requireToolApproval,
1862
+ tracingOptions
1863
+ });
1864
+ _onChunk.current = onChunk;
1865
+ _currentRunId.current = runId;
1866
+ await response.processDataStream({
1867
+ onChunk: async (chunk) => {
1868
+ setMessages((prev) => toUIMessage({ chunk, conversation: prev, metadata: { mode: "stream" } }));
1869
+ void onChunk?.(chunk);
1870
+ }
1871
+ });
1872
+ setIsRunning(false);
1873
+ };
1874
+ const network = async ({
1875
+ coreUserMessages,
1876
+ requestContext,
1877
+ threadId,
1878
+ onNetworkChunk,
1879
+ modelSettings,
1880
+ signal,
1881
+ tracingOptions
1882
+ }) => {
1883
+ const { frequencyPenalty, presencePenalty, maxRetries, maxTokens, temperature, topK, topP, maxSteps } = modelSettings || {};
1884
+ const resolvedRequestContext = requestContext ?? propsRequestContext;
1885
+ _requestContext.current = resolvedRequestContext;
1886
+ setIsRunning(true);
1887
+ const clientWithAbort = new clientJs.MastraClient({
1888
+ ...baseClient.options,
1889
+ abortSignal: signal
1890
+ });
1891
+ const agent = clientWithAbort.getAgent(agentId);
1892
+ const runId = uuid.v4();
1893
+ const response = await agent.network(coreUserMessages, {
1894
+ maxSteps,
1895
+ modelSettings: {
1896
+ frequencyPenalty,
1897
+ presencePenalty,
1898
+ maxRetries,
1899
+ maxOutputTokens: maxTokens,
1900
+ temperature,
1901
+ topK,
1902
+ topP
1903
+ },
1904
+ runId,
1905
+ requestContext: resolvedRequestContext,
1906
+ ...threadId ? { memory: { thread: threadId, resource: resourceId || agentId } } : {},
1907
+ tracingOptions
1908
+ });
1909
+ _onNetworkChunk.current = onNetworkChunk;
1910
+ _networkRunId.current = runId;
1911
+ const transformer = new AISdkNetworkTransformer();
1912
+ await response.processDataStream({
1913
+ onChunk: async (chunk) => {
1914
+ setMessages((prev) => transformer.transform({ chunk, conversation: prev, metadata: { mode: "network" } }));
1915
+ void onNetworkChunk?.(chunk);
1916
+ }
1917
+ });
1918
+ setIsRunning(false);
1919
+ };
1920
+ const handleCancelRun = () => {
1921
+ setIsRunning(false);
1922
+ _currentRunId.current = void 0;
1923
+ _onChunk.current = void 0;
1924
+ _networkRunId.current = void 0;
1925
+ _onNetworkChunk.current = void 0;
1926
+ _requestContext.current = void 0;
1927
+ };
1928
+ const approveToolCall = async (toolCallId) => {
1929
+ const onChunk = _onChunk.current;
1930
+ const currentRunId = _currentRunId.current;
1931
+ if (!currentRunId)
1932
+ return console.info("[approveToolCall] approveToolCall can only be called after a stream has started");
1933
+ setIsRunning(true);
1934
+ setToolCallApprovals((prev) => ({ ...prev, [toolCallId]: { status: "approved" } }));
1935
+ const agent = baseClient.getAgent(agentId);
1936
+ const response = await agent.approveToolCall({
1937
+ runId: currentRunId,
1938
+ toolCallId,
1939
+ requestContext: _requestContext.current
1940
+ });
1941
+ await response.processDataStream({
1942
+ onChunk: async (chunk) => {
1943
+ setMessages((prev) => toUIMessage({ chunk, conversation: prev, metadata: { mode: "stream" } }));
1944
+ void onChunk?.(chunk);
1945
+ }
1946
+ });
1947
+ setIsRunning(false);
1948
+ };
1949
+ const declineToolCall = async (toolCallId) => {
1950
+ const onChunk = _onChunk.current;
1951
+ const currentRunId = _currentRunId.current;
1952
+ if (!currentRunId)
1953
+ return console.info("[declineToolCall] declineToolCall can only be called after a stream has started");
1954
+ setIsRunning(true);
1955
+ setToolCallApprovals((prev) => ({ ...prev, [toolCallId]: { status: "declined" } }));
1956
+ const agent = baseClient.getAgent(agentId);
1957
+ const response = await agent.declineToolCall({
1958
+ runId: currentRunId,
1959
+ toolCallId,
1960
+ requestContext: _requestContext.current
1961
+ });
1962
+ await response.processDataStream({
1963
+ onChunk: async (chunk) => {
1964
+ setMessages((prev) => toUIMessage({ chunk, conversation: prev, metadata: { mode: "stream" } }));
1965
+ void onChunk?.(chunk);
1966
+ }
1967
+ });
1968
+ setIsRunning(false);
1969
+ };
1970
+ const approveToolCallGenerate = async (toolCallId) => {
1971
+ const currentRunId = _currentRunId.current;
1972
+ if (!currentRunId)
1973
+ return console.info(
1974
+ "[approveToolCallGenerate] approveToolCallGenerate can only be called after a generate has started"
1975
+ );
1976
+ setIsRunning(true);
1977
+ setToolCallApprovals((prev) => ({ ...prev, [toolCallId]: { status: "approved" } }));
1978
+ const agent = baseClient.getAgent(agentId);
1979
+ const response = await agent.approveToolCallGenerate({
1980
+ runId: currentRunId,
1981
+ toolCallId,
1982
+ requestContext: _requestContext.current
1983
+ });
1984
+ if (response && "uiMessages" in response.response && response.response.uiMessages) {
1985
+ const mastraUIMessages = (response.response.uiMessages || []).map((message) => ({
1986
+ ...message,
1987
+ metadata: {
1988
+ mode: "generate"
1989
+ }
1990
+ }));
1991
+ setMessages((prev) => [...prev, ...mastraUIMessages]);
1992
+ }
1993
+ setIsRunning(false);
1994
+ };
1995
+ const declineToolCallGenerate = async (toolCallId) => {
1996
+ const currentRunId = _currentRunId.current;
1997
+ if (!currentRunId)
1998
+ return console.info(
1999
+ "[declineToolCallGenerate] declineToolCallGenerate can only be called after a generate has started"
2000
+ );
2001
+ setIsRunning(true);
2002
+ setToolCallApprovals((prev) => ({ ...prev, [toolCallId]: { status: "declined" } }));
2003
+ const agent = baseClient.getAgent(agentId);
2004
+ const response = await agent.declineToolCallGenerate({
2005
+ runId: currentRunId,
2006
+ toolCallId,
2007
+ requestContext: _requestContext.current
2008
+ });
2009
+ if (response && "uiMessages" in response.response && response.response.uiMessages) {
2010
+ const mastraUIMessages = (response.response.uiMessages || []).map((message) => ({
2011
+ ...message,
2012
+ metadata: {
2013
+ mode: "generate"
2014
+ }
2015
+ }));
2016
+ setMessages((prev) => [...prev, ...mastraUIMessages]);
2017
+ }
2018
+ setIsRunning(false);
2019
+ };
2020
+ const approveNetworkToolCall = async (toolName, runId) => {
2021
+ const onNetworkChunk = _onNetworkChunk.current;
2022
+ const networkRunId = runId || _networkRunId.current;
2023
+ if (!networkRunId)
2024
+ return console.info(
2025
+ "[approveNetworkToolCall] approveNetworkToolCall can only be called after a network stream has started"
2026
+ );
2027
+ setIsRunning(true);
2028
+ setNetworkToolCallApprovals((prev) => ({
2029
+ ...prev,
2030
+ [runId ? `${runId}-${toolName}` : toolName]: { status: "approved" }
2031
+ }));
2032
+ const agent = baseClient.getAgent(agentId);
2033
+ const response = await agent.approveNetworkToolCall({
2034
+ runId: networkRunId,
2035
+ requestContext: _requestContext.current
2036
+ });
2037
+ const transformer = new AISdkNetworkTransformer();
2038
+ await response.processDataStream({
2039
+ onChunk: async (chunk) => {
2040
+ setMessages((prev) => transformer.transform({ chunk, conversation: prev, metadata: { mode: "network" } }));
2041
+ void onNetworkChunk?.(chunk);
2042
+ }
2043
+ });
2044
+ setIsRunning(false);
2045
+ };
2046
+ const declineNetworkToolCall = async (toolName, runId) => {
2047
+ const onNetworkChunk = _onNetworkChunk.current;
2048
+ const networkRunId = runId || _networkRunId.current;
2049
+ if (!networkRunId)
2050
+ return console.info(
2051
+ "[declineNetworkToolCall] declineNetworkToolCall can only be called after a network stream has started"
2052
+ );
2053
+ setIsRunning(true);
2054
+ setNetworkToolCallApprovals((prev) => ({
2055
+ ...prev,
2056
+ [runId ? `${runId}-${toolName}` : toolName]: { status: "declined" }
2057
+ }));
2058
+ const agent = baseClient.getAgent(agentId);
2059
+ const response = await agent.declineNetworkToolCall({
2060
+ runId: networkRunId,
2061
+ requestContext: _requestContext.current
2062
+ });
2063
+ const transformer = new AISdkNetworkTransformer();
2064
+ await response.processDataStream({
2065
+ onChunk: async (chunk) => {
2066
+ setMessages((prev) => transformer.transform({ chunk, conversation: prev, metadata: { mode: "network" } }));
2067
+ void onNetworkChunk?.(chunk);
2068
+ }
2069
+ });
2070
+ setIsRunning(false);
2071
+ };
2072
+ const sendMessage = async ({ mode = "stream", ...args }) => {
2073
+ const nextMessage = { role: "user", content: [{ type: "text", text: args.message }] };
2074
+ const coreUserMessages = [nextMessage];
2075
+ if (args.coreUserMessages) {
2076
+ coreUserMessages.push(...args.coreUserMessages);
2077
+ }
2078
+ const uiMessages = coreUserMessages.map(fromCoreUserMessageToUIMessage);
2079
+ setMessages((s) => [...s, ...uiMessages]);
2080
+ if (mode === "generate") {
2081
+ await generate({ ...args, coreUserMessages });
2082
+ } else if (mode === "stream") {
2083
+ await stream({ ...args, coreUserMessages });
2084
+ } else if (mode === "network") {
2085
+ await network({ ...args, coreUserMessages });
2086
+ }
2087
+ };
2088
+ return {
2089
+ setMessages,
2090
+ sendMessage,
2091
+ isRunning,
2092
+ messages,
2093
+ approveToolCall,
2094
+ declineToolCall,
2095
+ approveToolCallGenerate,
2096
+ declineToolCallGenerate,
2097
+ cancelRun: handleCancelRun,
2098
+ toolCallApprovals,
2099
+ approveNetworkToolCall,
2100
+ declineNetworkToolCall,
2101
+ networkToolCallApprovals
2102
+ };
2103
+ };
2104
+ var IconSizes = {
2105
+ sm: "mastra:[&>svg]:size-3",
2106
+ md: "mastra:[&>svg]:size-4",
2107
+ lg: "mastra:[&>svg]:size-5"
2108
+ };
2109
+ var Icon = ({ children, className, size = "md", ...props }) => {
2110
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: className || IconSizes[size], ...props, children });
2111
+ };
2112
+ var EntityContext = react.createContext({
2113
+ expanded: false,
2114
+ setExpanded: () => {
2115
+ },
2116
+ variant: "initial",
2117
+ disabled: false
2118
+ });
2119
+ var EntityProvider = EntityContext.Provider;
2120
+ var useEntity = () => react.useContext(EntityContext);
2121
+ var Entity = ({
2122
+ className,
2123
+ variant = "initial",
2124
+ initialExpanded = false,
2125
+ disabled = false,
2126
+ ...props
2127
+ }) => {
2128
+ const [expanded, setExpanded] = react.useState(initialExpanded);
2129
+ return /* @__PURE__ */ jsxRuntime.jsx(EntityProvider, { value: { expanded, setExpanded, variant, disabled }, children: /* @__PURE__ */ jsxRuntime.jsx("div", { className, ...props }) });
2130
+ };
2131
+ var EntityTriggerClass = tailwindMerge.twMerge(
2132
+ "mastra:aria-disabled:cursor-not-allowed mastra:aria-disabled:bg-surface5 mastra:aria-disabled:text-text3",
2133
+ "mastra:aria-expanded:rounded-b-none mastra:aria-expanded:border-b-0",
2134
+ "mastra:bg-surface3 mastra:text-text6 mastra:hover:bg-surface4 mastra:active:bg-surface5",
2135
+ "mastra:rounded-lg mastra:py-2 mastra:px-4 mastra:border mastra:border-border1",
2136
+ "mastra:cursor-pointer mastra:inline-flex mastra:items-center mastra:gap-1 mastra:font-mono"
2137
+ );
2138
+ var EntityTriggerVariantClasses = {
2139
+ agent: "mastra:[&_svg.mastra-icon]:text-accent1",
2140
+ workflow: "mastra:[&_svg.mastra-icon]:text-accent3",
2141
+ tool: "mastra:[&_svg.mastra-icon]:text-accent6",
2142
+ memory: "mastra:[&_svg.mastra-icon]:text-accent2",
2143
+ initial: "mastra:[&_svg.mastra-icon]:text-text3"
2144
+ };
2145
+ var EntityTrigger = ({ className, children, ...props }) => {
2146
+ const { expanded, setExpanded, variant, disabled } = useEntity();
2147
+ const handleClick = (e) => {
2148
+ if (disabled) return;
2149
+ setExpanded(!expanded);
2150
+ props?.onClick?.(e);
2151
+ };
2152
+ return /* @__PURE__ */ jsxRuntime.jsx(
2153
+ "button",
2154
+ {
2155
+ className: className || tailwindMerge.twMerge(EntityTriggerClass, !disabled && EntityTriggerVariantClasses[variant]),
2156
+ ...props,
2157
+ onClick: handleClick,
2158
+ "aria-expanded": expanded,
2159
+ "aria-disabled": disabled,
2160
+ children
2161
+ }
2162
+ );
2163
+ };
2164
+ var EntityContentClass = tailwindMerge.twMerge(
2165
+ "mastra:space-y-4",
2166
+ "mastra:rounded-lg mastra:rounded-tl-none mastra:p-4 mastra:border mastra:border-border1 mastra:-mt-[0.5px]",
2167
+ "mastra:bg-surface3 mastra:text-text6"
2168
+ );
2169
+ var EntityContent = ({ className, ...props }) => {
2170
+ const { expanded } = useEntity();
2171
+ if (!expanded) return null;
2172
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: className || EntityContentClass, ...props });
2173
+ };
2174
+ var EntityCaret = ({ className, ...props }) => {
2175
+ const { expanded } = useEntity();
2176
+ return /* @__PURE__ */ jsxRuntime.jsx(Icon, { children: /* @__PURE__ */ jsxRuntime.jsx(
2177
+ lucideReact.ChevronDownIcon,
2178
+ {
2179
+ className: tailwindMerge.twMerge(
2180
+ `mastra:text-text3 mastra:transition-transform mastra:duration-200 mastra:ease-in-out`,
2181
+ expanded ? "mastra:rotate-0" : "mastra:-rotate-90",
2182
+ className
2183
+ ),
2184
+ ...props
2185
+ }
2186
+ ) });
2187
+ };
2188
+ var ToolApprovalClass = tailwindMerge.twMerge(
2189
+ "mastra:rounded-lg mastra:border mastra:border-border1 mastra:max-w-1/2 mastra:mt-2",
2190
+ "mastra:bg-surface3 mastra:text-text6"
2191
+ );
2192
+ var ToolApproval = ({ className, ...props }) => {
2193
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: className || ToolApprovalClass, ...props });
2194
+ };
2195
+ var ToolApprovalTitleClass = tailwindMerge.twMerge("mastra:text-text6 mastra:inline-flex mastra:items-center mastra:gap-1");
2196
+ var ToolApprovalTitle = ({ className, ...props }) => {
2197
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: className || ToolApprovalTitleClass, ...props });
2198
+ };
2199
+ var ToolApprovalHeaderClass = tailwindMerge.twMerge(
2200
+ "mastra:flex mastra:justify-between mastra:items-center mastra:gap-2",
2201
+ "mastra:border-b mastra:border-border1 mastra:px-4 mastra:py-2"
2202
+ );
2203
+ var ToolApprovalHeader = ({ className, ...props }) => {
2204
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: className || ToolApprovalHeaderClass, ...props });
2205
+ };
2206
+ var ToolApprovalContentClass = tailwindMerge.twMerge("mastra:text-text6 mastra:p-4");
2207
+ var ToolApprovalContent = ({ className, ...props }) => {
2208
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: className || ToolApprovalContentClass, ...props });
2209
+ };
2210
+ var ToolApprovalActionsClass = tailwindMerge.twMerge("mastra:flex mastra:gap-2 mastra:items-center");
2211
+ var ToolApprovalActions = ({ className, ...props }) => {
2212
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: className || ToolApprovalActionsClass, ...props });
2213
+ };
2214
+ var EntryClass = "mastra:space-y-2";
2215
+ var Entry = ({ className, ...props }) => {
2216
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: className || EntryClass, ...props });
2217
+ };
2218
+ var EntryTitleClass = "mastra:font-mono mastra:text-sm mastra:text-text3";
2219
+ var EntryTitle = ({ className, as: Root = "h3", ...props }) => {
2220
+ return /* @__PURE__ */ jsxRuntime.jsx(Root, { className: className || EntryTitleClass, ...props });
2221
+ };
2222
+ var Tooltip = ({ children }) => {
2223
+ return /* @__PURE__ */ jsxRuntime.jsx(reactTooltip.TooltipProvider, { children: /* @__PURE__ */ jsxRuntime.jsx(reactTooltip.Root, { children }) });
2224
+ };
2225
+ var TooltipContentClass = "mastra:bg-surface4 mastra:text-text6 mastra mastra:rounded-lg mastra:py-1 mastra:px-2 mastra:text-xs mastra:border mastra:border-border1 mastra-tooltip-enter";
2226
+ var TooltipContent = ({ children, className, ...props }) => {
2227
+ return /* @__PURE__ */ jsxRuntime.jsx(reactTooltip.TooltipPortal, { children: /* @__PURE__ */ jsxRuntime.jsx(reactTooltip.TooltipContent, { className: className || TooltipContentClass, ...props, children }) });
2228
+ };
2229
+ var TooltipTrigger = (props) => {
2230
+ return /* @__PURE__ */ jsxRuntime.jsx(reactTooltip.TooltipTrigger, { ...props, asChild: true });
2231
+ };
2232
+ var IconButtonClass = "mastra:text-text3 mastra:hover:text-text6 mastra:active:text-text6 mastra:hover:bg-surface4 mastra:active:bg-surface5 mastra:rounded-md mastra:cursor-pointer";
2233
+ var IconButton = ({ children, tooltip, size = "md", className, ...props }) => {
2234
+ return /* @__PURE__ */ jsxRuntime.jsxs(Tooltip, { children: [
2235
+ /* @__PURE__ */ jsxRuntime.jsx(TooltipTrigger, { children: /* @__PURE__ */ jsxRuntime.jsx(
2236
+ "button",
2237
+ {
2238
+ ...props,
2239
+ className: className || tailwindMerge.twMerge(IconButtonClass, size === "md" && "mastra:p-0.5", size === "lg" && "mastra:p-1"),
2240
+ children: /* @__PURE__ */ jsxRuntime.jsx(Icon, { size, children })
2241
+ }
2242
+ ) }),
2243
+ /* @__PURE__ */ jsxRuntime.jsx(TooltipContent, { children: tooltip })
2244
+ ] });
2245
+ };
2246
+ async function highlight(code, lang) {
2247
+ const out = await web.codeToHast(code, {
2248
+ lang,
2249
+ theme: "dracula-soft"
2250
+ });
2251
+ return hastUtilToJsxRuntime.toJsxRuntime(out, {
2252
+ Fragment: react.Fragment,
2253
+ jsx: jsxRuntime.jsx,
2254
+ jsxs: jsxRuntime.jsxs
2255
+ });
2256
+ }
2257
+ var CodeBlockClass = "mastra:rounded-lg mastra:[&>pre]:p-4 mastra:overflow-hidden mastra:[&>pre]:!bg-surface4 mastra:[&>pre>code]:leading-5 mastra:relative";
2258
+ var CodeBlock = ({ code, language, className, cta }) => {
2259
+ const [nodes, setNodes] = react.useState(null);
2260
+ react.useLayoutEffect(() => {
2261
+ void highlight(code, language).then(setNodes);
2262
+ }, [language]);
2263
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: className || CodeBlockClass, children: [
2264
+ nodes ?? null,
2265
+ cta
2266
+ ] });
2267
+ };
2268
+ var CodeCopyButton = ({ code }) => {
2269
+ const [isCopied, setIsCopied] = react.useState(false);
2270
+ const handleCopy = () => {
2271
+ void navigator.clipboard.writeText(code);
2272
+ setIsCopied(true);
2273
+ setTimeout(() => setIsCopied(false), 2e3);
2274
+ };
2275
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mastra:absolute mastra:top-2 mastra:right-2", children: /* @__PURE__ */ jsxRuntime.jsx(IconButton, { tooltip: "Copy", onClick: handleCopy, children: isCopied ? /* @__PURE__ */ jsxRuntime.jsx(lucideReact.CheckIcon, {}) : /* @__PURE__ */ jsxRuntime.jsx(lucideReact.CopyIcon, {}) }) });
2276
+ };
2277
+ var AgentIcon = ({ className, ...props }) => /* @__PURE__ */ jsxRuntime.jsxs(
2278
+ "svg",
2279
+ {
2280
+ width: "17",
2281
+ height: "16",
2282
+ viewBox: "0 0 17 16",
2283
+ fill: "none",
2284
+ xmlns: "http://www.w3.org/2000/svg",
2285
+ ...props,
2286
+ className: tailwindMerge.twMerge("mastra-icon", className),
2287
+ children: [
2288
+ /* @__PURE__ */ jsxRuntime.jsx(
2289
+ "path",
2290
+ {
2291
+ fillRule: "evenodd",
2292
+ clipRule: "evenodd",
2293
+ d: "M8.5 15C10.3565 15 12.137 14.2625 13.4497 12.9497C14.7625 11.637 15.5 9.85652 15.5 8C15.5 6.14348 14.7625 4.36301 13.4497 3.05025C12.137 1.7375 10.3565 1 8.5 1C6.64348 1 4.86301 1.7375 3.55025 3.05025C2.2375 4.36301 1.5 6.14348 1.5 8C1.5 9.85652 2.2375 11.637 3.55025 12.9497C4.86301 14.2625 6.64348 15 8.5 15ZM5.621 10.879L4.611 11.889C3.84179 11.1198 3.31794 10.1398 3.1057 9.07291C2.89346 8.00601 3.00236 6.90013 3.41864 5.89512C3.83491 4.89012 4.53986 4.03112 5.44434 3.42676C6.34881 2.8224 7.41219 2.49983 8.5 2.49983C9.58781 2.49983 10.6512 2.8224 11.5557 3.42676C12.4601 4.03112 13.1651 4.89012 13.5814 5.89512C13.9976 6.90013 14.1065 8.00601 13.8943 9.07291C13.6821 10.1398 13.1582 11.1198 12.389 11.889L11.379 10.879C11.1004 10.6003 10.7696 10.3792 10.4055 10.2284C10.0414 10.0776 9.6511 9.99995 9.257 10H7.743C7.3489 9.99995 6.95865 10.0776 6.59455 10.2284C6.23045 10.3792 5.89963 10.6003 5.621 10.879Z",
2294
+ fill: "currentColor"
2295
+ }
2296
+ ),
2297
+ /* @__PURE__ */ jsxRuntime.jsx(
2298
+ "path",
2299
+ {
2300
+ d: "M8.5 4C7.96957 4 7.46086 4.21071 7.08579 4.58579C6.71071 4.96086 6.5 5.46957 6.5 6V6.5C6.5 7.03043 6.71071 7.53914 7.08579 7.91421C7.46086 8.28929 7.96957 8.5 8.5 8.5C9.03043 8.5 9.53914 8.28929 9.91421 7.91421C10.2893 7.53914 10.5 7.03043 10.5 6.5V6C10.5 5.46957 10.2893 4.96086 9.91421 4.58579C9.53914 4.21071 9.03043 4 8.5 4Z",
2301
+ fill: "currentColor"
2302
+ }
2303
+ )
2304
+ ]
2305
+ }
2306
+ );
2307
+ var ToolsIcon = ({ className, ...props }) => /* @__PURE__ */ jsxRuntime.jsx(
2308
+ "svg",
2309
+ {
2310
+ width: "17",
2311
+ height: "16",
2312
+ viewBox: "0 0 17 16",
2313
+ fill: "none",
2314
+ xmlns: "http://www.w3.org/2000/svg",
2315
+ ...props,
2316
+ className: tailwindMerge.twMerge("mastra-icon", className),
2317
+ children: /* @__PURE__ */ jsxRuntime.jsx(
2318
+ "path",
2319
+ {
2320
+ fillRule: "evenodd",
2321
+ clipRule: "evenodd",
2322
+ d: "M7.5605 1.42351C8.0791 0.904904 8.92215 0.906157 9.4395 1.42351L10.6922 2.67617C11.2108 3.19477 11.2095 4.03782 10.6922 4.55517L9.4395 5.80783C8.9209 6.32643 8.07785 6.32518 7.5605 5.80783L6.30784 4.55517C5.78923 4.03656 5.79049 3.19352 6.30784 2.67617L7.5605 1.42351ZM3.17618 5.80783C3.69478 5.28923 4.53782 5.29048 5.05517 5.80783L6.30784 7.0605C6.82644 7.5791 6.82519 8.42214 6.30784 8.93949L5.05517 10.1922C4.53657 10.7108 3.69353 10.7095 3.17618 10.1922L1.92351 8.93949C1.40491 8.42089 1.40616 7.57785 1.92351 7.0605L3.17618 5.80783ZM11.9448 5.80783C12.4634 5.28923 13.3065 5.29048 13.8238 5.80783L15.0765 7.0605C15.5951 7.5791 15.5938 8.42214 15.0765 8.93949L13.8238 10.1922C13.3052 10.7108 12.4622 10.7095 11.9448 10.1922L10.6922 8.93949C10.1736 8.42089 10.1748 7.57785 10.6922 7.0605L11.9448 5.80783ZM7.5605 10.1922C8.0791 9.67355 8.92215 9.67481 9.4395 10.1922L10.6922 11.4448C11.2108 11.9634 11.2095 12.8065 10.6922 13.3238L9.4395 14.5765C8.9209 15.0951 8.07785 15.0938 7.5605 14.5765L6.30784 13.3238C5.78923 12.8052 5.79049 11.9622 6.30784 11.4448L7.5605 10.1922Z",
2323
+ fill: "currentColor"
2324
+ }
2325
+ )
2326
+ }
2327
+ );
2328
+ var WorkflowIcon = ({ className, ...props }) => /* @__PURE__ */ jsxRuntime.jsx(
2329
+ "svg",
2330
+ {
2331
+ width: "17",
2332
+ height: "16",
2333
+ viewBox: "0 0 17 16",
2334
+ fill: "none",
2335
+ xmlns: "http://www.w3.org/2000/svg",
2336
+ ...props,
2337
+ className: tailwindMerge.twMerge("mastra-icon", className),
2338
+ children: /* @__PURE__ */ jsxRuntime.jsx(
2339
+ "path",
2340
+ {
2341
+ fillRule: "evenodd",
2342
+ clipRule: "evenodd",
2343
+ d: "M6.24388 2.4018C6.24388 2.0394 6.53767 1.74561 6.90008 1.74561H10.0991C10.4614 1.74561 10.7553 2.0394 10.7553 2.4018V4.57546C10.7553 4.93787 10.4614 5.23166 10.0991 5.23166H9.31982V7.35469L10.0033 9.22664C9.90442 9.20146 9.80035 9.1761 9.6915 9.14986L9.62652 9.13422C9.30473 9.05687 8.92256 8.96501 8.61993 8.84491C8.5819 8.82981 8.54147 8.81292 8.49957 8.79391C8.45767 8.81292 8.41724 8.82981 8.3792 8.84491C8.07657 8.96501 7.6944 9.05687 7.37261 9.13422L7.30763 9.14986C7.19879 9.1761 7.09471 9.20146 6.99577 9.22664L7.67932 7.35469V5.23166H6.90008C6.53767 5.23166 6.24388 4.93787 6.24388 4.57546V2.4018ZM6.99577 9.22664C6.99577 9.22664 6.99578 9.22664 6.99577 9.22664L6.43283 10.7683H6.81806C7.18047 10.7683 7.47426 11.0622 7.47426 11.4245V13.5982C7.47426 13.9606 7.18047 14.2544 6.81806 14.2544H3.61909C3.25668 14.2544 2.96289 13.9606 2.96289 13.5982V11.4245C2.96289 11.0622 3.25668 10.7683 3.61909 10.7683H4.26617C4.2921 10.4663 4.32783 10.1494 4.37744 9.85171C4.43762 9.49063 4.52982 9.08135 4.68998 8.76102C4.93975 8.2615 5.44743 8.01751 5.7771 7.88788C6.14684 7.74249 6.57537 7.63889 6.92317 7.55505C7.24707 7.47696 7.49576 7.41679 7.67932 7.35469L6.99577 9.22664ZM6.43283 10.7683L6.99577 9.22664C6.75846 9.28705 6.55067 9.34646 6.37745 9.41458C6.22784 9.47341 6.1623 9.51712 6.14023 9.53254C6.09752 9.63631 6.04409 9.83055 5.99562 10.1214C5.96201 10.3231 5.93498 10.5439 5.91341 10.7683H6.43283ZM10.0033 9.22664L9.31982 7.35469C9.50338 7.41679 9.75206 7.47696 10.076 7.55505C10.4238 7.63889 10.8523 7.74249 11.2221 7.88788C11.5517 8.01751 12.0594 8.2615 12.3091 8.76102C12.4693 9.08135 12.5615 9.49063 12.6217 9.85171C12.6713 10.1494 12.707 10.4663 12.733 10.7683H13.38C13.7424 10.7683 14.0362 11.0622 14.0362 11.4245V13.5982C14.0362 13.9606 13.7424 14.2544 13.38 14.2544H10.1811C9.81867 14.2544 9.52488 13.9606 9.52488 13.5982V11.4245C9.52488 11.0622 9.81867 10.7683 10.1811 10.7683H10.5663L10.0033 9.22664ZM10.0033 9.22664L10.5663 10.7683H11.0857C11.0642 10.5439 11.0372 10.3231 11.0035 10.1214C10.9551 9.83055 10.9016 9.63631 10.8589 9.53254C10.8369 9.51712 10.7713 9.47341 10.6217 9.41458C10.4485 9.34646 10.2407 9.28705 10.0033 9.22664Z",
2344
+ fill: "currentColor"
2345
+ }
2346
+ )
2347
+ }
2348
+ );
2349
+ var MessageClass = "mastra:flex mastra:flex-col mastra:w-full mastra:py-4 mastra:gap-2 mastra:group";
2350
+ var Message = ({ position, className, children, ...props }) => {
2351
+ return /* @__PURE__ */ jsxRuntime.jsx(
2352
+ "div",
2353
+ {
2354
+ className: className || tailwindMerge.twMerge(
2355
+ MessageClass,
2356
+ position === "left" ? "" : "mastra:items-end mastra:[&_.mastra-message-content]:bg-surface4 mastra:[&_.mastra-message-content]:px-4"
2357
+ ),
2358
+ ...props,
2359
+ children
2360
+ }
2361
+ );
2362
+ };
2363
+ var MessageContentClass = "mastra:max-w-4/5 mastra:py-2 mastra:text-text6 mastra:rounded-lg mastra-message-content mastra:text-md";
2364
+ var MessageContent = ({ children, className, isStreaming, ...props }) => {
2365
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: className || MessageContentClass, ...props, children: [
2366
+ children,
2367
+ isStreaming && /* @__PURE__ */ jsxRuntime.jsx(MessageStreaming, {})
2368
+ ] });
2369
+ };
2370
+ var MessageActionsClass = "mastra:gap-2 mastra:flex mastra:opacity-0 mastra:group-hover:opacity-100 mastra:group-focus-within:opacity-100 mastra:items-center";
2371
+ var MessageActions = ({ children, className, ...props }) => {
2372
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: className || MessageActionsClass, ...props, children });
2373
+ };
2374
+ var MessageUsagesClass = "mastra:flex mastra:gap-2 mastra:items-center";
2375
+ var MessageUsages = ({ children, className, ...props }) => {
2376
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: className || MessageUsagesClass, ...props, children });
2377
+ };
2378
+ var MessageUsageClass = "mastra:flex mastra:gap-2 mastra:items-center mastra:font-mono mastra:text-xs mastra:bg-surface3 mastra:rounded-lg mastra:px-2 mastra:py-1";
2379
+ var MessageUsage = ({ children, className, ...props }) => {
2380
+ return /* @__PURE__ */ jsxRuntime.jsx("dl", { className: className || MessageUsageClass, ...props, children });
2381
+ };
2382
+ var MessageUsageEntryClass = "mastra:text-text3 mastra:text-xs mastra:flex mastra:gap-1 mastra:items-center";
2383
+ var MessageUsageEntry = ({ children, className, ...props }) => {
2384
+ return /* @__PURE__ */ jsxRuntime.jsx("dt", { className: className || MessageUsageEntryClass, ...props, children });
2385
+ };
2386
+ var MessageUsageValueClass = "mastra:text-text6 mastra:text-xs";
2387
+ var MessageUsageValue = ({ children, className, ...props }) => {
2388
+ return /* @__PURE__ */ jsxRuntime.jsx("dd", { className: className || MessageUsageValueClass, ...props, children });
2389
+ };
2390
+ var MessageListClass = "mastra:overflow-y-auto mastra:h-full mastra-list";
2391
+ var MessageList = ({ children, className, ...props }) => {
2392
+ const listRef = react.useRef(null);
2393
+ react.useEffect(() => {
2394
+ const scrollToBottom = () => {
2395
+ if (!listRef.current) return;
2396
+ listRef.current.scrollTo({ top: listRef.current.scrollHeight, behavior: "smooth" });
2397
+ };
2398
+ requestAnimationFrame(scrollToBottom);
2399
+ });
2400
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: className || MessageListClass, ...props, ref: listRef, children });
2401
+ };
2402
+ var MessageStreamingClass = "mastra:inline-block mastra:w-[2px] mastra:h-[1em] mastra:bg-text5 mastra:ml-0.5 mastra:align-text-bottom mastra:animate-pulse";
2403
+ var MessageStreaming = ({ className, ...props }) => {
2404
+ return /* @__PURE__ */ jsxRuntime.jsx("span", { className: className || MessageStreamingClass, ...props });
2405
+ };
2406
+ function useMutation(mutationFn) {
2407
+ const [isPending, setIsPending] = react.useState(false);
2408
+ const [isSuccess, setIsSuccess] = react.useState(false);
2409
+ const [isError, setIsError] = react.useState(false);
2410
+ const [error, setError] = react.useState(null);
2411
+ const [data, setData] = react.useState(void 0);
2412
+ const mutationFnRef = react.useRef(mutationFn);
2413
+ mutationFnRef.current = mutationFn;
2414
+ const reset = react.useCallback(() => {
2415
+ setIsPending(false);
2416
+ setIsSuccess(false);
2417
+ setIsError(false);
2418
+ setError(null);
2419
+ setData(void 0);
2420
+ }, []);
2421
+ const mutateAsync = react.useCallback(async (variables) => {
2422
+ setIsPending(true);
2423
+ setIsSuccess(false);
2424
+ setIsError(false);
2425
+ setError(null);
2426
+ try {
2427
+ const result = await mutationFnRef.current(variables);
2428
+ setData(result);
2429
+ setIsSuccess(true);
2430
+ return result;
2431
+ } catch (err) {
2432
+ const typedError = err;
2433
+ setError(typedError);
2434
+ setIsError(true);
2435
+ throw err;
2436
+ } finally {
2437
+ setIsPending(false);
2438
+ }
2439
+ }, []);
2440
+ const mutate = react.useCallback(
2441
+ (variables) => {
2442
+ mutateAsync(variables).catch(() => {
2443
+ });
2444
+ },
2445
+ [mutateAsync]
2446
+ );
2447
+ return {
2448
+ mutate,
2449
+ mutateAsync,
2450
+ isPending,
2451
+ isSuccess,
2452
+ isError,
2453
+ error,
2454
+ data,
2455
+ reset
2456
+ };
2457
+ }
2458
+ function useStreamWorkflow({ debugMode, tracingOptions, onError }) {
2459
+ const client = useMastraClient();
2460
+ const [streamResult, setStreamResult] = react.useState({});
2461
+ const [isStreaming, setIsStreaming] = react.useState(false);
2462
+ const readerRef = react.useRef(null);
2463
+ const observerRef = react.useRef(null);
2464
+ const resumeStreamRef = react.useRef(null);
2465
+ const timeTravelStreamRef = react.useRef(null);
2466
+ const isMountedRef = react.useRef(true);
2467
+ react.useEffect(() => {
2468
+ isMountedRef.current = true;
2469
+ return () => {
2470
+ isMountedRef.current = false;
2471
+ if (readerRef.current) {
2472
+ try {
2473
+ readerRef.current.releaseLock();
2474
+ } catch {
2475
+ }
2476
+ readerRef.current = null;
2477
+ }
2478
+ if (observerRef.current) {
2479
+ try {
2480
+ observerRef.current.releaseLock();
2481
+ } catch {
2482
+ }
2483
+ observerRef.current = null;
2484
+ }
2485
+ if (resumeStreamRef.current) {
2486
+ try {
2487
+ resumeStreamRef.current.releaseLock();
2488
+ } catch {
2489
+ }
2490
+ resumeStreamRef.current = null;
2491
+ }
2492
+ if (timeTravelStreamRef.current) {
2493
+ try {
2494
+ timeTravelStreamRef.current.releaseLock();
2495
+ } catch {
2496
+ }
2497
+ timeTravelStreamRef.current = null;
2498
+ }
2499
+ };
2500
+ }, []);
2501
+ const handleStreamError = react.useCallback(
2502
+ (err, defaultMessage, setStreamingState) => {
2503
+ if (err instanceof TypeError) {
2504
+ return;
2505
+ }
2506
+ const error = err instanceof Error ? err : new Error(defaultMessage);
2507
+ onError?.(error, defaultMessage);
2508
+ setStreamingState?.(false);
2509
+ },
2510
+ [onError]
2511
+ );
2512
+ const handleWorkflowFinish = react.useCallback((value) => {
2513
+ if (value.type === "workflow-finish") {
2514
+ const streamStatus = value.payload?.workflowStatus;
2515
+ const metadata = value.payload?.metadata;
2516
+ setStreamResult((prev) => ({
2517
+ ...prev,
2518
+ status: streamStatus
2519
+ }));
2520
+ if (streamStatus === "failed") {
2521
+ throw new Error(metadata?.errorMessage || "Workflow execution failed");
2522
+ }
2523
+ }
2524
+ }, []);
2525
+ const streamWorkflow = useMutation(
2526
+ async ({ workflowId, runId, inputData, initialState, requestContext: playgroundRequestContext, perStep }) => {
2527
+ if (readerRef.current) {
2528
+ readerRef.current.releaseLock();
2529
+ }
2530
+ if (!isMountedRef.current) return;
2531
+ setIsStreaming(true);
2532
+ setStreamResult({ input: inputData });
2533
+ const workflow = client.getWorkflow(workflowId);
2534
+ const run = await workflow.createRun({ runId });
2535
+ const stream = await run.stream({
2536
+ inputData,
2537
+ initialState,
2538
+ requestContext: playgroundRequestContext,
2539
+ closeOnSuspend: true,
2540
+ tracingOptions,
2541
+ perStep: perStep ?? debugMode
2542
+ });
2543
+ if (!stream) {
2544
+ return handleStreamError(new Error("No stream returned"), "No stream returned", setIsStreaming);
2545
+ }
2546
+ const reader = stream.getReader();
2547
+ readerRef.current = reader;
2548
+ try {
2549
+ while (true) {
2550
+ if (!isMountedRef.current) break;
2551
+ const { done, value } = await reader.read();
2552
+ if (done) break;
2553
+ if (isMountedRef.current) {
2554
+ setStreamResult((prev) => {
2555
+ const newResult = mapWorkflowStreamChunkToWatchResult(prev, value);
2556
+ return newResult;
2557
+ });
2558
+ if (value.type === "workflow-step-start") {
2559
+ setIsStreaming(true);
2560
+ }
2561
+ if (value.type === "workflow-step-suspended") {
2562
+ setIsStreaming(false);
2563
+ }
2564
+ if (value.type === "workflow-finish") {
2565
+ handleWorkflowFinish(value);
2566
+ }
2567
+ }
2568
+ }
2569
+ } catch (err) {
2570
+ handleStreamError(err, "Error streaming workflow");
2571
+ } finally {
2572
+ if (isMountedRef.current) {
2573
+ setIsStreaming(false);
2574
+ }
2575
+ if (readerRef.current) {
2576
+ readerRef.current.releaseLock();
2577
+ readerRef.current = null;
2578
+ }
2579
+ }
2580
+ }
2581
+ );
2582
+ const observeWorkflowStream = useMutation(
2583
+ async ({ workflowId, runId, storeRunResult }) => {
2584
+ if (observerRef.current) {
2585
+ observerRef.current.releaseLock();
2586
+ }
2587
+ if (!isMountedRef.current) return;
2588
+ setIsStreaming(true);
2589
+ setStreamResult(storeRunResult || {});
2590
+ if (storeRunResult?.status === "suspended") {
2591
+ setIsStreaming(false);
2592
+ return;
2593
+ }
2594
+ const workflow = client.getWorkflow(workflowId);
2595
+ const run = await workflow.createRun({ runId });
2596
+ const stream = await run.observeStream();
2597
+ if (!stream) {
2598
+ return handleStreamError(new Error("No stream returned"), "No stream returned", setIsStreaming);
2599
+ }
2600
+ const reader = stream.getReader();
2601
+ observerRef.current = reader;
2602
+ try {
2603
+ while (true) {
2604
+ if (!isMountedRef.current) break;
2605
+ const { done, value } = await reader.read();
2606
+ if (done) break;
2607
+ if (isMountedRef.current) {
2608
+ setStreamResult((prev) => {
2609
+ const newResult = mapWorkflowStreamChunkToWatchResult(prev, value);
2610
+ return newResult;
2611
+ });
2612
+ if (value.type === "workflow-step-start") {
2613
+ setIsStreaming(true);
2614
+ }
2615
+ if (value.type === "workflow-step-suspended") {
2616
+ setIsStreaming(false);
2617
+ }
2618
+ if (value.type === "workflow-finish") {
2619
+ handleWorkflowFinish(value);
2620
+ }
2621
+ }
2622
+ }
2623
+ } catch (err) {
2624
+ handleStreamError(err, "Error observing workflow");
2625
+ } finally {
2626
+ if (isMountedRef.current) {
2627
+ setIsStreaming(false);
2628
+ }
2629
+ if (observerRef.current) {
2630
+ observerRef.current.releaseLock();
2631
+ observerRef.current = null;
2632
+ }
2633
+ }
2634
+ }
2635
+ );
2636
+ const resumeWorkflowStream = useMutation(
2637
+ async ({ workflowId, runId, step, resumeData, requestContext: playgroundRequestContext, perStep }) => {
2638
+ if (resumeStreamRef.current) {
2639
+ resumeStreamRef.current.releaseLock();
2640
+ }
2641
+ if (!isMountedRef.current) return;
2642
+ setIsStreaming(true);
2643
+ const workflow = client.getWorkflow(workflowId);
2644
+ const run = await workflow.createRun({ runId });
2645
+ const stream = await run.resumeStream({
2646
+ step,
2647
+ resumeData,
2648
+ requestContext: playgroundRequestContext,
2649
+ tracingOptions,
2650
+ perStep: perStep ?? debugMode
2651
+ });
2652
+ if (!stream) {
2653
+ return handleStreamError(new Error("No stream returned"), "No stream returned", setIsStreaming);
2654
+ }
2655
+ const reader = stream.getReader();
2656
+ resumeStreamRef.current = reader;
2657
+ try {
2658
+ while (true) {
2659
+ if (!isMountedRef.current) break;
2660
+ const { done, value } = await reader.read();
2661
+ if (done) break;
2662
+ if (isMountedRef.current) {
2663
+ setStreamResult((prev) => {
2664
+ const newResult = mapWorkflowStreamChunkToWatchResult(prev, value);
2665
+ return newResult;
2666
+ });
2667
+ if (value.type === "workflow-step-start") {
2668
+ setIsStreaming(true);
2669
+ }
2670
+ if (value.type === "workflow-step-suspended") {
2671
+ setIsStreaming(false);
2672
+ }
2673
+ if (value.type === "workflow-finish") {
2674
+ handleWorkflowFinish(value);
2675
+ }
2676
+ }
2677
+ }
2678
+ } catch (err) {
2679
+ handleStreamError(err, "Error resuming workflow stream");
2680
+ } finally {
2681
+ if (isMountedRef.current) {
2682
+ setIsStreaming(false);
2683
+ }
2684
+ if (resumeStreamRef.current) {
2685
+ resumeStreamRef.current.releaseLock();
2686
+ resumeStreamRef.current = null;
2687
+ }
2688
+ }
2689
+ }
2690
+ );
2691
+ const timeTravelWorkflowStream = useMutation(
2692
+ async ({ workflowId, requestContext: playgroundRequestContext, runId, perStep, ...params }) => {
2693
+ if (timeTravelStreamRef.current) {
2694
+ timeTravelStreamRef.current.releaseLock();
2695
+ }
2696
+ if (!isMountedRef.current) return;
2697
+ setIsStreaming(true);
2698
+ const workflow = client.getWorkflow(workflowId);
2699
+ const run = await workflow.createRun({ runId });
2700
+ const stream = await run.timeTravelStream({
2701
+ ...params,
2702
+ perStep: perStep ?? debugMode,
2703
+ requestContext: playgroundRequestContext,
2704
+ tracingOptions
2705
+ });
2706
+ if (!stream) {
2707
+ return handleStreamError(new Error("No stream returned"), "No stream returned", setIsStreaming);
2708
+ }
2709
+ const reader = stream.getReader();
2710
+ timeTravelStreamRef.current = reader;
2711
+ try {
2712
+ while (true) {
2713
+ if (!isMountedRef.current) break;
2714
+ const { done, value } = await reader.read();
2715
+ if (done) break;
2716
+ if (isMountedRef.current) {
2717
+ setStreamResult((prev) => {
2718
+ const newResult = mapWorkflowStreamChunkToWatchResult(prev, value);
2719
+ return newResult;
2720
+ });
2721
+ if (value.type === "workflow-step-start") {
2722
+ setIsStreaming(true);
2723
+ }
2724
+ if (value.type === "workflow-step-suspended") {
2725
+ setIsStreaming(false);
2726
+ }
2727
+ if (value.type === "workflow-finish") {
2728
+ handleWorkflowFinish(value);
2729
+ }
2730
+ }
2731
+ }
2732
+ } catch (err) {
2733
+ handleStreamError(err, "Error time traveling workflow stream");
2734
+ } finally {
2735
+ if (isMountedRef.current) {
2736
+ setIsStreaming(false);
2737
+ }
2738
+ if (timeTravelStreamRef.current) {
2739
+ timeTravelStreamRef.current.releaseLock();
2740
+ timeTravelStreamRef.current = null;
2741
+ }
2742
+ }
2743
+ }
2744
+ );
2745
+ const closeStreamsAndReset = react.useCallback(() => {
2746
+ setIsStreaming(false);
2747
+ setStreamResult({});
2748
+ if (readerRef.current) {
2749
+ try {
2750
+ readerRef.current.releaseLock();
2751
+ } catch {
2752
+ }
2753
+ readerRef.current = null;
2754
+ }
2755
+ if (observerRef.current) {
2756
+ try {
2757
+ observerRef.current.releaseLock();
2758
+ } catch {
2759
+ }
2760
+ observerRef.current = null;
2761
+ }
2762
+ if (resumeStreamRef.current) {
2763
+ try {
2764
+ resumeStreamRef.current.releaseLock();
2765
+ } catch {
2766
+ }
2767
+ resumeStreamRef.current = null;
2768
+ }
2769
+ if (timeTravelStreamRef.current) {
2770
+ try {
2771
+ timeTravelStreamRef.current.releaseLock();
2772
+ } catch {
2773
+ }
2774
+ timeTravelStreamRef.current = null;
2775
+ }
2776
+ }, []);
2777
+ return {
2778
+ streamWorkflow,
2779
+ streamResult,
2780
+ isStreaming,
2781
+ observeWorkflowStream,
2782
+ closeStreamsAndReset,
2783
+ resumeWorkflowStream,
2784
+ timeTravelWorkflowStream
2785
+ };
2786
+ }
2787
+
2788
+ // src/workflows/hooks.ts
2789
+ function useCreateWorkflowRun() {
2790
+ const client = useMastraClient();
2791
+ return useMutation(async ({ workflowId, prevRunId }) => {
2792
+ try {
2793
+ const workflow = client.getWorkflow(workflowId);
2794
+ const { runId: newRunId } = await workflow.createRun({ runId: prevRunId });
2795
+ return { runId: newRunId };
2796
+ } catch (error) {
2797
+ console.error("Error creating workflow run:", error);
2798
+ throw error;
2799
+ }
2800
+ });
2801
+ }
2802
+ function useCancelWorkflowRun() {
2803
+ const client = useMastraClient();
2804
+ return useMutation(async ({ workflowId, runId }) => {
2805
+ try {
2806
+ const workflow = client.getWorkflow(workflowId);
2807
+ const run = await workflow.createRun({ runId });
2808
+ return run.cancelRun();
2809
+ } catch (error) {
2810
+ console.error("Error canceling workflow run:", error);
2811
+ throw error;
2812
+ }
2813
+ });
2814
+ }
2815
+
2816
+ exports.AgentIcon = AgentIcon;
2817
+ exports.CodeBlock = CodeBlock;
2818
+ exports.CodeBlockClass = CodeBlockClass;
2819
+ exports.CodeCopyButton = CodeCopyButton;
2820
+ exports.Entity = Entity;
2821
+ exports.EntityCaret = EntityCaret;
2822
+ exports.EntityContent = EntityContent;
2823
+ exports.EntityContentClass = EntityContentClass;
2824
+ exports.EntityTrigger = EntityTrigger;
2825
+ exports.EntityTriggerClass = EntityTriggerClass;
2826
+ exports.EntityTriggerVariantClasses = EntityTriggerVariantClasses;
2827
+ exports.Entry = Entry;
2828
+ exports.EntryClass = EntryClass;
2829
+ exports.EntryTitle = EntryTitle;
2830
+ exports.EntryTitleClass = EntryTitleClass;
2831
+ exports.Icon = Icon;
2832
+ exports.IconButton = IconButton;
2833
+ exports.IconButtonClass = IconButtonClass;
2834
+ exports.IconSizes = IconSizes;
2835
+ exports.MastraReactProvider = MastraReactProvider;
2836
+ exports.Message = Message;
2837
+ exports.MessageActions = MessageActions;
2838
+ exports.MessageActionsClass = MessageActionsClass;
2839
+ exports.MessageClass = MessageClass;
2840
+ exports.MessageContent = MessageContent;
2841
+ exports.MessageContentClass = MessageContentClass;
2842
+ exports.MessageList = MessageList;
2843
+ exports.MessageListClass = MessageListClass;
2844
+ exports.MessageStreaming = MessageStreaming;
2845
+ exports.MessageStreamingClass = MessageStreamingClass;
2846
+ exports.MessageUsage = MessageUsage;
2847
+ exports.MessageUsageClass = MessageUsageClass;
2848
+ exports.MessageUsageEntry = MessageUsageEntry;
2849
+ exports.MessageUsageEntryClass = MessageUsageEntryClass;
2850
+ exports.MessageUsageValue = MessageUsageValue;
2851
+ exports.MessageUsageValueClass = MessageUsageValueClass;
2852
+ exports.MessageUsages = MessageUsages;
2853
+ exports.MessageUsagesClass = MessageUsagesClass;
2854
+ exports.ToolApproval = ToolApproval;
2855
+ exports.ToolApprovalActions = ToolApprovalActions;
2856
+ exports.ToolApprovalActionsClass = ToolApprovalActionsClass;
2857
+ exports.ToolApprovalClass = ToolApprovalClass;
2858
+ exports.ToolApprovalContent = ToolApprovalContent;
2859
+ exports.ToolApprovalContentClass = ToolApprovalContentClass;
2860
+ exports.ToolApprovalHeader = ToolApprovalHeader;
2861
+ exports.ToolApprovalHeaderClass = ToolApprovalHeaderClass;
2862
+ exports.ToolApprovalTitle = ToolApprovalTitle;
2863
+ exports.ToolApprovalTitleClass = ToolApprovalTitleClass;
2864
+ exports.ToolsIcon = ToolsIcon;
2865
+ exports.Tooltip = Tooltip;
2866
+ exports.TooltipContent = TooltipContent;
2867
+ exports.TooltipContentClass = TooltipContentClass;
2868
+ exports.TooltipTrigger = TooltipTrigger;
2869
+ exports.WorkflowIcon = WorkflowIcon;
2870
+ exports.mapWorkflowStreamChunkToWatchResult = mapWorkflowStreamChunkToWatchResult;
2871
+ exports.resolveToChildMessages = resolveToChildMessages;
2872
+ exports.toAssistantUIMessage = toAssistantUIMessage;
2873
+ exports.toUIMessage = toUIMessage;
2874
+ exports.useCancelWorkflowRun = useCancelWorkflowRun;
2875
+ exports.useChat = useChat;
2876
+ exports.useCreateWorkflowRun = useCreateWorkflowRun;
2877
+ exports.useEntity = useEntity;
2878
+ exports.useMastraClient = useMastraClient;
2879
+ exports.useStreamWorkflow = useStreamWorkflow;
73
2880
  //# sourceMappingURL=index.cjs.map
2881
+ //# sourceMappingURL=index.cjs.map