UNPKG

@mastra/core

Version:
1 lines • 44.5 kB
{"version":3,"file":"worker-CrY54A4Z.cjs","names":["assertDrainTimeout","waitMs","WorkflowEventProcessor","resolveAgentById","computeScheduleDefinitionHash","Scheduler","BackgroundTaskManager","getStepEntry","RequestContext","StepExecutor","getNestedWorkflow"],"sources":["../src/worker/worker.ts","../src/worker/strategies/http-remote-strategy.ts","../src/worker/transport/pull-transport.ts","../src/worker/workers/orchestration-worker.ts","../src/worker/workers/scheduler-worker.ts","../src/worker/workers/background-task-worker.ts","../src/worker/strategies/in-process-strategy.ts"],"sourcesContent":["import type { PubSub } from '../events/pubsub';\nimport type { IMastraLogger } from '../logger';\nimport type { Mastra } from '../mastra';\nimport type { MastraCompositeStore } from '../storage';\n\n/**\n * Infrastructure dependencies provided to workers during initialization.\n */\nexport interface WorkerStopOptions {\n /** Max time to wait for in-flight work before tearing down, in ms. */\n drainTimeout?: number;\n}\n\nexport interface WorkerDeps {\n pubsub: PubSub;\n storage: MastraCompositeStore;\n logger: IMastraLogger;\n mastra?: Mastra;\n}\n\n/**\n * Abstract base class for Mastra workers.\n *\n * Each worker is a self-contained, independently deployable unit of\n * background processing. Concrete implementations include:\n * - OrchestrationWorker: processes workflow events\n * - SchedulerWorker: fires cron-based workflow schedules\n * - BackgroundTaskWorker: manages background tool execution\n *\n * Workers are registered on a Mastra instance and run inline by default.\n * They can also be launched standalone via the CLI for separate deployment.\n */\nexport abstract class MastraWorker {\n abstract readonly name: string;\n\n protected mastra?: Mastra;\n protected deps?: WorkerDeps;\n\n /** Called by Mastra during registration to provide the instance reference. */\n __registerMastra(mastra: Mastra): void {\n this.mastra = mastra;\n }\n\n /** Initialize with infrastructure deps. Called before start(). */\n async init(deps: WorkerDeps): Promise<void> {\n this.deps = deps;\n if (!this.mastra && deps.mastra) {\n this.mastra = deps.mastra;\n }\n }\n\n abstract start(): Promise<void>;\n abstract stop(options?: WorkerStopOptions): Promise<void>;\n abstract get isRunning(): boolean;\n}\n","import type { StepResult } from '../../workflows/types';\nimport type { StepExecutionParams, StepExecutionStrategy } from '../types';\n\n/**\n * Auth credential used by `HttpRemoteStrategy` when calling the server's\n * step-execution endpoint. The server's configured Mastra auth provider\n * (`authenticateToken`) decides whether to accept the credential — this\n * strategy just forwards it.\n *\n * - `bearer`: send `Authorization: Bearer <token>` (default when only a\n * token string is available)\n * - `api-key`: send `x-worker-api-key: <key>` for deployments that prefer\n * a custom header (the auth provider's `authenticateToken(_, request)`\n * callback can read it from `request.headers`)\n * - `header`: arbitrary header / value pair for fully custom schemes\n */\nexport type HttpRemoteAuthConfig =\n | { type: 'bearer'; token: string }\n | { type: 'api-key'; key: string }\n | { type: 'header'; name: string; value: string };\n\n/**\n * Executes workflow steps by calling a remote server endpoint over HTTP.\n * Used in standalone worker deployments where the worker runs orchestration\n * logic but delegates actual step execution to the server.\n *\n * Authentication piggy-backs on Mastra's existing auth pipeline: the route\n * is marked `requiresAuth: true` and the deployer's `authenticateToken`\n * provider validates the credential we send here. There is no separate\n * \"worker secret\" — whatever auth scheme the rest of the server uses is\n * what the worker uses too.\n */\nexport class HttpRemoteStrategy implements StepExecutionStrategy {\n #baseUrl: URL;\n #auth?: HttpRemoteAuthConfig;\n #timeoutMs: number;\n\n constructor({ serverUrl, auth, timeoutMs }: { serverUrl: string; auth?: HttpRemoteAuthConfig; timeoutMs?: number }) {\n // Normalize once: ensure trailing slash so URL joins compose correctly.\n const normalized = serverUrl.endsWith('/') ? serverUrl : `${serverUrl}/`;\n this.#baseUrl = new URL(normalized);\n this.#auth = auth ?? HttpRemoteStrategy.#authFromEnv();\n this.#timeoutMs = timeoutMs ?? 30_000;\n }\n\n /**\n * Default credential resolution: when `MASTRA_WORKER_AUTH_TOKEN` is set,\n * send it as a bearer token. The server's auth provider decides whether\n * to accept it.\n */\n static #authFromEnv(): HttpRemoteAuthConfig | undefined {\n const token = process.env.MASTRA_WORKER_AUTH_TOKEN;\n if (!token) return undefined;\n return { type: 'bearer', token };\n }\n\n async executeStep(params: StepExecutionParams): Promise<StepResult<unknown, unknown, unknown, unknown>> {\n const url = new URL(\n `workflows/${encodeURIComponent(params.workflowId)}/runs/${encodeURIComponent(params.runId)}/steps/execute`,\n this.#baseUrl,\n );\n\n const body = this.#buildBody(params);\n\n const signal = this.#combineSignals(params.abortSignal);\n\n const res = await fetch(url, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n ...this.#buildAuthHeaders(),\n },\n body,\n signal,\n });\n\n if (!res.ok) {\n const text = await res.text();\n throw new StepExecutionError(res.status, text);\n }\n\n return res.json() as Promise<StepResult<unknown, unknown, unknown, unknown>>;\n }\n\n /**\n * Build a JSON-serializable request body. The `params.requestContext` is\n * a plain object; if a caller stuffed a non-serializable value into it we\n * surface a clear error instead of silently dropping fields.\n *\n * `abortSignal` is consumed via fetch's `signal` argument — it must not\n * be in the body.\n */\n #buildBody(params: StepExecutionParams): string {\n const { abortSignal: _abortSignal, requestContext, ...rest } = params;\n let safeRequestContext: Record<string, unknown>;\n try {\n safeRequestContext = JSON.parse(JSON.stringify(requestContext ?? {}));\n } catch (err) {\n throw new Error(\n `HttpRemoteStrategy: requestContext is not JSON-serializable. ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n\n return JSON.stringify({\n ...rest,\n requestContext: safeRequestContext,\n });\n }\n\n #combineSignals(externalSignal?: AbortSignal): AbortSignal {\n const timeoutSignal = AbortSignal.timeout(this.#timeoutMs);\n if (!externalSignal) return timeoutSignal;\n // AbortSignal.any aborts when any input aborts.\n if (typeof AbortSignal.any === 'function') {\n return AbortSignal.any([timeoutSignal, externalSignal]);\n }\n // Fallback for runtimes without AbortSignal.any\n const controller = new AbortController();\n const onAbort = (reason: unknown) => controller.abort(reason);\n if (externalSignal.aborted) onAbort(externalSignal.reason);\n else externalSignal.addEventListener('abort', () => onAbort(externalSignal.reason), { once: true });\n if (timeoutSignal.aborted) onAbort(timeoutSignal.reason);\n else timeoutSignal.addEventListener('abort', () => onAbort(timeoutSignal.reason), { once: true });\n return controller.signal;\n }\n\n #buildAuthHeaders(): Record<string, string> {\n if (!this.#auth) return {};\n if (this.#auth.type === 'api-key') {\n return { 'x-worker-api-key': this.#auth.key };\n }\n if (this.#auth.type === 'header') {\n return { [this.#auth.name]: this.#auth.value };\n }\n return { authorization: `Bearer ${this.#auth.token}` };\n }\n}\n\nexport class StepExecutionError extends Error {\n readonly status: number;\n readonly body: string;\n\n constructor(status: number, body: string) {\n super(`Step execution failed with status ${status}: ${body}`);\n this.name = 'StepExecutionError';\n this.status = status;\n this.body = body;\n }\n}\n","import type { PubSub } from '../../events/pubsub';\nimport type { EventCallback } from '../../events/types';\nimport type { IMastraLogger } from '../../logger';\nimport { waitMs } from '../../utils/test-waits';\nimport { assertDrainTimeout } from '../drain-timeout';\nimport type { EventRouter, WorkerTransport, WorkerTransportStopOptions } from './transport';\n\nconst TOPIC_WORKFLOWS = 'workflows';\nconst DEFAULT_DRAIN_TIMEOUT_MS = 5_000;\n\nexport class PullTransport implements WorkerTransport {\n #pubsub: PubSub;\n #group: string;\n #topic: string;\n #logger?: IMastraLogger;\n #drainTimeout: number;\n #callbacks: Array<{ topic: string; cb: EventCallback }> = [];\n // route() calls that have been dispatched but not yet settled. stop() waits\n // for these (bounded) so an event mid-processing is not abandoned.\n #inFlight = new Set<Promise<void>>();\n\n constructor({\n pubsub,\n group,\n topic,\n logger,\n drainTimeout,\n }: {\n pubsub: PubSub;\n group: string;\n /** Pubsub topic to subscribe to. Defaults to the workflows topic. */\n topic?: string;\n logger?: IMastraLogger;\n /** Max time stop() waits for in-flight route() calls, in ms. Defaults to 5000. */\n drainTimeout?: number;\n }) {\n this.#pubsub = pubsub;\n this.#group = group;\n this.#topic = topic ?? TOPIC_WORKFLOWS;\n this.#logger = logger;\n this.#drainTimeout = assertDrainTimeout(drainTimeout ?? waitMs(DEFAULT_DRAIN_TIMEOUT_MS, 50), 'PullTransport');\n }\n\n async start(router: EventRouter): Promise<void> {\n if (this.#callbacks.length > 0) {\n this.#logger?.debug('[PullTransport] start() called while already subscribed; ignoring duplicate call');\n return;\n }\n const cb: EventCallback = (event, ack, nack, extend) => {\n // route() is async; surface unexpected rejections as a nack instead\n // of an unhandledRejection. The router's own try/catch already turns\n // expected processing errors into nack — this guard only catches\n // synchronous-throw-becomes-rejected-promise leaks.\n const inFlight = router.route(event, ack, nack, extend).catch(err => {\n try {\n // Best-effort: ack/nack are optional in some PubSub backends.\n if (typeof nack === 'function') {\n void nack();\n }\n } finally {\n this.#logger?.error('[PullTransport] router.route rejected', { err });\n }\n });\n this.#inFlight.add(inFlight);\n void inFlight.finally(() => this.#inFlight.delete(inFlight));\n };\n await this.#pubsub.subscribe(this.#topic, cb, { group: this.#group });\n this.#callbacks.push({ topic: this.#topic, cb });\n }\n\n async stop(options?: WorkerTransportStopOptions): Promise<void> {\n const drainTimeout = assertDrainTimeout(options?.drainTimeout ?? this.#drainTimeout, 'PullTransport.stop()');\n // Unsubscribe first so no new events land while we drain; events already\n // handed to the router keep running and may still publish/ack/nack.\n for (const { topic, cb } of this.#callbacks) {\n await this.#pubsub.unsubscribe(topic, cb);\n }\n this.#callbacks = [];\n await this.#drainInFlight(drainTimeout);\n\n await this.#pubsub.flush();\n }\n\n async #drainInFlight(drainTimeout: number): Promise<void> {\n if (this.#inFlight.size === 0) return;\n const pending = this.#inFlight.size;\n let timeoutHandle: ReturnType<typeof setTimeout> | undefined;\n try {\n const timedOut = await Promise.race([\n Promise.allSettled([...this.#inFlight]).then(() => false),\n new Promise<boolean>(resolve => {\n timeoutHandle = setTimeout(() => resolve(true), drainTimeout);\n }),\n ]);\n if (timedOut) {\n this.#logger?.warn(\n `[PullTransport] stop() timed out after ${drainTimeout}ms waiting for ${pending} in-flight event(s)`,\n );\n }\n } finally {\n if (timeoutHandle) clearTimeout(timeoutHandle);\n }\n }\n}\n","import type { Event } from '../../events/types';\nimport { WorkflowEventProcessor } from '../../workflows/evented/workflow-event-processor';\nimport { HttpRemoteStrategy } from '../strategies/http-remote-strategy';\nimport { PullTransport } from '../transport/pull-transport';\nimport type { WorkerTransport } from '../transport/transport';\nimport type { StepExecutionStrategy } from '../types';\nimport { MastraWorker } from '../worker';\nimport type { WorkerDeps, WorkerStopOptions } from '../worker';\n\nconst DEFAULT_GROUP = 'mastra-orchestration';\nconst DEFAULT_LEASE_RENEW_INTERVAL_MS = 10_000;\n\nexport interface OrchestrationWorkerConfig {\n group?: string;\n /**\n * How often (in ms) to renew an in-flight event's delivery lease while it is\n * being handled, for PubSub backends that support it. Defaults to 10000.\n */\n leaseRenewIntervalMs?: number;\n}\n\n/**\n * Processes workflow events (step.run, step.end, start, cancel, etc.)\n * by delegating to the WorkflowEventProcessor.\n *\n * Subscribes to the PubSub \"workflows\" topic and routes events to WEP.\n *\n * When MASTRA_STEP_EXECUTION_URL is set, injects HttpRemoteStrategy into\n * WEP so step execution happens over HTTP to the server. Otherwise WEP\n * executes steps directly in-process.\n */\nexport class OrchestrationWorker extends MastraWorker {\n readonly name = 'orchestration';\n\n #config: OrchestrationWorkerConfig;\n #transport?: WorkerTransport;\n #processor?: WorkflowEventProcessor;\n #strategy?: StepExecutionStrategy;\n #running = false;\n\n constructor(config: OrchestrationWorkerConfig = {}) {\n super();\n const interval = config.leaseRenewIntervalMs;\n if (interval !== undefined && (!Number.isFinite(interval) || interval <= 0)) {\n throw new Error(`OrchestrationWorker: leaseRenewIntervalMs must be a positive number, got ${interval}`);\n }\n this.#config = config;\n }\n\n async init(deps: WorkerDeps): Promise<void> {\n await super.init(deps);\n\n if (!deps.mastra) {\n throw new Error('OrchestrationWorker requires Mastra instance');\n }\n\n // OrchestrationWorker drives a pull subscription on the workflow topic.\n // Push-only pubsubs (EventEmitter, GCP push subscriptions) deliver events\n // through different paths and must not be paired with this worker.\n const modes = deps.pubsub.supportedModes ?? ['pull'];\n if (!modes.includes('pull')) {\n throw new Error(\n `OrchestrationWorker requires a pull-capable PubSub, but the configured pubsub only supports: ${modes.join(', ')}. ` +\n `Either remove OrchestrationWorker from the workers list or use a pull-capable PubSub (e.g. Redis Streams).`,\n );\n }\n\n // If MASTRA_STEP_EXECUTION_URL is set, use HttpRemoteStrategy\n // (standalone worker calling back to the server for step execution).\n // The strategy reads MASTRA_WORKER_AUTH_TOKEN itself and forwards it\n // through the server's normal Mastra auth provider — there is no\n // separate \"worker secret\" gate.\n const remoteUrl = process.env.MASTRA_STEP_EXECUTION_URL;\n if (remoteUrl) {\n this.#strategy = new HttpRemoteStrategy({\n serverUrl: remoteUrl,\n });\n }\n\n this.#processor = new WorkflowEventProcessor({\n mastra: deps.mastra,\n stepExecutionStrategy: this.#strategy,\n });\n }\n\n async start(): Promise<void> {\n if (this.#running) return;\n if (!this.deps) throw new Error('OrchestrationWorker: call init() before start()');\n\n const group = this.#config.group ?? DEFAULT_GROUP;\n this.#transport = new PullTransport({ pubsub: this.deps.pubsub, group, logger: this.deps.logger });\n\n await this.#transport.start({\n route: (event, ack, nack, extend) => this.#processEvent(event, ack, nack, extend),\n });\n\n this.#running = true;\n }\n\n async stop(options?: WorkerStopOptions): Promise<void> {\n if (!this.#running) return;\n\n try {\n if (this.#transport) {\n await this.#transport.stop(options);\n this.#transport = undefined;\n }\n } finally {\n this.#running = false;\n }\n }\n\n get isRunning(): boolean {\n return this.#running;\n }\n\n async #processEvent(\n event: Event,\n ack?: () => Promise<void>,\n nack?: () => Promise<void>,\n extend?: () => Promise<void>,\n ): Promise<void> {\n if (!this.#processor) {\n throw new Error('OrchestrationWorker not initialized');\n }\n\n // The local processor is used (rather than mastra.handleWorkflowEvent)\n // because it carries the standalone-worker step-execution strategy\n // (HttpRemoteStrategy when MASTRA_STEP_EXECUTION_URL is set), which the\n // shared in-process handler doesn't have.\n // Keep the delivery's lease alive while the handler runs so the broker\n // does not redeliver a long-running step to another consumer (#24589).\n const heartbeat = extend\n ? setInterval(() => {\n extend().catch(e => {\n this.deps?.logger?.error('OrchestrationWorker: error extending event lease', { error: e });\n });\n }, this.#config.leaseRenewIntervalMs ?? DEFAULT_LEASE_RENEW_INTERVAL_MS)\n : undefined;\n let result: Awaited<ReturnType<WorkflowEventProcessor['handle']>>;\n try {\n result = await this.#processor.handle(event);\n } finally {\n if (heartbeat) clearInterval(heartbeat);\n }\n if (result.ok) {\n try {\n await ack?.();\n } catch (e) {\n this.deps?.logger?.error('OrchestrationWorker: error acking event', { error: e });\n }\n return;\n }\n\n this.deps?.logger?.error('OrchestrationWorker: error processing event', {\n type: event.type,\n runId: event.runId,\n retry: result.retry,\n });\n // Only ask the transport to redeliver on retryable failures. On terminal\n // failures (e.g. WorkflowEventProcessor exhausted its delivery budget and\n // already published workflow.fail) we ack so the poisoned event drops out\n // of the queue instead of looping forever.\n if (result.retry) {\n if (nack) {\n try {\n await nack();\n } catch (e) {\n this.deps?.logger?.error('OrchestrationWorker: error nacking event', { error: e });\n }\n }\n return;\n }\n if (ack) {\n try {\n await ack();\n } catch (e) {\n this.deps?.logger?.error('OrchestrationWorker: error acking terminal event', { error: e });\n }\n }\n }\n}\n","import { resolveAgentById } from '../../mastra/resolve-agent';\nimport type { ScheduleTarget } from '../../storage/domains/schedules/base';\nimport { computeScheduleDefinitionHash } from '../../workflows/scheduler/definition-hash';\nimport { Scheduler } from '../../workflows/scheduler/scheduler';\nimport type { SchedulerConfig } from '../../workflows/scheduler/types';\nimport { MastraWorker } from '../worker';\nimport type { WorkerDeps } from '../worker';\n\n/**\n * Drives cron-based workflow and agent schedules. On each tick it polls\n * storage for due schedules, computes next fire times, and publishes fire\n * events. Does not consume events — only produces them.\n *\n * This is the **single** scheduler code path. `Mastra.startWorkers()` adds it\n * when scheduling work exists or the scheduler is explicitly enabled.\n */\nexport class SchedulerWorker extends MastraWorker {\n readonly name = 'scheduler';\n\n #scheduler?: Scheduler;\n #config: SchedulerConfig;\n #running = false;\n\n constructor(config: SchedulerConfig = {}) {\n super();\n this.#config = config;\n }\n\n async init(deps: WorkerDeps): Promise<void> {\n await super.init(deps);\n\n if (!deps.storage) {\n deps.logger.warn('SchedulerWorker: no storage configured, scheduler will not run');\n return;\n }\n\n const schedulesStore = await deps.storage.getStore('schedules');\n if (!schedulesStore) {\n deps.logger.warn('SchedulerWorker: no schedules store available, scheduler will not run');\n return;\n }\n\n // Bind a target-existence predicate so the scheduler can reclaim\n // schedule rows whose target (workflow id or agent id) is no longer\n // registered with Mastra. `getWorkflowById` / `getAgentById` throw on\n // miss; we adapt that into a boolean.\n const mastra = this.mastra;\n const isTargetReady = mastra\n ? async (target: ScheduleTarget) => {\n if (target.type === 'workflow') {\n try {\n mastra.getWorkflowById(target.workflowId);\n return true;\n } catch {\n return false;\n }\n }\n if (target.type === 'agent') {\n // Only a *confirmed* miss (registry AND editor agree the agent is\n // gone) counts toward deletion. A transient editor/storage failure\n // is treated as ready: the schedule fires, and the execute path\n // retries resolution and records a failed trigger row without\n // deleting the schedule. Trade-off: during a sustained editor\n // outage each due tick publishes a fire that fails at execute\n // time — noisy, but never destroys a schedule on ambiguity.\n const resolved = await resolveAgentById(mastra, target.agentId);\n return resolved.status !== 'missing';\n }\n return false;\n }\n : undefined;\n\n // Bind a stale-build fence (#19169): scheduled runs execute `localOnly`\n // in the claiming process against its own workflow registry, so an\n // instance whose local step graph differs from the hash recorded on the\n // schedule row (a straggler from a previous deploy) must not claim the\n // fire. Fails open for rows without a hash (legacy/imperative\n // schedules) and for agent targets, which have no step graph.\n const isTargetCurrent = mastra\n ? (target: ScheduleTarget) => {\n if (target.type !== 'workflow' || !target.definitionHash) return true;\n try {\n const workflow = mastra.getWorkflowById(target.workflowId);\n const localHash = computeScheduleDefinitionHash(workflow.serializedStepGraph);\n // Unhashable local graph → can't compare, fail open.\n if (!localHash) return true;\n return localHash === target.definitionHash;\n } catch {\n // Missing workflow is the readiness predicate's concern.\n return true;\n }\n }\n : undefined;\n\n // Claim/execute affinity (#19169). Workers receive the *raw* pubsub, not\n // the `Mastra.pubsub` proxy that tags run-scoped workflow events\n // `localOnly`, so without this the scheduler's fire always fans out to\n // every instance on the shared topic. Evaluated per fire rather than\n // captured here because execution workers can start lazily\n // (`__ensureExecutionWorkersStarted`) after the scheduler is already up.\n const canExecuteLocally = mastra ? () => mastra.__hasLocalWorkflowExecution() : undefined;\n\n this.#scheduler = new Scheduler({\n schedulesStore,\n pubsub: deps.pubsub,\n config: { ...this.#config, isTargetReady, isTargetCurrent, canExecuteLocally },\n });\n this.#scheduler.__setLogger(deps.logger);\n\n // Register declarative schedules from workflow configs before starting\n // the tick loop. This syncs code-declared schedules to the DB.\n if (this.mastra) {\n try {\n await this.mastra.registerDeclarativeSchedules(schedulesStore);\n } catch (err) {\n deps.logger.error?.('SchedulerWorker: failed to register declarative schedules', { error: err });\n }\n }\n }\n\n async start(): Promise<void> {\n if (this.#running) return;\n if (this.#scheduler) {\n await this.#scheduler.start();\n }\n this.#running = true;\n }\n\n async stop(): Promise<void> {\n if (!this.#running) return;\n if (this.#scheduler) {\n await this.#scheduler.stop();\n }\n this.#running = false;\n }\n\n get isRunning(): boolean {\n return this.#running;\n }\n\n /** Expose the underlying scheduler for direct API access (e.g., schedule management). */\n get scheduler(): Scheduler | undefined {\n return this.#scheduler;\n }\n}\n","import { BackgroundTaskManager } from '../../background-tasks/manager';\nimport type { Mastra } from '../../mastra';\nimport { MastraWorker } from '../worker';\nimport type { WorkerDeps } from '../worker';\n\n/**\n * Minimal shape of a tool callable usable for cross-process static\n * background-task execution. We intentionally avoid pulling the full\n * `ToolAction` generic into this file — only `execute` is needed.\n */\ntype StaticToolLike = {\n execute?: (\n args: Record<string, unknown>,\n options: { toolCallId: string; messages: unknown[]; abortSignal?: AbortSignal },\n ) => Promise<unknown>;\n};\n\nexport interface BackgroundTaskWorkerConfig {\n globalConcurrency?: number;\n perAgentConcurrency?: number;\n /** Per-owner overrides of `perAgentConcurrency`, keyed by the task's `agentId`. */\n perOwnerConcurrency?: Record<string, number>;\n backpressure?: 'queue' | 'reject' | 'fallback-sync';\n defaultTimeoutMs?: number;\n}\n\n/**\n * Manages background tool execution for agents. Handles task queuing,\n * concurrency limits, and lifecycle. Subscribes to PubSub internally\n * via BackgroundTaskManager's own subscription mechanism.\n */\nexport class BackgroundTaskWorker extends MastraWorker {\n readonly name = 'backgroundTasks';\n\n #manager?: BackgroundTaskManager;\n #ownsManager = false;\n #config: BackgroundTaskWorkerConfig;\n #running = false;\n\n constructor(config: BackgroundTaskWorkerConfig = {}) {\n super();\n this.#config = config;\n }\n\n async init(deps: WorkerDeps): Promise<void> {\n await super.init(deps);\n\n // Reuse Mastra's existing BackgroundTaskManager when available so the\n // worker shares the per-task `taskContexts` registry populated by the\n // producer. Spinning up a second manager subscribes the same WORKER_GROUP\n // twice, runs `recoverStaleTasks` twice, and breaks per-task closures —\n // any task dispatched from the producer that lands on this worker's\n // duplicate manager has no `taskContexts` entry.\n const existing = deps.mastra?.backgroundTaskManager;\n if (existing) {\n this.#manager = existing;\n this.#ownsManager = false;\n return;\n }\n\n this.#createOwnedManager(deps);\n }\n\n #createOwnedManager(deps: WorkerDeps): void {\n this.#manager = new BackgroundTaskManager({\n enabled: true,\n mode: 'worker',\n globalConcurrency: this.#config.globalConcurrency,\n perAgentConcurrency: this.#config.perAgentConcurrency,\n perOwnerConcurrency: this.#config.perOwnerConcurrency,\n backpressure: this.#config.backpressure,\n defaultTimeoutMs: this.#config.defaultTimeoutMs,\n });\n this.#ownsManager = true;\n\n if (deps.mastra) {\n this.#manager.__registerMastra(deps.mastra);\n this.#wireStaticTools(deps.mastra);\n }\n }\n\n /**\n * Populate the manager's static executor registry from tools registered\n * on `Mastra`, so that cross-process dispatches can be resolved by tool\n * name on this worker. Mirrors the wiring Mastra does for its own\n * managed background-task manager — the worker owns a separate manager\n * instance, so it has to populate its own registry.\n */\n #wireStaticTools(mastra: Mastra): void {\n const listTools = (mastra as unknown as { listTools?: () => Record<string, StaticToolLike> }).listTools;\n const tools = listTools?.call(mastra);\n if (!tools || !this.#manager) return;\n for (const [name, tool] of Object.entries(tools)) {\n if (!tool || typeof tool.execute !== 'function') continue;\n const execute = tool.execute.bind(tool);\n this.#manager.registerStaticExecutor(name, {\n execute: async (args, options) => {\n return execute(args, {\n toolCallId: '',\n messages: [],\n abortSignal: options?.abortSignal,\n });\n },\n });\n }\n }\n\n async start(): Promise<void> {\n if (this.#running) return;\n if (!this.deps) {\n throw new Error('BackgroundTaskWorker: call init() before start()');\n }\n // An owned manager has a terminal shutdown lifecycle. Recreate it on a\n // direct stop → start cycle instead of attempting to reinitialize a\n // manager whose subscriptions and executor registry were released.\n if (!this.#manager) {\n this.#createOwnedManager(this.deps);\n }\n const manager = this.#manager;\n if (!manager) {\n throw new Error('BackgroundTaskWorker: failed to initialize background task manager');\n }\n // When sharing Mastra's manager, Mastra has already fired off init() in\n // its constructor as fire-and-forget. Don't re-await it here — that would\n // surface init errors twice (the constructor's `.catch` already reports\n // them) and serialize startWorkers() behind the manager's full bootstrap.\n if (this.#ownsManager) {\n await manager.init(this.deps.pubsub);\n }\n this.#running = true;\n }\n\n async stop(): Promise<void> {\n if (!this.#running) return;\n // Only tear down the manager if this worker owns it. When sharing Mastra's\n // manager, Mastra's stopWorkers() / shutdown is responsible.\n if (this.#manager && this.#ownsManager) {\n try {\n await this.#manager.shutdown();\n } finally {\n this.#manager = undefined;\n this.#ownsManager = false;\n }\n }\n this.#running = false;\n }\n\n get isRunning(): boolean {\n return this.#running;\n }\n\n /** Expose the underlying manager for direct API access. */\n get manager(): BackgroundTaskManager | undefined {\n return this.#manager;\n }\n}\n","import { RequestContext } from '../../di';\nimport type { Mastra } from '../../mastra';\nimport { StepExecutor } from '../../workflows/evented/step-executor';\nimport { getNestedWorkflow, getStepEntry } from '../../workflows/evented/workflow-event-processor/utils';\nimport type { StepResult } from '../../workflows/types';\nimport type { Workflow } from '../../workflows/workflow';\nimport type { StepExecutionParams, StepExecutionParentWorkflow, StepExecutionStrategy } from '../types';\n\n/**\n * Executes workflow steps in the same process by delegating to StepExecutor.\n * This is the default strategy used when the worker runs co-located with the server.\n */\nexport class InProcessStrategy implements StepExecutionStrategy {\n #mastra?: Mastra;\n\n constructor({ mastra }: { mastra?: Mastra } = {}) {\n this.#mastra = mastra;\n }\n\n __registerMastra(mastra: Mastra): void {\n this.#mastra = mastra;\n }\n\n async executeStep(params: StepExecutionParams): Promise<StepResult<any, any, any, any>> {\n if (!this.#mastra) {\n throw new Error('InProcessStrategy requires Mastra instance. Call __registerMastra() first.');\n }\n\n const workflow = this.#resolveWorkflow(params);\n const entry = workflow ? getStepEntry(workflow, params.executionPath) : null;\n\n if (!entry) {\n throw new Error(\n `InProcessStrategy: could not resolve step \"${params.stepId}\" at executionPath [${params.executionPath.join(',')}] in workflow \"${params.workflowId}\"`,\n );\n }\n\n const rc = new RequestContext<unknown>(Object.entries(params.requestContext ?? {}));\n\n let abortController: AbortController | undefined;\n if (params.abortSignal) {\n abortController = new AbortController();\n if (params.abortSignal.aborted) {\n abortController.abort(params.abortSignal.reason);\n } else {\n params.abortSignal.addEventListener(\n 'abort',\n () => {\n abortController!.abort(params.abortSignal!.reason);\n },\n { once: true },\n );\n }\n }\n\n const executor = new StepExecutor({ mastra: this.#mastra });\n\n return executor.execute({\n workflowId: params.workflowId,\n entry,\n runId: params.runId,\n stepResults: params.stepResults as Record<string, StepResult<any, any, any, any>>,\n state: params.state,\n requestContext: rc,\n input: params.input,\n resumeData: params.resumeData,\n retryCount: params.retryCount,\n foreachIdx: params.foreachIdx,\n validateInputs: params.validateInputs,\n abortController,\n format: params.format,\n perStep: params.perStep,\n storageVersion: params.storageVersion,\n });\n }\n\n /**\n * Resolves the workflow in the same order the dispatching\n * `WorkflowEventProcessor` does: internal registrations first, then descent\n * from the parent chain for nested workflows (which may be registered\n * nowhere), then the public registry. Public lookups go through\n * `getWorkflowById` because events carry the workflow's `id` property\n * (e.g. \"scheduled-workflow\"), not the config key (\"scheduledWorkflow\").\n */\n #resolveWorkflow(params: StepExecutionParams): Workflow | null {\n const mastra = this.#mastra!;\n if (mastra.__hasInternalWorkflow(params.workflowId, params.runId)) {\n return mastra.__getInternalWorkflow(params.workflowId, params.runId) as Workflow;\n }\n if (params.parentWorkflow) {\n return resolveNestedWorkflow(mastra, params.workflowId, params.parentWorkflow);\n }\n return mastra.getWorkflowById(params.workflowId) as Workflow;\n }\n}\n\n/**\n * Descends from `parentWorkflow` and returns the nested workflow only when it,\n * and every workflow passed on the way, has the id the request names. The\n * parent chain addresses workflows by position, so a worker and server running\n * different builds could otherwise land on a different workflow and run it.\n */\nfunction resolveNestedWorkflow(\n mastra: Mastra,\n workflowId: string,\n parentWorkflow: StepExecutionParentWorkflow,\n): Workflow | null {\n if (\n parentWorkflow.parentWorkflow &&\n !resolveNestedWorkflow(mastra, parentWorkflow.workflowId, parentWorkflow.parentWorkflow)\n ) {\n return null;\n }\n const workflow = getNestedWorkflow(mastra, parentWorkflow);\n return workflow?.id === workflowId ? workflow : null;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgCA,IAAsB,eAAtB,MAAmC;CAGjC;CACA;;CAGA,iBAAiB,QAAsB;EACrC,KAAK,SAAS;CAChB;;CAGA,MAAM,KAAK,MAAiC;EAC1C,KAAK,OAAO;EACZ,IAAI,CAAC,KAAK,UAAU,KAAK,QACvB,KAAK,SAAS,KAAK;CAEvB;AAKF;;;;;;;;;;;;;ACtBA,IAAa,qBAAb,MAAa,mBAAoD;CAC/D;CACA;CACA;CAEA,YAAY,EAAE,WAAW,MAAM,aAAqF;EAElH,MAAM,aAAa,UAAU,SAAS,GAAG,IAAI,YAAY,GAAG,UAAU;EACtE,KAAK,WAAW,IAAI,IAAI,UAAU;EAClC,KAAK,QAAQ,QAAQ,mBAAmB,aAAa;EACrD,KAAK,aAAa,aAAa;CACjC;;;;;;CAOA,OAAO,eAAiD;EACtD,MAAM,QAAQ,QAAQ,IAAI;EAC1B,IAAI,CAAC,OAAO,OAAO,KAAA;EACnB,OAAO;GAAE,MAAM;GAAU;EAAM;CACjC;CAEA,MAAM,YAAY,QAAsF;EACtG,MAAM,MAAM,IAAI,IACd,aAAa,mBAAmB,OAAO,UAAU,EAAE,QAAQ,mBAAmB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