import { getErrorFromUnknown } from '../error'; import { withAck } from '../events/acking-callback'; import { EventEmitterPubSub } from '../events/event-emitter'; import { isLeaseProvider, NoopLeaseProvider } from '../events/pubsub'; import type { LeaseProvider, PubSub } from '../events/pubsub'; import { reachesOtherProcesses } from '../events/reach'; import type { EventCallback } from '../events/types'; import { AGENTIC_LOOP_WORKFLOW_ID } from '../loop/loop-builder'; import { parseMemoryRequestContext } from '../memory/types'; import { MASTRA_AUTH_TOKEN_KEY, MASTRA_RESOURCE_ID_KEY, MASTRA_SCOPES_KEY, MASTRA_THREAD_ID_KEY, RequestContext, withoutLiveRequestKeys, } from '../request-context'; import { getRequestContextInputSource } from '../request-context/input-source'; import type { MastraModelOutput } from '../stream/base/output'; import { getChunkProducedAt } from '../stream/base/produced-at'; import { isSignalChunkExcluded } from '../stream/signal-exclusions'; import { stripModelSnapshots } from '../stream/strip-model-snapshots'; import { ChunkFrom } from '../stream/types'; import type { ChunkType, ThreadHistoryChunk, ThreadRunStatusChunk, UserMessagePendingChunk, UserMessageCancelledChunk, } from '../stream/types'; import { readPositiveIntEnv } from '../utils'; import type { WorkflowRunStatus } from '../workflows/types'; import type { Agent } from './agent'; import type { AgentExecutionOptions } from './agent.types'; import { DurableStepIds } from './durable/constants'; import type { MessageListInput } from './message-list'; import { createRecentRequests } from './recent-requests'; import { liveRequestEntries, restoreRequestContext, snapshotRequestContextEntries } from './request-context-snapshot'; import { clearRunLeaseFence, hasRunningRunStep, isRunStepActive, setRunLeaseFence, whenRunStepsSettle, } from './run-lease-fence'; import { AGENT_LEASE_LOST_TOOL_GRACE_MS, AGENT_LEASE_RENEW_INTERVAL_MS, AGENT_LEASE_TTL_MS } from './run-ownership'; import { deriveAgentRunRequestContext, resolveAgentScopes } from './scopes'; import { createSignal, resolveDeliveryAttributes } from './signals'; import type { PendingSignalListener, AgentMessageInput, AgentStateSignalInput, CreatedAgentSignal } from './signals'; import { applyStateSignal } from './state-signals'; import { hasDurableExecution } from './streams/execution-capability'; import { createThreadHistoryFilter, getPartProducedAt, stampPartProducedAt } from './thread-history'; import { onThreadMessagesSaved } from './thread-saves'; import { AGENT_THREAD_KEY_SEPARATOR, agentThreadStreamKey, agentThreadStreamTopicForKey } from './thread-stream-topic'; import type { AgentAbortThreadOptions, AgentClaimThreadPeerOptions, AgentSignal, AgentSubscribeToThreadOptions, AgentThreadIdentityOptions, AgentThreadPeerAdvertisement, AgentThreadPeerInfo, AgentThreadSubscription, AgentUpdateThreadPeerOptions, DiscoverAgentThreadPeersOptions, DurableAgentLike, CancelQueuedAgentMessagesOptions, CancelQueuedAgentMessagesResult, AgentThreadEventListener, SubscribeAgentThreadEventsOptions, QueueAgentMessageOptions, QueueAgentMessageResult, QueueAgentSignalOptions, QueueAgentSignalResult, SendAgentMessageOptions, SendAgentMessageResult, SendAgentSignalOptions, SendAgentSignalAccepted, SendAgentSignalResult, SendAgentStateSignalOptions, SendAgentStateSignalResult, } from './types'; /** * DurableAgent.stream() resolves to a wrapper whose `output` is the model output; * Agent.stream() resolves to the model output itself. Normalize to the latter. */ function toModelOutput(result: unknown): MastraModelOutput { const inner = (result as { output?: unknown } | null)?.output; if (inner && typeof inner === 'object' && 'fullStream' in inner) { return inner as MastraModelOutput; } return result as MastraModelOutput; } function userMessageSignalId(part: unknown): string | undefined { if (!part || typeof part !== 'object' || !('type' in part) || part.type !== 'data-user-message') return; if (!('data' in part) || !part.data || typeof part.data !== 'object') return; return 'id' in part.data && typeof part.data.id === 'string' ? part.data.id : undefined; } const TERMINAL_STORED_RUN_STATUSES = new Set([ 'success', 'failed', 'canceled', 'bailed', 'tripwire', ]); /** Keys {@link AgentThreadRuntimeState.claimedQueuedMessages} by thread and signal id. */ function claimedQueuedMessageKey(key: string, signalId: string): string { return JSON.stringify([key, signalId]); } /** * Formats a thread key for use in error messages. * * Thread keys are `resourceId + NUL + threadId`. Never put a raw key in an * error message: these errors flow back to senders (e.g. `agent_signal_send`) * and into a notification's `lastDeliveryError`, and anything that treats the * string as NUL-terminated (SQLite text binding, terminals, the TUI) silently * drops everything after the resource id, including the thread id and the rest * of the message. Ids themselves may contain NUL, so it is escaped as well. */ function describeThreadKey(key: string): string { const separator = key.indexOf(AGENT_THREAD_KEY_SEPARATOR); // An id containing NUL makes the split ambiguous: show the whole key, escaped. if (separator === -1 || key.lastIndexOf(AGENT_THREAD_KEY_SEPARATOR) !== separator) { return `thread ${key.replaceAll(AGENT_THREAD_KEY_SEPARATOR, '\\0')}`; } const resourceId = key.slice(0, separator); const threadId = key.slice(separator + AGENT_THREAD_KEY_SEPARATOR.length); return resourceId ? `thread ${threadId} (resource ${resourceId})` : `thread ${threadId}`; } const AGENT_THREAD_OWNER_DISCOVERY_TOPIC = 'agent.thread-owner-discovery'; /** * Per-attempt window for a claimed thread owner to answer a discovery request. * Kept short because the claim path waits out the full window whenever no owner * exists. Overridable via `MASTRA_AGENT_THREAD_OWNER_DISCOVERY_TIMEOUT_MS`. */ const AGENT_THREAD_OWNER_DISCOVERY_TIMEOUT_MS = readPositiveIntEnv( 'MASTRA_AGENT_THREAD_OWNER_DISCOVERY_TIMEOUT_MS', 100, ); /** * Total budget a `requireClaimedOwner` wake spends retrying owner discovery * before rejecting. A live owner on a loaded host can miss a single short * window; retrying with growing per-attempt timeouts keeps that from reading as * "no owner". Overridable via `MASTRA_AGENT_THREAD_WAKE_OWNER_DISCOVERY_DEADLINE_MS`. */ const AGENT_THREAD_WAKE_OWNER_DISCOVERY_DEADLINE_MS = readPositiveIntEnv( 'MASTRA_AGENT_THREAD_WAKE_OWNER_DISCOVERY_DEADLINE_MS', 1_000, ); const AGENT_THREAD_CLAIM_LEASE_PREFIX = 'thread-claim:'; const AGENT_THREAD_OWNER_ACCEPTANCE_TIMEOUT_MS = 5_000; // Long enough for live subscribers (including cross-process readers polling the // topic) to read an unsaved run's output before its entries are deleted. const UNSAVED_RUN_TRIM_DELAY_MS = 30_000; const AGENT_THREAD_PEER_DISCOVERY_TOPIC = 'agent.thread-peer-discovery'; const AGENT_THREAD_PEER_DISCOVERY_TIMEOUT_MS = 100; const THREAD_LEASE_OWNER_PREFIX = 'mastra:thread-lease:'; type ThreadLeaseIdentity = | [runId: string, kind: 'run', value: null] | [runId: string, kind: 'generation', value: number] | [runId: string, kind: 'execution' | 'retake', value: string]; function encodeThreadLeaseOwner(identity: ThreadLeaseIdentity): string { return THREAD_LEASE_OWNER_PREFIX + JSON.stringify(identity); } function parseThreadLeaseOwner(owner: string | undefined): ThreadLeaseIdentity | undefined { if (!owner?.startsWith(THREAD_LEASE_OWNER_PREFIX)) return undefined; try { const identity: unknown = JSON.parse(owner.slice(THREAD_LEASE_OWNER_PREFIX.length)); if (!Array.isArray(identity) || identity.length !== 3 || typeof identity[0] !== 'string') return undefined; const [runId, kind, value] = identity; if (kind === 'run' && value === null) return [runId, kind, value]; if (kind === 'generation' && typeof value === 'number') return [runId, kind, value]; if ((kind === 'execution' || kind === 'retake') && typeof value === 'string') return [runId, kind, value]; } catch { // Legacy owners are bare run IDs, including IDs that happen to start with the encoding prefix. } return undefined; } function threadLeaseOwner(runId: string, generation?: number, executionId?: string): string { if (generation !== undefined) return encodeThreadLeaseOwner([runId, 'generation', generation]); if (executionId) return encodeThreadLeaseOwner([runId, 'execution', executionId]); return runId.startsWith(THREAD_LEASE_OWNER_PREFIX) ? encodeThreadLeaseOwner([runId, 'run', null]) : runId; } function threadLeaseRunId(owner: string): string { return parseThreadLeaseOwner(owner)?.[0] ?? owner; } // Retake token suffix written by releases before the encoded lease-owner format. const LEGACY_RETAKE_LEASE_MARKER = '\u0000retake\u0000'; /** Resolves a follow-up address forwarded as a lease owner, in either format, to its run ID. */ function forwardedSignalRunId(address: string): string { const legacyRetake = address.lastIndexOf(LEGACY_RETAKE_LEASE_MARKER); const owner = legacyRetake > 0 ? address.slice(0, legacyRetake) : address; return threadLeaseRunId(owner); } /** * A handover token in either format. The legacy shape can also be a caller-supplied run id, so it is only * ever waited on, never rejected. */ function isHandoverLeaseOwner(owner: string | undefined): boolean { if (isRetakeLeaseOwner(owner)) return true; return !!owner && !parseThreadLeaseOwner(owner) && owner.lastIndexOf(LEGACY_RETAKE_LEASE_MARKER) > 0; } /** @internal Distinguishes temporary handover tokens from qualified execution owners. */ export function isRetakeLeaseOwner(owner: string | undefined): boolean { return parseThreadLeaseOwner(owner)?.[1] === 'retake'; } // How much longer than its window a discovery may wait for a caller whose event loop was busy. const AGENT_THREAD_PEER_DISCOVERY_MAX_EXTRA_MS = 1_000; /** * Calls `close` once the caller has had `windowMs` in which it could read replies, or after * `windowMs + maxExtraMs` of wall time. Time the event loop spent busy doesn't count: replies that * arrived meanwhile are still unread when the loop frees up, so closing on a plain timer then * would drop every answer and report live peers as absent. Elapsed time is read from the monotonic * clock, so a wall-clock step can't keep the window open. Returns a cancel function. */ function startListeningWindow(windowMs: number, maxExtraMs: number, close: () => void): () => void { const tickMs = Math.max(1, Math.min(10, Math.floor(windowMs / 10))); const startedAt = performance.now(); let lastTickAt = startedAt; let listenedMs = 0; let timer: ReturnType; const tick = () => { const now = performance.now(); // A tick far later than scheduled means the loop was busy; credit only a normal tick for it. listenedMs += Math.min(now - lastTickAt, tickMs * 2); lastTickAt = now; if (listenedMs >= windowMs || now - startedAt >= windowMs + maxExtraMs) close(); else timer = setTimeout(tick, tickMs); }; timer = setTimeout(tick, tickMs); return () => clearTimeout(timer); } /** * Slack added to a request's carried `expiresAt` before a responder drops it * as stale. Requests cross processes, so the check compares two machines' * clocks; without slack, skew larger than the 100ms discovery window would * make responders drop every live request and silently break cross-process * discovery. The grace only needs to be small next to the delays it exists to * reject — reclaim redelivery (tens of seconds) and backlog replay on a fresh * fan-out group (arbitrarily old) — where a late reply would recreate the * caller's already-released reply stream on persistent backends. */ const AGENT_REQUEST_EXPIRY_SKEW_GRACE_MS = 5_000; /** * True when a request's caller-side deadline has passed by more than the skew * grace. Tolerates events without a deadline (older senders): comparisons * against `undefined`/`NaN` are false, which degrades to the previous * always-respond behavior. */ function isStaleRequest(expiresAt: number | undefined): boolean { return ( typeof expiresAt === 'number' && Number.isFinite(expiresAt) && Date.now() - expiresAt > AGENT_REQUEST_EXPIRY_SKEW_GRACE_MS ); } /** Thread lease TTL and renew interval; shared with the durable execution lease. */ const AGENT_THREAD_LEASE_TTL_MS = AGENT_LEASE_TTL_MS; const AGENT_THREAD_LEASE_RENEW_INTERVAL_MS = AGENT_LEASE_RENEW_INTERVAL_MS; const DURABLE_THREAD_CLAIM_WAIT_MS = 5_000; const DURABLE_THREAD_CLAIM_POLL_MS = 100; /** * TTL for a suspended run's warm in-memory state — the parked thread-run record * (swept by #sweepStaleSuspendedRecords). The Mastra internal-workflow registry * reads the same `MASTRA_SUSPENDED_RUN_TTL_MS` so both expire on one bound. A * suspended run is kept warm so a same-instance resume can reattach and the thread * stays blocked; once it lapses the state is evicted and resume falls back to the * durable snapshot. Multi-instance deployments (resume rarely lands on the origin) * can shed it sooner; 30 minute default. */ const AGENT_SUSPENDED_RUN_TTL_MS = readPositiveIntEnv('MASTRA_SUSPENDED_RUN_TTL_MS', 30 * 60 * 1000); export const AGENT_THREAD_LEASE_CONFLICT_CODE = 'AGENT_THREAD_LEASE_CONFLICT'; export class AgentThreadLeaseConflictError extends Error { readonly code = AGENT_THREAD_LEASE_CONFLICT_CODE; constructor(runId: string, owner: string) { super(`Cannot register run ${runId}: thread lease is held by ${owner}`); this.name = 'AgentThreadLeaseConflictError'; } } /** The `reason` an `abort` chunk carries when its run stopped because another run holds its thread lease. */ export const THREAD_LEASE_LOST_ABORT_REASON = 'thread-lease-lost'; export class AgentThreadLeaseLostError extends Error { constructor(runId: string) { super(`Thread run ${runId} lost its lease before publishing a terminal event`); this.name = 'AgentThreadLeaseLostError'; } } export let defaultAgentThreadPubSub: PubSub = new EventEmitterPubSub(); /** * Strip raw model-request bookkeeping from a chunk before it is broadcast to * the thread-stream topic (and retained for subscriber replay). `step-start` * embeds the full serialized provider request (including any base64 media in * context), and `step-finish`/`finish` repeat it via `metadata.request`, * `output.steps[]` (each step re-embeds its cumulative request/response) and * `messages`. No thread subscriber needs those — they are available to the * local caller via `output.request`/`output.steps` — and broadcasting them * multiplies the largest object in the system ≥5× per step, persists it in * durable pubsub backends, and exposes prompt contents to every subscriber. * Delegated agent chunks are wrapped in `tool-output.payload.output`, so known * agent-stream wrappers are sanitized recursively. Only broadcast copies are * rewritten; the caller's MastraModelOutput is untouched. */ const DEFAULT_INITIAL_HISTORY_PER_PAGE = 40; function sanitizeBroadcastPart(part: unknown): unknown { if (!part || typeof part !== 'object' || !('type' in part)) return part; const typed = part as { type?: string; payload?: Record }; const payload = typed.payload; if (!payload || typeof payload !== 'object') return part; if (typed.type === 'tool-output') { const output = payload.output; if (output && typeof output === 'object' && 'type' in output && 'from' in output && output.from === 'AGENT') { const sanitizedOutput = sanitizeBroadcastPart(output); if (sanitizedOutput !== output) { return { ...typed, payload: { ...payload, output: sanitizedOutput } }; } } return part; } return stripModelSnapshots(part); } /** * Tear down a per-request reply topic once its request has settled. The * requester mints the topic name (it embeds a fresh UUID), is its only * subscriber, and nothing will publish to it again — so beyond unsubscribing, * ask the broker to drop the topic entirely. On persistent backends (e.g. * Redis Streams) merely subscribing creates a real key; without the * `clearTopic` every discovery/acceptance round trip would leak one stream * forever. Best-effort and fire-and-forget: `clearTopic` is a no-op on * in-memory brokers and failures here must never affect the request outcome. */ function releaseReplyTopic(pubsub: PubSub, replyTopic: string, cb: EventCallback): void { void pubsub .unsubscribe(replyTopic, cb) .catch(() => {}) .then(() => pubsub.clearTopic(replyTopic)) .catch(() => {}); } /** * The caller's request context as it crosses to a claimed owner in another process. Scopes are * dropped: they don't cross processes (a message naming scopes is refused before it gets here). * The caller's signed-in user is dropped too: the owner's run acts as the owner's own user. */ function snapshotWireRequestContext(requestContext: RequestContext | undefined): Record | undefined { const entries = snapshotRequestContextEntries(getRequestContextInputSource(requestContext) ?? requestContext); if (!entries) return undefined; const { [MASTRA_SCOPES_KEY]: _scopes, ...rest } = withoutLiveRequestKeys(entries); return Object.keys(rest).length > 0 ? rest : undefined; } /** * The caller's request context, as a claimed owner's run uses it. The caller's thread and * resource keys would override the owner's `memory` (Agent reads them first), so the run would * execute and save on the caller's thread: the owner's own values (usually none) replace them. * An owner with its own auth token keeps it; an owner without one acts with the caller's. * The caller's context is returned as-is when nothing differs. */ function claimedOwnerRequestContext(caller: RequestContext, owner: RequestContext | undefined): RequestContext { // An owner with its own token runs as its own signed-in user: its whole live identity (token, // user, roles, permissions) replaces the caller's, as on the remote path. An owner without one // keeps the caller's whole identity, so the two are never mixed. const ownerHasToken = owner?.getRaw(MASTRA_AUTH_TOKEN_KEY) !== undefined; const ownerLive = ownerHasToken ? liveRequestEntries(owner) : []; const swapLive = ownerHasToken && !sameEntries(liveRequestEntries(caller), ownerLive); const replaced = [MASTRA_THREAD_ID_KEY, MASTRA_RESOURCE_ID_KEY] .map(key => [key, owner?.getRaw(key)] as const) .filter(([key, value]) => caller.getRaw(key) !== value); if (!swapLive && replaced.length === 0) return caller; // Copy the input form, so a schema-transformed tool view is validated as its inputs again. const source = Object.fromEntries((getRequestContextInputSource(caller) ?? caller).entries()); const restored: RequestContext = new RequestContext( swapLive ? [...Object.entries(withoutLiveRequestKeys(source)), ...ownerLive] : Object.entries(source), ); for (const [key, value] of replaced) { if (value === undefined) restored.deleteRaw(key); else restored.setRaw(key, value); } return restored; } /** Two entry lists hold the same keys with identical values. */ function sameEntries(a: [string, unknown][], b: [string, unknown][]): boolean { const right = new Map(b); return a.length === b.length && a.every(([key, value]) => right.has(key) && right.get(key) === value); } /** Unions scope lists, dropping duplicates. */ function unionScopes(...lists: Array): string[] { return [...new Set(lists.flatMap(list => list ?? []))]; } /** Two scope lists hold the same scopes, ignoring order and duplicates. */ function sameScopes(a: readonly string[], b: readonly string[]): boolean { const left = new Set(a); const right = new Set(b); return left.size === right.size && [...left].every(scope => right.has(scope)); } type ThreadTargetScopes = { scopes?: string[]; ifIdle?: { streamOptions?: { scopes?: string[]; requestContext?: RequestContext } }; }; /** * Validates the scopes a thread target carries: top-level `scopes` unioned with * `ifIdle.streamOptions.scopes`. `resource:`/`thread:` scopes must equal the target's ids. * Returns the union, or undefined when the target carries no scopes. * * The agent's Mastra instance and the queued run's request context are passed through so * the boundary checks fire at intake — an outdated registered server * (`AGENT_SCOPES_SERVER_OUTDATED`) or a reserved-key identity conflict must reject the * signal before `accepted` resolves, not when the queued run eventually starts. */ function resolveThreadTargetScopes( target: ThreadTargetScopes, ids: { resourceId?: string; threadId?: string }, mastra?: { getMastraServer?(): unknown }, ): string[] | undefined { const idleScopes = target.ifIdle?.streamOptions?.scopes; if (target.scopes === undefined && idleScopes === undefined) return undefined; const scopes = unionScopes(target.scopes, idleScopes); resolveAgentScopes({ callScopes: scopes, resourceId: ids.resourceId, threadId: ids.threadId, requestContext: target.ifIdle?.streamOptions?.requestContext, mastra, }); return scopes; } /** * Moves a signal target's top-level `scopes` onto the run it may start * (`ifIdle.streamOptions.scopes`). A target that delivers to a known run only has its * scopes validated: an active run keeps the scopes it started with. */ function withThreadTargetScopes>( target: T, mastra?: { getMastraServer?(): unknown }, ): T { const scopes = resolveThreadTargetScopes(target, target, mastra); if (target.scopes === undefined) return target; const { scopes: _scopes, ...rest } = target; const startsRun = !!target.resourceId && !!target.threadId && (target.runId === undefined || !!target.ifIdle); if (!startsRun) return rest as T; return { ...rest, ifIdle: { ...target.ifIdle, streamOptions: { ...target.ifIdle?.streamOptions, scopes } }, } as T; } function withThreadMemory(memory: unknown, resourceId: string, threadId: string) { return { ...((memory && typeof memory === 'object' ? memory : {}) as Record), resource: (memory as { resource?: string } | undefined)?.resource ?? resourceId, thread: (memory as { thread?: string } | undefined)?.thread ?? threadId, }; } type AgentThreadRunLifecycle = 'running' | 'suspending' | 'suspended' | 'completed' | 'failed' | 'aborted'; type AgentThreadRunSuspension = { toolCallId?: string; toolName?: string; kind: 'approval' | 'generic-tool'; }; type AgentThreadRunContinuation = { sourceOutput: MastraModelOutput; canContinue: () => boolean; didPublishTerminal: () => boolean; }; type AgentThreadRunRecord = { agent: Agent; /** The source output that owns the subscriber-facing broadcast. */ output: MastraModelOutput; /** The latest execution segment attached to a suspension-spanning broadcast. */ currentSegmentOutput?: MastraModelOutput; 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; /** When the record was parked as suspended (ms epoch); drives the TTL sweep. */ suspendedAt?: number; threadId: string; resourceId?: string; streamOptions: AgentExecutionOptions; createSubscriberStream?: () => ReadableStream; /** Settles once every stream-part broadcast publish for this run completed. */ broadcastFinished?: Promise; /** Present only while the broadcast may accept resumed execution segments. */ continuation?: AgentThreadRunContinuation; }; type ThreadControlSubscription = { ready: Promise; references: number; observers: number; ownedRunIds: Set; admittedSignalIds: Set; /** * Runs this process lost to an execution elsewhere while idle messages or * continuations stayed queued here, keyed to the lost execution's stream. * The successor's terminal event drains those queues; the lost stream's own * terminal event does not, since the run is still executing elsewhere. */ successorRunIds: Map; /** * Runs that another runtime registered on the thread while this one had a run * active there, mapped to that run. When one of them ends after the local run * parked on a tool suspension, the thread has moved on without the parked run. */ supersedingRunIds: Map; unsubscribe: () => void; }; type PreparedThreadRun = { threadKey?: string; abortController: AbortController; cleanup: () => void; cleanupAbortedRun?: () => Promise; output?: WeakRef<{ status: string }>; finalizerToken?: object; }; type PendingIdleSignal = { agent: Agent; signal: CreatedAgentSignal; runId: string; resourceId: string; threadId: string; streamOptions?: AgentExecutionOptions; queueOwnerId?: string; cancelled?: boolean; }; type PendingContinuation = { agent: Agent; messages: MessageListInput; runId: string; resourceId: string; threadId: string; streamOptions?: AgentExecutionOptions; }; type ClaimedThreadOwnerStreamOptions = | AgentExecutionOptions | (() => AgentExecutionOptions | Promise>); type ClaimedThreadOwner = { agent: Agent; resourceId: string; threadId: string; streamOptions?: ClaimedThreadOwnerStreamOptions; peer?: AdvertisedThreadPeer; unsubscribe: () => void; }; type AdvertisedThreadPeer = AgentThreadPeerInfo & { sourceId: string; unsubscribe: () => void; }; type ThreadEventListenerRegistration = SubscribeAgentThreadEventsOptions & { agent: Agent; listener: AgentThreadEventListener; lastCount: number; }; /** * What a claimed owner remembers about an idle signal once it has acted on it. * A redelivery must not act on the signal again, but it may still have to * deliver the caller's reply if the first attempt never reached the backend. */ type HandledIdleSignal = { /** Where the caller is waiting for its reply. */ replyTopic: string; /** The acceptance reply, kept so a repeat can re-send it verbatim. */ reply?: AgentThreadIdleSignalAcceptanceEvent; /** Whether that reply reached the backend. Set once its publish resolves. */ replyPublished: boolean; }; /** * A claimed owner's record of a logical cross-agent message it has already * accepted. `HandledIdleSignal` remembers the transport request id, but a sender * whose acknowledgement never landed retries the *same* logical message with a * fresh request id, so accepting has to be remembered against the message's own * identity instead. Starting the wake is not idempotent — it re-runs the turn's * tools — so the retry must resolve to whatever the first attempt reached. */ type AcceptedIdleMessage = { /** The run that accepted the logical message, whether queued or started. */ runId: string; /** * Set once the accepted message can no longer run (for example it was * cancelled while queued), so a retry is told the original outcome instead of * waiting on a run that will never start. */ terminalReason?: string; /** * Set while the first delivery attempt is still resolving its admission — the * owner's stream options, the thread control subscription, the execution lease. * A duplicate arriving in that window waits on this promise for the real * outcome; answering it from the provisional reservation would report a * delivery for a wake the first attempt may yet reject. */ admission?: Promise; }; type ThreadAdmissionOutcome = { action: 'local' | 'remote' | 'blocked'; runId: string; }; type PendingThreadAdmission = { runId: string; /** The agent whose run holds the reservation. */ agentId: string; outcome: Promise; }; /** A claimed-owner message queued for a run in flight, tracked so cancelling it ends the logical message. */ type ClaimedQueuedMessage = { identity?: string; /** The run the logical message was settled on, once it is. */ runId?: string; cancelled?: boolean; }; const CANCELLED_BEFORE_RUN = 'The accepted message was cancelled before it ran'; /** An idle message forwarded to the run holding the thread lease, kept until that run admits it. */ type ForwardedIdleSignal = { pendingIdle: PendingIdleSignal; /** The run it was forwarded to, as the owner resolves the address (see `forwardedSignalRunId`). */ runId: string; /** The last lease check found the lease no longer naming `runId`. */ leaseGone?: boolean; }; type AgentThreadRuntimeState = { threadRunsById: Map>; threadRunsByStreamId: Map>; threadKeysByRunId: Map; remoteThreadKeysByRunId: Map; remoteAgentIdsByRunId: Map; unobservedRemoteRunIds: Set; activeThreadRunIds: Map; activeThreadStreamIds: Map; streamSeqByRunId: Map; approvalSuspendedRunIds: Set; suspendedRunIds: Set; suspensionMetadataByRunId: Map>; pendingSignalsByThread: Map; // Signal IDs this runtime queued locally before publishing them, mapped to the owner run they were // later forwarded to (if any). Replays of these are echoes, except one addressed to that forwarded owner. locallyQueuedSignalIdsByThread: Map>; pendingSignalListenersByRunId: Map>; // Signals queued for a run that is starting but has not made its first model // request yet. The first LLM step drains these and folds them into that // request; `pendingSignalsByThread` follow-ups instead become their own turn. preRunSignalsByThread: Map; /** * Threads whose queued signals belong to a run whose execution here lost it * before the run's next execution registered, keyed by thread key to that * execution's record. The next registration takes the queues: one in this * process adopts them, one of the same run elsewhere gets them re-published. */ lostRunsByThread: Map>; pendingIdleSignalsByThread: Map[]>; /** * Idle messages this runtime forwarded to another process's lease-owning run, keyed by thread key and then * signal ID. A forward can reach the owner after its run has finished locally, and the owner then drops it, so * each copy is kept until the owner admits it on that run (`user-message-admitted`, or the pending presentation * from owners that predate it) and is queued * again here if the run ends first, or if the lease stops naming that run (see `forwardedIdleLeaseChecks`). */ forwardedIdleSignalsByThread: Map>; /** Per thread key, the timer that checks the lease while `forwardedIdleSignalsByThread` holds messages for it. */ forwardedIdleLeaseChecks: Map>; /** * Runs the suspended-run TTL sweep evicted, mapped to when their lease was last * known to be extended. The sweep keeps their lease, so until it lapses an idle * send loses the lease to a run that no longer exists here. */ sweptLeasedRunIds: Map; /** Lease renewals still awaiting a result, by runId. */ pendingLeaseRenewals: Map; /** A dequeued idle message retains its cancellation identity until execution begins. */ drainingIdleSignalsByThread: Map>; drainingPendingSignalsByThread: Map; pendingContinuationsByThread: Map[]>; claimedThreadOwnerDiscoveries: Map>; /** Idle-start reservations whose execution lease has not resolved yet. */ pendingThreadAdmissions: Map; /** Call scopes of runs this process reserved through an idle start, until their record registers. */ reservedRunScopes: Map; /** * Idle signals this process has already acted on, keyed by request id, with the * reply it sent. Backends deliver at least once, so a redelivery of a signal * that already started or joined a run must not queue it again or start a * second run — the wake path is not idempotent — but it may still have to * re-send a reply that never reached the caller. */ handledIdleSignals: ReturnType>; /** * Logical cross-agent messages this process has already accepted, keyed by * target agent, thread, source peer and message id — the identity a sender * preserves when it retries a message whose acknowledgement never landed. */ acceptedIdleMessagesByIdentity: ReturnType>; /** * Claimed-owner messages queued for a run in flight, keyed by {@link claimedQueuedMessageKey}: the thread and the * signal id, since callers may choose signal ids and two threads can queue the same one. */ claimedQueuedMessages: ReturnType>; claimedThreadOwners: Map>; advertisedThreadPeers: Map; watchedThreadStreamIds: Set; preparedRunsById: Map; resumeTailsByRunId: Map>; abortedRunIds: Set; resumeFencedRunIds: Set; startingQueuedRunIds: Set; /** Run ids an idle `persist` signal holds while its storage write is pending. */ persistingIdleRunIds: Set; /** * Active lease-renewal timers keyed by runId. Set when the owner * process wins the cross-process lease, cleared on release. Stored * here (not on a Map) so a run's renewal timer survives even * if `activeThreadRunIds` is rotated by a follow-up signal. */ leaseRenewalTimers: Map>; leaseOwners: Map; /** * Per-run local lease deadline: one TTL after the last acquire or renewal * this process sent and had confirmed. When it fires, the run can no longer * prove it still holds the lease, so it is aborted. */ leaseDeadlines: Map; confirmedSentAt: number }>; leaseFences: Map Promise>; /** A run's in-flight attempt to take back a lease that lapsed, so the renewal, deadline and fence share one. */ leaseRetakes: Map>; /** Runs this runtime stopped because another run holds their thread lease, until their abort is broadcast. */ leaseLostRunIds: Set; /** * Streams of runs a shutting-down Mastra is handing back, by stream id. `ending` while an aborted run gets a * moment to stop: its parts still go out, but its own end publishes nothing and keeps its lease. `ended` once * shutdown published its terminal event and released its lease: nothing more goes out for it. */ shutdownStreams: Map; threadEventListeners: Set; threadControlSubscriptions: Map; /** * Thread subscribers reading a run's stream, by run id, with the stream each * reads. A parked run that continues across its suspension keeps its stream * open; once the thread moves on without it, its readers stop and read the * runs queued behind it. */ runStreamReaders: Map void }>>; /** * Parked records the thread moved on without: swept, taken over, released or * aborted. A subscriber that queued one before reading it skips it instead of * waiting on its open stream, and ends an aborted one with an abort. */ displacedRecords: WeakMap, 'moved-on' | 'aborted'>; }; 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; /** * 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; }; type SerializableAgentSignal = AgentSignal & Pick; type AgentThreadStreamRuntimeEvent = | { type: 'run-registered'; runId: string; streamId: string; streamSeq: number; sourceId?: string; agentId?: string; generation?: number; /** See {@link AgentThreadRunRecord.supersedes}. */ supersedes?: boolean; } | { type: 'stream-part'; runId: string; streamId: string; part: unknown; sourceId: string; generation?: number; /** Epoch ms the part was produced; publishing can lag behind it. */ producedAt?: number; /** Kept by save-time trims; removed only when the whole run is trimmed. */ pinned?: boolean; } | { type: 'run-completed'; runId: string; streamId?: string; persisted?: boolean; /** * The run's final status; `success` means storage holds all of it and nothing is left to act on. A shutdown * hand-back of a durable run sends `interrupted`, which isn't final: recovery can continue the run. */ status?: string; /** Remains non-authoritative even if retention evicts the recovery registration. */ superseded?: boolean; } | { type: 'run-suspended'; runId: string; streamId?: string } | { type: 'run-discarded'; runId: string; streamId: string } // Without a streamId the sender found the run through the thread lease, not a stream it watches. | { type: 'run-abort-requested'; runId: string; streamId?: string; clearPendingSignals?: boolean } | { type: 'signals-cancelled'; signalIds: string[] } // runId is the run whose trim removes the entry; a cancellation has no owning run. | { type: 'user-message-presentation'; runId?: string; chunk: UserMessagePendingChunk | UserMessageCancelledChunk } | { type: 'user-message-delivered'; signalId: string } // The owner admitted a forwarded message on admittedRunId. Unlike the presentation, it carries no runId of its own, so // the run's trim keeps it for a forwarder that reads the thread after that run ended. | { type: 'user-message-admitted'; signalId: string; admittedRunId: string } | { type: 'run-aborted'; runId: string; streamId?: string; superseded?: boolean } | { type: 'run-failed'; runId: string; streamId?: string; error: string } | { type: 'signal-enqueued'; runId: string; signal: SerializableAgentSignal; sourceId: string; preRun?: boolean } | { type: 'idle-signal-enqueued'; runId: string; signal: SerializableAgentSignal; sourceId: string; requestId: string; replyTopic: string; targetSourceId: string; /** * Caller's absolute deadline. Optional only on the wire: current senders * always set it, but during a rolling deploy an older process publishes * `timeoutMs` instead. The receiving handler normalizes. */ expiresAt?: number; /** Legacy relative window from pre-`expiresAt` senders. */ timeoutMs?: number; /** * The sender asks for this to join a run in flight at the owner. Absent (queued input, and every * sender from before this field) keeps it waiting until the thread is idle. */ joinActiveRun?: boolean; /** * The same signal with the sender's `ifActive` attributes, for an owner that hands it to a run in flight. The * sender can't see that run, so `signal` carries its `ifIdle` attributes. */ joinSignal?: SerializableAgentSignal; /** * JSON-safe snapshot of the caller's request context (see `snapshotRequestContextEntries`), so the owner's * run resolves request-scoped model, instructions and memory as the caller's would. Absent from senders * before this field, and when the caller passed no context. */ requestContextEntries?: Record; }; type AgentThreadIdleSignalAcceptanceEvent = | { type: 'idle-signal-accepted'; requestId: string; runId: string; sourceId: string } | { type: 'idle-signal-rejected'; requestId: string; runId: string; sourceId: string; error: string }; type AgentThreadOwnerDiscoveryEvent = | { type: 'thread-owner-request'; key: string; requestId: string; replyTopic: string; sourceId: string; /** Caller's absolute deadline; optional on the wire (legacy senders omit it). */ expiresAt?: number; /** * Set when the requester wants to own the thread itself (as opposed to * looking the owner up for signal delivery). Owners may yield to it. */ intent?: 'claim'; /** Lease owner the request is addressed to. Older senders omit it. */ targetSourceId?: string; } | { type: 'thread-owner-response'; key: string; requestId: string; sourceId: string }; type AgentThreadPeerDiscoveryEvent = // expiresAt is optional on the wire: legacy senders omit it. | { type: 'thread-peer-request'; requestId: string; replyTopic: string; sourceId: string; expiresAt?: number } | { type: 'thread-peer-response'; requestId: string; peer: AgentThreadPeerInfo; sourceId: string }; function toPublicThreadPeer(peer: AdvertisedThreadPeer): Omit { const { unsubscribe: _unsubscribe, ...publicPeer } = peer; return publicPeer; } function createThreadPeerId(agentId: string, resourceId: string, threadId: string): string { return [agentId, resourceId, threadId].map(part => encodeURIComponent(part)).join(':'); } const MAX_LOCALLY_QUEUED_SIGNAL_IDS_PER_THREAD = 1000; // Resume fences outlive their stream segment until the suspended snapshot is gone, so cap them. const MAX_RESUME_FENCED_RUN_IDS = 1000; function createRuntimeState(): AgentThreadRuntimeState { return { threadRunsById: new Map(), threadRunsByStreamId: new Map(), threadKeysByRunId: new Map(), remoteThreadKeysByRunId: new Map(), remoteAgentIdsByRunId: new Map(), unobservedRemoteRunIds: new Set(), activeThreadRunIds: new Map(), activeThreadStreamIds: new Map(), streamSeqByRunId: new Map(), approvalSuspendedRunIds: new Set(), suspendedRunIds: new Set(), suspensionMetadataByRunId: new Map(), pendingSignalsByThread: new Map(), locallyQueuedSignalIdsByThread: new Map(), pendingSignalListenersByRunId: new Map(), preRunSignalsByThread: new Map(), lostRunsByThread: new Map(), pendingIdleSignalsByThread: new Map(), forwardedIdleSignalsByThread: new Map(), forwardedIdleLeaseChecks: new Map(), sweptLeasedRunIds: new Map(), pendingLeaseRenewals: new Map(), drainingIdleSignalsByThread: new Map(), drainingPendingSignalsByThread: new Map(), pendingContinuationsByThread: new Map(), claimedThreadOwnerDiscoveries: new Map(), pendingThreadAdmissions: new Map(), reservedRunScopes: new Map(), handledIdleSignals: createRecentRequests(), acceptedIdleMessagesByIdentity: createRecentRequests(), claimedQueuedMessages: createRecentRequests(), claimedThreadOwners: new Map(), advertisedThreadPeers: new Map(), watchedThreadStreamIds: new Set(), preparedRunsById: new Map(), resumeTailsByRunId: new Map(), abortedRunIds: new Set(), resumeFencedRunIds: new Set(), startingQueuedRunIds: new Set(), persistingIdleRunIds: new Set(), leaseRenewalTimers: new Map(), leaseOwners: new Map(), leaseDeadlines: new Map(), leaseFences: new Map(), leaseRetakes: new Map(), leaseLostRunIds: new Set(), shutdownStreams: new Map(), threadEventListeners: new Set(), threadControlSubscriptions: new Map(), runStreamReaders: new Map(), displacedRecords: new WeakMap(), }; } export class AgentThreadStreamRuntime { #id?: string; #statesByPubSub = new WeakMap(); #preparedRunsByAbortSignal = new WeakMap(); #stalledLeaseReads = new WeakMap>(); // Some runtimes, such as Cloudflare Workers with a compatibility date before 2025-05-05, do not provide // FinalizationRegistry. There, an abandoned output that is never consumed keeps its prepared run until the // run finishes, is aborted, or the runtime state is reset; every other cleanup path is unchanged. #threadlessRunFinalizer = typeof FinalizationRegistry === 'function' ? new FinalizationRegistry<{ state: AgentThreadRuntimeState; runId: string; token: object; }>(({ state, runId, token }) => { if (state.preparedRunsById.get(runId)?.finalizerToken !== token) return; this.#cleanupPreparedRun(state, runId); }) : undefined; #getPubSub(pubsub?: PubSub): PubSub { return pubsub ?? defaultAgentThreadPubSub; } /** * Resolve the {@link LeaseProvider} for the configured pubsub. Leasing is * a separate capability from event delivery: a backend only implements it * when it can genuinely coordinate a distributed lock (Redis via SET-NX, * in-memory for single-process). We feature-detect once here so all lease * call sites can use the resolved provider unconditionally. * * `CachingPubSub` exposes its inner's lease provider via `getLeaseProvider` * (caching is transparent to leasing). Otherwise we duck-type the pubsub * directly. Backends that cannot lease fall back to {@link NoopLeaseProvider} * (always-win / no-op), preserving single-process behavior. */ #getLeaseProvider(pubsub?: PubSub): LeaseProvider { const resolved = this.#getPubSub(pubsub); const unwrap = (resolved as { getLeaseProvider?: () => LeaseProvider | undefined }).getLeaseProvider; if (typeof unwrap === 'function') { const inner = unwrap.call(resolved); return inner ?? NoopLeaseProvider; } return isLeaseProvider(resolved) ? resolved : NoopLeaseProvider; } #resolveLeaseProvider(pubsub?: PubSub): { provider: LeaseProvider; isFallback: boolean } { const provider = this.#getLeaseProvider(pubsub); return { provider, isFallback: provider === NoopLeaseProvider }; } /** * Remembers a lease read that outlived its deadline until it settles. Reads behind it on the same backend * connection can't answer sooner, so waiting on each of them again would cost a full deadline per event. * After one lease TTL the backend is asked again, so a read that never settles can't skip it for good. */ #noteStalledLeaseRead(provider: LeaseProvider, key: string, read: Promise) { let stalled = this.#stalledLeaseReads.get(provider); if (!stalled) this.#stalledLeaseReads.set(provider, (stalled = new Map())); if (this.#isLeaseReadStalled(provider, key)) return; const since = Date.now(); // Reads that never settle never clear their own mark; drop expired marks so they can't pile up. for (const [staleKey, staleSince] of stalled) { if (since - staleSince >= AGENT_THREAD_LEASE_TTL_MS) stalled.delete(staleKey); } stalled.set(key, since); const clear = () => { if (stalled.get(key) === since) stalled.delete(key); }; void read.then(clear, clear); } #isLeaseReadStalled(provider: LeaseProvider, key: string): boolean { const since = this.#stalledLeaseReads.get(provider)?.get(key); return since !== undefined && Date.now() - since < AGENT_THREAD_LEASE_TTL_MS; } async #hasLiveThreadLease(pubsub: PubSub, key: string, runId: string): Promise { const { provider, isFallback } = this.#resolveLeaseProvider(pubsub); if (isFallback) return true; // Subscribers process events in order, so a read that never answers would hold every later event, and // initial history waits on those events. An unanswered read counts as no lease, like a failed one. if (this.#isLeaseReadStalled(provider, key)) return false; const read = provider.getLeaseOwner(key); let giveUp: ReturnType | undefined; // A read that answered by the time the deadline fired still wins, even when the deadline settles the race. let reply: boolean | undefined; const answered = await Promise.race([ read.then( owner => (reply = owner !== undefined && threadLeaseRunId(owner) === runId && !isRetakeLeaseOwner(owner)), () => (reply = false), ), new Promise( resolve => (giveUp = setTimeout(() => resolve(undefined), AGENT_THREAD_LEASE_RENEW_INTERVAL_MS)), ), ]).finally(() => clearTimeout(giveUp)); if (answered !== undefined) return answered; if (reply !== undefined) return reply; this.#noteStalledLeaseRead(provider, key, read); return false; } /** * Like #hasLiveThreadLease, but also counts a lease this process holds under a temporary * retake token for `runId`: it waits for that retake and counts the lease only once handed * back to the run. A token minted anywhere else doesn't count. */ async #holdsThreadLeaseThroughRetake(pubsub: PubSub, key: string, runId: string): Promise { const { provider, isFallback } = this.#resolveLeaseProvider(pubsub); if (isFallback) return true; // A backend that fails or doesn't answer in time is no proof the run holds the thread. const owner = await this.#readLeaseOwnerInTime(provider, key).catch(() => undefined); const expectedOwner = this.#threadLeaseOwner(pubsub, runId); if (owner === expectedOwner) return true; if (!isHandoverLeaseOwner(owner) || forwardedSignalRunId(owner!) !== runId) return false; const retake = this.#getState(pubsub).leaseRetakes.get(runId); if (retake) return retake.catch(() => false); // The retake may have settled between the two reads; the owner then names the run again. return (await this.#readLeaseOwnerInTime(provider, key).catch(() => undefined)) === expectedOwner; } /** The lease owner of `key`, rejecting when the backend doesn't answer within one renewal interval. */ async #readLeaseOwnerInTime(provider: LeaseProvider, key: string): Promise { let giveUp: ReturnType | undefined; return Promise.race([ provider.getLeaseOwner(key), new Promise((_, reject) => { giveUp = setTimeout( () => reject(new Error('Thread lease backend did not answer')), AGENT_THREAD_LEASE_RENEW_INTERVAL_MS, ); }), ]).finally(() => clearTimeout(giveUp)); } /** * 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. */ async isRunHoldingThreadLease( pubsub: PubSub | undefined, runId: string, threadId: string, resourceId?: string, ): Promise { const { provider, isFallback } = this.#resolveLeaseProvider(pubsub); if (isFallback) return false; const owner = await provider.getLeaseOwner(this.#threadKey(resourceId, threadId)); return owner !== undefined && threadLeaseRunId(owner) === runId && !isRetakeLeaseOwner(owner); } /** * The owner `runId` holds its thread lease under. A run keeps the owner it acquired the lease with for as long as * it holds it: a generation learned later must not change the owner its renewals, fence and release use. Pass * `generation` only to name the owner a new acquisition takes. */ #threadLeaseOwner(pubsub: PubSub | undefined, runId: string, generation?: number): string { if (!reachesOtherProcesses(this.#getPubSub(pubsub))) return threadLeaseOwner(runId); if (generation !== undefined) return threadLeaseOwner(runId, generation); const state = this.#getState(pubsub); return state.leaseOwners.get(runId) ?? threadLeaseOwner(runId, state.threadRunsById.get(runId)?.generation); } /** @internal Qualify a shared thread lease before dispatching this execution. */ async claimDurableThreadLease( pubsub: PubSub, runId: string, threadId: string, resourceId: string | undefined, generation: number | undefined, executionId?: string, workerFenced = false, ): Promise { const key = this.#threadKey(resourceId, threadId); const owner = threadLeaseOwner(runId, generation, executionId); let lease = await this.#acquireThreadLease(pubsub, key, runId, owner); const previousOwner = parseThreadLeaseOwner(lease.owner); if ( !lease.acquired && (lease.owner === undefined || (previousOwner && previousOwner[0] !== runId && (previousOwner[1] === 'generation' || previousOwner[1] === 'execution'))) ) { // A shared evented worker can publish finish before releasing the thread. An // ownerless failure can mean the lease disappeared between the claim and owner lookup. // Retry within the same deadline, but don't wait behind a new owner. const blockingOwner = lease.owner; const deadline = Date.now() + DURABLE_THREAD_CLAIM_WAIT_MS; while (!lease.acquired && (lease.owner === undefined || lease.owner === blockingOwner)) { const remaining = deadline - Date.now(); if (remaining <= 0) break; await new Promise(resolve => setTimeout(resolve, Math.min(remaining, DURABLE_THREAD_CLAIM_POLL_MS))); lease = await this.#acquireThreadLease(pubsub, key, runId, owner); } } if (!lease.acquired) throw new AgentThreadLeaseConflictError(runId, lease.owner ?? 'another owner'); if (this.#getState(pubsub).leaseRenewalTimers.has(runId)) { this.#stopLeaseRenewal(pubsub, runId); this.#startLeaseRenewal(pubsub, key, runId, owner, workerFenced); } } /** @internal Renew only the captured execution's thread lease; never acquire or transfer it. */ async renewDurableThreadLease( pubsub: PubSub, runId: string, threadId: string, resourceId?: string, generation?: number, executionId?: string, ): Promise { return this.#getLeaseProvider(pubsub).renewLease( this.#threadKey(resourceId, threadId), threadLeaseOwner(runId, generation, executionId), AGENT_THREAD_LEASE_TTL_MS, ); } /** * @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. */ async reclaimDurableThreadLease( pubsub: PubSub, runId: string, threadId: string, resourceId?: string, generation?: number, executionId?: string, ): Promise { const { acquired } = await this.#getLeaseProvider(pubsub).acquireLease( this.#threadKey(resourceId, threadId), threadLeaseOwner(runId, generation, executionId), AGENT_THREAD_LEASE_TTL_MS, ); return acquired; } /** @internal Missing ownership is not evidence that another run took the thread. */ async isDurableThreadLeaseHeldByAnotherRun( pubsub: PubSub, runId: string, threadId: string, resourceId?: string, ): Promise { const owner = await this.#getLeaseProvider(pubsub).getLeaseOwner(this.#threadKey(resourceId, threadId)); return owner !== undefined && threadLeaseRunId(owner) !== runId; } /** @internal Whether `error` from the thread lease backend means it is refusing every client, not just this one. */ isThreadLeaseBackendUnavailableToAll(pubsub: PubSub, error: unknown): boolean { return this.#getLeaseProvider(pubsub).isUnavailableToAll?.(error) === true; } /** @internal Release only the terminal execution's thread lease, never a recovered successor's. */ async releaseDurableThreadLease( pubsub: PubSub, runId: string, threadId: string, resourceId?: string, generation?: number, executionId?: string, ): Promise { await this.#getLeaseProvider(pubsub).releaseLease( this.#threadKey(resourceId, threadId), threadLeaseOwner(runId, generation, executionId), ); } /** @internal Stop this process renewing an abandoned execution's thread lease, then release it. */ async abandonDurableThreadLease( pubsub: PubSub, runId: string, threadId: string, resourceId?: string, generation?: number, executionId?: string, ): Promise { const owner = threadLeaseOwner(runId, generation, executionId); if (this.#getState(pubsub).leaseOwners.get(runId) === owner) this.#stopLeaseRenewal(pubsub, runId); await this.#getLeaseProvider(pubsub).releaseLease(this.#threadKey(resourceId, threadId), owner); } async #acquireThreadLease( pubsub: PubSub, key: string, runId: string, owner: string, ): Promise<{ acquired: boolean; owner?: string }> { const provider = this.#getLeaseProvider(pubsub); const lease = await provider.acquireLease(key, owner, AGENT_THREAD_LEASE_TTL_MS); if (lease.acquired || !lease.owner || threadLeaseRunId(lease.owner) !== runId || isRetakeLeaseOwner(lease.owner)) return lease; const previousIdentity = parseThreadLeaseOwner(lease.owner); const identity = parseThreadLeaseOwner(owner); if ( identity?.[1] !== 'generation' || (previousIdentity !== undefined && previousIdentity[1] !== 'run' && (previousIdentity[1] !== 'generation' || previousIdentity[2] >= identity[2])) ) return lease; const acquired = await provider.transferLease(key, lease.owner, owner, AGENT_THREAD_LEASE_TTL_MS); return { acquired, owner: acquired ? owner : lease.owner }; } /** * 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. */ async getThreadLeaseOwnerRunId( pubsub: PubSub | undefined, options: AgentThreadIdentityOptions, ): Promise { const { provider, isFallback } = this.#resolveLeaseProvider(pubsub); if (isFallback) return undefined; const owner = await this.#readLeaseOwnerInTime(provider, this.#threadKey(options.resourceId, options.threadId)); return owner ? forwardedSignalRunId(owner) : 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 { return this.#publishAndWait(this.#getPubSub(pubsub), this.#threadKey(options.resourceId, options.threadId), { type: 'run-abort-requested', runId, ...(options.clearPendingSignals ? { clearPendingSignals: true } : {}), }); } /** How long a thread lease outlives the process that stopped renewing it. */ get threadLeaseTtlMs(): number { return AGENT_THREAD_LEASE_TTL_MS; } /** * @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. */ async shutdown( pubsub: PubSub | undefined, owner: unknown, { abortGraceMs, executesElsewhere = () => false, }: { abortGraceMs: number; executesElsewhere?: (runId: string) => boolean }, ): Promise { const resolved = this.#getPubSub(pubsub); const state = this.#statesByPubSub.get(resolved); if (!state) return; const { provider, isFallback } = this.#resolveLeaseProvider(resolved); const records = [...state.threadRunsById.values()].filter( record => record.agent.getMastraInstance?.() === owner && !state.shutdownStreams.has(record.streamId), ); const handBack = async (record: AgentThreadRunRecord) => { const { runId, streamId } = record; if (executesElsewhere(runId)) { // Another process executes this run and keeps its thread lease alive; leave the thread to it. this.#stopLeaseRenewal(resolved, runId); return; } // A run is parked only once its suspension settled and no step of it still executes. A partially resumed run is // still parked on its sibling suspensions while its resumed segment executes, and a step raising a suspension // can end its segment while a sibling tool call of that step still executes: both are aborted like any executing // run. Neither its suspension bookkeeping nor the output a resumed segment reuses says whether it still executes. // A durable run's steps register under its registry entry instead; abandoning the run already aborted them. const preparedRun = state.preparedRunsById.get(runId); const controller = preparedRun?.abortController ?? record.segmentAbortController; const stepOwners = [controller?.signal, record.stepOwner?.()].filter(owner => owner !== undefined); const executing = (!!preparedRun && record.lifecycle !== 'suspended') || stepOwners.some(owner => hasRunningRunStep(owner)); const abortController = executing ? controller : undefined; if (!state.leaseRenewalTimers.has(runId) || record.registeredElsewhere || record.lateRetakeHandoff) { // Another execution has the thread; it ends the run and releases the thread. abortController?.abort(); this.#stopLeaseRenewal(resolved, runId); return; } const key = state.threadKeysByRunId.get(runId) ?? this.#threadKey(record.resourceId, record.threadId); const leaseOwner = state.leaseOwners.get(runId) ?? record.leaseOwner ?? this.#threadLeaseOwner(resolved, runId); // From here the run's own end neither publishes nor gives up its lease: shutdown does both below. state.shutdownStreams.set(streamId, 'ending'); abortController?.abort(); // Ask the lease backend rather than the record: a durable run this Mastra just abandoned counts as having lost // its execution, yet still holds its thread here until released. The read runs while the run winds down and // shares its grace, so a slow backend can neither keep the run executing nor outlast shutdown; a backend that // doesn't answer in time leaves the lease to expire. The run has stopped once its output finished and no step // of it, such as a tool call ignoring the abort, still executes. const [holdsLease, stopped] = await Promise.all([ isFallback || this.#withinGrace( this.#readLeaseOwnerInTime(provider, key).then( current => current === leaseOwner, () => false, ), abortGraceMs, false, ), executing ? this.#withinGrace( Promise.allSettled([ preparedRun && (record.currentSegmentOutput ?? record.output)._waitUntilFinished(), preparedRun && record.broadcastFinished, ...stepOwners.map(owner => new Promise(resolve => whenRunStepsSettle(owner, resolve))), ]).then(() => true), abortGraceMs, false, ) : true, ]); state.shutdownStreams.set(streamId, 'ended'); const event: AgentThreadStreamRuntimeEvent = this.#isParkedRun(state, runId) ? { type: 'run-suspended', runId, streamId } : hasDurableExecution(record.agent) ? // Not final: durable recovery can continue the run under the same runId. Older subscribers read it as failed. { type: 'run-completed', runId, streamId, persisted: false, status: 'interrupted' } : // Nothing recovers a regular agent's run, so the hand-back ends it. { type: 'run-completed', runId, streamId, persisted: false }; // Release even if the publish failed: holding the lease past this process only delays every observer by a TTL. await this.#publishAndWait(resolved, key, event).catch(() => {}); this.#stopLeaseRenewal(resolved, runId); if (!stopped) { // The run's output didn't finish after the abort, so it may still call tools or write: fail its remaining // tool calls and leave the lease to expire instead of handing the thread over now. const handedBack = async () => { throw new AgentThreadLeaseLostError(runId); }; state.leaseFences.set(runId, handedBack); setRunLeaseFence(runId, handedBack); return; } if (holdsLease) await provider.releaseLease(key, leaseOwner).catch(() => {}); }; await Promise.all(records.map(handBack)); } /** `promise`'s value, or `fallback` once `ms` pass first. */ async #withinGrace(promise: Promise, ms: number, fallback: T): Promise { let timer: ReturnType | undefined; return Promise.race([ promise, new Promise(resolve => { timer = setTimeout(() => resolve(fallback), ms); }), ]).finally(() => clearTimeout(timer)); } #getSourceId(): string { this.#id ??= globalThis.crypto.randomUUID(); return this.#id; } /** * Whether `runId` is a suspended run this instance's TTL sweep evicted whose kept * lease may still be held. Nothing here consumes signals for it any more. */ /** * Whether a run on this thread was started with exactly `scopes` as its call scopes. A run * whose scopes this process can't see (owned by another process, or reserved without going * through an idle start) never matches, so a signal naming scopes waits for it instead. */ #runHoldsScopes(state: AgentThreadRuntimeState, runId: string, scopes: readonly string[]): boolean { const record = state.threadRunsById.get(runId); if (record) return sameScopes(record.streamOptions?.scopes ?? [], scopes); if (!state.reservedRunScopes.has(runId)) return false; return sameScopes(state.reservedRunScopes.get(runId) ?? [], scopes); } /** Whether `runId` already names a run this runtime knows about (active, retained, reserved, queued or remote). */ #isRunIdInUse(state: AgentThreadRuntimeState, runId: string): boolean { if ( state.threadRunsById.has(runId) || state.threadKeysByRunId.has(runId) || state.reservedRunScopes.has(runId) || state.remoteThreadKeysByRunId.has(runId) || state.startingQueuedRunIds.has(runId) || state.persistingIdleRunIds.has(runId) || state.preparedRunsById.has(runId) ) { return true; } for (const queue of state.pendingIdleSignalsByThread.values()) { if (queue.some(pending => pending.runId === runId)) return true; } for (const draining of state.drainingIdleSignalsByThread.values()) { if (draining.runId === runId) return true; } for (const queue of state.pendingContinuationsByThread.values()) { if (queue.some(pending => pending.runId === runId)) return true; } return false; } /** * The run id a signal-started run uses: the caller's `ifIdle.streamOptions.runId` when * non-empty, else a fresh one (`agent.stream()` also replaces an empty id). A caller id naming a run already known here is refused. */ #idleStartRunId( state: AgentThreadRuntimeState, requestedRunId: string | undefined, ): { runId: string; refused?: undefined } | { runId?: undefined; refused: Promise } { if (!requestedRunId) return { runId: globalThis.crypto.randomUUID() }; if (!this.#isRunIdInUse(state, requestedRunId)) return { runId: requestedRunId }; const refused = Promise.reject( new Error(`Run id "${requestedRunId}" is already in use; ifIdle.streamOptions.runId must name a new run.`), ); void refused.catch(() => {}); return { refused }; } #isSweptLeaseOwner(state: AgentThreadRuntimeState, runId: string): boolean { const sweptAt = state.sweptLeasedRunIds.get(runId); if (sweptAt === undefined || state.threadRunsById.has(runId)) return false; // A renewal still in flight may yet extend the kept lease, however old the marker is. return Date.now() - sweptAt <= AGENT_THREAD_LEASE_TTL_MS || state.pendingLeaseRenewals.has(runId); } /** * Fire-and-forget release of the cross-process thread lease held by * this owner. Safe to call when no lease was ever acquired — the * pubsub's `releaseLease` is a no-op for non-owners (Lua-guarded * GET+DEL on Redis), and the default in-memory implementation is * identical. Also stops the renewal timer if one is running for * this run. */ #releaseThreadLease(pubsub: PubSub | undefined, key: string, runId: string, owner?: string): void { const resolved = this.#getPubSub(pubsub); const state = this.#getState(resolved); const current = this.#threadLeaseOwner(pubsub, runId); // An execution whose run id a successor re-registered under its own owner gives back only what it held. if (owner !== undefined && owner !== current && state.leaseOwners.has(runId)) { void this.#getLeaseProvider(resolved) .releaseLease(key, owner) .catch(() => {}); return; } this.#stopLeaseRenewal(resolved, runId); void this.#getLeaseProvider(resolved) .releaseLease(key, owner ?? current) .catch(() => {}); this.#releaseUnusedThreadControlSubscription(state, key); } /** * Start a background timer that renews the cross-process lease at * TTL/3 intervals while the run is still going. If the lease is lost * (e.g. expired due to clock skew or pubsub outage) the renewal stops * and the run is aborted, since a successor may already own the thread. * * A renewal that rejects or never settles proves nothing either way, so * the run also keeps a local deadline one TTL after the send time of its * last confirmed acquire or renewal. The backend's lease can't outlive * that point, so once it passes a successor may own the thread and the * run is aborted, even if the backend never answers. */ #startLeaseRenewal( pubsub: PubSub, key: string, runId: string, owner = this.#threadLeaseOwner(pubsub, runId), workerFenced = false, confirmedSentAt = Date.now(), ): void { const state = this.#getState(pubsub); if (state.leaseRenewalTimers.has(runId)) { if (state.leaseOwners.get(runId) === owner) return; this.#stopLeaseRenewal(pubsub, runId); } const leaseProvider = this.#getLeaseProvider(pubsub); // Shared evented dispatch delegates lease-loss decisions to the worker's execution fence. const timer = setInterval(() => { if (workerFenced && state.pendingLeaseRenewals.has(runId)) return; const sentAt = Date.now(); state.pendingLeaseRenewals.set(runId, (state.pendingLeaseRenewals.get(runId) ?? 0) + 1); void leaseProvider .renewLease(key, owner, AGENT_THREAD_LEASE_TTL_MS) .then(renewed => { if (!renewed) { if (workerFenced) return; // A renewal that settles after the run ended or re-registered speaks for no live run, and must not // leave a rejecting fence behind for a later run with this id. if (state.leaseRenewalTimers.get(runId) !== timer) return; // Answered after the lease had already run out by this process's own clock, the renewal may have found the // lease lapsed only because this process was late (a stall under load, even one that began after the // renewal went out); it can take it back if nobody else did. Answered while the lease should still have // been live, it means the backend lost or gave away a live lease, and another process may already own the // thread: stop this run instead of letting it keep calling the model and tools beside its successor. const confirmed = state.leaseDeadlines.get(runId)?.confirmedSentAt; const lapsedHere = confirmed === undefined || Date.now() >= confirmed + AGENT_THREAD_LEASE_TTL_MS; const retaken = lapsedHere ? this.#retakeLease(pubsub, key, runId, timer) : Promise.resolve(false); void retaken.then(kept => { if (kept || state.leaseRenewalTimers.get(runId) !== timer) return; this.#stopLeaseRenewal(pubsub, runId, timer); this.#abortLeaseLostRun(state, runId); }); } else { if (!workerFenced && state.leaseRenewalTimers.get(runId) === timer) { this.#armLeaseDeadline(pubsub, key, runId, sentAt); } if (state.sweptLeasedRunIds.has(runId)) { // A renewal in flight when the sweep stopped this timer still extended the lease. state.sweptLeasedRunIds.set(runId, Date.now()); } } }) // A failed renewal leaves the deadline in place: the run stops once the lease may have lapsed. .catch(() => {}) // Stop counting the renewal only after the marker is refreshed, so nothing sees a stale marker in between. .finally(() => { const pending = (state.pendingLeaseRenewals.get(runId) ?? 1) - 1; if (pending > 0) state.pendingLeaseRenewals.set(runId, pending); else state.pendingLeaseRenewals.delete(runId); }); }, AGENT_THREAD_LEASE_RENEW_INTERVAL_MS); // Don't keep the process alive solely to renew a lease. if (typeof timer === 'object' && timer && typeof (timer as any).unref === 'function') { (timer as any).unref(); } state.leaseRenewalTimers.set(runId, timer); state.leaseOwners.set(runId, owner); if (workerFenced) return; // The lease was acquired or transferred just before this call. this.#armLeaseDeadline(pubsub, key, runId, confirmedSentAt); // A pubsub that can't lease has no owner to check, so every tool call would look like a takeover. if (!this.#resolveLeaseProvider(pubsub).isFallback) { const fence = this.#leaseFence(pubsub, key, runId, timer, owner); state.leaseFences.set(runId, fence); setRunLeaseFence(runId, fence); } } /** * Checked before each tool call. Renewals run every TTL/3, so a lease that was * taken over is otherwise only noticed after the run may have called tools beside * its successor. A backend that can't answer leaves the decision to the deadline. * A lease that lapsed past the run's deadline with no other owner is taken back rather than stopping the run. */ #leaseFence( pubsub: PubSub, key: string, runId: string, timer: ReturnType, expectedOwner: string, ): () => Promise { const state = this.#getState(pubsub); const leaseProvider = this.#getLeaseProvider(pubsub); return async () => { const deadline = state.leaseDeadlines.get(runId); if (state.leaseRenewalTimers.get(runId) !== timer || !deadline) return; let onExpired: (value: undefined) => void = () => {}; const expiredAt = new Promise(resolve => (onExpired = resolve)); const expired = setTimeout( () => onExpired(undefined), Math.max(0, deadline.confirmedSentAt + AGENT_THREAD_LEASE_TTL_MS - Date.now()), ); const unreachable = Symbol('unreachable'); let owner = await Promise.race([leaseProvider.getLeaseOwner(key).catch(() => unreachable), expiredAt]).finally( () => clearTimeout(expired), ); // A check that began before this process moved the run onto a new owner (a generation learned at // registration) reads the new owner; the run still holds the lease under it. const heldByRun = (current: unknown) => current === expectedOwner || (state.leaseRenewalTimers.get(runId) !== timer && current !== undefined && current === state.leaseOwners.get(runId)); if (heldByRun(owner)) return; // This run's own retake holds the lease under a temporary token until it hands it to the run id, which a // queued tool call can still catch in flight. Nobody else took the thread, so the run keeps it. if (typeof owner === 'string' && threadLeaseRunId(owner) === runId && isRetakeLeaseOwner(owner)) { const retake = state.leaseRetakes.get(runId); if (await (retake ?? Promise.resolve(false))) return; // That check may have settled it, so read the owner once more. Bound that read by one renewal interval: // a backend that answered the token and then stalls must not leave this fence pending. A silent read is // reported as unreachable, and every answer falls through to the policy below exactly like the first read. let giveUp: ReturnType | undefined; owner = await Promise.race([ leaseProvider.getLeaseOwner(key).catch(() => unreachable), new Promise( resolve => (giveUp = setTimeout(() => resolve(unreachable), AGENT_THREAD_LEASE_RENEW_INTERVAL_MS)), ), ]).finally(() => clearTimeout(giveUp)); if (owner === expectedOwner) return; } // A backend error only passes while the last confirmed renewal still covers this call. if (owner === unreachable) { const covering = state.leaseDeadlines.get(runId); if (covering && Date.now() < covering.confirmedSentAt + AGENT_THREAD_LEASE_TTL_MS) return; } // Past the deadline with no owner, or no answer: the lease lapsed while this process was late, and is this // run's again if nobody took it. No owner before the deadline means the backend lost a live lease. const current = state.leaseDeadlines.get(runId); const pastDeadline = !current || Date.now() >= current.confirmedSentAt + AGENT_THREAD_LEASE_TTL_MS; if (typeof owner !== 'string' && pastDeadline && (await this.#retakeLease(pubsub, key, runId, timer))) return; // Only the registration that owns this fence may stop the run. if (state.leaseRenewalTimers.get(runId) === timer) { this.#stopLeaseRenewal(pubsub, runId, timer); this.#abortLeaseLostRun(state, runId); } // A parked run calls no tools, so this call belongs to a resume of it. A resume on another server holds the // lease under this run id (a newer generation), and its step's delivery ownership is checked on its own, so // the parked registration doesn't stop it. A different run holding the thread is still a takeover. if ( state.threadRunsById.get(runId)?.lifecycle === 'suspended' && typeof owner === 'string' && threadLeaseRunId(owner) === runId ) { return; } throw new AgentThreadLeaseLostError(runId); }; } #armLeaseDeadline(pubsub: PubSub, key: string, runId: string, confirmedSentAt: number): void { const state = this.#getState(pubsub); const previous = state.leaseDeadlines.get(runId); // A slow renewal that settles after a newer one must not pull the deadline back. if (previous && previous.confirmedSentAt >= confirmedSentAt) return; if (previous) clearTimeout(previous.timer); const timer = setTimeout( () => { if (state.leaseDeadlines.get(runId)?.timer !== timer) return; // The lease may have lapsed, say while this process stalled past the TTL. The run keeps going only // if it gets the lease back, which it can't when another run took the thread. const renewal = state.leaseRenewalTimers.get(runId); void (renewal ? this.#retakeLease(pubsub, key, runId, renewal) : Promise.resolve(false)).then(kept => { if (kept || (renewal && state.leaseRenewalTimers.get(runId) !== renewal)) return; this.#stopLeaseRenewal(pubsub, runId); this.#abortLeaseLostRun(state, runId); }); }, Math.max(0, confirmedSentAt + AGENT_THREAD_LEASE_TTL_MS - Date.now()), ); if (typeof timer === 'object' && timer && typeof (timer as any).unref === 'function') { (timer as any).unref(); } state.leaseDeadlines.set(runId, { timer, confirmedSentAt }); } /** * Takes back a lease that lapsed while its run was still going because this process was late: * it stalled past the TTL, so a renewal went out after the lease had run out, or not at all * before the deadline. A free lease is acquired under a token unique to this attempt and then * handed to the run id; a lease still held under the run id is taken again under it. A run another process * took over under a different id is still stopped. A retake granted after this run gave up * releases only a grant made under its own token: a lease under the run id may be a successor's * (a durable recover takes the run under the same id), so it is left to expire. * The run keeps calling the model while this waits, so a backend that doesn't answer within one * renewal interval counts as a lost lease: a process that only stalled answers at once when it runs again. */ #retakeLease(pubsub: PubSub, key: string, runId: string, timer: ReturnType): Promise { const state = this.#getState(pubsub); const inFlight = state.leaseRetakes.get(runId); if (inFlight) return inFlight; // The record this attempt belongs to. A later run can register under the same id while this attempt is in // flight, so the marking below must use this reference and never a fresh lookup that could land on it. const record = state.threadRunsById.get(runId); const expectedOwner = this.#threadLeaseOwner(pubsub, runId); const sentAt = Date.now(); const leaseProvider = this.#getLeaseProvider(pubsub); const newToken = () => encodeThreadLeaseOwner([runId, 'retake', globalThis.crypto.randomUUID()]); let token = newToken(); // Tokens this retake gave back. A release can land after the next acquire, which then names one as the owner. const released = new Set(); const releaseToken = (held = token) => { released.add(held); void leaseProvider.releaseLease(key, held).catch(() => {}); }; /** * `token` when it acquired a free lease under the token, `run` when the lease was still under the run id, * `refused` when another owner holds it, `unavailable` when the backend refused every client (so nobody else * could take the thread either), and `unanswered` when the backend failed to answer. */ const take = async (asked: string): Promise<'token' | 'run' | 'refused' | 'unavailable' | 'unanswered'> => { // A token this retake already gave back, whose release hasn't landed yet: the thread is still this run's. const heldByReleasedToken = (owner: string | undefined) => owner !== undefined && released.has(owner); try { let lease = await leaseProvider.acquireLease(key, asked, AGENT_THREAD_LEASE_TTL_MS); if (!lease.acquired && asked === token && heldByReleasedToken(lease.owner)) { await leaseProvider.releaseLease(key, lease.owner!); lease = await leaseProvider.acquireLease(key, asked, AGENT_THREAD_LEASE_TTL_MS); } if (lease.acquired) return 'token'; if (heldByReleasedToken(lease.owner)) return 'unanswered'; if (lease.owner !== expectedOwner) return 'refused'; return (await leaseProvider.acquireLease(key, expectedOwner, AGENT_THREAD_LEASE_TTL_MS)).acquired ? 'run' : 'refused'; } catch (error) { return leaseProvider.isUnavailableToAll?.(error) ? 'unavailable' : 'unanswered'; } }; /** * While the run has a step running, a backend that doesn't answer is no reason to stop it: only another owner * is. The retake keeps asking, one renewal interval at a time, until it gets an answer or the run is idle, but * no longer than the grace period after the lease ran out: a backend silent that long is treated as lost too. * A backend refusing every client (restarting, say) can't have given the thread to anyone else, so an idle run * waits for it within the same grace period too. */ const lapsedAt = (state.leaseDeadlines.get(runId)?.confirmedSentAt ?? sentAt) + AGENT_THREAD_LEASE_TTL_MS; let backendUnavailable = false; const keepAsking = () => state.leaseRenewalTimers.get(runId) === timer && Date.now() < lapsedAt + AGENT_LEASE_LOST_TOOL_GRACE_MS && (backendUnavailable || isRunStepActive( state.preparedRunsById.get(runId)?.abortController.signal ?? record?.stepOwner?.(), AGENT_THREAD_LEASE_RENEW_INTERVAL_MS, )); const retake = (async () => { // One renewal interval bounds each attempt, handoff included: a thread this process can't take back within // it counts as lost unless a step is running, so the deadline, renewal and fence paths never wait on a silent // backend for an idle run. let giveUpAt = sentAt + AGENT_THREAD_LEASE_RENEW_INTERVAL_MS; const gaveUp = Symbol('gave-up'); const remaining = (work: Promise) => { const left = giveUpAt - Date.now(); if (left <= 0) return Promise.resolve(gaveUp); let giveUp: ReturnType | undefined; return Promise.race([ work, new Promise(resolve => (giveUp = setTimeout(() => resolve(gaveUp), left))), ]).finally(() => clearTimeout(giveUp)) as Promise; }; // Every attempt of a round asks under the same token, and acquiring a lease its owner already holds succeeds, // so a late grant of an earlier attempt never reads as another owner. The first answer wins; attempts that // answer after the round settled give back what they took. let taken: 'token' | 'run'; let takenSentAt: number; let handoverRetryDelay = 5; for (;;) { const asked = token; let settled = false; let answer!: (result: { taken: 'token' | 'run' | 'refused'; sentAt: number }) => void; const answered = new Promise<{ taken: 'token' | 'run' | 'refused'; sentAt: number }>( resolve => (answer = resolve), ); const attempt = () => { const attemptSentAt = Date.now(); void take(asked).then(result => { if (result === 'unavailable' || result === 'unanswered') { backendUnavailable = result === 'unavailable'; return; } if (settled) { if (result === 'token') releaseToken(asked); return; } answer({ taken: result, sentAt: attemptSentAt }); }); }; attempt(); let first = await remaining(answered); while (first === gaveUp && keepAsking()) { giveUpAt = Date.now() + AGENT_THREAD_LEASE_RENEW_INTERVAL_MS; attempt(); first = await remaining(answered); } settled = true; // The run stops now, but the backend may still grant an attempt; that grant is released above. if (first === gaveUp) return false; if (first.taken === 'refused') return false; taken = first.taken; takenSentAt = first.sentAt; if (taken !== 'token') break; // The run ended meanwhile: don't hold its thread for a TTL. if (state.leaseRenewalTimers.get(runId) !== timer) { releaseToken(asked); return false; } const transferring = leaseProvider .transferLease(key, asked, expectedOwner, AGENT_THREAD_LEASE_TTL_MS) .catch(() => false); let handedOver = await remaining(transferring); while (handedOver === gaveUp && keepAsking()) { // Keep the token alive while a slow handover runs, so it can still land. void leaseProvider.renewLease(key, asked, AGENT_THREAD_LEASE_TTL_MS).catch(() => false); giveUpAt = Date.now() + AGENT_THREAD_LEASE_RENEW_INTERVAL_MS; handedOver = await remaining(transferring); } if (handedOver === gaveUp) { // The run stops now. A handoff that lands after this installs the run id on a lease this execution no // longer renews, so this record's end must leave that lease to expire instead of releasing it. The flag // sits on this record, captured when the attempt began: a run that registered under the same id since // then owns its own lease and must not inherit the exemption. if (record) record.lateRetakeHandoff = true; releaseToken(asked); void transferring.then(late => { // Only the attempt that set the flag clears it, and only while that same record still holds the id. if (!late && record && state.threadRunsById.get(runId) === record) record.lateRetakeHandoff = false; }); return false; } if (handedOver) break; releaseToken(asked); // The handoff failed, for instance because the token's lease ran out while it was slow. Nobody else is // known to hold the thread, so a run with a step running takes it again under a new token. A backend that // rejects every handoff at once would otherwise be asked in a tight loop, so wait a little longer each // round, never more than a quarter of the renewal interval so a retake can still land within one. if (!keepAsking()) return false; handoverRetryDelay = Math.min(handoverRetryDelay * 2, AGENT_THREAD_LEASE_RENEW_INTERVAL_MS / 4); await new Promise(resolve => setTimeout(resolve, handoverRetryDelay)); if (!keepAsking()) return false; token = newToken(); giveUpAt = Date.now() + AGENT_THREAD_LEASE_RENEW_INTERVAL_MS; } if (state.leaseRenewalTimers.get(runId) !== timer) { // The run ended meanwhile. A lease this attempt handed over is its own, so free it unless a later // registration of the run now renews it. One it found under the run id may be a successor's: leave it. if (taken === 'token' && !state.leaseRenewalTimers.has(runId)) { void leaseProvider.releaseLease(key, expectedOwner).catch(() => {}); } return false; } this.#armLeaseDeadline(pubsub, key, runId, takenSentAt); return true; })().finally(() => state.leaseRetakes.delete(runId)); state.leaseRetakes.set(runId, retake); return retake; } #abortLeaseLostRun(state: AgentThreadRuntimeState, runId: string): void { const record = state.threadRunsById.get(runId); // A parked run calls neither the model nor tools, so there is nothing to stop, and aborting it would delete the // snapshot it resumes from. It gets no lost fence either: its resumed tool calls would throw on it. Its resume // must hold the lease again, so every resume calls reacquireParkedRunLease before it runs, which refuses the // resume when a successor now holds the thread. The in-place continuation is dropped so the resume registers // again. A run that is still suspending, or a partly resumed run whose sibling suspensions are pending, is still // executing (its lifecycle is not 'suspended'), so it is stopped. if (record?.lifecycle === 'suspended') { record.continuation = undefined; return; } state.leaseLostRunIds.add(runId); // Tool calls the step already queued check the fence after this, so they must keep failing until the // run ends, not find no fence and run beside the successor. const lost = async () => { throw new AgentThreadLeaseLostError(runId); }; state.leaseFences.set(runId, lost); setRunLeaseFence(runId, lost); const preparedRun = state.preparedRunsById.get(runId); // A step already running (a model request or a tool call) finishes, fails or is aborted first: stopping it // mid-way would lose its work, and the fence above already keeps the run from starting a tool. The run stops as // soon as the step settles, before another can start. One that never ends is stopped after a grace period, so it // can't keep working beside the thread's new owner for long. let stopped = false; let grace: ReturnType | undefined; const stop = () => { if (stopped) return; stopped = true; clearTimeout(grace); if (preparedRun) preparedRun.abortController.abort(new AgentThreadLeaseLostError(runId)); // Durable runs own their controller outside the thread runtime. else this.#abortAgentRunStream(state, runId); }; grace = setTimeout(stop, AGENT_LEASE_LOST_TOOL_GRACE_MS); if (typeof grace === 'object' && grace && typeof (grace as any).unref === 'function') (grace as any).unref(); whenRunStepsSettle(preparedRun?.abortController.signal ?? record?.stepOwner?.(), stop); } /** Guard the detached lease-loss callback; awaited control events must reject so the backend can retry. */ #abortAgentRunStream(state: AgentThreadRuntimeState, runId: string): void { try { state.threadRunsById.get(runId)?.agent.abortRunStream?.(runId); } catch { // Nothing to recover: the caller has already fenced the run or released its queue. } } /** * Pass `only` to stop that timer alone, never one a later registration of the run started. * Without `only`, also clears the fence a lost lease left after its renewal had stopped. */ #stopLeaseRenewal(pubsub: PubSub, runId: string, only?: ReturnType): void { const state = this.#getState(pubsub); const timer = state.leaseRenewalTimers.get(runId); if (only ? timer !== only : !timer && !state.leaseFences.has(runId)) return; if (timer) clearInterval(timer); state.leaseRenewalTimers.delete(runId); state.leaseOwners.delete(runId); const fence = state.leaseFences.get(runId); if (fence) clearRunLeaseFence(runId, fence); state.leaseFences.delete(runId); const deadline = state.leaseDeadlines.get(runId); if (deadline) clearTimeout(deadline.timer); state.leaseDeadlines.delete(runId); } /** * Hand the cross-process thread lease from a finishing run (`fromRunId`) * to the run that will drain queued follow-up work next (`toRunId`), * without the lease key ever going empty. * * The previous owner releases its renewal timer and the new owner starts * its own; the lease key is re-stamped by `transferLease` (with a full fresh * TTL). On atomic backends (Redis, in-memory) a racing process cannot win a * freed key between a release and a re-acquire. Backends that can't transfer * atomically implement `transferLease` as release+acquire internally and own * that race cost. Returns `true` if the new owner now holds the lease. */ async #transferThreadLease( pubsub: PubSub | undefined, key: string, fromRunId: string, toRunId: string, ): Promise { const resolved = this.#getPubSub(pubsub); const leaseProvider = this.#getLeaseProvider(resolved); // `transferLease` is a required `LeaseProvider` method. Atomic backends // (Redis, in-memory) swap the key gap-free; backends that can't be atomic // implement it as release+acquire internally and own that race cost. const toOwner = this.#threadLeaseOwner(resolved, toRunId); const held = await leaseProvider .transferLease(key, this.#threadLeaseOwner(resolved, fromRunId), toOwner, AGENT_THREAD_LEASE_TTL_MS) .catch(() => false); // Move the renewal timer to the new owner regardless: the old timer is // owner-guarded and would only no-op now, and the new owner needs its // own keep-alive for long drains. this.#stopLeaseRenewal(resolved, fromRunId); if (held) { this.#startLeaseRenewal(resolved, key, toRunId, toOwner); } return held; } async #waitForRetakeOwner( provider: LeaseProvider, key: string, lease: { acquired: boolean; owner?: string }, ): Promise<{ acquired: boolean; owner?: string }> { if (lease.acquired) return lease; if (!isHandoverLeaseOwner(lease.owner)) return lease; // The token is not a run. Wait briefly for its handover, without acquiring a // new lease that could arrive after this caller has already given up. let stopped = false; let timeout: ReturnType | undefined; try { return await Promise.race([ (async () => { while (!stopped) { await new Promise(resolve => setTimeout(resolve, 10)); if (stopped) break; const owner = await provider.getLeaseOwner(key); // Stop on the first owner that differs from the token, even one shaped like a legacy token: a run id // can contain the marker, and the handover may resolve to it. if (!stopped && owner && owner !== lease.owner && !isRetakeLeaseOwner(owner)) return { acquired: false, owner }; } return lease; })().catch(() => lease), new Promise(resolve => { timeout = setTimeout(() => resolve(lease), AGENT_THREAD_LEASE_RENEW_INTERVAL_MS); }), ]); } finally { stopped = true; clearTimeout(timeout); } } #trackPendingThreadAdmission( state: AgentThreadRuntimeState, key: string, runId: string, agentId: string, outcome: Promise, ): void { const pendingAdmission: PendingThreadAdmission = { runId, agentId, outcome }; state.pendingThreadAdmissions.set(key, pendingAdmission); const clearPendingAdmission = () => { if (state.pendingThreadAdmissions.get(key) === pendingAdmission) { state.pendingThreadAdmissions.delete(key); } }; void outcome.then(clearPendingAdmission, clearPendingAdmission); } #threadAdmissionOutcome(runId: string, lease: { acquired: boolean; owner?: string }): ThreadAdmissionOutcome { if (lease.acquired) return { action: 'local', runId }; if (lease.owner && !isRetakeLeaseOwner(lease.owner)) return { action: 'remote', runId: threadLeaseRunId(lease.owner) }; return { action: 'blocked', runId: lease.owner ? threadLeaseRunId(lease.owner) : runId }; } /** * Ensure this process owns the cross-process lease for `toRunId` before it * starts a run, regardless of whether it already held the lease. * * - When `fromRunId` is provided (draining after a run this process owned), * atomically transfer the held lease to `toRunId` — gap-free, no empty key. * - When `fromRunId` is absent, or the transfer reports the old owner no * longer holds the lease, fall back to a fresh `acquireLease`. This covers * a *different* process that observed the owner finish via pub/sub and now * wants to wake the thread: it never held the lease, so it must win one. * * On success the renewal timer is started for `toRunId`. On failure the * returned `owner` is the current holder so the caller can forward work to it. */ async #acquireOrTransferThreadLease( pubsub: PubSub | undefined, key: string, toRunId: string, fromRunId?: string, ): Promise<{ acquired: boolean; owner?: string }> { const resolved = this.#getPubSub(pubsub); if (fromRunId) { const transferred = await this.#transferThreadLease(pubsub, key, fromRunId, toRunId); if (transferred) return { acquired: true, owner: toRunId }; // Old owner lost the lease before the handoff — fall through to acquire. } const leaseProvider = this.#getLeaseProvider(resolved); const owner = this.#threadLeaseOwner(resolved, toRunId); const result = await this.#acquireThreadLease(resolved, key, toRunId, owner).catch(() => ({ acquired: false as boolean, owner: undefined as string | undefined, })); if (result.acquired) { this.#startLeaseRenewal(resolved, key, toRunId, owner); return { acquired: true, owner: toRunId }; } return this.#waitForRetakeOwner(leaseProvider, key, result); } /** * Whether the thread has any queued follow-up work that a finishing run's * completion handler would drain next: pending follow-up signals (including * any pre-run leftover that will be folded in), queued continuations, or * queued idle signals. */ #hasPendingThreadWork(state: AgentThreadRuntimeState, key: string): boolean { return ( (state.pendingSignalsByThread.get(key)?.length ?? 0) > 0 || (state.preRunSignalsByThread.get(key)?.length ?? 0) > 0 || (state.pendingContinuationsByThread.get(key)?.length ?? 0) > 0 || (state.pendingIdleSignalsByThread.get(key)?.length ?? 0) > 0 ); } #ensureThreadControlSubscription( state: AgentThreadRuntimeState, pubsub: PubSub | undefined, key: string, ): ThreadControlSubscription { const ownedRunIds = new Set( [...state.threadKeysByRunId].filter(([, threadKey]) => threadKey === key).map(([runId]) => runId), ); const existing = state.threadControlSubscriptions.get(key); if (existing) { for (const runId of ownedRunIds) existing.ownedRunIds.add(runId); return existing; } const resolvedPubSub = this.#getPubSub(pubsub); const topic = this.#threadTopic(key); let active = true; let tail = Promise.resolve(); const handleEvent = async (event: Parameters[0]) => { if (!active) return; const data = event.data as AgentThreadStreamRuntimeEvent | undefined; if (data?.type === 'signal-enqueued') { if ( (data.sourceId === this.#id && this.#isLocalSignalEcho(state, key, data.signal.id, data.runId)) || subscription.admittedSignalIds.has(data.signal.id) ) return; // Keep predecessor routing through a handoff, but never promote observer copies into execution. const answersTo = (runId: string) => state.threadKeysByRunId.get(runId) === key || subscription.ownedRunIds.has(runId); // A sender on another lease-owner format forwards the lease owner verbatim. Use the literal // address when a run here answers to it (a caller run ID may look like an encoded owner). const runId = answersTo(data.runId) ? data.runId : forwardedSignalRunId(data.runId); if (!answersTo(runId)) { return; } const queues = data.preRun ? state.preRunSignalsByThread : state.pendingSignalsByThread; if ( [state.preRunSignalsByThread.get(key), state.pendingSignalsByThread.get(key)].some(queue => queue?.some(signal => signal.id === data.signal.id), ) ) return; const signal = createSignal(data.signal); // Not awaited: if the run ended while this runtime waited on the publish, the forwarder would settle its copy // on this event while this runtime never queued it, losing the message. if (this.#pendingUserMessageChunk(runId, signal, 'pending')) { this.#publish(pubsub, key, { type: 'user-message-admitted', signalId: signal.id, admittedRunId: runId }); } const queue = queues.get(key) ?? []; queue.push(signal); queues.set(key, queue); subscription.admittedSignalIds.add(data.signal.id); this.#publishPendingUserMessage(pubsub, key, runId, signal, 'pending'); this.#notifyPendingSignals(state, key, signal); } else if (data?.type === 'user-message-admitted') { this.#settleForwardedIdleSignal(state, key, data.signalId, data.admittedRunId); } else if (data?.type === 'user-message-presentation') { // Owners that predate user-message-admitted only announce the admission this way. const { chunk } = data; if (chunk.type === 'data-user-message-pending' && chunk.data.metadata?.status === 'pending') { this.#settleForwardedIdleSignal(state, key, chunk.data.id, chunk.runId); } } else if (data?.type === 'signals-cancelled') { for (const id of data.signalIds) this.#settleForwardedIdleSignal(state, key, id); // A backend retry can deliver the original enqueue after its cancellation. for (const id of data.signalIds) subscription.admittedSignalIds.add(id); this.#cancelPendingSignals(state, key, new Set(data.signalIds), pubsub); this.#notifyThreadEvents(state); } else if (data?.type === 'run-abort-requested') { const ownsRun = () => active && (state.preparedRunsById.has(data.runId) || state.threadRunsById.has(data.runId)) && state.threadKeysByRunId.get(data.runId) === key && state.activeThreadRunIds.get(key) === data.runId && (data.streamId === undefined || state.activeThreadStreamIds.get(key) === data.streamId); // Queued input is cleared only while this run still holds the lease: after a // handover it may belong to the successor. The run itself is stopped either way, // since one that lost its lease keeps running until its renewal or deadline notices. const clearPendingSignals = ownsRun() && data.clearPendingSignals && (await this.#holdsThreadLeaseThroughRetake(resolvedPubSub, key, data.runId)); if (ownsRun()) { if (clearPendingSignals) this.#cancelPendingSignals(state, key, undefined, pubsub); if (state.preparedRunsById.has(data.runId) || this.#isParkedRun(state, data.runId)) { // A parked (suspended) run has no prepared run left, but abortRun's // parked branch releases it so the thread stops blocking on it. this.abortRun(data.runId, resolvedPubSub); } else { // Durable runs own their controller outside the thread runtime. state.threadRunsById.get(data.runId)?.agent.abortRunStream?.(data.runId); } if (clearPendingSignals) this.#notifyThreadEvents(state); } } else if (data?.type === 'run-registered') { // Recorded whether or not the local run has parked yet: a run that starts // while it is still streaming can end after it parks. const localRunId = this.#localActiveRunId(state, key); if (localRunId !== undefined && localRunId !== data.runId && !state.threadRunsByStreamId.has(data.streamId)) { subscription.supersedingRunIds.set(data.runId, localRunId); } const lost = state.lostRunsByThread.get(key); if (data.sourceId === this.#id) { const record = state.threadRunsByStreamId.get(data.streamId) ?? (lost?.streamId === data.streamId ? lost : undefined); if (record) record.registrationSeen = true; return; } // Registrations of the run read before this process's own are history // (e.g. a replayed backlog); one read after it is a later execution. const current = state.threadRunsById.get(data.runId); if (current?.registrationSeen) current.registeredElsewhere = true; if (lost?.runId === data.runId && lost.registrationSeen) { state.lostRunsByThread.delete(key); this.#handOffQueuedSignals(state, resolvedPubSub, key, data.runId, lost.streamId); } } else if (data?.type === 'run-aborted' || data?.type === 'run-discarded') { // A superseding run that parks and is then aborted, or whose // registration is rolled back, never publishes a completion. this.#releaseRunSupersededBy(state, resolvedPubSub, key, subscription, data.runId); // A discarded run never starts, so it admits nothing. A stopped run still admits until its stream ends and // then completes; one stopped while parked never completes, and the lease check covers it. // A discard can roll back an older registration of a run that still lives under a newer one, which may have // admitted the forward already; while the lease still names the run (or can't be read), keep holding. if ( data.type === 'run-discarded' && !( state.forwardedIdleLeaseChecks.has(key) && (await this.#leaseMayStillName(resolvedPubSub, key, data.runId)) ) && this.#requeueUnadmittedForwards(state, key, data.runId) ) { await this.#drainPendingIdleSignals(state, resolvedPubSub, key, data.runId); } } else if (data?.type === 'run-completed' || data?.type === 'run-failed') { this.#releaseRunSupersededBy(state, resolvedPubSub, key, subscription, data.runId); const lostStreamId = subscription.successorRunIds.get(data.runId); // The lost segment ended but the run goes on elsewhere: its forwards stay held so its admission settles them. if (lostStreamId !== undefined && data.streamId === lostStreamId) return; // A superseded end hands the run to another execution this runtime never registered, so it has no successor // id for it. The lease check requeues the forwards if that execution never admits them; without a lease // check (no lease provider) requeue now. if ( lostStreamId === undefined && data.type === 'run-completed' && data.superseded && state.forwardedIdleLeaseChecks.has(key) ) { return; } const requeued = this.#requeueUnadmittedForwards(state, key, data.runId); if (lostStreamId === undefined) { // Like a remote completion drain, take the lease over from the ended run if it still holds it. if (requeued) await this.#drainPendingIdleSignals(state, resolvedPubSub, key, data.runId); return; } subscription.successorRunIds.delete(data.runId); if (await this.#drainPendingContinuations(state, resolvedPubSub, key, data.runId)) return; await this.#drainPendingIdleSignals(state, resolvedPubSub, key, data.runId); } }; const onEvent: EventCallback = (event, ack) => { const type = (event.data as AgentThreadStreamRuntimeEvent | undefined)?.type; const awaitingForwards = state.forwardedIdleSignalsByThread.has(key); if ( type !== 'signal-enqueued' && type !== 'signals-cancelled' && type !== 'run-abort-requested' && type !== 'run-registered' && !((type === 'user-message-presentation' || type === 'user-message-admitted') && awaitingForwards) && !( (type === 'run-completed' || type === 'run-failed') && // While a local run is active, its superseding runs are looked up in // handleEvent: their registration may still be queued behind `tail`. (awaitingForwards || subscription.successorRunIds.has((event.data as { runId: string }).runId) || this.#localActiveRunId(state, key) !== undefined) ) && !((type === 'run-aborted' || type === 'run-discarded') && this.#localActiveRunId(state, key) !== undefined) && !(type === 'run-discarded' && awaitingForwards) ) return ack?.(); // Finish acknowledging the delivery before an empty queue can release its listener. subscription.references++; const handled = tail.then(() => handleEvent(event)); tail = handled.catch(() => {}); return handled .then(() => ack?.()) .finally(() => { subscription.references--; this.#releaseUnusedThreadControlSubscription(state, key); }); }; const subscription: ThreadControlSubscription = { ready: Promise.resolve(), references: 0, observers: 0, ownedRunIds, admittedSignalIds: new Set(), successorRunIds: new Map(), supersedingRunIds: new Map(), unsubscribe: () => { active = false; void subscription.ready.then(() => resolvedPubSub.unsubscribe(topic, onEvent)).catch(() => {}); }, }; state.threadControlSubscriptions.set(key, subscription); subscription.ready = resolvedPubSub.subscribe(topic, onEvent).catch(error => { if (state.threadControlSubscriptions.get(key) === subscription) state.threadControlSubscriptions.delete(key); active = false; void resolvedPubSub.unsubscribe(topic, onEvent).catch(() => {}); throw error; }); // Synchronous queue APIs install immediately; their async execution/acceptance paths await readiness. void subscription.ready.catch(() => {}); return subscription; } #releaseUnusedThreadControlSubscription(state: AgentThreadRuntimeState, key: string) { const subscription = state.threadControlSubscriptions.get(key); if ( !subscription || subscription.references > subscription.observers || this.#hasPendingThreadWork(state, key) || state.forwardedIdleSignalsByThread.has(key) || state.drainingPendingSignalsByThread.has(key) || state.drainingIdleSignalsByThread.has(key) || [...state.threadKeysByRunId.values()].includes(key) || [...state.preparedRunsById.values()].some(run => run.threadKey === key) ) return; subscription.ownedRunIds.clear(); subscription.admittedSignalIds.clear(); state.locallyQueuedSignalIdsByThread.delete(key); if (subscription.observers) return; state.threadControlSubscriptions.delete(key); subscription.unsubscribe(); } #getState(pubsub?: PubSub): AgentThreadRuntimeState { const resolvedPubSub = this.#getPubSub(pubsub); let state = this.#statesByPubSub.get(resolvedPubSub); if (!state) { state = createRuntimeState(); this.#statesByPubSub.set(resolvedPubSub, state); } return state; } #queuedMessageCount( state: AgentThreadRuntimeState, scope: SubscribeAgentThreadEventsOptions & { agent: Agent }, ): number { const key = this.#threadKey(scope.resourceId, scope.threadId); const matches = (pending: PendingIdleSignal | undefined) => pending !== undefined && !pending.cancelled && (scope.queueOwnerId === undefined || (pending.agent === scope.agent && pending.queueOwnerId === scope.queueOwnerId)); let forwarded = 0; for (const entry of state.forwardedIdleSignalsByThread.get(key)?.values() ?? []) { if (matches(entry.pendingIdle)) forwarded++; } return ( (state.pendingIdleSignalsByThread.get(key)?.filter(matches).length ?? 0) + (matches(state.drainingIdleSignalsByThread.get(key)) ? 1 : 0) + forwarded ); } /** The thread's active run, when it is one this runtime is running. */ #localActiveRunId(state: AgentThreadRuntimeState, key: string): string | undefined { const runId = state.activeThreadRunIds.get(key); return runId !== undefined && state.threadKeysByRunId.get(runId) === key && state.threadRunsById.has(runId) ? runId : undefined; } #notifyThreadEvents(state: AgentThreadRuntimeState): void { for (const registration of [...state.threadEventListeners]) { const count = this.#queuedMessageCount(state, registration); if (count === registration.lastCount) continue; registration.lastCount = count; try { registration.listener({ type: 'queue-count-changed', count }); } catch {} } for (const key of state.threadControlSubscriptions.keys()) this.#releaseUnusedThreadControlSubscription(state, key); } /** * A `runId` target that also names a `resourceId` must name the run's own resource. Without this, the signal * would be created for the caller's resource and delivered into another resource's run. Core cannot know who the * caller is: a target naming only a `runId` is trusted, so callers exposing `runId` targets to untrusted input * must pass the caller's `resourceId` or check ownership with `getThreadRunTarget()` first. */ #assertRunTargetOwner(state: AgentThreadRuntimeState, target: { runId?: string; resourceId?: string }): void { if (!target.runId || !target.resourceId) return; const owner = state.threadRunsById.get(target.runId)?.resourceId; if (owner && owner !== target.resourceId) { throw new Error(`Agent run ${target.runId} belongs to a different resource`); } } #threadKey(resourceId: string | undefined, threadId: string): string { return agentThreadStreamKey(resourceId, threadId); } #parseThreadKey(key: string): { resourceId?: string; threadId: string } { const separator = key.indexOf(AGENT_THREAD_KEY_SEPARATOR); const resourceId = key.slice(0, separator); return { resourceId: resourceId || undefined, threadId: key.slice(separator + AGENT_THREAD_KEY_SEPARATOR.length) }; } #threadTopic(key: string): string { return agentThreadStreamTopicForKey(key); } /** * The identity of a logical cross-agent idle message: the target agent and * thread plus the sender's peer id and message id. These are the * `(targetAgentId, targetResourceId, targetThreadId, sourcePeerId, messageId)` * tuple a retrying sender preserves. Returns undefined for signals that carry * no message identity (for example a plain `sendSignal`), which are never * deduplicated — unlike the transport `requestId`, which the sender regenerates. */ #idleMessageIdentity(agentId: string, key: string, signal: CreatedAgentSignal): string | undefined { const messageId = signal.attributes?.messageId; const sourcePeerId = signal.attributes?.sourcePeerId; if (typeof messageId !== 'string' || messageId === '') return undefined; if (typeof sourcePeerId !== 'string' || sourcePeerId === '') return undefined; return [agentId, key, sourcePeerId, messageId].map(part => encodeURIComponent(part)).join(':'); } /** * Marks an accepted logical message as cancelled so a sender retrying it is * told the original outcome instead of waiting on a run that will never start. */ #markIdleMessageCancelled(state: AgentThreadRuntimeState, key: string, pending: PendingIdleSignal): void { const identity = this.#idleMessageIdentity(pending.agent.id, key, pending.signal); if (identity) this.#markAcceptedMessageCancelled(state, identity, pending.runId); } #markAcceptedMessageCancelled(state: AgentThreadRuntimeState, identity: string, runId: string): void { const acceptedMessage = state.acceptedIdleMessagesByIdentity.get(identity); if (!acceptedMessage || acceptedMessage.runId !== runId) return; state.acceptedIdleMessagesByIdentity.set(identity, { runId, terminalReason: CANCELLED_BEFORE_RUN }); } #isApprovalSuspendedRun(state: AgentThreadRuntimeState, runId: string) { return state.approvalSuspendedRunIds.has(runId); } #isSuspendedRun(state: AgentThreadRuntimeState, runId: string) { return state.suspendedRunIds.has(runId) || this.#isApprovalSuspendedRun(state, runId); } /** * Reads the persisted state of an agent run from the regular or durable agent * loop row, including the namespaced loop name a durable engine advertises * (e.g. Inngest). Returns 'missing' when storage was read but holds no row for the * run (both loops delete the row once a run finishes), and undefined when the * agent has no storage or the read fails, so callers keep the event-derived view. */ async #readStoredRunStatus( agent: Agent, runId: string, ): Promise { try { const workflowsStore = await agent.getMastraInstance?.()?.getStorage?.()?.getStore('workflows'); if (!workflowsStore) return undefined; const workflowNames = new Set([AGENTIC_LOOP_WORKFLOW_ID, DurableStepIds.AGENTIC_LOOP]); const advertisedLoopWorkflowName = (agent as Partial>) .durableLoopWorkflowName; if (typeof advertisedLoopWorkflowName === 'string') workflowNames.add(advertisedLoopWorkflowName); // Status only: the full run would pull a multi-megabyte snapshot into memory. for (const workflowName of workflowNames) { const status = await workflowsStore.loadWorkflowRunStatus({ runId, workflowName }); if (typeof status === 'string') return status; } return 'missing'; } catch { return undefined; } } #isThreadBlockingRun(state: AgentThreadRuntimeState, record: AgentThreadRunRecord) { return ( record.output.status === 'running' || record.output.status === 'suspended' || record.lifecycle === 'suspending' || record.lifecycle === 'suspended' || !!record.suspensions?.size || this.#isSuspendedRun(state, record.runId) ); } #isActivelyRunning(record: AgentThreadRunRecord) { // Activity is derived from the current execution segment and the record lifecycle only. // Pending sibling suspensions legitimately coexist with an actively running resumed // segment (partial resume), so suspension bookkeeping must not make the run look idle. return (record.currentSegmentOutput ?? record.output).status === 'running' && record.lifecycle === 'running'; } #serializeSignal(signal: CreatedAgentSignal): SerializableAgentSignal { return signal; } #nextStreamIdentity(state: AgentThreadRuntimeState, runId: string) { const streamSeq = (state.streamSeqByRunId.get(runId) ?? 0) + 1; state.streamSeqByRunId.set(runId, streamSeq); return { streamId: globalThis.crypto.randomUUID(), streamSeq }; } #markRunSuspending( state: AgentThreadRuntimeState, runId: string, streamId: string, suspension: AgentThreadRunSuspension, ) { state.suspendedRunIds.add(runId); const suspensions = state.suspensionMetadataByRunId.get(runId) ?? new Map(); suspensions.set(suspension.toolCallId, suspension); state.suspensionMetadataByRunId.set(runId, suspensions); const record = state.threadRunsByStreamId.get(streamId) ?? state.threadRunsById.get(runId); if (record) { record.lifecycle = 'suspending'; record.suspensions = suspensions; } if (suspension.kind === 'approval') { state.approvalSuspendedRunIds.add(runId); } } #clearSuspendedRun(state: AgentThreadRuntimeState, runId: string) { state.suspendedRunIds.delete(runId); state.suspensionMetadataByRunId.delete(runId); state.approvalSuspendedRunIds.delete(runId); const record = state.threadRunsById.get(runId); if (record) { record.suspensions = undefined; } } #clearSuspendedToolCall(state: AgentThreadRuntimeState, runId: string, toolCallId: string) { const suspensions = state.suspensionMetadataByRunId.get(runId); suspensions?.delete(toolCallId); if (suspensions?.size) { if (![...suspensions.values()].some(suspension => suspension.kind === 'approval')) { state.approvalSuspendedRunIds.delete(runId); } return; } this.#clearSuspendedRun(state, runId); } #generateSignalMessageId( agent: Agent, target: { threadId?: string; resourceId?: string }, ): string { return ( agent.getMastraInstance?.()?.generateId({ idType: 'message', source: 'agent', entityId: agent.id, threadId: target.threadId, resourceId: target.resourceId, }) ?? globalThis.crypto.randomUUID() ); } #createMessageSignalInput(message: AgentMessageInput): AgentSignal { const normalizedMessage = typeof message === 'string' || Array.isArray(message) ? { contents: message } : message; return { ...normalizedMessage, type: 'user', tagName: 'user', }; } getThreadState(options: { resourceId?: string; threadId: string }, pubsub?: PubSub): AgentThreadState { const state = this.#getState(pubsub); const key = this.#threadKey(options.resourceId, options.threadId); const activeRunId = state.activeThreadRunIds.get(key); if (!activeRunId) return 'idle'; const activeRecord = state.threadRunsById.get(activeRunId); if (activeRecord && !this.#isThreadBlockingRun(state, activeRecord)) { state.activeThreadRunIds.delete(key); return 'idle'; } return 'active'; } async claimThreadOwnership( agent: Agent, options: { resourceId: string; threadId: string; streamOptions?: ClaimedThreadOwnerStreamOptions; peer?: false | AgentClaimThreadPeerOptions; yieldOwnership?: () => boolean; onOwnershipYielded?: () => void; onOwnershipLost?: () => void; }, pubsub?: PubSub, ): Promise<{ claimed: boolean; unsubscribe: () => void }> { const resolvedPubSub = this.#getPubSub(pubsub); const state = this.#getState(resolvedPubSub); const key = this.#threadKey(options.resourceId, options.threadId); const topic = this.#threadTopic(key); const sourceId = this.#getSourceId(); const initialLocalClaim = state.claimedThreadOwners.get(key); const claimLeaseKey = `${AGENT_THREAD_CLAIM_LEASE_PREFIX}${key}`; const { provider: leaseProvider, isFallback: isLeaseFallback } = this.#resolveLeaseProvider(resolvedPubSub); if (isLeaseFallback) { if (!initialLocalClaim) { const remoteOwnerSourceId = await this.#findClaimedThreadOwner(resolvedPubSub, key, { includeLocal: false, intent: 'claim', }); if (remoteOwnerSourceId) { return { claimed: false, unsubscribe: () => {} }; } } } else { let lease = await leaseProvider.acquireLease(claimLeaseKey, sourceId, AGENT_THREAD_LEASE_TTL_MS); if (!lease.acquired) { await this.#findClaimedThreadOwner(resolvedPubSub, key, { includeLocal: false, intent: 'claim', targetSourceId: lease.owner, }); lease = await leaseProvider.acquireLease(claimLeaseKey, sourceId, AGENT_THREAD_LEASE_TTL_MS); } if (!lease.acquired) { return { claimed: false, unsubscribe: () => {} }; } } const peerOptions = options.peer === false ? undefined : (options.peer ?? {}); const peerAgentId = peerOptions?.agentId ?? agent.id; const peer: AdvertisedThreadPeer | undefined = peerOptions ? { id: peerOptions.id ?? createThreadPeerId(peerAgentId, options.resourceId, options.threadId), agentId: peerAgentId, resourceId: options.resourceId, threadId: options.threadId, ...(peerOptions.label ? { label: peerOptions.label } : {}), ...(peerOptions.title ? { title: peerOptions.title } : {}), ...(peerOptions.metadata ? { metadata: peerOptions.metadata } : {}), sourceId, unsubscribe: () => {}, } : undefined; let active = false; const onEvent: EventCallback = withAck(async event => { if (!active) return; const data = event.data as AgentThreadStreamRuntimeEvent | undefined; if (data?.type !== 'idle-signal-enqueued' || data.sourceId === sourceId || data.targetSourceId !== sourceId) { return; } // The caller's deadline, normalized for a legacy sender (a rolling-deploy // peer on an older core) that published a relative `timeoutMs` instead of // an absolute `expiresAt`. Deriving at receipt is exactly what that // sender expected; without a deadline at all the checks degrade to the // previous always-respond behavior. const expiresAt = data.expiresAt ?? (data.timeoutMs === undefined ? Number.POSITIVE_INFINITY : Date.now() + data.timeoutMs); // The caller already timed out on this request (it arrived via backlog // replay or redelivery). Starting a run now would duplicate work the // caller reported as failed, and the reply would recreate its released // reply stream. Returning still acks: a stale request must not redeliver. if (isStaleRequest(expiresAt)) return; const owner = state.claimedThreadOwners.get(key); if (!owner) return; const handled = state.handledIdleSignals.get(data.requestId); if (handled) { // Backends deliver at least once. This handler starts a run or queues the // signal onto one, and neither is idempotent, so the repeat must not touch // the signal again. What it still owes the caller is the reply: without // it the caller waits out its acceptance timeout and reports that no // owner accepted, when a run is in fact already in flight. if (handled.reply && !handled.replyPublished) { const reply = handled.reply; await resolvedPubSub.publish(handled.replyTopic, { type: reply.type, runId: reply.runId, data: reply, }); handled.replyPublished = true; } return; } const handledSignal: HandledIdleSignal = { replyTopic: data.replyTopic, replyPublished: false }; state.handledIdleSignals.set(data.requestId, handledSignal); let replyAttempted = false; const reply = async (response: AgentThreadIdleSignalAcceptanceEvent) => { if (replyAttempted) return; replyAttempted = true; // Record the reply before the publish settles, so a repeat can re-send the // same answer if this attempt never lands. A duplicate reply is harmless: // the caller settles on the first one it sees. handledSignal.reply = response; await resolvedPubSub.publish(handledSignal.replyTopic, { type: response.type, runId: response.runId, data: response, }); handledSignal.replyPublished = true; }; try { const accepted = await this.#startClaimedIdleRun( state, resolvedPubSub, key, owner, data.runId, createSignal(data.signal), // The caller's deadline translated onto this process's clock. The // deadline crossed machines, so the strict `Date.now() >= expiresAt` // checks inside #startClaimedIdleRun would reject live requests // whenever this clock runs ahead of the caller's; the same skew // grace `isStaleRequest` applies covers that. The cap keeps a // request that arrived late (but inside the grace) or a slow local // clock from granting more than one fresh acceptance window — // deriving an uncapped fresh window at receive time is exactly the // bug that let arbitrarily old replayed requests start runs. Math.min( expiresAt + AGENT_REQUEST_EXPIRY_SKEW_GRACE_MS, Date.now() + AGENT_THREAD_OWNER_ACCEPTANCE_TIMEOUT_MS, ), () => active && state.claimedThreadOwners.get(key)?.unsubscribe === unsubscribe, undefined, data.joinActiveRun !== true, data.joinActiveRun === true && data.joinSignal?.id === data.signal.id ? createSignal(data.joinSignal) : undefined, undefined, data.requestContextEntries, ); if (!active || state.claimedThreadOwners.get(key)?.unsubscribe !== unsubscribe) return; if (!accepted) { await reply({ type: 'idle-signal-rejected', requestId: data.requestId, runId: data.runId, sourceId, error: `Claimed thread owner could not acquire the execution lease for ${describeThreadKey(key)}`, }); } else if (accepted.error) { await reply({ type: 'idle-signal-rejected', requestId: data.requestId, runId: accepted.runId, sourceId, error: accepted.error, }); } else { await reply({ type: 'idle-signal-accepted', requestId: data.requestId, runId: accepted.runId, sourceId, }); } } catch (error) { if (!active || state.claimedThreadOwners.get(key)?.unsubscribe !== unsubscribe) return; if (replyAttempted) { // The reply never reached the backend, so the caller cannot learn the // signal was accepted. Let the rejection reach the nack path: the // backend redelivers, and the repeat re-sends the remembered reply // instead of acting on the signal again. Swallowing it here would leave // the caller waiting on a timeout for a run that is already in flight. throw error; } await reply({ type: 'idle-signal-rejected', requestId: data.requestId, runId: data.runId, sourceId, error: getErrorFromUnknown(error).message, }); } }); // Both discovery handlers await their reply before returning, so the request is only // acked once the reply publish has settled. Acking first would let a failed publish lose // the request — the backend sees it as handled and cannot redeliver, leaving the caller's // `#deliverAfterClaimedOwnerDiscovery` to throw with no response. Awaiting keeps the ack // behind the publish and lets a rejection reach the nack path, matching `onEvent`. const onOwnerDiscovery: EventCallback = withAck(async event => { if (!active) return; const data = event.data as AgentThreadOwnerDiscoveryEvent | undefined; if ( data?.type !== 'thread-owner-request' || data.key !== key || data.sourceId === sourceId || (data.targetSourceId !== undefined && data.targetSourceId !== sourceId) ) { return; } // A stale request's caller has timed out and released its reply topic; // replying would recreate the stream on persistent backends. Fan-out // groups anchor at the stream start, so a fresh claimant replays the // whole discovery backlog — without this guard it would answer every // request ever retained. if (isStaleRequest(data.expiresAt)) return; // Yield-on-demand: a requester that wants to own this thread asks first. // Lease-backed transports hand the claim over atomically before this // owner unsubscribes. Lease-less transports preserve the legacy silent // release, allowing the requester's discovery to settle without an owner. const requesterStillWaiting = data.expiresAt === undefined || Date.now() < data.expiresAt; if (data.intent === 'claim' && requesterStillWaiting && options.yieldOwnership?.()) { if (!isLeaseFallback) { const transferred = await leaseProvider.transferLease( claimLeaseKey, sourceId, data.sourceId, AGENT_THREAD_LEASE_TTL_MS, ); if (!transferred) return; unsubscribe(); options.onOwnershipYielded?.(); await resolvedPubSub.publish(data.replyTopic, { type: 'thread-owner-response', runId: data.requestId, data: { type: 'thread-owner-response', key, requestId: data.requestId, sourceId }, }); return; } unsubscribe(); options.onOwnershipYielded?.(); return; } await resolvedPubSub.publish(data.replyTopic, { type: 'thread-owner-response', runId: data.requestId, data: { type: 'thread-owner-response', key, requestId: data.requestId, sourceId }, }); }); const onPeerDiscovery: EventCallback = withAck(async event => { if (!active || !peer) return; const data = event.data as AgentThreadPeerDiscoveryEvent | undefined; if (data?.type !== 'thread-peer-request' || data.sourceId === sourceId) return; if (isStaleRequest(data.expiresAt)) return; // see onOwnerDiscovery await resolvedPubSub.publish(data.replyTopic, { type: 'thread-peer-response', runId: data.requestId, data: { type: 'thread-peer-response', requestId: data.requestId, peer: toPublicThreadPeer(peer), sourceId }, }); }); let threadSubscribed = false; let ownerDiscoverySubscribed = false; let peerDiscoverySubscribed = false; try { await resolvedPubSub.subscribe(topic, onEvent); threadSubscribed = true; await resolvedPubSub.subscribe(AGENT_THREAD_OWNER_DISCOVERY_TOPIC, onOwnerDiscovery); ownerDiscoverySubscribed = true; if (peer) { await resolvedPubSub.subscribe(AGENT_THREAD_PEER_DISCOVERY_TOPIC, onPeerDiscovery); peerDiscoverySubscribed = true; } } catch (error) { await Promise.all([ threadSubscribed ? resolvedPubSub.unsubscribe(topic, onEvent).catch(() => {}) : Promise.resolve(), ownerDiscoverySubscribed ? resolvedPubSub.unsubscribe(AGENT_THREAD_OWNER_DISCOVERY_TOPIC, onOwnerDiscovery).catch(() => {}) : Promise.resolve(), peerDiscoverySubscribed ? resolvedPubSub.unsubscribe(AGENT_THREAD_PEER_DISCOVERY_TOPIC, onPeerDiscovery).catch(() => {}) : Promise.resolve(), !isLeaseFallback && !initialLocalClaim ? leaseProvider.releaseLease(claimLeaseKey, sourceId).catch(() => {}) : Promise.resolve(), ]); throw error; } let claimLeaseRenewalTimer: ReturnType | undefined; const unsubscribe = () => { active = false; if (claimLeaseRenewalTimer) { clearInterval(claimLeaseRenewalTimer); claimLeaseRenewalTimer = undefined; } const currentOwner = state.claimedThreadOwners.get(key); if (currentOwner?.unsubscribe === unsubscribe) { state.claimedThreadOwners.delete(key); if (!isLeaseFallback) void leaseProvider.releaseLease(claimLeaseKey, sourceId).catch(() => {}); } if (peer && state.advertisedThreadPeers.get(peer.id)?.unsubscribe === unsubscribe) { state.advertisedThreadPeers.delete(peer.id); } void resolvedPubSub.unsubscribe(topic, onEvent).catch(() => {}); void resolvedPubSub.unsubscribe(AGENT_THREAD_OWNER_DISCOVERY_TOPIC, onOwnerDiscovery).catch(() => {}); if (peer) { void resolvedPubSub.unsubscribe(AGENT_THREAD_PEER_DISCOVERY_TOPIC, onPeerDiscovery).catch(() => {}); } }; const displacedClaim = state.claimedThreadOwners.get(key); const displacedPeer = peer ? state.advertisedThreadPeers.get(peer.id) : undefined; if (peer) { peer.unsubscribe = unsubscribe; state.advertisedThreadPeers.set(peer.id, peer); } let claimLeaseRenewalInFlight = false; if (!isLeaseFallback) { claimLeaseRenewalTimer = setInterval(() => { if (claimLeaseRenewalInFlight) return; claimLeaseRenewalInFlight = true; void leaseProvider .renewLease(claimLeaseKey, sourceId, AGENT_THREAD_LEASE_TTL_MS) .then(async renewed => { if (renewed || !active || state.claimedThreadOwners.get(key)?.unsubscribe !== unsubscribe) return; const reacquired = await leaseProvider.acquireLease(claimLeaseKey, sourceId, AGENT_THREAD_LEASE_TTL_MS); if (reacquired.acquired || !active || state.claimedThreadOwners.get(key)?.unsubscribe !== unsubscribe) return; unsubscribe(); options.onOwnershipLost?.(); }) .catch(() => {}) .finally(() => { claimLeaseRenewalInFlight = false; }); }, AGENT_THREAD_LEASE_RENEW_INTERVAL_MS); claimLeaseRenewalTimer.unref?.(); } state.claimedThreadOwners.set(key, { agent, resourceId: options.resourceId, threadId: options.threadId, streamOptions: options.streamOptions, peer, unsubscribe, }); active = true; displacedClaim?.unsubscribe(); if (displacedPeer?.unsubscribe !== displacedClaim?.unsubscribe) displacedPeer?.unsubscribe(); return { claimed: true, unsubscribe }; } updateThreadPeerAdvertisement( agent: Agent, options: { resourceId: string; threadId: string; peer: AgentUpdateThreadPeerOptions }, pubsub?: PubSub, ): boolean { const state = this.#getState(this.#getPubSub(pubsub)); const key = this.#threadKey(options.resourceId, options.threadId); const owner = state.claimedThreadOwners.get(key); if (!owner?.peer || owner.agent.id !== agent.id) return false; const peer = owner.peer; if (Object.hasOwn(options.peer, 'label')) peer.label = options.peer.label; if (Object.hasOwn(options.peer, 'title')) peer.title = options.peer.title; if (Object.hasOwn(options.peer, 'metadata')) peer.metadata = options.peer.metadata; return true; } async discoverThreadPeers( options: DiscoverAgentThreadPeersOptions = {}, pubsub?: PubSub, callerAgent?: Agent, ): Promise { const resolvedPubSub = this.#getPubSub(pubsub); const state = this.#getState(resolvedPubSub); const requestId = globalThis.crypto.randomUUID(); const replyTopic = `${AGENT_THREAD_PEER_DISCOVERY_TOPIC}.${requestId}`; const peers = new Map(); const discoveredAt = new Date(); for (const peer of state.advertisedThreadPeers.values()) { peers.set(peer.id, { ...toPublicThreadPeer(peer), discoveredAt }); } await new Promise(resolve => { let settled = false; const finish = () => { if (settled) return; settled = true; cancelWindow(); resolve(); releaseReplyTopic(resolvedPubSub, replyTopic, onReply); }; const onReply: EventCallback = withAck(event => { const data = event.data as AgentThreadPeerDiscoveryEvent | undefined; if (data?.type !== 'thread-peer-response' || data.requestId !== requestId) return; peers.set(data.peer.id, { ...data.peer, sourceId: data.sourceId, discoveredAt: new Date() }); }); const timeoutMs = options.timeoutMs ?? AGENT_THREAD_PEER_DISCOVERY_TIMEOUT_MS; // Absolute deadline carried on the request so a responder that receives // it late (backlog replay, redelivery) can drop it instead of replying // into the released reply topic. const expiresAt = Date.now() + timeoutMs; const cancelWindow = startListeningWindow(timeoutMs, AGENT_THREAD_PEER_DISCOVERY_MAX_EXTRA_MS, finish); void resolvedPubSub .subscribe(replyTopic, onReply) .then(() => { // If the timeout already settled the request, the reply topic has // been released. Publishing now would invite replies that recreate // it, and the subscribe that just finished may have attached the // callback after the release — so release again instead. if (settled) { releaseReplyTopic(resolvedPubSub, replyTopic, onReply); return; } return resolvedPubSub.publish(AGENT_THREAD_PEER_DISCOVERY_TOPIC, { type: 'thread-peer-request', runId: requestId, data: { type: 'thread-peer-request', requestId, replyTopic, sourceId: this.#getSourceId(), expiresAt }, }); }) .catch(() => finish()); }); // The mark is applied after every pass that can produce an entry: a reply can // describe a thread this caller already owns — a second live instance with the // same thread loaded answers discovery too, and its reply replaces the local // entry. The runtime is shared by every agent in the process, so the mark is // scoped to the claiming agent: a sibling agent's claim stays a real peer. if (callerAgent !== undefined) { for (const [id, peer] of peers) { const owner = state.claimedThreadOwners.get(this.#threadKey(peer.resourceId, peer.threadId)); if (owner?.agent === callerAgent) peers.set(id, { ...peer, selfAdvertised: true }); } } return [...peers.values()].sort((a, b) => a.id.localeCompare(b.id)); } async #startClaimedIdleRun( state: AgentThreadRuntimeState, pubsub: PubSub, key: string, owner: ClaimedThreadOwner, runId: string, signal: CreatedAgentSignal, expiresAt: number, isOwnerActive: () => boolean, incomingStreamOptions?: AgentExecutionOptions, waitForIdle = false, joinSignal?: CreatedAgentSignal, messageScopes?: string[], remoteRequestContextEntries?: Record, ): Promise<{ runId: string; error?: string; blocked?: boolean; output?: MastraModelOutput } | undefined> { // A message naming scopes joins only a run started with exactly those scopes; otherwise // it falls through to the queued idle start below, which runs after the run in flight. const joins = (activeRunId: string) => !waitForIdle && (messageScopes === undefined || this.#runHoldsScopes(state, activeRunId, messageScopes)); const messageIdentity = this.#idleMessageIdentity(owner.agent.id, key, signal); let admissionSettled = false; // Records this attempt's real admission outcome for the logical message and // resolves a duplicate that raced in behind the reservation on it. `keep` // retains the reservation (the message queued or ran); otherwise the // reservation is released so a later retry can route. let settleMessageIdentity: ((result: AcceptedIdleMessage, keep?: boolean) => void) | undefined; // Releases the reservation for an admission that produced no result to report. // A duplicate waiting on the reservation is rejected with the same failure // instead of being told the message was delivered. let failMessageIdentity: ((error: unknown) => void) | undefined; if (messageIdentity) { const acceptedMessage = state.acceptedIdleMessagesByIdentity.get(messageIdentity); if (acceptedMessage) { // This logical message was already accepted on an earlier delivery attempt. // The sender regenerates the transport request id when it retries, so // `handledIdleSignals` cannot catch this — and admitting it again would run // the wake a second time and repeat the turn's tools' side effects. Resolve // the retry to what the first attempt reached, waiting for an admission that // is still in flight: answering now would report a delivery for a wake that // may yet be rejected. const settled = acceptedMessage.admission ? await acceptedMessage.admission : acceptedMessage; return settled.terminalReason ? { runId: settled.runId, error: settled.terminalReason } : { runId: settled.runId }; } // Reserve the identity before the first await, so two delivery attempts of the // same logical message racing into this method cannot both admit a run. The // reservation carries the pending admission so a duplicate that arrives in that // window settles on this attempt's real outcome instead of a provisional one. // It is released below if this attempt turns out not to admit a run. const admission = new Promise((resolve, reject) => { settleMessageIdentity = (result, keep = true) => { admissionSettled = true; if (state.acceptedIdleMessagesByIdentity.get(messageIdentity)?.runId === runId) { if (keep) state.acceptedIdleMessagesByIdentity.set(messageIdentity, result); else state.acceptedIdleMessagesByIdentity.delete(messageIdentity); } resolve(result); }; failMessageIdentity = error => { admissionSettled = true; if (state.acceptedIdleMessagesByIdentity.get(messageIdentity)?.runId === runId) { state.acceptedIdleMessagesByIdentity.delete(messageIdentity); } reject(error); }; }); // A reservation nobody is waiting on must not surface as an unhandled // rejection when this attempt fails. void admission.catch(() => {}); state.acceptedIdleMessagesByIdentity.set(messageIdentity, { runId, admission }); } // Releases the reservation for an attempt that did not admit the message, so a // later retry of the same logical message is still free to route. A duplicate // already waiting on it observes the same failure. const releaseMessageIdentity = (failure: string | Error) => { if (typeof failure === 'string') settleMessageIdentity?.({ runId, terminalReason: failure }, false); else failMessageIdentity?.(failure); }; if (!isOwnerActive()) { releaseMessageIdentity(`Claimed thread owner was released for ${describeThreadKey(key)}`); return { runId, error: `Claimed thread owner was released for ${describeThreadKey(key)}` }; } if (Date.now() >= expiresAt) { releaseMessageIdentity(`Claimed thread owner acceptance expired for ${describeThreadKey(key)}`); return { runId, error: `Claimed thread owner acceptance expired for ${describeThreadKey(key)}` }; } // Only a wake or a queued run uses the owner's stream options, so they are resolved after the joins below, // which never read them: a slow or failing options factory must not hold up input joining a run. // Resolving them can reject. A later retry of the same logical message must be free to route instead of // being told this message was already accepted, so release the reservation before propagating. let streamOptions: AgentExecutionOptions | undefined; let streamOptionsResolved = false; const resolveStreamOptions = async () => { let ownerStreamOptions: AgentExecutionOptions | undefined; try { ownerStreamOptions = typeof owner.streamOptions === 'function' ? await owner.streamOptions() : owner.streamOptions; } catch (error) { releaseMessageIdentity(getErrorFromUnknown(error)); throw error; } // The run executes inside the claiming owner's session, so the owner's // options stay authoritative for everything that shapes the run — memory, // toolsets, provider options. Only `requestContext` crosses over: it // identifies the caller this wake acts for rather than the shape of the run. // A dispatcher waking a session on behalf of an authenticated caller needs // that identity visible downstream, or the run starts anonymously and a // workspace resolver that requires a caller rejects it. // // Deliberately narrower than the no-owner path below, which spreads the whole // incoming `streamOptions` because there is no owner configuration to keep. // // Scopes cross over with the request context for the same reason: they say // what the caller acts as. They are unioned with any owner scopes. // // A caller in another process sends a snapshot instead of the live context. // It never holds an auth token, so the owner's own token is kept. // // Either way the run keeps the owner's thread and resource, and the owner's // own auth token when it has one (see `claimedOwnerRequestContext`). const callerRequestContext = remoteRequestContextEntries ? restoreRequestContext(remoteRequestContextEntries, ownerStreamOptions?.requestContext) : incomingStreamOptions?.requestContext; const incomingRequestContext = callerRequestContext && claimedOwnerRequestContext(callerRequestContext, ownerStreamOptions?.requestContext); streamOptions = incomingRequestContext === undefined ? ownerStreamOptions : { ...ownerStreamOptions, requestContext: incomingRequestContext }; if (incomingStreamOptions?.scopes?.length) { streamOptions = { ...streamOptions, scopes: unionScopes(ownerStreamOptions?.scopes, incomingStreamOptions.scopes), }; } streamOptionsResolved = true; }; let control: ThreadControlSubscription | undefined; try { let activeRunId: string | undefined; let activeRecord: AgentThreadRunRecord | undefined; for (;;) { activeRunId = state.activeThreadRunIds.get(key); activeRecord = activeRunId ? state.threadRunsById.get(activeRunId) : undefined; // Queued input waits for the thread to go idle; only a send joins a run in flight. const pendingAdmission = activeRunId && !activeRecord && joins(activeRunId) ? state.pendingThreadAdmissions.get(key) : undefined; if (pendingAdmission && pendingAdmission.runId === activeRunId && pendingAdmission.agentId === owner.agent.id) { // The owner has reserved the thread for a run that has not started yet. Hand // it the input for its first model request, as a local send does. const queue = state.preRunSignalsByThread.get(key) ?? []; queue.push(joinSignal ?? signal); state.preRunSignalsByThread.set(key, queue); const queued: ClaimedQueuedMessage = { identity: messageIdentity }; state.claimedQueuedMessages.set(claimedQueuedMessageKey(key, signal.id), queued); this.#recordLocallyQueuedSignal(state, key, signal.id); this.#notifyPendingSignals(state, key, joinSignal ?? signal); const admission = await pendingAdmission.outcome.catch(() => undefined); if (queued.cancelled) { // Cancelled while waiting. It was admitted like queued input on an idle owner, so // this attempt is accepted; the message is ended so a retry learns it was cancelled. const cancelledRunId = admission?.action === 'local' ? admission.runId : runId; settleMessageIdentity?.({ runId: cancelledRunId, terminalReason: CANCELLED_BEFORE_RUN }); return { runId: cancelledRunId }; } if (admission?.action === 'local') { queued.runId = admission.runId; settleMessageIdentity?.({ runId: admission.runId }); return { runId: admission.runId }; } // That run never started here, so it will not take the input; route it again. state.claimedQueuedMessages.delete(claimedQueuedMessageKey(key, signal.id)); this.#discardQueuedPreRunSignal(state, key, signal.id); if (!isOwnerActive()) { releaseMessageIdentity(`Claimed thread owner was released for ${describeThreadKey(key)}`); return { runId, error: `Claimed thread owner was released for ${describeThreadKey(key)}` }; } activeRunId = state.activeThreadRunIds.get(key); activeRecord = activeRunId ? state.threadRunsById.get(activeRunId) : undefined; } if ( activeRecord && joins(activeRecord.runId) && activeRecord.agent.id === owner.agent.id && this.#isThreadBlockingRun(state, activeRecord) ) { // The sender asked for an idle wake only because it cannot see this run from // its process. Hand the input to the run in flight, the way a local send does, // so it reaches the next model request instead of waiting for the run to end. // Tracked before it is queued: queuing can cut the run's request short at once, and // whatever cancels the input from there must find it. const queued: ClaimedQueuedMessage = { identity: messageIdentity, runId: activeRecord.runId }; state.claimedQueuedMessages.set(claimedQueuedMessageKey(key, signal.id), queued); this.#queueForActiveRun(state, pubsub, key, activeRecord, joinSignal ?? signal); settleMessageIdentity?.( queued.cancelled ? { runId: activeRecord.runId, terminalReason: CANCELLED_BEFORE_RUN } : { runId: activeRecord.runId }, ); return { runId: activeRecord.runId }; } if (streamOptionsResolved) break; // No join applies: this wakes or queues a run, which needs the owner's options and the thread's // control subscription. The thread may change while they settle, so look at it again after. await resolveStreamOptions(); const subscription = this.#ensureThreadControlSubscription(state, pubsub, key); control = subscription; subscription.references++; await subscription.ready; if (!isOwnerActive()) { releaseMessageIdentity(`Claimed thread owner was released for ${describeThreadKey(key)}`); return { runId, error: `Claimed thread owner was released for ${describeThreadKey(key)}` }; } if (Date.now() >= expiresAt) { releaseMessageIdentity(`Claimed thread owner acceptance expired for ${describeThreadKey(key)}`); return { runId, error: `Claimed thread owner acceptance expired for ${describeThreadKey(key)}` }; } } if (activeRunId && (!activeRecord || this.#isThreadBlockingRun(state, activeRecord))) { const idleQueue = state.pendingIdleSignalsByThread.get(key) ?? []; idleQueue.push({ agent: owner.agent, signal, runId, resourceId: owner.resourceId, threadId: owner.threadId, streamOptions, }); state.pendingIdleSignalsByThread.set(key, idleQueue); this.#publishPendingUserMessage(pubsub, key, activeRunId, signal, 'queued'); if (activeRecord) { this.#watchThreadRunCompletion(state, pubsub, key, activeRecord); } // No run starts here. The thread is held by another agent's run, or by a // reservation this process is not admitting, so the signal waits and starts // its own run once the thread clears. Returning without `output` is what tells the caller this // queued instead of running, so it reports `deliver` rather than `wake`. Queueing // is an admission, so a duplicate waiting on this reservation is told the // same thing rather than left to start a second run. settleMessageIdentity?.({ runId }); return { runId }; } if (activeRunId) { state.activeThreadRunIds.delete(key); } if (!isOwnerActive()) { releaseMessageIdentity(`Claimed thread owner was released for ${describeThreadKey(key)}`); return { runId, error: `Claimed thread owner was released for ${describeThreadKey(key)}` }; } state.activeThreadRunIds.set(key, runId); state.threadKeysByRunId.set(runId, key); let settleThreadAdmission!: (outcome: ThreadAdmissionOutcome) => void; let failThreadAdmission!: (error: unknown) => void; const threadAdmission = new Promise((resolve, reject) => { settleThreadAdmission = resolve; failThreadAdmission = reject; }); this.#trackPendingThreadAdmission(state, key, runId, owner.agent.id, threadAdmission); let lease: { acquired: boolean; owner?: string }; try { lease = await this.#acquireOrTransferThreadLease(pubsub, key, runId); } catch (error) { failThreadAdmission(error); // No run and no lease exist for this attempt yet, so unwind the run // bookkeeping it just claimed and let a retry of the logical message route. releaseMessageIdentity(getErrorFromUnknown(error)); if (state.activeThreadRunIds.get(key) === runId) { state.activeThreadRunIds.delete(key); // Concurrent senders queued pre-run copies behind this reservation; // dropping them keeps a later local run from replaying input this // attempt never delivered. state.preRunSignalsByThread.delete(key); } state.threadKeysByRunId.delete(runId); throw error; } const ownerActive = isOwnerActive(); const expired = Date.now() >= expiresAt; if (!lease.acquired || !ownerActive || expired) { // This attempt admitted no run of its own — the owner went away, the // deadline passed, or the wake was handed to another live lease owner — so // a later retry of the same logical message must be free to route. Give up // the reservation identity-first: a newer reservation may own the thread // slot, and only this attempt's provisional pre-run copies (queued behind // its own admission and forwarded by their senders on a remote outcome) // may be discarded — otherwise a later local run replays them. if (state.activeThreadRunIds.get(key) === runId) { state.activeThreadRunIds.delete(key); state.preRunSignalsByThread.delete(key); } state.threadKeysByRunId.delete(runId); if (!ownerActive || expired) { settleThreadAdmission({ action: 'blocked', runId }); const error = !ownerActive ? `Claimed thread owner was released for ${describeThreadKey(key)}` : `Claimed thread owner acceptance expired for ${describeThreadKey(key)}`; releaseMessageIdentity(error); const drained = await this.#drainPendingIdleSignals(state, pubsub, key, lease.acquired ? runId : undefined); if (lease.acquired && !drained) this.#releaseThreadLease(pubsub, key, runId); return { runId, error }; } if (lease.owner && isRetakeLeaseOwner(lease.owner)) { const ownerRunId = threadLeaseRunId(lease.owner); settleThreadAdmission({ action: 'blocked', runId: ownerRunId }); const error = `Thread ${describeThreadKey(key)} is waiting for its lease owner to finish starting`; releaseMessageIdentity(error); return { runId: ownerRunId, error, blocked: true }; } const ownerRunId = lease.owner ? threadLeaseRunId(lease.owner) : undefined; if (ownerRunId && this.#isSweptLeaseOwner(state, ownerRunId)) { // The lease still belongs to a suspended run the TTL sweep evicted, so a // signal forwarded to it is never consumed. Fail the admission instead. settleThreadAdmission({ action: 'blocked', runId: ownerRunId }); const error = `Thread ${describeThreadKey(key)} is still leased to a suspended run that was released from memory; retry once its lease expires`; releaseMessageIdentity(error); return { runId: ownerRunId, error, blocked: true }; } if (ownerRunId) { settleThreadAdmission({ action: 'remote', runId: ownerRunId }); this.#publish(pubsub, key, { type: 'signal-enqueued', runId: ownerRunId, signal: this.#serializeSignal(signal), sourceId: this.#getSourceId(), }); // Another live lease owner took the wake, so this attempt delivered it // without running it here. Report that to a duplicate instead of leaving // it waiting, while still releasing the reservation so a later retry routes. settleMessageIdentity?.({ runId: ownerRunId }, false); return { runId: ownerRunId }; } settleThreadAdmission({ action: 'blocked', runId }); releaseMessageIdentity( new Error(`Claimed thread owner could not acquire the execution lease for ${describeThreadKey(key)}`), ); await this.#drainPendingIdleSignals(state, pubsub, key); return undefined; } settleThreadAdmission({ action: 'local', runId }); try { const output = toModelOutput( await owner.agent.stream(signal, { ...(streamOptions as any), runId, memory: withThreadMemory(streamOptions?.memory, owner.resourceId, owner.threadId), }), ); // The run started, so the admission a duplicate is waiting on succeeded. settleMessageIdentity?.({ runId }); return { runId, output }; } catch (error) { const message = getErrorFromUnknown(error).message; // The run did start, so keep the identity instead of releasing it: a sender // retrying the same logical message must learn the original turn failed // rather than run that turn's tools a second time. Only settle the identity // this run reserved — a newer reservation for the same logical message must // survive an older run's failure. settleMessageIdentity?.({ runId, terminalReason: message }); state.threadKeysByRunId.delete(runId); this.#cleanupPreparedRun(state, runId); if (state.activeThreadRunIds.get(key) === runId) { state.activeThreadRunIds.delete(key); } this.#publish(pubsub, key, { type: 'run-failed', runId, error: message, }); this.#trimRunLater(pubsub, key, runId); if (!(await this.#drainPendingIdleSignals(state, pubsub, key, runId))) { this.#releaseThreadLease(pubsub, key, runId); } return { runId, error: message }; } } finally { // An unexpected failure before admission settled (a control subscription that // never became ready, for example) must not leave a duplicate waiting on an // outcome that will never arrive. if (!admissionSettled) { failMessageIdentity?.( new Error(`Claimed thread owner admission for ${describeThreadKey(key)} did not complete`), ); } if (control) { control.references--; this.#releaseUnusedThreadControlSubscription(state, key); } } } /** Stop tracking a forwarded idle message: admitted (by `runId`, when given) or cancelled. */ #settleForwardedIdleSignal(state: AgentThreadRuntimeState, key: string, signalId: string, runId?: string) { const forwarded = state.forwardedIdleSignalsByThread.get(key); const entry = forwarded?.get(signalId); if (!forwarded || !entry || (runId !== undefined && entry.runId !== runId)) return; forwarded.delete(signalId); if (forwarded.size === 0) this.#stopTrackingForwards(state, key); this.#notifyThreadEvents(state); } #stopTrackingForwards(state: AgentThreadRuntimeState, key: string) { state.forwardedIdleSignalsByThread.delete(key); clearInterval(state.forwardedIdleLeaseChecks.get(key)); state.forwardedIdleLeaseChecks.delete(key); } /** * Queues held forwards again once the lease stops naming the run they went to without this runtime seeing that * run end: its process died, or it ended before the forward was recorded. The lease must be gone on two checks in * a row, so an admission the owner published just before letting go still arrives first. */ #watchForwardedIdleLease(state: AgentThreadRuntimeState, pubsub: PubSub | undefined, key: string) { if (state.forwardedIdleLeaseChecks.has(key)) return; const { provider, isFallback } = this.#resolveLeaseProvider(pubsub); if (isFallback) return; let checking = false; const checkLease = async () => { const forwarded = state.forwardedIdleSignalsByThread.get(key); if (!forwarded) return; const streamBeforeRead = state.activeThreadStreamIds.get(key); // Bounded, so a read that never returns frees the in-flight guard and the next tick retries. const owner = await this.#readLeaseOwnerInTime(provider, key); const holder = owner === undefined ? undefined : forwardedSignalRunId(owner); const ended = new Set(); for (const entry of forwarded.values()) { if (entry.runId === holder) entry.leaseGone = false; else if (entry.leaseGone) ended.add(entry.runId); else entry.leaseGone = true; } for (const runId of ended) { if (this.#requeueUnadmittedForwards(state, key, runId)) { // The lease has dropped that run, so a remote run this runtime saw register but never saw end (its observer // unsubscribed) no longer holds the thread; left marked active, it would keep the drain waiting. A run that // registered here, or a new stream that took the slot while the lease was read, is not that remote run. // The drain still runs either way: it waits while any run holds the thread. if ( !state.threadRunsById.has(runId) && state.activeThreadStreamIds.get(key) === streamBeforeRead && state.activeThreadRunIds.get(key) === runId ) { state.activeThreadRunIds.delete(key); state.activeThreadStreamIds.delete(key); } await this.#drainPendingIdleSignals(state, pubsub, key, runId); } } }; // A slow lease read must not overlap the next tick: two overlapping reads would count as two checks. const check = setInterval(() => { if (checking) return; checking = true; void checkLease() .catch(() => {}) .finally(() => { checking = false; }); }, AGENT_THREAD_LEASE_RENEW_INTERVAL_MS); check.unref?.(); state.forwardedIdleLeaseChecks.set(key, check); } /** Whether the thread lease may still name `runId`: it does, or the backend could not say. */ async #leaseMayStillName(pubsub: PubSub | undefined, key: string, runId: string): Promise { const { provider } = this.#resolveLeaseProvider(pubsub); try { const owner = await this.#readLeaseOwnerInTime(provider, key); return owner !== undefined && forwardedSignalRunId(owner) === runId; } catch { return true; } } /** Queue again the idle messages forwarded to `runId` that it ended without admitting. */ #requeueUnadmittedForwards(state: AgentThreadRuntimeState, key: string, runId: string): boolean { const forwarded = state.forwardedIdleSignalsByThread.get(key); if (!forwarded) return false; const unadmitted = [...forwarded].filter(([, entry]) => entry.runId === runId); if (unadmitted.length === 0) return false; for (const [signalId] of unadmitted) forwarded.delete(signalId); if (forwarded.size === 0) this.#stopTrackingForwards(state, key); state.pendingIdleSignalsByThread.set(key, [ ...unadmitted.map(([, entry]) => entry.pendingIdle), ...(state.pendingIdleSignalsByThread.get(key) ?? []), ]); return true; } #recordLocallyQueuedSignal(state: AgentThreadRuntimeState, key: string, signalId: string) { const ids = state.locallyQueuedSignalIdsByThread.get(key) ?? new Map(); ids.delete(signalId); ids.set(signalId, undefined); // Bound memory: retained replays of very old local signals are vanishingly rare, so evict oldest first. if (ids.size > MAX_LOCALLY_QUEUED_SIGNAL_IDS_PER_THREAD) ids.delete(ids.keys().next().value!); state.locallyQueuedSignalIdsByThread.set(key, ids); } /** * Remove exactly one caller's queued pre-run copy. A reservation's losing * rollback can only clear the whole queue while it still owns the thread * slot; once a newer reservation replaced it, each sender discards its own * acknowledged-or-rejected copy here so a later run cannot replay it. */ #discardQueuedPreRunSignal(state: AgentThreadRuntimeState, key: string, signalId: string) { const queue = state.preRunSignalsByThread.get(key); if (!queue) return; const index = queue.findIndex(signal => signal.id === signalId); if (index === -1) return; queue.splice(index, 1); if (queue.length === 0) state.preRunSignalsByThread.delete(key); } #isLocalSignalEcho(state: AgentThreadRuntimeState, key: string, signalId: string, runId: string) { const ids = state.locallyQueuedSignalIdsByThread.get(key); return !!ids?.has(signalId) && ids.get(signalId) !== runId; } #publish(pubsub: PubSub | undefined, key: string, event: AgentThreadStreamRuntimeEvent) { void this.#publishAndWait(pubsub, key, event).catch(() => {}); } async #publishAndWait(pubsub: PubSub | undefined, key: string, event: AgentThreadStreamRuntimeEvent) { const resolvedPubSub = this.#getPubSub(pubsub); const topic = this.#threadTopic(key); await resolvedPubSub.publish(topic, { type: event.type, // Events tied to a run carry its ID so that run's trim removes them; thread-scoped // control events fall back to the thread key. runId: ('runId' in event ? event.runId : undefined) ?? key, data: event, }); } async #deliverToClaimedThreadOwner( pubsub: PubSub, key: string, runId: string, signal: CreatedAgentSignal, targetSourceId: string, waitForIdle: boolean, joinSignal?: CreatedAgentSignal, requestContext?: RequestContext, ): Promise { const requestId = globalThis.crypto.randomUUID(); const requestContextEntries = snapshotWireRequestContext(requestContext); const replyTopic = `${this.#threadTopic(key)}.idle-acceptance.${requestId}`; return new Promise((resolve, reject) => { let settled = false; const finish = (result: { runId: string } | { error: Error }) => { if (settled) return; settled = true; clearTimeout(timeout); if ('error' in result) reject(result.error); else resolve(result.runId); releaseReplyTopic(pubsub, replyTopic, onReply); }; const onReply: EventCallback = withAck(event => { const data = event.data as AgentThreadIdleSignalAcceptanceEvent | undefined; if (!data || data.requestId !== requestId || data.sourceId !== targetSourceId) return; if (data.type === 'idle-signal-rejected') { finish({ error: new Error(data.error) }); return; } if (data.type === 'idle-signal-accepted') { finish({ runId: data.runId }); } }); // Absolute deadline carried on the request so a responder that receives // it late (backlog replay, redelivery) drops it instead of starting a run // this caller has already reported as timed out. const expiresAt = Date.now() + AGENT_THREAD_OWNER_ACCEPTANCE_TIMEOUT_MS; const timeout = setTimeout( () => finish({ error: new Error(`Claimed thread owner did not accept signal for ${describeThreadKey(key)}`) }), AGENT_THREAD_OWNER_ACCEPTANCE_TIMEOUT_MS, ); // This event can reach a claimed owner in another process. Besides the // signal, the request/reply ids and the timeout, it carries a JSON-safe // snapshot of the caller's request context, so the owner's run sees the // caller's request-scoped values as a locally claimed owner's does (see // `#startClaimedIdleRun`). The live context is an open map that may hold // non-serializable values; the snapshot keeps only what survives JSON and // never the auth token. void pubsub .subscribe(replyTopic, onReply) .then(() => { // If the acceptance timeout already settled the request, the reply // topic has been released and the caller has its timeout error. // Publishing now would recreate the topic and enqueue a signal the // caller will never see accepted, and the subscribe that just // finished may have attached the callback after the release — so // release again instead. if (settled) { releaseReplyTopic(pubsub, replyTopic, onReply); return; } return this.#publishAndWait(pubsub, key, { type: 'idle-signal-enqueued', runId, signal: this.#serializeSignal(signal), sourceId: this.#getSourceId(), requestId, replyTopic, targetSourceId, expiresAt, ...(waitForIdle ? {} : { joinActiveRun: true }), ...(!waitForIdle && joinSignal ? { joinSignal: this.#serializeSignal(joinSignal) } : {}), ...(requestContextEntries ? { requestContextEntries } : {}), }); }) .catch(error => finish({ error: getErrorFromUnknown(error) })); }); } async #deliverAfterClaimedOwnerDiscovery( pubsub: PubSub, key: string, runId: string, signal: CreatedAgentSignal, discovery: Promise, waitForIdle = false, joinSignal?: CreatedAgentSignal, requestContext?: RequestContext, ): Promise> { const claimedOwnerSourceId = await discovery; if (!claimedOwnerSourceId) { throw new Error( `No claimed thread owner responded for ${describeThreadKey(key)} within ${AGENT_THREAD_WAKE_OWNER_DISCOVERY_DEADLINE_MS}ms`, ); } const acceptedRunId = await this.#deliverToClaimedThreadOwner( pubsub, key, runId, signal, claimedOwnerSourceId, waitForIdle, joinSignal, requestContext, ); return { action: 'deliver', runId: acceptedRunId }; } async #findClaimedThreadOwnerWithRetry(pubsub: PubSub, key: string): Promise { const deadline = Date.now() + AGENT_THREAD_WAKE_OWNER_DISCOVERY_DEADLINE_MS; let attemptTimeoutMs = AGENT_THREAD_OWNER_DISCOVERY_TIMEOUT_MS; while (true) { const remainingMs = deadline - Date.now(); if (remainingMs <= 0) return undefined; const attemptMs = Math.min(attemptTimeoutMs, remainingMs); const attemptStartedAt = Date.now(); const sourceId = await this.#findClaimedThreadOwner(pubsub, key, { includeLocal: false, timeoutMs: attemptMs, }); if (sourceId) return sourceId; // A PubSub subscribe/publish failure settles the attempt immediately; // wait out the rest of its window so retries stay paced. const unusedMs = attemptMs - (Date.now() - attemptStartedAt); if (unusedMs > 0) await new Promise(resolve => setTimeout(resolve, unusedMs)); // Stop when this window ran to the deadline. Rereading Date.now() here can come up a // millisecond short, since timers can fire just before it reaches their due time. if (attemptStartedAt + attemptMs >= deadline) return undefined; attemptTimeoutMs *= 2; } } async #findClaimedThreadOwner( pubsub: PubSub, key: string, options?: { includeLocal?: boolean; intent?: 'claim'; targetSourceId?: string; timeoutMs?: number }, ): Promise { const hasLocalOwner = this.#getState(pubsub).claimedThreadOwners.has(key); if (options?.includeLocal !== false && hasLocalOwner) { return this.#getSourceId(); } const requestId = globalThis.crypto.randomUUID(); const replyTopic = `${AGENT_THREAD_OWNER_DISCOVERY_TOPIC}.${requestId}`; return new Promise(resolve => { let settled = false; const finish = (sourceId?: string) => { if (settled) return; settled = true; clearTimeout(timeout); resolve(sourceId); releaseReplyTopic(pubsub, replyTopic, onReply); }; const onReply: EventCallback = withAck(event => { const data = event.data as AgentThreadOwnerDiscoveryEvent | undefined; if (data?.type === 'thread-owner-response' && data.key === key && data.requestId === requestId) { finish(data.sourceId); } }); // Absolute deadline carried on the request; see discoverThreadPeers. const timeoutMs = options?.timeoutMs ?? AGENT_THREAD_OWNER_DISCOVERY_TIMEOUT_MS; const expiresAt = Date.now() + timeoutMs; const timeout = setTimeout(() => finish(), timeoutMs); void pubsub .subscribe(replyTopic, onReply) .then(() => { // If the timeout already settled the request, the reply topic has // been released. Publishing now would invite replies that recreate // it, and the subscribe that just finished may have attached the // callback after the release — so release again instead. if (settled) { releaseReplyTopic(pubsub, replyTopic, onReply); return; } return pubsub.publish(AGENT_THREAD_OWNER_DISCOVERY_TOPIC, { type: 'thread-owner-request', runId: requestId, data: { type: 'thread-owner-request', key, requestId, replyTopic, sourceId: this.#getSourceId(), expiresAt, ...(options?.intent ? { intent: options.intent } : {}), ...(options?.targetSourceId ? { targetSourceId: options.targetSourceId } : {}), }, }); }) .catch(() => finish()); }); } #withBroadcastStream( output: MastraModelOutput, pubsub: PubSub | undefined, key: string, streamId: string, resumed = false, // Read per part: a run continued across suspension takes the resuming claim's generation. getGeneration?: () => number | undefined, ) { const runtime = this; const parts: unknown[] = []; // Parts already dropped from the front of `parts`; reader positions are absolute. let dropped = 0; let published = 0; const readers = new Set<{ index: number }>(); let startPart: unknown; const waiters = new Set<() => void>(); let started = false; let done = false; let cancelled = false; let failed = false; let publishedTerminal = false; let error: unknown; let cancelSource: (() => Promise) | undefined; let suspensionBoundaryHandler: (() => Promise) | undefined; let stopSaveListener: (() => void) | undefined; let startSaveListener: () => void; // Resolves once the broadcast pump has drained the source stream AND every // stream-part publish has completed. Terminal events (`run-completed` / // `run-suspended`) must wait on this: publishing the terminal event while // part publishes are still in flight lets it overtake them on the wire, // and a subscriber that deferred the run would flush an empty buffer and // then drop the late-arriving parts. let resolveBroadcastFinished!: () => void; const broadcastFinished = new Promise(resolve => { resolveBroadcastFinished = resolve; }); const wake = () => { const pending = [...waiters]; waiters.clear(); for (const waiter of pending) waiter(); }; let needsStart = resumed; const emitPart = async (rawPart: unknown): Promise => { startSaveListener(); if (needsStart) { needsStart = false; // A resumed half of a run doesn't emit its own `start`, and the first // half's is dropped once saved. Open the resumed half so subscribers // (and joiners) see the run running again. if ((rawPart as { type?: string } | null | undefined)?.type !== 'start') { await emitPart({ type: 'start', runId: output.runId, from: ChunkFrom.AGENT, payload: { messageId: output.messageId }, }); } } let isSuspensionBoundary = false; if (rawPart && typeof rawPart === 'object' && 'type' in rawPart) { const typedPart = rawPart as { type?: string; payload?: { toolCallId?: string; toolName?: string } }; if (typedPart.type === 'tool-call-approval' || typedPart.type === 'tool-call-suspended') { isSuspensionBoundary = true; runtime.#markRunSuspending(runtime.#getState(pubsub), output.runId, streamId, { toolCallId: typedPart.payload?.toolCallId, toolName: typedPart.payload?.toolName, kind: typedPart.type === 'tool-call-approval' ? 'approval' : 'generic-tool', }); } } let part = sanitizeBroadcastPart(rawPart); const producedAt = getChunkProducedAt(rawPart) ?? Date.now(); // Say why a run stopped when it lost its thread lease, so a subscriber can show more than "aborted". if ((part as { type?: string } | null)?.type === 'abort') { const runState = runtime.#getState(pubsub); if (runState.leaseLostRunIds.delete(output.runId)) { const abortPart = part as { payload?: Record }; part = { ...abortPart, payload: { ...abortPart.payload, reason: THREAD_LEASE_LOST_ABORT_REASON } }; } } stampPartProducedAt(part, producedAt); parts.push(part); if ((part as { type?: string } | null | undefined)?.type === 'start') startPart = part; const partType = (part as { type?: string } | null | undefined)?.type; const deliveredSignalId = userMessageSignalId(part); if (deliveredSignalId) { await runtime.#publishAndWait(pubsub, key, { type: 'user-message-delivered', signalId: deliveredSignalId }); } // Shutdown already announced this run's end; a later part would make observers track the stream again. if (runtime.#getState(pubsub).shutdownStreams.get(streamId) !== 'ended') { await runtime.#publishAndWait(pubsub, key, { type: 'stream-part', runId: output.runId, streamId, part, sourceId: runtime.#getSourceId(), generation: getGeneration?.(), producedAt, // `start` and prompts stay on the topic until the run is trimmed as a // whole, so a subscriber joining mid-run still sees the run begin. ...(partType === 'start' || partType === 'tool-call-approval' || partType === 'tool-call-suspended' ? { pinned: true } : {}), }); } const typedPart = part as { type?: string; finishReason?: string; payload?: { finishReason?: string } }; const finishReason = typedPart.finishReason ?? typedPart.payload?.finishReason; if ( typedPart.type === 'error' || typedPart.type === 'abort' || typedPart.type === 'tripwire' || (typedPart.type === 'finish' && finishReason !== 'tool-calls') ) { publishedTerminal = true; } published++; if (savedAt !== undefined) trimSaved(); wake(); if (isSuspensionBoundary) { await suspensionBoundaryHandler?.().catch(() => {}); stopSaveListener?.(); stopSaveListener = undefined; } // An error chunk settles `_waitUntilFinished()` without closing // `fullStream` (durable error-recovery keeps consuming), so the pump can // stay blocked on `read()` forever. The error chunk is the last part // this run broadcasts, and it has now been published — settle // `broadcastFinished` here so the terminal publish gate (and the lease // release/drain behind it) is never stranded on the error path. if ((part as { type?: string } | null | undefined)?.type === 'error') { failed = true; resolveBroadcastFinished(); } }; const start = () => { if (started) return; started = true; void (async () => { try { if (cancelled) return; const source = (output.__getUnfilteredFullStream?.() ?? output.fullStream) as | ReadableStream | undefined; if (!source) return; if (typeof source.getReader === 'function') { const reader = source.getReader(); cancelSource = async () => { await reader.cancel().catch(() => {}); }; try { while (!cancelled) { const { value: part, done: streamDone } = await reader.read(); if (streamDone) break; await emitPart(part); } } finally { reader.releaseLock(); } } else { const iterable = source as AsyncIterable | Iterable; const iterator = Symbol.asyncIterator in Object(iterable) ? (iterable as AsyncIterable)[Symbol.asyncIterator]() : (iterable as Iterable)[Symbol.iterator](); let iteratorClosed = false; const closeIterator = async () => { if (iteratorClosed) return; iteratorClosed = true; await iterator.return?.(); }; cancelSource = async () => { await closeIterator().catch(() => {}); }; try { while (!cancelled) { const { value: part, done: streamDone } = await iterator.next(); if (streamDone) { iteratorClosed = true; break; } await emitPart(part); } } finally { if (!iteratorClosed) await closeIterator(); } } } catch (caught) { failed = true; error = caught; } finally { done = true; resolveBroadcastFinished(); wake(); } })(); }; const cancel = async () => { if (cancelled) return; cancelled = true; if (!started) { done = true; resolveBroadcastFinished(); wake(); return; } await cancelSource?.(); // The pump can already be awaiting an in-flight publish. Do not let the // rollback return until that work has drained and no later part can land. await broadcastFinished; }; // Messages saved mid-run (e.g. at each step) already hold every part up to // the last finished step: drop those parts from the topic and, once every // open reader has passed them, from this buffer. // Latest save not yet fully trimmed; publishing can lag behind the save. let savedAt: number | undefined; let trimmedThrough = -1; const trimSaved = () => { if (savedAt === undefined) return; let cutoff = -1; let cutoffAt: number | undefined; for (let i = dropped; i < published; i++) { const part = parts[i - dropped] as { type?: string } | undefined; const at = getPartProducedAt(part); if (at === undefined || at > savedAt) { // Saves at a step's end (savePerStep) start before its step-finish is // produced: every part of the step is saved, only the marker is newer. if (at !== undefined && part?.type === 'step-finish' && i > cutoff + 1) { cutoff = i; cutoffAt = at; } savedAt = undefined; break; } if (part?.type === 'step-finish') { cutoff = i; cutoffAt = at; } } if (cutoffAt === undefined || cutoff <= trimmedThrough) return; trimmedThrough = cutoff; void runtime.#getPubSub(pubsub) .trimTopic(runtime.#threadTopic(key), { runId: output.runId, producedBefore: cutoffAt }) .catch(() => {}); let keep = cutoff + 1; for (const reader of readers) keep = Math.min(keep, reader.index); for (let i = dropped; i < keep; i++) { const type = (parts[i - dropped] as { type?: string } | undefined)?.type; if (type === 'tool-call-approval' || type === 'tool-call-suspended') { keep = i; break; } } if (keep > dropped) { parts.splice(0, keep - dropped); dropped = keep; } }; const { threadId: savedThreadId, resourceId: savedResourceId } = runtime.#parseThreadKey(key); startSaveListener = () => { // Once the broadcast has finished (including the error path, where the pump // keeps reading), nothing would stop a listener attached here. if (stopSaveListener || done || failed || cancelled) return; stopSaveListener = onThreadMessagesSaved({ threadId: savedThreadId, resourceId: savedResourceId }, at => { savedAt = Math.max(savedAt ?? at, at); trimSaved(); }); }; startSaveListener(); void broadcastFinished.then(() => { stopSaveListener?.(); stopSaveListener = undefined; }); const createStream = () => { // A subscriber that joins late starts after parts already dropped as // saved, but still gets the run's `start`. const reader = { index: dropped }; let pendingStart = dropped > 0 ? startPart : undefined; let closed = false; let waiter: (() => void) | undefined; readers.add(reader); return new ReadableStream({ async pull(controller) { start(); while (!closed) { if (pendingStart !== undefined) { controller.enqueue(pendingStart); pendingStart = undefined; return; } if (reader.index < dropped) reader.index = dropped; if (reader.index - dropped < parts.length) { controller.enqueue(parts[reader.index++ - dropped]); return; } if (error) { controller.error(error); return; } if (done) { readers.delete(reader); controller.close(); return; } await new Promise(resolve => { waiter = resolve; waiters.add(resolve); }); if (waiter) { waiters.delete(waiter); waiter = undefined; } } }, cancel() { closed = true; readers.delete(reader); if (waiter) { waiters.delete(waiter); waiter(); waiter = undefined; } }, }); }; return { output, createSubscriberStream: createStream, startBroadcast: start, cancelBroadcast: cancel, canContinueBroadcast: () => started && !done && !cancelled && !failed, setSuspensionBoundaryHandler: (handler: () => Promise) => { suspensionBoundaryHandler = handler; }, didPublishTerminal: () => publishedTerminal, broadcastFinished, }; } #getThreadTarget(options?: { memory?: AgentExecutionOptions['memory']; requestContext?: RequestContext }) { const thread = options?.memory?.thread; const threadId = (options?.requestContext?.get(MASTRA_THREAD_ID_KEY) as string | undefined) || (typeof thread === 'string' ? thread : thread?.id); const resourceId = (options?.requestContext?.get(MASTRA_RESOURCE_ID_KEY) as string | undefined) || options?.memory?.resource; return { threadId, resourceId }; } prepareRunOptions( options: AgentExecutionOptions, pubsub?: PubSub, cleanupAbortedRun?: () => Promise, ): AgentExecutionOptions { if (!options.runId) return options; const { threadId, resourceId } = this.#getThreadTarget(options); const key = threadId ? this.#threadKey(resourceId, threadId) : undefined; const state = this.#getState(pubsub); const abortController = new AbortController(); const upstreamAbortSignal = options.abortSignal; const abort = () => abortController.abort(upstreamAbortSignal?.reason); if (upstreamAbortSignal?.aborted) { abort(); } else { upstreamAbortSignal?.addEventListener('abort', abort, { once: true }); } const preparedRun: PreparedThreadRun = { ...(key ? { threadKey: key } : {}), abortController, cleanup: () => upstreamAbortSignal?.removeEventListener('abort', abort), cleanupAbortedRun, }; state.preparedRunsById.set(options.runId, preparedRun); this.#preparedRunsByAbortSignal.set(abortController.signal, preparedRun); if (key) this.#ensureThreadControlSubscription(state, pubsub, key); if (state.abortedRunIds.has(options.runId)) { abort(); } const requestContext = options.requestContext; const controllerContext = requestContext?.get('controller'); if (requestContext && typeof controllerContext === 'object' && controllerContext !== null) { const preparedRequestContext = new RequestContext(requestContext.entries()); preparedRequestContext.set('controller', { ...controllerContext, abortSignal: abortController.signal }); return { ...options, abortSignal: abortController.signal, requestContext: preparedRequestContext, }; } return { ...options, abortSignal: abortController.signal, }; } isRunAborted(runId: string, pubsub?: PubSub): boolean { return this.#getState(pubsub).abortedRunIds.has(runId); } /** * 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 { return this.#getState(pubsub).resumeFencedRunIds.has(runId); } #fenceResume(state: AgentThreadRuntimeState, runId: string): void { state.resumeFencedRunIds.delete(runId); state.resumeFencedRunIds.add(runId); if (state.resumeFencedRunIds.size > MAX_RESUME_FENCED_RUN_IDS) { state.resumeFencedRunIds.delete(state.resumeFencedRunIds.values().next().value!); } } /** * `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 { const fenceResume = options.fenceResume ?? true; const state = this.#getState(pubsub); const preparedRun = state.preparedRunsById.get(runId); if (!preparedRun) { state.abortedRunIds.add(runId); if (fenceResume) this.#fenceResume(state, runId); // A run parked on a tool suspension (a question to the user, a pending // generation) has no prepared run left to abort, and its completion // watcher returned when it suspended, so nothing else frees its thread. return this.#releaseParkedRun(state, pubsub, runId); } preparedRun.abortController.abort(); state.abortedRunIds.add(runId); // Only a suspension that already existed is fenced. One that parks after the // abort (the loop finishing its in-flight tools) stays answerable (#26871). if (fenceResume && preparedRun.output?.deref()?.status === 'suspended') this.#fenceResume(state, runId); const key = state.threadKeysByRunId.get(runId); if (key) { const streamId = state.activeThreadRunIds.get(key) === runId ? state.activeThreadStreamIds.get(key) : undefined; const record = streamId ? state.threadRunsByStreamId.get(streamId) : undefined; this.#releaseThreadLease(pubsub, key, runId); this.#publish(pubsub, key, { type: 'run-aborted', runId, streamId, superseded: record?.ownershipLost?.() || record?.lateRetakeHandoff, }); } return true; } /** * 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 { return this.#isParkedRun(this.#getState(pubsub), runId); } #isParkedRun(state: AgentThreadRuntimeState, runId: string): boolean { const record = state.threadRunsById.get(runId); return state.suspendedRunIds.has(runId) || record?.lifecycle === 'suspended' || record?.lifecycle === 'suspending'; } /** * Release an aborted run that is parked on a tool suspension. Its completion * watcher returned when it suspended, so without this the thread keeps it as * its blocking run: every later message is queued onto a run that will never * resume, and nothing sent after Stop is answered. The run is released the * way a finished run is: its records and thread reservation are dropped, then * the thread's pending work starts or its lease is given up. A run parked on * a tool approval is released the same way: the abort is the decision. */ #releaseParkedRun(state: AgentThreadRuntimeState, pubsub: PubSub | undefined, runId: string): boolean { const record = state.threadRunsById.get(runId); if (!this.#isParkedRun(state, runId) || !record) return false; const key = state.threadKeysByRunId.get(runId) ?? this.#threadKey(record.resourceId, record.threadId); this.#clearSuspendedRun(state, runId); record.lifecycle = 'completed'; state.displacedRecords.set(record, 'aborted'); state.threadRunsByStreamId.delete(record.streamId); if (state.threadRunsById.get(runId) === record) state.threadRunsById.delete(runId); state.threadKeysByRunId.delete(runId); if (state.activeThreadRunIds.get(key) !== runId) return true; state.activeThreadRunIds.delete(key); if (state.activeThreadStreamIds.get(key) === record.streamId) state.activeThreadStreamIds.delete(key); this.#publish(pubsub, key, { type: 'run-aborted', runId, streamId: record.streamId, superseded: record.ownershipLost?.() || record.lateRetakeHandoff, }); if (this.#hasPendingThreadWork(state, key)) { void this.#drainPendingSignals(state, pubsub, key, record); } else { this.#releaseThreadLease(pubsub, key, runId); } return true; } /** Release the local run that `runId` superseded, if it superseded one. */ #releaseRunSupersededBy( state: AgentThreadRuntimeState, pubsub: PubSub, key: string, subscription: ThreadControlSubscription, runId: string, ): void { const supersededRunId = subscription.supersedingRunIds.get(runId); if (supersededRunId === undefined) return; subscription.supersedingRunIds.delete(runId); this.#releaseSupersededParkedRun(state, pubsub, key, supersededRunId); } /** * Another runtime ran the thread to an end while this process's run was * parked on it. The parked run keeps its record and stays resumable, but it * no longer holds the thread: otherwise every later send would be queued * onto it, reported delivered, and never run. Queued work starts now, the * way it does after a run finishes. */ #releaseSupersededParkedRun(state: AgentThreadRuntimeState, pubsub: PubSub, key: string, runId: string): void { const record = state.threadRunsById.get(runId); if (!record || state.activeThreadRunIds.get(key) !== runId || !this.#isParkedRun(state, runId)) return; state.activeThreadRunIds.delete(key); if (state.activeThreadStreamIds.get(key) === record.streamId) state.activeThreadStreamIds.delete(key); this.#stopReadingDisplacedRun(state, runId); if (this.#hasPendingThreadWork(state, key)) { void this.#drainPendingSignals(state, pubsub, key, record); } else { this.#releaseThreadLease(pubsub, key, runId); } } /** * A parked run no longer holds its thread, so its answer resumes it on a new * stream. Subscribers reading its open stream, or with it still queued, move on * to the runs queued behind it. */ #stopReadingDisplacedRun(state: AgentThreadRuntimeState, runId: string, streamId?: string): void { if (streamId === undefined) { const record = state.threadRunsById.get(runId); if (record) state.displacedRecords.set(record, 'moved-on'); } for (const reader of [...(state.runStreamReaders.get(runId) ?? [])]) { if (streamId === undefined || reader.streamId === streamId) reader.stop(); } } getActiveThreadRunId(options: AgentThreadIdentityOptions, pubsub?: PubSub): string | undefined { const state = this.#getState(pubsub); const key = this.#threadKey(options.resourceId, options.threadId); const activeRunId = state.activeThreadRunIds.get(key); if (!activeRunId) return undefined; const record = state.threadRunsById.get(activeRunId); if (record && !this.#isThreadBlockingRun(state, record)) return undefined; return activeRunId; } /** Same predicate as {@link getActiveThreadRunId}, over every tracked thread. */ listActiveThreadRuns(pubsub?: PubSub): ActiveThreadRun[] { const state = this.#getState(pubsub); const runs: ActiveThreadRun[] = []; for (const [key, runId] of state.activeThreadRunIds) { const record = state.threadRunsById.get(runId); if (record && !this.#isThreadBlockingRun(state, record)) continue; runs.push({ runId, ...this.#parseThreadKey(key) }); } return runs; } hasThreadRun(runId: string, pubsub?: PubSub): boolean { return this.#getState(pubsub).threadRunsById.has(runId); } /** The resource and thread a `runId`-only signal or message target resolves to in this process. */ getThreadRunTarget(runId: string, pubsub?: PubSub): { resourceId?: string; threadId: string } | undefined { const record = this.#getState(pubsub).threadRunsById.get(runId); return record ? { resourceId: record.resourceId, threadId: record.threadId } : undefined; } /** Whether the run's original stream is still live and carries its resumed segments. */ hasRunContinuation(runId: string, pubsub?: PubSub): boolean { return this.#getState(pubsub).threadRunsById.get(runId)?.continuation?.canContinue() === true; } /** Capture whether the currently registered continuation publishes its terminal stream part. */ captureThreadRunTerminalPublish(runId: string, pubsub?: PubSub): (() => boolean) | undefined { return this.#getState(pubsub).threadRunsById.get(runId)?.continuation?.didPublishTerminal; } getResumableThreadRunSuspension( options: AgentSubscribeToThreadOptions & { runId: string; toolCallId?: string }, pubsub?: PubSub, ): AgentThreadRunSuspension | undefined { const state = this.#getState(pubsub); const key = this.#threadKey(options.resourceId, options.threadId); const record = state.threadRunsById.get(options.runId); const isSuspended = this.#isSuspendedRun(state, options.runId); if (!record || state.threadKeysByRunId.get(options.runId) !== key || !isSuspended) { return undefined; } const suspensions = state.suspensionMetadataByRunId.get(options.runId); return options.toolCallId ? suspensions?.get(options.toolCallId) : suspensions?.values().next().value; } /** @internal Restore a suspension consumed while attaching a second observer. */ __restoreThreadRunSuspension( options: AgentSubscribeToThreadOptions & { runId: string }, suspension: AgentThreadRunSuspension, pubsub?: PubSub, ): boolean { const state = this.#getState(pubsub); const key = this.#threadKey(options.resourceId, options.threadId); const record = state.threadRunsById.get(options.runId); if ( !record || state.threadKeysByRunId.get(options.runId) !== key || (record.lifecycle !== 'suspending' && record.lifecycle !== 'suspended') ) { return false; } const lifecycle = record.lifecycle; this.#markRunSuspending(state, options.runId, record.streamId, suspension); record.lifecycle = lifecycle; return true; } getResumableThreadRun( options: AgentSubscribeToThreadOptions & { runId: string; toolCallId?: string }, pubsub?: PubSub, ): { runId: string; toolCallId?: string } | undefined { const state = this.#getState(pubsub); const key = this.#threadKey(options.resourceId, options.threadId); const record = state.threadRunsById.get(options.runId); const isSuspended = this.#isSuspendedRun(state, options.runId); if (!record || state.threadKeysByRunId.get(options.runId) !== key || !isSuspended) { return undefined; } const suspensions = state.suspensionMetadataByRunId.get(options.runId); const suspension = options.toolCallId ? suspensions?.get(options.toolCallId) : suspensions?.values().next().value; if (options.toolCallId && !suspension) { return undefined; } return { runId: options.runId, toolCallId: options.toolCallId ?? suspension?.toolCallId }; } /** * 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. */ async queueStreamResume( runId: string, resume: () => Promise>, pubsub?: PubSub, ): Promise> { const state = this.#getState(pubsub); const previousTail = state.resumeTailsByRunId.get(runId) ?? Promise.resolve(); let resolveStarted!: (output: MastraModelOutput) => void; let rejectStarted!: (error: unknown) => void; const started = new Promise>((resolve, reject) => { resolveStarted = resolve; rejectStarted = reject; }); const resumeTail = previousTail .catch(() => {}) .then(async () => { try { const output = await resume(); resolveStarted(output); await output._waitUntilFinished(); } catch (error) { rejectStarted(error); throw error; } }); const settledTail = resumeTail .catch(() => {}) .finally(() => { if (state.resumeTailsByRunId.get(runId) === settledTail) { state.resumeTailsByRunId.delete(runId); } }); state.resumeTailsByRunId.set(runId, settledTail); return started; } abortThread(options: AgentAbortThreadOptions, pubsub?: PubSub): boolean { const resolvedPubSub = this.#getPubSub(pubsub); const state = this.#getState(resolvedPubSub); const key = this.#threadKey(options.resourceId, options.threadId); const runId = this.getActiveThreadRunId(options, resolvedPubSub); // A stale request conditioned on a run that is no longer active must not // stop the successor run or clear input queued for it. if (options.expectedRunId !== undefined && options.expectedRunId !== runId) return false; if (options.clearPendingSignals) this.#cancelPendingSignals(state, key, undefined, pubsub); try { if (!runId) return false; if (options.localOnly && this.#isParkedRun(state, runId) && !state.preparedRunsById.has(runId)) { this.#releaseSupersededParkedRun(state, resolvedPubSub, key, runId); return true; } const abortOptions = { fenceResume: !options.localOnly }; if (state.preparedRunsById.has(runId)) return this.abortRun(runId, resolvedPubSub, abortOptions); if (state.threadKeysByRunId.get(runId) === key) { // Reserved locally (a sendSignal wake that has not prepared its run yet): // record the abort intent so preparation aborts the run before it starts. this.abortRun(runId, resolvedPubSub, abortOptions); return true; } if (state.remoteThreadKeysByRunId.get(runId) !== key) return false; const streamId = state.activeThreadStreamIds.get(key); if (!streamId) return false; // A remote owner's run is only stopped when the abort is meant for it. Thread // lifecycle transitions abort locally on the way out and must not reach across // processes: a follower running `/new` would otherwise kill the owner's run. if (options.localOnly) return false; this.#publish(resolvedPubSub, key, { type: 'run-abort-requested', runId, streamId, ...(options.clearPendingSignals ? { clearPendingSignals: true } : {}), }); return true; } finally { // Synchronous listeners must see the completed clear/abort, not an intermediate state. if (options.clearPendingSignals) this.#notifyThreadEvents(state); } } /** @internal */ resetForTests() { for (const pubsub of [defaultAgentThreadPubSub]) { this.#resetState(pubsub); void (pubsub as { close?: () => Promise }).close?.(); } defaultAgentThreadPubSub = new EventEmitterPubSub(); } #resetState(pubsub: PubSub) { const state = this.#statesByPubSub.get(pubsub); if (!state) return; state.preparedRunsById.forEach(preparedRun => { preparedRun.abortController.abort(); preparedRun.cleanup(); }); for (const subscription of state.threadControlSubscriptions.values()) subscription.unsubscribe(); state.threadControlSubscriptions.clear(); state.leaseRenewalTimers.forEach(timer => clearInterval(timer)); state.leaseRenewalTimers.clear(); state.leaseDeadlines.forEach(({ timer }) => clearTimeout(timer)); state.leaseDeadlines.clear(); state.leaseFences.forEach((fence, runId) => clearRunLeaseFence(runId, fence)); state.leaseFences.clear(); state.threadRunsById.clear(); state.threadRunsByStreamId.clear(); state.threadKeysByRunId.clear(); state.remoteThreadKeysByRunId.clear(); state.remoteAgentIdsByRunId.clear(); state.unobservedRemoteRunIds.clear(); state.activeThreadRunIds.clear(); state.approvalSuspendedRunIds.clear(); state.suspendedRunIds.clear(); state.suspensionMetadataByRunId.clear(); state.pendingSignalsByThread.clear(); state.locallyQueuedSignalIdsByThread.clear(); state.preRunSignalsByThread.clear(); state.lostRunsByThread.clear(); state.pendingIdleSignalsByThread.clear(); state.forwardedIdleSignalsByThread.clear(); for (const check of state.forwardedIdleLeaseChecks.values()) clearInterval(check); state.forwardedIdleLeaseChecks.clear(); state.sweptLeasedRunIds.clear(); state.pendingLeaseRenewals.clear(); state.leaseRetakes.clear(); state.leaseLostRunIds.clear(); state.shutdownStreams.clear(); state.drainingPendingSignalsByThread.clear(); state.pendingContinuationsByThread.clear(); state.claimedThreadOwnerDiscoveries.clear(); state.pendingThreadAdmissions.clear(); state.handledIdleSignals.clear(); state.acceptedIdleMessagesByIdentity.clear(); state.claimedQueuedMessages.clear(); for (const claim of [...state.claimedThreadOwners.values()]) { claim.unsubscribe(); } state.claimedThreadOwners.clear(); for (const peer of [...state.advertisedThreadPeers.values()]) { peer.unsubscribe(); } state.advertisedThreadPeers.clear(); state.activeThreadStreamIds.clear(); state.streamSeqByRunId.clear(); state.watchedThreadStreamIds.clear(); for (const preparedRun of state.preparedRunsById.values()) { if (preparedRun.finalizerToken) this.#threadlessRunFinalizer?.unregister(preparedRun.finalizerToken); } state.preparedRunsById.clear(); state.resumeTailsByRunId.clear(); state.abortedRunIds.clear(); state.resumeFencedRunIds.clear(); } #cleanupPreparedRun(state: AgentThreadRuntimeState, runId: string, expectedPreparedRun?: PreparedThreadRun) { const preparedRun = state.preparedRunsById.get(runId); if (expectedPreparedRun && preparedRun !== expectedPreparedRun) { expectedPreparedRun.cleanup(); if (expectedPreparedRun.finalizerToken) { this.#threadlessRunFinalizer?.unregister(expectedPreparedRun.finalizerToken); } return; } preparedRun?.cleanup(); if (preparedRun?.finalizerToken) this.#threadlessRunFinalizer?.unregister(preparedRun.finalizerToken); const record = state.threadRunsById.get(runId); if (preparedRun && record) record.segmentAbortController = preparedRun.abortController; state.preparedRunsById.delete(runId); state.pendingSignalListenersByRunId.delete(runId); state.abortedRunIds.delete(runId); if (state.resumeFencedRunIds.has(runId) && preparedRun?.cleanupAbortedRun) { // The aborted segment persisted a suspended snapshot. Keep the fence until that // snapshot is deleted; if deletion fails the fence stays (bounded by MAX_RESUME_FENCED_RUN_IDS). void preparedRun.cleanupAbortedRun().then( deleted => { if (deleted) state.resumeFencedRunIds.delete(runId); }, () => {}, ); } } #pendingUserMessageChunk( runId: string, signal: CreatedAgentSignal, status: 'pending' | 'queued', ): UserMessagePendingChunk | undefined { if (signal.type !== 'user' || signal.transient) return; const { data } = signal.toDataPart(); return { type: 'data-user-message-pending', runId, from: ChunkFrom.AGENT, transient: true, data: { ...data, metadata: { ...data.metadata, status } }, }; } /** * Queues a signal for in-loop draining by a same-agent run that is already in * flight here, so it becomes that run's next model input instead of waiting for * the run to finish. */ #queueForActiveRun( state: AgentThreadRuntimeState, pubsub: PubSub | undefined, key: string, record: AgentThreadRunRecord, signal: CreatedAgentSignal, ) { const queue = state.pendingSignalsByThread.get(key) ?? []; queue.push(signal); state.pendingSignalsByThread.set(key, queue); this.#recordLocallyQueuedSignal(state, key, signal.id); this.#publishPendingUserMessage(pubsub, key, record.runId, signal, 'pending'); this.#notifyPendingSignals(state, key, signal); this.#publish(pubsub, key, { type: 'signal-enqueued', runId: record.runId, signal: this.#serializeSignal(signal), sourceId: this.#getSourceId(), }); this.#watchThreadRunCompletion(state, pubsub, key, record); } #publishPendingUserMessage( pubsub: PubSub | undefined, key: string, runId: string, signal: CreatedAgentSignal, status: 'pending' | 'queued', ) { const chunk = this.#pendingUserMessageChunk(runId, signal, status); if (chunk) this.#publish(pubsub, key, { type: 'user-message-presentation', runId, chunk }); } #publishCancelledUserMessages(pubsub: PubSub | undefined, key: string, signalIds: string[]) { for (const id of signalIds) { this.#publish(pubsub, key, { type: 'user-message-presentation', chunk: { type: 'data-user-message-cancelled', runId: '', from: ChunkFrom.AGENT, transient: true, data: { id } }, }); } } async #persistSignal( agent: Agent, signal: CreatedAgentSignal, resourceId: string, threadId: string, requestContext?: RequestContext, ) { // Transient signals are delivery-only: never write them to storage, even when the // active-behavior asked to persist. Honored here (not just in the memory layer) so it holds // for any memory implementation, including ones without a signal-aware save filter. if (signal.transient) return; const memory = await agent.getMemory({ requestContext }); if (!memory) return; await memory.saveMessages({ messages: [signal.toDBMessage({ resourceId, threadId })], }); } #broadcastPersistedSignal( state: AgentThreadRuntimeState, pubsub: PubSub | undefined, key: string, runId: string, agentId: string, signal: CreatedAgentSignal, resourceId: string, threadId: string, ) { let finish!: () => void; const finished = new Promise(resolve => { finish = resolve; }); // Mirror the shape every real `start` emitter uses (see loop/workflows/stream.ts). // The messageId is derived from the signal id rather than reused verbatim so // consumers keying messages by id don't collide with the persisted signal row. const startChunk: ChunkType = { type: 'start', runId, from: ChunkFrom.AGENT, payload: { id: agentId, messageId: `persisted-signal:${signal.id}` }, }; const parts: any[] = [ startChunk, { ...signal.toDataPart(), runId }, { type: 'finish', runId, from: ChunkFrom.AGENT, payload: { stepResult: { reason: 'stop' }, output: { usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 }, }, }, }, ]; const output = { runId, status: 'running', fullStream: new ReadableStream({ start(controller) { for (const part of parts) controller.enqueue(part); controller.close(); finish(); }, }), _waitUntilFinished: () => finished, } as MastraModelOutput; const { streamId, streamSeq } = this.#nextStreamIdentity(state, runId); const { output: outputForSubscribers, createSubscriberStream, startBroadcast, broadcastFinished, } = this.#withBroadcastStream(output, pubsub, key, streamId); const record: AgentThreadRunRecord = { agent: { id: `persisted-signal:${signal.id}` } as Agent, output: outputForSubscribers, runId, streamId, streamSeq, lifecycle: 'running', threadId, resourceId, streamOptions: {}, createSubscriberStream, }; state.threadRunsById.set(runId, record); state.threadRunsByStreamId.set(streamId, record); state.threadKeysByRunId.set(runId, key); state.activeThreadStreamIds.set(key, streamId); const registered = this.#publishAndWait(pubsub, key, { type: 'run-registered', runId, streamId, streamSeq, sourceId: this.#getSourceId(), agentId, }); void registered.then(startBroadcast, startBroadcast); // Wait for the local stream to finish AND for every stream-part publish to // land before publishing `run-completed`: the terminal event must not // overtake the parts on the wire, or a deferred subscriber flushes an // empty buffer and drops the late parts. void Promise.allSettled([outputForSubscribers._waitUntilFinished(), broadcastFinished]).then(() => { setTimeout(() => { state.threadRunsByStreamId.delete(streamId); if (state.threadRunsById.get(runId) === record) { state.threadRunsById.delete(runId); state.threadKeysByRunId.delete(runId); } if (state.activeThreadRunIds.get(key) === runId && state.activeThreadStreamIds.get(key) === streamId) { state.activeThreadRunIds.delete(key); state.activeThreadStreamIds.delete(key); } if (state.shutdownStreams.has(streamId)) return; this.#releaseThreadLease(pubsub, key, runId); // The signal this run rebroadcasts is persisted by definition. // The signal this run rebroadcasts is persisted by definition, so once // run-completed lands its entries can leave the topic. void this.#publishAndWait(pubsub, key, { type: 'run-completed', runId, streamId, persisted: true, status: 'success', }) .then(() => this.#getPubSub(pubsub).trimTopic(this.#threadTopic(key), { runId, retainTerminalEvents: true })) .catch(() => {}); }, 0); }); } async #persistAndBroadcastIdleSignal( state: AgentThreadRuntimeState, pubsub: PubSub | undefined, key: string, runId: string, agent: Agent, signal: CreatedAgentSignal, resourceId: string, threadId: string, requestContext?: RequestContext, ) { if (signal.transient) return; state.persistingIdleRunIds.add(runId); try { await this.#persistSignal(agent, signal, resourceId, threadId, requestContext); this.#broadcastPersistedSignal(state, pubsub, key, runId, agent.id, signal, resourceId, threadId); } finally { state.persistingIdleRunIds.delete(runId); } } /** * Evict SUSPENDED records parked longer than {@link AGENT_SUSPENDED_RUN_TTL_MS}. * Called lazily on each registration so cleanup is proportional to activity and * zero-cost when idle — mirrors the internal-workflow registry sweep. Bounds the * records left behind by abandoned suspends and by resumes that land on a * different instance (which never clean the origin instance's record). * * An expiring record only proves that this runtime no longer owns warm state. * Another instance may have resumed the same runId and taken over its lease, so * cleanup must remain local: stop this runtime's renewal timer and let an * abandoned lease expire naturally instead of releasing or broadcasting a * terminal event that could disrupt the resumed run. */ #sweepStaleSuspendedRecords(state: AgentThreadRuntimeState, pubsub: PubSub | undefined) { const now = Date.now(); for (const [runId, sweptAt] of state.sweptLeasedRunIds) { if (now - sweptAt > AGENT_THREAD_LEASE_TTL_MS && !state.pendingLeaseRenewals.has(runId)) { state.sweptLeasedRunIds.delete(runId); } } for (const [streamId, record] of state.threadRunsByStreamId) { if (record.lifecycle !== 'suspended' || record.suspendedAt === undefined) continue; if (now - record.suspendedAt <= AGENT_SUSPENDED_RUN_TTL_MS) continue; state.threadRunsByStreamId.delete(streamId); state.watchedThreadStreamIds.delete(streamId); // A same-instance resume re-registers the run under a newer streamId, so a // record that is no longer the run's current record is just the superseded // older stream: dropping its stream entry above is enough. Only the current // record (an abandoned suspend) gets the full run-level teardown below. if (state.threadRunsById.get(record.runId) !== record) continue; const staleKey = this.#threadKey(record.resourceId, record.threadId); state.threadRunsById.delete(record.runId); state.threadKeysByRunId.delete(record.runId); this.#clearSuspendedRun(state, record.runId); this.#stopLeaseRenewal(this.#getPubSub(pubsub), record.runId); state.sweptLeasedRunIds.set(record.runId, now); state.displacedRecords.set(record, 'moved-on'); // A run parked across its suspension keeps its stream open, so subscribers // reading it would never reach the runs queued behind it. Only this record's // stream: a subscriber may be reading another instance's resume of the run. this.#stopReadingDisplacedRun(state, record.runId, streamId); if ( state.activeThreadRunIds.get(staleKey) === record.runId && state.activeThreadStreamIds.get(staleKey) === streamId ) { state.activeThreadRunIds.delete(staleKey); state.activeThreadStreamIds.delete(staleKey); } this.#releaseUnusedThreadControlSubscription(state, staleKey); } } continueRun( agent: Agent, output: MastraModelOutput, streamOptions: AgentExecutionOptions, pubsub?: PubSub, claim?: AgentThreadRunClaim & { generation?: number }, ): boolean { const { threadId, resourceId } = this.#getThreadTarget(streamOptions); if (!threadId) return false; const state = this.#getState(pubsub); this.#sweepStaleSuspendedRecords(state, pubsub); const key = this.#threadKey(resourceId, threadId); const existing = state.threadRunsById.get(output.runId); if ( !existing?.continuation?.canContinue() || existing.agent !== agent || existing.threadId !== threadId || existing.resourceId !== resourceId || state.activeThreadRunIds.get(key) !== output.runId || state.activeThreadStreamIds.get(key) !== existing.streamId || (output.status !== 'running' && output.status !== 'suspended') || existing.lifecycle === 'completed' || existing.lifecycle === 'failed' || existing.lifecycle === 'aborted' ) { return false; } const resumedToolCallId = (streamOptions as AgentExecutionOptions & { toolCallId?: string }).toolCallId; if (resumedToolCallId) this.#clearSuspendedToolCall(state, output.runId, resumedToolCallId); else this.#clearSuspendedRun(state, output.runId); existing.lifecycle = 'running'; existing.streamOptions = streamOptions; existing.currentSegmentOutput = output; if (claim?.generation !== undefined) existing.generation = claim.generation; if (claim?.ownershipLost) existing.ownershipLost = claim.ownershipLost; if (claim?.stepOwner) existing.stepOwner = claim.stepOwner; // Resume callers may only send an approval and never read this segment. // Drain its native output so completion and subsequent approvals advance. void output.consumeStream(); return true; } /** * 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. */ async reacquireParkedRunLease(runId: string, pubsub?: PubSub): Promise { const state = this.#getState(pubsub); const record = state.threadRunsById.get(runId); if (record?.lifecycle !== 'suspended' || state.leaseRenewalTimers.has(runId)) return; const key = this.#threadKey(record.resourceId, record.threadId); if (state.activeThreadRunIds.get(key) !== runId) return; const resolvedPubSub = this.#getPubSub(pubsub); const owner = record.leaseOwner ?? this.#threadLeaseOwner(resolvedPubSub, runId, record.generation); const lease = await this.#acquireThreadLease(resolvedPubSub, key, runId, owner); if (!lease.acquired) throw new AgentThreadLeaseConflictError(runId, lease.owner ?? 'another owner'); // The run may have been aborted (and its record dropped) while the lease was being taken. Give back // only this lease; a newer registration of the run owns and renews its own. if ( state.threadRunsById.get(runId) !== record || record.lifecycle !== 'suspended' || state.activeThreadRunIds.get(key) !== runId ) { if (!state.threadRunsById.has(runId)) { void this.#getLeaseProvider(resolvedPubSub) .releaseLease(key, owner) .catch(() => {}); } return; } this.#startLeaseRenewal(resolvedPubSub, key, runId, owner); record.leaseOwner = owner; } closeRunContinuation(ownerOutput: MastraModelOutput, pubsub?: PubSub): boolean { const record = this.#getState(pubsub).threadRunsById.get(ownerOutput.runId); if ( !record?.continuation || (record.continuation.sourceOutput !== ownerOutput && record.currentSegmentOutput !== ownerOutput) ) { return false; } record.continuation = undefined; return true; } #attachInvocationOutput( state: AgentThreadRuntimeState, agent: Agent, output: MastraModelOutput, streamOptions: AgentExecutionOptions, pubsub: PubSub | undefined, threadId: string, resourceId: string | undefined, registrationOptions?: AgentThreadStrictRegistrationOptions | AgentThreadStreamRegistrationOptions, leaseOwner?: string, ) { const key = this.#threadKey(resourceId, threadId); const { streamId, streamSeq } = this.#nextStreamIdentity(state, output.runId); const broadcast = this.#withBroadcastStream(output, pubsub, key, streamId, streamSeq > 1, () => record.generation); if (!registrationOptions?.strict) { const resumedToolCallId = (streamOptions as AgentExecutionOptions & { toolCallId?: string }).toolCallId; if (resumedToolCallId) this.#clearSuspendedToolCall(state, output.runId, resumedToolCallId); else this.#clearSuspendedRun(state, output.runId); } const record: AgentThreadRunRecord = { agent, output: broadcast.output, currentSegmentOutput: output, runId: output.runId, streamId, streamSeq, generation: registrationOptions?.generation, ...(registrationOptions?.strict ? { supersedes: registrationOptions.generation !== undefined, leaseOwner } : {}), ownershipLost: registrationOptions?.ownershipLost, stepOwner: registrationOptions?.stepOwner, lifecycle: 'running', threadId, resourceId, streamOptions: streamOptions as AgentThreadRunRecord['streamOptions'], createSubscriberStream: broadcast.createSubscriberStream, suspensions: state.suspensionMetadataByRunId.get(output.runId), broadcastFinished: broadcast.broadcastFinished, continuation: registrationOptions?.continuation === 'across-suspension' ? { sourceOutput: output, canContinue: broadcast.canContinueBroadcast, didPublishTerminal: broadcast.didPublishTerminal, } : undefined, }; return { record, streamId, streamSeq, ...broadcast }; } registerRun( agent: Agent, output: MastraModelOutput, streamOptions: AgentExecutionOptions, pubsub: PubSub | undefined, registrationOptions: AgentThreadStrictRegistrationOptions, ): Promise | undefined; registerRun( agent: Agent, output: MastraModelOutput, streamOptions: AgentExecutionOptions, pubsub?: PubSub, registrationOptions?: AgentThreadStreamRegistrationOptions, ): Promise | undefined; registerRun( agent: Agent, output: MastraModelOutput, streamOptions: AgentExecutionOptions, pubsub?: PubSub, registrationOptions?: AgentThreadStrictRegistrationOptions | AgentThreadStreamRegistrationOptions, ): Promise | undefined { const { threadId, resourceId } = this.#getThreadTarget(streamOptions); const preparedRun = streamOptions.abortSignal ? this.#preparedRunsByAbortSignal.get(streamOptions.abortSignal) : undefined; // Weak, so the threadless finalizer below can still collect an abandoned output. if (preparedRun) preparedRun.output = new WeakRef(output); if (!threadId) { if (registrationOptions?.strict) return; const state = this.#getState(pubsub); const runId = output.runId; const finalizerToken = {}; if (preparedRun) { preparedRun.finalizerToken = finalizerToken; this.#threadlessRunFinalizer?.register(output, { state, runId, token: finalizerToken }, finalizerToken); void Promise.allSettled([output._waitUntilFinished()]).then(() => { this.#cleanupPreparedRun(state, runId, preparedRun); }); } return; } if (registrationOptions?.strict) { return this.#registerRunStrict(agent, output, streamOptions, pubsub, threadId, resourceId, registrationOptions); } const state = this.#getState(pubsub); this.#sweepStaleSuspendedRecords(state, pubsub); const key = this.#threadKey(resourceId, threadId); const { record, streamId, streamSeq, startBroadcast, setSuspensionBoundaryHandler } = this.#attachInvocationOutput( state, agent, output, streamOptions, pubsub, threadId, resourceId, registrationOptions, ); // A run parked on a tool suspension keeps renewing the thread lease while it // waits. A run that starts on the thread anyway takes the thread over, so it // takes the lease too: otherwise, once it ends, every send loses the lease to // the parked run and is forwarded to a run nothing resumes. The parked run // keeps its record and stays resumable. const activeRunId = state.activeThreadRunIds.get(key); const takesLeaseFrom = activeRunId !== undefined && activeRunId !== output.runId && state.threadKeysByRunId.get(activeRunId) === key && this.#isParkedRun(state, activeRunId) ? activeRunId : undefined; state.threadRunsById.set(output.runId, record); state.threadRunsByStreamId.set(streamId, record); state.threadKeysByRunId.set(output.runId, key); state.activeThreadRunIds.set(key, output.runId); state.activeThreadStreamIds.set(key, streamId); state.lostRunsByThread.delete(key); if (takesLeaseFrom) this.#stopReadingDisplacedRun(state, takesLeaseFrom); const resolvedPubSub = this.#getPubSub(pubsub); const registered = (async () => { await this.#ensureThreadControlSubscription(state, resolvedPubSub, key).ready; // Every thread-bound run must hold the cross-process lease while it is // live: the liveness checks (markActiveIfLive / #waitForRemoteRunToFinish) // treat a lease-less run as a ghost, so a plain `agent.stream()` run that // never acquired would let contending instances start competing runs // instead of serializing behind it. Acquire BEFORE publishing // `run-registered` so an observer that checks liveness on receipt finds // the lease held. Same-owner acquire is an idempotent TTL refresh, so // signal-woken runs that already hold the lease under this runId just // renew. Fail-open on loss or error (simultaneous-start race): proceed // and never roll back the local registration — matches pre-lease // semantics and sendSignal's documented fail-open rationale. A thrown // acquire (transient provider error) is treated as acquired so renewal // starts: if the acquire landed server-side but the response failed, // skipping renewal would let the lease expire mid-run; renewal // self-stops when we don't own the key. if (takesLeaseFrom) { // Starts the renewal under the owner it took the lease with. const taken = await this.#acquireOrTransferThreadLease(resolvedPubSub, key, output.runId, takesLeaseFrom); if (taken.acquired) record.leaseOwner = state.leaseOwners.get(output.runId); else record.leaseNotAcquired = true; } else { const owner = this.#threadLeaseOwner(resolvedPubSub, output.runId, record.generation); const lease = await this.#acquireThreadLease(resolvedPubSub, key, output.runId, owner).catch(() => ({ acquired: true as boolean, })); if (lease.acquired) { this.#startLeaseRenewal(resolvedPubSub, key, output.runId, owner); record.leaseOwner = owner; } else { record.leaseNotAcquired = true; } } await this.#publishAndWait(pubsub, key, { type: 'run-registered', runId: output.runId, streamId, streamSeq, sourceId: this.#getSourceId(), agentId: agent.id, generation: registrationOptions?.generation, }); })(); // Always drive the run's stream to completion, even when no caller consumes // the returned output (e.g. a fire-and-forget schedule wake). The broadcast // tee buffers every part, so a later/external subscriber still replays the // full stream; without this pump the run never reaches a terminal state and // its active-run record + thread lease would never release, permanently // wedging the thread. if (record.continuation) { setSuspensionBoundaryHandler(() => this.#publishRunSuspended(pubsub, key, record)); } void registered.then(startBroadcast, startBroadcast); this.#watchThreadRunCompletion(state, pubsub, key, record, registered); return registered; } async #registerRunStrict( agent: Agent, output: MastraModelOutput, streamOptions: AgentExecutionOptions, pubsub: PubSub | undefined, threadId: string, resourceId: string | undefined, registrationOptions: AgentThreadStrictRegistrationOptions, ): Promise { await registrationOptions.validate?.(); const state = this.#getState(pubsub); this.#sweepStaleSuspendedRecords(state, pubsub); const key = this.#threadKey(resourceId, threadId); const activeRunId = state.activeThreadRunIds.get(key); const activeRecord = activeRunId ? state.threadRunsById.get(activeRunId) : undefined; if (activeRecord && activeRecord.runId !== output.runId && this.#isThreadBlockingRun(state, activeRecord)) { throw new Error(`Cannot register run ${output.runId}: thread is already active with run ${activeRunId}`); } const resolvedPubSub = this.#getPubSub(pubsub); const owner = this.#threadLeaseOwner(resolvedPubSub, output.runId, registrationOptions.generation); const lease = await this.#acquireThreadLease(resolvedPubSub, key, output.runId, owner); if (!lease.acquired) { throw new AgentThreadLeaseConflictError(output.runId, lease.owner ?? 'another owner'); } // A failed external-ownership validation means another recovery attempt may // already own this same runId. Do not release its indistinguishable thread // lease; its TTL or the successor registration will take over renewal. await registrationOptions.validate?.(); this.#stopLeaseRenewal(resolvedPubSub, output.runId); this.#startLeaseRenewal(resolvedPubSub, key, output.runId, owner); const { record, streamId, streamSeq, startBroadcast, cancelBroadcast, setSuspensionBoundaryHandler } = this.#attachInvocationOutput( state, agent, output, streamOptions, pubsub, threadId, resourceId, registrationOptions, owner, ); let rolledBack = false; let registrationPublished = false; let completionWatcherDisabled = false; const rollback = async ({ releaseLease = true }: { releaseLease?: boolean } = {}) => { if (rolledBack) return; rolledBack = true; completionWatcherDisabled = true; await cancelBroadcast(); const ownsCurrentRecord = state.threadRunsById.get(record.runId) === record; if (state.threadRunsByStreamId.get(record.streamId) === record) { state.threadRunsByStreamId.delete(record.streamId); } state.watchedThreadStreamIds.delete(record.streamId); if (ownsCurrentRecord) { state.threadRunsById.delete(record.runId); if (state.threadKeysByRunId.get(record.runId) === key) { state.threadKeysByRunId.delete(record.runId); } } if ( state.activeThreadRunIds.get(key) === record.runId && state.activeThreadStreamIds.get(key) === record.streamId ) { state.activeThreadRunIds.delete(key); state.activeThreadStreamIds.delete(key); } // Renewal is keyed by runId, so only the current record may stop or // release it; an older rollback must not disturb a newer registration. if (ownsCurrentRecord) { this.#stopLeaseRenewal(resolvedPubSub, record.runId); if (releaseLease) { await this.#getLeaseProvider(resolvedPubSub) .releaseLease(key, owner) .catch(() => {}); } } if (registrationPublished) await discardPublishedRegistration().catch(() => {}); this.#releaseUnusedThreadControlSubscription(state, key); }; const discardPublishedRegistration = async () => { await this.#publishAndWait(pubsub, key, { type: 'run-discarded', runId: record.runId, streamId: record.streamId, }); }; state.threadRunsById.set(output.runId, record); state.threadRunsByStreamId.set(streamId, record); state.threadKeysByRunId.set(output.runId, key); state.activeThreadRunIds.set(key, output.runId); state.activeThreadStreamIds.set(key, streamId); try { await this.#ensureThreadControlSubscription(state, resolvedPubSub, key).ready; await this.#publishAndWait(pubsub, key, { type: 'run-registered', runId: output.runId, streamId, streamSeq, sourceId: this.#getSourceId(), agentId: agent.id, generation: registrationOptions.generation, supersedes: record.supersedes, }); registrationPublished = true; await registrationOptions.validate?.(); } catch (error) { if (!rolledBack) { let releaseLease = true; try { await registrationOptions.validate?.(); } catch { releaseLease = false; } await rollback({ releaseLease }); // A durable backend may accept/deliver the registration and still fail // its acknowledgement. `rollback` compensates every confirmed publish; // an ambiguous acknowledgement also gets an idempotent discard here. if (!registrationPublished) await discardPublishedRegistration().catch(() => {}); } throw error; } // Adopt only once registered: a rolled-back registration leaves them for the run's next execution. state.lostRunsByThread.delete(key); const resumedToolCallId = (streamOptions as AgentExecutionOptions & { toolCallId?: string }).toolCallId; if (resumedToolCallId) { this.#clearSuspendedToolCall(state, output.runId, resumedToolCallId); } else { this.#clearSuspendedRun(state, output.runId); } if (record.continuation) { setSuspensionBoundaryHandler(() => this.#publishRunSuspended(pubsub, key, record)); } this.#watchThreadRunCompletion(state, pubsub, key, record, undefined, () => completionWatcherDisabled); startBroadcast(); return { rollback }; } async #publishRunSuspended( pubsub: PubSub | undefined, key: string, record: AgentThreadRunRecord, ): Promise { record.lifecycle = 'suspended'; // Keep the record intact for resume routing while bounding how long a parked // run remains cached in this process. record.suspendedAt = Date.now(); const state = this.#getState(pubsub); // A suspended worker no longer renews the thread. Restore the parked runtime's // deadline and fence if the shared dispatch had put its timer in passive mode. const owner = state.leaseOwners.get(record.runId); if (owner && state.threadRunsById.get(record.runId) === record && !state.leaseDeadlines.has(record.runId)) { const resolvedPubSub = this.#getPubSub(pubsub); this.#stopLeaseRenewal(resolvedPubSub, record.runId); // No local deadline was tracked during dispatch. Verify the lease immediately. this.#startLeaseRenewal( resolvedPubSub, key, record.runId, owner, false, record.suspendedAt - AGENT_THREAD_LEASE_TTL_MS, ); } // Shutdown announces the runs it hands back itself. if (state.shutdownStreams.has(record.streamId)) return; await this.#publishAndWait(pubsub, key, { type: 'run-suspended', runId: record.runId, streamId: record.streamId, }); } #watchThreadRunCompletion( state: AgentThreadRuntimeState, pubsub: PubSub | undefined, key: string, record: AgentThreadRunRecord, registered?: Promise, isDisabled?: () => boolean, ) { if (state.watchedThreadStreamIds.has(record.streamId)) return; state.watchedThreadStreamIds.add(record.streamId); // Wait for BOTH the run to finish AND `run-registered` to be on the wire // before publishing the terminal event. A run that finishes faster than // the async lease-acquire that precedes the registration publish would // otherwise put `run-completed` on the wire before `run-registered`, // which subscribers cannot reconcile (and would release a lease that is // still being acquired). const finished = record.output._waitUntilFinished(); void Promise.allSettled(registered ? [finished, registered] : [finished]).then(async () => { if (isDisabled?.()) { state.watchedThreadStreamIds.delete(record.streamId); return; } this.#cleanupPreparedRun(state, record.runId); // The output settles ahead of the broadcast pump, which awaits one publish // per part. Only the pump marks the run suspended (when it reads the // approval/suspend part), so with pubsub latency the check below would // misread a suspended run as completed. Wait for the pump to drain; a // suspended stream has ended, so it settles. Continuation runs keep their // stream open across the suspension and publish `run-suspended` from the pump. // The stream stays marked as watched while waiting so no second watcher // can attach to this record and publish its terminal event again. if (record.output.status === 'suspended' && !record.continuation && !this.#isSuspendedRun(state, record.runId)) { await Promise.resolve(record.broadcastFinished); } state.watchedThreadStreamIds.delete(record.streamId); if (isDisabled?.()) return; if (record.output.status === 'suspended' && this.#isSuspendedRun(state, record.runId)) { void this.#publishRunSuspended(pubsub, key, record).catch(() => {}); return; } record.lifecycle = 'completed'; this.#clearSuspendedRun(state, record.runId); state.threadRunsByStreamId.delete(record.streamId); if (state.threadRunsById.get(record.runId) === record) { state.threadRunsById.delete(record.runId); state.threadKeysByRunId.delete(record.runId); } if ( state.activeThreadRunIds.get(key) === record.runId && state.activeThreadStreamIds.get(key) === record.streamId ) { state.activeThreadRunIds.delete(key); state.activeThreadStreamIds.delete(key); } // If queued follow-up work exists, keep the cross-process lease held by // handing it to the next run instead of releasing it: releasing here // would briefly empty the lease key, letting a racing process win it and // start a competing run on this thread. The drain runs under the // transferred lease and releases it only once every queue is empty. If // there's no pending work, release as usual so other processes can wake // the thread. // Wait for every stream-part broadcast publish to land before putting the // terminal event on the wire: `run-completed` overtaking in-flight parts // makes a deferred subscriber flush an empty buffer and drop the late // parts. The stream has already ended here (the run is terminal, not // suspended), so the broadcast pump is guaranteed to settle. Local state // cleanup above stays immediate. void Promise.resolve(record.broadcastFinished).then(() => { // A run shutdown hands back gets its terminal event and lease release from shutdown. if (isDisabled?.() || state.shutdownStreams.has(record.streamId)) return; // Suspended runs save their messages too, so their parts are backed by // storage; only a successful run leaves nothing actionable to trim. const persisted = record.output.status === 'success' || record.output.status === 'suspended'; void this.#publishAndWait(pubsub, key, { type: 'run-completed', runId: record.runId, streamId: record.streamId, // Origin-side truth for replay filtering: only a successful run flushed // its messages to storage, so only its retained chunks are backed by a // persisted message and safe to replay to fresh subscribers. persisted, status: record.output.status, superseded: record.ownershipLost?.() || record.lateRetakeHandoff, }) .then(() => record.output.status === 'success' ? this.#trimSavedRun(pubsub, key, record) : record.output.status !== 'suspended' ? this.#trimRunLater(pubsub, key, record.runId) : undefined, ) .catch(() => {}); if (record.ownershipLost?.()) { // The execution that took the run over holds its lease under the same // runId, so neither release it nor hand it to queued work here. Queued // follow-ups go to that execution instead. One in this process already // shares this thread's queues and the run's lease renewal. if (!state.threadRunsById.has(record.runId)) { this.#stopLeaseRenewal(this.#getPubSub(pubsub), record.runId); if (record.registeredElsewhere) { this.#handOffQueuedSignals(state, pubsub, key, record.runId, record.streamId); } else if (this.#hasPendingThreadWork(state, key)) { // It has not registered yet; its registration takes the queues. state.lostRunsByThread.set(key, record); } this.#releaseUnusedThreadControlSubscription(state, key); } } else if (record.lateRetakeHandoff) { // This record may no longer own the lease it holds the run id under: a handoff that landed after the // retake gave up installed that id on a lease nothing here renews, and a successor can hold it. Neither // release it nor drain through it — a drain transfers the lease from the run id to its own run. Mirror // the ownership-lost sibling and leave the lease to expire. if (!state.threadRunsById.has(record.runId)) { this.#stopLeaseRenewal(this.#getPubSub(pubsub), record.runId); if (record.registeredElsewhere) { this.#handOffQueuedSignals(state, pubsub, key, record.runId, record.streamId); } else if (this.#hasPendingThreadWork(state, key)) { // Nothing has taken the run yet; its registration takes the queues. Handing off now would publish // to a run id no execution holds and drop the local copies with it. state.lostRunsByThread.set(key, record); } this.#releaseUnusedThreadControlSubscription(state, key); } } else if ( record.leaseNotAcquired && (!this.#hasPendingThreadWork(state, key) || [...state.threadRunsByStreamId.values()].some(other => other.runId === record.runId)) ) { // A registration that never got the lease has no lease to release, and a drain transfers the lease to the // follow-up run, so it must not drain while the execution holding the lease is still live here; that // execution takes the queued work when it finishes. Once it has finished, this is the last execution that // can take the queue, and the drain moves the lease from the run's held owner or acquires it fresh. this.#releaseUnusedThreadControlSubscription(state, key); } else if (this.#hasPendingThreadWork(state, key)) { void this.#drainPendingSignals(state, pubsub, key, record); } else { this.#releaseThreadLease(pubsub, key, record.runId, record.leaseOwner); } }); }); } /** * Re-publish the thread's queued signals for `runId` to its execution in * another process, which ignores ones it already admitted. Never awaited: * this can run inside a delivery of the thread topic it publishes to. */ #handOffQueuedSignals( state: AgentThreadRuntimeState, pubsub: PubSub | undefined, key: string, runId: string, lostStreamId: string, ) { // Idle messages and continuations start new runs once the thread is idle, // so they stay here and start when that execution's run ends. if (state.pendingIdleSignalsByThread.get(key)?.length || state.pendingContinuationsByThread.get(key)?.length) { this.#ensureThreadControlSubscription(state, pubsub, key).successorRunIds.set(runId, lostStreamId); } for (const preRun of [true, false]) { const queues = preRun ? state.preRunSignalsByThread : state.pendingSignalsByThread; for (const signal of queues.get(key) ?? []) { void this.#publishAndWait(pubsub, key, { type: 'signal-enqueued', runId, signal: this.#serializeSignal(signal), sourceId: this.#getSourceId(), preRun, }).catch(() => {}); } queues.delete(key); } } /** * Delete a run's output while retaining outcomes and execution authority. * Matching by runId also removes output published before a restart, * including a resumed run's suspended half. Other runs' entries are never * touched. */ async #trimRun(pubsub: PubSub | undefined, key: string, runId: string) { await this.#getPubSub(pubsub).trimTopic(this.#threadTopic(key), { runId, retainTerminalEvents: true, }); } /** * Trim a run that finished successfully. With storage its output is saved, * so it goes now. Without storage the topic is the only copy live readers * have, so it goes after the same delay as an unsaved run. */ async #trimSavedRun( pubsub: PubSub | undefined, key: string, record: Pick, 'agent' | 'streamOptions' | 'runId'>, ) { const memory = await record.agent.getMemory?.({ requestContext: record.streamOptions.requestContext }); if (memory) await this.#trimRun(pubsub, key, record.runId); else this.#trimRunLater(pubsub, key, record.runId); } /** * Delay trimming output that storage doesn't back (failed, canceled, or * aborted runs, and every run of an agent without storage) so live * subscribers can finish reading it. Keep compact terminal events and * execution authority metadata so opted-in reconnecting subscribers can * recover the outcome. */ #trimRunLater(pubsub: PubSub | undefined, key: string, runId: string) { const timer = setTimeout(() => { this.#trimRun(pubsub, key, runId).catch(() => {}); }, UNSAVED_RUN_TRIM_DELAY_MS); timer.unref?.(); } async #drainPendingSignals( state: AgentThreadRuntimeState, pubsub: PubSub | undefined, key: string, previousRun: Pick, 'agent' | 'streamOptions' | 'runId' | 'resourceId' | 'threadId'>, ) { if (state.activeThreadRunIds.has(key)) { return; } // A run can finish before its first model request drained its pre-run // signals (e.g. it errored early). Don't strand them — fold them into the // follow-up queue so the next run still picks them up. const preRunLeftover = state.preRunSignalsByThread.get(key); if (preRunLeftover?.length) { state.preRunSignalsByThread.delete(key); state.pendingSignalsByThread.set(key, [...preRunLeftover, ...(state.pendingSignalsByThread.get(key) ?? [])]); } const queue = state.pendingSignalsByThread.get(key); let signal: CreatedAgentSignal | undefined; let nextRunId: string | undefined; let draining: { signal: CreatedAgentSignal; cancelled: boolean; handedOff: boolean } | undefined; try { signal = queue?.shift(); if (signal && queue) { if (queue.length === 0) { state.pendingSignalsByThread.delete(key); } // Hand the lease from the finished run to this drained run before // streaming, so the lease key never goes empty during the handoff. If the // old owner already lost the lease (e.g. a pubsub blip let the TTL lapse // and another process took over), forward the signal to the new winner // instead of starting a competing run here. nextRunId = globalThis.crypto.randomUUID(); const reservedRunId = nextRunId; state.activeThreadRunIds.set(key, reservedRunId); state.threadKeysByRunId.set(reservedRunId, key); draining = { signal, cancelled: false, handedOff: false }; state.drainingPendingSignalsByThread.set(key, draining); const ownership = this.#acquireOrTransferThreadLease(pubsub, key, reservedRunId, previousRun.runId); this.#trackPendingThreadAdmission( state, key, reservedRunId, previousRun.agent.id, ownership.then(lease => this.#threadAdmissionOutcome(reservedRunId, lease)), ); const owns = await ownership; if (draining.cancelled) { if (state.activeThreadRunIds.get(key) === nextRunId) state.activeThreadRunIds.delete(key); state.threadKeysByRunId.delete(nextRunId); this.#cleanupPreparedRun(state, nextRunId); await this.#drainPendingSignals(state, pubsub, key, { ...previousRun, runId: owns.acquired ? nextRunId : previousRun.runId, }); return; } // Selective cancellation ends here, but retain clear-on-abort intent through startup recovery. draining.handedOff = true; if (!owns.acquired) { if (state.activeThreadRunIds.get(key) === nextRunId) { state.activeThreadRunIds.delete(key); } state.threadKeysByRunId.delete(nextRunId); // Early follow-ups were already published as retained signal-enqueued // events, so only discard this runtime's local pre-run copies. state.preRunSignalsByThread.delete(key); if (owns.owner && !isRetakeLeaseOwner(owns.owner)) { const ownerRunId = threadLeaseRunId(owns.owner); // Forwarding is a handoff: the signal is no longer locally cancellable. // Echoes of the original enqueue stay suppressed, but the forwarded event must be // queued if this runtime later takes over the owner run. const ids = state.locallyQueuedSignalIdsByThread.get(key); if (ids?.has(signal.id)) ids.set(signal.id, ownerRunId); await this.#publishAndWait(pubsub, key, { type: 'signal-enqueued', runId: ownerRunId, signal: this.#serializeSignal(signal), sourceId: this.#getSourceId(), }).catch(() => {}); } else { const restored = state.pendingSignalsByThread.get(key) ?? []; state.pendingSignalsByThread.set(key, [signal, ...restored]); } return; } // Every signal sent to the finished run belongs in one follow-up turn, so // fold the rest of the queue into this run's first model request instead // of starting one run per signal. Read the map, not `queue`: cancellation // during the lease await replaces the array. const batched = state.pendingSignalsByThread.get(key) ?? []; if (batched.length > 0) { state.pendingSignalsByThread.delete(key); state.preRunSignalsByThread.set(key, [...batched, ...(state.preRunSignalsByThread.get(key) ?? [])]); } state.startingQueuedRunIds.add(nextRunId); const output = await previousRun.agent.stream(signal, { ...(previousRun.streamOptions as any), // Cancellation belongs to the finished run, not its queued follow-up. abortSignal: undefined, runId: nextRunId, memory: withThreadMemory( previousRun.streamOptions.memory, previousRun.resourceId ?? '', previousRun.threadId ?? '', ), }); // If the follow-up stops before its first model request, its completion // must drain the batched signals left in the pre-run queue. if (batched.length > 0) { const nextRecord = state.threadRunsById.get(output.runId); if (nextRecord) { this.#watchThreadRunCompletion(state, pubsub, key, nextRecord); } } return; } } catch (err) { // Starting the follow-up run failed (e.g. a transient connection error // from `agent.stream`, or the lease transfer itself threw). Mirror the // `#startContinuation` failure path: clean up the failed run's state, // restore the signal so it is not lost, surface the failure, then hand // the lease to remaining queued work and only release once nothing is // left to drain. The restored signal is deliberately NOT re-drained here // (that would tight-loop against a still-broken upstream); it delivers on // the next natural drain trigger instead. const failedRunId = nextRunId ?? previousRun.runId; if (nextRunId) { state.threadKeysByRunId.delete(nextRunId); this.#cleanupPreparedRun(state, nextRunId); if (state.activeThreadRunIds.get(key) === nextRunId) { state.activeThreadRunIds.delete(key); } } // Restore through the map, not the local `queue` array: the shift above // deletes the map entry when it empties the queue, so the local array // may be detached from the map by the time we get here. Signals batched // into the failed run's pre-run queue go back behind the drained signal. const batchedLeftover = state.preRunSignalsByThread.get(key) ?? []; state.preRunSignalsByThread.delete(key); const restored = [ ...(signal && !draining?.cancelled ? [signal] : []), ...batchedLeftover, ...(state.pendingSignalsByThread.get(key) ?? []), ]; if (restored.length > 0) state.pendingSignalsByThread.set(key, restored); this.#publish(pubsub, key, { type: 'run-failed', runId: failedRunId, error: `failed to start follow-up run for queued message: ${getErrorFromUnknown(err).message}${draining?.cancelled ? '; the message was cancelled' : '; the message was requeued and will deliver on the next turn'}`, }); if (previousRun.runId !== failedRunId) { this.#trimRunLater(pubsub, key, failedRunId); } if (previousRun.runId !== failedRunId) { // A synchronous throw from the lease transfer leaves the lease still // owned by the finished previous run with its renewal timer alive, // which would hold the key forever. Release it unconditionally before // the handoff below: the handoff helpers can report work without // starting a local run (e.g. the idle drain's lease-lost branch), so // gating this release on their outcome would leak the lease. Releasing // is owner-guarded, so this is a no-op when the transfer completed and // the failed run owned the lease. this.#releaseThreadLease(pubsub, key, previousRun.runId); } if (draining?.cancelled) { await this.#drainPendingSignals(state, pubsub, key, { ...previousRun, runId: failedRunId }); return; } void this.#drainPendingContinuations(state, pubsub, key, failedRunId).then(async started => { if (started) return; if (await this.#drainPendingIdleSignals(state, pubsub, key, failedRunId)) return; this.#releaseThreadLease(pubsub, key, failedRunId); }); return; } finally { if (state.drainingPendingSignalsByThread.get(key) === draining) state.drainingPendingSignalsByThread.delete(key); if (nextRunId) state.startingQueuedRunIds.delete(nextRunId); this.#releaseUnusedThreadControlSubscription(state, key); } if (await this.#drainPendingContinuations(state, pubsub, key, previousRun.runId)) { return; } if (await this.#drainPendingIdleSignals(state, pubsub, key, previousRun.runId)) { return; } // Nothing left to drain: release the lease we kept held for the drain. this.#releaseThreadLease(pubsub, key, previousRun.runId); } async #drainPendingContinuations( state: AgentThreadRuntimeState, pubsub: PubSub | undefined, key: string, fromRunId?: string, ) { if (state.activeThreadRunIds.has(key)) { return false; } const queue = state.pendingContinuationsByThread.get(key); const pending = queue?.shift(); if (!pending || !queue) { return false; } if (queue.length === 0) { state.pendingContinuationsByThread.delete(key); } // A continuation only ever drains in the process that owned the finished // run, so it always carries a `fromRunId` to hand the held lease to. If the // old owner already lost the lease, re-queue the continuation and let the // new lease owner take over rather than starting a competing run here. if (fromRunId) { state.activeThreadRunIds.set(key, pending.runId); state.threadKeysByRunId.set(pending.runId, key); const ownership = this.#acquireOrTransferThreadLease(pubsub, key, pending.runId, fromRunId); this.#trackPendingThreadAdmission( state, key, pending.runId, pending.agent.id, ownership.then(lease => this.#threadAdmissionOutcome(pending.runId, lease)), ); const owns = await ownership; if (!owns.acquired) { if (state.activeThreadRunIds.get(key) === pending.runId) { state.activeThreadRunIds.delete(key); } state.threadKeysByRunId.delete(pending.runId); state.preRunSignalsByThread.delete(key); const restored = state.pendingContinuationsByThread.get(key) ?? []; state.pendingContinuationsByThread.set(key, [pending, ...restored]); return false; } } this.#startContinuation(state, pubsub, key, pending); return true; } #startContinuation( state: AgentThreadRuntimeState, pubsub: PubSub | undefined, key: string, pending: PendingContinuation, ) { state.activeThreadRunIds.set(key, pending.runId); state.threadKeysByRunId.set(pending.runId, key); void pending.agent .stream(pending.messages, { ...(pending.streamOptions as any), runId: pending.runId, memory: withThreadMemory(pending.streamOptions?.memory, pending.resourceId, pending.threadId), }) .then(output => { if ((state.pendingContinuationsByThread.get(key)?.length ?? 0) > 0) { const nextRecord = state.threadRunsById.get(output.runId); if (nextRecord) { this.#watchThreadRunCompletion(state, pubsub, key, nextRecord); } } }) .catch(err => { state.threadKeysByRunId.delete(pending.runId); this.#cleanupPreparedRun(state, pending.runId); if (state.activeThreadRunIds.get(key) === pending.runId) { state.activeThreadRunIds.delete(key); } this.#publish(pubsub, key, { type: 'run-failed', runId: pending.runId, error: getErrorFromUnknown(err).message, }); this.#trimRunLater(pubsub, key, pending.runId); // Hand the lease to remaining queued work (transfer keeps the key from // going empty); only release once nothing is left to drain. void this.#drainPendingContinuations(state, pubsub, key, pending.runId).then(async started => { if (started) return; if (await this.#drainPendingIdleSignals(state, pubsub, key, pending.runId)) return; this.#releaseThreadLease(pubsub, key, pending.runId); }); }); } continueWithMessages( agent: Agent, messages: MessageListInput, target: { resourceId: string; threadId: string; streamOptions?: AgentExecutionOptions; runId?: string }, pubsub?: PubSub, ): { accepted: true; runId: string } { const state = this.#getState(pubsub); const key = this.#threadKey(target.resourceId, target.threadId); const runId = target.runId ?? globalThis.crypto.randomUUID(); const pending: PendingContinuation = { agent, messages, runId, resourceId: target.resourceId, threadId: target.threadId, streamOptions: target.streamOptions, }; const activeRunId = state.activeThreadRunIds.get(key); const activeRecord = activeRunId ? state.threadRunsById.get(activeRunId) : undefined; if (state.activeThreadRunIds.has(key)) { const queue = state.pendingContinuationsByThread.get(key) ?? []; queue.push(pending); state.pendingContinuationsByThread.set(key, queue); if (activeRecord) { this.#watchThreadRunCompletion(state, pubsub, key, activeRecord); } return { accepted: true, runId }; } this.#startContinuation(state, pubsub, key, pending); return { accepted: true, runId }; } async #drainPendingIdleSignals( state: AgentThreadRuntimeState, pubsub: PubSub | undefined, key: string, fromRunId?: string, ): Promise { if (state.activeThreadRunIds.has(key)) { return false; } const idleQueue = state.pendingIdleSignalsByThread.get(key); const pendingIdle = idleQueue?.shift(); if (!pendingIdle || !idleQueue) { return false; } if (idleQueue.length === 0) { state.pendingIdleSignalsByThread.delete(key); } state.drainingIdleSignalsByThread.set(key, pendingIdle); // A retry can be admitted with a new run id after this copy was queued (for // example the accepted record was evicted by newer messages before the retry // arrived). The accepted record is authoritative, so drop the superseded copy // rather than start a second run for the same logical message. const drainedIdentity = this.#idleMessageIdentity(pendingIdle.agent.id, key, pendingIdle.signal); if (drainedIdentity) { const acceptedMessage = state.acceptedIdleMessagesByIdentity.get(drainedIdentity); if (acceptedMessage && acceptedMessage.runId !== pendingIdle.runId) { state.drainingIdleSignalsByThread.delete(key); this.#notifyThreadEvents(state); // Hand the finishing run's lease on to whatever drains next, and report // whether work actually started — the caller only keeps the lease if so. return await this.#drainPendingIdleSignals(state, pubsub, key, fromRunId); } } state.activeThreadRunIds.set(key, pendingIdle.runId); state.threadKeysByRunId.set(pendingIdle.runId, key); // A queued idle signal may be draining either in the process that just // finished a run (it still holds the lease — hand it over) or in a // *different* process that observed the owner's run finish via pub/sub and // now wants to wake the thread (it holds no lease — it must win one). Either // way the run must only start if this process owns the cross-process lease, // otherwise two processes could each start a competing idle run. let owns: { acquired: boolean; owner?: string }; try { const ownership = this.#acquireOrTransferThreadLease(pubsub, key, pendingIdle.runId, fromRunId); this.#trackPendingThreadAdmission( state, key, pendingIdle.runId, pendingIdle.agent.id, ownership.then(lease => this.#threadAdmissionOutcome(pendingIdle.runId, lease)), ); owns = await ownership; } catch (err) { // No run started for this message and it will not be retried from the queue, // so the accepted identity must not keep claiming delivery — a sender retry // has to be free to route it again. Unless the signal was cancelled while the // lease was pending: that cancellation is the outcome a retry must observe, so // the tombstone has to outlive this failure instead of being cleared. if ( !pendingIdle.cancelled && drainedIdentity && state.acceptedIdleMessagesByIdentity.get(drainedIdentity)?.runId === pendingIdle.runId ) { state.acceptedIdleMessagesByIdentity.delete(drainedIdentity); } state.drainingIdleSignalsByThread.delete(key); state.threadKeysByRunId.delete(pendingIdle.runId); if (state.activeThreadRunIds.get(key) === pendingIdle.runId) { state.activeThreadRunIds.delete(key); } this.#notifyThreadEvents(state); this.#publish(pubsub, key, { type: 'run-failed', runId: pendingIdle.runId, error: getErrorFromUnknown(err).message, }); this.#trimRunLater(pubsub, key, pendingIdle.runId); if (!(await this.#drainPendingIdleSignals(state, pubsub, key, fromRunId))) { this.#releaseThreadLease(pubsub, key, fromRunId ?? pendingIdle.runId); } return true; } if (!owns.acquired) { // A cancellation during lease acquisition must not forward the signal. if (pendingIdle.cancelled) { state.drainingIdleSignalsByThread.delete(key); state.threadKeysByRunId.delete(pendingIdle.runId); if (state.activeThreadRunIds.get(key) === pendingIdle.runId) state.activeThreadRunIds.delete(key); this.#notifyThreadEvents(state); void this.#drainPendingIdleSignals(state, pubsub, key); return true; } // Roll back the optimistic local reservation. If another process owns the // lease, hand the already-accepted signal to that run. if (state.activeThreadRunIds.get(key) === pendingIdle.runId) { state.activeThreadRunIds.delete(key); } state.drainingIdleSignalsByThread.delete(key); state.threadKeysByRunId.delete(pendingIdle.runId); state.preRunSignalsByThread.delete(key); if (isRetakeLeaseOwner(owns.owner)) { // Keep the accepted input for the next natural drain trigger, rather // than forwarding to a token that no run can consume. const queue = state.pendingIdleSignalsByThread.get(key) ?? []; state.pendingIdleSignalsByThread.set(key, [pendingIdle, ...queue]); this.#notifyThreadEvents(state); return true; } const ownerRunId = owns.owner ? threadLeaseRunId(owns.owner) : undefined; // Only user messages have an admission the owner announces (`user-message-admitted`), so only // they can be held until admitted without risking a second delivery. Known limit: if the owner admits it // but that admission's publish fails, the held copy is queued again when the run ends and the message runs twice. // If the owner dies after admitting it but before running it, the held copy is already settled and the message is lost. // A forward to a run this runtime registered and then lost to a takeover is kept by the lost-segment guard in // the control subscription's terminal handler; that narrow window has no in-process test. if (owns.owner && ownerRunId && this.#pendingUserMessageChunk(ownerRunId, pendingIdle.signal, 'pending')) { const forwarded = state.forwardedIdleSignalsByThread.get(key) ?? new Map(); // The owner presents it under the run ID it resolves the address to, which drops a legacy retake marker. forwarded.set(pendingIdle.signal.id, { pendingIdle, runId: forwardedSignalRunId(owns.owner) }); state.forwardedIdleSignalsByThread.set(key, forwarded); this.#ensureThreadControlSubscription(state, pubsub, key); this.#watchForwardedIdleLease(state, pubsub, key); } // Only now is a held forward tracked, so the count never dips while the message moves to it. this.#notifyThreadEvents(state); if (ownerRunId) { await this.#publishAndWait(pubsub, key, { type: 'signal-enqueued', runId: ownerRunId, signal: this.#serializeSignal(pendingIdle.signal), sourceId: this.#getSourceId(), }).catch(() => {}); } const drained = await this.#drainPendingIdleSignals( state, pubsub, key, owns.acquired ? pendingIdle.runId : fromRunId, ); if (owns.acquired && !drained) this.#releaseThreadLease(pubsub, key, pendingIdle.runId); return drained || owns.acquired; } if (pendingIdle.cancelled) { state.drainingIdleSignalsByThread.delete(key); state.threadKeysByRunId.delete(pendingIdle.runId); if (state.activeThreadRunIds.get(key) === pendingIdle.runId) { state.activeThreadRunIds.delete(key); } this.#notifyThreadEvents(state); // Input that joined this reservation was acknowledged as delivered, so it still needs a run. The pending // drain starts one for it (and then the next queued wake) under the lease this reservation holds, or // releases the lease when nothing is left. void this.#drainPendingSignals(state, pubsub, key, { agent: pendingIdle.agent, runId: pendingIdle.runId, resourceId: pendingIdle.resourceId, threadId: pendingIdle.threadId, streamOptions: pendingIdle.streamOptions ?? {}, }); return true; } try { state.drainingIdleSignalsByThread.delete(key); this.#notifyThreadEvents(state); state.startingQueuedRunIds.add(pendingIdle.runId); const output = await pendingIdle.agent.stream(pendingIdle.signal, { ...(pendingIdle.streamOptions as any), runId: pendingIdle.runId, memory: withThreadMemory(pendingIdle.streamOptions?.memory, pendingIdle.resourceId, pendingIdle.threadId), }); if ((idleQueue?.length ?? 0) > 0) { const nextRecord = state.threadRunsById.get(output.runId); if (nextRecord) { this.#watchThreadRunCompletion(state, pubsub, key, nextRecord); } } } catch (err) { const message = getErrorFromUnknown(err).message; // The queued run did start, so settle its identity on the failure the same // way the immediate-start path does: a sender retrying this logical message // must learn the turn failed rather than be told it was delivered. Only // settle the identity this run reserved. if (drainedIdentity && state.acceptedIdleMessagesByIdentity.get(drainedIdentity)?.runId === pendingIdle.runId) { state.acceptedIdleMessagesByIdentity.set(drainedIdentity, { runId: pendingIdle.runId, terminalReason: message, }); } state.threadKeysByRunId.delete(pendingIdle.runId); this.#cleanupPreparedRun(state, pendingIdle.runId); if (state.activeThreadRunIds.get(key) === pendingIdle.runId) { state.activeThreadRunIds.delete(key); } this.#publish(pubsub, key, { type: 'run-failed', runId: pendingIdle.runId, error: message, }); this.#trimRunLater(pubsub, key, pendingIdle.runId); // No completion watcher exists for a failed startup. Preserve pending-before-idle recovery here too. await this.#drainPendingSignals(state, pubsub, key, { agent: pendingIdle.agent, runId: pendingIdle.runId, resourceId: pendingIdle.resourceId, threadId: pendingIdle.threadId, streamOptions: pendingIdle.streamOptions ?? {}, }); } finally { state.startingQueuedRunIds.delete(pendingIdle.runId); } return true; } /** @internal Listen only to input actually admitted to this process's owning run. */ subscribePendingSignals(runId: string, listener: PendingSignalListener, pubsub?: PubSub): () => void { const state = this.#getState(pubsub); if (!state.threadKeysByRunId.has(runId)) return () => {}; const listeners = state.pendingSignalListenersByRunId.get(runId) ?? new Set(); listeners.add(listener); state.pendingSignalListenersByRunId.set(runId, listeners); return () => { listeners.delete(listener); if (listeners.size === 0 && state.pendingSignalListenersByRunId.get(runId) === listeners) { state.pendingSignalListenersByRunId.delete(runId); } }; } #notifyPendingSignals(state: AgentThreadRuntimeState, key: string, signal: CreatedAgentSignal): void { const runId = state.activeThreadRunIds.get(key); if ( !runId || state.threadKeysByRunId.get(runId) !== key || state.abortedRunIds.has(runId) || state.preparedRunsById.get(runId)?.abortController.signal.aborted ) { return; } const listeners = [...(state.pendingSignalListenersByRunId.get(runId) ?? [])]; if (listeners.length === 0) return; const signals = [signal.toDataPart().data]; for (const listener of listeners) listener(signals); } /** * 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' = 'pending'): CreatedAgentSignal[] { const state = this.#getState(pubsub); // Leave queued input for the completion handler to deliver in a fresh run. if (state.abortedRunIds.has(runId) || state.preparedRunsById.get(runId)?.abortController.signal.aborted) { return []; } const record = state.threadRunsById.get(runId); const key = record ? this.#threadKey(record.resourceId, record.threadId) : state.threadKeysByRunId.get(runId); if (!key) return []; const signalsByThread = scope === 'pre-run' ? state.preRunSignalsByThread : state.pendingSignalsByThread; const queue = signalsByThread.get(key); if (!queue || queue.length === 0) { return []; } signalsByThread.delete(key); return queue; } /** Resolves `'reserved'` when this call reserved the thread for `runId`. The caller then owns the reservation. */ async waitForCrossAgentThreadRun( agent: Agent, options: { memory?: AgentExecutionOptions['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' | 'reserved' | undefined> { const { threadId, resourceId } = this.#getThreadTarget(options); if (!threadId) return; // Read-only runs never persist to the thread, so they cannot corrupt // message ordering and must not serialize (or reserve): structured-output's // `useAgent` path re-enters agent.stream() on the same thread mid-run and // would deadlock behind its own parent run. const memory = options.memory; if (memory && typeof memory === 'object' && 'options' in memory && memory.options?.readOnly) return; const state = this.#getState(pubsub); const key = this.#threadKey(resourceId, threadId); const control = this.#ensureThreadControlSubscription(state, pubsub, key); control.references++; try { await control.ready; while (true) { const activeRunId = state.activeThreadRunIds.get(key); if (!activeRunId) { if (options.untilSuspended) { // A parked run the sweep dropped keeps its lease until it expires, and the // thread stays blocked until then. Nothing announces the expiry. const owner = await this.#getLeaseProvider(this.#getPubSub(pubsub)) .getLeaseOwner(key) .catch(() => undefined); if (owner && !isRetakeLeaseOwner(owner) && this.#isSweptLeaseOwner(state, threadLeaseRunId(owner))) { await this.#waitForRemoteRunToFinish(pubsub, key, threadLeaseRunId(owner)); continue; } } // Reserve the thread for this run before returning so a concurrent // stream() on the same thread waits instead of racing us during the // window between this wait and registerRun. The reservation is // superseded by registerRun (same runId) or released by the caller // on failure. if (options.runId) { state.activeThreadRunIds.set(key, options.runId); state.threadKeysByRunId.set(options.runId, key); return 'reserved'; } return; } // A caller that targets the active run (resumeStream, approval continuations) is a // continuation of that run, not a contender — never wait on ourselves. if (options.runId && options.runId === activeRunId) return; const activeRecord = state.threadRunsById.get(activeRunId); if (activeRecord) { if (!this.#isThreadBlockingRun(state, activeRecord)) { return; } if ( (options.untilSuspended || activeRecord.agent.id === agent.id) && !this.#isActivelyRunning(activeRecord) ) { // A suspended/suspending record waits on human input (resume/approval), so waiting // could block indefinitely. Same-agent callers keep the historical exemption; with // `untilSuspended`, any agent's parked run ends the wait. return 'suspended'; } await activeRecord.output._waitUntilFinished().catch(() => {}); // Awaiting a record that is already settled but still blocking (a persisted-signal // broadcast, a suspended run) does not yield the macrotask queue, so re-checking here would // spin on microtasks and starve the timers that end the wait. Force a macrotask whenever the // same run is still active after the await. if (state.activeThreadRunIds.get(key) === activeRunId) { await new Promise(resolve => setTimeout(resolve, 10)); } continue; } if (state.threadKeysByRunId.get(activeRunId) === key) { // A local run reserved the thread but has not registered yet (it is // between its own wait and registerRun). There is no record to await, // so yield briefly and re-check; the window ends when the run // registers or its caller releases the reservation. await new Promise(resolve => setTimeout(resolve, 10)); continue; } if (options.untilSuspended && this.#isSuspendedRun(state, activeRunId)) return 'suspended'; const outcome = await this.#waitForRemoteRunToFinish(pubsub, key, activeRunId, options.untilSuspended); if (options.untilSuspended && (outcome === 'suspended' || this.#isSuspendedRun(state, activeRunId))) { return 'suspended'; } } } finally { control.references--; this.#releaseUnusedThreadControlSubscription(state, key); } } /** * 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, 'agent' | 'streamOptions'>, expectedAbortSignal?: AbortSignal, ) { const state = this.#getState(pubsub); // Queued startups have their own catch path, which must restore input before draining anything else. if (state.threadRunsById.has(runId) || state.startingQueuedRunIds.has(runId)) return; const preparedRun = state.preparedRunsById.get(runId); const expectedPreparedRun = expectedAbortSignal ? this.#preparedRunsByAbortSignal.get(expectedAbortSignal) : undefined; if (expectedAbortSignal && preparedRun !== expectedPreparedRun) { if (expectedPreparedRun) this.#cleanupPreparedRun(state, runId, expectedPreparedRun); return; } const key = state.threadKeysByRunId.get(runId) ?? preparedRun?.threadKey; if (!key) { this.#cleanupPreparedRun(state, runId, expectedPreparedRun); return; } try { state.threadKeysByRunId.delete(runId); const activeRunId = state.activeThreadRunIds.get(key); const wasAborted = state.abortedRunIds.has(runId) || state.preparedRunsById.get(runId)?.abortController.signal.aborted; if (activeRunId !== runId && (activeRunId || !wasAborted)) return; state.activeThreadRunIds.delete(key); const target = failedRun ? this.#getThreadTarget(failedRun.streamOptions) : undefined; if (wasAborted && failedRun && target?.threadId) { // Failed preparation never registers a completion watcher. Recover pending input before idle work. this.#cleanupPreparedRun(state, runId, expectedPreparedRun); void this.#drainPendingSignals(state, pubsub, key, { ...failedRun, threadId: target.threadId, resourceId: target.resourceId, runId, }); } else { void this.#drainPendingIdleSignals(state, pubsub, key); } } finally { this.#cleanupPreparedRun(state, runId, expectedPreparedRun); this.#releaseUnusedThreadControlSubscription(state, key); } } async #waitForRemoteRunToFinish( pubsub: PubSub | undefined, key: string, runId: string, untilSuspended = false, ): Promise<'ended' | 'suspended'> { const resolvedPubSub = this.#getPubSub(pubsub); const { provider, isFallback } = this.#resolveLeaseProvider(resolvedPubSub); const topic = this.#threadTopic(key); let timer: ReturnType | undefined; let subscribed = false; let settled = false; // Another subscription records the park in `suspendedRunIds`, and a backend need not // run it before this one, so report a park seen here directly. let outcome: 'ended' | 'suspended' = 'ended'; let resolveWait!: () => void; const wait = new Promise(resolve => { resolveWait = resolve; }); const clearRemoteActive = (streamId?: string) => { const state = this.#getState(resolvedPubSub); if ( state.activeThreadRunIds.get(key) !== runId || (streamId && state.activeThreadStreamIds.get(key) !== streamId) ) { return; } state.activeThreadRunIds.delete(key); state.activeThreadStreamIds.delete(key); if (state.remoteThreadKeysByRunId.get(runId) === key) { state.remoteThreadKeysByRunId.delete(runId); state.remoteAgentIdsByRunId.delete(runId); state.unobservedRemoteRunIds.delete(runId); } }; const finish = () => { if (settled) return; settled = true; if (timer) clearTimeout(timer); resolveWait(); }; const checkLease = async () => { if (settled) return; if (isFallback) return; const owner = await provider.getLeaseOwner(key).catch(() => undefined); if (settled) return; if (!owner || threadLeaseRunId(owner) !== runId || isRetakeLeaseOwner(owner)) { clearRemoteActive(); finish(); return; } timer = setTimeout(() => void checkLease(), AGENT_THREAD_LEASE_TTL_MS); }; const onEvent: EventCallback = async (event, ack) => { const data = event.data as AgentThreadStreamRuntimeEvent | undefined; const isTerminal = (data?.type === 'run-completed' || data?.type === 'run-aborted' || data?.type === 'run-failed' || data?.type === 'run-discarded') && data.runId === runId; // Acknowledge every delivered event, not just the terminal one — this is a // private fan-out subscription, so anything left unacked stays pending on // the backend. The terminal ack completes before the waiter resolves so // the subsequent unsubscribe cannot race it. // A failing ack must never strand the waiter: the backend's ack deadline // will redeliver or expire the entry, but this run is still finished. try { await ack?.(); } catch {} if (isTerminal) { clearRemoteActive(data.streamId); finish(); } else if (untilSuspended && data?.type === 'run-suspended' && data.runId === runId) { outcome = 'suspended'; finish(); } }; try { await resolvedPubSub.subscribe(topic, onEvent); subscribed = true; // It may have parked before this subscription could see it. if (untilSuspended && this.#isSuspendedRun(this.#getState(resolvedPubSub), runId)) { outcome = 'suspended'; finish(); } if (!isFallback) timer = setTimeout(() => void checkLease(), AGENT_THREAD_LEASE_TTL_MS); await wait; } catch { finish(); await wait; } finally { if (timer) clearTimeout(timer); if (subscribed) await resolvedPubSub.unsubscribe(topic, onEvent).catch(() => {}); } return outcome; } async #loadThreadHistory(agent: Agent, options: AgentSubscribeToThreadOptions) { const memory = await agent.getMemory({ requestContext: options.requestContext }); if (!memory) return { messages: [], hasMore: false }; // The controller subscribes as soon as it creates a thread, before memory // may hold it; a thread that doesn't exist yet has no history. if (!(await memory.getThreadById({ threadId: options.threadId }))) return { messages: [], hasMore: false }; const perPage = typeof options.withInitialHistory === 'object' && options.withInitialHistory.perPage !== undefined ? options.withInitialHistory.perPage : DEFAULT_INITIAL_HISTORY_PER_PAGE; const result = await memory.recall({ threadId: options.threadId, resourceId: options.resourceId, perPage, page: 0, orderBy: { field: 'createdAt', direction: 'DESC' }, hideSignals: options.hideSignals, }); // DESC selects the newest page; implementations differ in the order they // return it (Memory sorts chronologically, storage-backed mocks keep DESC). const messages = [...result.messages].sort( (a, b) => new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime(), ); return { messages, hasMore: result.hasMore }; } async subscribeToThread( agent: Agent, options: AgentSubscribeToThreadOptions, pubsub?: PubSub, ): Promise> { const resolvedPubSub = this.#getPubSub(pubsub); const { provider: leaseProvider, isFallback: hasFallbackLeaseProvider } = this.#resolveLeaseProvider(resolvedPubSub); const state = this.#getState(resolvedPubSub); const key = this.#threadKey(options.resourceId, options.threadId); const topic = this.#threadTopic(key); const seenStreamIds = new Set(); const pendingRuns: AgentThreadRunRecord[] = []; const statuses: Array<{ chunk: ThreadRunStatusChunk; streamId: string }> = []; const settledRunIds = new Map(); const reportedSuspensions = new Set(); const reportedInterruptions = new Set(); const presentations: Array = []; const presentedSignalIds = new Set(); const settledSignalIds = new Set(); const waiters: Array<() => void> = []; const remoteRuns = new Map< string, { parts: unknown[]; waiters: Array<() => void>; finishWaiters: Array<() => void>; done: boolean; stream: ReadableStream; } >(); let done = false; const wake = () => { while (waiters.length) waiters.shift()?.(); }; const activeRunId = () => { const runId = state.activeThreadRunIds.get(key); if (!runId) return null; const record = state.threadRunsById.get(runId); // No record yet means either a remote run (record never lives locally) or a local run // that sendSignal has reserved but has not yet registered via registerRun. Both are // in flight from the subscriber's perspective; treat them as active. if (!record) return runId; return this.#isThreadBlockingRun(state, record) ? runId : null; }; const enqueueStatus = (runId: string, streamId: string, status: ThreadRunStatusChunk['payload']['status']) => { if (supersededStreamIds.has(streamId) || isAnsweredHalf(runId, streamId) || settledRunIds.has(runId)) return; if (status === 'suspended') { if (reportedSuspensions.has(streamId)) return; reportedSuspensions.add(streamId); } else if (status === 'interrupted') { if (reportedInterruptions.has(streamId)) return; reportedInterruptions.add(streamId); } else { settledRunIds.set(runId, streamId); } if (!options.withRunStatus) return; statuses.push({ streamId, chunk: { type: 'thread-run-status', runId, from: ChunkFrom.AGENT, payload: { status } }, }); wake(); }; const enqueuePresentation = (chunk: UserMessagePendingChunk | UserMessageCancelledChunk) => { const id = chunk.data.id; if (chunk.type === 'data-user-message-cancelled') { if (settledSignalIds.has(id)) return; settledSignalIds.add(id); } else { if (settledSignalIds.has(id) || presentedSignalIds.has(id)) return; presentedSignalIds.add(id); } presentations.push(chunk); wake(); }; const enqueueRun = (record: AgentThreadRunRecord) => { if (done || seenStreamIds.has(record.streamId)) return; seenStreamIds.add(record.streamId); pendingRuns.push(record); wake(); }; const createRemoteRun = (runId: string, streamId: string, streamSeq: number): AgentThreadRunRecord => { const remoteRun = { parts: [] as unknown[], waiters: [] as Array<() => void>, finishWaiters: [] as Array<() => void>, done: false, stream: undefined as unknown as ReadableStream, closed: false, }; remoteRun.stream = new ReadableStream({ pull(controller) { const drain = () => { if (remoteRun.closed) return; while (remoteRun.parts.length > 0) { controller.enqueue(remoteRun.parts.shift()); } if (remoteRun.done) { remoteRun.closed = true; try { controller.close(); } catch {} } }; drain(); if (!remoteRun.done && !remoteRun.closed) { remoteRun.waiters.push(drain); } }, cancel() { remoteRun.done = true; remoteRun.closed = true; remoteRun.waiters.length = 0; while (remoteRun.finishWaiters.length) remoteRun.finishWaiters.shift()?.(); }, }); remoteRuns.set(streamId, remoteRun); return { agent, output: { runId, status: 'running', fullStream: remoteRun.stream, _waitUntilFinished: async () => { if (remoteRun.done) return; await new Promise(resolve => remoteRun.finishWaiters.push(resolve)); }, } as MastraModelOutput, runId, streamId, streamSeq, lifecycle: 'running', threadId: options.threadId, resourceId: options.resourceId, streamOptions: {}, }; }; const localStreamIds = new Set(); const replayedStreamIds = new Set(); // Replayed runs whose origin no longer holds the thread lease (the run is // terminal or its process died). Their parts are buffered instead of being // yielded live: a retained backend replays every run's chunks to a fresh // subscriber, but a run that failed mid-stream never persisted a message, // so replaying it would surface a phantom partial message that hydrated // history can never reconcile. The run is only released to the subscriber // once its terminal control event proves it finished cleanly; failed, // aborted, or never-terminated (process crash) runs are dropped. const deferredRunsByStreamId = new Map>(); // Earlier segments of a run retired by a newer live segment or a later // recovery generation (the original process died or lost the run and // recovery took over). Redeliveries for them are ignored. const supersededStreamIds = new Set(); const remoteRunLeaseTimers = new Map>(); const remoteRunLeaseWatchTokens = new Map(); const remoteRunSuspensionPrompts = new Set(); let currentReader: ReadableStreamDefaultReader | null = null; let activeReaderRunId: string | null = null; let activeReaderStreamId: string | null = null; let currentRunRequestContext: RequestContext | undefined; let cancelledByAbort = false; /** Runs whose suspension or approval prompt this subscriber yielded. */ const parkedPromptRunIds = new Set(); /** Parked runs aborted after their stream ended here, awaiting a synthetic abort. */ const parkedAbortRunIds: string[] = []; // Queued streams of a run aborted before this subscriber read them. const abortedPendingStreamIds = new Set(); /** Owner agents of remote runs registered here, kept for runs whose lease check deferred them. */ const remoteAgentIdsByRegisteredRunId = new Map(); const markActiveIfLive = async (runId: string, streamId: string, local: boolean): Promise => { if (!local && !(await this.#hasLiveThreadLease(resolvedPubSub, key, runId))) return false; state.activeThreadRunIds.set(key, runId); state.activeThreadStreamIds.set(key, streamId); if (!local) { state.remoteThreadKeysByRunId.set(runId, key); const agentId = remoteAgentIdsByRegisteredRunId.get(runId); if (agentId) state.remoteAgentIdsByRunId.set(runId, agentId); // The lease check awaited; only trust the run if someone still observes the thread. if (state.threadControlSubscriptions.get(key)?.observers) state.unobservedRemoteRunIds.delete(runId); } return true; }; // A deferred run may be flushed only when its replayed chunks ended with a // clean `finish` — the origin publishes `run-completed` after the run's // messages were flushed to storage, so a clean finish implies a persisted // message backs the replay. An in-band `error` chunk, a finish with // `stepResult.reason: 'error'`, or a missing finish all mean nothing was // persisted for the run. const deferredRunEndedCleanly = (parts: unknown[]) => { let sawFinish = false; for (const part of parts) { const typed = part as { type?: string; payload?: { stepResult?: { reason?: string } } } | undefined; if (typed?.type === 'error' || typed?.type === 'abort') return false; if (typed?.type === 'finish') { if (typed.payload?.stepResult?.reason === 'error') return false; sawFinish = true; } } return sawFinish; }; const discardDeferredRun = (streamId: string) => { deferredRunsByStreamId.delete(streamId); remoteRunSuspensionPrompts.delete(streamId); remoteRunLeaseWatchTokens.delete(streamId); const timer = remoteRunLeaseTimers.get(streamId); if (timer) clearTimeout(timer); remoteRunLeaseTimers.delete(streamId); const remoteRun = remoteRuns.get(streamId); if (!remoteRun) return; remoteRun.parts.length = 0; remoteRun.done = true; while (remoteRun.waiters.length) remoteRun.waiters.shift()?.(); while (remoteRun.finishWaiters.length) remoteRun.finishWaiters.shift()?.(); remoteRuns.delete(streamId); }; const clearActiveIfCurrent = (runId: string, streamId?: string) => { if ( state.activeThreadRunIds.get(key) !== runId || (streamId && state.activeThreadStreamIds.get(key) !== streamId) ) { return; } state.activeThreadRunIds.delete(key); state.activeThreadStreamIds.delete(key); if (state.remoteThreadKeysByRunId.get(runId) === key) { state.remoteThreadKeysByRunId.delete(runId); state.remoteAgentIdsByRunId.delete(runId); state.unobservedRemoteRunIds.delete(runId); } }; const stopRemoteRunLeaseWatch = (streamId: string) => { remoteRunLeaseWatchTokens.delete(streamId); const timer = remoteRunLeaseTimers.get(streamId); if (timer) clearTimeout(timer); remoteRunLeaseTimers.delete(streamId); }; const startRemoteRunLeaseWatch = (runId: string, streamId: string) => { if (hasFallbackLeaseProvider || remoteRunLeaseWatchTokens.has(streamId)) return; const watchToken = Symbol(streamId); remoteRunLeaseWatchTokens.set(streamId, watchToken); const scheduleCheck = () => { if (remoteRunLeaseWatchTokens.get(streamId) !== watchToken) return; remoteRunLeaseTimers.set( streamId, setTimeout(() => void checkLease(), AGENT_THREAD_LEASE_TTL_MS), ); }; const checkLease = async () => { remoteRunLeaseTimers.delete(streamId); const remoteRun = remoteRuns.get(streamId); if (done || remoteRunLeaseWatchTokens.get(streamId) !== watchToken || !remoteRun || remoteRun.done) return; let owner: string | undefined; try { owner = await leaseProvider.getLeaseOwner(key); } catch { if ( done || remoteRunLeaseWatchTokens.get(streamId) !== watchToken || remoteRuns.get(streamId) !== remoteRun || remoteRun.done ) { return; } scheduleCheck(); return; } if ( done || remoteRunLeaseWatchTokens.get(streamId) !== watchToken || remoteRuns.get(streamId) !== remoteRun || remoteRun.done ) { return; } if (owner && threadLeaseRunId(owner) === runId && !isRetakeLeaseOwner(owner)) { scheduleCheck(); return; } // The lease alone cannot tell a parked run from a dead producer: a run // suspended on approval releases its lease, and the prompt that would // tell us so may never have reached this subscriber. A stored suspended // row settles it; anything else keeps the prompt heuristic, since a // running regular-loop run has no row either. const storedStatus = await this.#readStoredRunStatus(agent, runId); if ( done || remoteRunLeaseWatchTokens.get(streamId) !== watchToken || remoteRuns.get(streamId) !== remoteRun || remoteRun.done ) { return; } stopRemoteRunLeaseWatch(streamId); const promptSeen = remoteRunSuspensionPrompts.delete(streamId); const parked = storedStatus === 'suspended' || storedStatus === 'waiting' || promptSeen; if (parked) { const deferredRecord = deferredRunsByStreamId.get(streamId); if (deferredRecord) { deferredRunsByStreamId.delete(streamId); enqueueRun(deferredRecord); } suspendedStreamIdsByRunId.set(runId, streamId); noteRunHalf(runId); state.suspendedRunIds.add(runId); const record = state.threadRunsByStreamId.get(streamId) ?? state.threadRunsById.get(runId); if (record) record.lifecycle = 'suspended'; } else { clearActiveIfCurrent(runId, streamId); remoteRun.parts.push({ type: 'error', payload: { error: new AgentThreadLeaseLostError(runId) }, }); } remoteRun.done = true; while (remoteRun.waiters.length) remoteRun.waiters.shift()?.(); while (remoteRun.finishWaiters.length) remoteRun.finishWaiters.shift()?.(); remoteRuns.delete(streamId); seenStreamIds.delete(streamId); if (!parked) { await this.#drainPendingIdleSignals(state, resolvedPubSub, key, runId); } wake(); }; scheduleCheck(); }; const resolveTerminalEventStreamId = ( runId: string, type: 'run-failed' | 'run-completed' | 'run-aborted' | 'run-suspended', streamId?: string, ) => { if (streamId) { terminalEventStreamIds.add(streamId); return streamId; } const registered = registeredSeqsByRunId.get(runId); let oldestUnmatched: { streamId: string; streamSeq: number } | undefined; let newestTracked: { streamId: string; streamSeq: number } | undefined; for (const [registeredStreamId, streamSeq] of registered ?? []) { if (terminalEventStreamIds.has(registeredStreamId)) continue; if (oldestUnmatched === undefined || streamSeq < oldestUnmatched.streamSeq) { oldestUnmatched = { streamId: registeredStreamId, streamSeq }; } const tracked = remoteRuns.has(registeredStreamId) || deferredRunsByStreamId.has(registeredStreamId) || remoteRunLeaseWatchTokens.has(registeredStreamId); if (tracked && (newestTracked === undefined || streamSeq > newestTracked.streamSeq)) { newestTracked = { streamId: registeredStreamId, streamSeq }; } } const resolvedStreamId = (type === 'run-suspended' ? oldestUnmatched?.streamId : newestTracked?.streamId) ?? oldestUnmatched?.streamId ?? runId; terminalEventStreamIds.add(resolvedStreamId); return resolvedStreamId; }; const discardStream = (runId: string, streamId: string) => { stopRemoteRunLeaseWatch(streamId); remoteRunSuspensionPrompts.delete(streamId); clearActiveIfCurrent(runId, streamId); localStreamIds.delete(streamId); replayedStreamIds.delete(streamId); for (let index = pendingRuns.length - 1; index >= 0; index--) { if (pendingRuns[index]?.streamId === streamId) pendingRuns.splice(index, 1); } discardDeferredRun(streamId); const remoteRun = remoteRuns.get(streamId); if (remoteRun) { remoteRun.done = true; while (remoteRun.waiters.length) remoteRun.waiters.shift()?.(); while (remoteRun.finishWaiters.length) remoteRun.finishWaiters.shift()?.(); remoteRuns.delete(streamId); } seenStreamIds.delete(streamId); if (activeReaderRunId === runId && activeReaderStreamId === streamId && currentReader) { try { void currentReader.cancel(); } catch {} } wake(); }; // A process recovering a durable run re-registers it under a later claim // generation. Streams of the run under an earlier generation belong to a // superseded execution: the original process may have died mid-stream (its // stream never terminates) or may still be relaying output it no longer owns. // A resume also claims a later generation, but its suspended half ended // cleanly and stays readable, so only a recovery registration supersedes. // A superseded stream's own terminal event (its abort, failure, or // completion once it notices the loss) must not end the recovered stream. const supersededBelowByRunId = new Map(); const generationsByStreamId = new Map(); const isSuperseded = (runId: string, generation: number | undefined) => generation !== undefined && generation < (supersededBelowByRunId.get(runId) ?? -Infinity); const noteGeneration = ( runId: string, streamId: string, generation: number | undefined, supersedes: boolean | undefined, ) => { if (generation === undefined) return; generationsByStreamId.set(streamId, { runId, generation }); if (!supersedes || generation <= (supersededBelowByRunId.get(runId) ?? -Infinity)) return; supersededBelowByRunId.set(runId, generation); for (const [olderStreamId, older] of generationsByStreamId) { if (older.runId !== runId || older.generation >= generation) continue; generationsByStreamId.delete(olderStreamId); supersededStreamIds.add(olderStreamId); discardStream(runId, olderStreamId); } }; const handleEvent = async (event: Parameters[0]) => { if (done) return; const data = event.data as AgentThreadStreamRuntimeEvent | undefined; if (!data) return; if (data.type === 'user-message-presentation') { enqueuePresentation(data.chunk); return; } if (data.type === 'user-message-delivered') { settledSignalIds.add(data.signalId); return; } if ('streamId' in data && data.streamId !== undefined && supersededStreamIds.has(data.streamId)) return; if ( (data.type === 'run-completed' || data.type === 'run-aborted') && data.superseded && data.streamId !== undefined ) { supersededStreamIds.add(data.streamId); discardStream(data.runId, data.streamId); return; } if (data.type === 'run-registered') { if (isSuperseded(data.runId, data.generation)) return; noteGeneration(data.runId, data.streamId, data.generation, data.supersedes); const registrationRedelivery = handledRegistrationEventIds.has(event.id); handledRegistrationEventIds.add(event.id); const firstRegistration = !registeredSeqsByRunId.get(data.runId)?.has(data.streamId); noteRunHalf(data.runId, { streamId: data.streamId, streamSeq: data.streamSeq }); // A redelivered registration for a stream that already ended must not // restore the finished run as the thread's active run. if (registrationRedelivery && terminalEventStreamIds.has(data.streamId)) { discardDeferredRun(data.streamId); wake(); return; } const localRecord = state.threadRunsByStreamId.get(data.streamId); if (localRecord) { localStreamIds.add(data.streamId); } else { replayedStreamIds.add(data.streamId); } const local = Boolean(localRecord); // This instance's own registration of a run its TTL sweep evicted is a // redelivery of the dead execution, however held its kept lease looks. // Restoring it as active would route sends to a run nothing consumes. // Another instance resuming the run registers under its own source id. const registeredAt = event.createdAt === undefined ? undefined : new Date(event.createdAt).getTime(); if (!localRecord && this.#isSweptLeaseOwner(state, data.runId)) { if (data.sourceId === this.#getSourceId()) { discardDeferredRun(data.streamId); wake(); return; } // Only a registration published after the sweep proves a live resume elsewhere; // an older or undated one may be a replay of an execution that has since ended. const sweptAt = state.sweptLeasedRunIds.get(data.runId)!; if (registeredAt !== undefined && registeredAt > sweptAt) state.sweptLeasedRunIds.delete(data.runId); } // A history subscriber reads registrations published before its // history load as backlog: only a held lease makes those runs live. const backlog = historyReadAt !== undefined && registeredAt !== undefined && registeredAt <= historyReadAt; // A registration published by this very runtime instance is always a // live delivery — a restarted process gets a fresh source id, so a // matching id can never be a stale replay of a dead run. This also // covers runs that complete before the event is delivered in-process // (record cleaned up, lease released) where deferral would strand the // run because its terminal event was already processed. // A finished local record must not displace a different active run. // Without a record (already cleaned up), a redelivered registration // must not displace a different local run that still blocks the thread. const currentActiveRunId = state.activeThreadRunIds.get(key); const currentActiveRecord = currentActiveRunId ? state.threadRunsById.get(currentActiveRunId) : undefined; const displacesActiveRun = currentActiveRunId !== undefined && currentActiveRunId !== data.runId && (localRecord !== undefined || (currentActiveRecord !== undefined && this.#isThreadBlockingRun(state, currentActiveRecord))); const sameSourceLive = !backlog && !displacesActiveRun && data.sourceId !== undefined && data.sourceId === this.#getSourceId(); // A nonblocking local record is never live via the lease: fallback lease // providers report every run as leased. const live = localRecord !== undefined ? this.#isThreadBlockingRun(state, localRecord) || sameSourceLive : !displacesActiveRun && (sameSourceLive || (await this.#hasLiveThreadLease(resolvedPubSub, key, data.runId))); if (!local && data.agentId) remoteAgentIdsByRegisteredRunId.set(data.runId, data.agentId); if (live) { state.activeThreadRunIds.set(key, data.runId); state.activeThreadStreamIds.set(key, data.streamId); if (!local) { state.remoteThreadKeysByRunId.set(data.runId, key); if (state.threadControlSubscriptions.get(key)?.observers) state.unobservedRemoteRunIds.delete(data.runId); if (data.agentId) state.remoteAgentIdsByRunId.set(data.runId, data.agentId); } // A live new segment of a run supersedes any earlier segment of the // same run that never saw a terminal event: that segment's process // died (e.g. recovery took the run over), and the lease now held // under the same runId would otherwise keep it looking alive and // queue the new segment behind it forever. Order by arrival, not // streamSeq: sequences restart at 1 in a recovering process, and // redeliveries of a segment never retire others. for (const staleStreamId of firstRegistration ? (registeredSeqsByRunId.get(data.runId)?.keys() ?? []) : []) { if (staleStreamId === data.streamId || terminalEventStreamIds.has(staleStreamId)) continue; const staleRun = remoteRuns.get(staleStreamId); if (!staleRun || staleRun.done) continue; supersededStreamIds.add(staleStreamId); if (deferredRunsByStreamId.has(staleStreamId)) { discardDeferredRun(staleStreamId); continue; } stopRemoteRunLeaseWatch(staleStreamId); remoteRunSuspensionPrompts.delete(staleStreamId); staleRun.done = true; while (staleRun.waiters.length) staleRun.waiters.shift()?.(); while (staleRun.finishWaiters.length) staleRun.finishWaiters.shift()?.(); remoteRuns.delete(staleStreamId); } } // Reuse a proxy that a stream-part-first delivery already created for // this stream — creating a fresh record here would orphan its // buffered parts. const record = localRecord ?? deferredRunsByStreamId.get(data.streamId) ?? createRemoteRun(data.runId, data.streamId, data.streamSeq); if (live) { deferredRunsByStreamId.delete(data.streamId); enqueueRun(record); } else { // Replayed run from a retained backend with no live owner: buffer it // until its terminal event proves it completed cleanly. deferredRunsByStreamId.set(data.streamId, record); } wake(); return; } if (data.type === 'stream-part') { if (supersededStreamIds.has(data.streamId)) return; if ( data.sourceId === this.#id && (localStreamIds.has(data.streamId) || !replayedStreamIds.has(data.streamId)) ) { return; } if (isSuperseded(data.runId, data.generation)) return; noteGeneration(data.runId, data.streamId, data.generation, false); if ( deferredRunsByStreamId.has(data.streamId) || state.activeThreadRunIds.get(key) !== data.runId || state.activeThreadStreamIds.get(key) !== data.streamId ) { // A run deferred because its lease read failed or timed out turns out to be live: stream it now // instead of buffering every part until its terminal event. The deferral is per subscriber, so // check it even when another subscriber in this process already marked the run active. const live = await markActiveIfLive(data.runId, data.streamId, false); const deferredRecord = deferredRunsByStreamId.get(data.streamId); if (live && deferredRecord) { deferredRunsByStreamId.delete(data.streamId); enqueueRun(deferredRecord); } } let remoteRun = remoteRuns.get(data.streamId); if (!remoteRun) { // A subscriber can attach after another runtime already broadcast run-registered. // Treat the first stream-part on this thread topic as proof of the remote run and // create the local proxy stream from that point forward. const record = createRemoteRun(data.runId, data.streamId, state.streamSeqByRunId.get(data.runId) ?? 1); if (await this.#hasLiveThreadLease(resolvedPubSub, key, data.runId)) { enqueueRun(record); } else { deferredRunsByStreamId.set(data.streamId, record); } remoteRun = remoteRuns.get(data.streamId); if (!remoteRun) return; } stampPartProducedAt(data.part, data.producedAt ?? new Date(event.createdAt ?? Date.now()).getTime()); const typedPart = data.part as { type?: string } | undefined; if (typedPart?.type === 'tool-call-approval' || typedPart?.type === 'tool-call-suspended') { remoteRunSuspensionPrompts.add(data.streamId); } else { remoteRunSuspensionPrompts.delete(data.streamId); } remoteRun.parts.push(data.part); while (remoteRun.waiters.length) remoteRun.waiters.shift()?.(); return; } if (data.type === 'run-failed') { const eventStreamId = resolveTerminalEventStreamId(data.runId, data.type, data.streamId); stopRemoteRunLeaseWatch(eventStreamId); remoteRunSuspensionPrompts.delete(eventStreamId); clearActiveIfCurrent(data.runId, data.streamId); if (deferredRunsByStreamId.has(eventStreamId)) { // Replayed failure of a run that never persisted anything — drop it. discardDeferredRun(eventStreamId); seenStreamIds.delete(eventStreamId); await this.#drainPendingIdleSignals(state, resolvedPubSub, key, data.runId); enqueueStatus(data.runId, eventStreamId, 'failed'); wake(); return; } let errorRun: AgentThreadRunRecord | undefined; let remoteRun = remoteRuns.get(eventStreamId); if (!remoteRun) { errorRun = createRemoteRun(data.runId, eventStreamId, state.streamSeqByRunId.get(data.runId) ?? 1); remoteRun = remoteRuns.get(eventStreamId); } if (remoteRun) { remoteRun.parts.push({ type: 'error', payload: { error: new Error(data.error) } }); remoteRun.done = true; while (remoteRun.waiters.length) remoteRun.waiters.shift()?.(); while (remoteRun.finishWaiters.length) remoteRun.finishWaiters.shift()?.(); remoteRuns.delete(eventStreamId); seenStreamIds.delete(eventStreamId); } if (errorRun) enqueueRun(errorRun); await this.#drainPendingIdleSignals(state, resolvedPubSub, key, data.runId); enqueueStatus(data.runId, eventStreamId, 'failed'); wake(); return; } if (data.type === 'run-discarded') { discardStream(data.runId, data.streamId); // The control-channel drain ran before discardStream released the run, so it found the thread busy. await this.#drainPendingIdleSignals(state, resolvedPubSub, key, data.runId); return; } if (data.type === 'run-completed' || data.type === 'run-aborted' || data.type === 'run-suspended') { const eventStreamId = resolveTerminalEventStreamId(data.runId, data.type, data.streamId); stopRemoteRunLeaseWatch(eventStreamId); remoteRunSuspensionPrompts.delete(eventStreamId); const deferredRecord = deferredRunsByStreamId.get(eventStreamId); if (options.withInitialHistory && data.type === 'run-completed' && data.status === 'success') { // Judge by publish time, not delivery time: backends such as Redis // Streams deliver the backlog after subscribe() returns. const completedAt = event.createdAt === undefined ? undefined : new Date(event.createdAt).getTime(); if (historyReadAt === undefined || (completedAt !== undefined && completedAt <= historyReadAt)) { // Finished successfully before history was read, so storage holds all of it. storedStreamIds.add(eventStreamId); } } // A replayed run-suspended can describe a run that has since resumed and // finished. Both loops persist the suspended row before publishing // run-suspended and delete it when the run finishes, so a readable store // without that row (or with a terminal one) means the run is no longer parked. // A missing row only counts for backlog suspensions (deferred, or // published before this subscription): a live suspension whose // persistence policy skips suspended rows is still parked. const storedStatus = data.type === 'run-suspended' ? await this.#readStoredRunStatus(agent, data.runId) : undefined; const suspendedAt = event.createdAt === undefined ? undefined : new Date(event.createdAt).getTime(); const historicalSuspension = deferredRecord !== undefined || (suspendedAt !== undefined && suspendedAt < subscribedAt); const suspendedRunEnded = (storedStatus === 'missing' && historicalSuspension) || (storedStatus !== undefined && storedStatus !== 'missing' && TERMINAL_STORED_RUN_STATUSES.has(storedStatus)); // Its prompt was answered; keep the history but drop the stale prompt. if (suspendedRunEnded) answeredStreamIds.add(eventStreamId); if (deferredRecord) { deferredRunsByStreamId.delete(eventStreamId); const bufferedRun = remoteRuns.get(eventStreamId); // Prefer the origin's explicit `persisted` verdict; fall back to the // clean-finish heuristic for events published by older origins. const flush = data.type === 'run-suspended' || (data.type === 'run-completed' && (data.persisted ?? (bufferedRun !== undefined && deferredRunEndedCleanly(bufferedRun.parts)))); if (storedStreamIds.has(eventStreamId)) { discardDeferredRun(eventStreamId); } else if (flush) { enqueueRun(deferredRecord); } else { // Unpersisted terminal run (mid-stream failure surfaces as // `run-completed` on the wire, aborts as `run-aborted`): no stored // message backs its partial content, so it must not replay. discardDeferredRun(eventStreamId); } } if (data.type === 'run-suspended' && !suspendedRunEnded) { suspendedStreamIdsByRunId.set(data.runId, eventStreamId); noteRunHalf(data.runId); state.suspendedRunIds.add(data.runId); const record = state.threadRunsByStreamId.get(eventStreamId) ?? state.threadRunsById.get(data.runId); if (record) record.lifecycle = 'suspended'; } else { clearActiveIfCurrent(data.runId, data.streamId); } if (data.type !== 'run-suspended' || suspendedRunEnded) { this.#clearSuspendedRun(state, data.runId); } const remoteRun = remoteRuns.get(eventStreamId); if (remoteRun) { remoteRun.done = true; while (remoteRun.waiters.length) remoteRun.waiters.shift()?.(); while (remoteRun.finishWaiters.length) remoteRun.finishWaiters.shift()?.(); remoteRuns.delete(eventStreamId); seenStreamIds.delete(eventStreamId); } // When a run is aborted, cancel the current subscriber stream reader so // the generator's inner loop unblocks and can yield the synthetic abort. if ( data.type === 'run-aborted' && activeReaderRunId === data.runId && (data.streamId === undefined || activeReaderStreamId === data.streamId) && currentReader ) { cancelledByAbort = true; try { void currentReader.cancel(); } catch {} } else if (data.type === 'run-aborted' && parkedPromptRunIds.has(data.runId)) { const abortedPending = pendingRuns.filter( pending => pending.runId === data.runId && (data.streamId === undefined || pending.streamId === data.streamId), ); if (abortedPending.length > 0) { // Not read yet: yield the abort once that stream ends without one. for (const pending of abortedPending) abortedPendingStreamIds.add(pending.streamId); } else if (activeReaderRunId !== data.runId) { // A run whose prompt this subscriber surfaced, aborted while parked: // its stream already ended here, so yield the abort without a reader. parkedAbortRunIds.push(data.runId); } } if (data.type !== 'run-suspended') parkedPromptRunIds.delete(data.runId); // An abort is not completion: the owner still needs to finish and drain // pending signals before idle messages can start. if (data.type === 'run-completed') { await this.#drainPendingIdleSignals(state, resolvedPubSub, key, data.runId); } if (data.type !== 'run-suspended' || !suspendedRunEnded) { const status = data.type === 'run-aborted' ? 'aborted' : data.type === 'run-suspended' || data.status === 'suspended' ? 'suspended' : data.status === 'canceled' ? 'aborted' : data.status === 'interrupted' ? 'interrupted' : data.status === 'success' || (data.status === undefined && data.persisted !== false) ? 'success' : 'failed'; enqueueStatus(data.runId, eventStreamId, status); } wake(); } }; let historyReadAt: number | undefined; /** Events published before this subscription started are backlog. */ const subscribedAt = Date.now(); const storedStreamIds = new Set(); const suspendedStreamIdsByRunId = new Map(); /** streamSeq of each registered stream, per run. */ const registeredSeqsByRunId = new Map>(); /** Registered streams already matched to an explicit or legacy terminal event. */ const terminalEventStreamIds = new Set(); /** Terminal deliveries whose lifecycle side effects completed successfully. */ const handledTerminalEventIds = new Set(); /** Registration deliveries already handled by this subscription. */ const handledRegistrationEventIds = new Set(); /** Suspended halves whose run has since resumed: their prompts are already answered. */ const answeredStreamIds = new Set(); // A run registering a later stream means its suspension was answered. A // lagging publisher can deliver that registration before the suspended // half's `run-suspended`, so check whichever arrives second. Only a later // stream answers: a resumed half that suspends again is still pending. function noteRunHalf(runId: string, registration?: { streamId: string; streamSeq: number }) { const registered = registeredSeqsByRunId.get(runId) ?? new Map(); if (registration) { registered.set(registration.streamId, registration.streamSeq); const settledStreamId = settledRunIds.get(runId); if (settledStreamId && settledStreamId !== registration.streamId) settledRunIds.delete(runId); } registeredSeqsByRunId.set(runId, registered); const suspendedStreamId = suspendedStreamIdsByRunId.get(runId); if (suspendedStreamId === undefined) return; const suspendedSeq = registered.get(suspendedStreamId); for (const [streamId, streamSeq] of registered) { if (streamId === suspendedStreamId) continue; if (suspendedSeq === undefined || streamSeq > suspendedSeq) answeredStreamIds.add(suspendedStreamId); } } // The resumed half's registration can still be queued behind the suspended // half's parts; a local run already records which stream it moved to. const isAnsweredHalf = (runId: string, streamId: string) => { if (answeredStreamIds.has(streamId)) return true; // A run registers a later stream only after this one ended, so its // prompts were answered even if `run-suspended` hasn't arrived yet. const registered = registeredSeqsByRunId.get(runId); const seq = registered?.get(streamId); if (seq !== undefined && [...registered!.values()].some(other => other > seq)) return true; const current = state.threadRunsById.get(runId); return current !== undefined && current.streamId !== streamId && current.lifecycle !== 'suspended'; }; let eventTail = Promise.resolve(); const onEvent: EventCallback = (event, ack) => { // Events are processed strictly in publish order, but each delivery is // acknowledged on its own outcome. Every delivered event is acked once it // has been inspected — including events this subscriber filters out — // because a persistent backend (Redis consumer groups) keeps unacked // deliveries pending for the lifetime of the subscription. const data = event.data as AgentThreadStreamRuntimeEvent | undefined; const terminal = data?.type === 'run-failed' || data?.type === 'run-completed' || data?.type === 'run-aborted' || data?.type === 'run-suspended'; const processed = eventTail.then(async () => { if (terminal && handledTerminalEventIds.has(event.id)) return; await handleEvent(event); if (terminal) handledTerminalEventIds.add(event.id); }); // The tail must survive a failed event so later events still run. eventTail = processed.then( () => {}, () => {}, ); // Returned rejection lets the backend nack and redeliver. return processed.then(() => ack?.()); }; const control = this.#ensureThreadControlSubscription(state, resolvedPubSub, key); control.references++; control.observers++; try { await control.ready; await resolvedPubSub.subscribe(topic, onEvent); } catch (error) { control.references--; control.observers--; this.#releaseUnusedThreadControlSubscription(state, key); throw error; } // Subscribe first, then load: parts published while history loads are held // by the subscription and filtered against it, so nothing falls in the gap. let historyChunk: ThreadHistoryChunk | undefined; let historyFilter: ((part: unknown, runId: string) => boolean) | undefined; if (options.withInitialHistory) { // Events already processed were published before this read, so any run // they completed is in storage. await eventTail; historyReadAt = Date.now(); try { const history = await this.#loadThreadHistory(agent, options); // Only activeRunId depends on the lease backend, so it must not decide whether the subscription opens. // All reads share one renewal interval; a stalled or failing backend falls back to this process's view. const unreachable = Symbol('unreachable'); let giveUp: ReturnType | undefined; let expired = false; const deadline = new Promise( resolve => (giveUp = setTimeout(() => { expired = true; resolve(unreachable); }, AGENT_THREAD_LEASE_RENEW_INTERVAL_MS)), ); let leaseError: unknown; const readOwner = async (): Promise => { if (hasFallbackLeaseProvider) return activeRunId(); if (this.#isLeaseReadStalled(leaseProvider, key)) return unreachable; const read = leaseProvider.getLeaseOwner(key); let settled = false; let reply: { owner: string | null | undefined } | undefined; void read.then( owner => { settled = true; reply = { owner }; }, () => (settled = true), ); const owner = await Promise.race([ read.catch((error): typeof unreachable => { leaseError = error; return unreachable; }), deadline.then((timedOut): typeof unreachable => { if (!settled) this.#noteStalledLeaseRead(leaseProvider, key, read); return timedOut; }), ]); // A read that answered by the time the deadline fired still wins, even when the deadline settles the race. return owner === unreachable && reply ? reply.owner : owner; }; let leaseOwner: string | null | undefined | typeof unreachable; let localOwner = false; try { leaseOwner = await readOwner(); for (let attempt = 0; attempt < 3 && leaseOwner !== unreachable; attempt++) { const tail = eventTail; await tail; // The deadline passed while earlier events were processed: keep the last answer rather than // issue a read that would get no time and be noted as a stall on a healthy backend. if (expired) break; const nextOwner = await readOwner(); // A re-read that got no answer in the time left keeps the answer the backend already gave. if (nextOwner === unreachable) break; const stable = nextOwner === leaseOwner && tail === eventTail; leaseOwner = nextOwner; if (stable) break; } } finally { clearTimeout(giveUp); } if (leaseOwner === unreachable) { agent.__getLogger?.()?.warn('Could not read the thread lease owner for initial history; using local state', { threadId: options.threadId, resourceId: options.resourceId, error: leaseError ?? `no answer within ${AGENT_THREAD_LEASE_RENEW_INTERVAL_MS}ms`, }); leaseOwner = activeRunId(); localOwner = true; } // Only an owner read from the lease backend is encoded; a local run id round-trips unchanged. const ownerRunId = leaseOwner && !hasFallbackLeaseProvider && !localOwner ? threadLeaseRunId(leaseOwner) : leaseOwner; const snapshotRunId = ownerRunId && !settledRunIds.has(ownerRunId) ? ownerRunId : null; historyChunk = { type: 'thread-history', runId: '', from: ChunkFrom.AGENT, payload: { ...history, activeRunId: snapshotRunId }, }; historyFilter = createThreadHistoryFilter(history.messages); for (const message of history.messages) settledSignalIds.add(message.id); } catch (error) { control.references--; control.observers--; this.#releaseUnusedThreadControlSubscription(state, key); await resolvedPubSub.unsubscribe(topic, onEvent).catch(() => {}); throw error; } } const currentRunId = activeRunId(); // Pending input is not in saved history or a finished-step stream buffer. for (const queue of [state.preRunSignalsByThread.get(key), state.pendingSignalsByThread.get(key)]) { for (const signal of queue ?? []) { const chunk = this.#pendingUserMessageChunk(currentRunId ?? '', signal, 'pending'); if (chunk) enqueuePresentation(chunk); } } for (const pending of state.pendingIdleSignalsByThread.get(key) ?? []) { const chunk = this.#pendingUserMessageChunk(currentRunId ?? pending.runId, pending.signal, 'queued'); if (chunk) enqueuePresentation(chunk); } // An aborted run stays active until it terminalizes, but its lifecycle already // ended for earlier subscribers. Seeding it here would replay that run. const currentRecord = currentRunId && !state.abortedRunIds.has(currentRunId) ? state.threadRunsById.get(currentRunId) : undefined; if (currentRecord) { localStreamIds.add(currentRecord.streamId); enqueueRun(currentRecord); } const unsubscribe = () => { if (done) return; done = true; for (const timer of remoteRunLeaseTimers.values()) clearTimeout(timer); remoteRunLeaseTimers.clear(); remoteRunLeaseWatchTokens.clear(); remoteRunSuspensionPrompts.clear(); control.references--; control.observers--; // With no observer left, remote terminal events go unseen: stop trusting // these runs as signal targets until a live registration confirms them. if (!control.observers) { for (const [runId, runKey] of state.remoteThreadKeysByRunId) { if (runKey === key) state.unobservedRemoteRunIds.add(runId); } } this.#releaseUnusedThreadControlSubscription(state, key); void resolvedPubSub.unsubscribe(topic, onEvent).catch(() => {}); // Cancel current reader so the generator's inner loop breaks. if (currentReader) { try { void currentReader.cancel(); } catch {} } wake(); }; function* takePresentations() { while (presentations.length) { const chunk = presentations.shift()!; if (chunk.type === 'data-user-message-pending' && settledSignalIds.has(chunk.data.id)) continue; if (!isSignalChunkExcluded(chunk, options.hideSignals)) yield chunk; } } return { activeRunId, __getCurrentRunRequestContext: () => { const record = activeReaderStreamId ? state.threadRunsByStreamId.get(activeReaderStreamId) : undefined; return record ? record.streamOptions.requestContext : currentRunRequestContext; }, abort: abortOptions => this.abortThread({ ...options, ...abortOptions }, resolvedPubSub), unsubscribe, stream: (async function* () { try { if (historyChunk) yield historyChunk; while (!done || pendingRuns.length > 0 || presentations.length > 0 || statuses.length > 0) { for (let i = 0; i < statuses.length;) { const status = statuses[i]!; if (pendingRuns.some(run => run.streamId === status.streamId)) { i++; continue; } statuses.splice(i, 1); if (supersededStreamIds.has(status.streamId)) continue; if (status.chunk.payload.status === 'suspended' && isAnsweredHalf(status.chunk.runId, status.streamId)) continue; yield status.chunk; } yield* takePresentations(); const parkedAbortRunId = parkedAbortRunIds.shift(); if (parkedAbortRunId !== undefined) { yield { type: 'abort', runId: parkedAbortRunId } as any; continue; } if (pendingRuns.length === 0) { // Presentation draining can yield while a terminal event wakes us. if (statuses.length > 0 || presentations.length > 0 || done) continue; await new Promise(resolve => waiters.push(resolve)); continue; } const run = pendingRuns.shift()!; const displaced = state.displacedRecords.get(run); if (isSuperseded(run.runId, run.generation) || displaced) { abortedPendingStreamIds.delete(run.streamId); if (displaced === 'aborted' && !isSuperseded(run.runId, run.generation)) { yield { type: 'abort', runId: run.runId } as any; } continue; } // A local run can be read before its `run-registered` event arrives. noteGeneration(run.runId, run.streamId, run.generation, run.supersedes); noteRunHalf(run.runId, { streamId: run.streamId, streamSeq: run.streamSeq }); // Local registered runs expose createSubscriberStream, while remote runs are // already per-subscription streams. Do not silently skip locked streams here: // a locked fallback stream means a caller is sharing a non-multicast stream. const subscriberStream = run.createSubscriberStream?.() ?? run.output.fullStream; const reader = subscriberStream.getReader(); currentReader = reader as ReadableStreamDefaultReader; activeReaderRunId = run.runId; activeReaderStreamId = run.streamId; const stopReading = { streamId: run.streamId, stop: () => { try { void reader.cancel(); } catch {} }, }; const readers = state.runStreamReaders.get(run.runId) ?? new Set(); readers.add(stopReading); state.runStreamReaders.set(run.runId, readers); currentRunRequestContext = run.streamOptions.requestContext; if (remoteRuns.has(run.streamId)) startRemoteRunLeaseWatch(run.runId, run.streamId); let readerReleased = false; // A `start` covered by stored history is held back and sent before the // first live part of this stream, so a mid-run joiner sees the run begin. let heldStart: unknown; let pendingRead: ReturnType | undefined; try { while (true) { yield* takePresentations(); if (done) break; pendingRead ??= reader.read(); let notify!: () => void; const awakened = new Promise(resolve => { notify = resolve; waiters.push(notify); }); const next = await Promise.race([ pendingRead.then(value => ({ kind: 'part' as const, value })), awakened.then(() => ({ kind: 'wake' as const })), ]); const waiterIndex = waiters.indexOf(notify); if (waiterIndex !== -1) waiters.splice(waiterIndex, 1); if (next.kind === 'wake') continue; pendingRead = undefined; const { value: part, done: streamDone } = next.value; const deliveredSignalId = userMessageSignalId(part); if (deliveredSignalId) settledSignalIds.add(deliveredSignalId); if (streamDone) { break; } const typedPart = part as any; const partWithRunId = typedPart && typeof typedPart === 'object' && !('runId' in typedPart) ? { ...typedPart, runId: run.runId } : typedPart; if ( !isSignalChunkExcluded(partWithRunId, options.hideSignals) && !storedStreamIds.has(run.streamId) && !( (typedPart?.type === 'tool-call-approval' || typedPart?.type === 'tool-call-suspended') && isAnsweredHalf(run.runId, run.streamId) ) && (!historyFilter || historyFilter(typedPart, run.runId)) ) { const isPrompt = typedPart?.type === 'tool-call-approval' || typedPart?.type === 'tool-call-suspended'; if (heldStart !== undefined && typedPart?.type !== 'start' && !isPrompt) { yield heldStart; } if (!isPrompt) heldStart = undefined; else parkedPromptRunIds.add(run.runId); yield partWithRunId; } else if (typedPart?.type === 'start' && historyFilter && !storedStreamIds.has(run.streamId)) { heldStart = partWithRunId; } if (done) break; const finishReason = typedPart.finishReason ?? typedPart.payload?.finishReason; const terminalBoundary = typedPart.type === 'error' || typedPart.type === 'abort' || typedPart.type === 'tripwire' || (typedPart.type === 'finish' && finishReason !== 'tool-calls'); if (typedPart.type === 'error' || typedPart.type === 'abort' || typedPart.type === 'tripwire') { parkedPromptRunIds.delete(run.runId); } if (terminalBoundary) { // After a final terminal chunk, drain any non-visible trailing // data in the background to prevent upstream backpressure while // allowing the generator to immediately serve subsequent runs. readerReleased = true; void (async () => { try { while (true) { const { done: d } = await reader.read(); if (d) break; } } catch {} reader.releaseLock(); })(); break; } } // If the stream closed because we cancelled the reader after a // run-aborted event, yield a synthetic abort so subscribers // finalize the run. const abortedWhilePending = abortedPendingStreamIds.delete(run.streamId); if (!readerReleased && !done && (cancelledByAbort || abortedWhilePending)) { yield { type: 'abort', runId: run.runId } as any; cancelledByAbort = false; } } finally { readers.delete(stopReading); if (readers.size === 0 && state.runStreamReaders.get(run.runId) === readers) { state.runStreamReaders.delete(run.runId); } stopRemoteRunLeaseWatch(run.streamId); currentReader = null; activeReaderRunId = null; activeReaderStreamId = null; currentRunRequestContext = undefined; if (!readerReleased) { reader.releaseLock(); } } } } finally { unsubscribe(); } })(), }; } sendMessage( agent: Agent, message: AgentMessageInput, target: SendAgentMessageOptions, pubsub?: PubSub, ): SendAgentMessageResult { return this.sendSignal(agent, this.#createMessageSignalInput(message), target, pubsub); } subscribeThreadEvents( agent: Agent, scope: SubscribeAgentThreadEventsOptions, listener: AgentThreadEventListener, pubsub?: PubSub, ): () => void { const state = this.#getState(pubsub); const registration: ThreadEventListenerRegistration = { ...scope, agent, listener, lastCount: 0 }; const count = this.#queuedMessageCount(state, registration); registration.lastCount = count; state.threadEventListeners.add(registration); try { listener({ type: 'queue-count-changed', count }); } catch {} let subscribed = true; return () => { if (!subscribed) return; subscribed = false; state.threadEventListeners.delete(registration); }; } cancelQueuedMessages( agent: Agent, target: CancelQueuedAgentMessagesOptions, pubsub?: PubSub, ): CancelQueuedAgentMessagesResult { const state = this.#getState(pubsub); const key = this.#threadKey(target.resourceId, target.threadId); const hasSignalIds = Array.isArray((target as { signalIds?: unknown }).signalIds); const hasQueueOwnerId = typeof (target as { queueOwnerId?: unknown }).queueOwnerId === 'string'; if (hasSignalIds === hasQueueOwnerId) { throw new Error('cancelQueuedMessages requires exactly one of signalIds or queueOwnerId'); } if (hasSignalIds) { const signalIds = new Set(target.signalIds); const result = this.#cancelPendingSignals(state, key, signalIds, pubsub); this.#publish(pubsub, key, { type: 'signals-cancelled', signalIds: [...signalIds] }); if (result.cancelledSignalIds.length) { this.#notifyThreadEvents(state); } return result; } const matches = (pending: PendingIdleSignal) => pending.agent === agent && pending.queueOwnerId === target.queueOwnerId; const forwardedIds = [...(state.forwardedIdleSignalsByThread.get(key) ?? [])] .filter(([, entry]) => matches(entry.pendingIdle)) .map(([signalId]) => signalId); const cancelledSignalIds = this.#cancelIdleSignals(state, key, matches); this.#publishCancelledUserMessages(pubsub, key, cancelledSignalIds); // The owner may hold a forwarded copy in its own queue. if (forwardedIds.length) this.#publish(pubsub, key, { type: 'signals-cancelled', signalIds: forwardedIds }); if (cancelledSignalIds.length > 0) this.#notifyThreadEvents(state); return { cancelledSignalIds }; } #cancelIdleSignals( state: AgentThreadRuntimeState, key: string, matches: (pending: PendingIdleSignal) => boolean, ): string[] { const cancelledSignalIds: string[] = []; const queue = state.pendingIdleSignalsByThread.get(key); if (queue) { const remaining = queue.filter(pending => { if (!matches(pending)) return true; cancelledSignalIds.push(pending.signal.id); this.#markIdleMessageCancelled(state, key, pending); return false; }); if (remaining.length === 0) state.pendingIdleSignalsByThread.delete(key); else state.pendingIdleSignalsByThread.set(key, remaining); } const draining = state.drainingIdleSignalsByThread.get(key); if (draining && matches(draining) && !draining.cancelled) { draining.cancelled = true; cancelledSignalIds.push(draining.signal.id); this.#markIdleMessageCancelled(state, key, draining); } for (const [signalId, entry] of state.forwardedIdleSignalsByThread.get(key) ?? []) { if (!matches(entry.pendingIdle)) continue; this.#settleForwardedIdleSignal(state, key, signalId); entry.pendingIdle.cancelled = true; cancelledSignalIds.push(signalId); this.#markIdleMessageCancelled(state, key, entry.pendingIdle); } return cancelledSignalIds; } #cancelPendingSignals( state: AgentThreadRuntimeState, key: string, signalIds?: ReadonlySet, pubsub?: PubSub, ): CancelQueuedAgentMessagesResult { const matches = (signal: CreatedAgentSignal) => signalIds === undefined || signalIds.has(signal.id); const cancelled = new Set(); for (const queues of [state.preRunSignalsByThread, state.pendingSignalsByThread]) { const queue = queues.get(key); if (!queue) continue; const remaining = queue.filter(signal => { if (!matches(signal)) return true; cancelled.add(signal.id); return false; }); if (remaining.length) queues.set(key, remaining); else queues.delete(key); } const draining = state.drainingPendingSignalsByThread.get(key); if ( draining && !draining.cancelled && matches(draining.signal) && (!draining.handedOff || signalIds === undefined) ) { draining.cancelled = true; if (!draining.handedOff) cancelled.add(draining.signal.id); } // A claimed-owner message joined a run in flight: a retry must learn it was cancelled. for (const id of cancelled) { const queued = state.claimedQueuedMessages.get(claimedQueuedMessageKey(key, id)); if (!queued) continue; queued.cancelled = true; if (queued.identity && queued.runId) this.#markAcceptedMessageCancelled(state, queued.identity, queued.runId); } for (const id of this.#cancelIdleSignals(state, key, pending => matches(pending.signal))) cancelled.add(id); const control = state.threadControlSubscriptions.get(key); for (const id of cancelled) control?.admittedSignalIds.add(id); this.#publishCancelledUserMessages(pubsub, key, [...cancelled]); return { cancelledSignalIds: [...cancelled] }; } queueMessage( agent: Agent, message: AgentMessageInput, target: QueueAgentMessageOptions, pubsub?: PubSub, ): QueueAgentMessageResult { return this.queueSignal(agent, this.#createMessageSignalInput(message), target, pubsub); } /** * 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( agent: Agent, signalInput: AgentSignal, target: QueueAgentSignalOptions, pubsub?: PubSub, ): QueueAgentSignalResult { const state = this.#getState(pubsub); const acceptedAt = new Date(); let key: string | undefined; let runId = target.runId; let activeRecord: AgentThreadRunRecord | undefined; if (target.resourceId && target.threadId) { key = this.#threadKey(target.resourceId, target.threadId); let activeRunId = state.activeThreadRunIds.get(key); activeRecord = activeRunId ? state.threadRunsById.get(activeRunId) : undefined; if (activeRecord && !this.#isThreadBlockingRun(state, activeRecord)) { state.activeThreadRunIds.delete(key); activeRecord = undefined; } if (activeRunId && !activeRecord && this.#isSweptLeaseOwner(state, activeRunId)) { // A run the TTL sweep evicted never completes here to drain the idle queue; // let sendSignal decide from the lease instead. state.activeThreadRunIds.delete(key); state.activeThreadStreamIds.delete(key); activeRunId = undefined; } runId ??= activeRunId; } if (runId) { activeRecord ??= state.threadRunsById.get(runId); if (activeRecord) { key ??= this.#threadKey(activeRecord.resourceId, activeRecord.threadId); } } this.#assertRunTargetOwner(state, target); const resourceId = target.resourceId ?? activeRecord?.resourceId; const threadId = target.threadId ?? activeRecord?.threadId; if (!resourceId || !threadId) { throw new Error('resourceId and threadId are required to queue a message'); } key ??= this.#threadKey(resourceId, threadId); const signal = createSignal({ ...signalInput, id: signalInput.id ?? this.#generateSignalMessageId(agent, { resourceId, threadId }), acceptedAt, }); // Preserve explicit cancellation, but don't inherit the active run's signal. const baseQueuedStreamOptions = target.ifIdle?.streamOptions ?? { ...activeRecord?.streamOptions, abortSignal: undefined, }; const queuedScopes = resolveThreadTargetScopes(target, { resourceId, threadId }, agent.getMastraInstance?.()); // A queued run naming scopes holds exactly those (they already include // `ifIdle.streamOptions.scopes`), never the active run's it would otherwise fall back to. // Falling back to the active run's options, drop what pins them to that run's scopes: // its request context carries them, and a durable agent skips re-resolving options // carrying its (symbol-keyed) resolved marker. const inherited = target.ifIdle?.streamOptions ? undefined : baseQueuedStreamOptions; const queuedStreamOptions = queuedScopes ? { ...(inherited ? Object.fromEntries(Object.entries(inherited)) : baseQueuedStreamOptions), scopes: queuedScopes, ...(inherited?.requestContext ? { requestContext: deriveAgentRunRequestContext(inherited.requestContext, []) } : {}), } : baseQueuedStreamOptions; if (activeRecord || state.activeThreadRunIds.has(key)) { // The queued run starts once the thread is idle, so idle delivery attributes apply. const queuedSignal = resolveDeliveryAttributes(signal, target.ifIdle?.attributes); const queued = this.#idleStartRunId(state, target.ifIdle?.streamOptions?.runId); if (queued.refused) { return { signal: queuedSignal, accepted: queued.refused }; } const queuedRunId = queued.runId; const idleQueue = state.pendingIdleSignalsByThread.get(key) ?? []; idleQueue.push({ agent, signal: queuedSignal, runId: queuedRunId, resourceId, threadId, streamOptions: queuedStreamOptions, queueOwnerId: target.queueOwnerId, }); state.pendingIdleSignalsByThread.set(key, idleQueue); const control = this.#ensureThreadControlSubscription(state, pubsub, key); this.#publishPendingUserMessage(pubsub, key, runId ?? queuedRunId, queuedSignal, 'queued'); this.#notifyThreadEvents(state); if (activeRecord) { this.#watchThreadRunCompletion(state, pubsub, key, activeRecord); } return { signal: queuedSignal, accepted: control.ready.then(() => ({ action: 'deliver' as const, runId: queuedRunId })), }; } return this.#sendSignal( agent, signal, { ...target, runId, resourceId, threadId, ifIdle: { ...target.ifIdle, behavior: 'wake' } }, pubsub, true, ); } async sendStateSignal( agent: Agent, stateInput: AgentStateSignalInput, target: SendAgentStateSignalOptions, pubsub?: PubSub, ): Promise> { if (!target.resourceId || !target.threadId) { throw new Error('resourceId and threadId are required to send a state signal'); } const resourceId = target.resourceId; const threadId = target.threadId; const requestContext = target.ifIdle?.streamOptions?.requestContext; const memoryContext = parseMemoryRequestContext(requestContext); const memory = await agent.getMemory({ requestContext }); if (!memory) { throw new Error('sendStateSignal requires Mastra memory'); } const loadedThread = (await memory.getThreadById({ threadId })) ?? memoryContext?.thread; if (!loadedThread) { throw new Error(`sendStateSignal could not load thread ${threadId}`); } const thread = { ...loadedThread, id: threadId, resourceId: loadedThread.resourceId ?? resourceId, createdAt: loadedThread.createdAt ?? new Date(), updatedAt: loadedThread.updatedAt ?? new Date(), metadata: loadedThread.metadata, }; const applied = await applyStateSignal({ input: stateInput, memory, thread, resourceId, threadId, memoryConfig: memoryContext?.memoryConfig, acceptedAt: new Date(), }); if (applied.skipped) { return { skipped: true, reason: 'unchanged' }; } return this.sendSignal(agent, applied.signal, target, pubsub); } /** * 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( agent: Agent, signalInput: AgentSignal, inputTarget: SendAgentSignalOptions, pubsub?: PubSub, ): SendAgentSignalResult { return this.#sendSignal(agent, signalInput, inputTarget, pubsub, false); } /** `waitForIdle` keeps queued input out of a run in flight at a claimed owner in another process. */ #sendSignal( agent: Agent, signalInput: AgentSignal, inputTarget: SendAgentSignalOptions, pubsub: PubSub | undefined, waitForIdle: boolean, ): SendAgentSignalResult { const target = withThreadTargetScopes(inputTarget, agent.getMastraInstance?.()); const state = this.#getState(pubsub); // A run's scopes are fixed when it starts. A thread-targeted signal that names its // scopes joins an active run only when that run holds exactly those scopes; otherwise // it is refused with `scope-mismatch`, and the sender waits for that run to end and // sends again so the signal starts its own run. const messageScopes = inputTarget.resourceId && inputTarget.threadId ? inputTarget.scopes : undefined; const scopeMismatch = (activeRunId: string) => messageScopes !== undefined && !this.#runHoldsScopes(state, activeRunId, messageScopes); const refuseScopes = (activeRunId: string) => ({ signal, accepted: Promise.resolve({ action: 'blocked' as const, reason: 'scope-mismatch' as const, runId: activeRunId }), }); let key: string | undefined; let runId = target.runId; const activeBehavior = target.ifActive?.behavior ?? 'deliver'; const idleBehavior = target.ifIdle?.behavior ?? 'wake'; let activeRecord: AgentThreadRunRecord | undefined; let remoteCrossAgent = false; if (target.resourceId && target.threadId) { key = this.#threadKey(target.resourceId, target.threadId); const activeRunId = state.activeThreadRunIds.get(key); activeRecord = activeRunId ? state.threadRunsById.get(activeRunId) : undefined; if (activeRecord && !this.#isThreadBlockingRun(state, activeRecord)) { state.activeThreadRunIds.delete(key); activeRecord = undefined; } // Prefer the active same-agent run for thread-targeted signals. This is the normal // follow-up path used by clients that know the thread/resource but not the run id. if (activeRecord && activeRecord.agent.id === agent.id) { runId = activeRecord.runId; } else if (activeRunId && !activeRecord) { if ( // A run the TTL sweep evicted consumes nothing, whatever restored it as active. !this.#isSweptLeaseOwner(state, activeRunId) && (state.threadKeysByRunId.get(activeRunId) === key || (state.remoteThreadKeysByRunId.get(activeRunId) === key && !state.unobservedRemoteRunIds.has(activeRunId))) ) { // A remote run whose owner agent is unknown (e.g. seen via a stream part // before its registration) is not a safe target for this agent. remoteCrossAgent = state.threadKeysByRunId.get(activeRunId) !== key && state.remoteAgentIdsByRunId.get(activeRunId) !== agent.id; // A run can be reserved before its stream record is registered. Keep the reserved // id so early follow-ups still attach to the run that is starting. runId = activeRunId; } else { // Stale cross-pod entry. Clean it up from the local map, then let the lease decide. state.activeThreadRunIds.delete(key); state.activeThreadStreamIds.delete(key); } } } if (runId) { activeRecord ??= state.threadRunsById.get(runId); if (activeRecord) { key ??= this.#threadKey(activeRecord.resourceId, activeRecord.threadId); } } this.#assertRunTargetOwner(state, target); const resourceId = target.resourceId ?? activeRecord?.resourceId; const threadId = target.threadId ?? activeRecord?.threadId; if (!resourceId || !threadId) { throw new Error('No active agent run found for signal target'); } const isActiveTarget = Boolean( runId && (activeRecord?.output.status === 'running' || (key && state.activeThreadRunIds.get(key) === runId)), ); let signal = createSignal({ ...signalInput, id: signalInput.id ?? this.#generateSignalMessageId(agent, { resourceId, threadId }), acceptedAt: new Date(), }); // A claimed owner in another process may hand idle-routed input to a run this process can't see. It gets // the input as it would arrive at an active run too, and uses that copy if it joins a run. const joinSignal = !isActiveTarget && (target.ifActive?.attributes || target.ifIdle?.attributes) ? resolveDeliveryAttributes(signal, target.ifActive?.attributes) : undefined; // Resolve conditional delivery attributes now that we know the delivery path. signal = resolveDeliveryAttributes( signal, isActiveTarget ? target.ifActive?.attributes : target.ifIdle?.attributes, ); if (remoteCrossAgent) { return { signal, accepted: Promise.resolve({ action: 'blocked' as const, reason: 'thread-blocked' as const, runId: runId! }), }; } if (isActiveTarget && activeBehavior !== 'deliver') { if (activeBehavior === 'persist') { if (!resourceId || !threadId) { throw new Error('resourceId and threadId are required to persist an active signal'); } // Transient signals are never written to storage, so a `persist` behavior has nothing // to do with them — report the drop honestly as `discard` instead of `persist`. if (signal.transient) { return { signal, accepted: Promise.resolve({ action: 'discard' as const }), }; } const persisted = this.#persistSignal( agent, signal, resourceId, threadId, target.ifIdle?.streamOptions?.requestContext, ); void persisted.catch(() => {}); return { signal, persisted, accepted: Promise.resolve({ action: 'persist' as const }), }; } return { signal, accepted: Promise.resolve({ action: 'discard' as const }), }; } if (runId) { // A run is "blocking" while it is running or suspended awaiting tool approval. Both // states mean the run has already made model requests, so a follow-up signal must be // queued as a pending (next-turn) signal rather than folded into a not-yet-started // first request via the pre-run path below. if (activeRecord && this.#isThreadBlockingRun(state, activeRecord)) { key ??= this.#threadKey(activeRecord.resourceId, activeRecord.threadId); if (activeRecord.agent.id === agent.id) { if (scopeMismatch(runId)) return refuseScopes(runId); this.#queueForActiveRun(state, pubsub, key, activeRecord, signal); return { signal, accepted: Promise.resolve({ action: 'deliver' as const, runId }), }; } return { signal, accepted: Promise.resolve({ action: 'blocked' as const, reason: 'thread-blocked' as const, runId: activeRecord.runId, }), }; } if (key && state.activeThreadRunIds.get(key) === runId) { // A local reserved run has not registered its stream record yet, so it // has not made its first model request — queue the signal as a pre-run // signal so the first LLM step folds it into that request. A run owned // by another runtime instance is reached only via PubSub; treat it as a // follow-up, since the sender cannot see the owner's request state. const isLocalReservedRun = state.threadKeysByRunId.get(runId) === key; const pendingAdmission = isLocalReservedRun ? state.pendingThreadAdmissions.get(key) : undefined; // Scopes of a reserved run owned by another process are unknown here, so a // signal naming scopes never joins one. if (scopeMismatch(runId)) return refuseScopes(runId); if (pendingAdmission?.runId === runId) { const pendingKey = key; const queue = state.preRunSignalsByThread.get(key) ?? []; queue.push(signal); state.preRunSignalsByThread.set(key, queue); this.#recordLocallyQueuedSignal(state, key, signal.id); this.#notifyPendingSignals(state, key, signal); const accepted = pendingAdmission.outcome.then(async admission => { if (admission.action === 'local') { // The reserved run owns the lease and takes this signal from the pre-run queue. return { action: 'deliver' as const, runId: admission.runId }; } // This attempt never consumed the signal locally, so this caller drops // its own copy before acknowledging: the queue may now belong to a newer // reservation whose slot guard keeps the losing rollback from cleaning // it, and a later run there must not replay acknowledged input. this.#discardQueuedPreRunSignal(state, pendingKey, signal.id); if (admission.action === 'remote') { // The real owner's scopes are unknown here, so a signal naming scopes waits for it. if (messageScopes !== undefined) { return { action: 'blocked' as const, reason: 'scope-mismatch' as const, runId: admission.runId }; } // The reservation lost its lease; hand this signal to the same real // owner before acknowledging it. await this.#publishAndWait(pubsub, pendingKey, { type: 'signal-enqueued', runId: admission.runId, signal: this.#serializeSignal(signal), sourceId: this.#getSourceId(), }).catch(() => {}); return { action: 'deliver' as const, runId: admission.runId }; } return { action: 'blocked' as const, reason: 'thread-blocked' as const, runId: admission.runId }; }); void accepted.catch(() => { // No outcome was produced, so nothing acknowledged this signal; drop // its copy so a later run cannot replay input the caller must retry. this.#discardQueuedPreRunSignal(state, pendingKey, signal.id); }); return { signal, accepted }; } const claimedOwnerDiscovery = isLocalReservedRun ? state.claimedThreadOwnerDiscoveries.get(key) : undefined; if (claimedOwnerDiscovery) { if (messageScopes !== undefined) { // Discovered owners are in another process; the request carries no scopes. const refused = Promise.reject( new Error( `A message with scopes can't be sent to the owner of ${describeThreadKey(key)} in another process: scopes don't cross processes.`, ), ); void refused.catch(() => {}); return { signal, accepted: refused }; } const accepted = this.#deliverAfterClaimedOwnerDiscovery( this.#getPubSub(pubsub), key, globalThis.crypto.randomUUID(), signal, claimedOwnerDiscovery, false, undefined, target.ifIdle?.streamOptions?.requestContext, ); void accepted.catch(() => {}); return { signal, accepted }; } if (isLocalReservedRun) { const queue = state.preRunSignalsByThread.get(key) ?? []; queue.push(signal); state.preRunSignalsByThread.set(key, queue); this.#recordLocallyQueuedSignal(state, key, signal.id); this.#publishPendingUserMessage(pubsub, key, runId, signal, 'pending'); this.#notifyPendingSignals(state, key, signal); } this.#publish(pubsub, key, { type: 'signal-enqueued', runId, signal: this.#serializeSignal(signal), sourceId: this.#getSourceId(), preRun: isLocalReservedRun, }); return { signal, accepted: Promise.resolve({ action: 'deliver' as const, runId }), }; } } const idleStart = this.#idleStartRunId(state, target.ifIdle?.streamOptions?.runId); if (idleStart.refused) { return { signal, accepted: idleStart.refused }; } runId = idleStart.runId; key ??= this.#threadKey(resourceId, threadId); if (idleBehavior === 'persist') { // Transient signals are never written to storage, so an idle `persist` behavior drops // them entirely (no store, no broadcast) — report that as `discard`, not `persist`. if (signal.transient) { return { signal, accepted: Promise.resolve({ action: 'discard' as const }), }; } const persisted = this.#persistAndBroadcastIdleSignal( state, pubsub, key, runId, agent, signal, resourceId, threadId, target.ifIdle?.streamOptions?.requestContext, ); void persisted.catch(() => {}); return { signal, persisted, accepted: Promise.resolve({ action: 'persist' as const }), }; } if (idleBehavior !== 'wake') { return { signal, accepted: Promise.resolve({ action: 'discard' as const }), }; } if (state.activeThreadRunIds.has(key)) { const blockingRunId = state.activeThreadRunIds.get(key)!; const blockingRecord = activeRecord ?? state.threadRunsById.get(blockingRunId); if ( this.#isSuspendedRun(state, blockingRunId) || blockingRecord?.output.status === 'suspended' || blockingRecord?.lifecycle === 'suspended' ) { return { signal, accepted: Promise.resolve({ action: 'blocked' as const, reason: 'thread-blocked' as const, runId: blockingRunId, }), }; } // Another run owns the thread. Queue this idle-start request and let the watcher // launch it only after the active run clears the thread reservation. const idleQueue = state.pendingIdleSignalsByThread.get(key) ?? []; idleQueue.push({ agent, signal, runId, resourceId, threadId, streamOptions: target.ifIdle?.streamOptions }); state.pendingIdleSignalsByThread.set(key, idleQueue); if (activeRecord) { this.#watchThreadRunCompletion(state, pubsub, key, activeRecord); } return { signal, accepted: Promise.resolve({ action: 'deliver' as const, runId }), }; } // No active same-agent run accepted the signal. Reserve the thread before starting // the idle stream so concurrent callers do not launch duplicate runs. state.activeThreadRunIds.set(key, runId); state.threadKeysByRunId.set(runId, key); state.reservedRunScopes.set(runId, target.ifIdle?.streamOptions?.scopes); const reservedKey = key; const reservedRunId = runId; const resolvedPubSub = this.#getPubSub(pubsub); const leaseProvider = this.#getLeaseProvider(resolvedPubSub); // First acquire the cross-process lease via pubsub; on win, kick off the stream and // resolve a `wake` accepted result carrying the owned stream. On loss, hand the user // signal off to the winning process via signal-enqueued and resolve a `deliver` result // (the signal was queued onto the winning run, not run locally). const localClaimedOwner = state.claimedThreadOwners.get(reservedKey); const sharePendingAdmission = !localClaimedOwner && !target.ifIdle?.requireClaimedOwner; const accepted: Promise> = (async () => { if (localClaimedOwner) { if (state.activeThreadRunIds.get(reservedKey) === reservedRunId) { state.activeThreadRunIds.delete(reservedKey); } state.threadKeysByRunId.delete(reservedRunId); const localAcceptance = await this.#startClaimedIdleRun( state, resolvedPubSub, reservedKey, localClaimedOwner, reservedRunId, signal, Date.now() + AGENT_THREAD_OWNER_ACCEPTANCE_TIMEOUT_MS, () => state.claimedThreadOwners.get(reservedKey)?.unsubscribe === localClaimedOwner.unsubscribe, target.ifIdle?.streamOptions, waitForIdle, joinSignal, messageScopes, ); if (!localAcceptance) { throw new Error( `Claimed thread owner could not acquire the execution lease for ${describeThreadKey(reservedKey)}`, ); } if (localAcceptance.blocked) { return { action: 'blocked' as const, reason: 'thread-blocked' as const, runId: localAcceptance.runId }; } if (localAcceptance.error) throw new Error(localAcceptance.error); if (!localAcceptance.output) { // The signal joined a run that was still in flight, so nothing ran here. return { action: 'deliver' as const, runId: localAcceptance.runId }; } // This owner ran the turn. Reporting `deliver` would claim no run started, // leaving the caller waiting on a delivery that already happened and // re-sending into a run it believes is still in flight. return { action: 'wake' as const, runId: localAcceptance.runId, output: localAcceptance.output }; } if (target.ifIdle?.requireClaimedOwner) { if (messageScopes !== undefined) { if (state.activeThreadRunIds.get(reservedKey) === reservedRunId) { state.activeThreadRunIds.delete(reservedKey); } state.threadKeysByRunId.delete(reservedRunId); // The request to a claimed owner in another process carries no scopes, so the // owner would join or start a run without them. Refuse rather than drop them. throw new Error( `A message with scopes can't be sent to the owner of ${describeThreadKey(reservedKey)} in another process: scopes don't cross processes.`, ); } const discovery = this.#findClaimedThreadOwnerWithRetry(resolvedPubSub, reservedKey); state.claimedThreadOwnerDiscoveries.set(reservedKey, discovery); try { return await this.#deliverAfterClaimedOwnerDiscovery( resolvedPubSub, reservedKey, reservedRunId, signal, discovery, waitForIdle, joinSignal, target.ifIdle?.streamOptions?.requestContext, ); } finally { if (state.claimedThreadOwnerDiscoveries.get(reservedKey) === discovery) { state.claimedThreadOwnerDiscoveries.delete(reservedKey); } if (state.activeThreadRunIds.get(reservedKey) === reservedRunId) { state.activeThreadRunIds.delete(reservedKey); } state.threadKeysByRunId.delete(reservedRunId); } } try { await this.#ensureThreadControlSubscription(state, resolvedPubSub, reservedKey).ready; } catch (error) { this.releaseThreadRunReservation(reservedRunId, resolvedPubSub); throw error; } // Fail-open on pubsub errors: if the lease backend is unreachable we treat the // call as "acquired" so the caller still gets a response. The tradeoff is that // if multiple processes hit the same pubsub failure simultaneously they can each // start a stream for the same thread (the bug this lease is supposed to prevent), // but failing closed would silently drop user messages on any Redis blip which // is the worse failure mode. Lease TTL + renewal still bound the duplicate // window to a single run, and the next clean acquireLease re-serializes callers. const lease = await this.#waitForRetakeOwner( leaseProvider, reservedKey, await leaseProvider .acquireLease(reservedKey, threadLeaseOwner(reservedRunId), AGENT_THREAD_LEASE_TTL_MS) .catch(() => ({ acquired: true as boolean, owner: reservedRunId as string | undefined })), ); if (!lease.acquired) { // Lost the wake race to another process. Roll back our optimistic local reservation // so we don't trip our own activeThreadRunIds check on a follow-up. if (state.activeThreadRunIds.get(reservedKey) === reservedRunId) { state.activeThreadRunIds.delete(reservedKey); // Only discard the queue while this reservation still owns the slot — // a newer reservation's queued input must survive, and this attempt's // own senders discard their copies per signal when it settles. state.preRunSignalsByThread.delete(reservedKey); } state.threadKeysByRunId.delete(reservedRunId); const winnerRunId = lease.owner ? threadLeaseRunId(lease.owner) : undefined; if (isRetakeLeaseOwner(lease.owner)) { return { action: 'blocked' as const, reason: 'thread-blocked' as const, runId: winnerRunId!, }; } if (winnerRunId && this.#isSweptLeaseOwner(state, winnerRunId)) { // The lease still belongs to a suspended run the TTL sweep evicted. Nothing // consumes a signal forwarded to it, so report the thread blocked rather // than acknowledge a delivery that never happens. return { action: 'blocked' as const, reason: 'thread-blocked' as const, runId: winnerRunId }; } // The winner's scopes are unknown here, so a signal naming scopes waits for it. if (winnerRunId && messageScopes !== undefined) { return { action: 'blocked' as const, reason: 'scope-mismatch' as const, runId: winnerRunId }; } // Forward the user signal to the winning runId so the message is not dropped. // Await the publish so that callers using `accepted` resolution as their // "safe to exit" boundary (e.g. a serverless Lambda holding the request open // via waitUntil) don't tear down before the enqueue lands on the broker. if (winnerRunId) { await this.#publishAndWait(pubsub, reservedKey, { type: 'signal-enqueued', runId: winnerRunId, signal: this.#serializeSignal(signal), sourceId: this.#getSourceId(), }).catch(() => {}); } return { action: 'deliver' as const, runId: winnerRunId ?? reservedRunId }; } // We own the lease. Start the renewal timer so it survives runs // that outlive the TTL, then kick off the stream. this.#startLeaseRenewal(resolvedPubSub, reservedKey, reservedRunId, threadLeaseOwner(reservedRunId)); try { const output = toModelOutput( await agent.stream(signal, { // The woken run stays open until its background tasks finish, unless the app sets // `backgroundTasks.wokenRunsEndAfterTurn`; its deferred tasks then report back through // a `background-task` signal. The signal's own `untilIdle` wins either way. // TODO(v2): make ending after the turn the default and remove `wokenRunsEndAfterTurn`. untilIdle: !agent.getMastraInstance?.()?.backgroundTaskManager?.config.wokenRunsEndAfterTurn, ...(target.ifIdle?.streamOptions as any), runId: reservedRunId, memory: withThreadMemory(target.ifIdle?.streamOptions?.memory, resourceId, threadId), }), ); return { action: 'wake' as const, runId: reservedRunId, output }; } catch (error) { state.threadKeysByRunId.delete(reservedRunId); this.#cleanupPreparedRun(state, reservedRunId); if (state.activeThreadRunIds.get(reservedKey) === reservedRunId) { state.activeThreadRunIds.delete(reservedKey); } this.#releaseThreadLease(pubsub, reservedKey, reservedRunId); this.#publish(pubsub, reservedKey, { type: 'run-failed', runId: reservedRunId, error: getErrorFromUnknown(error).message, }); this.#trimRunLater(pubsub, reservedKey, reservedRunId); void this.#drainPendingIdleSignals(state, pubsub, reservedKey); throw error; } })(); if (sharePendingAdmission) { this.#trackPendingThreadAdmission( state, reservedKey, reservedRunId, agent.id, accepted.then(admission => { if (admission.action === 'wake') return { action: 'local' as const, runId: admission.runId }; if (admission.action === 'deliver') return { action: 'remote' as const, runId: admission.runId }; // This signal's scopes kept it from the run that won the lease; signals queued // behind this reservation still go to that run. if (admission.action === 'blocked' && admission.reason === 'scope-mismatch') { return { action: 'remote' as const, runId: admission.runId }; } if (admission.action === 'blocked') return { action: 'blocked' as const, runId: admission.runId }; throw new Error(`Unexpected ${admission.action} result while reserving ${describeThreadKey(reservedKey)}`); }), ); } void accepted.then( () => state.reservedRunScopes.delete(reservedRunId), () => state.reservedRunScopes.delete(reservedRunId), ); // Attach a detached no-op catch so that if stream setup throws (a misconfigured // agent: no/unsupported model, FGA denial) and the caller never awaits // `result.accepted`, the rejection does not surface as an unhandled rejection. // Callers that opt in to `accepted` still see the rejection via their own // await/catch — `accepted` itself remains rejectable; only this detached branch is // swallowed. void accepted.finally(() => this.#releaseUnusedThreadControlSubscription(state, reservedKey)).catch(() => {}); return { signal, accepted, }; } } export const agentThreadStreamRuntime = new AgentThreadStreamRuntime();