@mastra/core 0.19.1 → 0.20.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 (179) hide show
  1. package/CHANGELOG.md +100 -0
  2. package/dist/agent/agent.d.ts +17 -31
  3. package/dist/agent/agent.d.ts.map +1 -1
  4. package/dist/agent/agent.types.d.ts +2 -2
  5. package/dist/agent/agent.types.d.ts.map +1 -1
  6. package/dist/agent/index.cjs +11 -11
  7. package/dist/agent/index.js +2 -2
  8. package/dist/agent/input-processor/index.cjs +6 -6
  9. package/dist/agent/input-processor/index.js +1 -1
  10. package/dist/agent/types.d.ts +1 -6
  11. package/dist/agent/types.d.ts.map +1 -1
  12. package/dist/agent/workflows/prepare-stream/index.d.ts +3 -3
  13. package/dist/agent/workflows/prepare-stream/index.d.ts.map +1 -1
  14. package/dist/agent/workflows/prepare-stream/prepare-memory-step.d.ts +3 -3
  15. package/dist/agent/workflows/prepare-stream/prepare-memory-step.d.ts.map +1 -1
  16. package/dist/agent/workflows/prepare-stream/prepare-tools-step.d.ts +1 -1
  17. package/dist/agent/workflows/prepare-stream/prepare-tools-step.d.ts.map +1 -1
  18. package/dist/agent/workflows/prepare-stream/schema.d.ts +2 -2
  19. package/dist/ai-tracing/index.cjs +32 -32
  20. package/dist/ai-tracing/index.js +1 -1
  21. package/dist/{chunk-QFKTSGBI.js → chunk-2DVGQK2L.js} +4 -4
  22. package/dist/chunk-2DVGQK2L.js.map +1 -0
  23. package/dist/{chunk-HJQ7ANDX.cjs → chunk-2JUDZXVI.cjs} +4 -4
  24. package/dist/chunk-2JUDZXVI.cjs.map +1 -0
  25. package/dist/{chunk-SZD4WTRW.cjs → chunk-2SH5WPUA.cjs} +27 -22
  26. package/dist/chunk-2SH5WPUA.cjs.map +1 -0
  27. package/dist/{chunk-QMDJVXFQ.cjs → chunk-3NNB72OL.cjs} +15 -15
  28. package/dist/{chunk-QMDJVXFQ.cjs.map → chunk-3NNB72OL.cjs.map} +1 -1
  29. package/dist/{chunk-D2ZPF2AK.js → chunk-42VT5WOB.js} +3 -3
  30. package/dist/{chunk-D2ZPF2AK.js.map → chunk-42VT5WOB.js.map} +1 -1
  31. package/dist/{chunk-5QUE7HZF.js → chunk-6R46VE63.js} +5 -5
  32. package/dist/{chunk-5QUE7HZF.js.map → chunk-6R46VE63.js.map} +1 -1
  33. package/dist/{chunk-K3UPABLX.cjs → chunk-7EUC32F3.cjs} +16 -34
  34. package/dist/chunk-7EUC32F3.cjs.map +1 -0
  35. package/dist/{chunk-62I4SVWU.cjs → chunk-7HUKQ6SZ.cjs} +4 -4
  36. package/dist/{chunk-62I4SVWU.cjs.map → chunk-7HUKQ6SZ.cjs.map} +1 -1
  37. package/dist/{chunk-NLBX7Q47.cjs → chunk-7QC3MHP7.cjs} +4 -4
  38. package/dist/{chunk-NLBX7Q47.cjs.map → chunk-7QC3MHP7.cjs.map} +1 -1
  39. package/dist/{chunk-X6PLOE2T.js → chunk-AND6J5LG.js} +27 -22
  40. package/dist/chunk-AND6J5LG.js.map +1 -0
  41. package/dist/{chunk-TJHEGJNW.js → chunk-BOJNXNRV.js} +3 -3
  42. package/dist/{chunk-TJHEGJNW.js.map → chunk-BOJNXNRV.js.map} +1 -1
  43. package/dist/{chunk-NVMKTP4N.js → chunk-CJDOU6WP.js} +3 -3
  44. package/dist/chunk-CJDOU6WP.js.map +1 -0
  45. package/dist/{chunk-7CJKBCDL.js → chunk-COYTVUIL.js} +6 -24
  46. package/dist/chunk-COYTVUIL.js.map +1 -0
  47. package/dist/{chunk-2EMOWXLL.js → chunk-DQISKQDE.js} +86 -77
  48. package/dist/chunk-DQISKQDE.js.map +1 -0
  49. package/dist/{chunk-BBTR6DPH.cjs → chunk-DVHBWEYY.cjs} +3 -3
  50. package/dist/chunk-DVHBWEYY.cjs.map +1 -0
  51. package/dist/{chunk-T2CUZA2P.js → chunk-EF6Y74CN.js} +3 -3
  52. package/dist/{chunk-T2CUZA2P.js.map → chunk-EF6Y74CN.js.map} +1 -1
  53. package/dist/{chunk-57UPIDGK.cjs → chunk-I6TOPBP6.cjs} +14 -14
  54. package/dist/{chunk-57UPIDGK.cjs.map → chunk-I6TOPBP6.cjs.map} +1 -1
  55. package/dist/{chunk-M24QFL6S.js → chunk-KGBDRSMX.js} +8 -4
  56. package/dist/chunk-KGBDRSMX.js.map +1 -0
  57. package/dist/{chunk-CC4KO56Z.cjs → chunk-LCJP7LWN.cjs} +6 -6
  58. package/dist/{chunk-CC4KO56Z.cjs.map → chunk-LCJP7LWN.cjs.map} +1 -1
  59. package/dist/{chunk-2F4RLQ5V.cjs → chunk-NEWEONKX.cjs} +4 -4
  60. package/dist/{chunk-2F4RLQ5V.cjs.map → chunk-NEWEONKX.cjs.map} +1 -1
  61. package/dist/{chunk-3I3NRXSD.cjs → chunk-OKIHIKXV.cjs} +6 -6
  62. package/dist/{chunk-3I3NRXSD.cjs.map → chunk-OKIHIKXV.cjs.map} +1 -1
  63. package/dist/{chunk-M635OK6I.js → chunk-OXLN4CWA.js} +3 -3
  64. package/dist/{chunk-M635OK6I.js.map → chunk-OXLN4CWA.js.map} +1 -1
  65. package/dist/{chunk-LYRPXSHB.js → chunk-QR5VZWWT.js} +11 -11
  66. package/dist/{chunk-LYRPXSHB.js.map → chunk-QR5VZWWT.js.map} +1 -1
  67. package/dist/{chunk-WMGV4CS3.cjs → chunk-T4H33PBR.cjs} +115 -106
  68. package/dist/chunk-T4H33PBR.cjs.map +1 -0
  69. package/dist/{chunk-A7REAXWA.js → chunk-WP2KQXPV.js} +3 -3
  70. package/dist/{chunk-A7REAXWA.js.map → chunk-WP2KQXPV.js.map} +1 -1
  71. package/dist/{chunk-HV5ND4KF.cjs → chunk-YEEAHLAK.cjs} +4 -4
  72. package/dist/{chunk-HV5ND4KF.cjs.map → chunk-YEEAHLAK.cjs.map} +1 -1
  73. package/dist/{chunk-BMBWTBCL.js → chunk-ZJ2UFCTS.js} +5 -5
  74. package/dist/{chunk-BMBWTBCL.js.map → chunk-ZJ2UFCTS.js.map} +1 -1
  75. package/dist/{chunk-2C5AQMP5.cjs → chunk-ZNK5RN5D.cjs} +10 -6
  76. package/dist/chunk-ZNK5RN5D.cjs.map +1 -0
  77. package/dist/index.cjs +54 -54
  78. package/dist/index.js +10 -10
  79. package/dist/llm/index.cjs +5 -5
  80. package/dist/llm/index.js +1 -1
  81. package/dist/llm/model/gateways/netlify.d.ts.map +1 -1
  82. package/dist/llm/model/provider-registry.generated.d.ts +4 -4
  83. package/dist/llm/model/provider-registry.generated.d.ts.map +1 -1
  84. package/dist/loop/index.cjs +2 -2
  85. package/dist/loop/index.js +1 -1
  86. package/dist/loop/loop.d.ts.map +1 -1
  87. package/dist/loop/test-utils/streamObject.d.ts.map +1 -1
  88. package/dist/loop/types.d.ts +7 -6
  89. package/dist/loop/types.d.ts.map +1 -1
  90. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts +1 -1
  91. package/dist/loop/workflows/agentic-execution/llm-execution-step.d.ts.map +1 -1
  92. package/dist/loop/workflows/agentic-loop/index.d.ts +2 -2
  93. package/dist/loop/workflows/agentic-loop/index.d.ts.map +1 -1
  94. package/dist/loop/workflows/schema.d.ts +5 -3
  95. package/dist/loop/workflows/schema.d.ts.map +1 -1
  96. package/dist/loop/workflows/stream.d.ts +1 -1
  97. package/dist/loop/workflows/stream.d.ts.map +1 -1
  98. package/dist/mastra/index.cjs +2 -2
  99. package/dist/mastra/index.d.ts +3 -7
  100. package/dist/mastra/index.d.ts.map +1 -1
  101. package/dist/mastra/index.js +1 -1
  102. package/dist/memory/index.cjs +4 -4
  103. package/dist/memory/index.js +1 -1
  104. package/dist/memory/memory.d.ts +7 -2
  105. package/dist/memory/memory.d.ts.map +1 -1
  106. package/dist/memory/types.d.ts +256 -8
  107. package/dist/memory/types.d.ts.map +1 -1
  108. package/dist/processors/index.cjs +14 -10
  109. package/dist/processors/index.d.ts +1 -0
  110. package/dist/processors/index.d.ts.map +1 -1
  111. package/dist/processors/index.js +1 -1
  112. package/dist/processors/processors/structured-output.d.ts +15 -7
  113. package/dist/processors/processors/structured-output.d.ts.map +1 -1
  114. package/dist/processors/runner.d.ts +0 -1
  115. package/dist/processors/runner.d.ts.map +1 -1
  116. package/dist/relevance/index.cjs +4 -4
  117. package/dist/relevance/index.js +1 -1
  118. package/dist/scores/index.cjs +9 -9
  119. package/dist/scores/index.js +2 -2
  120. package/dist/scores/scoreTraces/index.cjs +8 -8
  121. package/dist/scores/scoreTraces/index.js +3 -3
  122. package/dist/server/index.cjs +2 -2
  123. package/dist/server/index.js +1 -1
  124. package/dist/storage/index.cjs +3 -3
  125. package/dist/storage/index.js +1 -1
  126. package/dist/stream/aisdk/v5/compat/ui-message.d.ts.map +1 -1
  127. package/dist/stream/aisdk/v5/output.d.ts +6 -6
  128. package/dist/stream/aisdk/v5/output.d.ts.map +1 -1
  129. package/dist/stream/aisdk/v5/transform.d.ts +5 -4
  130. package/dist/stream/aisdk/v5/transform.d.ts.map +1 -1
  131. package/dist/stream/base/output-format-handlers.d.ts +3 -7
  132. package/dist/stream/base/output-format-handlers.d.ts.map +1 -1
  133. package/dist/stream/base/output.d.ts +12 -6
  134. package/dist/stream/base/output.d.ts.map +1 -1
  135. package/dist/stream/index.cjs +4 -4
  136. package/dist/stream/index.js +1 -1
  137. package/dist/stream/types.d.ts +16 -5
  138. package/dist/stream/types.d.ts.map +1 -1
  139. package/dist/telemetry/index.cjs +7 -7
  140. package/dist/telemetry/index.js +1 -1
  141. package/dist/test-utils/llm-mock.cjs +2 -2
  142. package/dist/test-utils/llm-mock.js +1 -1
  143. package/dist/tts/index.cjs +2 -2
  144. package/dist/tts/index.js +1 -1
  145. package/dist/utils.cjs +17 -17
  146. package/dist/utils.d.ts +1 -1
  147. package/dist/utils.d.ts.map +1 -1
  148. package/dist/utils.js +1 -1
  149. package/dist/voice/index.cjs +4 -4
  150. package/dist/voice/index.js +1 -1
  151. package/dist/workflows/evented/index.cjs +10 -10
  152. package/dist/workflows/evented/index.js +1 -1
  153. package/dist/workflows/evented/workflow.d.ts.map +1 -1
  154. package/dist/workflows/index.cjs +12 -12
  155. package/dist/workflows/index.js +1 -1
  156. package/dist/workflows/legacy/index.cjs +22 -22
  157. package/dist/workflows/legacy/index.js +1 -1
  158. package/dist/workflows/workflow.d.ts +8 -8
  159. package/dist/workflows/workflow.d.ts.map +1 -1
  160. package/package.json +3 -3
  161. package/dist/chunk-2C5AQMP5.cjs.map +0 -1
  162. package/dist/chunk-2EMOWXLL.js.map +0 -1
  163. package/dist/chunk-7CJKBCDL.js.map +0 -1
  164. package/dist/chunk-BBTR6DPH.cjs.map +0 -1
  165. package/dist/chunk-HJQ7ANDX.cjs.map +0 -1
  166. package/dist/chunk-K3UPABLX.cjs.map +0 -1
  167. package/dist/chunk-M24QFL6S.js.map +0 -1
  168. package/dist/chunk-NVMKTP4N.js.map +0 -1
  169. package/dist/chunk-QFKTSGBI.js.map +0 -1
  170. package/dist/chunk-SZD4WTRW.cjs.map +0 -1
  171. package/dist/chunk-WMGV4CS3.cjs.map +0 -1
  172. package/dist/chunk-X6PLOE2T.js.map +0 -1
  173. package/dist/network/vNext/index.cjs +0 -990
  174. package/dist/network/vNext/index.cjs.map +0 -1
  175. package/dist/network/vNext/index.d.ts +0 -331
  176. package/dist/network/vNext/index.d.ts.map +0 -1
  177. package/dist/network/vNext/index.js +0 -988
  178. package/dist/network/vNext/index.js.map +0 -1
  179. package/network/vNext.d.ts +0 -1
