/**
 * Execution fence for DurableAgent runs (#23734).
 *
 * Every execution that drives a durable run (`stream()`, `generate()`,
 * `resume()`, `recover()`) claims the run under a fresh execution id.
 * `recover()` claims only a run nobody holds; `recover({ force: true })` takes
 * the claim over immediately, so a still-running original execution is
 * superseded without waiting for a TTL. The original checks its claim at
 * every step boundary and before its terminal writes, and stops instead of
 * overwriting the recovered answer.
 *
 * Ownership lives in one of two places:
 *
 * - Storage, when the workflows store supports run fencing. The store keeps a
 *   per-run owner record whose generation goes up on every claim. The memory
 *   store is raised to the same generation. Writes that carry the claim's
 *   fence are rejected by storage once a newer claim exists, which closes the
 *   gap between a check and the write it guards.
 * - A pubsub lease otherwise. This gives liveness only: a window of
 *   milliseconds remains between a successful check and the write it guards.
 *   With `NoopLeaseProvider` every check passes, which preserves the previous
 *   single-process behavior.
 */
import { ErrorCategory, ErrorDomain, MastraNonRetryableError } from '../../error/index.js';
import type { LeaseProvider, PubSub } from '../../events/pubsub.js';
import type { IMastraLogger } from '../../logger/index.js';
import type { Mastra } from '../../mastra/index.js';
import type { RunScopeKey } from '../../mastra/run-scope.js';
import type { RequestContext } from '../../request-context/index.js';
import type { MemoryStorage } from '../../storage/domains/memory/base.js';
import type { WorkflowsStorage } from '../../storage/domains/workflows/base.js';
import type { RunFence, RunFenceScope } from '../../storage/run-fencing.js';
import { MASTRA_DURABLE_EXECUTIONS_KEY } from '../request-context-snapshot.js';
import { ExecutionOwnershipGuard } from './execution-ownership-guard.js';
/** Execution lease timing follows the agent thread lease (`MASTRA_AGENT_THREAD_LEASE_TTL_MS`). */
export declare const EXECUTION_LEASE_TTL_MS: number;
export declare const EXECUTION_LEASE_RENEW_INTERVAL_MS: number;
export { MASTRA_DURABLE_EXECUTIONS_KEY };
export declare const EXECUTION_SUPERSEDED_ERROR_ID = "DURABLE_AGENT_EXECUTION_SUPERSEDED";
export declare const EXECUTION_UNVERIFIED_ERROR_ID = "DURABLE_AGENT_EXECUTION_UNVERIFIED";
export declare const EXECUTION_ABANDONED_ERROR_ID = "DURABLE_AGENT_EXECUTION_ABANDONED";
export declare const EXECUTION_CONFLICT_ERROR_ID = "DURABLE_AGENT_EXECUTION_CONFLICT";
export declare const RECOVER_RUN_ACTIVE_LOCALLY_ERROR_ID = "DURABLE_AGENT_RECOVER_RUN_ACTIVE_LOCALLY";
export declare const RUN_ACTIVE_ERROR_ID = "DURABLE_AGENT_RUN_ACTIVE";
type ExecutionLossErrorId = typeof EXECUTION_SUPERSEDED_ERROR_ID | typeof EXECUTION_UNVERIFIED_ERROR_ID | typeof EXECUTION_ABANDONED_ERROR_ID;
type ExecutionDetails = {
    agentId: string;
    runId: string;
    executionId: string;
};
/**
 * Thrown when an execution can no longer prove it owns its run. Extends
 * `MastraNonRetryableError` so the workflow engine fails the step instead of
 * retrying it.
 */
export declare class DurableExecutionFenceError extends MastraNonRetryableError {
    readonly id: ExecutionLossErrorId;
    readonly domain = ErrorDomain.AGENT;
    readonly category = ErrorCategory.SYSTEM;
    readonly details: ExecutionDetails;
    constructor(id: ExecutionLossErrorId, details: ExecutionDetails, cause?: unknown);
}
/**
 * Whether `error` (or anything in its cause chain) reports that an execution
 * lost ownership, including storage rejecting one of its writes. Matches on
 * `id` so serialized errors from the evented engine and wrappers such as the
 * nested-workflow `MastraNonRetryableError` match too.
 */
export declare function isExecutionFenceError(error: unknown): boolean;
export declare function executionLeaseKey(agentId: string, runId: string): string;
/**
 * Resolve the lease backend behind a pubsub. `CachingPubSub` exposes its
 * inner's capability through `getLeaseProvider()`; backends without leasing
 * fall back to the always-win {@link NoopLeaseProvider}.
 */
export declare function resolveLeaseProvider(pubsub: PubSub | undefined): LeaseProvider;
/**
 * Whether a store implements run fencing. Tolerates stores built against an
 * older contract. Rejects when the store can't tell yet.
 */
