UNPKG

@mastra/core

Version:
1,029 lines (1,028 loc) • 39.3 kB
const require_error = require("./error-D90lJ6M7.cjs"); const require_slugify = require("./slugify-D98M2vDP.cjs"); let zod_v4 = require("zod/v4"); let croner = require("croner"); // src/schedules/types.ts /** Stable schedule id prefix for agent schedules. */ const AGENT_SCHEDULE_PREFIX = "agent_"; /** * Stable schedule id prefix for imperative workflow schedules created via * `mastra.schedules.create({ workflowId, ... })`. Intentionally distinct from * the `wf_` prefix used by declarative `createWorkflow({ schedule })` rows — * the boot-time declarative sync sweeps `wf_` rows against the in-code * config and must never delete imperative rows. */ const WORKFLOW_SCHEDULE_PREFIX = "schedule_"; /** * Signal categories a schedule fire may use. Single runtime source for the zod * enum below and for schedule-definition validation, so the two can't drift. */ const SCHEDULE_SIGNAL_TYPES = [ "user", "state", "reactive", "notification", "user-message", "system-reminder" ]; /** Lifecycle statuses a schedule row may be created with. */ const SCHEDULE_STATUSES = ["active", "paused"]; /** Shared zod for {@link AgentSignalAttributes} (XML tag attribute values). */ const ScheduleAttributesSchema = zod_v4.z.record(zod_v4.z.string(), zod_v4.z.union([ zod_v4.z.string(), zod_v4.z.number(), zod_v4.z.boolean(), zod_v4.z.null() ])); /** Serializable stream options applied to a woken run. See {@link ScheduleStreamOptions}. */ const ScheduleStreamOptionsSchema = zod_v4.z.object({ requestContext: zod_v4.z.record(zod_v4.z.string(), zod_v4.z.unknown()).optional() }); /** Options applied when the target thread is actively streaming. */ const ScheduleIfActiveSchema = zod_v4.z.object({ behavior: zod_v4.z.enum([ "deliver", "persist", "discard" ]).optional(), attributes: ScheduleAttributesSchema.optional() }); /** Options applied when the target thread is idle. */ const ScheduleIfIdleSchema = zod_v4.z.object({ behavior: zod_v4.z.enum([ "wake", "persist", "discard" ]).optional(), attributes: ScheduleAttributesSchema.optional(), streamOptions: ScheduleStreamOptionsSchema.optional(), requireClaimedOwner: zod_v4.z.boolean().optional() }); /** * Input payload persisted in `Schedule.target.inputData` for the built-in * agent-schedule fire. The scheduler tick rehydrates this on every fire. */ const ScheduleInputSchema = zod_v4.z.object({ scheduleId: zod_v4.z.string(), agentId: zod_v4.z.string(), prompt: zod_v4.z.string(), threadId: zod_v4.z.string().optional(), resourceId: zod_v4.z.string().optional(), signalType: zod_v4.z.enum(SCHEDULE_SIGNAL_TYPES).optional(), /** * XML tag name the signal renders as. Defaults to `schedule`, so a fire * surfaces to the agent as `<schedule>…</schedule>`. Override to render a * different tag. */ tagName: zod_v4.z.string().optional(), /** Attributes rendered onto the signal's XML tag. */ attributes: ScheduleAttributesSchema.optional(), /** * Provider options merged into the schedule signal payload on every fire. * Stored as a plain JSON object (`MastraProviderMetadata` is JSON-safe) and * applied regardless of `ifActive` / `ifIdle`. */ providerOptions: zod_v4.z.record(zod_v4.z.string(), zod_v4.z.unknown()).optional(), ifActive: ScheduleIfActiveSchema.optional(), ifIdle: ScheduleIfIdleSchema.optional() }); const ScheduleOutputSchema = zod_v4.z.object({ status: zod_v4.z.enum([ "fired", "signal-accepted", "skipped-thread-blocked", "thread-missing", "agent-missing", "invalid-input" ]), reason: zod_v4.z.string().optional() }); // src/workflows/scheduler/cron.ts /** * Validate a cron expression. Throws if the pattern is invalid. * * @param cron - Cron expression (5-, 6-, or 7-part). * @param timezone - Optional IANA timezone (e.g. 'America/New_York'). */ function validateCron(cron, timezone) { if (typeof cron !== "string" || cron.trim() === "") throw new Error(`Invalid cron expression: expected a non-empty cron string (e.g. "0 * * * *"), but received ${cron === void 0 ? "undefined" : JSON.stringify(cron)}.`); let job; try { job = new croner.Cron(cron); } catch (error) { const reason = error instanceof Error ? error.message : String(error); throw new Error(`Invalid cron expression "${cron}": ${reason}`); } if (timezone !== void 0) try { new croner.Cron(cron, { timezone }).nextRun(); } catch (error) { const reason = error instanceof Error ? error.message : String(error); throw new Error(`Invalid timezone "${timezone}": ${reason}`); } else job.nextRun(); } /** * Compute the next fire time (ms since epoch) for a cron expression. * * @param cron - Cron expression. * @param options - Optional timezone and reference time (`after`, ms since epoch). * The next fire time is the first cron occurrence strictly after `after`. * Defaults to `Date.now()`. * @returns The next fire time in ms since epoch. * @throws If the cron expression is invalid or has no future occurrence. */ function computeNextFireAt(cron, options) { const reference = options?.after !== void 0 ? new Date(options.after) : /* @__PURE__ */ new Date(); const nextFireAt = findNextFireAt(cron, options?.timezone, reference); if (nextFireAt === null) throw new Error(`Cron expression "${cron}" has no future occurrence after ${reference.toISOString()}`); return nextFireAt; } /** * Resolve what a schedule claim should write after firing at `after`. * * - One-off (`runAt` set): keep `nextFireAt` and mark the row `completed`. * - Cron with no future occurrence: keep `nextFireAt` and mark the row `completed`. * - Bounded cron (`endAt` set): advance to the next cron occurrence, or mark * `completed` when that occurrence is after `endAt`. * - Unbounded cron: advance to the next cron occurrence. */ function computeNextFire(schedule, after) { if (schedule.runAt != null) return { nextFireAt: schedule.nextFireAt, completed: true }; const nextFireAt = findNextFireAt(schedule.cron, schedule.timezone, new Date(after)); if (nextFireAt === null) return { nextFireAt: schedule.nextFireAt, completed: true }; return { nextFireAt, completed: schedule.endAt != null && nextFireAt > schedule.endAt }; } function findNextFireAt(cron, timezone, reference) { return new croner.Cron(cron, { timezone }).nextRun(reference)?.getTime() ?? null; } /** * Validate the timing fields of a schedule: exactly one of `cron` or a future * `runAt`, `endAt` only alongside `cron` and in the future. Throws on invalid input. * Pass `requireFuture: false` for declarative config, which must survive redeploys * after its times have passed. */ function validateScheduleTiming(input, options = {}) { const hasCron = input.cron !== void 0 && input.cron !== ""; const hasRunAt = input.runAt !== void 0; if (hasCron === hasRunAt) throw new Error("Schedule must specify exactly one of `cron` or `runAt`."); if (hasRunAt) { const runAt = toEpochMs(input.runAt); if (!Number.isFinite(runAt)) throw new Error("Schedule `runAt` must be a valid date or ms epoch timestamp."); if (options.requireFuture !== false && runAt <= Date.now()) throw new Error("Schedule `runAt` must be in the future."); if (input.endAt !== void 0) throw new Error("Schedule `endAt` is only allowed together with `cron`."); return; } validateCron(input.cron, input.timezone); if (input.endAt !== void 0) { const endAt = toEpochMs(input.endAt); if (!Number.isFinite(endAt)) throw new Error("Schedule `endAt` must be a valid date or ms epoch timestamp."); if (options.requireFuture !== false && endAt <= Date.now()) throw new Error("Schedule `endAt` must be in the future."); } } /** * Compute the initial row timing for a new schedule. One-offs fire at * `runAt`; a bounded cron whose first occurrence is already past `endAt` * starts `completed`. */ function computeInitialFire(input) { if (input.runAt !== void 0) return { nextFireAt: input.runAt, completed: false }; const nextFireAt = computeNextFireAt(input.cron, { timezone: input.timezone }); return { nextFireAt, completed: input.endAt !== void 0 && nextFireAt > input.endAt }; } function toEpochMs(value) { return value instanceof Date ? value.getTime() : value; } // src/schedules/define.ts /** * Stable schedule id prefix for schedules declared by a file-based agent's * `schedules/` directory. * * Deliberately distinct from every other prefix in the system: * - `agent_` — imperative rows from `mastra.schedules.create({ agentId })` * - `schedule_` — imperative rows from `mastra.schedules.create({ workflowId })` * - `wf_` — declarative rows from `createWorkflow({ schedule })` * * The boot-time sync sweeps orphaned `fsa_` rows against the schedules declared * on disk, so sharing a prefix with any of the above would make a redeploy * delete schedules this feature does not own. */ const FS_AGENT_SCHEDULE_PREFIX = "fsa_"; /** * Identity helper for a schedule declared under `agents/<id>/schedules/`. * Returns the definition unchanged after validating it, so authoring mistakes * surface at import time rather than on the first cron fire. * * @example * ```ts * // src/mastra/agents/support/schedules/heartbeat.ts * import { defineSchedule } from '@mastra/core/schedules'; * * export default defineSchedule({ * cron: '0 9 * * *', * prompt: 'Check system health and report any failures.', * }); * ``` */ function defineSchedule(definition) { assertValidScheduleDefinition(definition); return definition; } /** * Validate a schedule definition, throwing a `MastraError` naming the offending * schedule. Shared by `defineSchedule` (author-time) and file-based agent * assembly (build-time, where markdown schedules never went through * `defineSchedule`). * * `label` describes the schedule in error text — `defineSchedule` has no * identity to report, so assembly passes `agents/<id>/schedules/<key>`. */ function assertValidScheduleDefinition(definition, label) { const where = label ? ` (${label})` : ""; if (!definition || typeof definition !== "object") throw new require_error.MastraError({ id: "SCHEDULES_INVALID_DEFINITION", domain: require_error.ErrorDomain.AGENT, category: require_error.ErrorCategory.USER, details: { label: label ?? "" }, text: `Schedule${where}: expected a schedule definition object, received ${definition === null ? "null" : typeof definition}.` }); const hasPrompt = typeof definition.prompt === "string" && definition.prompt.trim() !== ""; const hasHandler = typeof definition.handler === "function"; if (hasPrompt && hasHandler) throw new require_error.MastraError({ id: "SCHEDULES_AMBIGUOUS_MODE", domain: require_error.ErrorDomain.AGENT, category: require_error.ErrorCategory.USER, details: { label: label ?? "" }, text: `Schedule${where}: set exactly one execution mode — remove either 'prompt' or 'handler'.` }); if (!hasPrompt && !hasHandler) throw new require_error.MastraError({ id: "SCHEDULES_MISSING_MODE", domain: require_error.ErrorDomain.AGENT, category: require_error.ErrorCategory.USER, details: { label: label ?? "" }, text: `Schedule${where}: set exactly one execution mode — provide a non-empty 'prompt' or a 'handler' function.` }); try { validateCron(definition.cron, definition.timezone); } catch (error) { throw new require_error.MastraError({ id: "SCHEDULES_INVALID_CRON", domain: require_error.ErrorDomain.AGENT, category: require_error.ErrorCategory.USER, details: { label: label ?? "", cron: String(definition.cron) }, text: `Schedule${where}: ${error instanceof Error ? error.message : String(error)}` }, error); } if (definition.signalType !== void 0 && !SCHEDULE_SIGNAL_TYPES.includes(definition.signalType)) throw new require_error.MastraError({ id: "SCHEDULES_INVALID_SIGNAL_TYPE", domain: require_error.ErrorDomain.AGENT, category: require_error.ErrorCategory.USER, details: { label: label ?? "", signalType: String(definition.signalType) }, text: `Schedule${where}: unknown signalType "${definition.signalType}". Expected one of: ${SCHEDULE_SIGNAL_TYPES.join(", ")}.` }); if (definition.status !== void 0 && !SCHEDULE_STATUSES.includes(definition.status)) throw new require_error.MastraError({ id: "SCHEDULES_INVALID_STATUS", domain: require_error.ErrorDomain.AGENT, category: require_error.ErrorCategory.USER, details: { label: label ?? "", status: String(definition.status) }, text: `Schedule${where}: unknown status "${definition.status}". Expected one of: ${SCHEDULE_STATUSES.join(", ")}.` }); if (definition.threadId && !definition.resourceId) throw new require_error.MastraError({ id: "SCHEDULES_MISSING_RESOURCE_ID", domain: require_error.ErrorDomain.AGENT, category: require_error.ErrorCategory.USER, details: { label: label ?? "" }, text: `Schedule${where}: 'resourceId' is required when 'threadId' is set.` }); } /** * Encode one component of a row id so it cannot contain the `__` delimiter. * * `encodeURIComponent` leaves `_` untouched, so escaping it explicitly is what * actually makes the delimiter unambiguous — otherwise an agent named `a__b` * and one named `a` with a key starting `_b` would produce the same row id. * `decodeURIComponent` reverses `%5F` for free. */ function encodeRowIdPart(value) { return encodeURIComponent(value).replace(/_/g, "%5F"); } /** * Build the storage row id for a schedule declared on a file-based agent. * Both components are encoded so an agent id or nested path containing the * `__` delimiter can never forge another schedule's row id. */ function fsAgentScheduleRowId(agentId, key) { return `${FS_AGENT_SCHEDULE_PREFIX}${encodeRowIdPart(agentId)}__${encodeRowIdPart(key)}`; } /** * Decode an `fsa_<agent>__<key>` row id back into its parts. Returns * `undefined` when the id isn't one of ours, so callers sweeping or resolving * schedule rows leave other schedule sources alone. */ function parseFsAgentScheduleRowId(rowId) { if (!rowId.startsWith("fsa_")) return void 0; const rest = rowId.slice(4); const separator = rest.indexOf("__"); if (separator <= 0) return void 0; try { return { agentId: decodeURIComponent(rest.slice(0, separator)), key: decodeURIComponent(rest.slice(separator + 2)) }; } catch { return; } } // src/schedules/schedules.ts /** PubSub topic consumed by the workflow event processor. */ const TOPIC_WORKFLOWS = "workflows"; /** * Slugify the caller-facing portion of a schedule id into a canonical * `<prefix><slug>` shape. The slug part is lowercased and stripped of * characters that are unsafe in storage keys / URLs; the prefix is added only * if missing so a caller can pass either `nightly-summary` or * `agent_nightly-summary` and get the same canonical id. Returns an empty * string when nothing slug-able remains. */ function canonicalizeScheduleId(rawId, prefix) { const trimmed = rawId.trim(); const withoutPrefix = trimmed.startsWith(prefix) ? trimmed.slice(prefix.length) : trimmed; const slug = require_slugify.slugify(withoutPrefix); if (!slug) return ""; return `${prefix}${slug}`; } function invalidTiming(err, op) { return new require_error.MastraError({ id: "SCHEDULES_INVALID_TIMING", domain: require_error.ErrorDomain.AGENT, category: require_error.ErrorCategory.USER, details: { status: 400 }, text: `schedules.${op}: ${err instanceof Error ? err.message : String(err)}` }); } function scheduleCompleted(id, op) { return new require_error.MastraError({ id: "SCHEDULES_COMPLETED", domain: require_error.ErrorDomain.AGENT, category: require_error.ErrorCategory.USER, details: { status: 409 }, text: `schedules.${op}: schedule "${id}" is completed and can no longer be ${op === "pause" ? "paused" : "resumed"}.` }); } /** * Validate the cron/runAt/endAt fields of a create input and compute the * row fields plus the initial fire time. One-offs store `cron` as `''`. */ function resolveCreateTiming(input) { const runAt = input.runAt !== void 0 ? toEpochMs(input.runAt) : void 0; const endAt = input.endAt !== void 0 ? toEpochMs(input.endAt) : void 0; let nextFireAt; let completed; try { validateScheduleTiming(input); ({nextFireAt, completed} = computeInitialFire({ cron: input.cron, timezone: input.timezone, runAt, endAt })); } catch (err) { throw invalidTiming(err, "create"); } return { fields: { cron: input.cron ?? "", ...runAt !== void 0 ? { runAt } : {}, ...endAt !== void 0 ? { endAt } : {} }, nextFireAt, completed }; } /** * Normalize a caller-supplied schedule id for `create`. Throws * `SCHEDULES_INVALID_ID` when the id is empty after normalization so callers * cannot create an unaddressable schedule. */ function normalizeScheduleId(rawId, prefix) { const canonical = canonicalizeScheduleId(rawId, prefix); if (!canonical) throw new require_error.MastraError({ id: "SCHEDULES_INVALID_ID", domain: require_error.ErrorDomain.AGENT, category: require_error.ErrorCategory.USER, details: { status: 400 }, text: `schedules.create: id "${rawId}" is empty after normalization. Provide an id with at least one alphanumeric character.` }); return canonical; } /** * Unified service for cron schedules. Schedules are persisted as `Schedule` * rows whose `target` discriminates what fires: `type: 'agent'` rows run an * agent (via signal or `agent.generate`), `type: 'workflow'` rows start a * workflow run. This class is a typed projection over `SchedulesStorage` * that knows how to build targets and surface flat * {@link AgentSchedule} / {@link WorkflowSchedule} views. * * Use via `mastra.schedules` (the canonical CRUD surface). */ var Schedules = class { #mastra; constructor(mastra) { this.#mastra = mastra; } async #getStore() { const store = await this.#mastra.getStorage()?.getStore("schedules"); if (!store) throw new require_error.MastraError({ id: "SCHEDULES_NO_SCHEDULES_STORAGE", domain: require_error.ErrorDomain.AGENT, category: require_error.ErrorCategory.USER, text: "Schedules require a storage adapter that implements the schedules domain." }); return store; } /** * Resolve a caller-supplied id to a stored row. An id is first looked up * verbatim (covering `agent_`, `schedule_`, `wf_`, and legacy `hb_` ids); * when that misses, a bare caller id is canonicalized to `agent_<slug>` to * match what agent-schedule `create` persisted. */ async #load(id) { const store = await this.#getStore(); const trimmed = id.trim(); const exact = trimmed ? await store.getSchedule(trimmed) : null; if (exact) return exact; const canonical = canonicalizeScheduleId(trimmed, AGENT_SCHEDULE_PREFIX); if (!canonical || canonical === trimmed) return null; return store.getSchedule(canonical); } async create(input) { if ("workflowId" in input && input.workflowId) return this.#createWorkflowSchedule(input); return this.#createAgentSchedule(input); } async #createAgentSchedule(input) { const timing = resolveCreateTiming(input); if (!input.agentId) throw new require_error.MastraError({ id: "SCHEDULES_MISSING_TARGET_ID", domain: require_error.ErrorDomain.AGENT, category: require_error.ErrorCategory.USER, details: { status: 400 }, text: "schedules.create requires `agentId` or `workflowId`." }); if (input.threadId && !input.resourceId) throw new require_error.MastraError({ id: "SCHEDULES_MISSING_RESOURCE_ID", domain: require_error.ErrorDomain.AGENT, category: require_error.ErrorCategory.USER, details: { status: 400 }, text: "schedules.create requires `resourceId` when `threadId` is set." }); if (!input.threadId) { const offenders = []; if (input.signalType !== void 0) offenders.push("signalType"); if (input.ifActive !== void 0) offenders.push("ifActive"); if (input.ifIdle !== void 0) offenders.push("ifIdle"); if (input.resourceId !== void 0) offenders.push("resourceId"); if (offenders.length > 0) throw new require_error.MastraError({ id: "SCHEDULES_THREADLESS_OPTIONS", domain: require_error.ErrorDomain.AGENT, category: require_error.ErrorCategory.USER, details: { status: 400 }, text: `schedules.create: ${offenders.join(", ")} require a threadId.` }); } const store = await this.#getStore(); const id = input.id !== void 0 ? normalizeScheduleId(input.id, AGENT_SCHEDULE_PREFIX) : `${AGENT_SCHEDULE_PREFIX}${globalThis.crypto.randomUUID()}`; await this.#assertIdAvailable(store, id, input.id !== void 0); const now = Date.now(); const schedule = { id, target: { type: "agent", agentId: input.agentId, prompt: input.prompt, ...input.name !== void 0 ? { name: input.name } : {}, ...input.threadId ? { threadId: input.threadId } : {}, ...input.resourceId ? { resourceId: input.resourceId } : {}, ...input.signalType ? { signalType: input.signalType } : {}, ...input.tagName ? { tagName: input.tagName } : {}, ...input.attributes ? { attributes: input.attributes } : {}, ...input.providerOptions ? { providerOptions: input.providerOptions } : {}, ...input.ifActive ? { ifActive: input.ifActive } : {}, ...input.ifIdle ? { ifIdle: input.ifIdle } : {} }, ...timing.fields, timezone: input.timezone, status: timing.completed ? "completed" : input.status ?? "active", nextFireAt: timing.nextFireAt, createdAt: now, updatedAt: now, ownerType: "agent", ownerId: input.agentId, ...input.metadata ? { metadata: input.metadata } : {} }; const created = await store.createSchedule(schedule); await this.#mastra.__publishSchedulerWake(created.id); await this.#mastra.__ensureScheduleRuntimeReady(); return toAgentSchedule(created); } async #createWorkflowSchedule(input) { const timing = resolveCreateTiming(input); const store = await this.#getStore(); const id = input.id !== void 0 ? normalizeScheduleId(input.id, WORKFLOW_SCHEDULE_PREFIX) : `${WORKFLOW_SCHEDULE_PREFIX}${globalThis.crypto.randomUUID()}`; await this.#assertIdAvailable(store, id, input.id !== void 0); const now = Date.now(); const schedule = { id, target: { type: "workflow", workflowId: input.workflowId, ...input.inputData !== void 0 ? { inputData: input.inputData } : {}, ...input.initialState !== void 0 ? { initialState: input.initialState } : {}, ...input.requestContext !== void 0 ? { requestContext: input.requestContext } : {}, ...input.resourceId !== void 0 ? { resourceId: input.resourceId } : {} }, ...timing.fields, timezone: input.timezone, status: timing.completed ? "completed" : input.status ?? "active", nextFireAt: timing.nextFireAt, createdAt: now, updatedAt: now, ...input.metadata ? { metadata: input.metadata } : {} }; const created = await store.createSchedule(schedule); await this.#mastra.__publishSchedulerWake(created.id); await this.#mastra.__ensureScheduleRuntimeReady(); return toWorkflowSchedule(created); } async #assertIdAvailable(store, id, callerProvided) { if (!callerProvided) return; if (await store.getSchedule(id)) throw new require_error.MastraError({ id: "SCHEDULES_ID_EXISTS", domain: require_error.ErrorDomain.AGENT, category: require_error.ErrorCategory.USER, details: { status: 409 }, text: `schedules.create: a schedule with id "${id}" already exists. Use update() to modify it or choose a different id.` }); } async get(id) { const schedule = await this.#load(id); if (!schedule) return null; return toScheduleView(schedule); } async list(filter) { const store = await this.#getStore(); const storeFilter = { ...filter?.agentId ? { ownerType: "agent", ownerId: filter.agentId } : {}, ...filter?.workflowId ? { workflowId: filter.workflowId } : {} }; const views = (filter?.status ? await store.listSchedules({ ...storeFilter, status: filter.status }) : (await Promise.all([store.listSchedules({ ...storeFilter, status: "active" }), store.listSchedules({ ...storeFilter, status: "paused" })])).flat().sort((a, b) => a.createdAt - b.createdAt)).map(toScheduleView).filter((s) => s !== null).filter((s) => filter?.agentId ? s.agentId !== void 0 : true); const agentOnly = filter?.threadId !== void 0 || filter?.name !== void 0; if (!agentOnly && filter?.resourceId === void 0) return views; return views.filter((s) => { if (filter?.resourceId !== void 0 && s.resourceId !== filter.resourceId) return false; if (!agentOnly) return true; if (s.agentId === void 0) return false; if (filter?.threadId !== void 0 && s.threadId !== filter.threadId) return false; if (filter?.name !== void 0 && s.name !== filter.name) return false; return true; }); } async update(id, patch) { const store = await this.#getStore(); const existing = await this.#load(id); if (!existing) throw new require_error.MastraError({ id: "SCHEDULES_NOT_FOUND", domain: require_error.ErrorDomain.AGENT, category: require_error.ErrorCategory.USER, details: { status: 404 }, text: `Schedule "${id}" not found.` }); const isOneOff = existing.runAt != null; if (isOneOff && (patch.cron !== void 0 || patch.endAt !== void 0)) throw invalidTiming(/* @__PURE__ */ new Error("`cron` and `endAt` cannot be set on a one-off (`runAt`) schedule."), "update"); if (!isOneOff && patch.runAt !== void 0) throw invalidTiming(/* @__PURE__ */ new Error("`runAt` can only be set on a one-off schedule."), "update"); const nextCron = patch.cron ?? existing.cron; const nextTimezone = patch.timezone !== void 0 ? patch.timezone : existing.timezone; if (!isOneOff && (patch.cron !== void 0 || patch.timezone !== void 0)) try { validateCron(nextCron, nextTimezone); } catch (err) { throw invalidTiming(err, "update"); } const nextRunAt = patch.runAt !== void 0 ? toEpochMs(patch.runAt) : existing.runAt; if (patch.runAt !== void 0 && !Number.isFinite(nextRunAt)) throw invalidTiming(/* @__PURE__ */ new Error("`runAt` must be a valid date or ms epoch timestamp."), "update"); const nextEndAt = patch.endAt === void 0 ? existing.endAt : patch.endAt === null ? void 0 : toEpochMs(patch.endAt); if (patch.endAt != null && (!Number.isFinite(nextEndAt) || nextEndAt <= Date.now())) throw invalidTiming(/* @__PURE__ */ new Error("`endAt` must be a valid timestamp in the future."), "update"); const nextTarget = existing.target.type === "agent" ? this.#patchAgentTarget(existing.target, patch) : this.#patchWorkflowTarget(existing.target, patch); const timingChanged = isOneOff ? patch.runAt !== void 0 && nextRunAt !== existing.runAt : patch.cron !== void 0 || patch.timezone !== void 0 || patch.endAt !== void 0; if (existing.status === "completed" && patch.status !== void 0 && !timingChanged) throw scheduleCompleted(existing.id, patch.status === "paused" ? "pause" : "resume"); let nextStatus = existing.status === "completed" ? timingChanged ? patch.status ?? "active" : "completed" : patch.status ?? existing.status; const resuming = nextStatus === "active" && existing.status !== "active"; let nextFireAt; if (timingChanged || resuming) { if (isOneOff) nextFireAt = nextRunAt; else { const next = computeNextFire({ cron: nextCron, timezone: nextTimezone, endAt: nextEndAt, nextFireAt: existing.nextFireAt }, Date.now()); nextFireAt = next.nextFireAt; if (next.completed) nextStatus = "completed"; } } const updated = await store.updateSchedule(existing.id, { ...patch.cron !== void 0 ? { cron: patch.cron } : {}, ...patch.timezone !== void 0 ? { timezone: patch.timezone } : {}, ...patch.runAt !== void 0 ? { runAt: nextRunAt } : {}, ...patch.endAt !== void 0 ? { endAt: nextEndAt } : {}, target: nextTarget, ...nextFireAt !== void 0 ? { nextFireAt } : {}, ...patch.metadata !== void 0 ? { metadata: patch.metadata } : {}, ...nextStatus !== existing.status ? { status: nextStatus } : {} }); if (nextFireAt !== void 0 && updated.status === "active") { await this.#mastra.__publishSchedulerWake(updated.id); await this.#mastra.__ensureScheduleRuntimeReady(); } return toScheduleView(updated); } #patchAgentTarget(existingTarget, patch) { if (!existingTarget.threadId) { const offenders = []; if (patch.signalType !== void 0) offenders.push("signalType"); if (patch.ifActive !== void 0) offenders.push("ifActive"); if (patch.ifIdle !== void 0) offenders.push("ifIdle"); if (offenders.length > 0) throw new require_error.MastraError({ id: "SCHEDULES_THREADLESS_OPTIONS", domain: require_error.ErrorDomain.AGENT, category: require_error.ErrorCategory.USER, details: { status: 400 }, text: `schedules.update: ${offenders.join(", ")} require a threadId.` }); } return { ...existingTarget, ...patch.prompt !== void 0 ? { prompt: patch.prompt } : {}, ...patch.name !== void 0 ? { name: patch.name } : {}, ...patch.signalType !== void 0 ? { signalType: patch.signalType } : {}, ...patch.tagName !== void 0 ? { tagName: patch.tagName } : {}, ...patch.attributes !== void 0 ? { attributes: patch.attributes } : {}, ...patch.providerOptions !== void 0 ? { providerOptions: patch.providerOptions } : {}, ...patch.ifActive !== void 0 ? { ifActive: patch.ifActive } : {}, ...patch.ifIdle !== void 0 ? { ifIdle: patch.ifIdle } : {} }; } #patchWorkflowTarget(existingTarget, patch) { const offenders = [ "prompt", "name", "signalType", "tagName", "attributes", "providerOptions", "ifActive", "ifIdle" ].filter((key) => patch[key] !== void 0); if (offenders.length > 0) throw new require_error.MastraError({ id: "SCHEDULES_INVALID_WORKFLOW_PATCH", domain: require_error.ErrorDomain.AGENT, category: require_error.ErrorCategory.USER, details: { status: 400 }, text: `schedules.update: ${offenders.join(", ")} only apply to agent schedules.` }); const wfPatch = patch; return { ...existingTarget, ...wfPatch.inputData !== void 0 ? { inputData: wfPatch.inputData } : {}, ...wfPatch.initialState !== void 0 ? { initialState: wfPatch.initialState } : {}, ...wfPatch.requestContext !== void 0 ? { requestContext: wfPatch.requestContext } : {}, ...wfPatch.resourceId !== void 0 ? { resourceId: wfPatch.resourceId } : {} }; } async delete(id) { const store = await this.#getStore(); const existing = await this.#load(id); if (!existing) return; await store.deleteSchedule(existing.id); } async pause(id) { const store = await this.#getStore(); const existing = await this.#load(id); if (!existing) throw new require_error.MastraError({ id: "SCHEDULES_NOT_FOUND", domain: require_error.ErrorDomain.AGENT, category: require_error.ErrorCategory.USER, details: { status: 404 }, text: `Schedule "${id}" not found.` }); if (existing.status === "paused") return toScheduleView(existing); if (existing.status === "completed") throw scheduleCompleted(existing.id, "pause"); return toScheduleView(await store.updateSchedule(existing.id, { status: "paused" })); } async resume(id) { const store = await this.#getStore(); const existing = await this.#load(id); if (!existing) throw new require_error.MastraError({ id: "SCHEDULES_NOT_FOUND", domain: require_error.ErrorDomain.AGENT, category: require_error.ErrorCategory.USER, details: { status: 404 }, text: `Schedule "${id}" not found.` }); if (existing.status === "active") return toScheduleView(existing); if (existing.status === "completed") throw scheduleCompleted(existing.id, "resume"); if (existing.runAt != null) { const updated = await store.updateSchedule(existing.id, { status: "active", nextFireAt: existing.runAt }); await this.#mastra.__publishSchedulerWake(updated.id); await this.#mastra.__ensureScheduleRuntimeReady(); return toScheduleView(updated); } const { nextFireAt, completed: exhausted } = computeNextFire(existing, Date.now()); if (exhausted) return toScheduleView(await store.updateSchedule(existing.id, { status: "completed" })); const updated = await store.updateSchedule(existing.id, { status: "active", nextFireAt }); await this.#mastra.__publishSchedulerWake(updated.id); await this.#mastra.__ensureScheduleRuntimeReady(); return toScheduleView(updated); } async run(id) { const existing = await this.#load(id); if (!existing) throw new require_error.MastraError({ id: "SCHEDULES_NOT_FOUND", domain: require_error.ErrorDomain.AGENT, category: require_error.ErrorCategory.USER, details: { status: 404 }, text: `Schedule "${id}" not found.` }); const now = Date.now(); if (existing.target.type === "agent") { const claimId = `manual_${existing.id}_${now}`; await this.#mastra.pubsub.publish("agent-schedules", { type: "agent-schedule.fire", runId: claimId, data: { scheduleId: existing.id, claimId, scheduledFireAt: now, target: existing.target, triggerKind: "manual" } }); return { scheduleId: existing.id, claimId, scheduledFireAt: now }; } const { workflowId, inputData, initialState, requestContext, resourceId } = existing.target; const claimId = `sched_${existing.id}_${now}`; await this.#mastra.pubsub.publish(TOPIC_WORKFLOWS, { type: "workflow.start", runId: claimId, data: { workflowId, runId: claimId, prevResult: { status: "success", output: inputData ?? {} }, requestContext: requestContext ?? {}, initialState: initialState ?? {}, ...resourceId !== void 0 ? { resourceId } : {}, scheduleTrigger: { scheduleId: existing.id, scheduledFireAt: now, triggerKind: "manual" } } }); const store = await this.#getStore(); try { await store.recordTrigger({ scheduleId: existing.id, runId: claimId, scheduledFireAt: now, actualFireAt: now, outcome: "published", triggerKind: "manual" }); } catch {} return { scheduleId: existing.id, claimId, scheduledFireAt: now }; } }; /** * Project a `Schedule` row to a flat {@link AgentSchedule} view. Returns * `null` when the schedule is not an agent schedule * (`target.type !== 'agent'`), allowing callers to filter mixed result sets * in one pass. */ function toAgentSchedule(schedule) { if (schedule.target?.type !== "agent") return null; const target = schedule.target; return { id: schedule.id, agentId: target.agentId, ...target.name !== void 0 ? { name: target.name } : {}, ...target.threadId ? { threadId: target.threadId } : {}, ...target.resourceId ? { resourceId: target.resourceId } : {}, prompt: target.prompt, ...schedule.cron ? { cron: schedule.cron } : {}, ...schedule.timezone ? { timezone: schedule.timezone } : {}, ...schedule.runAt != null ? { runAt: schedule.runAt } : {}, ...schedule.endAt != null ? { endAt: schedule.endAt } : {}, status: schedule.status, nextFireAt: schedule.nextFireAt, ...schedule.lastFireAt !== void 0 ? { lastFireAt: schedule.lastFireAt } : {}, ...schedule.lastRunId ? { lastRunId: schedule.lastRunId } : {}, ...target.signalType ? { signalType: target.signalType } : {}, ...target.tagName ? { tagName: target.tagName } : {}, ...target.attributes ? { attributes: target.attributes } : {}, ...target.providerOptions ? { providerOptions: target.providerOptions } : {}, ...target.ifActive ? { ifActive: target.ifActive } : {}, ...target.ifIdle ? { ifIdle: target.ifIdle } : {}, ...schedule.metadata ? { metadata: schedule.metadata } : {}, createdAt: schedule.createdAt, updatedAt: schedule.updatedAt }; } /** * Project a `Schedule` row to a flat {@link WorkflowSchedule} view. Returns * `null` when the schedule is not a workflow schedule. */ function toWorkflowSchedule(schedule) { if (schedule.target?.type !== "workflow") return null; const target = schedule.target; return { id: schedule.id, workflowId: target.workflowId, ...schedule.cron ? { cron: schedule.cron } : {}, ...schedule.timezone ? { timezone: schedule.timezone } : {}, ...schedule.runAt != null ? { runAt: schedule.runAt } : {}, ...schedule.endAt != null ? { endAt: schedule.endAt } : {}, status: schedule.status, nextFireAt: schedule.nextFireAt, ...schedule.lastFireAt !== void 0 ? { lastFireAt: schedule.lastFireAt } : {}, ...schedule.lastRunId ? { lastRunId: schedule.lastRunId } : {}, ...target.inputData !== void 0 ? { inputData: target.inputData } : {}, ...target.initialState !== void 0 ? { initialState: target.initialState } : {}, ...target.requestContext !== void 0 ? { requestContext: target.requestContext } : {}, ...target.resourceId !== void 0 ? { resourceId: target.resourceId } : {}, ...schedule.metadata ? { metadata: schedule.metadata } : {}, createdAt: schedule.createdAt, updatedAt: schedule.updatedAt }; } /** Project a `Schedule` row to whichever flat view matches its target type. */ function toScheduleView(schedule) { return toAgentSchedule(schedule) ?? toWorkflowSchedule(schedule); } Object.defineProperty(exports, "AGENT_SCHEDULE_PREFIX", { enumerable: true, get: function() { return AGENT_SCHEDULE_PREFIX; } }); Object.defineProperty(exports, "FS_AGENT_SCHEDULE_PREFIX", { enumerable: true, get: function() { return FS_AGENT_SCHEDULE_PREFIX; } }); Object.defineProperty(exports, "ScheduleInputSchema", { enumerable: true, get: function() { return ScheduleInputSchema; } }); Object.defineProperty(exports, "ScheduleOutputSchema", { enumerable: true, get: function() { return ScheduleOutputSchema; } }); Object.defineProperty(exports, "Schedules", { enumerable: true, get: function() { return Schedules; } }); Object.defineProperty(exports, "WORKFLOW_SCHEDULE_PREFIX", { enumerable: true, get: function() { return WORKFLOW_SCHEDULE_PREFIX; } }); Object.defineProperty(exports, "assertValidScheduleDefinition", { enumerable: true, get: function() { return assertValidScheduleDefinition; } }); Object.defineProperty(exports, "computeNextFire", { enumerable: true, get: function() { return computeNextFire; } }); Object.defineProperty(exports, "computeNextFireAt", { enumerable: true, get: function() { return computeNextFireAt; } }); Object.defineProperty(exports, "defineSchedule", { enumerable: true, get: function() { return defineSchedule; } }); Object.defineProperty(exports, "fsAgentScheduleRowId", { enumerable: true, get: function() { return fsAgentScheduleRowId; } }); Object.defineProperty(exports, "parseFsAgentScheduleRowId", { enumerable: true, get: function() { return parseFsAgentScheduleRowId; } }); Object.defineProperty(exports, "toAgentSchedule", { enumerable: true, get: function() { return toAgentSchedule; } }); Object.defineProperty(exports, "toEpochMs", { enumerable: true, get: function() { return toEpochMs; } }); Object.defineProperty(exports, "toScheduleView", { enumerable: true, get: function() { return toScheduleView; } }); Object.defineProperty(exports, "toWorkflowSchedule", { enumerable: true, get: function() { return toWorkflowSchedule; } }); Object.defineProperty(exports, "validateCron", { enumerable: true, get: function() { return validateCron; } }); Object.defineProperty(exports, "validateScheduleTiming", { enumerable: true, get: function() { return validateScheduleTiming; } }); //# sourceMappingURL=schedules-CyoPADNx.cjs.map