import type { ActorSignal } from '../../../auth/ee/index.js';
import { EventProcessor } from '../../../events/processor.js';
import type { Event } from '../../../events/types.js';
import type { Mastra } from '../../../mastra/index.js';
import type { StepExecutionStrategy } from '../../../worker/types.js';
import type { NestedWorkflowParent, RestartExecutionParams, StepFlowEntry, StepResult, TimeTravelExecutionParams, WorkflowRunState } from '../../../workflows/types.js';
import type { Workflow } from '../../../workflows/workflow.js';
export type ProcessorArgs = {
    eventId?: string;
    activeStepsPath: Record<string, number[]>;
    workflow: Workflow;
    workflowId: string;
    runId: string;
    executionPath: number[];
    stepResults: Record<string, StepResult<any, any, any, any>>;
    resumeSteps: string[];
    prevResult: StepResult<any, any, any, any>;
    requestContext: Record<string, any>;
    /**
     * Caller identity for the run. Serialized alongside `requestContext` on
     * every re-published step event so tools/steps observe `context.actor`
     * across the whole event chain, mirroring the default engine.
     */
    actor?: ActorSignal;
    timeTravel?: TimeTravelExecutionParams;
    restart?: RestartExecutionParams;
    resumeData?: any;
    parentWorkflow?: ParentWorkflow;
    parentContext?: {
        workflowId: string;
        input: any;
    };
    retryCount?: number;
    perStep?: boolean;
    format?: 'legacy' | 'vnext';
    state?: Record<string, any>;
    outputOptions?: {
        includeState?: boolean;
        includeResumeLabels?: boolean;
    };
    forEachIndex?: number;
    nestedRunId?: string;
    /**
     * Resource the run is attributed to. Carried on the `workflow.start` event
     * for schedule-fired runs (which have no pre-existing snapshot to derive it
     * from) so the persisted run snapshot records the schedule's `resourceId`.
     */
    resourceId?: string;
};
export type ParentWorkflow = {
    workflowId: string;
    runId: string;
    executionPath: number[];
    resume: boolean;
    /** Not carried on storage v2: the parent's dispatches load its step results. */
    stepResults?: Record<string, StepResult<any, any, any, any>>;
    parentWorkflow?: ParentWorkflow;
    timeTravel?: TimeTravelExecutionParams;
    restart?: RestartExecutionParams;
    stepId: string;
    activeStepsPath: Record<string, number[]>;
    resumeSteps: string[];
    resumeData: any;
    input: any;
    parentContext?: {
        workflowId: string;
        input: any;
    };
};
/**
 * Control-path state taken by `#dispatch` before its state load for a
 * `workflow.step.run`, and `storedRun`, the snapshot that load read (`null`
 * when the run has none).
 */
