UNPKG

@mastra/core

Version:
1 lines • 158 kB
{"version":3,"file":"background-tasks-CVddYnZ1.cjs","names":["z"],"sources":["../src/background-tasks/workflow-id.ts","../src/background-tasks/manager.ts","../src/background-tasks/create.ts","../src/background-tasks/resolve-config.ts","../src/background-tasks/schema-injection.ts","../src/background-tasks/system-prompt.ts"],"sourcesContent":["/**\n * Workflow id used by the bg-task workflow registered on Mastra.\n * Double-underscore prefix marks it as internal — same convention as\n * `__batch-scoring-traces`.\n *\n * Lives in its own file (separate from `./workflow`) so `manager.ts` can\n * reference the id without statically pulling in `../workflows/evented`,\n * which would create a circular import via `agent → background-tasks →\n * workflow → evented → workflows/index → agent`.\n */\nexport const BACKGROUND_TASK_WORKFLOW_ID = '__background-task';\n","import type { Mastra } from '..';\nimport type { PubSub } from '../events/pubsub';\nimport type { Event, EventCallback } from '../events/types';\nimport type {\n  BackgroundTask,\n  BackgroundTaskManagerConfig,\n  BackgroundTaskStatus,\n  EnqueueOptions,\n  EnqueueResult,\n  ResumeOptions,\n  TaskContext,\n  TaskFilter,\n  TaskPayload,\n  TaskListResult,\n  ToolExecutor,\n  BackgroundTaskEvent,\n} from './types';\nimport { BACKGROUND_TASK_WORKFLOW_ID } from './workflow-id';\n\nconst TOPIC_DISPATCH = 'background-tasks';\nconst TOPIC_RESULT = 'background-tasks-result';\nconst WORKER_GROUP = 'background-task-workers';\nconst SHUTDOWN_GRACE_PERIOD_MS = 5_000;\nconst SHUTDOWN_ABORT_MESSAGE = 'Background task manager is shutting down';\nconst TASK_OWNERSHIP_LOST_MESSAGE = 'Background task execution ownership was taken over by another worker';\n\nfunction workflowRunError(result: { status: string; error?: unknown; tripwire?: { reason?: string } }): unknown {\n  if (result.error !== undefined) return result.error;\n  if (result.tripwire?.reason) return new Error(result.tripwire.reason);\n  return new Error(`Background task workflow run ended with status '${result.status}'`);\n}\n\n// Workflow results carry errors serialized to plain objects, not Error instances.\nfunction toTaskError(err: unknown): { message: string; stack?: string } {\n  if (err && typeof err === 'object' && typeof (err as { message?: unknown }).message === 'string') {\n    const { message, stack } = err as { message: string; stack?: unknown };\n    return typeof stack === 'string' ? { message, stack } : { message };\n  }\n  return { message: String(err) };\n}\n\n/** Pending rows each lapsed-pin sweep reads; later pages are read on later ticks. */\nconst PIN_SWEEP_PAGE_SIZE = 100;\n\n/** Test-only lower lease minimum; only ever lowers the default 3s. Read per manager, not at import. */\nfunction minLeaseOverride(): number | undefined {\n  const value = Number(process.env.MASTRA_BACKGROUND_TASKS_MIN_LEASE_MS);\n  return Number.isFinite(value) && value > 0 && value < 3_000 ? value : undefined;\n}\n\n/**\n * Runs, persists, and recovers background tasks for one Mastra process.\n *\n * Several managers (processes or replicas) may share one storage backend.\n * Execution is owned through a lease persisted on each task record:\n *\n * - Identity: each manager has a random `ownerId` (`workerId`), so a restarted\n *   process is a new owner.\n * - Acquisition: `handleDispatch` claims a task with a compare-and-set on the\n *   observed status/owner/lease, writing `ownerId` and\n *   `leaseExpiresAt = now + leaseDurationMs`. Losers of a race skip the task.\n * - Renewal: the heartbeat renews owned leases every `leaseDurationMs / 3`,\n *   fenced on `running` + this owner. Workflow terminal writes carry the same\n *   fence, so a superseded owner cannot commit results.\n * - Expiry and adoption: `recoverStaleTasks` only reclaims a `running` task\n *   once its lease has expired (or was released on shutdown), fenced on the\n *   owner/lease it read so one manager wins. It re-runs when the earliest live\n *   lease lapses. `restart()` is the one deliberate takeover of a live lease.\n * - Loss: a failed renewal aborts the local run's signal when another owner\n *   holds the task or it was cancelled.\n *\n * Guarantee: at most one owner can commit a task's state at a time, except\n * for the shutdown rollback of an interrupted resume in `handleResume`, which is\n * conditional on status only. The tool\n * itself may still run more than once (stalled owner past its lease, crash\n * before the result is saved, explicit restart), so external side effects need\n * idempotency. Assumes storage applies `updateTask` conditions atomically and\n * that clock skew between managers is well below `leaseDurationMs`, since\n * `leaseExpiresAt` is written by the owner's clock and read by others'.\n */\nexport class BackgroundTaskManager {\n  private pubsub!: PubSub;\n  private readonly workerId = globalThis.crypto.randomUUID();\n  private readonly processAffineDispatchTopic = `${TOPIC_DISPATCH}:${this.workerId}`;\n  config: Required<\n    Pick<\n      BackgroundTaskManagerConfig,\n      | 'globalConcurrency'\n      | 'perAgentConcurrency'\n      | 'backpressure'\n      | 'defaultTimeoutMs'\n      | 'recoverStaleTasksOnStart'\n      | 'leaseDurationMs'\n    >\n  > &\n    BackgroundTaskManagerConfig;\n\n  #mastra?: Mastra;\n\n  // Per-task contexts — keyed by task ID, holds closures from the caller's stream.\n  /** @internal — read by the workflow-engine step bodies in workflow.ts */\n  taskContexts: Map<string, TaskContext> = new Map();\n\n  // Static executors keyed by tool name. Populated by `Mastra` for every\n  // registered tool, and by `BackgroundTaskWorker.#wireStaticTools` on\n  // standalone worker processes. Used as the fallback for cross-process\n  // dispatch where the producer's per-task closure (taskContexts) is not\n  // visible — a remote worker resolves the tool by name instead.\n  private staticExecutors: Map<string, ToolExecutor> = new Map();\n\n  // Track active AbortControllers for running tasks (for cancellation + timeout)\n  /** @internal — read by the workflow-engine step bodies in workflow.ts */\n  activeAbortControllers: Map<string, AbortController> = new Map();\n\n  // Process-affine executors are runtime closures and cannot participate in\n  // storage-wide concurrency accounting. Keep their admission and queue\n  // ownership local to the manager that owns the closure so abandoned rows\n  // from another process cannot block them. Cross-process safety instead comes\n  // from the persisted execution lease (see `ownedLeases`): a task is only\n  // recoverable once its owner stops renewing the lease.\n  private localReservations = new Map<string, string>();\n  private localPendingTaskIds = new Set<string>();\n  // Resumes requested with `onNoSlot: 'queue'` while no slot was free, keyed by\n  // task ID. The rows stay `suspended`; `drainPending()` publishes them first.\n  private localPendingResumes = new Map<string, { resumeData: unknown; suspendedAt: number | null }>();\n  // Portable resumes this process has published that no worker has picked up\n  // yet. The row stays `suspended` until `handleResume` runs, so storage-wide\n  // running counts miss them; `checkConcurrency()` adds them back so one free\n  // slot can't admit several queued resumes. Entries expire after a lease\n  // duration in case the event is lost.\n  private inFlightPortableResumes = new Map<string, { agentId: string; suspendedAt: number | null; until: number }>();\n  private drainingPending = false;\n\n  // Task IDs this manager currently holds an execution lease for. Populated on\n  // a successful claim and drained by the lease heartbeat, which renews each\n  // lease at `leaseDurationMs / 3`. A worker that dies stops renewing, so its\n  // leases expire and other workers may safely reclaim the tasks.\n  private ownedLeases = new Set<string>();\n  // Pending task IDs enqueued with `pinToWorker`. Their rows carry this\n  // manager's owner ID and a lease, renewed by the same heartbeat, so other\n  // workers leave them alone until this manager claims them or dies.\n  private pinnedPendingLeases = new Set<string>();\n  private heartbeatInterval?: ReturnType<typeof setInterval>;\n  // Shortest heartbeat / stale-recovery delay: 1s, unless a test lowered the lease minimum.\n  readonly #timingFloorMs: number;\n\n  // Pending follow-up pass for stale-task recovery. A running task whose lease\n  // is still valid is left alone by a recovery scan, so if its owner died just\n  // before that scan the task would otherwise stay 'running' until the next\n  // process restart. This timer re-runs recovery once the earliest such lease\n  // lapses, which lets a crashed owner's tasks settle without a restart.\n  private staleRecoveryTimeout?: ReturnType<typeof setTimeout>;\n  // Periodic scan for `pinToWorker` rows whose owner stopped renewing; see `#sweepLapsedPins`.\n  private pinSweepInterval?: ReturnType<typeof setInterval>;\n  private sweepingPins = false;\n  // Page of pending rows the next pin sweep reads; see `#sweepLapsedPins`.\n  private pinSweepPage = 0;\n\n  // Settlement chains of workflow runs started by this manager, plus the run\n  // deletes they spawn. Shutdown drains these so they finish while storage is\n  // still open — Mastra closes storage right after the manager stops.\n  #settlingRuns = new Set<Promise<unknown>>();\n\n  // Pubsub callbacks (kept for unsubscribe)\n  private workerCallback?: EventCallback;\n  private resultCallback?: EventCallback;\n\n  private shuttingDown = false;\n\n  // Cleanup interval handle\n  private cleanupInterval?: ReturnType<typeof setInterval>;\n\n  // Tracks the in-flight `init(pubsub)` so consumers can await readiness.\n  // Mastra fires init as fire-and-forget in `#ensureBackgroundTaskManager`,\n  // so without this any caller that hits `enqueue`/`resume`/`cancel`\n  // before init completes races against worker subscription + workflow\n  // registration. Public methods that depend on init await this promise\n  // before doing work.\n  private initPromise?: Promise<void>;\n\n  // Serializes teardown and makes repeated shutdown calls safe. Shutdown may\n  // race the constructor-owned, fire-and-forget init path, so cleanup must not\n  // run until initialization has either completed or failed.\n  private shutdownPromise?: Promise<void>;\n\n  // Wall-clock deadline shared by every step of the teardown sequence. Set once\n  // when shutdown begins; steps that start after it has passed fire their\n  // cleanup without blocking on it.\n  private shutdownDeadline?: number;\n\n  constructor(config: BackgroundTaskManagerConfig = { enabled: false }) {\n    const leaseDurationMs = config.leaseDurationMs ?? 30_000;\n    // The heartbeat renews at `leaseDurationMs / 3`, floored to 1s. A lease\n    // shorter than 3s therefore expires before it can be renewed, so reject it\n    // rather than silently letting every task's lease lapse mid-run.\n    //\n    // Internal, for tests that prove lease expiry: MASTRA_BACKGROUND_TASKS_MIN_LEASE_MS\n    // lowers that 3s minimum, and the 1s timing floor scales down with it, so\n    // those tests wait milliseconds instead of seconds. Not a supported setting.\n    const minLeaseMs = minLeaseOverride() ?? 3_000;\n    this.#timingFloorMs = minLeaseMs / 3;\n    if (!Number.isFinite(leaseDurationMs) || leaseDurationMs < minLeaseMs) {\n      throw new Error(\n        `BackgroundTaskManager leaseDurationMs must be a finite number of at least ${minLeaseMs}ms (received: ${leaseDurationMs})`,\n      );\n    }\n    for (const [owner, limit] of Object.entries(config.perOwnerConcurrency ?? {})) {\n      if (!Number.isFinite(limit) || limit < 1) {\n        throw new Error(\n          `BackgroundTaskManager perOwnerConcurrency[\"${owner}\"] must be a finite number of at least 1 (received: ${limit})`,\n        );\n      }\n    }\n    this.config = {\n      ...config,\n      globalConcurrency: config.globalConcurrency ?? 10,\n      perAgentConcurrency: config.perAgentConcurrency ?? 5,\n      backpressure: config.backpressure ?? 'queue',\n      defaultTimeoutMs: config.defaultTimeoutMs ?? 300_000,\n      recoverStaleTasksOnStart: config.recoverStaleTasksOnStart ?? true,\n      leaseDurationMs,\n    };\n  }\n\n  __registerMastra(mastra: Mastra) {\n    this.#mastra = mastra;\n  }\n\n  /**\n   * @internal — execution-lease owner identity for this manager process.\n   * Persisted when a task is claimed so recovery can distinguish a live owner\n   * from a dead one, and used by the workflow step bodies to fence their\n   * terminal writes against a superseded owner.\n   */\n  get ownerId(): string {\n    return this.workerId;\n  }\n\n  async getStorage() {\n    const storage = this.#mastra?.getStorage();\n    if (!storage) {\n      throw new Error('Storage is not initialized');\n    }\n    const bgStore = await storage.getStore('backgroundTasks');\n    if (!bgStore) {\n      throw new Error('Background tasks storage is not available');\n    }\n    return bgStore;\n  }\n\n  async init(pubsub: PubSub): Promise<void> {\n    if (this.shuttingDown) {\n      throw new Error('BackgroundTaskManager is shutting down, cannot initialize');\n    }\n    if (this.initPromise) return this.initPromise;\n    this.initPromise = this.#doInit(pubsub);\n    return this.initPromise;\n  }\n\n  async #doInit(pubsub: PubSub): Promise<void> {\n    this.pubsub = pubsub;\n\n    const isProducerOnly = this.config.mode === 'producer';\n\n    // Result listener: fan-out so all processes receive results.\n    // Both producer and worker modes need this — the producer uses it\n    // to receive completion/failure notifications for dispatched tasks.\n    this.resultCallback = async (event: Event, ack?: () => Promise<void>) => {\n      if (event.type === 'task.completed' || event.type === 'task.failed') {\n        try {\n          await this.handleResult(event);\n        } finally {\n          await ack?.();\n        }\n        return;\n      }\n      if (event.type === 'task.cancelled') {\n        try {\n          await this.handleRemoteCancel(event.data.taskId);\n        } finally {\n          await ack?.();\n        }\n        return;\n      }\n      await ack?.();\n    };\n\n    if (!isProducerOnly) {\n      // Worker: subscribes with group so only one worker processes each task.\n      this.workerCallback = async (event: Event, ack?: () => Promise<void>) => {\n        // A grouped delivery consumed while this process is shutting down must\n        // remain unacked so a durable broker can redeliver it to a live worker.\n        if (this.shuttingDown) return;\n\n        let handled = true;\n        if (event.type === 'task.dispatch' || event.type === 'task.restart') {\n          handled = await this.handleDispatch(event);\n        } else if (event.type === 'task.resume') {\n          // Tracked so shutdown waits for a resume caught mid-preparation to\n          // decline before storage closes.\n          const resuming = this.handleResume(event);\n          this.#trackSettlingRun(resuming);\n          handled = await resuming;\n        } else if (event.type === 'task.cancel') {\n          this.handleCancel(event);\n        }\n        if (handled) await ack?.();\n      };\n\n      // Register the workflow BEFORE subscribing the worker so that any\n      // dispatch event the worker picks up can immediately resolve the\n      // workflow on Mastra. Reversing this order races: a publish that\n      // arrives between `subscribe(TOPIC_DISPATCH)` and the workflow\n      // registration triggers `__getInternalWorkflow` to throw\n      // `Workflow with id __background-task not found`, the task stays at\n      // `running` forever, and the dispatch is silently dropped.\n      if (this.#mastra) {\n        // Dynamic import breaks the static cycle:\n        // agent → background-tasks → manager → workflow → workflows/evented →\n        // workflows/index → agent. Static import works at runtime but during\n        // module evaluation in test environments the cycle leaves `Workflow`\n        // undefined when `evented/workflow.ts` evaluates its `class extends`.\n        const { buildBackgroundTaskWorkflow } = await import('./workflow');\n        const workflow = buildBackgroundTaskWorkflow(this);\n        if (!this.#mastra.__hasInternalWorkflow(BACKGROUND_TASK_WORKFLOW_ID)) {\n          // The `__background-task` workflow is typed against `EventedEngineType`\n          // and a concrete input/output schema, while `__registerInternalWorkflow`\n          // accepts the looser default `Workflow` shape. The cast is purely a\n          // type-level bridge — the runtime value is a real Workflow.\n          this.#mastra.__registerInternalWorkflow(\n            workflow as unknown as Parameters<Mastra['__registerInternalWorkflow']>[0],\n          );\n        }\n      }\n\n      await this.pubsub.subscribe(TOPIC_DISPATCH, this.workerCallback, { group: WORKER_GROUP });\n      await this.pubsub.subscribe(this.processAffineDispatchTopic, this.workerCallback);\n\n      if (this.shuttingDown) {\n        await this.#releaseLateInitSubscriptions([\n          [TOPIC_DISPATCH, this.workerCallback],\n          [this.processAffineDispatchTopic, this.workerCallback],\n        ]);\n        return;\n      }\n\n      if (this.config.recoverStaleTasksOnStart) {\n        // Recover stale tasks from a previous process — only workers should\n        // attempt recovery since they own execution.\n        await this.recoverStaleTasks();\n        this.#startPinSweep();\n      }\n    }\n\n    await this.pubsub.subscribe(TOPIC_RESULT, this.resultCallback);\n    if (this.shuttingDown) {\n      // Producer mode never registers a worker callback, so only include the\n      // dispatch subscriptions when they actually exist.\n      const lateSubscriptions: Array<[string, EventCallback]> = [];\n      if (this.workerCallback) {\n        lateSubscriptions.push([TOPIC_DISPATCH, this.workerCallback]);\n        lateSubscriptions.push([this.processAffineDispatchTopic, this.workerCallback]);\n      }\n      lateSubscriptions.push([TOPIC_RESULT, this.resultCallback]);\n      await this.#releaseLateInitSubscriptions(lateSubscriptions);\n      return;\n    }\n\n    // Start periodic cleanup if configured\n    const cleanupConfig = this.config.cleanup;\n    if (cleanupConfig && !this.shuttingDown) {\n      const intervalMs = cleanupConfig.cleanupIntervalMs ?? 60_000;\n      this.cleanupInterval = setInterval(() => {\n        void this.cleanup().catch(error => {\n          this.#mastra?.getLogger?.()?.warn('Background task cleanup failed:', error);\n        });\n      }, intervalMs);\n    }\n\n    // Renew execution leases while this process owns tasks. Idle managers do\n    // nothing — the handler returns immediately when `ownedLeases` is empty.\n    if (!this.shuttingDown) {\n      this.#startLeaseHeartbeat();\n    }\n  }\n\n  // --- Per-task context registration ---\n\n  /**\n   * Register per-task hooks (executor, stream emitter, result injector).\n   * Called internally by createBackgroundTask or directly for advanced usage.\n   */\n  registerTaskContext(taskId: string, context: TaskContext): void {\n    this.taskContexts.set(taskId, context);\n  }\n\n  /**\n   * Remove per-task hooks. Called after task reaches terminal state.\n   */\n  deregisterTaskContext(taskId: string): void {\n    this.taskContexts.delete(taskId);\n  }\n\n  /** @internal — called by the workflow step immediately before executor invocation. */\n  registerActiveAbortController(taskId: string, controller: AbortController): boolean {\n    if (this.shuttingDown) {\n      controller.abort(new Error(SHUTDOWN_ABORT_MESSAGE));\n      return false;\n    }\n    this.activeAbortControllers.set(taskId, controller);\n    return true;\n  }\n\n  /** @internal — read by workflow error classification during graceful shutdown. */\n  isShuttingDown(): boolean {\n    return this.shuttingDown;\n  }\n\n  /**\n   * Register a tool executor by tool name. Used for cross-process dispatch:\n   * when a worker in a different process picks up a `task.dispatch` event,\n   * it has no per-task closure (`taskContexts`) for that taskId, but it can\n   * resolve the executor by tool name via this registry.\n   */\n  registerStaticExecutor(toolName: string, executor: ToolExecutor): void {\n    if (this.staticExecutors.has(toolName)) {\n      this.#mastra?.getLogger?.()?.debug?.(`Overwriting existing static executor for tool \"${toolName}\"`);\n    }\n    this.staticExecutors.set(toolName, executor);\n  }\n\n  /**\n   * Symmetric to `registerStaticExecutor`. Called when a tool is removed\n   * from `Mastra`.\n   */\n  unregisterStaticExecutor(toolName: string): void {\n    this.staticExecutors.delete(toolName);\n  }\n\n  /**\n   * Look up an executor by tool name. Read by the workflow-step body in\n   * `workflow.ts:runAttemptStep` as a fallback when no per-task `TaskContext`\n   * is registered (cross-process path).\n   */\n  getStaticExecutor(toolName: string): ToolExecutor | undefined {\n    return this.staticExecutors.get(toolName);\n  }\n\n  // --- Core operations ---\n\n  /**\n   * Enqueue a task for background execution.\n   * Prefer `createBackgroundTask()` which returns a self-contained handle.\n   */\n  async enqueue(payload: TaskPayload, context?: TaskContext, options?: EnqueueOptions): Promise<EnqueueResult> {\n    if (this.shuttingDown) {\n      throw new Error('BackgroundTaskManager is shutting down, cannot enqueue new tasks');\n    }\n    const pinned = options?.pinToWorker === true;\n    if (pinned && !context) {\n      // A portable row pinned here would be skipped by every other worker on\n      // the shared dispatch topic while this process holds no closure for it.\n      throw new Error('pinToWorker requires a task context');\n    }\n\n    // Mastra fires `init` as fire-and-forget. If a caller hits enqueue\n    // before init completes, the dispatch publish fires before the worker\n    // subscribes and the event is dropped (or, worse, lands on a worker\n    // whose Mastra hasn't yet registered the bg-task workflow → \"Workflow\n    // with id __background-task not found\"). Await readiness up front.\n    if (this.initPromise) await this.initPromise;\n\n    const createdAt = new Date();\n    const task: BackgroundTask = {\n      id: this.#mastra?.generateId() ?? globalThis.crypto.randomUUID(),\n      status: 'pending',\n      toolName: payload.toolName,\n      toolCallId: payload.toolCallId,\n      args: payload.args,\n      agentId: payload.agentId,\n      threadId: payload.threadId,\n      resourceId: payload.resourceId,\n      runId: payload.runId,\n      retryCount: 0,\n      maxRetries: payload.maxRetries ?? this.config.defaultRetries?.maxRetries ?? 0,\n      timeoutMs: payload.timeoutMs ?? this.config.defaultTimeoutMs,\n      createdAt,\n      ...(payload.expiresAt ? { expiresAt: payload.expiresAt } : {}),\n      ...(payload.metadata ? { metadata: payload.metadata } : {}),\n      ...(pinned\n        ? { ownerId: this.workerId, leaseExpiresAt: new Date(createdAt.getTime() + this.config.leaseDurationMs) }\n        : {}),\n    };\n\n    // Register per-task context if provided\n    if (context) {\n      this.registerTaskContext(task.id, context);\n    }\n\n    const storage = await this.getStorage();\n    await storage.createTask(task);\n    if (pinned) this.pinnedPendingLeases.add(task.id);\n\n    const isProcessAffine = Boolean(context);\n    const canRun = isProcessAffine ? this.reserveLocalSlot(task) : await this.checkConcurrency(task.agentId);\n\n    if (canRun) {\n      try {\n        await this.dispatch(task);\n      } catch (error) {\n        this.pinnedPendingLeases.delete(task.id);\n        const failed = await storage.updateTask(\n          task.id,\n          {\n            status: 'failed',\n            error: { message: error instanceof Error ? error.message : String(error) },\n            completedAt: new Date(),\n            ...(pinned ? { ownerId: undefined, leaseExpiresAt: undefined } : {}),\n          },\n          { expectedStatus: 'pending' },\n        );\n        if (failed) {\n          this.releaseLocalSlot(task.id);\n          this.deregisterTaskContext(task.id);\n          void this.drainPending();\n        }\n        throw error;\n      }\n      return { task };\n    }\n\n    // Backpressure\n    switch (this.config.backpressure) {\n      case 'reject':\n        this.pinnedPendingLeases.delete(task.id);\n        this.deregisterTaskContext(task.id);\n        await storage.deleteTask(task.id);\n        throw new Error(`Concurrency limit reached, cannot enqueue task for tool \"${task.toolName}\"`);\n\n      case 'fallback-sync':\n        this.pinnedPendingLeases.delete(task.id);\n        this.deregisterTaskContext(task.id);\n        await storage.deleteTask(task.id);\n        return { task, fallbackToSync: true };\n\n      case 'queue':\n      default:\n        // Queue ownership stays local. A persisted pending row does not carry\n        // enough information to distinguish an invocation-bound closure from\n        // a portable static executor in another process.\n        this.localPendingTaskIds.add(task.id);\n        return { task };\n    }\n  }\n\n  async cancel(taskId: string): Promise<void> {\n    if (this.initPromise) await this.initPromise;\n    const storage = await this.getStorage();\n    let task = await storage.getTask(taskId);\n    if (!task) {\n      throw new Error(`Task not found: ${taskId}`);\n    }\n\n    while (true) {\n      if (\n        task.status === 'completed' ||\n        task.status === 'failed' ||\n        task.status === 'cancelled' ||\n        task.status === 'timed_out'\n      ) {\n        return; // no-op for terminal states\n      }\n\n      const previousStatus = task.status;\n      const isProcessAffine = this.taskContexts.has(taskId);\n      // Cancellation is an explicit operator action and may arrive from any\n      // process, so it is fenced on status only — but it must drop the lease,\n      // since the task is leaving `running` and no owner should keep renewing.\n      const cancelled = await storage.updateTask(\n        taskId,\n        { status: 'cancelled', completedAt: new Date(), ownerId: undefined, leaseExpiresAt: undefined },\n        { expectedStatus: previousStatus },\n      );\n      if (!cancelled) {\n        task = await storage.getTask(taskId);\n        if (!task) return;\n        continue;\n      }\n      this.ownedLeases.delete(taskId);\n      this.pinnedPendingLeases.delete(taskId);\n      this.localPendingResumes.delete(taskId);\n\n      if (previousStatus === 'pending') {\n        this.localPendingTaskIds.delete(taskId);\n        this.releaseLocalSlot(taskId);\n      }\n\n      if (previousStatus === 'running') {\n        // Abort the running tool\n        const controller = this.activeAbortControllers.get(taskId);\n        if (controller) {\n          controller.abort(new Error('Task cancelled'));\n          this.activeAbortControllers.delete(taskId);\n        }\n      }\n\n      if (previousStatus === 'running' || previousStatus === 'suspended') {\n        // Cancel the workflow run so workflow storage reflects the\n        // cancellation and any stored suspended snapshot is cleaned up.\n        if (this.#mastra) {\n          try {\n            const workflow = this.#mastra.__getInternalWorkflow(BACKGROUND_TASK_WORKFLOW_ID);\n            const wrapper = await workflow.createRun({ runId: taskId });\n            await wrapper.cancel();\n          } catch (err) {\n            this.#mastra?.getLogger?.()?.warn(`background-task workflow cancel failed for ${taskId}:`, err as any);\n          }\n        }\n      }\n\n      const cancelledTask = await storage.getTask(taskId);\n      if (cancelledTask) {\n        await this.publishLifecycleEvent('task.cancelled', cancelledTask);\n        try {\n          await this.config.onTaskCancelled?.(cancelledTask);\n        } catch (error) {\n          this.#mastra\n            ?.getLogger?.()\n            ?.warn(`background-task cancellation callback failed for ${taskId}:`, error as any);\n        }\n        // Cancelling answers nothing, but the open request on the tool call\n        // must go so a client doesn't offer to answer a dead task.\n        if (previousStatus === 'suspended') await this.runLocalExecutionHook(cancelledTask);\n      }\n      this.deregisterTaskContext(taskId);\n\n      if (previousStatus === 'running') {\n        // Route cancellation to the same process that owns an invocation-bound executor.\n        const dispatchTopic = isProcessAffine ? this.processAffineDispatchTopic : TOPIC_DISPATCH;\n        await this.pubsub.publish(dispatchTopic, {\n          type: 'task.cancel',\n          data: { taskId },\n          runId: taskId,\n        });\n      }\n      return;\n    }\n  }\n\n  /**\n   * Resume a suspended task. The tool executor must be re-registered via\n   * `registerTaskContext(taskId, ...)` before calling this if the original\n   * registration is gone (e.g. process restart) — the manager doesn't\n   * rehydrate executor closures from storage.\n   *\n   * `resumeData` is forwarded to the tool's `execute` options on the\n   * resumed run.\n   */\n  async resume(taskId: string, resumeData?: unknown, options?: ResumeOptions): Promise<BackgroundTask> {\n    if (this.shuttingDown) {\n      throw new Error('BackgroundTaskManager is shutting down, cannot resume tasks');\n    }\n    if (!this.#mastra) {\n      throw new Error('Mastra is not registered with this manager');\n    }\n\n    if (this.initPromise) await this.initPromise;\n\n    const storage = await this.getStorage();\n    const task = await storage.getTask(taskId);\n    if (!task) {\n      throw new Error(`Task not found: ${taskId}`);\n    }\n    if (task.status !== 'suspended') {\n      throw new Error(`Cannot resume task in status '${task.status}' (expected 'suspended')`);\n    }\n    if (options?.suspendedAt !== undefined && new Date(options.suspendedAt).getTime() !== suspensionToken(task)) {\n      throw new Error(`Cannot resume task \"${taskId}\": its suspension has changed since it was read`);\n    }\n\n    const isProcessAffine = this.taskContexts.has(taskId);\n    const canRun = isProcessAffine ? this.reserveLocalSlot(task) : await this.checkConcurrency(task.agentId);\n    if (!canRun) {\n      if (options?.onNoSlot === 'queue') {\n        // The row stays `suspended` until a slot frees and `drainPending()`\n        // publishes the resume. Only this process holds the queued resume, so\n        // if it exits first the task is still a resumable suspended row.\n        // The suspension token ties the queued data to this suspension: if the\n        // task is resumed elsewhere and suspends again, the entry is dropped.\n        this.localPendingResumes.set(taskId, { resumeData, suspendedAt: suspensionToken(task) });\n        return task;\n      }\n      // By default resume sits outside the queue/fallback-sync paths — there's\n      // no synchronous caller to fall back to, and silently leaving the task\n      // suspended hides the failure from the caller. Throw and let the\n      // caller retry once a slot frees.\n      throw new Error(`Concurrency limit reached, cannot resume task \"${taskId}\" — retry once a slot is available`);\n    }\n\n    this.localPendingResumes.delete(taskId);\n    await this.#publishResume(task, resumeData, isProcessAffine);\n    return task;\n  }\n\n  async #publishResume(task: BackgroundTask, resumeData: unknown, isProcessAffine: boolean): Promise<void> {\n    const taskId = task.id;\n    if (this.shuttingDown) {\n      if (isProcessAffine) this.releaseLocalSlot(taskId);\n      throw new Error('BackgroundTaskManager is shutting down, cannot resume tasks');\n    }\n    // Resume publishes directly (not via dispatch()), so it needs its own\n    // lazy worker start for the library-mode process-restart case.\n    await this.#ensureExecutionWorkersStarted();\n\n    // Resume invocation-bound executors on their owning manager. A task\n    // without local context remains portable through the shared worker group.\n    const dispatchTopic = isProcessAffine ? this.processAffineDispatchTopic : TOPIC_DISPATCH;\n    try {\n      await this.pubsub.publish(dispatchTopic, {\n        type: 'task.resume',\n        data: { taskId, resumeData, suspendedAt: suspensionToken(task) },\n        runId: taskId,\n      });\n    } catch (error) {\n      if (isProcessAffine) this.releaseLocalSlot(taskId);\n      throw error;\n    }\n    if (!isProcessAffine) {\n      this.inFlightPortableResumes.set(taskId, {\n        agentId: task.agentId,\n        suspendedAt: suspensionToken(task),\n        until: Date.now() + this.config.leaseDurationMs,\n      });\n    }\n  }\n\n  /**\n   * Re-dispatches a previously pending or running task. The tool executor is\n   * re-registered via `registerTaskContext(taskId, ...)` because the original\n   * registration is gone (e.g. process restart) — the manager doesn't\n   * rehydrate executor closures from storage.\n   *\n   * Restarting a `running` task is an explicit takeover: the claim is fenced on\n   * status only, so it succeeds even while another manager holds a live lease.\n   * The previous owner's next renewal fails and aborts its run, but that run\n   * may overlap this one until then.\n   */\n  async restart(taskId: string, context?: TaskContext): Promise<BackgroundTask> {\n    if (this.shuttingDown) {\n      throw new Error('BackgroundTaskManager is shutting down, cannot restart tasks');\n    }\n    if (!this.#mastra) {\n      throw new Error('Mastra is not registered with this manager');\n    }\n\n    if (this.initPromise) await this.initPromise;\n\n    const storage = await this.getStorage();\n    const task = await storage.getTask(taskId);\n    if (!task) {\n      throw new Error(`Task not found: ${taskId}`);\n    }\n    if (task.status !== 'pending' && task.status !== 'running') {\n      throw new Error(`Cannot restart task in status '${task.status}' (expected 'pending' or 'running')`);\n    }\n    const isRestart = task.status === 'running';\n\n    if (context) {\n      this.registerTaskContext(task.id, context);\n    }\n\n    const isProcessAffine = this.taskContexts.has(taskId);\n    const canRun = isProcessAffine ? this.reserveLocalSlot(task) : await this.checkConcurrency(task.agentId);\n    if (!canRun) {\n      // Restart sits outside the queue/fallback-sync paths — there's no\n      // synchronous caller to fall back to, and silently leaving the task\n      // running hides the failure from the caller. Throw and let the\n      // caller retry once a slot frees.\n      throw new Error(`Concurrency limit reached, cannot restart task \"${taskId}\" — retry once a slot is available`);\n    }\n\n    try {\n      await this.dispatch(task, isRestart);\n    } catch (error) {\n      if (isProcessAffine) this.releaseLocalSlot(taskId);\n      throw error;\n    }\n\n    return task;\n  }\n\n  async getTask(taskId: string): Promise<BackgroundTask | null> {\n    const storage = await this.getStorage();\n    return storage.getTask(taskId);\n  }\n\n  async listTasks(filter: TaskFilter = {}): Promise<TaskListResult> {\n    const storage = await this.getStorage();\n    return storage.listTasks(filter);\n  }\n\n  /**\n   * Deletes old completed/failed/cancelled/timed_out task records from storage.\n   */\n  async cleanup(): Promise<void> {\n    const completedTtlMs = this.config.cleanup?.completedTtlMs ?? 3_600_000;\n    const failedTtlMs = this.config.cleanup?.failedTtlMs ?? 86_400_000;\n    const now = Date.now();\n\n    const storage = await this.getStorage();\n    if (!storage.supportsTaskExpiry) {\n      // Adapters written before `expiresAt` existed ignore `hasExpiresAt` and\n      // treat an unknown `dateFilterBy` as `createdAt`, so the expiry pass\n      // would delete every finished row. Keep the global TTLs only.\n      await storage.deleteTasks({\n        status: ['completed'],\n        toDate: new Date(now - completedTtlMs),\n        dateFilterBy: 'completedAt',\n      });\n      await storage.deleteTasks({\n        status: ['failed', 'cancelled', 'timed_out'],\n        toDate: new Date(now - failedTtlMs),\n        dateFilterBy: 'completedAt',\n      });\n      return;\n    }\n    // Rows with their own `expiresAt` are retained until that deadline instead\n    // of the global TTLs. Only terminal rows are deleted, so a live row is never\n    // removed from under its lease owner.\n    await storage.deleteTasks({\n      status: ['completed', 'failed', 'cancelled', 'timed_out'],\n      toDate: new Date(now),\n      dateFilterBy: 'expiresAt',\n    });\n\n    await storage.deleteTasks({\n      status: ['completed'],\n      hasExpiresAt: false,\n      toDate: new Date(now - completedTtlMs),\n      dateFilterBy: 'completedAt',\n    });\n\n    await storage.deleteTasks({\n      status: ['failed', 'cancelled', 'timed_out'],\n      hasExpiresAt: false,\n      toDate: new Date(now - failedTtlMs),\n      dateFilterBy: 'completedAt',\n    });\n  }\n\n  /**\n   * Returns a promise that resolves when the next task from the given set\n   * reaches a terminal state.\n   */\n  async waitForNextTask(\n    taskIds: string[],\n    options?: {\n      timeoutMs?: number;\n      onProgress?: (elapsedMs: number) => void;\n      progressIntervalMs?: number;\n      abortSignal?: AbortSignal;\n    },\n  ): Promise<BackgroundTask> {\n    const storage = await this.getStorage();\n\n    const isTerminal = (status: string) =>\n      status === 'completed' || status === 'failed' || status === 'cancelled' || status === 'timed_out';\n\n    for (const id of taskIds) {\n      const task = await storage.getTask(id);\n      if (task && isTerminal(task.status)) {\n        return task;\n      }\n    }\n\n    return new Promise((resolve, reject) => {\n      const startTime = Date.now();\n      let timeout: ReturnType<typeof setTimeout> | undefined;\n      let progressInterval: ReturnType<typeof setInterval> | undefined;\n      let pollInterval: ReturnType<typeof setInterval> | undefined;\n\n      const cleanup = () => {\n        if (pollInterval) clearInterval(pollInterval);\n        if (timeout) clearTimeout(timeout);\n        if (progressInterval) clearInterval(progressInterval);\n        options?.abortSignal?.removeEventListener('abort', handleAbort);\n      };\n      const handleAbort = () => {\n        cleanup();\n        reject(options?.abortSignal?.reason ?? new Error('Background task wait aborted'));\n      };\n\n      if (options?.abortSignal?.aborted) {\n        handleAbort();\n        return;\n      }\n      options?.abortSignal?.addEventListener('abort', handleAbort, { once: true });\n\n      timeout = options?.timeoutMs\n        ? setTimeout(() => {\n            cleanup();\n            reject(new Error('Timed out waiting for background task'));\n          }, options.timeoutMs)\n        : undefined;\n\n      progressInterval = options?.onProgress\n        ? setInterval(() => {\n            options.onProgress!(Date.now() - startTime);\n          }, options.progressIntervalMs ?? 3000)\n        : undefined;\n\n      pollInterval = setInterval(async () => {\n        for (const id of taskIds) {\n          const task = await storage.getTask(id);\n          if (task && isTerminal(task.status)) {\n            cleanup();\n            resolve(task);\n            return;\n          }\n        }\n      }, 50);\n    });\n  }\n\n  /**\n   * Returns a ReadableStream of all background task lifecycle events,\n   * filtered by optional criteria. Intended to be piped directly to an SSE response.\n   *\n   * On connection, emits the current state of all non-terminal tasks as a snapshot,\n   * then subscribes to live pubsub events for subsequent updates.\n   *\n   * Events include:\n   * - `task.running` (status: 'running') — task picked up by a worker\n   * - `task.completed` (status: 'completed') — task finished successfully\n   * - `task.failed` (status: 'failed' or 'timed_out') — task errored or timed out\n   * - `task.cancelled` (status: 'cancelled') — task was cancelled\n   * - `task.suspended` (status: 'suspended') — task paused via `suspend()` from\n   *   inside its tool executor; resume with `manager.resume(taskId, data)`\n   * - `task.resumed` (status: 'running') — suspended task resumed\n   *\n   * The stream stays open until the caller's AbortSignal fires (client disconnect).\n   *\n   * Events are scoped to a resource: when `resourceId` is omitted, only tasks without a\n   * `resourceId` are delivered. Pass `allResources: true` to receive events for every\n   * resource (privileged consumers only — payloads include task args and results).\n   */\n  stream(options?: {\n    agentId?: string;\n    runId?: string;\n    threadId?: string;\n    resourceId?: string;\n    taskId?: string;\n    abortSignal?: AbortSignal;\n    includeExisting?: boolean;\n    allResources?: boolean;\n  }): ReadableStream<Record<string, unknown>> {\n    const manager = this;\n    const pubsub = this.pubsub;\n    const {\n      agentId,\n      runId,\n      threadId,\n      resourceId,\n      abortSignal,\n      taskId,\n      includeExisting = true,\n      allResources = false,\n    } = options ?? {};\n    const matchesResource = (taskResourceId: string | null | undefined) => {\n      if (resourceId !== undefined) return taskResourceId === resourceId;\n      return allResources || taskResourceId == null;\n    };\n\n    const EVENT_STATUS_MAP: Record<string, BackgroundTaskStatus> = {\n      'task.running': 'running',\n      'task.output': 'running',\n      'task.completed': 'completed',\n      'task.failed': 'failed',\n      'task.cancelled': 'cancelled',\n      'task.suspended': 'suspended',\n      'task.resumed': 'running',\n    };\n\n    const CHUNK_EVENT_MAP: Record<string, string> = {\n      'task.running': 'background-task-running',\n      'task.output': 'background-task-output',\n      'task.completed': 'background-task-completed',\n      'task.failed': 'background-task-failed',\n      'task.cancelled': 'background-task-cancelled',\n      'task.suspended': 'background-task-suspended',\n      'task.resumed': 'background-task-resumed',\n    };\n\n    return new ReadableStream({\n      async start(controller) {\n        // 1. Subscribe to live events first (so we don't miss anything between snapshot and subscribe)\n        const handler = async (event: Event) => {\n          const status = EVENT_STATUS_MAP[event.type];\n          if (!status) return;\n\n          const data = event.data;\n          if (agentId && data.agentId !== agentId) return;\n          if (runId && data.runId !== runId) return;\n          if (threadId && data.threadId !== threadId) return;\n          if (!matchesResource(data.resourceId)) return;\n          if (taskId && data.taskId !== taskId) return;\n\n          const payload: Record<string, unknown> = {\n            taskId: data.taskId,\n            toolName: data.toolName,\n            toolCallId: data.toolCallId,\n            agentId: data.agentId,\n            runId: data.runId,\n          };\n\n          switch (event.type) {\n            case 'task.running':\n              payload.startedAt = data.startedAt;\n              payload.args = data.args;\n              break;\n            case 'task.completed':\n              payload.completedAt = data.completedAt;\n              payload.result = data.result;\n              break;\n            case 'task.failed':\n              payload.completedAt = data.completedAt;\n              payload.error = data.error;\n              break;\n            case 'task.cancelled':\n              payload.completedAt = data.completedAt;\n              break;\n            case 'task.output':\n              payload.payload = data.chunk;\n              break;\n            case 'task.suspended':\n              payload.suspendPayload = data.suspendPayload;\n              payload.suspendedAt = data.suspendedAt;\n              payload.args = data.args;\n              break;\n            case 'task.resumed':\n              payload.startedAt = data.startedAt;\n              payload.args = data.args;\n              break;\n          }\n\n          try {\n            controller.enqueue({\n              type: CHUNK_EVENT_MAP[event.type],\n              payload,\n            });\n          } catch {\n            // Controller closed\n          }\n        };\n\n        await pubsub.subscribe(TOPIC_RESULT, handler);\n\n        const close = () => {\n          void pubsub.unsubscribe(TOPIC_RESULT, handler);\n          try {\n            controller.close();\n          } catch {\n            // Already closed\n          }\n        };\n        if (abortSignal?.aborted) {\n          close();\n          return;\n        }\n        abortSignal?.addEventListener('abort', close, { once: true });\n\n        // 2. Emit snapshot of existing in-flight tasks (running + suspended).\n        if (!includeExisting) return;\n        try {\n          const storage = await manager.getStorage();\n          if (taskId) {\n            const task = await storage.getTask(taskId);\n            if (task && task.status === 'running' && matchesResource(task.resourceId)) {\n              controller.enqueue({\n                type: 'background-task-running',\n                payload: {\n                  taskId: task.id,\n                  toolName: task.toolName,\n                  toolCallId: task.toolCallId,\n                  agentId: task.agentId,\n                  runId: task.runId,\n                  startedAt: task.startedAt,\n                  args: task.args,\n                },\n              });\n            }\n          } else {\n            const { tasks: existing } = await storage.listTasks({\n              agentId,\n              runId,\n              threadId,\n              resourceId,\n              status: ['running'],\n            });\n\n            for (const task of existing) {\n              if (abortSignal?.aborted) break;\n              if (!matchesResource(task.resourceId)) continue;\n              try {\n                controller.enqueue({\n                  type: 'background-task-running',\n                  payload: {\n                    taskId: task.id,\n                    toolName: task.toolName,\n                    toolCallId: task.toolCallId,\n                    agentId: task.agentId,\n                    runId: task.runId,\n                    startedAt: task.startedAt,\n                    args: task.args,\n                  },\n                });\n              } catch {\n                break;\n              }\n            }\n          }\n        } catch {\n          // Storage not available — continue with live events only\n        }\n      },\n    });\n  }\n\n  /**\n   * @param options.deadline - Absolute wall-clock deadline (ms since epoch) to\n   *   bound teardown by. `Mastra.shutdown()` passes the deadline shared with\n   *   its workflow drain so the two do not stack. Defaults to\n   *   `SHUTDOWN_GRACE_PERIOD_MS` from now when called standalone.\n   */\n  shutdown(options?: { deadline?: number }): Promise<void> {\n    if (this.shutdownPromise) return this.shutdownPromise;\n    this.shuttingDown = true;\n    this.shutdownDeadline = options?.deadline ?? Date.now() + SHUTDOWN_GRACE_PERIOD_MS;\n    this.shutdownPromise = this.#shutdown();\n    return this.shutdownPromise;\n  }\n\n  async #shutdown(): Promise<void> {\n    // Stop an already-running cleanup loop immediately. Init may still be in\n    // flight and install one later, so repeat this check after awaiting it.\n    if (this.cleanupInterval) {\n      clearInterval(this.cleanupInterval);\n      this.cleanupInterval = undefined;\n    }\n\n    // `Mastra` starts init without awaiting it. Give initialization a bounded\n    // chance to settle; if it completes later, #doInit observes shuttingDown\n    // and releases any subscription it installed after this teardown pass.\n    // Initialization failures are handled by Mastra's original init catch.\n    if (this.initPromise) {\n      await this.#waitForShutdownStep(\n        'background task manager initialization',\n        this.initPromise.catch(() => {}),\n      );\n    }\n\n    // Abort user code first, without waiting on storage or a remote broker.\n    // Retryable running tasks intentionally remain `running` in storage so\n    // the next process can recover them through recoverStaleTasks(). Tasks\n    // without retries retain the existing terminal cancellation behavior.\n    // Snapshot the held leases now: waiting for runs to settle below removes\n    // them from `ownedLeases`, but their leases still need handing back.\n    const leasesToRelease = new Set(this.ownedLeases);\n    const activeTaskIds = [...this.activeAbortControllers.keys()];\n    this.#abortActiveControllers();\n    const cancellationResults = await this.#waitForShutdownStep(\n      'background task cancellation',\n      Promise.allSettled(activeTaskIds.map(taskId => this.#cancelTaskForShutdown(taskId))),\n    );\n    cancellationResults?.forEach((result, index) => {\n      if (result.status === 'rejected') {\n        this.#mastra\n          ?.getLogger?.()\n          ?.warn(`Failed to cancel background task ${activeTaskIds[index]} during shutdown:`, result.reason as any);\n      }\n    });\n\n    // Aborted runs settle asynchronously and then delete their workflow run.\n    // Let them finish while storage is still open — Mastra closes it as soon\n    // as this returns. Re-snapshot because a settling run adds its delete.\n    const awaitedRuns = new Set<Promise<unknown>>();\n    for (;;) {\n      const pending = [...this.#settlingRuns].filter(run => !awaitedRuns.has(run));\n      if (pending.length === 0) break;\n      pending.forEach(run => awaitedRuns.add(run));\n      const settled = await this.#waitForShutdownStep('background task run settlement', Promise.allSettled(pending));\n      if (!settled) break;\n    }\n\n    if (this.cleanupInterval) {\n      clearInterval(this.cleanupInterval);\n      this.cleanupInterval = undefined;\n    }\n\n    const subscriptions: Array<[string, EventCallback]> = [];\n    if (this.workerCallback) {\n      subscriptions.push([TOPIC_DISPATCH, this.workerCallback]);\n      subscriptions.push([this.processAffineDispatchTopic, this.workerCallback]);\n    }\n    if (this.resultCallback) subscriptions.push([TOPIC_RESULT, this.resultCallback]);\n    const unsubscribeResults = await this.#waitForShutdownStep(\n      'background task subscription cleanup',\n      Promise.allSettled(subscriptions.map(([topic, callback]) => this.pubsub.unsubscribe(topic, callback))),\n    );\n    unsubscribeResults?.forEach((result, index) => {\n      if (result.status === 'rejected') {\n        this.#mastra\n          ?.getLogger?.()\n          ?.warn(\n            `Failed to unsubscribe from ${subscriptions[index]?.[0]} during background task shutdown:`,\n            result.reason,\n          );\n      }\n    });\n\n    // Defensive final sweep for any workflow attempt that was already between\n    // awaits when shutdown began. New registrations are rejected atomically by\n    // registerActiveAbortController().\n    this.#abortActiveControllers();\n\n    this.taskContexts.clear();\n    this.localReservations.clear();\n    this.localPendingTaskIds.clear();\n    this.localPendingResumes.clear();\n    this.inFlightPortableResumes.clear();\n    this.staticExecutors.clear();\n\n    // Stop renewing leases and hand back the ones still held so another worker\n    // can recover and re-run those tasks immediately instead of waiting for the\n    // lease to expire. Best-effort: storage may already be gone.\n    if (this.heartbeatInterval) {\n      clearInterval(this.heartbeatInterval);\n      this.heartbeatInterval = undefined;\n    }\n    if (this.staleRecoveryTimeout) {\n      clearTimeout(this.staleRecoveryTimeout);\n      this.staleRecoveryTimeout = undefined;\n    }\n    if (this.pinSweepInterval) {\n      clearInterval(this.pinSweepInterval);\n      this.pinSweepInterval = undefined;\n    }\n    for (const taskId of this.ownedLeases) leasesToRelease.add(taskId);\n    this.ownedLeases.clear();\n    if (leasesToRelease.size > 0) {\n      const ownedTaskIds = [...leasesToRelease];\n      try {\n        const storage = await this.getStorage();\n        // Fenced on `ownerId` so a task already reclaimed or finished elsewhere\n        // is left alone. Bounded by the shared shutdown deadline so a slow store\n        // cannot stall teardown; any lease left unreleased expires on its own.\n        await this.#waitForShutdownStep(\n          'background task lease release',\n          Promise.allSettled(\n            ownedTaskIds.map(taskId =>\n              storage.updateTask(\n                taskId,\n                { ownerId: undefined, leaseExpiresAt: undefined },\n                { expectedOwnerId: this.workerId },\n              ),\n            ),\n          ),\n        );\n      } catch {\n        // Storage unavailable — leases expire on their own.\n      }\n    }\n    if (this.pinnedPendingLeases.size > 0) {\n      const pinnedTaskIds = [...this.pinnedPendingLeases];\n      this.pinnedPendingLeases.clear();\n      try {\n        const storage = await this.getStorage();\n        // Expire the lease but keep the owner: the work this pin stood for is\n        // abandoned, so peers recover the row now as a lost attempt (consuming a\n        // retry or failing) rather than as fresh, never-run work.\n        await this.#waitForShutdownStep(\n          'background task pinned lease release',\n          Promise.allSettled(\n            pinnedTaskIds.map(taskId =>\n              storage.updateTask(\n                taskId,\n                { leaseExpiresAt: new Date() },\n                { expectedStatus: 'pending', expectedOwnerId: this.workerId },\n              ),\n            ),\n          ),\n        );\n      } catch {\n        // Storage unavailable — leases expire on their own.\n      }\n    }\n    if (this.initPromise) {\n      await this.#waitForShutdownStep('background task pubsub flush', this.pubsub.flush());\n    }\n  }\n\n  async #cancelTaskForShutdown(taskId: string): Promise<void> {\n    const storage = await this.getStorage();\n    const task = await storage.getTask(taskId);\n    if (task?.status === 'running' && task.maxRetries > 0) return;\n    await this.cancel(taskId);\n  }\n\n  #abortActiveControllers(): void {\n    for (const controller of this.activeAbortControllers.values()) {\n      controller.abort(new Error(SHUTDOWN_ABORT_MESSAGE));\n    }\n    this.activeAbortControllers.clear();\n  }\n\n  /**\n   * Await one teardown step against the shutdown-wide deadline. Callers pass an\n   * already-started promise, so a step that finds the budget spent still runs —\n   * it just stops blocking the rest of teardown, which keeps cleanup\n   * best-effort while bounding `#shutdown()` as a whole.\n   */\n  async #waitForShutdownStep<T>(description: string, promise: Promise<T>): Promise<T | undefined> {\n    const remainingMs = this.#remainingShutdownBudgetMs();\n    if (remainingMs <= 0) {\n      void promise.catch(() => {});\n      this.#mastra?.getLogger?.()?.warn(`${description} left running in the background: the shutdown budget is spent`);\n      return undefined;\n    }\n\n    let timeoutHandle: ReturnType<typeof setTimeout> | undefined;\n    let outcome: { status: 'settled'; value: T } | { status: 'timed-out' };\n    try {\n      outcome = await Promise.race([\n        promise.then(value => ({ status: 'settled' as const, value })),\n        new Promise<{ status: 'timed-out' }>(resolve => {\n          timeoutHandle = setTimeout(() => resolve({ status: 'timed-out' }), remainingMs);\n        }),\n      ]);\n    } catch (error) {\n      this.#mastra?.getLogger?.()?.warn(`${description} failed during shutdown:`, error as any);\n      return undefined;\n    } finally {\n      if (timeoutHandle) clearTimeout(timeoutHandle);\n    }\n\n    if (outcome.status === 'timed-out') {\n      this.#mastra\n        ?.getLogger?.()\n        ?.warn(`${description} exhausted the remaining ${remainingMs}ms of the graceful shutdown budget`);\n      return undefined;\n    }\n    return outcome.value;\n  }\n\n  #remainingShutdownBudgetMs(): number {\n    // No deadline means this ran outside `shutdown()`; fall back to the full\n    // budget rather than treating the step as already expired.\n    if (this.shutdownDeadline === undefined) return SHUTDOWN_GRACE_PERIOD_MS;\n    return this.shutdownDeadline - Date.now();\n  }\n\n  async #releaseLateInitSubscriptions(subscriptions: Array<[string, EventCallback]>): Promise<void> {\n    const results = await this.#waitForShutdownStep(\n      'late background task subscription cleanup',\n      Promise.allSettled(subscriptions.map(([topic, callback]) => this.pubsub.unsubscribe(topic, callback))),\n    );\n    results?.forEach((result, index) => {\n      if (result.status === 'rejected') {\n        this.#mastra\n          ?.getLogger?.()\n          ?.warn(`Failed to release late ${subscriptions[index]?.[0]} subscription after shutdown:`, result.reason);\n      }\n    });\n  }\n\n  // --- Internal ---\n\n  /**\n   * Lazily start Mastra's execution workers before publishing. In \"library\n   * mode\" nothing ever calls `mastra.startWorkers()`, so the evented\n   * `__background-task` workflow started by `handleDispatch` would publish\n   * to the `workflows` topic with no consumer and the task would sit at\n   * `running` forever (#19339). A no-op once workers are running; honors the\n   * `workers: false` / `MASTRA_WORKERS` opt-outs.\n   *\n   * Startup failures are logged but don't abort the publish — in distributed\n   * topologies a remote worker on the shared broker can still pick the task\n   * up, and throwing here would also abort `drainPending()` /\n   * `recoverStaleTasks()` loops.\n   */\n  async #ensureExecutionWorkersStarted(): Promise<void> {\n    if (this.shuttingDown) return;\n    if (!this.#mastra) return;\n    try {\n      await this.#mastra.__ensureExecutionWorkersStarted();\n    } catch (err) {\n      this.#mastra.getLogger?.()?.error('Failed to start execution workers for background task', err as any);\n    }\n  }\n\n  private async dispatch(task: BackgroundTask, isRestart?: boolean): Promise<void> {\n    if (this.shuttingDown) return;\n    await this.#ensureExecutionWorkersStarted();\n\n    // Invocation-bound executors are closures owned by this manager and cannot\n    // run in another process. Static executors remain portable and use the\n    // shared competing-consumer topic.\n    const dispatchTopic = this.taskContexts.has(task.id) ? this.processAffineDispatchTopic : TOPIC_DISPATCH;\n    await this.pubsub.publish(dispatchTopic, {\n      type: 'task.dispatch',\n      data: {\n        taskId: task.id,\n        toolName: task.toolName,\n        toolCallId: task.toolCallId,\n        args: task.args,\n        agentId: task.agentId,\n        threadId: task.threadId,\n        resourceId: task.resourceId,\n        timeoutMs: task.timeoutMs,\n        maxRetries: task.maxRetries,\n        runId: task.runId,\n        isRestart,\n      },\n      runId: task.id,\n    });\n  }\n\n  /**\n   * Handles a task.dispatch and task.restart events.\n   * Both events are similar, but the latter is used to restart a running task.\n   */\n  private async handleDispatch(event: Event): Promise<boolean> {\n    if (this.shuttingDown) return false;\n    const { taskId, isRestart } = event.data;\n    const deliveryAttempt = event.deliveryAttempt ?? 1;\n\n    const storage = await this.getStorage();\n    if (this.shuttingDown) return false;\n    const task = await storage.getTask(taskId);\n    if (this.shuttingDown) return false;\n    if (!task || task.status === 'cancelled') {\n      this.releaseLocalSlot(taskId);\n      this.deregisterTaskContext(taskId);\n      return true;\n    }\n\n    const isRunningRedelivery = task.status === 'running' && deliveryAttempt > 1;\n    const canDispatch = isRestart ? task.status === 'running' : task.status === 'pending' || isRunningRedelivery;\n\n    if (!canDispatch) {\n      // The task moved to a state this delivery cannot start. Acknowledge the\n      // stale event without clearing its context: suspended tasks still need\n      // that context to resume, and terminal result hooks may still be running.\n      return true;\n    }\n\n    if (isRunningRedelivery && task.leaseExpiresAt && task.leaseExpiresAt.getTime() > Date.now()) {\n      // The task still holds a live lease, so its owner is presumed alive and\n      // reclaiming it here would double-run the task. A duplicate delivery for a\n      // run this worker already tracks is acknowledged; any other case is left\n      // unacked so the broker redelivers it once the lease lapses and the task\n      // can be recovered by a live owner.\n      return task.ownerId === this.workerId;\n    }\n\n    if (task.status === 'pending' && task.ownerId && task.ownerId !== this.workerId) {\n      // Pinned to another worker (`pinToWorker`), which holds the work for it.\n      // Claiming it here would run the task twice. If that worker dies, stale\n      // recovery accounts for the lost attempt and re-dispatches the row.\n      return true;\n    }\n    // A row pinned to this worker is claimed fenced on the owner alone: the\n    // heartbeat may renew its lease between the read above and this write.\n    const pinnedHere = task.status === 'pending' && task.ownerId === this.workerId;\n\n    // A broker redelivery only counts against the retry budget when a previous\n    // delivery actually started execution (the task was marked `running`, e.g.\n    // the worker crashed mid-run). A dispatch declined cleanly during shutdown\n    // leaves the task `pending`, so the worker that picks up the redelivery\n    // still gets the full retry budget.\n    const retryCount = task.status === 'running' ? deliveryAttempt - 1 : task.retryCount;\n    // Claim execution ownership with an expiring lease. The compare-and-set on\n    // the previously observed owner/lease fences concurrent dispatchers: when\n    // two workers race for the same pending task, only the first claim wins and\n    // the loser acknowledges without starting a second execution. An explicit\n    // restart skips the owner fence — the caller is deliberately asking this\n    // worker to take the task over from whoever ran it before.\n    const now = new Date();\n    const started = await storage.updateTask(\n      taskId,\n      {\n        status: 'running',\n        startedAt: now,\n        retryCount,\n        ownerId: this.workerId,\n        leaseExpiresAt: new Date(now.getTime() + this.config.leaseDurationMs),\n      },\n      isRestart\n        ? { expectedStatus: task.status }\n        : pinnedHere\n          ? { expectedStatus: 'pending', expectedOwnerId: this.workerId }\n          : {\n              expectedStatus: task.status,\n              expectedOwnerId: task.ownerId ?? null,\n              expectedLeaseExpiresAt: task.leaseExpiresAt ?? null,\n            },\n    );\n    if (!started) return true;\n    this.pinnedPendingLeases.delete(taskId);\n    this.ownedLeases.add(taskId);\n    if (this.shuttingDown) return false;\n\n    // Publish running lifecycle event (fan-out, for stream consumers)\n    const runningTask = await storage.getTask(taskId);\n    if (!runningTask || runningTask.status !== 'running') return true;\n    await this.publishLifecycleEvent('task.running', runningTask);\n    if (this.shuttingDown) return false;\n\n    // Fire-and-forget the workflow run; the workflow step body owns\n    // executor invocation, retries, and suspend/resume. The local\n    // execution hook still runs here so callers see `onExecution` fire.\n    if (!this.#mastra) {\n      this.releaseLocalSlot(taskId);\n      this.ownedLeases.delete(taskId);\n      const markedFailed = await storage.updateTask(\n        taskId,\n        {\n          status: 'failed',\n          error: { message: 'Mastra is not registered with this background task manager' },\n          completedAt: new Date(),\n          ownerId: undefined,\n          leaseExpiresAt: undefined,\n        },\n        { expectedStatus: 'running', expectedOwnerId: this.workerId },\n      );\n      if (markedFailed) {\n        const failedTask = await storage.getTask(taskId);\n        if (failedTask?.status === 'failed') await this.publishLifecycleEvent('task.failed', failedTask);\n      }\n      void this.drainPending();\n      return true;\n    }\n\n    try {\n      if (runningTask) void this.runLocalExecutionHook(runningTask);\n      const workflow = this.#mastra.__getInternalWorkflow(BACKGROUND_TASK_WORKFLOW_ID);\n      const prevWorkflowRun = isRestart ? await workflow.getWorkflowRunById(taskId) : undefined;\n      if (this.shuttingDown) return false;\n      const shouldRestart = isRestart && prevWorkflowRun?.status === 'running';\n      const run = await workflow.createRun({ runId: taskId });\n      if (this.shuttingDown) return false;\n      const runPromise = shouldRestart ? run.restart() : run.start({ inputData: { taskId } });\n      const action = shouldRestart ? 'restart' : 'start';\n      this.#trackSettlingRun(\n        runPromise\n          .then(\n            result => {\n              if (result.status !== 'suspended') {\n                this.#deleteSettledRun(workflow, taskId);\n              }\n              if (result.status !== 'success' && result.status !== 'suspended') {\n                return this.failUnsettledTask(taskId, action, workflowRunError(result));\n              }\n            },\n            err => this.failUnsettledTask(taskId, action, err),\n          )\n          .finally(() => {\n            // The run has settled (suspended or terminal), so this worker no\n            // longer owns the lease: stop renewing it.\n            this.ownedLeases.delete(taskId);\n            this.releaseLocalSlot(taskId);\n            void this.drainPending();\n          }),\n      );\n    } catch (error) {\n      this.releaseLocalSlot(taskId);\n      this.ownedLeases.delete(taskId);\n      const markedFailed = await storage.updateTask(\n        taskId,\n        {\n          status: 'failed',\n          error: { message: error instanceof Error ? error.message : String(error) },\n          completedAt: new Date(),\n          ownerId: undefined,\n          leaseExpiresAt: undefined,\n        },\n        { expectedStatus: 'running', expectedOwnerId: this.workerId },\n      );\n      if (markedFailed) {\n        const failedTask = await storage.getTask(taskId);\n        if (failedTask?.status === 'failed') await this.publishLifecycleEvent('task.failed', failedTask);\n      }\n      void this.drainPending();\n    }\n    return true;\n  }\n\n  /**\n   * Handles a task.resume event. Mirrors the workflow branch of handleDispatch\n   * but resumes an existing run from its suspended snapshot instead of starting\n   * a fresh one. Concurrency gating, suspended-status validation, and the\n   * `task.resumed` lifecycle publish all happen here so a different process\n   * than the one that suspended the task can drive the resume.\n   */\n  private async handleResume(event: Event): Promise<boolean> {\n    if (this.shuttingDown) return false;\n    const { taskId, resumeData } = event.data;\n    // The suspension this event answers. Absent on events published by an\n    // older version, which fall back to the status-only check.\n    const answers: number | null | undefined = event.data.suspendedAt;\n    this.inFlightPortableResumes.delete(taskId);\n\n    const storage = await this.getStorage();\n    if (this.shuttingDown) return false;\n    const task = await storage.getTask(taskId);\n    if (this.shuttingDown) return false;\n    if (!task || task.status !== 'suspended' || (answers !== undefined && suspensionToken(task) !== answers)) {\n      // Either gone, already resumed/cancelled by another worker, or resumed\n      // and suspended again — this event's data answers an earlier\n      // suspension. Drop it.\n      this.releaseLocalSlot(taskId);\n      void this.drainPending();\n      return true;\n    }\n\n    const resumed = await storage.updateTask(\n      taskId,\n      {\n        status: 'running',\n        startedAt: new Date(),\n        suspendPayload: undefined,\n        suspendedAt: undefined,\n        ownerId: this.workerId,\n        leaseExpiresAt: new Date(Date.now() + this.config.leaseDurationMs),\n      },\n      { expectedStatus: 'suspended', expectedSuspendedAt: task.suspendedAt ?? null },\n    );\n    if (!resumed) {\n      this.releaseLocalSlot(taskId);\n      void this.drainPending();\n      return true;\n    }\n    // This suspension is answered; a resume queued here for it is now stale.\n    this.localPendingResumes.delete(taskId);\n    this.ownedLeases.add(taskId);\n    const resumedTask = await storage.getTask(taskId);\n    if (resumedTask) {\n      await this.publishLifecycleEvent('task.resumed', resumedTask);\n      // The suspension is answered: let the caller drop its open request from\n      // the tool call before the run can suspend again.\n      await this.runLocalExecutionHook(resumedTask);\n    }\n\n    if (!this.#mastra) {\n      this.releaseLocalSlot(taskId);\n      void this.drainPending();\n      return true;\n    }\n    const workflow = this.#mastra.__getInternalWorkflow(BACKGROUND_TASK_WORKFLOW_ID);\n    // `createRun({ runId })` reattaches to the existing snapshot when given a\n    // stable runId — we don't want a fresh run.\n    const run = await workflow.createRun({ runId: taskId });\n    if (this.shuttingDown) {\n      // Starting the run now would outlive shutdown and leave the task\n      // `running`, where recovery restarts it from scratch. Put it back to\n      // `suspended` and leave the event unacked so the resume can be retried.\n      this.ownedLeases.delete(taskId);\n      this.releaseLocalSlot(taskId);\n      await storage\n        .updateTask(\n          taskId,\n          {\n            status: 'suspended',\n            startedAt: task.startedAt,\n            suspendPayload: task.suspendPayload,\n            suspendedAt: task.suspendedAt,\n            ownerId: undefined,\n            leaseExpiresAt: undefined,\n          },\n          { expectedStatus: 'running' },\n        )\n        .catch(error => {\n          this.#mastra\n            ?.getLogger?.()\n            ?.warn(`Failed to restore suspended background task ${taskId} during shutdown:`, error);\n        });\n      return false;\n    }\n    this.#trackSettlingRun(\n      run\n        .resume({ resumeData })\n        .then(\n          result => {\n            if (result.status !== 'suspended') {\n              this.#deleteSettledRun(workflow, taskId);\n            }\n            if (result.status !== 'success' && result.status !== 'suspended') {\n              return this.failUnsettledTask(taskId, 'resume', workflowRunError(result));\n            }\n          },\n          err => this.failUnsettledTask(taskId, 'resume', err),\n        )\n        .finally(() => {\n          // The resumed run has settled (suspended or terminal): stop renewing\n          // the lease this worker held for it.\n          this.ownedLeases.delete(taskId);\n          this.releaseLocalSlot(taskId);\n          void this.drainPending();\n        }),\n    );\n    return true;\n  }\n\n  /** Track a run settlement (or its follow-up delete) so shutdown can drain it before storage closes. */\n  #trackSettlingRun(promise: Promise<unknown>): void {\n    const tracked = promise.finally(() => this.#settlingRuns.delete(tracked));\n    this.#settlingRuns.add(tracked);\n    void tracked.catch(error => {\n      this.#mastra?.getLogger?.()?.error('Background task workflow run settlement failed:', error);\n    });\n  }\n\n  #deleteSettledRun(workflow: { deleteWorkflowRunById(runId: string): Promise<void> }, taskId: string): void {\n    this.#trackSettlingRun(\n      workflow.deleteWorkflowRunById(taskId).catch(error => {\n        this.#mastra?.getLogger?.()?.warn(`Failed to delete workflow run for background task ${taskId}:`, error);\n      }),\n    );\n  }\n\n  /**\n   * Settles a task whose background-task workflow run ended in a non-success,\n   * non-suspended state (or rejected). On the ordinary failure path\n   * classify-outcome has already moved the task to `failed`, so the CAS below\n   * is a no-op. It only takes effect when a step threw before persisting a\n   * terminal status (e.g. the `completed` write failed), which would otherwise\n   * leave the task `running` forever.\n   */\n  private async failUnsettledTask(taskId: string, action: 'start' | 'restart' | 'resume', err: unknown) {\n    const errorInfo = toTaskError(err);\n    try {\n      const storage = await this.getStorage();\n      const marked = await storage.updateTask(\n        taskId,\n        {\n          status: 'failed',\n          error: errorInfo,\n          completedAt: new Date(),\n          ownerId: undefined,\n          leaseExpiresAt: undefined,\n        },\n        { expectedStatus: 'running', expectedOwnerId: this.workerId },\n      );\n      if (!marked) return;\n      this.#mastra?.getLogger?.()?.error(`background-task workflow ${action} failed for ${taskId}:`, err);\n      const failedTask = await storage.getTask(taskId);\n      if (failedTask?.status === 'failed') {\n        await this.runLocalCompletionHooks(failedTask, 'failed', { error: failedTask.error ?? errorInfo });\n        await this.publishLifecycleEvent('task.failed', failedTask);\n      }\n    } catch (settleError) {\n      this.#mastra\n        ?.getLogger?.()\n        ?.error(`background-task workflow ${action} failed for ${taskId} and the task could not be marked failed:`, {\n          error: err,\n          settleError,\n        });\n      this.deregisterTaskContext(taskId);\n    }\n  }\n\n  /**\n   * Run per-task hooks (onChunk, onResult, onComplete/onFailed) locally in the\n   * worker path, before publishing the terminal lifecycle event. Ensures\n   * memory / stream state is consistent by the time any pubsub subscriber is\n   * notified. After running, the task context is deregistered so\n   * `handleResult` (which also fires from pubsub) becomes a no-op for this\n   * task in the same process.\n   *\n   * In distributed deployments where the worker runs in a different process\n   * from the dispatcher, `this.taskContexts` won't contain an entry for\n   * `task.id` — this method is a no-op there, and `handleResult` in the\n   * dispatching process runs the hooks instead.\n   */\n  /**\n   * Terminal-state hooks only. Called when a task reaches `'completed'` or\n   * `'failed'`. Suspend is non-terminal — see `runLocalSuspendHooks` for that\n   * path.\n   *\n   * @internal — also called by the workflow-engine step bodies in workflow.ts\n   */\n  async runLocalCompletionHooks(\n    task: BackgroundTask,\n    status: 'completed' | 'failed',\n    extras: { result?: unknown; error?: { message: string; stack?: string } },\n  ): Promise<void> {\n    const ctx = this.taskContexts.get(task.id);\n    if (!ctx) return;\n\n    try {\n      if (status === 'completed') {\n        ctx.onChunk?.({\n          type: 'background-task-completed',\n          payload: {\n            taskId: task.id,\n            toolName: task.toolName,\n            toolCallId: task.toolCallId,\n            runId: task.runId,\n            result: extras.result,\n            completedAt: task.completedAt!,\n            agentId: task.agentId,\n          },\n        });\n\n        await ctx.onResult?.({\n          runId: task.runId,\n          taskId: task.id,\n          toolCallId: task.toolCallId,\n          toolName: task.toolName,\n          agentId: task.agentId,\n          threadId: task.threadId,\n          resourceId: task.resourceId,\n          result: extras.result,\n          status: 'completed',\n          completedAt: task.completedAt!,\n          startedAt: task.startedAt!,\n        });\n\n        // Globals (this.config.onTaskComplete / onTaskFailed) fire from\n        // handleResult via pubsub so they run once per subscribing process\n        // — in distributed deployments that's the dispatching process, which\n        // is where observers/metrics are typically wired.\n        await ctx.onComplete?.(task);\n      } else {\n        ctx.onChunk?.({\n          type: 'background-task-failed',\n          payload: {\n            taskId: task.id,\n            toolName: task.toolName,\n            toolCallId: task.toolCallId,\n            runId: task.runId,\n            error: extras.error ?? { message: 'Unknown error' },\n            completedAt: task.completedAt!,\n            agentId: task.agentId,\n          },\n        });\n\n        await ctx.onResult?.({\n          runId: task.runId,\n          taskId: task.id,\n          toolCallId: task.toolCallId,\n          toolName: task.toolName,\n          agentId: task.agentId,\n          threadId: task.threadId,\n          resourceId: task.resourceId,\n          error: extras.error,\n          status: 'failed',\n          completedAt: task.completedAt!,\n          startedAt: task.startedAt!,\n        });\n\n        // See comment above — globals are handled exclusively by\n        // handleResult so they fire once per subscribing process.\n        await ctx.onFailed?.(task);\n      }\n    } catch (hookError) {\n      // Callers publish the terminal lifecycle event right after this; a\n      // throwing per-task hook must not suppress it.\n      this.#mastra?.getLogger?.()?.warn(`background-task ${status} hooks threw for ${task.id}:`, hookError);\n    } finally {\n      this.deregisterTaskContext(task.id);\n    }\n  }\n\n  /**\n   * Per-task suspend hooks. Fires `ctx.onExecution({ suspendedAt, suspendPayload, ... })`\n   * so the message list / memory record the open suspension on the tool\n   * call. Does NOT deregister the task context — resume needs the executor\n   * closure intact.\n   *\n   * @internal — called by the workflow-engine step bodies in workflow.ts\n   */\n  async runLocalSuspendHooks(task: BackgroundTask): Promise<void> {\n    const ctx = this.taskContexts.get(task.id);\n    if (!ctx) return;\n    await ctx.onExecution?.({\n      runId: task.runId,\n      taskId: task.id,\n      toolCallId: task.toolCallId,\n      toolName: task.toolName,\n      agentId: task.agentId,\n      threadId: task.threadId,\n      resourceId: task.resourceId,\n      startedAt: task.startedAt!,\n      suspendedAt: task.suspendedAt,\n      suspendPayload: task.suspendPayload,\n    });\n  }\n\n  /** @internal — also called by the workflow-engine step bodies in workflow.ts */\n  async runLocalExecutionHook(task: BackgroundTask): Promise<void> {\n    const ctx = this.taskContexts.get(task.id);\n    if (!ctx) return;\n\n    try {\n      await ctx.onExecution?.({\n        runId: task.runId,\n        taskId: task.id,\n        toolCallId: task.toolCallId,\n        toolName: task.toolName,\n        agentId: task.agentId,\n        threadId: task.threadId,\n        resourceId: task.resourceId,\n        startedAt: task.startedAt!,\n      });\n    } catch {\n      //fail silently\n    }\n  }\n\n  /**\n   * Another process cancelled a task this one dispatched. Run its execution\n   * hook, so the dispatcher drops an open request it recorded for the task,\n   * and release the task's context. A cancel made here has already done both.\n   */\n  private async handleRemoteCancel(taskId: string): Promise<void> {\n    if (!this.taskContexts.has(taskId)) return;\n    const task = await (await this.getStorage()).getTask(taskId);\n    if (task?.status !== 'cancelled') return;\n    await this.runLocalExecutionHook(task);\n    this.deregisterTaskContext(taskId);\n  }\n\n  private async handleResult(event: Event): Promise<void> {\n    const { taskId, toolName, toolCallId, threadId, resourceId, runId } = event.data;\n    const storage = await this.getStorage();\n    const task = await storage.getTask(taskId);\n\n    if (!task?.completedAt) return;\n\n    // Look up per-task hooks\n    const ctx = this.taskContexts.get(taskId);\n\n    try {\n      if (event.type === 'task.completed') {\n        ctx?.onChunk?.({\n          type: 'background-task-completed',\n          payload: {\n            taskId,\n            toolName,\n            toolCallId,\n            runId,\n            result: event.data.result,\n            completedAt: task.completedAt,\n            agentId: task.agentId,\n          },\n        });\n\n        await ctx?.onResult?.({\n          runId,\n          taskId,\n          toolCallId,\n          toolName,\n          agentId: event.data.agentId,\n          threadId,\n          resourceId,\n          result: event.data.result,\n          status: 'completed',\n          completedAt: task.completedAt,\n          startedAt: task.startedAt!,\n        });\n\n        await Promise.all([\n          ctx?.onComplete?.(task),\n          (async () => {\n            try {\n              await this.config.onTaskComplete?.(task);\n            } catch (error) {\n              this.#mastra\n                ?.getLogger?.()\n                ?.warn(`background-task completion callback failed for ${taskId}:`, error as any);\n            }\n          })(),\n        ]);\n      }\n\n      if (event.type === 'task.failed') {\n        ctx?.onChunk?.({\n          type: 'background-task-failed',\n          payload: {\n            taskId,\n            toolName,\n            toolCallId,\n            runId,\n            error: event.data.error,\n            completedAt: task.completedAt,\n            agentId: task.agentId,\n          },\n        });\n\n        await ctx?.onResult?.({\n          runId,\n          taskId,\n          toolCallId,\n          toolName,\n          agentId: event.data.agentId,\n          threadId,\n          resourceId,\n          error: event.data.error,\n          status: 'failed',\n          completedAt: task.completedAt,\n          startedAt: task.startedAt!,\n        });\n\n        await Promise.all([\n          ctx?.onFailed?.(task),\n          (async () => {\n            try {\n              await this.config.onTaskFailed?.(task);\n            } catch (error) {\n              this.#mastra?.getLogger?.()?.warn(`background-task failure callback failed for ${taskId}:`, error as any);\n            }\n          })(),\n        ]);\n      }\n    } finally {\n      // Clean up context after terminal result and admit the next task owned\n      // by this manager. Portable tasks may have completed on another process,\n      // so the result fan-out is the origin manager's queue-drain signal.\n      this.deregisterTaskContext(taskId);\n      void this.drainPending();\n    }\n  }\n\n  private handleCancel(event: Event): void {\n    const { taskId } = event.data;\n    const controller = this.activeAbortControllers.get(taskId);\n    if (controller) {\n      controller.abort(new Error('Task cancelled'));\n      this.activeAbortControllers.delete(taskId);\n    }\n    this.deregisterTaskContext(taskId);\n  }\n\n  /** @internal — also called by the workflow-engine step bodies in workflow.ts */\n  async publishLifecycleEvent(\n    type:\n      | 'task.running'\n      | 'task.completed'\n      | 'task.failed'\n      | 'task.cancelled'\n      | 'task.output'\n      | 'task.suspended'\n      | 'task.resumed',\n    task: BackgroundTaskEvent,\n  ): Promise<void> {\n    await this.pubsub.publish(TOPIC_RESULT, {\n      type,\n      data: {\n        taskId: task.id,\n        toolName: task.toolName,\n        toolCallId: task.toolCallId,\n        runId: task.runId,\n        agentId: task.agentId,\n        threadId: task.threadId,\n        resourceId: task.resourceId,\n        // Output events can fire once per chunk; subscribers never read `args`\n        // from them, so don't repeat a possibly large input on each one.\n        args: type === 'task.output' ? undefined : task.args,\n        result: task.result,\n        error: task.error,\n        chunk: task.chunk,\n        completedAt: task.completedAt,\n        startedAt: task.startedAt,\n        suspendPayload: task.suspendPayload,\n        suspendedAt: task.suspendedAt,\n      },\n      runId: task.id,\n    });\n  }\n\n  /**\n   * Renew every lease this manager holds, at `leaseDurationMs / 3`. Called on\n   * an interval so a live owner keeps proving liveness; a task whose renewal\n   * fails has left `running` (completed/failed/suspended/cancelled) or been\n   * reclaimed by another owner, so it is dropped from the tracking set.\n   */\n  async #renewOwnedLeases(): Promise<void> {\n    if (this.ownedLeases.size === 0 && this.pinnedPendingLeases.size === 0) return;\n    let storage;\n    try {\n      storage = await this.getStorage();\n    } catch {\n      // Storage unavailable mid-shutdown — leases expire on their own.\n      return;\n    }\n    for (const taskId of [...this.ownedLeases]) {\n      try {\n        // Fenced on the owner so a worker whose lease already lapsed (and whose\n        // task was reclaimed) cannot revive it.\n        const renewed = await storage.updateTask(\n          taskId,\n          { leaseExpiresAt: new Date(Date.now() + this.config.leaseDurationMs) },\n          { expectedStatus: 'running', expectedOwnerId: this.workerId },\n        );\n        if (!renewed) {\n          this.ownedLeases.delete(taskId);\n          await this.#abortSupersededRun(taskId);\n        }\n      } catch {\n        // Transient storage error — keep the lease tracked and retry next tick.\n      }\n    }\n    for (const taskId of [...this.pinnedPendingLeases]) {\n      try {\n        // A failed renewal means the row was claimed, cancelled, or recovered\n        // by another worker after this lease lapsed — stop tracking it.\n        const renewed = await storage.updateTask(\n          taskId,\n          { leaseExpiresAt: new Date(Date.now() + this.config.leaseDurationMs) },\n          { expectedStatus: 'pending', expectedOwnerId: this.workerId },\n        );\n        if (!renewed) this.pinnedPendingLeases.delete(taskId);\n      } catch {\n        // Transient storage error — retry next tick.\n      }\n    }\n  }\n\n  /**\n   * Called when a lease renewal loses its compare-and-set. Renewal normally\n   * fails because the task left `running` (it completed, failed or suspended),\n   * which needs no action. Two cases still have a local executor to stop:\n   * - The task was *cancelled*, possibly by another process whose `task.cancel`\n   *   event never reached this one. The local run is aborted the same way a\n   *   local `cancel()` aborts it, so it settles as cancelled.\n   * - The task is *still running under a different owner*: another worker has\n   *   taken it over. Its fenced terminal writes would be rejected anyway;\n   *   aborting just stops the wasted run.\n   */\n  async #abortSupersededRun(taskId: string): Promise<void> {\n    try {\n      const storage = await this.getStorage();\n      const current = await storage.getTask(taskId);\n      if (current?.status === 'cancelled') {\n        const controller = this.activeAbortControllers.get(taskId);\n        if (!controller) return;\n        controller.abort(new Error('Task cancelled'));\n        this.activeAbortControllers.delete(taskId);\n        this.deregisterTaskContext(taskId);\n        return;\n      }\n      if (current?.status !== 'running') return;\n      if (current.ownerId === this.workerId || !current.ownerId) return;\n      const controller = this.activeAbortControllers.get(taskId);\n      if (!controller) return;\n      controller.abort(new Error(TASK_OWNERSHIP_LOST_MESSAGE));\n    } catch {\n      // Storage unavailable — the run will be superseded on its next write.\n    }\n  }\n\n  #startLeaseHeartbeat(): void {\n    if (this.heartbeatInterval) return;\n    const intervalMs = Math.max(this.#timingFloorMs, Math.floor(this.config.leaseDurationMs / 3));\n    this.heartbeatInterval = setInterval(() => {\n      void this.#renewOwnedLeases();\n      // Storage-wide admission can be freed by another process, which never\n      // triggers a local drain. Retry queued resumes on each tick.\n      if (this.localPendingResumes.size > 0) void this.drainPending();\n    }, intervalMs);\n    // Never keep the process alive just to renew leases.\n    this.heartbeatInterval.unref?.();\n  }\n\n  private reserveLocalSlot(task: Pick<BackgroundTask, 'id' | 'agentId'>): boolean {\n    if (this.localReservations.has(task.id)) return true;\n    if (this.localReservations.size >= this.config.globalConcurrency) return false;\n\n    let agentRunning = 0;\n    for (const agentId of this.localReservations.values()) {\n      if (agentId === task.agentId) agentRunning++;\n    }\n    if (agentRunning >= this.#ownerLimit(task.agentId)) return false;\n\n    this.localReservations.set(task.id, task.agentId);\n    return true;\n  }\n\n  #ownerLimit(agentId: string): number {\n    const overrides = this.config.perOwnerConcurrency;\n    return overrides && Object.hasOwn(overrides, agentId) ? overrides[agentId]! : this.config.perAgentConcurrency;\n  }\n\n  private releaseLocalSlot(taskId: string): void {\n    this.localReservations.delete(taskId);\n  }\n\n  private async checkConcurrency(agentId: string): Promise<boolean> {\n    const storage = await this.getStorage();\n    // Another worker may already have handled a resume this manager published.\n    await this.#pruneInFlightResumes();\n    let inFlightForAgent = 0;\n    for (const entry of this.inFlightPortableResumes.values()) {\n      if (entry.agentId === agentId) inFlightForAgent++;\n    }\n    const globalRunning = (await storage.getRunningCount()) + this.inFlightPortableResumes.size;\n    if (globalRunning >= this.config.globalConcurrency) {\n      return false;\n    }\n\n    const agentRunning = (await storage.getRunningCountByAgent(agentId)) + inFlightForAgent;\n    if (agentRunning >= this.#ownerLimit(agentId)) {\n      return false;\n    }\n\n    return true;\n  }\n\n  async #pruneInFlightResumes(): Promise<void> {\n    if (this.inFlightPortableResumes.size === 0) return;\n    const storage = await this.getStorage();\n    const now = Date.now();\n    for (const [taskId, entry] of [...this.inFlightPortableResumes]) {\n      if (entry.until <= now) {\n        this.inFlightPortableResumes.delete(taskId);\n        continue;\n      }\n      // Once the row leaves this suspension, storage counts it (or it is done).\n      const task = await storage.getTask(taskId);\n      if (!task || task.status !== 'suspended' || suspensionToken(task) !== entry.suspendedAt) {\n        this.inFlightPortableResumes.delete(taskId);\n      }\n    }\n  }\n\n  private async drainPending(): Promise<void> {\n    if (this.drainingPending || this.shuttingDown) return;\n    this.drainingPending = true;\n\n    try {\n      const storage = await this.getStorage();\n      // Queued resumes go first: they continue work that already started.\n      for (const [taskId, entry] of [...this.localPendingResumes]) {\n        const task = await storage.getTask(taskId);\n        // Drop the entry if the task left the suspension it was queued for —\n        // including being resumed elsewhere and suspending again.\n        if (!task || task.status !== 'suspended' || suspensionToken(task) !== entry.suspendedAt) {\n          this.localPendingResumes.delete(taskId);\n          continue;\n        }\n\n        const isProcessAffine = this.taskContexts.has(taskId);\n        const canRun = isProcessAffine ? this.reserveLocalSlot(task) : await this.checkConcurrency(task.agentId);\n        if (!canRun) continue;\n        if (this.shuttingDown) return;\n\n        this.localPendingResumes.delete(taskId);\n        try {\n          await this.#publishResume(task, entry.resumeData, isProcessAffine);\n        } catch (error) {\n          this.localPendingResumes.set(taskId, entry);\n          this.#mastra?.getLogger?.()?.warn(`background-task resume failed while draining ${taskId}:`, error as any);\n          return;\n        }\n      }\n\n      for (const taskId of [...this.localPendingTaskIds]) {\n        const task = await storage.getTask(taskId);\n        if (!task || task.status !== 'pending') {\n          this.localPendingTaskIds.delete(taskId);\n          continue;\n        }\n\n        const isProcessAffine = this.taskContexts.has(taskId);\n        const canRun = isProcessAffine ? this.reserveLocalSlot(task) : await this.checkConcurrency(task.agentId);\n        if (!canRun) continue;\n\n        this.localPendingTaskIds.delete(taskId);\n        try {\n          await this.dispatch(task);\n        } catch (error) {\n          if (isProcessAffine) this.releaseLocalSlot(taskId);\n          this.localPendingTaskIds.add(taskId);\n          this.#mastra?.getLogger?.()?.warn(`background-task dispatch failed while draining ${taskId}:`, error as any);\n          return;\n        }\n      }\n    } catch (error) {\n      this.#mastra?.getLogger?.()?.warn('background-task queue drain failed:', error as any);\n    } finally {\n      this.drainingPending = false;\n    }\n  }\n\n  /**\n   * Recovers tasks left in 'running' or 'pending' state from a previous process.\n   *\n   * Running tasks are only reclaimed once their execution lease has lapsed, so\n   * one whose owner died moments before this scan is still protected. When that\n   * happens the scan reschedules itself for the moment the earliest such lease\n   * expires — see `#scheduleStaleRecovery`.\n   */\n  private async recoverStaleTasks(): Promise<void> {\n    if (this.shuttingDown) return;\n    try {\n      const storage = await this.getStorage();\n      const now = Date.now();\n      const { tasks: staleTasks } = await storage.listTasks({ status: 'running' });\n      let nextSweepAt: number | undefined;\n      for (const task of staleTasks) {\n        // A still-valid lease proves the owner is alive — do not reclaim it.\n        // This is what stops a second worker from taking over a task another\n        // process is actively running.\n        if (task.ownerId && task.leaseExpiresAt && task.leaseExpiresAt.getTime() > now) {\n          const leaseExpiry = task.leaseExpiresAt.getTime();\n          nextSweepAt = nextSweepAt === undefined ? leaseExpiry : Math.min(nextSweepAt, leaseExpiry);\n          continue;\n        }\n\n        // Fence the reclaim on the owner/lease we observed. If another worker\n        // reclaimed this task between the list and now, the compare-and-set\n        // fails and we leave it to them instead of clobbering their run.\n        const fence = {\n          expectedStatus: 'running' as const,\n          expectedOwnerId: task.ownerId ?? null,\n          expectedLeaseExpiresAt: task.leaseExpiresAt ?? null,\n        };\n        if (task.maxRetries > 0) {\n          await storage.updateTask(\n            task.id,\n            {\n              status: 'pending',\n              startedAt: undefined,\n              ownerId: undefined,\n              leaseExpiresAt: undefined,\n            },\n            fence,\n          );\n        } else {\n          await storage.updateTask(\n            task.id,\n            {\n              status: 'failed',\n              error: { message: 'Worker process terminated before task completed' },\n              completedAt: new Date(),\n              ownerId: undefined,\n              leaseExpiresAt: undefined,\n            },\n            fence,\n          );\n        }\n      }\n\n      const { tasks: pendingTasks } = await storage.listTasks({\n        status: 'pending',\n        orderBy: 'createdAt',\n        orderDirection: 'asc',\n      });\n      for (const task of pendingTasks) {\n        if (task.ownerId) {\n          const leaseExpiry = task.leaseExpiresAt?.getTime();\n          if (leaseExpiry !== undefined && leaseExpiry > now) {\n            nextSweepAt = nextSweepAt === undefined ? leaseExpiry : Math.min(nextSweepAt, leaseExpiry);\n          }\n          if (await this.#recoverLapsedPinWhenFree(storage, task, now)) await this.#dispatchRecoveredPin(task);\n          continue;\n        }\n        if (await this.checkConcurrency(task.agentId)) {\n          await this.dispatch(task);\n        }\n      }\n\n      this.#scheduleStaleRecovery(nextSweepAt);\n    } catch (error) {\n      const logger = this.#mastra?.getLogger();\n      if (logger) {\n        logger.error('Failed to recover stale background tasks', error);\n      }\n    }\n  }\n\n  /**\n   * Accounts for a `pinToWorker` row whose owner stopped renewing its lease.\n   * A pin means work for the row was in flight on its owner, so a lapsed pin\n   * is a lost attempt, handled like a `running` row whose lease lapsed: it\n   * consumes a retry and is unpinned, or it fails. Returns `true` when the row\n   * was unpinned and should be dispatched; `false` when the lease is still\n   * live, the row was failed, or another worker got to it first.\n   */\n  async #recoverLapsedPin(\n    storage: Awaited<ReturnType<BackgroundTaskManager['getStorage']>>,\n    task: BackgroundTask,\n    now: number,\n  ): Promise<boolean> {\n    if (task.leaseExpiresAt && task.leaseExpiresAt.getTime() > now) return false;\n    const fence = {\n      expectedStatus: 'pending' as const,\n      expectedOwnerId: task.ownerId ?? null,\n      expectedLeaseExpiresAt: task.leaseExpiresAt ?? null,\n    };\n    const retry = task.retryCount < task.maxRetries;\n    const recovered = retry\n      ? await storage.updateTask(\n          task.id,\n          { retryCount: task.retryCount + 1, ownerId: undefined, leaseExpiresAt: undefined },\n          fence,\n        )\n      : await storage.updateTask(\n          task.id,\n          {\n            status: 'failed',\n            error: { message: 'Worker process terminated before task completed' },\n            completedAt: new Date(),\n            ownerId: undefined,\n            leaseExpiresAt: undefined,\n          },\n          fence,\n        );\n    if (recovered) {\n      // The lapse only proves the owner stopped renewing. Its adopted work may\n      // still be running, which is why pinned work must be idempotent.\n      this.#mastra\n        ?.getLogger()\n        ?.warn(\n          `Background task ${task.id} lost its pin: worker ${task.ownerId} stopped renewing its lease. ${\n            retry ? 'Retrying it on another worker.' : 'Marking it failed.'\n          }`,\n        );\n    }\n    return retry && recovered;\n  }\n\n  /**\n   * {@link #recoverLapsedPin}, but a row that would be retried is only unpinned\n   * while a slot is free: an unpinned pending row is no longer seen by the pin\n   * sweep, so unpinning it without dispatching would spend the retry and leave\n   * it waiting for a restart. Without a slot the pin stays lapsed and a later\n   * sweep tries again. A row out of retries is failed either way.\n   */\n  async #recoverLapsedPinWhenFree(\n    storage: Awaited<ReturnType<BackgroundTaskManager['getStorage']>>,\n    task: BackgroundTask,\n    now: number,\n  ): Promise<boolean> {\n    const lapsed = !task.leaseExpiresAt || task.leaseExpiresAt.getTime() <= now;\n    if (lapsed && task.retryCount < task.maxRetries && !(await this.checkConcurrency(task.agentId))) return false;\n    return this.#recoverLapsedPin(storage, task, now);\n  }\n\n  /**\n   * Dispatches a row just unpinned by {@link #recoverLapsedPin}. The row is now\n   * unowned, so the pin sweep no longer sees it: if publishing fails, queue it\n   * locally so `drainPending()` (also run by every pin sweep) retries it.\n   */\n  async #dispatchRecoveredPin(task: BackgroundTask): Promise<void> {\n    try {\n      await this.dispatch(task);\n    } catch (error) {\n      this.localPendingTaskIds.add(task.id);\n      this.#mastra\n        ?.getLogger?.()\n        ?.warn(`background-task dispatch failed after recovering pin ${task.id}:`, error as any);\n    }\n  }\n\n  /**\n   * Periodically recovers lapsed `pinToWorker` rows. The startup scan only\n   * sees rows that existed when this worker started, so without this a pin\n   * enqueued later by a worker that then died would wait for a restart.\n   * Unpinned pending rows are left alone: they are dispatched by their own\n   * worker and by startup recovery, as before.\n   */\n  async #sweepLapsedPins(): Promise<void> {\n    if (this.shuttingDown || this.sweepingPins) return;\n    this.sweepingPins = true;\n    try {\n      // Retry recovered pins whose dispatch failed on an earlier tick.\n      if (this.localPendingTaskIds.size > 0) await this.drainPending();\n      const storage = await this.getStorage();\n      const now = Date.now();\n      // One page per tick, so a long queue doesn't make every worker read every pending row each lease.\n      const { tasks } = await storage.listTasks({\n        status: 'pending',\n        orderBy: 'createdAt',\n        orderDirection: 'asc',\n        page: this.pinSweepPage,\n        perPage: PIN_SWEEP_PAGE_SIZE,\n      });\n      this.pinSweepPage = tasks.length < PIN_SWEEP_PAGE_SIZE ? 0 : this.pinSweepPage + 1;\n      for (const task of tasks) {\n        if (!task.ownerId || this.shuttingDown) continue;\n        if (await this.#recoverLapsedPinWhenFree(storage, task, now)) await this.#dispatchRecoveredPin(task);\n      }\n    } catch (error) {\n      this.#mastra?.getLogger()?.error('Failed to recover lapsed pinned background tasks', error);\n    } finally {\n      this.sweepingPins = false;\n    }\n  }\n\n  #startPinSweep(): void {\n    if (this.shuttingDown || this.pinSweepInterval) return;\n    this.pinSweepInterval = setInterval(() => void this.#sweepLapsedPins(), this.config.leaseDurationMs);\n    // Never keep the process alive just to sweep for lapsed pins.\n    this.pinSweepInterval.unref?.();\n  }\n\n  /**\n   * Re-runs the stale-task scan once the earliest still-valid lease lapses.\n   * Rescheduling is harmless while an owner stays alive: its heartbeat keeps\n   * pushing the expiry out, so each pass simply schedules the next one.\n   */\n  #scheduleStaleRecovery(nextSweepAt: number | undefined): void {\n    if (this.staleRecoveryTimeout) {\n      clearTimeout(this.staleRecoveryTimeout);\n      this.staleRecoveryTimeout = undefined;\n    }\n    if (nextSweepAt === undefined || this.shuttingDown) return;\n\n    // Wait just past the lease expiry (clocks drift between workers), but bound\n    // the delay so a stray far-future lease cannot park recovery indefinitely.\n    const floor = this.#timingFloorMs;\n    const delay = Math.min(\n      Math.max(nextSweepAt - Date.now() + floor, floor),\n      Math.max(this.config.leaseDurationMs, floor),\n    );\n    this.staleRecoveryTimeout = setTimeout(() => {\n      this.staleRecoveryTimeout = undefined;\n      void this.recoverStaleTasks();\n    }, delay);\n    // Never keep the process alive just to sweep for stale tasks.\n    this.staleRecoveryTimeout.unref?.();\n  }\n}\n\nfunction suspensionToken(task: BackgroundTask): number | null {\n  return task.suspendedAt?.getTime() ?? null;\n}\n","import type { BackgroundTaskManager } from './manager';\nimport type {\n  BackgroundTaskHandle,\n  CheckIfExistingPayload,\n  CheckIfRunningPayload,\n  CheckIfSuspendedPayload,\n  CreateBackgroundTaskOptions,\n  ResumeOptions,\n} from './types';\n\n/**\n * Creates a self-contained background task handle.\n *\n * Bundles the task payload with per-stream hooks (executor, onChunk, onResult)\n * so each dispatch is fully isolated — no shared mutable state on the manager.\n *\n * @example\n * ```ts\n * const bgTask = createBackgroundTask(manager, {\n *   toolName: 'research',\n *   toolCallId: 'call-1',\n *   args: { query: 'solana' },\n *   agentId: 'agent-1',\n *   runId: 'run-1',\n *   context: {\n *     executor: { execute: (args, opts) => tool.execute(args, opts) },\n *     onChunk: (chunk) => controller.enqueue(chunk),\n *     onResult: (params) => messageList.addToolResult(params),\n *   },\n * });\n *\n * const { task, fallbackToSync } = await bgTask.dispatch();\n * const completed = await bgTask.waitForCompletion();\n * await bgTask.cancel();\n * ```\n */\nexport function createBackgroundTask(\n  manager: BackgroundTaskManager,\n  options: CreateBackgroundTaskOptions,\n): BackgroundTaskHandle {\n  const { context, ...payload } = options;\n  let taskId: string | undefined;\n\n  return {\n    get task() {\n      if (!taskId) throw new Error('Task has not been dispatched yet');\n      // Synchronous access to task ID — full task data requires async getTask()\n      return { id: taskId } as any;\n    },\n\n    async dispatch() {\n      const result = await manager.enqueue(payload, context);\n      taskId = result.task.id;\n      return result;\n    },\n\n    async checkIfSuspended(args: CheckIfSuspendedPayload) {\n      const result = await manager.listTasks({\n        toolCallId: args.toolCallId,\n        runId: args.runId,\n        agentId: args.agentId,\n        threadId: args.threadId,\n        resourceId: args.resourceId,\n        toolName: args.toolName,\n        status: 'suspended',\n      });\n      if (result.total > 0) {\n        const task = result.tasks[0];\n        if (task) {\n          taskId = task.id;\n          return true;\n        }\n      }\n\n      return false;\n    },\n\n    async checkIfExisting(args: CheckIfExistingPayload) {\n      const result = await manager.listTasks({\n        toolCallId: args.toolCallId,\n        runId: args.runId,\n        agentId: args.agentId,\n        threadId: args.threadId,\n        resourceId: args.resourceId,\n        toolName: args.toolName,\n      });\n      if (result.total > 1) {\n        throw new Error(`Multiple background tasks found for run \"${args.runId}\" and tool call \"${args.toolCallId}\"`);\n      }\n\n      const task = result.tasks[0];\n      if (task) {\n        taskId = task.id;\n        if (task.status === 'pending' || task.status === 'running' || task.status === 'suspended') {\n          manager.registerTaskContext(task.id, context);\n        }\n      }\n      return task;\n    },\n\n    async checkIfRunning(args: CheckIfRunningPayload) {\n      const result = await manager.listTasks({\n        toolCallId: args.toolCallId,\n        runId: args.runId,\n        agentId: args.agentId,\n        threadId: args.threadId,\n        resourceId: args.resourceId,\n        toolName: args.toolName,\n        status: 'running',\n      });\n      if (result.total > 0) {\n        const task = result.tasks[0];\n        if (task) {\n          taskId = task.id;\n          return true;\n        }\n      }\n\n      return false;\n    },\n\n    async resume(resumeData?: unknown, resumeOptions?: ResumeOptions) {\n      if (!taskId) throw new Error('Task has not been dispatched yet');\n      manager.registerTaskContext(taskId, context);\n      try {\n        // Only forward options when given, so existing callers see the same call.\n        return resumeOptions\n          ? await manager.resume(taskId, resumeData, resumeOptions)\n          : await manager.resume(taskId, resumeData);\n      } catch (error) {\n        manager.deregisterTaskContext(taskId);\n        throw error;\n      }\n    },\n\n    async restart() {\n      if (!taskId) throw new Error('Task has not been dispatched yet');\n      return manager.restart(taskId, context);\n    },\n\n    async cancel() {\n      if (!taskId) throw new Error('Task has not been dispatched yet');\n      return manager.cancel(taskId);\n    },\n\n    async waitForCompletion(waitOptions) {\n      if (!taskId) throw new Error('Task has not been dispatched yet');\n      return manager.waitForNextTask([taskId], waitOptions);\n    },\n  };\n}\n","import type {\n  AgentBackgroundConfig,\n  AgentBackgroundToolConfig,\n  BackgroundExecutionDisposition,\n  BackgroundTaskManagerConfig,\n  LLMBackgroundOverride,\n  ToolBackgroundConfig,\n} from './types';\n\nexport interface ResolvedBackgroundConfig {\n  runInBackground: boolean;\n  disposition: BackgroundExecutionDisposition;\n  timeoutMs: number;\n  maxRetries: number;\n}\n\n/**\n * Resolves whether a tool call should run in the background, and with what config.\n *\n * Resolution order (highest to lowest priority):\n * 1. LLM per-call override (`_background` field in tool args)\n * 2. Agent-level backgroundTasks.tools config\n * 3. Tool-level background config\n * 4. Default for eligible tools: the configured `defaultDisposition`\n *    (deferred when unset); non-eligible tools always run foreground\n *\n * Strips the `_background` field from args (mutates the args object).\n */\nexport function resolveBackgroundConfig({\n  llmBgOverrides,\n  toolName,\n  toolConfig,\n  agentConfig,\n  managerConfig,\n}: {\n  llmBgOverrides: Record<string, unknown>;\n  toolName: string;\n  toolConfig?: ToolBackgroundConfig;\n  agentConfig?: AgentBackgroundConfig;\n  managerConfig?: BackgroundTaskManagerConfig;\n}): ResolvedBackgroundConfig {\n  const llmOverride = llmBgOverrides as LLMBackgroundOverride | undefined;\n\n  // If this agent has background tasks disabled, short-circuit so no tool can\n  // dispatch a background task even if its own config or the LLM override\n  // would otherwise enable it. Default timeoutMs/maxRetries are still returned\n  // so callers can use the shape safely.\n  if (agentConfig?.disabled) {\n    return {\n      runInBackground: false,\n      disposition: 'foreground',\n      timeoutMs: managerConfig?.defaultTimeoutMs ?? 300_000,\n      maxRetries: managerConfig?.defaultRetries?.maxRetries ?? 0,\n    };\n  }\n\n  // Resolve agent-level config for this specific tool\n  const agentToolConfig = resolveAgentToolConfig(toolName, agentConfig);\n\n  // --- disposition ---\n  // Tool and agent config gate eligibility. A non-eligible tool always runs\n  // foreground regardless of what the model emits, so `agent.generate()` /\n  // `agent.stream()` keep returning real tool results for deterministic\n  // tools. See issue #16783.\n  //\n  // For eligible tools, the `_background` override wins; when omitted, the\n  // configured `defaultDisposition` applies. It defaults to 'deferred' so an\n  // eligible tool without further config runs in the background. Set\n  // `defaultDisposition: 'foreground'` to make eligibility grant only the\n  // per-call option.\n  const baseEnabled = agentToolConfig?.enabled ?? toolConfig?.enabled ?? false;\n  const defaultDisposition = resolveDefaultDisposition({ toolName, toolConfig, agentConfig });\n  const requestedDisposition =\n    llmOverride?.disposition ??\n    (llmOverride?.enabled === false ? 'foreground' : llmOverride?.enabled === true ? 'deferred' : defaultDisposition);\n  const disposition: BackgroundExecutionDisposition = baseEnabled ? requestedDisposition : 'foreground';\n\n  // --- timeoutMs ---\n  const timeoutMs =\n    llmOverride?.timeoutMs ??\n    agentToolConfig?.timeoutMs ??\n    toolConfig?.timeoutMs ??\n    managerConfig?.defaultTimeoutMs ??\n    300_000;\n\n  // --- maxRetries ---\n  const maxRetries =\n    llmOverride?.maxRetries ?? toolConfig?.maxRetries ?? managerConfig?.defaultRetries?.maxRetries ?? 0;\n\n  return { runInBackground: disposition !== 'foreground', disposition, timeoutMs, maxRetries };\n}\n\n/**\n * Whether a tool is background-eligible: i.e. whether `resolveBackgroundConfig`\n * could ever dispatch it to the background. This is the same base-enabled\n * expression the runtime resolver uses (the LLM `_background` override is a\n * modifier only, never a standalone opt-in — see issue #16783), so advertising\n * paths (schema injection, system prompt) and dispatch cannot disagree.\n */\nexport function isToolBackgroundEligible({\n  toolName,\n  toolConfig,\n  agentConfig,\n}: {\n  toolName: string;\n  toolConfig?: ToolBackgroundConfig;\n  agentConfig?: AgentBackgroundConfig;\n}): boolean {\n  if (agentConfig?.disabled) return false;\n  const agentToolConfig = resolveAgentToolConfig(toolName, agentConfig);\n  return agentToolConfig?.enabled ?? toolConfig?.enabled ?? false;\n}\n\n/**\n * The disposition an eligible tool resolves to when a call carries no\n * `_background` override. Mirrors the fallback chain in\n * `resolveBackgroundConfig` so advertising paths (system prompt) and dispatch\n * cannot disagree.\n */\nexport function resolveDefaultDisposition({\n  toolName,\n  toolConfig,\n  agentConfig,\n}: {\n  toolName: string;\n  toolConfig?: ToolBackgroundConfig;\n  agentConfig?: AgentBackgroundConfig;\n}): 'foreground' | 'deferred' {\n  const agentToolConfig = resolveAgentToolConfig(toolName, agentConfig);\n  return agentToolConfig?.defaultDisposition ?? toolConfig?.defaultDisposition ?? 'deferred';\n}\n\nfunction resolveAgentToolConfig(\n  toolName: string,\n  agentConfig?: AgentBackgroundConfig,\n): { enabled: boolean; timeoutMs?: number; defaultDisposition?: 'foreground' | 'deferred' } | undefined {\n  if (!agentConfig?.tools) return undefined;\n\n  if (agentConfig.tools === 'all') {\n    return { enabled: true };\n  }\n\n  if (toolName.startsWith('agent-')) {\n    toolName = toolName.substring('agent-'.length);\n  } else if (toolName.startsWith('workflow-')) {\n    toolName = toolName.substring('workflow-'.length);\n  }\n\n  const entry: AgentBackgroundToolConfig | undefined = agentConfig.tools[toolName];\n  if (entry === undefined) return undefined;\n  if (typeof entry === 'boolean') return { enabled: entry };\n  return entry;\n}\n","import { z } from 'zod/v4';\n\n/**\n * JSON Schema definition for the `_background` override field.\n * Injected into background-eligible tool schemas so the LLM can override behavior per-call.\n */\nexport const backgroundOverrideJsonSchema = {\n  type: 'object' as const,\n  description:\n    'Optional: override how this specific call executes (foreground, deferred, or awaited). ' +\n    \"When omitted, the tool's configured default disposition applies. \" +\n    'The enabled boolean remains supported for compatibility.',\n  properties: {\n    enabled: {\n      type: 'boolean' as const,\n      description: 'Force deferred (true) or foreground (false) execution for this call.',\n    },\n    disposition: {\n      type: 'string' as const,\n      enum: ['foreground', 'deferred', 'awaited'],\n      description: 'Choose foreground, deferred, or awaited execution for this call.',\n    },\n    timeoutMs: {\n      type: 'number' as const,\n      description: 'Override timeout in milliseconds for this call.',\n    },\n    maxRetries: {\n      type: 'number' as const,\n      description: 'Override maximum retry attempts for this call.',\n    },\n  },\n  additionalProperties: false,\n};\n\nexport const backgroundOverrideZodSchema = z\n  .object({\n    enabled: z.boolean().optional().describe('Force deferred (true) or foreground (false) execution for this call.'),\n    disposition: z\n      .enum(['foreground', 'deferred', 'awaited'])\n      .optional()\n      .describe('Choose foreground, deferred, or awaited execution for this call.'),\n    timeoutMs: z.number().optional().describe('Override timeout in milliseconds for this call.'),\n    maxRetries: z.number().optional().describe('Override maximum retry attempts for this call.'),\n  })\n  .optional()\n  .describe(\n    \"Optional: override how this specific call executes (foreground, deferred, or awaited). When omitted, the tool's configured default disposition applies. The enabled boolean remains supported for compatibility.\",\n  );\n","import { isToolBackgroundEligible, resolveDefaultDisposition } from './resolve-config';\nimport type { AgentBackgroundConfig, ToolBackgroundConfig } from './types';\n\n/**\n * Tool shape accepted by the prompt generator. Callers may pass raw `Tool`s\n * (config on `background`) or converted `CoreTool`s (config on\n * `backgroundConfig`); both are honored.\n */\nexport interface BackgroundPromptTool {\n  background?: ToolBackgroundConfig;\n  backgroundConfig?: ToolBackgroundConfig;\n  description?: string;\n}\n\n/**\n * Generates the system prompt section that tells the LLM about background task capabilities.\n *\n * Only tools that `resolveBackgroundConfig` could actually dispatch to the\n * background are listed (agent-level opt-in, falling back to tool-level\n * config — see `isToolBackgroundEligible`). Returns undefined if no tools are\n * background-eligible (nothing to inject).\n */\nexport function generateBackgroundTaskSystemPrompt(\n  tools: Record<string, BackgroundPromptTool>,\n  agentConfig?: AgentBackgroundConfig,\n): string | undefined {\n  const eligibleTools: { toolName: string; defaultDisposition: 'foreground' | 'deferred' }[] = [];\n\n  for (const [toolName, tool] of Object.entries(tools)) {\n    const toolConfig = tool.backgroundConfig ?? tool.background;\n    if (isToolBackgroundEligible({ toolName, toolConfig, agentConfig })) {\n      eligibleTools.push({\n        toolName,\n        defaultDisposition: resolveDefaultDisposition({ toolName, toolConfig, agentConfig }),\n      });\n    }\n  }\n\n  if (eligibleTools.length === 0) {\n    return undefined;\n  }\n\n  // Each eligible tool advertises the disposition it resolves to when the\n  // call carries no `_background` override: 'deferred' defaults show as\n  // \"default: background\", while 'foreground' defaults require an explicit\n  // per-call opt-in.\n  const toolLines = eligibleTools\n    .map(({ toolName, defaultDisposition }) =>\n      defaultDisposition === 'deferred'\n        ? `- ${toolName} (default: background)`\n        : `- ${toolName} (default: foreground — opt in with \"_background\")`,\n    )\n    .join('\\n');\n\n  return `You have the ability to run certain tools in the background while continuing the conversation. The following tools support background execution:\n${toolLines}\n\nFor any of these tools, you can include a \"_background\" field in the tool arguments to override the default:\n  \"_background\": { \"disposition\": \"foreground\" | \"deferred\" | \"awaited\", \"timeoutMs\": number, \"maxRetries\": number }\n\nAll fields in \"_background\" are optional. Only include what you want to override. Tools listed with \"default: background\" run in the background unless you set \"disposition\": \"foreground\". Tools listed with \"default: foreground\" run inline unless you explicitly request \"deferred\" or \"awaited\" — for those tools, omitting \"_background\" never starts background work.\n\nDispositions:\n- \"deferred\": the tool runs in the background while you continue; you receive a placeholder result with a task ID and are notified when the task completes.\n- \"awaited\": the tool runs as a durable background task but your run waits for its result before continuing.\n- \"foreground\": the tool runs inline and returns its real result immediately.\n\nGuidelines:\n- Use background execution when the user doesn't need the result immediately, or when you're launching multiple independent tasks.\n- Use foreground execution when the user is directly waiting for the result and the conversation can't continue without it.\n- When a tool runs deferred, you'll receive a placeholder result with a task ID. You can reference this in your response to the user.\n\nIMPORTANT: \"_background\" field is always an object. The fields in the _background field should be inside the _background object, not outside of it.`;\n}\n"],"mappings":";;;;;;;;;;;;AAUA,MAAa,8BAA8B;;ACS3C,MAAM,iBAAiB;AACvB,MAAM,eAAe;AACrB,MAAM,eAAe;AACrB,MAAM,2BAA2B;AACjC,MAAM,yBAAyB;AAC/B,MAAM,8BAA8B;AAEpC,SAAS,iBAAiB,QAAsF;CAC9G,IAAI,OAAO,UAAU,KAAA,GAAW,OAAO,OAAO;CAC9C,IAAI,OAAO,UAAU,QAAQ,OAAO,IAAI,MAAM,OAAO,SAAS,MAAM;CACpE,uBAAO,IAAI,MAAM,mDAAmD,OAAO,OAAO,EAAE;AACtF;AAGA,SAAS,YAAY,KAAmD;CACtE,IAAI,OAAO,OAAO,QAAQ,YAAY,OAAQ,IAA8B,YAAY,UAAU;EAChG,MAAM,EAAE,SAAS,UAAU;EAC3B,OAAO,OAAO,UAAU,WAAW;GAAE;GAAS;EAAM,IAAI,EAAE,QAAQ;CACpE;CACA,OAAO,EAAE,SAAS,OAAO,GAAG,EAAE;AAChC;;AAGA,MAAM,sBAAsB;;AAG5B,SAAS,mBAAuC;CAC9C,MAAM,QAAQ,OAAO,QAAQ,IAAI,oCAAoC;CACrE,OAAO,OAAO,SAAS,KAAK,KAAK,QAAQ,KAAK,QAAQ,MAAQ,QAAQ,KAAA;AACxE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,IAAa,wBAAb,MAAmC;CACjC;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