export declare function supportsRunFencing(store: WorkflowsStorage | MemoryStorage | undefined): Promise<boolean>;
/**
 * Generation of the latest storage claim on a run, which is what the claiming
 * execution tags its stream events with. Undefined when storage holds no claim
 * for the run, including runs fenced by a pubsub lease, whose events carry no
 * generation.
 */
export declare function readRunGeneration(mastra: Mastra | undefined, runId: string): Promise<number | undefined>;
/** The claim an execution holds on a run, as carried on its RequestContext. */
export interface DurableExecutionClaim {
    executionId: string;
    /** Resolves the same lease backend on an evented worker. */
    agentId?: string;
    /** Storage claim generation. Absent when ownership is a pubsub lease. */
    generation?: number;
    /** Whether the memory store was raised to this claim's generation. */
    memoryFenced?: boolean;
    /** The existing thread lease to renew with this run's claim. */
    threadId?: string;
    resourceId?: string;
}
export declare function getExecutionClaim(requestContext: RequestContext | undefined, runId: string): DurableExecutionClaim | undefined;
type ExecutionParentWorkflow = {
    runId: string;
    parentWorkflow?: ExecutionParentWorkflow;
};
/** Select only the delivering run or its nearest explicitly declared workflow ancestor. */
export declare function getExecutionClaimScope(requestContext: RequestContext, runId: string, parentWorkflow?: ExecutionParentWorkflow): {
    runId: string;
    claim: DurableExecutionClaim;
    nestedRunIds: string[];
} | undefined;
export declare function isStorageFencedExecution(requestContext: RequestContext, runId: string, parentWorkflow?: ExecutionParentWorkflow): boolean;
/**
 * Whether a serialized request context (as carried on evented run events)
 * holds a claim on a run that `requestContext` also claims, under a different
 * execution. Missing claims on either side count as the same execution.
 */
export declare function isForeignExecutionContext(eventRequestContext: unknown, requestContext: RequestContext): boolean;
export declare function setExecutionClaim(requestContext: RequestContext, runId: string, claim: DurableExecutionClaim): void;
/**
 * The storage fence for writes `runId` makes to `domain`, or `undefined` when
 * that domain's writes are not fenced for this run.
 */
export declare function getRunFence(requestContext: RequestContext | undefined, runId: string, domain: 'workflows' | 'memory'): RunFence | undefined;
/**
 * Liveness of a run that has no ownership claim, such as one started by a
 * version that predates run ownership.
 */
export interface UntrackedRunLiveness {
    isLive(): Promise<boolean>;
    /** Upper bound on how long the signal behind `isLive` stays up after the run dies. */
    ttlMs: number;
}
export type ExecutionSettlement = 'owned' | 'orphaned' | 'superseded';
export declare const DURABLE_PARTICIPANT_FENCES: RunScopeKey<Map<string, ExecutionFence>>;
/**
 * One execution's claim on a durable run. Inside {@link ExecutionFence.run},
 * it is the {@link RunFenceScope} that fences every write the execution makes
 * to the run's workflows and memory stores.
 */