@@ -1,988 +0,0 @@
1
- import { Agent, createStep, createWorkflow, PRIMITIVE_TYPES } from '../../chunk-2EMOWXLL.js';
2
- import { EMITTER_SYMBOL } from '../../chunk-NLNKQD2T.js';
3
- import { MessageList } from '../../chunk-TJHEGJNW.js';
4
- import { RuntimeContext } from '../../chunk-HLRWYUFN.js';
5
- import { MastraBase } from '../../chunk-BMVFEBPE.js';
6
- import { RegisteredLogger } from '../../chunk-BN2M4UK5.js';
7
- import { randomUUID } from 'crypto';
8
- import { zodToJsonSchema } from '@mastra/schema-compat/zod-to-json';
9
- import { z } from 'zod';
10
-
11
- var NewAgentNetwork = class extends MastraBase {
12
- id;
13
- name;
14
- #instructions;
15
- #model;
16
- #agents;
17
- #defaultAgent;
18
- #workflows;
19
- #tools;
20
- #memory;
21
- #mastra;
22
- constructor({
23
- id,
24
- name,
25
- instructions,
26
- model,
27
- agents,
28
- workflows,
29
- memory,
30
- tools,
31
- defaultAgent
32
- }) {
33
- super({
34
- component: RegisteredLogger.NETWORK,
35
- name: name || "NewAgentNetwork"
36
- });
37
- console.warn(
38
- `\u26A0\uFE0F DEPRECATION WARNING: AgentNetwork vNext will be deprecated the week of September 30th, 2025 and will be removed in a future version. Please use agent.network() instead.`
39
- );
40
- this.id = id;
41
- this.name = name;
42
- this.#instructions = instructions;
43
- this.#model = model;
44
- this.#agents = agents;
45
- this.#workflows = workflows;
46
- this.#memory = memory;
47
- this.#tools = tools;
48
- this.#defaultAgent = defaultAgent;
49
- }
50
- __registerMastra(mastra) {
51
- this.#mastra = mastra;
52
- }
53
- getLastMessage(messages) {
54
- let message = "";
55
- if (typeof messages === "string") {
56
- message = messages;
57
- } else {
58
- const lastMessage = Array.isArray(messages) ? messages[messages.length - 1] : messages;
59
- if (typeof lastMessage === "string") {
60
- message = lastMessage;
61
- } else if (lastMessage && `content` in lastMessage && lastMessage?.content) {
62
- const lastMessageContent = lastMessage.content;
63
- if (typeof lastMessageContent === "string") {
64
- message = lastMessageContent;
65
- } else if (Array.isArray(lastMessageContent)) {
66
- const lastPart = lastMessageContent[lastMessageContent.length - 1];
67
- if (lastPart?.type === "text") {
68
- message = lastPart.text;
69
- }
70
- }
71
- }
72
- }
73
- return message;
74
- }
75
- async beforeRun({
76
- runtimeContext,
77
- threadId,
78
- resourceId,
79
- messages
80
- }) {
81
- const memory = await this.getMemory({ runtimeContext });
82
- let thread = await memory?.getThreadById({ threadId });
83
- if (!thread) {
84
- thread = await memory?.createThread({
85
- threadId,
86
- title: "",
87
- resourceId
88
- });
89
- }
90
- if (typeof messages === "string") {
91
- await memory?.saveMessages({
92
- messages: [
93
- {
94
- id: this.#mastra?.generateId() || randomUUID(),
95
- type: "text",
96
- role: "user",
97
- content: { parts: [{ type: "text", text: messages }], format: 2 },
98
- createdAt: /* @__PURE__ */ new Date(),
99
- threadId: thread?.id,
100
- resourceId: thread?.resourceId
101
- }
102
- ],
103
- format: "v2"
104
- });
105
- } else {
106
- const messageList = new MessageList({
107
- threadId: thread?.id,
108
- resourceId: thread?.resourceId
109
- });
110
- messageList.add(messages, "user");
111
- const messagesToSave = messageList.get.all.v2();
112
- await memory?.saveMessages({
113
- messages: messagesToSave,
114
- format: "v2"
115
- });
116
- }
117
- return thread;
118
- }
119
- async getAgents({ runtimeContext }) {
120
- let agentsToUse;
121
- if (typeof this.#agents === "function") {
122
- agentsToUse = await this.#agents({ runtimeContext: runtimeContext || new RuntimeContext() });
123
- } else {
124
- agentsToUse = this.#agents;
125
- }
126
- return agentsToUse;
127
- }
128
- async getWorkflows({ runtimeContext }) {
129
- let workflowsToUse;
130
- if (typeof this.#workflows === "function") {
131
- workflowsToUse = await this.#workflows({ runtimeContext: runtimeContext || new RuntimeContext() });
132
- } else {
133
- workflowsToUse = this.#workflows || {};
134
- }
135
- return workflowsToUse;
136
- }
137
- async getTools({ runtimeContext }) {
138
- let toolsToUse;
139
- if (typeof this.#tools === "function") {
140
- toolsToUse = await this.#tools({ runtimeContext: runtimeContext || new RuntimeContext() });
141
- } else {
142
- toolsToUse = this.#tools || {};
143
- }
144
- return toolsToUse;
145
- }
146
- async getMemory({ runtimeContext }) {
147
- let memoryToUse;
148
- if (!this.#memory) {
149
- return;
150
- }
151
- if (typeof this.#memory === "function") {
152
- memoryToUse = await this.#memory({ runtimeContext: runtimeContext || new RuntimeContext() });
153
- } else {
154
- memoryToUse = this.#memory;
155
- }
156
- return memoryToUse;
157
- }
158
- async getInstructions({ runtimeContext }) {
159
- let instructionsToUse = this.#instructions;
160
- if (typeof instructionsToUse === "function") {
161
- instructionsToUse = await instructionsToUse({ runtimeContext: runtimeContext || new RuntimeContext() });
162
- }
163
- return instructionsToUse;
164
- }
165
- async getRoutingAgent({ runtimeContext }) {
166
- const instructionsToUse = await this.getInstructions({ runtimeContext: runtimeContext || new RuntimeContext() });
167
- const memoryToUse = await this.getMemory({ runtimeContext: runtimeContext || new RuntimeContext() });
168
- const agentsToUse = await this.getAgents({ runtimeContext: runtimeContext || new RuntimeContext() });
169
- const workflowsToUse = await this.getWorkflows({ runtimeContext: runtimeContext || new RuntimeContext() });
170
- const toolsToUse = await this.getTools({ runtimeContext: runtimeContext || new RuntimeContext() });
171
- const agentList = Object.entries(agentsToUse).map(([name, agent]) => {
172
- return ` - **${name}**: ${agent.getDescription()}`;
173
- }).join("\n");
174
- const workflowList = Object.entries(workflowsToUse).map(([name, workflow]) => {
175
- return ` - **${name}**: ${workflow.description}, input schema: ${JSON.stringify(
176
- zodToJsonSchema(workflow.inputSchema)
177
- )}`;
178
- }).join("\n");
179
- const toolList = Object.entries(toolsToUse).map(([name, tool]) => {
180
- return ` - **${name}**: ${tool.description}, input schema: ${JSON.stringify(
181
- zodToJsonSchema(tool.inputSchema || z.object({}))
182
- )}`;
183
- }).join("\n");
184
- const instructions = `
185
- You are a router in a network of specialized AI agents.
186
- Your job is to decide which agent should handle each step of a task.
187
-
188
- If asking for completion of a task, make sure to follow system instructions closely.
189
-
190
- ## System Instructions
191
- ${instructionsToUse}
192
-
193
- 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.
194
-
195
- ## Available Agents in Network
196
- ${agentList}
197
-
198
- ## Available Workflows in Network (make sure to use inputs corresponding to the input schema when calling a workflow)
199
- ${workflowList}
200
-
201
- ## Available Tools in Network (make sure to use inputs corresponding to the input schema when calling a tool)
202
- ${toolList}
203
-
204
- ${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.` : ""}
205
-
206
- If you have multiple entries that need to be called with a workflow or agent, call them separately with each input.
207
- 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.
208
- 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.
209
- When calling an agent, the prompt should be a text value, like you would call an LLM in a chat interface.
210
-
211
- 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.
212
- `;
213
- return new Agent({
214
- name: "routing-agent",
215
- instructions,
216
- model: this.#model,
217
- memory: memoryToUse,
218
- // @ts-ignore
219
- _agentNetworkAppend: true
220
- });
221
- }
222
- async loop(messages, {
223
- runtimeContext,
224
- maxIterations,
225
- threadId,
226
- resourceId
227
- }) {
228
- const networkWorkflow = this.createWorkflow({ runtimeContext });
229
- const finalStep = createStep({
230
- id: "final-step",
231
- inputSchema: networkWorkflow.outputSchema,
232
- outputSchema: networkWorkflow.outputSchema,
233
- execute: async ({ inputData }) => {
234
- if (maxIterations && inputData.iteration >= maxIterations) {
235
- return {
236
- ...inputData,
237
- completionReason: `Max iterations reached: ${maxIterations}`
238
- };
239
- }
240
- return inputData;
241
- }
242
- });
243
- const mainWorkflow = createWorkflow({
244
- id: "Agent-Network-Main-Workflow",
245
- inputSchema: z.object({
246
- iteration: z.number(),
247
- task: z.string(),
248
- resourceType: PRIMITIVE_TYPES,
249
- threadId: z.string().optional(),
250
- threadResourceId: z.string().optional()
251
- }),
252
- outputSchema: networkWorkflow.outputSchema
253
- }).dountil(networkWorkflow, async ({ inputData }) => {
254
- return inputData.isComplete || maxIterations && inputData.iteration >= maxIterations;
255
- }).then(finalStep).commit();
256
- const run = await mainWorkflow.createRunAsync();
257
- const thread = await this.beforeRun({
258
- runtimeContext: runtimeContext || new RuntimeContext(),
259
- threadId: threadId || run.runId,
260
- resourceId: resourceId || this.name,
261
- messages
262
- });
263
- const message = this.getLastMessage(messages);
264
- const result = await run.start({
265
- inputData: {
266
- task: message,
267
- resourceType: "none",
268
- iteration: 0,
269
- threadResourceId: thread?.resourceId,
270
- threadId: thread?.id
271
- }
272
- });
273
- if (result.status === "failed") {
274
- throw result.error;
275
- }
276
- if (result.status === "suspended") {
277
- throw new Error("Workflow suspended");
278
- }
279
- return result;
280
- }
281
- async loopStream(messages, {
282
- runtimeContext,
283
- maxIterations,
284
- threadId,
285
- resourceId
286
- }) {
287
- const networkWorkflow = this.createWorkflow({ runtimeContext });
288
- const finalStep = createStep({
289
- id: "final-step",
290
- inputSchema: networkWorkflow.outputSchema,
291
- outputSchema: networkWorkflow.outputSchema,
292
- execute: async ({ inputData }) => {
293
- if (maxIterations && inputData.iteration >= maxIterations) {
294
- return {
295
- ...inputData,
296
- completionReason: `Max iterations reached: ${maxIterations}`
297
- };
298
- }
299
- return inputData;
300
- }
301
- });
302
- const mainWorkflow = createWorkflow({
303
- id: "Agent-Network-Main-Workflow",
304
- inputSchema: z.object({
305
- iteration: z.number(),
306
- task: z.string(),
307
- resourceId: z.string(),
308
- resourceType: PRIMITIVE_TYPES,
309
- result: z.string().optional(),
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: PRIMITIVE_TYPES,
319
- prompt: z.string(),
320
- result: z.string(),
321
- isComplete: z.boolean().optional(),
322
- completionReason: z.string().optional(),
323
- iteration: z.number()
324
- })
325
- }).dountil(networkWorkflow, async ({ inputData }) => {
326
- return inputData.isComplete || maxIterations && inputData.iteration >= maxIterations;
327
- }).then(finalStep).commit();
328
- const run = await mainWorkflow.createRunAsync();
329
- const thread = await this.beforeRun({
330
- runtimeContext: runtimeContext || new RuntimeContext(),
331
- threadId: threadId || run.runId,
332
- resourceId: resourceId || this.name,
333
- messages
334
- });
335
- const message = this.getLastMessage(messages);
336
- return run.stream({
337
- inputData: {
338
- task: message,
339
- resourceId: "",
340
- resourceType: "none",
341
- iteration: 0,
342
- threadResourceId: thread?.resourceId,
343
- threadId: thread?.id,
344
- isOneOff: false,
345
- verboseIntrospection: true
346
- }
347
- });
348
- }
349
- createWorkflow({ runtimeContext }) {
350
- const runId = this.#mastra?.generateId() || randomUUID();
351
- const runtimeContextToUse = runtimeContext || new RuntimeContext();
352
- const routingStep = createStep({
353
- id: "routing-step",
354
- inputSchema: z.object({
355
- task: z.string(),
356
- resourceId: z.string(),
357
- resourceType: PRIMITIVE_TYPES,
358
- result: z.string().optional(),
359
- iteration: z.number(),
360
- threadId: z.string().optional(),
361
- threadResourceId: z.string().optional(),
362
- isOneOff: z.boolean(),
363
- verboseIntrospection: z.boolean()
364
- }),
365
- outputSchema: z.object({
366
- task: z.string(),
367
- resourceId: z.string(),
368
- resourceType: PRIMITIVE_TYPES,
369
- prompt: z.string(),
370
- result: z.string(),
371
- isComplete: z.boolean().optional(),
372
- selectionReason: z.string(),
373
- iteration: z.number()
374
- }),
375
- execute: async ({ inputData, getInitData }) => {
376
- const initData = await getInitData();
377
- const routingAgent = await this.getRoutingAgent({ runtimeContext: runtimeContextToUse });
378
- const model = await routingAgent.getModel();
379
- const completionSchema = z.object({
380
- isComplete: z.boolean(),
381
- finalResult: z.string(),
382
- completionReason: z.string()
383
- });
384
- let completionResult;
385
- if (inputData.resourceType !== "none" && inputData?.result) {
386
- const completionPrompt = `
387
- The ${inputData.resourceType} ${inputData.resourceId} has contributed to the task.
388
- This is the result from the agent: ${inputData.result}
389
-
390
- 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.
391
- Original task: ${inputData.task}
392
-
393
- {
394
- "isComplete": boolean,
395
- "completionReason": string,
396
- "finalResult": string
397
- }
398
- `;
399
- if (model.specificationVersion === "v2") {
400
- completionResult = await routingAgent.generateVNext([{ role: "assistant", content: completionPrompt }], {
401
- output: completionSchema,
402
- threadId: initData?.threadId ?? runId,
403
- resourceId: initData?.threadResourceId ?? this.name,
404
- runtimeContext: runtimeContextToUse
405
- });
406
- } else {
407
- completionResult = await routingAgent.generate([{ role: "assistant", content: completionPrompt }], {
408
- output: completionSchema,
409
- threadId: initData?.threadId ?? runId,
410
- resourceId: initData?.threadResourceId ?? this.name,
411
- runtimeContext: runtimeContextToUse
412
- });
413
- }
414
- if (completionResult.object.isComplete) {
415
- return {
416
- task: inputData.task,
417
- resourceId: "",
418
- resourceType: "none",
419
- prompt: "",
420
- result: completionResult.object.finalResult,
421
- isComplete: true,
422
- selectionReason: completionResult.object.completionReason,
423
- iteration: inputData.iteration + 1
424
- };
425
- }
426
- }
427
- let result;
428
- const prompt = [
429
- {
430
- role: "assistant",
431
- content: `
432
- ${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."}
433
-
434
- The user has given you the following task:
435
- ${inputData.task}
436
- ${completionResult ? `
437
-
438
- ${completionResult.object.finalResult}` : ""}
439
-
440
- Please select the most appropriate primitive to handle this task and the prompt to be sent to the primitive.
441
- If you are calling the same agent again, make sure to adjust the prompt to be more specific.
442
-
443
- {
444
- "resourceId": string,
445
- "resourceType": "agent" | "workflow" | "tool",
446
- "prompt": string,
447
- "selectionReason": string
448
- }
449
-
450
- The 'selectionReason' property should explain why you picked the primitive${inputData.verboseIntrospection ? ", as well as why the other primitives were not picked." : "."}
451
- `
452
- }
453
- ];
454
- const options = {
455
- output: z.object({
456
- resourceId: z.string(),
457
- resourceType: PRIMITIVE_TYPES,
458
- prompt: z.string(),
459
- selectionReason: z.string()
460
- }),
461
- threadId: initData?.threadId ?? runId,
462
- resourceId: initData?.threadResourceId ?? this.name,
463
- runtimeContext: runtimeContextToUse
464
- };
465
- if (model.specificationVersion === "v2") {
466
- result = await routingAgent.generateVNext(prompt, options);
467
- } else {
468
- result = await routingAgent.generate(prompt, options);
469
- }
470
- return {
471
- task: inputData.task,
472
- result: "",
473
- resourceId: result.object.resourceId,
474
- resourceType: result.object.resourceType,
475
- prompt: result.object.prompt,
476
- isComplete: result.object.resourceId === "none" && result.object.resourceType === "none" ? true : false,
477
- selectionReason: result.object.selectionReason,
478
- iteration: inputData.iteration + 1
479
- };
480
- }
481
- });
482
- const agentStep = createStep({
483
- id: "agent-step",
484
- inputSchema: z.object({
485
- task: z.string(),
486
- resourceId: z.string(),
487
- resourceType: PRIMITIVE_TYPES,
488
- prompt: z.string(),
489
- result: z.string(),
490
- isComplete: z.boolean().optional(),
491
- selectionReason: z.string(),
492
- iteration: z.number()
493
- }),
494
- outputSchema: z.object({
495
- task: z.string(),
496
- resourceId: z.string(),
497
- resourceType: PRIMITIVE_TYPES,
498
- result: z.string(),
499
- isComplete: z.boolean().optional(),
500
- iteration: z.number()
501
- }),
502
- execute: async ({ inputData, [EMITTER_SYMBOL]: emitter, getInitData }) => {
503
- const agentsMap = await this.getAgents({ runtimeContext: runtimeContextToUse });
504
- const agentId = inputData.resourceId;
505
- const agent = agentsMap[inputData.resourceId];
506
- if (!agent) {
507
- throw new Error(`Agent ${agentId} not found`);
508
- }
509
- let streamPromise = {};
510
- streamPromise.promise = new Promise((resolve, reject) => {
511
- streamPromise.resolve = resolve;
512
- streamPromise.reject = reject;
513
- });
514
- const toolData = {
515
- name: agent.name,
516
- args: inputData
517
- };
518
- await emitter.emit("watch-v2", {
519
- type: "tool-call-streaming-start",
520
- ...toolData
521
- });
522
- const model = await agent.getModel();
523
- let result;
524
- if (model.specificationVersion === "v2") {
525
- result = await agent.streamVNext(inputData.prompt, {
526
- // resourceId: inputData.resourceId,
527
- // threadId: inputData.threadId,
528
- runtimeContext: runtimeContextToUse,
529
- onFinish: (result2) => {
530
- streamPromise.resolve(result2.text);
531
- }
532
- });
533
- for await (const chunk of result.fullStream) {
534
- switch (chunk.type) {
535
- case "text-delta":
536
- await emitter.emit("watch-v2", {
537
- type: "tool-call-delta",
538
- ...toolData,
539
- argsTextDelta: chunk.payload.text
540
- });
541
- break;
542
- case "step-start":
543
- case "step-finish":
544
- case "finish":
545
- case "tool-call":
546
- case "tool-result":
547
- case "tool-call-input-streaming-start":
548
- case "tool-call-delta":
549
- break;
550
- case "source":
551
- case "file":
552
- default:
553
- await emitter.emit("watch-v2", chunk);
554
- break;
555
- }
556
- }
557
- } else {
558
- result = await agent.stream(inputData.prompt, {
559
- // resourceId: inputData.resourceId,
560
- // threadId: inputData.threadId,
561
- runtimeContext: runtimeContextToUse,
562
- onFinish: (result2) => {
563
- streamPromise.resolve(result2.text);
564
- }
565
- });
566
- for await (const chunk of result.fullStream) {
567
- switch (chunk.type) {
568
- case "text-delta":
569
- await emitter.emit("watch-v2", {
570
- type: "tool-call-delta",
571
- ...toolData,
572
- argsTextDelta: chunk.textDelta
573
- });
574
- break;
575
- case "step-start":
576
- case "step-finish":
577
- case "finish":
578
- case "tool-call":
579
- case "tool-result":
580
- case "tool-call-streaming-start":
581
- case "tool-call-delta":
582
- break;
583
- case "source":
584
- case "file":
585
- default:
586
- await emitter.emit("watch-v2", chunk);
587
- break;
588
- }
589
- }
590
- }
591
- const finalResult = await streamPromise.promise;
592
- const memory = await this.getMemory({ runtimeContext: runtimeContext || new RuntimeContext() });
593
- const initData = await getInitData();
594
- await memory?.saveMessages({
595
- messages: [
596
- {
597
- id: this.#mastra?.generateId() || randomUUID(),
598
- type: "text",
599
- role: "assistant",
600
- content: { parts: [{ type: "text", text: finalResult }], format: 2 },
601
- createdAt: /* @__PURE__ */ new Date(),
602
- threadId: initData.threadId || runId,
603
- resourceId: initData.threadResourceId || this.name
604
- }
605
- ],
606
- format: "v2"
607
- });
608
- return {
609
- task: inputData.task,
610
- resourceId: inputData.resourceId,
611
- resourceType: inputData.resourceType,
612
- result: finalResult,
613
- isComplete: false,
614
- iteration: inputData.iteration
615
- };
616
- }
617
- });
618
- const workflowStep = createStep({
619
- id: "workflow-step",
620
- inputSchema: z.object({
621
- task: z.string(),
622
- resourceId: z.string(),
623
- resourceType: PRIMITIVE_TYPES,
624
- prompt: z.string(),
625
- result: z.string(),
626
- isComplete: z.boolean().optional(),
627
- selectionReason: z.string(),
628
- iteration: z.number()
629
- }),
630
- outputSchema: z.object({
631
- task: z.string(),
632
- resourceId: z.string(),
633
- resourceType: PRIMITIVE_TYPES,
634
- result: z.string(),
635
- isComplete: z.boolean().optional(),
636
- iteration: z.number()
637
- }),
638
- execute: async ({ inputData, [EMITTER_SYMBOL]: emitter, getInitData }) => {
639
- const workflowsMap = await this.getWorkflows({ runtimeContext: runtimeContextToUse });
640
- const wf = workflowsMap[inputData.resourceId];
641
- if (!wf) {
642
- throw new Error(`Workflow ${inputData.resourceId} not found`);
643
- }
644
- let input;
645
- try {
646
- input = JSON.parse(inputData.prompt);
647
- } catch (e) {
648
- console.error(e);
649
- throw new Error(`Invalid task input: ${inputData.task}`);
650
- }
651
- let streamPromise = {};
652
- streamPromise.promise = new Promise((resolve, reject) => {
653
- streamPromise.resolve = resolve;
654
- streamPromise.reject = reject;
655
- });
656
- const toolData = {
657
- name: wf.name,
658
- args: inputData
659
- };
660
- await emitter.emit("watch-v2", {
661
- type: "tool-call-streaming-start",
662
- ...toolData
663
- });
664
- const run = await wf.createRunAsync();
665
- const { stream, getWorkflowState } = run.stream({
666
- inputData: input,
667
- runtimeContext: runtimeContextToUse
668
- });
669
- let result;
670
- for await (const chunk of stream) {
671
- const c = chunk;
672
- switch (c.type) {
673
- case "text-delta":
674
- await emitter.emit("watch-v2", {
675
- type: "tool-call-delta",
676
- ...toolData,
677
- argsTextDelta: c.textDelta
678
- });
679
- break;
680
- case "step-result":
681
- if (c?.payload?.output) {
682
- result = c?.payload?.output;
683
- }
684
- await emitter.emit("watch-v2", c);
685
- break;
686
- case "finish":
687
- streamPromise.resolve(result);
688
- break;
689
- case "start":
690
- case "step-start":
691
- case "step-finish":
692
- case "tool-call":
693
- case "tool-result":
694
- case "tool-call-streaming-start":
695
- case "tool-call-delta":
696
- case "source":
697
- case "file":
698
- default:
699
- await emitter.emit("watch-v2", c);
700
- break;
701
- }
702
- }
703
- let runSuccess = true;
704
- const runResult = await streamPromise.promise;
705
- const workflowState = await getWorkflowState();
706
- if (workflowState.status === "failed") {
707
- runSuccess = false;
708
- }
709
- const finalResult = JSON.stringify({
710
- runId: run.runId,
711
- runResult,
712
- runSuccess
713
- });
714
- const memory = await this.getMemory({ runtimeContext: runtimeContext || new RuntimeContext() });
715
- const initData = await getInitData();
716
- await memory?.saveMessages({
717
- messages: [
718
- {
719
- id: this.#mastra?.generateId() || randomUUID(),
720
- type: "text",
721
- role: "assistant",
722
- content: { parts: [{ type: "text", text: finalResult }], format: 2 },
723
- createdAt: /* @__PURE__ */ new Date(),
724
- threadId: initData.threadId || runId,
725
- resourceId: initData.threadResourceId || this.name
726
- }
727
- ],
728
- format: "v2"
729
- });
730
- return {
731
- result: finalResult || "",
732
- task: inputData.task,
733
- resourceId: inputData.resourceId,
734
- resourceType: inputData.resourceType,
735
- isComplete: false,
736
- iteration: inputData.iteration
737
- };
738
- }
739
- });
740
- const toolStep = createStep({
741
- id: "toolStep",
742
- inputSchema: z.object({
743
- task: z.string(),
744
- resourceId: z.string(),
745
- resourceType: PRIMITIVE_TYPES,
746
- prompt: z.string(),
747
- result: z.string(),
748
- isComplete: z.boolean().optional(),
749
- selectionReason: z.string(),
750
- iteration: z.number()
751
- }),
752
- outputSchema: z.object({
753
- task: z.string(),
754
- resourceId: z.string(),
755
- resourceType: PRIMITIVE_TYPES,
756
- result: z.string(),
757
- isComplete: z.boolean().optional(),
758
- iteration: z.number()
759
- }),
760
- execute: async ({ inputData, getInitData }) => {
761
- const toolsMap = await this.getTools({ runtimeContext: runtimeContextToUse });
762
- const tool = toolsMap[inputData.resourceId];
763
- if (!tool) {
764
- throw new Error(`Tool ${inputData.resourceId} not found`);
765
- }
766
- if (!tool.execute) {
767
- throw new Error(`Tool ${inputData.resourceId} does not have an execute function`);
768
- }
769
- let inputDataToUse;
770
- try {
771
- inputDataToUse = JSON.parse(inputData.prompt);
772
- } catch (e) {
773
- console.error(e);
774
- throw new Error(`Invalid task input: ${inputData.task}`);
775
- }
776
- const finalResult = await tool.execute({
777
- runtimeContext: runtimeContextToUse,
778
- mastra: this.#mastra,
779
- resourceId: inputData.resourceId,
780
- threadId: runId,
781
- runId,
782
- context: inputDataToUse,
783
- // TODO: Pass proper tracing context when network supports tracing
784
- tracingContext: { currentSpan: void 0 },
785
- suspend: async () => {
786
- }
787
- // TODO
788
- });
789
- const memory = await this.getMemory({ runtimeContext: runtimeContext || new RuntimeContext() });
790
- const initData = await getInitData();
791
- await memory?.saveMessages({
792
- messages: [
793
- {
794
- id: this.#mastra?.generateId() || randomUUID(),
795
- type: "text",
796
- role: "assistant",
797
- content: { parts: [{ type: "text", text: JSON.stringify(finalResult) }], format: 2 },
798
- createdAt: /* @__PURE__ */ new Date(),
799
- threadId: initData.threadId || runId,
800
- resourceId: initData.threadResourceId || this.name
801
- }
802
- ],
803
- format: "v2"
804
- });
805
- return {
806
- task: inputData.task,
807
- resourceId: inputData.resourceId,
808
- resourceType: inputData.resourceType,
809
- result: finalResult,
810
- isComplete: false,
811
- iteration: inputData.iteration
812
- };
813
- }
814
- });
815
- const finishStep = createStep({
816
- id: "finish-step",
817
- inputSchema: z.object({
818
- task: z.string(),
819
- resourceId: z.string(),
820
- resourceType: PRIMITIVE_TYPES,
821
- prompt: z.string(),
822
- result: z.string(),
823
- isComplete: z.boolean().optional(),
824
- selectionReason: z.string(),
825
- iteration: z.number()
826
- }),
827
- outputSchema: z.object({
828
- task: z.string(),
829
- result: z.string(),
830
- isComplete: z.boolean(),
831
- iteration: z.number()
832
- }),
833
- execute: async ({ inputData }) => {
834
- return {
835
- task: inputData.task,
836
- result: inputData.result,
837
- isComplete: !!inputData.isComplete,
838
- iteration: inputData.iteration
839
- };
840
- }
841
- });
842
- const networkWorkflow = createWorkflow({
843
- id: "Agent-Network-Outer-Workflow",
844
- inputSchema: z.object({
845
- task: z.string(),
846
- resourceId: z.string(),
847
- resourceType: PRIMITIVE_TYPES,
848
- result: z.string().optional(),
849
- iteration: z.number(),
850
- threadId: z.string().optional(),
851
- threadResourceId: z.string().optional(),
852
- isOneOff: z.boolean(),
853
- verboseIntrospection: z.boolean()
854
- }),
855
- outputSchema: z.object({
856
- task: z.string(),
857
- resourceId: z.string(),
858
- resourceType: PRIMITIVE_TYPES,
859
- prompt: z.string(),
860
- result: z.string(),
861
- isComplete: z.boolean().optional(),
862
- completionReason: z.string().optional(),
863
- iteration: z.number(),
864
- threadId: z.string().optional(),
865
- threadResourceId: z.string().optional(),
866
- isOneOff: z.boolean()
867
- })
868
- });
869
- networkWorkflow.then(routingStep).branch([
870
- [async ({ inputData }) => !inputData.isComplete && inputData.resourceType === "agent", agentStep],
871
- [async ({ inputData }) => !inputData.isComplete && inputData.resourceType === "workflow", workflowStep],
872
- [async ({ inputData }) => !inputData.isComplete && inputData.resourceType === "tool", toolStep],
873
- [async ({ inputData }) => inputData.isComplete, finishStep]
874
- ]).map({
875
- task: {
876
- step: [routingStep, agentStep, workflowStep, toolStep],
877
- path: "task"
878
- },
879
- isComplete: {
880
- step: [agentStep, workflowStep, toolStep, finishStep],
881
- path: "isComplete"
882
- },
883
- completionReason: {
884
- step: [routingStep, agentStep, workflowStep, toolStep, finishStep],
885
- path: "completionReason"
886
- },
887
- result: {
888
- step: [agentStep, workflowStep, toolStep, finishStep],
889
- path: "result"
890
- },
891
- resourceId: {
892
- step: [routingStep, agentStep, workflowStep, toolStep],
893
- path: "resourceId"
894
- },
895
- resourceType: {
896
- step: [routingStep, agentStep, workflowStep, toolStep],
897
- path: "resourceType"
898
- },
899
- iteration: {
900
- step: [routingStep, agentStep, workflowStep, toolStep],
901
- path: "iteration"
902
- },
903
- isOneOff: {
904
- initData: networkWorkflow,
905
- path: "isOneOff"
906
- },
907
- threadId: {
908
- initData: networkWorkflow,
909
- path: "threadId"
910
- },
911
- threadResourceId: {
912
- initData: networkWorkflow,
913
- path: "threadResourceId"
914
- }
915
- }).commit();
916
- return networkWorkflow;
917
- }
918
- async generate(messages, {
919
- runtimeContext,
920
- threadId,
921
- resourceId
922
- }) {
923
- const networkWorkflow = this.createWorkflow({ runtimeContext });
924
- const run = await networkWorkflow.createRunAsync();
925
- const thread = await this.beforeRun({
926
- runtimeContext: runtimeContext || new RuntimeContext(),
927
- threadId: threadId || run.runId,
928
- resourceId: resourceId || this.name,
929
- messages
930
- });
931
- const message = this.getLastMessage(messages);
932
- const result = await run.start({
933
- inputData: {
934
- task: message,
935
- resourceId: "",
936
- resourceType: "none",
937
- iteration: 0,
938
- threadId: thread?.id,
939
- threadResourceId: thread?.resourceId,
940
- isOneOff: true,
941
- verboseIntrospection: true
942
- }
943
- });
944
- if (result.status === "failed") {
945
- throw result.error;
946
- }
947
- if (result.status === "suspended") {
948
- throw new Error("Workflow suspended");
949
- }
950
- return {
951
- task: result.result.task,
952
- result: result.result.result,
953
- resourceId: result.result.resourceId,
954
- resourceType: result.result.resourceType
955
- };
956
- }
957
- async stream(messages, {
958
- runtimeContext,
959
- threadId,
960
- resourceId
961
- }) {
962
- const networkWorkflow = this.createWorkflow({ runtimeContext });
963
- const run = await networkWorkflow.createRunAsync();
964
- const thread = await this.beforeRun({
965
- runtimeContext: runtimeContext || new RuntimeContext(),
966
- threadId: threadId || run.runId,
967
- resourceId: resourceId || this.name,
968
- messages
969
- });
970
- const message = this.getLastMessage(messages);
971
- return run.stream({
972
- inputData: {
973
- task: `You are executing just one primitive based on the following: ${message}`,
974
- resourceId: "",
975
- resourceType: "none",
976
- iteration: 0,
977
- threadResourceId: thread?.resourceId,
978
- threadId: thread?.id,
979
- isOneOff: true,
980
- verboseIntrospection: true
981
- }
982
- });
983
- }
984
- };
985
-
986
- export { NewAgentNetwork };
987
- //# sourceMappingURL=index.js.map
988
- //# sourceMappingURL=index.js.map