@mastra/core
Version:
462 lines • 20.7 kB
TypeScript
import type { ActorSignal } from '../auth/ee/index.js';
import { RequestContext } from '../di/index.js';
import type { SerializedError } from '../error/index.js';
import type { PubSub } from '../events/pubsub.js';
import type { ObservabilityContext, Span, SpanType, TracingPolicy, SpanOutcomeFields } from '../observability/index.js';
import type { ExecutionGraph } from './execution-engine.js';
import { ExecutionEngine } from './execution-engine.js';
import type { ExecuteConditionalParams, ExecuteForeachParams, ExecuteLoopParams, ExecuteParallelParams } from './handlers/control-flow.js';
import type { ExecuteEntryParams, PersistStepUpdateParams } from './handlers/entry.js';
import type { ExecuteSleepParams, ExecuteSleepUntilParams } from './handlers/sleep.js';
import type { ExecuteStepParams } from './handlers/step.js';
import { RunJournal } from './run-journal.js';
import type { StateBase } from './run-journal.js';
import type { ConditionFunction, ConditionFunctionParams, Step } from './step.js';
import type { FormattedWorkflowResult, DefaultEngineType, EntryExecutionResult, ExecutionContext, MutableContext, NestedWorkflowParent, OutputWriter, RestartExecutionParams, SerializedStepFlowEntry, SingleStepEntry, StepExecutionResult, StepFlowEntry, StepResult, StepTripwireInfo, TimeTravelExecutionParams, WorkflowRunStatus } from './types.js';
export type { ExecutionContext } from './types.js';
/** Params for the per-type execute methods: the same context `executeStep` takes,
* with the declarative graph entry instead of a pre-built `step`. */
export type ExecuteAgentParams = Omit<ExecuteStepParams, 'step'> & {
entry: Extract<SingleStepEntry, {
type: 'agent';
}>;
};
export type ExecuteToolParams = Omit<ExecuteStepParams, 'step'> & {
entry: Extract<SingleStepEntry, {
type: 'tool';
}>;
};
export type ExecuteClassifierParams = Omit<ExecuteStepParams, 'step'> & {
entry: Extract<SingleStepEntry, {
type: 'classifier';
}>;
};
export type ExecuteMappingParams = Omit<ExecuteStepParams, 'step'> & {
entry: Extract<SingleStepEntry, {
type: 'mapping';
}>;
};
/**
* Default implementation of the ExecutionEngine
*/
export declare class DefaultExecutionEngine extends ExecutionEngine {
#private;
/**
* Tracks the last workflow status this engine successfully persisted for a
* given run. Populated by `persistStepUpdate` after each write.
*
* Used to guard against overwriting a `suspended` / `paused` snapshot with a
* later `running` update from the same run (e.g. during resume, when the
* loop transitions suspended → running mid-execution and any step-update
* write would otherwise clobber the suspend record).
*
* Process-local by design: on a crash the map is empty, but any run that
* was in-flight (`running`) after crash will show `running` in storage
* because we now persist that status — which is exactly what boot-time
* recovery relies on.
*
* `replayingCanceled` marks a run that starts while its stored status is
* already `canceled`: a time-travel replay whose claim to flip it to
* `running` was skipped, or a fresh `start()` reusing the runId of a canceled
* attempt. That status is the run's starting point, not a cancellation of
* this execution, so it is not honored until the run writes a status of its own.
*/
protected lastPersistedStatusByRun: Map<string, {
status?: WorkflowRunStatus;
replayingCanceled: boolean;
}>;
/**
* @internal Returns the journal of the storage-v2 execution of `runId` this is called from; a run
* is on v2 when it has one. Each execution has its own: a restart or resume can start another
* execution of the run before a hung one ends, and neither may write through the other's.
*/
getRunJournal(runId: string): RunJournal | undefined;
/** Returns the last status persisted for a given run in this process, if any. */
getLastPersistedStatus(runId: string): WorkflowRunStatus | undefined;
/** Records the last status persisted for a given run in this process. */
setLastPersistedStatus(runId: string, status: WorkflowRunStatus): void;
/** Clears the last-persisted-status entry for a run (used on run cleanup). */
clearLastPersistedStatus(runId: string): void;
/** Whether stored `canceled` status should stop this run's execution. */
honorsStoredCancellation(runId: string): boolean;
/** True when the store refused a non-canceled write because the run was canceled meanwhile. */
private writeRejectedByCancellation;
/**
* Runs one snapshot write for `runId` after every write already queued for that run
* has settled. Snapshot writes are full upserts, so concurrent writes from parallel
* arms or foreach items could otherwise land out of order and replace a newer
* checkpoint with an older one (#26214).
*/
serializeSnapshotWrite(runId: string, write: () => Promise<void>): Promise<void>;
/** Returns the current step's zero-based retry attempt, or zero outside an attempt. */
getOrGenerateRetryCount(_stepId: Step['id']): number;
/**
* Check if a step is a nested workflow that requires special handling.
* Override this in subclasses to detect platform-specific workflow types.
*
* @param _step - The step to check
* @returns true if the step is a nested workflow, false otherwise
*/
isNestedWorkflowStep(_step: Step<any, any, any>): boolean;
/**
* Execute the sleep duration. Override to use platform-specific sleep primitives.
*
* @param duration - The duration to sleep in milliseconds
* @param _sleepId - Unique identifier for this sleep operation
* @param _workflowId - The workflow ID (for constructing platform-specific IDs)
*/
executeSleepDuration(duration: number, _sleepId: string, _workflowId: string, abortSignal?: AbortSignal): Promise<void>;
/**
* Execute sleep until a specific date. Override to use platform-specific sleep primitives.
*
* @param date - The date to sleep until
* @param _sleepUntilId - Unique identifier for this sleep operation
* @param _workflowId - The workflow ID (for constructing platform-specific IDs)
*/
executeSleepUntilDate(date: Date, _sleepUntilId: string, _workflowId: string, abortSignal?: AbortSignal): Promise<void>;
/**
* Wrap a durable operation (like dynamic sleep function evaluation).
* Override to add platform-specific durability.
*
* @param _operationId - Unique identifier for this operation
* @param operationFn - The function to execute
* @returns The result of the operation
*/
wrapDurableOperation<T>(_operationId: string, operationFn: () => Promise<T>): Promise<T>;
/**
* Get the engine context to pass to step execution functions.
* Override to provide platform-specific engine primitives (e.g., Inngest step).
*
* @returns An object containing engine-specific context
*/
getEngineContext(): Record<string, any>;
/**
* Evaluate a single condition for conditional execution.
* Override to add platform-specific durability (e.g., Inngest step.run wrapper).
*
* @param conditionFn - The condition function to evaluate
* @param index - The index of this condition
* @param context - The execution context for the condition
* @param operationId - Unique identifier for this operation
* @returns The index if condition is truthy, null otherwise
*/
evaluateCondition(conditionFn: ConditionFunction<any, any, any, any, any, DefaultEngineType>, index: number, context: ConditionFunctionParams<any, any, any, any, any, DefaultEngineType>, operationId: string): Promise<number | null>;
/**
* Handle step execution start - emit events and return start timestamp.
* Override to add platform-specific durability (e.g., Inngest step.run wrapper).
*
* @param params - Parameters for step start
* @returns The start timestamp (used by some engines like Inngest)
*/
onStepExecutionStart(params: {
step: Step<string, any, any>;
inputData: any;
pubsub: PubSub;
executionContext: ExecutionContext;
stepCallId: string;
stepInfo: Record<string, any>;
operationId: string;
skipEmits?: boolean;
}): Promise<number>;
/**
* Execute a nested workflow step. Override to use platform-specific workflow invocation.
* This hook is called when isNestedWorkflowStep returns true.
*
* Default behavior: returns null to indicate the base executeStep should handle it normally.
* Inngest overrides this to use inngestStep.invoke() for nested workflows.
*
* @param params - Parameters for nested workflow execution
* @returns StepResult if handled, null if should use default execution
*/
executeWorkflowStep(_params: ObservabilityContext & {
step: Step<string, any, any>;
stepResults: Record<string, StepResult<any, any, any, any>>;
executionContext: ExecutionContext;
resume?: {
steps: string[];
resumePayload: any;
runId?: string;
};
timeTravel?: TimeTravelExecutionParams;
prevOutput: any;
inputData: any;
pubsub: PubSub;
startedAt: number;
abortController: AbortController;
requestContext: RequestContext;
actor?: ActorSignal;
outputWriter?: OutputWriter;
stepSpan?: Span<SpanType.WORKFLOW_STEP>;
perStep?: boolean;
}): Promise<StepResult<any, any, any, any> | null>;
/**
* Create a child span for a workflow step.
* Override to add durability (e.g., Inngest memoization).
*
* Default: creates span directly via parent span's createChildSpan.
*
* @param params - Parameters for span creation
* @returns The created span, or undefined if no parent span or tracing disabled
*/
createStepSpan(params: {
parentSpan: Span<SpanType> | undefined;
stepId: string;
operationId: string;
options: SpanOutcomeFields & {
name: string;
type: SpanType;
input?: unknown;
entityType?: string;
entityId?: string;
attributes?: Record<string, unknown>;
tracingPolicy?: TracingPolicy;
requestContext?: RequestContext;
};
executionContext: ExecutionContext;
}): Promise<Span<SpanType> | undefined>;
/**
* End a workflow step span.
* Override to add durability (e.g., Inngest memoization).
*
* Default: calls span.end() directly.
*
* @param params - Parameters for ending the span
*/
endStepSpan(params: {
span: Span<SpanType> | undefined;
operationId: string;
endOptions: SpanOutcomeFields & {
output?: unknown;
attributes?: Record<string, unknown>;
};
}): Promise<void>;
/**
* Record an error on a workflow step span.
* Override to add durability (e.g., Inngest memoization).
*
* Default: calls span.error() directly.
*
* @param params - Parameters for recording the error
*/
errorStepSpan(params: {
span: Span<SpanType> | undefined;
operationId: string;
errorOptions: SpanOutcomeFields & {
error: Error;
origin?: 'new' | 'propagated';
attributes?: Record<string, unknown>;
};
}): Promise<void>;
/**
* Create a generic child span (for control-flow operations like parallel, conditional, loop).
* Override to add durability (e.g., Inngest memoization).
*
* Default: creates span directly via parent span's createChildSpan.
*
* @param params - Parameters for span creation
* @returns The created span, or undefined if no parent span or tracing disabled
*/
createChildSpan(params: {
parentSpan: Span<SpanType> | undefined;
operationId: string;
options: SpanOutcomeFields & {
name: string;
type: SpanType;
input?: unknown;
attributes?: Record<string, unknown>;
tracingPolicy?: TracingPolicy;
};
executionContext: ExecutionContext;
}): Promise<Span<SpanType> | undefined>;
/**
* End a generic child span (for control-flow operations).
* Override to add durability (e.g., Inngest memoization).
*
* Default: calls span.end() directly.
*
* @param params - Parameters for ending the span
*/
endChildSpan(params: {
span: Span<SpanType> | undefined;
operationId: string;
endOptions?: SpanOutcomeFields & {
output?: unknown;
attributes?: Record<string, unknown>;
};
}): Promise<void>;
/**
* Record an error on a generic child span (for control-flow operations).
* Override to add durability (e.g., Inngest memoization).
*
* Default: calls span.error() directly.
*
* @param params - Parameters for recording the error
*/
errorChildSpan(params: {
span: Span<SpanType> | undefined;
operationId: string;
errorOptions: SpanOutcomeFields & {
error: Error;
origin?: 'new' | 'propagated';
attributes?: Record<string, unknown>;
};
}): Promise<void>;
/**
* Execute a step with retry logic.
* Default engine: handles retries internally with a loop.
* Inngest engine: overrides to throw RetryAfterError for external retry handling.
*
* @param stepId - Unique identifier for the step (used for durability)
* @param runStep - The step execution function to run
* @param params - Retry parameters and context
* @returns Discriminated union: { ok: true, result: T } or { ok: false, error: ... }
*/
executeStepWithRetry<T>(stepId: string, runStep: () => Promise<T>, params: {
retries: number;
delay: number;
stepSpan?: Span<SpanType>;
workflowId: string;
runId: string;
}): Promise<{
ok: true;
result: T;
} | {
ok: false;
error: {
status: 'failed';
error: Error;
endedAt: number;
nonRetryable?: true;
tripwire?: StepTripwireInfo;
};
}>;
/**
* Format an error for the workflow result.
* Override to customize error formatting (e.g., include stack traces).
*/
protected formatResultError(error: Error | unknown, lastOutput: StepResult<any, any, any, any>): SerializedError;
protected fmtReturnValue<TOutput>(_pubsub: PubSub, stepResults: Record<string, StepResult<any, any, any, any>>, lastOutput: StepResult<any, any, any, any>, error?: Error | unknown, stepExecutionPath?: string[]): Promise<TOutput>;
/**
* Every field of a result except `steps`. Reads only `input` and results that aren't successful,
* which storage v2 never evicts.
*/
protected fmtResultEnvelope(stepResults: Record<string, StepResult<any, any, any, any>>, lastOutput: StepResult<any, any, any, any>, error?: Error | unknown, stepExecutionPath?: string[]): Omit<FormattedWorkflowResult, 'steps'>;
/**
* The `steps` of a result: internal metadata stripped and, with an execution path, each payload
* that repeats the previous step's output left out. Needs every result in full.
*/
protected fmtResultSteps(stepResults: Record<string, StepResult<any, any, any, any>>, stepExecutionPath?: string[]): Record<string, StepResult<any, any, any, any>>;
/**
* Serialize a RequestContext Map to a plain object for JSON serialization.
* Used by durable execution engines to persist context across step replays.
*/
serializeRequestContext(requestContext: RequestContext): Record<string, any>;
/**
* Deserialize a plain object back to a RequestContext instance.
* Used to restore context after durable execution replay.
*/
protected deserializeRequestContext(obj: Record<string, any>): RequestContext;
/**
* Whether this engine requires requestContext to be serialized for durable operations.
* Default engine passes by reference (no serialization needed).
* Inngest engine overrides to return true (serialization required for memoization).
*/
requiresDurableContextSerialization(): boolean;
/**
* Build MutableContext from current execution state.
* This extracts only the fields that can change during step execution.
*/
buildMutableContext(executionContext: ExecutionContext): MutableContext;
/**
* Apply mutable context changes back to the execution context.
*/
applyMutableContext(executionContext: ExecutionContext, mutableContext: MutableContext): 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
*/
execute<TState, TInput, TOutput>(params: {
workflowId: string;
runId: string;
parentWorkflow?: NestedWorkflowParent;
resourceId?: string;
disableScorers?: boolean;
graph: ExecutionGraph;
serializedStepGraph: SerializedStepFlowEntry[];
input?: TInput;
initialState?: TState;
restart?: RestartExecutionParams;
timeTravel?: TimeTravelExecutionParams;
resume?: {
steps: string[];
stepResults: Record<string, StepResult<any, any, any, any>>;
resumePayload: any;
resumePath: number[];
stepExecutionPath?: string[];
label?: string;
forEachIndex?: number;
};
pubsub: PubSub;
retryConfig?: {
attempts?: number;
delay?: number;
};
requestContext: RequestContext;
actor?: ActorSignal;
workflowSpan?: Span<SpanType.WORKFLOW_RUN>;
abortController: AbortController;
outputWriter?: OutputWriter;
format?: 'legacy' | 'vnext' | undefined;
outputOptions?: {
includeState?: boolean;
includeResumeLabels?: boolean;
};
perStep?: boolean;
/** @experimental */
storageVersion?: 1 | 2;
/** @internal */
storedState?: {
seq: number;
patchBytes: number;
patchCount: number;
};
/** @internal */
inheritedState?: StateBase;
/** Trace IDs for creating child spans in durable execution */
tracingIds?: {
traceId: string;
workflowSpanId: string;
};
}): Promise<TOutput>;
getStepOutput(stepResults: Record<string, any>, step?: StepFlowEntry): any;
executeSleep(params: ExecuteSleepParams): Promise<void>;
executeSleepUntil(params: ExecuteSleepUntilParams): Promise<void>;
executeStep(params: ExecuteStepParams): Promise<StepExecutionResult>;
/**
* Executes a declarative `agent` step: resolves the agent (live ref, else
* `mastra.getAgentById(agentId)`), builds its runnable step, and runs it through
* the shared step runner.
*/
executeAgent(params: ExecuteAgentParams): Promise<StepExecutionResult>;
/**
* Executes a declarative `tool` step: resolves the tool (live ref, else
* `mastra.getTool(toolId)`), builds its runnable step, and runs it through the
* shared step runner.
*/
executeTool(params: ExecuteToolParams): Promise<StepExecutionResult>;
executeClassifier(params: ExecuteClassifierParams): Promise<StepExecutionResult>;
/**
* Executes a declarative `mapping` step: builds the mapping step from the
* declarative config/fn and runs it through the shared step runner.
*/
executeMapping(params: ExecuteMappingParams): Promise<StepExecutionResult>;
executeParallel(params: ExecuteParallelParams): Promise<StepResult<any, any, any, any>>;
executeConditional(params: ExecuteConditionalParams): Promise<StepResult<any, any, any, any>>;
executeLoop(params: ExecuteLoopParams): Promise<StepResult<any, any, any, any>>;
executeForeach(params: ExecuteForeachParams): Promise<StepResult<any, any, any, any>>;
persistStepUpdate(params: PersistStepUpdateParams): Promise<void>;
executeEntry(params: ExecuteEntryParams): Promise<EntryExecutionResult>;
}
//# sourceMappingURL=default.d.ts.map