import * as ai from 'ai';
import { Tool as Tool$1, Schema, 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-CeEVvwRi.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 { JSONSchema7Type, 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 | JSONSchema7Type | Schema;
    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(args?: {
        fromDate?: Date;
        toDate?: Date;
        limit?: number;
        offset?: number;
        resourceId?: string;
    }): 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 serializedStepSubscriberGraph(): Record<string, StepGraph>;
    get steps(): Record<string, StepAction<string, any, any, any>>;
    setNested(isNested: boolean): void;
    toStep(): Step<TStepId, TTriggerSchema, z.ZodType<WorkflowRunResult<TTriggerSchema, TSteps, TResultSchema>>, any>;
}

type ExecuteFunction<TStepInput, TStepOutput, TResumeSchema, TSuspendSchema> = (params: {
    mastra: Mastra;
    runtimeContext: RuntimeContext;
    inputData: TStepInput;
    resumeData?: TResumeSchema;
    getInitData<T extends NewWorkflow<any, any, any, any, any>>(): T extends undefined ? unknown : z.infer<NonNullable<T['inputSchema']>>;
    getStepResult<T extends NewStep<any, any, any>>(stepId: T): T['outputSchema'] extends undefined ? unknown : z.infer<NonNullable<T['outputSchema']>>;
    suspend(suspendPayload: TSuspendSchema): Promise<void>;
    resume?: {
        steps: string[];
        resumePayload: any;
    };
    emitter: {
        emit: (event: string, data: any) => Promise<void>;
    };
}) => Promise<TStepOutput>;
interface NewStep<TStepId extends string = string, TSchemaIn extends z.ZodType<any> = z.ZodType<any>, TSchemaOut extends z.ZodType<any> = z.ZodType<any>, TResumeSchema extends z.ZodType<any> = z.ZodType<any>, TSuspendSchema extends z.ZodType<any> = z.ZodType<any>> {
    id: TStepId;
    description?: string;
    inputSchema: TSchemaIn;
    outputSchema: TSchemaOut;
    resumeSchema?: TResumeSchema;
    suspendSchema?: TSuspendSchema;
    execute: ExecuteFunction<z.infer<TSchemaIn>, z.infer<TSchemaOut>, z.infer<TResumeSchema>, z.infer<TSuspendSchema>>;
    retries?: number;
}

type StepSuccess<T> = {
    status: 'success';
    output: T;
};
type StepFailure = {
    status: 'failed';
    error: string | Error;
};
type StepSuspended<T> = {
    status: 'suspended';
    payload: T;
};
type StepResult<T> = StepSuccess<T> | StepFailure | StepSuspended<T>;
type StepsRecord<T extends readonly NewStep<any, any, any>[]> = {
    [K in T[number]['id']]: Extract<T[number], {
        id: K;
    }>;
};
type DynamicMapping<TPrevSchema extends z.ZodTypeAny, TSchemaOut extends z.ZodTypeAny> = {
    fn: ExecuteFunction<z.infer<TPrevSchema>, z.infer<TSchemaOut>, any, any>;
    schema: TSchemaOut;
};
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;
type ExtractSchemaType<T extends z.ZodType<any>> = T extends z.ZodObject<infer V> ? V : never;
type ExtractSchemaFromStep<TStep extends NewStep<any, any, any>, TKey extends 'inputSchema' | 'outputSchema'> = TStep[TKey];
type VariableReference<TStep extends NewStep<string, any, any> = NewStep<string, any, any>, TVarPath extends PathsToStringProps<ExtractSchemaType<ExtractSchemaFromStep<TStep, 'outputSchema'>>> | '' | '.' = PathsToStringProps<ExtractSchemaType<ExtractSchemaFromStep<TStep, 'outputSchema'>>> | '' | '.'> = {
    step: TStep;
    path: TVarPath;
} | {
    value: any;
    schema: z.ZodTypeAny;
};
type WatchEvent = {
    type: 'watch';
    payload: {
        currentStep?: {
            id: string;
            status: 'running' | 'success' | 'failed' | 'suspended';
            output?: Record<string, any>;
            payload?: Record<string, any>;
        };
        workflowState: {
            status: 'running' | 'success' | 'failed' | 'suspended';
            steps: Record<string, {
                status: 'running' | 'success' | 'failed' | 'suspended';
                output?: Record<string, any>;
                payload?: Record<string, any>;
            }>;
            output?: Record<string, any>;
            payload?: Record<string, any>;
        };
    };
    eventTimestamp: Date;
};
type ZodPathType<T extends z.ZodTypeAny, P extends string> = T extends z.ZodObject<infer Shape> ? P extends `${infer Key}.${infer Rest}` ? Key extends keyof Shape ? Shape[Key] extends z.ZodTypeAny ? ZodPathType<Shape[Key], Rest> : never : never : P extends keyof Shape ? Shape[P] : never : never;

/**
 * Represents an execution graph for a workflow
 */
interface ExecutionGraph {
    id: string;
    steps: StepFlowEntry[];
}
/**
 * Execution engine abstract class for building and executing workflow graphs
 * Providers will implement this class to provide their own execution logic
 */
declare abstract class ExecutionEngine extends MastraBase {
    protected mastra?: Mastra;
    constructor({ mastra }: {
        mastra?: Mastra;
    });
    __registerMastra(mastra: Mastra): void;
    /**
     * Executes a workflow run with the provided execution graph and input
     * @param graph The execution graph to execute
     * @param input The input data for the workflow
     * @returns A promise that resolves to the workflow output
     */
    abstract execute<TInput, TOutput>(params: {
        workflowId: string;
        runId: string;
        graph: ExecutionGraph;
        input?: TInput;
        resume?: {
            steps: string[];
            stepResults: Record<string, StepResult<any>>;
            resumePayload: any;
            resumePath: number[];
        };
        emitter: {
            emit: (event: string, data: any) => Promise<void>;
        };
        runtimeContext: RuntimeContext;
        retryConfig?: {
            attempts?: number;
            delay?: number;
        };
    }): Promise<TOutput>;
}

type StepFlowEntry = {
    type: 'step';
    step: NewStep;
} | {
    type: 'parallel';
    steps: StepFlowEntry[];
} | {
    type: 'conditional';
    steps: StepFlowEntry[];
    conditions: ExecuteFunction<any, any, any, any>[];
    serializedConditions: {
        id: string;
        fn: string;
    }[];
} | {
    type: 'loop';
    step: NewStep;
    condition: ExecuteFunction<any, any, any, any>;
    serializedCondition: {
        id: string;
        fn: string;
    };
    loopType: 'dowhile' | 'dountil';
} | {
    type: 'foreach';
    step: NewStep;
    opts: {
        concurrency: number;
    };
};
type SerializedStep = Pick<NewStep, 'id' | 'description'> & {
    component?: string;
    serializedStepFlow?: SerializedStepFlowEntry[];
};
type SerializedStepFlowEntry = {
    type: 'step';
    step: SerializedStep;
} | {
    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;
    };
};
/**
 * 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
 */
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: {
    id: TStepId;
    description?: string;
    inputSchema: TStepInput;
    outputSchema: TStepOutput;
    resumeSchema?: TResumeSchema;
    suspendSchema?: TSuspendSchema;
    execute: ExecuteFunction<z.infer<TStepInput>, z.infer<TStepOutput>, z.infer<TResumeSchema>, z.infer<TSuspendSchema>>;
}): NewStep<TStepId, TStepInput, TStepOutput, TResumeSchema, TSuspendSchema>;
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>): NewStep<TStepId, TStepInput, TStepOutput, TResumeSchema, TSuspendSchema>;
declare function createStep<TSchemaIn extends z.ZodType<any>, TSchemaOut extends z.ZodType<any>, TContext extends ToolExecutionContext<TSchemaIn>>(tool: Tool<TSchemaIn, TSchemaOut, TContext> & {
    inputSchema: TSchemaIn;
    outputSchema: TSchemaOut;
    execute: (context: TContext) => Promise<any>;
}): NewStep<string, TSchemaIn, TSchemaOut, z.ZodType<any>, z.ZodType<any>>;
declare function cloneStep<TStepId extends string>(step: NewStep<string, any, any>, opts: {
    id: TStepId;
}): NewStep<TStepId, any, any>;
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 NewStep<string, any, any, any, any>[] = NewStep<string, any, any, any, any>[]>(params: NewWorkflowConfig<TWorkflowId, TInput, TOutput, TSteps>): NewWorkflow<TSteps, TWorkflowId, TInput, TOutput, TInput>;
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 NewStep<string, any, any, any, any>[] = NewStep<string, any, any, any, any>[]>(workflow: NewWorkflow<TSteps, string, TInput, TOutput>, opts: {
    id: TWorkflowId;
}): NewWorkflow<TSteps, TWorkflowId, TInput, TOutput>;
type WorkflowResult<TOutput extends z.ZodType<any>, TSteps extends NewStep<string, any, any>[]> = {
    status: 'success';
    result: z.infer<TOutput>;
    steps: {
        [K in keyof StepsRecord<TSteps>]: StepsRecord<TSteps>[K]['outputSchema'] extends undefined ? StepResult<unknown> : StepResult<z.infer<NonNullable<StepsRecord<TSteps>[K]['outputSchema']>>>;
    };
} | {
    status: 'failed';
    steps: {
        [K in keyof StepsRecord<TSteps>]: StepsRecord<TSteps>[K]['outputSchema'] extends undefined ? StepResult<unknown> : StepResult<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> : StepResult<z.infer<NonNullable<StepsRecord<TSteps>[K]['outputSchema']>>>;
    };
    suspended: [string[], ...string[][]];
};
type NewWorkflowConfig<TWorkflowId extends string = string, TInput extends z.ZodType<any> = z.ZodType<any>, TOutput extends z.ZodType<any> = z.ZodType<any>, TSteps extends NewStep<string, any, any, any, any>[] = NewStep<string, any, any, any, any>[]> = {
    mastra?: Mastra;
    id: TWorkflowId;
    description?: string | undefined;
    inputSchema: TInput;
    outputSchema: TOutput;
    executionEngine?: ExecutionEngine;
    steps?: TSteps;
    retryConfig?: {
        attempts?: number;
        delay?: number;
    };
};
declare class NewWorkflow<TSteps extends NewStep<string, any, any, any, any>[] = NewStep<string, any, any, any, any>[], 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 NewStep<TWorkflowId, TInput, TOutput> {
    #private;
    id: TWorkflowId;
    description?: string | undefined;
    inputSchema: TInput;
    outputSchema: TOutput;
    steps: Record<string, NewStep<string, any, any, any, any>>;
    stepDefs?: TSteps;
    protected stepFlow: StepFlowEntry[];
    protected serializedStepFlow: SerializedStepFlowEntry[];
    protected executionEngine: ExecutionEngine;
    protected executionGraph: ExecutionGraph;
    protected retryConfig: {
        attempts?: number;
        delay?: number;
    };
    constructor({ mastra, id, inputSchema, outputSchema, description, executionEngine, retryConfig, steps, }: NewWorkflowConfig<TWorkflowId, TInput, TOutput, TSteps>);
    get runs(): Map<string, Run<TSteps, TInput, TOutput>>;
    get mastra(): Mastra<Record<string, Agent<any, ToolsInput, Record<string, Metric>>>, Record<string, Workflow<Step<string, any, any, StepExecutionContext<any, WorkflowContext<any, Step<string, any, any, any>[], Record<string, any>>>>[], string, any, any>>, Record<string, NewWorkflow<NewStep<string, any, any, any, any>[], string, z.ZodType<any, z.ZodTypeDef, any>, z.ZodType<any, z.ZodTypeDef, any>, z.ZodType<any, z.ZodTypeDef, any>>>, Record<string, MastraVector>, Record<string, MastraTTS>, Logger, Record<string, AgentNetwork>> | undefined;
    __registerMastra(mastra: Mastra): void;
    __registerPrimitives(p: MastraPrimitives): void;
    setStepFlow(stepFlow: StepFlowEntry[]): 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: NewStep<TStepId, TStepInputSchema, TSchemaOut, any, any>): NewWorkflow<TSteps, TWorkflowId, TInput, TOutput, TSchemaOut>;
    map<TSteps extends NewStep<string, any, any>[], TMapping extends {
        [K in keyof TMapping]: {
            step: TSteps[number] | TSteps[number][];
            path: PathsToStringProps<ExtractSchemaType<ExtractSchemaFromStep<TSteps[number], 'outputSchema'>>> | '.';
        } | {
            value: any;
            schema: z.ZodTypeAny;
        } | {
            initData: TSteps[number];
            path: PathsToStringProps<ExtractSchemaType<ExtractSchemaFromStep<TSteps[number], 'inputSchema'>>> | '.';
        } | {
            runtimeContextPath: string;
            schema: z.ZodTypeAny;
        } | DynamicMapping<TPrevSchema, z.ZodTypeAny>;
    }>(mappingConfig: TMapping | ExecuteFunction<z.infer<TPrevSchema>, any, any, any>): NewWorkflow<TSteps, TWorkflowId, TInput, TOutput, any>;
    parallel<TParallelSteps extends NewStep<string, TPrevSchema, any, any, any>[]>(steps: TParallelSteps): NewWorkflow<TSteps, TWorkflowId, TInput, TOutput, z.ZodObject<{ [K in keyof StepsRecord<TParallelSteps>]: StepsRecord<TParallelSteps>[K]["outputSchema"]["path"]; }, any, z.ZodTypeAny>>;
    branch<TBranchSteps extends Array<[
        ExecuteFunction<z.infer<TPrevSchema>, any, any, any>,
        NewStep<string, TPrevSchema, any, any, any>
    ]>>(steps: TBranchSteps): NewWorkflow<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: NewStep<TStepId, TStepInputSchema, TSchemaOut, any, any>, condition: ExecuteFunction<z.infer<TSchemaOut>, any, any, any>): NewWorkflow<TSteps, TWorkflowId, TInput, TOutput, TSchemaOut>;
    dountil<TStepInputSchema extends TPrevSchema, TStepId extends string, TSchemaOut extends z.ZodType<any>>(step: NewStep<TStepId, TStepInputSchema, TSchemaOut, any, any>, condition: ExecuteFunction<z.infer<TSchemaOut>, any, any, any>): NewWorkflow<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 ? NewStep<TStepId, TStepInputSchema, TSchemaOut, any, any> : 'Previous step must return an array type', opts?: {
        concurrency: number;
    }): NewWorkflow<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(): NewWorkflow<TSteps, TWorkflowId, TInput, TOutput, TOutput>;
    get stepGraph(): StepFlowEntry[];
    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<TSteps, TInput, TOutput>;
    execute({ inputData, resumeData, suspend, resume, emitter, mastra, }: {
        inputData: z.infer<TInput>;
        resumeData?: any;
        getStepResult<T extends NewStep<any, any, any>>(stepId: T): T['outputSchema'] extends undefined ? unknown : z.infer<NonNullable<T['outputSchema']>>;
        suspend: (suspendPayload: any) => Promise<void>;
        resume?: {
            steps: string[];
            resumePayload: any;
            runId?: string;
        };
        emitter: {
            emit: (event: string, data: any) => void;
        };
        mastra: Mastra;
    }): Promise<z.infer<TOutput>>;
    getWorkflowRuns(args?: {
        fromDate?: Date;
        toDate?: Date;
        limit?: number;
        offset?: number;
        resourceId?: string;
    }): Promise<WorkflowRuns>;
    getWorkflowRunById(runId: string): Promise<WorkflowRun | null>;
}
/**
 * Represents a workflow run that can be executed
 */
