import { createHash, randomUUID } from 'node:crypto'; import { parseShortcutSchedule } from './commands.js'; import { validateCron } from './schema.js'; import { createTask, listMissed, listTasks, markMissedRead, markRunsRead, patchTask, recentRuns, upsertTask, } from './store.js'; import type { CronListFilter, CronTask, CronTaskDraft, CronTaskPatch, } from './types.js'; import { cronToHuman } from './cronTime.js'; import { intervalToHuman, nextScheduleRunMs } from './scheduleEngine.js'; import { draftSchema, patchSchema } from './contract.js'; export interface CronDraftContext { cwd: string; sessionId: string; model?: string; sessionMode?: 'persistent' | 'fresh'; } export interface CronDraftResult { requestId: string; task: CronTaskDraft | null; missing: Array<'workspace' | 'session' | 'schedule' | 'action'>; error?: string; scheduleHuman?: string; nextRunAt?: string; } export function draftCronFromText( text: string, context: Partial, requestId: string = randomUUID(), ): CronDraftResult { const normalized = normalizeScheduleText(text); const once = normalized.match(/^(?:at|一次)\s+(\S+)\s+([\s\S]+)$/); if ( once && context.cwd && (context.sessionId || context.sessionMode === 'fresh') ) { const at = new Date(once[1]!); if (!Number.isFinite(at.getTime()) || at.getTime() <= Date.now()) return { requestId, task: null, missing: ['schedule'], error: '一次性时间必须是未来的 ISO 日期时间(带时区)', }; const action = once[2]!.trim(); return { requestId, missing: [], nextRunAt: at.toISOString(), scheduleHuman: `一次 · ${at.toLocaleString()}`, task: { name: action.slice(0, 60), status: 'active', kind: 'once', schedule: { type: 'once', at: at.toISOString() }, action: action.startsWith('/workflow ') ? { type: 'workflow', command: action.slice(10).trim() } : { type: 'prompt', prompt: action }, runtime: { cwd: context.cwd, sessionId: context.sessionId, sessionMode: context.sessionMode ?? 'persistent', model: context.model, }, }, }; } const [head = '', ...rest] = tokenize(normalized.replace(/^\/cron\s*/i, '')); const parsed = parseShortcutSchedule(head, rest); const missing: CronDraftResult['missing'] = []; if (!context.cwd) missing.push('workspace'); if (!context.sessionId && context.sessionMode !== 'fresh') missing.push('session'); if (!head || !parsed) missing.push('schedule'); if (parsed && 'error' in parsed) { if (parsed.error.includes('提示词') || parsed.error.includes('workflow')) missing.push('action'); return { requestId, task: null, missing: unique(missing), error: parsed.error, }; } if ( !parsed || !context.cwd || (!context.sessionId && context.sessionMode !== 'fresh') ) { return { requestId, task: null, missing: unique(missing) }; } const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'local'; const task: CronTaskDraft = { name: parsed.name, ...(parsed.description ? { description: parsed.description } : {}), status: 'active', kind: 'recurring', schedule: parsed.cron ? { type: 'cron', cron: parsed.cron, timezone, jitterMs: 0 } : { type: 'interval', intervalMs: parsed.intervalMs!, anchorAt: new Date().toISOString(), jitterMs: 0, }, action: parsed.action, runtime: { cwd: context.cwd, sessionId: context.sessionId, sessionMode: context.sessionMode ?? 'persistent', ...(context.model ? { model: context.model } : {}), }, }; const previewSchedule = task.schedule.type === 'once' ? { ...task.schedule, human: `一次 · ${task.schedule.at}` } : task.schedule.type === 'cron' ? { ...task.schedule, human: cronToHuman(task.schedule.cron) } : { ...task.schedule, anchorAt: task.schedule.anchorAt!, human: intervalToHuman(task.schedule.intervalMs), }; const next = nextScheduleRunMs(previewSchedule, Date.now()); return { requestId, task, missing: [], scheduleHuman: previewSchedule.human, ...(next ? { nextRunAt: new Date(next).toISOString() } : {}), }; } export async function createCronFromDraft( draft: CronTaskDraft, requestId?: string, ): Promise { draft = draftSchema.parse(draft); assertDraft(draft); if ( draft.status === 'active' && draft.schedule.type === 'once' && Date.parse(draft.schedule.at) <= Date.now() ) throw new Error('一次性任务的执行时间必须在未来。'); const task = createTask({ name: draft.name.trim(), ...(draft.description?.trim() ? { description: draft.description.trim() } : {}), ...(draft.schedule.type === 'once' ? { at: draft.schedule.at, timezone: 'UTC' } : draft.schedule.type === 'cron' ? { cron: draft.schedule.cron, timezone: draft.schedule.timezone } : { intervalMs: draft.schedule.intervalMs, anchorAt: draft.schedule.anchorAt, timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || 'local', }), cwd: draft.runtime.cwd, sessionId: draft.runtime.sessionId, sessionMode: draft.runtime.sessionMode ?? 'persistent', catchUp: draft.catchUp, notifications: draft.notifications, model: draft.runtime.model, maxTurns: draft.runtime.maxTurns, kind: draft.kind, permanent: draft.permanent, expiresAt: draft.expiresAt, maxRuns: draft.maxRuns, jitterMs: draft.schedule.jitterMs ?? 0, action: draft.action, }); task.status = draft.status; if (requestId) task.id = `cron-${createHash('sha256').update(requestId).digest('hex').slice(0, 24)}`; return await upsertTask(task, Boolean(requestId)); } export async function updateCronFromPatch( patch: CronTaskPatch, ): Promise { patch = patchSchema.parse(patch); if (!patch.id) throw new Error('缺少定时任务 ID'); if (patch.schedule?.type === 'cron') { const checked = validateCron(patch.schedule.cron); if (!checked.ok) throw new Error(checked.error); } if (patch.schedule) validateSchedule(patch.schedule); if (patch.name !== undefined && !patch.name.trim()) throw new Error('任务名称不能为空'); if ( patch.action && !( patch.action.type === 'prompt' ? patch.action.prompt : patch.action.command ).trim() ) throw new Error('执行内容不能为空'); for (const value of [patch.maxRuns, patch.runtime?.maxTurns]) if (value !== undefined && (!Number.isInteger(value) || value < 1)) throw new Error('次数必须是正整数'); const task = await patchTask(patch); if (!task) throw new Error(`未找到定时任务:${patch.id}`); if (task.runtime.bindingStatus !== 'bound' && patch.status === 'active') { throw new Error('请先重新绑定工作目录会话'); } return task; } export async function listCronTasks(filter: CronListFilter = {}) { const query = filter.query?.trim().toLocaleLowerCase(); const missed = await listMissed(500); const missedTaskIds = new Set( missed.filter((item) => !item.readAt).map((item) => item.taskId), ); const rows = await Promise.all( (await listTasks()).map(async (task) => { const runs = await recentRuns(task.id, 20); const unreadCount = runs.filter( (run) => !run.readAt && (run.status === 'failure' || run.status === 'interrupted' || run.attentionReason || (task.notifications === 'all' && run.status === 'success')), ).length + (missedTaskIds.has(task.id) ? 1 : 0) + (task.runtime.bindingStatus === 'needs_binding' ? 1 : 0); return { task, recentRuns: runs, unreadCount }; }), ); return rows.filter(({ task, unreadCount }) => { if (filter.cwd && task.runtime.cwd !== filter.cwd) return false; if (filter.sessionId && task.runtime.sessionId !== filter.sessionId) return false; if (filter.status && filter.status !== 'all') { if ( filter.status === 'attention' ? unreadCount === 0 : task.status !== filter.status ) return false; } if (!query) return true; const haystack = [ task.name, task.description, task.action.type === 'prompt' ? task.action.prompt : task.action.command, ] .filter(Boolean) .join(' ') .toLocaleLowerCase(); return haystack.includes(query); }); } export async function markCronRead(taskId?: string): Promise { await Promise.all([markRunsRead(taskId), markMissedRead(taskId)]); } function assertDraft(draft: CronTaskDraft): void { if (!draft.name.trim()) throw new Error('请输入任务名称'); if (!draft.runtime.cwd) throw new Error('请选择工作目录'); if (!draft.runtime.sessionId && draft.runtime.sessionMode !== 'fresh') throw new Error('请选择绑定会话'); validateSchedule(draft.schedule); for (const value of [draft.maxRuns, draft.runtime.maxTurns]) if (value !== undefined && (!Number.isInteger(value) || value < 1)) throw new Error('次数必须是正整数'); if ( draft.action.type === 'prompt' ? !draft.action.prompt.trim() : !draft.action.command.trim() ) { throw new Error('请输入执行内容'); } } function validateSchedule(schedule: CronTaskDraft['schedule']): void { if (schedule.type === 'once') { if (!Number.isFinite(Date.parse(schedule.at))) throw new Error('无效的一次性日期'); } else if (schedule.type === 'cron') { if (schedule.timezone !== 'local') new Intl.DateTimeFormat('en', { timeZone: schedule.timezone }).format(); const checked = validateCron(schedule.cron); if (!checked.ok) throw new Error(checked.error); } else if ( !Number.isFinite(schedule.intervalMs) || schedule.intervalMs < 60_000 ) { throw new Error('固定间隔最短为 1 分钟'); } if ( schedule.type === 'interval' && schedule.anchorAt && !Number.isFinite(Date.parse(schedule.anchorAt)) ) throw new Error('无效的间隔起点'); if ( schedule.jitterMs !== undefined && (!Number.isFinite(schedule.jitterMs) || schedule.jitterMs < 0) ) throw new Error('无效的时间偏移'); } function normalizeScheduleText(value: string): string { let text = value .trim() .replace(/^请(?:帮我)?/u, '') .replace(/每个工作日(?:的)?(?:早上|上午)?\s*/u, '工作日 ') .replace(/每天(?:的)?(?:早上|上午)?\s*/u, '每天 ') .replace(/每周([一二三四五六日天])(?:的)?(?:早上|上午)?\s*/u, '每周$1 ') .replace(/每隔\s*(\d+)\s*分钟/u, '$1m ') .replace(/每隔\s*(\d+)\s*小时/u, '$1h ') .replace(/每隔\s*(\d+)\s*天/u, '$1d ') .replace( /(?:下午|晚上)\s*(\d{1,2})[点时](\d{1,2})?分?/u, (_, h, m) => ` ${Number(h) < 12 ? Number(h) + 12 : h}:${m ?? '00'} `, ) .replace( /(?:上午|早上)?\s*(\d{1,2})[点时](\d{1,2})?分?/u, (_, h, m) => ` ${h}:${m ?? '00'} `, ) .replace( /早上\s*(\d{1,2})[点时](\d{1,2})?分?/u, (_, h, m) => `${h}:${m ?? '00'}`, ) .replace(/(\d{1,2})[点时](\d{1,2})分/u, '$1:$2') .replace(/\s+/g, ' ') .trim(); const tomorrow = text.match(/^明天\s*(\d{1,2}):(\d{1,2})\s+([\s\S]+)$/); if (tomorrow) { const at = new Date(); at.setDate(at.getDate() + 1); at.setHours(Number(tomorrow[1]), Number(tomorrow[2]), 0, 0); text = `at ${at.toISOString()} ${tomorrow[3]}`; } // A raw five-field expression is one schedule token, not five unrelated words. text = text.replace( /^([\d*/,\-]+\s+[\d*/,\-]+\s+[\d*/,\-]+\s+[\d*/,\-]+\s+[\d*/,\-]+)\s+/, '"$1" ', ); return text; } function tokenize(input: string): string[] { return ( input .match(/"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\S+/g) ?.map((item) => item.replace(/^['"]|['"]$/g, '')) ?? [] ); } function unique(items: T[]): T[] { return [...new Set(items)]; }