import type { PubSub } from '../events/pubsub.js';
import { RequestContext } from '../request-context/index.js';
import type { MastraModelOutput } from '../stream/base/output.js';
import type { Agent } from './agent.js';
import type { AgentExecutionOptions } from './agent.types.js';
import type { MessageListInput } from './message-list/index.js';
import type { PendingSignalListener, AgentMessageInput, AgentStateSignalInput, CreatedAgentSignal } from './signals.js';
import type { AgentAbortThreadOptions, AgentClaimThreadPeerOptions, AgentSignal, AgentSubscribeToThreadOptions, AgentThreadIdentityOptions, AgentThreadPeerAdvertisement, AgentThreadSubscription, AgentUpdateThreadPeerOptions, DiscoverAgentThreadPeersOptions, CancelQueuedAgentMessagesOptions, CancelQueuedAgentMessagesResult, AgentThreadEventListener, SubscribeAgentThreadEventsOptions, QueueAgentMessageOptions, QueueAgentMessageResult, QueueAgentSignalOptions, QueueAgentSignalResult, SendAgentMessageOptions, SendAgentMessageResult, SendAgentSignalOptions, SendAgentSignalResult, SendAgentStateSignalOptions, SendAgentStateSignalResult } from './types.js';
/** @internal Distinguishes temporary handover tokens from qualified execution owners. */
export declare function isRetakeLeaseOwner(owner: string | undefined): boolean;
export declare const AGENT_THREAD_LEASE_CONFLICT_CODE = "AGENT_THREAD_LEASE_CONFLICT";
export declare class AgentThreadLeaseConflictError extends Error {
    readonly code = "AGENT_THREAD_LEASE_CONFLICT";
    constructor(runId: string, owner: string);
}
/** The `reason` an `abort` chunk carries when its run stopped because another run holds its thread lease. */
export declare const THREAD_LEASE_LOST_ABORT_REASON = "thread-lease-lost";
export declare class AgentThreadLeaseLostError extends Error {
    constructor(runId: string);
}
export declare let defaultAgentThreadPubSub: PubSub;
type AgentThreadRunLifecycle = 'running' | 'suspending' | 'suspended' | 'completed' | 'failed' | 'aborted';
type AgentThreadRunSuspension = {
    toolCallId?: string;
    toolName?: string;
    kind: 'approval' | 'generic-tool';
};
type AgentThreadRunContinuation<OUTPUT = unknown> = {
    sourceOutput: MastraModelOutput<OUTPUT>;
    canContinue: () => boolean;
    didPublishTerminal: () => boolean;
};
type AgentThreadRunRecord<OUTPUT = unknown> = {
    agent: Agent<any, any, any, any>;
    /** The source output that owns the subscriber-facing broadcast. */
    output: MastraModelOutput<OUTPUT>;
    /** The latest execution segment attached to a suspension-spanning broadcast. */
    currentSegmentOutput?: MastraModelOutput<OUTPUT>;
    runId: string;
    streamId: string;
    streamSeq: number;
    /** Claim generation of the durable execution producing this stream, if fenced. */
    generation?: number;
    /** Registered by a recovering process: the run's streams under earlier generations are superseded. */
    supersedes?: boolean;
    /** See {@link AgentThreadRunClaim.ownershipLost}. */
    ownershipLost?: () => boolean;
    /** See {@link AgentThreadRunClaim.stepOwner}. */
    stepOwner?: () => object | undefined;
    /**
     * The abort controller of the run's last prepared segment, kept once that segment is cleaned up: a step raising a
     * suspension can end the segment while a sibling tool call of the same step still executes under it.
     */
    segmentAbortController?: AbortController;
    /** This process read the record's own `run-registered` back from the thread topic. */
    registrationSeen?: boolean;
    /** Another process registered the run after this record did, so it executes the run now. */
    registeredElsewhere?: boolean;
    /**
     * This record's retake gave up while its handoff was still in flight, so that handoff may yet install the run id
     * on a lease nothing here renews. Ending must leave such a lease to expire rather than release a successor's.
     * Kept on the record, not on the run id: a later execution reusing the id owns its own lease again.
     */
    lateRetakeHandoff?: boolean;
    /** The owner this record took the thread lease under. Ending releases only this owner. */
    leaseOwner?: string;
    /** Registration did not get the thread lease, so ending must not release whichever owner holds it. */
    leaseNotAcquired?: boolean;
    lifecycle: AgentThreadRunLifecycle;
    suspensions?: Map<string | undefined, AgentThreadRunSuspension>;
    /** When the record was parked as suspended (ms epoch); drives the TTL sweep. */
    suspendedAt?: number;
    threadId: string;
    resourceId?: string;
    streamOptions: AgentExecutionOptions<OUTPUT>;
    createSubscriberStream?: () => ReadableStream<unknown>;
    /** Settles once every stream-part broadcast publish for this run completed. */
    broadcastFinished?: Promise<void>;
    /** Present only while the broadcast may accept resumed execution segments. */
    continuation?: AgentThreadRunContinuation<OUTPUT>;
};
type ClaimedThreadOwnerStreamOptions = AgentExecutionOptions<any> | (() => AgentExecutionOptions<any> | Promise<AgentExecutionOptions<any>>);
export type AgentThreadState = 'active' | 'idle';
export type ActiveThreadRun = {
    runId: string;
    resourceId?: string;
    threadId: string;
};
type AgentThreadRunContinuationMode = 'across-suspension';
/** The durable execution claim producing a run, when the run is fenced. */
type AgentThreadRunClaim = {
    /**
     * Whether the execution producing the run lost its claim to another
     * execution. That execution holds the run's thread lease under the same
     * runId, so a run that ends after losing its claim leaves the lease alone
     * and leaves the follow-ups queued for it to the run's next execution.
     */
    ownershipLost?: () => boolean;
    /**
     * The object a durable run's steps mark themselves running under (its registry entry). A run that loses its
     * thread lease lets those steps finish before it stops; a run this runtime prepared uses its own abort signal.
     */
    stepOwner?: () => object | undefined;
};
export type AgentThreadStrictRegistrationOptions = AgentThreadRunClaim & {
    strict: true;
    continuation?: AgentThreadRunContinuationMode;
    /**
     * Revalidates ownership held outside this runtime (for example, a durable
     * recovery lease). A validation failure rolls back local registration but
     * deliberately leaves the same-run thread lease intact for the new owner.
     */
    validate?: () => void | Promise<void>;
    /**
     * Claim generation of the durable execution producing this run. A recovering
     * process strictly re-registers the run under a later generation, and
     * subscribers stop following the run's streams under earlier generations.
     */
    generation?: number;
};
type AgentThreadStreamRegistrationOptions = AgentThreadRunClaim & {
    strict?: false;
    continuation?: AgentThreadRunContinuationMode;
    /**
     * Claim generation of the durable execution producing this run. Stamped on
     * the stream; unlike a strict registration's, it supersedes nothing — a
     * resume claims a later generation but follows a cleanly suspended half.
     */
    generation?: number;
};
export type AgentThreadRunRegistration = {
    /**
     * Remove this exact registration. Callers that lost an external ownership
     * claim can preserve the same-run thread lease for its successor.
     */
    rollback(options?: {
        releaseLease?: boolean;
    }): Promise<void>;
};
export declare class AgentThreadStreamRuntime {
    #private;
    /**
     * Whether `runId` still holds its thread's lease, which it renews for as
     * long as it is live in some process. `false` without a lease backend.
     * Throws when the backend can't answer.
     */
    isRunHoldingThreadLease(pubsub: PubSub | undefined, runId: string, threadId: string, resourceId?: string): Promise<boolean>;
    /** @internal Qualify a shared thread lease before dispatching this execution. */
    claimDurableThreadLease(pubsub: PubSub, runId: string, threadId: string, resourceId: string | undefined, generation: number | undefined, executionId?: string): Promise<void>;
    /** @internal Renew only the captured execution's thread lease; never acquire or transfer it. */
    renewDurableThreadLease(pubsub: PubSub, runId: string, threadId: string, resourceId?: string, generation?: number, executionId?: string): Promise<boolean>;
    /**
     * @internal Renew the captured execution's thread lease, or take it back if it lapsed and nobody else holds it.
     * Only for an execution whose run ownership was just verified: a lease that expired while Redis was unreachable
     * (e.g. restarting) otherwise fences every redelivery of the run forever. Never takes a lease another owner holds.
     */
    reclaimDurableThreadLease(pubsub: PubSub, runId: string, threadId: string, resourceId?: string, generation?: number, executionId?: string): Promise<boolean>;
    /** @internal Whether `error` from the thread lease backend means it is refusing every client, not just this one. */
    isThreadLeaseBackendUnavailableToAll(pubsub: PubSub, error: unknown): boolean;
    /** @internal Release only the terminal execution's thread lease, never a recovered successor's. */
    releaseDurableThreadLease(pubsub: PubSub, runId: string, threadId: string, resourceId?: string, generation?: number, executionId?: string): Promise<void>;
    /** @internal Stop this process renewing an abandoned execution's thread lease, then release it. */
    abandonDurableThreadLease(pubsub: PubSub, runId: string, threadId: string, resourceId?: string, generation?: number, executionId?: string): Promise<void>;
    /**
     * The run holding the thread's lease, wherever it executes. Lets a process
     * that never saw a thread's run find it. `undefined` without a lease backend
     * or when no run holds the lease; rejects when the backend can't answer
     * within one renewal interval.
     */
    getThreadLeaseOwnerRunId(pubsub: PubSub | undefined, options: AgentThreadIdentityOptions): Promise<string | undefined>;
    /**
     * Ask whichever process runs `runId` on the thread to stop it, clearing the
     * thread's queued input there when requested. For a run found through the
     * thread lease: the owner clears input only while that run still holds it.
     */
    requestThreadRunAbort(pubsub: PubSub | undefined, options: AgentThreadIdentityOptions & {
        clearPendingSignals?: boolean;
    }, runId: string): Promise<void>;
    /** How long a thread lease outlives the process that stopped renewing it. */
    get threadLeaseTtlMs(): number;
    /**
     * @internal Hand back the thread runs a shutting-down Mastra (`owner`) still holds on `pubsub`. Observers in other
     * processes follow each run until its terminal event and watch its thread lease meanwhile; a process that exits
     * without either leaves them waiting for the lease to lapse and then failing the run as having lost its lease,
     * and leaves the thread blocked until then.
     *
     * A run still executing here is aborted and gets up to `abortGraceMs` to stop. A run parked on a suspension is
     * announced as `run-suspended`, so it stays resumable; any other run as an unpersisted `run-completed`. Each lease
     * is released only after that event is published, so no observer finds the thread free while the run still looks
     * live there. A run that hasn't stopped within the grace, such as one whose tool call ignores the abort, keeps its
     * lease until it expires, and its remaining tool calls fail. Every lease renewal
     * of the owner's runs stops, whether or not the run still held its thread. A run `executesElsewhere` reports as
     * executed by another process is left to that process, lease included.
     */
    shutdown(pubsub: PubSub | undefined, owner: unknown, { abortGraceMs, executesElsewhere, }: {
        abortGraceMs: number;
        executesElsewhere?: (runId: string) => boolean;
    }): Promise<void>;
    getThreadState(options: {
        resourceId?: string;
        threadId: string;
    }, pubsub?: PubSub): AgentThreadState;
    claimThreadOwnership<OUTPUT = unknown>(agent: Agent<any, any, any, any>, options: {
        resourceId: string;
        threadId: string;
        streamOptions?: ClaimedThreadOwnerStreamOptions;
        peer?: false | AgentClaimThreadPeerOptions;
        yieldOwnership?: () => boolean;
        onOwnershipYielded?: () => void;
        onOwnershipLost?: () => void;
    }, pubsub?: PubSub): Promise<{
        claimed: boolean;
        unsubscribe: () => void;
    }>;
    updateThreadPeerAdvertisement(agent: Agent<any, any, any, any>, options: {
        resourceId: string;
        threadId: string;
        peer: AgentUpdateThreadPeerOptions;
    }, pubsub?: PubSub): boolean;
    discoverThreadPeers(options?: DiscoverAgentThreadPeersOptions, pubsub?: PubSub, callerAgent?: Agent<any, any, any, any>): Promise<AgentThreadPeerAdvertisement[]>;
    prepareRunOptions<OUTPUT>(options: AgentExecutionOptions<OUTPUT>, pubsub?: PubSub, cleanupAbortedRun?: () => Promise<boolean>): AgentExecutionOptions<OUTPUT>;
    isRunAborted(runId: string, pubsub?: PubSub): boolean;
    /**
     * Whether an abort stopped `runId` while it was waiting on a tool approval or
     * suspension, so that suspension must never be resumed.
     */
    isResumeFenced(runId: string, pubsub?: PubSub): boolean;
    /**
     * `fenceResume: false` is for lifecycle teardowns (detach, thread switch) that
     * stop the local segment but leave its parked suspensions answerable.
     */
    abortRun(runId: string, pubsub?: PubSub, options?: {
        fenceResume?: boolean;
    }): boolean;
    /**
     * A run parked on a tool suspension: its active segment ended (so it was
     * evicted from `preparedRunsById` by {@link #cleanupPreparedRun}), but its
     * record remains the thread's blocking run until it is resumed or released.
     */
    /** Whether `runId` is parked on a tool suspension in this process. */
    isRunParked(runId: string, pubsub?: PubSub): boolean;
    getActiveThreadRunId(options: AgentThreadIdentityOptions, pubsub?: PubSub): string | undefined;
    /** Same predicate as {@link getActiveThreadRunId}, over every tracked thread. */
    listActiveThreadRuns(pubsub?: PubSub): ActiveThreadRun[];
    hasThreadRun(runId: string, pubsub?: PubSub): boolean;
    /** Whether the run's original stream is still live and carries its resumed segments. */
    hasRunContinuation(runId: string, pubsub?: PubSub): boolean;
    /** Capture whether the currently registered continuation publishes its terminal stream part. */
    captureThreadRunTerminalPublish(runId: string, pubsub?: PubSub): (() => boolean) | undefined;
    getResumableThreadRunSuspension(options: AgentSubscribeToThreadOptions & {
        runId: string;
        toolCallId?: string;
    }, pubsub?: PubSub): AgentThreadRunSuspension | undefined;
    /** @internal Restore a suspension consumed while attaching a second observer. */
    __restoreThreadRunSuspension(options: AgentSubscribeToThreadOptions & {
        runId: string;
    }, suspension: AgentThreadRunSuspension, pubsub?: PubSub): boolean;
    getResumableThreadRun(options: AgentSubscribeToThreadOptions & {
        runId: string;
        toolCallId?: string;
    }, pubsub?: PubSub): {
        runId: string;
        toolCallId?: string;
    } | undefined;
    /**
     * Starts resumes for the same parent run one at a time. A resume mutates the
     * parent's persisted workflow snapshot, so overlapping resumes can each load
     * the same stale snapshot and lose a sibling tool result. Callers still
     * resolve as soon as their resumed stream starts; only the next queued resume
     * waits for the current stream to suspend or finish.
     */
    queueStreamResume<OUTPUT>(runId: string, resume: () => Promise<MastraModelOutput<OUTPUT>>, pubsub?: PubSub): Promise<MastraModelOutput<OUTPUT>>;
    abortThread(options: AgentAbortThreadOptions, pubsub?: PubSub): boolean;
    /** @internal */
    resetForTests(): void;
    continueRun<OUTPUT>(agent: Agent<any, any, any, any>, output: MastraModelOutput<OUTPUT>, streamOptions: AgentExecutionOptions<OUTPUT>, pubsub?: PubSub, claim?: AgentThreadRunClaim & {
        generation?: number;
    }): boolean;
    /**
     * A parked run whose lease lapsed keeps its record (its snapshot is still needed) but holds no
     * lease, renewal or deadline. A resume can start executing before it re-registers, and non-strict
     * registration runs on even when another owner holds the lease, so the resume must take the lease
     * here, before it calls the model or tools. The lease is taken under the owner the run held it with,
     * since its renewals use that owner. It is a no-op when this process has no parked record of the run
     * for the thread, or the parked run still holds (and renews) its lease.
     *
     * @throws AgentThreadLeaseConflictError when another run now holds the thread, so the resume is
     * refused and the run stays parked.
     */
    reacquireParkedRunLease(runId: string, pubsub?: PubSub): Promise<void>;
    closeRunContinuation<OUTPUT>(ownerOutput: MastraModelOutput<OUTPUT>, pubsub?: PubSub): boolean;
    registerRun<OUTPUT>(agent: Agent<any, any, any, any>, output: MastraModelOutput<OUTPUT>, streamOptions: AgentExecutionOptions<OUTPUT>, pubsub: PubSub | undefined, registrationOptions: AgentThreadStrictRegistrationOptions): Promise<AgentThreadRunRegistration> | undefined;
    registerRun<OUTPUT>(agent: Agent<any, any, any, any>, output: MastraModelOutput<OUTPUT>, streamOptions: AgentExecutionOptions<OUTPUT>, pubsub?: PubSub, registrationOptions?: AgentThreadStreamRegistrationOptions): Promise<void> | undefined;
    continueWithMessages<OUTPUT = unknown>(agent: Agent<any, any, any, any>, messages: MessageListInput, target: {
        resourceId: string;
        threadId: string;
        streamOptions?: AgentExecutionOptions<OUTPUT>;
        runId?: string;
    }, pubsub?: PubSub): {
        accepted: true;
        runId: string;
    };
    /** @internal Listen only to input actually admitted to this process's owning run. */
    subscribePendingSignals(runId: string, listener: PendingSignalListener, pubsub?: PubSub): () => void;
    /**
     * Drains queued signals for a run.
     *
     * - `scope: 'pending'` (default) returns active-run follow-up signals — each
     *   becomes its own model turn via `signalDrainStep`.
     * - `scope: 'pre-run'` returns signals queued before the run's first model
     *   request — the first LLM step folds these into that request.
     */
    drainPendingSignals(runId: string, pubsub?: PubSub, scope?: 'pending' | 'pre-run'): CreatedAgentSignal[];
    waitForCrossAgentThreadRun(agent: Agent<any, any, any, any>, options: {
        memory?: AgentExecutionOptions<any>['memory'];
        requestContext?: RequestContext;
        runId?: string;
        /**
         * Also stop waiting once the run holding the thread parks on a prompt, and
         * wait out the lease of a parked run the TTL sweep dropped from memory.
         * Resolves `'suspended'` when it stopped because the run is parked.
         */
        untilSuspended?: boolean;
    }, pubsub?: PubSub): Promise<'suspended' | undefined>;
    /**
     * Releases a thread reservation made by `waitForCrossAgentThreadRun` when the
     * run fails before reaching `registerRun`. No-op once the run has registered
     * (registration owns cleanup from then on) or if the reservation was already
     * replaced.
     */
    releaseThreadRunReservation(runId: string, pubsub?: PubSub, failedRun?: Pick<AgentThreadRunRecord<any>, 'agent' | 'streamOptions'>, expectedAbortSignal?: AbortSignal): void;
    subscribeToThread<OUTPUT = unknown>(agent: Agent<any, any, any, any>, options: AgentSubscribeToThreadOptions, pubsub?: PubSub): Promise<AgentThreadSubscription<OUTPUT, boolean, boolean>>;
    sendMessage<OUTPUT = unknown>(agent: Agent<any, any, any, any>, message: AgentMessageInput, target: SendAgentMessageOptions<OUTPUT>, pubsub?: PubSub): SendAgentMessageResult<OUTPUT>;
    subscribeThreadEvents(agent: Agent<any, any, any, any>, scope: SubscribeAgentThreadEventsOptions, listener: AgentThreadEventListener, pubsub?: PubSub): () => void;
    cancelQueuedMessages(agent: Agent<any, any, any, any>, target: CancelQueuedAgentMessagesOptions, pubsub?: PubSub): CancelQueuedAgentMessagesResult;
    queueMessage<OUTPUT = unknown>(agent: Agent<any, any, any, any>, message: AgentMessageInput, target: QueueAgentMessageOptions<OUTPUT>, pubsub?: PubSub): QueueAgentMessageResult<OUTPUT>;
    /**
     * Queues a signal to start a new run after the active thread run completes, or wakes the
     * thread immediately when it is idle. Unlike `sendSignal`, it never joins the active run.
     */
    queueSignal<OUTPUT = unknown>(agent: Agent<any, any, any, any>, signalInput: AgentSignal, target: QueueAgentSignalOptions<OUTPUT>, pubsub?: PubSub): QueueAgentSignalResult<OUTPUT>;
    sendStateSignal<OUTPUT = unknown>(agent: Agent<any, any, any, any>, stateInput: AgentStateSignalInput, target: SendAgentStateSignalOptions<OUTPUT>, pubsub?: PubSub): Promise<SendAgentStateSignalResult<OUTPUT>>;
    /**
     * Routes a signal to an agent thread.
     *
     * Signals can land in three places:
     * - an active same-agent run, where they are queued for the execution loop to drain;
     * - a reserved thread run that has not registered its stream record yet;
     * - a new idle-started run, when the caller opts into `ifIdle`.
     *
     * Cross-agent active runs are intentionally not interrupted here. They either finish first
     * through `waitForCrossAgentThreadRun()` on the stream path, or this method falls through to
     * the idle-start path when the caller provided a resource/thread target and `ifIdle` options.
     */
    sendSignal<OUTPUT = unknown>(agent: Agent<any, any, any, any>, signalInput: AgentSignal, inputTarget: SendAgentSignalOptions<OUTPUT>, pubsub?: PubSub): SendAgentSignalResult<OUTPUT>;
}
export declare const agentThreadStreamRuntime: AgentThreadStreamRuntime;
export {};
//# sourceMappingURL=thread-stream-runtime.d.ts.map