declare class Run<TSteps extends NewStep<string, any, any>[] = NewStep<string, any, any>[], TInput extends z.ZodType<any> = z.ZodType<any>, TOutput extends z.ZodType<any> = z.ZodType<any>> {
    #private;
    protected emitter: EventEmitter$1;
    /**
     * 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;
    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;
    });
    /**
     * 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, }: {
        inputData?: z.infer<TInput>;
        runtimeContext?: RuntimeContext;
    }): Promise<WorkflowResult<TOutput, TSteps>>;
    watch(cb: (event: WatchEvent) => void): () => void;
    resume<TResumeSchema extends z.ZodType<any>>(params: {
        resumeData?: z.infer<TResumeSchema>;
        step: NewStep<string, any, any, TResumeSchema, any> | [...NewStep<string, any, any, any, any>[], NewStep<string, any, any, TResumeSchema, any>] | string | string[];
        runtimeContext?: RuntimeContext;
    }): 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;
}

type MemoryProcessorOpts = {
    systemMessage?: string;
    memorySystemMessage?: string;
    newMessages?: CoreMessage$1[];
};
/**
 * Interface for message processors that can filter or transform messages
 * before they're sent to the LLM.
 */
declare abstract class MemoryProcessor extends MastraBase {
    /**
     * Process a list of messages and return a filtered or transformed list.
     * @param messages The messages to process
     * @returns The processed messages
     */
    process(messages: CoreMessage$1[], _opts: MemoryProcessorOpts): CoreMessage$1[];
}
declare const memoryDefaultOptions: {
    lastMessages: number;
    semanticRecall: {
        topK: number;
        messageRange: {
            before: number;
            after: number;
        };
    };
    threads: {
        generateTitle: true;
    };
    workingMemory: {
        use: "text-stream";
        enabled: false;
        template: string;
    };
};
/**
 * 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>;
    private processors;
    private deprecationWarnings;
    protected threadConfig: MemoryConfig;
    constructor(config: {
        name: string;
    } & SharedMemoryConfig);
    private addImplicitDefaultsWarning;
    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(dimensions?: number): Promise<{
        indexName: string;
    }>;
    getMergedThreadConfig(config?: MemoryConfig): MemoryConfig;
    /**
     * Apply all configured message processors to a list of messages.
     * @param messages The messages to process
     * @returns The processed messages
     */
    private applyProcessors;
    processMessages({ messages, processors, ...opts }: {
        messages: CoreMessage$1[];
        processors?: MemoryProcessor[];
    } & MemoryProcessorOpts): CoreMessage$1[];
    abstract rememberMessages({ threadId, resourceId, vectorMessageSearch, systemMessage, config, }: {
        threadId: string;
        resourceId?: string;
        vectorMessageSearch?: string;
        systemMessage?: CoreMessage$1;
        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, resourceId, config, content, role, type, toolNames, toolCallArgs, toolCallIds, }: {
        threadId: string;
        resourceId: 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;
}

declare class MastraLLMBase extends MastraBase {
    #private;
    constructor({ name, model }: {
        name: string;
        model: LanguageModel$1;
    });
    getProvider(): string;
    getModelId(): string;
    getModel(): ai.LanguageModelV1;
    convertToMessages(messages: string | string[] | CoreMessage$1[]): CoreMessage$1[];
    __registerPrimitives(p: MastraPrimitives): void;
    __registerMastra(p: Mastra): void;
    __text<Z extends ZodSchema | JSONSchema7 | undefined>(input: LLMTextOptions<Z>): Promise<GenerateTextResult<any, any>>;
    __textObject<T extends ZodSchema | JSONSchema7 | undefined>(input: LLMTextObjectOptions<T>): Promise<GenerateObjectResult<T>>;
    generate<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[], options: LLMStreamOptions<Z>): Promise<GenerateReturn<Z>>;
    __stream<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(input: LLMInnerStreamOptions<Z>): Promise<StreamTextResult<any, any>>;
    __streamObject<T extends ZodSchema | JSONSchema7 | undefined>(input: LLMStreamObjectOptions<T>): Promise<StreamObjectResult<DeepPartial<T>, T, never>>;
    stream<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[], options: LLMStreamOptions<Z>): Promise<StreamReturn<Z>>;
}

