@mastra/core 0.10.13 → 0.10.15-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (235) hide show
  1. package/a2a.d.ts +1 -0
  2. package/agent.d.ts +1 -0
  3. package/base.d.ts +1 -0
  4. package/bundler.d.ts +1 -0
  5. package/deployer.d.ts +1 -0
  6. package/di.d.ts +1 -0
  7. package/dist/a2a/index.cjs +79 -0
  8. package/dist/a2a/index.d.cts +780 -0
  9. package/dist/a2a/index.d.ts +780 -0
  10. package/dist/a2a/index.js +68 -0
  11. package/dist/agent/index.cjs +15 -0
  12. package/dist/agent/index.d.cts +29 -0
  13. package/dist/agent/index.d.ts +29 -0
  14. package/dist/agent/index.js +2 -0
  15. package/dist/base-B_y9sMg0.d.cts +162 -0
  16. package/dist/base-CTj7ESwt.d.cts +4132 -0
  17. package/dist/base-ClrXcCRx.d.ts +162 -0
  18. package/dist/base-qVqAnB-c.d.ts +4132 -0
  19. package/dist/base.cjs +10 -0
  20. package/dist/base.d.cts +6 -0
  21. package/dist/base.d.ts +6 -0
  22. package/dist/base.js +1 -0
  23. package/dist/bundler/index.cjs +10 -0
  24. package/dist/bundler/index.d.cts +30 -0
  25. package/dist/bundler/index.d.ts +30 -0
  26. package/dist/bundler/index.js +1 -0
  27. package/dist/chunk-32C7JDIZ.js +1 -0
  28. package/dist/chunk-4UWPFBC6.js +88 -0
  29. package/dist/chunk-4Z3OU5RY.cjs +31 -0
  30. package/dist/chunk-5HTMDAXP.js +359 -0
  31. package/dist/chunk-5IEKR756.js +53 -0
  32. package/dist/chunk-5YDTZN2X.js +114 -0
  33. package/dist/chunk-6UNGH46J.js +75 -0
  34. package/dist/chunk-6Y4UL5Z6.cjs +94 -0
  35. package/dist/chunk-7H2GET5Z.cjs +668 -0
  36. package/dist/chunk-7HZ6NIAF.cjs +2 -0
  37. package/dist/chunk-7XQIPES3.js +668 -0
  38. package/dist/chunk-AKYTYALY.js +70 -0
  39. package/dist/chunk-AOWJUV2N.js +2415 -0
  40. package/dist/chunk-ATXBSEFT.js +22 -0
  41. package/dist/chunk-B6TOBUS6.cjs +80 -0
  42. package/dist/chunk-B7SQOKEC.cjs +91 -0
  43. package/dist/chunk-BB4KXGBU.js +83 -0
  44. package/dist/chunk-BB6DPGIV.cjs +6 -0
  45. package/dist/chunk-BVD7NVAR.cjs +244 -0
  46. package/dist/chunk-C4LMN2IR.js +27 -0
  47. package/dist/chunk-DR4JS662.js +989 -0
  48. package/dist/chunk-F2WMR75C.cjs +183 -0
  49. package/dist/chunk-FEYYOBBG.cjs +24 -0
  50. package/dist/chunk-FL5SZ2XU.js +181 -0
  51. package/dist/chunk-GH2KM66J.js +37 -0
  52. package/dist/chunk-GWFS5DAR.cjs +37 -0
  53. package/dist/chunk-HNEE7IF4.js +60 -0
  54. package/dist/chunk-HSVOEWAM.cjs +2 -0
  55. package/dist/chunk-IBKM5CLQ.js +428 -0
  56. package/dist/chunk-ID5LG5CQ.cjs +659 -0
  57. package/dist/chunk-J52TXHZV.cjs +73 -0
  58. package/dist/chunk-J62R4M7K.js +240 -0
  59. package/dist/chunk-JNMQKJH4.js +10 -0
  60. package/dist/chunk-JQOMTERC.js +89 -0
  61. package/dist/chunk-LABUWBKX.cjs +71 -0
  62. package/dist/chunk-LBUQ6YNU.cjs +447 -0
  63. package/dist/chunk-LXFZUKP3.cjs +34 -0
  64. package/dist/chunk-MP2QBLUJ.cjs +70 -0
  65. package/dist/chunk-MUNFCOMB.cjs +62 -0
  66. package/dist/chunk-MVCHTRVB.js +5038 -0
  67. package/dist/chunk-NH5WJNNS.js +1 -0
  68. package/dist/chunk-P3Q73CAW.cjs +55 -0
  69. package/dist/chunk-Q33INUG2.cjs +81 -0
  70. package/dist/chunk-QFTBW7ZZ.cjs +2 -0
  71. package/dist/chunk-QQ5K5TZE.cjs +619 -0
  72. package/dist/chunk-R4V75T7J.js +1 -0
  73. package/dist/chunk-RVFWMGGR.js +77 -0
  74. package/dist/chunk-SGGPJWRQ.js +69 -0
  75. package/dist/chunk-ST5RMVLG.cjs +87 -0
  76. package/dist/chunk-TC2SCOTE.js +605 -0
  77. package/dist/chunk-TTMYHBQM.js +657 -0
  78. package/dist/chunk-U64IJDC5.cjs +109 -0
  79. package/dist/chunk-ULZ6MRTN.cjs +5065 -0
  80. package/dist/chunk-V5D2LIF5.js +68 -0
  81. package/dist/chunk-WQNOATKB.js +103 -0
  82. package/dist/chunk-Y7D2JLKS.js +4 -0
  83. package/dist/chunk-YOQP5T77.js +32 -0
  84. package/dist/chunk-ZCU3PLIL.cjs +2429 -0
  85. package/dist/chunk-ZIZ3CVHN.cjs +120 -0
  86. package/dist/chunk-ZPOUMTTH.cjs +362 -0
  87. package/dist/chunk-ZTPPDHQK.cjs +991 -0
  88. package/dist/chunk-ZZLBNB3U.cjs +12 -0
  89. package/dist/deployer/index.cjs +10 -0
  90. package/dist/deployer/index.d.cts +19 -0
  91. package/dist/deployer/index.d.ts +19 -0
  92. package/dist/deployer/index.js +1 -0
  93. package/dist/di/index.cjs +10 -0
  94. package/dist/di/index.d.cts +1 -0
  95. package/dist/di/index.d.ts +1 -0
  96. package/dist/di/index.js +1 -0
  97. package/dist/error/index.cjs +22 -0
  98. package/dist/error/index.d.cts +86 -0
  99. package/dist/error/index.d.ts +86 -0
  100. package/dist/error/index.js +1 -0
  101. package/dist/eval/index.cjs +14 -0
  102. package/dist/eval/index.d.cts +43 -0
  103. package/dist/eval/index.d.ts +43 -0
  104. package/dist/eval/index.js +1 -0
  105. package/dist/hooks/index.cjs +18 -0
  106. package/dist/hooks/index.d.cts +33 -0
  107. package/dist/hooks/index.d.ts +33 -0
  108. package/dist/hooks/index.js +1 -0
  109. package/dist/index.cjs +285 -0
  110. package/dist/index.d.cts +92 -0
  111. package/dist/index.d.ts +92 -0
  112. package/dist/index.js +112 -0
  113. package/dist/integration/index.cjs +14 -0
  114. package/dist/integration/index.d.cts +65 -0
  115. package/dist/integration/index.d.ts +65 -0
  116. package/dist/integration/index.js +1 -0
  117. package/dist/llm/index.cjs +10 -0
  118. package/dist/llm/index.d.cts +29 -0
  119. package/dist/llm/index.d.ts +29 -0
  120. package/dist/llm/index.js +1 -0
  121. package/dist/logger/index.cjs +43 -0
  122. package/dist/logger/index.d.cts +96 -0
  123. package/dist/logger/index.d.ts +96 -0
  124. package/dist/logger/index.js +2 -0
  125. package/dist/logger-B8XXh6ya.d.cts +159 -0
  126. package/dist/logger-Bpa2oLL4.d.ts +159 -0
  127. package/dist/mastra/index.cjs +10 -0
  128. package/dist/mastra/index.d.cts +29 -0
  129. package/dist/mastra/index.d.ts +29 -0
  130. package/dist/mastra/index.js +1 -0
  131. package/dist/mcp/index.cjs +106 -0
  132. package/dist/mcp/index.d.cts +29 -0
  133. package/dist/mcp/index.d.ts +29 -0
  134. package/dist/mcp/index.js +100 -0
  135. package/dist/memory/index.cjs +18 -0
  136. package/dist/memory/index.d.cts +29 -0
  137. package/dist/memory/index.d.ts +29 -0
  138. package/dist/memory/index.js +1 -0
  139. package/dist/network/index.cjs +311 -0
  140. package/dist/network/index.d.cts +29 -0
  141. package/dist/network/index.d.ts +29 -0
  142. package/dist/network/index.js +309 -0
  143. package/dist/network/vNext/index.cjs +880 -0
  144. package/dist/network/vNext/index.d.cts +29 -0
  145. package/dist/network/vNext/index.d.ts +29 -0
  146. package/dist/network/vNext/index.js +878 -0
  147. package/dist/relevance/index.cjs +18 -0
  148. package/dist/relevance/index.d.cts +50 -0
  149. package/dist/relevance/index.d.ts +50 -0
  150. package/dist/relevance/index.js +1 -0
  151. package/dist/runtime-context/index.cjs +10 -0
  152. package/dist/runtime-context/index.d.cts +52 -0
  153. package/dist/runtime-context/index.d.ts +52 -0
  154. package/dist/runtime-context/index.js +1 -0
  155. package/dist/server/index.cjs +62 -0
  156. package/dist/server/index.d.cts +52 -0
  157. package/dist/server/index.d.ts +52 -0
  158. package/dist/server/index.js +59 -0
  159. package/dist/storage/index.cjs +336 -0
  160. package/dist/storage/index.d.cts +149 -0
  161. package/dist/storage/index.d.ts +149 -0
  162. package/dist/storage/index.js +303 -0
  163. package/dist/telemetry/index.cjs +30 -0
  164. package/dist/telemetry/index.d.cts +75 -0
  165. package/dist/telemetry/index.d.ts +75 -0
  166. package/dist/telemetry/index.js +1 -0
  167. package/dist/telemetry/otel-vendor.cjs +103 -0
  168. package/dist/telemetry/otel-vendor.d.cts +20 -0
  169. package/dist/telemetry/otel-vendor.d.ts +20 -0
  170. package/dist/telemetry/otel-vendor.js +57 -0
  171. package/dist/tools/index.cjs +18 -0
  172. package/dist/tools/index.d.cts +41 -0
  173. package/dist/tools/index.d.ts +41 -0
  174. package/dist/tools/index.js +1 -0
  175. package/dist/tts/index.cjs +10 -0
  176. package/dist/tts/index.d.cts +28 -0
  177. package/dist/tts/index.d.ts +28 -0
  178. package/dist/tts/index.js +1 -0
  179. package/dist/types-Bo1uigWx.d.cts +17 -0
  180. package/dist/types-Bo1uigWx.d.ts +17 -0
  181. package/dist/utils.cjs +62 -0
  182. package/dist/utils.d.cts +150 -0
  183. package/dist/utils.d.ts +150 -0
  184. package/dist/utils.js +1 -0
  185. package/dist/vector/filter/index.cjs +192 -0
  186. package/dist/vector/filter/index.d.cts +128 -0
  187. package/dist/vector/filter/index.d.ts +128 -0
  188. package/dist/vector/filter/index.js +190 -0
  189. package/dist/vector/index.cjs +10 -0
  190. package/dist/vector/index.d.cts +77 -0
  191. package/dist/vector/index.d.ts +77 -0
  192. package/dist/vector/index.js +1 -0
  193. package/dist/voice/index.cjs +18 -0
  194. package/dist/voice/index.d.cts +29 -0
  195. package/dist/voice/index.d.ts +29 -0
  196. package/dist/voice/index.js +1 -0
  197. package/dist/workflows/constants.cjs +10 -0
  198. package/dist/workflows/constants.d.cts +3 -0
  199. package/dist/workflows/constants.d.ts +3 -0
  200. package/dist/workflows/constants.js +1 -0
  201. package/dist/workflows/index.cjs +42 -0
  202. package/dist/workflows/index.d.cts +285 -0
  203. package/dist/workflows/index.d.ts +285 -0
  204. package/dist/workflows/index.js +1 -0
  205. package/dist/workflows/legacy/index.cjs +90 -0
  206. package/dist/workflows/legacy/index.d.cts +91 -0
  207. package/dist/workflows/legacy/index.d.ts +91 -0
  208. package/dist/workflows/legacy/index.js +1 -0
  209. package/error.d.ts +1 -0
  210. package/eval.d.ts +1 -0
  211. package/hooks.d.ts +1 -0
  212. package/integration.d.ts +1 -0
  213. package/llm.d.ts +1 -0
  214. package/logger.d.ts +1 -0
  215. package/mastra.d.ts +1 -0
  216. package/mcp.d.ts +1 -0
  217. package/memory.d.ts +1 -0
  218. package/network/vNext.d.ts +1 -0
  219. package/network.d.ts +1 -0
  220. package/package.json +2 -3
  221. package/relevance.d.ts +1 -0
  222. package/runtime-context.d.ts +1 -0
  223. package/server.d.ts +1 -0
  224. package/storage.d.ts +1 -0
  225. package/telemetry/otel-vendor.d.ts +1 -0
  226. package/telemetry.d.ts +1 -0
  227. package/tools.d.ts +1 -0
  228. package/tts.d.ts +1 -0
  229. package/utils.d.ts +1 -0
  230. package/vector/filter.d.ts +1 -0
  231. package/vector.d.ts +1 -0
  232. package/voice.d.ts +1 -0
  233. package/workflows/_constants.d.ts +1 -0
  234. package/workflows/legacy.d.ts +1 -0
  235. package/workflows.d.ts +1 -0
