UNPKG

@mastra/core

Version:

The core foundation of the Mastra framework, providing essential components and interfaces for building AI-powered applications.

1,202 lines (1,192 loc) • 88.5 kB
import * as ai from 'ai'; import { Tool as Tool$1, ToolExecutionOptions, CoreMessage as CoreMessage$1, TelemetrySettings, generateText, generateObject, streamText, GenerateTextResult, GenerateObjectResult, streamObject, StreamTextResult, StreamObjectResult, CoreSystemMessage as CoreSystemMessage$1, CoreAssistantMessage as CoreAssistantMessage$1, CoreUserMessage as CoreUserMessage$1, CoreToolMessage as CoreToolMessage$1, EmbedResult as EmbedResult$1, EmbedManyResult as EmbedManyResult$1, EmbeddingModel, Message, UserContent, AssistantContent, LanguageModelV1, GenerateTextOnStepFinishCallback, StreamTextOnFinishCallback, StreamObjectOnFinishCallback, StreamTextOnStepFinishCallback, LanguageModel as LanguageModel$1, DeepPartial, ToolContent } from 'ai'; import { M as MastraBase, T as Telemetry, O as OtelConfig } from './base-ObPJ-w8K.cjs'; import { M as Metric, a as MetricResult, T as TestInfo } from './types-CwTG2XyQ.cjs'; import { Query } from 'sift'; import { z, ZodSchema } from 'zod'; import { JSONSchema7 } from 'json-schema'; import { d as Run, B as BaseLogMessage, R as RegisteredLogger, L as Logger } from './index-CquI0inB.cjs'; import { Span } from '@opentelemetry/api'; import * as xstate from 'xstate'; import { Snapshot } from 'xstate'; import EventEmitter from 'node:events'; import { MastraVector } from './vector/index.cjs'; import { MastraTTS } from './tts/index.cjs'; import { MastraDeployer } from './deployer/index.cjs'; type VercelTool = Tool$1; type CoreTool = { id?: string; description?: string; parameters: ZodSchema; execute?: (params: any, options: ToolExecutionOptions) => Promise<any>; } & ({ type?: 'function' | undefined; id?: string; } | { type: 'provider-defined'; id: `${string}.${string}`; args: Record<string, unknown>; }); interface ToolExecutionContext<TSchemaIn extends z.ZodSchema | undefined = undefined> extends IExecutionContext<TSchemaIn> { mastra?: MastraUnion; } 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> { description: string; execute?: (context: TContext, options?: ToolExecutionOptions) => Promise<TSchemaOut extends z.ZodSchema ? z.infer<TSchemaOut> : unknown>; mastra?: Mastra; } 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> { id: string; description: string; inputSchema?: TSchemaIn; outputSchema?: TSchemaOut; execute?: ToolAction<TSchemaIn, TSchemaOut, TContext>['execute']; mastra?: Mastra; constructor(opts: ToolAction<TSchemaIn, TSchemaOut, TContext>); } 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>; type LanguageModel = MastraLanguageModel; type CoreMessage = CoreMessage$1; type CoreSystemMessage = CoreSystemMessage$1; type CoreAssistantMessage = CoreAssistantMessage$1; type CoreUserMessage = CoreUserMessage$1; type CoreToolMessage = CoreToolMessage$1; type EmbedResult<T> = EmbedResult$1<T>; type EmbedManyResult<T> = EmbedManyResult$1<T>; type BaseStructuredOutputType = 'string' | 'number' | 'boolean' | 'date'; type StructuredOutputType = 'array' | 'string' | 'number' | 'object' | 'boolean' | 'date'; type StructuredOutputArrayItem = { type: BaseStructuredOutputType; } | { type: 'object'; items: StructuredOutput; }; type StructuredOutput = { [key: string]: { type: BaseStructuredOutputType; } | { type: 'object'; items: StructuredOutput; } | { type: 'array'; items: StructuredOutputArrayItem; }; }; 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>; 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>; type OutputType = StructuredOutput | ZodSchema | JSONSchema7 | undefined; type GenerateTextOptions = Parameters<typeof generateText>[0]; type StreamTextOptions = Parameters<typeof streamText>[0]; type GenerateObjectOptions = Parameters<typeof generateObject>[0]; type StreamObjectOptions = Parameters<typeof streamObject>[0]; type MastraCustomLLMOptionsKeys = 'messages' | 'tools' | 'model' | 'onStepFinish' | 'experimental_output' | 'experimental_telemetry' | 'messages' | 'onFinish' | 'output'; type DefaultLLMTextOptions = Omit<GenerateTextOptions, MastraCustomLLMOptionsKeys>; type DefaultLLMTextObjectOptions = Omit<GenerateObjectOptions, MastraCustomLLMOptionsKeys>; type DefaultLLMStreamOptions = Omit<StreamTextOptions, MastraCustomLLMOptionsKeys>; type DefaultLLMStreamObjectOptions = Omit<StreamObjectOptions, MastraCustomLLMOptionsKeys>; type MastraCustomLLMOptions<Z extends ZodSchema | JSONSchema7 | undefined = undefined> = { tools?: ToolsInput; convertedTools?: Record<string, CoreTool>; onStepFinish?: (step: unknown) => void; experimental_output?: Z; telemetry?: TelemetrySettings; threadId?: string; resourceId?: string; } & Run; type LLMTextOptions<Z extends ZodSchema | JSONSchema7 | undefined = undefined> = { messages: CoreMessage[]; } & MastraCustomLLMOptions<Z> & DefaultLLMTextOptions; type LLMTextObjectOptions<T extends ZodSchema | JSONSchema7 | undefined = undefined> = LLMTextOptions<T> & DefaultLLMTextObjectOptions & { structuredOutput: JSONSchema7 | z.ZodType<T> | StructuredOutput; }; type LLMStreamOptions<Z extends ZodSchema | JSONSchema7 | undefined = undefined> = { output?: OutputType | Z; onFinish?: (result: string) => Promise<void> | void; } & MastraCustomLLMOptions<Z> & DefaultLLMStreamOptions; type LLMInnerStreamOptions<Z extends ZodSchema | JSONSchema7 | undefined = undefined> = { messages: CoreMessage[]; onFinish?: (result: string) => Promise<void> | void; } & MastraCustomLLMOptions<Z> & DefaultLLMStreamOptions; type LLMStreamObjectOptions<T extends ZodSchema | JSONSchema7 | undefined = undefined> = { structuredOutput: JSONSchema7 | z.ZodType<T> | StructuredOutput; } & LLMInnerStreamOptions<T> & DefaultLLMStreamObjectOptions; /** * Abstract Memory class that defines the interface for storing and retrieving * conversation threads and messages. */ declare abstract class MastraMemory extends MastraBase { MAX_CONTEXT_TOKENS?: number; storage: MastraStorage; vector: MastraVector; embedder: EmbeddingModel<string>; protected threadConfig: MemoryConfig; constructor(config: { name: string; } & SharedMemoryConfig); setStorage(storage: MastraStorage): void; setVector(vector: MastraVector): void; setEmbedder(embedder: EmbeddingModel<string>): void; /** * Get a system message to inject into the conversation. * This will be called before each conversation turn. * Implementations can override this to inject custom system messages. */ getSystemMessage(_input: { threadId: string; memoryConfig?: MemoryConfig; }): Promise<string | null>; /** * Get tools that should be available to the agent. * This will be called when converting tools for the agent. * Implementations can override this to provide additional tools. */ getTools(_config?: MemoryConfig): Record<string, CoreTool>; protected createEmbeddingIndex(): Promise<{ indexName: string; }>; getMergedThreadConfig(config?: MemoryConfig): MemoryConfig; abstract rememberMessages({ threadId, resourceId, vectorMessageSearch, config, }: { threadId: string; resourceId?: string; vectorMessageSearch?: string; config?: MemoryConfig; }): Promise<{ threadId: string; messages: CoreMessage$1[]; uiMessages: Message[]; }>; estimateTokens(text: string): number; protected parseMessages(messages: MessageType[]): CoreMessage$1[]; protected convertToUIMessages(messages: MessageType[]): Message[]; /** * Retrieves a specific thread by its ID * @param threadId - The unique identifier of the thread * @returns Promise resolving to the thread or null if not found */ abstract getThreadById({ threadId }: { threadId: string; }): Promise<StorageThreadType | null>; abstract getThreadsByResourceId({ resourceId }: { resourceId: string; }): Promise<StorageThreadType[]>; /** * Saves or updates a thread * @param thread - The thread data to save * @returns Promise resolving to the saved thread */ abstract saveThread({ thread, memoryConfig, }: { thread: StorageThreadType; memoryConfig?: MemoryConfig; }): Promise<StorageThreadType>; /** * Saves messages to a thread * @param messages - Array of messages to save * @returns Promise resolving to the saved messages */ abstract saveMessages({ messages, memoryConfig, }: { messages: MessageType[]; memoryConfig: MemoryConfig | undefined; }): Promise<MessageType[]>; /** * Retrieves all messages for a specific thread * @param threadId - The unique identifier of the thread * @returns Promise resolving to array of messages and uiMessages */ abstract query({ threadId, resourceId, selectBy, }: StorageGetMessagesArg): Promise<{ messages: CoreMessage$1[]; uiMessages: Message[]; }>; /** * Helper method to create a new thread * @param title - Optional title for the thread * @param metadata - Optional metadata for the thread * @returns Promise resolving to the created thread */ createThread({ threadId, resourceId, title, metadata, memoryConfig, }: { resourceId: string; threadId?: string; title?: string; metadata?: Record<string, unknown>; memoryConfig?: MemoryConfig; }): Promise<StorageThreadType>; /** * Helper method to delete a thread * @param threadId - the id of the thread to delete */ abstract deleteThread(threadId: string): Promise<void>; /** * Helper method to add a single message to a thread * @param threadId - The thread to add the message to * @param content - The message content * @param role - The role of the message sender * @param type - The type of the message * @param toolNames - Optional array of tool names that were called * @param toolCallArgs - Optional array of tool call arguments * @param toolCallIds - Optional array of tool call ids * @returns Promise resolving to the saved message */ addMessage({ threadId, config, content, role, type, toolNames, toolCallArgs, toolCallIds, }: { threadId: string; config?: MemoryConfig; content: UserContent | AssistantContent; role: 'user' | 'assistant'; type: 'text' | 'tool-call' | 'tool-result'; toolNames?: string[]; toolCallArgs?: Record<string, unknown>[]; toolCallIds?: string[]; }): Promise<MessageType>; /** * Generates a unique identifier * @returns A unique string ID */ generateId(): string; } type VoiceEventType = 'speaking' | 'writing' | 'error' | string; interface VoiceEventMap { speaker: NodeJS.ReadableStream; speaking: { audio?: string; }; writing: { text: string; role: 'assistant' | 'user'; }; error: { message: string; code?: string; details?: unknown; }; [key: string]: unknown; } interface BuiltInModelConfig { name: string; apiKey?: string; } interface VoiceConfig<T = unknown> { listeningModel?: BuiltInModelConfig; speechModel?: BuiltInModelConfig; speaker?: string; name?: string; realtimeConfig?: { model?: string; apiKey?: string; options?: T; }; } declare abstract class MastraVoice<TOptions = unknown, TSpeakOptions = unknown, TListenOptions = unknown, TTools extends ToolsInput = ToolsInput, TEventArgs extends VoiceEventMap = VoiceEventMap, TSpeakerMetadata = unknown> extends MastraBase { protected listeningModel?: BuiltInModelConfig; protected speechModel?: BuiltInModelConfig; protected speaker?: string; protected realtimeConfig?: { model?: string; apiKey?: string; options?: TOptions; }; constructor({ listeningModel, speechModel, speaker, realtimeConfig, name }?: VoiceConfig<TOptions>); traced<T extends Function>(method: T, methodName: string): T; /** * Convert text to speech * @param input Text or text stream to convert to speech * @param options Speech options including speaker and provider-specific options * @returns Audio stream */ /** * Convert text to speech * @param input Text or text stream to convert to speech * @param options Speech options including speaker and provider-specific options * @returns Audio stream or void if in chat mode */ abstract speak(input: string | NodeJS.ReadableStream, options?: { speaker?: string; } & TSpeakOptions): Promise<NodeJS.ReadableStream | void>; /** * Convert speech to text * @param audioStream Audio stream to transcribe * @param options Provider-specific transcription options * @returns Text or text stream */ /** * Convert speech to text * @param audioStream Audio stream to transcribe * @param options Provider-specific transcription options * @returns Text, text stream, or void if in chat mode */ abstract listen(audioStream: NodeJS.ReadableStream | unknown, // Allow other audio input types for OpenAI realtime API options?: TListenOptions): Promise<string | NodeJS.ReadableStream | void>; updateConfig(_options: Record<string, unknown>): void; /** * Initializes a WebSocket or WebRTC connection for real-time communication * @returns Promise that resolves when the connection is established */ connect(_options?: Record<string, unknown>): Promise<void>; /** * Relay audio data to the voice provider for real-time processing * @param audioData Audio data to relay */ send(_audioData: NodeJS.ReadableStream | Int16Array): Promise<void>; /** * Trigger voice providers to respond */ answer(_options?: Record<string, unknown>): Promise<void>; /** * Equip the voice provider with instructions * @param instructions Instructions to add */ addInstructions(_instructions?: string): void; /** * Equip the voice provider with tools * @param tools Array of tools to add */ addTools(_tools: TTools): void; /** * Disconnect from the WebSocket or WebRTC connection */ close(): void; /** * Register an event listener * @param event Event name (e.g., 'speaking', 'writing', 'error') * @param callback Callback function that receives event data */ on<E extends VoiceEventType>(_event: E, _callback: (data: E extends keyof TEventArgs ? TEventArgs[E] : unknown) => void): void; /** * Remove an event listener * @param event Event name (e.g., 'speaking', 'writing', 'error') * @param callback Callback function to remove */ off<E extends VoiceEventType>(_event: E, _callback: (data: E extends keyof TEventArgs ? TEventArgs[E] : unknown) => void): void; /** * Get available speakers/voices * @returns Array of available voice IDs and their metadata */ getSpeakers(): Promise<Array<{ voiceId: string; } & TSpeakerMetadata>>; } declare class CompositeVoice extends MastraVoice<unknown, unknown, unknown, ToolsInput, VoiceEventMap> { protected speakProvider?: MastraVoice; protected listenProvider?: MastraVoice; protected realtimeProvider?: MastraVoice; constructor({ speakProvider, listenProvider, realtimeProvider, }: { speakProvider?: MastraVoice; listenProvider?: MastraVoice; realtimeProvider?: MastraVoice; }); /** * Convert text to speech using the configured provider * @param input Text or text stream to convert to speech * @param options Speech options including speaker and provider-specific options * @returns Audio stream or void if in realtime mode */ speak(input: string | NodeJS.ReadableStream, options?: { speaker?: string; } & any): Promise<NodeJS.ReadableStream | void>; listen(audioStream: NodeJS.ReadableStream, options?: any): Promise<string | void | NodeJS.ReadableStream>; getSpeakers(): Promise<{ voiceId: string; }[]>; updateConfig(options: Record<string, unknown>): void; /** * Initializes a WebSocket or WebRTC connection for real-time communication * @returns Promise that resolves when the connection is established */ connect(options?: Record<string, unknown>): Promise<void>; /** * Relay audio data to the voice provider for real-time processing * @param audioData Audio data to send */ send(audioData: NodeJS.ReadableStream | Int16Array): Promise<void>; /** * Trigger voice providers to respond */ answer(options?: Record<string, unknown>): Promise<void>; /** * Equip the voice provider with instructions * @param instructions Instructions to add */ addInstructions(instructions: string): void; /** * Equip the voice provider with tools * @param tools Array of tools to add */ addTools(tools: ToolsInput): void; /** * Disconnect from the WebSocket or WebRTC connection */ close(): void; /** * Register an event listener * @param event Event name (e.g., 'speaking', 'writing', 'error') * @param callback Callback function that receives event data */ on<E extends VoiceEventType>(event: E, callback: (data: E extends keyof VoiceEventMap ? VoiceEventMap[E] : unknown) => void): void; /** * Remove an event listener * @param event Event name (e.g., 'speaking', 'writing', 'error') * @param callback Callback function to remove */ off<E extends VoiceEventType>(event: E, callback: (data: E extends keyof VoiceEventMap ? VoiceEventMap[E] : unknown) => void): void; } type ToolsInput = Record<string, ToolAction<any, any, any> | VercelTool>; type ToolsetsInput = Record<string, ToolsInput>; type MastraLanguageModel = LanguageModelV1; interface AgentConfig<TTools extends ToolsInput = ToolsInput, TMetrics extends Record<string, Metric> = Record<string, Metric>> { name: string; instructions: string; model: MastraLanguageModel; tools?: TTools; mastra?: Mastra; /** @deprecated This property is deprecated. Use evals instead to add evaluation metrics. */ metrics?: TMetrics; evals?: TMetrics; memory?: MastraMemory; voice?: CompositeVoice; } /** * Options for generating responses with an agent * @template Z - The schema type for structured output (Zod schema or JSON schema) */ type AgentGenerateOptions<Z extends ZodSchema | JSONSchema7 | undefined = undefined> = { /** Optional instructions to override the agent's default instructions */ instructions?: string; /** Additional tool sets that can be used for this generation */ toolsets?: ToolsetsInput; /** Additional context messages to include */ context?: CoreMessage[]; /** Memory configuration options */ memoryOptions?: MemoryConfig; /** Unique ID for this generation run */ runId?: string; /** Callback fired after each generation step completes */ onStepFinish?: Z extends undefined ? GenerateTextOnStepFinishCallback<any> : never; /** Maximum number of steps allowed for generation */ maxSteps?: number; /** Schema for structured output, does not work with tools, use experimental_output instead */ output?: OutputType | Z; /** Schema for structured output generation alongside tool calls. */ experimental_output?: Z; /** Controls how tools are selected during generation */ toolChoice?: 'auto' | 'none' | 'required' | { type: 'tool'; toolName: string; }; /** Telemetry settings */ telemetry?: TelemetrySettings; } & ({ resourceId?: undefined; threadId?: undefined; } | { resourceId: string; threadId: string; }) & (Z extends undefined ? DefaultLLMTextOptions : DefaultLLMTextObjectOptions); /** * Options for streaming responses with an agent * @template Z - The schema type for structured output (Zod schema or JSON schema) */ type AgentStreamOptions<Z extends ZodSchema | JSONSchema7 | undefined = undefined> = { /** Optional instructions to override the agent's default instructions */ instructions?: string; /** Additional tool sets that can be used for this generation */ toolsets?: ToolsetsInput; /** Additional context messages to include */ context?: CoreMessage[]; /** Memory configuration options */ memoryOptions?: MemoryConfig; /** Unique ID for this generation run */ runId?: string; /** Callback fired when streaming completes */ onFinish?: Z extends undefined ? StreamTextOnFinishCallback<any> : Z extends ZodSchema ? StreamObjectOnFinishCallback<z.infer<Z>> : StreamObjectOnFinishCallback<any>; /** Callback fired after each generation step completes */ onStepFinish?: Z extends undefined ? StreamTextOnStepFinishCallback<any> : never; /** Maximum number of steps allowed for generation */ maxSteps?: number; /** Schema for structured output */ output?: OutputType | Z; /** Temperature parameter for controlling randomness */ temperature?: number; /** Controls how tools are selected during generation */ toolChoice?: 'auto' | 'none' | 'required' | { type: 'tool'; toolName: string; }; /** Experimental schema for structured output */ experimental_output?: Z; /** Telemetry settings */ telemetry?: TelemetrySettings; } & ({ resourceId?: undefined; threadId?: undefined; } | { resourceId: string; threadId: string; }) & (Z extends undefined ? DefaultLLMStreamOptions : DefaultLLMStreamObjectOptions); 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> { steps?: TSteps; name: TWorkflowName; triggerSchema?: TTriggerSchema; result?: { schema: TResultSchema; mapping?: { [K in keyof z.infer<TResultSchema>]?: any; }; }; events?: Record<string, { schema: z.ZodObject<any>; }>; retryConfig?: RetryConfig; mastra?: Mastra; } interface StepExecutionContext<TSchemaIn extends z.ZodSchema | undefined = undefined, TContext extends WorkflowContext = WorkflowContext> extends IExecutionContext<TSchemaIn> { context: TSchemaIn extends z.ZodSchema ? { inputData: z.infer<TSchemaIn>; } & TContext : TContext; suspend: (payload?: unknown, softSuspend?: any) => Promise<void>; runId: string; emit: (event: string, data: any) => void; mastra?: MastraUnion; } 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> { mastra?: Mastra; payload?: TSchemaIn extends z.ZodSchema ? Partial<z.infer<TSchemaIn>> : unknown; execute: (context: TContext) => Promise<TSchemaOut extends z.ZodSchema ? z.infer<TSchemaOut> : unknown>; retryConfig?: RetryConfig; workflow?: Workflow; } interface SimpleConditionalType { [key: `${string}.${string}`]: string | Query<any>; } 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' | { id: string; }; type StepNode = { step: StepAction<any, any, any, any>; config: StepDef<any, any, any, any>[any]; }; type StepGraph = { initial: StepNode[]; [key: string]: StepNode[]; }; type RetryConfig = { attempts?: number; delay?: number; }; type VariableReference<TStep extends StepVariableType<any, any, any, any>, TTriggerSchema extends z.ZodObject<any>> = TStep extends StepAction<any, any, any, any> ? { step: TStep; path: PathsToStringProps<ExtractSchemaType<ExtractSchemaFromStep<TStep, 'outputSchema'>>> | '' | '.'; } : TStep extends 'trigger' ? { step: 'trigger'; path: PathsToStringProps<ExtractSchemaType<TTriggerSchema>> | '.' | ''; } : { step: { id: string; }; path: string; }; interface BaseCondition<TStep extends StepVariableType<any, any, any, any>, TTriggerSchema extends z.ZodObject<any>> { ref: TStep extends StepAction<any, any, any, any> ? { step: TStep; path: PathsToStringProps<ExtractSchemaType<ExtractSchemaFromStep<TStep, 'outputSchema'>>> | '' | '.' | 'status'; } : TStep extends 'trigger' ? { step: 'trigger'; path: PathsToStringProps<ExtractSchemaType<TTriggerSchema>> | '.' | ''; } : { step: { id: string; }; path: string; }; query: Query<any>; } type ActionContext<TSchemaIn extends z.ZodType<any>> = StepExecutionContext<z.infer<TSchemaIn>, WorkflowContext>; declare enum WhenConditionReturnValue { CONTINUE = "continue", CONTINUE_FAILED = "continue_failed", ABORT = "abort", LIMBO = "limbo" } 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, { when?: Condition<any, any> | ((args: { context: WorkflowContext; mastra?: Mastra; }) => Promise<boolean | WhenConditionReturnValue>); serializedWhen?: Condition<any, any> | string; loopLabel?: string; loopType?: 'while' | 'until'; data: TSchemaIn; handler: (args: ActionContext<TSchemaIn>) => Promise<z.infer<TSchemaOut>>; }>; type StepCondition<TStep extends StepVariableType<any, any, any, any>, TTriggerSchema extends z.ZodObject<any>> = BaseCondition<TStep, TTriggerSchema> | SimpleConditionalType | { and: StepCondition<TStep, TTriggerSchema>[]; } | { or: StepCondition<TStep, TTriggerSchema>[]; } | { not: StepCondition<TStep, TTriggerSchema>; }; type Condition<TStep extends StepVariableType<any, any, any, any>, TTriggerSchema extends z.ZodObject<any>> = BaseCondition<TStep, TTriggerSchema> | SimpleConditionalType | { and: Condition<TStep, TTriggerSchema>[]; } | { or: Condition<TStep, TTriggerSchema>[]; } | { not: Condition<TStep, TTriggerSchema>; }; 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>[]> { when?: Condition<CondStep, TTriggerSchema> | ((args: { context: WorkflowContext<TTriggerSchema, TSteps>; mastra?: Mastra; }) => Promise<boolean | WhenConditionReturnValue>); variables?: StepInputType<TStep, 'inputSchema'> extends never ? Record<string, VariableReference<VarStep, TTriggerSchema>> : { [K in keyof StepInputType<TStep, 'inputSchema'>]?: VariableReference<VarStep, TTriggerSchema>; }; '#internal'?: { when?: Condition<CondStep, TTriggerSchema> | ((args: { context: WorkflowContext<TTriggerSchema, TSteps>; mastra?: Mastra; }) => Promise<boolean | WhenConditionReturnValue>); loopLabel?: string; loopType?: 'while' | 'until' | undefined; }; } type StepSuccess<T> = { status: 'success'; output: T; }; type StepSuspended<T> = { status: 'suspended'; suspendPayload?: any; output?: T; }; type StepWaiting = { status: 'waiting'; }; type StepFailure = { status: 'failed'; error: string; }; type StepSkipped = { status: 'skipped'; }; type StepResult<T> = StepSuccess<T> | StepFailure | StepSuspended<T> | StepWaiting | StepSkipped; type StepsRecord<T extends readonly Step<any, any, z.ZodType<any> | undefined>[]> = { [K in T[number]['id']]: Extract<T[number], { id: K; }>; }; interface WorkflowRunResult<T extends z.ZodObject<any>, TSteps extends Step<string, any, z.ZodType<any> | undefined>[], TResult extends z.ZodObject<any>> { triggerData?: z.infer<T>; result?: z.infer<TResult>; results: { [K in keyof StepsRecord<TSteps>]: StepsRecord<TSteps>[K]['outputSchema'] extends undefined ? StepResult<unknown> : StepResult<z.infer<NonNullable<StepsRecord<TSteps>[K]['outputSchema']>>>; }; runId: string; activePaths: Map<keyof StepsRecord<TSteps>, { status: string; suspendPayload?: any; }>; } 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>> { isResume?: { runId: string; stepId: string; }; mastra?: MastraUnion; steps: { [K in keyof StepsRecord<TSteps>]: StepsRecord<TSteps>[K]['outputSchema'] extends undefined ? StepResult<unknown> : StepResult<z.infer<NonNullable<StepsRecord<TSteps>[K]['outputSchema']>>>; }; triggerData: z.infer<TTrigger>; inputData: TInputData; attempts: Record<string, number>; getStepResult(stepId: 'trigger'): z.infer<TTrigger>; 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; getStepResult<T extends Step<any, any, any, any>>(stepId: T): T['outputSchema'] extends undefined ? unknown : z.infer<NonNullable<T['outputSchema']>>; } interface WorkflowLogMessage extends BaseLogMessage { type: typeof RegisteredLogger.WORKFLOW; workflowName: string; stepId?: StepId; data?: unknown; runId?: string; } type WorkflowEvent = { type: 'RESET_TO_PENDING'; stepId: string; } | { type: 'CONDITIONS_MET'; stepId: string; } | { type: 'CONDITION_FAILED'; stepId: string; error: string; } | { type: 'SUSPENDED'; stepId: string; suspendPayload?: any; softSuspend?: any; } | { type: 'WAITING'; stepId: string; } | { type: `xstate.error.actor.${string}`; error: Error; } | { type: `xstate.done.actor.${string}`; output: ResolverFunctionOutput; }; type ResolverFunctionInput = { stepNode: StepNode; context: WorkflowContext; }; type ResolverFunctionOutput = { stepId: StepId; result: unknown; }; type SubscriberFunctionOutput = { stepId: StepId; result: unknown; }; type DependencyCheckOutput = { type: 'CONDITIONS_MET'; } | { type: 'CONDITIONS_SKIPPED'; } | { type: 'CONDITIONS_SKIP_TO_COMPLETED'; } | { type: 'CONDITION_FAILED'; error: string; } | { type: 'SUSPENDED'; } | { type: 'WAITING'; } | { type: 'CONDITIONS_LIMBO'; }; type StepResolverOutput = { type: 'STEP_SUCCESS'; output: unknown; } | { type: 'STEP_FAILED'; error: string; } | { type: 'STEP_WAITING'; }; type WorkflowActors = { resolverFunction: { input: ResolverFunctionInput; output: StepResolverOutput; }; conditionCheck: { input: { context: WorkflowContext; stepId: string; }; output: DependencyCheckOutput; }; spawnSubscriberFunction: { input: { context: WorkflowContext; stepId: string; }; output: SubscriberFunctionOutput; }; }; type WorkflowActionParams = { stepId: string; }; type WorkflowActions = { type: 'updateStepResult' | 'setStepError' | 'notifyStepCompletion' | 'decrementAttemptCount'; params: WorkflowActionParams; }; type WorkflowState = { [key: string]: { initial: 'pending'; states: { pending: { invoke: { src: 'conditionCheck'; input: ({ context }: { context: WorkflowContext; }) => { context: WorkflowContext; stepId: string; }; onDone: [ { guard: (_: any, event: { output: DependencyCheckOutput; }) => boolean; target: 'executing'; }, { guard: (_: any, event: { output: DependencyCheckOutput; }) => boolean; target: 'waiting'; } ]; }; }; waiting: { after: { CHECK_INTERVAL: { target: 'pending'; }; }; }; executing: { invoke: { src: 'resolverFunction'; input: ({ context }: { context: WorkflowContext; }) => ResolverFunctionInput; onDone: { target: 'completed'; actions: ['updateStepResult']; }; onError: { target: 'failed'; actions: ['setStepError']; }; }; }; completed: { type: 'final'; entry: ['notifyStepCompletion']; }; failed: { type: 'final'; entry: ['notifyStepCompletion']; }; }; }; }; declare const StepIdBrand: unique symbol; type StepId = string & { readonly [StepIdBrand]: typeof StepIdBrand; }; type ExtractSchemaFromStep<TStep extends StepAction<any, any, any, any>, TKey extends 'inputSchema' | 'outputSchema'> = TStep[TKey]; type ExtractStepResult<T> = T extends (data: any) => Promise<infer R> ? R : never; 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; type ExtractSchemaType<T extends z.ZodSchema> = T extends z.ZodSchema<infer V> ? V : never; type PathsToStringProps<T> = T extends object ? { [K in keyof T]: T[K] extends object ? K extends string ? K | `${K}.${PathsToStringProps<T[K]>}` : never : K extends string ? K : never; }[keyof T] : never; interface WorkflowRunState { value: Record<string, string>; context: { steps: Record<string, { status: 'success' | 'failed' | 'suspended' | 'waiting' | 'skipped'; payload?: any; error?: string; }>; triggerData: Record<string, any>; attempts: Record<string, number>; }; activePaths: Array<{ stepPath: string[]; stepId: string; status: string; }>; runId: string; timestamp: number; childStates?: Record<string, WorkflowRunState>; suspendedSteps?: Record<string, string>; } type WorkflowResumeResult<TTriggerSchema extends z.ZodObject<any>> = { triggerData?: z.infer<TTriggerSchema>; results: Record<string, StepResult<any>>; }; 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> { id: TStepId; description?: string; inputSchema?: TSchemaIn; outputSchema?: TSchemaOut; payload?: TSchemaIn extends z.ZodSchema ? Partial<z.infer<TSchemaIn>> : unknown; execute: (context: TContext) => Promise<TSchemaOut extends z.ZodSchema ? z.infer<TSchemaOut> : unknown>; retryConfig?: RetryConfig; mastra?: Mastra; constructor({ id, description, execute, payload, outputSchema, inputSchema, retryConfig, }: StepAction<TStepId, TSchemaIn, TSchemaOut, TContext>); } 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>; declare class Machine<TSteps extends Step<any, any, any>[] = any, TTriggerSchema extends z.ZodObject<any> = any, TResultSchema extends z.ZodObject<any> = any> extends EventEmitter { #private; logger: Logger; name: string; constructor({ logger, mastra, workflowInstance, executionSpan, name, runId, steps, stepGraph, retryConfig, startStepId, }: { logger: Logger; mastra?: Mastra; workflowInstance: WorkflowInstance; executionSpan?: Span; name: string; runId: string; steps: Record<string, TSteps[0]>; stepGraph: StepGraph; retryConfig?: RetryConfig; startStepId: string; }); get startStepId(): string; execute({ stepId, input, snapshot, resumeData, }?: { stepId?: string; input?: any; snapshot?: Snapshot<any>; resumeData?: any; }): Promise<Pick<WorkflowRunResult<TTriggerSchema, TSteps, TResultSchema>, 'results' | 'activePaths'>>; private initializeMachine; getSnapshot(): xstate.MachineSnapshot<Omit<WorkflowContext<any, Step<string, any, any, any>[], Record<string, any>>, "getStepResult">, { type: "RESET_TO_PENDING"; stepId: string; } | { type: "CONDITIONS_MET"; stepId: string; } | { type: "CONDITION_FAILED"; stepId: string; error: string; } | { type: "SUSPENDED"; stepId: string; suspendPayload?: any; softSuspend?: any; } | { type: "WAITING"; stepId: string; } | { type: `xstate.error.actor.${string}`; error: Error; } | { type: `xstate.done.actor.${string}`; output: ResolverFunctionOutput; }, { [x: string]: xstate.ActorRefFromLogic<xstate.PromiseActorLogic<{ type: "CONDITIONS_MET"; error?: undefined; } | { type: "CONDITIONS_SKIP_TO_COMPLETED"; error?: undefined; } | { type: "CONDITIONS_LIMBO"; error?: undefined; } | { type: "CONDITIONS_SKIPPED"; error?: undefined; } | { type: "CONDITION_FAILED"; error: string; }, { context: WorkflowContext; stepNode: StepNode; }, xstate.EventObject>> | xstate.ActorRefFromLogic<xstate.PromiseActorLogic<{ type: "STEP_FAILED"; error: string; stepId: any; result?: undefined; } | { type: "STEP_WAITING"; stepId: any; error?: undefined; result?: undefined; } | { type: "STEP_SUCCESS"; result: any; stepId: any; error?: undefined; }, ResolverFunctionInput, xstate.EventObject>> | xstate.ActorRefFromLogic<xstate.PromiseActorLogic<{ steps: {}; }, { parentStepId: string; context: WorkflowContext; }, xstate.EventObject>> | undefined; }, { [x: string]: {} | { [x: string]: {} | /*elided*/ any | { [x: string]: {} | /*elided*/ any | /*elided*/ any; }; } | { [x: string]: {} | { [x: string]: {} | /*elided*/ any | /*elided*/ any; } | /*elided*/ any; }; }, string, xstate.NonReducibleUnknown, xstate.MetaObject, { readonly id: string; readonly type: "parallel"; readonly context: ({ input }: { spawn: { <TSrc extends "conditionCheck" | "resolverFunction" | "spawnSubscriberFunction">(logic: TSrc, ...[options]: ({ src: "conditionCheck"; logic: xstate.PromiseActorLogic<{ type: "CONDITIONS_MET"; error?: undefined; } | { type: "CONDITIONS_SKIP_TO_COMPLETED"; error?: undefined; } | { type: "CONDITIONS_LIMBO"; error?: undefined; } | { type: "CONDITIONS_SKIPPED"; error?: undefined; } | { type: "CONDITION_FAILED"; error: string; }, { context: WorkflowContext; stepNode: StepNode; }, xstate.EventObject>; id: string | undefined; } extends infer T ? T extends { src: "conditionCheck"; logic: xstate.PromiseActorLogic<{ type: "CONDITIONS_MET"; error?: undefined; } | { type: "CONDITIONS_SKIP_TO_COMPLETED"; error?: undefined; } | { type: "CONDITIONS_LIMBO"; error?: undefined; } | { type: "CONDITIONS_SKIPPED"; error?: undefined; } | { type: "CONDITION_FAILED"; error: string; }, { context: WorkflowContext; stepNode: StepNode; }, xstate.EventObject>; id: string | undefined; } ? T extends { src: TSrc; } ? xstate.ConditionalRequired<[options?: ({ id?: T["id"] | undefined; systemId?: string; input?: xstate.InputFrom<T["logic"]> | undefined; syncSnapshot?: boolean; } & { [K in xstate.RequiredActorOptions<T>]: unknown; }) | undefined], xstate.IsNotNever<xstate.RequiredActorOptions<T>>> : never : never : never) | ({ src: "resolverFunction"; logic: xstate.PromiseActorLogic<{ type: "STEP_FAILED"; error: string; stepId: any; result?: undefined; } | { type: "STEP_WAITING"; stepId: any; error?: undefined; result?: undefined; } | { type: "STEP_SUCCESS"; result: any; stepId: any; error?: undefined; }, ResolverFunctionInput, xstate.EventObject>; id: string | undefined; } extends infer T_1 ? T_1 extends { src: "resolverFunction"; logic: xstate.PromiseActorLogic<{ type: "STEP_FAILED"; error: string; stepId: any; result?: undefined; } | { type: "STEP_WAITING"; stepId: any; error?: undefined; result?: undefined; } | { type: "STEP_SUCCESS"; result: any; stepId: any; error?: undefined; }, ResolverFunctionInput, xstate.EventObject>; id: string | undefined; } ? T_1 extends { src: TSrc; } ? xstate.ConditionalRequired<[options?: ({ id?: T_1["id"] | undefined; systemId?: string; input?: xstate.InputFrom<T_1["logic"]> | undefined; syncSnapshot?: boolean; } & { [K_1 in xstate.RequiredActorOptions<T_1>]: unknown; }) | undefined], xstate.IsNotNever<xstate.RequiredActorOptions<T_1>>> : never : never : never) | ({ src: "spawnSubscriberFunction"; logic: xstate.PromiseActorLogic<{ steps: {}; }, { parentStepId: string; context: WorkflowContext; }, xstate.EventObject>; id: string | undefined; } extends infer T_2 ? T_2 extends { src: "spawnSubscriberFunction"; logic: xstate.PromiseActorLogic<{ steps: {}; }, { parentStepId: string; context: WorkflowContext; }, xstate.EventObject>; id: string | undefined; } ? T_2 extends { src: TSrc; } ? xstate.ConditionalRequired<[options?: ({ id?: T_2["id"] | undefined; systemId?: string; input?: xstate.InputFrom<T_2["logic"]> | undefined; syncSnapshot?: boolean; } & { [K_2 in xstate.RequiredActorOptions<T_2>]: unknown; }) | undefined], xstate.IsNotNever<xstate.RequiredActorOptions<T_2>>> : never : never : never)): xstate.ActorRefFromLogic<xstate.GetConcreteByKey<xstate.Values<{ conditionCheck: { src: "conditionCheck"; logic: xstate.PromiseActorLogic<{ type: "CONDITIONS_MET"; error?: undefined; } | { type: "CONDITIONS_SKIP_TO_COMPLETED"; error?: undefined; } | { type: "CONDITIONS_LIMBO"; error?: undefined; } | { type: "CONDITIONS_SKIPPED"; error?: undefined; } | { type: "CONDITION_FAILED"; error: string; }, { context: WorkflowContext; stepNode: StepNode; }, xstate.EventObject>; id: string | undefined; }; resolverFunction: { src: "resolverFunction"; logic: xstate.PromiseActorLogic<{ type: "STEP_FAILED"; error: string; stepId: any; result?: undefined; } | { type: "STEP_WAITING"; stepId: any; error?: undefined; result?: undefined; } | { type: "STEP_SUCCESS"; result: any; stepId: any; error?: undefined; }, ResolverFunctionInput, xstate.EventObject>; id: string | undefined; }; spawnSubscriberFunction: { src: "spawnSubscriberFunction"; logic: xstate.PromiseActorLogic<{ steps: {}; }, { parentStepId: string; context: WorkflowContext; }, xstate.EventObject>; id: string | undefined; }; }>, "src", TSrc>["logic"]>; <TLogic extends xstate.AnyActorLogic>(src: TLogic, ...[options]: xstate.ConditionalRequired<[options?: ({ id?: never; systemId?: string; input?: xstate.InputFrom<TLogic> | undefined; syncSnapshot?: boolean; } & { [K in xstate.RequiredLogicInput<TLogic>]: unknown; }) | undefined], xstate.Is