declare function createMockModel({ objectGenerationMode, mockText, spyGenerate, spyStream, }: {
    objectGenerationMode?: 'json';
    mockText: string | Record<string, any>;
    spyGenerate?: (props: any) => void;
    spyStream?: (props: any) => void;
}): MockLanguageModelV1;

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?: Record<string, CoreTool>;
    onStepFinish?: (step: unknown) => void;
    experimental_output?: Z;
    telemetry?: TelemetrySettings;
    threadId?: string;
    resourceId?: string;
    runtimeContext: RuntimeContext;
} & Run$1;
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;

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({ input, output, realtime, speakProvider, listenProvider, realtimeProvider, }: {
        /** @deprecated use output instead */
        speakProvider?: MastraVoice;
        /** @deprecated use input instead */
        listenProvider?: MastraVoice;
        /** @deprecated use realtime instead */
        realtimeProvider?: MastraVoice;
        input?: MastraVoice;
        output?: MastraVoice;
        realtime?: 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;
}

declare class DefaultVoice extends MastraVoice {
    constructor();
    speak(_input: string | NodeJS.ReadableStream): Promise<NodeJS.ReadableStream>;
    listen(_input: string | NodeJS.ReadableStream): Promise<string>;
    getSpeakers(): Promise<{
        voiceId: string;
    }[]>;
}

type ToolsInput = Record<string, ToolAction<any, any, any> | VercelTool>;
type ToolsetsInput = Record<string, ToolsInput>;
type MastraLanguageModel = LanguageModelV1;
type DynamicArgument<T> = T | (({ runtimeContext }: {
    runtimeContext: RuntimeContext;
}) => Promise<T> | T);
interface AgentConfig<TAgentId extends string = string, TTools extends ToolsInput = ToolsInput, TMetrics extends Record<string, Metric> = Record<string, Metric>> {
    name: TAgentId;
    instructions: DynamicArgument<string>;
    model: DynamicArgument<MastraLanguageModel>;
    tools?: DynamicArgument<TTools>;
    defaultGenerateOptions?: AgentGenerateOptions;
    defaultStreamOptions?: AgentStreamOptions;
    mastra?: Mastra;
    evals?: TMetrics;
    memory?: MastraMemory;
    voice?: CompositeVoice;
    /** @deprecated This property is deprecated. Use evals instead to add evaluation metrics. */
    metrics?: TMetrics;
}
/**
 * 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;
    clientTools?: ToolsInput;
    /** 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;
    /** RuntimeContext for dependency injection */
    runtimeContext?: RuntimeContext;
} & ({
    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;
    clientTools?: ToolsInput;
    /** 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;
    /** RuntimeContext for dependency injection */
    runtimeContext?: RuntimeContext;
} & ({
    resourceId?: undefined;
    threadId?: undefined;
} | {
    resourceId: string;
    threadId: string;
}) & (Z extends undefined ? DefaultLLMStreamOptions : DefaultLLMStreamObjectOptions);

type Methods = 'GET' | 'POST' | 'PUT' | 'DELETE' | 'ALL';
type ApiRoute = {
    path: string;
    method: Methods;
    handler: Handler;
    middleware?: MiddlewareHandler | MiddlewareHandler[];
    openapi?: DescribeRouteOptions;
} | {
    path: string;
    method: Methods;
    createHandler: ({ mastra }: {
        mastra: Mastra;
    }) => Promise<Handler>;
    middleware?: MiddlewareHandler | MiddlewareHandler[];
    openapi?: DescribeRouteOptions;
};
type Middleware = MiddlewareHandler | {
    path: string;
    handler: MiddlewareHandler;
};
type ServerConfig = {
    /**
     * Port for the server
     * @default 4111
     */
    port?: number;
    /**
     * Host for the server
     * @default 'localhost'
     */
    host?: string;
    /**
     * Timeout for the server
     */
    timeout?: number;
    /**
     * Custom API routes for the server
     */
    apiRoutes?: ApiRoute[];
    /**
     * Middleware for the server
     */
    middleware?: Middleware | Middleware[];
    /**
     * CORS configuration for the server
     * @default { origin: '*', allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], allowHeaders: ['Content-Type', 'Authorization', 'x-mastra-client-type'], exposeHeaders: ['Content-Length', 'X-Requested-With'], credentials: false }
     */
    cors?: Parameters<typeof cors>[0] | false;
    /**
     * Build configuration for the server
     */
    build?: {
        /**
         * Enable Swagger UI
         * @default false
         */
        swaggerUI?: boolean;
        /**
         * Enable API request logging
         * @default false
         */
        apiReqLogs?: boolean;
        /**
         * Enable OpenAPI documentation
         * @default false
         */
        openAPIDocs?: boolean;
    };
    /**
     * Body size limit for the server
     * @default 4.5mb
     */
    bodySizeLimit?: number;
};

interface Config<TAgents extends Record<string, Agent<any>> = Record<string, Agent<any>>, TWorkflows extends Record<string, Workflow> = Record<string, Workflow>, TNewWorkflows extends Record<string, NewWorkflow> = Record<string, NewWorkflow>, TVectors extends Record<string, MastraVector> = Record<string, MastraVector>, TTTS extends Record<string, MastraTTS> = Record<string, MastraTTS>, TLogger extends Logger = Logger, TNetworks extends Record<string, AgentNetwork> = Record<string, AgentNetwork>> {
    agents?: TAgents;
    networks?: TNetworks;
    storage?: MastraStorage;
    vectors?: TVectors;
    logger?: TLogger | false;
    workflows?: TWorkflows;
    vnext_workflows?: TNewWorkflows;
    tts?: TTTS;
    telemetry?: OtelConfig;
    deployer?: MastraDeployer;
    server?: ServerConfig;
    /**
     * Server middleware functions to be applied to API routes
     * Each middleware can specify a path pattern (defaults to '/api/*')
     * @deprecated use server.middleware instead
     */
    serverMiddleware?: Array<{
        handler: (c: any, next: () => Promise<void>) => Promise<Response | void>;
        path?: string;
    }>;
    memory?: MastraMemory;
}
declare class Mastra<TAgents extends Record<string, Agent<any>> = Record<string, Agent<any>>, TWorkflows extends Record<string, Workflow> = Record<string, Workflow>, TNewWorkflows extends Record<string, NewWorkflow> = Record<string, NewWorkflow>, TVectors extends Record<string, MastraVector> = Record<string, MastraVector>, TTTS extends Record<string, MastraTTS> = Record<string, MastraTTS>, TLogger extends Logger = Logger, TNetworks extends Record<string, AgentNetwork> = Record<string, AgentNetwork>> {
    #private;
    /**
     * @deprecated use getTelemetry() instead
     */
    get telemetry(): Telemetry | undefined;
    /**
     * @deprecated use getStorage() instead
     */
    get storage(): MastraStorage | undefined;
    /**
     * @deprecated use getMemory() instead
     */
    get memory(): MastraMemory | undefined;
    constructor(config?: Config<TAgents, TWorkflows, TNewWorkflows, TVectors, TTTS, TLogger>);
    getAgent<TAgentName extends keyof TAgents>(name: TAgentName): TAgents[TAgentName];
    getAgents(): TAgents;
    getVector<TVectorName extends keyof TVectors>(name: TVectorName): TVectors[TVectorName];
    getVectors(): TVectors | undefined;
    getDeployer(): MastraDeployer | undefined;
    getWorkflow<TWorkflowId extends keyof TWorkflows>(id: TWorkflowId, { serialized }?: {
        serialized?: boolean;
    }): TWorkflows[TWorkflowId];
    vnext_getWorkflow<TWorkflowId extends keyof TNewWorkflows>(id: TWorkflowId, { serialized }?: {
        serialized?: boolean;
    }): TNewWorkflows[TWorkflowId];
    getWorkflows(props?: {
        serialized?: boolean;
    }): Record<string, Workflow>;
    vnext_getWorkflows(props?: {
        serialized?: boolean;
    }): Record<string, NewWorkflow>;
    setStorage(storage: MastraStorage): void;
    setLogger({ logger }: {
        logger: TLogger;
    }): void;
    setTelemetry(telemetry: OtelConfig): void;
    getTTS(): TTTS | undefined;
    getLogger(): TLogger;
    getTelemetry(): Telemetry | undefined;
    getMemory(): MastraMemory | undefined;
    getStorage(): MastraStorage | undefined;
    getServerMiddleware(): {
        handler: (c: any, next: () => Promise<void>) => Promise<Response | void>;
        path: string;
    }[];
    getNetworks(): AgentNetwork[];
    getServer(): ServerConfig | undefined;
    /**
     * Get a specific network by ID
     * @param networkId - The ID of the network to retrieve
     * @returns The network with the specified ID, or undefined if not found
     */
    getNetwork(networkId: string): AgentNetwork | undefined;
    getLogsByRunId({ runId, transportId }: {
        runId: string;
        transportId: string;
    }): Promise<BaseLogMessage[] | undefined>;
    getLogs(transportId: string): Promise<BaseLogMessage[]>;
}

type MastraPrimitives = {
    logger?: Logger;
    telemetry?: Telemetry;
    storage?: MastraStorage;
    agents?: Record<string, Agent>;
    tts?: Record<string, MastraTTS>;
    vectors?: Record<string, MastraVector>;
    memory?: MastraMemory;
};
type MastraUnion = {
    [K in keyof Mastra]: Mastra[K];
} & MastraPrimitives;
interface IExecutionContext<TSchemaIn extends z.ZodSchema | undefined = undefined> {
    context: TSchemaIn extends z.ZodSchema ? z.infer<TSchemaIn> : {};
    runId?: string;
    threadId?: string;
    resourceId?: string;
}
interface IAction<TId extends string, TSchemaIn extends z.ZodSchema | undefined, TSchemaOut extends z.ZodSchema | undefined, TContext extends IExecutionContext<TSchemaIn>, TOptions extends unknown = unknown> {
    id: TId;
    description?: string;
    inputSchema?: TSchemaIn;
    outputSchema?: TSchemaOut;
    execute?: (context: TContext, options?: TOptions) => Promise<TSchemaOut extends z.ZodSchema ? z.infer<TSchemaOut> : unknown>;
}

declare class Agent<TAgentId extends string = string, TTools extends ToolsInput = ToolsInput, TMetrics extends Record<string, Metric> = Record<string, Metric>> extends MastraBase {
    #private;
    id: TAgentId;
    name: TAgentId;
    readonly model?: DynamicArgument<MastraLanguageModel>;
    /** @deprecated This property is deprecated. Use evals instead. */
    metrics: TMetrics;
    evals: TMetrics;
    constructor(config: AgentConfig<TAgentId, TTools, TMetrics>);
    hasOwnMemory(): boolean;
    getMemory(): MastraMemory | undefined;
    get voice(): CompositeVoice;
    getVoice({ runtimeContext }?: {
        runtimeContext?: RuntimeContext;
    }): Promise<CompositeVoice | DefaultVoice>;
    get instructions(): string;
    getInstructions({ runtimeContext }?: {
        runtimeContext?: RuntimeContext;
    }): string | Promise<string>;
    get tools(): TTools;
    getTools({ runtimeContext }?: {
        runtimeContext?: RuntimeContext;
    }): TTools | Promise<TTools>;
    get llm(): MastraLLMBase | Promise<MastraLLMBase>;
    /**
     * Gets or creates an LLM instance based on the current model
     * @param options Options for getting the LLM
     * @returns A promise that resolves to the LLM instance
     */
    getLLM({ runtimeContext }?: {
        runtimeContext?: RuntimeContext;
    }): MastraLLMBase | Promise<MastraLLMBase>;
    /**
     * Gets the model, resolving it if it's a function
     * @param options Options for getting the model
     * @returns A promise that resolves to the model
     */
    getModel({ runtimeContext }?: {
        runtimeContext?: RuntimeContext;
    }): MastraLanguageModel | Promise<MastraLanguageModel>;
    __updateInstructions(newInstructions: string): void;
    __registerPrimitives(p: MastraPrimitives): void;
    __registerMastra(mastra: Mastra): void;
    /**
     * Set the concrete tools for the agent
     * @param tools
     */
    __setTools(tools: TTools): void;
    generateTitleFromUserMessage({ message, runtimeContext, }: {
        message: CoreUserMessage$1;
        runtimeContext?: RuntimeContext;
    }): Promise<string>;
    getMostRecentUserMessage(messages: Array<CoreMessage$1>): CoreUserMessage$1 | undefined;
    genTitle(userMessage: CoreUserMessage$1 | undefined): Promise<string>;
    fetchMemory({ threadId, thread: passedThread, memoryConfig, resourceId, userMessages, systemMessage, runId, }: {
        resourceId: string;
        threadId: string;
        thread?: StorageThreadType;
        memoryConfig?: MemoryConfig;
        userMessages: CoreMessage$1[];
        systemMessage: CoreMessage$1;
        time?: Date;
        keyword?: string;
        runId?: string;
    }): Promise<{
        threadId: string;
        messages: CoreMessage$1[];
    }>;
    private getResponseMessages;
    sanitizeResponseMessages(messages: Array<CoreMessage$1>): Array<CoreMessage$1>;
    private convertTools;
    preExecute({ resourceId, runId, threadId, thread, memoryConfig, messages, systemMessage, }: {
        runId?: string;
        threadId: string;
        thread?: StorageThreadType;
        memoryConfig?: MemoryConfig;
        messages: CoreMessage$1[];
        resourceId: string;
        systemMessage: CoreMessage$1;
    }): Promise<{
        coreMessages: CoreMessage$1[];
        threadIdToUse: string;
    }>;
    __primitive({ instructions, messages, context, threadId, memoryConfig, resourceId, runId, toolsets, clientTools, runtimeContext, }: {
        instructions?: string;
        toolsets?: ToolsetsInput;
        clientTools?: ToolsInput;
        resourceId?: string;
        threadId?: string;
        memoryConfig?: MemoryConfig;
        context?: CoreMessage$1[];
        runId?: string;
        messages: CoreMessage$1[];
        runtimeContext: RuntimeContext;
    }): {
        before: () => Promise<{
            messageObjects: CoreMessage$1[];
            convertedTools: Record<string, CoreTool>;
            threadId: string;
            thread: StorageThreadType | null | undefined;
        }>;
        after: ({ result, thread: threadAfter, threadId, memoryConfig, outputText, runId, }: {
            runId: string;
            result: Record<string, any>;
            thread: StorageThreadType | null | undefined;
            threadId: string;
            memoryConfig: MemoryConfig | undefined;
            outputText: string;
        }) => Promise<void>;
    };
    generate<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[] | Message[], 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[] | Message[], args?: AgentGenerateOptions<Z> & {
        output?: Z;
        experimental_output?: never;
    }): Promise<GenerateObjectResult<Z extends ZodSchema ? z.infer<Z> : unknown>>;
    generate<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[] | Message[], args?: AgentGenerateOptions<Z> & {
        output?: never;
        experimental_output?: Z;
    }): Promise<GenerateTextResult<any, Z extends ZodSchema ? z.infer<Z> : unknown> & {
        object: Z extends ZodSchema ? z.infer<Z> : unknown;
    }>;
    stream<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[] | Message[], 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[] | Message[], args?: AgentStreamOptions<Z> & {
        output?: Z;
        experimental_output?: never;
    }): Promise<StreamObjectResult<any, Z extends ZodSchema ? z.infer<Z> : unknown, any>>;
    stream<Z extends ZodSchema | JSONSchema7 | undefined = undefined>(messages: string | string[] | CoreMessage$1[] | Message[], args?: AgentStreamOptions<Z> & {
        output?: never;
        experimental_output?: Z;
    }): Promise<StreamTextResult<any, Z extends ZodSchema ? z.infer<Z> : unknown> & {
        partialObjectStream: StreamTextResult<any, Z extends ZodSchema ? z.infer<Z> : unknown>['experimental_partialOutputStream'];
    }>;
    /**
     * Convert text to speech using the configured voice provider
     * @param input Text or text stream to convert to speech
     * @param options Speech options including speaker and provider-specific options
     * @returns Audio stream
     * @deprecated Use agent.voice.speak() instead
     */
    speak(input: string | NodeJS.ReadableStream, options?: {
        speaker?: string;
        [key: string]: any;
    }): Promise<NodeJS.ReadableStream | void>;
    /**
     * Convert speech to text using the configured voice provider
     * @param audioStream Audio stream to transcribe
     * @param options Provider-specific transcription options
     * @returns Text or text stream
     * @deprecated Use agent.voice.listen() instead
     */
    listen(audioStream: NodeJS.ReadableStream, options?: {
        [key: string]: any;
    }): Promise<string | NodeJS.ReadableStream | void>;
    /**
     * Get a list of available speakers from the configured voice provider
     * @throws {Error} If no voice provider is configured
     * @returns {Promise<Array<{voiceId: string}>>} List of available speakers
     * @deprecated Use agent.voice.getSpeakers() instead
     */
    getSpeakers(): Promise<{
        voiceId: string;
    }[]>;
    toStep(): Step<TAgentId, z.ZodObject<{
        prompt: z.ZodString;
    }>, z.ZodObject<{
        text: z.ZodString;
    }>, any>;
}

