UNPKG

@mastra/core

Version:

Mastra is a framework for building AI-powered applications and agents with a modern TypeScript stack.

1 lines 38.3 kB
{"version":3,"sources":["../src/worker/worker.ts","../src/worker/strategies/http-remote-strategy.ts","../src/worker/transport/pull-transport.ts","../src/worker/workers/orchestration-worker.ts","../src/worker/workers/scheduler-worker.ts","../src/worker/workers/background-task-worker.ts","../src/worker/strategies/in-process-strategy.ts"],"names":["WorkflowEventProcessor","WorkflowScheduler","BackgroundTaskManager","getStep","RequestContext","StepExecutor"],"mappings":";;;;;;;;AA2BO,IAAe,eAAf,MAA4B;AAAA,EAGvB,MAAA;AAAA,EACA,IAAA;AAAA;AAAA,EAGV,iBAAiB,MAAA,EAAsB;AACrC,IAAA,IAAA,CAAK,MAAA,GAAS,MAAA;AAAA,EAChB;AAAA;AAAA,EAGA,MAAM,KAAK,IAAA,EAAiC;AAC1C,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAI,CAAC,IAAA,CAAK,MAAA,IAAU,IAAA,CAAK,MAAA,EAAQ;AAC/B,MAAA,IAAA,CAAK,SAAS,IAAA,CAAK,MAAA;AAAA,IACrB;AAAA,EACF;AAKF;;;ACjBO,IAAM,kBAAA,GAAN,MAAM,mBAAA,CAAoD;AAAA,EAC/D,QAAA;AAAA,EACA,KAAA;AAAA,EACA,UAAA;AAAA,EAEA,WAAA,CAAY,EAAE,SAAA,EAAW,IAAA,EAAM,WAAU,EAA2E;AAElH,IAAA,MAAM,aAAa,SAAA,CAAU,QAAA,CAAS,GAAG,CAAA,GAAI,SAAA,GAAY,GAAG,SAAS,CAAA,CAAA,CAAA;AACrE,IAAA,IAAA,CAAK,QAAA,GAAW,IAAI,GAAA,CAAI,UAAU,CAAA;AAClC,IAAA,IAAA,CAAK,KAAA,GAAQ,IAAA,IAAQ,mBAAA,CAAmB,YAAA,EAAa;AACrD,IAAA,IAAA,CAAK,aAAa,SAAA,IAAa,GAAA;AAAA,EACjC;AAAA;AAAA;AAAA;AAAA;AA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,EACH;AACF","file":"chunk-LPGOWFV7.cjs","sourcesContent":["import type { PubSub } from '../events/pubsub';\nimport type { IMastraLogger } from '../logger';\nimport type { Mastra } from '../mastra';\nimport type { MastraCompositeStore } from '../storage';\n\n/**\n * Infrastructure dependencies provided to workers during initialization.\n */\nexport interface WorkerDeps {\n pubsub: PubSub;\n storage: MastraCompositeStore;\n logger: IMastraLogger;\n mastra?: Mastra;\n}\n\n/**\n * Abstract base class for Mastra workers.\n *\n * Each worker is a self-contained, independently deployable unit of\n * background processing. Concrete implementations include:\n * - OrchestrationWorker: processes workflow events\n * - SchedulerWorker: fires cron-based workflow schedules\n * - BackgroundTaskWorker: manages background tool execution\n *\n * Workers are registered on a Mastra instance and run inline by default.\n * They can also be launched standalone via the CLI for separate deployment.\n */\nexport abstract class MastraWorker {\n abstract readonly name: string;\n\n protected mastra?: Mastra;\n protected deps?: WorkerDeps;\n\n /** Called by Mastra during registration to provide the instance reference. */\n __registerMastra(mastra: Mastra): void {\n this.mastra = mastra;\n }\n\n /** Initialize with infrastructure deps. Called before start(). */\n async init(deps: WorkerDeps): Promise<void> {\n this.deps = deps;\n if (!this.mastra && deps.mastra) {\n this.mastra = deps.mastra;\n }\n }\n\n abstract start(): Promise<void>;\n abstract stop(): Promise<void>;\n abstract get isRunning(): boolean;\n}\n","import type { StepResult } from '../../workflows/types';\nimport type { StepExecutionParams, StepExecutionStrategy } from '../types';\n\n/**\n * Auth credential used by `HttpRemoteStrategy` when calling the server's\n * step-execution endpoint. The server's configured Mastra auth provider\n * (`authenticateToken`) decides whether to accept the credential — this\n * strategy just forwards it.\n *\n * - `bearer`: send `Authorization: Bearer <token>` (default when only a\n * token string is available)\n * - `api-key`: send `x-worker-api-key: <key>` for deployments that prefer\n * a custom header (the auth provider's `authenticateToken(_, request)`\n * callback can read it from `request.headers`)\n * - `header`: arbitrary header / value pair for fully custom schemes\n */\nexport type HttpRemoteAuthConfig =\n | { type: 'bearer'; token: string }\n | { type: 'api-key'; key: string }\n | { type: 'header'; name: string; value: string };\n\n/**\n * Executes workflow steps by calling a remote server endpoint over HTTP.\n * Used in standalone worker deployments where the worker runs orchestration\n * logic but delegates actual step execution to the server.\n *\n * Authentication piggy-backs on Mastra's existing auth pipeline: the route\n * is marked `requiresAuth: true` and the deployer's `authenticateToken`\n * provider validates the credential we send here. There is no separate\n * \"worker secret\" — whatever auth scheme the rest of the server uses is\n * what the worker uses too.\n */\nexport class HttpRemoteStrategy implements StepExecutionStrategy {\n #baseUrl: URL;\n #auth?: HttpRemoteAuthConfig;\n #timeoutMs: number;\n\n constructor({ serverUrl, auth, timeoutMs }: { serverUrl: string; auth?: HttpRemoteAuthConfig; timeoutMs?: number }) {\n // Normalize once: ensure trailing slash so URL joins compose correctly.\n const normalized = serverUrl.endsWith('/') ? serverUrl : `${serverUrl}/`;\n this.#baseUrl = new URL(normalized);\n this.#auth = auth ?? HttpRemoteStrategy.#authFromEnv();\n this.#timeoutMs = timeoutMs ?? 30_000;\n }\n\n /**\n * Default credential resolution: when `MASTRA_WORKER_AUTH_TOKEN` is set,\n * send it as a bearer token. The server's auth provider decides whether\n * to accept it.\n */\n static #authFromEnv(): HttpRemoteAuthConfig | undefined {\n const token = process.env.MASTRA_WORKER_AUTH_TOKEN;\n if (!token) return undefined;\n return { type: 'bearer', token };\n }\n\n async executeStep(params: StepExecutionParams): Promise<StepResult<unknown, unknown, unknown, unknown>> {\n const url = new URL(\n `workflows/${encodeURIComponent(params.workflowId)}/runs/${encodeURIComponent(params.runId)}/steps/execute`,\n this.#baseUrl,\n );\n\n const body = this.#buildBody(params);\n\n const signal = this.#combineSignals(params.abortSignal);\n\n const res = await fetch(url, {\n method: 'POST',\n headers: {\n 'content-type': 'application/json',\n ...this.#buildAuthHeaders(),\n },\n body,\n signal,\n });\n\n if (!res.ok) {\n const text = await res.text();\n throw new StepExecutionError(res.status, text);\n }\n\n return res.json() as Promise<StepResult<unknown, unknown, unknown, unknown>>;\n }\n\n /**\n * Build a JSON-serializable request body. The `params.requestContext` is\n * a plain object; if a caller stuffed a non-serializable value into it we\n * surface a clear error instead of silently dropping fields.\n *\n * `abortSignal` is consumed via fetch's `signal` argument — it must not\n * be in the body.\n */\n #buildBody(params: StepExecutionParams): string {\n const { abortSignal: _abortSignal, requestContext, ...rest } = params;\n let safeRequestContext: Record<string, unknown>;\n try {\n safeRequestContext = JSON.parse(JSON.stringify(requestContext ?? {}));\n } catch (err) {\n throw new Error(\n `HttpRemoteStrategy: requestContext is not JSON-serializable. ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n\n return JSON.stringify({\n ...rest,\n requestContext: safeRequestContext,\n });\n }\n\n #combineSignals(externalSignal?: AbortSignal): AbortSignal {\n const timeoutSignal = AbortSignal.timeout(this.#timeoutMs);\n if (!externalSignal) return timeoutSignal;\n // AbortSignal.any aborts when any input aborts.\n if (typeof AbortSignal.any === 'function') {\n return AbortSignal.any([timeoutSignal, externalSignal]);\n }\n // Fallback for runtimes without AbortSignal.any\n const controller = new AbortController();\n const onAbort = (reason: unknown) => controller.abort(reason);\n if (externalSignal.aborted) onAbort(externalSignal.reason);\n else externalSignal.addEventListener('abort', () => onAbort(externalSignal.reason), { once: true });\n if (timeoutSignal.aborted) onAbort(timeoutSignal.reason);\n else timeoutSignal.addEventListener('abort', () => onAbort(timeoutSignal.reason), { once: true });\n return controller.signal;\n }\n\n #buildAuthHeaders(): Record<string, string> {\n if (!this.#auth) return {};\n if (this.#auth.type === 'api-key') {\n return { 'x-worker-api-key': this.#auth.key };\n }\n if (this.#auth.type === 'header') {\n return { [this.#auth.name]: this.#auth.value };\n }\n return { authorization: `Bearer ${this.#auth.token}` };\n }\n}\n\nexport class StepExecutionError extends Error {\n readonly status: number;\n readonly body: string;\n\n constructor(status: number, body: string) {\n super(`Step execution failed with status ${status}: ${body}`);\n this.name = 'StepExecutionError';\n this.status = status;\n this.body = body;\n }\n}\n","import type { PubSub } from '../../events/pubsub';\nimport type { EventCallback } from '../../events/types';\nimport type { IMastraLogger } from '../../logger';\nimport type { EventRouter, WorkerTransport } from './transport';\n\nconst TOPIC_WORKFLOWS = 'workflows';\n\nexport class PullTransport implements WorkerTransport {\n #pubsub: PubSub;\n #group: string;\n #logger?: IMastraLogger;\n #callbacks: Array<{ topic: string; cb: EventCallback }> = [];\n\n constructor({ pubsub, group, logger }: { pubsub: PubSub; group: string; logger?: IMastraLogger }) {\n this.#pubsub = pubsub;\n this.#group = group;\n this.#logger = logger;\n }\n\n async start(router: EventRouter): Promise<void> {\n if (this.#callbacks.length > 0) {\n this.#logger?.debug('[PullTransport] start() called while already subscribed; ignoring duplicate call');\n return;\n }\n const workflowCb: EventCallback = (event, ack, nack) => {\n // route() is async; surface unexpected rejections as a nack instead\n // of an unhandledRejection. The router's own try/catch already turns\n // expected processing errors into nack — this guard only catches\n // synchronous-throw-becomes-rejected-promise leaks.\n router.route(event, ack, nack).catch(err => {\n try {\n // Best-effort: ack/nack are optional in some PubSub backends.\n if (typeof nack === 'function') {\n void nack();\n }\n } finally {\n this.#logger?.error('[PullTransport] router.route rejected', { err });\n }\n });\n };\n await this.#pubsub.subscribe(TOPIC_WORKFLOWS, workflowCb, { group: this.#group });\n this.#callbacks.push({ topic: TOPIC_WORKFLOWS, cb: workflowCb });\n }\n\n async stop(): Promise<void> {\n for (const { topic, cb } of this.#callbacks) {\n await this.#pubsub.unsubscribe(topic, cb);\n }\n this.#callbacks = [];\n await this.#pubsub.flush();\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 if (nack) {\n await nack();\n }\n }\n}\n","import type { IMastraLogger } from '../../logger';\nimport { WorkflowScheduler } from '../../workflows/scheduler/scheduler';\nimport type { WorkflowSchedulerConfig } 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?: WorkflowScheduler;\n #config: WorkflowSchedulerConfig;\n #running = false;\n\n constructor(config: WorkflowSchedulerConfig = {}) {\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 workflow-existence predicate so the scheduler can reclaim\n // schedule rows whose target workflow is no longer registered with\n // Mastra (e.g. workflow renamed or deleted in code). `getWorkflowById`\n // throws on miss; we adapt that into a boolean.\n const mastra = this.mastra;\n const isWorkflowRegistered = mastra\n ? (workflowId: string) => {\n try {\n mastra.getWorkflowById(workflowId);\n return true;\n } catch {\n return false;\n }\n }\n : undefined;\n\n this.#scheduler = new WorkflowScheduler({\n schedulesStore,\n pubsub: deps.pubsub,\n config: { ...this.#config, isWorkflowRegistered },\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(): WorkflowScheduler | 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 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 const workflow = this.#mastra.getWorkflow(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"]}