@mastra/core
Version:
The core foundation of the Mastra framework, providing essential components and interfaces for building AI-powered applications.
1,116 lines (1,107 loc) • 121 kB
TypeScript
import * as ai from 'ai';
import { Tool as Tool$1, ToolExecutionOptions, LanguageModelV1, CoreMessage as CoreMessage$1, GenerateTextResult, GenerateObjectResult, StreamTextResult, StreamObjectResult, EmbeddingModel, Message, UserContent, AssistantContent, LanguageModel as LanguageModel$1, DeepPartial, generateText, generateObject, streamText, streamObject, TelemetrySettings, 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, ToolContent } from 'ai';
import { M as MastraBase, T as Telemetry, O as OtelConfig } from './base-DT2poiVK.js';
import { a as Metric, M as MetricResult, T as TestInfo } from './types-BtMyV38I.js';
import { Query } from 'sift';
import { z, ZodSchema } from 'zod';
import { JSONSchema7 } from 'json-schema';
import { B as BaseLogMessage, R as RegisteredLogger, L as Logger, d as Run$1 } from './index-CquI0inB.js';
import { RuntimeContext } from './runtime-context/index.js';
import { Span } from '@opentelemetry/api';
import * as xstate from 'xstate';
import { Snapshot } from 'xstate';
import EventEmitter from 'node:events';
import { MastraVector } from './vector/index.js';
import { MastraTTS } from './tts/index.js';
import EventEmitter$1 from 'events';
import { MastraDeployer } from './deployer/index.js';
import { Handler, MiddlewareHandler } from 'hono';
import { cors } from 'hono/cors';
import { DescribeRouteOptions } from 'hono-openapi';
import { MockLanguageModelV1 } from 'ai/test';
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;
runtimeContext: RuntimeContext;
}
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>, TExecute extends ToolAction<TSchemaIn, TSchemaOut, TContext>['execute'] = ToolAction<TSchemaIn, TSchemaOut, TContext>['execute']>(opts: ToolAction<TSchemaIn, TSchemaOut, TContext> & {
execute?: TExecute;
}): [TSchemaIn, TSchemaOut, TExecute] extends [z.ZodSchema, z.ZodSchema, Function] ? Tool<TSchemaIn, TSchemaOut, TContext> & {
inputSchema: TSchemaIn;
outputSchema: TSchemaOut;
execute: (context: TContext) => Promise<any>;
} : Tool<TSchemaIn, TSchemaOut, TContext>;
type AgentNetworkConfig = {
name: string;
agents: Agent[];
model: LanguageModelV1;
instructions: string;
};
declare class AgentNetwork extends MastraBase {
#private;
constructor(config: AgentNetworkConfig);
formatAgentId(name: string): string;
getTools(): {
readonly transmit: Tool<z.ZodObject<{
actions: z.ZodArray<z.ZodObject<{
agent: z.ZodString;
input: z.ZodString;
includeHistory: z.ZodOptional<z.ZodBoolean>;
}, "strip", z.ZodTypeAny, {
input: string;
agent: string;
includeHistory?: boolean | undefined;
}, {
input: string;
agent: string;
includeHistory?: boolean | undefined;
}>, "many">;
}, "strip", z.ZodTypeAny, {
actions: {
input: string;
agent: string;
includeHistory?: boolean | undefined;
}[];
}, {
actions: {
input: string;
agent: string;
includeHistory?: boolean | undefined;
}[];
}>, undefined, ToolExecutionContext<z.ZodObject<{
actions: z.ZodArray<z.ZodObject<{
agent: z.ZodString;
input: z.ZodString;
includeHistory: z.ZodOptional<z.ZodBoolean>;
}, "strip", z.ZodTypeAny, {
input: string;
agent: string;
includeHistory?: boolean | undefined;
}, {
input: string;
agent: string;
includeHistory?: boolean | undefined;
}>, "many">;
}, "strip", z.ZodTypeAny, {
actions: {
input: string;
agent: string;
includeHistory?: boolean | undefined;
}[];
}, {
actions: {
input: string;
agent: string;
includeHistory?: boolean | undefined;
}[];
}>>>;
};
getAgentHistory(agentId: string): {
input: string;
output: string;
timestamp: string;
}[];
/**
* Get the history of all agent interactions that have occurred in this network
* @returns A record of agent interactions, keyed by agent ID
*/
getAgentInteractionHistory(): {
[x: string]: {
input: string;
output: string;
timestamp: string;
}[];
};
/**
* Get a summary of agent interactions in a more readable format, displayed chronologically
* @returns A formatted string with all agent interactions in chronological order
*/
getAgentInteractionSummary(): string;
executeAgent(agentId: string, input: CoreMessage$1[], includeHistory?: boolean, runtimeContext?: RuntimeContext): Promise<string>;
getInstructions(): string;
getRoutingAgent(): Agent<string, ToolsInput, Record<string, Metric>>;
getAgents(): Agent<string, ToolsInput, Record<string, Metric>>[];
generate<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[], args?: AgentGenerateOptions<Z> & {
output?: never;
experimental_output?: never;
}): Promise<GenerateTextResult<any, Z extends ZodSchema ? z.infer<Z> : unknown>>;
generate<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[], args?: AgentGenerateOptions<Z> & ({
output: Z;
experimental_output?: never;
} | {
experimental_output: Z;
output?: never;
})): Promise<GenerateObjectResult<Z extends ZodSchema ? z.infer<Z> : unknown>>;
stream<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[], args?: AgentStreamOptions<Z> & {
output?: never;
experimental_output?: never;
}): Promise<StreamTextResult<any, Z extends ZodSchema ? z.infer<Z> : unknown>>;
stream<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[], args?: AgentStreamOptions<Z> & ({
output: Z;
experimental_output?: never;
} | {
experimental_output: Z;
output?: never;
})): Promise<StreamObjectResult<any, Z extends ZodSchema ? z.infer<Z> : unknown, any>>;
__registerMastra(p: Mastra): void;
}
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;
runtimeContext: RuntimeContext;
}
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;
workflowId?: string;
}
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 = {
id: string;
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$1<TStep extends StepVariableType<any, any, any, any>, TTriggerSchema extends z.ZodObject<any>> = TStep extends StepAction<any, any, any, any> ? {
step: TStep;
path: PathsToStringProps$1<ExtractSchemaType$1<ExtractSchemaFromStep$1<TStep, 'outputSchema'>>> | '' | '.';
} : TStep extends 'trigger' ? {
step: 'trigger';
path: PathsToStringProps$1<ExtractSchemaType$1<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$1<ExtractSchemaType$1<ExtractSchemaFromStep$1<TStep, 'outputSchema'>>> | '' | '.' | 'status';
} : TStep extends 'trigger' ? {
step: 'trigger';
path: PathsToStringProps$1<ExtractSchemaType$1<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, {
id?: string;
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$1<VarStep, TTriggerSchema>> : {
[K in keyof StepInputType<TStep, 'inputSchema'>]?: VariableReference$1<VarStep, TTriggerSchema>;
};
'#internal'?: {
when?: Condition<CondStep, TTriggerSchema> | ((args: {
context: WorkflowContext<TTriggerSchema, TSteps>;
mastra?: Mastra;
}) => Promise<boolean | WhenConditionReturnValue>);
loopLabel?: string;
loopType?: 'while' | 'until' | undefined;
};
id?: string;
}
type StepSuccess$1<T> = {
status: 'success';
output: T;
};
type StepSuspended$1<T> = {
status: 'suspended';
suspendPayload?: any;
output?: T;
};
type StepWaiting = {
status: 'waiting';
};
type StepFailure$1 = {
status: 'failed';
error: string;
};
type StepSkipped = {
status: 'skipped';
};
type StepResult$1<T> = StepSuccess$1<T> | StepFailure$1 | StepSuspended$1<T> | StepWaiting | StepSkipped;
type StepsRecord$1<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$1<TSteps>]: StepsRecord$1<TSteps>[K]['outputSchema'] extends undefined ? StepResult$1<unknown> : StepResult$1<z.infer<NonNullable<StepsRecord$1<TSteps>[K]['outputSchema']>>>;
};
runId: string;
timestamp: number;
activePaths: Map<keyof StepsRecord$1<TSteps>, {
status: string;
suspendPayload?: any;
stepPath: string[];
}>;
}
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$1<TSteps>]: StepsRecord$1<TSteps>[K]['outputSchema'] extends undefined ? StepResult$1<unknown> : StepResult$1<z.infer<NonNullable<StepsRecord$1<TSteps>[K]['outputSchema']>>>;
};
triggerData: z.infer<TTrigger>;
inputData: TInputData;
attempts: Record<string, number>;
getStepResult(stepId: 'trigger'): z.infer<TTrigger>;
getStepResult<T extends keyof StepsRecord$1<TSteps> | unknown>(stepId: T extends keyof StepsRecord$1<TSteps> ? T : string): T extends keyof StepsRecord$1<TSteps> ? StepsRecord$1<TSteps>[T]['outputSchema'] extends undefined ? unknown : z.infer<NonNullable<StepsRecord$1<TSteps>[T]['outputSchema']>> : T;
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$1<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$1<TStep, TKey> extends infer Schema ? Schema extends z.ZodType<any> ? z.infer<Schema> : never : never;
type ExtractSchemaType$1<T extends z.ZodSchema> = T extends z.ZodSchema<infer V> ? V : never;
type PathsToStringProps$1<T> = T extends object ? {
[K in keyof T]: T[K] extends object ? K extends string ? K | `${K}.${PathsToStringProps$1<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;
}>;
suspendedPaths: Record<string, number[]>;
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$1<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 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 {
#private;
logger: Logger;
name: string;
constructor({ logger, mastra, runtimeContext, workflowInstance, executionSpan, name, runId, steps, stepGraph, retryConfig, startStepId, }: {
logger: Logger;
mastra?: Mastra;
runtimeContext: RuntimeContext;
workflowInstance: WorkflowInstance;
executionSpan?: Span;
name: string;
runId: string;
steps: Record<string, StepNode>;
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' | 'runId' | 'timestamp'>>;
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: string;
result?: undefined;
} | {
type: "STEP_WAITING";
stepId: string;
error?: undefined;
result?: undefined;
} | {
type: "STEP_SUCCESS";
result: any;
stepId: string;
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: string;
result?: undefined;
} | {
type: "STEP_WAITING";
stepId: string;
error?: undefined;
result?: undefined;
} | {
type: "STEP_SUCCESS";
result: any;
stepId: string;
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: string;
result?: undefined;
} | {
type: "STEP_WAITING";
stepId: string;
error?: undefined;
result?: undefined;
} | {
type: "STEP_SUCCESS";
result: any;
stepId: string;
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: string;
result?: undefined;
} | {
type: "STEP_WAITING";
stepId: string;
error?: undefined;
result?: undefined;
} | {
type: "STEP_SUCCESS";
result: any;
stepId: string;
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.IsNotNever<xstate.RequiredLogicInput<TLogic>>>): xstate.ActorRefFromLogic<TLogic>;
};
input: Omit<WorkflowContext<any, Step<string, any, any, any>[], Record<string, any>>, "getStepResult">;
self: xstate.ActorRef<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;
}, Record<string, xstate.AnyActorRef | undefined>, xstate.StateValue, string, unknown, any, any>, {
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;
}, xstate.AnyEventObject>;
}) => {
mastra?: MastraUnion | undefined;
triggerData: any;
isResume?: {
runId: string;
stepId: string;
} | undefined;
steps: {
[x: string]: {
status: "failed";
error: string;
} | {
status: "waiting";
} | {
status: "skipped";
} | {
status: "success";
output: unknown;
} | {
status: "suspended";
suspendPayload?: any;
output?: unknown;
} | {
status: "success";
output: any;
} | {
status: "suspended";
suspendPayload?: any;
output?: any;
};
};
inputData: Record<string, any>;
attempts: Record<string, number>;
};
readonly states: any;
}> | undefined;
}
interface WorkflowResultReturn<TResult extends z.ZodObject<any>, T extends z.ZodObject<any>, TSteps extends Step<any, any, any>[]> {
runId: string;
start: (props?: {
triggerData?: z.infer<T>;
runtimeContext?: RuntimeContext;
} | undefined) => Promise<WorkflowRunResult<T, TSteps, TResult>>;
watch: (onTransition: (state: Pick<WorkflowRunResult<T, TSteps, TResult>, 'results' | 'activePaths' | 'runId'>) => void) => () => void;
resume: (props: {
stepId: string;
context?: Record<string, any>;
runtimeContext?: RuntimeContext;
}) => Promise<Omit<WorkflowRunResult<T, TSteps, TResult>, 'runId'> | undefined>;
resumeWithEvent: (eventName: string, data: any, runtimeContext?: RuntimeContext) => Promise<Omit<WorkflowRunResult<T, TSteps, TResult>, 'runId'> | undefined>;
}
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> {
#private;
name: string;
logger: Logger;
events?: Record<string, {
schema: z.ZodObject<any>;
}>;
constructor({ name, logger, steps, runId, retryConfig, mastra, stepGraph, stepSubscriberGraph, onFinish, onStepTransition, resultMapping, events, }: {
name: string;
logger: Logger;
steps: Record<string, StepNode>;
mastra?: Mastra;
retryConfig?: RetryConfig;
runId?: string;
stepGraph: StepGraph;
stepSubscriberGraph: Record<string, StepGraph>;
onFinish?: () => void;
onStepTransition?: Set<(state: Pick<WorkflowRunResult<TTriggerSchema, TSteps, TResult>, 'results' | 'activePaths' | 'runId' | 'timestamp'>) => void | Promise<void>>;
resultMapping?: Record<string, {
step: StepAction<any, any, any, any>;
path: string;
}>;
events?: Record<string, {
schema: z.ZodObject<any>;
}>;
});
setState(state: any): void;
get runId(): string;
get executionSpan(): Span | undefined;
watch(onTransition: (state: Pick<WorkflowRunResult<TTriggerSchema, TSteps, TResult>, 'results' | 'activePaths' | 'runId' | 'timestamp'>) => void): () => void;
start({ triggerData, runtimeContext, }?: {
triggerData?: z.infer<TTriggerSchema>;
runtimeContext?: RuntimeContext;
}): Promise<{
runId: string;
timestamp: number;
result?: z.TypeOf<TResult> | undefined;
triggerData?: z.TypeOf<TTriggerSchema> | undefined;
results: { [K in keyof StepsRecord$1<TSteps>]: StepsRecord$1<TSteps>[K]["outputSchema"] extends undefined ? StepResult$1<unknown> : StepResult$1<z.TypeOf<NonNullable<StepsRecord$1<TSteps>[K]["outputSchema"]>>>; };
activePaths: Map<TSteps[number]["id"], {
status: string;
suspendPayload?: any;
stepPath: string[];
}>;
}>;
private isCompoundDependencyMet;
execute({ triggerData, snapshot, stepId, resumeData, runtimeContext, }?: {
stepId?: string;
triggerData?: z.infer<TTriggerSchema>;
snapshot?: Snapshot<any>;
resumeData?: any;
runtimeContext: RuntimeContext;
}): Promise<Omit<WorkflowRunResult<TTriggerSchema, TSteps, TResult>, 'runId'>>;
hasSubscribers(stepId: string): boolean;
runMachine(parentStepId: string, input: any, runtimeContext?: RuntimeContext): Promise<(Pick<WorkflowRunResult<TTriggerSchema, TSteps, TResult>, "runId" | "timestamp" | "results" | "activePaths"> | undefined)[]>;
suspend(stepId: string, machine: Machine<TSteps, TTriggerSchema>): Promise<void>;
/**
* Persists the workflow state to the database
*/
persistWorkflowSnapshot(): Promise<void>;
getState(): Promise<WorkflowRunState | null>;
resumeWithEvent(eventName: string, data: any, runtimeContext?: RuntimeContext): Promise<Omit<WorkflowRunResult<TTriggerSchema, TSteps, TResult>, "runId"> | undefined>;
resume({ stepId, context: resumeContext, runtimeContext, }: {
stepId: string;
context?: Record<string, any>;
runtimeContext?: RuntimeContext;
}): Promise<Omit<WorkflowRunResult<TTriggerSchema, TSteps, TResult>, "runId"> | undefined>;
_resume({ stepId, context: resumeContext, runtimeContext, }: {
stepId: string;
context?: Record<string, any>;
runtimeContext: RuntimeContext;
}): Promise<Omit<WorkflowRunResult<TTriggerSchema, TSteps, TResult>, "runId"> | undefined>;
}
type WorkflowBuilder<T extends Workflow<any, any>> = Pick<T, 'step' | 'then' | 'after' | 'while' | 'until' | 'if' | 'else' | 'afterEvent' | 'commit'>;
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 {
#private;
name: TStepId;
triggerSchema?: TTriggerSchema;
resultSchema?: TResultSchema;
resultMapping?: Record<string, {
step: StepAction<string, any, any, any>;
path: string;
}>;
events?: Record<string, {
schema: z.ZodObject<any>;
}>;
isNested: boolean;
/**
* Creates a new Workflow instance
* @param name - Identifier for the workflow (not necessarily unique)
* @param logger - Optional logger instance
*/
constructor({ name, triggerSchema, result, retryConfig, mastra, events, }: WorkflowOptions<TStepId, TSteps, TTriggerSchema, TResultSchema>);
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>;
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>;
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>;
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;
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;
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;
private loop;
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">;
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">;
if<TStep extends StepAction<string, any, any, any>>(condition: StepConfig<TStep, any, any, TTriggerSchema>['when'], ifStep?: TStep | Workflow, elseStep?: TStep | Workflow): this | WorkflowBuilder<this>;
else(): WorkflowBuilder<this>;
after<TStep extends StepAction<string, any, any, any>>(steps: string | TStep | TStep[] | (TStep | string)[]): Omit<WorkflowBuilder<this>, 'then' | 'after'>;
after<TWorkflow extends Workflow<any, any, any, any>>(steps: TWorkflow | TWorkflow[]): Omit<WorkflowBuilder<this>, 'then' | 'after'>;
after<TAgent extends Agent<any, any, any>>(steps: TAgent | TAgent[]): Omit<WorkflowBuilder<this>, 'then' | 'after'>;
afterEvent(eventName: string): WorkflowBuilder<this>;
/**
* Executes the workflow with the given trigger data
* @param triggerData - Initial data to start the workflow with
* @returns Promise resolving to workflow results or rejecting with error
* @throws Error if trigger schema validation fails
*/
createRun({ runId, events, }?: {
runId?: string;
events?: Record<string, {
schema: z.ZodObject<any>;
}>;
}): WorkflowResultReturn<TResultSchema, TTriggerSchema, TSteps>;
/**
* Gets a workflow run instance by ID
* @param runId - ID of the run to retrieve
* @returns The workflow run instance if found, undefined otherwise
*/
getRun(runId: string): WorkflowInstance<TSteps, TTriggerSchema, any> | undefined;
/**
* Rebuilds the machine with the current steps configuration and validates the workflow
*
* This is the last step of a workflow builder method chain
* @throws Error if validation fails
*
* @returns this instance for method chaining
*/
commit(): this;
getWorkflowRuns(): Promise<WorkflowRuns>;
getExecutionSpan(runId: string): Span | undefined;
getState(runId: string): Promise<WorkflowRunState | null>;
resume({ runId, stepId, context: resumeContext, runtimeContext, }: {
runId: string;
stepId: string;
context?: Record<string, any>;
runtimeContext: RuntimeContext;
}): Promise<Omit<WorkflowRunResult<TTriggerSchema, TSteps, any>, "runId"> | undefined>;
watch(onTransition: (state: Pick<WorkflowRunResult<TTriggerSchema, TSteps, TResultSchema>, 'results' | 'activePaths' | 'runId' | 'timestamp'>) => void): () => void;
resumeWithEvent(runId: string, eventName: string, data: any): Promise<Omit<WorkflowRunResult<TTriggerSchema, TSteps, any>, "runId"> | undefined>;
__registerMastra(mastra: Mastra): void;
__registerPrimitives(p: MastraPrimitives): void;
get stepGraph(): StepGraph;
get stepSubscriberGraph(): Record<string, StepGraph>;
get serializedStepGraph(): StepGraph;
get serializedS