import type { WorkflowsStorage } from '../storage/domains/workflows/base.js';
import type { StateRef, StepResultSummary } from '../storage/domains/workflows/journal.js';
import type { StepResult, WorkflowRunState, WorkflowRunStatus } from './types.js';
type StepResults = Record<string, StepResult<any, any, any, any>>;
/**
 * A stand-in for a successful step result that is stored but no longer held in memory: the
 * result's summary fields, without its data. `RunJournal.hydrate` swaps it back for the stored
 * result.
 *
 * @internal
 */
export declare function stubStepResult(result: StepResultSummary): StepResult<any, any, any, any>;
/** @internal */
export declare function isStepResultStub(value: unknown): boolean;
/**
 * A version of a stored run state (possibly another run's), and a JSON copy of that state, which
 * is shared and never edited.
 *
 * @internal
 */
export type StateBase = {
    ref: StateRef;
    state: Record<string, unknown>;
};
/**
 * What a storage v2 parent hands a nested workflow step: a stored version of the parent's state
 * for a nested run starting from `state` to build on, undefined when it stores a full copy.
 *
 * @internal
 */
export type ParentStateLink = (state: unknown) => Promise<StateBase | undefined>;
/**
 * Tracks what a storage-v2 run has written, so each engine write sends only the
 * step results that changed (and the state's changes) instead of the whole snapshot.
 * It also lets the engine drop stored results from memory (`evict`) and read them back
 * (`hydrate`, `getStepResultAsync`).
 *
 * Step results are replaced, never edited in place, so a step changed when its object
 * differs from the one last written. State can be edited in place, so the journal keeps a
 * JSON copy of the state it last wrote and diffs the live state against it. A change is written
 * as a patch, unless the patches written since the latest full state would outgrow the state:
 * then the full state is written again, so reading the state back never replays more than
 * about twice its size. A step result that is rewritten before it succeeds (a running foreach
 * recording its finished items) is written the same way, as a `step-patch` on the result last
 * written, once it has been written twice.
 *
 * The start writes of a parallel or branch block's steps are in flight at the same time, and
 * the store can commit them in any order. If two of them carried the same step, the older value
 * could commit last while the journal believes storage holds the newer one, and it never resends
 * what it believes is stored. So a write that can overlap others names its steps (`stepIds`) and
 * sends only those, and overlapping writes name different steps. Everything else (other steps'
 * changes, the state, the checkpoint) goes out with boundary writes, which the engine makes only
 * when no other write of the run is in flight (an entry's end, a loop iteration's start, a
 * finished parallel arm or foreach item, sleeps, the run stopping). `write` throws when a write
 * breaks that.
 *
 * @internal
 */
export declare class RunJournal {
    #private;
    /** Undefined when Mastra has no storage: nothing is written, so nothing is evicted. */
    readonly store: WorkflowsStorage | undefined;
    readonly workflowName: string;
    readonly runId: string;
    /**
     * The run's `lastSeq` once its execution has ended (`close`) and every write and draft sent has
     * settled: the version a read of its stored steps must still find to see what the execution left.
     * Undefined when the run wasn't loaded and nothing was stored.
     */
    readonly settledLastSeq: Promise<number | undefined>;
    readonly settledRunToken: Promise<string | undefined>;
    /**
     * @param seed The step results already in storage (a resumed or restarted run's loaded snapshot
     * context). Without it, the first boundary write is a checkpoint that replaces whatever is stored.
     * @param state The state already in storage, with `seed`.
     * @param storedState What the store reported for `state`: its `lastSeq`, `statePatchBytes` and `statePatchCount`.
     * @param inherited For a nested run that starts from a version of its parent's state (the parent
     * journal's `baseFor`): the checkpoint stores that version as the base, and only the changes to it.
     * @param resumed Set for a resume: the run's new drive starts from `storedState`, which the first
     * append records as the run's `startStateSeq`.
     */
    constructor({ store, workflowName, runId, seed, state, storedState, inherited, resumed, }: {
        store: WorkflowsStorage | undefined;
        workflowName: string;
        runId: string;
        seed?: Record<string, unknown>;
        state?: unknown;
        storedState?: {
            seq: number;
            patchBytes: number;
            patchCount: number;
            runToken?: string;
        };
        inherited?: StateBase;
        resumed?: boolean;
    });
    /**
     * A stored version of this run's state, for a nested run starting from `state` to build on: the
     * stored state or the latest draft when `state` matches it, else a new draft of `state` (a patch
     * on the latest version, or the full state once the draft patches would outgrow it). Undefined
     * when there is nothing to build on (no store, the run isn't stored, a state that isn't JSON).
     *
     * Drafts don't change the run's state, so a restart never reads them: they only hold the live
     * state that a block's earlier steps changed, so the nested runs of a foreach or a loop each store
     * only their own changes.
     */
    baseFor(state: unknown): Promise<StateBase | undefined>;
    /**
     * Called when the run's execution ends. A step of a parallel or branch block can still be
     * running then (the block's `Promise.all` rejects on the first failure), and its write is dropped.
     */
    close(): void;
    /**
     * @param stepIds Set by a write that can be in flight together with other writes of the run (a
     * step's start write): only these steps are sent, never the state, and no other write in flight
     * may name them. Leave it unset for a boundary write, made when no other write of the run is in
     * flight (an entry's end, a loop iteration's start, a finished parallel arm or foreach item,
     * sleeps, the run stopping): it sends every step result that changed since it was last written,
     * the state's changes, and the checkpoint when that is still to do.
     * @param foreachItems Set by a running foreach's progress write: the foreach's result differs
     * from the one it last wrote only by these indices' `metadata.foreachProgress` entries. When the
     * last written result can be patched, only those entries are sent, so recording a finished item
     * costs that item rather than every item finished so far.
     * @param expectedStatus Sent with the write as the store's compare-and-set guard on the stored status.
     * @returns False when the store rejected the write because of `expectedStatus`. Nothing was
     * stored, as with a write that throws.
     */
    write({ resourceId, snapshot, stepIds, foreachItems, expectedStatus, }: {
        resourceId?: string;
        snapshot: WorkflowRunState;
        stepIds?: readonly string[];
        foreachItems?: {
            stepId: string;
            indices: readonly number[];
        };
        expectedStatus?: WorkflowRunStatus[];
    }): Promise<boolean>;
    /**
     * Replace stored successful results with stubs, except `input` and the steps in `keep`.
     * Only results that are exactly what was last written are replaced, so nothing the store
     * doesn't have is dropped.
     */
    evict(stepResults: StepResults, keep: readonly string[]): void;
    /** Whether `result` is what the store holds for `stepId`, as of the writes that have settled. */
    isStored(stepId: string, result: unknown): boolean;
    /** Swap the stubs among `stepIds` back for their stored results, with one read. */
    hydrate(stepResults: StepResults, stepIds?: readonly string[]): Promise<void>;
    /** `getStepResultAsync` for step code: reads an evicted step from storage first. */
    getStepResultAsync(stepResults: StepResults, step: unknown): Promise<any>;
}
/**
 * `getStepResult` over step results that may hold stubs: a stubbed step is read back with
 * `hydrate` first. The result stays in `stepResults`, so later reads of it are free.
 *
 * @internal
 */
