{"version":3,"file":"worker-H14yjTvH.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","getStepEntry","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 { getStepEntry } 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 entry = getStepEntry(workflow, params.executionPath);\n\n    if (!entry) {\n      throw new Error(\n        `InProcessStrategy: could not resolve step \"${params.stepId}\" at executionPath [${params.executionPath.join(',')}] in workflow \"${params.workflowId}\"`,\n      );\n    }\n\n    const rc = new RequestContext<unknown>(Object.entries(params.requestContext ?? {}));\n\n    let abortController: AbortController | undefined;\n    if (params.abortSignal) {\n      abortController = new AbortController();\n      if (params.abortSignal.aborted) {\n        abortController.abort(params.abortSignal.reason);\n      } else {\n        params.abortSignal.addEventListener(\n          'abort',\n          () => {\n            abortController!.abort(params.abortSignal!.reason);\n          },\n          { once: true },\n        );\n      }\n    }\n\n    const executor = new StepExecutor({ mastra: this.#mastra });\n\n    return executor.execute({\n      workflowId: params.workflowId,\n      entry,\n      runId: params.runId,\n      stepResults: params.stepResults as Record<string, StepResult<any, any, any, any>>,\n      state: params.state,\n      requestContext: rc,\n      input: params.input,\n      resumeData: params.resumeData,\n      retryCount: params.retryCount,\n      foreachIdx: params.foreachIdx,\n      validateInputs: params.validateInputs,\n      abortController,\n      format: params.format,\n      perStep: params.perStep,\n    });\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,IAA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