export declare class ExecutionFence implements RunFenceScope {
    #private;
    readonly executionId: string;
    readonly agentId: string;
    readonly runId: string;
    /** Storage claim generation. Absent when ownership is a pubsub lease. */
    readonly generation?: number;
    /** Resolves once {@link settle} has finished and the claim is released or left to its new holder. */
    readonly whenSettled: Promise<void>;
    /** Set only by the winning total-deadline settlement, for late stream readers. */
    deadlineError?: Error;
    private constructor();
    /**
     * Claim the run.
     *
     * - `acquire` (stream/generate/resume) fails with
     *   `DURABLE_AGENT_EXECUTION_CONFLICT` while another execution holds it.
     * - `recover` (recover) claims a run nobody holds, and fails with
     *   `DURABLE_AGENT_RUN_ACTIVE` while the run is live: it has a live claim,
     *   or it has none and `untrackedRun` reports it live.
     * - `takeover` (recover with `force`) moves the claim from its current
     *   holder to this execution immediately, superseding it.
     *
     * Ownership lives in `workflowsStore` when it supports run fencing, and in
     * `leaseProvider` otherwise.
     */
    static claim(args: {
        leaseProvider: LeaseProvider;
        workflowsStore?: WorkflowsStorage;
        agentId: string;
        runId: string;
        mode: 'acquire' | 'recover' | 'takeover';
        untrackedRun?: UntrackedRunLiveness;
        logger?: IMastraLogger;
    }): Promise<ExecutionFence>;
    /**
     * Release only the captured claim; a successor is never affected. `settled`: the run's root settled, so a renewal
     * this process's fences of the execution still have in flight is answered by the release, not a takeover.
     * `abandoned`: nothing settled the run, and a live coordinator must see the loss.
     */
    static releaseSharedClaim(mastra: Mastra, runId: string, claim: DurableExecutionClaim, reason: 'settled' | 'abandoned'): Promise<void>;
    /** Join an existing claim without acquiring ownership or advancing its generation. */
    static follow(mastra: Mastra, runId: string, claim: DurableExecutionClaim): Promise<ExecutionFence | undefined>;
    /**
     * The unsettled execution this process is running for `runId`, if any.
     */
    static getLocalActive(runId: string): ExecutionFence | undefined;
    /** The claim to carry on the run's RequestContext. */
    get claim(): DurableExecutionClaim;
    isLost(): boolean;
    get settlement(): ExecutionSettlement | undefined;
    /** An owned deadline settlement revokes writes without handing its topics to another execution. */
    ownsRunTopics(): boolean;
    /** Throw the loss error once this execution lost the run. Checks local state only. */
    throwIfLost(): void;
    /**
     * Call `listener` once when this execution loses the run: a check or
     * renewal failed, or storage rejected one of its writes. Called right away
     * when the run is already lost.
     */
    onLost(listener: (error: DurableExecutionFenceError) => void): () => void;
    /**
     * Run `fn` with this fence carried by every write it makes to the run's
     * workflows and memory stores, including writes from processors, tools and
     * memory that never see the fence.
     */
    run<T>(fn: () => T): T;
    /**
     * {@link RunFenceScope.fenceFor}: covers the workflows rows of this run and
     * its nested runs, and the memory store raised to the claim.
     */
    fenceFor(store: object, runId?: string): RunFence | undefined;
    /** {@link RunFenceScope.coverNestedRun} */
    coverNestedRun(parentRunId: string, nestedRunId: string): void;
    /** {@link RunFenceScope.generationFor} */
    generationFor(runId: string): number | undefined;
    /**
     * {@link RunFenceScope.onConflict}: storage rejected one of this execution's
     * writes, even if the writer swallowed the error. Settlement still asks the
     * workflows record whether another execution took the run.
     */
    onConflict(fence: RunFence): void;
    /**
     * Raise the run's memory store to this claim's generation, so memory writes
     * carrying the claim are rejected once a newer claim raises it further.
     * Call before the execution writes to memory. A no-op for lease-backed
     * claims and for memory stores without run fencing.
     */
    coverMemory(store: MemoryStorage | undefined): Promise<void>;
    /**
     * Prove this execution still owns the run before a write. Throws a
     * {@link DurableExecutionFenceError} once ownership is lost; a lost fence
     * never recovers.
     */
    verify(): Promise<void>;
    /**
     * {@link verify} for writes that may land after settlement, such as a
     * background task's result or suspension: refuses only once another
     * execution claimed the run. A released or lapsed claim still passes, as
     * storage accepts the claim's writes until the next claim, and the write's
     * own fence ({@link runFencedToClaim}) rejects it once a successor raised
     * memory. Never waits for a release in flight.
     *
     * Only storage-backed claims get this rule: their generation tells a
     * released claim from one a successor claimed, released or not. A lease
     * keeps no record once released, so an empty lease can't tell this claim's
     * release from a successor that claimed and released it since, and nothing
     * fences the write behind it. A lease-backed claim always gets {@link verify}.
     */
    verifyNotSuperseded(): Promise<void>;
    stopHeartbeat(): void;
    /** Cancel only this worker's invocations, keeping the shared claim valid for survivors. */
    interruptParticipant(): void;
    /**
     * End this execution exactly once and release the claim unless another
     * execution holds it. `whileOwned` (the terminal writes) runs only when the
     * execution still owns the run. Later calls resolve to the first settlement
     * without running their `whileOwned`.
     *
     * Release keeps the owner record, so a write the execution makes after
     * settling is still rejected once a newer claim exists. An owned execution
     * stops fencing its writes after settling, leaving late background work to
     * land as it did before fencing. With `interrupt`, the old claim is fenced
     * out before terminal writes run under a temporary replacement claim.
     *
     * - `owned`: ownership verified; `whileOwned` ran.
     * - `orphaned`: ownership could not be verified, but nobody else claimed
     *   the run, so the failure can still be reported to this execution's caller.
     * - `superseded`: another execution holds the run (or its holder is
     *   unknown); nothing may be written on its topic or rows.
     */
    settle(whileOwned: () => Promise<void>, interrupt?: boolean): Promise<ExecutionSettlement>;
    /** Detach a coordinator without changing the claim shared with remote workers. */
    detach(): void;
    /**
     * Stop this execution without finishing the run, for a process that is
     * shutting down. The execution loses the run at once, so it aborts and
     * writes nothing more, and the claim is released so recovery can take the
     * run right away instead of waiting for it to expire. With ownership in
     * storage, the run is first claimed past this execution, so storage rejects
     * writes that were already on their way. Settles as `superseded`.
     *
     * A no-op once the execution has settled or lost the run.
     */
    abandon(): Promise<void>;
    /**
     * The error to give this execution's caller once it lost the run: superseded when another execution holds the run,
     * otherwise unverified. `undefined` while the run is still held, or when this process gave the run up itself.
     */
    callerLossError(): Promise<DurableExecutionFenceError | undefined>;
}
/**
 * Watch for this process's execution of `runId` losing the run, and report it with the error its caller should see.
 * A finishing worker releases the claim right after publishing its finish, so the loss is only reported if no finish
 * stopped the watch within a renewal interval.
 */