interface StorageColumn {
    type: 'text' | 'timestamp' | 'uuid' | 'jsonb' | 'integer' | 'bigint';
    primaryKey?: boolean;
    nullable?: boolean;
    references?: {
        table: string;
        column: string;
    };
}
interface WorkflowRuns {
    runs: WorkflowRun[];
    total: number;
}
interface WorkflowRun {
    workflowName: string;
    runId: string;
    snapshot: WorkflowRunState | string;
    createdAt: Date;
    updatedAt: Date;
    resourceId?: string;
}
type StorageGetMessagesArg = {
    threadId: string;
    resourceId?: string;
    selectBy?: {
        vectorSearchString?: string;
        last?: number | false;
        include?: {
            id: string;
            withPreviousMessages?: number;
            withNextMessages?: number;
        }[];
    };
    threadConfig?: MemoryConfig;
};
type EvalRow = {
    input: string;
    output: string;
    result: MetricResult;
    agentName: string;
    createdAt: string;
    metricName: string;
    instructions: string;
    runId: string;
    globalRunId: string;
    testInfo?: TestInfo;
};

declare const TABLE_WORKFLOW_SNAPSHOT = "mastra_workflow_snapshot";
declare const TABLE_EVALS = "mastra_evals";
declare const TABLE_MESSAGES = "mastra_messages";
declare const TABLE_THREADS = "mastra_threads";
declare const TABLE_TRACES = "mastra_traces";
type TABLE_NAMES = typeof TABLE_WORKFLOW_SNAPSHOT | typeof TABLE_EVALS | typeof TABLE_MESSAGES | typeof TABLE_THREADS | typeof TABLE_TRACES;
declare const TABLE_SCHEMAS: Record<TABLE_NAMES, Record<string, StorageColumn>>;

