{"version":3,"file":"schedules-D_aayWxz.cjs","names":["z","MastraError","ErrorDomain","ErrorCategory","#mastra","#getStore","#load","#createWorkflowSchedule","#createAgentSchedule","#assertIdAvailable","computeNextFireAt","#patchAgentTarget","#patchWorkflowTarget"],"sources":["../src/schedules/types.ts","../src/schedules/schedules.ts"],"sourcesContent":["import { z } from 'zod/v4';\nimport type { AgentSignalAttributes, AgentSignalType } from '../agent/signals';\nimport type { AgentSignalActiveBehavior, AgentSignalIdleBehavior } from '../agent/types';\n\n/**\n * Serializable subset of `AgentExecutionOptions` that an agent schedule persists and\n * applies to the woken run. Schedule config is JSON-persisted to schedule\n * storage, so only JSON-safe fields are accepted here — non-serializable run\n * options (callbacks, abort signals, live handles) are excluded by design.\n *\n * `requestContext` is stored as a plain object and rehydrated into a\n * `RequestContext` by the worker before the wake signal runs. This is how a\n * schedule-woken run receives request context (e.g. channel render context).\n */\nexport type ScheduleStreamOptions = {\n  /** Request context applied to the woken run, stored as a plain object. */\n  requestContext?: Record<string, unknown>;\n};\n\n/**\n * Options applied when the target thread is actively streaming. Threaded only.\n * Mirrors the signal runtime's `ifActive` options so agent schedules accept the same\n * shape `agent.sendSignal` allows.\n */\nexport type ScheduleIfActive = {\n  behavior?: AgentSignalActiveBehavior;\n  attributes?: AgentSignalAttributes;\n};\n\n/**\n * Options applied when the target thread is idle. Threaded only. Mirrors the\n * signal runtime's `ifIdle` options, but `streamOptions` is restricted to the\n * serializable {@link ScheduleStreamOptions} subset so the config can be\n * persisted to schedule storage.\n */\nexport type ScheduleIfIdle = {\n  behavior?: AgentSignalIdleBehavior;\n  attributes?: AgentSignalAttributes;\n  streamOptions?: ScheduleStreamOptions;\n};\n\n/** Stable schedule id prefix for agent schedules. */\nexport const AGENT_SCHEDULE_PREFIX = 'agent_';\n\n/**\n * Stable schedule id prefix for imperative workflow schedules created via\n * `mastra.schedules.create({ workflowId, ... })`. Intentionally distinct from\n * the `wf_` prefix used by declarative `createWorkflow({ schedule })` rows —\n * the boot-time declarative sync sweeps `wf_` rows against the in-code\n * config and must never delete imperative rows.\n */\nexport const WORKFLOW_SCHEDULE_PREFIX = 'schedule_';\n\n/**\n * Status reported by a single agent-schedule run. The {@link AgentScheduleWorker}\n * derives the scheduler trigger row's `outcome` (`succeeded`, `delivered`,\n * `persisted`, `discarded`, `skipped`, `aborted`, or `failed`) from this;\n * the status is also surfaced on the trigger row's metadata.\n *\n * Distinct from `ScheduleTriggerOutcome` (which describes scheduler-level\n * dispatch results); this describes what the agent-schedule tick itself did.\n */\nexport type ScheduleRunStatus =\n  | 'fired'\n  | 'signal-accepted'\n  | 'skipped-thread-blocked'\n  | 'thread-missing'\n  | 'agent-missing'\n  | 'invalid-input';\n\n/** Shared zod for {@link AgentSignalAttributes} (XML tag attribute values). */\nconst ScheduleAttributesSchema = z.record(z.string(), z.union([z.string(), z.number(), z.boolean(), z.null()]));\n\n/** Serializable stream options applied to a woken run. See {@link ScheduleStreamOptions}. */\nconst ScheduleStreamOptionsSchema = z.object({\n  requestContext: z.record(z.string(), z.unknown()).optional(),\n});\n\n/** Options applied when the target thread is actively streaming. */\nconst ScheduleIfActiveSchema = z.object({\n  behavior: z.enum(['deliver', 'persist', 'discard']).optional(),\n  attributes: ScheduleAttributesSchema.optional(),\n});\n\n/** Options applied when the target thread is idle. */\nconst ScheduleIfIdleSchema = z.object({\n  behavior: z.enum(['wake', 'persist', 'discard']).optional(),\n  attributes: ScheduleAttributesSchema.optional(),\n  streamOptions: ScheduleStreamOptionsSchema.optional(),\n});\n\n/**\n * Input payload persisted in `Schedule.target.inputData` for the built-in\n * agent-schedule fire. The scheduler tick rehydrates this on every fire.\n */\nexport const ScheduleInputSchema = z.object({\n  scheduleId: z.string(),\n  agentId: z.string(),\n  prompt: z.string(),\n  threadId: z.string().optional(),\n  resourceId: z.string().optional(),\n  signalType: z.enum(['user', 'state', 'reactive', 'notification', 'user-message', 'system-reminder']).optional(),\n  /**\n   * XML tag name the signal renders as. Defaults to `schedule`, so a fire\n   * surfaces to the agent as `<schedule>…</schedule>`. Override to render a\n   * different tag.\n   */\n  tagName: z.string().optional(),\n  /** Attributes rendered onto the signal's XML tag. */\n  attributes: ScheduleAttributesSchema.optional(),\n  /**\n   * Provider options merged into the schedule signal payload on every fire.\n   * Stored as a plain JSON object (`MastraProviderMetadata` is JSON-safe) and\n   * applied regardless of `ifActive` / `ifIdle`.\n   */\n  providerOptions: z.record(z.string(), z.unknown()).optional(),\n  ifActive: ScheduleIfActiveSchema.optional(),\n  ifIdle: ScheduleIfIdleSchema.optional(),\n});\n\nexport type ScheduleInput = z.infer<typeof ScheduleInputSchema>;\n\nexport const ScheduleOutputSchema = z.object({\n  status: z.enum([\n    'fired',\n    'signal-accepted',\n    'skipped-thread-blocked',\n    'thread-missing',\n    'agent-missing',\n    'invalid-input',\n  ]),\n  reason: z.string().optional(),\n});\n\nexport type ScheduleOutput = z.infer<typeof ScheduleOutputSchema>;\n\n// ---------------------------------------------------------------------------\n// Lifecycle hooks\n//\n// User-defined callbacks configured via `new Mastra({ schedules: { ... } })`.\n// A single hook bundle runs for every schedule fire; each context carries\n// `agentId` so a hook can branch per agent. Mirror the\n// `agent.stream` `onFinish`/`onError`/`onAbort` conventions so users learn one\n// mental model. `prepare` lets users compute fire-time parameters (e.g. create\n// a Slack thread per fire) or skip the fire entirely by returning null.\n// ---------------------------------------------------------------------------\n\n/** Effective parameters the agent-schedule worker uses on a single fire. */\nexport type ScheduleEffective = {\n  threadId?: string;\n  resourceId?: string;\n  prompt: string;\n  signalType?: AgentSignalType;\n  tagName?: string;\n  ifActive?: ScheduleIfActive;\n  ifIdle?: ScheduleIfIdle;\n  attributes?: AgentSignalAttributes;\n  providerOptions?: Record<string, unknown>;\n};\n\n/** Trigger context passed to every hook. */\nexport type ScheduleTriggerInfo = {\n  kind: 'cron' | 'manual';\n  firedAt: Date;\n};\n\n/** Limited terminal-state snapshot for a schedule-driven agent run. */\nexport type ScheduleRunResultSnapshot = {\n  text?: string;\n  usage?: Record<string, unknown>;\n  finishReason?: string;\n};\n\n/** Forward-declared so this file does not import from `./schedules`. */\ninterface ScheduleRef {\n  id: string;\n  agentId: string;\n  name?: string;\n  [key: string]: unknown;\n}\n\n/** Argument passed to `schedules.prepare`. */\nexport type SchedulePrepareContext<TMastra = unknown> = {\n  mastra: TMastra;\n  /** The agent this schedule fires. Convenience alias for `schedule.agentId`. */\n  agentId: string;\n  schedule: ScheduleRef;\n  trigger: ScheduleTriggerInfo;\n};\n\n/**\n * Return value from `schedules.prepare`.\n *\n * - object    → merged into the row defaults; missing fields fall back to the row\n * - `null`    → skip this fire (outcome: 'skipped'); the worker records the trigger\n *               row and fires `onFinish({ outcome: 'skipped' })`\n * - `undefined` → use row defaults verbatim\n */\nexport type SchedulePrepareResult = Partial<ScheduleEffective>;\n\n/** Argument passed to `schedules.onFinish` for any non-error, non-abort outcome. */\nexport type ScheduleFinishContext<TMastra = unknown> = {\n  mastra: TMastra;\n  /** The agent this schedule fires. Convenience alias for `schedule.agentId`. */\n  agentId: string;\n  schedule: ScheduleRef;\n  trigger: ScheduleTriggerInfo;\n  outcome: 'succeeded' | 'delivered' | 'persisted' | 'discarded' | 'skipped';\n  /** Present for `succeeded` and `delivered` outcomes. */\n  runId?: string;\n  /** True when `outcome === 'delivered'` and the signal joined an active run. */\n  joinedExistingRun?: boolean;\n  /** Best-effort terminal snapshot; populated for `succeeded` runs. */\n  result?: ScheduleRunResultSnapshot;\n  effective: ScheduleEffective;\n};\n\n/** Argument passed to `schedules.onError` whenever `prepare`, `sendSignal`, or the agent run threw. */\nexport type ScheduleErrorContext<TMastra = unknown> = {\n  mastra: TMastra;\n  /** The agent this schedule fires. Convenience alias for `schedule.agentId`. */\n  agentId: string;\n  schedule: ScheduleRef;\n  trigger: ScheduleTriggerInfo;\n  phase: 'prepare' | 'run';\n  error: Error;\n  runId?: string;\n  /** Best-effort effective view; may be partial if `prepare` threw before merging. */\n  effective?: ScheduleEffective;\n};\n\n/** Argument passed to `schedules.onAbort` when the run was aborted mid-stream. */\nexport type ScheduleAbortContext<TMastra = unknown> = {\n  mastra: TMastra;\n  /** The agent this schedule fires. Convenience alias for `schedule.agentId`. */\n  agentId: string;\n  schedule: ScheduleRef;\n  trigger: ScheduleTriggerInfo;\n  runId: string;\n  effective: ScheduleEffective;\n};\n\n/**\n * Bundle of lifecycle hooks. A single bundle runs for every schedule fire;\n * each context carries `agentId` so a hook can branch per agent.\n *\n * `onFinish` fires once per schedule trigger when the trigger reached a\n * non-error, non-abort terminal state. `onError` fires when `prepare`,\n * `sendSignal`, or the agent run threw. `onAbort` fires when the run was\n * aborted mid-stream. `prepare` can return overrides, `null` to skip, or\n * `undefined` to use row defaults.\n *\n * Hook exceptions are caught and logged; they never re-route the worker or\n * recurse into another hook.\n */\nexport type ScheduleHooks<TMastra = unknown> = {\n  prepare?: (\n    ctx: SchedulePrepareContext<TMastra>,\n  ) => Promise<SchedulePrepareResult | null | undefined> | SchedulePrepareResult | null | undefined;\n  onFinish?: (ctx: ScheduleFinishContext<TMastra>) => Promise<void> | void;\n  onError?: (ctx: ScheduleErrorContext<TMastra>) => Promise<void> | void;\n  onAbort?: (ctx: ScheduleAbortContext<TMastra>) => Promise<void> | void;\n};\n\n/**\n * Schedules runtime configuration passed to the Mastra constructor via\n * `schedules`. Holds a single lifecycle hook bundle that runs for every\n * schedule fire. Hooks live at the Mastra level so they apply to both\n * code-defined and stored agents (stored agents cannot define functions in\n * their serialized config). Each hook context carries `agentId`, so branch\n * on it when a hook should behave differently per agent.\n *\n * @example\n * ```typescript\n * new Mastra({\n *   schedules: {\n *     prepare: async ({ agentId, schedule }) => ({ threadId: '...' }),\n *     onFinish: async ({ agentId, trigger }) => { ... },\n *   },\n * });\n * ```\n */\nexport type SchedulesConfig<TMastra = unknown> = ScheduleHooks<TMastra>;\n","import { randomUUID } from 'node:crypto';\nimport slugify from '@sindresorhus/slugify';\nimport type { AgentSignalAttributes, AgentSignalType } from '../agent/signals';\nimport { ErrorCategory, ErrorDomain, MastraError } from '../error';\nimport type { Mastra } from '../mastra';\nimport type { Schedule, SchedulesStorage } from '../storage/domains/schedules/base';\nimport { computeNextFireAt, validateCron } from '../workflows/scheduler/cron';\nimport type { ScheduleIfActive, ScheduleIfIdle } from './types';\nimport { AGENT_SCHEDULE_PREFIX, WORKFLOW_SCHEDULE_PREFIX } from './types';\n\ntype AgentTarget = Extract<Schedule['target'], { type: 'agent' }>;\ntype WorkflowTarget = Extract<Schedule['target'], { type: 'workflow' }>;\n\n/** PubSub topic consumed by the workflow event processor. */\nconst TOPIC_WORKFLOWS = 'workflows';\n\n/**\n * Slugify the caller-facing portion of a schedule id into a canonical\n * `<prefix><slug>` shape. The slug part is lowercased and stripped of\n * characters that are unsafe in storage keys / URLs; the prefix is added only\n * if missing so a caller can pass either `nightly-summary` or\n * `agent_nightly-summary` and get the same canonical id. Returns an empty\n * string when nothing slug-able remains.\n */\nfunction canonicalizeScheduleId(rawId: string, prefix: string): string {\n  const trimmed = rawId.trim();\n  const withoutPrefix = trimmed.startsWith(prefix) ? trimmed.slice(prefix.length) : trimmed;\n  const slug = slugify(withoutPrefix);\n  if (!slug) return '';\n  return `${prefix}${slug}`;\n}\n\n/**\n * Normalize a caller-supplied schedule id for `create`. Throws\n * `SCHEDULES_INVALID_ID` when the id is empty after normalization so callers\n * cannot create an unaddressable schedule.\n */\nfunction normalizeScheduleId(rawId: string, prefix: string): string {\n  const canonical = canonicalizeScheduleId(rawId, prefix);\n  if (!canonical) {\n    throw new MastraError({\n      id: 'SCHEDULES_INVALID_ID',\n      domain: ErrorDomain.AGENT,\n      category: ErrorCategory.USER,\n      text: `schedules.create: id \"${rawId}\" is empty after normalization. Provide an id with at least one alphanumeric character.`,\n    });\n  }\n  return canonical;\n}\n\n/**\n * Flat agent-schedule view returned by the {@link Schedules} service.\n * Projects the underlying `Schedule` row + `target.type === 'agent'` payload\n * onto a single object so callers never have to know about the schedules\n * storage shape. Discriminate from {@link WorkflowSchedule} via the\n * `agentId` field.\n */\nexport interface AgentSchedule {\n  id: string;\n  agentId: string;\n  /** Discriminant mirror — always absent on agent schedules. Check `workflowId` to narrow {@link AnySchedule}. */\n  workflowId?: undefined;\n  name?: string;\n  threadId?: string;\n  resourceId?: string;\n  prompt: string;\n  cron: string;\n  timezone?: string;\n  status: 'active' | 'paused';\n  nextFireAt: number;\n  lastFireAt?: number;\n  lastRunId?: string;\n  signalType?: AgentSignalType;\n  tagName?: string;\n  attributes?: AgentSignalAttributes;\n  providerOptions?: Record<string, unknown>;\n  ifActive?: ScheduleIfActive;\n  ifIdle?: ScheduleIfIdle;\n  metadata?: Record<string, unknown>;\n  createdAt: number;\n  updatedAt: number;\n}\n\n/**\n * Flat workflow-schedule view returned by the {@link Schedules} service.\n * Discriminate from {@link AgentSchedule} via the `workflowId` field.\n */\nexport interface WorkflowSchedule {\n  id: string;\n  workflowId: string;\n  /** Discriminant mirror — always absent on workflow schedules. Check `agentId` to narrow {@link AnySchedule}. */\n  agentId?: undefined;\n  cron: string;\n  timezone?: string;\n  status: 'active' | 'paused';\n  nextFireAt: number;\n  lastFireAt?: number;\n  lastRunId?: string;\n  inputData?: unknown;\n  initialState?: unknown;\n  requestContext?: Record<string, unknown>;\n  metadata?: Record<string, unknown>;\n  createdAt: number;\n  updatedAt: number;\n}\n\n/** Union of the flat views returned by the {@link Schedules} service. */\nexport type AnySchedule = AgentSchedule | WorkflowSchedule;\n\n/** Agent variant of {@link CreateScheduleInput}. */\nexport interface CreateAgentScheduleInput {\n  /**\n   * Optional stable id. Normalized to `agent_<slug>` (the `agent_` prefix is\n   * added if missing and the rest is slugified). When omitted, a random\n   * `agent_<uuid>` id is generated. Creating a schedule with an id that\n   * already exists throws.\n   */\n  id?: string;\n  agentId: string;\n  cron: string;\n  prompt: string;\n  /** Optional free-form label for distinguishing multiple schedules on the same agent/thread. */\n  name?: string;\n  timezone?: string;\n  threadId?: string;\n  resourceId?: string;\n  /** Signal category for the fire. Defaults to `'notification'`. */\n  signalType?: AgentSignalType;\n  /** XML tag the signal renders as. Defaults to `'schedule'` (so a fire surfaces as `<schedule>…</schedule>`). */\n  tagName?: string;\n  /** Attributes rendered onto the signal's XML tag. */\n  attributes?: AgentSignalAttributes;\n  /** Provider options merged into the schedule signal payload on every fire. JSON-safe. */\n  providerOptions?: Record<string, unknown>;\n  ifActive?: ScheduleIfActive;\n  ifIdle?: ScheduleIfIdle;\n  metadata?: Record<string, unknown>;\n  /** Schedule lifecycle status. Defaults to `'active'`. */\n  status?: 'active' | 'paused';\n}\n\n/** Workflow variant of {@link CreateScheduleInput}. */\nexport interface CreateWorkflowScheduleInput {\n  /**\n   * Optional stable id. Normalized to `schedule_<slug>`. When omitted, a\n   * random `schedule_<uuid>` id is generated. Imperative workflow schedules\n   * intentionally never use the `wf_` prefix — that prefix is reserved for\n   * declarative `createWorkflow({ schedule })` rows, which the boot-time\n   * sync sweeps against the in-code config.\n   */\n  id?: string;\n  workflowId: string;\n  cron: string;\n  timezone?: string;\n  inputData?: unknown;\n  initialState?: unknown;\n  requestContext?: Record<string, unknown>;\n  metadata?: Record<string, unknown>;\n  /** Schedule lifecycle status. Defaults to `'active'`. */\n  status?: 'active' | 'paused';\n}\n\n/**\n * Input to {@link Schedules.create}. Discriminated by `agentId` vs\n * `workflowId`.\n */\nexport type CreateScheduleInput = CreateAgentScheduleInput | CreateWorkflowScheduleInput;\n\n/** Agent variant of {@link UpdateScheduleInput}. */\nexport interface UpdateAgentScheduleInput {\n  cron?: string;\n  timezone?: string;\n  prompt?: string;\n  name?: string;\n  signalType?: AgentSignalType;\n  tagName?: string;\n  attributes?: AgentSignalAttributes;\n  providerOptions?: Record<string, unknown>;\n  ifActive?: ScheduleIfActive;\n  ifIdle?: ScheduleIfIdle;\n  metadata?: Record<string, unknown>;\n  status?: 'active' | 'paused';\n}\n\n/** Workflow variant of {@link UpdateScheduleInput}. */\nexport interface UpdateWorkflowScheduleInput {\n  cron?: string;\n  timezone?: string;\n  inputData?: unknown;\n  initialState?: unknown;\n  requestContext?: Record<string, unknown>;\n  metadata?: Record<string, unknown>;\n  status?: 'active' | 'paused';\n}\n\n/** Patch input to {@link Schedules.update}. */\nexport type UpdateScheduleInput = UpdateAgentScheduleInput | UpdateWorkflowScheduleInput;\n\n/** Filter for {@link Schedules.list}. */\nexport interface ListSchedulesFilter {\n  /** Return only agent schedules for this agent. */\n  agentId?: string;\n  /** Return only workflow schedules for this workflow. */\n  workflowId?: string;\n  /** Agent-schedule only: match the target threadId. */\n  threadId?: string;\n  /** Agent-schedule only: match the target resourceId. */\n  resourceId?: string;\n  /** Agent-schedule only: match the free-form target name. */\n  name?: string;\n  status?: 'active' | 'paused';\n}\n\n/**\n * Unified service for cron schedules. Schedules are persisted as `Schedule`\n * rows whose `target` discriminates what fires: `type: 'agent'` rows run an\n * agent (via signal or `agent.generate`), `type: 'workflow'` rows start a\n * workflow run. This class is a typed projection over `SchedulesStorage`\n * that knows how to build targets and surface flat\n * {@link AgentSchedule} / {@link WorkflowSchedule} views.\n *\n * Use via `mastra.schedules` (the canonical CRUD surface).\n */\nexport class Schedules {\n  #mastra: Mastra;\n\n  constructor(mastra: Mastra) {\n    this.#mastra = mastra;\n  }\n\n  async #getStore() {\n    const storage = this.#mastra.getStorage();\n    const store = await storage?.getStore('schedules');\n    if (!store) {\n      throw new MastraError({\n        id: 'SCHEDULES_NO_SCHEDULES_STORAGE',\n        domain: ErrorDomain.AGENT,\n        category: ErrorCategory.USER,\n        text: 'Schedules require a storage adapter that implements the schedules domain.',\n      });\n    }\n    return store;\n  }\n\n  /**\n   * Resolve a caller-supplied id to a stored row. An id is first looked up\n   * verbatim (covering `agent_`, `schedule_`, `wf_`, and legacy `hb_` ids);\n   * when that misses, a bare caller id is canonicalized to `agent_<slug>` to\n   * match what agent-schedule `create` persisted.\n   */\n  async #load(id: string): Promise<Schedule | null> {\n    const store = await this.#getStore();\n    const trimmed = id.trim();\n    const exact = trimmed ? await store.getSchedule(trimmed) : null;\n    if (exact) return exact;\n    const canonical = canonicalizeScheduleId(trimmed, AGENT_SCHEDULE_PREFIX);\n    if (!canonical || canonical === trimmed) return null;\n    return store.getSchedule(canonical);\n  }\n\n  async create(input: CreateAgentScheduleInput): Promise<AgentSchedule>;\n  async create(input: CreateWorkflowScheduleInput): Promise<WorkflowSchedule>;\n  async create(input: CreateScheduleInput): Promise<AnySchedule> {\n    if ('workflowId' in input && input.workflowId) {\n      return this.#createWorkflowSchedule(input);\n    }\n    return this.#createAgentSchedule(input as CreateAgentScheduleInput);\n  }\n\n  async #createAgentSchedule(input: CreateAgentScheduleInput): Promise<AgentSchedule> {\n    validateCron(input.cron, input.timezone);\n\n    if (!input.agentId) {\n      throw new MastraError({\n        id: 'SCHEDULES_MISSING_TARGET_ID',\n        domain: ErrorDomain.AGENT,\n        category: ErrorCategory.USER,\n        text: 'schedules.create requires `agentId` or `workflowId`.',\n      });\n    }\n\n    if (input.threadId && !input.resourceId) {\n      throw new MastraError({\n        id: 'SCHEDULES_MISSING_RESOURCE_ID',\n        domain: ErrorDomain.AGENT,\n        category: ErrorCategory.USER,\n        text: 'schedules.create requires `resourceId` when `threadId` is set.',\n      });\n    }\n    if (!input.threadId) {\n      const offenders: string[] = [];\n      if (input.signalType !== undefined) offenders.push('signalType');\n      if (input.ifActive !== undefined) offenders.push('ifActive');\n      if (input.ifIdle !== undefined) offenders.push('ifIdle');\n      if (input.resourceId !== undefined) offenders.push('resourceId');\n      if (offenders.length > 0) {\n        throw new MastraError({\n          id: 'SCHEDULES_THREADLESS_OPTIONS',\n          domain: ErrorDomain.AGENT,\n          category: ErrorCategory.USER,\n          text: `schedules.create: ${offenders.join(', ')} require a threadId.`,\n        });\n      }\n    }\n\n    const store = await this.#getStore();\n    // Make sure the scheduler + agent-schedule worker are running. Boot-time\n    // detection covers existing rows; imperative creates after\n    // startWorkers() need to flip the request flag and lazily inject.\n    await this.#mastra.__ensureScheduleRuntimeReady();\n\n    const id =\n      input.id !== undefined\n        ? normalizeScheduleId(input.id, AGENT_SCHEDULE_PREFIX)\n        : `${AGENT_SCHEDULE_PREFIX}${randomUUID()}`;\n    await this.#assertIdAvailable(store, id, input.id !== undefined);\n    const now = Date.now();\n    const nextFireAt = computeNextFireAt(input.cron, { timezone: input.timezone, after: now });\n\n    const target: AgentTarget = {\n      type: 'agent',\n      agentId: input.agentId,\n      prompt: input.prompt,\n      ...(input.name !== undefined ? { name: input.name } : {}),\n      ...(input.threadId ? { threadId: input.threadId } : {}),\n      ...(input.resourceId ? { resourceId: input.resourceId } : {}),\n      ...(input.signalType ? { signalType: input.signalType } : {}),\n      ...(input.tagName ? { tagName: input.tagName } : {}),\n      ...(input.attributes ? { attributes: input.attributes } : {}),\n      ...(input.providerOptions ? { providerOptions: input.providerOptions } : {}),\n      ...(input.ifActive ? { ifActive: input.ifActive } : {}),\n      ...(input.ifIdle ? { ifIdle: input.ifIdle } : {}),\n    };\n\n    const schedule: Schedule = {\n      id,\n      target,\n      cron: input.cron,\n      timezone: input.timezone,\n      status: input.status ?? 'active',\n      nextFireAt,\n      createdAt: now,\n      updatedAt: now,\n      ownerType: 'agent',\n      ownerId: input.agentId,\n      ...(input.metadata ? { metadata: input.metadata } : {}),\n    };\n\n    const created = await store.createSchedule(schedule);\n    return toAgentSchedule(created)!;\n  }\n\n  async #createWorkflowSchedule(input: CreateWorkflowScheduleInput): Promise<WorkflowSchedule> {\n    validateCron(input.cron, input.timezone);\n\n    const store = await this.#getStore();\n    // Imperative workflow schedules need the scheduler tick loop running,\n    // same as agent schedules created after startWorkers().\n    await this.#mastra.__ensureScheduleRuntimeReady();\n\n    const id =\n      input.id !== undefined\n        ? normalizeScheduleId(input.id, WORKFLOW_SCHEDULE_PREFIX)\n        : `${WORKFLOW_SCHEDULE_PREFIX}${randomUUID()}`;\n    await this.#assertIdAvailable(store, id, input.id !== undefined);\n    const now = Date.now();\n    const nextFireAt = computeNextFireAt(input.cron, { timezone: input.timezone, after: now });\n\n    const target: WorkflowTarget = {\n      type: 'workflow',\n      workflowId: input.workflowId,\n      ...(input.inputData !== undefined ? { inputData: input.inputData } : {}),\n      ...(input.initialState !== undefined ? { initialState: input.initialState } : {}),\n      ...(input.requestContext !== undefined ? { requestContext: input.requestContext } : {}),\n    };\n\n    const schedule: Schedule = {\n      id,\n      target,\n      cron: input.cron,\n      timezone: input.timezone,\n      status: input.status ?? 'active',\n      nextFireAt,\n      createdAt: now,\n      updatedAt: now,\n      ...(input.metadata ? { metadata: input.metadata } : {}),\n    };\n\n    const created = await store.createSchedule(schedule);\n    return toWorkflowSchedule(created)!;\n  }\n\n  async #assertIdAvailable(store: SchedulesStorage, id: string, callerProvided: boolean): Promise<void> {\n    if (!callerProvided) return;\n    const existing = await store.getSchedule(id);\n    if (existing) {\n      throw new MastraError({\n        id: 'SCHEDULES_ID_EXISTS',\n        domain: ErrorDomain.AGENT,\n        category: ErrorCategory.USER,\n        text: `schedules.create: a schedule with id \"${id}\" already exists. Use update() to modify it or choose a different id.`,\n      });\n    }\n  }\n\n  async get(id: string): Promise<AnySchedule | null> {\n    const schedule = await this.#load(id);\n    if (!schedule) return null;\n    return toScheduleView(schedule);\n  }\n\n  async list(filter?: ListSchedulesFilter): Promise<AnySchedule[]> {\n    const store = await this.#getStore();\n    const schedules = await store.listSchedules({\n      ...(filter?.agentId ? { ownerType: 'agent', ownerId: filter.agentId } : {}),\n      ...(filter?.workflowId ? { workflowId: filter.workflowId } : {}),\n      ...(filter?.status ? { status: filter.status } : {}),\n    });\n    const views = schedules\n      .map(toScheduleView)\n      .filter((s): s is AnySchedule => s !== null)\n      // `workflowId` filters at the store level, but an `agentId` filter must\n      // not surface workflow rows (and vice versa when both are set).\n      .filter(s => (filter?.agentId ? s.agentId !== undefined : true));\n    const agentOnly = filter?.threadId !== undefined || filter?.resourceId !== undefined || filter?.name !== undefined;\n    if (!agentOnly) return views;\n    return views.filter(s => {\n      if (s.agentId === undefined) return false;\n      if (filter?.threadId !== undefined && s.threadId !== filter.threadId) return false;\n      if (filter?.resourceId !== undefined && s.resourceId !== filter.resourceId) return false;\n      if (filter?.name !== undefined && s.name !== filter.name) return false;\n      return true;\n    });\n  }\n\n  async update(id: string, patch: UpdateScheduleInput): Promise<AnySchedule> {\n    const store = await this.#getStore();\n    const existing = await this.#load(id);\n    if (!existing) {\n      throw new MastraError({\n        id: 'SCHEDULES_NOT_FOUND',\n        domain: ErrorDomain.AGENT,\n        category: ErrorCategory.USER,\n        text: `Schedule \"${id}\" not found.`,\n      });\n    }\n\n    const nextCron = patch.cron ?? existing.cron;\n    const nextTimezone = patch.timezone !== undefined ? patch.timezone : existing.timezone;\n    if (patch.cron !== undefined || patch.timezone !== undefined) {\n      validateCron(nextCron, nextTimezone);\n    }\n\n    const nextTarget =\n      existing.target.type === 'agent'\n        ? this.#patchAgentTarget(existing.target, patch as UpdateAgentScheduleInput)\n        : this.#patchWorkflowTarget(existing.target, patch);\n\n    // Recompute the next fire when the cadence changes OR when this patch\n    // resumes a paused schedule. Resuming must follow the same semantics as\n    // resume(): a paused row carries a stale nextFireAt (often in the past),\n    // so flipping status back to 'active' without recomputing would trigger\n    // an immediate spurious fire instead of waiting for the next cron tick.\n    const resuming = patch.status === 'active' && existing.status === 'paused';\n    const nextFireAt =\n      patch.cron !== undefined || patch.timezone !== undefined || resuming\n        ? computeNextFireAt(nextCron, { timezone: nextTimezone, after: Date.now() })\n        : undefined;\n\n    const updated = await store.updateSchedule(existing.id, {\n      ...(patch.cron !== undefined ? { cron: patch.cron } : {}),\n      ...(patch.timezone !== undefined ? { timezone: patch.timezone } : {}),\n      target: nextTarget,\n      ...(nextFireAt !== undefined ? { nextFireAt } : {}),\n      ...(patch.metadata !== undefined ? { metadata: patch.metadata } : {}),\n      ...(patch.status !== undefined ? { status: patch.status } : {}),\n    });\n    return toScheduleView(updated)!;\n  }\n\n  #patchAgentTarget(existingTarget: AgentTarget, patch: UpdateAgentScheduleInput): AgentTarget {\n    // Threadless agent schedules run `agent.generate` in isolation, so\n    // thread-scoped signal options are meaningless and would be silently\n    // ignored on every fire. `create()` rejects them upfront; mirror that\n    // here so `update()` can't sneak the same invalid state onto a\n    // threadless schedule after the fact. `threadId`/`resourceId` are not\n    // patchable, so the thread-ness of a schedule is fixed at create time.\n    if (!existingTarget.threadId) {\n      const offenders: string[] = [];\n      if (patch.signalType !== undefined) offenders.push('signalType');\n      if (patch.ifActive !== undefined) offenders.push('ifActive');\n      if (patch.ifIdle !== undefined) offenders.push('ifIdle');\n      if (offenders.length > 0) {\n        throw new MastraError({\n          id: 'SCHEDULES_THREADLESS_OPTIONS',\n          domain: ErrorDomain.AGENT,\n          category: ErrorCategory.USER,\n          text: `schedules.update: ${offenders.join(', ')} require a threadId.`,\n        });\n      }\n    }\n\n    return {\n      ...existingTarget,\n      ...(patch.prompt !== undefined ? { prompt: patch.prompt } : {}),\n      ...(patch.name !== undefined ? { name: patch.name } : {}),\n      ...(patch.signalType !== undefined ? { signalType: patch.signalType } : {}),\n      ...(patch.tagName !== undefined ? { tagName: patch.tagName } : {}),\n      ...(patch.attributes !== undefined ? { attributes: patch.attributes } : {}),\n      ...(patch.providerOptions !== undefined ? { providerOptions: patch.providerOptions } : {}),\n      ...(patch.ifActive !== undefined ? { ifActive: patch.ifActive } : {}),\n      ...(patch.ifIdle !== undefined ? { ifIdle: patch.ifIdle } : {}),\n    };\n  }\n\n  #patchWorkflowTarget(existingTarget: WorkflowTarget, patch: UpdateScheduleInput): WorkflowTarget {\n    const agentOnly = [\n      'prompt',\n      'name',\n      'signalType',\n      'tagName',\n      'attributes',\n      'providerOptions',\n      'ifActive',\n      'ifIdle',\n    ];\n    const offenders = agentOnly.filter(key => (patch as Record<string, unknown>)[key] !== undefined);\n    if (offenders.length > 0) {\n      throw new MastraError({\n        id: 'SCHEDULES_INVALID_WORKFLOW_PATCH',\n        domain: ErrorDomain.AGENT,\n        category: ErrorCategory.USER,\n        text: `schedules.update: ${offenders.join(', ')} only apply to agent schedules.`,\n      });\n    }\n    const wfPatch = patch as UpdateWorkflowScheduleInput;\n    return {\n      ...existingTarget,\n      ...(wfPatch.inputData !== undefined ? { inputData: wfPatch.inputData } : {}),\n      ...(wfPatch.initialState !== undefined ? { initialState: wfPatch.initialState } : {}),\n      ...(wfPatch.requestContext !== undefined ? { requestContext: wfPatch.requestContext } : {}),\n    };\n  }\n\n  async delete(id: string): Promise<void> {\n    const store = await this.#getStore();\n    const existing = await this.#load(id);\n    if (!existing) return;\n    await store.deleteSchedule(existing.id);\n  }\n\n  async pause(id: string): Promise<AnySchedule> {\n    const store = await this.#getStore();\n    const existing = await this.#load(id);\n    if (!existing) {\n      throw new MastraError({\n        id: 'SCHEDULES_NOT_FOUND',\n        domain: ErrorDomain.AGENT,\n        category: ErrorCategory.USER,\n        text: `Schedule \"${id}\" not found.`,\n      });\n    }\n    if (existing.status === 'paused') return toScheduleView(existing)!;\n    const updated = await store.updateSchedule(existing.id, { status: 'paused' });\n    return toScheduleView(updated)!;\n  }\n\n  async resume(id: string): Promise<AnySchedule> {\n    const store = await this.#getStore();\n    const existing = await this.#load(id);\n    if (!existing) {\n      throw new MastraError({\n        id: 'SCHEDULES_NOT_FOUND',\n        domain: ErrorDomain.AGENT,\n        category: ErrorCategory.USER,\n        text: `Schedule \"${id}\" not found.`,\n      });\n    }\n    if (existing.status === 'active') return toScheduleView(existing)!;\n    const nextFireAt = computeNextFireAt(existing.cron, {\n      timezone: existing.timezone,\n      after: Date.now(),\n    });\n    const updated = await store.updateSchedule(existing.id, { status: 'active', nextFireAt });\n    return toScheduleView(updated)!;\n  }\n\n  async run(id: string): Promise<{ scheduleId: string; claimId: string; scheduledFireAt: number }> {\n    const existing = await this.#load(id);\n    if (!existing) {\n      throw new MastraError({\n        id: 'SCHEDULES_NOT_FOUND',\n        domain: ErrorDomain.AGENT,\n        category: ErrorCategory.USER,\n        text: `Schedule \"${id}\" not found.`,\n      });\n    }\n    const now = Date.now();\n    if (existing.target.type === 'agent') {\n      const claimId = `manual_${existing.id}_${now}`;\n      await this.#mastra.pubsub.publish('agent-schedules', {\n        type: 'agent-schedule.fire',\n        runId: claimId,\n        data: {\n          scheduleId: existing.id,\n          claimId,\n          scheduledFireAt: now,\n          target: existing.target,\n          triggerKind: 'manual',\n        },\n      });\n      return { scheduleId: existing.id, claimId, scheduledFireAt: now };\n    }\n\n    // Workflow target: mirror the scheduler's fire path. The workflow event\n    // processor consumes `workflow.start` and reuses the claim id as the run\n    // id, so record the trigger row here (the scheduler is not involved in\n    // manual fires).\n    const { workflowId, inputData, initialState, requestContext } = existing.target;\n    const claimId = `sched_${existing.id}_${now}`;\n    await this.#mastra.pubsub.publish(TOPIC_WORKFLOWS, {\n      type: 'workflow.start',\n      runId: claimId,\n      data: {\n        workflowId,\n        runId: claimId,\n        prevResult: { status: 'success', output: inputData ?? {} },\n        requestContext: requestContext ?? {},\n        initialState: initialState ?? {},\n      },\n    });\n    const store = await this.#getStore();\n    try {\n      await store.recordTrigger({\n        scheduleId: existing.id,\n        runId: claimId,\n        scheduledFireAt: now,\n        actualFireAt: now,\n        outcome: 'published',\n        triggerKind: 'manual',\n      });\n    } catch {\n      // Trigger rows are best-effort audit records; the run already fired.\n    }\n    return { scheduleId: existing.id, claimId, scheduledFireAt: now };\n  }\n}\n\n/**\n * Project a `Schedule` row to a flat {@link AgentSchedule} view. Returns\n * `null` when the schedule is not an agent schedule\n * (`target.type !== 'agent'`), allowing callers to filter mixed result sets\n * in one pass.\n */\nexport function toAgentSchedule(schedule: Schedule): AgentSchedule | null {\n  if (schedule.target?.type !== 'agent') return null;\n  const target = schedule.target as AgentTarget;\n  return {\n    id: schedule.id,\n    agentId: target.agentId,\n    ...(target.name !== undefined ? { name: target.name } : {}),\n    ...(target.threadId ? { threadId: target.threadId } : {}),\n    ...(target.resourceId ? { resourceId: target.resourceId } : {}),\n    prompt: target.prompt,\n    cron: schedule.cron,\n    ...(schedule.timezone ? { timezone: schedule.timezone } : {}),\n    status: schedule.status,\n    nextFireAt: schedule.nextFireAt,\n    ...(schedule.lastFireAt !== undefined ? { lastFireAt: schedule.lastFireAt } : {}),\n    ...(schedule.lastRunId ? { lastRunId: schedule.lastRunId } : {}),\n    ...(target.signalType ? { signalType: target.signalType } : {}),\n    ...(target.tagName ? { tagName: target.tagName } : {}),\n    ...(target.attributes ? { attributes: target.attributes } : {}),\n    ...(target.providerOptions ? { providerOptions: target.providerOptions } : {}),\n    ...(target.ifActive ? { ifActive: target.ifActive } : {}),\n    ...(target.ifIdle ? { ifIdle: target.ifIdle } : {}),\n    ...(schedule.metadata ? { metadata: schedule.metadata } : {}),\n    createdAt: schedule.createdAt,\n    updatedAt: schedule.updatedAt,\n  };\n}\n\n/**\n * Project a `Schedule` row to a flat {@link WorkflowSchedule} view. Returns\n * `null` when the schedule is not a workflow schedule.\n */\nexport function toWorkflowSchedule(schedule: Schedule): WorkflowSchedule | null {\n  if (schedule.target?.type !== 'workflow') return null;\n  const target = schedule.target as WorkflowTarget;\n  return {\n    id: schedule.id,\n    workflowId: target.workflowId,\n    cron: schedule.cron,\n    ...(schedule.timezone ? { timezone: schedule.timezone } : {}),\n    status: schedule.status,\n    nextFireAt: schedule.nextFireAt,\n    ...(schedule.lastFireAt !== undefined ? { lastFireAt: schedule.lastFireAt } : {}),\n    ...(schedule.lastRunId ? { lastRunId: schedule.lastRunId } : {}),\n    ...(target.inputData !== undefined ? { inputData: target.inputData } : {}),\n    ...(target.initialState !== undefined ? { initialState: target.initialState } : {}),\n    ...(target.requestContext !== undefined ? { requestContext: target.requestContext } : {}),\n    ...(schedule.metadata ? { metadata: schedule.metadata } : {}),\n    createdAt: schedule.createdAt,\n    updatedAt: schedule.updatedAt,\n  };\n}\n\n/** Project a `Schedule` row to whichever flat view matches its target type. */\nexport function toScheduleView(schedule: Schedule): AnySchedule | null {\n  return toAgentSchedule(schedule) ?? toWorkflowSchedule(schedule);\n}\n"],"mappings":";;;;;;;;;AA0CA,MAAa,wBAAwB;;;;;;;;AASrC,MAAa,2BAA2B;;AAoBxC,MAAM,2BAA2BA,OAAAA,EAAE,OAAOA,OAAAA,EAAE,OAAO,GAAGA,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