@mastra/core
Version:
1 lines • 87.7 kB
Source Map (JSON)
{"version":3,"file":"schedules-CyoPADNx.cjs","names":["z","Cron","MastraError","ErrorDomain","ErrorCategory","slugify","MastraError","ErrorDomain","ErrorCategory"],"sources":["../src/schedules/types.ts","../src/workflows/scheduler/cron.ts","../src/schedules/define.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 * Reject the wake unless an advertised thread owner acknowledges it, so the\n * process that claimed the thread runs the turn with its claim options. When\n * no owner answers, the fire fails. Same as `AgentSignalIfIdleOptions.requireClaimedOwner`.\n */\n requireClaimedOwner?: boolean;\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/**\n * Signal categories a schedule fire may use. Single runtime source for the zod\n * enum below and for schedule-definition validation, so the two can't drift.\n */\nexport const SCHEDULE_SIGNAL_TYPES = [\n 'user',\n 'state',\n 'reactive',\n 'notification',\n 'user-message',\n 'system-reminder',\n] as const satisfies readonly AgentSignalType[];\n\n/** Lifecycle statuses a schedule row may be created with. */\nexport const SCHEDULE_STATUSES = ['active', 'paused'] as const;\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 requireClaimedOwner: z.boolean().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(SCHEDULE_SIGNAL_TYPES).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 /** `'once'` for a scheduled fire of a one-off (`runAt`) schedule. */\n kind: 'cron' | 'once' | '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/**\n * Argument passed to `schedules.onFinish` for any non-error, non-abort outcome.\n * For a threaded schedule, `succeeded` means the run was started, not that it completed.\n */\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/**\n * Argument passed to `schedules.onError` whenever `prepare` or `sendSignal` threw\n * (including the signal failing to route), or a threadless agent run threw a\n * non-abort error.\n */\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 a threadless run was aborted. */\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 outcome. `onError` fires when `prepare` or\n * `sendSignal` threw, or a threadless agent run threw a non-abort error.\n * `onAbort` fires when a threadless run was aborted. A threaded schedule hands the prompt\n * to the thread without waiting for the run, so failures or aborts after the\n * run starts surface on the thread's run stream, not through these hooks.\n * `prepare` can return overrides, `null` to skip, or `undefined` to use row\n * 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 { Cron } from 'croner';\n\n/**\n * Validate a cron expression. Throws if the pattern is invalid.\n *\n * @param cron - Cron expression (5-, 6-, or 7-part).\n * @param timezone - Optional IANA timezone (e.g. 'America/New_York').\n */\nexport function validateCron(cron: string, timezone?: string): void {\n if (typeof cron !== 'string' || cron.trim() === '') {\n throw new Error(\n `Invalid cron expression: expected a non-empty cron string (e.g. \"0 * * * *\"), but received ${cron === undefined ? 'undefined' : JSON.stringify(cron)}.`,\n );\n }\n // Croner throws synchronously on an invalid pattern when the job is\n // constructed. Validate the pattern on its own first so timezone problems\n // (which croner only surfaces lazily) are not mislabeled as cron errors.\n let job: Cron;\n try {\n job = new Cron(cron);\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new Error(`Invalid cron expression \"${cron}\": ${reason}`);\n }\n // The timezone is only exercised when a fire time is computed.\n if (timezone !== undefined) {\n try {\n new Cron(cron, { timezone }).nextRun();\n } catch (error) {\n const reason = error instanceof Error ? error.message : String(error);\n throw new Error(`Invalid timezone \"${timezone}\": ${reason}`);\n }\n } else {\n job.nextRun();\n }\n}\n\n/**\n * Compute the next fire time (ms since epoch) for a cron expression.\n *\n * @param cron - Cron expression.\n * @param options - Optional timezone and reference time (`after`, ms since epoch).\n * The next fire time is the first cron occurrence strictly after `after`.\n * Defaults to `Date.now()`.\n * @returns The next fire time in ms since epoch.\n * @throws If the cron expression is invalid or has no future occurrence.\n */\nexport function computeNextFireAt(cron: string, options?: { timezone?: string; after?: number }): number {\n const reference = options?.after !== undefined ? new Date(options.after) : new Date();\n const nextFireAt = findNextFireAt(cron, options?.timezone, reference);\n if (nextFireAt === null) {\n throw new Error(`Cron expression \"${cron}\" has no future occurrence after ${reference.toISOString()}`);\n }\n return nextFireAt;\n}\n\n/**\n * Resolve what a schedule claim should write after firing at `after`.\n *\n * - One-off (`runAt` set): keep `nextFireAt` and mark the row `completed`.\n * - Cron with no future occurrence: keep `nextFireAt` and mark the row `completed`.\n * - Bounded cron (`endAt` set): advance to the next cron occurrence, or mark\n * `completed` when that occurrence is after `endAt`.\n * - Unbounded cron: advance to the next cron occurrence.\n */\nexport function computeNextFire(\n schedule: { cron: string; timezone?: string; runAt?: number; endAt?: number; nextFireAt: number },\n after: number,\n): { nextFireAt: number; completed: boolean } {\n if (schedule.runAt != null) {\n return { nextFireAt: schedule.nextFireAt, completed: true };\n }\n const nextFireAt = findNextFireAt(schedule.cron, schedule.timezone, new Date(after));\n if (nextFireAt === null) {\n return { nextFireAt: schedule.nextFireAt, completed: true };\n }\n return { nextFireAt, completed: schedule.endAt != null && nextFireAt > schedule.endAt };\n}\n\nfunction findNextFireAt(cron: string, timezone: string | undefined, reference: Date): number | null {\n return new Cron(cron, { timezone }).nextRun(reference)?.getTime() ?? null;\n}\n\n/**\n * Validate the timing fields of a schedule: exactly one of `cron` or a future\n * `runAt`, `endAt` only alongside `cron` and in the future. Throws on invalid input.\n * Pass `requireFuture: false` for declarative config, which must survive redeploys\n * after its times have passed.\n */\nexport function validateScheduleTiming(\n input: {\n cron?: string;\n timezone?: string;\n runAt?: number | Date;\n endAt?: number | Date;\n },\n options: { requireFuture?: boolean } = {},\n): void {\n const hasCron = input.cron !== undefined && input.cron !== '';\n const hasRunAt = input.runAt !== undefined;\n if (hasCron === hasRunAt) {\n throw new Error('Schedule must specify exactly one of `cron` or `runAt`.');\n }\n if (hasRunAt) {\n const runAt = toEpochMs(input.runAt!);\n if (!Number.isFinite(runAt)) {\n throw new Error('Schedule `runAt` must be a valid date or ms epoch timestamp.');\n }\n if (options.requireFuture !== false && runAt <= Date.now()) {\n throw new Error('Schedule `runAt` must be in the future.');\n }\n if (input.endAt !== undefined) {\n throw new Error('Schedule `endAt` is only allowed together with `cron`.');\n }\n return;\n }\n validateCron(input.cron!, input.timezone);\n if (input.endAt !== undefined) {\n const endAt = toEpochMs(input.endAt);\n if (!Number.isFinite(endAt)) {\n throw new Error('Schedule `endAt` must be a valid date or ms epoch timestamp.');\n }\n if (options.requireFuture !== false && endAt <= Date.now()) {\n throw new Error('Schedule `endAt` must be in the future.');\n }\n }\n}\n\n/**\n * Compute the initial row timing for a new schedule. One-offs fire at\n * `runAt`; a bounded cron whose first occurrence is already past `endAt`\n * starts `completed`.\n */\nexport function computeInitialFire(input: { cron?: string; timezone?: string; runAt?: number; endAt?: number }): {\n nextFireAt: number;\n completed: boolean;\n} {\n if (input.runAt !== undefined) {\n return { nextFireAt: input.runAt, completed: false };\n }\n const nextFireAt = computeNextFireAt(input.cron!, { timezone: input.timezone });\n return { nextFireAt, completed: input.endAt !== undefined && nextFireAt > input.endAt };\n}\n\nexport function toEpochMs(value: number | Date): number {\n return value instanceof Date ? value.getTime() : value;\n}\n","import type { AgentSignalAttributes, AgentSignalType } from '../agent/signals';\nimport { ErrorCategory, ErrorDomain, MastraError } from '../error';\nimport { validateCron } from '../workflows/scheduler/cron';\nimport { SCHEDULE_SIGNAL_TYPES, SCHEDULE_STATUSES } from './types';\nimport type { ScheduleEffective, ScheduleIfActive, ScheduleIfIdle, ScheduleTriggerInfo } from './types';\n\n/**\n * Stable schedule id prefix for schedules declared by a file-based agent's\n * `schedules/` directory.\n *\n * Deliberately distinct from every other prefix in the system:\n * - `agent_` — imperative rows from `mastra.schedules.create({ agentId })`\n * - `schedule_` — imperative rows from `mastra.schedules.create({ workflowId })`\n * - `wf_` — declarative rows from `createWorkflow({ schedule })`\n *\n * The boot-time sync sweeps orphaned `fsa_` rows against the schedules declared\n * on disk, so sharing a prefix with any of the above would make a redeploy\n * delete schedules this feature does not own.\n */\nexport const FS_AGENT_SCHEDULE_PREFIX = 'fsa_';\n\n/** Context passed to a handler-mode schedule on every fire. */\nexport type AgentScheduleHandlerContext<TMastra = unknown> = {\n mastra: TMastra;\n /** The agent that owns this schedule. */\n agentId: string;\n /** Storage row id of the firing schedule (`fsa_<agent>__<path>`). */\n scheduleId: string;\n /** Path-derived identity of the schedule within the agent (e.g. `billing/sweep`). */\n key: string;\n trigger: ScheduleTriggerInfo;\n};\n\n/**\n * Return value from a handler-mode schedule.\n *\n * - object → fire the agent with these fields merged over the row defaults\n * - `null` → skip this fire entirely (recorded with outcome `skipped`)\n * - `undefined` → fire with the row defaults verbatim\n *\n * Channel delivery goes through `ifIdle.streamOptions.requestContext`, which the\n * worker rehydrates into a `RequestContext` before the woken run starts.\n */\nexport type AgentScheduleHandlerResult = Partial<ScheduleEffective>;\n\nexport type AgentScheduleHandler<TMastra = unknown> = (\n ctx: AgentScheduleHandlerContext<TMastra>,\n) =>\n | Promise<AgentScheduleHandlerResult | null | undefined | void>\n | AgentScheduleHandlerResult\n | null\n | undefined\n | void;\n\n/** Fields shared by both execution modes. */\ntype AgentScheduleCommon = {\n /** Cron expression with 5, 6, or 7 parts (e.g. `0 * * * *` for hourly). */\n cron: string;\n /** IANA timezone the cron is evaluated in. Defaults to the host timezone. */\n timezone?: string;\n /** Free-form label shown in Studio and filterable via `mastra.schedules.list({ name })`. */\n name?: string;\n /** Threaded schedules send a signal into this thread instead of starting a fresh run. */\n threadId?: string;\n /** Required when `threadId` is set. */\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'`. */\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 /** Options applied when the target thread is actively streaming. Threaded only. */\n ifActive?: ScheduleIfActive;\n /** Options applied when the target thread is idle. Threaded only. */\n ifIdle?: ScheduleIfIdle;\n /** Arbitrary metadata persisted alongside the schedule row. */\n metadata?: Record<string, unknown>;\n /** Lifecycle status the row is created with. Defaults to `'active'`. */\n status?: 'active' | 'paused';\n};\n\n/** Prompt mode: fire the owning agent with a fixed prompt. */\nexport type AgentSchedulePromptDefinition = AgentScheduleCommon & {\n prompt: string;\n handler?: never;\n};\n\n/**\n * Handler mode: compute the fire's parameters at trigger time, skip\n * conditionally by returning `null`, and route delivery through a channel by\n * returning request context.\n */\nexport type AgentScheduleHandlerDefinition<TMastra = unknown> = AgentScheduleCommon & {\n handler: AgentScheduleHandler<TMastra>;\n prompt?: never;\n};\n\n/**\n * A single schedule declared under `agents/<id>/schedules/`. Exactly one\n * execution mode — `prompt` or `handler` — must be set.\n */\nexport type AgentScheduleDefinition<TMastra = unknown> =\n | AgentSchedulePromptDefinition\n | AgentScheduleHandlerDefinition<TMastra>;\n\n/**\n * A schedule definition paired with its path-derived identity, as attached to\n * an assembled file-based agent. `key` comes from the file's path relative to\n * `schedules/` with the extension stripped (`billing/sweep.ts` → `billing/sweep`).\n */\nexport type DeclaredAgentSchedule<TMastra = unknown> = {\n key: string;\n definition: AgentScheduleDefinition<TMastra>;\n};\n\n/**\n * Identity helper for a schedule declared under `agents/<id>/schedules/`.\n * Returns the definition unchanged after validating it, so authoring mistakes\n * surface at import time rather than on the first cron fire.\n *\n * @example\n * ```ts\n * // src/mastra/agents/support/schedules/heartbeat.ts\n * import { defineSchedule } from '@mastra/core/schedules';\n *\n * export default defineSchedule({\n * cron: '0 9 * * *',\n * prompt: 'Check system health and report any failures.',\n * });\n * ```\n */\nexport function defineSchedule<TMastra = unknown>(\n definition: AgentScheduleDefinition<TMastra>,\n): AgentScheduleDefinition<TMastra> {\n assertValidScheduleDefinition(definition);\n return definition;\n}\n\n/**\n * Validate a schedule definition, throwing a `MastraError` naming the offending\n * schedule. Shared by `defineSchedule` (author-time) and file-based agent\n * assembly (build-time, where markdown schedules never went through\n * `defineSchedule`).\n *\n * `label` describes the schedule in error text — `defineSchedule` has no\n * identity to report, so assembly passes `agents/<id>/schedules/<key>`.\n */\nexport function assertValidScheduleDefinition(definition: AgentScheduleDefinition<any>, label?: string): void {\n const where = label ? ` (${label})` : '';\n\n if (!definition || typeof definition !== 'object') {\n throw new MastraError({\n id: 'SCHEDULES_INVALID_DEFINITION',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n details: { label: label ?? '' },\n text: `Schedule${where}: expected a schedule definition object, received ${definition === null ? 'null' : typeof definition}.`,\n });\n }\n\n const hasPrompt = typeof definition.prompt === 'string' && definition.prompt.trim() !== '';\n const hasHandler = typeof definition.handler === 'function';\n\n if (hasPrompt && hasHandler) {\n throw new MastraError({\n id: 'SCHEDULES_AMBIGUOUS_MODE',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n details: { label: label ?? '' },\n text: `Schedule${where}: set exactly one execution mode — remove either 'prompt' or 'handler'.`,\n });\n }\n\n if (!hasPrompt && !hasHandler) {\n throw new MastraError({\n id: 'SCHEDULES_MISSING_MODE',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n details: { label: label ?? '' },\n text: `Schedule${where}: set exactly one execution mode — provide a non-empty 'prompt' or a 'handler' function.`,\n });\n }\n\n try {\n validateCron(definition.cron, definition.timezone);\n } catch (error) {\n throw new MastraError(\n {\n id: 'SCHEDULES_INVALID_CRON',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n details: { label: label ?? '', cron: String(definition.cron) },\n text: `Schedule${where}: ${error instanceof Error ? error.message : String(error)}`,\n },\n error,\n );\n }\n\n // Markdown schedules never pass through TypeScript, so these enum-ish fields\n // are only checked here. An unchecked value would reach schedule storage and\n // surface as a confusing runtime failure on the first fire.\n if (definition.signalType !== undefined && !SCHEDULE_SIGNAL_TYPES.includes(definition.signalType)) {\n throw new MastraError({\n id: 'SCHEDULES_INVALID_SIGNAL_TYPE',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n details: { label: label ?? '', signalType: String(definition.signalType) },\n text: `Schedule${where}: unknown signalType \"${definition.signalType}\". Expected one of: ${SCHEDULE_SIGNAL_TYPES.join(', ')}.`,\n });\n }\n\n if (definition.status !== undefined && !SCHEDULE_STATUSES.includes(definition.status)) {\n throw new MastraError({\n id: 'SCHEDULES_INVALID_STATUS',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n details: { label: label ?? '', status: String(definition.status) },\n text: `Schedule${where}: unknown status \"${definition.status}\". Expected one of: ${SCHEDULE_STATUSES.join(', ')}.`,\n });\n }\n\n if (definition.threadId && !definition.resourceId) {\n throw new MastraError({\n id: 'SCHEDULES_MISSING_RESOURCE_ID',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n details: { label: label ?? '' },\n text: `Schedule${where}: 'resourceId' is required when 'threadId' is set.`,\n });\n }\n}\n\n/**\n * Encode one component of a row id so it cannot contain the `__` delimiter.\n *\n * `encodeURIComponent` leaves `_` untouched, so escaping it explicitly is what\n * actually makes the delimiter unambiguous — otherwise an agent named `a__b`\n * and one named `a` with a key starting `_b` would produce the same row id.\n * `decodeURIComponent` reverses `%5F` for free.\n */\nfunction encodeRowIdPart(value: string): string {\n return encodeURIComponent(value).replace(/_/g, '%5F');\n}\n\n/**\n * Build the storage row id for a schedule declared on a file-based agent.\n * Both components are encoded so an agent id or nested path containing the\n * `__` delimiter can never forge another schedule's row id.\n */\nexport function fsAgentScheduleRowId(agentId: string, key: string): string {\n return `${FS_AGENT_SCHEDULE_PREFIX}${encodeRowIdPart(agentId)}__${encodeRowIdPart(key)}`;\n}\n\n/**\n * Decode an `fsa_<agent>__<key>` row id back into its parts. Returns\n * `undefined` when the id isn't one of ours, so callers sweeping or resolving\n * schedule rows leave other schedule sources alone.\n */\nexport function parseFsAgentScheduleRowId(rowId: string): { agentId: string; key: string } | undefined {\n if (!rowId.startsWith(FS_AGENT_SCHEDULE_PREFIX)) return undefined;\n const rest = rowId.slice(FS_AGENT_SCHEDULE_PREFIX.length);\n const separator = rest.indexOf('__');\n if (separator <= 0) return undefined;\n try {\n return {\n agentId: decodeURIComponent(rest.slice(0, separator)),\n key: decodeURIComponent(rest.slice(separator + 2)),\n };\n } catch {\n return undefined;\n }\n}\n","import type { AgentSignalAttributes, AgentSignalType } from '../agent/signals';\nimport { ErrorCategory, ErrorDomain, MastraError } from '../error';\nimport type { Mastra } from '../mastra';\nimport type { Schedule, ScheduleStatus, SchedulesStorage } from '../storage/domains/schedules/base';\nimport { slugify } from '../utils/slugify';\nimport {\n computeInitialFire,\n computeNextFire,\n toEpochMs,\n validateCron,\n validateScheduleTiming,\n} from '../workflows/scheduler/cron';\nimport type { ScheduledWorkflowTrigger } from '../workflows/scheduler/types';\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\nfunction invalidTiming(err: unknown, op: 'create' | 'update'): MastraError {\n return new MastraError({\n id: 'SCHEDULES_INVALID_TIMING',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n details: { status: 400 },\n text: `schedules.${op}: ${err instanceof Error ? err.message : String(err)}`,\n });\n}\n\nfunction scheduleCompleted(id: string, op: string): MastraError {\n return new MastraError({\n id: 'SCHEDULES_COMPLETED',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n details: { status: 409 },\n text: `schedules.${op}: schedule \"${id}\" is completed and can no longer be ${op === 'pause' ? 'paused' : 'resumed'}.`,\n });\n}\n\n/**\n * Validate the cron/runAt/endAt fields of a create input and compute the\n * row fields plus the initial fire time. One-offs store `cron` as `''`.\n */\nfunction resolveCreateTiming(input: {\n cron?: string;\n timezone?: string;\n runAt?: number | Date;\n endAt?: number | Date;\n}): {\n fields: Pick<Schedule, 'cron' | 'runAt' | 'endAt'>;\n nextFireAt: number;\n completed: boolean;\n} {\n const runAt = input.runAt !== undefined ? toEpochMs(input.runAt) : undefined;\n const endAt = input.endAt !== undefined ? toEpochMs(input.endAt) : undefined;\n let nextFireAt: number;\n let completed: boolean;\n try {\n validateScheduleTiming(input);\n // A cadence whose final occurrence has already passed is rejected rather\n // than persisted: the row could never run, so nothing is gained by storing\n // it. Editing an existing schedule is different — those rows go terminal.\n ({ nextFireAt, completed } = computeInitialFire({\n cron: input.cron,\n timezone: input.timezone,\n runAt,\n endAt,\n }));\n } catch (err) {\n throw invalidTiming(err, 'create');\n }\n return {\n fields: {\n cron: input.cron ?? '',\n ...(runAt !== undefined ? { runAt } : {}),\n ...(endAt !== undefined ? { endAt } : {}),\n },\n nextFireAt,\n completed,\n };\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 details: { status: 400 },\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 expression. Absent on one-off schedules (see `runAt`). */\n cron?: string;\n timezone?: string;\n /** One-off fire time (ms epoch). */\n runAt?: number;\n /** Bounded cron end (ms epoch). */\n endAt?: number;\n status: ScheduleStatus;\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 expression. Absent on one-off schedules (see `runAt`). */\n cron?: string;\n timezone?: string;\n /** One-off fire time (ms epoch). */\n runAt?: number;\n /** Bounded cron end (ms epoch). */\n endAt?: number;\n status: ScheduleStatus;\n nextFireAt: number;\n lastFireAt?: number;\n lastRunId?: string;\n inputData?: unknown;\n initialState?: unknown;\n requestContext?: Record<string, unknown>;\n /** Resource that runs fired by this schedule are attributed to. */\n resourceId?: string;\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 expression. Exactly one of `cron` or `runAt` is required. */\n cron?: string;\n /** Fire once at this time (Date or ms epoch), then mark the schedule `completed`. */\n runAt?: number | Date;\n /** Stop a cron schedule after this time (Date or ms epoch) and mark it `completed`. */\n endAt?: number | Date;\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 expression. Exactly one of `cron` or `runAt` is required. */\n cron?: string;\n /** Fire once at this time (Date or ms epoch), then mark the schedule `completed`. */\n runAt?: number | Date;\n /** Stop a cron schedule after this time (Date or ms epoch) and mark it `completed`. */\n endAt?: number | Date;\n timezone?: string;\n inputData?: unknown;\n initialState?: unknown;\n requestContext?: Record<string, unknown>;\n /** Resource that runs fired by this schedule are attributed to. */\n resourceId?: string;\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 /** Reschedule a one-off schedule. Only valid on schedules created with `runAt`. */\n runAt?: number | Date;\n /** Change the end of a cron schedule, or `null` to remove it. Only valid on cron schedules. */\n endAt?: number | Date | null;\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 /** Reschedule a one-off schedule. Only valid on schedules created with `runAt`. */\n runAt?: number | Date;\n /** Change the end of a cron schedule, or `null` to remove it. Only valid on cron schedules. */\n endAt?: number | Date | null;\n timezone?: string;\n inputData?: unknown;\n initialState?: unknown;\n requestContext?: Record<string, unknown>;\n /** Resource that runs fired by this schedule are attributed to. */\n resourceId?: string;\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 /** Match the schedule's resourceId (agent thread identity or workflow run attribution). */\n resourceId?: string;\n /** Agent-schedule only: match the free-form target name. */\n name?: string;\n /**\n * Return only schedules with this status. Completed schedules are omitted\n * from the result unless this is set.\n */\n status?: ScheduleStatus;\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 const timing = resolveCreateTiming(input);\n\n if (!input.agentId) {\n throw new MastraError({\n id: 'SCHEDULES_MISSING_TARGET_ID',\n domain: ErrorDomain.AGENT,\n category: ErrorCategory.USER,\n details: { status: 400 },\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 details: { status: 400 },\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 details: { status: 400 },\n text: `schedules.create: ${offenders.join(', ')} require a threadId.`,\n });\n }\n }\n\n const store = await this.#getStore();\n\n const id =\n input.id !== undefined\n ? normalizeScheduleId(input.id, AGENT_SCHEDULE_PREFIX)\n : `${AGENT_SCHEDULE_PREFIX}${globalThis.crypto.randomUUID()}`;\n await this.#assertIdAvailable(store, id, input.id !== undefined);\n const now = Date.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 ...timing.fields,\n timezone: input.timezone,\n status: timing.completed ? 'completed' : (input.status ?? 'active'),\n nextFireAt: timing.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 // The row is durable now: wake schedulers in other processes, then make\n // sure this process's scheduler + agent-schedule worker are running.\n await this.#mastra.__publishSchedulerWake(created.id);\n await this.#mastra.__ensureScheduleRuntimeReady();\n return toAgentSchedule(created)!;\n }\n\n async #createWorkflowSchedule(input: CreateWorkflowScheduleInput): Promise<WorkflowSchedule> {\n const timing = resolveCreateTiming(input);\n\n const store = await this.#getStore();\n\n const id =\n input.id !== undefined\n ? normalizeScheduleId(input.id, WORKFLOW_SCHEDULE_PREFIX)\n : `${WORKFLOW_SCHEDULE_PREFIX}${globalThis.crypto.randomUUID()}`;\n await this.#assertIdAvailable(store, id, input.id !== undefined);\n const now = Date.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 ...(input.resourceId !== undefined ? { resourceId: input.resourceId } : {}),\n };\n\n const schedule: Schedule = {\n id,\n target,\n ...timing.fields,\n timezone: input.timezone,\n status: timing.completed ? 'completed' : (input.status ?? 'active'),\n nextFireAt: timing.nextFireAt,\n createdAt: now,\n updatedAt: now,\n ...(input.metadata ? { metadata: input.metadata } : {}),\n };\n\n const created = await store.createSchedule(schedule);\n await this.#mastra.__publishSchedulerWake(created.id);\n await this.#mastra.__ensureScheduleRuntimeReady();\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 details: { status: 409 },\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 storeFilter = {\n ...(filter?.agentId ? { ownerType: 'agent' as const, ownerId: filter.agentId } : {}),\n ...(filter?.workflowId ? { workflowId: filter.workflowId } : {}),\n };\n const schedules = filter?.status\n ? await store.listSchedules({ ...storeFilter, status: filter.status })\n : (\n await Promise.all([\n store.listSchedules({ ...storeFilter, status: 'active' }),\n store.listSchedules({ ...storeFilter, status: 'paused' }),\n ])\n )\n .flat()\n .sort((a, b) => a.createdAt - b.createdAt);\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?.name !== undefined;\n if (!agentOnly && filter?.resourceId === undefined) return views;\n return views.filter(s => {\n // `resourceId` exists on both kinds (agent thread identity / workflow run\n // attribution), so it filters across both; threadId/name are agent-only.\n if (filter?.resourceId !== undefined && s.resourceId !== filter.resourceId) return false;\n if (!agentOnly) return true;\n if (s.agentId === undefined) return false;\n if (filter?.threadId !== undefined && s.threadId !== filter.threadId) 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 details: { status: 404 },\n text: `Schedule \"${id}\" not found.`,\n });\n }\n\n const isOneOff = existing.runAt != null;\n if (isOneOff && (patch.cron !== undefined || patch.endAt !== undefined)) {\n throw invalidTiming(new Error('`cron` and `endAt` cannot be set on a one-off (`runAt`) schedule.'), 'update');\n }\n if (!isOneOff && patch.runAt !== undefined) {\n throw invalidTiming(new Error('`runAt` can only be set on a one-off schedule.'), 'update');\n }\n\n const nextCron = patch.cron ?? existing.cron;\n const nextTimezone = patch.timezone !== undefined ? patch.timezone : existing.timezone;\n if (!isOneOff && (patch.cron !== undefined || patch.timezone !== undefined)) {\n try {\n validateCron(nextCron, nextTimezone);\n } catch (err) {\n throw invalidTiming(err, 'update');\n }\n }\n const nextRunAt = patch.runAt !== undefined ? toEpochMs(patch.runAt) : existing.runAt;\n if (patch.runAt !== undefined && !Number.isFinite(nextRunAt)) {\n throw invalidTiming(new Error('`runAt` must be a valid date or ms epoch timestamp.'), 'update');\n }\n const nextEndAt =\n patch.endAt === undefined ? existing.endAt : patch.endAt === null ? undefined : toEpochMs(patch.endAt);\n if (patch.endAt != null && (!Number.isFinite(nextEndAt) || nextEndAt! <= Date.now())) {\n throw invalidTiming(new Error('`endAt` must be a valid timestamp in the future.'), 'update');\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 timing 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 // A completed schedule can only be reactivated by changing its timing: a\n // completed row whose cadence is edited comes back as `active` when the new\n // cadence has future occurrences, and stays `completed` when it has none.\n // Lifecycle-only patches cannot resume a completed row.\n const timingChanged = isOneOff\n ? patch.runAt !== undefined && nextRunAt !== existing.runAt\n : patch.cron !== undefined || patch.timezone !== undefined || patch.endAt !== undefined;\n if (existing.status === 'completed' && patch.status !== undefined && !timingChanged) {\n throw scheduleCompleted(existing.id, patch.status === 'paused' ? 'pause' : 'resume');\n }\n let nextStatus: ScheduleStatus =\n existing.status === 'completed'\n ? timingChanged\n ? (patch.status ?? 'active')\n : 'completed'\n : (patch.status ?? existing.status);\n const resuming = nextStatus === 'active' && existing.status !== 'active';\n let nextFireAt: number | undefined;\n if (timingChanged || resuming) {\n if (isOneOff) {\n nextFireAt = nextRunAt!;\n } else {\n const next = computeNextFire(\n { cron: nextCron, timezone: nextTimezone, endAt: nextEndAt, nextFireAt: existing.nextFireAt },\n Date.now(),\n );\n nextFireAt = next.nextFireAt;\n // An edit that leaves the row with no future occurrence is accepted, but\n // the row cannot stay runnable: the cadence is exhausted, so the row is\n // terminal regardless of its previous or requested status. `nextFireAt`\n // is retained as the last known occurrence.\n if (next.completed) nextStatus = 'completed';\n }\n }\n\n const updated = await store.updateSchedule(existing.id, {\n ...(patch.cron !== undefined ? { cron: patch.cron } : {}),\n ...(patch.timezone !== undefined ? { timezone: patch.timezone } : {}),\n ...(patch.runAt !== undefined ? { runAt: nextRunAt } : {}),\n ...(patch.endAt !== undefined ? { endAt: nextEndAt } : {}),\n target: nextTarget,\n ...(nextFireAt !== undefined ? { nextFireAt } : {}),\n ...(patch.metadata !== undefined ? { metadata: patch.metadata } : {}),\n ...(nextStatus !== existing.status ? { status: nextStatus } : {}),\n });\n // Schedulers sleep until their earliest fire; a new fire time may be sooner.\n if (nextFireAt !== undefined && updated.status === 'active') {\n await this.#mastra.__publishSchedulerWake(updated.id);\n await this.#mastra.__ensureScheduleRuntimeReady();\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 details: { status: 400 },\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 details: { status: 400 },\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 ...(wfPatch.resourceId !== undefined ? { resourceId: wfPatch.resourceId } : {}),\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 details: { status: 404 },\n text: `Schedule \"${id}\" not found.`,\n });\n }\n if (existing.status === 'paused') return toScheduleView(existing)!;\n if (existing.status === 'completed') throw scheduleCompleted(existing.id, 'pause');\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 details: { status: 404 },\n text: `Schedule \"${id}\" not found.`,\n });\n }\n if (existing.status === 'active') return toScheduleView(existing)!;\n if (existing.status === 'completed') throw scheduleCompleted(existing.id, 'resume');\n // One-offs keep their runAt (a past runAt fires on the next tick).\n if (existing.runAt != null) {\n const updated = await store.updateSchedule(existing.id, { status: 'active', nextFireAt: existing.runAt });\n await this.#mastra.__publishSchedulerWake(updated.id);\n await this.#mastra.__ensureScheduleRuntimeReady();\n return toScheduleView(updated)!;\n }\n // A paused schedule whose cadence has run out has nothing left to resume.\n // Complete it instead of failing with a server error.\n const { nextFireAt, completed: exhausted } = computeNextFire(existing, Date.now());\n if (exhausted) {\n const completed = await store.updateSchedule(existing.id, { status: 'completed' });\n return toScheduleView(completed)!;\n }\n const updated = await store.updateSchedule(existing.id, { status: 'active', nextFireAt });\n // Schedulers sleep until their earliest fire; wake them for this one.\n await this.#mastra.__publishSchedulerWake(updated.id);\n await this.#mastra.__ensureScheduleRuntimeReady();\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 details: { status: 404 },\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, resourceId } = 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 ...(resourceId !== undefined ? { resourceId } : {}),\n scheduleTrigger: {\n scheduleId: existing.id,\n scheduledFireAt: now,\n triggerKind: 'manual',\n } satisfies ScheduledWorkflowTrigger,\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 ...(schedule.cron ? { cron: schedule.cron } : {}),\n ...(schedule.timezone ? { timezone: schedule.timezone } : {}),\n ...(schedule.runAt != null ? { runAt: schedule.runAt } : {}),\n ...(schedule.endAt != null ? { endAt: schedule.endAt } : {}),\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 ...(schedule.cron ? { cron: schedule.cron } : {}),\n ...(schedule.timezone ? { timezone: schedule.timezone } : {}),\n ...(schedule.runAt != null ? { runAt: schedule.runAt } : {}),\n ...(schedule.endAt != null ? { endAt: schedule.endAt } : {}),\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 ...(target.resourceId !== undefined ? { resourceId: target.resourceId } : {}),\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":";;;;;;AAgDA,MAAa,wBAAwB;;;;;;;;AASrC,MAAa,2BAA2B;;;;;AAuBxC,MAAa,wBAAwB;CACnC;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAa,oBAAoB,CAAC,UAAU,QAAQ;;AAGpD,MAAM,2BAA2BA,OAAAA,EAAE,OAAOA,OAAAA,EAAE,OAAO,GAAGA,OAAAA,EAAE,MAAM;CAACA,OAAAA,EAAE,OAAO;CAAGA,OAAAA,EAAE,OAAO;CAAGA,OAAAA,EAAE,QAAQ;CAAGA,OAAAA,EAAE,KAAK;AAAC,CAAC,CAAC;;AAG9G,MAAM,8BAA8BA,OAAAA,EAAE,OAAO,EAC3C,gBAAgBA,OAAAA,EAAE,OAAOA,OAAAA,EAAE,OAAO,GAAGA,OAAAA,EAAE,QAAQ,CAAC,CAAC,CAAC,SAAS,EAC7D,CAAC;;AAGD,MAAM,yBAAyBA,OAAAA,EAAE,OAAO;CACtC,UAAUA,OA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