type MessageType = {
    id: string;
    content: UserContent | AssistantContent | ToolContent;
    role: 'system' | 'user' | 'assistant' | 'tool';
    createdAt: Date;
    threadId: string;
    resourceId: string;
    toolCallIds?: string[];
    toolCallArgs?: Record<string, unknown>[];
    toolNames?: string[];
    type: 'text' | 'tool-call' | 'tool-result';
};
type StorageThreadType = {
    id: string;
    title?: string;
    resourceId: string;
    createdAt: Date;
    updatedAt: Date;
    metadata?: Record<string, unknown>;
};
type MessageResponse<T extends 'raw' | 'core_message'> = {
    raw: MessageType[];
    core_message: CoreMessage$1[];
}[T];
type MemoryConfig = {
    lastMessages?: number | false;
    semanticRecall?: boolean | {
        topK: number;
        messageRange: number | {
            before: number;
            after: number;
        };
    };
    workingMemory?: {
        enabled: boolean;
        template?: string;
        use: 'tool-call';
    } | {
        enabled: boolean;
        template?: string;
        /** @deprecated the 'text-stream' working memory option (which is the current default) will be full removed in favor of the 'tool-call' option in a future breaking change. */
        use?: 'text-stream';
    };
    threads?: {
        generateTitle?: boolean;
    };
};
type SharedMemoryConfig = {
    storage?: MastraStorage;
    options?: MemoryConfig;
    vector?: MastraVector | false;
    embedder?: EmbeddingModel<string>;
    processors?: MemoryProcessor[];
};