export declare function getHydratedStepResult(stepResults: StepResults, step: unknown, hydrate: (stepIds: string[]) => Promise<unknown>): Promise<any>;
/**
 * The `getStepResult` / `getStepResultAsync` pair handed to step code. On storage v2
 * runs, sync `getStepResult` throws: their step results won't always be in memory.
 *
 * @internal
 */
export declare function buildStepResultAccessors(engine: {
    getRunJournal(runId: string): RunJournal | undefined;
}, runId: string, stepResults: StepResults): {
    getStepResult: (step: any) => any;
    getStepResultAsync: (step: any) => Promise<any>;
};
/**
 * The accessor pair for step code in a storage v2 run: sync `getStepResult` throws, as the run's
 * step results won't always be in memory, and points to `getStepResultAsync`.
 *
 * @internal
 */
export declare function storageV2StepResultAccessors(getStepResultAsync: (step: unknown) => Promise<any>): {
    getStepResult: (step: any) => never;
    getStepResultAsync: (step: any) => Promise<any>;
};
/**
 * Swaps the stubs among `stepIds` back for the run's stored results, with one read.
 *
 * @returns The stored results put in, by step id.
 * @internal
 */
export declare function hydrateStepResults(run: {
    runId: string;
    loadSteps: (stepIds: string[]) => Promise<StepResults | null | undefined>;
}, stepResults: StepResults, stepIds?: readonly string[]): Promise<Map<string, StepResult<any, any, any, any>>>;
/**
 * The `steps()` of a storage v2 run's result: its step results as the execution left them, formatted
 * by `format`. The successful results the journal evicted are read from storage on the first call,
 * with one read shared by concurrent calls; the read fails if the run was written to since its
 * execution ended (e.g. resumed or restarted), since storage then no longer holds what the result
 * describes. A failed read isn't cached, so a later call retries.
 *
 * Holds the stubs and the results that weren't evicted until the run's writes settle; then the
 * stored successful results are evicted too, so it holds only stubs, `input` and the results a
 * reader needs without loading (suspended, failed, running). Call it after the run's last write is
 * sent, and close the journal before anything awaits the loader.
 *
 * @internal
 */
export declare function lazyStepResults(journal: RunJournal, stepResults: StepResults, format: (stepResults: StepResults) => StepResults): () => Promise<StepResults>;
/**
 * The `steps()` of a storage v2 result reconstructed from stored state. Holds successful-step
 * stubs and hydrates them on the first call while the stored run identity and `lastSeq` still match.
 *
 * @internal
 */
export declare function loadedStepResults({ store, workflowName, runId, lastSeq, runToken, }: {
    store: WorkflowsStorage;
    workflowName: string;
    runId: string;
    lastSeq: number;
    runToken?: string;
}, stepResults: StepResults, format: (stepResults: StepResults) => StepResults): () => Promise<StepResults>;
/**
 * The `steps()` of a storage v2 result that already holds every step result, so it reads none
 * from storage: an evented run's, whose finish event carries them all.
 *
 * @internal
 */
export declare function residentStepResultsLoader(stepResults: StepResults): () => Promise<StepResults>;
/**
 * The step results a storage v2 result's `steps` loader holds without reading storage: every result
 * but the successful ones that were evicted, which are stubs. Undefined for anything else (a v1
 * result's `steps` record). For the engine's own reads of a nested run's suspended and failed steps.
 *
 * @internal
 */
export declare function residentStepResults(steps: unknown): StepResults | undefined;
/**
 * Every step result of a run's result: a storage v2 result's `steps` loader is called, a v1
 * result's record returned as is. For the framework's readers that hand all of them on.
 *
 * @internal
 */
export declare function loadStepResults(steps: unknown): Promise<StepResults>;
export {};
//# sourceMappingURL=run-journal.d.ts.map