export declare function watchExecutionLoss(requestContext: RequestContext, runId: string, onLost: (error: DurableExecutionFenceError) => void): () => void;
/**
 * `pubsub` as seen by the execution holding `fence`. Once the execution
 * loses the run, its publishes are dropped: the run's topics are shared with
 * the new owner's consumers. Every call runs outside the run's fence scope,
 * so connections and subscriptions opened lazily here never carry the run's
 * fence into deliveries for other runs.
 */
export declare function fencePubSub(pubsub: PubSub, fence: Pick<ExecutionFence, 'isLost'>): PubSub;
/**
 * Test-only: forget every local execution, as a process crash would. Their
 * claims stop renewing, and executions still running keep their fence objects
 * but no longer count as local. `recover()` in the same process then treats
 * their runs as another process's: refused while a claim is live, recoverable
 * once it lapses.
 */
export declare function __resetExecutionFencesForTests(): void;
/**
 * Assert that the execution recorded in `requestContext` for `runId` still
 * owns the run. No-op for runs without a claim (started by code without
 * fencing). Uses the local fence when this process drives the run; otherwise
 * (a remote evented worker) checks the claim where it lives.
 */
export declare function assertExecutionOwned(args: {
    runId: string;
    agentId: string;
    requestContext: RequestContext | undefined;
    mastra: Mastra | undefined;
}): Promise<void>;
/**
 * {@link assertExecutionOwned} for writes that may land after the execution
 * settled, such as a background task's result. Once the claim is released,
 * the write is accepted until another execution claims the run, as storage
 * accepts the released claim's writes.
 */
export declare function assertExecutionNotSuperseded(args: {
    runId: string;
    agentId: string;
    requestContext: RequestContext | undefined;
    mastra: Mastra | undefined;
}): Promise<void>;
/**
 * {@link assertExecutionNotSuperseded} for a claim with a storage generation,
 * {@link assertExecutionOwned} for one without. For writes that refused a
 * released claim before late writes were accepted, such as a background
 * task's suspension: only a generation tells this claim's release from
 * another execution that claimed and released the run since, and a
 * lease-backed write has no storage fence behind it (#30182).
 */
export declare function assertExecutionNotSupersededInStorage(args: Parameters<typeof assertExecutionNotSuperseded>[0]): Promise<void>;
/**
 * Run `fn` with its writes to `memoryStore` carrying the memory fence of the
 * claim `requestContext` holds for `runId`, also once that execution settled
 * and stopped fencing its own writes. For writes that may land after the run
 * finished, such as a background task's suspension: an ownership check before
 * the write can't see a successor that claims the run while the write is on
 * its way, but storage rejects the write once that successor raised the memory
 * fence. Runs `fn` unchanged when the claim never raised memory (lease-backed
 * claims, memory stores without run fencing). Other writes keep the fence of
 * the enclosing scope.
 */
export declare function runFencedToClaim<T>(args: {
    requestContext: RequestContext | undefined;
    runId: string;
    /** Resolves the memory store the claim raised; called only when it raised one. */
    memoryStore: () => Promise<object | undefined>;
}, fn: () => Promise<T>): Promise<T>;
/**
 * Reject a superseded claim without verifying or mutating the local fence, so a late reader
 * can settle after its execution releases the claim. Does not require an active lease;
 * skips the check when no ownership backend is available.
 */
export declare function assertExecutionGenerationCurrent(args: {
    runId: string;
    agentId: string;
    mastra: Mastra | undefined;
    claim: DurableExecutionClaim;
}): Promise<void>;
export declare function getExecutionOwnershipGuard(params: object): ExecutionOwnershipGuard | undefined;
type FenceableStep = {
    execute: (params: any) => Promise<any>;
};
/**
 * Check ownership before a step starts (skipping duplicate model, tool, or
 * scorer work after a takeover) and again after it returns. The post-check
 * throws inside `execute`, so the engine records the step as failed instead
 * of persisting a `running` snapshot over the new owner's state.
 */
export declare function withExecutionFence<TStep extends FenceableStep>(step: TStep): TStep;
//# sourceMappingURL=execution-fence.d.ts.map