declare abstract class MastraStorage extends MastraBase {
    /** @deprecated import from { TABLE_WORKFLOW_SNAPSHOT } '@mastra/core/storage' instead */
    static readonly TABLE_WORKFLOW_SNAPSHOT = "mastra_workflow_snapshot";
    /** @deprecated import from { TABLE_EVALS } '@mastra/core/storage' instead */
    static readonly TABLE_EVALS = "mastra_evals";
    /** @deprecated import from { TABLE_MESSAGES } '@mastra/core/storage' instead */
    static readonly TABLE_MESSAGES = "mastra_messages";
    /** @deprecated import from { TABLE_THREADS } '@mastra/core/storage' instead */
    static readonly TABLE_THREADS = "mastra_threads";
    /** @deprecated import { TABLE_TRACES } from '@mastra/core/storage' instead */
    static readonly TABLE_TRACES = "mastra_traces";
    protected hasInitialized: null | Promise<boolean>;
    protected shouldCacheInit: boolean;
    constructor({ name }: {
        name: string;
    });
    abstract createTable({ tableName }: {
        tableName: TABLE_NAMES;
        schema: Record<string, StorageColumn>;
    }): Promise<void>;
    abstract clearTable({ tableName }: {
        tableName: TABLE_NAMES;
    }): Promise<void>;
    abstract insert({ tableName, record }: {
        tableName: TABLE_NAMES;
        record: Record<string, any>;
    }): Promise<void>;
    abstract batchInsert({ tableName, records, }: {
        tableName: TABLE_NAMES;
        records: Record<string, any>[];
    }): Promise<void>;
    batchTraceInsert({ records }: {
        records: Record<string, any>[];
    }): Promise<void>;
    abstract load<R>({ tableName, keys }: {
        tableName: TABLE_NAMES;
        keys: Record<string, string>;
    }): Promise<R | null>;
    abstract getThreadById({ threadId }: {
        threadId: string;
    }): Promise<StorageThreadType | null>;
    abstract getThreadsByResourceId({ resourceId }: {
        resourceId: string;
    }): Promise<StorageThreadType[]>;
    abstract saveThread({ thread }: {
        thread: StorageThreadType;
    }): Promise<StorageThreadType>;
    abstract updateThread({ id, title, metadata, }: {
        id: string;
        title: string;
        metadata: Record<string, unknown>;
    }): Promise<StorageThreadType>;
    abstract deleteThread({ threadId }: {
        threadId: string;
    }): Promise<void>;
    abstract getMessages({ threadId, selectBy, threadConfig }: StorageGetMessagesArg): Promise<MessageType[]>;
    abstract saveMessages({ messages }: {
        messages: MessageType[];
    }): Promise<MessageType[]>;
    abstract getTraces({ name, scope, page, perPage, attributes, filters, }: {
        name?: string;
        scope?: string;
        page: number;
        perPage: number;
        attributes?: Record<string, string>;
        filters?: Record<string, any>;
        fromDate?: Date;
        toDate?: Date;
    }): Promise<any[]>;
    init(): Promise<void>;
    persistWorkflowSnapshot({ workflowName, runId, snapshot, }: {
        workflowName: string;
        runId: string;
        snapshot: WorkflowRunState;
    }): Promise<void>;
    loadWorkflowSnapshot({ workflowName, runId, }: {
        workflowName: string;
        runId: string;
    }): Promise<WorkflowRunState | null>;
    abstract getEvalsByAgentName(agentName: string, type?: 'test' | 'live'): Promise<EvalRow[]>;
    abstract getWorkflowRuns(args?: {
        workflowName?: string;
        fromDate?: Date;
        toDate?: Date;
        limit?: number;
        offset?: number;
        resourceId?: string;
    }): Promise<WorkflowRuns>;
    abstract getWorkflowRunById(args: {
        runId: string;
        workflowName?: string;
    }): Promise<WorkflowRun | null>;
}