type ControlAtDispatch = {
    ready?: boolean;
    missedAborts?: number;
    storedRun?: WorkflowRunState | null;
};
export declare class WorkflowEventProcessor extends EventProcessor {
    #private;
    private stepExecutor;
    private stepExecutionStrategy?;
    private abortControllers;
    private controllerGenerations;
    private cancelHandledControllers;
    private parentChildRelationships;
    private controlSubscription?;
    private missedControlAborts;
    private stepRunRefs;
    private controlAbortedControllers;
    private startedRuns;
    private runFormats;
    private deliveryAttempts;
    private static readonly MAX_DELIVERY_ATTEMPTS;
    /** TTL of the lease fencing a running `workflow.step.run`; renewed every ttl/3. */
    static STEP_FENCE_TTL_MS: number;
    private static readonly TERMINAL_SENTINEL;
    private pendingFailures;
    private static readonly MAX_FAIL_PUBLISH_ATTEMPTS;
    private static readonly DELIVERY_ATTEMPTS_MAX_ENTRIES;
    private readonly topicCleanupDelayMs;
    private static readonly DEFAULT_TOPIC_CLEANUP_DELAY_MS;
    private readonly pendingTopicCleanups;
    private static readonly ACTIVE_RUN_STATUSES;
    constructor({ mastra, stepExecutionStrategy, topicCleanupDelayMs, }: {
        mastra: Mastra;
        stepExecutionStrategy?: StepExecutionStrategy;
        topicCleanupDelayMs?: number;
    });
    /**
     * Schedule deletion of a finished run's `workflow.events.v2.<runId>` topic.
     *
     * Per-run watch topics are written by every step of a run; on transports
     * that retain messages (e.g. Redis Streams) they would otherwise live
     * forever once the run ends. Deletion is delayed so subscribers still
     * draining the terminal `workflow-finish` event aren't cut off, and
     * fire-and-forget because topic cleanup must never affect run completion.
     *
     * Best-effort by design: if the process exits before the timer fires, the
     * transport-level idle TTL (e.g. `streamIdleTtlMs`) is the backstop.
     *
     * A finished run can be re-executed under the same runId (`timeTravel`,
     * `restart`), so deletion is double-guarded: a restart processed by this
     * process cancels the pending timer directly, and when the timer fires we
     * re-check the run's persisted status — a restart may have been picked up
     * by a different worker process — and skip deletion while the run is
     * active again.
     */
    private scheduleRunTopicCleanup;
    private cancelRunTopicCleanup;
    private clearRunTopicUnlessActive;
    /**
     * Get or create an AbortController for a workflow run
     */
    private getOrCreateAbortController;
    /**
     * Cancel a workflow run and all its nested child workflows
     */
    private cancelRunAndChildren;
    /**
     * Handle an abort for `runId` received on its control topic.
     *
     * The processor that consumed `workflow.cancel` already aborted its own
     * controllers and is finalizing the run, so the run's own controller here is
     * marked cancel-handled: the step unwinds without publishing a second
     * `workflow.cancel`. Nested runs are aborted unhandled, exactly as
     * {@link cancelRunAndChildren} does locally, so each publishes its own
     * cancel and settles canceled. Idempotent: a redelivered or self-echoed
     * abort finds the controllers already aborted.
     */
    private abortRunFromControl;
    /**
     * Make sure this processor listens on {@link WORKFLOW_CONTROL_TOPIC}.
     *
     * `workflow.cancel` is consumed by one processor of the consumer group, but
     * the step it must abort can be running on any replica, so the cancelling
     * processor broadcasts an abort that every processor receives and matches
     * against the runs it is executing. One ungrouped subscription per
     * processor, opened by its first step and kept for its lifetime: transports
     * share one reader/subscription per topic per process, so the cost does not
     * grow with runs or steps. `latest`: aborts from before the subscription
     * belong to runs this processor was not executing; the window before it is
     * ready is covered by {@link abortRunsCanceledInStorage}.
     *
     * A failed subscribe is not fatal — the step falls back to the storage
     * re-check and the next step retries the subscribe.
     */
    private ensureControlSubscription;
    /**
     * Whether an abort broadcast published from now on reaches this processor:
     * delivered to {@link abortRunFromControl}, which aborts it or counts it in
     * {@link missedControlAborts}. Taken by {@link #dispatch} before its state
     * load, so a step whose event passed the guard while this was false
     * re-checks storage: a cancel landing in between was never delivered.
     */
    private isControlSubscriptionReady;
    /**
     * Abort the step's runs if a cancel was persisted for any of them (`runIds`:
     * the step's run and its ancestors) before this processor could hear its
     * broadcast — between the dispatch guard's state load and the step's
     * controller being registered (counted in {@link missedControlAborts}), or
     * before the control subscription was ready when the step was dispatched.
     * Only called in those windows:
     * each call is a full snapshot read per run.
     * `EventedRun.cancel` persists `canceled` before publishing `workflow.cancel`,
     * so the processor handling that event finalizes the run, as with a
     * broadcast abort.
     */
    private abortRunsCanceledInStorage;
    /**
     * Count an in-flight step against `runIds` (its run and its ancestors).
     *
     * @returns A release function that must be called when the step finishes.
     */
    private retainRunsForStep;
    /**
     * Clean up abort controller and relationships when a workflow completes.
     * Also cleans up any orphaned child entries that reference this run as parent.
     */
    private cleanupRun;
    /**
     * Resolves the tracing context for a run, walking up the parent chain so a
     * nested workflow run (e.g. `agentic-execution` inside `agentic-loop`)
     * inherits its parent's parent span. `EventedRun.start` records the context
     * on Mastra keyed by runId; nested runs are only registered against their
     * parent.
     */
    private resolveRunTracingContext;
    private endRunSpans;
    /**
     * The evented engine holds the live span on Mastra (since it can't ride pubsub
     * events), so we resolve it via runId here.
     */
    private resolveSuspendTracingContext;
    /**
     * Applies the workflow's `pruneSnapshot` option to an already-persisted snapshot.
     *
     * The evented engine persists suspensions via merge operations
     * (`updateWorkflowResults` + `updateWorkflowState`) rather than writing a full
     * snapshot object, so the prune hook can't intercept the write itself. Instead,
     * after the merge completes, we load the merged snapshot, prune it, and
     * re-persist the full row. No-op when the workflow has no `pruneSnapshot` option.
     */
    private pruneAndRepersistSnapshot;
    /**
     * Applies the workflow's `pruneSnapshot` hook to a single completed step
     * result before it is written by `updateWorkflowResults`, so the prune rides
     * the same atomic merge write instead of a second full-row read-modify-write.
     *
     * The merge write bypasses the prune hook, so a completed step would keep its
     * full `payload`/`output` — for the durable loop, the whole iteration state
     * (`accumulatedSteps`/`messageListState`) — and the stored row (which every
     * merge re-reads and re-serializes) grows with each step until the process
     * OOMs (COR-1431). Returns `storedResult` unchanged when the workflow has no
     * `pruneSnapshot` option. The hook needs the surrounding run context
     * (`activeStepsPath`, `activePaths`, `serializedStepGraph`) to decide what a
     * restart still reads, so it is invoked with a complete running snapshot built
     * from the in-flight run state.
     *
     * Live execution keeps the FULL result (the caller stores `storedResult` in
     * its in-memory `stepResults`); only the persisted record is pruned, matching
     * the default engine, which treats its in-memory `stepResults` as truth.
     */
    private pruneStepResultForPersist;
    private serializeParentWorkflow;
    restoreParentWorkflow(parent: NestedWorkflowParent): Promise<ParentWorkflow>;
    __registerMastra(mastra: Mastra): void;
    private errorWorkflow;
    protected processWorkflowCancel({ workflowId, runId, prevResult, ...args }: ProcessorArgs): Promise<void>;
    protected processWorkflowStart({ workflow, parentWorkflow, workflowId, runId, resumeSteps, prevResult, resumeData, timeTravel, restart, executionPath, stepResults, requestContext, actor, perStep, format, state, outputOptions, forEachIndex, resourceId: eventResourceId, eventId, }: ProcessorArgs & {
        initialState?: Record<string, any>;
    }): Promise<void>;
    /**
     * `pausesRun` is false for an end that finishes a step-by-step run (a bail), which still
     * forwards `perStep` so a parent workflow pauses after this nested run.
     */
    protected endWorkflow(args: ProcessorArgs, status?: 'success' | 'failed' | 'canceled' | 'paused', pausesRun?: boolean): Promise<void>;
    private publishFinishEvent;
    private assertCurrentRunFence;
    protected processWorkflowEnd(args: ProcessorArgs & {
        deleteSnapshotAfterEnd?: boolean;
    }): Promise<void>;
    protected processWorkflowSuspend(args: ProcessorArgs): Promise<void>;
    protected processWorkflowFail(args: ProcessorArgs): Promise<void>;
    /**
     * Handles a `workflow.step.run` event: routes control entries (parallel,
     * conditional, foreach, sleep) to their dispatchers, ends the run past its
     * last entry, and runs a leaf step unless the stored run shows that
     * occurrence already finished.
     */
    protected processWorkflowStepRun(args: ProcessorArgs, control?: ControlAtDispatch): Promise<void>;
    /**
     * Shared leaf-step runner. Executes a single leaf entry - a plain `step`, a
     * declarative `agent` / `tool` / `mapping` entry, or a `loop` / `foreach`
     * body - and emits its lifecycle events (`workflow.step.end`, retries,
     * suspend, cancel). The per-kind interpretation happens in the step
     * executor's dispatch; here entries are only inspected via the `step-entry`
     * accessors.
     */
    protected runLeafStep(args: ProcessorArgs & {
        step: Extract<StepFlowEntry, {
            type: 'step' | 'agent' | 'tool' | 'mapping' | 'loop' | 'foreach';
        }>;
    }, control?: ControlAtDispatch): Promise<void>;
    /**
     * Aggregate the results of all branches of a `parallel` / `conditional` entry once
     * every branch has reached a terminal state (`success` / `skipped`) or `suspended`.
     *
     * This runs once per branch completion. It only acts when every branch is accounted
     * for; otherwise it returns and lets a later branch finish the aggregation. Because
     * `stepResults` is the snapshot returned by the caller's `updateWorkflowResults`
     * call — which grows monotonically per branch — only the branch whose write landed
     * last observes the full set, so exactly one branch emits (no double emit).
     *
     * - if any branch is still suspended → re-emit `workflow.suspend` with the full set
     *   of suspended paths and persist the workflow state. This both fixes the race where
     *   each branch would overwrite `suspendedPaths` on its own, and lets the workflow
     *   stay suspended while only some branches have been resumed.
     * - otherwise → emit `workflow.step.end` for the parallel/conditional entry with the
     *   merged branch outputs (the existing behaviour).
     */
    protected aggregateBranchResults({ workflow, workflowId, runId, branchEntry, branchExecutionPath, latestBranchResult, resumeSteps, timeTravel, restart, parentWorkflow, stepResults, activeStepsPath, requestContext, actor, state, outputOptions, }: {
        workflow: Workflow;
        workflowId: string;
        runId: string;
        branchEntry: Extract<StepFlowEntry, {
            type: 'parallel' | 'conditional';
        }>;
        branchExecutionPath: number[];
        /**
         * The in-flight result of the branch that just finished (i.e. the one at
         * `branchExecutionPath`). Used for that branch's output so non-JSON values (e.g.
         * `Date`) survive — the copy in `stepResults` has been round-tripped through storage
         * serialization. Other branches' outputs unavoidably come from `stepResults`.
         */
        latestBranchResult?: StepResult<any, any, any, any>;
        resumeSteps: string[];
        timeTravel?: TimeTravelExecutionParams;
        restart?: RestartExecutionParams;
        parentWorkflow?: ParentWorkflow;
        stepResults: Record<string, any>;
        activeStepsPath: Record<string, number[]>;
        requestContext: Record<string, any>;
        actor?: ActorSignal;
        state: Record<string, any>;
        outputOptions?: {
            includeState?: boolean;
            includeResumeLabels?: boolean;
        };
    }): Promise<void>;
    protected processWorkflowStepEnd({ workflow, workflowId, runId, executionPath, resumeSteps, timeTravel, restart, prevResult, parentWorkflow, stepResults, activeStepsPath, parentContext, requestContext, actor, perStep, state, outputOptions, forEachIndex, nestedRunId, }: ProcessorArgs): Promise<void>;
    loadData({ workflowId, runId, }: {
        workflowId: string;
        runId: string;
    }): Promise<WorkflowRunState | null | undefined>;
    /**
     * Result of handling a single workflow event.
     *
     * - `ok: true` — event was processed; the transport should ack.
     * - `ok: false, retry: true` — transient failure, the transport should
     *   nack/redeliver (or, for HTTP push, return 5xx so the broker retries).
     * - `ok: false, retry: false` — terminal/poison failure, the transport
     *   should drop the event (or return 4xx for HTTP push).
     */
    handle(event: Event): Promise<{
        ok: true;
    } | {
        ok: false;
        retry: boolean;
    }>;
    /**
     * @deprecated prefer {@link WorkflowEventProcessor.handle}, which returns a
     * structured result instead of relying on an ack callback. Kept as a thin
     * wrapper so existing pull-mode call sites continue to work.
     */
    process(event: Event, ack?: () => Promise<void>): Promise<void>;
}
export {};
//# sourceMappingURL=index.d.ts.map