@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,4132 @@
1
+ import { Tool as Tool$2, Schema, ToolExecutionOptions, LanguageModelV1, CoreMessage as CoreMessage$1, GenerateTextResult, GenerateObjectResult, StreamTextResult, StreamObjectResult, TextStreamPart, UserContent, AssistantContent, ToolContent, EmbeddingModel, UIMessage, Message, IDGenerator as IDGenerator$1, CoreSystemMessage as CoreSystemMessage$1, DeepPartial, generateText, generateObject, streamText, streamObject, TelemetrySettings, CoreAssistantMessage as CoreAssistantMessage$1, CoreUserMessage as CoreUserMessage$1, CoreToolMessage as CoreToolMessage$1, EmbedResult as EmbedResult$1, EmbedManyResult as EmbedManyResult$1, GenerateTextOnStepFinishCallback, StreamTextOnFinishCallback, StreamObjectOnFinishCallback, StreamTextOnStepFinishCallback } from 'ai';
2
+ import { M as MastraBase, a as Telemetry, O as OtelConfig, T as Trace } from './base-ClrXcCRx.js';
3
+ import { JSONSchema7Type, JSONSchema7 } from 'json-schema';
4
+ import { z, ZodSchema, ZodObject } from 'zod';
5
+ import { B as BaseLogMessage, R as RegisteredLogger, I as IMastraLogger, a as LogLevel } from './logger-Bpa2oLL4.js';
6
+ import { M as Metric, a as MetricResult, T as TestInfo } from './types-Bo1uigWx.js';
7
+ import { Query } from 'sift';
8
+ import { RuntimeContext } from './runtime-context/index.js';
9
+ import { Span } from '@opentelemetry/api';
10
+ import * as xstate from 'xstate';
11
+ import { Snapshot } from 'xstate';
12
+ import EventEmitter from 'node:events';
13
+ import { MastraVector } from './vector/index.js';
14
+ import { MastraTTS } from './tts/index.js';
15
+ import * as http from 'node:http';
16
+ import { Context, HonoRequest, Handler, MiddlewareHandler } from 'hono';
17
+ import * as stream_web from 'stream/web';
18
+ import { VectorFilter } from './vector/filter/index.js';
19
+ import EventEmitter$1 from 'events';
20
+ import { ReadableStream } from 'node:stream/web';
21
+ import { EMITTER_SYMBOL } from './workflows/constants.js';
22
+ import { MockLanguageModelV1 } from 'ai/test';
23
+ import { MastraDeployer } from './deployer/index.js';
24
+ import { cors } from 'hono/cors';
25
+ import { DescribeRouteOptions } from 'hono-openapi';
26
+
27
+ type BundlerConfig = {
28
+ externals?: string[];
29
+ };
30
+
31
+ type VercelTool = Tool$2;
32
+ type CoreTool = {
33
+ id?: string;
34
+ description?: string;
35
+ parameters: ZodSchema | JSONSchema7Type | Schema;
36
+ outputSchema?: ZodSchema | JSONSchema7Type | Schema;
37
+ execute?: (params: any, options: ToolExecutionOptions) => Promise<any>;
38
+ } & ({
39
+ type?: 'function' | undefined;
40
+ id?: string;
41
+ } | {
42
+ type: 'provider-defined';
43
+ id: `${string}.${string}`;
44
+ args: Record<string, unknown>;
45
+ });
46
+ type InternalCoreTool = {
47
+ id?: string;
48
+ description?: string;
49
+ parameters: Schema;
50
+ outputSchema?: Schema;
51
+ execute?: (params: any, options: ToolExecutionOptions) => Promise<any>;
52
+ } & ({
53
+ type?: 'function' | undefined;
54
+ id?: string;
55
+ } | {
56
+ type: 'provider-defined';
57
+ id: `${string}.${string}`;
58
+ args: Record<string, unknown>;
59
+ });
60
+ interface ToolExecutionContext<TSchemaIn extends z.ZodSchema | undefined = undefined> extends IExecutionContext<TSchemaIn> {
61
+ mastra?: MastraUnion;
62
+ runtimeContext: RuntimeContext;
63
+ }
64
+ interface ToolAction<TSchemaIn extends z.ZodSchema | undefined = undefined, TSchemaOut extends z.ZodSchema | undefined = undefined, TContext extends ToolExecutionContext<TSchemaIn> = ToolExecutionContext<TSchemaIn>> extends IAction<string, TSchemaIn, TSchemaOut, TContext, ToolExecutionOptions> {
65
+ description: string;
66
+ execute?: (context: TContext, options?: ToolExecutionOptions) => Promise<TSchemaOut extends z.ZodSchema ? z.infer<TSchemaOut> : unknown>;
67
+ mastra?: Mastra;
68
+ }
69
+
70
+ declare class Tool$1<TSchemaIn extends z.ZodSchema | undefined = undefined, TSchemaOut extends z.ZodSchema | undefined = undefined, TContext extends ToolExecutionContext<TSchemaIn> = ToolExecutionContext<TSchemaIn>> implements ToolAction<TSchemaIn, TSchemaOut, TContext> {
71
+ id: string;
72
+ description: string;
73
+ inputSchema?: TSchemaIn;
74
+ outputSchema?: TSchemaOut;
75
+ execute?: ToolAction<TSchemaIn, TSchemaOut, TContext>['execute'];
76
+ mastra?: Mastra;
77
+ constructor(opts: ToolAction<TSchemaIn, TSchemaOut, TContext>);
78
+ }
79
+ declare function createTool<TSchemaIn extends z.ZodSchema | undefined = undefined, TSchemaOut extends z.ZodSchema | undefined = undefined, TContext extends ToolExecutionContext<TSchemaIn> = ToolExecutionContext<TSchemaIn>, TExecute extends ToolAction<TSchemaIn, TSchemaOut, TContext>['execute'] = ToolAction<TSchemaIn, TSchemaOut, TContext>['execute']>(opts: ToolAction<TSchemaIn, TSchemaOut, TContext> & {
80
+ execute?: TExecute;
81
+ }): [TSchemaIn, TSchemaOut, TExecute] extends [z.ZodSchema, z.ZodSchema, Function] ? Tool$1<TSchemaIn, TSchemaOut, TContext> & {
82
+ inputSchema: TSchemaIn;
83
+ outputSchema: TSchemaOut;
84
+ execute: (context: TContext) => Promise<any>;
85
+ } : Tool$1<TSchemaIn, TSchemaOut, TContext>;
86
+
87
+ type RunStatus = 'created' | 'running' | 'completed' | 'failed';
88
+ type Run$1 = {
89
+ runId?: string;
90
+ runStatus?: RunStatus;
91
+ };
92
+
93
+ type AgentNetworkConfig = {
94
+ name: string;
95
+ agents: Agent[];
96
+ model: LanguageModelV1;
97
+ instructions: string;
98
+ };
99
+
100
+ declare class AgentNetwork extends MastraBase {
101
+ #private;
102
+ constructor(config: AgentNetworkConfig);
103
+ formatAgentId(name: string): string;
104
+ getTools(): {
105
+ readonly transmit: Tool$1<z.ZodObject<{
106
+ actions: z.ZodArray<z.ZodObject<{
107
+ agent: z.ZodString;
108
+ input: z.ZodString;
109
+ includeHistory: z.ZodOptional<z.ZodBoolean>;
110
+ }, "strip", z.ZodTypeAny, {
111
+ input: string;
112
+ agent: string;
113
+ includeHistory?: boolean | undefined;
114
+ }, {
115
+ input: string;
116
+ agent: string;
117
+ includeHistory?: boolean | undefined;
118
+ }>, "many">;
119
+ }, "strip", z.ZodTypeAny, {
120
+ actions: {
121
+ input: string;
122
+ agent: string;
123
+ includeHistory?: boolean | undefined;
124
+ }[];
125
+ }, {
126
+ actions: {
127
+ input: string;
128
+ agent: string;
129
+ includeHistory?: boolean | undefined;
130
+ }[];
131
+ }>, undefined, ToolExecutionContext<z.ZodObject<{
132
+ actions: z.ZodArray<z.ZodObject<{
133
+ agent: z.ZodString;
134
+ input: z.ZodString;
135
+ includeHistory: z.ZodOptional<z.ZodBoolean>;
136
+ }, "strip", z.ZodTypeAny, {
137
+ input: string;
138
+ agent: string;
139
+ includeHistory?: boolean | undefined;
140
+ }, {
141
+ input: string;
142
+ agent: string;
143
+ includeHistory?: boolean | undefined;
144
+ }>, "many">;
145
+ }, "strip", z.ZodTypeAny, {
146
+ actions: {
147
+ input: string;
148
+ agent: string;
149
+ includeHistory?: boolean | undefined;
150
+ }[];
151
+ }, {
152
+ actions: {
153
+ input: string;
154
+ agent: string;
155
+ includeHistory?: boolean | undefined;
156
+ }[];
157
+ }>>>;
158
+ };
159
+ getAgentHistory(agentId: string): {
160
+ input: string;
161
+ output: string;
162
+ timestamp: string;
163
+ }[];
164
+ /**
165
+ * Get the history of all agent interactions that have occurred in this network
166
+ * @returns A record of agent interactions, keyed by agent ID
167
+ */
168
+ getAgentInteractionHistory(): {
169
+ [x: string]: {
170
+ input: string;
171
+ output: string;
172
+ timestamp: string;
173
+ }[];
174
+ };
175
+ /**
176
+ * Get a summary of agent interactions in a more readable format, displayed chronologically
177
+ * @returns A formatted string with all agent interactions in chronological order
178
+ */
179
+ getAgentInteractionSummary(): string;
180
+ executeAgent(agentId: string, input: CoreMessage$1[], includeHistory?: boolean, runtimeContext?: RuntimeContext): Promise<string>;
181
+ getInstructions(): string;
182
+ getRoutingAgent(): Agent<string, ToolsInput, Record<string, Metric>>;
183
+ getAgents(): Agent<string, ToolsInput, Record<string, Metric>>[];
184
+ generate<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[], args?: AgentGenerateOptions<Z> & {
185
+ output?: never;
186
+ experimental_output?: never;
187
+ }): Promise<GenerateTextResult<any, Z extends ZodSchema ? z.infer<Z> : unknown>>;
188
+ generate<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[], args?: AgentGenerateOptions<Z> & ({
189
+ output: Z;
190
+ experimental_output?: never;
191
+ } | {
192
+ experimental_output: Z;
193
+ output?: never;
194
+ })): Promise<GenerateObjectResult<Z extends ZodSchema ? z.infer<Z> : unknown>>;
195
+ stream<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[], args?: AgentStreamOptions<Z> & {
196
+ output?: never;
197
+ experimental_output?: never;
198
+ }): Promise<StreamTextResult<any, Z extends ZodSchema ? z.infer<Z> : unknown>>;
199
+ stream<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[], args?: AgentStreamOptions<Z> & ({
200
+ output: Z;
201
+ experimental_output?: never;
202
+ } | {
203
+ experimental_output: Z;
204
+ output?: never;
205
+ })): Promise<StreamObjectResult<any, Z extends ZodSchema ? z.infer<Z> : unknown, any>>;
206
+ __registerMastra(p: Mastra): void;
207
+ }
208
+
209
+ interface WorkflowOptions<TWorkflowName extends string = string, TSteps extends LegacyStep<string, any, any, any>[] = LegacyStep<string, any, any, any>[], TTriggerSchema extends z.ZodObject<any> = any, TResultSchema extends z.ZodObject<any> = any> {
210
+ steps?: TSteps;
211
+ name: TWorkflowName;
212
+ triggerSchema?: TTriggerSchema;
213
+ result?: {
214
+ schema: TResultSchema;
215
+ mapping?: {
216
+ [K in keyof z.infer<TResultSchema>]?: any;
217
+ };
218
+ };
219
+ events?: Record<string, {
220
+ schema: z.ZodObject<any>;
221
+ }>;
222
+ retryConfig?: RetryConfig;
223
+ mastra?: Mastra;
224
+ }
225
+ interface StepExecutionContext<TSchemaIn extends z.ZodSchema | undefined = undefined, TContext extends WorkflowContext = WorkflowContext> extends IExecutionContext<TSchemaIn> {
226
+ context: TSchemaIn extends z.ZodSchema ? {
227
+ inputData: z.infer<TSchemaIn>;
228
+ } & TContext : TContext;
229
+ suspend: (payload?: unknown, softSuspend?: any) => Promise<void>;
230
+ runId: string;
231
+ emit: (event: string, data: any) => void;
232
+ mastra?: MastraUnion;
233
+ runtimeContext: RuntimeContext;
234
+ }
235
+ interface StepAction<TId extends string, TSchemaIn extends z.ZodSchema | undefined, TSchemaOut extends z.ZodSchema | undefined, TContext extends StepExecutionContext<TSchemaIn>> extends IAction<TId, TSchemaIn, TSchemaOut, TContext> {
236
+ mastra?: Mastra;
237
+ payload?: TSchemaIn extends z.ZodSchema ? Partial<z.infer<TSchemaIn>> : unknown;
238
+ execute: (context: TContext) => Promise<TSchemaOut extends z.ZodSchema ? z.infer<TSchemaOut> : unknown>;
239
+ retryConfig?: RetryConfig;
240
+ workflow?: LegacyWorkflow;
241
+ workflowId?: string;
242
+ }
243
+ interface SimpleConditionalType {
244
+ [key: `${string}.${string}`]: string | Query<any>;
245
+ }
246
+ type StepVariableType<TId extends string, TSchemaIn extends z.ZodSchema | undefined, TSchemaOut extends z.ZodSchema | undefined, TContext extends StepExecutionContext<TSchemaIn>> = StepAction<TId, TSchemaIn, TSchemaOut, TContext> | 'trigger' | {
247
+ id: string;
248
+ };
249
+ type StepNode = {
250
+ id: string;
251
+ step: StepAction<any, any, any, any>;
252
+ config: StepDef<any, any, any, any>[any];
253
+ };
254
+ type StepGraph = {
255
+ initial: StepNode[];
256
+ [key: string]: StepNode[];
257
+ };
258
+ type RetryConfig = {
259
+ attempts?: number;
260
+ delay?: number;
261
+ };
262
+ type VariableReference$1<TStep extends StepVariableType<any, any, any, any>, TTriggerSchema extends z.ZodObject<any>> = TStep extends StepAction<any, any, any, any> ? {
263
+ step: TStep;
264
+ path: PathsToStringProps$1<ExtractSchemaType$1<ExtractSchemaFromStep$1<TStep, 'outputSchema'>>> | '' | '.';
265
+ } : TStep extends 'trigger' ? {
266
+ step: 'trigger';
267
+ path: PathsToStringProps$1<ExtractSchemaType$1<TTriggerSchema>> | '.' | '';
268
+ } : {
269
+ step: {
270
+ id: string;
271
+ };
272
+ path: string;
273
+ };
274
+ interface BaseCondition<TStep extends StepVariableType<any, any, any, any>, TTriggerSchema extends z.ZodObject<any>> {
275
+ ref: TStep extends StepAction<any, any, any, any> ? {
276
+ step: TStep;
277
+ path: PathsToStringProps$1<ExtractSchemaType$1<ExtractSchemaFromStep$1<TStep, 'outputSchema'>>> | '' | '.' | 'status';
278
+ } : TStep extends 'trigger' ? {
279
+ step: 'trigger';
280
+ path: PathsToStringProps$1<ExtractSchemaType$1<TTriggerSchema>> | '.' | '';
281
+ } : {
282
+ step: {
283
+ id: string;
284
+ };
285
+ path: string;
286
+ };
287
+ query: Query<any>;
288
+ }
289
+ type ActionContext<TSchemaIn extends z.ZodType<any>> = StepExecutionContext<z.infer<TSchemaIn>, WorkflowContext>;
290
+ declare enum WhenConditionReturnValue {
291
+ CONTINUE = "continue",
292
+ CONTINUE_FAILED = "continue_failed",
293
+ ABORT = "abort",
294
+ LIMBO = "limbo"
295
+ }
296
+ type StepDef<TStepId extends TSteps[number]['id'], TSteps extends StepAction<any, any, any, any>[], TSchemaIn extends z.ZodType<any>, TSchemaOut extends z.ZodType<any>> = Record<TStepId, {
297
+ id?: string;
298
+ when?: Condition<any, any> | ((args: {
299
+ context: WorkflowContext;
300
+ mastra?: Mastra;
301
+ }) => Promise<boolean | WhenConditionReturnValue>);
302
+ serializedWhen?: Condition<any, any> | string;
303
+ loopLabel?: string;
304
+ loopType?: 'while' | 'until';
305
+ data: TSchemaIn;
306
+ handler: (args: ActionContext<TSchemaIn>) => Promise<z.infer<TSchemaOut>>;
307
+ }>;
308
+ type StepCondition<TStep extends StepVariableType<any, any, any, any>, TTriggerSchema extends z.ZodObject<any>> = BaseCondition<TStep, TTriggerSchema> | SimpleConditionalType | {
309
+ and: StepCondition<TStep, TTriggerSchema>[];
310
+ } | {
311
+ or: StepCondition<TStep, TTriggerSchema>[];
312
+ } | {
313
+ not: StepCondition<TStep, TTriggerSchema>;
314
+ };
315
+ type Condition<TStep extends StepVariableType<any, any, any, any>, TTriggerSchema extends z.ZodObject<any>> = BaseCondition<TStep, TTriggerSchema> | SimpleConditionalType | {
316
+ and: Condition<TStep, TTriggerSchema>[];
317
+ } | {
318
+ or: Condition<TStep, TTriggerSchema>[];
319
+ } | {
320
+ not: Condition<TStep, TTriggerSchema>;
321
+ };
322
+ interface StepConfig<TStep extends StepAction<any, any, any, any>, CondStep extends StepVariableType<any, any, any, any>, VarStep extends StepVariableType<any, any, any, any>, TTriggerSchema extends z.ZodObject<any>, TSteps extends LegacyStep<string, any, any, any>[] = LegacyStep<string, any, any, any>[]> {
323
+ when?: Condition<CondStep, TTriggerSchema> | ((args: {
324
+ context: WorkflowContext<TTriggerSchema, TSteps>;
325
+ mastra?: Mastra;
326
+ }) => Promise<boolean | WhenConditionReturnValue>);
327
+ variables?: StepInputType<TStep, 'inputSchema'> extends never ? Record<string, VariableReference$1<VarStep, TTriggerSchema>> : {
328
+ [K in keyof StepInputType<TStep, 'inputSchema'>]?: VariableReference$1<VarStep, TTriggerSchema>;
329
+ };
330
+ '#internal'?: {
331
+ when?: Condition<CondStep, TTriggerSchema> | ((args: {
332
+ context: WorkflowContext<TTriggerSchema, TSteps>;
333
+ mastra?: Mastra;
334
+ }) => Promise<boolean | WhenConditionReturnValue>);
335
+ loopLabel?: string;
336
+ loopType?: 'while' | 'until' | undefined;
337
+ };
338
+ id?: string;
339
+ }
340
+ type StepSuccess$1<T> = {
341
+ status: 'success';
342
+ output: T;
343
+ };
344
+ type StepSuspended$1<T> = {
345
+ status: 'suspended';
346
+ suspendPayload?: any;
347
+ output?: T;
348
+ };
349
+ type StepWaiting$1 = {
350
+ status: 'waiting';
351
+ };
352
+ type StepFailure$1 = {
353
+ status: 'failed';
354
+ error: string;
355
+ };
356
+ type StepSkipped = {
357
+ status: 'skipped';
358
+ };
359
+ type StepResult$1<T> = StepSuccess$1<T> | StepFailure$1 | StepSuspended$1<T> | StepWaiting$1 | StepSkipped;
360
+ type StepsRecord$1<T extends readonly LegacyStep<any, any, z.ZodType<any> | undefined>[]> = {
361
+ [K in T[number]['id']]: Extract<T[number], {
362
+ id: K;
363
+ }>;
364
+ };
365
+ interface LegacyWorkflowRunResult<T extends z.ZodObject<any>, TSteps extends LegacyStep<string, any, z.ZodType<any> | undefined>[], TResult extends z.ZodObject<any>> {
366
+ triggerData?: z.infer<T>;
367
+ result?: z.infer<TResult>;
368
+ results: {
369
+ [K in keyof StepsRecord$1<TSteps>]: StepsRecord$1<TSteps>[K]['outputSchema'] extends undefined ? StepResult$1<unknown> : StepResult$1<z.infer<NonNullable<StepsRecord$1<TSteps>[K]['outputSchema']>>>;
370
+ };
371
+ runId: string;
372
+ timestamp: number;
373
+ activePaths: Map<keyof StepsRecord$1<TSteps>, {
374
+ status: string;
375
+ suspendPayload?: any;
376
+ stepPath: string[];
377
+ }>;
378
+ }
379
+ interface WorkflowContext<TTrigger extends z.ZodObject<any> = any, TSteps extends LegacyStep<string, any, any, any>[] = LegacyStep<string, any, any, any>[], TInputData extends Record<string, any> = Record<string, any>> {
380
+ isResume?: {
381
+ runId: string;
382
+ stepId: string;
383
+ };
384
+ mastra?: MastraUnion;
385
+ steps: {
386
+ [K in keyof StepsRecord$1<TSteps>]: StepsRecord$1<TSteps>[K]['outputSchema'] extends undefined ? StepResult$1<unknown> : StepResult$1<z.infer<NonNullable<StepsRecord$1<TSteps>[K]['outputSchema']>>>;
387
+ };
388
+ triggerData: z.infer<TTrigger>;
389
+ inputData: TInputData;
390
+ attempts: Record<string, number>;
391
+ getStepResult(stepId: 'trigger'): z.infer<TTrigger>;
392
+ getStepResult<T extends keyof StepsRecord$1<TSteps> | unknown>(stepId: T extends keyof StepsRecord$1<TSteps> ? T : string): T extends keyof StepsRecord$1<TSteps> ? StepsRecord$1<TSteps>[T]['outputSchema'] extends undefined ? unknown : z.infer<NonNullable<StepsRecord$1<TSteps>[T]['outputSchema']>> : T;
393
+ getStepResult<T extends LegacyStep<any, any, any, any>>(stepId: T): T['outputSchema'] extends undefined ? unknown : z.infer<NonNullable<T['outputSchema']>>;
394
+ }
395
+ interface WorkflowLogMessage extends BaseLogMessage {
396
+ type: typeof RegisteredLogger.WORKFLOW;
397
+ workflowName: string;
398
+ stepId?: StepId;
399
+ data?: unknown;
400
+ runId?: string;
401
+ }
402
+ type WorkflowEvent = {
403
+ type: 'RESET_TO_PENDING';
404
+ stepId: string;
405
+ } | {
406
+ type: 'CONDITIONS_MET';
407
+ stepId: string;
408
+ } | {
409
+ type: 'CONDITION_FAILED';
410
+ stepId: string;
411
+ error: string;
412
+ } | {
413
+ type: 'SUSPENDED';
414
+ stepId: string;
415
+ suspendPayload?: any;
416
+ softSuspend?: any;
417
+ } | {
418
+ type: 'WAITING';
419
+ stepId: string;
420
+ } | {
421
+ type: `xstate.error.actor.${string}`;
422
+ error: Error;
423
+ } | {
424
+ type: `xstate.done.actor.${string}`;
425
+ output: ResolverFunctionOutput;
426
+ };
427
+ type ResolverFunctionInput = {
428
+ stepNode: StepNode;
429
+ context: WorkflowContext;
430
+ };
431
+ type ResolverFunctionOutput = {
432
+ stepId: StepId;
433
+ result: unknown;
434
+ };
435
+ type SubscriberFunctionOutput = {
436
+ stepId: StepId;
437
+ result: unknown;
438
+ };
439
+ type DependencyCheckOutput = {
440
+ type: 'CONDITIONS_MET';
441
+ } | {
442
+ type: 'CONDITIONS_SKIPPED';
443
+ } | {
444
+ type: 'CONDITIONS_SKIP_TO_COMPLETED';
445
+ } | {
446
+ type: 'CONDITION_FAILED';
447
+ error: string;
448
+ } | {
449
+ type: 'SUSPENDED';
450
+ } | {
451
+ type: 'WAITING';
452
+ } | {
453
+ type: 'CONDITIONS_LIMBO';
454
+ };
455
+ type StepResolverOutput = {
456
+ type: 'STEP_SUCCESS';
457
+ output: unknown;
458
+ } | {
459
+ type: 'STEP_FAILED';
460
+ error: string;
461
+ } | {
462
+ type: 'STEP_WAITING';
463
+ };
464
+ type WorkflowActors = {
465
+ resolverFunction: {
466
+ input: ResolverFunctionInput;
467
+ output: StepResolverOutput;
468
+ };
469
+ conditionCheck: {
470
+ input: {
471
+ context: WorkflowContext;
472
+ stepId: string;
473
+ };
474
+ output: DependencyCheckOutput;
475
+ };
476
+ spawnSubscriberFunction: {
477
+ input: {
478
+ context: WorkflowContext;
479
+ stepId: string;
480
+ };
481
+ output: SubscriberFunctionOutput;
482
+ };
483
+ };
484
+ type WorkflowActionParams = {
485
+ stepId: string;
486
+ };
487
+ type WorkflowActions = {
488
+ type: 'updateStepResult' | 'setStepError' | 'notifyStepCompletion' | 'decrementAttemptCount';
489
+ params: WorkflowActionParams;
490
+ };
491
+ type LegacyWorkflowState = {
492
+ [key: string]: {
493
+ initial: 'pending';
494
+ states: {
495
+ pending: {
496
+ invoke: {
497
+ src: 'conditionCheck';
498
+ input: ({ context }: {
499
+ context: WorkflowContext;
500
+ }) => {
501
+ context: WorkflowContext;
502
+ stepId: string;
503
+ };
504
+ onDone: [
505
+ {
506
+ guard: (_: any, event: {
507
+ output: DependencyCheckOutput;
508
+ }) => boolean;
509
+ target: 'executing';
510
+ },
511
+ {
512
+ guard: (_: any, event: {
513
+ output: DependencyCheckOutput;
514
+ }) => boolean;
515
+ target: 'waiting';
516
+ }
517
+ ];
518
+ };
519
+ };
520
+ waiting: {
521
+ after: {
522
+ CHECK_INTERVAL: {
523
+ target: 'pending';
524
+ };
525
+ };
526
+ };
527
+ executing: {
528
+ invoke: {
529
+ src: 'resolverFunction';
530
+ input: ({ context }: {
531
+ context: WorkflowContext;
532
+ }) => ResolverFunctionInput;
533
+ onDone: {
534
+ target: 'completed';
535
+ actions: ['updateStepResult'];
536
+ };
537
+ onError: {
538
+ target: 'failed';
539
+ actions: ['setStepError'];
540
+ };
541
+ };
542
+ };
543
+ completed: {
544
+ type: 'final';
545
+ entry: ['notifyStepCompletion'];
546
+ };
547
+ failed: {
548
+ type: 'final';
549
+ entry: ['notifyStepCompletion'];
550
+ };
551
+ };
552
+ };
553
+ };
554
+ declare const StepIdBrand: unique symbol;
555
+ type StepId = string & {
556
+ readonly [StepIdBrand]: typeof StepIdBrand;
557
+ };
558
+ type ExtractSchemaFromStep$1<TStep extends StepAction<any, any, any, any>, TKey extends 'inputSchema' | 'outputSchema'> = TStep[TKey];
559
+ type ExtractStepResult<T> = T extends (data: any) => Promise<infer R> ? R : never;
560
+ type StepInputType<TStep extends StepAction<any, any, any, any>, TKey extends 'inputSchema' | 'outputSchema'> = ExtractSchemaFromStep$1<TStep, TKey> extends infer Schema ? Schema extends z.ZodType<any> ? z.infer<Schema> : never : never;
561
+ type ExtractSchemaType$1<T extends z.ZodSchema> = T extends z.ZodSchema<infer V> ? V : never;
562
+ type PathsToStringProps$1<T> = T extends object ? {
563
+ [K in keyof T]: T[K] extends object ? K extends string ? K | `${K}.${PathsToStringProps$1<T[K]>}` : never : K extends string ? K : never;
564
+ }[keyof T] : never;
565
+ interface LegacyWorkflowRunState {
566
+ value: Record<string, string>;
567
+ context: {
568
+ steps: Record<string, {
569
+ status: 'success' | 'failed' | 'suspended' | 'waiting' | 'skipped';
570
+ payload?: any;
571
+ error?: string;
572
+ }>;
573
+ triggerData: Record<string, any>;
574
+ attempts: Record<string, number>;
575
+ };
576
+ activePaths: Array<{
577
+ stepPath: string[];
578
+ stepId: string;
579
+ status: string;
580
+ }>;
581
+ suspendedPaths: Record<string, number[]>;
582
+ runId: string;
583
+ timestamp: number;
584
+ childStates?: Record<string, LegacyWorkflowRunState>;
585
+ suspendedSteps?: Record<string, string>;
586
+ }
587
+ type WorkflowResumeResult<TTriggerSchema extends z.ZodObject<any>> = {
588
+ triggerData?: z.infer<TTriggerSchema>;
589
+ results: Record<string, StepResult$1<any>>;
590
+ };
591
+
592
+ declare class LegacyStep<TStepId extends string = any, TSchemaIn extends z.ZodSchema | undefined = undefined, TSchemaOut extends z.ZodSchema | undefined = undefined, TContext extends StepExecutionContext<TSchemaIn> = StepExecutionContext<TSchemaIn>> implements StepAction<TStepId, TSchemaIn, TSchemaOut, TContext> {
593
+ id: TStepId;
594
+ description?: string;
595
+ inputSchema?: TSchemaIn;
596
+ outputSchema?: TSchemaOut;
597
+ payload?: TSchemaIn extends z.ZodSchema ? Partial<z.infer<TSchemaIn>> : unknown;
598
+ execute: (context: TContext) => Promise<TSchemaOut extends z.ZodSchema ? z.infer<TSchemaOut> : unknown>;
599
+ retryConfig?: RetryConfig;
600
+ mastra?: Mastra;
601
+ constructor({ id, description, execute, payload, outputSchema, inputSchema, retryConfig, }: StepAction<TStepId, TSchemaIn, TSchemaOut, TContext>);
602
+ }
603
+
604
+ declare class Machine<TSteps extends LegacyStep<any, any, any, any>[] = LegacyStep<any, any, any, any>[], TTriggerSchema extends z.ZodObject<any> = any, TResultSchema extends z.ZodObject<any> = any> extends EventEmitter {
605
+ #private;
606
+ logger: IMastraLogger;
607
+ name: string;
608
+ constructor({ logger, mastra, runtimeContext, workflowInstance, executionSpan, name, runId, steps, stepGraph, retryConfig, startStepId, }: {
609
+ logger: IMastraLogger;
610
+ mastra?: Mastra;
611
+ runtimeContext: RuntimeContext;
612
+ workflowInstance: WorkflowInstance;
613
+ executionSpan?: Span;
614
+ name: string;
615
+ runId: string;
616
+ steps: Record<string, StepNode>;
617
+ stepGraph: StepGraph;
618
+ retryConfig?: RetryConfig;
619
+ startStepId: string;
620
+ });
621
+ get startStepId(): string;
622
+ execute({ stepId, input, snapshot, resumeData, }?: {
623
+ stepId?: string;
624
+ input?: any;
625
+ snapshot?: Snapshot<any>;
626
+ resumeData?: any;
627
+ }): Promise<Pick<LegacyWorkflowRunResult<TTriggerSchema, TSteps, TResultSchema>, 'results' | 'activePaths' | 'runId' | 'timestamp'>>;
628
+ private initializeMachine;
629
+ getSnapshot(): xstate.MachineSnapshot<Omit<WorkflowContext<any, LegacyStep<string, any, any, any>[], Record<string, any>>, "getStepResult">, {
630
+ type: "RESET_TO_PENDING";
631
+ stepId: string;
632
+ } | {
633
+ type: "CONDITIONS_MET";
634
+ stepId: string;
635
+ } | {
636
+ type: "CONDITION_FAILED";
637
+ stepId: string;
638
+ error: string;
639
+ } | {
640
+ type: "SUSPENDED";
641
+ stepId: string;
642
+ suspendPayload?: any;
643
+ softSuspend?: any;
644
+ } | {
645
+ type: "WAITING";
646
+ stepId: string;
647
+ } | {
648
+ type: `xstate.error.actor.${string}`;
649
+ error: Error;
650
+ } | {
651
+ type: `xstate.done.actor.${string}`;
652
+ output: ResolverFunctionOutput;
653
+ }, {
654
+ [x: string]: xstate.ActorRefFromLogic<xstate.PromiseActorLogic<{
655
+ type: "CONDITIONS_MET";
656
+ error?: undefined;
657
+ } | {
658
+ type: "CONDITIONS_SKIP_TO_COMPLETED";
659
+ error?: undefined;
660
+ } | {
661
+ type: "CONDITIONS_LIMBO";
662
+ error?: undefined;
663
+ } | {
664
+ type: "CONDITIONS_SKIPPED";
665
+ error?: undefined;
666
+ } | {
667
+ type: "CONDITION_FAILED";
668
+ error: string;
669
+ }, {
670
+ context: WorkflowContext;
671
+ stepNode: StepNode;
672
+ }, xstate.EventObject>> | xstate.ActorRefFromLogic<xstate.PromiseActorLogic<{
673
+ type: "STEP_FAILED";
674
+ error: string;
675
+ stepId: string;
676
+ result?: undefined;
677
+ } | {
678
+ type: "STEP_WAITING";
679
+ stepId: string;
680
+ error?: undefined;
681
+ result?: undefined;
682
+ } | {
683
+ type: "STEP_SUCCESS";
684
+ result: any;
685
+ stepId: string;
686
+ error?: undefined;
687
+ }, ResolverFunctionInput, xstate.EventObject>> | xstate.ActorRefFromLogic<xstate.PromiseActorLogic<{
688
+ steps: {};
689
+ }, {
690
+ parentStepId: string;
691
+ context: WorkflowContext;
692
+ }, xstate.EventObject>> | undefined;
693
+ }, {
694
+ [x: string]: {} | {
695
+ [x: string]: {} | /*elided*/ any | {
696
+ [x: string]: {} | /*elided*/ any | /*elided*/ any;
697
+ };
698
+ } | {
699
+ [x: string]: {} | {
700
+ [x: string]: {} | /*elided*/ any | /*elided*/ any;
701
+ } | /*elided*/ any;
702
+ };
703
+ }, string, xstate.NonReducibleUnknown, xstate.MetaObject, {
704
+ readonly id: string;
705
+ readonly type: "parallel";
706
+ readonly context: ({ input }: {
707
+ spawn: {
708
+ <TSrc extends "conditionCheck" | "resolverFunction" | "spawnSubscriberFunction">(logic: TSrc, ...[options]: ({
709
+ src: "conditionCheck";
710
+ logic: xstate.PromiseActorLogic<{
711
+ type: "CONDITIONS_MET";
712
+ error?: undefined;
713
+ } | {
714
+ type: "CONDITIONS_SKIP_TO_COMPLETED";
715
+ error?: undefined;
716
+ } | {
717
+ type: "CONDITIONS_LIMBO";
718
+ error?: undefined;
719
+ } | {
720
+ type: "CONDITIONS_SKIPPED";
721
+ error?: undefined;
722
+ } | {
723
+ type: "CONDITION_FAILED";
724
+ error: string;
725
+ }, {
726
+ context: WorkflowContext;
727
+ stepNode: StepNode;
728
+ }, xstate.EventObject>;
729
+ id: string | undefined;
730
+ } extends infer T ? T extends {
731
+ src: "conditionCheck";
732
+ logic: xstate.PromiseActorLogic<{
733
+ type: "CONDITIONS_MET";
734
+ error?: undefined;
735
+ } | {
736
+ type: "CONDITIONS_SKIP_TO_COMPLETED";
737
+ error?: undefined;
738
+ } | {
739
+ type: "CONDITIONS_LIMBO";
740
+ error?: undefined;
741
+ } | {
742
+ type: "CONDITIONS_SKIPPED";
743
+ error?: undefined;
744
+ } | {
745
+ type: "CONDITION_FAILED";
746
+ error: string;
747
+ }, {
748
+ context: WorkflowContext;
749
+ stepNode: StepNode;
750
+ }, xstate.EventObject>;
751
+ id: string | undefined;
752
+ } ? T extends {
753
+ src: TSrc;
754
+ } ? xstate.ConditionalRequired<[options?: ({
755
+ id?: T["id"] | undefined;
756
+ systemId?: string;
757
+ input?: xstate.InputFrom<T["logic"]> | undefined;
758
+ syncSnapshot?: boolean;
759
+ } & { [K in xstate.RequiredActorOptions<T>]: unknown; }) | undefined], xstate.IsNotNever<xstate.RequiredActorOptions<T>>> : never : never : never) | ({
760
+ src: "resolverFunction";
761
+ logic: xstate.PromiseActorLogic<{
762
+ type: "STEP_FAILED";
763
+ error: string;
764
+ stepId: string;
765
+ result?: undefined;
766
+ } | {
767
+ type: "STEP_WAITING";
768
+ stepId: string;
769
+ error?: undefined;
770
+ result?: undefined;
771
+ } | {
772
+ type: "STEP_SUCCESS";
773
+ result: any;
774
+ stepId: string;
775
+ error?: undefined;
776
+ }, ResolverFunctionInput, xstate.EventObject>;
777
+ id: string | undefined;
778
+ } extends infer T_1 ? T_1 extends {
779
+ src: "resolverFunction";
780
+ logic: xstate.PromiseActorLogic<{
781
+ type: "STEP_FAILED";
782
+ error: string;
783
+ stepId: string;
784
+ result?: undefined;
785
+ } | {
786
+ type: "STEP_WAITING";
787
+ stepId: string;
788
+ error?: undefined;
789
+ result?: undefined;
790
+ } | {
791
+ type: "STEP_SUCCESS";
792
+ result: any;
793
+ stepId: string;
794
+ error?: undefined;
795
+ }, ResolverFunctionInput, xstate.EventObject>;
796
+ id: string | undefined;
797
+ } ? T_1 extends {
798
+ src: TSrc;
799
+ } ? xstate.ConditionalRequired<[options?: ({
800
+ id?: T_1["id"] | undefined;
801
+ systemId?: string;
802
+ input?: xstate.InputFrom<T_1["logic"]> | undefined;
803
+ syncSnapshot?: boolean;
804
+ } & { [K_1 in xstate.RequiredActorOptions<T_1>]: unknown; }) | undefined], xstate.IsNotNever<xstate.RequiredActorOptions<T_1>>> : never : never : never) | ({
805
+ src: "spawnSubscriberFunction";
806
+ logic: xstate.PromiseActorLogic<{
807
+ steps: {};
808
+ }, {
809
+ parentStepId: string;
810
+ context: WorkflowContext;
811
+ }, xstate.EventObject>;
812
+ id: string | undefined;
813
+ } extends infer T_2 ? T_2 extends {
814
+ src: "spawnSubscriberFunction";
815
+ logic: xstate.PromiseActorLogic<{
816
+ steps: {};
817
+ }, {
818
+ parentStepId: string;
819
+ context: WorkflowContext;
820
+ }, xstate.EventObject>;
821
+ id: string | undefined;
822
+ } ? T_2 extends {
823
+ src: TSrc;
824
+ } ? xstate.ConditionalRequired<[options?: ({
825
+ id?: T_2["id"] | undefined;
826
+ systemId?: string;
827
+ input?: xstate.InputFrom<T_2["logic"]> | undefined;
828
+ syncSnapshot?: boolean;
829
+ } & { [K_2 in xstate.RequiredActorOptions<T_2>]: unknown; }) | undefined], xstate.IsNotNever<xstate.RequiredActorOptions<T_2>>> : never : never : never)): xstate.ActorRefFromLogic<xstate.GetConcreteByKey<xstate.Values<{
830
+ conditionCheck: {
831
+ src: "conditionCheck";
832
+ logic: xstate.PromiseActorLogic<{
833
+ type: "CONDITIONS_MET";
834
+ error?: undefined;
835
+ } | {
836
+ type: "CONDITIONS_SKIP_TO_COMPLETED";
837
+ error?: undefined;
838
+ } | {
839
+ type: "CONDITIONS_LIMBO";
840
+ error?: undefined;
841
+ } | {
842
+ type: "CONDITIONS_SKIPPED";
843
+ error?: undefined;
844
+ } | {
845
+ type: "CONDITION_FAILED";
846
+ error: string;
847
+ }, {
848
+ context: WorkflowContext;
849
+ stepNode: StepNode;
850
+ }, xstate.EventObject>;
851
+ id: string | undefined;
852
+ };
853
+ resolverFunction: {
854
+ src: "resolverFunction";
855
+ logic: xstate.PromiseActorLogic<{
856
+ type: "STEP_FAILED";
857
+ error: string;
858
+ stepId: string;
859
+ result?: undefined;
860
+ } | {
861
+ type: "STEP_WAITING";
862
+ stepId: string;
863
+ error?: undefined;
864
+ result?: undefined;
865
+ } | {
866
+ type: "STEP_SUCCESS";
867
+ result: any;
868
+ stepId: string;
869
+ error?: undefined;
870
+ }, ResolverFunctionInput, xstate.EventObject>;
871
+ id: string | undefined;
872
+ };
873
+ spawnSubscriberFunction: {
874
+ src: "spawnSubscriberFunction";
875
+ logic: xstate.PromiseActorLogic<{
876
+ steps: {};
877
+ }, {
878
+ parentStepId: string;
879
+ context: WorkflowContext;
880
+ }, xstate.EventObject>;
881
+ id: string | undefined;
882
+ };
883
+ }>, "src", TSrc>["logic"]>;
884
+ <TLogic extends xstate.AnyActorLogic>(src: TLogic, ...[options]: xstate.ConditionalRequired<[options?: ({
885
+ id?: never;
886
+ systemId?: string;
887
+ input?: xstate.InputFrom<TLogic> | undefined;
888
+ syncSnapshot?: boolean;
889
+ } & { [K in xstate.RequiredLogicInput<TLogic>]: unknown; }) | undefined], xstate.IsNotNever<xstate.RequiredLogicInput<TLogic>>>): xstate.ActorRefFromLogic<TLogic>;
890
+ };
891
+ input: Omit<WorkflowContext<any, LegacyStep<string, any, any, any>[], Record<string, any>>, "getStepResult">;
892
+ self: xstate.ActorRef<xstate.MachineSnapshot<Omit<WorkflowContext<any, LegacyStep<string, any, any, any>[], Record<string, any>>, "getStepResult">, {
893
+ type: "RESET_TO_PENDING";
894
+ stepId: string;
895
+ } | {
896
+ type: "CONDITIONS_MET";
897
+ stepId: string;
898
+ } | {
899
+ type: "CONDITION_FAILED";
900
+ stepId: string;
901
+ error: string;
902
+ } | {
903
+ type: "SUSPENDED";
904
+ stepId: string;
905
+ suspendPayload?: any;
906
+ softSuspend?: any;
907
+ } | {
908
+ type: "WAITING";
909
+ stepId: string;
910
+ } | {
911
+ type: `xstate.error.actor.${string}`;
912
+ error: Error;
913
+ } | {
914
+ type: `xstate.done.actor.${string}`;
915
+ output: ResolverFunctionOutput;
916
+ }, Record<string, xstate.AnyActorRef | undefined>, xstate.StateValue, string, unknown, any, any>, {
917
+ type: "RESET_TO_PENDING";
918
+ stepId: string;
919
+ } | {
920
+ type: "CONDITIONS_MET";
921
+ stepId: string;
922
+ } | {
923
+ type: "CONDITION_FAILED";
924
+ stepId: string;
925
+ error: string;
926
+ } | {
927
+ type: "SUSPENDED";
928
+ stepId: string;
929
+ suspendPayload?: any;
930
+ softSuspend?: any;
931
+ } | {
932
+ type: "WAITING";
933
+ stepId: string;
934
+ } | {
935
+ type: `xstate.error.actor.${string}`;
936
+ error: Error;
937
+ } | {
938
+ type: `xstate.done.actor.${string}`;
939
+ output: ResolverFunctionOutput;
940
+ }, xstate.AnyEventObject>;
941
+ }) => {
942
+ steps: {
943
+ [x: string]: {
944
+ status: "failed";
945
+ error: string;
946
+ } | {
947
+ status: "waiting";
948
+ } | {
949
+ status: "skipped";
950
+ } | {
951
+ status: "success";
952
+ output: unknown;
953
+ } | {
954
+ status: "suspended";
955
+ suspendPayload?: any;
956
+ output?: unknown;
957
+ } | {
958
+ status: "success";
959
+ output: any;
960
+ } | {
961
+ status: "suspended";
962
+ suspendPayload?: any;
963
+ output?: any;
964
+ };
965
+ };
966
+ mastra?: MastraUnion | undefined;
967
+ attempts: Record<string, number>;
968
+ inputData: Record<string, any>;
969
+ triggerData: any;
970
+ isResume?: {
971
+ runId: string;
972
+ stepId: string;
973
+ } | undefined;
974
+ };
975
+ readonly states: any;
976
+ }> | undefined;
977
+ }
978
+
979
+ interface WorkflowResultReturn<TResult extends z.ZodObject<any>, T extends z.ZodObject<any>, TSteps extends LegacyStep<any, any, any>[]> {
980
+ runId: string;
981
+ start: (props?: {
982
+ triggerData?: z.infer<T>;
983
+ runtimeContext?: RuntimeContext;
984
+ } | undefined) => Promise<LegacyWorkflowRunResult<T, TSteps, TResult>>;
985
+ watch: (onTransition: (state: Pick<LegacyWorkflowRunResult<T, TSteps, TResult>, 'results' | 'activePaths' | 'runId' | 'timestamp'>) => void) => () => void;
986
+ resume: (props: {
987
+ stepId: string;
988
+ context?: Record<string, any>;
989
+ runtimeContext?: RuntimeContext;
990
+ }) => Promise<Omit<LegacyWorkflowRunResult<T, TSteps, TResult>, 'runId'> | undefined>;
991
+ resumeWithEvent: (eventName: string, data: any, runtimeContext?: RuntimeContext) => Promise<Omit<LegacyWorkflowRunResult<T, TSteps, TResult>, 'runId'> | undefined>;
992
+ }
993
+ declare class WorkflowInstance<TSteps extends LegacyStep<any, any, any, any>[] = LegacyStep<any, any, any, any>[], TTriggerSchema extends z.ZodObject<any> = any, TResult extends z.ZodObject<any> = any> implements WorkflowResultReturn<TResult, TTriggerSchema, TSteps> {
994
+ #private;
995
+ name: string;
996
+ logger: IMastraLogger;
997
+ events?: Record<string, {
998
+ schema: z.ZodObject<any>;
999
+ }>;
1000
+ constructor({ name, logger, steps, runId, retryConfig, mastra, stepGraph, stepSubscriberGraph, onFinish, onStepTransition, resultMapping, events, }: {
1001
+ name: string;
1002
+ logger: IMastraLogger;
1003
+ steps: Record<string, StepNode>;
1004
+ mastra?: Mastra;
1005
+ retryConfig?: RetryConfig;
1006
+ runId?: string;
1007
+ stepGraph: StepGraph;
1008
+ stepSubscriberGraph: Record<string, StepGraph>;
1009
+ onFinish?: () => void;
1010
+ onStepTransition?: Set<(state: Pick<LegacyWorkflowRunResult<TTriggerSchema, TSteps, TResult>, 'results' | 'activePaths' | 'runId' | 'timestamp'>) => void | Promise<void>>;
1011
+ resultMapping?: Record<string, {
1012
+ step: StepAction<any, any, any, any>;
1013
+ path: string;
1014
+ }>;
1015
+ events?: Record<string, {
1016
+ schema: z.ZodObject<any>;
1017
+ }>;
1018
+ });
1019
+ setState(state: any): void;
1020
+ get runId(): string;
1021
+ get executionSpan(): Span | undefined;
1022
+ watch(onTransition: (state: Pick<LegacyWorkflowRunResult<TTriggerSchema, TSteps, TResult>, 'results' | 'activePaths' | 'runId' | 'timestamp'>) => void): () => void;
1023
+ start({ triggerData, runtimeContext, }?: {
1024
+ triggerData?: z.infer<TTriggerSchema>;
1025
+ runtimeContext?: RuntimeContext;
1026
+ }): Promise<{
1027
+ runId: string;
1028
+ result?: z.TypeOf<TResult> | undefined;
1029
+ triggerData?: z.TypeOf<TTriggerSchema> | undefined;
1030
+ results: { [K in keyof StepsRecord$1<TSteps>]: StepsRecord$1<TSteps>[K]["outputSchema"] extends undefined ? StepResult$1<unknown> : StepResult$1<z.TypeOf<NonNullable<StepsRecord$1<TSteps>[K]["outputSchema"]>>>; };
1031
+ timestamp: number;
1032
+ activePaths: Map<TSteps[number]["id"], {
1033
+ status: string;
1034
+ suspendPayload?: any;
1035
+ stepPath: string[];
1036
+ }>;
1037
+ }>;
1038
+ private isCompoundDependencyMet;
1039
+ execute({ triggerData, snapshot, stepId, resumeData, runtimeContext, }?: {
1040
+ stepId?: string;
1041
+ triggerData?: z.infer<TTriggerSchema>;
1042
+ snapshot?: Snapshot<any>;
1043
+ resumeData?: any;
1044
+ runtimeContext: RuntimeContext;
1045
+ }): Promise<Omit<LegacyWorkflowRunResult<TTriggerSchema, TSteps, TResult>, 'runId'>>;
1046
+ hasSubscribers(stepId: string): boolean;
1047
+ runMachine(parentStepId: string, input: any, runtimeContext?: RuntimeContext): Promise<(Pick<LegacyWorkflowRunResult<TTriggerSchema, TSteps, TResult>, "runId" | "results" | "timestamp" | "activePaths"> | undefined)[]>;
1048
+ suspend(stepId: string, machine: Machine<TSteps, TTriggerSchema>): Promise<void>;
1049
+ /**
1050
+ * Persists the workflow state to the database
1051
+ */
1052
+ persistWorkflowSnapshot(): Promise<void>;
1053
+ getState(): Promise<LegacyWorkflowRunState | null>;
1054
+ resumeWithEvent(eventName: string, data: any, runtimeContext?: RuntimeContext): Promise<Omit<LegacyWorkflowRunResult<TTriggerSchema, TSteps, TResult>, "runId"> | undefined>;
1055
+ resume({ stepId, context: resumeContext, runtimeContext, }: {
1056
+ stepId: string;
1057
+ context?: Record<string, any>;
1058
+ runtimeContext?: RuntimeContext;
1059
+ }): Promise<Omit<LegacyWorkflowRunResult<TTriggerSchema, TSteps, TResult>, "runId"> | undefined>;
1060
+ _resume({ stepId, context: resumeContext, runtimeContext, }: {
1061
+ stepId: string;
1062
+ context?: Record<string, any>;
1063
+ runtimeContext: RuntimeContext;
1064
+ }): Promise<Omit<LegacyWorkflowRunResult<TTriggerSchema, TSteps, TResult>, "runId"> | undefined>;
1065
+ }
1066
+
1067
+ type WorkflowBuilder<T extends LegacyWorkflow<any, any>> = Pick<T, 'step' | 'then' | 'after' | 'while' | 'until' | 'if' | 'else' | 'afterEvent' | 'commit'>;
1068
+ declare class LegacyWorkflow<TSteps extends LegacyStep<string, any, any>[] = LegacyStep<string, any, any>[], TStepId extends string = string, TTriggerSchema extends z.ZodObject<any> = any, TResultSchema extends z.ZodObject<any> = any> extends MastraBase {
1069
+ #private;
1070
+ name: TStepId;
1071
+ triggerSchema?: TTriggerSchema;
1072
+ resultSchema?: TResultSchema;
1073
+ resultMapping?: Record<string, {
1074
+ step: StepAction<string, any, any, any>;
1075
+ path: string;
1076
+ }>;
1077
+ events?: Record<string, {
1078
+ schema: z.ZodObject<any>;
1079
+ }>;
1080
+ isNested: boolean;
1081
+ /**
1082
+ * Creates a new LegacyWorkflow instance
1083
+ * @param name - Identifier for the workflow (not necessarily unique)
1084
+ * @param logger - Optional logger instance
1085
+ */
1086
+ constructor({ name, triggerSchema, result, retryConfig, mastra, events, }: WorkflowOptions<TStepId, TSteps, TTriggerSchema, TResultSchema>);
1087
+ step<TWorkflow extends LegacyWorkflow<any, any, any, any>, CondStep extends StepVariableType<any, any, any, any>, VarStep extends StepVariableType<any, any, any, any>, Steps extends StepAction<any, any, any, any>[] = TSteps>(next: TWorkflow, config?: StepConfig<ReturnType<TWorkflow['toStep']>, CondStep, VarStep, TTriggerSchema, Steps>): WorkflowBuilder<this>;
1088
+ step<TAgent extends Agent<any, any, any>, CondStep extends StepVariableType<any, any, any, any>, VarStep extends StepVariableType<any, any, any, any>, Steps extends StepAction<any, any, any, any>[] = TSteps>(next: TAgent, config?: StepConfig<ReturnType<TAgent['toStep']>, CondStep, VarStep, TTriggerSchema, Steps>): WorkflowBuilder<this>;
1089
+ step<TStep extends StepAction<any, any, any, any>, CondStep extends StepVariableType<any, any, any, any>, VarStep extends StepVariableType<any, any, any, any>, Steps extends StepAction<any, any, any, any>[] = TSteps>(step: TStep, config?: StepConfig<TStep, CondStep, VarStep, TTriggerSchema, Steps>): WorkflowBuilder<this>;
1090
+ then<TStep extends StepAction<string, any, any, any>, CondStep extends StepVariableType<any, any, any, any>, VarStep extends StepVariableType<any, any, any, any>>(next: TStep | TStep[], config?: StepConfig<TStep, CondStep, VarStep, TTriggerSchema>): this;
1091
+ then<TWorkflow extends LegacyWorkflow<any, any, any, any>, CondStep extends StepVariableType<any, any, any, any>, VarStep extends StepVariableType<any, any, any, any>>(next: TWorkflow | TWorkflow[], config?: StepConfig<StepAction<string, any, any, any>, CondStep, VarStep, TTriggerSchema>): this;
1092
+ then<TAgent extends Agent<any, any, any>, CondStep extends StepVariableType<any, any, any, any>, VarStep extends StepVariableType<any, any, any, any>>(next: TAgent | TAgent[], config?: StepConfig<StepAction<string, any, any, any>, CondStep, VarStep, TTriggerSchema>): this;
1093
+ private loop;
1094
+ while<FallbackStep extends StepAction<string, any, any, any>, CondStep extends StepVariableType<any, any, any, any>, VarStep extends StepVariableType<any, any, any, any>>(condition: StepConfig<FallbackStep, CondStep, VarStep, TTriggerSchema, TSteps>['when'], fallbackStep: FallbackStep, variables?: StepConfig<FallbackStep, CondStep, VarStep, TTriggerSchema, TSteps>['variables']): Pick<WorkflowBuilder<this>, "then" | "commit">;
1095
+ until<FallbackStep extends StepAction<string, any, any, any>, CondStep extends StepVariableType<any, any, any, any>, VarStep extends StepVariableType<any, any, any, any>>(condition: StepConfig<FallbackStep, CondStep, VarStep, TTriggerSchema, TSteps>['when'], fallbackStep: FallbackStep, variables?: StepConfig<FallbackStep, CondStep, VarStep, TTriggerSchema, TSteps>['variables']): Pick<WorkflowBuilder<this>, "then" | "commit">;
1096
+ if<TStep extends StepAction<string, any, any, any>>(condition: StepConfig<TStep, any, any, TTriggerSchema>['when'], ifStep?: TStep | LegacyWorkflow, elseStep?: TStep | LegacyWorkflow): this | WorkflowBuilder<this>;
1097
+ else(): WorkflowBuilder<this>;
1098
+ after<TStep extends StepAction<string, any, any, any>>(steps: string | TStep | TStep[] | (TStep | string)[]): Omit<WorkflowBuilder<this>, 'then' | 'after'>;
1099
+ after<TWorkflow extends LegacyWorkflow<any, any, any, any>>(steps: TWorkflow | TWorkflow[]): Omit<WorkflowBuilder<this>, 'then' | 'after'>;
1100
+ after<TAgent extends Agent<any, any, any>>(steps: TAgent | TAgent[]): Omit<WorkflowBuilder<this>, 'then' | 'after'>;
1101
+ afterEvent(eventName: string): WorkflowBuilder<this>;
1102
+ /**
1103
+ * Executes the workflow with the given trigger data
1104
+ * @param triggerData - Initial data to start the workflow with
1105
+ * @returns Promise resolving to workflow results or rejecting with error
1106
+ * @throws Error if trigger schema validation fails
1107
+ */
1108
+ createRun({ runId, events, }?: {
1109
+ runId?: string;
1110
+ events?: Record<string, {
1111
+ schema: z.ZodObject<any>;
1112
+ }>;
1113
+ }): WorkflowResultReturn<TResultSchema, TTriggerSchema, TSteps>;
1114
+ /**
1115
+ * Gets a workflow run instance by ID
1116
+ * @param runId - ID of the run to retrieve
1117
+ * @returns The workflow run instance if found, undefined otherwise
1118
+ */
1119
+ getRun(runId: string): Promise<WorkflowRun | WorkflowInstance<TSteps, TTriggerSchema, any> | null>;
1120
+ /**
1121
+ * Gets a workflow run instance by ID, from memory
1122
+ * @param runId - ID of the run to retrieve
1123
+ * @returns The workflow run instance if found, undefined otherwise
1124
+ */
1125
+ getMemoryRun(runId: string): WorkflowInstance<TSteps, TTriggerSchema, any> | undefined;
1126
+ /**
1127
+ * Rebuilds the machine with the current steps configuration and validates the workflow
1128
+ *
1129
+ * This is the last step of a workflow builder method chain
1130
+ * @throws Error if validation fails
1131
+ *
1132
+ * @returns this instance for method chaining
1133
+ */
1134
+ commit(): this;
1135
+ getWorkflowRuns(args?: {
1136
+ fromDate?: Date;
1137
+ toDate?: Date;
1138
+ limit?: number;
1139
+ offset?: number;
1140
+ resourceId?: string;
1141
+ }): Promise<LegacyWorkflowRuns>;
1142
+ getExecutionSpan(runId: string): Span | undefined;
1143
+ getState(runId: string): Promise<LegacyWorkflowRunState | null>;
1144
+ resume({ runId, stepId, context: resumeContext, runtimeContext, }: {
1145
+ runId: string;
1146
+ stepId: string;
1147
+ context?: Record<string, any>;
1148
+ runtimeContext: RuntimeContext;
1149
+ }): Promise<Omit<LegacyWorkflowRunResult<TTriggerSchema, TSteps, any>, "runId"> | undefined>;
1150
+ watch(onTransition: (state: Pick<LegacyWorkflowRunResult<TTriggerSchema, TSteps, TResultSchema>, 'results' | 'activePaths' | 'runId' | 'timestamp'>) => void): () => void;
1151
+ resumeWithEvent(runId: string, eventName: string, data: any): Promise<Omit<LegacyWorkflowRunResult<TTriggerSchema, TSteps, any>, "runId"> | undefined>;
1152
+ __registerMastra(mastra: Mastra): void;
1153
+ __registerPrimitives(p: MastraPrimitives): void;
1154
+ get stepGraph(): StepGraph;
1155
+ get stepSubscriberGraph(): Record<string, StepGraph>;
1156
+ get serializedStepGraph(): StepGraph;
1157
+ get serializedStepSubscriberGraph(): Record<string, StepGraph>;
1158
+ get steps(): Record<string, StepAction<string, any, any, any>>;
1159
+ setNested(isNested: boolean): void;
1160
+ toStep(): LegacyStep<TStepId, TTriggerSchema, z.ZodType<LegacyWorkflowRunResult<TTriggerSchema, TSteps, TResultSchema>>, any>;
1161
+ }
1162
+
1163
+ type ExecuteFunction<TStepInput, TStepOutput, TResumeSchema, TSuspendSchema, EngineType> = (params: {
1164
+ runId: string;
1165
+ mastra: Mastra;
1166
+ runtimeContext: RuntimeContext;
1167
+ inputData: TStepInput;
1168
+ resumeData?: TResumeSchema;
1169
+ runCount: number;
1170
+ getInitData<T extends z.ZodType<any>>(): z.infer<T>;
1171
+ getInitData<T extends Workflow<any, any, any, any, any>>(): T extends undefined ? unknown : z.infer<NonNullable<T['inputSchema']>>;
1172
+ getStepResult<T extends Step<any, any, any>>(stepId: T): T['outputSchema'] extends undefined ? unknown : z.infer<NonNullable<T['outputSchema']>>;
1173
+ suspend(suspendPayload: TSuspendSchema): Promise<any>;
1174
+ bail(result: any): any;
1175
+ abort(): any;
1176
+ resume?: {
1177
+ steps: string[];
1178
+ resumePayload: any;
1179
+ };
1180
+ [EMITTER_SYMBOL]: Emitter;
1181
+ engine: EngineType;
1182
+ abortSignal: AbortSignal;
1183
+ }) => Promise<TStepOutput>;
1184
+ interface Step<TStepId extends string = string, TSchemaIn extends z.ZodType<any> = z.ZodType<any>, TSchemaOut extends z.ZodType<any> = z.ZodType<any>, TResumeSchema extends z.ZodType<any> = z.ZodType<any>, TSuspendSchema extends z.ZodType<any> = z.ZodType<any>, TEngineType = any> {
1185
+ id: TStepId;
1186
+ description?: string;
1187
+ inputSchema: TSchemaIn;
1188
+ outputSchema: TSchemaOut;
1189
+ resumeSchema?: TResumeSchema;
1190
+ suspendSchema?: TSuspendSchema;
1191
+ execute: ExecuteFunction<z.infer<TSchemaIn>, z.infer<TSchemaOut>, z.infer<TResumeSchema>, z.infer<TSuspendSchema>, TEngineType>;
1192
+ retries?: number;
1193
+ }
1194
+
1195
+ type Emitter = {
1196
+ emit: (event: string, data: any) => Promise<void>;
1197
+ on: (event: string, callback: (data: any) => void) => void;
1198
+ off: (event: string, callback: (data: any) => void) => void;
1199
+ once: (event: string, callback: (data: any) => void) => void;
1200
+ };
1201
+ type StepSuccess<P, R, S, T> = {
1202
+ status: 'success';
1203
+ output: T;
1204
+ payload: P;
1205
+ resumePayload?: R;
1206
+ suspendPayload?: S;
1207
+ startedAt: number;
1208
+ endedAt: number;
1209
+ suspendedAt?: number;
1210
+ resumedAt?: number;
1211
+ };
1212
+ type StepFailure<P, R, S> = {
1213
+ status: 'failed';
1214
+ error: string | Error;
1215
+ payload: P;
1216
+ resumePayload?: R;
1217
+ suspendPayload?: S;
1218
+ startedAt: number;
1219
+ endedAt: number;
1220
+ suspendedAt?: number;
1221
+ resumedAt?: number;
1222
+ };
1223
+ type StepSuspended<P, S> = {
1224
+ status: 'suspended';
1225
+ payload: P;
1226
+ suspendPayload?: S;
1227
+ startedAt: number;
1228
+ suspendedAt: number;
1229
+ };
1230
+ type StepRunning<P, R, S> = {
1231
+ status: 'running';
1232
+ payload: P;
1233
+ resumePayload?: R;
1234
+ suspendPayload?: S;
1235
+ startedAt: number;
1236
+ suspendedAt?: number;
1237
+ resumedAt?: number;
1238
+ };
1239
+ type StepWaiting<P, R, S> = {
1240
+ status: 'waiting';
1241
+ payload: P;
1242
+ suspendPayload?: S;
1243
+ resumePayload?: R;
1244
+ startedAt: number;
1245
+ };
1246
+ type StepResult<P, R, S, T> = StepSuccess<P, R, S, T> | StepFailure<P, R, S> | StepSuspended<P, S> | StepRunning<P, R, S> | StepWaiting<P, R, S>;
1247
+ type StepsRecord<T extends readonly Step<any, any, any>[]> = {
1248
+ [K in T[number]['id']]: Extract<T[number], {
1249
+ id: K;
1250
+ }>;
1251
+ };
1252
+ type DynamicMapping<TPrevSchema extends z.ZodTypeAny, TSchemaOut extends z.ZodTypeAny> = {
1253
+ fn: ExecuteFunction<z.infer<TPrevSchema>, z.infer<TSchemaOut>, any, any, any>;
1254
+ schema: TSchemaOut;
1255
+ };
1256
+ type PathsToStringProps<T> = T extends z.ZodObject<infer V> ? PathsToStringProps<V> : T extends object ? {
1257
+ [K in keyof T]: T[K] extends object ? K extends string ? K | `${K}.${PathsToStringProps<T[K]>}` : never : K extends string ? K : never;
1258
+ }[keyof T] : never;
1259
+ type ExtractSchemaType<T extends z.ZodType<any>> = T extends z.ZodObject<infer V> ? V : never;
1260
+ type ExtractSchemaFromStep<TStep extends Step<any, any, any>, TKey extends 'inputSchema' | 'outputSchema'> = TStep[TKey];
1261
+ type VariableReference<TStep extends Step<string, any, any> = Step<string, any, any>, TVarPath extends PathsToStringProps<ExtractSchemaType<ExtractSchemaFromStep<TStep, 'outputSchema'>>> | '' | '.' = PathsToStringProps<ExtractSchemaType<ExtractSchemaFromStep<TStep, 'outputSchema'>>> | '' | '.'> = {
1262
+ step: TStep;
1263
+ path: TVarPath;
1264
+ } | {
1265
+ value: any;
1266
+ schema: z.ZodTypeAny;
1267
+ };
1268
+ type StreamEvent = TextStreamPart<any> | {
1269
+ type: 'step-suspended';
1270
+ payload: any;
1271
+ id: string;
1272
+ } | {
1273
+ type: 'step-waiting';
1274
+ payload: any;
1275
+ id: string;
1276
+ };
1277
+ type WorkflowRunStatus = 'running' | 'success' | 'failed' | 'suspended' | 'waiting' | 'pending' | 'canceled';
1278
+ type WatchEvent = {
1279
+ type: 'watch';
1280
+ payload: {
1281
+ currentStep?: {
1282
+ id: string;
1283
+ status: WorkflowRunStatus;
1284
+ output?: Record<string, any>;
1285
+ resumePayload?: Record<string, any>;
1286
+ payload?: Record<string, any>;
1287
+ error?: string | Error;
1288
+ };
1289
+ workflowState: {
1290
+ status: WorkflowRunStatus;
1291
+ steps: Record<string, {
1292
+ status: WorkflowRunStatus;
1293
+ output?: Record<string, any>;
1294
+ payload?: Record<string, any>;
1295
+ resumePayload?: Record<string, any>;
1296
+ error?: string | Error;
1297
+ startedAt: number;
1298
+ endedAt: number;
1299
+ suspendedAt?: number;
1300
+ resumedAt?: number;
1301
+ }>;
1302
+ result?: Record<string, any>;
1303
+ payload?: Record<string, any>;
1304
+ error?: string | Error;
1305
+ };
1306
+ };
1307
+ eventTimestamp: Date;
1308
+ };
1309
+ type ZodPathType<T extends z.ZodTypeAny, P extends string> = T extends z.ZodObject<infer Shape> ? P extends `${infer Key}.${infer Rest}` ? Key extends keyof Shape ? Shape[Key] extends z.ZodTypeAny ? ZodPathType<Shape[Key], Rest> : never : never : P extends keyof Shape ? Shape[P] : never : never;
1310
+ interface WorkflowRunState {
1311
+ runId: string;
1312
+ status: WorkflowRunStatus;
1313
+ result?: Record<string, any>;
1314
+ error?: string | Error;
1315
+ runtimeContext?: Record<string, any>;
1316
+ value: Record<string, string>;
1317
+ context: {
1318
+ input?: Record<string, any>;
1319
+ } & Record<string, StepResult<any, any, any, any>>;
1320
+ serializedStepGraph: SerializedStepFlowEntry[];
1321
+ activePaths: Array<unknown>;
1322
+ suspendedPaths: Record<string, number[]>;
1323
+ timestamp: number;
1324
+ }
1325
+
1326
+ /**
1327
+ * Represents an execution graph for a workflow
1328
+ */
1329
+ interface ExecutionGraph<TEngineType = any> {
1330
+ id: string;
1331
+ steps: StepFlowEntry<TEngineType>[];
1332
+ }
1333
+ /**
1334
+ * Execution engine abstract class for building and executing workflow graphs
1335
+ * Providers will implement this class to provide their own execution logic
1336
+ */
1337
+ declare abstract class ExecutionEngine extends MastraBase {
1338
+ protected mastra?: Mastra;
1339
+ constructor({ mastra }: {
1340
+ mastra?: Mastra;
1341
+ });
1342
+ __registerMastra(mastra: Mastra): void;
1343
+ /**
1344
+ * Executes a workflow run with the provided execution graph and input
1345
+ * @param graph The execution graph to execute
1346
+ * @param input The input data for the workflow
1347
+ * @returns A promise that resolves to the workflow output
1348
+ */
1349
+ abstract execute<TInput, TOutput>(params: {
1350
+ workflowId: string;
1351
+ runId: string;
1352
+ graph: ExecutionGraph;
1353
+ serializedStepGraph: SerializedStepFlowEntry[];
1354
+ input?: TInput;
1355
+ resume?: {
1356
+ steps: string[];
1357
+ stepResults: Record<string, StepResult<any, any, any, any>>;
1358
+ resumePayload: any;
1359
+ resumePath: number[];
1360
+ snapshotRuntimeContext?: Record<string, any>;
1361
+ };
1362
+ emitter: Emitter;
1363
+ runtimeContext: RuntimeContext;
1364
+ retryConfig?: {
1365
+ attempts?: number;
1366
+ delay?: number;
1367
+ };
1368
+ abortController: AbortController;
1369
+ }): Promise<TOutput>;
1370
+ }
1371
+
1372
+ type DefaultEngineType = {};
1373
+ type StepFlowEntry<TEngineType = DefaultEngineType> = {
1374
+ type: 'step';
1375
+ step: Step;
1376
+ } | {
1377
+ type: 'sleep';
1378
+ id: string;
1379
+ duration?: number;
1380
+ fn?: ExecuteFunction<any, any, any, any, TEngineType>;
1381
+ } | {
1382
+ type: 'sleepUntil';
1383
+ id: string;
1384
+ date?: Date;
1385
+ fn?: ExecuteFunction<any, any, any, any, TEngineType>;
1386
+ } | {
1387
+ type: 'waitForEvent';
1388
+ event: string;
1389
+ step: Step;
1390
+ timeout?: number;
1391
+ } | {
1392
+ type: 'parallel';
1393
+ steps: StepFlowEntry[];
1394
+ } | {
1395
+ type: 'conditional';
1396
+ steps: StepFlowEntry[];
1397
+ conditions: ExecuteFunction<any, any, any, any, TEngineType>[];
1398
+ serializedConditions: {
1399
+ id: string;
1400
+ fn: string;
1401
+ }[];
1402
+ } | {
1403
+ type: 'loop';
1404
+ step: Step;
1405
+ condition: ExecuteFunction<any, any, any, any, TEngineType>;
1406
+ serializedCondition: {
1407
+ id: string;
1408
+ fn: string;
1409
+ };
1410
+ loopType: 'dowhile' | 'dountil';
1411
+ } | {
1412
+ type: 'foreach';
1413
+ step: Step;
1414
+ opts: {
1415
+ concurrency: number;
1416
+ };
1417
+ };
1418
+ type SerializedStep<TEngineType = DefaultEngineType> = Pick<Step<any, any, any, any, any, TEngineType>, 'id' | 'description'> & {
1419
+ component?: string;
1420
+ serializedStepFlow?: SerializedStepFlowEntry[];
1421
+ mapConfig?: string;
1422
+ };
1423
+ type SerializedStepFlowEntry = {
1424
+ type: 'step';
1425
+ step: SerializedStep;
1426
+ } | {
1427
+ type: 'sleep';
1428
+ id: string;
1429
+ duration?: number;
1430
+ fn?: string;
1431
+ } | {
1432
+ type: 'sleepUntil';
1433
+ id: string;
1434
+ date?: Date;
1435
+ fn?: string;
1436
+ } | {
1437
+ type: 'waitForEvent';
1438
+ event: string;
1439
+ step: SerializedStep;
1440
+ timeout?: number;
1441
+ } | {
1442
+ type: 'parallel';
1443
+ steps: SerializedStepFlowEntry[];
1444
+ } | {
1445
+ type: 'conditional';
1446
+ steps: SerializedStepFlowEntry[];
1447
+ serializedConditions: {
1448
+ id: string;
1449
+ fn: string;
1450
+ }[];
1451
+ } | {
1452
+ type: 'loop';
1453
+ step: SerializedStep;
1454
+ serializedCondition: {
1455
+ id: string;
1456
+ fn: string;
1457
+ };
1458
+ loopType: 'dowhile' | 'dountil';
1459
+ } | {
1460
+ type: 'foreach';
1461
+ step: SerializedStep;
1462
+ opts: {
1463
+ concurrency: number;
1464
+ };
1465
+ };
1466
+ type StepWithComponent = Step<string, any, any, any, any, any> & {
1467
+ component?: string;
1468
+ steps?: Record<string, StepWithComponent>;
1469
+ };
1470
+ declare function mapVariable<TStep extends Step<string, any, any, any, any, any>>({ step, path, }: {
1471
+ step: TStep;
1472
+ path: PathsToStringProps<ExtractSchemaType<ExtractSchemaFromStep<TStep, 'outputSchema'>>> | '.';
1473
+ }): {
1474
+ step: TStep;
1475
+ path: PathsToStringProps<ExtractSchemaType<ExtractSchemaFromStep<TStep, 'outputSchema'>>> | '.';
1476
+ };
1477
+ declare function mapVariable<TWorkflow extends Workflow<any, any, any, any, any, any>>({ initData: TWorkflow, path, }: {
1478
+ initData: TWorkflow;
1479
+ path: PathsToStringProps<ExtractSchemaType<ExtractSchemaFromStep<TWorkflow, 'inputSchema'>>> | '.';
1480
+ }): {
1481
+ initData: TWorkflow;
1482
+ path: PathsToStringProps<ExtractSchemaType<ExtractSchemaFromStep<TWorkflow, 'inputSchema'>>> | '.';
1483
+ };
1484
+ /**
1485
+ * Creates a new workflow step
1486
+ * @param params Configuration parameters for the step
1487
+ * @param params.id Unique identifier for the step
1488
+ * @param params.description Optional description of what the step does
1489
+ * @param params.inputSchema Zod schema defining the input structure
1490
+ * @param params.outputSchema Zod schema defining the output structure
1491
+ * @param params.execute Function that performs the step's operations
1492
+ * @returns A Step object that can be added to the workflow
1493
+ */
1494
+ declare function createStep<TStepId extends string, TStepInput extends z.ZodType<any>, TStepOutput extends z.ZodType<any>, TResumeSchema extends z.ZodType<any>, TSuspendSchema extends z.ZodType<any>>(params: {
1495
+ id: TStepId;
1496
+ description?: string;
1497
+ inputSchema: TStepInput;
1498
+ outputSchema: TStepOutput;
1499
+ resumeSchema?: TResumeSchema;
1500
+ suspendSchema?: TSuspendSchema;
1501
+ retries?: number;
1502
+ execute: ExecuteFunction<z.infer<TStepInput>, z.infer<TStepOutput>, z.infer<TResumeSchema>, z.infer<TSuspendSchema>, DefaultEngineType>;
1503
+ }): Step<TStepId, TStepInput, TStepOutput, TResumeSchema, TSuspendSchema, DefaultEngineType>;
1504
+ declare function createStep<TStepId extends string, TStepInput extends z.ZodObject<{
1505
+ prompt: z.ZodString;
1506
+ }>, TStepOutput extends z.ZodObject<{
1507
+ text: z.ZodString;
1508
+ }>, TResumeSchema extends z.ZodType<any>, TSuspendSchema extends z.ZodType<any>>(agent: Agent<TStepId, any, any>): Step<TStepId, TStepInput, TStepOutput, TResumeSchema, TSuspendSchema, DefaultEngineType>;
1509
+ declare function createStep<TSchemaIn extends z.ZodType<any>, TSchemaOut extends z.ZodType<any>, TContext extends ToolExecutionContext<TSchemaIn>>(tool: Tool$1<TSchemaIn, TSchemaOut, TContext> & {
1510
+ inputSchema: TSchemaIn;
1511
+ outputSchema: TSchemaOut;
1512
+ execute: (context: TContext) => Promise<any>;
1513
+ }): Step<string, TSchemaIn, TSchemaOut, z.ZodType<any>, z.ZodType<any>, DefaultEngineType>;
1514
+ declare function cloneStep<TStepId extends string>(step: Step<string, any, any, any, any, DefaultEngineType>, opts: {
1515
+ id: TStepId;
1516
+ }): Step<TStepId, any, any, any, any, DefaultEngineType>;
1517
+ declare function createWorkflow<TWorkflowId extends string = string, TInput extends z.ZodType<any> = z.ZodType<any>, TOutput extends z.ZodType<any> = z.ZodType<any>, TSteps extends Step<string, any, any, any, any, DefaultEngineType>[] = Step<string, any, any, any, any, DefaultEngineType>[]>(params: WorkflowConfig<TWorkflowId, TInput, TOutput, TSteps>): Workflow<DefaultEngineType, TSteps, TWorkflowId, TInput, TOutput, TInput>;
1518
+ declare function cloneWorkflow<TWorkflowId extends string = string, TInput extends z.ZodType<any> = z.ZodType<any>, TOutput extends z.ZodType<any> = z.ZodType<any>, TSteps extends Step<string, any, any, any, any, DefaultEngineType>[] = Step<string, any, any, any, any, DefaultEngineType>[], TPrevSchema extends z.ZodType<any> = TInput>(workflow: Workflow<DefaultEngineType, TSteps, string, TInput, TOutput, TPrevSchema>, opts: {
1519
+ id: TWorkflowId;
1520
+ }): Workflow<DefaultEngineType, TSteps, TWorkflowId, TInput, TOutput, TPrevSchema>;
1521
+ type WorkflowResult<TOutput extends z.ZodType<any>, TSteps extends Step<string, any, any>[]> = {
1522
+ status: 'success';
1523
+ result: z.infer<TOutput>;
1524
+ steps: {
1525
+ [K in keyof StepsRecord<TSteps>]: StepsRecord<TSteps>[K]['outputSchema'] extends undefined ? StepResult<unknown, unknown, unknown, unknown> : StepResult<z.infer<NonNullable<StepsRecord<TSteps>[K]['inputSchema']>>, z.infer<NonNullable<StepsRecord<TSteps>[K]['resumeSchema']>>, z.infer<NonNullable<StepsRecord<TSteps>[K]['suspendSchema']>>, z.infer<NonNullable<StepsRecord<TSteps>[K]['outputSchema']>>>;
1526
+ };
1527
+ } | {
1528
+ status: 'failed';
1529
+ steps: {
1530
+ [K in keyof StepsRecord<TSteps>]: StepsRecord<TSteps>[K]['outputSchema'] extends undefined ? StepResult<unknown, unknown, unknown, unknown> : StepResult<z.infer<NonNullable<StepsRecord<TSteps>[K]['inputSchema']>>, z.infer<NonNullable<StepsRecord<TSteps>[K]['resumeSchema']>>, z.infer<NonNullable<StepsRecord<TSteps>[K]['suspendSchema']>>, z.infer<NonNullable<StepsRecord<TSteps>[K]['outputSchema']>>>;
1531
+ };
1532
+ error: Error;
1533
+ } | {
1534
+ status: 'suspended';
1535
+ steps: {
1536
+ [K in keyof StepsRecord<TSteps>]: StepsRecord<TSteps>[K]['outputSchema'] extends undefined ? StepResult<unknown, unknown, unknown, unknown> : StepResult<z.infer<NonNullable<StepsRecord<TSteps>[K]['inputSchema']>>, z.infer<NonNullable<StepsRecord<TSteps>[K]['resumeSchema']>>, z.infer<NonNullable<StepsRecord<TSteps>[K]['suspendSchema']>>, z.infer<NonNullable<StepsRecord<TSteps>[K]['outputSchema']>>>;
1537
+ };
1538
+ suspended: [string[], ...string[][]];
1539
+ };
1540
+ type WorkflowConfig<TWorkflowId extends string = string, TInput extends z.ZodType<any> = z.ZodType<any>, TOutput extends z.ZodType<any> = z.ZodType<any>, TSteps extends Step<string, any, any, any, any, any>[] = Step<string, any, any, any, any, any>[]> = {
1541
+ mastra?: Mastra;
1542
+ id: TWorkflowId;
1543
+ description?: string | undefined;
1544
+ inputSchema: TInput;
1545
+ outputSchema: TOutput;
1546
+ executionEngine?: ExecutionEngine;
1547
+ steps?: TSteps;
1548
+ retryConfig?: {
1549
+ attempts?: number;
1550
+ delay?: number;
1551
+ };
1552
+ };
1553
+ declare class Workflow<TEngineType = any, TSteps extends Step<string, any, any, any, any, TEngineType>[] = Step<string, any, any, any, any, TEngineType>[], TWorkflowId extends string = string, TInput extends z.ZodType<any> = z.ZodType<any>, TOutput extends z.ZodType<any> = z.ZodType<any>, TPrevSchema extends z.ZodType<any> = TInput> extends MastraBase implements Step<TWorkflowId, TInput, TOutput, any, any, DefaultEngineType> {
1554
+ #private;
1555
+ id: TWorkflowId;
1556
+ description?: string | undefined;
1557
+ inputSchema: TInput;
1558
+ outputSchema: TOutput;
1559
+ steps: Record<string, StepWithComponent>;
1560
+ stepDefs?: TSteps;
1561
+ protected stepFlow: StepFlowEntry<TEngineType>[];
1562
+ protected serializedStepFlow: SerializedStepFlowEntry[];
1563
+ protected executionEngine: ExecutionEngine;
1564
+ protected executionGraph: ExecutionGraph;
1565
+ protected retryConfig: {
1566
+ attempts?: number;
1567
+ delay?: number;
1568
+ };
1569
+ constructor({ mastra, id, inputSchema, outputSchema, description, executionEngine, retryConfig, steps, }: WorkflowConfig<TWorkflowId, TInput, TOutput, TSteps>);
1570
+ get runs(): Map<string, Run<TEngineType, TSteps, TInput, TOutput>>;
1571
+ get mastra(): Mastra<Record<string, Agent<any, ToolsInput, Record<string, Metric>>>, Record<string, LegacyWorkflow<LegacyStep<string, any, any, StepExecutionContext<any, WorkflowContext<any, LegacyStep<string, any, any, any>[], Record<string, any>>>>[], string, any, any>>, Record<string, Workflow<any, Step<string, any, any, any, any, any>[], string, z.ZodType<any, z.ZodTypeDef, any>, z.ZodType<any, z.ZodTypeDef, any>, z.ZodType<any, z.ZodTypeDef, any>>>, Record<string, MastraVector<VectorFilter>>, Record<string, MastraTTS>, IMastraLogger, Record<string, AgentNetwork>, Record<string, NewAgentNetwork>, Record<string, MCPServerBase>> | undefined;
1572
+ __registerMastra(mastra: Mastra): void;
1573
+ __registerPrimitives(p: MastraPrimitives): void;
1574
+ setStepFlow(stepFlow: StepFlowEntry<TEngineType>[]): void;
1575
+ /**
1576
+ * Adds a step to the workflow
1577
+ * @param step The step to add to the workflow
1578
+ * @returns The workflow instance for chaining
1579
+ */
1580
+ then<TStepInputSchema extends TPrevSchema, TStepId extends string, TSchemaOut extends z.ZodType<any>>(step: Step<TStepId, TStepInputSchema, TSchemaOut, any, any, TEngineType>): Workflow<TEngineType, TSteps, TWorkflowId, TInput, TOutput, TSchemaOut>;
1581
+ /**
1582
+ * Adds a sleep step to the workflow
1583
+ * @param duration The duration to sleep for
1584
+ * @returns The workflow instance for chaining
1585
+ */
1586
+ sleep(duration: number | ExecuteFunction<z.infer<TPrevSchema>, number, any, any, TEngineType>): Workflow<TEngineType, TSteps, TWorkflowId, TInput, TOutput, TPrevSchema>;
1587
+ /**
1588
+ * Adds a sleep until step to the workflow
1589
+ * @param date The date to sleep until
1590
+ * @returns The workflow instance for chaining
1591
+ */
1592
+ sleepUntil(date: Date | ExecuteFunction<z.infer<TPrevSchema>, Date, any, any, TEngineType>): Workflow<TEngineType, TSteps, TWorkflowId, TInput, TOutput, TPrevSchema>;
1593
+ waitForEvent<TStepInputSchema extends TPrevSchema, TStepId extends string, TSchemaOut extends z.ZodType<any>>(event: string, step: Step<TStepId, TStepInputSchema, TSchemaOut, any, any, TEngineType>, opts?: {
1594
+ timeout?: number;
1595
+ }): Workflow<TEngineType, TSteps, TWorkflowId, TInput, TOutput, TSchemaOut>;
1596
+ map(mappingConfig: {
1597
+ [k: string]: {
1598
+ step: Step<string, any, any, any, any, TEngineType> | Step<string, any, any, any, any, TEngineType>[];
1599
+ path: string;
1600
+ } | {
1601
+ value: any;
1602
+ schema: z.ZodType<any>;
1603
+ } | {
1604
+ initData: Workflow<TEngineType, any, any, any, any, any>;
1605
+ path: string;
1606
+ } | {
1607
+ runtimeContextPath: string;
1608
+ schema: z.ZodType<any>;
1609
+ } | DynamicMapping<TPrevSchema, z.ZodType<any>>;
1610
+ } | ExecuteFunction<z.infer<TPrevSchema>, any, any, any, TEngineType>): Workflow<TEngineType, TSteps, TWorkflowId, TInput, TOutput, any>;
1611
+ parallel<TParallelSteps extends Step<string, TPrevSchema, any, any, any, TEngineType>[]>(steps: TParallelSteps): Workflow<TEngineType, TSteps, TWorkflowId, TInput, TOutput, z.ZodObject<{ [K in keyof StepsRecord<TParallelSteps>]: StepsRecord<TParallelSteps>[K]["outputSchema"]; }, any, z.ZodTypeAny>>;
1612
+ branch<TBranchSteps extends Array<[
1613
+ ExecuteFunction<z.infer<TPrevSchema>, any, any, any, TEngineType>,
1614
+ Step<string, TPrevSchema, any, any, any, TEngineType>
1615
+ ]>>(steps: TBranchSteps): Workflow<TEngineType, TSteps, TWorkflowId, TInput, TOutput, z.ZodObject<{ [K in keyof StepsRecord<{ [K_1 in keyof TBranchSteps]: TBranchSteps[K_1][1]; }[number][]>]: StepsRecord<{ [K_1 in keyof TBranchSteps]: TBranchSteps[K_1][1]; }[number][]>[K]["outputSchema"]; }, any, z.ZodTypeAny>>;
1616
+ dowhile<TStepInputSchema extends TPrevSchema, TStepId extends string, TSchemaOut extends z.ZodType<any>>(step: Step<TStepId, TStepInputSchema, TSchemaOut, any, any, TEngineType>, condition: ExecuteFunction<z.infer<TSchemaOut>, any, any, any, TEngineType>): Workflow<TEngineType, TSteps, TWorkflowId, TInput, TOutput, TSchemaOut>;
1617
+ dountil<TStepInputSchema extends TPrevSchema, TStepId extends string, TSchemaOut extends z.ZodType<any>>(step: Step<TStepId, TStepInputSchema, TSchemaOut, any, any, TEngineType>, condition: ExecuteFunction<z.infer<TSchemaOut>, any, any, any, TEngineType>): Workflow<TEngineType, TSteps, TWorkflowId, TInput, TOutput, TSchemaOut>;
1618
+ foreach<TPrevIsArray extends TPrevSchema extends z.ZodArray<any> ? true : false, TStepInputSchema extends TPrevSchema extends z.ZodArray<infer TElement> ? TElement : never, TStepId extends string, TSchemaOut extends z.ZodType<any>>(step: TPrevIsArray extends true ? Step<TStepId, TStepInputSchema, TSchemaOut, any, any, TEngineType> : 'Previous step must return an array type', opts?: {
1619
+ concurrency: number;
1620
+ }): Workflow<TEngineType, TSteps, TWorkflowId, TInput, TOutput, z.ZodArray<TSchemaOut>>;
1621
+ /**
1622
+ * Builds the execution graph for this workflow
1623
+ * @returns The execution graph that can be used to execute the workflow
1624
+ */
1625
+ buildExecutionGraph(): ExecutionGraph;
1626
+ /**
1627
+ * Finalizes the workflow definition and prepares it for execution
1628
+ * This method should be called after all steps have been added to the workflow
1629
+ * @returns A built workflow instance ready for execution
1630
+ */
1631
+ commit(): Workflow<TEngineType, TSteps, TWorkflowId, TInput, TOutput, TOutput>;
1632
+ get stepGraph(): StepFlowEntry<TEngineType>[];
1633
+ get serializedStepGraph(): SerializedStepFlowEntry[];
1634
+ /**
1635
+ * Creates a new workflow run instance
1636
+ * @param options Optional configuration for the run
1637
+ * @returns A Run instance that can be used to execute the workflow
1638
+ */
1639
+ createRun(options?: {
1640
+ runId?: string;
1641
+ }): Run<TEngineType, TSteps, TInput, TOutput>;
1642
+ /**
1643
+ * Creates a new workflow run instance and stores a snapshot of the workflow in the storage
1644
+ * @param options Optional configuration for the run
1645
+ * @returns A Run instance that can be used to execute the workflow
1646
+ */
1647
+ createRunAsync(options?: {
1648
+ runId?: string;
1649
+ }): Promise<Run<TEngineType, TSteps, TInput, TOutput>>;
1650
+ execute({ inputData, resumeData, suspend, resume, [EMITTER_SYMBOL]: emitter, mastra, runtimeContext, abort, abortSignal, runCount, }: {
1651
+ inputData: z.infer<TInput>;
1652
+ resumeData?: any;
1653
+ getStepResult<T extends Step<any, any, any, any, any, TEngineType>>(stepId: T): T['outputSchema'] extends undefined ? unknown : z.infer<NonNullable<T['outputSchema']>>;
1654
+ suspend: (suspendPayload: any) => Promise<any>;
1655
+ resume?: {
1656
+ steps: string[];
1657
+ resumePayload: any;
1658
+ runId?: string;
1659
+ };
1660
+ [EMITTER_SYMBOL]: {
1661
+ emit: (event: string, data: any) => void;
1662
+ };
1663
+ mastra: Mastra;
1664
+ runtimeContext?: RuntimeContext;
1665
+ engine: DefaultEngineType;
1666
+ abortSignal: AbortSignal;
1667
+ bail: (result: any) => any;
1668
+ abort: () => any;
1669
+ runCount?: number;
1670
+ }): Promise<z.infer<TOutput>>;
1671
+ getWorkflowRuns(args?: {
1672
+ fromDate?: Date;
1673
+ toDate?: Date;
1674
+ limit?: number;
1675
+ offset?: number;
1676
+ resourceId?: string;
1677
+ }): Promise<WorkflowRuns>;
1678
+ getWorkflowRunById(runId: string): Promise<WorkflowRun | null>;
1679
+ getWorkflowRunExecutionResult(runId: string): Promise<WatchEvent['payload']['workflowState'] | null>;
1680
+ }
1681
+ /**
1682
+ * Represents a workflow run that can be executed
1683
+ */
1684
+ declare class Run<TEngineType = any, TSteps extends Step<string, any, any, any, any, TEngineType>[] = Step<string, any, any, any, any, TEngineType>[], TInput extends z.ZodType<any> = z.ZodType<any>, TOutput extends z.ZodType<any> = z.ZodType<any>> {
1685
+ #private;
1686
+ abortController: AbortController;
1687
+ protected emitter: EventEmitter$1;
1688
+ /**
1689
+ * Unique identifier for this workflow
1690
+ */
1691
+ readonly workflowId: string;
1692
+ /**
1693
+ * Unique identifier for this run
1694
+ */
1695
+ readonly runId: string;
1696
+ /**
1697
+ * Internal state of the workflow run
1698
+ */
1699
+ protected state: Record<string, any>;
1700
+ /**
1701
+ * The execution engine for this run
1702
+ */
1703
+ executionEngine: ExecutionEngine;
1704
+ /**
1705
+ * The execution graph for this run
1706
+ */
1707
+ executionGraph: ExecutionGraph;
1708
+ /**
1709
+ * The serialized step graph for this run
1710
+ */
1711
+ serializedStepGraph: SerializedStepFlowEntry[];
1712
+ protected closeStreamAction?: () => Promise<void>;
1713
+ protected executionResults?: Promise<WorkflowResult<TOutput, TSteps>>;
1714
+ protected cleanup?: () => void;
1715
+ protected retryConfig?: {
1716
+ attempts?: number;
1717
+ delay?: number;
1718
+ };
1719
+ constructor(params: {
1720
+ workflowId: string;
1721
+ runId: string;
1722
+ executionEngine: ExecutionEngine;
1723
+ executionGraph: ExecutionGraph;
1724
+ mastra?: Mastra;
1725
+ retryConfig?: {
1726
+ attempts?: number;
1727
+ delay?: number;
1728
+ };
1729
+ cleanup?: () => void;
1730
+ serializedStepGraph: SerializedStepFlowEntry[];
1731
+ });
1732
+ /**
1733
+ * Cancels the workflow execution
1734
+ */
1735
+ cancel(): Promise<void>;
1736
+ sendEvent(event: string, data: any): Promise<void>;
1737
+ /**
1738
+ * Starts the workflow execution with the provided input
1739
+ * @param input The input data for the workflow
1740
+ * @returns A promise that resolves to the workflow output
1741
+ */
1742
+ start({ inputData, runtimeContext, }: {
1743
+ inputData?: z.infer<TInput>;
1744
+ runtimeContext?: RuntimeContext;
1745
+ }): Promise<WorkflowResult<TOutput, TSteps>>;
1746
+ /**
1747
+ * Starts the workflow execution with the provided input as a stream
1748
+ * @param input The input data for the workflow
1749
+ * @returns A promise that resolves to the workflow output
1750
+ */
1751
+ stream({ inputData, runtimeContext }?: {
1752
+ inputData?: z.infer<TInput>;
1753
+ runtimeContext?: RuntimeContext;
1754
+ }): {
1755
+ stream: ReadableStream<StreamEvent>;
1756
+ getWorkflowState: () => Promise<WorkflowResult<TOutput, TSteps>>;
1757
+ };
1758
+ watch(cb: (event: WatchEvent) => void, type?: 'watch' | 'watch-v2'): () => void;
1759
+ resume<TResumeSchema extends z.ZodType<any>>(params: {
1760
+ resumeData?: z.infer<TResumeSchema>;
1761
+ step: Step<string, any, any, TResumeSchema, any, TEngineType> | [...Step<string, any, any, any, any, TEngineType>[], Step<string, any, any, TResumeSchema, any, TEngineType>] | string | string[];
1762
+ runtimeContext?: RuntimeContext;
1763
+ runCount?: number;
1764
+ }): Promise<WorkflowResult<TOutput, TSteps>>;
1765
+ /**
1766
+ * Returns the current state of the workflow run
1767
+ * @returns The current state of the workflow run
1768
+ */
1769
+ getState(): Record<string, any>;
1770
+ updateState(state: Record<string, any>): void;
1771
+ }
1772
+
1773
+ interface StorageColumn {
1774
+ type: 'text' | 'timestamp' | 'uuid' | 'jsonb' | 'integer' | 'bigint';
1775
+ primaryKey?: boolean;
1776
+ nullable?: boolean;
1777
+ references?: {
1778
+ table: string;
1779
+ column: string;
1780
+ };
1781
+ }
1782
+ interface LegacyWorkflowRuns {
1783
+ runs: LegacyWorkflowRun[];
1784
+ total: number;
1785
+ }
1786
+ interface LegacyWorkflowRun {
1787
+ workflowName: string;
1788
+ runId: string;
1789
+ snapshot: LegacyWorkflowRunState | string;
1790
+ createdAt: Date;
1791
+ updatedAt: Date;
1792
+ resourceId?: string;
1793
+ }
1794
+ interface WorkflowRuns {
1795
+ runs: WorkflowRun[];
1796
+ total: number;
1797
+ }
1798
+ interface WorkflowRun {
1799
+ workflowName: string;
1800
+ runId: string;
1801
+ snapshot: WorkflowRunState | string;
1802
+ createdAt: Date;
1803
+ updatedAt: Date;
1804
+ resourceId?: string;
1805
+ }
1806
+ type PaginationArgs = {
1807
+ dateRange?: {
1808
+ start?: Date;
1809
+ end?: Date;
1810
+ };
1811
+ page?: number;
1812
+ perPage?: number;
1813
+ };
1814
+ type PaginationInfo = {
1815
+ total: number;
1816
+ page: number;
1817
+ perPage: number;
1818
+ hasMore: boolean;
1819
+ };
1820
+ type StorageGetMessagesArg = {
1821
+ threadId: string;
1822
+ resourceId?: string;
1823
+ selectBy?: {
1824
+ vectorSearchString?: string;
1825
+ last?: number | false;
1826
+ include?: {
1827
+ id: string;
1828
+ threadId?: string;
1829
+ withPreviousMessages?: number;
1830
+ withNextMessages?: number;
1831
+ }[];
1832
+ pagination?: PaginationArgs;
1833
+ };
1834
+ threadConfig?: MemoryConfig;
1835
+ format?: 'v1' | 'v2';
1836
+ };
1837
+ type EvalRow = {
1838
+ input: string;
1839
+ output: string;
1840
+ result: MetricResult;
1841
+ agentName: string;
1842
+ createdAt: string;
1843
+ metricName: string;
1844
+ instructions: string;
1845
+ runId: string;
1846
+ globalRunId: string;
1847
+ testInfo?: TestInfo;
1848
+ };
1849
+ type StorageGetTracesArg = {
1850
+ name?: string;
1851
+ scope?: string;
1852
+ page: number;
1853
+ perPage: number;
1854
+ attributes?: Record<string, string>;
1855
+ filters?: Record<string, any>;
1856
+ fromDate?: Date;
1857
+ toDate?: Date;
1858
+ };
1859
+ type StorageResourceType = {
1860
+ id: string;
1861
+ workingMemory?: string;
1862
+ metadata?: Record<string, unknown>;
1863
+ createdAt: Date;
1864
+ updatedAt: Date;
1865
+ };
1866
+
1867
+ declare const TABLE_WORKFLOW_SNAPSHOT = "mastra_workflow_snapshot";
1868
+ declare const TABLE_EVALS = "mastra_evals";
1869
+ declare const TABLE_MESSAGES = "mastra_messages";
1870
+ declare const TABLE_THREADS = "mastra_threads";
1871
+ declare const TABLE_TRACES = "mastra_traces";
1872
+ declare const TABLE_RESOURCES = "mastra_resources";
1873
+ type TABLE_NAMES = typeof TABLE_WORKFLOW_SNAPSHOT | typeof TABLE_EVALS | typeof TABLE_MESSAGES | typeof TABLE_THREADS | typeof TABLE_TRACES | typeof TABLE_RESOURCES;
1874
+ declare const TABLE_SCHEMAS: Record<TABLE_NAMES, Record<string, StorageColumn>>;
1875
+
1876
+ type MastraMessageV1 = {
1877
+ id: string;
1878
+ content: string | UserContent | AssistantContent | ToolContent;
1879
+ role: 'system' | 'user' | 'assistant' | 'tool';
1880
+ createdAt: Date;
1881
+ threadId?: string;
1882
+ resourceId?: string;
1883
+ toolCallIds?: string[];
1884
+ toolCallArgs?: Record<string, unknown>[];
1885
+ toolNames?: string[];
1886
+ type: 'text' | 'tool-call' | 'tool-result';
1887
+ };
1888
+ /**
1889
+ * @deprecated use MastraMessageV1 or MastraMessageV2
1890
+ */
1891
+ type MessageType = MastraMessageV1;
1892
+ type StorageThreadType = {
1893
+ id: string;
1894
+ title?: string;
1895
+ resourceId: string;
1896
+ createdAt: Date;
1897
+ updatedAt: Date;
1898
+ metadata?: Record<string, unknown>;
1899
+ };
1900
+ type MessageResponse<T extends 'raw' | 'core_message'> = {
1901
+ raw: MastraMessageV1[];
1902
+ core_message: CoreMessage$1[];
1903
+ }[T];
1904
+ type BaseWorkingMemory = {
1905
+ enabled: boolean;
1906
+ scope?: 'thread' | 'resource';
1907
+ /** @deprecated The `use` option has been removed. Working memory always uses tool-call mode. */
1908
+ use?: never;
1909
+ };
1910
+ type TemplateWorkingMemory = BaseWorkingMemory & {
1911
+ template: string;
1912
+ schema?: never;
1913
+ };
1914
+ type SchemaWorkingMemory = BaseWorkingMemory & {
1915
+ schema: ZodObject<any> | JSONSchema7;
1916
+ template?: never;
1917
+ };
1918
+ type WorkingMemoryNone = BaseWorkingMemory & {
1919
+ template?: never;
1920
+ schema?: never;
1921
+ };
1922
+ type WorkingMemory = TemplateWorkingMemory | SchemaWorkingMemory | WorkingMemoryNone;
1923
+ type MemoryConfig = {
1924
+ lastMessages?: number | false;
1925
+ semanticRecall?: boolean | {
1926
+ topK: number;
1927
+ messageRange: number | {
1928
+ before: number;
1929
+ after: number;
1930
+ };
1931
+ scope?: 'thread' | 'resource';
1932
+ };
1933
+ workingMemory?: WorkingMemory;
1934
+ threads?: {
1935
+ generateTitle?: boolean | {
1936
+ model: DynamicArgument<MastraLanguageModel>;
1937
+ instructions?: DynamicArgument<string>;
1938
+ };
1939
+ };
1940
+ };
1941
+ type SharedMemoryConfig = {
1942
+ storage?: MastraStorage;
1943
+ options?: MemoryConfig;
1944
+ vector?: MastraVector | false;
1945
+ embedder?: EmbeddingModel<string>;
1946
+ processors?: MemoryProcessor[];
1947
+ };
1948
+ type TraceType = {
1949
+ id: string;
1950
+ parentSpanId: string | null;
1951
+ name: string;
1952
+ traceId: string;
1953
+ scope: string;
1954
+ kind: number;
1955
+ attributes: Record<string, unknown> | null;
1956
+ status: Record<string, unknown> | null;
1957
+ events: Record<string, unknown> | null;
1958
+ links: Record<string, unknown> | null;
1959
+ other: Record<string, unknown> | null;
1960
+ startTime: number;
1961
+ endTime: number;
1962
+ createdAt: Date;
1963
+ };
1964
+ type WorkingMemoryFormat = 'json' | 'markdown';
1965
+ type WorkingMemoryTemplate = {
1966
+ format: WorkingMemoryFormat;
1967
+ content: string;
1968
+ };
1969
+
1970
+ type MastraMessageContentV2 = {
1971
+ format: 2;
1972
+ parts: UIMessage['parts'];
1973
+ experimental_attachments?: UIMessage['experimental_attachments'];
1974
+ content?: UIMessage['content'];
1975
+ toolInvocations?: UIMessage['toolInvocations'];
1976
+ reasoning?: UIMessage['reasoning'];
1977
+ annotations?: UIMessage['annotations'];
1978
+ metadata?: Record<string, unknown>;
1979
+ };
1980
+ type MastraMessageV2 = {
1981
+ id: string;
1982
+ content: MastraMessageContentV2;
1983
+ role: 'user' | 'assistant';
1984
+ createdAt: Date;
1985
+ threadId?: string;
1986
+ resourceId?: string;
1987
+ type?: string;
1988
+ };
1989
+ type MessageInput = UIMessage | Message | MastraMessageV1 | CoreMessage$1 | MastraMessageV2;
1990
+ type MessageSource = 'memory' | 'response' | 'user' | 'system' | 'context';
1991
+ declare class MessageList {
1992
+ private messages;
1993
+ private systemMessages;
1994
+ private taggedSystemMessages;
1995
+ private memoryInfo;
1996
+ private memoryMessages;
1997
+ private newUserMessages;
1998
+ private newResponseMessages;
1999
+ private userContextMessages;
2000
+ private generateMessageId?;
2001
+ constructor({ threadId, resourceId, generateMessageId, }?: {
2002
+ threadId?: string;
2003
+ resourceId?: string;
2004
+ generateMessageId?: IDGenerator$1;
2005
+ });
2006
+ add(messages: string | string[] | MessageInput | MessageInput[], messageSource: MessageSource): this;
2007
+ getLatestUserContent(): string | null;
2008
+ get get(): {
2009
+ all: {
2010
+ v2: () => MastraMessageV2[];
2011
+ v1: () => MastraMessageV1[];
2012
+ ui: () => UIMessage[];
2013
+ core: () => CoreMessage$1[];
2014
+ prompt: () => CoreMessage$1[];
2015
+ };
2016
+ remembered: {
2017
+ v2: () => MastraMessageV2[];
2018
+ v1: () => MastraMessageV1[];
2019
+ ui: () => UIMessage[];
2020
+ core: () => CoreMessage$1[];
2021
+ };
2022
+ input: {
2023
+ v2: () => MastraMessageV2[];
2024
+ v1: () => MastraMessageV1[];
2025
+ ui: () => UIMessage[];
2026
+ core: () => CoreMessage$1[];
2027
+ };
2028
+ response: {
2029
+ v2: () => MastraMessageV2[];
2030
+ };
2031
+ };
2032
+ private all;
2033
+ private remembered;
2034
+ private input;
2035
+ private response;
2036
+ drainUnsavedMessages(): MastraMessageV2[];
2037
+ getEarliestUnsavedMessageTimestamp(): number | undefined;
2038
+ getSystemMessages(tag?: string): CoreMessage$1[];
2039
+ addSystem(messages: CoreSystemMessage$1 | CoreSystemMessage$1[] | string | string[] | null, tag?: string): this;
2040
+ private convertToCoreMessages;
2041
+ private sanitizeUIMessages;
2042
+ private addOneSystem;
2043
+ private isDuplicateSystem;
2044
+ private static toUIMessage;
2045
+ private getMessageById;
2046
+ private shouldReplaceMessage;
2047
+ private addOne;
2048
+ private inputToMastraMessageV2;
2049
+ private lastCreatedAt?;
2050
+ private generateCreatedAt;
2051
+ private newMessageId;
2052
+ private mastraMessageV1ToMastraMessageV2;
2053
+ private hydrateMastraMessageV2Fields;
2054
+ private vercelUIMessageToMastraMessageV2;
2055
+ private vercelCoreMessageToMastraMessageV2;
2056
+ static isVercelUIMessage(msg: MessageInput): msg is UIMessage;
2057
+ static isVercelCoreMessage(msg: MessageInput): msg is CoreMessage$1;
2058
+ static isMastraMessage(msg: MessageInput): msg is MastraMessageV2 | MastraMessageV1;
2059
+ static isMastraMessageV1(msg: MessageInput): msg is MastraMessageV1;
2060
+ static isMastraMessageV2(msg: MessageInput): msg is MastraMessageV2;
2061
+ private static getRole;
2062
+ private static cacheKeyFromParts;
2063
+ private static coreContentToString;
2064
+ private static cacheKeyFromContent;
2065
+ private static messagesAreEqual;
2066
+ }
2067
+
2068
+ type MemoryProcessorOpts = {
2069
+ systemMessage?: string;
2070
+ memorySystemMessage?: string;
2071
+ newMessages?: CoreMessage$1[];
2072
+ };
2073
+ /**
2074
+ * Interface for message processors that can filter or transform messages
2075
+ * before they're sent to the LLM.
2076
+ */
2077
+ declare abstract class MemoryProcessor extends MastraBase {
2078
+ /**
2079
+ * Process a list of messages and return a filtered or transformed list.
2080
+ * @param messages The messages to process
2081
+ * @returns The processed messages
2082
+ */
2083
+ process(messages: CoreMessage$1[], _opts: MemoryProcessorOpts): CoreMessage$1[];
2084
+ }
2085
+ declare const memoryDefaultOptions: {
2086
+ lastMessages: number;
2087
+ semanticRecall: false;
2088
+ threads: {
2089
+ generateTitle: false;
2090
+ };
2091
+ workingMemory: {
2092
+ enabled: false;
2093
+ template: string;
2094
+ };
2095
+ };
2096
+ /**
2097
+ * Abstract Memory class that defines the interface for storing and retrieving
2098
+ * conversation threads and messages.
2099
+ */
2100
+ declare abstract class MastraMemory extends MastraBase {
2101
+ MAX_CONTEXT_TOKENS?: number;
2102
+ protected _storage?: MastraStorage;
2103
+ vector?: MastraVector;
2104
+ embedder?: EmbeddingModel<string>;
2105
+ private processors;
2106
+ protected threadConfig: MemoryConfig;
2107
+ constructor(config: {
2108
+ name: string;
2109
+ } & SharedMemoryConfig);
2110
+ protected _hasOwnStorage: boolean;
2111
+ get hasOwnStorage(): boolean;
2112
+ get storage(): MastraStorage;
2113
+ setStorage(storage: MastraStorage): void;
2114
+ setVector(vector: MastraVector): void;
2115
+ setEmbedder(embedder: EmbeddingModel<string>): void;
2116
+ /**
2117
+ * Get a system message to inject into the conversation.
2118
+ * This will be called before each conversation turn.
2119
+ * Implementations can override this to inject custom system messages.
2120
+ */
2121
+ getSystemMessage(_input: {
2122
+ threadId: string;
2123
+ resourceId?: string;
2124
+ memoryConfig?: MemoryConfig;
2125
+ }): Promise<string | null>;
2126
+ /**
2127
+ * Get tools that should be available to the agent.
2128
+ * This will be called when converting tools for the agent.
2129
+ * Implementations can override this to provide additional tools.
2130
+ */
2131
+ getTools(_config?: MemoryConfig): Record<string, CoreTool>;
2132
+ protected createEmbeddingIndex(dimensions?: number): Promise<{
2133
+ indexName: string;
2134
+ }>;
2135
+ getMergedThreadConfig(config?: MemoryConfig): MemoryConfig;
2136
+ /**
2137
+ * Apply all configured message processors to a list of messages.
2138
+ * @param messages The messages to process
2139
+ * @returns The processed messages
2140
+ */
2141
+ protected applyProcessors(messages: CoreMessage$1[], opts: {
2142
+ processors?: MemoryProcessor[];
2143
+ } & MemoryProcessorOpts): CoreMessage$1[];
2144
+ processMessages({ messages, processors, ...opts }: {
2145
+ messages: CoreMessage$1[];
2146
+ processors?: MemoryProcessor[];
2147
+ } & MemoryProcessorOpts): CoreMessage$1[];
2148
+ abstract rememberMessages({ threadId, resourceId, vectorMessageSearch, config, }: {
2149
+ threadId: string;
2150
+ resourceId?: string;
2151
+ vectorMessageSearch?: string;
2152
+ config?: MemoryConfig;
2153
+ }): Promise<{
2154
+ messages: MastraMessageV1[];
2155
+ messagesV2: MastraMessageV2[];
2156
+ }>;
2157
+ estimateTokens(text: string): number;
2158
+ /**
2159
+ * Retrieves a specific thread by its ID
2160
+ * @param threadId - The unique identifier of the thread
2161
+ * @returns Promise resolving to the thread or null if not found
2162
+ */
2163
+ abstract getThreadById({ threadId }: {
2164
+ threadId: string;
2165
+ }): Promise<StorageThreadType | null>;
2166
+ abstract getThreadsByResourceId({ resourceId }: {
2167
+ resourceId: string;
2168
+ }): Promise<StorageThreadType[]>;
2169
+ /**
2170
+ * Saves or updates a thread
2171
+ * @param thread - The thread data to save
2172
+ * @returns Promise resolving to the saved thread
2173
+ */
2174
+ abstract saveThread({ thread, memoryConfig, }: {
2175
+ thread: StorageThreadType;
2176
+ memoryConfig?: MemoryConfig;
2177
+ }): Promise<StorageThreadType>;
2178
+ /**
2179
+ * Saves messages to a thread
2180
+ * @param messages - Array of messages to save
2181
+ * @returns Promise resolving to the saved messages
2182
+ */
2183
+ abstract saveMessages(args: {
2184
+ messages: (MastraMessageV1 | MastraMessageV2)[] | MastraMessageV1[] | MastraMessageV2[];
2185
+ memoryConfig?: MemoryConfig | undefined;
2186
+ format?: 'v1';
2187
+ }): Promise<MastraMessageV1[]>;
2188
+ abstract saveMessages(args: {
2189
+ messages: (MastraMessageV1 | MastraMessageV2)[] | MastraMessageV1[] | MastraMessageV2[];
2190
+ memoryConfig?: MemoryConfig | undefined;
2191
+ format: 'v2';
2192
+ }): Promise<MastraMessageV2[]>;
2193
+ abstract saveMessages(args: {
2194
+ messages: (MastraMessageV1 | MastraMessageV2)[] | MastraMessageV1[] | MastraMessageV2[];
2195
+ memoryConfig?: MemoryConfig | undefined;
2196
+ format?: 'v1' | 'v2';
2197
+ }): Promise<MastraMessageV2[] | MastraMessageV1[]>;
2198
+ /**
2199
+ * Retrieves all messages for a specific thread
2200
+ * @param threadId - The unique identifier of the thread
2201
+ * @returns Promise resolving to array of messages and uiMessages
2202
+ */
2203
+ abstract query({ threadId, resourceId, selectBy, }: StorageGetMessagesArg): Promise<{
2204
+ messages: CoreMessage$1[];
2205
+ uiMessages: UIMessage[];
2206
+ }>;
2207
+ /**
2208
+ * Helper method to create a new thread
2209
+ * @param title - Optional title for the thread
2210
+ * @param metadata - Optional metadata for the thread
2211
+ * @returns Promise resolving to the created thread
2212
+ */
2213
+ createThread({ threadId, resourceId, title, metadata, memoryConfig, }: {
2214
+ resourceId: string;
2215
+ threadId?: string;
2216
+ title?: string;
2217
+ metadata?: Record<string, unknown>;
2218
+ memoryConfig?: MemoryConfig;
2219
+ }): Promise<StorageThreadType>;
2220
+ /**
2221
+ * Helper method to delete a thread
2222
+ * @param threadId - the id of the thread to delete
2223
+ */
2224
+ abstract deleteThread(threadId: string): Promise<void>;
2225
+ /**
2226
+ * Helper method to add a single message to a thread
2227
+ * @param threadId - The thread to add the message to
2228
+ * @param content - The message content
2229
+ * @param role - The role of the message sender
2230
+ * @param type - The type of the message
2231
+ * @param toolNames - Optional array of tool names that were called
2232
+ * @param toolCallArgs - Optional array of tool call arguments
2233
+ * @param toolCallIds - Optional array of tool call ids
2234
+ * @returns Promise resolving to the saved message
2235
+ * @deprecated use saveMessages instead
2236
+ */
2237
+ addMessage({ threadId, resourceId, config, content, role, type, toolNames, toolCallArgs, toolCallIds, }: {
2238
+ threadId: string;
2239
+ resourceId: string;
2240
+ config?: MemoryConfig;
2241
+ content: UserContent | AssistantContent;
2242
+ role: 'user' | 'assistant';
2243
+ type: 'text' | 'tool-call' | 'tool-result';
2244
+ toolNames?: string[];
2245
+ toolCallArgs?: Record<string, unknown>[];
2246
+ toolCallIds?: string[];
2247
+ }): Promise<MastraMessageV1>;
2248
+ /**
2249
+ * Generates a unique identifier
2250
+ * @returns A unique string ID
2251
+ */
2252
+ generateId(): string;
2253
+ /**
2254
+ * Retrieves working memory for a specific thread
2255
+ * @param threadId - The unique identifier of the thread
2256
+ * @param resourceId - The unique identifier of the resource
2257
+ * @param memoryConfig - Optional memory configuration
2258
+ * @returns Promise resolving to working memory data or null if not found
2259
+ */
2260
+ abstract getWorkingMemory({ threadId, resourceId, memoryConfig, }: {
2261
+ threadId: string;
2262
+ resourceId?: string;
2263
+ memoryConfig?: MemoryConfig;
2264
+ }): Promise<string | null>;
2265
+ /**
2266
+ * Retrieves working memory template for a specific thread
2267
+ * @param memoryConfig - Optional memory configuration
2268
+ * @returns Promise resolving to working memory template or null if not found
2269
+ */
2270
+ abstract getWorkingMemoryTemplate({ memoryConfig, }?: {
2271
+ memoryConfig?: MemoryConfig;
2272
+ }): Promise<WorkingMemoryTemplate | null>;
2273
+ abstract updateWorkingMemory({ threadId, resourceId, workingMemory, memoryConfig, }: {
2274
+ threadId: string;
2275
+ resourceId?: string;
2276
+ workingMemory: string;
2277
+ memoryConfig?: MemoryConfig;
2278
+ }): Promise<void>;
2279
+ }
2280
+
2281
+ declare abstract class MastraLLMBase extends MastraBase {
2282
+ constructor({ name }: {
2283
+ name: string;
2284
+ });
2285
+ abstract getProvider(): string;
2286
+ abstract getModelId(): string;
2287
+ abstract __registerMastra(p: Mastra): void;
2288
+ abstract __text<Z extends ZodSchema | JSONSchema7 | undefined>(input: LLMTextOptions<Z>): Promise<GenerateTextResult<any, any>>;
2289
+ abstract __textObject<T extends ZodSchema | JSONSchema7 | undefined>(input: LLMTextObjectOptions<T>): Promise<GenerateObjectResult<T>>;
2290
+ abstract generate<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[], options: LLMStreamOptions<Z>): Promise<GenerateReturn<Z>>;
2291
+ abstract __stream<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(input: LLMInnerStreamOptions<Z>): StreamTextResult<any, any>;
2292
+ abstract __streamObject<T extends ZodSchema | JSONSchema7 | undefined>(input: LLMStreamObjectOptions<T>): StreamObjectResult<DeepPartial<T>, T, never>;
2293
+ abstract stream<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[], options: LLMStreamOptions<Z>): StreamReturn<Z>;
2294
+ convertToMessages(messages: string | string[] | CoreMessage$1[]): CoreMessage$1[];
2295
+ __registerPrimitives(p: MastraPrimitives): void;
2296
+ }
2297
+
2298
+ declare function createMockModel({ objectGenerationMode, mockText, spyGenerate, spyStream, }: {
2299
+ objectGenerationMode?: 'json';
2300
+ mockText: string | Record<string, any>;
2301
+ spyGenerate?: (props: any) => void;
2302
+ spyStream?: (props: any) => void;
2303
+ }): MockLanguageModelV1;
2304
+
2305
+ type LanguageModel = MastraLanguageModel;
2306
+ type CoreMessage = CoreMessage$1;
2307
+ type CoreSystemMessage = CoreSystemMessage$1;
2308
+ type CoreAssistantMessage = CoreAssistantMessage$1;
2309
+ type CoreUserMessage = CoreUserMessage$1;
2310
+ type CoreToolMessage = CoreToolMessage$1;
2311
+ type EmbedResult<T> = EmbedResult$1<T>;
2312
+ type EmbedManyResult<T> = EmbedManyResult$1<T>;
2313
+ type BaseStructuredOutputType = 'string' | 'number' | 'boolean' | 'date';
2314
+ type StructuredOutputType = 'array' | 'string' | 'number' | 'object' | 'boolean' | 'date';
2315
+ type StructuredOutputArrayItem = {
2316
+ type: BaseStructuredOutputType;
2317
+ } | {
2318
+ type: 'object';
2319
+ items: StructuredOutput;
2320
+ };
2321
+ type StructuredOutput = {
2322
+ [key: string]: {
2323
+ type: BaseStructuredOutputType;
2324
+ } | {
2325
+ type: 'object';
2326
+ items: StructuredOutput;
2327
+ } | {
2328
+ type: 'array';
2329
+ items: StructuredOutputArrayItem;
2330
+ };
2331
+ };
2332
+ type GenerateReturn<Z extends ZodSchema | JSONSchema7 | undefined = undefined> = Z extends undefined ? GenerateTextResult<any, Z extends ZodSchema ? z.infer<Z> : unknown> : GenerateObjectResult<Z extends ZodSchema ? z.infer<Z> : unknown>;
2333
+ type StreamReturn<Z extends ZodSchema | JSONSchema7 | undefined = undefined> = Z extends undefined ? StreamTextResult<any, Z extends ZodSchema ? z.infer<Z> : unknown> : StreamObjectResult<any, Z extends ZodSchema ? z.infer<Z> : unknown, any>;
2334
+ type OutputType = StructuredOutput | ZodSchema | JSONSchema7 | undefined;
2335
+ type GenerateTextOptions = Parameters<typeof generateText>[0];
2336
+ type StreamTextOptions = Parameters<typeof streamText>[0];
2337
+ type GenerateObjectOptions = Parameters<typeof generateObject>[0];
2338
+ type StreamObjectOptions = Parameters<typeof streamObject>[0];
2339
+ type MastraCustomLLMOptionsKeys = 'messages' | 'tools' | 'model' | 'onStepFinish' | 'experimental_output' | 'experimental_telemetry' | 'messages' | 'onFinish' | 'output';
2340
+ type DefaultLLMTextOptions = Omit<GenerateTextOptions, MastraCustomLLMOptionsKeys>;
2341
+ type DefaultLLMTextObjectOptions = Omit<GenerateObjectOptions, MastraCustomLLMOptionsKeys>;
2342
+ type DefaultLLMStreamOptions = Omit<StreamTextOptions, MastraCustomLLMOptionsKeys>;
2343
+ type DefaultLLMStreamObjectOptions = Omit<StreamObjectOptions, MastraCustomLLMOptionsKeys>;
2344
+ type MastraCustomLLMOptions<Z extends ZodSchema | JSONSchema7 | undefined = undefined> = {
2345
+ tools?: Record<string, CoreTool>;
2346
+ onStepFinish?: (step: unknown) => Promise<void> | void;
2347
+ experimental_output?: Z;
2348
+ telemetry?: TelemetrySettings;
2349
+ threadId?: string;
2350
+ resourceId?: string;
2351
+ runtimeContext: RuntimeContext;
2352
+ } & Run$1;
2353
+ type LLMTextOptions<Z extends ZodSchema | JSONSchema7 | undefined = undefined> = {
2354
+ messages: UIMessage[] | CoreMessage[];
2355
+ } & MastraCustomLLMOptions<Z> & DefaultLLMTextOptions;
2356
+ type LLMTextObjectOptions<T extends ZodSchema | JSONSchema7 | undefined = undefined> = LLMTextOptions<T> & DefaultLLMTextObjectOptions & {
2357
+ structuredOutput: JSONSchema7 | z.ZodType<T> | StructuredOutput;
2358
+ };
2359
+ type LLMStreamOptions<Z extends ZodSchema | JSONSchema7 | undefined = undefined> = {
2360
+ output?: OutputType | Z;
2361
+ onFinish?: (result: string) => Promise<void> | void;
2362
+ } & MastraCustomLLMOptions<Z> & DefaultLLMStreamOptions;
2363
+ type LLMInnerStreamOptions<Z extends ZodSchema | JSONSchema7 | undefined = undefined> = {
2364
+ messages: UIMessage[] | CoreMessage[];
2365
+ onFinish?: (result: string) => Promise<void> | void;
2366
+ } & MastraCustomLLMOptions<Z> & DefaultLLMStreamOptions;
2367
+ type LLMStreamObjectOptions<T extends ZodSchema | JSONSchema7 | undefined = undefined> = {
2368
+ structuredOutput: JSONSchema7 | z.ZodType<T> | StructuredOutput;
2369
+ } & LLMInnerStreamOptions<T> & DefaultLLMStreamObjectOptions;
2370
+
2371
+ type VoiceEventType = 'speaking' | 'writing' | 'error' | string;
2372
+ interface VoiceEventMap {
2373
+ speaker: NodeJS.ReadableStream;
2374
+ speaking: {
2375
+ audio?: string;
2376
+ };
2377
+ writing: {
2378
+ text: string;
2379
+ role: 'assistant' | 'user';
2380
+ };
2381
+ error: {
2382
+ message: string;
2383
+ code?: string;
2384
+ details?: unknown;
2385
+ };
2386
+ [key: string]: unknown;
2387
+ }
2388
+ interface BuiltInModelConfig {
2389
+ name: string;
2390
+ apiKey?: string;
2391
+ }
2392
+ interface VoiceConfig<T = unknown> {
2393
+ listeningModel?: BuiltInModelConfig;
2394
+ speechModel?: BuiltInModelConfig;
2395
+ speaker?: string;
2396
+ name?: string;
2397
+ realtimeConfig?: {
2398
+ model?: string;
2399
+ apiKey?: string;
2400
+ options?: T;
2401
+ };
2402
+ }
2403
+ declare abstract class MastraVoice<TOptions = unknown, TSpeakOptions = unknown, TListenOptions = unknown, TTools extends ToolsInput = ToolsInput, TEventArgs extends VoiceEventMap = VoiceEventMap, TSpeakerMetadata = unknown> extends MastraBase {
2404
+ protected listeningModel?: BuiltInModelConfig;
2405
+ protected speechModel?: BuiltInModelConfig;
2406
+ protected speaker?: string;
2407
+ protected realtimeConfig?: {
2408
+ model?: string;
2409
+ apiKey?: string;
2410
+ options?: TOptions;
2411
+ };
2412
+ constructor({ listeningModel, speechModel, speaker, realtimeConfig, name }?: VoiceConfig<TOptions>);
2413
+ traced<T extends Function>(method: T, methodName: string): T;
2414
+ /**
2415
+ * Convert text to speech
2416
+ * @param input Text or text stream to convert to speech
2417
+ * @param options Speech options including speaker and provider-specific options
2418
+ * @returns Audio stream
2419
+ */
2420
+ /**
2421
+ * Convert text to speech
2422
+ * @param input Text or text stream to convert to speech
2423
+ * @param options Speech options including speaker and provider-specific options
2424
+ * @returns Audio stream or void if in chat mode
2425
+ */
2426
+ abstract speak(input: string | NodeJS.ReadableStream, options?: {
2427
+ speaker?: string;
2428
+ } & TSpeakOptions): Promise<NodeJS.ReadableStream | void>;
2429
+ /**
2430
+ * Convert speech to text
2431
+ * @param audioStream Audio stream to transcribe
2432
+ * @param options Provider-specific transcription options
2433
+ * @returns Text or text stream
2434
+ */
2435
+ /**
2436
+ * Convert speech to text
2437
+ * @param audioStream Audio stream to transcribe
2438
+ * @param options Provider-specific transcription options
2439
+ * @returns Text, text stream, or void if in chat mode
2440
+ */
2441
+ abstract listen(audioStream: NodeJS.ReadableStream | unknown, // Allow other audio input types for OpenAI realtime API
2442
+ options?: TListenOptions): Promise<string | NodeJS.ReadableStream | void>;
2443
+ updateConfig(_options: Record<string, unknown>): void;
2444
+ /**
2445
+ * Initializes a WebSocket or WebRTC connection for real-time communication
2446
+ * @returns Promise that resolves when the connection is established
2447
+ */
2448
+ connect(_options?: Record<string, unknown>): Promise<void>;
2449
+ /**
2450
+ * Relay audio data to the voice provider for real-time processing
2451
+ * @param audioData Audio data to relay
2452
+ */
2453
+ send(_audioData: NodeJS.ReadableStream | Int16Array): Promise<void>;
2454
+ /**
2455
+ * Trigger voice providers to respond
2456
+ */
2457
+ answer(_options?: Record<string, unknown>): Promise<void>;
2458
+ /**
2459
+ * Equip the voice provider with instructions
2460
+ * @param instructions Instructions to add
2461
+ */
2462
+ addInstructions(_instructions?: string): void;
2463
+ /**
2464
+ * Equip the voice provider with tools
2465
+ * @param tools Array of tools to add
2466
+ */
2467
+ addTools(_tools: TTools): void;
2468
+ /**
2469
+ * Disconnect from the WebSocket or WebRTC connection
2470
+ */
2471
+ close(): void;
2472
+ /**
2473
+ * Register an event listener
2474
+ * @param event Event name (e.g., 'speaking', 'writing', 'error')
2475
+ * @param callback Callback function that receives event data
2476
+ */
2477
+ on<E extends VoiceEventType>(_event: E, _callback: (data: E extends keyof TEventArgs ? TEventArgs[E] : unknown) => void): void;
2478
+ /**
2479
+ * Remove an event listener
2480
+ * @param event Event name (e.g., 'speaking', 'writing', 'error')
2481
+ * @param callback Callback function to remove
2482
+ */
2483
+ off<E extends VoiceEventType>(_event: E, _callback: (data: E extends keyof TEventArgs ? TEventArgs[E] : unknown) => void): void;
2484
+ /**
2485
+ * Get available speakers/voices
2486
+ * @returns Array of available voice IDs and their metadata
2487
+ */
2488
+ getSpeakers(): Promise<Array<{
2489
+ voiceId: string;
2490
+ } & TSpeakerMetadata>>;
2491
+ /**
2492
+ * Get available speakers/voices
2493
+ * @returns Array of available voice IDs and their metadata
2494
+ */
2495
+ getListener(): Promise<{
2496
+ enabled: boolean;
2497
+ }>;
2498
+ }
2499
+
2500
+ declare class CompositeVoice extends MastraVoice<unknown, unknown, unknown, ToolsInput, VoiceEventMap> {
2501
+ protected speakProvider?: MastraVoice;
2502
+ protected listenProvider?: MastraVoice;
2503
+ protected realtimeProvider?: MastraVoice;
2504
+ constructor({ input, output, realtime, speakProvider, listenProvider, realtimeProvider, }: {
2505
+ /** @deprecated use output instead */
2506
+ speakProvider?: MastraVoice;
2507
+ /** @deprecated use input instead */
2508
+ listenProvider?: MastraVoice;
2509
+ /** @deprecated use realtime instead */
2510
+ realtimeProvider?: MastraVoice;
2511
+ input?: MastraVoice;
2512
+ output?: MastraVoice;
2513
+ realtime?: MastraVoice;
2514
+ });
2515
+ /**
2516
+ * Convert text to speech using the configured provider
2517
+ * @param input Text or text stream to convert to speech
2518
+ * @param options Speech options including speaker and provider-specific options
2519
+ * @returns Audio stream or void if in realtime mode
2520
+ */
2521
+ speak(input: string | NodeJS.ReadableStream, options?: {
2522
+ speaker?: string;
2523
+ } & any): Promise<NodeJS.ReadableStream | void>;
2524
+ listen(audioStream: NodeJS.ReadableStream, options?: any): Promise<string | void | NodeJS.ReadableStream>;
2525
+ getSpeakers(): Promise<{
2526
+ voiceId: string;
2527
+ }[]>;
2528
+ getListener(): Promise<{
2529
+ enabled: boolean;
2530
+ }>;
2531
+ updateConfig(options: Record<string, unknown>): void;
2532
+ /**
2533
+ * Initializes a WebSocket or WebRTC connection for real-time communication
2534
+ * @returns Promise that resolves when the connection is established
2535
+ */
2536
+ connect(options?: Record<string, unknown>): Promise<void>;
2537
+ /**
2538
+ * Relay audio data to the voice provider for real-time processing
2539
+ * @param audioData Audio data to send
2540
+ */
2541
+ send(audioData: NodeJS.ReadableStream | Int16Array): Promise<void>;
2542
+ /**
2543
+ * Trigger voice providers to respond
2544
+ */
2545
+ answer(options?: Record<string, unknown>): Promise<void>;
2546
+ /**
2547
+ * Equip the voice provider with instructions
2548
+ * @param instructions Instructions to add
2549
+ */
2550
+ addInstructions(instructions: string): void;
2551
+ /**
2552
+ * Equip the voice provider with tools
2553
+ * @param tools Array of tools to add
2554
+ */
2555
+ addTools(tools: ToolsInput): void;
2556
+ /**
2557
+ * Disconnect from the WebSocket or WebRTC connection
2558
+ */
2559
+ close(): void;
2560
+ /**
2561
+ * Register an event listener
2562
+ * @param event Event name (e.g., 'speaking', 'writing', 'error')
2563
+ * @param callback Callback function that receives event data
2564
+ */
2565
+ on<E extends VoiceEventType>(event: E, callback: (data: E extends keyof VoiceEventMap ? VoiceEventMap[E] : unknown) => void): void;
2566
+ /**
2567
+ * Remove an event listener
2568
+ * @param event Event name (e.g., 'speaking', 'writing', 'error')
2569
+ * @param callback Callback function to remove
2570
+ */
2571
+ off<E extends VoiceEventType>(event: E, callback: (data: E extends keyof VoiceEventMap ? VoiceEventMap[E] : unknown) => void): void;
2572
+ }
2573
+
2574
+ declare class DefaultVoice extends MastraVoice {
2575
+ constructor();
2576
+ speak(_input: string | NodeJS.ReadableStream): Promise<NodeJS.ReadableStream>;
2577
+ listen(_input: string | NodeJS.ReadableStream): Promise<string>;
2578
+ getSpeakers(): Promise<{
2579
+ voiceId: string;
2580
+ }[]>;
2581
+ getListener(): Promise<{
2582
+ enabled: boolean;
2583
+ }>;
2584
+ }
2585
+
2586
+ type ToolsInput = Record<string, ToolAction<any, any, any> | VercelTool>;
2587
+ type ToolsetsInput = Record<string, ToolsInput>;
2588
+ type MastraLanguageModel = LanguageModelV1;
2589
+ type DynamicArgument<T> = T | (({ runtimeContext }: {
2590
+ runtimeContext: RuntimeContext;
2591
+ }) => Promise<T> | T);
2592
+ interface AgentConfig<TAgentId extends string = string, TTools extends ToolsInput = ToolsInput, TMetrics extends Record<string, Metric> = Record<string, Metric>> {
2593
+ name: TAgentId;
2594
+ description?: string;
2595
+ instructions: DynamicArgument<string>;
2596
+ model: DynamicArgument<MastraLanguageModel>;
2597
+ tools?: DynamicArgument<TTools>;
2598
+ workflows?: DynamicArgument<Record<string, Workflow>>;
2599
+ defaultGenerateOptions?: DynamicArgument<AgentGenerateOptions>;
2600
+ defaultStreamOptions?: DynamicArgument<AgentStreamOptions>;
2601
+ mastra?: Mastra;
2602
+ evals?: TMetrics;
2603
+ memory?: MastraMemory;
2604
+ voice?: CompositeVoice;
2605
+ /** @deprecated This property is deprecated. Use evals instead to add evaluation metrics. */
2606
+ metrics?: TMetrics;
2607
+ }
2608
+ type AgentMemoryOption = {
2609
+ thread: string | (Partial<StorageThreadType> & {
2610
+ id: string;
2611
+ });
2612
+ resource: string;
2613
+ options?: MemoryConfig;
2614
+ };
2615
+ /**
2616
+ * Options for generating responses with an agent
2617
+ * @template OUTPUT - The schema type for structured output (Zod schema or JSON schema)
2618
+ * @template EXPERIMENTAL_OUTPUT - The schema type for structured output generation alongside tool calls (Zod schema or JSON schema)
2619
+ */
2620
+ type AgentGenerateOptions<OUTPUT extends ZodSchema | JSONSchema7 | undefined = undefined, EXPERIMENTAL_OUTPUT extends ZodSchema | JSONSchema7 | undefined = undefined> = {
2621
+ /** Optional instructions to override the agent's default instructions */
2622
+ instructions?: string;
2623
+ /** Additional tool sets that can be used for this generation */
2624
+ toolsets?: ToolsetsInput;
2625
+ clientTools?: ToolsInput;
2626
+ /** Additional context messages to include */
2627
+ context?: CoreMessage[];
2628
+ /**
2629
+ * @deprecated Use the `memory` property instead for all memory-related options.
2630
+ */
2631
+ memoryOptions?: MemoryConfig;
2632
+ /** New memory options (preferred) */
2633
+ memory?: AgentMemoryOption;
2634
+ /** Unique ID for this generation run */
2635
+ runId?: string;
2636
+ /** Callback fired after each generation step completes */
2637
+ onStepFinish?: OUTPUT extends undefined ? EXPERIMENTAL_OUTPUT extends undefined ? GenerateTextOnStepFinishCallback<any> : GenerateTextOnStepFinishCallback<any> : never;
2638
+ /** Maximum number of steps allowed for generation */
2639
+ maxSteps?: number;
2640
+ /** Schema for structured output, does not work with tools, use experimental_output instead */
2641
+ output?: OutputType | OUTPUT;
2642
+ /** Schema for structured output generation alongside tool calls. */
2643
+ experimental_output?: EXPERIMENTAL_OUTPUT;
2644
+ /** Controls how tools are selected during generation */
2645
+ toolChoice?: 'auto' | 'none' | 'required' | {
2646
+ type: 'tool';
2647
+ toolName: string;
2648
+ };
2649
+ /** Telemetry settings */
2650
+ telemetry?: TelemetrySettings;
2651
+ /** RuntimeContext for dependency injection */
2652
+ runtimeContext?: RuntimeContext;
2653
+ /**
2654
+ * Whether to save messages incrementally on step finish
2655
+ * @default false
2656
+ */
2657
+ savePerStep?: boolean;
2658
+ } & ({
2659
+ /**
2660
+ * @deprecated Use the `memory` property instead for all memory-related options.
2661
+ */
2662
+ resourceId?: undefined;
2663
+ /**
2664
+ * @deprecated Use the `memory` property instead for all memory-related options.
2665
+ */
2666
+ threadId?: undefined;
2667
+ } | {
2668
+ /**
2669
+ * @deprecated Use the `memory` property instead for all memory-related options.
2670
+ */
2671
+ resourceId: string;
2672
+ /**
2673
+ * @deprecated Use the `memory` property instead for all memory-related options.
2674
+ */
2675
+ threadId: string;
2676
+ }) & (OUTPUT extends undefined ? DefaultLLMTextOptions : DefaultLLMTextObjectOptions);
2677
+ /**
2678
+ * Options for streaming responses with an agent
2679
+ * @template OUTPUT - The schema type for structured output (Zod schema or JSON schema)
2680
+ * @template EXPERIMENTAL_OUTPUT - The schema type for structured output generation alongside tool calls (Zod schema or JSON schema)
2681
+ */
2682
+ type AgentStreamOptions<OUTPUT extends ZodSchema | JSONSchema7 | undefined = undefined, EXPERIMENTAL_OUTPUT extends ZodSchema | JSONSchema7 | undefined = undefined> = {
2683
+ /** Optional instructions to override the agent's default instructions */
2684
+ instructions?: string;
2685
+ /** Additional tool sets that can be used for this generation */
2686
+ toolsets?: ToolsetsInput;
2687
+ clientTools?: ToolsInput;
2688
+ /** Additional context messages to include */
2689
+ context?: CoreMessage[];
2690
+ /**
2691
+ * @deprecated Use the `memory` property instead for all memory-related options.
2692
+ */
2693
+ memoryOptions?: MemoryConfig;
2694
+ /** New memory options (preferred) */
2695
+ memory?: AgentMemoryOption;
2696
+ /** Unique ID for this generation run */
2697
+ runId?: string;
2698
+ /** Callback fired when streaming completes */
2699
+ onFinish?: OUTPUT extends undefined ? StreamTextOnFinishCallback<any> : OUTPUT extends ZodSchema ? StreamObjectOnFinishCallback<z.infer<OUTPUT>> : StreamObjectOnFinishCallback<any>;
2700
+ /** Callback fired after each generation step completes */
2701
+ onStepFinish?: OUTPUT extends undefined ? EXPERIMENTAL_OUTPUT extends undefined ? StreamTextOnStepFinishCallback<any> : StreamTextOnStepFinishCallback<any> : never;
2702
+ /** Maximum number of steps allowed for generation */
2703
+ maxSteps?: number;
2704
+ /** Schema for structured output */
2705
+ output?: OutputType | OUTPUT;
2706
+ /** Temperature parameter for controlling randomness */
2707
+ temperature?: number;
2708
+ /** Controls how tools are selected during generation */
2709
+ toolChoice?: 'auto' | 'none' | 'required' | {
2710
+ type: 'tool';
2711
+ toolName: string;
2712
+ };
2713
+ /** Experimental schema for structured output */
2714
+ experimental_output?: EXPERIMENTAL_OUTPUT;
2715
+ /** Telemetry settings */
2716
+ telemetry?: TelemetrySettings;
2717
+ /** RuntimeContext for dependency injection */
2718
+ runtimeContext?: RuntimeContext;
2719
+ /**
2720
+ * Whether to save messages incrementally on step finish
2721
+ * @default false
2722
+ */
2723
+ savePerStep?: boolean;
2724
+ } & ({
2725
+ /**
2726
+ * @deprecated Use the `memory` property instead for all memory-related options.
2727
+ */
2728
+ resourceId?: undefined;
2729
+ /**
2730
+ * @deprecated Use the `memory` property instead for all memory-related options.
2731
+ */
2732
+ threadId?: undefined;
2733
+ } | {
2734
+ /**
2735
+ * @deprecated Use the `memory` property instead for all memory-related options.
2736
+ */
2737
+ resourceId: string;
2738
+ /**
2739
+ * @deprecated Use the `memory` property instead for all memory-related options.
2740
+ */
2741
+ threadId: string;
2742
+ }) & (OUTPUT extends undefined ? DefaultLLMStreamOptions : DefaultLLMStreamObjectOptions);
2743
+
2744
+ declare class Tool<TSchemaIn extends z.ZodSchema | undefined = undefined, TSchemaOut extends z.ZodSchema | undefined = undefined, TContext extends ToolExecutionContext<TSchemaIn> = ToolExecutionContext<TSchemaIn>> extends Tool$1<TSchemaIn, TSchemaOut, TContext> {
2745
+ constructor(opts: ToolAction<TSchemaIn, TSchemaOut, TContext>);
2746
+ }
2747
+
2748
+ interface NewAgentNetworkConfig {
2749
+ id: string;
2750
+ name: string;
2751
+ instructions: DynamicArgument<string>;
2752
+ model: DynamicArgument<MastraLanguageModel>;
2753
+ agents: DynamicArgument<Record<string, Agent>>;
2754
+ workflows?: DynamicArgument<Record<string, Workflow>>;
2755
+ tools?: DynamicArgument<Record<string, Tool<any, any, any>>>;
2756
+ memory?: DynamicArgument<MastraMemory>;
2757
+ defaultAgent?: DynamicArgument<Agent>;
2758
+ }
2759
+ declare class NewAgentNetwork extends MastraBase {
2760
+ #private;
2761
+ id: string;
2762
+ name: string;
2763
+ constructor({ id, name, instructions, model, agents, workflows, memory, tools, defaultAgent, }: NewAgentNetworkConfig);
2764
+ __registerMastra(mastra: Mastra): void;
2765
+ private beforeRun;
2766
+ getAgents({ runtimeContext }: {
2767
+ runtimeContext?: RuntimeContext;
2768
+ }): Promise<Record<string, Agent<string, ToolsInput, Record<string, Metric>>>>;
2769
+ getWorkflows({ runtimeContext }: {
2770
+ runtimeContext?: RuntimeContext;
2771
+ }): Promise<Record<string, Workflow<any, Step<string, any, any, any, any, any>[], string, z.ZodType<any, z.ZodTypeDef, any>, z.ZodType<any, z.ZodTypeDef, any>, z.ZodType<any, z.ZodTypeDef, any>>>>;
2772
+ getTools({ runtimeContext }: {
2773
+ runtimeContext?: RuntimeContext;
2774
+ }): Promise<Record<string, Tool<undefined, undefined, ToolExecutionContext<undefined>>>>;
2775
+ getMemory({ runtimeContext }: {
2776
+ runtimeContext?: RuntimeContext;
2777
+ }): Promise<MastraMemory | undefined>;
2778
+ getInstructions({ runtimeContext }: {
2779
+ runtimeContext?: RuntimeContext;
2780
+ }): Promise<string>;
2781
+ getRoutingAgent({ runtimeContext }: {
2782
+ runtimeContext?: RuntimeContext;
2783
+ }): Promise<Agent<"routing-agent", ToolsInput, Record<string, Metric>>>;
2784
+ loop(message: string, { runtimeContext, maxIterations, }: {
2785
+ runtimeContext?: RuntimeContext;
2786
+ maxIterations?: number;
2787
+ }): Promise<{
2788
+ status: "success";
2789
+ result: {
2790
+ text: string;
2791
+ iteration: number;
2792
+ };
2793
+ steps: {
2794
+ [x: string]: StepResult<any, any, any, any> | StepResult<unknown, unknown, unknown, unknown>;
2795
+ };
2796
+ }>;
2797
+ loopStream(message: string, { runtimeContext, maxIterations, threadId, resourceId, }: {
2798
+ runtimeContext?: RuntimeContext;
2799
+ maxIterations?: number;
2800
+ threadId?: string;
2801
+ resourceId?: string;
2802
+ }): Promise<{
2803
+ stream: stream_web.ReadableStream<StreamEvent>;
2804
+ getWorkflowState: () => Promise<WorkflowResult<z.ZodObject<{
2805
+ task: z.ZodString;
2806
+ resourceId: z.ZodString;
2807
+ resourceType: z.ZodEnum<["agent", "workflow", "none", "tool", "none"]>;
2808
+ prompt: z.ZodString;
2809
+ result: z.ZodString;
2810
+ isComplete: z.ZodOptional<z.ZodBoolean>;
2811
+ completionReason: z.ZodOptional<z.ZodString>;
2812
+ iteration: z.ZodNumber;
2813
+ }, "strip", z.ZodTypeAny, {
2814
+ prompt: string;
2815
+ resourceId: string;
2816
+ result: string;
2817
+ task: string;
2818
+ resourceType: "none" | "tool" | "workflow" | "agent";
2819
+ iteration: number;
2820
+ isComplete?: boolean | undefined;
2821
+ completionReason?: string | undefined;
2822
+ }, {
2823
+ prompt: string;
2824
+ resourceId: string;
2825
+ result: string;
2826
+ task: string;
2827
+ resourceType: "none" | "tool" | "workflow" | "agent";
2828
+ iteration: number;
2829
+ isComplete?: boolean | undefined;
2830
+ completionReason?: string | undefined;
2831
+ }>, Step<string, any, any, any, any, DefaultEngineType>[]>>;
2832
+ }>;
2833
+ createWorkflow({ runtimeContext }: {
2834
+ runtimeContext?: RuntimeContext;
2835
+ }): Workflow<DefaultEngineType, Step<string, any, any, any, any, DefaultEngineType>[], "Agent-Network-Outer-Workflow", z.ZodObject<{
2836
+ task: z.ZodString;
2837
+ resourceId: z.ZodString;
2838
+ resourceType: z.ZodEnum<["agent", "workflow", "none", "tool", "none"]>;
2839
+ result: z.ZodOptional<z.ZodString>;
2840
+ iteration: z.ZodNumber;
2841
+ threadId: z.ZodOptional<z.ZodString>;
2842
+ threadResourceId: z.ZodOptional<z.ZodString>;
2843
+ isOneOff: z.ZodBoolean;
2844
+ verboseIntrospection: z.ZodBoolean;
2845
+ }, "strip", z.ZodTypeAny, {
2846
+ resourceId: string;
2847
+ task: string;
2848
+ resourceType: "none" | "tool" | "workflow" | "agent";
2849
+ iteration: number;
2850
+ isOneOff: boolean;
2851
+ verboseIntrospection: boolean;
2852
+ threadId?: string | undefined;
2853
+ result?: string | undefined;
2854
+ threadResourceId?: string | undefined;
2855
+ }, {
2856
+ resourceId: string;
2857
+ task: string;
2858
+ resourceType: "none" | "tool" | "workflow" | "agent";
2859
+ iteration: number;
2860
+ isOneOff: boolean;
2861
+ verboseIntrospection: boolean;
2862
+ threadId?: string | undefined;
2863
+ result?: string | undefined;
2864
+ threadResourceId?: string | undefined;
2865
+ }>, z.ZodObject<{
2866
+ task: z.ZodString;
2867
+ resourceId: z.ZodString;
2868
+ resourceType: z.ZodEnum<["agent", "workflow", "none", "tool", "none"]>;
2869
+ prompt: z.ZodString;
2870
+ result: z.ZodString;
2871
+ isComplete: z.ZodOptional<z.ZodBoolean>;
2872
+ completionReason: z.ZodOptional<z.ZodString>;
2873
+ iteration: z.ZodNumber;
2874
+ threadId: z.ZodOptional<z.ZodString>;
2875
+ threadResourceId: z.ZodOptional<z.ZodString>;
2876
+ isOneOff: z.ZodBoolean;
2877
+ }, "strip", z.ZodTypeAny, {
2878
+ prompt: string;
2879
+ resourceId: string;
2880
+ result: string;
2881
+ task: string;
2882
+ resourceType: "none" | "tool" | "workflow" | "agent";
2883
+ iteration: number;
2884
+ isOneOff: boolean;
2885
+ threadId?: string | undefined;
2886
+ threadResourceId?: string | undefined;
2887
+ isComplete?: boolean | undefined;
2888
+ completionReason?: string | undefined;
2889
+ }, {
2890
+ prompt: string;
2891
+ resourceId: string;
2892
+ result: string;
2893
+ task: string;
2894
+ resourceType: "none" | "tool" | "workflow" | "agent";
2895
+ iteration: number;
2896
+ isOneOff: boolean;
2897
+ threadId?: string | undefined;
2898
+ threadResourceId?: string | undefined;
2899
+ isComplete?: boolean | undefined;
2900
+ completionReason?: string | undefined;
2901
+ }>, z.ZodObject<{
2902
+ task: z.ZodString;
2903
+ resourceId: z.ZodString;
2904
+ resourceType: z.ZodEnum<["agent", "workflow", "none", "tool", "none"]>;
2905
+ result: z.ZodOptional<z.ZodString>;
2906
+ iteration: z.ZodNumber;
2907
+ threadId: z.ZodOptional<z.ZodString>;
2908
+ threadResourceId: z.ZodOptional<z.ZodString>;
2909
+ isOneOff: z.ZodBoolean;
2910
+ verboseIntrospection: z.ZodBoolean;
2911
+ }, "strip", z.ZodTypeAny, {
2912
+ resourceId: string;
2913
+ task: string;
2914
+ resourceType: "none" | "tool" | "workflow" | "agent";
2915
+ iteration: number;
2916
+ isOneOff: boolean;
2917
+ verboseIntrospection: boolean;
2918
+ threadId?: string | undefined;
2919
+ result?: string | undefined;
2920
+ threadResourceId?: string | undefined;
2921
+ }, {
2922
+ resourceId: string;
2923
+ task: string;
2924
+ resourceType: "none" | "tool" | "workflow" | "agent";
2925
+ iteration: number;
2926
+ isOneOff: boolean;
2927
+ verboseIntrospection: boolean;
2928
+ threadId?: string | undefined;
2929
+ result?: string | undefined;
2930
+ threadResourceId?: string | undefined;
2931
+ }>>;
2932
+ generate(message: string, { runtimeContext, threadId, resourceId, }: {
2933
+ runtimeContext?: RuntimeContext;
2934
+ threadId?: string;
2935
+ resourceId?: string;
2936
+ }): Promise<{
2937
+ task: string;
2938
+ result: string;
2939
+ resourceId: string;
2940
+ resourceType: "none" | "tool" | "workflow" | "agent";
2941
+ }>;
2942
+ stream(message: string, { runtimeContext, threadId, resourceId, }: {
2943
+ runtimeContext?: RuntimeContext;
2944
+ resourceId?: string;
2945
+ threadId?: string;
2946
+ }): Promise<{
2947
+ stream: stream_web.ReadableStream<StreamEvent>;
2948
+ getWorkflowState: () => Promise<WorkflowResult<z.ZodObject<{
2949
+ task: z.ZodString;
2950
+ resourceId: z.ZodString;
2951
+ resourceType: z.ZodEnum<["agent", "workflow", "none", "tool", "none"]>;
2952
+ prompt: z.ZodString;
2953
+ result: z.ZodString;
2954
+ isComplete: z.ZodOptional<z.ZodBoolean>;
2955
+ completionReason: z.ZodOptional<z.ZodString>;
2956
+ iteration: z.ZodNumber;
2957
+ threadId: z.ZodOptional<z.ZodString>;
2958
+ threadResourceId: z.ZodOptional<z.ZodString>;
2959
+ isOneOff: z.ZodBoolean;
2960
+ }, "strip", z.ZodTypeAny, {
2961
+ prompt: string;
2962
+ resourceId: string;
2963
+ result: string;
2964
+ task: string;
2965
+ resourceType: "none" | "tool" | "workflow" | "agent";
2966
+ iteration: number;
2967
+ isOneOff: boolean;
2968
+ threadId?: string | undefined;
2969
+ threadResourceId?: string | undefined;
2970
+ isComplete?: boolean | undefined;
2971
+ completionReason?: string | undefined;
2972
+ }, {
2973
+ prompt: string;
2974
+ resourceId: string;
2975
+ result: string;
2976
+ task: string;
2977
+ resourceType: "none" | "tool" | "workflow" | "agent";
2978
+ iteration: number;
2979
+ isOneOff: boolean;
2980
+ threadId?: string | undefined;
2981
+ threadResourceId?: string | undefined;
2982
+ isComplete?: boolean | undefined;
2983
+ completionReason?: string | undefined;
2984
+ }>, Step<string, any, any, any, any, DefaultEngineType>[]>>;
2985
+ }>;
2986
+ }
2987
+
2988
+ type ConvertedTool = {
2989
+ name: string;
2990
+ description?: string;
2991
+ parameters: InternalCoreTool['parameters'];
2992
+ execute: InternalCoreTool['execute'];
2993
+ toolType?: MCPToolType;
2994
+ outputSchema?: InternalCoreTool['parameters'];
2995
+ };
2996
+ interface MCPServerSSEOptionsBase {
2997
+ /**
2998
+ * Parsed URL of the incoming request
2999
+ */
3000
+ url: URL;
3001
+ /**
3002
+ * Path for establishing the SSE connection (e.g. '/sse')
3003
+ */
3004
+ ssePath: string;
3005
+ /**
3006
+ * Path for POSTing client messages (e.g. '/message')
3007
+ */
3008
+ messagePath: string;
3009
+ }
3010
+ /**
3011
+ * Options for starting an MCP server with SSE transport
3012
+ */
3013
+ interface MCPServerSSEOptions extends MCPServerSSEOptionsBase {
3014
+ /**
3015
+ * Incoming HTTP request
3016
+ */
3017
+ req: http.IncomingMessage;
3018
+ /**
3019
+ * HTTP response (must support .write/.end)
3020
+ */
3021
+ res: http.ServerResponse<http.IncomingMessage>;
3022
+ }
3023
+ /**
3024
+ * Options for starting an MCP server with Hono SSE transport
3025
+ */
3026
+ interface MCPServerHonoSSEOptions extends MCPServerSSEOptionsBase {
3027
+ /**
3028
+ * Incoming Hono context
3029
+ */
3030
+ context: Context;
3031
+ }
3032
+ interface MCPServerHTTPOptions {
3033
+ /**
3034
+ * Parsed URL of the incoming request
3035
+ */
3036
+ url: URL;
3037
+ /**
3038
+ * Path for establishing the HTTP connection (e.g. '/mcp')
3039
+ */
3040
+ httpPath: string;
3041
+ /**
3042
+ * Incoming HTTP request
3043
+ */
3044
+ req: http.IncomingMessage;
3045
+ /**
3046
+ * HTTP response (must support .write/.end)
3047
+ */
3048
+ res: http.ServerResponse<http.IncomingMessage>;
3049
+ /**
3050
+ * Optional options to pass to the transport (e.g. sessionIdGenerator)
3051
+ */
3052
+ options?: any;
3053
+ }
3054
+ /** Describes a source code repository. */
3055
+ interface Repository {
3056
+ /** The URL of the repository (e.g., a GitHub URL). */
3057
+ url: string;
3058
+ /** The source control platform (e.g., 'github', 'gitlab'). */
3059
+ source: 'github' | 'gitlab' | string;
3060
+ /** A unique identifier for the repository at the source. */
3061
+ id: string;
3062
+ }
3063
+ /** Provides details about a specific version of an MCP server. */
3064
+ interface VersionDetail {
3065
+ /** The semantic version string (e.g., "1.0.2"). */
3066
+ version: string;
3067
+ /** The ISO 8601 date-time string when this version was released or registered. */
3068
+ release_date: string;
3069
+ /** Indicates if this version is the latest available. */
3070
+ is_latest: boolean;
3071
+ }
3072
+ /** Base interface for command-line arguments. */
3073
+ interface ArgumentInfo {
3074
+ /** The name of the argument. */
3075
+ name: string;
3076
+ /** A description of what the argument is for. */
3077
+ description: string;
3078
+ /** Whether the argument is required. */
3079
+ is_required: boolean;
3080
+ /** Whether the argument can be specified multiple times. */
3081
+ is_repeatable?: boolean;
3082
+ /** Whether the argument's value can be edited by the user (e.g., in a UI). */
3083
+ is_editable?: boolean;
3084
+ /** A list of predefined choices for the argument's value. */
3085
+ choices?: string[];
3086
+ /** The default value for the argument if not specified. */
3087
+ default_value?: string | number | boolean;
3088
+ }
3089
+ /** Describes a positional argument for a command. */
3090
+ interface PositionalArgumentInfo extends ArgumentInfo {
3091
+ /** The 0-indexed position of the argument. */
3092
+ position: number;
3093
+ }
3094
+ /** Describes a named argument (flag) for a command. */
3095
+ interface NamedArgumentInfo extends ArgumentInfo {
3096
+ /** The short flag for the argument (e.g., "-y"). */
3097
+ short_flag?: string;
3098
+ /** The long flag for the argument (e.g., "--yes"). */
3099
+ long_flag?: string;
3100
+ /** Whether the flag requires a value (e.g., `--config <value>`) or is a boolean flag. */
3101
+ requires_value?: boolean;
3102
+ }
3103
+ /** Describes a subcommand for a command-line tool. */
3104
+ interface SubcommandInfo {
3105
+ /** The name of the subcommand (e.g., "run", "list"). */
3106
+ name: string;
3107
+ /** A description of what the subcommand does. */
3108
+ description: string;
3109
+ /** Whether this subcommand is required if its parent command is used. */
3110
+ is_required?: boolean;
3111
+ /** Nested subcommands. */
3112
+ subcommands?: SubcommandInfo[];
3113
+ /** Positional arguments for this subcommand. */
3114
+ positional_arguments?: PositionalArgumentInfo[];
3115
+ /** Named arguments (flags) for this subcommand. */
3116
+ named_arguments?: NamedArgumentInfo[];
3117
+ }
3118
+ /** Describes a command to run an MCP server package. */
3119
+ interface CommandInfo {
3120
+ /** The primary command executable (e.g., "npx", "docker"). */
3121
+ name: 'npx' | 'docker' | 'pypi' | 'uvx' | string;
3122
+ /** Subcommands to append to the primary command. */
3123
+ subcommands?: SubcommandInfo[];
3124
+ /** Positional arguments for the command. */
3125
+ positional_arguments?: PositionalArgumentInfo[];
3126
+ /** Named arguments (flags) for the command. */
3127
+ named_arguments?: NamedArgumentInfo[];
3128
+ }
3129
+ /** Describes an environment variable required or used by an MCP server package. */
3130
+ interface EnvironmentVariableInfo {
3131
+ /** The name of the environment variable (e.g., "API_KEY"). */
3132
+ name: string;
3133
+ /** A description of what the environment variable is for. */
3134
+ description: string;
3135
+ /** Whether the environment variable is required. */
3136
+ required?: boolean;
3137
+ /** The default value for the environment variable if not set. */
3138
+ default_value?: string;
3139
+ }
3140
+ /** Describes an installable package for an MCP server. */
3141
+ interface PackageInfo {
3142
+ /** The name of the package registry (e.g., "npm", "docker"). */
3143
+ registry_name: 'npm' | 'docker' | 'pypi' | 'homebrew' | string;
3144
+ /** The name of the package. */
3145
+ name: string;
3146
+ /** The version of the package. */
3147
+ version: string;
3148
+ /** The command structure to run this package as an MCP server. */
3149
+ command?: CommandInfo;
3150
+ /** Environment variables relevant to this package. */
3151
+ environment_variables?: EnvironmentVariableInfo[];
3152
+ }
3153
+ /** Describes a remote endpoint for accessing an MCP server. */
3154
+ interface RemoteInfo {
3155
+ /** The transport type for the remote connection (e.g., "sse", "streamable"). */
3156
+ transport_type: 'streamable' | 'sse' | string;
3157
+ /** The URL of the remote endpoint. */
3158
+ url: string;
3159
+ }
3160
+ /** Configuration options for creating an MCPServer instance. */
3161
+ interface MCPServerConfig {
3162
+ /** The display name of the MCP server. */
3163
+ name: string;
3164
+ /** The semantic version of the MCP server. */
3165
+ version: string;
3166
+ /** The tools that this MCP server will expose. */
3167
+ tools: ToolsInput;
3168
+ /**
3169
+ * Optional Agent instances to be exposed as tools.
3170
+ * Each agent will be converted into a tool named 'ask_<agentName>'.
3171
+ */
3172
+ agents?: Record<string, Agent>;
3173
+ /**
3174
+ * Optional Workflow instances to be exposed as tools.
3175
+ * Each workflow will be converted into a tool named 'run_<workflowKey>'.
3176
+ */
3177
+ workflows?: Record<string, Workflow>;
3178
+ /**
3179
+ * Optional unique identifier for the server.
3180
+ * If not provided, a UUID will be generated.
3181
+ * If provided, this ID is considered final and cannot be changed by Mastra.
3182
+ */
3183
+ id?: string;
3184
+ /** Optional description of the MCP server. */
3185
+ description?: string;
3186
+ /** Optional repository information for the server's source code. */
3187
+ repository?: Repository;
3188
+ /**
3189
+ * Optional release date of this server version (ISO 8601 string).
3190
+ * Defaults to the time of instantiation if not provided.
3191
+ */
3192
+ releaseDate?: string;
3193
+ /**
3194
+ * Optional flag indicating if this is the latest version.
3195
+ * Defaults to true if not provided.
3196
+ */
3197
+ isLatest?: boolean;
3198
+ /**
3199
+ * Optional canonical packaging format if the server is distributed as a package
3200
+ * (e.g., "npm", "docker").
3201
+ */
3202
+ packageCanonical?: 'npm' | 'docker' | 'pypi' | 'crates' | string;
3203
+ /** Optional list of installable packages for this server. */
3204
+ packages?: PackageInfo[];
3205
+ /** Optional list of remote access points for this server. */
3206
+ remotes?: RemoteInfo[];
3207
+ }
3208
+ /** Basic information about an MCP server, conforming to the MCP Registry 'Server' schema. */
3209
+ interface ServerInfo {
3210
+ /** The unique ID of the server. */
3211
+ id: string;
3212
+ /** The name of the server. */
3213
+ name: string;
3214
+ /** A description of the server. */
3215
+ description?: string;
3216
+ /** Repository information for the server. */
3217
+ repository?: Repository;
3218
+ /** Detailed version information. */
3219
+ version_detail: VersionDetail;
3220
+ }
3221
+ /** Detailed information about an MCP server, conforming to the MCP Registry 'ServerDetail' schema. */
3222
+ interface ServerDetailInfo extends ServerInfo {
3223
+ /** The canonical packaging format, if applicable. */
3224
+ package_canonical?: MCPServerConfig['packageCanonical'];
3225
+ /** Information about installable packages for this server. */
3226
+ packages?: PackageInfo[];
3227
+ /** Information about remote access points for this server. */
3228
+ remotes?: RemoteInfo[];
3229
+ }
3230
+ /**
3231
+ * The type of tool registered with the MCP server.
3232
+ * This is used to categorize tools in the MCP Server playground.
3233
+ * If not specified, it defaults to a regular tool.
3234
+ */
3235
+ type MCPToolType = 'agent' | 'workflow';
3236
+
3237
+ /**
3238
+ * Abstract base class for MCP server implementations.
3239
+ * This provides a common interface and shared functionality for all MCP servers
3240
+ * that can be registered with Mastra, including handling of server metadata.
3241
+ */
3242
+ declare abstract class MCPServerBase extends MastraBase {
3243
+ /** Tracks if the server ID has been definitively set. */
3244
+ private idWasSet;
3245
+ /** The display name of the MCP server. */
3246
+ readonly name: string;
3247
+ /** The semantic version of the MCP server. */
3248
+ readonly version: string;
3249
+ /** Internal storage for the server's unique ID. */
3250
+ private _id;
3251
+ /** A description of what the MCP server does. */
3252
+ readonly description?: string;
3253
+ /** Repository information for the server's source code. */
3254
+ readonly repository?: Repository;
3255
+ /** The release date of this server version (ISO 8601 string). */
3256
+ readonly releaseDate: string;
3257
+ /** Indicates if this version is the latest available. */
3258
+ readonly isLatest: boolean;
3259
+ /** The canonical packaging format (e.g., "npm", "docker"), if applicable. */
3260
+ readonly packageCanonical?: MCPServerConfig['packageCanonical'];
3261
+ /** Information about installable packages for this server. */
3262
+ readonly packages?: PackageInfo[];
3263
+ /** Information about remote access points for this server. */
3264
+ readonly remotes?: RemoteInfo[];
3265
+ /** The tools registered with and converted by this MCP server. */
3266
+ readonly convertedTools: Record<string, ConvertedTool>;
3267
+ /** Reference to the Mastra instance if this server is registered with one. */
3268
+ mastra: Mastra | undefined;
3269
+ /** Agents to be exposed as tools. */
3270
+ protected readonly agents?: MCPServerConfig['agents'];
3271
+ /** Workflows to be exposed as tools. */
3272
+ protected readonly workflows?: MCPServerConfig['workflows'];
3273
+ /**
3274
+ * Public getter for the server's unique ID.
3275
+ * The ID is set at construction or by Mastra and is read-only afterwards.
3276
+ */
3277
+ get id(): string;
3278
+ /**
3279
+ * Gets a read-only view of the registered tools.
3280
+ * @returns A readonly record of converted tools.
3281
+ */
3282
+ tools(): Readonly<Record<string, ConvertedTool>>;
3283
+ /**
3284
+ * Sets the server's unique ID. This method is typically called by Mastra when
3285
+ * registering the server, using the key provided in the Mastra configuration.
3286
+ * It ensures the ID is set only once.
3287
+ * If an ID was already provided in the MCPServerConfig, this method will be a no-op.
3288
+ * @param id The unique ID to assign to the server.
3289
+ */
3290
+ setId(id: string): void;
3291
+ /**
3292
+ * Abstract method to convert and validate tool definitions provided to the server.
3293
+ * This method will also handle agents passed in the config.
3294
+ * @param tools Tool definitions to convert.
3295
+ * @param agents Agent definitions to convert to tools.
3296
+ * @param workflows Workflow definitions to convert to tools.
3297
+ * @returns A record of converted and validated tools.
3298
+ */
3299
+ abstract convertTools(tools: ToolsInput, agents?: MCPServerConfig['agents'], workflows?: MCPServerConfig['workflows']): Record<string, ConvertedTool>;
3300
+ /**
3301
+ * Internal method used by Mastra to register itself with the server.
3302
+ * @param mastra The Mastra instance.
3303
+ * @internal
3304
+ */
3305
+ __registerMastra(mastra: Mastra): void;
3306
+ /**
3307
+ * Constructor for the MCPServerBase.
3308
+ * @param config Configuration options for the MCP server, including metadata.
3309
+ */
3310
+ constructor(config: MCPServerConfig);
3311
+ /**
3312
+ * Start the MCP server using stdio transport
3313
+ * This is typically used for Windsurf integration
3314
+ */
3315
+ abstract startStdio(): Promise<void>;
3316
+ /**
3317
+ * Start the MCP server using SSE transport
3318
+ * This is typically used for web integration
3319
+ * @param options Options for the SSE transport
3320
+ */
3321
+ abstract startSSE(options: MCPServerSSEOptions): Promise<void>;
3322
+ /**
3323
+ * Start the MCP server using Hono SSE transport
3324
+ * Used for Hono servers
3325
+ * @param options Options for the SSE transport
3326
+ */
3327
+ abstract startHonoSSE(options: MCPServerHonoSSEOptions): Promise<Response | undefined>;
3328
+ /**
3329
+ * Start the MCP server using HTTP transport
3330
+ * @param options Options for the HTTP transport
3331
+ */
3332
+ abstract startHTTP(options: MCPServerHTTPOptions): Promise<void>;
3333
+ /**
3334
+ * Close the MCP server and all its connections
3335
+ */
3336
+ abstract close(): Promise<void>;
3337
+ /**
3338
+ * Gets the basic information about the server, conforming to the MCP Registry 'Server' schema.
3339
+ * This information is suitable for listing multiple servers.
3340
+ * @returns ServerInfo object containing basic server metadata.
3341
+ */
3342
+ abstract getServerInfo(): ServerInfo;
3343
+ /**
3344
+ * Gets detailed information about the server, conforming to the MCP Registry 'ServerDetail' schema.
3345
+ * This includes all information from `getServerInfo` plus package and remote details.
3346
+ * @returns ServerDetailInfo object containing comprehensive server metadata.
3347
+ */
3348
+ abstract getServerDetail(): ServerDetailInfo;
3349
+ /**
3350
+ * Gets a list of tools provided by this MCP server, including their schemas.
3351
+ * @returns An object containing an array of tool information.
3352
+ */
3353
+ abstract getToolListInfo(): {
3354
+ tools: Array<{
3355
+ name: string;
3356
+ description?: string;
3357
+ inputSchema: any;
3358
+ outputSchema?: any;
3359
+ toolType?: MCPToolType;
3360
+ }>;
3361
+ };
3362
+ /**
3363
+ * Gets information for a specific tool provided by this MCP server.
3364
+ * @param toolId The ID/name of the tool to retrieve.
3365
+ * @returns Tool information (name, description, inputSchema) or undefined if not found.
3366
+ */
3367
+ abstract getToolInfo(toolId: string): {
3368
+ name: string;
3369
+ description?: string;
3370
+ inputSchema: any;
3371
+ outputSchema?: any;
3372
+ toolType?: MCPToolType;
3373
+ } | undefined;
3374
+ /**
3375
+ * Executes a specific tool provided by this MCP server.
3376
+ * @param toolId The ID/name of the tool to execute.
3377
+ * @param args The arguments to pass to the tool's execute function.
3378
+ * @param executionContext Optional context for the tool execution (e.g., messages, toolCallId).
3379
+ * @returns A promise that resolves to the result of the tool execution.
3380
+ * @throws Error if the tool is not found, or if execution fails.
3381
+ */
3382
+ abstract executeTool(toolId: string, args: any, executionContext?: {
3383
+ messages?: any[];
3384
+ toolCallId?: string;
3385
+ }): Promise<any>;
3386
+ }
3387
+
3388
+ interface MastraAuthProviderOptions<TUser = unknown> {
3389
+ name?: string;
3390
+ authorizeUser?: (user: TUser, request: HonoRequest) => Promise<boolean> | boolean;
3391
+ }
3392
+ declare abstract class MastraAuthProvider<TUser = unknown> extends MastraBase {
3393
+ constructor(options?: MastraAuthProviderOptions<TUser>);
3394
+ /**
3395
+ * Authenticate a token and return the payload
3396
+ * @param token - The token to authenticate
3397
+ * @param request - The request
3398
+ * @returns The payload
3399
+ */
3400
+ abstract authenticateToken(token: string, request: HonoRequest): Promise<TUser | null>;
3401
+ /**
3402
+ * Authorize a user for a path and method
3403
+ * @param user - The user to authorize
3404
+ * @param request - The request
3405
+ * @returns The authorization result
3406
+ */
3407
+ abstract authorizeUser(user: TUser, request: HonoRequest): Promise<boolean> | boolean;
3408
+ protected registerOptions(opts?: MastraAuthProviderOptions<TUser>): void;
3409
+ }
3410
+
3411
+ type Methods = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'ALL';
3412
+ type ApiRoute = {
3413
+ path: string;
3414
+ method: Methods;
3415
+ handler: Handler;
3416
+ middleware?: MiddlewareHandler | MiddlewareHandler[];
3417
+ openapi?: DescribeRouteOptions;
3418
+ } | {
3419
+ path: string;
3420
+ method: Methods;
3421
+ createHandler: ({ mastra }: {
3422
+ mastra: Mastra;
3423
+ }) => Promise<Handler>;
3424
+ middleware?: MiddlewareHandler | MiddlewareHandler[];
3425
+ openapi?: DescribeRouteOptions;
3426
+ };
3427
+ type Middleware = MiddlewareHandler | {
3428
+ path: string;
3429
+ handler: MiddlewareHandler;
3430
+ };
3431
+ type ContextWithMastra = Context<{
3432
+ Variables: {
3433
+ mastra: Mastra;
3434
+ runtimeContext: RuntimeContext;
3435
+ };
3436
+ }>;
3437
+ type MastraAuthConfig<TUser = unknown> = {
3438
+ /**
3439
+ * Protected paths for the server
3440
+ */
3441
+ protected?: (RegExp | string | [string, Methods | Methods[]])[];
3442
+ /**
3443
+ * Public paths for the server
3444
+ */
3445
+ public?: (RegExp | string | [string, Methods | Methods[]])[];
3446
+ /**
3447
+ * Public paths for the server
3448
+ */
3449
+ authenticateToken?: (token: string, request: HonoRequest) => Promise<TUser>;
3450
+ /**
3451
+ * Authorization function for the server
3452
+ */
3453
+ authorize?: (path: string, method: string, user: TUser, context: ContextWithMastra) => Promise<boolean>;
3454
+ /**
3455
+ * Rules for the server
3456
+ */
3457
+ rules?: {
3458
+ /**
3459
+ * Path for the rule
3460
+ */
3461
+ path?: RegExp | string | string[];
3462
+ /**
3463
+ * Method for the rule
3464
+ */
3465
+ methods?: Methods | Methods[];
3466
+ /**
3467
+ * Condition for the rule
3468
+ */
3469
+ condition?: (user: TUser) => Promise<boolean> | boolean;
3470
+ /**
3471
+ * Allow the rule
3472
+ */
3473
+ allow?: boolean;
3474
+ }[];
3475
+ };
3476
+ type ServerConfig = {
3477
+ /**
3478
+ * Port for the server
3479
+ * @default 4111
3480
+ */
3481
+ port?: number;
3482
+ /**
3483
+ * Host for the server
3484
+ * @default 'localhost'
3485
+ */
3486
+ host?: string;
3487
+ /**
3488
+ * Timeout for the server
3489
+ */
3490
+ timeout?: number;
3491
+ /**
3492
+ * Custom API routes for the server
3493
+ */
3494
+ apiRoutes?: ApiRoute[];
3495
+ /**
3496
+ * Middleware for the server
3497
+ */
3498
+ middleware?: Middleware | Middleware[];
3499
+ /**
3500
+ * CORS configuration for the server
3501
+ * @default { origin: '*', allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], allowHeaders: ['Content-Type', 'Authorization', 'x-mastra-client-type'], exposeHeaders: ['Content-Length', 'X-Requested-With'], credentials: false }
3502
+ */
3503
+ cors?: Parameters<typeof cors>[0] | false;
3504
+ /**
3505
+ * Build configuration for the server
3506
+ */
3507
+ build?: {
3508
+ /**
3509
+ * Enable Swagger UI
3510
+ * @default false
3511
+ */
3512
+ swaggerUI?: boolean;
3513
+ /**
3514
+ * Enable API request logging
3515
+ * @default false
3516
+ */
3517
+ apiReqLogs?: boolean;
3518
+ /**
3519
+ * Enable OpenAPI documentation
3520
+ * @default false
3521
+ */
3522
+ openAPIDocs?: boolean;
3523
+ };
3524
+ /**
3525
+ * Body size limit for the server
3526
+ * @default 4.5mb
3527
+ */
3528
+ bodySizeLimit?: number;
3529
+ /**
3530
+ * Authentication configuration for the server
3531
+ */
3532
+ experimental_auth?: MastraAuthConfig<any> | MastraAuthProvider<any>;
3533
+ };
3534
+
3535
+ interface Config<TAgents extends Record<string, Agent<any>> = Record<string, Agent<any>>, TLegacyWorkflows extends Record<string, LegacyWorkflow> = Record<string, LegacyWorkflow>, TWorkflows extends Record<string, Workflow> = Record<string, Workflow>, TVectors extends Record<string, MastraVector> = Record<string, MastraVector>, TTTS extends Record<string, MastraTTS> = Record<string, MastraTTS>, TLogger extends IMastraLogger = IMastraLogger, TNetworks extends Record<string, AgentNetwork> = Record<string, AgentNetwork>, TVNextNetworks extends Record<string, NewAgentNetwork> = Record<string, NewAgentNetwork>, TMCPServers extends Record<string, MCPServerBase> = Record<string, MCPServerBase>> {
3536
+ agents?: TAgents;
3537
+ networks?: TNetworks;
3538
+ vnext_networks?: TVNextNetworks;
3539
+ storage?: MastraStorage;
3540
+ vectors?: TVectors;
3541
+ logger?: TLogger | false;
3542
+ legacy_workflows?: TLegacyWorkflows;
3543
+ workflows?: TWorkflows;
3544
+ tts?: TTTS;
3545
+ telemetry?: OtelConfig;
3546
+ deployer?: MastraDeployer;
3547
+ server?: ServerConfig;
3548
+ mcpServers?: TMCPServers;
3549
+ bundler?: BundlerConfig;
3550
+ /**
3551
+ * Server middleware functions to be applied to API routes
3552
+ * Each middleware can specify a path pattern (defaults to '/api/*')
3553
+ * @deprecated use server.middleware instead
3554
+ */
3555
+ serverMiddleware?: Array<{
3556
+ handler: (c: any, next: () => Promise<void>) => Promise<Response | void>;
3557
+ path?: string;
3558
+ }>;
3559
+ memory?: never;
3560
+ }
3561
+ declare class Mastra<TAgents extends Record<string, Agent<any>> = Record<string, Agent<any>>, TLegacyWorkflows extends Record<string, LegacyWorkflow> = Record<string, LegacyWorkflow>, TWorkflows extends Record<string, Workflow> = Record<string, Workflow>, TVectors extends Record<string, MastraVector> = Record<string, MastraVector>, TTTS extends Record<string, MastraTTS> = Record<string, MastraTTS>, TLogger extends IMastraLogger = IMastraLogger, TNetworks extends Record<string, AgentNetwork> = Record<string, AgentNetwork>, TVNextNetworks extends Record<string, NewAgentNetwork> = Record<string, NewAgentNetwork>, TMCPServers extends Record<string, MCPServerBase> = Record<string, MCPServerBase>> {
3562
+ #private;
3563
+ /**
3564
+ * @deprecated use getTelemetry() instead
3565
+ */
3566
+ get telemetry(): Telemetry | undefined;
3567
+ /**
3568
+ * @deprecated use getStorage() instead
3569
+ */
3570
+ get storage(): MastraStorage | undefined;
3571
+ /**
3572
+ * @deprecated use getMemory() instead
3573
+ */
3574
+ get memory(): MastraMemory | undefined;
3575
+ constructor(config?: Config<TAgents, TLegacyWorkflows, TWorkflows, TVectors, TTTS, TLogger, TNetworks, TVNextNetworks, TMCPServers>);
3576
+ getAgent<TAgentName extends keyof TAgents>(name: TAgentName): TAgents[TAgentName];
3577
+ getAgents(): TAgents;
3578
+ getVector<TVectorName extends keyof TVectors>(name: TVectorName): TVectors[TVectorName];
3579
+ getVectors(): TVectors | undefined;
3580
+ getDeployer(): MastraDeployer | undefined;
3581
+ legacy_getWorkflow<TWorkflowId extends keyof TLegacyWorkflows>(id: TWorkflowId, { serialized }?: {
3582
+ serialized?: boolean;
3583
+ }): TLegacyWorkflows[TWorkflowId];
3584
+ getWorkflow<TWorkflowId extends keyof TWorkflows>(id: TWorkflowId, { serialized }?: {
3585
+ serialized?: boolean;
3586
+ }): TWorkflows[TWorkflowId];
3587
+ legacy_getWorkflows(props?: {
3588
+ serialized?: boolean;
3589
+ }): Record<string, LegacyWorkflow>;
3590
+ getWorkflows(props?: {
3591
+ serialized?: boolean;
3592
+ }): Record<string, Workflow>;
3593
+ setStorage(storage: MastraStorage): void;
3594
+ setLogger({ logger }: {
3595
+ logger: TLogger;
3596
+ }): void;
3597
+ setTelemetry(telemetry: OtelConfig): void;
3598
+ getTTS(): TTTS | undefined;
3599
+ getLogger(): TLogger;
3600
+ getTelemetry(): Telemetry | undefined;
3601
+ getMemory(): MastraMemory | undefined;
3602
+ getStorage(): MastraStorage | undefined;
3603
+ getServerMiddleware(): {
3604
+ handler: (c: any, next: () => Promise<void>) => Promise<Response | void>;
3605
+ path: string;
3606
+ }[];
3607
+ setServerMiddleware(serverMiddleware: Middleware | Middleware[]): void;
3608
+ getNetworks(): AgentNetwork[];
3609
+ vnext_getNetworks(): NewAgentNetwork[];
3610
+ getServer(): ServerConfig | undefined;
3611
+ getBundlerConfig(): BundlerConfig | undefined;
3612
+ /**
3613
+ * Get a specific network by ID
3614
+ * @param networkId - The ID of the network to retrieve
3615
+ * @returns The network with the specified ID, or undefined if not found
3616
+ */
3617
+ getNetwork(networkId: string): AgentNetwork | undefined;
3618
+ vnext_getNetwork(networkId: string): NewAgentNetwork | undefined;
3619
+ getLogsByRunId({ runId, transportId, fromDate, toDate, logLevel, filters, page, perPage, }: {
3620
+ runId: string;
3621
+ transportId: string;
3622
+ fromDate?: Date;
3623
+ toDate?: Date;
3624
+ logLevel?: LogLevel;
3625
+ filters?: Record<string, any>;
3626
+ page?: number;
3627
+ perPage?: number;
3628
+ }): Promise<{
3629
+ logs: BaseLogMessage[];
3630
+ total: number;
3631
+ page: number;
3632
+ perPage: number;
3633
+ hasMore: boolean;
3634
+ }>;
3635
+ getLogs(transportId: string, params?: {
3636
+ fromDate?: Date;
3637
+ toDate?: Date;
3638
+ logLevel?: LogLevel;
3639
+ filters?: Record<string, any>;
3640
+ page?: number;
3641
+ perPage?: number;
3642
+ }): Promise<{
3643
+ logs: BaseLogMessage[];
3644
+ total: number;
3645
+ page: number;
3646
+ perPage: number;
3647
+ hasMore: boolean;
3648
+ }>;
3649
+ /**
3650
+ * Get all registered MCP server instances.
3651
+ * @returns A record of MCP server ID to MCPServerBase instance, or undefined if none are registered.
3652
+ */
3653
+ getMCPServers(): Record<string, MCPServerBase> | undefined;
3654
+ /**
3655
+ * Get a specific MCP server instance.
3656
+ * If a version is provided, it attempts to find the server with that exact logical ID and version.
3657
+ * If no version is provided, it returns the server with the specified logical ID that has the most recent releaseDate.
3658
+ * The logical ID should match the `id` property of the MCPServer instance (typically set via MCPServerConfig.id).
3659
+ * @param serverId - The logical ID of the MCP server to retrieve.
3660
+ * @param version - Optional specific version of the MCP server to retrieve.
3661
+ * @returns The MCP server instance, or undefined if not found or if the specific version is not found.
3662
+ */
3663
+ getMCPServer(serverId: string, version?: string): MCPServerBase | undefined;
3664
+ }
3665
+
3666
+ type MastraPrimitives = {
3667
+ logger?: IMastraLogger;
3668
+ telemetry?: Telemetry;
3669
+ storage?: MastraStorage;
3670
+ agents?: Record<string, Agent>;
3671
+ tts?: Record<string, MastraTTS>;
3672
+ vectors?: Record<string, MastraVector>;
3673
+ memory?: MastraMemory;
3674
+ };
3675
+ type MastraUnion = {
3676
+ [K in keyof Mastra]: Mastra[K];
3677
+ } & MastraPrimitives;
3678
+ interface IExecutionContext<TSchemaIn extends z.ZodSchema | undefined = undefined> {
3679
+ context: TSchemaIn extends z.ZodSchema ? z.infer<TSchemaIn> : {};
3680
+ runId?: string;
3681
+ threadId?: string;
3682
+ resourceId?: string;
3683
+ }
3684
+ interface IAction<TId extends string, TSchemaIn extends z.ZodSchema | undefined, TSchemaOut extends z.ZodSchema | undefined, TContext extends IExecutionContext<TSchemaIn>, TOptions extends unknown = unknown> {
3685
+ id: TId;
3686
+ description?: string;
3687
+ inputSchema?: TSchemaIn;
3688
+ outputSchema?: TSchemaOut;
3689
+ execute?: (context: TContext, options?: TOptions) => Promise<TSchemaOut extends z.ZodSchema ? z.infer<TSchemaOut> : unknown>;
3690
+ }
3691
+
3692
+ declare class SaveQueueManager {
3693
+ private logger?;
3694
+ private debounceMs;
3695
+ private memory?;
3696
+ private static MAX_STALENESS_MS;
3697
+ constructor({ logger, debounceMs, memory }: {
3698
+ logger?: IMastraLogger;
3699
+ debounceMs?: number;
3700
+ memory?: MastraMemory;
3701
+ });
3702
+ private saveQueues;
3703
+ private saveDebounceTimers;
3704
+ /**
3705
+ * Debounces save operations for a thread, ensuring that consecutive save requests
3706
+ * are batched and only the latest is executed after a short delay.
3707
+ * @param threadId - The ID of the thread to debounce saves for.
3708
+ * @param saveFn - The save function to debounce.
3709
+ */
3710
+ private debounceSave;
3711
+ /**
3712
+ * Enqueues a save operation for a thread, ensuring that saves are executed in order and
3713
+ * only one save runs at a time per thread. If a save is already in progress for the thread,
3714
+ * the new save is queued to run after the previous completes.
3715
+ *
3716
+ * @param threadId - The ID of the thread whose messages should be saved.
3717
+ * @param messageList - The MessageList instance containing unsaved messages.
3718
+ * @param memoryConfig - Optional memory configuration to use for saving.
3719
+ */
3720
+ private enqueueSave;
3721
+ /**
3722
+ * Clears any pending debounced save for a thread, preventing the scheduled save
3723
+ * from executing if it hasn't already fired.
3724
+ *
3725
+ * @param threadId - The ID of the thread whose debounced save should be cleared.
3726
+ */
3727
+ clearDebounce(threadId: string): void;
3728
+ /**
3729
+ * Persists any unsaved messages from the MessageList to memory storage.
3730
+ * Drains the list of unsaved messages and writes them using the memory backend.
3731
+ * @param messageList - The MessageList instance for the current thread.
3732
+ * @param memoryConfig - The memory configuration for saving.
3733
+ */
3734
+ private persistUnsavedMessages;
3735
+ /**
3736
+ * Batches a save of unsaved messages for a thread, using debouncing to batch rapid updates.
3737
+ * If the oldest unsaved message is stale (older than MAX_STALENESS_MS), the save is performed immediately.
3738
+ * Otherwise, the save is delayed to batch multiple updates and reduce redundant writes.
3739
+ *
3740
+ * @param messageList - The MessageList instance containing unsaved messages.
3741
+ * @param threadId - The ID of the thread whose messages are being saved.
3742
+ * @param memoryConfig - Optional memory configuration for saving.
3743
+ */
3744
+ batchMessages(messageList: MessageList, threadId?: string, memoryConfig?: MemoryConfig): Promise<void>;
3745
+ /**
3746
+ * Forces an immediate save of unsaved messages for a thread, bypassing any debounce delay.
3747
+ * This is used when a flush to persistent storage is required (e.g., on shutdown or critical transitions).
3748
+ *
3749
+ * @param messageList - The MessageList instance containing unsaved messages.
3750
+ * @param threadId - The ID of the thread whose messages are being saved.
3751
+ * @param memoryConfig - Optional memory configuration for saving.
3752
+ */
3753
+ flushMessages(messageList: MessageList, threadId?: string, memoryConfig?: MemoryConfig): Promise<void>;
3754
+ }
3755
+
3756
+ type IDGenerator = () => string;
3757
+ declare class Agent<TAgentId extends string = string, TTools extends ToolsInput = ToolsInput, TMetrics extends Record<string, Metric> = Record<string, Metric>> extends MastraBase {
3758
+ #private;
3759
+ id: TAgentId;
3760
+ name: TAgentId;
3761
+ readonly model?: DynamicArgument<MastraLanguageModel>;
3762
+ /** @deprecated This property is deprecated. Use evals instead. */
3763
+ metrics: TMetrics;
3764
+ evals: TMetrics;
3765
+ constructor(config: AgentConfig<TAgentId, TTools, TMetrics>);
3766
+ hasOwnMemory(): boolean;
3767
+ getMemory(): MastraMemory | undefined;
3768
+ get voice(): CompositeVoice;
3769
+ getWorkflows({ runtimeContext, }?: {
3770
+ runtimeContext?: RuntimeContext;
3771
+ }): Promise<Record<string, Workflow>>;
3772
+ getVoice({ runtimeContext }?: {
3773
+ runtimeContext?: RuntimeContext;
3774
+ }): Promise<CompositeVoice | DefaultVoice>;
3775
+ get instructions(): string;
3776
+ getInstructions({ runtimeContext }?: {
3777
+ runtimeContext?: RuntimeContext;
3778
+ }): string | Promise<string>;
3779
+ getDescription(): string;
3780
+ getDefaultGenerateOptions({ runtimeContext, }?: {
3781
+ runtimeContext?: RuntimeContext;
3782
+ }): AgentGenerateOptions | Promise<AgentGenerateOptions>;
3783
+ getDefaultStreamOptions({ runtimeContext }?: {
3784
+ runtimeContext?: RuntimeContext;
3785
+ }): AgentStreamOptions | Promise<AgentStreamOptions>;
3786
+ get tools(): TTools;
3787
+ getTools({ runtimeContext }?: {
3788
+ runtimeContext?: RuntimeContext;
3789
+ }): TTools | Promise<TTools>;
3790
+ get llm(): MastraLLMBase | Promise<MastraLLMBase>;
3791
+ /**
3792
+ * Gets or creates an LLM instance based on the current model
3793
+ * @param options Options for getting the LLM
3794
+ * @returns A promise that resolves to the LLM instance
3795
+ */
3796
+ getLLM({ runtimeContext, model, }?: {
3797
+ runtimeContext?: RuntimeContext;
3798
+ model?: MastraLanguageModel | DynamicArgument<MastraLanguageModel>;
3799
+ }): MastraLLMBase | Promise<MastraLLMBase>;
3800
+ /**
3801
+ * Gets the model, resolving it if it's a function
3802
+ * @param options Options for getting the model
3803
+ * @returns A promise that resolves to the model
3804
+ */
3805
+ getModel({ runtimeContext }?: {
3806
+ runtimeContext?: RuntimeContext;
3807
+ }): MastraLanguageModel | Promise<MastraLanguageModel>;
3808
+ __updateInstructions(newInstructions: string): void;
3809
+ __registerPrimitives(p: MastraPrimitives): void;
3810
+ __registerMastra(mastra: Mastra): void;
3811
+ /**
3812
+ * Set the concrete tools for the agent
3813
+ * @param tools
3814
+ */
3815
+ __setTools(tools: TTools): void;
3816
+ generateTitleFromUserMessage({ message, runtimeContext, model, instructions, }: {
3817
+ message: string | MessageInput;
3818
+ runtimeContext?: RuntimeContext;
3819
+ model?: DynamicArgument<MastraLanguageModel>;
3820
+ instructions?: DynamicArgument<string>;
3821
+ }): Promise<string>;
3822
+ getMostRecentUserMessage(messages: Array<UIMessage>): UIMessage | undefined;
3823
+ genTitle(userMessage: string | MessageInput | undefined, runtimeContext: RuntimeContext, model?: DynamicArgument<MastraLanguageModel>, instructions?: DynamicArgument<string>): Promise<string | undefined>;
3824
+ fetchMemory({ threadId, thread: passedThread, memoryConfig, resourceId, runId, userMessages, systemMessage, messageList, }: {
3825
+ resourceId: string;
3826
+ threadId: string;
3827
+ thread?: StorageThreadType;
3828
+ memoryConfig?: MemoryConfig;
3829
+ userMessages?: CoreMessage$1[];
3830
+ systemMessage?: CoreMessage$1;
3831
+ runId?: string;
3832
+ messageList?: MessageList;
3833
+ }): Promise<{
3834
+ threadId: string;
3835
+ messages: CoreMessage$1[];
3836
+ }>;
3837
+ private getMemoryTools;
3838
+ private getMemoryMessages;
3839
+ private getAssignedTools;
3840
+ private getToolsets;
3841
+ private getClientTools;
3842
+ private getWorkflowTools;
3843
+ private convertTools;
3844
+ /**
3845
+ * Adds response messages from a step to the MessageList and schedules persistence.
3846
+ * This is used for incremental saving: after each agent step, messages are added to a save queue
3847
+ * and a debounced save operation is triggered to avoid redundant writes.
3848
+ *
3849
+ * @param result - The step result containing response messages.
3850
+ * @param messageList - The MessageList instance for the current thread.
3851
+ * @param threadId - The thread ID.
3852
+ * @param memoryConfig - The memory configuration for saving.
3853
+ * @param runId - (Optional) The run ID for logging.
3854
+ */
3855
+ private saveStepMessages;
3856
+ __primitive({ instructions, messages, context, thread, memoryConfig, resourceId, runId, toolsets, clientTools, runtimeContext, generateMessageId, saveQueueManager, }: {
3857
+ instructions?: string;
3858
+ toolsets?: ToolsetsInput;
3859
+ clientTools?: ToolsInput;
3860
+ resourceId?: string;
3861
+ thread?: (Partial<StorageThreadType> & {
3862
+ id: string;
3863
+ }) | undefined;
3864
+ memoryConfig?: MemoryConfig;
3865
+ context?: CoreMessage$1[];
3866
+ runId?: string;
3867
+ messages: string | string[] | CoreMessage$1[] | Message[];
3868
+ runtimeContext: RuntimeContext;
3869
+ generateMessageId: undefined | IDGenerator;
3870
+ saveQueueManager: SaveQueueManager;
3871
+ }): {
3872
+ before: () => Promise<{
3873
+ messageObjects: CoreMessage$1[];
3874
+ convertedTools: Record<string, CoreTool>;
3875
+ messageList: MessageList;
3876
+ thread?: undefined;
3877
+ } | {
3878
+ convertedTools: Record<string, CoreTool>;
3879
+ thread: StorageThreadType;
3880
+ messageList: MessageList;
3881
+ messageObjects: CoreMessage$1[];
3882
+ }>;
3883
+ after: ({ result, thread: threadAfter, threadId, memoryConfig, outputText, runId, messageList, }: {
3884
+ runId: string;
3885
+ result: Record<string, any>;
3886
+ thread: StorageThreadType | null | undefined;
3887
+ threadId?: string;
3888
+ memoryConfig: MemoryConfig | undefined;
3889
+ outputText: string;
3890
+ messageList: MessageList;
3891
+ }) => Promise<void>;
3892
+ };
3893
+ generate<OUTPUT extends ZodSchema | JSONSchema7 | undefined = undefined, EXPERIMENTAL_OUTPUT extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[] | Message[], args?: AgentGenerateOptions<OUTPUT, EXPERIMENTAL_OUTPUT> & {
3894
+ output?: never;
3895
+ experimental_output?: never;
3896
+ }): Promise<GenerateTextResult<any, OUTPUT extends ZodSchema ? z.infer<OUTPUT> : unknown>>;
3897
+ generate<OUTPUT extends ZodSchema | JSONSchema7 | undefined = undefined, EXPERIMENTAL_OUTPUT extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[] | Message[], args?: AgentGenerateOptions<OUTPUT, EXPERIMENTAL_OUTPUT> & {
3898
+ output?: OUTPUT;
3899
+ experimental_output?: never;
3900
+ }): Promise<GenerateObjectResult<OUTPUT extends ZodSchema ? z.infer<OUTPUT> : unknown>>;
3901
+ generate<OUTPUT extends ZodSchema | JSONSchema7 | undefined = undefined, EXPERIMENTAL_OUTPUT extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[] | Message[], args?: AgentGenerateOptions<OUTPUT, EXPERIMENTAL_OUTPUT> & {
3902
+ output?: never;
3903
+ experimental_output?: EXPERIMENTAL_OUTPUT;
3904
+ }): Promise<GenerateTextResult<any, OUTPUT extends ZodSchema ? z.infer<OUTPUT> : unknown> & {
3905
+ object: OUTPUT extends ZodSchema ? z.infer<OUTPUT> : EXPERIMENTAL_OUTPUT extends ZodSchema ? z.infer<EXPERIMENTAL_OUTPUT> : unknown;
3906
+ }>;
3907
+ stream<OUTPUT extends ZodSchema | JSONSchema7 | undefined = undefined, EXPERIMENTAL_OUTPUT extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[] | Message[], args?: AgentStreamOptions<OUTPUT, EXPERIMENTAL_OUTPUT> & {
3908
+ output?: never;
3909
+ experimental_output?: never;
3910
+ }): Promise<StreamTextResult<any, OUTPUT extends ZodSchema ? z.infer<OUTPUT> : unknown>>;
3911
+ stream<OUTPUT extends ZodSchema | JSONSchema7 | undefined = undefined, EXPERIMENTAL_OUTPUT extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[] | Message[], args?: AgentStreamOptions<OUTPUT, EXPERIMENTAL_OUTPUT> & {
3912
+ output?: OUTPUT;
3913
+ experimental_output?: never;
3914
+ }): Promise<StreamObjectResult<any, OUTPUT extends ZodSchema ? z.infer<OUTPUT> : unknown, any>>;
3915
+ stream<OUTPUT extends ZodSchema | JSONSchema7 | undefined = undefined, EXPERIMENTAL_OUTPUT extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[] | Message[], args?: AgentStreamOptions<OUTPUT, EXPERIMENTAL_OUTPUT> & {
3916
+ output?: never;
3917
+ experimental_output?: EXPERIMENTAL_OUTPUT;
3918
+ }): Promise<StreamTextResult<any, OUTPUT extends ZodSchema ? z.infer<OUTPUT> : unknown> & {
3919
+ partialObjectStream: StreamTextResult<any, OUTPUT extends ZodSchema ? z.infer<OUTPUT> : EXPERIMENTAL_OUTPUT extends ZodSchema ? z.infer<EXPERIMENTAL_OUTPUT> : unknown>['experimental_partialOutputStream'];
3920
+ }>;
3921
+ /**
3922
+ * Convert text to speech using the configured voice provider
3923
+ * @param input Text or text stream to convert to speech
3924
+ * @param options Speech options including speaker and provider-specific options
3925
+ * @returns Audio stream
3926
+ * @deprecated Use agent.voice.speak() instead
3927
+ */
3928
+ speak(input: string | NodeJS.ReadableStream, options?: {
3929
+ speaker?: string;
3930
+ [key: string]: any;
3931
+ }): Promise<NodeJS.ReadableStream | void>;
3932
+ /**
3933
+ * Convert speech to text using the configured voice provider
3934
+ * @param audioStream Audio stream to transcribe
3935
+ * @param options Provider-specific transcription options
3936
+ * @returns Text or text stream
3937
+ * @deprecated Use agent.voice.listen() instead
3938
+ */
3939
+ listen(audioStream: NodeJS.ReadableStream, options?: {
3940
+ [key: string]: any;
3941
+ }): Promise<string | NodeJS.ReadableStream | void>;
3942
+ /**
3943
+ * Get a list of available speakers from the configured voice provider
3944
+ * @throws {Error} If no voice provider is configured
3945
+ * @returns {Promise<Array<{voiceId: string}>>} List of available speakers
3946
+ * @deprecated Use agent.voice.getSpeakers() instead
3947
+ */
3948
+ getSpeakers(): Promise<{
3949
+ voiceId: string;
3950
+ }[]>;
3951
+ toStep(): LegacyStep<TAgentId, z.ZodObject<{
3952
+ prompt: z.ZodString;
3953
+ }>, z.ZodObject<{
3954
+ text: z.ZodString;
3955
+ }>, any>;
3956
+ /**
3957
+ * Resolves the configuration for title generation.
3958
+ * @private
3959
+ */
3960
+ private resolveTitleGenerationConfig;
3961
+ /**
3962
+ * Resolves title generation instructions, handling both static strings and dynamic functions
3963
+ * @private
3964
+ */
3965
+ private resolveTitleInstructions;
3966
+ }
3967
+
3968
+ declare abstract class MastraStorage extends MastraBase {
3969
+ /** @deprecated import from { TABLE_WORKFLOW_SNAPSHOT } '@mastra/core/storage' instead */
3970
+ static readonly TABLE_WORKFLOW_SNAPSHOT = "mastra_workflow_snapshot";
3971
+ /** @deprecated import from { TABLE_EVALS } '@mastra/core/storage' instead */
3972
+ static readonly TABLE_EVALS = "mastra_evals";
3973
+ /** @deprecated import from { TABLE_MESSAGES } '@mastra/core/storage' instead */
3974
+ static readonly TABLE_MESSAGES = "mastra_messages";
3975
+ /** @deprecated import from { TABLE_THREADS } '@mastra/core/storage' instead */
3976
+ static readonly TABLE_THREADS = "mastra_threads";
3977
+ /** @deprecated import { TABLE_TRACES } from '@mastra/core/storage' instead */
3978
+ static readonly TABLE_TRACES = "mastra_traces";
3979
+ protected hasInitialized: null | Promise<boolean>;
3980
+ protected shouldCacheInit: boolean;
3981
+ constructor({ name }: {
3982
+ name: string;
3983
+ });
3984
+ get supports(): {
3985
+ selectByIncludeResourceScope: boolean;
3986
+ resourceWorkingMemory: boolean;
3987
+ };
3988
+ protected ensureDate(date: Date | string | undefined): Date | undefined;
3989
+ protected serializeDate(date: Date | string | undefined): string | undefined;
3990
+ /**
3991
+ * Resolves limit for how many messages to fetch
3992
+ *
3993
+ * @param last The number of messages to fetch
3994
+ * @param defaultLimit The default limit to use if last is not provided
3995
+ * @returns The resolved limit
3996
+ */
3997
+ protected resolveMessageLimit({ last, defaultLimit, }: {
3998
+ last: number | false | undefined;
3999
+ defaultLimit: number;
4000
+ }): number;
4001
+ protected getSqlType(type: StorageColumn['type']): string;
4002
+ protected getDefaultValue(type: StorageColumn['type']): string;
4003
+ abstract createTable({ tableName }: {
4004
+ tableName: TABLE_NAMES;
4005
+ schema: Record<string, StorageColumn>;
4006
+ }): Promise<void>;
4007
+ abstract clearTable({ tableName }: {
4008
+ tableName: TABLE_NAMES;
4009
+ }): Promise<void>;
4010
+ abstract alterTable(args: {
4011
+ tableName: TABLE_NAMES;
4012
+ schema: Record<string, StorageColumn>;
4013
+ ifNotExists: string[];
4014
+ }): Promise<void>;
4015
+ abstract insert({ tableName, record }: {
4016
+ tableName: TABLE_NAMES;
4017
+ record: Record<string, any>;
4018
+ }): Promise<void>;
4019
+ abstract batchInsert({ tableName, records, }: {
4020
+ tableName: TABLE_NAMES;
4021
+ records: Record<string, any>[];
4022
+ }): Promise<void>;
4023
+ batchTraceInsert({ records }: {
4024
+ records: Record<string, any>[];
4025
+ }): Promise<void>;
4026
+ abstract load<R>({ tableName, keys }: {
4027
+ tableName: TABLE_NAMES;
4028
+ keys: Record<string, string>;
4029
+ }): Promise<R | null>;
4030
+ abstract getThreadById({ threadId }: {
4031
+ threadId: string;
4032
+ }): Promise<StorageThreadType | null>;
4033
+ abstract getThreadsByResourceId({ resourceId }: {
4034
+ resourceId: string;
4035
+ }): Promise<StorageThreadType[]>;
4036
+ abstract saveThread({ thread }: {
4037
+ thread: StorageThreadType;
4038
+ }): Promise<StorageThreadType>;
4039
+ abstract updateThread({ id, title, metadata, }: {
4040
+ id: string;
4041
+ title: string;
4042
+ metadata: Record<string, unknown>;
4043
+ }): Promise<StorageThreadType>;
4044
+ abstract deleteThread({ threadId }: {
4045
+ threadId: string;
4046
+ }): Promise<void>;
4047
+ getResourceById(_: {
4048
+ resourceId: string;
4049
+ }): Promise<StorageResourceType | null>;
4050
+ saveResource(_: {
4051
+ resource: StorageResourceType;
4052
+ }): Promise<StorageResourceType>;
4053
+ updateResource(_: {
4054
+ resourceId: string;
4055
+ workingMemory?: string;
4056
+ metadata?: Record<string, unknown>;
4057
+ }): Promise<StorageResourceType>;
4058
+ abstract getMessages(args: StorageGetMessagesArg & {
4059
+ format?: 'v1';
4060
+ }): Promise<MastraMessageV1[]>;
4061
+ abstract getMessages(args: StorageGetMessagesArg & {
4062
+ format: 'v2';
4063
+ }): Promise<MastraMessageV2[]>;
4064
+ abstract getMessages({ threadId, resourceId, selectBy, format, }: StorageGetMessagesArg & {
4065
+ format?: 'v1' | 'v2';
4066
+ }): Promise<MastraMessageV1[] | MastraMessageV2[]>;
4067
+ abstract saveMessages(args: {
4068
+ messages: MastraMessageV1[];
4069
+ format?: undefined | 'v1';
4070
+ }): Promise<MastraMessageV1[]>;
4071
+ abstract saveMessages(args: {
4072
+ messages: MastraMessageV2[];
4073
+ format: 'v2';
4074
+ }): Promise<MastraMessageV2[]>;
4075
+ abstract saveMessages(args: {
4076
+ messages: MastraMessageV1[];
4077
+ format?: undefined | 'v1';
4078
+ } | {
4079
+ messages: MastraMessageV2[];
4080
+ format: 'v2';
4081
+ }): Promise<MastraMessageV2[] | MastraMessageV1[]>;
4082
+ abstract updateMessages(args: {
4083
+ messages: Partial<Omit<MastraMessageV2, 'createdAt'>> & {
4084
+ id: string;
4085
+ content?: {
4086
+ metadata?: MastraMessageContentV2['metadata'];
4087
+ content?: MastraMessageContentV2['content'];
4088
+ };
4089
+ }[];
4090
+ }): Promise<MastraMessageV2[]>;
4091
+ abstract getTraces(args: StorageGetTracesArg): Promise<any[]>;
4092
+ init(): Promise<void>;
4093
+ persistWorkflowSnapshot({ workflowName, runId, snapshot, }: {
4094
+ workflowName: string;
4095
+ runId: string;
4096
+ snapshot: WorkflowRunState;
4097
+ }): Promise<void>;
4098
+ loadWorkflowSnapshot({ workflowName, runId, }: {
4099
+ workflowName: string;
4100
+ runId: string;
4101
+ }): Promise<WorkflowRunState | null>;
4102
+ abstract getEvalsByAgentName(agentName: string, type?: 'test' | 'live'): Promise<EvalRow[]>;
4103
+ abstract getWorkflowRuns(args?: {
4104
+ workflowName?: string;
4105
+ fromDate?: Date;
4106
+ toDate?: Date;
4107
+ limit?: number;
4108
+ offset?: number;
4109
+ resourceId?: string;
4110
+ }): Promise<WorkflowRuns>;
4111
+ abstract getWorkflowRunById(args: {
4112
+ runId: string;
4113
+ workflowName?: string;
4114
+ }): Promise<WorkflowRun | null>;
4115
+ abstract getTracesPaginated(args: StorageGetTracesArg): Promise<PaginationInfo & {
4116
+ traces: Trace[];
4117
+ }>;
4118
+ abstract getThreadsByResourceIdPaginated(args: {
4119
+ resourceId: string;
4120
+ page: number;
4121
+ perPage: number;
4122
+ }): Promise<PaginationInfo & {
4123
+ threads: StorageThreadType[];
4124
+ }>;
4125
+ abstract getMessagesPaginated(args: StorageGetMessagesArg & {
4126
+ format?: 'v1' | 'v2';
4127
+ }): Promise<PaginationInfo & {
4128
+ messages: MastraMessageV1[] | MastraMessageV2[];
4129
+ }>;
4130
+ }
4131
+
4132
+ export { type StepGraph as $, Agent as A, type PaginationArgs as B, type CoreTool as C, type StorageGetTracesArg as D, type EvalRow as E, TABLE_WORKFLOW_SNAPSHOT as F, TABLE_EVALS as G, TABLE_MESSAGES as H, TABLE_THREADS as I, TABLE_TRACES as J, TABLE_RESOURCES as K, LegacyWorkflow as L, Mastra as M, NewAgentNetwork as N, TABLE_SCHEMAS as O, type PaginationInfo as P, type VariableReference$1 as Q, type StepResult$1 as R, type StepExecutionContext as S, type ToolsInput as T, type StepAction as U, type VercelTool as V, type WorkflowContext as W, type LegacyWorkflowRunResult as X, type WorkflowOptions as Y, type StepVariableType as Z, type StepNode as _, type MastraPrimitives as a, type MessageResponse as a$, type RetryConfig as a0, type BaseCondition as a1, type ActionContext as a2, WhenConditionReturnValue as a3, type StepDef as a4, type StepCondition as a5, type StepConfig as a6, type StepsRecord$1 as a7, type WorkflowLogMessage as a8, type WorkflowEvent as a9, type CoreSystemMessage as aA, type CoreAssistantMessage as aB, type CoreUserMessage as aC, type CoreToolMessage as aD, type EmbedResult as aE, type EmbedManyResult as aF, type BaseStructuredOutputType as aG, type StructuredOutputType as aH, type StructuredOutputArrayItem as aI, type StructuredOutput as aJ, type GenerateReturn as aK, type StreamReturn as aL, type OutputType as aM, type DefaultLLMTextOptions as aN, type DefaultLLMTextObjectOptions as aO, type DefaultLLMStreamOptions as aP, type DefaultLLMStreamObjectOptions as aQ, type LLMTextOptions as aR, type LLMTextObjectOptions as aS, type LLMStreamOptions as aT, type LLMInnerStreamOptions as aU, type LLMStreamObjectOptions as aV, createMockModel as aW, type Config as aX, type MastraLanguageModel as aY, type DynamicArgument as aZ, type MessageType as a_, type ResolverFunctionInput as aa, type ResolverFunctionOutput as ab, type SubscriberFunctionOutput as ac, type DependencyCheckOutput as ad, type StepResolverOutput as ae, type WorkflowActors as af, type WorkflowActionParams as ag, type WorkflowActions as ah, type LegacyWorkflowState as ai, type StepId as aj, type ExtractSchemaFromStep$1 as ak, type ExtractStepResult as al, type StepInputType as am, type ExtractSchemaType$1 as an, type PathsToStringProps$1 as ao, type LegacyWorkflowRunState as ap, type WorkflowResumeResult as aq, Tool$1 as ar, createTool as as, type InternalCoreTool as at, type ToolExecutionContext as au, type AgentConfig as av, type DefaultEngineType as aw, type WorkflowConfig as ax, type LanguageModel as ay, type CoreMessage as az, MastraMemory as b, type MCPServerConfig as b$, type WorkingMemory as b0, type MemoryConfig as b1, type SharedMemoryConfig as b2, type TraceType as b3, type WorkingMemoryFormat as b4, type WorkingMemoryTemplate as b5, type MemoryProcessorOpts as b6, MemoryProcessor as b7, memoryDefaultOptions as b8, Tool as b9, type VariableReference as bA, type StreamEvent as bB, type WorkflowRunStatus as bC, type WatchEvent as bD, type ZodPathType as bE, type WorkflowRunState as bF, type AgentNetworkConfig as bG, type VoiceEventType as bH, type VoiceEventMap as bI, type VoiceConfig as bJ, MastraVoice as bK, CompositeVoice as bL, DefaultVoice as bM, type ConvertedTool as bN, type MCPServerSSEOptions as bO, type MCPServerHonoSSEOptions as bP, type MCPServerHTTPOptions as bQ, type Repository as bR, type VersionDetail as bS, type ArgumentInfo as bT, type PositionalArgumentInfo as bU, type NamedArgumentInfo as bV, type SubcommandInfo as bW, type CommandInfo as bX, type EnvironmentVariableInfo as bY, type PackageInfo as bZ, type RemoteInfo as b_, type StepFlowEntry as ba, type SerializedStep as bb, type SerializedStepFlowEntry as bc, type StepWithComponent as bd, mapVariable as be, createStep as bf, cloneStep as bg, createWorkflow as bh, cloneWorkflow as bi, type WorkflowResult as bj, Run as bk, type ExecutionGraph as bl, ExecutionEngine as bm, type ExecuteFunction as bn, type Emitter as bo, type StepSuccess as bp, type StepFailure as bq, type StepSuspended as br, type StepRunning as bs, type StepWaiting as bt, type StepResult as bu, type StepsRecord as bv, type DynamicMapping as bw, type PathsToStringProps as bx, type ExtractSchemaType as by, type ExtractSchemaFromStep as bz, type ToolAction as c, type ServerInfo as c0, type ServerDetailInfo as c1, type MCPToolType as c2, MessageList as c3, type ToolsetsInput as c4, type AgentMemoryOption as c5, type AgentGenerateOptions as c6, type AgentStreamOptions as c7, type MastraMessageContentV2 as c8, LegacyStep as d, Workflow as e, type Step as f, AgentNetwork as g, MCPServerBase as h, type Methods as i, type ApiRoute as j, type MastraAuthConfig as k, type ContextWithMastra as l, MastraAuthProvider as m, type MastraAuthProviderOptions as n, MastraStorage as o, type TABLE_NAMES as p, type StorageColumn as q, type StorageThreadType as r, type StorageResourceType as s, type MastraMessageV2 as t, type StorageGetMessagesArg as u, type MastraMessageV1 as v, type WorkflowRuns as w, type WorkflowRun as x, type LegacyWorkflowRuns as y, type LegacyWorkflowRun as z };