export { type CoreToolMessage as $, type ApiRoute as A, type WatchEvent as B, type ToolAction as C, type DynamicMapping as D, type EvalRow as E, Agent as F, type AgentConfig as G, MastraMemory as H, type ToolExecutionContext as I, Tool as J, Step as K, Workflow as L, type Methods as M, type NewStep as N, type WorkflowOptions as O, type PathsToStringProps as P, type LanguageModel as Q, Run as R, type StorageColumn as S, type TABLE_NAMES as T, type CoreMessage as U, type VariableReference as V, type WorkflowRuns as W, type CoreSystemMessage as X, type CoreAssistantMessage as Y, type ZodPathType as Z, type CoreUserMessage as _, Mastra as a, type WorkflowRunState as a$, type EmbedResult as a0, type EmbedManyResult as a1, type BaseStructuredOutputType as a2, type StructuredOutputType as a3, type StructuredOutputArrayItem as a4, type StructuredOutput as a5, type GenerateReturn as a6, type StreamReturn as a7, type OutputType as a8, type DefaultLLMTextOptions as a9, type BaseCondition as aA, type ActionContext as aB, WhenConditionReturnValue as aC, type StepDef as aD, type StepCondition as aE, type StepConfig as aF, type StepResult$1 as aG, type StepsRecord$1 as aH, type WorkflowRunResult as aI, type WorkflowContext as aJ, type WorkflowLogMessage as aK, type WorkflowEvent as aL, type ResolverFunctionInput as aM, type ResolverFunctionOutput as aN, type SubscriberFunctionOutput as aO, type DependencyCheckOutput as aP, type StepResolverOutput as aQ, type WorkflowActors as aR, type WorkflowActionParams as aS, type WorkflowActions as aT, type WorkflowState as aU, type StepId as aV, type ExtractSchemaFromStep$1 as aW, type ExtractStepResult as aX, type StepInputType as aY, type ExtractSchemaType$1 as aZ, type PathsToStringProps$1 as a_, type DefaultLLMTextObjectOptions as aa, type DefaultLLMStreamOptions as ab, type DefaultLLMStreamObjectOptions as ac, type LLMTextOptions as ad, type LLMTextObjectOptions as ae, type LLMStreamOptions as af, type LLMInnerStreamOptions as ag, type LLMStreamObjectOptions as ah, createMockModel as ai, type Config as aj, type MessageResponse as ak, type MemoryConfig as al, type SharedMemoryConfig as am, type MemoryProcessorOpts as an, MemoryProcessor as ao, memoryDefaultOptions as ap, createTool as aq, type VercelTool as ar, type CoreTool as as, type StepExecutionContext as at, type StepAction as au, type StepVariableType as av, type StepNode as aw, type StepGraph as ax, type RetryConfig as ay, type VariableReference$1 as az, MastraStorage as b, type WorkflowResumeResult as b0, type MastraLanguageModel as b1, type MastraPrimitives as b2, type ToolsInput as b3, AgentNetwork as b4, type AgentNetworkConfig as b5, type VoiceEventType as b6, type VoiceEventMap as b7, type VoiceConfig as b8, MastraVoice as b9, CompositeVoice as ba, DefaultVoice as bb, type ToolsetsInput as bc, type DynamicArgument as bd, type AgentGenerateOptions as be, type AgentStreamOptions as bf, TABLE_WORKFLOW_SNAPSHOT as bg, TABLE_EVALS as bh, TABLE_MESSAGES as bi, TABLE_THREADS as bj, TABLE_TRACES as bk, TABLE_SCHEMAS as bl, type StorageThreadType as c, type MessageType as d, type StorageGetMessagesArg as e, type WorkflowRun as f, ExecutionEngine as g, type StepResult as h, type ExecutionGraph as i, type StepFlowEntry as j, type ExecuteFunction as k, type SerializedStep as l, type SerializedStepFlowEntry as m, createStep as n, cloneStep as o, createWorkflow as p, cloneWorkflow as q, type WorkflowResult as r, type NewWorkflowConfig as s, NewWorkflow as t, type StepSuccess as u, type StepFailure as v, type StepSuspended as w, type StepsRecord as x, type ExtractSchemaType as y, type ExtractSchemaFromStep as z };
