@mastra/core
Version:
179 lines • 7.97 kB
TypeScript
import type { ActorSignal } from '../auth/ee/index.js';
import { MastraBase } from '../base.js';
import type { RequestContext } from '../di/index.js';
import type { PubSub } from '../events/pubsub.js';
import type { IMastraLogger } from '../logger/index.js';
import type { Mastra } from '../mastra/index.js';
import type { Span, SpanType, TracingPolicy } from '../observability/index.js';
import type { StateBase } from './run-journal.js';
import type { NestedWorkflowParent, OutputWriter, SerializedStepFlowEntry, StepResult, WorkflowRunStatus, WorkflowRunState, WorkflowFinishCallbackResult, WorkflowErrorCallbackInfo, WorkflowStartCallbackInfo, WorkflowStateTracingContext, WorkflowStepResults } from './types.js';
import type { RestartExecutionParams, StepFlowEntry, TimeTravelExecutionParams } from '.';
/**
* Represents an execution graph for a workflow
*/
export interface ExecutionGraph<TEngineType = any> {
id: string;
steps: StepFlowEntry<TEngineType>[];
}
export interface ExecutionEngineOptions {
/** @internal Explicit suspension context supplied by agent-loop workflows. */
resumeTracingContext?: WorkflowStateTracingContext;
tracingPolicy?: TracingPolicy;
validateInputs: boolean;
emitStepEvents?: boolean;
shouldPersistSnapshot: (params: {
stepResults: Record<string, StepResult<any, any, any, any>>;
workflowStatus: WorkflowRunStatus;
}) => boolean;
evaluatePersistencePredicateBeforeDurableOperation?: boolean;
/**
* Acknowledges that `resume()` calls cannot be de-duplicated via the persisted
* resume claim, suppressing the per-resume warning. See `WorkflowOptions.allowUnclaimedResumes`.
*/
allowUnclaimedResumes?: boolean;
/**
* Writes the resume claim even when `shouldPersistSnapshot` excludes `running`.
* See `WorkflowOptions.persistResumeClaim`.
*/
persistResumeClaim?: boolean;
/**
* Skips reading a stored `canceled` status. See `WorkflowOptions.localCancellationOnly`.
* @internal
*/
localCancellationOnly?: boolean;
/**
* Transforms the run snapshot immediately before it is persisted.
* Must be pure and return JSON-safe data. Defaults to identity.
*/
pruneSnapshot?: (params: {
snapshot: WorkflowRunState;
workflowStatus: WorkflowRunStatus;
}) => WorkflowRunState;
/**
* Called and awaited before a run starts executing. Errors are propagated, which
* aborts the run before any step executes.
*/
onStart?: (info: WorkflowStartCallbackInfo) => Promise<void> | void;
/**
* Called when workflow execution completes (success, failed, suspended, or tripwire).
* Errors thrown in this callback are caught and logged, not propagated.
*/
onFinish?(result: WorkflowFinishCallbackResult<1 | 2>): Promise<void> | void;
/**
* Called only when workflow execution fails (failed or tripwire status).
* Errors thrown in this callback are caught and logged, not propagated.
*/
onError?(errorInfo: WorkflowErrorCallbackInfo<1 | 2>): Promise<void> | void;
}
/**
* Execution engine abstract class for building and executing workflow graphs
* Providers will implement this class to provide their own execution logic
*/
export declare abstract class ExecutionEngine extends MastraBase {
mastra?: Mastra;
options: ExecutionEngineOptions;
/**
* Per-run overrides of `options.shouldPersistSnapshot`, keyed by runId.
*
* `options` is shared by every run of a workflow, so persistence is otherwise a
* per-workflow decision. Some callers need it per run: an agent output processor
* executes its workflow once per streamed chunk, and those runs must never write
* snapshots even when the same workflow instance persists normally when the user
* starts it directly (#19605).
*/
private runPersistenceOverrides;
constructor({ mastra, options }: {
mastra?: Mastra;
options: ExecutionEngineOptions;
});
/** Registers a run-scoped `shouldPersistSnapshot` predicate. */
setRunPersistenceOverride(runId: string, shouldPersistSnapshot: ExecutionEngineOptions['shouldPersistSnapshot']): void;
/** Returns the run-scoped `shouldPersistSnapshot` predicate, if one was registered. */
getRunPersistenceOverride(runId: string): ExecutionEngineOptions['shouldPersistSnapshot'] | undefined;
/** Clears the run-scoped predicate (called on run cleanup). */
clearRunPersistenceOverride(runId: string): void;
__registerMastra(mastra: Mastra): void;
getLogger(): IMastraLogger;
/**
* Invokes the onStart lifecycle callback if it is defined, before any step runs.
* Errors are intentionally propagated so the hook can gate the run (for example a
* quota check): the caller rejects and the run never executes.
*/
invokeStartCallback(info: Omit<WorkflowStartCallbackInfo, 'mastra' | 'logger'>): Promise<void>;
/**
* Invokes the onFinish and onError lifecycle callbacks if they are defined.
* Errors in callbacks are caught and logged, not propagated.
* @param result The workflow result containing status, result, error, steps, tripwire info, and context
*/
invokeLifecycleCallbacks(result: {
status: WorkflowRunStatus;
result?: any;
error?: any;
steps: WorkflowStepResults<Record<string, StepResult<any, any, any, any>>, 1 | 2>;
tripwire?: any;
runId: string;
workflowId: string;
resourceId?: string;
input?: any;
requestContext: RequestContext;
state: Record<string, any>;
stepExecutionPath?: string[];
}): Promise<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<TState, TInput, TOutput>(params: {
workflowId: string;
runId: string;
parentWorkflow?: NestedWorkflowParent;
resourceId?: string;
disableScorers?: boolean;
graph: ExecutionGraph;
serializedStepGraph: SerializedStepFlowEntry[];
input?: TInput;
initialState?: TState;
timeTravel?: TimeTravelExecutionParams;
restart?: RestartExecutionParams;
resume?: {
steps: string[];
stepResults: Record<string, StepResult<any, any, any, any>>;
resumePayload: any;
resumePath: number[];
stepExecutionPath?: string[];
forEachIndex?: number;
label?: string;
};
pubsub: PubSub;
requestContext: RequestContext;
actor?: ActorSignal;
workflowSpan?: Span<SpanType.WORKFLOW_RUN>;
retryConfig?: {
attempts?: number;
delay?: number;
};
abortController: AbortController;
outputWriter?: OutputWriter;
format?: 'legacy' | 'vnext' | undefined;
outputOptions?: {
includeState?: boolean;
includeResumeLabels?: boolean;
};
perStep?: boolean;
/** How the run is stored. Engines that don't support version 2 ignore it. @experimental */
storageVersion?: 1 | 2;
/** Called once the run is handed to workers. Engines that execute in-process ignore it. @internal */
onDispatched?: () => void;
/** For a storage v2 resume or restart, what the store reported for the loaded state. @internal */
storedState?: {
seq: number;
patchBytes: number;
patchCount: number;
};
/** For a storage v2 nested start or time travel, the version of the parent's state it starts from. @internal */
inheritedState?: StateBase;
}): Promise<TOutput>;
}
//# sourceMappingURL=execution-engine.d.ts.map