import { randomUUID } from 'node:crypto'; import { constants, copyFile, mkdir, readFile, rename, writeFile, } from 'node:fs/promises'; import { agentStateDir } from '../../../src/plugin-sdk.js'; import { dirname, join } from 'node:path'; import type { CronMissedRecord, CronRunRecord, CronTask, CronTaskFile, CronTaskPatch, } from './types.js'; import { cronToHuman } from './cronTime.js'; import { intervalToHuman, nextScheduleRunMs } from './scheduleEngine.js'; import { schedulerLockFile, withStoreLock } from './lock.js'; import { appendMissed as appendMissedRecord, appendRun as appendRunRecord, listMissed as listMissedRecords, markMissedRead as markMissedRecordsRead, markRunsRead as markRunRecordsRead, recentRuns as readRecentRuns, } from './runs.js'; import { normalizeTask } from './schema.js'; import { taskTransaction, outsideTaskTransaction } from './transaction.js'; import { requestStop } from './requests.js'; function root(): string { return process.env.MINIMAL_AGENT_CRON_RUNNER_HOME ? join(process.env.MINIMAL_AGENT_CRON_RUNNER_HOME, 'cron-runner') : join(agentStateDir(), 'plugins', 'cron-runner'); } function tasksFile(): string { return join(root(), 'tasks.json'); } function runsDir(): string { return join(root(), 'runs'); } function missedFile(): string { return join(root(), 'missed.jsonl'); } let mutationQueue: Promise = Promise.resolve(); const taskChangeListeners = new Set<() => void>(); function notifyTaskChanges(): void { outsideTaskTransaction(() => { for (const listener of taskChangeListeners) { try { listener(); } catch { /* Notifications cannot roll back a durable mutation. */ } } }); } export function subscribeTaskChanges(listener: () => void): () => void { taskChangeListeners.add(listener); return () => taskChangeListeners.delete(listener); } export function cronDataRoot(): string { return root(); } export function cronLockFile(): string { return schedulerLockFile(root()); } /** Upgrade legacy fresh/hidden-session tasks once, keeping an immutable pre-migration backup. */ export async function migrateCronTasks(): Promise { return await enqueueMutation(async () => { let raw: string; try { raw = await readFile(tasksFile(), 'utf8'); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false; throw error; } let parsed: Partial; try { parsed = JSON.parse(raw) as Partial; } catch { throw new Error(`计划任务 JSON 损坏,原件未修改:${tasksFile()}`); } if (!Array.isArray(parsed.tasks)) throw new Error(`计划任务缺少 tasks 数组:${tasksFile()}`); const needsMigration = parsed.tasks.some((value) => { const task = value as Partial; return ( !task.schedule || !('type' in task.schedule) || !task.runtime?.bindingStatus || (task.version !== 2 && (task.runtime.sessionMode === 'fresh' || task.runtime.sessionId?.startsWith('cron-'))) ); }); if (!needsMigration) return false; await mkdir(root(), { recursive: true }); try { await copyFile( tasksFile(), join(root(), 'tasks.pre-session-binding.backup.json'), constants.COPYFILE_EXCL, ); } catch (error) { if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error; } const migrated = parsed.tasks.map(normalizeTask); if (migrated.some((task) => !task)) throw new Error('计划任务数据损坏,已保留原件;迁移未写入。'); await writeTasksFile( (migrated as CronTask[]).map((task) => ({ ...task, version: 2 })), ); notifyTaskChanges(); return true; }); } async function readTasks(fromMs = Date.now()): Promise { try { const raw = await readFile(tasksFile(), 'utf8'); const parsed = JSON.parse(raw) as Partial; if (!Array.isArray(parsed.tasks)) throw new Error('缺少 tasks 数组'); const tasks = parsed.tasks.map(normalizeTask); if (tasks.some((task) => !task)) throw new Error('存在无效任务'); return ( (tasks as CronTask[]) // 注意:不能写成 .map(refreshNextRun)——Array.map 会把 (element, index, array) // 全传进去,第二个实参 index(0,1,2...) 会顶掉 refreshNextRun 的 fromMs=Date.now() // 默认值,导致 nextRunAt/expired 全按 Unix 纪元(≈0ms)计算(真机 e2e 抓到 // nextRunAt 恒为 1970-01-01)。必须用箭头包一层只透传 task。 .map((task) => refreshNextRun(task, fromMs)) ); } catch (error) { if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []; throw new Error( `无法读取计划任务 ${tasksFile()},原件未修改:${String(error)}`, ); } } export async function listTasks(): Promise { return await readTasks(); } async function writeTasksFile(tasks: CronTask[]): Promise { const file = tasksFile(); await mkdir(dirname(file), { recursive: true }); const tmp = `${file}.${process.pid}.${Date.now()}.tmp`; await writeFile( tmp, JSON.stringify( { tasks: tasks.map((task) => refreshNextRun(task)) }, null, 2, ), 'utf8', ); await rename(tmp, file); } function enqueueMutation(mutate: () => Promise): Promise { const dataRoot = root(); const operation = mutationQueue.then(() => withStoreLock(dataRoot, mutate)); mutationQueue = operation.then( () => undefined, () => undefined, ); return operation; } export async function writeTasks(tasks: CronTask[]): Promise { await enqueueMutation(async () => { await writeTasksFile(tasks); notifyTaskChanges(); }); } export async function upsertTask( task: CronTask, ifAbsent = false, ): Promise { return await enqueueMutation(async () => { const tasks = await readTasks(); const idx = tasks.findIndex((t) => t.id === task.id); if (idx >= 0 && ifAbsent) return tasks[idx]!; const saved = refreshNextRun({ ...task, updatedAt: new Date().toISOString(), }); if (idx >= 0) tasks[idx] = saved; else tasks.push(saved); await writeTasksFile(tasks); notifyTaskChanges(); return saved; }); } export async function updateTask( id: string, updater: (task: CronTask) => CronTask, ): Promise { return await taskTransaction(root(), id, () => enqueueMutation(async () => { const tasks = await readTasks(); const idx = tasks.findIndex((task) => task.id === id); if (idx < 0) return undefined; const saved = refreshNextRun({ ...updater(tasks[idx]!), revision: (tasks[idx]!.revision ?? 0) + 1, updatedAt: new Date().toISOString(), }); tasks[idx] = saved; await writeTasksFile(tasks); notifyTaskChanges(); return saved; }), ); } export async function deleteTask(id: string): Promise { return await taskTransaction(root(), id, async () => { await requestStop(id); return enqueueMutation(async () => { const tasks = await readTasks(); const next = tasks.filter((t) => t.id !== id); if (next.length === tasks.length) return false; await writeTasksFile(next); notifyTaskChanges(); return true; }); }); } export async function getTask( idOrPrefix: string, ): Promise { const tasks = await listTasks(); const exact = tasks.find((t) => t.id === idOrPrefix); if (exact) return exact; const matches = tasks.filter((t) => t.id.startsWith(idOrPrefix)); if (matches.length > 1) throw new Error('任务 ID 前缀不唯一'); return matches[0]; } export async function appendRun(record: CronRunRecord): Promise { await appendRunRecord(runsDir(), record); } export async function recentRuns( taskId: string, limit = 5, ): Promise { return await readRecentRuns(runsDir(), taskId, limit); } export async function activeRuns(taskId: string): Promise { return readRecentRuns(runsDir(), taskId, Infinity, true); } export async function markRunsRead(taskId?: string): Promise { await markRunRecordsRead(runsDir(), taskId); } export async function appendMissed(record: CronMissedRecord): Promise { await appendMissedRecord(missedFile(), record); } export async function listMissed(limit = 20): Promise { return await listMissedRecords(missedFile(), limit); } export async function markMissedRead(taskId?: string): Promise { await markMissedRecordsRead(missedFile(), taskId); } export function createTask(input: { name: string; description?: string; cron?: string; at?: string; catchUp?: CronTask['catchUp']; notifications?: CronTask['notifications']; intervalMs?: number; anchorAt?: string; timezone: string; cwd: string; sessionId?: string; model?: string; maxTurns?: number; kind?: CronTask['kind']; permanent?: boolean; expiresAt?: string; maxRuns?: number; sessionMode?: CronTask['runtime']['sessionMode']; jitterMs?: number; action: CronTask['action']; }): CronTask { const now = new Date().toISOString(); const id = `cron-${randomUUID().slice(0, 8)}`; if (!input.at && !input.cron && !input.intervalMs) { throw new Error('createTask requires cron or intervalMs'); } const schedule = input.at ? { type: 'once' as const, at: input.at, human: `一次 · ${input.at}` } : input.intervalMs ? { type: 'interval' as const, intervalMs: input.intervalMs, anchorAt: input.anchorAt ?? now, human: intervalToHuman(input.intervalMs), jitterMs: input.jitterMs ?? 0, } : { type: 'cron' as const, cron: input.cron!, timezone: input.timezone, human: cronToHuman(input.cron!), jitterMs: input.jitterMs ?? 0, }; return refreshNextRun({ version: 2, revision: 0, planId: randomUUID(), catchUp: input.catchUp ?? 'skip', notifications: input.notifications ?? 'all', id, name: input.name, ...(input.description ? { description: input.description } : {}), status: 'active', kind: input.at ? 'once' : (input.kind ?? 'recurring'), ...(input.permanent ? { permanent: true } : {}), ...(input.expiresAt ? { expiresAt: input.expiresAt } : {}), ...(input.maxRuns ? { maxRuns: input.maxRuns } : {}), schedule, action: input.action, runtime: { cwd: input.cwd, environment: 'project', sessionId: input.sessionId ?? 'default', sessionMode: input.sessionMode ?? 'persistent', bindingStatus: input.sessionMode === 'fresh' || !input.sessionId || !input.sessionId.startsWith('cron-') ? 'bound' : 'needs_binding', ...(input.model ? { model: input.model } : {}), ...(input.maxTurns ? { maxTurns: input.maxTurns } : {}), }, stats: { runCount: 0, successCount: 0, failureCount: 0, skippedCount: 0, }, createdAt: now, updatedAt: now, }); } export function refreshNextRun(task: CronTask, fromMs = Date.now()): CronTask { const expired = task.expiresAt && !task.permanent && Date.parse(task.expiresAt) <= fromMs; const next = task.status === 'active' && !expired ? nextScheduleRunMs(task.schedule, fromMs) : null; return { ...task, ...(expired ? { status: 'completed' as const } : {}), schedule: { ...task.schedule, human: task.schedule.type === 'once' ? `一次 · ${task.schedule.at}` : task.schedule.type === 'cron' ? cronToHuman(task.schedule.cron) : intervalToHuman(task.schedule.intervalMs), jitterMs: typeof task.schedule.jitterMs === 'number' ? task.schedule.jitterMs : 0, ...(next ? { nextRunAt: new Date(next).toISOString() } : { nextRunAt: undefined }), }, }; } /** Update only user-editable fields while preserving scheduler cursors, stats and creation time. */ export async function patchTask( patch: CronTaskPatch, ): Promise { return await updateTask(patch.id, (current) => { if ( patch.expectedRevision !== undefined && patch.expectedRevision !== (current.revision ?? 0) ) throw new Error('任务已被其他操作更新,请刷新后再编辑。'); const nextSchedule = patch.schedule ? patch.schedule.type === 'once' ? { type: 'once' as const, at: patch.schedule.at, human: `一次 · ${patch.schedule.at}`, } : patch.schedule.type === 'cron' ? { ...current.schedule, type: 'cron' as const, cron: patch.schedule.cron, timezone: patch.schedule.timezone, jitterMs: patch.schedule.jitterMs ?? 0, human: cronToHuman(patch.schedule.cron), } : { ...current.schedule, type: 'interval' as const, intervalMs: patch.schedule.intervalMs, anchorAt: patch.schedule.anchorAt ?? (current.schedule.type === 'interval' ? current.schedule.anchorAt : new Date().toISOString()), jitterMs: patch.schedule.jitterMs ?? 0, human: intervalToHuman(patch.schedule.intervalMs), } : current.schedule; const runtime = patch.runtime ? { ...current.runtime, ...patch.runtime, sessionMode: patch.runtime.sessionMode ?? current.runtime.sessionMode, bindingStatus: patch.runtime.sessionId && !patch.runtime.sessionId.startsWith('cron-') ? ('bound' as const) : current.runtime.bindingStatus, } : { ...current.runtime }; if (runtime.sessionMode === 'fresh') runtime.bindingStatus = 'bound'; if (patch.clearMaxTurns) runtime.maxTurns = undefined; if ( (patch.status ?? current.status) === 'active' && runtime.bindingStatus !== 'bound' ) throw new Error('请先重新绑定工作目录会话'); const identity = (schedule: CronTask['schedule']) => JSON.stringify( schedule.type === 'once' ? [schedule.type, schedule.at] : schedule.type === 'cron' ? [ schedule.type, schedule.cron, schedule.timezone, schedule.jitterMs ?? 0, ] : [ schedule.type, schedule.intervalMs, schedule.anchorAt, schedule.jitterMs ?? 0, ], ); const changed = identity(nextSchedule) !== identity(current.schedule); const executionChanged = changed || (patch.action !== undefined && JSON.stringify(patch.action) !== JSON.stringify(current.action)) || JSON.stringify(runtime) !== JSON.stringify(current.runtime) || (patch.kind !== undefined && patch.kind !== current.kind) || (patch.maxRuns !== undefined && patch.maxRuns !== current.maxRuns) || patch.clearMaxRuns; const reactivating = patch.status === 'active' && current.status !== 'active'; if ( nextSchedule.type === 'once' && (patch.status ?? current.status) === 'active' && (changed || reactivating) && Date.parse(nextSchedule.at) <= Date.now() ) throw new Error( '重新启用一次性任务时,请设置未来的执行时间;立即执行请使用运行按钮。', ); if (changed || (reactivating && nextSchedule.type !== 'once')) { nextSchedule.lastScheduledFor = new Date().toISOString(); if (nextSchedule.type === 'once') nextSchedule.lastScheduledFor = undefined; } else nextSchedule.lastScheduledFor = current.schedule.lastScheduledFor; return { ...current, version: 2, planId: executionChanged ? randomUUID() : (current.planId ?? current.id), ...(patch.catchUp ? { catchUp: patch.catchUp } : {}), ...(patch.notifications ? { notifications: patch.notifications } : {}), ...(patch.name !== undefined ? { name: patch.name.trim() } : {}), ...(patch.description !== undefined ? patch.description.trim() ? { description: patch.description.trim() } : { description: undefined } : {}), ...(patch.status !== undefined ? { status: patch.status } : {}), ...(patch.schedule ? { kind: patch.schedule.type === 'once' ? ('once' as const) : (patch.kind ?? ('recurring' as const)), } : patch.kind !== undefined ? { kind: patch.kind } : {}), ...(patch.permanent !== undefined ? { permanent: patch.permanent || undefined } : {}), ...(patch.expiresAt !== undefined ? { expiresAt: patch.expiresAt || undefined } : {}), ...(patch.maxRuns !== undefined ? { maxRuns: patch.maxRuns || undefined } : {}), ...(patch.clearMaxRuns ? { maxRuns: undefined } : {}), schedule: nextSchedule, ...(patch.action ? { action: patch.action } : {}), runtime, }; }); }