@mastra/core 0.0.0-a2a-20250421213654

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 (198) hide show
  1. package/LICENSE.md +46 -0
  2. package/README.md +182 -0
  3. package/agent.d.ts +1 -0
  4. package/base.d.ts +1 -0
  5. package/bundler.d.ts +1 -0
  6. package/deployer.d.ts +1 -0
  7. package/di.d.ts +1 -0
  8. package/dist/agent/index.cjs +10 -0
  9. package/dist/agent/index.d.cts +23 -0
  10. package/dist/agent/index.d.ts +23 -0
  11. package/dist/agent/index.js +1 -0
  12. package/dist/base-BihKcqDY.d.cts +146 -0
  13. package/dist/base-BlGpZfLc.d.ts +2139 -0
  14. package/dist/base-DT2poiVK.d.ts +146 -0
  15. package/dist/base-xpk2ifTz.d.cts +2139 -0
  16. package/dist/base.cjs +10 -0
  17. package/dist/base.d.cts +6 -0
  18. package/dist/base.d.ts +6 -0
  19. package/dist/base.js +1 -0
  20. package/dist/bundler/index.cjs +10 -0
  21. package/dist/bundler/index.d.cts +28 -0
  22. package/dist/bundler/index.d.ts +28 -0
  23. package/dist/bundler/index.js +1 -0
  24. package/dist/chunk-2BVZNKLX.js +153 -0
  25. package/dist/chunk-3C6V2FEP.cjs +38 -0
  26. package/dist/chunk-3PBEAM6M.js +69 -0
  27. package/dist/chunk-3XWBNOSO.cjs +91 -0
  28. package/dist/chunk-5TFGORLG.js +10 -0
  29. package/dist/chunk-7JBINHJX.cjs +37 -0
  30. package/dist/chunk-ANYT6KP7.js +96 -0
  31. package/dist/chunk-BB4KXGBU.js +83 -0
  32. package/dist/chunk-BBDXZGCM.cjs +4758 -0
  33. package/dist/chunk-BUNPX6LU.js +4730 -0
  34. package/dist/chunk-C6A6W6XS.js +77 -0
  35. package/dist/chunk-CLJQYXNM.js +49 -0
  36. package/dist/chunk-D63P5O4Q.cjs +51 -0
  37. package/dist/chunk-DGL5RCEO.js +739 -0
  38. package/dist/chunk-F4WOCJZQ.cjs +65 -0
  39. package/dist/chunk-FKUPMQZP.cjs +270 -0
  40. package/dist/chunk-FPM2XCMS.cjs +92 -0
  41. package/dist/chunk-FRQFWZDN.cjs +2 -0
  42. package/dist/chunk-FY57LEMC.js +35 -0
  43. package/dist/chunk-GHK3HBWN.js +22 -0
  44. package/dist/chunk-H6SGDOA4.cjs +394 -0
  45. package/dist/chunk-HFOT2NFM.js +443 -0
  46. package/dist/chunk-HHDP5KHS.js +61 -0
  47. package/dist/chunk-KAJSLFMA.js +430 -0
  48. package/dist/chunk-KR6AYHNH.cjs +449 -0
  49. package/dist/chunk-KRSZNW2W.cjs +421 -0
  50. package/dist/chunk-KWV5ZLOF.js +90 -0
  51. package/dist/chunk-LANFNMEE.js +127 -0
  52. package/dist/chunk-LGERQTJM.js +190 -0
  53. package/dist/chunk-LZQIMLJV.cjs +71 -0
  54. package/dist/chunk-M6MZXBG5.js +88 -0
  55. package/dist/chunk-MWLZJBPF.js +267 -0
  56. package/dist/chunk-O7IW545H.cjs +167 -0
  57. package/dist/chunk-P6KJ7FZZ.cjs +37 -0
  58. package/dist/chunk-PK5QRKSG.js +35 -0
  59. package/dist/chunk-PSMMSO72.js +394 -0
  60. package/dist/chunk-RIBNDTA6.cjs +449 -0
  61. package/dist/chunk-RWTSGWWL.cjs +81 -0
  62. package/dist/chunk-RZCYBC7D.cjs +12 -0
  63. package/dist/chunk-ST5RMVLG.cjs +87 -0
  64. package/dist/chunk-TEEAQX2B.cjs +741 -0
  65. package/dist/chunk-TNILINST.cjs +103 -0
  66. package/dist/chunk-WAW7QBY4.cjs +24 -0
  67. package/dist/chunk-WEYWYKLG.cjs +130 -0
  68. package/dist/chunk-YK3XJ52U.cjs +192 -0
  69. package/dist/chunk-ZDWFBE5L.js +1 -0
  70. package/dist/chunk-ZI2W5BQV.js +413 -0
  71. package/dist/chunk-ZRMY72JX.js +37 -0
  72. package/dist/deployer/index.cjs +10 -0
  73. package/dist/deployer/index.d.cts +19 -0
  74. package/dist/deployer/index.d.ts +19 -0
  75. package/dist/deployer/index.js +1 -0
  76. package/dist/di/index.cjs +10 -0
  77. package/dist/di/index.d.cts +52 -0
  78. package/dist/di/index.d.ts +52 -0
  79. package/dist/di/index.js +1 -0
  80. package/dist/eval/index.cjs +14 -0
  81. package/dist/eval/index.d.cts +37 -0
  82. package/dist/eval/index.d.ts +37 -0
  83. package/dist/eval/index.js +1 -0
  84. package/dist/hooks/index.cjs +18 -0
  85. package/dist/hooks/index.d.cts +33 -0
  86. package/dist/hooks/index.d.ts +33 -0
  87. package/dist/hooks/index.js +1 -0
  88. package/dist/index-CquI0inB.d.cts +91 -0
  89. package/dist/index-CquI0inB.d.ts +91 -0
  90. package/dist/index.cjs +350 -0
  91. package/dist/index.d.cts +97 -0
  92. package/dist/index.d.ts +97 -0
  93. package/dist/index.js +117 -0
  94. package/dist/integration/index.cjs +14 -0
  95. package/dist/integration/index.d.cts +59 -0
  96. package/dist/integration/index.d.ts +59 -0
  97. package/dist/integration/index.js +1 -0
  98. package/dist/llm/index.cjs +2 -0
  99. package/dist/llm/index.d.cts +23 -0
  100. package/dist/llm/index.d.ts +23 -0
  101. package/dist/llm/index.js +1 -0
  102. package/dist/logger/index.cjs +38 -0
  103. package/dist/logger/index.d.cts +3 -0
  104. package/dist/logger/index.d.ts +3 -0
  105. package/dist/logger/index.js +1 -0
  106. package/dist/mastra/index.cjs +10 -0
  107. package/dist/mastra/index.d.cts +23 -0
  108. package/dist/mastra/index.d.ts +23 -0
  109. package/dist/mastra/index.js +1 -0
  110. package/dist/memory/index.cjs +14 -0
  111. package/dist/memory/index.d.cts +23 -0
  112. package/dist/memory/index.d.ts +23 -0
  113. package/dist/memory/index.js +1 -0
  114. package/dist/network/index.cjs +305 -0
  115. package/dist/network/index.d.cts +23 -0
  116. package/dist/network/index.d.ts +23 -0
  117. package/dist/network/index.js +303 -0
  118. package/dist/relevance/index.cjs +18 -0
  119. package/dist/relevance/index.d.cts +43 -0
  120. package/dist/relevance/index.d.ts +43 -0
  121. package/dist/relevance/index.js +1 -0
  122. package/dist/server/index.cjs +17 -0
  123. package/dist/server/index.d.cts +39 -0
  124. package/dist/server/index.d.ts +39 -0
  125. package/dist/server/index.js +15 -0
  126. package/dist/storage/index.cjs +35 -0
  127. package/dist/storage/index.d.cts +23 -0
  128. package/dist/storage/index.d.ts +23 -0
  129. package/dist/storage/index.js +2 -0
  130. package/dist/storage/libsql/index.cjs +506 -0
  131. package/dist/storage/libsql/index.d.cts +106 -0
  132. package/dist/storage/libsql/index.d.ts +106 -0
  133. package/dist/storage/libsql/index.js +503 -0
  134. package/dist/telemetry/index.cjs +26 -0
  135. package/dist/telemetry/index.d.cts +59 -0
  136. package/dist/telemetry/index.d.ts +59 -0
  137. package/dist/telemetry/index.js +1 -0
  138. package/dist/telemetry/otel-vendor.cjs +103 -0
  139. package/dist/telemetry/otel-vendor.d.cts +20 -0
  140. package/dist/telemetry/otel-vendor.d.ts +20 -0
  141. package/dist/telemetry/otel-vendor.js +57 -0
  142. package/dist/tools/index.cjs +18 -0
  143. package/dist/tools/index.d.cts +24 -0
  144. package/dist/tools/index.d.ts +24 -0
  145. package/dist/tools/index.js +1 -0
  146. package/dist/tts/index.cjs +10 -0
  147. package/dist/tts/index.d.cts +28 -0
  148. package/dist/tts/index.d.ts +28 -0
  149. package/dist/tts/index.js +1 -0
  150. package/dist/types-BtMyV38I.d.cts +17 -0
  151. package/dist/types-BtMyV38I.d.ts +17 -0
  152. package/dist/utils.cjs +54 -0
  153. package/dist/utils.d.cts +101 -0
  154. package/dist/utils.d.ts +101 -0
  155. package/dist/utils.js +1 -0
  156. package/dist/vector/filter/index.cjs +10 -0
  157. package/dist/vector/filter/index.d.cts +90 -0
  158. package/dist/vector/filter/index.d.ts +90 -0
  159. package/dist/vector/filter/index.js +1 -0
  160. package/dist/vector/index.cjs +10 -0
  161. package/dist/vector/index.d.cts +66 -0
  162. package/dist/vector/index.d.ts +66 -0
  163. package/dist/vector/index.js +1 -0
  164. package/dist/vector/libsql/index.cjs +14 -0
  165. package/dist/vector/libsql/index.d.cts +49 -0
  166. package/dist/vector/libsql/index.d.ts +49 -0
  167. package/dist/vector/libsql/index.js +1 -0
  168. package/dist/voice/index.cjs +18 -0
  169. package/dist/voice/index.d.cts +35 -0
  170. package/dist/voice/index.d.ts +35 -0
  171. package/dist/voice/index.js +1 -0
  172. package/dist/workflows/index.cjs +94 -0
  173. package/dist/workflows/index.d.cts +85 -0
  174. package/dist/workflows/index.d.ts +85 -0
  175. package/dist/workflows/index.js +1 -0
  176. package/eval.d.ts +1 -0
  177. package/hooks.d.ts +1 -0
  178. package/integration.d.ts +1 -0
  179. package/llm.d.ts +1 -0
  180. package/logger.d.ts +1 -0
  181. package/mastra.d.ts +1 -0
  182. package/memory.d.ts +1 -0
  183. package/network.d.ts +1 -0
  184. package/package.json +181 -0
  185. package/relevance.d.ts +1 -0
  186. package/server.d.ts +1 -0
  187. package/storage/libsql.d.ts +1 -0
  188. package/storage.d.ts +1 -0
  189. package/telemetry/otel-vendor.d.ts +1 -0
  190. package/telemetry.d.ts +1 -0
  191. package/tools.d.ts +1 -0
  192. package/tts.d.ts +1 -0
  193. package/utils.d.ts +1 -0
  194. package/vector/filter.d.ts +1 -0
  195. package/vector/libsql.d.ts +1 -0
  196. package/vector.d.ts +1 -0
  197. package/voice.d.ts +1 -0
  198. package/workflows.d.ts +1 -0
