@mastra/core 1.55.0-alpha.2 → 1.55.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +86 -0
- package/dist/agent/agent.d.ts.map +1 -1
- package/dist/agent/durable/index.cjs +1 -1
- package/dist/agent/durable/index.js +1 -1
- package/dist/agent/index.cjs +2 -2
- package/dist/agent/index.js +2 -2
- package/dist/{agent-BvRfRKIt.js → agent-0y2cApTZ.js} +57 -82
- package/dist/agent-0y2cApTZ.js.map +1 -0
- package/dist/agent-builder/ee/index.cjs +1 -1
- package/dist/agent-builder/ee/index.js +1 -1
- package/dist/agent-controller/index.cjs +1 -1
- package/dist/agent-controller/index.js +1 -1
- package/dist/{agent-controller-CM6tQSMj.js → agent-controller-ByW51eCC.js} +5 -5
- package/dist/{agent-controller-CM6tQSMj.js.map → agent-controller-ByW51eCC.js.map} +1 -1
- package/dist/{agent-controller-C75dc544.cjs → agent-controller-DahKlMET.cjs} +5 -5
- package/dist/{agent-controller-C75dc544.cjs.map → agent-controller-DahKlMET.cjs.map} +1 -1
- package/dist/{agent-CwUYflGG.cjs → agent-um2LJs-0.cjs} +57 -82
- package/dist/agent-um2LJs-0.cjs.map +1 -0
- package/dist/background-tasks/index.cjs +1 -1
- package/dist/background-tasks/index.js +1 -1
- package/dist/{background-tasks-AKlv5tIo.js → background-tasks-CM94BIj8.js} +2 -2
- package/dist/{background-tasks-AKlv5tIo.js.map → background-tasks-CM94BIj8.js.map} +1 -1
- package/dist/{background-tasks-Chpan7PB.cjs → background-tasks-CobPW4Z3.cjs} +2 -2
- package/dist/{background-tasks-Chpan7PB.cjs.map → background-tasks-CobPW4Z3.cjs.map} +1 -1
- package/dist/browser/index.cjs +1 -1
- package/dist/browser/index.js +1 -1
- package/dist/channels/index.cjs +2 -2
- package/dist/channels/index.js +2 -2
- package/dist/{channels-BW52ccH_.cjs → channels-BgbloDjB.cjs} +2 -2
- package/dist/{channels-BW52ccH_.cjs.map → channels-BgbloDjB.cjs.map} +1 -1
- package/dist/{channels-Da9lEAi1.js → channels-MegO_4KL.js} +2 -2
- package/dist/{channels-Da9lEAi1.js.map → channels-MegO_4KL.js.map} +1 -1
- package/dist/coding-agent/index.cjs +1 -1
- package/dist/coding-agent/index.js +1 -1
- package/dist/{create-durable-agent-DmTTvoGi.cjs → create-durable-agent-ChmjQwzE.cjs} +8 -8
- package/dist/{create-durable-agent-DmTTvoGi.cjs.map → create-durable-agent-ChmjQwzE.cjs.map} +1 -1
- package/dist/{create-durable-agent-Bd4Bm5FV.js → create-durable-agent-DH_dWTMR.js} +8 -8
- package/dist/{create-durable-agent-Bd4Bm5FV.js.map → create-durable-agent-DH_dWTMR.js.map} +1 -1
- package/dist/datasets/index.cjs +1 -1
- package/dist/datasets/index.js +1 -1
- package/dist/{dist-C077BlAN.js → dist-BZBxELZo.js} +2 -2
- package/dist/{dist-C077BlAN.js.map → dist-BZBxELZo.js.map} +1 -1
- package/dist/{dist-CsR_D1uk.cjs → dist-ftJxyNRx.cjs} +2 -2
- package/dist/{dist-CsR_D1uk.cjs.map → dist-ftJxyNRx.cjs.map} +1 -1
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +1 -1
- package/dist/evals/index.cjs +1 -1
- package/dist/evals/index.js +1 -1
- package/dist/evals/scoreTraces/index.cjs +1 -1
- package/dist/evals/scoreTraces/index.js +1 -1
- package/dist/harness/index.cjs +1 -1
- package/dist/harness/index.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/llm/index.cjs +5 -5
- package/dist/llm/index.js +5 -5
- package/dist/{llm-DlVyw1cX.js → llm-DGuYy_Nx.js} +5 -5
- package/dist/{llm-DlVyw1cX.js.map → llm-DGuYy_Nx.js.map} +1 -1
- package/dist/{llm-Bjt2hZ3f.cjs → llm-DmAhSSgh.cjs} +5 -5
- package/dist/{llm-Bjt2hZ3f.cjs.map → llm-DmAhSSgh.cjs.map} +1 -1
- package/dist/loop/index.cjs +1 -1
- package/dist/loop/index.js +1 -1
- package/dist/{manager-CYGpXJfK.js → manager-DDRcONBK.js} +3 -3
- package/dist/{manager-CYGpXJfK.js.map → manager-DDRcONBK.js.map} +1 -1
- package/dist/{manager-BjrFnt_A.cjs → manager-DqHiikx1.cjs} +3 -3
- package/dist/{manager-BjrFnt_A.cjs.map → manager-DqHiikx1.cjs.map} +1 -1
- package/dist/mastra/index.cjs +1 -1
- package/dist/mastra/index.js +1 -1
- package/dist/{mastra-CVLF1dWt.js → mastra-B6CffFOC.js} +9 -9
- package/dist/{mastra-CVLF1dWt.js.map → mastra-B6CffFOC.js.map} +1 -1
- package/dist/{mastra-Bxx9WPf6.cjs → mastra-BlT9srQJ.cjs} +9 -9
- package/dist/{mastra-Bxx9WPf6.cjs.map → mastra-BlT9srQJ.cjs.map} +1 -1
- package/dist/memory/index.cjs +1 -1
- package/dist/memory/index.js +1 -1
- package/dist/{model-CA0WLISt.js → model-DQzxkQqM.js} +2 -2
- package/dist/{model-CA0WLISt.js.map → model-DQzxkQqM.js.map} +1 -1
- package/dist/{model-DMVq6nAS.cjs → model-Iow-mV9i.cjs} +2 -2
- package/dist/{model-DMVq6nAS.cjs.map → model-Iow-mV9i.cjs.map} +1 -1
- package/dist/{models-dev-Cbus1Uh2.js → models-dev-BFOUCgyS.js} +2 -2
- package/dist/{models-dev-Cbus1Uh2.js.map → models-dev-BFOUCgyS.js.map} +1 -1
- package/dist/{models-dev-D_X4VMSu.cjs → models-dev-BUEaCBxL.cjs} +2 -2
- package/dist/{models-dev-D_X4VMSu.cjs.map → models-dev-BUEaCBxL.cjs.map} +1 -1
- package/dist/{netlify-C-nnPVSj.js → netlify-7eHXUkln.js} +2 -2
- package/dist/{netlify-C-nnPVSj.js.map → netlify-7eHXUkln.js.map} +1 -1
- package/dist/{netlify-CUuCnmtd.cjs → netlify-Db5icdAJ.cjs} +2 -2
- package/dist/{netlify-CUuCnmtd.cjs.map → netlify-Db5icdAJ.cjs.map} +1 -1
- package/dist/processor-provider/index.cjs +1 -1
- package/dist/processor-provider/index.js +1 -1
- package/dist/processors/index.cjs +2 -2
- package/dist/processors/index.js +2 -2
- package/dist/processors/processors/index.d.ts +1 -1
- package/dist/processors/processors/index.d.ts.map +1 -1
- package/dist/processors/tool-result-reminder.d.ts +23 -0
- package/dist/processors/tool-result-reminder.d.ts.map +1 -1
- package/dist/{provider-registry-BFknh6Fu.cjs → provider-registry-DRJihW5_.cjs} +6 -6
- package/dist/{provider-registry-BFknh6Fu.cjs.map → provider-registry-DRJihW5_.cjs.map} +1 -1
- package/dist/{provider-registry-DIbls44Z.js → provider-registry-DzSSAz1R.js} +6 -6
- package/dist/{provider-registry-DIbls44Z.js.map → provider-registry-DzSSAz1R.js.map} +1 -1
- package/dist/relevance/index.cjs +2 -2
- package/dist/relevance/index.js +2 -2
- package/dist/stream/index.cjs +3 -3
- package/dist/stream/index.js +3 -3
- package/dist/{stream-tlVjYkAO.cjs → stream-D-cHV05r.cjs} +3 -3
- package/dist/{stream-tlVjYkAO.cjs.map → stream-D-cHV05r.cjs.map} +1 -1
- package/dist/{stream-Cd_isEZJ.js → stream-DJaosaeO.js} +3 -3
- package/dist/{stream-Cd_isEZJ.js.map → stream-DJaosaeO.js.map} +1 -1
- package/dist/test-utils/llm-mock.cjs +1 -1
- package/dist/test-utils/llm-mock.js +1 -1
- package/dist/tool-loop-agent/index.cjs +1 -1
- package/dist/tool-loop-agent/index.js +1 -1
- package/dist/{tool-loop-agent-th9L-ls9.cjs → tool-loop-agent-ByrutV2Q.cjs} +4 -4
- package/dist/{tool-loop-agent-th9L-ls9.cjs.map → tool-loop-agent-ByrutV2Q.cjs.map} +1 -1
- package/dist/{tool-loop-agent-CcT-TTcT.js → tool-loop-agent-BzHXZDL3.js} +4 -4
- package/dist/{tool-loop-agent-CcT-TTcT.js.map → tool-loop-agent-BzHXZDL3.js.map} +1 -1
- package/dist/{trip-wire-Cj0cJivR.js → trip-wire-DxpTS3jV.js} +2 -2
- package/dist/{trip-wire-Cj0cJivR.js.map → trip-wire-DxpTS3jV.js.map} +1 -1
- package/dist/{trip-wire-BNzxirr0.cjs → trip-wire-utCESgMt.cjs} +2 -2
- package/dist/{trip-wire-BNzxirr0.cjs.map → trip-wire-utCESgMt.cjs.map} +1 -1
- package/dist/{utils-BoQofieM.cjs → utils-CPUQn5dX.cjs} +2 -2
- package/dist/{utils-BoQofieM.cjs.map → utils-CPUQn5dX.cjs.map} +1 -1
- package/dist/{utils-DUfAZ4gr.js → utils-CrKEOVUo.js} +2 -2
- package/dist/{utils-DUfAZ4gr.js.map → utils-CrKEOVUo.js.map} +1 -1
- package/dist/utils.cjs +1 -1
- package/dist/utils.js +1 -1
- package/dist/worker/index.cjs +1 -1
- package/dist/worker/index.js +1 -1
- package/dist/{worker-DwlyX5l8.js → worker-Ciya6mfo.js} +3 -3
- package/dist/{worker-DwlyX5l8.js.map → worker-Ciya6mfo.js.map} +1 -1
- package/dist/{worker-CsbZPhWb.cjs → worker-YT_pMttZ.cjs} +3 -3
- package/dist/{worker-CsbZPhWb.cjs.map → worker-YT_pMttZ.cjs.map} +1 -1
- package/dist/{workflow-BR5D6ij_.cjs → workflow-DcS_0R0Z.cjs} +3 -3
- package/dist/{workflow-BR5D6ij_.cjs.map → workflow-DcS_0R0Z.cjs.map} +1 -1
- package/dist/{workflow-OjZRiiCG.js → workflow-k6s0ESOR.js} +3 -3
- package/dist/{workflow-OjZRiiCG.js.map → workflow-k6s0ESOR.js.map} +1 -1
- package/dist/workflows/evented/index.cjs +1 -1
- package/dist/workflows/evented/index.js +1 -1
- package/dist/workflows/index.cjs +1 -1
- package/dist/workflows/index.js +1 -1
- package/package.json +12 -12
- package/dist/agent-BvRfRKIt.js.map +0 -1
- package/dist/agent-CwUYflGG.cjs.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-DwlyX5l8.js","names":["#baseUrl","#auth","#authFromEnv","#timeoutMs","#buildBody","#combineSignals","#buildAuthHeaders","#config","#strategy","#processor","#running","#transport","#processEvent","#config","#scheduler","#running","#config","#manager","#ownsManager","#wireStaticTools","#running","#mastra"],"sources":["../src/worker/strategies/http-remote-strategy.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 { 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 { 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 } from '../worker';\n\nconst DEFAULT_GROUP = 'mastra-orchestration';\n\nexport interface OrchestrationWorkerConfig {\n group?: string;\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 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) => this.#processEvent(event, ack, nack),\n });\n\n this.#running = true;\n }\n\n async stop(): Promise<void> {\n if (!this.#running) return;\n\n try {\n if (this.#transport) {\n await this.#transport.stop();\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(event: Event, ack?: () => Promise<void>, nack?: () => Promise<void>): 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 const result = await this.#processor.handle(event);\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 type { IMastraLogger } from '../../logger';\nimport type { ScheduleTarget } from '../../storage/domains/schedules/base';\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 schedules. On each tick it polls storage\n * for due schedules, computes next fire times, and publishes\n * workflow.start events. Does not consume events — only produces them.\n *\n * This is the **single** scheduler code path. The Mastra constructor\n * adds the worker to the default workers list (guarded by\n * `#shouldEnableScheduler()`), and `startWorkers()` initializes it.\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 ? (target: ScheduleTarget) => {\n try {\n if (target.type === 'workflow') {\n mastra.getWorkflowById(target.workflowId);\n return true;\n }\n if (target.type === 'agent') {\n mastra.getAgentById(target.agentId);\n return true;\n }\n return false;\n } catch {\n return false;\n }\n }\n : undefined;\n\n this.#scheduler = new Scheduler({\n schedulesStore,\n pubsub: deps.pubsub,\n config: { ...this.#config, isTargetReady },\n });\n this.#scheduler.__setLogger(deps.logger as IMastraLogger);\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 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.#manager = new BackgroundTaskManager({\n enabled: true,\n mode: 'worker',\n globalConcurrency: this.#config.globalConcurrency,\n perAgentConcurrency: this.#config.perAgentConcurrency,\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.#manager || !this.deps) {\n throw new Error('BackgroundTaskWorker: call init() before start()');\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 this.#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 await this.#manager.shutdown();\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 { getStep } from '../../workflows/evented/workflow-event-processor/utils';\nimport type { StepResult } from '../../workflows/types';\nimport type { StepExecutionParams, 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 // Use getWorkflowById — events carry the workflow's `id` property\n // (e.g. \"scheduled-workflow\"), not the config key (\"scheduledWorkflow\").\n const workflow = this.#mastra.getWorkflowById(params.workflowId);\n const step = getStep(workflow, params.executionPath);\n\n if (!step) {\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 step,\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 });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgCA,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,KAAKA,WAAW,IAAI,IAAI,UAAU;EAClC,KAAKC,QAAQ,QAAQ,mBAAmBC,aAAa;EACrD,KAAKC,aAAa,aAAa;CACjC;;;;;;CAOA,OAAOD,eAAiD;EACtD,MAAM,QAAQ,QAAQ,IAAI;EAC1B,IAAI,CAAC,OAAO,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M;GACnD,GACA,EAAE,MAAM,KAAK,CACf;EAEJ;EAIA,OAAO,IAFc,aAAa,EAAE,QAAQ,KAAKA,QAAQ,CAE3C,CAAC,CAAC,QAAQ;GACtB,YAAY,OAAO;GACnB;GACA,OAAO,OAAO;GACd,aAAa,OAAO;GACpB,OAAO,OAAO;GACd,gBAAgB;GAChB,OAAO,OAAO;GACd,YAAY,OAAO;GACnB,YAAY,OAAO;GACnB,YAAY,OAAO;GACnB,gBAAgB,OAAO;GACvB;GACA,QAAQ,OAAO;GACf,SAAS,OAAO;EAClB,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"worker-Ciya6mfo.js","names":["#baseUrl","#auth","#authFromEnv","#timeoutMs","#buildBody","#combineSignals","#buildAuthHeaders","#config","#strategy","#processor","#running","#transport","#processEvent","#config","#scheduler","#running","#config","#manager","#ownsManager","#wireStaticTools","#running","#mastra"],"sources":["../src/worker/strategies/http-remote-strategy.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 { 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 { 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 } from '../worker';\n\nconst DEFAULT_GROUP = 'mastra-orchestration';\n\nexport interface OrchestrationWorkerConfig {\n group?: string;\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 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) => this.#processEvent(event, ack, nack),\n });\n\n this.#running = true;\n }\n\n async stop(): Promise<void> {\n if (!this.#running) return;\n\n try {\n if (this.#transport) {\n await this.#transport.stop();\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(event: Event, ack?: () => Promise<void>, nack?: () => Promise<void>): 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 const result = await this.#processor.handle(event);\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 type { IMastraLogger } from '../../logger';\nimport type { ScheduleTarget } from '../../storage/domains/schedules/base';\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 schedules. On each tick it polls storage\n * for due schedules, computes next fire times, and publishes\n * workflow.start events. Does not consume events — only produces them.\n *\n * This is the **single** scheduler code path. The Mastra constructor\n * adds the worker to the default workers list (guarded by\n * `#shouldEnableScheduler()`), and `startWorkers()` initializes it.\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 ? (target: ScheduleTarget) => {\n try {\n if (target.type === 'workflow') {\n mastra.getWorkflowById(target.workflowId);\n return true;\n }\n if (target.type === 'agent') {\n mastra.getAgentById(target.agentId);\n return true;\n }\n return false;\n } catch {\n return false;\n }\n }\n : undefined;\n\n this.#scheduler = new Scheduler({\n schedulesStore,\n pubsub: deps.pubsub,\n config: { ...this.#config, isTargetReady },\n });\n this.#scheduler.__setLogger(deps.logger as IMastraLogger);\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 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.#manager = new BackgroundTaskManager({\n enabled: true,\n mode: 'worker',\n globalConcurrency: this.#config.globalConcurrency,\n perAgentConcurrency: this.#config.perAgentConcurrency,\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.#manager || !this.deps) {\n throw new Error('BackgroundTaskWorker: call init() before start()');\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 this.#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 await this.#manager.shutdown();\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 { getStep } from '../../workflows/evented/workflow-event-processor/utils';\nimport type { StepResult } from '../../workflows/types';\nimport type { StepExecutionParams, 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 // Use getWorkflowById — events carry the workflow's `id` property\n // (e.g. \"scheduled-workflow\"), not the config key (\"scheduledWorkflow\").\n const workflow = this.#mastra.getWorkflowById(params.workflowId);\n const step = getStep(workflow, params.executionPath);\n\n if (!step) {\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 step,\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 });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgCA,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,KAAKA,WAAW,IAAI,IAAI,UAAU;EAClC,KAAKC,QAAQ,QAAQ,mBAAmBC,aAAa;EACrD,KAAKC,aAAa,aAAa;CACjC;;;;;;CAOA,OAAOD,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,OAAO,KAAK,EAAE,iBAC5F,KAAKF,QACP;EAEA,MAAM,OAAO,KAAKI,WAAW,MAAM;EAEnC,MAAM,SAAS,KAAKC,gBAAgB,OAAO,WAAW;EAEtD,MAAM,MAAM,MAAM,MAAM,KAAK;GAC3B,QAAQ;GACR,SAAS;IACP,gBAAgB;IAChB,GAAG,KAAKC,kBAAkB;GAC5B;GACA;GACA;EACF,CAAC;EAED,IAAI,CAAC,IAAI,IAAI;GACX,MAAM,OAAO,MAAM,IAAI,KAAK;GAC5B,MAAM,IAAI,mBAAmB,IAAI,QAAQ,IAAI;EAC/C;EAEA,OAAO,IAAI,KAAK;CAClB;;;;;;;;;CAUA,WAAW,QAAqC;EAC9C,MAAM,EAAE,aAAa,cAAc,gBAAgB,GAAG,SAAS;EAC/D,IAAI;EACJ,IAAI;GACF,qBAAqB,KAAK,MAAM,KAAK,UAAU,kBAAkB,CAAC,CAAC,CAAC;EACtE,SAAS,KAAK;GACZ,MAAM,IAAI,MACR,gEAAgE,e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,KAAKA,QAAQ,gBAAgB,OAAO,UACzB,GAAG,OAAO,aAAa;EAEnD,IAAI,CAAC,MACH,MAAM,IAAI,MACR,8CAA8C,OAAO,OAAO,sBAAsB,OAAO,cAAc,KAAK,GAAG,EAAE,iBAAiB,OAAO,WAAW,EACtJ;EAGF,MAAM,KAAK,IAAI,eAAwB,OAAO,QAAQ,OAAO,kBAAkB,CAAC,CAAC,CAAC;EAElF,IAAI;EACJ,IAAI,OAAO,aAAa;GACtB,kBAAkB,IAAI,gBAAgB;GACtC,IAAI,OAAO,YAAY,SACrB,gBAAgB,MAAM,OAAO,YAAY,MAAM;QAE/C,OAAO,YAAY,iBACjB,eACM;IACJ,gBAAiB,MAAM,OAAO,YAAa,MAAM;GACnD,GACA,EAAE,MAAM,KAAK,CACf;EAEJ;EAIA,OAAO,IAFc,aAAa,EAAE,QAAQ,KAAKA,QAAQ,CAE3C,CAAC,CAAC,QAAQ;GACtB,YAAY,OAAO;GACnB;GACA,OAAO,OAAO;GACd,aAAa,OAAO;GACpB,OAAO,OAAO;GACd,gBAAgB;GAChB,OAAO,OAAO;GACd,YAAY,OAAO;GACnB,YAAY,OAAO;GACnB,YAAY,OAAO;GACnB,gBAAgB,OAAO;GACvB;GACA,QAAQ,OAAO;GACf,SAAS,OAAO;EAClB,CAAC;CACH;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
const require_request_context = require("./request-context-C6X9IcNF.cjs");
|
|
2
|
-
const require_background_tasks = require("./background-tasks-
|
|
3
|
-
const require_agent = require("./agent-
|
|
2
|
+
const require_background_tasks = require("./background-tasks-CobPW4Z3.cjs");
|
|
3
|
+
const require_agent = require("./agent-um2LJs-0.cjs");
|
|
4
4
|
const require_scheduler = require("./scheduler-DhXuncOg.cjs");
|
|
5
5
|
const require_pull_transport = require("./pull-transport-BlEVfOcc.cjs");
|
|
6
6
|
//#region src/worker/strategies/http-remote-strategy.ts
|
|
@@ -443,4 +443,4 @@ Object.defineProperty(exports, "StepExecutionError", {
|
|
|
443
443
|
}
|
|
444
444
|
});
|
|
445
445
|
|
|
446
|
-
//# sourceMappingURL=worker-
|
|
446
|
+
//# sourceMappingURL=worker-YT_pMttZ.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-CsbZPhWb.cjs","names":["#baseUrl","#auth","#authFromEnv","#timeoutMs","#buildBody","#combineSignals","#buildAuthHeaders","MastraWorker","#config","#strategy","#processor","WorkflowEventProcessor","#running","#transport","PullTransport","#processEvent","MastraWorker","#config","#scheduler","Scheduler","#running","MastraWorker","#config","#manager","#ownsManager","BackgroundTaskManager","#wireStaticTools","#running","#mastra","getStep","RequestContext","StepExecutor"],"sources":["../src/worker/strategies/http-remote-strategy.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 { 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 { 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 } from '../worker';\n\nconst DEFAULT_GROUP = 'mastra-orchestration';\n\nexport interface OrchestrationWorkerConfig {\n group?: string;\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 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) => this.#processEvent(event, ack, nack),\n });\n\n this.#running = true;\n }\n\n async stop(): Promise<void> {\n if (!this.#running) return;\n\n try {\n if (this.#transport) {\n await this.#transport.stop();\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(event: Event, ack?: () => Promise<void>, nack?: () => Promise<void>): 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 const result = await this.#processor.handle(event);\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 type { IMastraLogger } from '../../logger';\nimport type { ScheduleTarget } from '../../storage/domains/schedules/base';\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 schedules. On each tick it polls storage\n * for due schedules, computes next fire times, and publishes\n * workflow.start events. Does not consume events — only produces them.\n *\n * This is the **single** scheduler code path. The Mastra constructor\n * adds the worker to the default workers list (guarded by\n * `#shouldEnableScheduler()`), and `startWorkers()` initializes it.\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 ? (target: ScheduleTarget) => {\n try {\n if (target.type === 'workflow') {\n mastra.getWorkflowById(target.workflowId);\n return true;\n }\n if (target.type === 'agent') {\n mastra.getAgentById(target.agentId);\n return true;\n }\n return false;\n } catch {\n return false;\n }\n }\n : undefined;\n\n this.#scheduler = new Scheduler({\n schedulesStore,\n pubsub: deps.pubsub,\n config: { ...this.#config, isTargetReady },\n });\n this.#scheduler.__setLogger(deps.logger as IMastraLogger);\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 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.#manager = new BackgroundTaskManager({\n enabled: true,\n mode: 'worker',\n globalConcurrency: this.#config.globalConcurrency,\n perAgentConcurrency: this.#config.perAgentConcurrency,\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.#manager || !this.deps) {\n throw new Error('BackgroundTaskWorker: call init() before start()');\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 this.#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 await this.#manager.shutdown();\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 { getStep } from '../../workflows/evented/workflow-event-processor/utils';\nimport type { StepResult } from '../../workflows/types';\nimport type { StepExecutionParams, 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 // Use getWorkflowById — events carry the workflow's `id` property\n // (e.g. \"scheduled-workflow\"), not the config key (\"scheduledWorkflow\").\n const workflow = this.#mastra.getWorkflowById(params.workflowId);\n const step = getStep(workflow, params.executionPath);\n\n if (!step) {\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 step,\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 });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgCA,IAAa,qBAAb,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aAAa;EAEnD,IAAI,CAAC,MACH,MAAM,IAAI,MACR,8CAA8C,OAAO,OAAO,sBAAsB,OAAO,cAAc,KAAK,GAAG,EAAE,iBAAiB,OAAO,WAAW,EACtJ;EAGF,MAAM,KAAK,IAAIE,wBAAAA,eAAwB,OAAO,QAAQ,OAAO,kBAAkB,CAAC,CAAC,CAAC;EAElF,IAAI;EACJ,IAAI,OAAO,aAAa;GACtB,kBAAkB,IAAI,gBAAgB;GACtC,IAAI,OAAO,YAAY,SACrB,gBAAgB,MAAM,OAAO,YAAY,MAAM;QAE/C,OAAO,YAAY,iBACjB,eACM;IACJ,gBAAiB,MAAM,OAAO,YAAa,MAAM;GACnD,GACA,EAAE,MAAM,KAAK,CACf;EAEJ;EAIA,OAAO,IAFcC,cAAAA,aAAa,EAAE,QAAQ,KAAKH,QAAQ,CAE3C,CAAC,CAAC,QAAQ;GACtB,YAAY,OAAO;GACnB;GACA,OAAO,OAAO;GACd,aAAa,OAAO;GACpB,OAAO,OAAO;GACd,gBAAgB;GAChB,OAAO,OAAO;GACd,YAAY,OAAO;GACnB,YAAY,OAAO;GACnB,YAAY,OAAO;GACnB,gBAAgB,OAAO;GACvB;GACA,QAAQ,OAAO;GACf,SAAS,OAAO;EAClB,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"worker-YT_pMttZ.cjs","names":["#baseUrl","#auth","#authFromEnv","#timeoutMs","#buildBody","#combineSignals","#buildAuthHeaders","MastraWorker","#config","#strategy","#processor","WorkflowEventProcessor","#running","#transport","PullTransport","#processEvent","MastraWorker","#config","#scheduler","Scheduler","#running","MastraWorker","#config","#manager","#ownsManager","BackgroundTaskManager","#wireStaticTools","#running","#mastra","getStep","RequestContext","StepExecutor"],"sources":["../src/worker/strategies/http-remote-strategy.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 { 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 { 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 } from '../worker';\n\nconst DEFAULT_GROUP = 'mastra-orchestration';\n\nexport interface OrchestrationWorkerConfig {\n group?: string;\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 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) => this.#processEvent(event, ack, nack),\n });\n\n this.#running = true;\n }\n\n async stop(): Promise<void> {\n if (!this.#running) return;\n\n try {\n if (this.#transport) {\n await this.#transport.stop();\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(event: Event, ack?: () => Promise<void>, nack?: () => Promise<void>): 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 const result = await this.#processor.handle(event);\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 type { IMastraLogger } from '../../logger';\nimport type { ScheduleTarget } from '../../storage/domains/schedules/base';\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 schedules. On each tick it polls storage\n * for due schedules, computes next fire times, and publishes\n * workflow.start events. Does not consume events — only produces them.\n *\n * This is the **single** scheduler code path. The Mastra constructor\n * adds the worker to the default workers list (guarded by\n * `#shouldEnableScheduler()`), and `startWorkers()` initializes it.\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 ? (target: ScheduleTarget) => {\n try {\n if (target.type === 'workflow') {\n mastra.getWorkflowById(target.workflowId);\n return true;\n }\n if (target.type === 'agent') {\n mastra.getAgentById(target.agentId);\n return true;\n }\n return false;\n } catch {\n return false;\n }\n }\n : undefined;\n\n this.#scheduler = new Scheduler({\n schedulesStore,\n pubsub: deps.pubsub,\n config: { ...this.#config, isTargetReady },\n });\n this.#scheduler.__setLogger(deps.logger as IMastraLogger);\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 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.#manager = new BackgroundTaskManager({\n enabled: true,\n mode: 'worker',\n globalConcurrency: this.#config.globalConcurrency,\n perAgentConcurrency: this.#config.perAgentConcurrency,\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.#manager || !this.deps) {\n throw new Error('BackgroundTaskWorker: call init() before start()');\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 this.#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 await this.#manager.shutdown();\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 { getStep } from '../../workflows/evented/workflow-event-processor/utils';\nimport type { StepResult } from '../../workflows/types';\nimport type { StepExecutionParams, 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 // Use getWorkflowById — events carry the workflow's `id` property\n // (e.g. \"scheduled-workflow\"), not the config key (\"scheduledWorkflow\").\n const workflow = this.#mastra.getWorkflowById(params.workflowId);\n const step = getStep(workflow, params.executionPath);\n\n if (!step) {\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 step,\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 });\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAgCA,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,KAAKA,WAAW,IAAI,IAAI,UAAU;EAClC,KAAKC,QAAQ,QAAQ,mBAAmBC,aAAa;EACrD,KAAKC,aAAa,aAAa;CACjC;;;;;;CAOA,OAAOD,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,OAAO,KAAK,EAAE,iBAC5F,KAAKF,QACP;EAEA,MAAM,OAAO,KAAKI,WAAW,MAAM;EAEnC,MAAM,SAAS,KAAKC,gBAAg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,aAAa,OAAO;GACpB,OAAO,OAAO;GACd,gBAAgB;GAChB,OAAO,OAAO;GACd,YAAY,OAAO;GACnB,YAAY,OAAO;GACnB,YAAY,OAAO;GACnB,gBAAgB,OAAO;GACvB;GACA,QAAQ,OAAO;GACf,SAAS,OAAO;EAClB,CAAC;CACH;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
require("./tracing-lPEd0a_y.cjs");
|
|
2
|
-
const require_background_tasks = require("./background-tasks-
|
|
3
|
-
const require_agent = require("./agent-
|
|
2
|
+
const require_background_tasks = require("./background-tasks-CobPW4Z3.cjs");
|
|
3
|
+
const require_agent = require("./agent-um2LJs-0.cjs");
|
|
4
4
|
let zod = require("zod");
|
|
5
5
|
//#region src/background-tasks/workflow.ts
|
|
6
6
|
const inputSchema = zod.z.object({ taskId: zod.z.string() });
|
|
@@ -285,4 +285,4 @@ function buildBackgroundTaskWorkflow(manager) {
|
|
|
285
285
|
//#endregion
|
|
286
286
|
exports.buildBackgroundTaskWorkflow = buildBackgroundTaskWorkflow;
|
|
287
287
|
|
|
288
|
-
//# sourceMappingURL=workflow-
|
|
288
|
+
//# sourceMappingURL=workflow-DcS_0R0Z.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workflow-BR5D6ij_.cjs","names":["z","createStep","createWorkflow","BACKGROUND_TASK_WORKFLOW_ID"],"sources":["../src/background-tasks/workflow.ts"],"sourcesContent":["import { z } from 'zod';\nimport { InternalSpans } from '../observability';\nimport type { SuspendOptions } from '../workflows';\nimport { createStep, createWorkflow } from '../workflows';\nimport type { BackgroundTaskManager } from './manager';\nimport type { BackgroundTaskStatus } from './types';\nimport { BACKGROUND_TASK_WORKFLOW_ID } from './workflow-id';\n\nexport { BACKGROUND_TASK_WORKFLOW_ID } from './workflow-id';\n\nconst inputSchema = z.object({ taskId: z.string() });\n\nconst attemptOutcomeSchema = z.enum(['success', 'retry', 'failed', 'cancelled', 'timed_out']);\n\nconst attemptOutputSchema = z.object({\n taskId: z.string(),\n outcome: attemptOutcomeSchema,\n result: z.unknown().optional(),\n error: z.any().optional(),\n});\n\nconst bodyIOSchema = z.object({\n taskId: z.string(),\n done: z.boolean().optional(),\n result: z.unknown().optional(),\n});\n\nconst bodyOutputSchema = z.object({\n taskId: z.string(),\n done: z.boolean(),\n result: z.unknown().optional(),\n});\n\nconst WORKFLOW_STATUS_TO_PERSIST = ['suspended', 'pending', 'paused', 'waiting'];\n\n/**\n * Builds the per-task workflow that owns executor + retries.\n *\n * Uses the standard (default) execution engine so the workflow runs entirely\n * in-process on whatever host calls `run.start()`. This is critical for\n * distributed deployments where the background-task worker must\n * execute tools locally — routing through the evented pipeline would send\n * step execution to the orchestration worker / API, which don't have the\n * internal workflow or task contexts registered.\n *\n * Shape: outer workflow runs an inner `[run-attempt, classify-outcome]`\n * workflow inside a `dountil` loop. `run-attempt` invokes the executor and\n * categorises the outcome; `classify-outcome` persists final state, advances\n * retry bookkeeping, and decides whether the loop is done. The dountil\n * predicate exits on `done === true`.\n *\n * Step bodies close over `manager` directly — the bg-tasks layer is the only\n * consumer of the `@internal` private fields.\n */\nexport function buildBackgroundTaskWorkflow(manager: BackgroundTaskManager) {\n const runAttemptStep = createStep({\n id: 'run-attempt',\n inputSchema: bodyIOSchema,\n outputSchema: attemptOutputSchema,\n execute: async ({ inputData, abortSignal: workflowAbortSignal, suspend, resumeData }) => {\n const { taskId } = inputData;\n const storage = await manager.getStorage();\n const task = await storage.getTask(taskId);\n if (!task || task.status === 'cancelled') {\n manager.deregisterTaskContext(taskId);\n return { taskId, outcome: 'cancelled' as const };\n }\n\n // Resolve the executor. Two paths:\n // 1. Per-task `TaskContext` registered on the producer (in-process).\n // Carries closure-captured state (e.g. agent memory hooks) and\n // wins when present.\n // 2. Static executor registered by tool name. Used by remote workers\n // that received the dispatch via PubSub and don't have access to\n // the producer's per-task closure. Agent-owned executors are\n // namespaced as `agentId:toolName` to avoid cross-agent collisions;\n // we try the namespaced key first, then fall back to the plain key.\n const ctx = manager.taskContexts.get(taskId);\n const executor =\n ctx?.executor ??\n (task.agentId ? manager.getStaticExecutor(`${task.agentId}:${task.toolName}`) : undefined) ??\n manager.getStaticExecutor(task.toolName);\n if (!executor) {\n const errorInfo = {\n message:\n `No executor registered for tool \"${task.toolName}\". ` +\n `Register the tool on Mastra (so workers can resolve it cross-process) ` +\n `or run the task in the same process as the producer.`,\n };\n await storage.updateTask(taskId, { status: 'failed', error: errorInfo, completedAt: new Date() });\n const failedTask = await storage.getTask(taskId);\n if (failedTask) {\n await manager.runLocalCompletionHooks(failedTask, 'failed', { error: errorInfo });\n await manager.publishLifecycleEvent('task.failed', failedTask);\n }\n manager.deregisterTaskContext(taskId);\n throw new Error(errorInfo.message);\n }\n\n // Throttled progress publisher.\n const progressThrottleMs = manager.config.progressThrottleMs;\n const shouldThrottleProgress =\n typeof progressThrottleMs === 'number' && Number.isFinite(progressThrottleMs) && progressThrottleMs > 0;\n let lastProgressEmitMs: number | undefined;\n const onProgress = async (chunk: any) => {\n if (shouldThrottleProgress) {\n const now = Date.now();\n if (lastProgressEmitMs !== undefined && now - lastProgressEmitMs < progressThrottleMs) return;\n lastProgressEmitMs = now;\n }\n await manager.publishLifecycleEvent('task.output', { ...task, chunk });\n };\n\n const abortController = new AbortController();\n manager.activeAbortControllers.set(taskId, abortController);\n // Wire the workflow's run-level abort signal into our local controller\n // so `workflow.getRun(taskId).cancel()` propagates to the executor.\n const onWorkflowAbort = () => abortController.abort(new Error('Task cancelled'));\n if (workflowAbortSignal.aborted) {\n abortController.abort(new Error('Task cancelled'));\n } else {\n workflowAbortSignal.addEventListener('abort', onWorkflowAbort, { once: true });\n }\n const timeoutHandle = setTimeout(() => {\n abortController.abort(new Error(`Task timed out after ${task.timeoutMs}ms`));\n }, task.timeoutMs);\n\n // Wrap the workflow runtime's `suspend` so we persist\n // `status: 'suspended'` + `suspendPayload`, fire the per-task\n // suspend hook (so the bg-task's `onResult` updates the agent's\n // message list), and publish the lifecycle event before\n // delegating. The runtime's `suspend` does not throw — it sets a\n // flag the step-executor reads after `execute` returns. We\n // capture the args here and call the runtime's suspend from the\n // step body after the executor returns, so `wrappedSuspend` can\n // safely run all its side effects synchronously inside the\n // tool's call.\n let pendingSuspend: { data?: unknown; suspendOptions?: SuspendOptions } | undefined;\n const wrappedSuspend = async (data?: unknown, suspendOptions?: SuspendOptions) => {\n await storage.updateTask(taskId, {\n status: 'suspended',\n suspendPayload: data,\n suspendedAt: new Date(),\n });\n const suspendedTask = await storage.getTask(taskId);\n if (suspendedTask) {\n // Suspend is non-terminal — DO NOT use `runLocalCompletionHooks`\n // here. That helper deregisters the task context in its `finally`\n // block, which would strand the resume call (the workflow step\n // body re-enters and looks up `manager.taskContexts.get(taskId)`).\n await manager.runLocalSuspendHooks(suspendedTask);\n await manager.publishLifecycleEvent('task.suspended', suspendedTask);\n }\n pendingSuspend = { data, suspendOptions };\n };\n\n try {\n const result = await executor.execute(task.args, {\n abortSignal: abortController.signal,\n onProgress,\n suspend: wrappedSuspend,\n // On resume the runtime populates `resumeData`; undefined on\n // the initial run.\n resumeData,\n });\n\n if (pendingSuspend) {\n return suspend(pendingSuspend.data, pendingSuspend.suspendOptions as SuspendOptions);\n }\n\n return { taskId, outcome: 'success' as const, result };\n } catch (error: any) {\n const currentTask = await storage.getTask(taskId);\n if (!currentTask || (currentTask.status as BackgroundTaskStatus) === 'cancelled') {\n manager.deregisterTaskContext(taskId);\n return { taskId, outcome: 'cancelled' as const };\n }\n\n // Treat any aborted-signal exit as a timeout. The cancel path is\n // already handled by the storage-status check above, so if we reach\n // here with `signal.aborted`, it's the timeout abort. The\n // `AbortError` / message checks are belt-and-braces for executors\n // that throw their own abort error instead of propagating ours.\n if (\n abortController.signal.aborted ||\n error?.name === 'AbortError' ||\n error?.message === 'Task cancelled' ||\n error?.message?.startsWith('Task timed out after ')\n ) {\n return { taskId, outcome: 'timed_out' as const };\n }\n\n // Authorization denials are non-retryable — retrying cannot succeed\n // and would just burn attempts before surfacing the denial.\n if (error?.name === 'FGADeniedError') {\n return {\n taskId,\n outcome: 'failed' as const,\n error: { name: error.name, message: error?.message ?? 'Authorization denied', stack: error?.stack },\n };\n }\n\n return {\n taskId,\n outcome: 'retry' as const,\n error: { message: error?.message ?? 'Unknown error', stack: error?.stack },\n };\n } finally {\n clearTimeout(timeoutHandle);\n workflowAbortSignal.removeEventListener('abort', onWorkflowAbort);\n manager.activeAbortControllers.delete(taskId);\n }\n },\n });\n\n const classifyOutcomeStep = createStep({\n id: 'classify-outcome',\n inputSchema: attemptOutputSchema,\n outputSchema: bodyOutputSchema,\n execute: async ({ inputData }) => {\n const { taskId, outcome, result, error } = inputData;\n const storage = await manager.getStorage();\n const task = await storage.getTask(taskId);\n if (!task) return { taskId, done: true };\n\n if (outcome === 'cancelled') {\n manager.deregisterTaskContext(taskId);\n return { taskId, done: true };\n }\n\n if (outcome === 'timed_out') {\n const status = task.status as string;\n if (status !== 'timed_out' && status !== 'cancelled') {\n await storage.updateTask(taskId, {\n status: 'timed_out',\n error: { message: `Task timed out after ${task.timeoutMs}ms` },\n completedAt: new Date(),\n });\n const timedOutTask = await storage.getTask(taskId);\n if (timedOutTask) await manager.publishLifecycleEvent('task.failed', timedOutTask);\n }\n return { taskId, done: true };\n }\n\n if (outcome === 'success') {\n if ((task.status as BackgroundTaskStatus) === 'cancelled') {\n manager.deregisterTaskContext(taskId);\n return { taskId, done: true };\n }\n await storage.updateTask(taskId, { status: 'completed', result, completedAt: new Date() });\n const completedTask = await storage.getTask(taskId);\n if (completedTask) {\n await manager.runLocalCompletionHooks(completedTask, 'completed', { result });\n await manager.publishLifecycleEvent('task.completed', completedTask);\n }\n return { taskId, done: true, result };\n }\n\n // outcome === 'retry' | 'failed'\n if (outcome === 'retry' && task.retryCount < task.maxRetries) {\n await storage.updateTask(taskId, {\n retryCount: task.retryCount + 1,\n error: undefined,\n startedAt: new Date(),\n });\n return { taskId, done: false };\n }\n\n // Retries exhausted (or non-retryable failure): persist failure and\n // throw so the workflow run ends\n // in `failed` rather than completing cleanly. Throw matches the prior\n // single-step behavior — workflow-run history stays accurate.\n const errorInfo = error ?? { message: 'Unknown error' };\n await storage.updateTask(taskId, { status: 'failed', error: errorInfo, completedAt: new Date() });\n const failedTask = await storage.getTask(taskId);\n if (failedTask) {\n await manager.runLocalCompletionHooks(failedTask, 'failed', { error: errorInfo });\n await manager.publishLifecycleEvent('task.failed', failedTask);\n }\n const thrown = new Error(errorInfo.message);\n if (errorInfo.name) thrown.name = errorInfo.name;\n if (errorInfo.stack) thrown.stack = errorInfo.stack;\n throw thrown;\n },\n });\n\n const attemptBodyWorkflow = createWorkflow({\n id: `${BACKGROUND_TASK_WORKFLOW_ID}__attempt`,\n inputSchema: bodyIOSchema,\n outputSchema: bodyOutputSchema,\n steps: [runAttemptStep, classifyOutcomeStep],\n options: {\n // `dountil` feeds the prior iteration's output back in as input. The\n // body's actual entry point only needs `taskId`, but the loop's\n // feedback shape includes `done`/`result`/etc. Skip validation rather\n // than widen every step's input schema.\n validateInputs: false,\n shouldPersistSnapshot: ({ workflowStatus }) => WORKFLOW_STATUS_TO_PERSIST.includes(workflowStatus),\n // Internal scheduler plumbing — hide workflow spans from exported\n // traces. The task body itself runs as user code and keeps its own\n // spans.\n tracingPolicy: {\n internal: InternalSpans.WORKFLOW,\n },\n },\n })\n .then(runAttemptStep)\n .then(classifyOutcomeStep)\n .commit();\n\n return createWorkflow({\n id: BACKGROUND_TASK_WORKFLOW_ID,\n inputSchema,\n outputSchema: bodyOutputSchema,\n steps: [attemptBodyWorkflow],\n options: {\n shouldPersistSnapshot: ({ workflowStatus }) => WORKFLOW_STATUS_TO_PERSIST.includes(workflowStatus),\n // Internal scheduler plumbing — see the inner workflow comment.\n tracingPolicy: {\n internal: InternalSpans.WORKFLOW,\n },\n },\n })\n .dountil(attemptBodyWorkflow, async ({ inputData }) => inputData?.done === true)\n .commit();\n}\n"],"mappings":";;;;;AAUA,MAAM,cAAcA,IAAAA,EAAE,OAAO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"}
|
|
1
|
+
{"version":3,"file":"workflow-DcS_0R0Z.cjs","names":["z","createStep","createWorkflow","BACKGROUND_TASK_WORKFLOW_ID"],"sources":["../src/background-tasks/workflow.ts"],"sourcesContent":["import { z } from 'zod';\nimport { InternalSpans } from '../observability';\nimport type { SuspendOptions } from '../workflows';\nimport { createStep, createWorkflow } from '../workflows';\nimport type { BackgroundTaskManager } from './manager';\nimport type { BackgroundTaskStatus } from './types';\nimport { BACKGROUND_TASK_WORKFLOW_ID } from './workflow-id';\n\nexport { BACKGROUND_TASK_WORKFLOW_ID } from './workflow-id';\n\nconst inputSchema = z.object({ taskId: z.string() });\n\nconst attemptOutcomeSchema = z.enum(['success', 'retry', 'failed', 'cancelled', 'timed_out']);\n\nconst attemptOutputSchema = z.object({\n taskId: z.string(),\n outcome: attemptOutcomeSchema,\n result: z.unknown().optional(),\n error: z.any().optional(),\n});\n\nconst bodyIOSchema = z.object({\n taskId: z.string(),\n done: z.boolean().optional(),\n result: z.unknown().optional(),\n});\n\nconst bodyOutputSchema = z.object({\n taskId: z.string(),\n done: z.boolean(),\n result: z.unknown().optional(),\n});\n\nconst WORKFLOW_STATUS_TO_PERSIST = ['suspended', 'pending', 'paused', 'waiting'];\n\n/**\n * Builds the per-task workflow that owns executor + retries.\n *\n * Uses the standard (default) execution engine so the workflow runs entirely\n * in-process on whatever host calls `run.start()`. This is critical for\n * distributed deployments where the background-task worker must\n * execute tools locally — routing through the evented pipeline would send\n * step execution to the orchestration worker / API, which don't have the\n * internal workflow or task contexts registered.\n *\n * Shape: outer workflow runs an inner `[run-attempt, classify-outcome]`\n * workflow inside a `dountil` loop. `run-attempt` invokes the executor and\n * categorises the outcome; `classify-outcome` persists final state, advances\n * retry bookkeeping, and decides whether the loop is done. The dountil\n * predicate exits on `done === true`.\n *\n * Step bodies close over `manager` directly — the bg-tasks layer is the only\n * consumer of the `@internal` private fields.\n */\nexport function buildBackgroundTaskWorkflow(manager: BackgroundTaskManager) {\n const runAttemptStep = createStep({\n id: 'run-attempt',\n inputSchema: bodyIOSchema,\n outputSchema: attemptOutputSchema,\n execute: async ({ inputData, abortSignal: workflowAbortSignal, suspend, resumeData }) => {\n const { taskId } = inputData;\n const storage = await manager.getStorage();\n const task = await storage.getTask(taskId);\n if (!task || task.status === 'cancelled') {\n manager.deregisterTaskContext(taskId);\n return { taskId, outcome: 'cancelled' as const };\n }\n\n // Resolve the executor. Two paths:\n // 1. Per-task `TaskContext` registered on the producer (in-process).\n // Carries closure-captured state (e.g. agent memory hooks) and\n // wins when present.\n // 2. Static executor registered by tool name. Used by remote workers\n // that received the dispatch via PubSub and don't have access to\n // the producer's per-task closure. Agent-owned executors are\n // namespaced as `agentId:toolName` to avoid cross-agent collisions;\n // we try the namespaced key first, then fall back to the plain key.\n const ctx = manager.taskContexts.get(taskId);\n const executor =\n ctx?.executor ??\n (task.agentId ? manager.getStaticExecutor(`${task.agentId}:${task.toolName}`) : undefined) ??\n manager.getStaticExecutor(task.toolName);\n if (!executor) {\n const errorInfo = {\n message:\n `No executor registered for tool \"${task.toolName}\". ` +\n `Register the tool on Mastra (so workers can resolve it cross-process) ` +\n `or run the task in the same process as the producer.`,\n };\n await storage.updateTask(taskId, { status: 'failed', error: errorInfo, completedAt: new Date() });\n const failedTask = await storage.getTask(taskId);\n if (failedTask) {\n await manager.runLocalCompletionHooks(failedTask, 'failed', { error: errorInfo });\n await manager.publishLifecycleEvent('task.failed', failedTask);\n }\n manager.deregisterTaskContext(taskId);\n throw new Error(errorInfo.message);\n }\n\n // Throttled progress publisher.\n const progressThrottleMs = manager.config.progressThrottleMs;\n const shouldThrottleProgress =\n typeof progressThrottleMs === 'number' && Number.isFinite(progressThrottleMs) && progressThrottleMs > 0;\n let lastProgressEmitMs: number | undefined;\n const onProgress = async (chunk: any) => {\n if (shouldThrottleProgress) {\n const now = Date.now();\n if (lastProgressEmitMs !== undefined && now - lastProgressEmitMs < progressThrottleMs) return;\n lastProgressEmitMs = now;\n }\n await manager.publishLifecycleEvent('task.output', { ...task, chunk });\n };\n\n const abortController = new AbortController();\n manager.activeAbortControllers.set(taskId, abortController);\n // Wire the workflow's run-level abort signal into our local controller\n // so `workflow.getRun(taskId).cancel()` propagates to the executor.\n const onWorkflowAbort = () => abortController.abort(new Error('Task cancelled'));\n if (workflowAbortSignal.aborted) {\n abortController.abort(new Error('Task cancelled'));\n } else {\n workflowAbortSignal.addEventListener('abort', onWorkflowAbort, { once: true });\n }\n const timeoutHandle = setTimeout(() => {\n abortController.abort(new Error(`Task timed out after ${task.timeoutMs}ms`));\n }, task.timeoutMs);\n\n // Wrap the workflow runtime's `suspend` so we persist\n // `status: 'suspended'` + `suspendPayload`, fire the per-task\n // suspend hook (so the bg-task's `onResult` updates the agent's\n // message list), and publish the lifecycle event before\n // delegating. The runtime's `suspend` does not throw — it sets a\n // flag the step-executor reads after `execute` returns. We\n // capture the args here and call the runtime's suspend from the\n // step body after the executor returns, so `wrappedSuspend` can\n // safely run all its side effects synchronously inside the\n // tool's call.\n let pendingSuspend: { data?: unknown; suspendOptions?: SuspendOptions } | undefined;\n const wrappedSuspend = async (data?: unknown, suspendOptions?: SuspendOptions) => {\n await storage.updateTask(taskId, {\n status: 'suspended',\n suspendPayload: data,\n suspendedAt: new Date(),\n });\n const suspendedTask = await storage.getTask(taskId);\n if (suspendedTask) {\n // Suspend is non-terminal — DO NOT use `runLocalCompletionHooks`\n // here. That helper deregisters the task context in its `finally`\n // block, which would strand the resume call (the workflow step\n // body re-enters and looks up `manager.taskContexts.get(taskId)`).\n await manager.runLocalSuspendHooks(suspendedTask);\n await manager.publishLifecycleEvent('task.suspended', suspendedTask);\n }\n pendingSuspend = { data, suspendOptions };\n };\n\n try {\n const result = await executor.execute(task.args, {\n abortSignal: abortController.signal,\n onProgress,\n suspend: wrappedSuspend,\n // On resume the runtime populates `resumeData`; undefined on\n // the initial run.\n resumeData,\n });\n\n if (pendingSuspend) {\n return suspend(pendingSuspend.data, pendingSuspend.suspendOptions as SuspendOptions);\n }\n\n return { taskId, outcome: 'success' as const, result };\n } catch (error: any) {\n const currentTask = await storage.getTask(taskId);\n if (!currentTask || (currentTask.status as BackgroundTaskStatus) === 'cancelled') {\n manager.deregisterTaskContext(taskId);\n return { taskId, outcome: 'cancelled' as const };\n }\n\n // Treat any aborted-signal exit as a timeout. The cancel path is\n // already handled by the storage-status check above, so if we reach\n // here with `signal.aborted`, it's the timeout abort. The\n // `AbortError` / message checks are belt-and-braces for executors\n // that throw their own abort error instead of propagating ours.\n if (\n abortController.signal.aborted ||\n error?.name === 'AbortError' ||\n error?.message === 'Task cancelled' ||\n error?.message?.startsWith('Task timed out after ')\n ) {\n return { taskId, outcome: 'timed_out' as const };\n }\n\n // Authorization denials are non-retryable — retrying cannot succeed\n // and would just burn attempts before surfacing the denial.\n if (error?.name === 'FGADeniedError') {\n return {\n taskId,\n outcome: 'failed' as const,\n error: { name: error.name, message: error?.message ?? 'Authorization denied', stack: error?.stack },\n };\n }\n\n return {\n taskId,\n outcome: 'retry' as const,\n error: { message: error?.message ?? 'Unknown error', stack: error?.stack },\n };\n } finally {\n clearTimeout(timeoutHandle);\n workflowAbortSignal.removeEventListener('abort', onWorkflowAbort);\n manager.activeAbortControllers.delete(taskId);\n }\n },\n });\n\n const classifyOutcomeStep = createStep({\n id: 'classify-outcome',\n inputSchema: attemptOutputSchema,\n outputSchema: bodyOutputSchema,\n execute: async ({ inputData }) => {\n const { taskId, outcome, result, error } = inputData;\n const storage = await manager.getStorage();\n const task = await storage.getTask(taskId);\n if (!task) return { taskId, done: true };\n\n if (outcome === 'cancelled') {\n manager.deregisterTaskContext(taskId);\n return { taskId, done: true };\n }\n\n if (outcome === 'timed_out') {\n const status = task.status as string;\n if (status !== 'timed_out' && status !== 'cancelled') {\n await storage.updateTask(taskId, {\n status: 'timed_out',\n error: { message: `Task timed out after ${task.timeoutMs}ms` },\n completedAt: new Date(),\n });\n const timedOutTask = await storage.getTask(taskId);\n if (timedOutTask) await manager.publishLifecycleEvent('task.failed', timedOutTask);\n }\n return { taskId, done: true };\n }\n\n if (outcome === 'success') {\n if ((task.status as BackgroundTaskStatus) === 'cancelled') {\n manager.deregisterTaskContext(taskId);\n return { taskId, done: true };\n }\n await storage.updateTask(taskId, { status: 'completed', result, completedAt: new Date() });\n const completedTask = await storage.getTask(taskId);\n if (completedTask) {\n await manager.runLocalCompletionHooks(completedTask, 'completed', { result });\n await manager.publishLifecycleEvent('task.completed', completedTask);\n }\n return { taskId, done: true, result };\n }\n\n // outcome === 'retry' | 'failed'\n if (outcome === 'retry' && task.retryCount < task.maxRetries) {\n await storage.updateTask(taskId, {\n retryCount: task.retryCount + 1,\n error: undefined,\n startedAt: new Date(),\n });\n return { taskId, done: false };\n }\n\n // Retries exhausted (or non-retryable failure): persist failure and\n // throw so the workflow run ends\n // in `failed` rather than completing cleanly. Throw matches the prior\n // single-step behavior — workflow-run history stays accurate.\n const errorInfo = error ?? { message: 'Unknown error' };\n await storage.updateTask(taskId, { status: 'failed', error: errorInfo, completedAt: new Date() });\n const failedTask = await storage.getTask(taskId);\n if (failedTask) {\n await manager.runLocalCompletionHooks(failedTask, 'failed', { error: errorInfo });\n await manager.publishLifecycleEvent('task.failed', failedTask);\n }\n const thrown = new Error(errorInfo.message);\n if (errorInfo.name) thrown.name = errorInfo.name;\n if (errorInfo.stack) thrown.stack = errorInfo.stack;\n throw thrown;\n },\n });\n\n const attemptBodyWorkflow = createWorkflow({\n id: `${BACKGROUND_TASK_WORKFLOW_ID}__attempt`,\n inputSchema: bodyIOSchema,\n outputSchema: bodyOutputSchema,\n steps: [runAttemptStep, classifyOutcomeStep],\n options: {\n // `dountil` feeds the prior iteration's output back in as input. The\n // body's actual entry point only needs `taskId`, but the loop's\n // feedback shape includes `done`/`result`/etc. Skip validation rather\n // than widen every step's input schema.\n validateInputs: false,\n shouldPersistSnapshot: ({ workflowStatus }) => WORKFLOW_STATUS_TO_PERSIST.includes(workflowStatus),\n // Internal scheduler plumbing — hide workflow spans from exported\n // traces. The task body itself runs as user code and keeps its own\n // spans.\n tracingPolicy: {\n internal: InternalSpans.WORKFLOW,\n },\n },\n })\n .then(runAttemptStep)\n .then(classifyOutcomeStep)\n .commit();\n\n return createWorkflow({\n id: BACKGROUND_TASK_WORKFLOW_ID,\n inputSchema,\n outputSchema: bodyOutputSchema,\n steps: [attemptBodyWorkflow],\n options: {\n shouldPersistSnapshot: ({ workflowStatus }) => WORKFLOW_STATUS_TO_PERSIST.includes(workflowStatus),\n // Internal scheduler plumbing — see the inner workflow comment.\n tracingPolicy: {\n internal: InternalSpans.WORKFLOW,\n },\n },\n })\n .dountil(attemptBodyWorkflow, async ({ inputData }) => inputData?.done === true)\n .commit();\n}\n"],"mappings":";;;;;AAUA,MAAM,cAAcA,IAAAA,EAAE,OAAO,EAAE,QAAQA,IAAAA,EAAE,OAAO,EAAE,CAAC;AAEnD,MAAM,uBAAuBA,IAAAA,EAAE,KAAK;CAAC;CAAW;CAAS;CAAU;CAAa;AAAW,CAAC;AAE5F,MAAM,sBAAsBA,IAAAA,EAAE,OAAO;CACnC,QAAQA,IAAAA,EAAE,OAAO;CACjB,SAAS;CACT,QAAQA,IAAAA,EAAE,QAAQ,CAAC,CAAC,SAAS;CAC7B,OAAOA,IAAAA,EAAE,IAAI,CAAC,CAAC,SAAS;AAC1B,CAAC;AAED,MAAM,eAAeA,IAAAA,EAAE,OAAO;CAC5B,QAAQA,IAAAA,EAAE,OAAO;CACjB,MAAMA,IAAAA,EAAE,QAAQ,CAAC,CAAC,SAAS;CAC3B,QAAQA,IAAAA,EAAE,QAAQ,CAAC,CAAC,SAAS;AAC/B,CAAC;AAED,MAAM,mBAAmBA,IAAAA,EAAE,OAAO;CAChC,QAAQA,IAAAA,EAAE,OAAO;CACjB,MAAMA,IAAAA,EAAE,QAAQ;CAChB,QAAQA,IAAAA,EAAE,QAAQ,CAAC,CAAC,SAAS;AAC/B,CAAC;AAED,MAAM,6BAA6B;CAAC;CAAa;CAAW;CAAU;AAAS;;;;;;;;;;;;;;;;;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C3C,SAAS;GAKP,gBAAgB;GAChB,wBAAwB,EAAE,qBAAqB,2BAA2B,SAAS,cAAc;GAIjG,eAAe,EACb,UAAA,EACF;EACF;CACF,CAAC,CAAC,CACC,KAAK,cAAc,CAAC,CACpB,KAAK,mBAAmB,CAAC,CACzB,OAAO;CAEV,OAAOD,cAAAA,eAAe;EACpB,IAAIC,yBAAAA;EACJ;EACA,cAAc;EACd,OAAO,CAAC,mBAAmB;EAC3B,SAAS;GACP,wBAAwB,EAAE,qBAAqB,2BAA2B,SAAS,cAAc;GAEjG,eAAe,EACb,UAAA,EACF;EACF;CACF,CAAC,CAAC,CACC,QAAQ,qBAAqB,OAAO,EAAE,gBAAgB,WAAW,SAAS,IAAI,CAAC,CAC/E,OAAO;AACZ"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import "./tracing-NiBfLy3R.js";
|
|
2
|
-
import { s as BACKGROUND_TASK_WORKFLOW_ID } from "./background-tasks-
|
|
3
|
-
import { qt as createWorkflow, sn as createStep } from "./agent-
|
|
2
|
+
import { s as BACKGROUND_TASK_WORKFLOW_ID } from "./background-tasks-CM94BIj8.js";
|
|
3
|
+
import { qt as createWorkflow, sn as createStep } from "./agent-0y2cApTZ.js";
|
|
4
4
|
import { z } from "zod";
|
|
5
5
|
//#region src/background-tasks/workflow.ts
|
|
6
6
|
const inputSchema = z.object({ taskId: z.string() });
|
|
@@ -285,4 +285,4 @@ function buildBackgroundTaskWorkflow(manager) {
|
|
|
285
285
|
//#endregion
|
|
286
286
|
export { buildBackgroundTaskWorkflow };
|
|
287
287
|
|
|
288
|
-
//# sourceMappingURL=workflow-
|
|
288
|
+
//# sourceMappingURL=workflow-k6s0ESOR.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workflow-OjZRiiCG.js","names":[],"sources":["../src/background-tasks/workflow.ts"],"sourcesContent":["import { z } from 'zod';\nimport { InternalSpans } from '../observability';\nimport type { SuspendOptions } from '../workflows';\nimport { createStep, createWorkflow } from '../workflows';\nimport type { BackgroundTaskManager } from './manager';\nimport type { BackgroundTaskStatus } from './types';\nimport { BACKGROUND_TASK_WORKFLOW_ID } from './workflow-id';\n\nexport { BACKGROUND_TASK_WORKFLOW_ID } from './workflow-id';\n\nconst inputSchema = z.object({ taskId: z.string() });\n\nconst attemptOutcomeSchema = z.enum(['success', 'retry', 'failed', 'cancelled', 'timed_out']);\n\nconst attemptOutputSchema = z.object({\n taskId: z.string(),\n outcome: attemptOutcomeSchema,\n result: z.unknown().optional(),\n error: z.any().optional(),\n});\n\nconst bodyIOSchema = z.object({\n taskId: z.string(),\n done: z.boolean().optional(),\n result: z.unknown().optional(),\n});\n\nconst bodyOutputSchema = z.object({\n taskId: z.string(),\n done: z.boolean(),\n result: z.unknown().optional(),\n});\n\nconst WORKFLOW_STATUS_TO_PERSIST = ['suspended', 'pending', 'paused', 'waiting'];\n\n/**\n * Builds the per-task workflow that owns executor + retries.\n *\n * Uses the standard (default) execution engine so the workflow runs entirely\n * in-process on whatever host calls `run.start()`. This is critical for\n * distributed deployments where the background-task worker must\n * execute tools locally — routing through the evented pipeline would send\n * step execution to the orchestration worker / API, which don't have the\n * internal workflow or task contexts registered.\n *\n * Shape: outer workflow runs an inner `[run-attempt, classify-outcome]`\n * workflow inside a `dountil` loop. `run-attempt` invokes the executor and\n * categorises the outcome; `classify-outcome` persists final state, advances\n * retry bookkeeping, and decides whether the loop is done. The dountil\n * predicate exits on `done === true`.\n *\n * Step bodies close over `manager` directly — the bg-tasks layer is the only\n * consumer of the `@internal` private fields.\n */\nexport function buildBackgroundTaskWorkflow(manager: BackgroundTaskManager) {\n const runAttemptStep = createStep({\n id: 'run-attempt',\n inputSchema: bodyIOSchema,\n outputSchema: attemptOutputSchema,\n execute: async ({ inputData, abortSignal: workflowAbortSignal, suspend, resumeData }) => {\n const { taskId } = inputData;\n const storage = await manager.getStorage();\n const task = await storage.getTask(taskId);\n if (!task || task.status === 'cancelled') {\n manager.deregisterTaskContext(taskId);\n return { taskId, outcome: 'cancelled' as const };\n }\n\n // Resolve the executor. Two paths:\n // 1. Per-task `TaskContext` registered on the producer (in-process).\n // Carries closure-captured state (e.g. agent memory hooks) and\n // wins when present.\n // 2. Static executor registered by tool name. Used by remote workers\n // that received the dispatch via PubSub and don't have access to\n // the producer's per-task closure. Agent-owned executors are\n // namespaced as `agentId:toolName` to avoid cross-agent collisions;\n // we try the namespaced key first, then fall back to the plain key.\n const ctx = manager.taskContexts.get(taskId);\n const executor =\n ctx?.executor ??\n (task.agentId ? manager.getStaticExecutor(`${task.agentId}:${task.toolName}`) : undefined) ??\n manager.getStaticExecutor(task.toolName);\n if (!executor) {\n const errorInfo = {\n message:\n `No executor registered for tool \"${task.toolName}\". ` +\n `Register the tool on Mastra (so workers can resolve it cross-process) ` +\n `or run the task in the same process as the producer.`,\n };\n await storage.updateTask(taskId, { status: 'failed', error: errorInfo, completedAt: new Date() });\n const failedTask = await storage.getTask(taskId);\n if (failedTask) {\n await manager.runLocalCompletionHooks(failedTask, 'failed', { error: errorInfo });\n await manager.publishLifecycleEvent('task.failed', failedTask);\n }\n manager.deregisterTaskContext(taskId);\n throw new Error(errorInfo.message);\n }\n\n // Throttled progress publisher.\n const progressThrottleMs = manager.config.progressThrottleMs;\n const shouldThrottleProgress =\n typeof progressThrottleMs === 'number' && Number.isFinite(progressThrottleMs) && progressThrottleMs > 0;\n let lastProgressEmitMs: number | undefined;\n const onProgress = async (chunk: any) => {\n if (shouldThrottleProgress) {\n const now = Date.now();\n if (lastProgressEmitMs !== undefined && now - lastProgressEmitMs < progressThrottleMs) return;\n lastProgressEmitMs = now;\n }\n await manager.publishLifecycleEvent('task.output', { ...task, chunk });\n };\n\n const abortController = new AbortController();\n manager.activeAbortControllers.set(taskId, abortController);\n // Wire the workflow's run-level abort signal into our local controller\n // so `workflow.getRun(taskId).cancel()` propagates to the executor.\n const onWorkflowAbort = () => abortController.abort(new Error('Task cancelled'));\n if (workflowAbortSignal.aborted) {\n abortController.abort(new Error('Task cancelled'));\n } else {\n workflowAbortSignal.addEventListener('abort', onWorkflowAbort, { once: true });\n }\n const timeoutHandle = setTimeout(() => {\n abortController.abort(new Error(`Task timed out after ${task.timeoutMs}ms`));\n }, task.timeoutMs);\n\n // Wrap the workflow runtime's `suspend` so we persist\n // `status: 'suspended'` + `suspendPayload`, fire the per-task\n // suspend hook (so the bg-task's `onResult` updates the agent's\n // message list), and publish the lifecycle event before\n // delegating. The runtime's `suspend` does not throw — it sets a\n // flag the step-executor reads after `execute` returns. We\n // capture the args here and call the runtime's suspend from the\n // step body after the executor returns, so `wrappedSuspend` can\n // safely run all its side effects synchronously inside the\n // tool's call.\n let pendingSuspend: { data?: unknown; suspendOptions?: SuspendOptions } | undefined;\n const wrappedSuspend = async (data?: unknown, suspendOptions?: SuspendOptions) => {\n await storage.updateTask(taskId, {\n status: 'suspended',\n suspendPayload: data,\n suspendedAt: new Date(),\n });\n const suspendedTask = await storage.getTask(taskId);\n if (suspendedTask) {\n // Suspend is non-terminal — DO NOT use `runLocalCompletionHooks`\n // here. That helper deregisters the task context in its `finally`\n // block, which would strand the resume call (the workflow step\n // body re-enters and looks up `manager.taskContexts.get(taskId)`).\n await manager.runLocalSuspendHooks(suspendedTask);\n await manager.publishLifecycleEvent('task.suspended', suspendedTask);\n }\n pendingSuspend = { data, suspendOptions };\n };\n\n try {\n const result = await executor.execute(task.args, {\n abortSignal: abortController.signal,\n onProgress,\n suspend: wrappedSuspend,\n // On resume the runtime populates `resumeData`; undefined on\n // the initial run.\n resumeData,\n });\n\n if (pendingSuspend) {\n return suspend(pendingSuspend.data, pendingSuspend.suspendOptions as SuspendOptions);\n }\n\n return { taskId, outcome: 'success' as const, result };\n } catch (error: any) {\n const currentTask = await storage.getTask(taskId);\n if (!currentTask || (currentTask.status as BackgroundTaskStatus) === 'cancelled') {\n manager.deregisterTaskContext(taskId);\n return { taskId, outcome: 'cancelled' as const };\n }\n\n // Treat any aborted-signal exit as a timeout. The cancel path is\n // already handled by the storage-status check above, so if we reach\n // here with `signal.aborted`, it's the timeout abort. The\n // `AbortError` / message checks are belt-and-braces for executors\n // that throw their own abort error instead of propagating ours.\n if (\n abortController.signal.aborted ||\n error?.name === 'AbortError' ||\n error?.message === 'Task cancelled' ||\n error?.message?.startsWith('Task timed out after ')\n ) {\n return { taskId, outcome: 'timed_out' as const };\n }\n\n // Authorization denials are non-retryable — retrying cannot succeed\n // and would just burn attempts before surfacing the denial.\n if (error?.name === 'FGADeniedError') {\n return {\n taskId,\n outcome: 'failed' as const,\n error: { name: error.name, message: error?.message ?? 'Authorization denied', stack: error?.stack },\n };\n }\n\n return {\n taskId,\n outcome: 'retry' as const,\n error: { message: error?.message ?? 'Unknown error', stack: error?.stack },\n };\n } finally {\n clearTimeout(timeoutHandle);\n workflowAbortSignal.removeEventListener('abort', onWorkflowAbort);\n manager.activeAbortControllers.delete(taskId);\n }\n },\n });\n\n const classifyOutcomeStep = createStep({\n id: 'classify-outcome',\n inputSchema: attemptOutputSchema,\n outputSchema: bodyOutputSchema,\n execute: async ({ inputData }) => {\n const { taskId, outcome, result, error } = inputData;\n const storage = await manager.getStorage();\n const task = await storage.getTask(taskId);\n if (!task) return { taskId, done: true };\n\n if (outcome === 'cancelled') {\n manager.deregisterTaskContext(taskId);\n return { taskId, done: true };\n }\n\n if (outcome === 'timed_out') {\n const status = task.status as string;\n if (status !== 'timed_out' && status !== 'cancelled') {\n await storage.updateTask(taskId, {\n status: 'timed_out',\n error: { message: `Task timed out after ${task.timeoutMs}ms` },\n completedAt: new Date(),\n });\n const timedOutTask = await storage.getTask(taskId);\n if (timedOutTask) await manager.publishLifecycleEvent('task.failed', timedOutTask);\n }\n return { taskId, done: true };\n }\n\n if (outcome === 'success') {\n if ((task.status as BackgroundTaskStatus) === 'cancelled') {\n manager.deregisterTaskContext(taskId);\n return { taskId, done: true };\n }\n await storage.updateTask(taskId, { status: 'completed', result, completedAt: new Date() });\n const completedTask = await storage.getTask(taskId);\n if (completedTask) {\n await manager.runLocalCompletionHooks(completedTask, 'completed', { result });\n await manager.publishLifecycleEvent('task.completed', completedTask);\n }\n return { taskId, done: true, result };\n }\n\n // outcome === 'retry' | 'failed'\n if (outcome === 'retry' && task.retryCount < task.maxRetries) {\n await storage.updateTask(taskId, {\n retryCount: task.retryCount + 1,\n error: undefined,\n startedAt: new Date(),\n });\n return { taskId, done: false };\n }\n\n // Retries exhausted (or non-retryable failure): persist failure and\n // throw so the workflow run ends\n // in `failed` rather than completing cleanly. Throw matches the prior\n // single-step behavior — workflow-run history stays accurate.\n const errorInfo = error ?? { message: 'Unknown error' };\n await storage.updateTask(taskId, { status: 'failed', error: errorInfo, completedAt: new Date() });\n const failedTask = await storage.getTask(taskId);\n if (failedTask) {\n await manager.runLocalCompletionHooks(failedTask, 'failed', { error: errorInfo });\n await manager.publishLifecycleEvent('task.failed', failedTask);\n }\n const thrown = new Error(errorInfo.message);\n if (errorInfo.name) thrown.name = errorInfo.name;\n if (errorInfo.stack) thrown.stack = errorInfo.stack;\n throw thrown;\n },\n });\n\n const attemptBodyWorkflow = createWorkflow({\n id: `${BACKGROUND_TASK_WORKFLOW_ID}__attempt`,\n inputSchema: bodyIOSchema,\n outputSchema: bodyOutputSchema,\n steps: [runAttemptStep, classifyOutcomeStep],\n options: {\n // `dountil` feeds the prior iteration's output back in as input. The\n // body's actual entry point only needs `taskId`, but the loop's\n // feedback shape includes `done`/`result`/etc. Skip validation rather\n // than widen every step's input schema.\n validateInputs: false,\n shouldPersistSnapshot: ({ workflowStatus }) => WORKFLOW_STATUS_TO_PERSIST.includes(workflowStatus),\n // Internal scheduler plumbing — hide workflow spans from exported\n // traces. The task body itself runs as user code and keeps its own\n // spans.\n tracingPolicy: {\n internal: InternalSpans.WORKFLOW,\n },\n },\n })\n .then(runAttemptStep)\n .then(classifyOutcomeStep)\n .commit();\n\n return createWorkflow({\n id: BACKGROUND_TASK_WORKFLOW_ID,\n inputSchema,\n outputSchema: bodyOutputSchema,\n steps: [attemptBodyWorkflow],\n options: {\n shouldPersistSnapshot: ({ workflowStatus }) => WORKFLOW_STATUS_TO_PERSIST.includes(workflowStatus),\n // Internal scheduler plumbing — see the inner workflow comment.\n tracingPolicy: {\n internal: InternalSpans.WORKFLOW,\n },\n },\n })\n .dountil(attemptBodyWorkflow, async ({ inputData }) => inputData?.done === true)\n .commit();\n}\n"],"mappings":";;;;;AAUA,MAAM,cAAc,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC;AAEnD,MAAM,uBAAuB,EAAE,KAAK;CAAC;CAAW;CAAS;CAAU;CAAa;AAAW,CAAC;AAE5F,MAAM,sBAAsB,EAAE,OAAO;CACnC,QAAQ,EAAE,OAAO;CACjB,SAAS;CACT,QAAQ,EAAE,QAAQ,CAAC,CAAC,SAAS;CAC7B,OAAO,EAAE,IAAI,CAAC,CAAC,SAAS;AAC1B,CAAC;AAED,MAAM,eAAe,EAAE,OAAO;CAC5B,QAAQ,EAAE,OAAO;CACjB,MAAM,EAAE,QAAQ,CAAC,CAAC,SAAS;CAC3B,QAAQ,EAAE,QAAQ,CAAC,CAAC,SAAS;AAC/B,CAAC;AAED,MAAM,mBAAmB,EAAE,OAAO;CAChC,QAAQ,EAAE,OAAO;CACjB,MAAM,EAAE,QAAQ;CAChB,QAAQ,EAAE,QAAQ,CAAC,CAAC,SAAS;AAC/B,CAAC;AAED,MAAM,6BAA6B;CAAC;CAAa;CAAW;CAAU;AAAS;;;;;;;;;;;;;;;;;;;;AAqB/E,SAAgB,4BAA4B,SAAgC;CAC1E,MAAM,iBAAiB,WAAW;EAChC,IAAI;EACJ,aAAa;EACb,cAAc;EACd,SAAS,OAAO,EAAE,WAAW,aAAa,qBAAqB,SAAS,iBAAiB;GACvF,MAAM,EAAE,WAAW;GACnB,MAAM,UAAU,MAAM,QAAQ,WAAW;GACzC,MAAM,OAAO,MAAM,QAAQ,QAAQ,MAAM;GACzC,IAAI,CAAC,QAAQ,KAAK,WAAW,aAAa;IACxC,QAAQ,sBAAsB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AAC,CAAC,CACC,QAAQ,qBAAqB,OAAO,EAAE,gBAAgB,WAAW,SAAS,IAAI,CAAC,CAC/E,OAAO;AACZ"}
|
|
1
|
+
{"version":3,"file":"workflow-k6s0ESOR.js","names":[],"sources":["../src/background-tasks/workflow.ts"],"sourcesContent":["import { z } from 'zod';\nimport { InternalSpans } from '../observability';\nimport type { SuspendOptions } from '../workflows';\nimport { createStep, createWorkflow } from '../workflows';\nimport type { BackgroundTaskManager } from './manager';\nimport type { BackgroundTaskStatus } from './types';\nimport { BACKGROUND_TASK_WORKFLOW_ID } from './workflow-id';\n\nexport { BACKGROUND_TASK_WORKFLOW_ID } from './workflow-id';\n\nconst inputSchema = z.object({ taskId: z.string() });\n\nconst attemptOutcomeSchema = z.enum(['success', 'retry', 'failed', 'cancelled', 'timed_out']);\n\nconst attemptOutputSchema = z.object({\n taskId: z.string(),\n outcome: attemptOutcomeSchema,\n result: z.unknown().optional(),\n error: z.any().optional(),\n});\n\nconst bodyIOSchema = z.object({\n taskId: z.string(),\n done: z.boolean().optional(),\n result: z.unknown().optional(),\n});\n\nconst bodyOutputSchema = z.object({\n taskId: z.string(),\n done: z.boolean(),\n result: z.unknown().optional(),\n});\n\nconst WORKFLOW_STATUS_TO_PERSIST = ['suspended', 'pending', 'paused', 'waiting'];\n\n/**\n * Builds the per-task workflow that owns executor + retries.\n *\n * Uses the standard (default) execution engine so the workflow runs entirely\n * in-process on whatever host calls `run.start()`. This is critical for\n * distributed deployments where the background-task worker must\n * execute tools locally — routing through the evented pipeline would send\n * step execution to the orchestration worker / API, which don't have the\n * internal workflow or task contexts registered.\n *\n * Shape: outer workflow runs an inner `[run-attempt, classify-outcome]`\n * workflow inside a `dountil` loop. `run-attempt` invokes the executor and\n * categorises the outcome; `classify-outcome` persists final state, advances\n * retry bookkeeping, and decides whether the loop is done. The dountil\n * predicate exits on `done === true`.\n *\n * Step bodies close over `manager` directly — the bg-tasks layer is the only\n * consumer of the `@internal` private fields.\n */\nexport function buildBackgroundTaskWorkflow(manager: BackgroundTaskManager) {\n const runAttemptStep = createStep({\n id: 'run-attempt',\n inputSchema: bodyIOSchema,\n outputSchema: attemptOutputSchema,\n execute: async ({ inputData, abortSignal: workflowAbortSignal, suspend, resumeData }) => {\n const { taskId } = inputData;\n const storage = await manager.getStorage();\n const task = await storage.getTask(taskId);\n if (!task || task.status === 'cancelled') {\n manager.deregisterTaskContext(taskId);\n return { taskId, outcome: 'cancelled' as const };\n }\n\n // Resolve the executor. Two paths:\n // 1. Per-task `TaskContext` registered on the producer (in-process).\n // Carries closure-captured state (e.g. agent memory hooks) and\n // wins when present.\n // 2. Static executor registered by tool name. Used by remote workers\n // that received the dispatch via PubSub and don't have access to\n // the producer's per-task closure. Agent-owned executors are\n // namespaced as `agentId:toolName` to avoid cross-agent collisions;\n // we try the namespaced key first, then fall back to the plain key.\n const ctx = manager.taskContexts.get(taskId);\n const executor =\n ctx?.executor ??\n (task.agentId ? manager.getStaticExecutor(`${task.agentId}:${task.toolName}`) : undefined) ??\n manager.getStaticExecutor(task.toolName);\n if (!executor) {\n const errorInfo = {\n message:\n `No executor registered for tool \"${task.toolName}\". ` +\n `Register the tool on Mastra (so workers can resolve it cross-process) ` +\n `or run the task in the same process as the producer.`,\n };\n await storage.updateTask(taskId, { status: 'failed', error: errorInfo, completedAt: new Date() });\n const failedTask = await storage.getTask(taskId);\n if (failedTask) {\n await manager.runLocalCompletionHooks(failedTask, 'failed', { error: errorInfo });\n await manager.publishLifecycleEvent('task.failed', failedTask);\n }\n manager.deregisterTaskContext(taskId);\n throw new Error(errorInfo.message);\n }\n\n // Throttled progress publisher.\n const progressThrottleMs = manager.config.progressThrottleMs;\n const shouldThrottleProgress =\n typeof progressThrottleMs === 'number' && Number.isFinite(progressThrottleMs) && progressThrottleMs > 0;\n let lastProgressEmitMs: number | undefined;\n const onProgress = async (chunk: any) => {\n if (shouldThrottleProgress) {\n const now = Date.now();\n if (lastProgressEmitMs !== undefined && now - lastProgressEmitMs < progressThrottleMs) return;\n lastProgressEmitMs = now;\n }\n await manager.publishLifecycleEvent('task.output', { ...task, chunk });\n };\n\n const abortController = new AbortController();\n manager.activeAbortControllers.set(taskId, abortController);\n // Wire the workflow's run-level abort signal into our local controller\n // so `workflow.getRun(taskId).cancel()` propagates to the executor.\n const onWorkflowAbort = () => abortController.abort(new Error('Task cancelled'));\n if (workflowAbortSignal.aborted) {\n abortController.abort(new Error('Task cancelled'));\n } else {\n workflowAbortSignal.addEventListener('abort', onWorkflowAbort, { once: true });\n }\n const timeoutHandle = setTimeout(() => {\n abortController.abort(new Error(`Task timed out after ${task.timeoutMs}ms`));\n }, task.timeoutMs);\n\n // Wrap the workflow runtime's `suspend` so we persist\n // `status: 'suspended'` + `suspendPayload`, fire the per-task\n // suspend hook (so the bg-task's `onResult` updates the agent's\n // message list), and publish the lifecycle event before\n // delegating. The runtime's `suspend` does not throw — it sets a\n // flag the step-executor reads after `execute` returns. We\n // capture the args here and call the runtime's suspend from the\n // step body after the executor returns, so `wrappedSuspend` can\n // safely run all its side effects synchronously inside the\n // tool's call.\n let pendingSuspend: { data?: unknown; suspendOptions?: SuspendOptions } | undefined;\n const wrappedSuspend = async (data?: unknown, suspendOptions?: SuspendOptions) => {\n await storage.updateTask(taskId, {\n status: 'suspended',\n suspendPayload: data,\n suspendedAt: new Date(),\n });\n const suspendedTask = await storage.getTask(taskId);\n if (suspendedTask) {\n // Suspend is non-terminal — DO NOT use `runLocalCompletionHooks`\n // here. That helper deregisters the task context in its `finally`\n // block, which would strand the resume call (the workflow step\n // body re-enters and looks up `manager.taskContexts.get(taskId)`).\n await manager.runLocalSuspendHooks(suspendedTask);\n await manager.publishLifecycleEvent('task.suspended', suspendedTask);\n }\n pendingSuspend = { data, suspendOptions };\n };\n\n try {\n const result = await executor.execute(task.args, {\n abortSignal: abortController.signal,\n onProgress,\n suspend: wrappedSuspend,\n // On resume the runtime populates `resumeData`; undefined on\n // the initial run.\n resumeData,\n });\n\n if (pendingSuspend) {\n return suspend(pendingSuspend.data, pendingSuspend.suspendOptions as SuspendOptions);\n }\n\n return { taskId, outcome: 'success' as const, result };\n } catch (error: any) {\n const currentTask = await storage.getTask(taskId);\n if (!currentTask || (currentTask.status as BackgroundTaskStatus) === 'cancelled') {\n manager.deregisterTaskContext(taskId);\n return { taskId, outcome: 'cancelled' as const };\n }\n\n // Treat any aborted-signal exit as a timeout. The cancel path is\n // already handled by the storage-status check above, so if we reach\n // here with `signal.aborted`, it's the timeout abort. The\n // `AbortError` / message checks are belt-and-braces for executors\n // that throw their own abort error instead of propagating ours.\n if (\n abortController.signal.aborted ||\n error?.name === 'AbortError' ||\n error?.message === 'Task cancelled' ||\n error?.message?.startsWith('Task timed out after ')\n ) {\n return { taskId, outcome: 'timed_out' as const };\n }\n\n // Authorization denials are non-retryable — retrying cannot succeed\n // and would just burn attempts before surfacing the denial.\n if (error?.name === 'FGADeniedError') {\n return {\n taskId,\n outcome: 'failed' as const,\n error: { name: error.name, message: error?.message ?? 'Authorization denied', stack: error?.stack },\n };\n }\n\n return {\n taskId,\n outcome: 'retry' as const,\n error: { message: error?.message ?? 'Unknown error', stack: error?.stack },\n };\n } finally {\n clearTimeout(timeoutHandle);\n workflowAbortSignal.removeEventListener('abort', onWorkflowAbort);\n manager.activeAbortControllers.delete(taskId);\n }\n },\n });\n\n const classifyOutcomeStep = createStep({\n id: 'classify-outcome',\n inputSchema: attemptOutputSchema,\n outputSchema: bodyOutputSchema,\n execute: async ({ inputData }) => {\n const { taskId, outcome, result, error } = inputData;\n const storage = await manager.getStorage();\n const task = await storage.getTask(taskId);\n if (!task) return { taskId, done: true };\n\n if (outcome === 'cancelled') {\n manager.deregisterTaskContext(taskId);\n return { taskId, done: true };\n }\n\n if (outcome === 'timed_out') {\n const status = task.status as string;\n if (status !== 'timed_out' && status !== 'cancelled') {\n await storage.updateTask(taskId, {\n status: 'timed_out',\n error: { message: `Task timed out after ${task.timeoutMs}ms` },\n completedAt: new Date(),\n });\n const timedOutTask = await storage.getTask(taskId);\n if (timedOutTask) await manager.publishLifecycleEvent('task.failed', timedOutTask);\n }\n return { taskId, done: true };\n }\n\n if (outcome === 'success') {\n if ((task.status as BackgroundTaskStatus) === 'cancelled') {\n manager.deregisterTaskContext(taskId);\n return { taskId, done: true };\n }\n await storage.updateTask(taskId, { status: 'completed', result, completedAt: new Date() });\n const completedTask = await storage.getTask(taskId);\n if (completedTask) {\n await manager.runLocalCompletionHooks(completedTask, 'completed', { result });\n await manager.publishLifecycleEvent('task.completed', completedTask);\n }\n return { taskId, done: true, result };\n }\n\n // outcome === 'retry' | 'failed'\n if (outcome === 'retry' && task.retryCount < task.maxRetries) {\n await storage.updateTask(taskId, {\n retryCount: task.retryCount + 1,\n error: undefined,\n startedAt: new Date(),\n });\n return { taskId, done: false };\n }\n\n // Retries exhausted (or non-retryable failure): persist failure and\n // throw so the workflow run ends\n // in `failed` rather than completing cleanly. Throw matches the prior\n // single-step behavior — workflow-run history stays accurate.\n const errorInfo = error ?? { message: 'Unknown error' };\n await storage.updateTask(taskId, { status: 'failed', error: errorInfo, completedAt: new Date() });\n const failedTask = await storage.getTask(taskId);\n if (failedTask) {\n await manager.runLocalCompletionHooks(failedTask, 'failed', { error: errorInfo });\n await manager.publishLifecycleEvent('task.failed', failedTask);\n }\n const thrown = new Error(errorInfo.message);\n if (errorInfo.name) thrown.name = errorInfo.name;\n if (errorInfo.stack) thrown.stack = errorInfo.stack;\n throw thrown;\n },\n });\n\n const attemptBodyWorkflow = createWorkflow({\n id: `${BACKGROUND_TASK_WORKFLOW_ID}__attempt`,\n inputSchema: bodyIOSchema,\n outputSchema: bodyOutputSchema,\n steps: [runAttemptStep, classifyOutcomeStep],\n options: {\n // `dountil` feeds the prior iteration's output back in as input. The\n // body's actual entry point only needs `taskId`, but the loop's\n // feedback shape includes `done`/`result`/etc. Skip validation rather\n // than widen every step's input schema.\n validateInputs: false,\n shouldPersistSnapshot: ({ workflowStatus }) => WORKFLOW_STATUS_TO_PERSIST.includes(workflowStatus),\n // Internal scheduler plumbing — hide workflow spans from exported\n // traces. The task body itself runs as user code and keeps its own\n // spans.\n tracingPolicy: {\n internal: InternalSpans.WORKFLOW,\n },\n },\n })\n .then(runAttemptStep)\n .then(classifyOutcomeStep)\n .commit();\n\n return createWorkflow({\n id: BACKGROUND_TASK_WORKFLOW_ID,\n inputSchema,\n outputSchema: bodyOutputSchema,\n steps: [attemptBodyWorkflow],\n options: {\n shouldPersistSnapshot: ({ workflowStatus }) => WORKFLOW_STATUS_TO_PERSIST.includes(workflowStatus),\n // Internal scheduler plumbing — see the inner workflow comment.\n tracingPolicy: {\n internal: InternalSpans.WORKFLOW,\n },\n },\n })\n .dountil(attemptBodyWorkflow, async ({ inputData }) => inputData?.done === true)\n .commit();\n}\n"],"mappings":";;;;;AAUA,MAAM,cAAc,EAAE,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,CAAC;AAEnD,MAAM,uBAAuB,EAAE,KAAK;CAAC;CAAW;CAAS;CAAU;CAAa;AAAW,CAAC;AAE5F,MAAM,sBAAsB,EAAE,OAAO;CACnC,QAAQ,EAAE,OAAO;CACjB,SAAS;CACT,QAAQ,EAAE,QAAQ,CAAC,CAAC,SAAS;CAC7B,OAAO,EAAE,IAAI,CAAC,CAAC,SAAS;AAC1B,CAAC;AAED,MAAM,eAAe,EAAE,OAAO;CAC5B,QAAQ,EAAE,OAAO;CACjB,MAAM,EAAE,QAAQ,CAAC,CAAC,SAAS;CAC3B,QAAQ,EAAE,QAAQ,CAAC,CAAC,SAAS;AAC/B,CAAC;AAED,MAAM,mBAAmB,EAAE,OAAO;CAChC,QAAQ,EAAE,OAAO;CACjB,MAAM,EAAE,QAAQ;CAChB,QAAQ,EAAE,QAAQ,CAAC,CAAC,SAAS;AAC/B,CAAC;AAED,MAAM,6BAA6B;CAAC;CAAa;CAAW;CAAU;AAAS;;;;;;;;;;;;;;;;;;;;AAqB/E,SAAgB,4BAA4B,SAAgC;CAC1E,MAAM,iBAAiB,WAAW;EAChC,IA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F;CACF,CAAC,CAAC,CACC,KAAK,cAAc,CAAC,CACpB,KAAK,mBAAmB,CAAC,CACzB,OAAO;CAEV,OAAO,eAAe;EACpB,IAAI;EACJ;EACA,cAAc;EACd,OAAO,CAAC,mBAAmB;EAC3B,SAAS;GACP,wBAAwB,EAAE,qBAAqB,2BAA2B,SAAS,cAAc;GAEjG,eAAe,EACb,UAAA,EACF;EACF;CACF,CAAC,CAAC,CACC,QAAQ,qBAAqB,OAAO,EAAE,gBAAgB,WAAW,SAAS,IAAI,CAAC,CAC/E,OAAO;AACZ"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_agent = require("../../agent-
|
|
2
|
+
const require_agent = require("../../agent-um2LJs-0.cjs");
|
|
3
3
|
exports.EventedExecutionEngine = require_agent.EventedExecutionEngine;
|
|
4
4
|
exports.EventedRun = require_agent.EventedRun;
|
|
5
5
|
exports.EventedWorkflow = require_agent.EventedWorkflow;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $t as createWorkflow, Jt as EventedRun, Qt as createStep, Xt as cloneStep, Yt as EventedWorkflow, Zt as cloneWorkflow, en as WorkflowEventProcessor, nn as EventedExecutionEngine, tn as StepExecutor } from "../../agent-
|
|
1
|
+
import { $t as createWorkflow, Jt as EventedRun, Qt as createStep, Xt as cloneStep, Yt as EventedWorkflow, Zt as cloneWorkflow, en as WorkflowEventProcessor, nn as EventedExecutionEngine, tn as StepExecutor } from "../../agent-0y2cApTZ.js";
|
|
2
2
|
export { EventedExecutionEngine, EventedRun, EventedWorkflow, StepExecutor, WorkflowEventProcessor, cloneStep, cloneWorkflow, createStep, createWorkflow };
|
package/dist/workflows/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_agent = require("../agent-
|
|
2
|
+
const require_agent = require("../agent-um2LJs-0.cjs");
|
|
3
3
|
const require_schedules = require("../schedules-dsrvt_6g.cjs");
|
|
4
4
|
const require_scheduler = require("../scheduler-DhXuncOg.cjs");
|
|
5
5
|
//#region src/workflows/state-reader.ts
|
package/dist/workflows/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { Cn as validateStepResumeData, Dn as getStepResult, En as waitForSuspendedSnapshot, Gt as cloneWorkflow, Kt as createEventedWorkflow, On as ExecutionEngine, Sn as validateStepRequestContext, Tn as validateStepSuspendData, _n as getStepIds, an as Workflow, bn as runCountDeprecationMessage, cn as isProcessor, fn as cleanStepResult, gn as getResumeLabelsByStepId, hn as createTimeTravelExecutionParams, in as Run, ln as mapVariable, mn as createRestartExecutionParams, on as cloneStep, pn as createDeprecationProxy, qt as createWorkflow, sn as createStep, un as DefaultExecutionEngine, vn as hydrateSerializedStepErrors, wn as validateStepStateData, xn as validateStepInput, yn as resolveForeachConcurrency } from "../agent-
|
|
1
|
+
import { Cn as validateStepResumeData, Dn as getStepResult, En as waitForSuspendedSnapshot, Gt as cloneWorkflow, Kt as createEventedWorkflow, On as ExecutionEngine, Sn as validateStepRequestContext, Tn as validateStepSuspendData, _n as getStepIds, an as Workflow, bn as runCountDeprecationMessage, cn as isProcessor, fn as cleanStepResult, gn as getResumeLabelsByStepId, hn as createTimeTravelExecutionParams, in as Run, ln as mapVariable, mn as createRestartExecutionParams, on as cloneStep, pn as createDeprecationProxy, qt as createWorkflow, sn as createStep, un as DefaultExecutionEngine, vn as hydrateSerializedStepErrors, wn as validateStepStateData, xn as validateStepInput, yn as resolveForeachConcurrency } from "../agent-0y2cApTZ.js";
|
|
2
2
|
import { a as computeNextFireAt, o as validateCron } from "../schedules-D3ilPNe9.js";
|
|
3
3
|
import { n as WorkflowScheduler, t as Scheduler } from "../scheduler-ttSQLz5R.js";
|
|
4
4
|
//#region src/workflows/state-reader.ts
|