UNPKG

@mastra/core

Version:

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

441 lines • 22.6 kB
import EventEmitter from 'events'; import type { ReadableStream, WritableStream } from 'node:stream/web'; import { z } from 'zod'; import type { Mastra, WorkflowRun } from '..'; import type { MastraPrimitives } from '../action'; import { Agent } from '../agent'; import { MastraBase } from '../base'; import { RuntimeContext } from '../di'; import type { MastraScorers } from '../scores'; import type { ChunkType } from '../stream/MastraAgentStream'; import { MastraWorkflowStream } from '../stream/MastraWorkflowStream'; import { Tool } from '../tools'; import type { ToolExecutionContext } from '../tools/types'; import type { DynamicArgument } from '../types'; import { EMITTER_SYMBOL } from './constants'; import type { ExecutionEngine, ExecutionGraph } from './execution-engine'; import type { ExecuteFunction, Step } from './step'; import type { DynamicMapping, ExtractSchemaFromStep, ExtractSchemaType, PathsToStringProps, StepResult, StepsRecord, StreamEvent, WatchEvent } from './types'; export type DefaultEngineType = {}; export type StepFlowEntry<TEngineType = DefaultEngineType> = { type: 'step'; step: Step; } | { type: 'sleep'; id: string; duration?: number; fn?: ExecuteFunction<any, any, any, any, TEngineType>; } | { type: 'sleepUntil'; id: string; date?: Date; fn?: ExecuteFunction<any, any, any, any, TEngineType>; } | { type: 'waitForEvent'; event: string; step: Step; timeout?: number; } | { type: 'parallel'; steps: StepFlowEntry[]; } | { type: 'conditional'; steps: StepFlowEntry[]; conditions: ExecuteFunction<any, any, any, any, TEngineType>[]; serializedConditions: { id: string; fn: string; }[]; } | { type: 'loop'; step: Step; condition: ExecuteFunction<any, any, any, any, TEngineType>; serializedCondition: { id: string; fn: string; }; loopType: 'dowhile' | 'dountil'; } | { type: 'foreach'; step: Step; opts: { concurrency: number; }; }; export type SerializedStep<TEngineType = DefaultEngineType> = Pick<Step<any, any, any, any, any, TEngineType>, 'id' | 'description'> & { component?: string; serializedStepFlow?: SerializedStepFlowEntry[]; mapConfig?: string; }; export type SerializedStepFlowEntry = { type: 'step'; step: SerializedStep; } | { type: 'sleep'; id: string; duration?: number; fn?: string; } | { type: 'sleepUntil'; id: string; date?: Date; fn?: string; } | { type: 'waitForEvent'; event: string; step: SerializedStep; timeout?: number; } | { type: 'parallel'; steps: SerializedStepFlowEntry[]; } | { type: 'conditional'; steps: SerializedStepFlowEntry[]; serializedConditions: { id: string; fn: string; }[]; } | { type: 'loop'; step: SerializedStep; serializedCondition: { id: string; fn: string; }; loopType: 'dowhile' | 'dountil'; } | { type: 'foreach'; step: SerializedStep; opts: { concurrency: number; }; }; export type StepWithComponent = Step<string, any, any, any, any, any> & { component?: string; steps?: Record<string, StepWithComponent>; }; export declare function mapVariable<TStep extends Step<string, any, any, any, any, any>>({ step, path, }: { step: TStep; path: PathsToStringProps<ExtractSchemaType<ExtractSchemaFromStep<TStep, 'outputSchema'>>> | '.'; }): { step: TStep; path: PathsToStringProps<ExtractSchemaType<ExtractSchemaFromStep<TStep, 'outputSchema'>>> | '.'; }; export declare function mapVariable<TWorkflow extends Workflow<any, any, any, any, any, any>>({ initData: TWorkflow, path, }: { initData: TWorkflow; path: PathsToStringProps<ExtractSchemaType<ExtractSchemaFromStep<TWorkflow, 'inputSchema'>>> | '.'; }): { initData: TWorkflow; path: PathsToStringProps<ExtractSchemaType<ExtractSchemaFromStep<TWorkflow, 'inputSchema'>>> | '.'; }; type StepParams<TStepId extends string, TStepInput extends z.ZodType<any>, TStepOutput extends z.ZodType<any>, TResumeSchema extends z.ZodType<any>, TSuspendSchema extends z.ZodType<any>> = { id: TStepId; description?: string; inputSchema: TStepInput; outputSchema: TStepOutput; resumeSchema?: TResumeSchema; suspendSchema?: TSuspendSchema; retries?: number; scorers?: DynamicArgument<MastraScorers>; execute: ExecuteFunction<z.infer<TStepInput>, z.infer<TStepOutput>, z.infer<TResumeSchema>, z.infer<TSuspendSchema>, DefaultEngineType>; }; type ToolStep<TSchemaIn extends z.ZodType<any>, TSchemaOut extends z.ZodType<any>, TContext extends ToolExecutionContext<TSchemaIn>> = Tool<TSchemaIn, TSchemaOut, TContext> & { inputSchema: TSchemaIn; outputSchema: TSchemaOut; execute: (context: TContext) => Promise<any>; }; /** * Creates a new workflow step * @param params Configuration parameters for the step * @param params.id Unique identifier for the step * @param params.description Optional description of what the step does * @param params.inputSchema Zod schema defining the input structure * @param params.outputSchema Zod schema defining the output structure * @param params.execute Function that performs the step's operations * @returns A Step object that can be added to the workflow */ export declare function createStep<TStepId extends string, TStepInput extends z.ZodType<any>, TStepOutput extends z.ZodType<any>, TResumeSchema extends z.ZodType<any>, TSuspendSchema extends z.ZodType<any>>(params: StepParams<TStepId, TStepInput, TStepOutput, TResumeSchema, TSuspendSchema>): Step<TStepId, TStepInput, TStepOutput, TResumeSchema, TSuspendSchema, DefaultEngineType>; export declare function createStep<TStepId extends string, TStepInput extends z.ZodObject<{ prompt: z.ZodString; }>, TStepOutput extends z.ZodObject<{ text: z.ZodString; }>, TResumeSchema extends z.ZodType<any>, TSuspendSchema extends z.ZodType<any>>(agent: Agent<TStepId, any, any>): Step<TStepId, TStepInput, TStepOutput, TResumeSchema, TSuspendSchema, DefaultEngineType>; export declare function createStep<TSchemaIn extends z.ZodType<any>, TSchemaOut extends z.ZodType<any>, TContext extends ToolExecutionContext<TSchemaIn>>(tool: ToolStep<TSchemaIn, TSchemaOut, TContext>): Step<string, TSchemaIn, TSchemaOut, z.ZodType<any>, z.ZodType<any>, DefaultEngineType>; export declare function cloneStep<TStepId extends string>(step: Step<string, any, any, any, any, DefaultEngineType>, opts: { id: TStepId; }): Step<TStepId, any, any, any, any, DefaultEngineType>; export declare function createWorkflow<TWorkflowId extends string = string, TInput extends z.ZodType<any> = z.ZodType<any>, TOutput extends z.ZodType<any> = z.ZodType<any>, TSteps extends Step<string, any, any, any, any, DefaultEngineType>[] = Step<string, any, any, any, any, DefaultEngineType>[]>(params: WorkflowConfig<TWorkflowId, TInput, TOutput, TSteps>): Workflow<DefaultEngineType, TSteps, TWorkflowId, TInput, TOutput, TInput>; export declare function cloneWorkflow<TWorkflowId extends string = string, TInput extends z.ZodType<any> = z.ZodType<any>, TOutput extends z.ZodType<any> = z.ZodType<any>, TSteps extends Step<string, any, any, any, any, DefaultEngineType>[] = Step<string, any, any, any, any, DefaultEngineType>[], TPrevSchema extends z.ZodType<any> = TInput>(workflow: Workflow<DefaultEngineType, TSteps, string, TInput, TOutput, TPrevSchema>, opts: { id: TWorkflowId; }): Workflow<DefaultEngineType, TSteps, TWorkflowId, TInput, TOutput, TPrevSchema>; export type WorkflowResult<TOutput extends z.ZodType<any>, TSteps extends Step<string, any, any>[]> = { status: 'success'; result: z.infer<TOutput>; steps: { [K in keyof StepsRecord<TSteps>]: StepsRecord<TSteps>[K]['outputSchema'] extends undefined ? StepResult<unknown, unknown, unknown, unknown> : StepResult<z.infer<NonNullable<StepsRecord<TSteps>[K]['inputSchema']>>, z.infer<NonNullable<StepsRecord<TSteps>[K]['resumeSchema']>>, z.infer<NonNullable<StepsRecord<TSteps>[K]['suspendSchema']>>, z.infer<NonNullable<StepsRecord<TSteps>[K]['outputSchema']>>>; }; } | { status: 'failed'; steps: { [K in keyof StepsRecord<TSteps>]: StepsRecord<TSteps>[K]['outputSchema'] extends undefined ? StepResult<unknown, unknown, unknown, unknown> : StepResult<z.infer<NonNullable<StepsRecord<TSteps>[K]['inputSchema']>>, z.infer<NonNullable<StepsRecord<TSteps>[K]['resumeSchema']>>, z.infer<NonNullable<StepsRecord<TSteps>[K]['suspendSchema']>>, z.infer<NonNullable<StepsRecord<TSteps>[K]['outputSchema']>>>; }; error: Error; } | { status: 'suspended'; steps: { [K in keyof StepsRecord<TSteps>]: StepsRecord<TSteps>[K]['outputSchema'] extends undefined ? StepResult<unknown, unknown, unknown, unknown> : StepResult<z.infer<NonNullable<StepsRecord<TSteps>[K]['inputSchema']>>, z.infer<NonNullable<StepsRecord<TSteps>[K]['resumeSchema']>>, z.infer<NonNullable<StepsRecord<TSteps>[K]['suspendSchema']>>, z.infer<NonNullable<StepsRecord<TSteps>[K]['outputSchema']>>>; }; suspended: [string[], ...string[][]]; }; export type WorkflowConfig<TWorkflowId extends string = string, TInput extends z.ZodType<any> = z.ZodType<any>, TOutput extends z.ZodType<any> = z.ZodType<any>, TSteps extends Step<string, any, any, any, any, any>[] = Step<string, any, any, any, any, any>[]> = { mastra?: Mastra; id: TWorkflowId; description?: string | undefined; inputSchema: TInput; outputSchema: TOutput; executionEngine?: ExecutionEngine; steps?: TSteps; retryConfig?: { attempts?: number; delay?: number; }; }; export declare class Workflow<TEngineType = any, TSteps extends Step<string, any, any, any, any, TEngineType>[] = Step<string, any, any, any, any, TEngineType>[], TWorkflowId extends string = string, TInput extends z.ZodType<any> = z.ZodType<any>, TOutput extends z.ZodType<any> = z.ZodType<any>, TPrevSchema extends z.ZodType<any> = TInput> extends MastraBase implements Step<TWorkflowId, TInput, TOutput, any, any, DefaultEngineType> { #private; id: TWorkflowId; description?: string | undefined; inputSchema: TInput; outputSchema: TOutput; steps: Record<string, StepWithComponent>; stepDefs?: TSteps; protected stepFlow: StepFlowEntry<TEngineType>[]; protected serializedStepFlow: SerializedStepFlowEntry[]; protected executionEngine: ExecutionEngine; protected executionGraph: ExecutionGraph; protected retryConfig: { attempts?: number; delay?: number; }; constructor({ mastra, id, inputSchema, outputSchema, description, executionEngine, retryConfig, steps, }: WorkflowConfig<TWorkflowId, TInput, TOutput, TSteps>); get runs(): Map<string, Run<TEngineType, TSteps, TInput, TOutput>>; get mastra(): Mastra<Record<string, Agent<any, import("../agent").ToolsInput, Record<string, import("..").Metric>>>, Record<string, import("./legacy").LegacyWorkflow<import("./legacy").LegacyStep<string, any, any, import("./legacy").StepExecutionContext<any, import("./legacy").WorkflowContext<any, import("./legacy").LegacyStep<string, any, any, any>[], Record<string, any>>>>[], string, any, any>>, Record<string, Workflow<any, Step<string, any, any, any, any, any>[], string, z.ZodType<any, z.ZodTypeDef, any>, z.ZodType<any, z.ZodTypeDef, any>, z.ZodType<any, z.ZodTypeDef, any>>>, Record<string, import("../vector").MastraVector<import("../vector/filter").VectorFilter>>, Record<string, import("../tts").MastraTTS>, import("../logger").IMastraLogger, Record<string, import("../network").AgentNetwork>, Record<string, import("../network/vNext").NewAgentNetwork>, Record<string, import("../mcp").MCPServerBase>> | undefined; __registerMastra(mastra: Mastra): void; __registerPrimitives(p: MastraPrimitives): void; setStepFlow(stepFlow: StepFlowEntry<TEngineType>[]): void; /** * Adds a step to the workflow * @param step The step to add to the workflow * @returns The workflow instance for chaining */ then<TStepInputSchema extends TPrevSchema, TStepId extends string, TSchemaOut extends z.ZodType<any>>(step: Step<TStepId, TStepInputSchema, TSchemaOut, any, any, TEngineType>): Workflow<TEngineType, TSteps, TWorkflowId, TInput, TOutput, TSchemaOut>; /** * Adds a sleep step to the workflow * @param duration The duration to sleep for * @returns The workflow instance for chaining */ sleep(duration: number | ExecuteFunction<z.infer<TPrevSchema>, number, any, any, TEngineType>): Workflow<TEngineType, TSteps, TWorkflowId, TInput, TOutput, TPrevSchema>; /** * Adds a sleep until step to the workflow * @param date The date to sleep until * @returns The workflow instance for chaining */ sleepUntil(date: Date | ExecuteFunction<z.infer<TPrevSchema>, Date, any, any, TEngineType>): Workflow<TEngineType, TSteps, TWorkflowId, TInput, TOutput, TPrevSchema>; waitForEvent<TStepInputSchema extends TPrevSchema, TStepId extends string, TSchemaOut extends z.ZodType<any>>(event: string, step: Step<TStepId, TStepInputSchema, TSchemaOut, any, any, TEngineType>, opts?: { timeout?: number; }): Workflow<TEngineType, TSteps, TWorkflowId, TInput, TOutput, TSchemaOut>; map(mappingConfig: { [k: string]: { step: Step<string, any, any, any, any, TEngineType> | Step<string, any, any, any, any, TEngineType>[]; path: string; } | { value: any; schema: z.ZodType<any>; } | { initData: Workflow<TEngineType, any, any, any, any, any>; path: string; } | { runtimeContextPath: string; schema: z.ZodType<any>; } | DynamicMapping<TPrevSchema, z.ZodType<any>>; } | ExecuteFunction<z.infer<TPrevSchema>, any, any, any, TEngineType>): Workflow<TEngineType, TSteps, TWorkflowId, TInput, TOutput, any>; parallel<TParallelSteps extends Step<string, TPrevSchema, any, any, any, TEngineType>[]>(steps: TParallelSteps): Workflow<TEngineType, TSteps, TWorkflowId, TInput, TOutput, z.ZodObject<{ [K in keyof StepsRecord<TParallelSteps>]: StepsRecord<TParallelSteps>[K]["outputSchema"]; }, any, z.ZodTypeAny>>; branch<TBranchSteps extends Array<[ ExecuteFunction<z.infer<TPrevSchema>, any, any, any, TEngineType>, Step<string, TPrevSchema, any, any, any, TEngineType> ]>>(steps: TBranchSteps): Workflow<TEngineType, TSteps, TWorkflowId, TInput, TOutput, z.ZodObject<{ [K in keyof StepsRecord<{ [K_1 in keyof TBranchSteps]: TBranchSteps[K_1][1]; }[number][]>]: StepsRecord<{ [K_1 in keyof TBranchSteps]: TBranchSteps[K_1][1]; }[number][]>[K]["outputSchema"]; }, any, z.ZodTypeAny>>; dowhile<TStepInputSchema extends TPrevSchema, TStepId extends string, TSchemaOut extends z.ZodType<any>>(step: Step<TStepId, TStepInputSchema, TSchemaOut, any, any, TEngineType>, condition: ExecuteFunction<z.infer<TSchemaOut>, any, any, any, TEngineType>): Workflow<TEngineType, TSteps, TWorkflowId, TInput, TOutput, TSchemaOut>; dountil<TStepInputSchema extends TPrevSchema, TStepId extends string, TSchemaOut extends z.ZodType<any>>(step: Step<TStepId, TStepInputSchema, TSchemaOut, any, any, TEngineType>, condition: ExecuteFunction<z.infer<TSchemaOut>, any, any, any, TEngineType>): Workflow<TEngineType, TSteps, TWorkflowId, TInput, TOutput, TSchemaOut>; foreach<TPrevIsArray extends TPrevSchema extends z.ZodArray<any> ? true : false, TStepInputSchema extends TPrevSchema extends z.ZodArray<infer TElement> ? TElement : never, TStepId extends string, TSchemaOut extends z.ZodType<any>>(step: TPrevIsArray extends true ? Step<TStepId, TStepInputSchema, TSchemaOut, any, any, TEngineType> : 'Previous step must return an array type', opts?: { concurrency: number; }): Workflow<TEngineType, TSteps, TWorkflowId, TInput, TOutput, z.ZodArray<TSchemaOut>>; /** * Builds the execution graph for this workflow * @returns The execution graph that can be used to execute the workflow */ buildExecutionGraph(): ExecutionGraph; /** * Finalizes the workflow definition and prepares it for execution * This method should be called after all steps have been added to the workflow * @returns A built workflow instance ready for execution */ commit(): Workflow<TEngineType, TSteps, TWorkflowId, TInput, TOutput, TOutput>; get stepGraph(): StepFlowEntry<TEngineType>[]; get serializedStepGraph(): SerializedStepFlowEntry[]; /** * Creates a new workflow run instance * @param options Optional configuration for the run * @returns A Run instance that can be used to execute the workflow */ createRun(options?: { runId?: string; }): Run<TEngineType, TSteps, TInput, TOutput>; /** * Creates a new workflow run instance and stores a snapshot of the workflow in the storage * @param options Optional configuration for the run * @returns A Run instance that can be used to execute the workflow */ createRunAsync(options?: { runId?: string; }): Promise<Run<TEngineType, TSteps, TInput, TOutput>>; getScorers({ runtimeContext, }?: { runtimeContext?: RuntimeContext; }): Promise<MastraScorers>; execute({ inputData, resumeData, suspend, resume, [EMITTER_SYMBOL]: emitter, mastra, runtimeContext, abort, abortSignal, runCount, }: { inputData: z.infer<TInput>; resumeData?: any; getStepResult<T extends Step<any, any, any, any, any, TEngineType>>(stepId: T): T['outputSchema'] extends undefined ? unknown : z.infer<NonNullable<T['outputSchema']>>; suspend: (suspendPayload: any) => Promise<any>; resume?: { steps: string[]; resumePayload: any; runId?: string; }; [EMITTER_SYMBOL]: { emit: (event: string, data: any) => void; }; mastra: Mastra; runtimeContext?: RuntimeContext; engine: DefaultEngineType; abortSignal: AbortSignal; bail: (result: any) => any; abort: () => any; runCount?: number; }): Promise<z.infer<TOutput>>; getWorkflowRuns(args?: { fromDate?: Date; toDate?: Date; limit?: number; offset?: number; resourceId?: string; }): Promise<import("..").WorkflowRuns>; getWorkflowRunById(runId: string): Promise<WorkflowRun | null>; getWorkflowRunExecutionResult(runId: string): Promise<WatchEvent['payload']['workflowState'] | null>; } /** * Represents a workflow run that can be executed */ export declare class Run<TEngineType = any, TSteps extends Step<string, any, any, any, any, TEngineType>[] = Step<string, any, any, any, any, TEngineType>[], TInput extends z.ZodType<any> = z.ZodType<any>, TOutput extends z.ZodType<any> = z.ZodType<any>> { #private; abortController: AbortController; protected emitter: EventEmitter; /** * Unique identifier for this workflow */ readonly workflowId: string; /** * Unique identifier for this run */ readonly runId: string; /** * Internal state of the workflow run */ protected state: Record<string, any>; /** * The execution engine for this run */ executionEngine: ExecutionEngine; /** * The execution graph for this run */ executionGraph: ExecutionGraph; /** * The serialized step graph for this run */ serializedStepGraph: SerializedStepFlowEntry[]; protected closeStreamAction?: () => Promise<void>; protected executionResults?: Promise<WorkflowResult<TOutput, TSteps>>; protected cleanup?: () => void; protected retryConfig?: { attempts?: number; delay?: number; }; constructor(params: { workflowId: string; runId: string; executionEngine: ExecutionEngine; executionGraph: ExecutionGraph; mastra?: Mastra; retryConfig?: { attempts?: number; delay?: number; }; cleanup?: () => void; serializedStepGraph: SerializedStepFlowEntry[]; }); /** * Cancels the workflow execution */ cancel(): Promise<void>; sendEvent(event: string, data: any): Promise<void>; /** * Starts the workflow execution with the provided input * @param input The input data for the workflow * @returns A promise that resolves to the workflow output */ start({ inputData, runtimeContext, writableStream, }: { inputData?: z.infer<TInput>; runtimeContext?: RuntimeContext; writableStream?: WritableStream<ChunkType>; }): Promise<WorkflowResult<TOutput, TSteps>>; /** * Starts the workflow execution with the provided input as a stream * @param input The input data for the workflow * @returns A promise that resolves to the workflow output */ stream({ inputData, runtimeContext }?: { inputData?: z.infer<TInput>; runtimeContext?: RuntimeContext; }): { stream: ReadableStream<StreamEvent>; getWorkflowState: () => Promise<WorkflowResult<TOutput, TSteps>>; }; /** * Starts the workflow execution with the provided input as a stream * @param input The input data for the workflow * @returns A promise that resolves to the workflow output */ streamVNext({ inputData, runtimeContext }?: { inputData?: z.infer<TInput>; runtimeContext?: RuntimeContext; }): MastraWorkflowStream; watch(cb: (event: WatchEvent) => void, type?: 'watch' | 'watch-v2'): () => void; resume<TResumeSchema extends z.ZodType<any>>(params: { resumeData?: z.infer<TResumeSchema>; step?: Step<string, any, any, TResumeSchema, any, TEngineType> | [...Step<string, any, any, any, any, TEngineType>[], Step<string, any, any, TResumeSchema, any, TEngineType>] | string | string[]; runtimeContext?: RuntimeContext; runCount?: number; }): Promise<WorkflowResult<TOutput, TSteps>>; /** * Returns the current state of the workflow run * @returns The current state of the workflow run */ getState(): Record<string, any>; updateState(state: Record<string, any>): void; /** * @access private * @returns The execution results of the workflow run */ _getExecutionResults(): Promise<WorkflowResult<TOutput, TSteps>> | undefined; } export {}; //# sourceMappingURL=workflow.d.ts.map