@@ -0,0 +1,2139 @@
1
+ import * as ai from 'ai';
2
+ import { Tool as Tool$1, ToolExecutionOptions, LanguageModelV1, CoreMessage as CoreMessage$1, GenerateTextResult, GenerateObjectResult, StreamTextResult, StreamObjectResult, EmbeddingModel, Message, UserContent, AssistantContent, TelemetrySettings, generateText, generateObject, streamText, streamObject, CoreSystemMessage as CoreSystemMessage$1, CoreAssistantMessage as CoreAssistantMessage$1, CoreUserMessage as CoreUserMessage$1, CoreToolMessage as CoreToolMessage$1, EmbedResult as EmbedResult$1, EmbedManyResult as EmbedManyResult$1, GenerateTextOnStepFinishCallback, StreamTextOnFinishCallback, StreamObjectOnFinishCallback, StreamTextOnStepFinishCallback, LanguageModel as LanguageModel$1, DeepPartial, ToolContent } from 'ai';
3
+ import { M as MastraBase, T as Telemetry, O as OtelConfig } from './base-DT2poiVK.js';
4
+ import { a as Metric, M as MetricResult, T as TestInfo } from './types-BtMyV38I.js';
5
+ import { Query } from 'sift';
6
+ import { z, ZodSchema } from 'zod';
7
+ import { JSONSchema7 } from 'json-schema';
8
+ import { Container } from './di/index.js';
9
+ import { B as BaseLogMessage, R as RegisteredLogger, L as Logger, d as Run } from './index-CquI0inB.js';
10
+ import { Span } from '@opentelemetry/api';
11
+ import * as xstate from 'xstate';
12
+ import { Snapshot } from 'xstate';
13
+ import EventEmitter from 'node:events';
14
+ import { MastraVector } from './vector/index.js';
15
+ import { MastraTTS } from './tts/index.js';
16
+ import { MastraDeployer } from './deployer/index.js';
17
+ import { Handler, MiddlewareHandler } from 'hono';
18
+ import { cors } from 'hono/cors';
19
+ import { DescribeRouteOptions } from 'hono-openapi';
20
+
21
+ type VercelTool = Tool$1;
22
+ type CoreTool = {
23
+ id?: string;
24
+ description?: string;
25
+ parameters: ZodSchema;
26
+ execute?: (params: any, options: ToolExecutionOptions) => Promise<any>;
27
+ } & ({
28
+ type?: 'function' | undefined;
29
+ id?: string;
30
+ } | {
31
+ type: 'provider-defined';
32
+ id: `${string}.${string}`;
33
+ args: Record<string, unknown>;
34
+ });
35
+ interface ToolExecutionContext<TSchemaIn extends z.ZodSchema | undefined = undefined> extends IExecutionContext<TSchemaIn> {
36
+ mastra?: MastraUnion;
37
+ container: Container;
38
+ }
39
+ 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> {
40
+ description: string;
41
+ execute?: (context: TContext, options?: ToolExecutionOptions) => Promise<TSchemaOut extends z.ZodSchema ? z.infer<TSchemaOut> : unknown>;
42
+ mastra?: Mastra;
43
+ }
44
+
45
+ declare class Tool<TSchemaIn extends z.ZodSchema | undefined = undefined, TSchemaOut extends z.ZodSchema | undefined = undefined, TContext extends ToolExecutionContext<TSchemaIn> = ToolExecutionContext<TSchemaIn>> implements ToolAction<TSchemaIn, TSchemaOut, TContext> {
46
+ id: string;
47
+ description: string;
48
+ inputSchema?: TSchemaIn;
49
+ outputSchema?: TSchemaOut;
50
+ execute?: ToolAction<TSchemaIn, TSchemaOut, TContext>['execute'];
51
+ mastra?: Mastra;
52
+ constructor(opts: ToolAction<TSchemaIn, TSchemaOut, TContext>);
53
+ }
54
+ declare function createTool<TSchemaIn extends z.ZodSchema | undefined = undefined, TSchemaOut extends z.ZodSchema | undefined = undefined, TContext extends ToolExecutionContext<TSchemaIn> = ToolExecutionContext<TSchemaIn>>(opts: ToolAction<TSchemaIn, TSchemaOut, TContext>): Tool<TSchemaIn, TSchemaOut, TContext>;
55
+
56
+ type AgentNetworkConfig = {
57
+ name: string;
58
+ agents: Agent[];
59
+ model: LanguageModelV1;
60
+ instructions: string;
61
+ };
62
+
63
+ declare class AgentNetwork extends MastraBase {
64
+ #private;
65
+ constructor(config: AgentNetworkConfig);
66
+ formatAgentId(name: string): string;
67
+ getTools(): {
68
+ readonly transmit: Tool<z.ZodObject<{
69
+ actions: z.ZodArray<z.ZodObject<{
70
+ agent: z.ZodString;
71
+ input: z.ZodString;
72
+ includeHistory: z.ZodOptional<z.ZodBoolean>;
73
+ }, "strip", z.ZodTypeAny, {
74
+ input: string;
75
+ agent: string;
76
+ includeHistory?: boolean | undefined;
77
+ }, {
78
+ input: string;
79
+ agent: string;
80
+ includeHistory?: boolean | undefined;
81
+ }>, "many">;
82
+ }, "strip", z.ZodTypeAny, {
83
+ actions: {
84
+ input: string;
85
+ agent: string;
86
+ includeHistory?: boolean | undefined;
87
+ }[];
88
+ }, {
89
+ actions: {
90
+ input: string;
91
+ agent: string;
92
+ includeHistory?: boolean | undefined;
93
+ }[];
94
+ }>, undefined, ToolExecutionContext<z.ZodObject<{
95
+ actions: z.ZodArray<z.ZodObject<{
96
+ agent: z.ZodString;
97
+ input: z.ZodString;
98
+ includeHistory: z.ZodOptional<z.ZodBoolean>;
99
+ }, "strip", z.ZodTypeAny, {
100
+ input: string;
101
+ agent: string;
102
+ includeHistory?: boolean | undefined;
103
+ }, {
104
+ input: string;
105
+ agent: string;
106
+ includeHistory?: boolean | undefined;
107
+ }>, "many">;
108
+ }, "strip", z.ZodTypeAny, {
109
+ actions: {
110
+ input: string;
111
+ agent: string;
112
+ includeHistory?: boolean | undefined;
113
+ }[];
114
+ }, {
115
+ actions: {
116
+ input: string;
117
+ agent: string;
118
+ includeHistory?: boolean | undefined;
119
+ }[];
120
+ }>>>;
121
+ };
122
+ getAgentHistory(agentId: string): {
123
+ input: string;
124
+ output: string;
125
+ timestamp: string;
126
+ }[];
127
+ /**
128
+ * Get the history of all agent interactions that have occurred in this network
129
+ * @returns A record of agent interactions, keyed by agent ID
130
+ */
131
+ getAgentInteractionHistory(): {
132
+ [x: string]: {
133
+ input: string;
134
+ output: string;
135
+ timestamp: string;
136
+ }[];
137
+ };
138
+ /**
139
+ * Get a summary of agent interactions in a more readable format, displayed chronologically
140
+ * @returns A formatted string with all agent interactions in chronological order
141
+ */
142
+ getAgentInteractionSummary(): string;
143
+ executeAgent(agentId: string, input: CoreMessage$1[], includeHistory?: boolean, container?: Container): Promise<string>;
144
+ getInstructions(): string;
145
+ getRoutingAgent(): Agent<string, ToolsInput, Record<string, Metric>>;
146
+ getAgents(): Agent<string, ToolsInput, Record<string, Metric>>[];
147
+ generate<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[], args?: AgentGenerateOptions<Z> & {
148
+ output?: never;
149
+ experimental_output?: never;
150
+ }): Promise<GenerateTextResult<any, Z extends ZodSchema ? z.infer<Z> : unknown>>;
151
+ generate<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[], args?: AgentGenerateOptions<Z> & ({
152
+ output: Z;
153
+ experimental_output?: never;
154
+ } | {
155
+ experimental_output: Z;
156
+ output?: never;
157
+ })): Promise<GenerateObjectResult<Z extends ZodSchema ? z.infer<Z> : unknown>>;
158
+ stream<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[], args?: AgentStreamOptions<Z> & {
159
+ output?: never;
160
+ experimental_output?: never;
161
+ }): Promise<StreamTextResult<any, Z extends ZodSchema ? z.infer<Z> : unknown>>;
162
+ stream<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[], args?: AgentStreamOptions<Z> & ({
163
+ output: Z;
164
+ experimental_output?: never;
165
+ } | {
166
+ experimental_output: Z;
167
+ output?: never;
168
+ })): Promise<StreamObjectResult<any, Z extends ZodSchema ? z.infer<Z> : unknown, any>>;
169
+ __registerMastra(p: Mastra): void;
170
+ }
171
+
172
+ interface WorkflowOptions<TWorkflowName extends string = string, TSteps extends Step<string, any, any, any>[] = Step<string, any, any, any>[], TTriggerSchema extends z.ZodObject<any> = any, TResultSchema extends z.ZodObject<any> = any> {
173
+ steps?: TSteps;
174
+ name: TWorkflowName;
175
+ triggerSchema?: TTriggerSchema;
176
+ result?: {
177
+ schema: TResultSchema;
178
+ mapping?: {
179
+ [K in keyof z.infer<TResultSchema>]?: any;
180
+ };
181
+ };
182
+ events?: Record<string, {
183
+ schema: z.ZodObject<any>;
184
+ }>;
185
+ retryConfig?: RetryConfig;
186
+ mastra?: Mastra;
187
+ }
188
+ interface StepExecutionContext<TSchemaIn extends z.ZodSchema | undefined = undefined, TContext extends WorkflowContext = WorkflowContext> extends IExecutionContext<TSchemaIn> {
189
+ context: TSchemaIn extends z.ZodSchema ? {
190
+ inputData: z.infer<TSchemaIn>;
191
+ } & TContext : TContext;
192
+ suspend: (payload?: unknown, softSuspend?: any) => Promise<void>;
193
+ runId: string;
194
+ emit: (event: string, data: any) => void;
195
+ mastra?: MastraUnion;
196
+ container: Container;
197
+ }
198
+ 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> {
199
+ mastra?: Mastra;
200
+ payload?: TSchemaIn extends z.ZodSchema ? Partial<z.infer<TSchemaIn>> : unknown;
201
+ execute: (context: TContext) => Promise<TSchemaOut extends z.ZodSchema ? z.infer<TSchemaOut> : unknown>;
202
+ retryConfig?: RetryConfig;
203
+ workflow?: Workflow;
204
+ workflowId?: string;
205
+ }
206
+ interface SimpleConditionalType {
207
+ [key: `${string}.${string}`]: string | Query<any>;
208
+ }
209
+ 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' | {
210
+ id: string;
211
+ };
212
+ type StepNode = {
213
+ id: string;
214
+ step: StepAction<any, any, any, any>;
215
+ config: StepDef<any, any, any, any>[any];
216
+ };
217
+ type StepGraph = {
218
+ initial: StepNode[];
219
+ [key: string]: StepNode[];
220
+ };
221
+ type RetryConfig = {
222
+ attempts?: number;
223
+ delay?: number;
224
+ };
225
+ type VariableReference<TStep extends StepVariableType<any, any, any, any>, TTriggerSchema extends z.ZodObject<any>> = TStep extends StepAction<any, any, any, any> ? {
226
+ step: TStep;
227
+ path: PathsToStringProps<ExtractSchemaType<ExtractSchemaFromStep<TStep, 'outputSchema'>>> | '' | '.';
228
+ } : TStep extends 'trigger' ? {
229
+ step: 'trigger';
230
+ path: PathsToStringProps<ExtractSchemaType<TTriggerSchema>> | '.' | '';
231
+ } : {
232
+ step: {
233
+ id: string;
234
+ };
235
+ path: string;
236
+ };
237
+ interface BaseCondition<TStep extends StepVariableType<any, any, any, any>, TTriggerSchema extends z.ZodObject<any>> {
238
+ ref: TStep extends StepAction<any, any, any, any> ? {
239
+ step: TStep;
240
+ path: PathsToStringProps<ExtractSchemaType<ExtractSchemaFromStep<TStep, 'outputSchema'>>> | '' | '.' | 'status';
241
+ } : TStep extends 'trigger' ? {
242
+ step: 'trigger';
243
+ path: PathsToStringProps<ExtractSchemaType<TTriggerSchema>> | '.' | '';
244
+ } : {
245
+ step: {
246
+ id: string;
247
+ };
248
+ path: string;
249
+ };
250
+ query: Query<any>;
251
+ }
252
+ type ActionContext<TSchemaIn extends z.ZodType<any>> = StepExecutionContext<z.infer<TSchemaIn>, WorkflowContext>;
253
+ declare enum WhenConditionReturnValue {
254
+ CONTINUE = "continue",
255
+ CONTINUE_FAILED = "continue_failed",
256
+ ABORT = "abort",
257
+ LIMBO = "limbo"
258
+ }
259
+ 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, {
260
+ id?: string;
261
+ when?: Condition<any, any> | ((args: {
262
+ context: WorkflowContext;
263
+ mastra?: Mastra;
264
+ }) => Promise<boolean | WhenConditionReturnValue>);
265
+ serializedWhen?: Condition<any, any> | string;
266
+ loopLabel?: string;
267
+ loopType?: 'while' | 'until';
268
+ data: TSchemaIn;
269
+ handler: (args: ActionContext<TSchemaIn>) => Promise<z.infer<TSchemaOut>>;
270
+ }>;
271
+ type StepCondition<TStep extends StepVariableType<any, any, any, any>, TTriggerSchema extends z.ZodObject<any>> = BaseCondition<TStep, TTriggerSchema> | SimpleConditionalType | {
272
+ and: StepCondition<TStep, TTriggerSchema>[];
273
+ } | {
274
+ or: StepCondition<TStep, TTriggerSchema>[];
275
+ } | {
276
+ not: StepCondition<TStep, TTriggerSchema>;
277
+ };
278
+ type Condition<TStep extends StepVariableType<any, any, any, any>, TTriggerSchema extends z.ZodObject<any>> = BaseCondition<TStep, TTriggerSchema> | SimpleConditionalType | {
279
+ and: Condition<TStep, TTriggerSchema>[];
280
+ } | {
281
+ or: Condition<TStep, TTriggerSchema>[];
282
+ } | {
283
+ not: Condition<TStep, TTriggerSchema>;
284
+ };
285
+ 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 Step<string, any, any, any>[] = Step<string, any, any, any>[]> {
286
+ when?: Condition<CondStep, TTriggerSchema> | ((args: {
287
+ context: WorkflowContext<TTriggerSchema, TSteps>;
288
+ mastra?: Mastra;
289
+ }) => Promise<boolean | WhenConditionReturnValue>);
290
+ variables?: StepInputType<TStep, 'inputSchema'> extends never ? Record<string, VariableReference<VarStep, TTriggerSchema>> : {
291
+ [K in keyof StepInputType<TStep, 'inputSchema'>]?: VariableReference<VarStep, TTriggerSchema>;
292
+ };
293
+ '#internal'?: {
294
+ when?: Condition<CondStep, TTriggerSchema> | ((args: {
295
+ context: WorkflowContext<TTriggerSchema, TSteps>;
296
+ mastra?: Mastra;
297
+ }) => Promise<boolean | WhenConditionReturnValue>);
298
+ loopLabel?: string;
299
+ loopType?: 'while' | 'until' | undefined;
300
+ };
301
+ id?: string;
302
+ }
303
+ type StepSuccess<T> = {
304
+ status: 'success';
305
+ output: T;
306
+ };
307
+ type StepSuspended<T> = {
308
+ status: 'suspended';
309
+ suspendPayload?: any;
310
+ output?: T;
311
+ };
312
+ type StepWaiting = {
313
+ status: 'waiting';
314
+ };
315
+ type StepFailure = {
316
+ status: 'failed';
317
+ error: string;
318
+ };
319
+ type StepSkipped = {
320
+ status: 'skipped';
321
+ };
322
+ type StepResult<T> = StepSuccess<T> | StepFailure | StepSuspended<T> | StepWaiting | StepSkipped;
323
+ type StepsRecord<T extends readonly Step<any, any, z.ZodType<any> | undefined>[]> = {
324
+ [K in T[number]['id']]: Extract<T[number], {
325
+ id: K;
326
+ }>;
327
+ };
328
+ interface WorkflowRunResult<T extends z.ZodObject<any>, TSteps extends Step<string, any, z.ZodType<any> | undefined>[], TResult extends z.ZodObject<any>> {
329
+ triggerData?: z.infer<T>;
330
+ result?: z.infer<TResult>;
331
+ results: {
332
+ [K in keyof StepsRecord<TSteps>]: StepsRecord<TSteps>[K]['outputSchema'] extends undefined ? StepResult<unknown> : StepResult<z.infer<NonNullable<StepsRecord<TSteps>[K]['outputSchema']>>>;
333
+ };
334
+ runId: string;
335
+ timestamp: number;
336
+ activePaths: Map<keyof StepsRecord<TSteps>, {
337
+ status: string;
338
+ suspendPayload?: any;
339
+ stepPath: string[];
340
+ }>;
341
+ }
342
+ interface WorkflowContext<TTrigger extends z.ZodObject<any> = any, TSteps extends Step<string, any, any, any>[] = Step<string, any, any, any>[], TInputData extends Record<string, any> = Record<string, any>> {
343
+ isResume?: {
344
+ runId: string;
345
+ stepId: string;
346
+ };
347
+ mastra?: MastraUnion;
348
+ steps: {
349
+ [K in keyof StepsRecord<TSteps>]: StepsRecord<TSteps>[K]['outputSchema'] extends undefined ? StepResult<unknown> : StepResult<z.infer<NonNullable<StepsRecord<TSteps>[K]['outputSchema']>>>;
350
+ };
351
+ triggerData: z.infer<TTrigger>;
352
+ inputData: TInputData;
353
+ attempts: Record<string, number>;
354
+ getStepResult(stepId: 'trigger'): z.infer<TTrigger>;
355
+ getStepResult<T extends keyof StepsRecord<TSteps> | unknown>(stepId: T extends keyof StepsRecord<TSteps> ? T : string): T extends keyof StepsRecord<TSteps> ? StepsRecord<TSteps>[T]['outputSchema'] extends undefined ? unknown : z.infer<NonNullable<StepsRecord<TSteps>[T]['outputSchema']>> : T;
356
+ getStepResult<T extends Step<any, any, any, any>>(stepId: T): T['outputSchema'] extends undefined ? unknown : z.infer<NonNullable<T['outputSchema']>>;
357
+ }
358
+ interface WorkflowLogMessage extends BaseLogMessage {
359
+ type: typeof RegisteredLogger.WORKFLOW;
360
+ workflowName: string;
361
+ stepId?: StepId;
362
+ data?: unknown;
363
+ runId?: string;
364
+ }
365
+ type WorkflowEvent = {
366
+ type: 'RESET_TO_PENDING';
367
+ stepId: string;
368
+ } | {
369
+ type: 'CONDITIONS_MET';
370
+ stepId: string;
371
+ } | {
372
+ type: 'CONDITION_FAILED';
373
+ stepId: string;
374
+ error: string;
375
+ } | {
376
+ type: 'SUSPENDED';
377
+ stepId: string;
378
+ suspendPayload?: any;
379
+ softSuspend?: any;
380
+ } | {
381
+ type: 'WAITING';
382
+ stepId: string;
383
+ } | {
384
+ type: `xstate.error.actor.${string}`;
385
+ error: Error;
386
+ } | {
387
+ type: `xstate.done.actor.${string}`;
388
+ output: ResolverFunctionOutput;
389
+ };
390
+ type ResolverFunctionInput = {
391
+ stepNode: StepNode;
392
+ context: WorkflowContext;
393
+ };
394
+ type ResolverFunctionOutput = {
395
+ stepId: StepId;
396
+ result: unknown;
397
+ };
398
+ type SubscriberFunctionOutput = {
399
+ stepId: StepId;
400
+ result: unknown;
401
+ };
402
+ type DependencyCheckOutput = {
403
+ type: 'CONDITIONS_MET';
404
+ } | {
405
+ type: 'CONDITIONS_SKIPPED';
406
+ } | {
407
+ type: 'CONDITIONS_SKIP_TO_COMPLETED';
408
+ } | {
409
+ type: 'CONDITION_FAILED';
410
+ error: string;
411
+ } | {
412
+ type: 'SUSPENDED';
413
+ } | {
414
+ type: 'WAITING';
415
+ } | {
416
+ type: 'CONDITIONS_LIMBO';
417
+ };
418
+ type StepResolverOutput = {
419
+ type: 'STEP_SUCCESS';
420
+ output: unknown;
421
+ } | {
422
+ type: 'STEP_FAILED';
423
+ error: string;
424
+ } | {
425
+ type: 'STEP_WAITING';
426
+ };
427
+ type WorkflowActors = {
428
+ resolverFunction: {
429
+ input: ResolverFunctionInput;
430
+ output: StepResolverOutput;
431
+ };
432
+ conditionCheck: {
433
+ input: {
434
+ context: WorkflowContext;
435
+ stepId: string;
436
+ };
437
+ output: DependencyCheckOutput;
438
+ };
439
+ spawnSubscriberFunction: {
440
+ input: {
441
+ context: WorkflowContext;
442
+ stepId: string;
443
+ };
444
+ output: SubscriberFunctionOutput;
445
+ };
446
+ };
447
+ type WorkflowActionParams = {
448
+ stepId: string;
449
+ };
450
+ type WorkflowActions = {
451
+ type: 'updateStepResult' | 'setStepError' | 'notifyStepCompletion' | 'decrementAttemptCount';
452
+ params: WorkflowActionParams;
453
+ };
454
+ type WorkflowState = {
455
+ [key: string]: {
456
+ initial: 'pending';
457
+ states: {
458
+ pending: {
459
+ invoke: {
460
+ src: 'conditionCheck';
461
+ input: ({ context }: {
462
+ context: WorkflowContext;
463
+ }) => {
464
+ context: WorkflowContext;
465
+ stepId: string;
466
+ };
467
+ onDone: [
468
+ {
469
+ guard: (_: any, event: {
470
+ output: DependencyCheckOutput;
471
+ }) => boolean;
472
+ target: 'executing';
473
+ },
474
+ {
475
+ guard: (_: any, event: {
476
+ output: DependencyCheckOutput;
477
+ }) => boolean;
478
+ target: 'waiting';
479
+ }
480
+ ];
481
+ };
482
+ };
483
+ waiting: {
484
+ after: {
485
+ CHECK_INTERVAL: {
486
+ target: 'pending';
487
+ };
488
+ };
489
+ };
490
+ executing: {
491
+ invoke: {
492
+ src: 'resolverFunction';
493
+ input: ({ context }: {
494
+ context: WorkflowContext;
495
+ }) => ResolverFunctionInput;
496
+ onDone: {
497
+ target: 'completed';
498
+ actions: ['updateStepResult'];
499
+ };
500
+ onError: {
501
+ target: 'failed';
502
+ actions: ['setStepError'];
503
+ };
504
+ };
505
+ };
506
+ completed: {
507
+ type: 'final';
508
+ entry: ['notifyStepCompletion'];
509
+ };
510
+ failed: {
511
+ type: 'final';
512
+ entry: ['notifyStepCompletion'];
513
+ };
514
+ };
515
+ };
516
+ };
517
+ declare const StepIdBrand: unique symbol;
518
+ type StepId = string & {
519
+ readonly [StepIdBrand]: typeof StepIdBrand;
520
+ };
521
+ type ExtractSchemaFromStep<TStep extends StepAction<any, any, any, any>, TKey extends 'inputSchema' | 'outputSchema'> = TStep[TKey];
522
+ type ExtractStepResult<T> = T extends (data: any) => Promise<infer R> ? R : never;
523
+ type StepInputType<TStep extends StepAction<any, any, any, any>, TKey extends 'inputSchema' | 'outputSchema'> = ExtractSchemaFromStep<TStep, TKey> extends infer Schema ? Schema extends z.ZodType<any> ? z.infer<Schema> : never : never;
524
+ type ExtractSchemaType<T extends z.ZodSchema> = T extends z.ZodSchema<infer V> ? V : never;
525
+ type PathsToStringProps<T> = T extends object ? {
526
+ [K in keyof T]: T[K] extends object ? K extends string ? K | `${K}.${PathsToStringProps<T[K]>}` : never : K extends string ? K : never;
527
+ }[keyof T] : never;
528
+ interface WorkflowRunState {
529
+ value: Record<string, string>;
530
+ context: {
531
+ steps: Record<string, {
532
+ status: 'success' | 'failed' | 'suspended' | 'waiting' | 'skipped';
533
+ payload?: any;
534
+ error?: string;
535
+ }>;
536
+ triggerData: Record<string, any>;
537
+ attempts: Record<string, number>;
538
+ };
539
+ activePaths: Array<{
540
+ stepPath: string[];
541
+ stepId: string;
542
+ status: string;
543
+ }>;
544
+ runId: string;
545
+ timestamp: number;
546
+ childStates?: Record<string, WorkflowRunState>;
547
+ suspendedSteps?: Record<string, string>;
548
+ }
549
+ type WorkflowResumeResult<TTriggerSchema extends z.ZodObject<any>> = {
550
+ triggerData?: z.infer<TTriggerSchema>;
551
+ results: Record<string, StepResult<any>>;
552
+ };
553
+
554
+ declare class Step<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> {
555
+ id: TStepId;
556
+ description?: string;
557
+ inputSchema?: TSchemaIn;
558
+ outputSchema?: TSchemaOut;
559
+ payload?: TSchemaIn extends z.ZodSchema ? Partial<z.infer<TSchemaIn>> : unknown;
560
+ execute: (context: TContext) => Promise<TSchemaOut extends z.ZodSchema ? z.infer<TSchemaOut> : unknown>;
561
+ retryConfig?: RetryConfig;
562
+ mastra?: Mastra;
563
+ constructor({ id, description, execute, payload, outputSchema, inputSchema, retryConfig, }: StepAction<TStepId, TSchemaIn, TSchemaOut, TContext>);
564
+ }
565
+ declare function createStep<TId extends string, TSchemaIn extends z.ZodSchema | undefined, TSchemaOut extends z.ZodSchema | undefined, TContext extends StepExecutionContext<TSchemaIn>>(opts: StepAction<TId, TSchemaIn, TSchemaOut, TContext>): Step<TId, TSchemaIn, TSchemaOut, TContext>;
566
+
567
+ declare class Machine<TSteps extends Step<any, any, any, any>[] = Step<any, any, any, any>[], TTriggerSchema extends z.ZodObject<any> = any, TResultSchema extends z.ZodObject<any> = any> extends EventEmitter {
568
+ #private;
569
+ logger: Logger;
570
+ name: string;
571
+ constructor({ logger, mastra, container, workflowInstance, executionSpan, name, runId, steps, stepGraph, retryConfig, startStepId, }: {
572
+ logger: Logger;
573
+ mastra?: Mastra;
574
+ container: Container;
575
+ workflowInstance: WorkflowInstance;
576
+ executionSpan?: Span;
577
+ name: string;
578
+ runId: string;
579
+ steps: Record<string, StepNode>;
580
+ stepGraph: StepGraph;
581
+ retryConfig?: RetryConfig;
582
+ startStepId: string;
583
+ });
584
+ get startStepId(): string;
585
+ execute({ stepId, input, snapshot, resumeData, }?: {
586
+ stepId?: string;
587
+ input?: any;
588
+ snapshot?: Snapshot<any>;
589
+ resumeData?: any;
590
+ }): Promise<Pick<WorkflowRunResult<TTriggerSchema, TSteps, TResultSchema>, 'results' | 'activePaths' | 'runId' | 'timestamp'>>;
591
+ private initializeMachine;
592
+ getSnapshot(): xstate.MachineSnapshot<Omit<WorkflowContext<any, Step<string, any, any, any>[], Record<string, any>>, "getStepResult">, {
593
+ type: "RESET_TO_PENDING";
594
+ stepId: string;
595
+ } | {
596
+ type: "CONDITIONS_MET";
597
+ stepId: string;
598
+ } | {
599
+ type: "CONDITION_FAILED";
600
+ stepId: string;
601
+ error: string;
602
+ } | {
603
+ type: "SUSPENDED";
604
+ stepId: string;
605
+ suspendPayload?: any;
606
+ softSuspend?: any;
607
+ } | {
608
+ type: "WAITING";
609
+ stepId: string;
610
+ } | {
611
+ type: `xstate.error.actor.${string}`;
612
+ error: Error;
613
+ } | {
614
+ type: `xstate.done.actor.${string}`;
615
+ output: ResolverFunctionOutput;
616
+ }, {
617
+ [x: string]: xstate.ActorRefFromLogic<xstate.PromiseActorLogic<{
618
+ type: "CONDITIONS_MET";
619
+ error?: undefined;
620
+ } | {
621
+ type: "CONDITIONS_SKIP_TO_COMPLETED";
622
+ error?: undefined;
623
+ } | {
624
+ type: "CONDITIONS_LIMBO";
625
+ error?: undefined;
626
+ } | {
627
+ type: "CONDITIONS_SKIPPED";
628
+ error?: undefined;
629
+ } | {
630
+ type: "CONDITION_FAILED";
631
+ error: string;
632
+ }, {
633
+ context: WorkflowContext;
634
+ stepNode: StepNode;
635
+ }, xstate.EventObject>> | xstate.ActorRefFromLogic<xstate.PromiseActorLogic<{
636
+ type: "STEP_FAILED";
637
+ error: string;
638
+ stepId: string;
639
+ result?: undefined;
640
+ } | {
641
+ type: "STEP_WAITING";
642
+ stepId: string;
643
+ error?: undefined;
644
+ result?: undefined;
645
+ } | {
646
+ type: "STEP_SUCCESS";
647
+ result: any;
648
+ stepId: string;
649
+ error?: undefined;
650
+ }, ResolverFunctionInput, xstate.EventObject>> | xstate.ActorRefFromLogic<xstate.PromiseActorLogic<{
651
+ steps: {};
652
+ }, {
653
+ parentStepId: string;
654
+ context: WorkflowContext;
655
+ }, xstate.EventObject>> | undefined;
656
+ }, {
657
+ [x: string]: {} | {
658
+ [x: string]: {} | /*elided*/ any | {
659
+ [x: string]: {} | /*elided*/ any | /*elided*/ any;
660
+ };
661
+ } | {
662
+ [x: string]: {} | {
663
+ [x: string]: {} | /*elided*/ any | /*elided*/ any;
664
+ } | /*elided*/ any;
665
+ };
666
+ }, string, xstate.NonReducibleUnknown, xstate.MetaObject, {
667
+ readonly id: string;
668
+ readonly type: "parallel";
669
+ readonly context: ({ input }: {
670
+ spawn: {
671
+ <TSrc extends "conditionCheck" | "resolverFunction" | "spawnSubscriberFunction">(logic: TSrc, ...[options]: ({
672
+ src: "conditionCheck";
673
+ logic: xstate.PromiseActorLogic<{
674
+ type: "CONDITIONS_MET";
675
+ error?: undefined;
676
+ } | {
677
+ type: "CONDITIONS_SKIP_TO_COMPLETED";
678
+ error?: undefined;
679
+ } | {
680
+ type: "CONDITIONS_LIMBO";
681
+ error?: undefined;
682
+ } | {
683
+ type: "CONDITIONS_SKIPPED";
684
+ error?: undefined;
685
+ } | {
686
+ type: "CONDITION_FAILED";
687
+ error: string;
688
+ }, {
689
+ context: WorkflowContext;
690
+ stepNode: StepNode;
691
+ }, xstate.EventObject>;
692
+ id: string | undefined;
693
+ } extends infer T ? T extends {
694
+ src: "conditionCheck";
695
+ logic: xstate.PromiseActorLogic<{
696
+ type: "CONDITIONS_MET";
697
+ error?: undefined;
698
+ } | {
699
+ type: "CONDITIONS_SKIP_TO_COMPLETED";
700
+ error?: undefined;
701
+ } | {
702
+ type: "CONDITIONS_LIMBO";
703
+ error?: undefined;
704
+ } | {
705
+ type: "CONDITIONS_SKIPPED";
706
+ error?: undefined;
707
+ } | {
708
+ type: "CONDITION_FAILED";
709
+ error: string;
710
+ }, {
711
+ context: WorkflowContext;
712
+ stepNode: StepNode;
713
+ }, xstate.EventObject>;
714
+ id: string | undefined;
715
+ } ? T extends {
716
+ src: TSrc;
717
+ } ? xstate.ConditionalRequired<[options?: ({
718
+ id?: T["id"] | undefined;
719
+ systemId?: string;
720
+ input?: xstate.InputFrom<T["logic"]> | undefined;
721
+ syncSnapshot?: boolean;
722
+ } & { [K in xstate.RequiredActorOptions<T>]: unknown; }) | undefined], xstate.IsNotNever<xstate.RequiredActorOptions<T>>> : never : never : never) | ({
723
+ src: "resolverFunction";
724
+ logic: xstate.PromiseActorLogic<{
725
+ type: "STEP_FAILED";
726
+ error: string;
727
+ stepId: string;
728
+ result?: undefined;
729
+ } | {
730
+ type: "STEP_WAITING";
731
+ stepId: string;
732
+ error?: undefined;
733
+ result?: undefined;
734
+ } | {
735
+ type: "STEP_SUCCESS";
736
+ result: any;
737
+ stepId: string;
738
+ error?: undefined;
739
+ }, ResolverFunctionInput, xstate.EventObject>;
740
+ id: string | undefined;
741
+ } extends infer T_1 ? T_1 extends {
742
+ src: "resolverFunction";
743
+ logic: xstate.PromiseActorLogic<{
744
+ type: "STEP_FAILED";
745
+ error: string;
746
+ stepId: string;
747
+ result?: undefined;
748
+ } | {
749
+ type: "STEP_WAITING";
750
+ stepId: string;
751
+ error?: undefined;
752
+ result?: undefined;
753
+ } | {
754
+ type: "STEP_SUCCESS";
755
+ result: any;
756
+ stepId: string;
757
+ error?: undefined;
758
+ }, ResolverFunctionInput, xstate.EventObject>;
759
+ id: string | undefined;
760
+ } ? T_1 extends {
761
+ src: TSrc;
762
+ } ? xstate.ConditionalRequired<[options?: ({
763
+ id?: T_1["id"] | undefined;
764
+ systemId?: string;
765
+ input?: xstate.InputFrom<T_1["logic"]> | undefined;
766
+ syncSnapshot?: boolean;
767
+ } & { [K_1 in xstate.RequiredActorOptions<T_1>]: unknown; }) | undefined], xstate.IsNotNever<xstate.RequiredActorOptions<T_1>>> : never : never : never) | ({
768
+ src: "spawnSubscriberFunction";
769
+ logic: xstate.PromiseActorLogic<{
770
+ steps: {};
771
+ }, {
772
+ parentStepId: string;
773
+ context: WorkflowContext;
774
+ }, xstate.EventObject>;
775
+ id: string | undefined;
776
+ } extends infer T_2 ? T_2 extends {
777
+ src: "spawnSubscriberFunction";
778
+ logic: xstate.PromiseActorLogic<{
779
+ steps: {};
780
+ }, {
781
+ parentStepId: string;
782
+ context: WorkflowContext;
783
+ }, xstate.EventObject>;
784
+ id: string | undefined;
785
+ } ? T_2 extends {
786
+ src: TSrc;
787
+ } ? xstate.ConditionalRequired<[options?: ({
788
+ id?: T_2["id"] | undefined;
789
+ systemId?: string;
790
+ input?: xstate.InputFrom<T_2["logic"]> | undefined;
791
+ syncSnapshot?: boolean;
792
+ } & { [K_2 in xstate.RequiredActorOptions<T_2>]: unknown; }) | undefined], xstate.IsNotNever<xstate.RequiredActorOptions<T_2>>> : never : never : never)): xstate.ActorRefFromLogic<xstate.GetConcreteByKey<xstate.Values<{
793
+ conditionCheck: {
794
+ src: "conditionCheck";
795
+ logic: xstate.PromiseActorLogic<{
796
+ type: "CONDITIONS_MET";
797
+ error?: undefined;
798
+ } | {
799
+ type: "CONDITIONS_SKIP_TO_COMPLETED";
800
+ error?: undefined;
801
+ } | {
802
+ type: "CONDITIONS_LIMBO";
803
+ error?: undefined;
804
+ } | {
805
+ type: "CONDITIONS_SKIPPED";
806
+ error?: undefined;
807
+ } | {
808
+ type: "CONDITION_FAILED";
809
+ error: string;
810
+ }, {
811
+ context: WorkflowContext;
812
+ stepNode: StepNode;
813
+ }, xstate.EventObject>;
814
+ id: string | undefined;
815
+ };
816
+ resolverFunction: {
817
+ src: "resolverFunction";
818
+ logic: xstate.PromiseActorLogic<{
819
+ type: "STEP_FAILED";
820
+ error: string;
821
+ stepId: string;
822
+ result?: undefined;
823
+ } | {
824
+ type: "STEP_WAITING";
825
+ stepId: string;
826
+ error?: undefined;
827
+ result?: undefined;
828
+ } | {
829
+ type: "STEP_SUCCESS";
830
+ result: any;
831
+ stepId: string;
832
+ error?: undefined;
833
+ }, ResolverFunctionInput, xstate.EventObject>;
834
+ id: string | undefined;
835
+ };
836
+ spawnSubscriberFunction: {
837
+ src: "spawnSubscriberFunction";
838
+ logic: xstate.PromiseActorLogic<{
839
+ steps: {};
840
+ }, {
841
+ parentStepId: string;
842
+ context: WorkflowContext;
843
+ }, xstate.EventObject>;
844
+ id: string | undefined;
845
+ };
846
+ }>, "src", TSrc>["logic"]>;
847
+ <TLogic extends xstate.AnyActorLogic>(src: TLogic, ...[options]: xstate.ConditionalRequired<[options?: ({
848
+ id?: never;
849
+ systemId?: string;
850
+ input?: xstate.InputFrom<TLogic> | undefined;
851
+ syncSnapshot?: boolean;
852
+ } & { [K in xstate.RequiredLogicInput<TLogic>]: unknown; }) | undefined], xstate.IsNotNever<xstate.RequiredLogicInput<TLogic>>>): xstate.ActorRefFromLogic<TLogic>;
853
+ };
854
+ input: Omit<WorkflowContext<any, Step<string, any, any, any>[], Record<string, any>>, "getStepResult">;
855
+ self: xstate.ActorRef<xstate.MachineSnapshot<Omit<WorkflowContext<any, Step<string, any, any, any>[], Record<string, any>>, "getStepResult">, {
856
+ type: "RESET_TO_PENDING";
857
+ stepId: string;
858
+ } | {
859
+ type: "CONDITIONS_MET";
860
+ stepId: string;
861
+ } | {
862
+ type: "CONDITION_FAILED";
863
+ stepId: string;
864
+ error: string;
865
+ } | {
866
+ type: "SUSPENDED";
867
+ stepId: string;
868
+ suspendPayload?: any;
869
+ softSuspend?: any;
870
+ } | {
871
+ type: "WAITING";
872
+ stepId: string;
873
+ } | {
874
+ type: `xstate.error.actor.${string}`;
875
+ error: Error;
876
+ } | {
877
+ type: `xstate.done.actor.${string}`;
878
+ output: ResolverFunctionOutput;
879
+ }, Record<string, xstate.AnyActorRef | undefined>, xstate.StateValue, string, unknown, any, any>, {
880
+ type: "RESET_TO_PENDING";
881
+ stepId: string;
882
+ } | {
883
+ type: "CONDITIONS_MET";
884
+ stepId: string;
885
+ } | {
886
+ type: "CONDITION_FAILED";
887
+ stepId: string;
888
+ error: string;
889
+ } | {
890
+ type: "SUSPENDED";
891
+ stepId: string;
892
+ suspendPayload?: any;
893
+ softSuspend?: any;
894
+ } | {
895
+ type: "WAITING";
896
+ stepId: string;
897
+ } | {
898
+ type: `xstate.error.actor.${string}`;
899
+ error: Error;
900
+ } | {
901
+ type: `xstate.done.actor.${string}`;
902
+ output: ResolverFunctionOutput;
903
+ }, xstate.AnyEventObject>;
904
+ }) => {
905
+ mastra?: MastraUnion | undefined;
906
+ triggerData: any;
907
+ isResume?: {
908
+ runId: string;
909
+ stepId: string;
910
+ } | undefined;
911
+ steps: {
912
+ [x: string]: {
913
+ status: "failed";
914
+ error: string;
915
+ } | {
916
+ status: "waiting";
917
+ } | {
918
+ status: "skipped";
919
+ } | {
920
+ status: "success";
921
+ output: unknown;
922
+ } | {
923
+ status: "suspended";
924
+ suspendPayload?: any;
925
+ output?: unknown;
926
+ } | {
927
+ status: "success";
928
+ output: any;
929
+ } | {
930
+ status: "suspended";
931
+ suspendPayload?: any;
932
+ output?: any;
933
+ };
934
+ };
935
+ inputData: Record<string, any>;
936
+ attempts: Record<string, number>;
937
+ };
938
+ readonly states: any;
939
+ }> | undefined;
940
+ }
941
+
942
+ interface WorkflowResultReturn<TResult extends z.ZodObject<any>, T extends z.ZodObject<any>, TSteps extends Step<any, any, any>[]> {
943
+ runId: string;
944
+ start: (props?: {
945
+ triggerData?: z.infer<T>;
946
+ container?: Container;
947
+ } | undefined) => Promise<WorkflowRunResult<T, TSteps, TResult>>;
948
+ watch: (onTransition: (state: Pick<WorkflowRunResult<T, TSteps, TResult>, 'results' | 'activePaths' | 'runId'>) => void) => () => void;
949
+ resume: (props: {
950
+ stepId: string;
951
+ context?: Record<string, any>;
952
+ container?: Container;
953
+ }) => Promise<Omit<WorkflowRunResult<T, TSteps, TResult>, 'runId'> | undefined>;
954
+ resumeWithEvent: (eventName: string, data: any, container?: Container) => Promise<Omit<WorkflowRunResult<T, TSteps, TResult>, 'runId'> | undefined>;
955
+ }
956
+ declare class WorkflowInstance<TSteps extends Step<any, any, any, any>[] = Step<any, any, any, any>[], TTriggerSchema extends z.ZodObject<any> = any, TResult extends z.ZodObject<any> = any> implements WorkflowResultReturn<TResult, TTriggerSchema, TSteps> {
957
+ #private;
958
+ name: string;
959
+ logger: Logger;
960
+ events?: Record<string, {
961
+ schema: z.ZodObject<any>;
962
+ }>;
963
+ constructor({ name, logger, steps, runId, retryConfig, mastra, stepGraph, stepSubscriberGraph, onFinish, onStepTransition, resultMapping, events, }: {
964
+ name: string;
965
+ logger: Logger;
966
+ steps: Record<string, StepNode>;
967
+ mastra?: Mastra;
968
+ retryConfig?: RetryConfig;
969
+ runId?: string;
970
+ stepGraph: StepGraph;
971
+ stepSubscriberGraph: Record<string, StepGraph>;
972
+ onFinish?: () => void;
973
+ onStepTransition?: Set<(state: Pick<WorkflowRunResult<TTriggerSchema, TSteps, TResult>, 'results' | 'activePaths' | 'runId' | 'timestamp'>) => void | Promise<void>>;
974
+ resultMapping?: Record<string, {
975
+ step: StepAction<any, any, any, any>;
976
+ path: string;
977
+ }>;
978
+ events?: Record<string, {
979
+ schema: z.ZodObject<any>;
980
+ }>;
981
+ });
982
+ setState(state: any): void;
983
+ get runId(): string;
984
+ get executionSpan(): Span | undefined;
985
+ watch(onTransition: (state: Pick<WorkflowRunResult<TTriggerSchema, TSteps, TResult>, 'results' | 'activePaths' | 'runId' | 'timestamp'>) => void): () => void;
986
+ start({ triggerData, container }?: {
987
+ triggerData?: z.infer<TTriggerSchema>;
988
+ container?: Container;
989
+ }): Promise<{
990
+ runId: string;
991
+ timestamp: number;
992
+ result?: z.TypeOf<TResult> | undefined;
993
+ triggerData?: z.TypeOf<TTriggerSchema> | undefined;
994
+ results: { [K in keyof StepsRecord<TSteps>]: StepsRecord<TSteps>[K]["outputSchema"] extends undefined ? StepResult<unknown> : StepResult<z.TypeOf<NonNullable<StepsRecord<TSteps>[K]["outputSchema"]>>>; };
995
+ activePaths: Map<TSteps[number]["id"], {
996
+ status: string;
997
+ suspendPayload?: any;
998
+ stepPath: string[];
999
+ }>;
1000
+ }>;
1001
+ private isCompoundDependencyMet;
1002
+ execute({ triggerData, snapshot, stepId, resumeData, container, }?: {
1003
+ stepId?: string;
1004
+ triggerData?: z.infer<TTriggerSchema>;
1005
+ snapshot?: Snapshot<any>;
1006
+ resumeData?: any;
1007
+ container: Container;
1008
+ }): Promise<Omit<WorkflowRunResult<TTriggerSchema, TSteps, TResult>, 'runId'>>;
1009
+ hasSubscribers(stepId: string): boolean;
1010
+ runMachine(parentStepId: string, input: any, container?: Container): Promise<(Pick<WorkflowRunResult<TTriggerSchema, TSteps, TResult>, "runId" | "timestamp" | "results" | "activePaths"> | undefined)[]>;
1011
+ suspend(stepId: string, machine: Machine<TSteps, TTriggerSchema>): Promise<void>;
1012
+ /**
1013
+ * Persists the workflow state to the database
1014
+ */
1015
+ persistWorkflowSnapshot(): Promise<void>;
1016
+ getState(): Promise<WorkflowRunState | null>;
1017
+ resumeWithEvent(eventName: string, data: any, container?: Container): Promise<Omit<WorkflowRunResult<TTriggerSchema, TSteps, TResult>, "runId"> | undefined>;
1018
+ resume({ stepId, context: resumeContext, container, }: {
1019
+ stepId: string;
1020
+ context?: Record<string, any>;
1021
+ container?: Container;
1022
+ }): Promise<Omit<WorkflowRunResult<TTriggerSchema, TSteps, TResult>, "runId"> | undefined>;
1023
+ _resume({ stepId, context: resumeContext, container, }: {
1024
+ stepId: string;
1025
+ context?: Record<string, any>;
1026
+ container: Container;
1027
+ }): Promise<Omit<WorkflowRunResult<TTriggerSchema, TSteps, TResult>, "runId"> | undefined>;
1028
+ }
1029
+
1030
+ type WorkflowBuilder<T extends Workflow<any, any>> = Pick<T, 'step' | 'then' | 'after' | 'while' | 'until' | 'if' | 'else' | 'afterEvent' | 'commit'>;
1031
+ declare class Workflow<TSteps extends Step<string, any, any>[] = Step<string, any, any>[], TStepId extends string = string, TTriggerSchema extends z.ZodObject<any> = any, TResultSchema extends z.ZodObject<any> = any> extends MastraBase {
1032
+ #private;
1033
+ name: TStepId;
1034
+ triggerSchema?: TTriggerSchema;
1035
+ resultSchema?: TResultSchema;
1036
+ resultMapping?: Record<string, {
1037
+ step: StepAction<string, any, any, any>;
1038
+ path: string;
1039
+ }>;
1040
+ events?: Record<string, {
1041
+ schema: z.ZodObject<any>;
1042
+ }>;
1043
+ isNested: boolean;
1044
+ /**
1045
+ * Creates a new Workflow instance
1046
+ * @param name - Identifier for the workflow (not necessarily unique)
1047
+ * @param logger - Optional logger instance
1048
+ */
1049
+ constructor({ name, triggerSchema, result, retryConfig, mastra, events, }: WorkflowOptions<TStepId, TSteps, TTriggerSchema, TResultSchema>);
1050
+ step<TWorkflow extends Workflow<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>;
1051
+ 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>;
1052
+ 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>;
1053
+ 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;
1054
+ then<TWorkflow extends Workflow<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;
1055
+ 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;
1056
+ private loop;
1057
+ 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">;
1058
+ 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">;
1059
+ if<TStep extends StepAction<string, any, any, any>>(condition: StepConfig<TStep, any, any, TTriggerSchema>['when'], ifStep?: TStep | Workflow, elseStep?: TStep | Workflow): this | WorkflowBuilder<this>;
1060
+ else(): WorkflowBuilder<this>;
1061
+ after<TStep extends StepAction<string, any, any, any>>(steps: string | TStep | TStep[] | (TStep | string)[]): Omit<WorkflowBuilder<this>, 'then' | 'after'>;
1062
+ after<TWorkflow extends Workflow<any, any, any, any>>(steps: TWorkflow | TWorkflow[]): Omit<WorkflowBuilder<this>, 'then' | 'after'>;
1063
+ after<TAgent extends Agent<any, any, any>>(steps: TAgent | TAgent[]): Omit<WorkflowBuilder<this>, 'then' | 'after'>;
1064
+ afterEvent(eventName: string): WorkflowBuilder<this>;
1065
+ /**
1066
+ * Executes the workflow with the given trigger data
1067
+ * @param triggerData - Initial data to start the workflow with
1068
+ * @returns Promise resolving to workflow results or rejecting with error
1069
+ * @throws Error if trigger schema validation fails
1070
+ */
1071
+ createRun({ runId, events, }?: {
1072
+ runId?: string;
1073
+ events?: Record<string, {
1074
+ schema: z.ZodObject<any>;
1075
+ }>;
1076
+ }): WorkflowResultReturn<TResultSchema, TTriggerSchema, TSteps>;
1077
+ /**
1078
+ * Gets a workflow run instance by ID
1079
+ * @param runId - ID of the run to retrieve
1080
+ * @returns The workflow run instance if found, undefined otherwise
1081
+ */
1082
+ getRun(runId: string): WorkflowInstance<TSteps, TTriggerSchema, any> | undefined;
1083
+ /**
1084
+ * Rebuilds the machine with the current steps configuration and validates the workflow
1085
+ *
1086
+ * This is the last step of a workflow builder method chain
1087
+ * @throws Error if validation fails
1088
+ *
1089
+ * @returns this instance for method chaining
1090
+ */
1091
+ commit(): this;
1092
+ getWorkflowRuns(): Promise<WorkflowRuns>;
1093
+ getExecutionSpan(runId: string): Span | undefined;
1094
+ getState(runId: string): Promise<WorkflowRunState | null>;
1095
+ resume({ runId, stepId, context: resumeContext, container, }: {
1096
+ runId: string;
1097
+ stepId: string;
1098
+ context?: Record<string, any>;
1099
+ container: Container;
1100
+ }): Promise<Omit<WorkflowRunResult<TTriggerSchema, TSteps, any>, "runId"> | undefined>;
1101
+ watch(onTransition: (state: Pick<WorkflowRunResult<TTriggerSchema, TSteps, TResultSchema>, 'results' | 'activePaths' | 'runId' | 'timestamp'>) => void): () => void;
1102
+ resumeWithEvent(runId: string, eventName: string, data: any): Promise<Omit<WorkflowRunResult<TTriggerSchema, TSteps, any>, "runId"> | undefined>;
1103
+ __registerMastra(mastra: Mastra): void;
1104
+ __registerPrimitives(p: MastraPrimitives): void;
1105
+ get stepGraph(): StepGraph;
1106
+ get stepSubscriberGraph(): Record<string, StepGraph>;
1107
+ get serializedStepGraph(): StepGraph;
1108
+ get serializedStepSubscriberGraph(): Record<string, StepGraph>;
1109
+ get steps(): Record<string, StepAction<string, any, any, any>>;
1110
+ setNested(isNested: boolean): void;
1111
+ toStep(): Step<TStepId, TTriggerSchema, z.ZodType<WorkflowRunResult<TTriggerSchema, TSteps, TResultSchema>>, any>;
1112
+ }
1113
+
1114
+ type MemoryProcessorOpts = {
1115
+ systemMessage?: string;
1116
+ memorySystemMessage?: string;
1117
+ newMessages?: CoreMessage$1[];
1118
+ };
1119
+ /**
1120
+ * Interface for message processors that can filter or transform messages
1121
+ * before they're sent to the LLM.
1122
+ */
1123
+ declare abstract class MemoryProcessor extends MastraBase {
1124
+ /**
1125
+ * Process a list of messages and return a filtered or transformed list.
1126
+ * @param messages The messages to process
1127
+ * @returns The processed messages
1128
+ */
1129
+ process(messages: CoreMessage$1[], _opts: MemoryProcessorOpts): CoreMessage$1[];
1130
+ }
1131
+ /**
1132
+ * Abstract Memory class that defines the interface for storing and retrieving
1133
+ * conversation threads and messages.
1134
+ */
1135
+ declare abstract class MastraMemory extends MastraBase {
1136
+ MAX_CONTEXT_TOKENS?: number;
1137
+ storage: MastraStorage;
1138
+ vector?: MastraVector;
1139
+ embedder?: EmbeddingModel<string>;
1140
+ private processors;
1141
+ protected threadConfig: MemoryConfig;
1142
+ constructor(config: {
1143
+ name: string;
1144
+ } & SharedMemoryConfig);
1145
+ setStorage(storage: MastraStorage): void;
1146
+ setVector(vector: MastraVector): void;
1147
+ setEmbedder(embedder: EmbeddingModel<string>): void;
1148
+ /**
1149
+ * Get a system message to inject into the conversation.
1150
+ * This will be called before each conversation turn.
1151
+ * Implementations can override this to inject custom system messages.
1152
+ */
1153
+ getSystemMessage(_input: {
1154
+ threadId: string;
1155
+ memoryConfig?: MemoryConfig;
1156
+ }): Promise<string | null>;
1157
+ /**
1158
+ * Get tools that should be available to the agent.
1159
+ * This will be called when converting tools for the agent.
1160
+ * Implementations can override this to provide additional tools.
1161
+ */
1162
+ getTools(_config?: MemoryConfig): Record<string, CoreTool>;
1163
+ protected createEmbeddingIndex(dimensions?: number): Promise<{
1164
+ indexName: string;
1165
+ }>;
1166
+ getMergedThreadConfig(config?: MemoryConfig): MemoryConfig;
1167
+ /**
1168
+ * Apply all configured message processors to a list of messages.
1169
+ * @param messages The messages to process
1170
+ * @returns The processed messages
1171
+ */
1172
+ private applyProcessors;
1173
+ processMessages({ messages, processors, ...opts }: {
1174
+ messages: CoreMessage$1[];
1175
+ processors?: MemoryProcessor[];
1176
+ } & MemoryProcessorOpts): CoreMessage$1[];
1177
+ abstract rememberMessages({ threadId, resourceId, vectorMessageSearch, systemMessage, config, }: {
1178
+ threadId: string;
1179
+ resourceId?: string;
1180
+ vectorMessageSearch?: string;
1181
+ systemMessage?: CoreMessage$1;
1182
+ config?: MemoryConfig;
1183
+ }): Promise<{
1184
+ threadId: string;
1185
+ messages: CoreMessage$1[];
1186
+ uiMessages: Message[];
1187
+ }>;
1188
+ estimateTokens(text: string): number;
1189
+ protected parseMessages(messages: MessageType[]): CoreMessage$1[];
1190
+ protected convertToUIMessages(messages: MessageType[]): Message[];
1191
+ /**
1192
+ * Retrieves a specific thread by its ID
1193
+ * @param threadId - The unique identifier of the thread
1194
+ * @returns Promise resolving to the thread or null if not found
1195
+ */
1196
+ abstract getThreadById({ threadId }: {
1197
+ threadId: string;
1198
+ }): Promise<StorageThreadType | null>;
1199
+ abstract getThreadsByResourceId({ resourceId }: {
1200
+ resourceId: string;
1201
+ }): Promise<StorageThreadType[]>;
1202
+ /**
1203
+ * Saves or updates a thread
1204
+ * @param thread - The thread data to save
1205
+ * @returns Promise resolving to the saved thread
1206
+ */
1207
+ abstract saveThread({ thread, memoryConfig, }: {
1208
+ thread: StorageThreadType;
1209
+ memoryConfig?: MemoryConfig;
1210
+ }): Promise<StorageThreadType>;
1211
+ /**
1212
+ * Saves messages to a thread
1213
+ * @param messages - Array of messages to save
1214
+ * @returns Promise resolving to the saved messages
1215
+ */
1216
+ abstract saveMessages({ messages, memoryConfig, }: {
1217
+ messages: MessageType[];
1218
+ memoryConfig: MemoryConfig | undefined;
1219
+ }): Promise<MessageType[]>;
1220
+ /**
1221
+ * Retrieves all messages for a specific thread
1222
+ * @param threadId - The unique identifier of the thread
1223
+ * @returns Promise resolving to array of messages and uiMessages
1224
+ */
1225
+ abstract query({ threadId, resourceId, selectBy, }: StorageGetMessagesArg): Promise<{
1226
+ messages: CoreMessage$1[];
1227
+ uiMessages: Message[];
1228
+ }>;
1229
+ /**
1230
+ * Helper method to create a new thread
1231
+ * @param title - Optional title for the thread
1232
+ * @param metadata - Optional metadata for the thread
1233
+ * @returns Promise resolving to the created thread
1234
+ */
1235
+ createThread({ threadId, resourceId, title, metadata, memoryConfig, }: {
1236
+ resourceId: string;
1237
+ threadId?: string;
1238
+ title?: string;
1239
+ metadata?: Record<string, unknown>;
1240
+ memoryConfig?: MemoryConfig;
1241
+ }): Promise<StorageThreadType>;
1242
+ /**
1243
+ * Helper method to delete a thread
1244
+ * @param threadId - the id of the thread to delete
1245
+ */
1246
+ abstract deleteThread(threadId: string): Promise<void>;
1247
+ /**
1248
+ * Helper method to add a single message to a thread
1249
+ * @param threadId - The thread to add the message to
1250
+ * @param content - The message content
1251
+ * @param role - The role of the message sender
1252
+ * @param type - The type of the message
1253
+ * @param toolNames - Optional array of tool names that were called
1254
+ * @param toolCallArgs - Optional array of tool call arguments
1255
+ * @param toolCallIds - Optional array of tool call ids
1256
+ * @returns Promise resolving to the saved message
1257
+ */
1258
+ addMessage({ threadId, resourceId, config, content, role, type, toolNames, toolCallArgs, toolCallIds, }: {
1259
+ threadId: string;
1260
+ resourceId: string;
1261
+ config?: MemoryConfig;
1262
+ content: UserContent | AssistantContent;
1263
+ role: 'user' | 'assistant';
1264
+ type: 'text' | 'tool-call' | 'tool-result';
1265
+ toolNames?: string[];
1266
+ toolCallArgs?: Record<string, unknown>[];
1267
+ toolCallIds?: string[];
1268
+ }): Promise<MessageType>;
1269
+ /**
1270
+ * Generates a unique identifier
1271
+ * @returns A unique string ID
1272
+ */
1273
+ generateId(): string;
1274
+ }
1275
+
1276
+ type LanguageModel = MastraLanguageModel;
1277
+ type CoreMessage = CoreMessage$1;
1278
+ type CoreSystemMessage = CoreSystemMessage$1;
1279
+ type CoreAssistantMessage = CoreAssistantMessage$1;
1280
+ type CoreUserMessage = CoreUserMessage$1;
1281
+ type CoreToolMessage = CoreToolMessage$1;
1282
+ type EmbedResult<T> = EmbedResult$1<T>;
1283
+ type EmbedManyResult<T> = EmbedManyResult$1<T>;
1284
+ type BaseStructuredOutputType = 'string' | 'number' | 'boolean' | 'date';
1285
+ type StructuredOutputType = 'array' | 'string' | 'number' | 'object' | 'boolean' | 'date';
1286
+ type StructuredOutputArrayItem = {
1287
+ type: BaseStructuredOutputType;
1288
+ } | {
1289
+ type: 'object';
1290
+ items: StructuredOutput;
1291
+ };
1292
+ type StructuredOutput = {
1293
+ [key: string]: {
1294
+ type: BaseStructuredOutputType;
1295
+ } | {
1296
+ type: 'object';
1297
+ items: StructuredOutput;
1298
+ } | {
1299
+ type: 'array';
1300
+ items: StructuredOutputArrayItem;
1301
+ };
1302
+ };
1303
+ 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>;
1304
+ 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>;
1305
+ type OutputType = StructuredOutput | ZodSchema | JSONSchema7 | undefined;
1306
+ type GenerateTextOptions = Parameters<typeof generateText>[0];
1307
+ type StreamTextOptions = Parameters<typeof streamText>[0];
1308
+ type GenerateObjectOptions = Parameters<typeof generateObject>[0];
1309
+ type StreamObjectOptions = Parameters<typeof streamObject>[0];
1310
+ type MastraCustomLLMOptionsKeys = 'messages' | 'tools' | 'model' | 'onStepFinish' | 'experimental_output' | 'experimental_telemetry' | 'messages' | 'onFinish' | 'output';
1311
+ type DefaultLLMTextOptions = Omit<GenerateTextOptions, MastraCustomLLMOptionsKeys>;
1312
+ type DefaultLLMTextObjectOptions = Omit<GenerateObjectOptions, MastraCustomLLMOptionsKeys>;
1313
+ type DefaultLLMStreamOptions = Omit<StreamTextOptions, MastraCustomLLMOptionsKeys>;
1314
+ type DefaultLLMStreamObjectOptions = Omit<StreamObjectOptions, MastraCustomLLMOptionsKeys>;
1315
+ type MastraCustomLLMOptions<Z extends ZodSchema | JSONSchema7 | undefined = undefined> = {
1316
+ tools?: ToolsInput;
1317
+ convertedTools?: Record<string, CoreTool>;
1318
+ onStepFinish?: (step: unknown) => void;
1319
+ experimental_output?: Z;
1320
+ telemetry?: TelemetrySettings;
1321
+ threadId?: string;
1322
+ resourceId?: string;
1323
+ container: Container;
1324
+ } & Run;
1325
+ type LLMTextOptions<Z extends ZodSchema | JSONSchema7 | undefined = undefined> = {
1326
+ messages: CoreMessage[];
1327
+ } & MastraCustomLLMOptions<Z> & DefaultLLMTextOptions;
1328
+ type LLMTextObjectOptions<T extends ZodSchema | JSONSchema7 | undefined = undefined> = LLMTextOptions<T> & DefaultLLMTextObjectOptions & {
1329
+ structuredOutput: JSONSchema7 | z.ZodType<T> | StructuredOutput;
1330
+ };
1331
+ type LLMStreamOptions<Z extends ZodSchema | JSONSchema7 | undefined = undefined> = {
1332
+ output?: OutputType | Z;
1333
+ onFinish?: (result: string) => Promise<void> | void;
1334
+ } & MastraCustomLLMOptions<Z> & DefaultLLMStreamOptions;
1335
+ type LLMInnerStreamOptions<Z extends ZodSchema | JSONSchema7 | undefined = undefined> = {
1336
+ messages: CoreMessage[];
1337
+ onFinish?: (result: string) => Promise<void> | void;
1338
+ } & MastraCustomLLMOptions<Z> & DefaultLLMStreamOptions;
1339
+ type LLMStreamObjectOptions<T extends ZodSchema | JSONSchema7 | undefined = undefined> = {
1340
+ structuredOutput: JSONSchema7 | z.ZodType<T> | StructuredOutput;
1341
+ } & LLMInnerStreamOptions<T> & DefaultLLMStreamObjectOptions;
1342
+
1343
+ type VoiceEventType = 'speaking' | 'writing' | 'error' | string;
1344
+ interface VoiceEventMap {
1345
+ speaker: NodeJS.ReadableStream;
1346
+ speaking: {
1347
+ audio?: string;
1348
+ };
1349
+ writing: {
1350
+ text: string;
1351
+ role: 'assistant' | 'user';
1352
+ };
1353
+ error: {
1354
+ message: string;
1355
+ code?: string;
1356
+ details?: unknown;
1357
+ };
1358
+ [key: string]: unknown;
1359
+ }
1360
+ interface BuiltInModelConfig {
1361
+ name: string;
1362
+ apiKey?: string;
1363
+ }
1364
+ interface VoiceConfig<T = unknown> {
1365
+ listeningModel?: BuiltInModelConfig;
1366
+ speechModel?: BuiltInModelConfig;
1367
+ speaker?: string;
1368
+ name?: string;
1369
+ realtimeConfig?: {
1370
+ model?: string;
1371
+ apiKey?: string;
1372
+ options?: T;
1373
+ };
1374
+ }
1375
+ declare abstract class MastraVoice<TOptions = unknown, TSpeakOptions = unknown, TListenOptions = unknown, TTools extends ToolsInput = ToolsInput, TEventArgs extends VoiceEventMap = VoiceEventMap, TSpeakerMetadata = unknown> extends MastraBase {
1376
+ protected listeningModel?: BuiltInModelConfig;
1377
+ protected speechModel?: BuiltInModelConfig;
1378
+ protected speaker?: string;
1379
+ protected realtimeConfig?: {
1380
+ model?: string;
1381
+ apiKey?: string;
1382
+ options?: TOptions;
1383
+ };
1384
+ constructor({ listeningModel, speechModel, speaker, realtimeConfig, name }?: VoiceConfig<TOptions>);
1385
+ traced<T extends Function>(method: T, methodName: string): T;
1386
+ /**
1387
+ * Convert text to speech
1388
+ * @param input Text or text stream to convert to speech
1389
+ * @param options Speech options including speaker and provider-specific options
1390
+ * @returns Audio stream
1391
+ */
1392
+ /**
1393
+ * Convert text to speech
1394
+ * @param input Text or text stream to convert to speech
1395
+ * @param options Speech options including speaker and provider-specific options
1396
+ * @returns Audio stream or void if in chat mode
1397
+ */
1398
+ abstract speak(input: string | NodeJS.ReadableStream, options?: {
1399
+ speaker?: string;
1400
+ } & TSpeakOptions): Promise<NodeJS.ReadableStream | void>;
1401
+ /**
1402
+ * Convert speech to text
1403
+ * @param audioStream Audio stream to transcribe
1404
+ * @param options Provider-specific transcription options
1405
+ * @returns Text or text stream
1406
+ */
1407
+ /**
1408
+ * Convert speech to text
1409
+ * @param audioStream Audio stream to transcribe
1410
+ * @param options Provider-specific transcription options
1411
+ * @returns Text, text stream, or void if in chat mode
1412
+ */
1413
+ abstract listen(audioStream: NodeJS.ReadableStream | unknown, // Allow other audio input types for OpenAI realtime API
1414
+ options?: TListenOptions): Promise<string | NodeJS.ReadableStream | void>;
1415
+ updateConfig(_options: Record<string, unknown>): void;
1416
+ /**
1417
+ * Initializes a WebSocket or WebRTC connection for real-time communication
1418
+ * @returns Promise that resolves when the connection is established
1419
+ */
1420
+ connect(_options?: Record<string, unknown>): Promise<void>;
1421
+ /**
1422
+ * Relay audio data to the voice provider for real-time processing
1423
+ * @param audioData Audio data to relay
1424
+ */
1425
+ send(_audioData: NodeJS.ReadableStream | Int16Array): Promise<void>;
1426
+ /**
1427
+ * Trigger voice providers to respond
1428
+ */
1429
+ answer(_options?: Record<string, unknown>): Promise<void>;
1430
+ /**
1431
+ * Equip the voice provider with instructions
1432
+ * @param instructions Instructions to add
1433
+ */
1434
+ addInstructions(_instructions?: string): void;
1435
+ /**
1436
+ * Equip the voice provider with tools
1437
+ * @param tools Array of tools to add
1438
+ */
1439
+ addTools(_tools: TTools): void;
1440
+ /**
1441
+ * Disconnect from the WebSocket or WebRTC connection
1442
+ */
1443
+ close(): void;
1444
+ /**
1445
+ * Register an event listener
1446
+ * @param event Event name (e.g., 'speaking', 'writing', 'error')
1447
+ * @param callback Callback function that receives event data
1448
+ */
1449
+ on<E extends VoiceEventType>(_event: E, _callback: (data: E extends keyof TEventArgs ? TEventArgs[E] : unknown) => void): void;
1450
+ /**
1451
+ * Remove an event listener
1452
+ * @param event Event name (e.g., 'speaking', 'writing', 'error')
1453
+ * @param callback Callback function to remove
1454
+ */
1455
+ off<E extends VoiceEventType>(_event: E, _callback: (data: E extends keyof TEventArgs ? TEventArgs[E] : unknown) => void): void;
1456
+ /**
1457
+ * Get available speakers/voices
1458
+ * @returns Array of available voice IDs and their metadata
1459
+ */
1460
+ getSpeakers(): Promise<Array<{
1461
+ voiceId: string;
1462
+ } & TSpeakerMetadata>>;
1463
+ }
1464
+
1465
+ declare class CompositeVoice extends MastraVoice<unknown, unknown, unknown, ToolsInput, VoiceEventMap> {
1466
+ protected speakProvider?: MastraVoice;
1467
+ protected listenProvider?: MastraVoice;
1468
+ protected realtimeProvider?: MastraVoice;
1469
+ constructor({ input, output, realtime, speakProvider, listenProvider, realtimeProvider, }: {
1470
+ /** @deprecated use output instead */
1471
+ speakProvider?: MastraVoice;
1472
+ /** @deprecated use input instead */
1473
+ listenProvider?: MastraVoice;
1474
+ /** @deprecated use realtime instead */
1475
+ realtimeProvider?: MastraVoice;
1476
+ input?: MastraVoice;
1477
+ output?: MastraVoice;
1478
+ realtime?: MastraVoice;
1479
+ });
1480
+ /**
1481
+ * Convert text to speech using the configured provider
1482
+ * @param input Text or text stream to convert to speech
1483
+ * @param options Speech options including speaker and provider-specific options
1484
+ * @returns Audio stream or void if in realtime mode
1485
+ */
1486
+ speak(input: string | NodeJS.ReadableStream, options?: {
1487
+ speaker?: string;
1488
+ } & any): Promise<NodeJS.ReadableStream | void>;
1489
+ listen(audioStream: NodeJS.ReadableStream, options?: any): Promise<string | void | NodeJS.ReadableStream>;
1490
+ getSpeakers(): Promise<{
1491
+ voiceId: string;
1492
+ }[]>;
1493
+ updateConfig(options: Record<string, unknown>): void;
1494
+ /**
1495
+ * Initializes a WebSocket or WebRTC connection for real-time communication
1496
+ * @returns Promise that resolves when the connection is established
1497
+ */
1498
+ connect(options?: Record<string, unknown>): Promise<void>;
1499
+ /**
1500
+ * Relay audio data to the voice provider for real-time processing
1501
+ * @param audioData Audio data to send
1502
+ */
1503
+ send(audioData: NodeJS.ReadableStream | Int16Array): Promise<void>;
1504
+ /**
1505
+ * Trigger voice providers to respond
1506
+ */
1507
+ answer(options?: Record<string, unknown>): Promise<void>;
1508
+ /**
1509
+ * Equip the voice provider with instructions
1510
+ * @param instructions Instructions to add
1511
+ */
1512
+ addInstructions(instructions: string): void;
1513
+ /**
1514
+ * Equip the voice provider with tools
1515
+ * @param tools Array of tools to add
1516
+ */
1517
+ addTools(tools: ToolsInput): void;
1518
+ /**
1519
+ * Disconnect from the WebSocket or WebRTC connection
1520
+ */
1521
+ close(): void;
1522
+ /**
1523
+ * Register an event listener
1524
+ * @param event Event name (e.g., 'speaking', 'writing', 'error')
1525
+ * @param callback Callback function that receives event data
1526
+ */
1527
+ on<E extends VoiceEventType>(event: E, callback: (data: E extends keyof VoiceEventMap ? VoiceEventMap[E] : unknown) => void): void;
1528
+ /**
1529
+ * Remove an event listener
1530
+ * @param event Event name (e.g., 'speaking', 'writing', 'error')
1531
+ * @param callback Callback function to remove
1532
+ */
1533
+ off<E extends VoiceEventType>(event: E, callback: (data: E extends keyof VoiceEventMap ? VoiceEventMap[E] : unknown) => void): void;
1534
+ }
1535
+
1536
+ type ToolsInput = Record<string, ToolAction<any, any, any> | VercelTool>;
1537
+ type ToolsetsInput = Record<string, ToolsInput>;
1538
+ type MastraLanguageModel = LanguageModelV1;
1539
+ interface AgentConfig<TAgentId extends string = string, TTools extends ToolsInput = ToolsInput, TMetrics extends Record<string, Metric> = Record<string, Metric>> {
1540
+ name: TAgentId;
1541
+ instructions: string;
1542
+ model: MastraLanguageModel;
1543
+ defaultGenerateOptions?: AgentGenerateOptions;
1544
+ defaultStreamOptions?: AgentStreamOptions;
1545
+ tools?: TTools;
1546
+ mastra?: Mastra;
1547
+ /** @deprecated This property is deprecated. Use evals instead to add evaluation metrics. */
1548
+ metrics?: TMetrics;
1549
+ evals?: TMetrics;
1550
+ memory?: MastraMemory;
1551
+ voice?: CompositeVoice;
1552
+ }
1553
+ /**
1554
+ * Options for generating responses with an agent
1555
+ * @template Z - The schema type for structured output (Zod schema or JSON schema)
1556
+ */
1557
+ type AgentGenerateOptions<Z extends ZodSchema | JSONSchema7 | undefined = undefined> = {
1558
+ /** Optional instructions to override the agent's default instructions */
1559
+ instructions?: string;
1560
+ /** Additional tool sets that can be used for this generation */
1561
+ toolsets?: ToolsetsInput;
1562
+ clientTools?: ToolsInput;
1563
+ /** Additional context messages to include */
1564
+ context?: CoreMessage[];
1565
+ /** Memory configuration options */
1566
+ memoryOptions?: MemoryConfig;
1567
+ /** Unique ID for this generation run */
1568
+ runId?: string;
1569
+ /** Callback fired after each generation step completes */
1570
+ onStepFinish?: Z extends undefined ? GenerateTextOnStepFinishCallback<any> : never;
1571
+ /** Maximum number of steps allowed for generation */
1572
+ maxSteps?: number;
1573
+ /** Schema for structured output, does not work with tools, use experimental_output instead */
1574
+ output?: OutputType | Z;
1575
+ /** Schema for structured output generation alongside tool calls. */
1576
+ experimental_output?: Z;
1577
+ /** Controls how tools are selected during generation */
1578
+ toolChoice?: 'auto' | 'none' | 'required' | {
1579
+ type: 'tool';
1580
+ toolName: string;
1581
+ };
1582
+ /** Telemetry settings */
1583
+ telemetry?: TelemetrySettings;
1584
+ /** Container for dependency injection */
1585
+ container?: Container;
1586
+ } & ({
1587
+ resourceId?: undefined;
1588
+ threadId?: undefined;
1589
+ } | {
1590
+ resourceId: string;
1591
+ threadId: string;
1592
+ }) & (Z extends undefined ? DefaultLLMTextOptions : DefaultLLMTextObjectOptions);
1593
+ /**
1594
+ * Options for streaming responses with an agent
1595
+ * @template Z - The schema type for structured output (Zod schema or JSON schema)
1596
+ */
1597
+ type AgentStreamOptions<Z extends ZodSchema | JSONSchema7 | undefined = undefined> = {
1598
+ /** Optional instructions to override the agent's default instructions */
1599
+ instructions?: string;
1600
+ /** Additional tool sets that can be used for this generation */
1601
+ toolsets?: ToolsetsInput;
1602
+ clientTools?: ToolsInput;
1603
+ /** Additional context messages to include */
1604
+ context?: CoreMessage[];
1605
+ /** Memory configuration options */
1606
+ memoryOptions?: MemoryConfig;
1607
+ /** Unique ID for this generation run */
1608
+ runId?: string;
1609
+ /** Callback fired when streaming completes */
1610
+ onFinish?: Z extends undefined ? StreamTextOnFinishCallback<any> : Z extends ZodSchema ? StreamObjectOnFinishCallback<z.infer<Z>> : StreamObjectOnFinishCallback<any>;
1611
+ /** Callback fired after each generation step completes */
1612
+ onStepFinish?: Z extends undefined ? StreamTextOnStepFinishCallback<any> : never;
1613
+ /** Maximum number of steps allowed for generation */
1614
+ maxSteps?: number;
1615
+ /** Schema for structured output */
1616
+ output?: OutputType | Z;
1617
+ /** Temperature parameter for controlling randomness */
1618
+ temperature?: number;
1619
+ /** Controls how tools are selected during generation */
1620
+ toolChoice?: 'auto' | 'none' | 'required' | {
1621
+ type: 'tool';
1622
+ toolName: string;
1623
+ };
1624
+ /** Experimental schema for structured output */
1625
+ experimental_output?: Z;
1626
+ /** Telemetry settings */
1627
+ telemetry?: TelemetrySettings;
1628
+ /** Container for dependency injection */
1629
+ container?: Container;
1630
+ } & ({
1631
+ resourceId?: undefined;
1632
+ threadId?: undefined;
1633
+ } | {
1634
+ resourceId: string;
1635
+ threadId: string;
1636
+ }) & (Z extends undefined ? DefaultLLMStreamOptions : DefaultLLMStreamObjectOptions);
1637
+
1638
+ type Methods = 'GET' | 'POST' | 'PUT' | 'DELETE';
1639
+ type ApiRoute = {
1640
+ path: string;
1641
+ method: Methods;
1642
+ handler: Handler;
1643
+ middleware?: MiddlewareHandler | MiddlewareHandler[];
1644
+ openapi?: DescribeRouteOptions;
1645
+ };
1646
+ type Middleware = MiddlewareHandler | {
1647
+ path: string;
1648
+ handler: MiddlewareHandler;
1649
+ };
1650
+ type ServerConfig = {
1651
+ port?: number;
1652
+ timeout?: number;
1653
+ apiRoutes?: ApiRoute[];
1654
+ middleware?: Middleware | Middleware[];
1655
+ /**
1656
+ * CORS configuration for the server
1657
+ * @default { origin: '*', allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], allowHeaders: ['Content-Type', 'Authorization', 'x-mastra-client-type'], exposeHeaders: ['Content-Length', 'X-Requested-With'], credentials: false }
1658
+ */
1659
+ cors?: Parameters<typeof cors>[0] | false;
1660
+ };
1661
+
1662
+ interface Config<TAgents extends Record<string, Agent<any>> = Record<string, Agent<any>>, 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 Logger = Logger, TNetworks extends Record<string, AgentNetwork> = Record<string, AgentNetwork>> {
1663
+ agents?: TAgents;
1664
+ networks?: TNetworks;
1665
+ storage?: MastraStorage;
1666
+ vectors?: TVectors;
1667
+ logger?: TLogger | false;
1668
+ workflows?: TWorkflows;
1669
+ tts?: TTTS;
1670
+ telemetry?: OtelConfig;
1671
+ deployer?: MastraDeployer;
1672
+ server?: ServerConfig;
1673
+ /**
1674
+ * Server middleware functions to be applied to API routes
1675
+ * Each middleware can specify a path pattern (defaults to '/api/*')
1676
+ * @deprecated use server.middleware instead
1677
+ */
1678
+ serverMiddleware?: Array<{
1679
+ handler: (c: any, next: () => Promise<void>) => Promise<Response | void>;
1680
+ path?: string;
1681
+ }>;
1682
+ memory?: MastraMemory;
1683
+ }
1684
+ declare class Mastra<TAgents extends Record<string, Agent<any>> = Record<string, Agent<any>>, 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 Logger = Logger, TNetworks extends Record<string, AgentNetwork> = Record<string, AgentNetwork>> {
1685
+ #private;
1686
+ /**
1687
+ * @deprecated use getTelemetry() instead
1688
+ */
1689
+ get telemetry(): Telemetry | undefined;
1690
+ /**
1691
+ * @deprecated use getStorage() instead
1692
+ */
1693
+ get storage(): MastraStorage | undefined;
1694
+ /**
1695
+ * @deprecated use getMemory() instead
1696
+ */
1697
+ get memory(): MastraMemory | undefined;
1698
+ constructor(config?: Config<TAgents, TWorkflows, TVectors, TTTS, TLogger>);
1699
+ getAgent<TAgentName extends keyof TAgents>(name: TAgentName): TAgents[TAgentName];
1700
+ getAgents(): TAgents;
1701
+ getVector<TVectorName extends keyof TVectors>(name: TVectorName): TVectors[TVectorName];
1702
+ getVectors(): TVectors | undefined;
1703
+ getDeployer(): MastraDeployer | undefined;
1704
+ getWorkflow<TWorkflowId extends keyof TWorkflows>(id: TWorkflowId, { serialized }?: {
1705
+ serialized?: boolean;
1706
+ }): TWorkflows[TWorkflowId];
1707
+ getWorkflows(props?: {
1708
+ serialized?: boolean;
1709
+ }): Record<string, Workflow>;
1710
+ setStorage(storage: MastraStorage): void;
1711
+ setLogger({ logger }: {
1712
+ logger: TLogger;
1713
+ }): void;
1714
+ setTelemetry(telemetry: OtelConfig): void;
1715
+ getTTS(): TTTS | undefined;
1716
+ getLogger(): TLogger;
1717
+ getTelemetry(): Telemetry | undefined;
1718
+ getMemory(): MastraMemory | undefined;
1719
+ getStorage(): MastraStorage | undefined;
1720
+ getServerMiddleware(): {
1721
+ handler: (c: any, next: () => Promise<void>) => Promise<Response | void>;
1722
+ path: string;
1723
+ }[];
1724
+ getNetworks(): AgentNetwork[];
1725
+ getServer(): ServerConfig | undefined;
1726
+ /**
1727
+ * Get a specific network by ID
1728
+ * @param networkId - The ID of the network to retrieve
1729
+ * @returns The network with the specified ID, or undefined if not found
1730
+ */
1731
+ getNetwork(networkId: string): AgentNetwork | undefined;
1732
+ getLogsByRunId({ runId, transportId }: {
1733
+ runId: string;
1734
+ transportId: string;
1735
+ }): Promise<BaseLogMessage[] | undefined>;
1736
+ getLogs(transportId: string): Promise<BaseLogMessage[]>;
1737
+ }
1738
+
1739
+ type MastraPrimitives = {
1740
+ logger?: Logger;
1741
+ telemetry?: Telemetry;
1742
+ storage?: MastraStorage;
1743
+ agents?: Record<string, Agent>;
1744
+ tts?: Record<string, MastraTTS>;
1745
+ vectors?: Record<string, MastraVector>;
1746
+ memory?: MastraMemory;
1747
+ };
1748
+ type MastraUnion = {
1749
+ [K in keyof Mastra]: Mastra[K];
1750
+ } & MastraPrimitives;
1751
+ interface IExecutionContext<TSchemaIn extends z.ZodSchema | undefined = undefined> {
1752
+ context: TSchemaIn extends z.ZodSchema ? z.infer<TSchemaIn> : {};
1753
+ runId?: string;
1754
+ threadId?: string;
1755
+ resourceId?: string;
1756
+ }
1757
+ interface IAction<TId extends string, TSchemaIn extends z.ZodSchema | undefined, TSchemaOut extends z.ZodSchema | undefined, TContext extends IExecutionContext<TSchemaIn>, TOptions extends unknown = unknown> {
1758
+ id: TId;
1759
+ description?: string;
1760
+ inputSchema?: TSchemaIn;
1761
+ outputSchema?: TSchemaOut;
1762
+ execute?: (context: TContext, options?: TOptions) => Promise<TSchemaOut extends z.ZodSchema ? z.infer<TSchemaOut> : unknown>;
1763
+ }
1764
+
1765
+ declare class MastraLLMBase extends MastraBase {
1766
+ #private;
1767
+ constructor({ name, model }: {
1768
+ name: string;
1769
+ model: LanguageModel$1;
1770
+ });
1771
+ getProvider(): string;
1772
+ getModelId(): string;
1773
+ getModel(): ai.LanguageModelV1;
1774
+ convertToMessages(messages: string | string[] | CoreMessage$1[]): CoreMessage$1[];
1775
+ __registerPrimitives(p: MastraPrimitives): void;
1776
+ __registerMastra(p: Mastra): void;
1777
+ __text<Z extends ZodSchema | JSONSchema7 | undefined>(input: LLMTextOptions<Z>): Promise<GenerateTextResult<any, any>>;
1778
+ __textObject<T extends ZodSchema | JSONSchema7 | undefined>(input: LLMTextObjectOptions<T>): Promise<GenerateObjectResult<T>>;
1779
+ generate<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[], options: LLMStreamOptions<Z>): Promise<GenerateReturn<Z>>;
1780
+ __stream<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(input: LLMInnerStreamOptions<Z>): Promise<StreamTextResult<any, any>>;
1781
+ __streamObject<T extends ZodSchema | JSONSchema7 | undefined>(input: LLMStreamObjectOptions<T>): Promise<StreamObjectResult<DeepPartial<T>, T, never>>;
1782
+ stream<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[], options: LLMStreamOptions<Z>): Promise<StreamReturn<Z>>;
1783
+ }
1784
+
1785
+ declare class Agent<TAgentId extends string = string, TTools extends ToolsInput = ToolsInput, TMetrics extends Record<string, Metric> = Record<string, Metric>> extends MastraBase {
1786
+ #private;
1787
+ name: TAgentId;
1788
+ readonly llm: MastraLLMBase;
1789
+ instructions: string;
1790
+ readonly model?: MastraLanguageModel;
1791
+ tools: TTools;
1792
+ /** @deprecated This property is deprecated. Use evals instead. */
1793
+ metrics: TMetrics;
1794
+ evals: TMetrics;
1795
+ voice: CompositeVoice;
1796
+ constructor(config: AgentConfig<TAgentId, TTools, TMetrics>);
1797
+ hasOwnMemory(): boolean;
1798
+ getMemory(): MastraMemory | undefined;
1799
+ __updateInstructions(newInstructions: string): void;
1800
+ __registerPrimitives(p: MastraPrimitives): void;
1801
+ __registerMastra(mastra: Mastra): void;
1802
+ /**
1803
+ * Set the concrete tools for the agent
1804
+ * @param tools
1805
+ */
1806
+ __setTools(tools: TTools): void;
1807
+ generateTitleFromUserMessage({ message }: {
1808
+ message: CoreUserMessage$1;
1809
+ }): Promise<string>;
1810
+ getMostRecentUserMessage(messages: Array<CoreMessage$1>): CoreUserMessage$1 | undefined;
1811
+ genTitle(userMessage: CoreUserMessage$1 | undefined): Promise<string>;
1812
+ fetchMemory({ threadId, thread: passedThread, memoryConfig, resourceId, userMessages, systemMessage, runId, }: {
1813
+ resourceId: string;
1814
+ threadId: string;
1815
+ thread?: StorageThreadType;
1816
+ memoryConfig?: MemoryConfig;
1817
+ userMessages: CoreMessage$1[];
1818
+ systemMessage: CoreMessage$1;
1819
+ time?: Date;
1820
+ keyword?: string;
1821
+ runId?: string;
1822
+ }): Promise<{
1823
+ threadId: string;
1824
+ messages: CoreMessage$1[];
1825
+ }>;
1826
+ private getResponseMessages;
1827
+ sanitizeResponseMessages(messages: Array<CoreMessage$1>): Array<CoreMessage$1>;
1828
+ convertTools({ toolsets, clientTools, threadId, resourceId, runId, container, }: {
1829
+ toolsets?: ToolsetsInput;
1830
+ clientTools?: ToolsInput;
1831
+ threadId?: string;
1832
+ resourceId?: string;
1833
+ runId?: string;
1834
+ container: Container;
1835
+ }): Record<string, CoreTool>;
1836
+ preExecute({ resourceId, runId, threadId, thread, memoryConfig, messages, systemMessage, }: {
1837
+ runId?: string;
1838
+ threadId: string;
1839
+ thread?: StorageThreadType;
1840
+ memoryConfig?: MemoryConfig;
1841
+ messages: CoreMessage$1[];
1842
+ resourceId: string;
1843
+ systemMessage: CoreMessage$1;
1844
+ }): Promise<{
1845
+ coreMessages: CoreMessage$1[];
1846
+ threadIdToUse: string;
1847
+ }>;
1848
+ __primitive({ instructions, messages, context, threadId, memoryConfig, resourceId, runId, toolsets, clientTools, container, }: {
1849
+ instructions?: string;
1850
+ toolsets?: ToolsetsInput;
1851
+ clientTools?: ToolsInput;
1852
+ resourceId?: string;
1853
+ threadId?: string;
1854
+ memoryConfig?: MemoryConfig;
1855
+ context?: CoreMessage$1[];
1856
+ runId?: string;
1857
+ messages: CoreMessage$1[];
1858
+ container: Container;
1859
+ }): {
1860
+ before: () => Promise<{
1861
+ messageObjects: CoreMessage$1[];
1862
+ convertedTools: Record<string, CoreTool> | undefined;
1863
+ threadId: string;
1864
+ thread: StorageThreadType | null | undefined;
1865
+ }>;
1866
+ after: ({ result, thread: threadAfter, threadId, memoryConfig, outputText, runId, }: {
1867
+ runId: string;
1868
+ result: Record<string, any>;
1869
+ thread: StorageThreadType | null | undefined;
1870
+ threadId: string;
1871
+ memoryConfig: MemoryConfig | undefined;
1872
+ outputText: string;
1873
+ }) => Promise<void>;
1874
+ };
1875
+ generate<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[] | Message[], args?: AgentGenerateOptions<Z> & {
1876
+ output?: never;
1877
+ experimental_output?: never;
1878
+ }): Promise<GenerateTextResult<any, Z extends ZodSchema ? z.infer<Z> : unknown>>;
1879
+ generate<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[] | Message[], args?: AgentGenerateOptions<Z> & {
1880
+ output?: Z;
1881
+ experimental_output?: never;
1882
+ }): Promise<GenerateObjectResult<Z extends ZodSchema ? z.infer<Z> : unknown>>;
1883
+ generate<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[] | Message[], args?: AgentGenerateOptions<Z> & {
1884
+ output?: never;
1885
+ experimental_output?: Z;
1886
+ }): Promise<GenerateTextResult<any, Z extends ZodSchema ? z.infer<Z> : unknown> & {
1887
+ object: Z extends ZodSchema ? z.infer<Z> : unknown;
1888
+ }>;
1889
+ stream<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[] | Message[], args?: AgentStreamOptions<Z> & {
1890
+ output?: never;
1891
+ experimental_output?: never;
1892
+ }): Promise<StreamTextResult<any, Z extends ZodSchema ? z.infer<Z> : unknown>>;
1893
+ stream<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[] | Message[], args?: AgentStreamOptions<Z> & {
1894
+ output?: Z;
1895
+ experimental_output?: never;
1896
+ }): Promise<StreamObjectResult<any, Z extends ZodSchema ? z.infer<Z> : unknown, any>>;
1897
+ stream<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[] | Message[], args?: AgentStreamOptions<Z> & {
1898
+ output?: never;
1899
+ experimental_output?: Z;
1900
+ }): Promise<StreamTextResult<any, Z extends ZodSchema ? z.infer<Z> : unknown> & {
1901
+ partialObjectStream: StreamTextResult<any, Z extends ZodSchema ? z.infer<Z> : unknown>['experimental_partialOutputStream'];
1902
+ }>;
1903
+ /**
1904
+ * Convert text to speech using the configured voice provider
1905
+ * @param input Text or text stream to convert to speech
1906
+ * @param options Speech options including speaker and provider-specific options
1907
+ * @returns Audio stream
1908
+ * @deprecated Use agent.voice.speak() instead
1909
+ */
1910
+ speak(input: string | NodeJS.ReadableStream, options?: {
1911
+ speaker?: string;
1912
+ [key: string]: any;
1913
+ }): Promise<NodeJS.ReadableStream | void>;
1914
+ /**
1915
+ * Convert speech to text using the configured voice provider
1916
+ * @param audioStream Audio stream to transcribe
1917
+ * @param options Provider-specific transcription options
1918
+ * @returns Text or text stream
1919
+ * @deprecated Use agent.voice.listen() instead
1920
+ */
1921
+ listen(audioStream: NodeJS.ReadableStream, options?: {
1922
+ [key: string]: any;
1923
+ }): Promise<string | NodeJS.ReadableStream | void>;
1924
+ /**
1925
+ * Get a list of available speakers from the configured voice provider
1926
+ * @throws {Error} If no voice provider is configured
1927
+ * @returns {Promise<Array<{voiceId: string}>>} List of available speakers
1928
+ * @deprecated Use agent.voice.getSpeakers() instead
1929
+ */
1930
+ getSpeakers(): Promise<{
1931
+ voiceId: string;
1932
+ }[]>;
1933
+ toStep(): Step<TAgentId, z.ZodObject<{
1934
+ prompt: z.ZodString;
1935
+ }>, z.ZodObject<{
1936
+ text: z.ZodString;
1937
+ }>, any>;
1938
+ }
1939
+
1940
+ interface StorageColumn {
1941
+ type: 'text' | 'timestamp' | 'uuid' | 'jsonb' | 'integer' | 'bigint';
1942
+ primaryKey?: boolean;
1943
+ nullable?: boolean;
1944
+ references?: {
1945
+ table: string;
1946
+ column: string;
1947
+ };
1948
+ }
1949
+ interface WorkflowRow {
1950
+ workflow_name: string;
1951
+ run_id: string;
1952
+ snapshot: WorkflowRunState;
1953
+ created_at: Date;
1954
+ updated_at: Date;
1955
+ }
1956
+ interface WorkflowRuns {
1957
+ runs: Array<{
1958
+ workflowName: string;
1959
+ runId: string;
1960
+ snapshot: WorkflowRunState | string;
1961
+ createdAt: Date;
1962
+ updatedAt: Date;
1963
+ }>;
1964
+ total: number;
1965
+ }
1966
+ type StorageGetMessagesArg = {
1967
+ threadId: string;
1968
+ resourceId?: string;
1969
+ selectBy?: {
1970
+ vectorSearchString?: string;
1971
+ last?: number | false;
1972
+ include?: {
1973
+ id: string;
1974
+ withPreviousMessages?: number;
1975
+ withNextMessages?: number;
1976
+ }[];
1977
+ };
1978
+ threadConfig?: MemoryConfig;
1979
+ };
1980
+ type EvalRow = {
1981
+ input: string;
1982
+ output: string;
1983
+ result: MetricResult;
1984
+ agentName: string;
1985
+ createdAt: string;
1986
+ metricName: string;
1987
+ instructions: string;
1988
+ runId: string;
1989
+ globalRunId: string;
1990
+ testInfo?: TestInfo;
1991
+ };
1992
+
1993
+ declare const TABLE_WORKFLOW_SNAPSHOT = "mastra_workflow_snapshot";
1994
+ declare const TABLE_EVALS = "mastra_evals";
1995
+ declare const TABLE_MESSAGES = "mastra_messages";
1996
+ declare const TABLE_THREADS = "mastra_threads";
1997
+ declare const TABLE_TRACES = "mastra_traces";
1998
+ type TABLE_NAMES = typeof TABLE_WORKFLOW_SNAPSHOT | typeof TABLE_EVALS | typeof TABLE_MESSAGES | typeof TABLE_THREADS | typeof TABLE_TRACES;
1999
+ declare const TABLE_SCHEMAS: Record<TABLE_NAMES, Record<string, StorageColumn>>;
2000
+
2001
+ type MessageType = {
2002
+ id: string;
2003
+ content: UserContent | AssistantContent | ToolContent;
2004
+ role: 'system' | 'user' | 'assistant' | 'tool';
2005
+ createdAt: Date;
2006
+ threadId: string;
2007
+ resourceId: string;
2008
+ toolCallIds?: string[];
2009
+ toolCallArgs?: Record<string, unknown>[];
2010
+ toolNames?: string[];
2011
+ type: 'text' | 'tool-call' | 'tool-result';
2012
+ };
2013
+ type StorageThreadType = {
2014
+ id: string;
2015
+ title?: string;
2016
+ resourceId: string;
2017
+ createdAt: Date;
2018
+ updatedAt: Date;
2019
+ metadata?: Record<string, unknown>;
2020
+ };
2021
+ type MessageResponse<T extends 'raw' | 'core_message'> = {
2022
+ raw: MessageType[];
2023
+ core_message: CoreMessage$1[];
2024
+ }[T];
2025
+ type MemoryConfig = {
2026
+ lastMessages?: number | false;
2027
+ semanticRecall?: boolean | {
2028
+ topK: number;
2029
+ messageRange: number | {
2030
+ before: number;
2031
+ after: number;
2032
+ };
2033
+ };
2034
+ workingMemory?: {
2035
+ enabled: boolean;
2036
+ template?: string;
2037
+ use?: 'text-stream' | 'tool-call';
2038
+ };
2039
+ threads?: {
2040
+ generateTitle?: boolean;
2041
+ };
2042
+ };
2043
+ type SharedMemoryConfig = {
2044
+ storage?: MastraStorage;
2045
+ options?: MemoryConfig;
2046
+ vector?: MastraVector | false;
2047
+ embedder?: EmbeddingModel<string>;
2048
+ processors?: MemoryProcessor[];
2049
+ };
2050
+
2051
+ declare abstract class MastraStorage extends MastraBase {
2052
+ /** @deprecated import from { TABLE_WORKFLOW_SNAPSHOT } '@mastra/core/storage' instead */
2053
+ static readonly TABLE_WORKFLOW_SNAPSHOT = "mastra_workflow_snapshot";
2054
+ /** @deprecated import from { TABLE_EVALS } '@mastra/core/storage' instead */
2055
+ static readonly TABLE_EVALS = "mastra_evals";
2056
+ /** @deprecated import from { TABLE_MESSAGES } '@mastra/core/storage' instead */
2057
+ static readonly TABLE_MESSAGES = "mastra_messages";
2058
+ /** @deprecated import from { TABLE_THREADS } '@mastra/core/storage' instead */
2059
+ static readonly TABLE_THREADS = "mastra_threads";
2060
+ /** @deprecated import { TABLE_TRACES } from '@mastra/core/storage' instead */
2061
+ static readonly TABLE_TRACES = "mastra_traces";
2062
+ protected hasInitialized: null | Promise<boolean>;
2063
+ protected shouldCacheInit: boolean;
2064
+ constructor({ name }: {
2065
+ name: string;
2066
+ });
2067
+ abstract createTable({ tableName }: {
2068
+ tableName: TABLE_NAMES;
2069
+ schema: Record<string, StorageColumn>;
2070
+ }): Promise<void>;
2071
+ abstract clearTable({ tableName }: {
2072
+ tableName: TABLE_NAMES;
2073
+ }): Promise<void>;
2074
+ abstract insert({ tableName, record }: {
2075
+ tableName: TABLE_NAMES;
2076
+ record: Record<string, any>;
2077
+ }): Promise<void>;
2078
+ abstract batchInsert({ tableName, records, }: {
2079
+ tableName: TABLE_NAMES;
2080
+ records: Record<string, any>[];
2081
+ }): Promise<void>;
2082
+ batchTraceInsert({ records }: {
2083
+ records: Record<string, any>[];
2084
+ }): Promise<void>;
2085
+ abstract load<R>({ tableName, keys }: {
2086
+ tableName: TABLE_NAMES;
2087
+ keys: Record<string, string>;
2088
+ }): Promise<R | null>;
2089
+ abstract getThreadById({ threadId }: {
2090
+ threadId: string;
2091
+ }): Promise<StorageThreadType | null>;
2092
+ abstract getThreadsByResourceId({ resourceId }: {
2093
+ resourceId: string;
2094
+ }): Promise<StorageThreadType[]>;
2095
+ abstract saveThread({ thread }: {
2096
+ thread: StorageThreadType;
2097
+ }): Promise<StorageThreadType>;
2098
+ abstract updateThread({ id, title, metadata, }: {
2099
+ id: string;
2100
+ title: string;
2101
+ metadata: Record<string, unknown>;
2102
+ }): Promise<StorageThreadType>;
2103
+ abstract deleteThread({ threadId }: {
2104
+ threadId: string;
2105
+ }): Promise<void>;
2106
+ abstract getMessages({ threadId, selectBy, threadConfig }: StorageGetMessagesArg): Promise<MessageType[]>;
2107
+ abstract saveMessages({ messages }: {
2108
+ messages: MessageType[];
2109
+ }): Promise<MessageType[]>;
2110
+ abstract getTraces({ name, scope, page, perPage, attributes, filters, }: {
2111
+ name?: string;
2112
+ scope?: string;
2113
+ page: number;
2114
+ perPage: number;
2115
+ attributes?: Record<string, string>;
2116
+ filters?: Record<string, any>;
2117
+ }): Promise<any[]>;
2118
+ init(): Promise<void>;
2119
+ persistWorkflowSnapshot({ workflowName, runId, snapshot, }: {
2120
+ workflowName: string;
2121
+ runId: string;
2122
+ snapshot: WorkflowRunState;
2123
+ }): Promise<void>;
2124
+ loadWorkflowSnapshot({ workflowName, runId, }: {
2125
+ workflowName: string;
2126
+ runId: string;
2127
+ }): Promise<WorkflowRunState | null>;
2128
+ abstract getEvalsByAgentName(agentName: string, type?: 'test' | 'live'): Promise<EvalRow[]>;
2129
+ abstract getWorkflowRuns(args?: {
2130
+ namespace?: string;
2131
+ workflowName?: string;
2132
+ fromDate?: Date;
2133
+ toDate?: Date;
2134
+ limit?: number;
2135
+ offset?: number;
2136
+ }): Promise<WorkflowRuns>;
2137
+ }
2138
+
2139
+ export { type MemoryConfig as $, type ApiRoute as A, type BaseStructuredOutputType as B, CompositeVoice as C, type StructuredOutputType as D, type EvalRow as E, type StructuredOutputArrayItem as F, type StructuredOutput as G, type GenerateReturn as H, type StreamReturn as I, type DefaultLLMTextOptions as J, type DefaultLLMTextObjectOptions as K, type LanguageModel as L, type Methods as M, type DefaultLLMStreamOptions as N, type OutputType as O, type DefaultLLMStreamObjectOptions as P, type LLMTextOptions as Q, type LLMTextObjectOptions as R, type StorageColumn as S, type TABLE_NAMES as T, type LLMStreamOptions as U, type VoiceEventType as V, type WorkflowRunState as W, type LLMInnerStreamOptions as X, type LLMStreamObjectOptions as Y, type Config as Z, type MessageResponse as _, Mastra as a, type SharedMemoryConfig as a0, type MemoryProcessorOpts as a1, MemoryProcessor as a2, createTool as a3, type VercelTool as a4, type CoreTool as a5, type StepExecutionContext as a6, type StepAction as a7, type StepVariableType as a8, type StepNode as a9, type ExtractStepResult as aA, type StepInputType as aB, type ExtractSchemaType as aC, type PathsToStringProps as aD, type WorkflowResumeResult as aE, createStep as aF, type MastraLanguageModel as aG, type ToolsInput as aH, type MastraPrimitives as aI, AgentNetwork as aJ, type AgentNetworkConfig as aK, type ToolsetsInput as aL, type AgentGenerateOptions as aM, type AgentStreamOptions as aN, TABLE_WORKFLOW_SNAPSHOT as aO, TABLE_EVALS as aP, TABLE_MESSAGES as aQ, TABLE_THREADS as aR, TABLE_TRACES as aS, TABLE_SCHEMAS as aT, type StepGraph as aa, type RetryConfig as ab, type VariableReference as ac, type BaseCondition as ad, type ActionContext as ae, WhenConditionReturnValue as af, type StepDef as ag, type StepCondition as ah, type StepConfig as ai, type StepResult as aj, type StepsRecord as ak, type WorkflowRunResult as al, type WorkflowContext as am, type WorkflowLogMessage as an, type WorkflowEvent as ao, type ResolverFunctionInput as ap, type ResolverFunctionOutput as aq, type SubscriberFunctionOutput as ar, type DependencyCheckOutput as as, type StepResolverOutput as at, type WorkflowActors as au, type WorkflowActionParams as av, type WorkflowActions as aw, type WorkflowState as ax, type StepId as ay, type ExtractSchemaFromStep as az, MastraVoice as b, type VoiceEventMap as c, type VoiceConfig as d, MastraStorage as e, type StorageThreadType as f, type MessageType as g, type StorageGetMessagesArg as h, type ToolAction as i, Agent as j, type AgentConfig as k, MastraMemory as l, type ToolExecutionContext as m, Tool as n, Step as o, Workflow as p, type WorkflowOptions as q, type WorkflowRow as r, type WorkflowRuns as s, type CoreMessage as t, type CoreSystemMessage as u, type CoreAssistantMessage as v, type CoreUserMessage as w, type CoreToolMessage as x, type EmbedResult as y, type EmbedManyResult as z };