@@ -0,0 +1,878 @@
1
+ import { createStep, createWorkflow } from '../../chunk-AOWJUV2N.js';
2
+ import { EMITTER_SYMBOL } from '../../chunk-Y7D2JLKS.js';
3
+ import { Agent } from '../../chunk-MVCHTRVB.js';
4
+ import { MastraBase } from '../../chunk-5IEKR756.js';
5
+ import { RegisteredLogger } from '../../chunk-5YDTZN2X.js';
6
+ import { RuntimeContext } from '../../chunk-SGGPJWRQ.js';
7
+ import { randomUUID } from 'crypto';
8
+ import { z } from 'zod';
9
+ import { zodToJsonSchema } from 'zod-to-json-schema';
10
+
11
+ var RESOURCE_TYPES = z.enum(["agent", "workflow", "none", "tool", "none"]);
12
+ var NewAgentNetwork = class extends MastraBase {
13
+ id;
14
+ name;
15
+ #instructions;
16
+ #model;
17
+ #agents;
18
+ #defaultAgent;
19
+ #workflows;
20
+ #tools;
21
+ #memory;
22
+ #mastra;
23
+ constructor({
24
+ id,
25
+ name,
26
+ instructions,
27
+ model,
28
+ agents,
29
+ workflows,
30
+ memory,
31
+ tools,
32
+ defaultAgent
33
+ }) {
34
+ super({
35
+ component: RegisteredLogger.NETWORK,
36
+ name: name || "NewAgentNetwork"
37
+ });
38
+ this.id = id;
39
+ this.name = name;
40
+ this.#instructions = instructions;
41
+ this.#model = model;
42
+ this.#agents = agents;
43
+ this.#workflows = workflows;
44
+ this.#memory = memory;
45
+ this.#tools = tools;
46
+ this.#defaultAgent = defaultAgent;
47
+ }
48
+ __registerMastra(mastra) {
49
+ this.#mastra = mastra;
50
+ }
51
+ async beforeRun({
52
+ runtimeContext,
53
+ threadId,
54
+ resourceId,
55
+ message
56
+ }) {
57
+ const memory = await this.getMemory({ runtimeContext });
58
+ let thread = await memory?.getThreadById({ threadId });
59
+ if (!thread) {
60
+ thread = await memory?.createThread({
61
+ threadId,
62
+ title: "",
63
+ resourceId
64
+ });
65
+ }
66
+ await memory?.saveMessages({
67
+ messages: [
68
+ {
69
+ id: randomUUID(),
70
+ type: "text",
71
+ role: "user",
72
+ content: { parts: [{ type: "text", text: message }], format: 2 },
73
+ createdAt: /* @__PURE__ */ new Date(),
74
+ threadId: thread?.id,
75
+ resourceId: thread?.resourceId
76
+ }
77
+ ],
78
+ format: "v2"
79
+ });
80
+ return thread;
81
+ }
82
+ async getAgents({ runtimeContext }) {
83
+ let agentsToUse;
84
+ if (typeof this.#agents === "function") {
85
+ agentsToUse = await this.#agents({ runtimeContext: runtimeContext || new RuntimeContext() });
86
+ } else {
87
+ agentsToUse = this.#agents;
88
+ }
89
+ return agentsToUse;
90
+ }
91
+ async getWorkflows({ runtimeContext }) {
92
+ let workflowsToUse;
93
+ if (typeof this.#workflows === "function") {
94
+ workflowsToUse = await this.#workflows({ runtimeContext: runtimeContext || new RuntimeContext() });
95
+ } else {
96
+ workflowsToUse = this.#workflows || {};
97
+ }
98
+ return workflowsToUse;
99
+ }
100
+ async getTools({ runtimeContext }) {
101
+ let toolsToUse;
102
+ if (typeof this.#tools === "function") {
103
+ toolsToUse = await this.#tools({ runtimeContext: runtimeContext || new RuntimeContext() });
104
+ } else {
105
+ toolsToUse = this.#tools || {};
106
+ }
107
+ return toolsToUse;
108
+ }
109
+ async getMemory({ runtimeContext }) {
110
+ let memoryToUse;
111
+ if (!this.#memory) {
112
+ return;
113
+ }
114
+ if (typeof this.#memory === "function") {
115
+ memoryToUse = await this.#memory({ runtimeContext: runtimeContext || new RuntimeContext() });
116
+ } else {
117
+ memoryToUse = this.#memory;
118
+ }
119
+ return memoryToUse;
120
+ }
121
+ async getInstructions({ runtimeContext }) {
122
+ let instructionsToUse = this.#instructions;
123
+ if (typeof instructionsToUse === "function") {
124
+ instructionsToUse = await instructionsToUse({ runtimeContext: runtimeContext || new RuntimeContext() });
125
+ }
126
+ return instructionsToUse;
127
+ }
128
+ async getRoutingAgent({ runtimeContext }) {
129
+ const instructionsToUse = await this.getInstructions({ runtimeContext: runtimeContext || new RuntimeContext() });
130
+ const memoryToUse = await this.getMemory({ runtimeContext: runtimeContext || new RuntimeContext() });
131
+ const agentsToUse = await this.getAgents({ runtimeContext: runtimeContext || new RuntimeContext() });
132
+ const workflowsToUse = await this.getWorkflows({ runtimeContext: runtimeContext || new RuntimeContext() });
133
+ const toolsToUse = await this.getTools({ runtimeContext: runtimeContext || new RuntimeContext() });
134
+ const agentList = Object.entries(agentsToUse).map(([name, agent]) => {
135
+ return ` - **${name}**: ${agent.getDescription()}`;
136
+ }).join("\n");
137
+ const workflowList = Object.entries(workflowsToUse).map(([name, workflow]) => {
138
+ return ` - **${name}**: ${workflow.description}, input schema: ${JSON.stringify(
139
+ zodToJsonSchema(workflow.inputSchema)
140
+ )}`;
141
+ }).join("\n");
142
+ const toolList = Object.entries(toolsToUse).map(([name, tool]) => {
143
+ return ` - **${name}**: ${tool.description}, input schema: ${JSON.stringify(
144
+ zodToJsonSchema(tool.inputSchema || z.object({}))
145
+ )}`;
146
+ }).join("\n");
147
+ const instructions = `
148
+ You are a router in a network of specialized AI agents.
149
+ Your job is to decide which agent should handle each step of a task.
150
+
151
+ If asking for completion of a task, make sure to follow system instructions closely.
152
+
153
+ ## System Instructions
154
+ ${instructionsToUse}
155
+
156
+ You can only pick agents and workflows that are available in the lists below. Never call any agents or workflows that are not available in the lists below.
157
+
158
+ ## Available Agents in Network
159
+ ${agentList}
160
+
161
+ ## Available Workflows in Network (make sure to use inputs corresponding to the input schema when calling a workflow)
162
+ ${workflowList}
163
+
164
+ ## Available Tools in Network (make sure to use inputs corresponding to the input schema when calling a tool)
165
+ ${toolList}
166
+
167
+ ${this.#defaultAgent ? `If none of the agents or workflows are appropriate, call the default agent: ${this.#defaultAgent.name}.This should not be done lightly. You should only do this if you have exhausted all other options.` : ""}
168
+
169
+ If you have multiple entries that need to be called with a workflow or agent, call them separately with each input.
170
+ When calling a workflow, the prompt should be a JSON value that corresponds to the input schema of the workflow. The JSON value is stringified.
171
+ When calling a tool, the prompt should be a JSON value that corresponds to the input schema of the tool. The JSON value is stringified.
172
+ When calling an agent, the prompt should be a text value, like you would call an LLM in a chat interface.
173
+
174
+ Keep in mind that the user only sees the final result of the task. When reviewing completion, you should know that the user will not see the intermediate results.
175
+ `;
176
+ return new Agent({
177
+ name: "routing-agent",
178
+ instructions,
179
+ model: this.#model,
180
+ memory: memoryToUse
181
+ });
182
+ }
183
+ async loop(message, {
184
+ runtimeContext,
185
+ maxIterations
186
+ }) {
187
+ const networkWorkflow = this.createWorkflow({ runtimeContext });
188
+ const finalStep = createStep({
189
+ id: "final-step",
190
+ inputSchema: networkWorkflow.outputSchema,
191
+ outputSchema: networkWorkflow.outputSchema,
192
+ execute: async ({ inputData }) => {
193
+ if (maxIterations && inputData.iteration >= maxIterations) {
194
+ return {
195
+ ...inputData,
196
+ completionReason: `Max iterations reached: ${maxIterations}`
197
+ };
198
+ }
199
+ return inputData;
200
+ }
201
+ });
202
+ const mainWorkflow = createWorkflow({
203
+ id: "Agent-Network-Main-Workflow",
204
+ inputSchema: z.object({
205
+ iteration: z.number(),
206
+ task: z.string(),
207
+ resourceType: RESOURCE_TYPES
208
+ }),
209
+ outputSchema: z.object({
210
+ text: z.string(),
211
+ iteration: z.number()
212
+ })
213
+ }).dountil(networkWorkflow, async ({ inputData }) => {
214
+ return inputData.isComplete || maxIterations && inputData.iteration >= maxIterations;
215
+ }).then(finalStep).commit();
216
+ const run = mainWorkflow.createRun();
217
+ const result = await run.start({
218
+ inputData: {
219
+ task: message,
220
+ resourceType: "none",
221
+ iteration: 0
222
+ }
223
+ });
224
+ if (result.status === "failed") {
225
+ throw result.error;
226
+ }
227
+ if (result.status === "suspended") {
228
+ throw new Error("Workflow suspended");
229
+ }
230
+ return result;
231
+ }
232
+ async loopStream(message, {
233
+ runtimeContext,
234
+ maxIterations,
235
+ threadId,
236
+ resourceId
237
+ }) {
238
+ const networkWorkflow = this.createWorkflow({ runtimeContext });
239
+ const finalStep = createStep({
240
+ id: "final-step",
241
+ inputSchema: networkWorkflow.outputSchema,
242
+ outputSchema: networkWorkflow.outputSchema,
243
+ execute: async ({ inputData }) => {
244
+ if (maxIterations && inputData.iteration >= maxIterations) {
245
+ return {
246
+ ...inputData,
247
+ completionReason: `Max iterations reached: ${maxIterations}`
248
+ };
249
+ }
250
+ return inputData;
251
+ }
252
+ });
253
+ const mainWorkflow = createWorkflow({
254
+ id: "Agent-Network-Main-Workflow",
255
+ inputSchema: z.object({
256
+ iteration: z.number(),
257
+ task: z.string(),
258
+ resourceId: z.string(),
259
+ resourceType: RESOURCE_TYPES,
260
+ result: z.string().optional(),
261
+ threadId: z.string().optional(),
262
+ threadResourceId: z.string().optional(),
263
+ isOneOff: z.boolean(),
264
+ verboseIntrospection: z.boolean()
265
+ }),
266
+ outputSchema: z.object({
267
+ task: z.string(),
268
+ resourceId: z.string(),
269
+ resourceType: RESOURCE_TYPES,
270
+ prompt: z.string(),
271
+ result: z.string(),
272
+ isComplete: z.boolean().optional(),
273
+ completionReason: z.string().optional(),
274
+ iteration: z.number()
275
+ })
276
+ }).dountil(networkWorkflow, async ({ inputData }) => {
277
+ return inputData.isComplete || maxIterations && inputData.iteration >= maxIterations;
278
+ }).then(finalStep).commit();
279
+ const run = mainWorkflow.createRun();
280
+ const thread = await this.beforeRun({
281
+ runtimeContext: runtimeContext || new RuntimeContext(),
282
+ threadId: threadId || run.runId,
283
+ resourceId: resourceId || this.name,
284
+ message
285
+ });
286
+ return run.stream({
287
+ inputData: {
288
+ task: message,
289
+ resourceId: "",
290
+ resourceType: "none",
291
+ iteration: 0,
292
+ threadResourceId: thread?.resourceId,
293
+ threadId: thread?.id,
294
+ isOneOff: false,
295
+ verboseIntrospection: true
296
+ }
297
+ });
298
+ }
299
+ createWorkflow({ runtimeContext }) {
300
+ const runId = randomUUID();
301
+ const runtimeContextToUse = runtimeContext || new RuntimeContext();
302
+ const routingStep = createStep({
303
+ id: "routing-step",
304
+ inputSchema: z.object({
305
+ task: z.string(),
306
+ resourceId: z.string(),
307
+ resourceType: RESOURCE_TYPES,
308
+ result: z.string().optional(),
309
+ iteration: z.number(),
310
+ threadId: z.string().optional(),
311
+ threadResourceId: z.string().optional(),
312
+ isOneOff: z.boolean(),
313
+ verboseIntrospection: z.boolean()
314
+ }),
315
+ outputSchema: z.object({
316
+ task: z.string(),
317
+ resourceId: z.string(),
318
+ resourceType: RESOURCE_TYPES,
319
+ prompt: z.string(),
320
+ result: z.string(),
321
+ isComplete: z.boolean().optional(),
322
+ selectionReason: z.string(),
323
+ iteration: z.number()
324
+ }),
325
+ execute: async ({ inputData, getInitData }) => {
326
+ const initData = await getInitData();
327
+ const routingAgent = await this.getRoutingAgent({ runtimeContext: runtimeContextToUse });
328
+ let completionResult;
329
+ if (inputData.resourceType !== "none" && inputData?.result) {
330
+ const completionPrompt = `
331
+ The ${inputData.resourceType} ${inputData.resourceId} has contributed to the task.
332
+ This is the result from the agent: ${inputData.result}
333
+
334
+ You need to evaluate that our task is complete. Pay very close attention to the SYSTEM INSTRUCTIONS for when the task is considered complete. Only return true if the task is complete according to the system instructions. Pay close attention to the finalResult and completionReason.
335
+ Original task: ${inputData.task}
336
+
337
+ {
338
+ "isComplete": boolean,
339
+ "completionReason": string,
340
+ "finalResult": string
341
+ }
342
+ `;
343
+ completionResult = await routingAgent.generate([{ role: "assistant", content: completionPrompt }], {
344
+ output: z.object({
345
+ isComplete: z.boolean(),
346
+ finalResult: z.string(),
347
+ completionReason: z.string()
348
+ }),
349
+ threadId: initData?.threadId ?? runId,
350
+ resourceId: initData?.threadResourceId ?? this.name,
351
+ runtimeContext: runtimeContextToUse
352
+ });
353
+ if (completionResult.object.isComplete) {
354
+ return {
355
+ task: inputData.task,
356
+ resourceId: "",
357
+ resourceType: "none",
358
+ prompt: "",
359
+ result: completionResult.object.finalResult,
360
+ isComplete: true,
361
+ selectionReason: completionResult.object.completionReason,
362
+ iteration: inputData.iteration + 1
363
+ };
364
+ }
365
+ }
366
+ const result = await routingAgent.generate(
367
+ [
368
+ {
369
+ role: "assistant",
370
+ content: `
371
+ ${inputData.isOneOff ? "You are executing just one primitive based on the user task. Make sure to pick the primitive that is the best suited to accomplish the whole task. Primitives that execute only part of the task should be avoided." : "You will be calling just *one* primitive at a time to accomplish the user task, every call to you is one decision in the process of accomplishing the user task. Make sure to pick primitives that are the best suited to accomplish the whole task. Completeness is the highest priority."}
372
+
373
+ The user has given you the following task:
374
+ ${inputData.task}
375
+ ${completionResult ? `
376
+
377
+ ${completionResult.object.finalResult}` : ""}
378
+
379
+ Please select the most appropriate primitive to handle this task and the prompt to be sent to the primitive.
380
+ If you are calling the same agent again, make sure to adjust the prompt to be more specific.
381
+
382
+ {
383
+ "resourceId": string,
384
+ "resourceType": "agent" | "workflow" | "tool",
385
+ "prompt": string,
386
+ "selectionReason": string
387
+ }
388
+
389
+ The 'selectionReason' property should explain why you picked the primitive${inputData.verboseIntrospection ? ", as well as why the other primitives were not picked." : "."}
390
+ `
391
+ }
392
+ ],
393
+ {
394
+ output: z.object({
395
+ resourceId: z.string(),
396
+ resourceType: RESOURCE_TYPES,
397
+ prompt: z.string(),
398
+ selectionReason: z.string()
399
+ }),
400
+ threadId: initData?.threadId ?? runId,
401
+ resourceId: initData?.threadResourceId ?? this.name,
402
+ runtimeContext: runtimeContextToUse
403
+ }
404
+ );
405
+ return {
406
+ task: inputData.task,
407
+ result: "",
408
+ resourceId: result.object.resourceId,
409
+ resourceType: result.object.resourceType,
410
+ prompt: result.object.prompt,
411
+ isComplete: result.object.resourceId === "none" && result.object.resourceType === "none" ? true : false,
412
+ selectionReason: result.object.selectionReason,
413
+ iteration: inputData.iteration + 1
414
+ };
415
+ }
416
+ });
417
+ const agentStep = createStep({
418
+ id: "agent-step",
419
+ inputSchema: z.object({
420
+ task: z.string(),
421
+ resourceId: z.string(),
422
+ resourceType: RESOURCE_TYPES,
423
+ prompt: z.string(),
424
+ result: z.string(),
425
+ isComplete: z.boolean().optional(),
426
+ selectionReason: z.string(),
427
+ iteration: z.number()
428
+ }),
429
+ outputSchema: z.object({
430
+ task: z.string(),
431
+ resourceId: z.string(),
432
+ resourceType: RESOURCE_TYPES,
433
+ result: z.string(),
434
+ isComplete: z.boolean().optional(),
435
+ iteration: z.number()
436
+ }),
437
+ execute: async ({ inputData, [EMITTER_SYMBOL]: emitter, getInitData }) => {
438
+ const agentsMap = await this.getAgents({ runtimeContext: runtimeContextToUse });
439
+ const agentId = inputData.resourceId;
440
+ const agent = agentsMap[inputData.resourceId];
441
+ if (!agent) {
442
+ throw new Error(`Agent ${agentId} not found`);
443
+ }
444
+ let streamPromise = {};
445
+ streamPromise.promise = new Promise((resolve, reject) => {
446
+ streamPromise.resolve = resolve;
447
+ streamPromise.reject = reject;
448
+ });
449
+ const toolData = {
450
+ name: agent.name,
451
+ args: inputData
452
+ };
453
+ await emitter.emit("watch-v2", {
454
+ type: "tool-call-streaming-start",
455
+ ...toolData
456
+ });
457
+ const { fullStream } = await agent.stream(inputData.prompt, {
458
+ // resourceId: inputData.resourceId,
459
+ // threadId: inputData.threadId,
460
+ runtimeContext: runtimeContextToUse,
461
+ onFinish: (result) => {
462
+ streamPromise.resolve(result.text);
463
+ }
464
+ });
465
+ for await (const chunk of fullStream) {
466
+ switch (chunk.type) {
467
+ case "text-delta":
468
+ await emitter.emit("watch-v2", {
469
+ type: "tool-call-delta",
470
+ ...toolData,
471
+ argsTextDelta: chunk.textDelta
472
+ });
473
+ break;
474
+ case "step-start":
475
+ case "step-finish":
476
+ case "finish":
477
+ case "tool-call":
478
+ case "tool-result":
479
+ case "tool-call-streaming-start":
480
+ case "tool-call-delta":
481
+ break;
482
+ case "source":
483
+ case "file":
484
+ default:
485
+ await emitter.emit("watch-v2", chunk);
486
+ break;
487
+ }
488
+ }
489
+ const finalResult = await streamPromise.promise;
490
+ const memory = await this.getMemory({ runtimeContext: runtimeContext || new RuntimeContext() });
491
+ const initData = await getInitData();
492
+ await memory?.saveMessages({
493
+ messages: [
494
+ {
495
+ id: randomUUID(),
496
+ type: "text",
497
+ role: "assistant",
498
+ content: { parts: [{ type: "text", text: finalResult }], format: 2 },
499
+ createdAt: /* @__PURE__ */ new Date(),
500
+ threadId: initData.threadId || runId,
501
+ resourceId: initData.threadResourceId || this.name
502
+ }
503
+ ],
504
+ format: "v2"
505
+ });
506
+ return {
507
+ task: inputData.task,
508
+ resourceId: inputData.resourceId,
509
+ resourceType: inputData.resourceType,
510
+ result: finalResult,
511
+ isComplete: false,
512
+ iteration: inputData.iteration
513
+ };
514
+ }
515
+ });
516
+ const workflowStep = createStep({
517
+ id: "workflow-step",
518
+ inputSchema: z.object({
519
+ task: z.string(),
520
+ resourceId: z.string(),
521
+ resourceType: RESOURCE_TYPES,
522
+ prompt: z.string(),
523
+ result: z.string(),
524
+ isComplete: z.boolean().optional(),
525
+ selectionReason: z.string(),
526
+ iteration: z.number()
527
+ }),
528
+ outputSchema: z.object({
529
+ task: z.string(),
530
+ resourceId: z.string(),
531
+ resourceType: RESOURCE_TYPES,
532
+ result: z.string(),
533
+ isComplete: z.boolean().optional(),
534
+ iteration: z.number()
535
+ }),
536
+ execute: async ({ inputData, [EMITTER_SYMBOL]: emitter, getInitData }) => {
537
+ const workflowsMap = await this.getWorkflows({ runtimeContext: runtimeContextToUse });
538
+ const wf = workflowsMap[inputData.resourceId];
539
+ if (!wf) {
540
+ throw new Error(`Workflow ${inputData.resourceId} not found`);
541
+ }
542
+ let input;
543
+ try {
544
+ input = JSON.parse(inputData.prompt);
545
+ } catch (e) {
546
+ console.error(e);
547
+ throw new Error(`Invalid task input: ${inputData.task}`);
548
+ }
549
+ let streamPromise = {};
550
+ streamPromise.promise = new Promise((resolve, reject) => {
551
+ streamPromise.resolve = resolve;
552
+ streamPromise.reject = reject;
553
+ });
554
+ const toolData = {
555
+ name: wf.name,
556
+ args: inputData
557
+ };
558
+ await emitter.emit("watch-v2", {
559
+ type: "tool-call-streaming-start",
560
+ ...toolData
561
+ });
562
+ const run = wf.createRun();
563
+ const { stream, getWorkflowState } = run.stream({
564
+ inputData: input,
565
+ runtimeContext: runtimeContextToUse
566
+ });
567
+ let result;
568
+ for await (const chunk of stream) {
569
+ const c = chunk;
570
+ switch (c.type) {
571
+ case "text-delta":
572
+ await emitter.emit("watch-v2", {
573
+ type: "tool-call-delta",
574
+ ...toolData,
575
+ argsTextDelta: c.textDelta
576
+ });
577
+ break;
578
+ case "step-result":
579
+ if (c?.payload?.output) {
580
+ result = c?.payload?.output;
581
+ }
582
+ await emitter.emit("watch-v2", c);
583
+ break;
584
+ case "finish":
585
+ streamPromise.resolve(result);
586
+ break;
587
+ case "start":
588
+ case "finish":
589
+ case "step-start":
590
+ case "step-finish":
591
+ case "tool-call":
592
+ case "tool-result":
593
+ case "tool-call-streaming-start":
594
+ case "tool-call-delta":
595
+ case "source":
596
+ case "file":
597
+ default:
598
+ await emitter.emit("watch-v2", c);
599
+ break;
600
+ }
601
+ }
602
+ let runSuccess = true;
603
+ const runResult = await streamPromise.promise;
604
+ const workflowState = await getWorkflowState();
605
+ if (workflowState.status === "failed") {
606
+ runSuccess = false;
607
+ }
608
+ const finalResult = JSON.stringify({
609
+ runId: run.runId,
610
+ runResult,
611
+ runSuccess
612
+ });
613
+ const memory = await this.getMemory({ runtimeContext: runtimeContext || new RuntimeContext() });
614
+ const initData = await getInitData();
615
+ await memory?.saveMessages({
616
+ messages: [
617
+ {
618
+ id: randomUUID(),
619
+ type: "text",
620
+ role: "assistant",
621
+ content: { parts: [{ type: "text", text: finalResult }], format: 2 },
622
+ createdAt: /* @__PURE__ */ new Date(),
623
+ threadId: initData.threadId || runId,
624
+ resourceId: initData.threadResourceId || this.name
625
+ }
626
+ ],
627
+ format: "v2"
628
+ });
629
+ return {
630
+ result: finalResult || "",
631
+ task: inputData.task,
632
+ resourceId: inputData.resourceId,
633
+ resourceType: inputData.resourceType,
634
+ isComplete: false,
635
+ iteration: inputData.iteration
636
+ };
637
+ }
638
+ });
639
+ const toolStep = createStep({
640
+ id: "toolStep",
641
+ inputSchema: z.object({
642
+ task: z.string(),
643
+ resourceId: z.string(),
644
+ resourceType: RESOURCE_TYPES,
645
+ prompt: z.string(),
646
+ result: z.string(),
647
+ isComplete: z.boolean().optional(),
648
+ selectionReason: z.string(),
649
+ iteration: z.number()
650
+ }),
651
+ outputSchema: z.object({
652
+ task: z.string(),
653
+ resourceId: z.string(),
654
+ resourceType: RESOURCE_TYPES,
655
+ result: z.string(),
656
+ isComplete: z.boolean().optional(),
657
+ iteration: z.number()
658
+ }),
659
+ execute: async ({ inputData, getInitData }) => {
660
+ const toolsMap = await this.getTools({ runtimeContext: runtimeContextToUse });
661
+ const tool = toolsMap[inputData.resourceId];
662
+ if (!tool) {
663
+ throw new Error(`Tool ${inputData.resourceId} not found`);
664
+ }
665
+ if (!tool.execute) {
666
+ throw new Error(`Tool ${inputData.resourceId} does not have an execute function`);
667
+ }
668
+ let inputDataToUse;
669
+ try {
670
+ inputDataToUse = JSON.parse(inputData.prompt);
671
+ } catch (e) {
672
+ console.error(e);
673
+ throw new Error(`Invalid task input: ${inputData.task}`);
674
+ }
675
+ const finalResult = await tool.execute({
676
+ runtimeContext: runtimeContextToUse,
677
+ mastra: this.#mastra,
678
+ resourceId: inputData.resourceId,
679
+ threadId: runId,
680
+ runId,
681
+ context: inputDataToUse
682
+ });
683
+ const memory = await this.getMemory({ runtimeContext: runtimeContext || new RuntimeContext() });
684
+ const initData = await getInitData();
685
+ await memory?.saveMessages({
686
+ messages: [
687
+ {
688
+ id: randomUUID(),
689
+ type: "text",
690
+ role: "assistant",
691
+ content: { parts: [{ type: "text", text: JSON.stringify(finalResult) }], format: 2 },
692
+ createdAt: /* @__PURE__ */ new Date(),
693
+ threadId: initData.threadId || runId,
694
+ resourceId: initData.threadResourceId || this.name
695
+ }
696
+ ],
697
+ format: "v2"
698
+ });
699
+ return {
700
+ task: inputData.task,
701
+ resourceId: inputData.resourceId,
702
+ resourceType: inputData.resourceType,
703
+ result: finalResult,
704
+ isComplete: false,
705
+ iteration: inputData.iteration
706
+ };
707
+ }
708
+ });
709
+ const finishStep = createStep({
710
+ id: "finish-step",
711
+ inputSchema: z.object({
712
+ task: z.string(),
713
+ resourceId: z.string(),
714
+ resourceType: RESOURCE_TYPES,
715
+ prompt: z.string(),
716
+ result: z.string(),
717
+ isComplete: z.boolean().optional(),
718
+ selectionReason: z.string(),
719
+ iteration: z.number()
720
+ }),
721
+ outputSchema: z.object({
722
+ task: z.string(),
723
+ result: z.string(),
724
+ isComplete: z.boolean(),
725
+ iteration: z.number()
726
+ }),
727
+ execute: async ({ inputData }) => {
728
+ return {
729
+ task: inputData.task,
730
+ result: inputData.result,
731
+ isComplete: !!inputData.isComplete,
732
+ iteration: inputData.iteration
733
+ };
734
+ }
735
+ });
736
+ const networkWorkflow = createWorkflow({
737
+ id: "Agent-Network-Outer-Workflow",
738
+ inputSchema: z.object({
739
+ task: z.string(),
740
+ resourceId: z.string(),
741
+ resourceType: RESOURCE_TYPES,
742
+ result: z.string().optional(),
743
+ iteration: z.number(),
744
+ threadId: z.string().optional(),
745
+ threadResourceId: z.string().optional(),
746
+ isOneOff: z.boolean(),
747
+ verboseIntrospection: z.boolean()
748
+ }),
749
+ outputSchema: z.object({
750
+ task: z.string(),
751
+ resourceId: z.string(),
752
+ resourceType: RESOURCE_TYPES,
753
+ prompt: z.string(),
754
+ result: z.string(),
755
+ isComplete: z.boolean().optional(),
756
+ completionReason: z.string().optional(),
757
+ iteration: z.number(),
758
+ threadId: z.string().optional(),
759
+ threadResourceId: z.string().optional(),
760
+ isOneOff: z.boolean()
761
+ })
762
+ });
763
+ networkWorkflow.then(routingStep).branch([
764
+ [async ({ inputData }) => !inputData.isComplete && inputData.resourceType === "agent", agentStep],
765
+ [async ({ inputData }) => !inputData.isComplete && inputData.resourceType === "workflow", workflowStep],
766
+ [async ({ inputData }) => !inputData.isComplete && inputData.resourceType === "tool", toolStep],
767
+ [async ({ inputData }) => inputData.isComplete, finishStep]
768
+ ]).map({
769
+ task: {
770
+ step: [routingStep, agentStep, workflowStep, toolStep],
771
+ path: "task"
772
+ },
773
+ isComplete: {
774
+ step: [agentStep, workflowStep, toolStep, finishStep],
775
+ path: "isComplete"
776
+ },
777
+ completionReason: {
778
+ step: [routingStep, agentStep, workflowStep, toolStep, finishStep],
779
+ path: "completionReason"
780
+ },
781
+ result: {
782
+ step: [agentStep, workflowStep, toolStep, finishStep],
783
+ path: "result"
784
+ },
785
+ resourceId: {
786
+ step: [routingStep, agentStep, workflowStep, toolStep],
787
+ path: "resourceId"
788
+ },
789
+ resourceType: {
790
+ step: [routingStep, agentStep, workflowStep, toolStep],
791
+ path: "resourceType"
792
+ },
793
+ iteration: {
794
+ step: [routingStep, agentStep, workflowStep, toolStep],
795
+ path: "iteration"
796
+ },
797
+ isOneOff: {
798
+ initData: networkWorkflow,
799
+ path: "isOneOff"
800
+ },
801
+ threadId: {
802
+ initData: networkWorkflow,
803
+ path: "threadId"
804
+ },
805
+ threadResourceId: {
806
+ initData: networkWorkflow,
807
+ path: "threadResourceId"
808
+ }
809
+ }).commit();
810
+ return networkWorkflow;
811
+ }
812
+ async generate(message, {
813
+ runtimeContext,
814
+ threadId,
815
+ resourceId
816
+ }) {
817
+ const networkWorkflow = this.createWorkflow({ runtimeContext });
818
+ const run = networkWorkflow.createRun();
819
+ const thread = await this.beforeRun({
820
+ runtimeContext: runtimeContext || new RuntimeContext(),
821
+ threadId: threadId || run.runId,
822
+ resourceId: resourceId || this.name,
823
+ message
824
+ });
825
+ const result = await run.start({
826
+ inputData: {
827
+ task: message,
828
+ resourceId: "",
829
+ resourceType: "none",
830
+ iteration: 0,
831
+ threadId: thread?.id,
832
+ threadResourceId: thread?.resourceId,
833
+ isOneOff: true,
834
+ verboseIntrospection: true
835
+ }
836
+ });
837
+ if (result.status === "failed") {
838
+ throw result.error;
839
+ }
840
+ if (result.status === "suspended") {
841
+ throw new Error("Workflow suspended");
842
+ }
843
+ return {
844
+ task: result.result.task,
845
+ result: result.result.result,
846
+ resourceId: result.result.resourceId,
847
+ resourceType: result.result.resourceType
848
+ };
849
+ }
850
+ async stream(message, {
851
+ runtimeContext,
852
+ threadId,
853
+ resourceId
854
+ }) {
855
+ const networkWorkflow = this.createWorkflow({ runtimeContext });
856
+ const run = networkWorkflow.createRun();
857
+ const thread = await this.beforeRun({
858
+ runtimeContext: runtimeContext || new RuntimeContext(),
859
+ threadId: threadId || run.runId,
860
+ resourceId: resourceId || this.name,
861
+ message
862
+ });
863
+ return run.stream({
864
+ inputData: {
865
+ task: `You are executing just one primitive based on the following: ${message}`,
866
+ resourceId: "",
867
+ resourceType: "none",
868
+ iteration: 0,
869
+ threadResourceId: thread?.resourceId,
870
+ threadId: thread?.id,
871
+ isOneOff: true,
872
+ verboseIntrospection: true
873
+ }
874
+ });
875
+ }
876
+ };
877
+
878
+ export { NewAgentNetwork };