import { getWorkingDir } from '../../../src/plugin-sdk.js'; import { formatDateTime } from './cronTime.js'; import { createTask, deleteTask, getTask, listMissed, listTasks, recentRuns, } from './store.js'; import type { CronTask } from './types.js'; import type { Scheduler } from './scheduler.js'; import { validateCron, validateIsoDate } from './schema.js'; import { requestRun, requestStop } from './requests.js'; import { createCronFromDraft, updateCronFromPatch } from './service.js'; export interface CronCommandContext { cwd: string; sessionId?: string; } export async function handleCronCommand( commandName: string, args: string, scheduler: Scheduler | null, context?: CronCommandContext, ): Promise { if (commandName === 'crons') return await formatTaskList(await listTasks()); const argv = tokenize(args); const action = argv.shift() ?? 'list'; if (action === 'list') return await formatTaskList(await listTasks()); if (action === 'create') return await createFromArgs(argv, context); if (action === 'pause' || action === 'resume') return await setStatus(argv[0], action === 'resume' ? 'active' : 'paused'); if (action === 'delete' || action === 'remove') return await remove(argv[0]); if (action === 'show') return await show(argv[0]); if (action === 'run') return await runNow(argv[0], scheduler); if (action === 'stop') { if (!argv[0]) return '请提供任务 id。'; const task = await getTask(argv[0]); if (!task) return '未找到任务'; await requestStop(task.id); await scheduler?.stopTaskNow(task.id); return `已请求停止本次执行 ${task.id},后续计划不变。`; } if (action === 'missed') return await formatMissed(); if (action === 'help') return helpText(); const shortcut = await createFromShortcut(action, argv, context); if (shortcut) return shortcut; if (/^\d+\S*$/.test(action)) { return `无效间隔:${action}。支持 1m、2h、1d、1w(最小 1 分钟)。`; } return `未知 /cron 子命令:${action}\n\n${helpText()}`; } async function createFromArgs( argv: string[], context?: CronCommandContext, ): Promise { const opts = parseOptions(argv); const cron = opts.cron; const at = opts.at; const intervalMs = opts.interval ? parseIntervalShortcut(opts.interval) : undefined; const name = opts.name; const prompt = opts.prompt; const workflow = opts.workflow; if ((!cron && !at && !intervalMs) || !name || (!prompt && !workflow)) { return helpText(); } const cronValidation = cron ? validateCron(cron) : { ok: true as const }; if (!cronValidation.ok) { return `无效 cron 表达式:${cron}\n${cronValidation.error}`; } if (at && (!Number.isFinite(Date.parse(at)) || Date.parse(at) <= Date.now())) return 'at 必须是未来的 ISO 日期时间。'; const timezone = opts.timezone ?? Intl.DateTimeFormat().resolvedOptions().timeZone; try { new Intl.DateTimeFormat('en', { timeZone: timezone }).format(); } catch { return '无效的 IANA 时区'; } if ( [cron, at, opts.interval].filter(Boolean).length !== 1 || [prompt, workflow].filter(Boolean).length !== 1 ) return '必须且只能指定一种计划和一种执行内容'; if (!opts.session && !context?.sessionId && opts.freshSession !== 'true') return '缺少当前会话;请指定 --session 或 --fresh-session,不能自动绑定 default。'; const maxTurns = opts.maxTurns ? Number(opts.maxTurns) : undefined; if (opts.maxTurns && (!Number.isInteger(maxTurns) || maxTurns! <= 0)) { return `无效 maxTurns:${opts.maxTurns}`; } const maxRuns = opts.maxRuns ? Number(opts.maxRuns) : undefined; if (opts.maxRuns && (!Number.isInteger(maxRuns) || maxRuns! <= 0)) { return `无效 max-runs:${opts.maxRuns}(须是正整数,跑满这么多次后自动完成)`; } if (opts.expiresAt) { const expiresAtValidation = validateIsoDate(opts.expiresAt, 'expires-at'); if (!expiresAtValidation.ok) return expiresAtValidation.error; } const task = createTask({ name, ...(opts.description ? { description: opts.description } : {}), cron, at, intervalMs: intervalMs ?? undefined, timezone, sessionId: opts.session ?? context?.sessionId, catchUp: opts.catchUp === 'latest' ? 'latest' : 'skip', notifications: opts.notifications === 'failures' ? 'failures' : 'all', cwd: context?.cwd ?? getWorkingDir(), ...(opts.model ? { model: opts.model } : {}), ...(maxTurns ? { maxTurns } : {}), kind: opts.once === 'true' ? 'once' : 'recurring', ...(opts.permanent === 'true' ? { permanent: true } : {}), ...(opts.expiresAt ? { expiresAt: opts.expiresAt } : {}), ...(maxRuns ? { maxRuns } : {}), sessionMode: opts.freshSession === 'true' ? 'fresh' : 'persistent', action: workflow ? { type: 'workflow', command: workflow } : { type: 'prompt', prompt: prompt! }, }); await saveCommandTask(task); return `已创建 cron:${task.id}\n${await formatTask(task)}`; } async function createFromShortcut( head: string, rest: string[], context?: CronCommandContext, ): Promise { const parsed = parseShortcutSchedule(head, rest); if (!parsed) return null; if ('error' in parsed) return parsed.error; if (!context?.sessionId) return '缺少当前会话;请指定 --session 或 --fresh-session,不能自动绑定 default。'; const task = createTask({ name: parsed.name, ...(parsed.description ? { description: parsed.description } : {}), ...(parsed.cron ? { cron: parsed.cron } : {}), ...(parsed.intervalMs ? { intervalMs: parsed.intervalMs, anchorAt: new Date().toISOString() } : {}), timezone: Intl.DateTimeFormat().resolvedOptions().timeZone || 'local', cwd: context.cwd, sessionId: context.sessionId, action: parsed.action, }); await saveCommandTask(task); return `已创建 cron:${task.id}\n${await formatTask(task)}`; } async function saveCommandTask(task: CronTask): Promise { const schedule = task.schedule.type === 'once' ? { type: 'once' as const, at: task.schedule.at } : task.schedule.type === 'cron' ? { type: 'cron' as const, cron: task.schedule.cron, timezone: task.schedule.timezone, } : { type: 'interval' as const, intervalMs: task.schedule.intervalMs, anchorAt: task.schedule.anchorAt, }; const { environment, bindingStatus, ...runtime } = task.runtime; const saved = await createCronFromDraft({ name: task.name, description: task.description, status: task.status, kind: task.kind, catchUp: task.catchUp, notifications: task.notifications, permanent: task.permanent, expiresAt: task.expiresAt, maxRuns: task.maxRuns, schedule, runtime, action: task.action, }); Object.assign(task, saved); } export function parseShortcutSchedule( head: string, rest: string[], ): | ({ cron?: string; intervalMs?: number; } & { action: CronTask['action']; description?: string; name: string; }) | { error: string } | null { const intervalMs = parseIntervalShortcut(head); let actionTokens = rest; let cron: string | undefined; if (head.trim().split(/\s+/).length === 5 && validateCron(head).ok) { cron = head; } else if (!intervalMs) { const time = rest[0]; if (!time) return null; const parsedTime = parseClockTime(time); if (!parsedTime) return null; actionTokens = rest.slice(1); const { hour, minute } = parsedTime; const cronTime = `${minute} ${hour}`; if (head === '每天' || head === '每日') cron = `${cronTime} * * *`; else if (head === '工作日') cron = `${cronTime} * * 1-5`; else { const weekly = head.match(/^每周([一二三四五六日天])$/); if (!weekly) return null; cron = `${cronTime} * * ${weekdayNumber(weekly[1]!)}`; } } const parsedAction = parseShortcutAction(actionTokens); if ('error' in parsedAction) return parsedAction; return { ...(cron ? { cron } : {}), ...(intervalMs ? { intervalMs } : {}), ...parsedAction, }; } export function parseIntervalShortcut(text: string): number | null { const match = text.match(/^(\d+)(m|min|分钟|h|小时|d|天|w|周)$/i); if (!match) return null; const value = Number.parseInt(match[1]!, 10); if (!Number.isFinite(value) || value <= 0) return null; const unit = match[2]!.toLowerCase(); const multiplier = unit === 'w' || unit === '周' ? 7 * 24 * 60 * 60_000 : unit === 'd' || unit === '天' ? 24 * 60 * 60_000 : unit === 'h' || unit === '小时' ? 60 * 60_000 : 60_000; const intervalMs = value * multiplier; return Number.isSafeInteger(intervalMs) && intervalMs >= 60_000 ? intervalMs : null; } function parseShortcutAction( tokens: string[], ): | { action: CronTask['action']; description?: string; name: string } | { error: string } { if (tokens.length === 0) { return { error: '请在时间后面写提示词或 workflow。\n例如:/cron 1d /workflow research 生成中文新闻稿', }; } const markerIndex = tokens.findIndex( (token) => token === '/workflow' || token === 'workflow', ); if (markerIndex < 0) { const prompt = tokens.join(' ').trim(); return { action: { type: 'prompt', prompt }, name: deriveName(prompt) }; } const workflowName = tokens[markerIndex + 1]; if (!workflowName) return { error: 'workflow 标记后缺少工作流名称。' }; const description = tokens.slice(0, markerIndex).join(' ').trim(); const command = serializeTokens(tokens.slice(markerIndex + 1)); return { action: { type: 'workflow', command }, ...(description ? { description } : {}), name: description || deriveName(workflowName.replace(/\.ya?ml$/i, '')), }; } function serializeTokens(tokens: string[]): string { return tokens .map((token) => (/\s|["'\\]/.test(token) ? JSON.stringify(token) : token)) .join(' '); } function parseClockTime(text: string): { hour: number; minute: number } | null { const match = text.match(/^(\d{1,2})[::](\d{1,2})$/); if (!match) return null; const hour = Number.parseInt(match[1]!, 10); const minute = Number.parseInt(match[2]!, 10); if (hour < 0 || hour > 23 || minute < 0 || minute > 59) return null; return { hour, minute }; } function weekdayNumber(day: string): number { return ( ( { 日: 0, 天: 0, 一: 1, 二: 2, 三: 3, 四: 4, 五: 5, 六: 6 } as Record< string, number > )[day] ?? 1 ); } function deriveName(prompt: string): string { const compact = prompt.replace(/\s+/g, ' ').trim(); return compact.length > 18 ? `${compact.slice(0, 18)}...` : compact || 'cron task'; } async function setStatus( id: string | undefined, status: CronTask['status'], ): Promise { if (!id) return '请提供任务 id。'; const task = await getTask(id); if (!task) return `未找到任务:${id}`; await updateCronFromPatch({ id: task.id, status }); return `已${status === 'active' ? '恢复' : '暂停'} ${task.id}`; } async function remove(id: string | undefined): Promise { if (!id) return '请提供任务 id。'; const task = await getTask(id); if (!task) return `未找到任务:${id}`; await requestStop(task.id); return (await deleteTask(task.id)) ? `已删除 ${id}` : `未找到任务:${id}`; } async function show(id: string | undefined): Promise { if (!id) return '请提供任务 id。'; const task = await getTask(id); if (!task) return `未找到任务:${id}`; const runs = await recentRuns(task.id, 5); const runLines = runs.length === 0 ? '最近运行:无' : `最近运行:\n${runs.map((r) => `- ${formatDateTime(r.startedAt)} ${r.status}${r.error ? ` · ${r.error}` : ''}`).join('\n')}`; return `${await formatTask(task)}\n${runLines}`; } async function runNow( id: string | undefined, scheduler: Scheduler | null, ): Promise { if (!id) return '请提供任务 id。'; if (!scheduler) return 'cron scheduler 尚未启动;请在 TUI 中运行。'; const task = await getTask(id); if (!task) return `未找到任务:${id}`; const run = await requestRun(task.id); scheduler.wake(); return `已加入执行队列 ${task.id}(${run.id}),使用 /cron show 查看结果。`; } async function formatMissed(): Promise { const missed = await listMissed(20); if (missed.length === 0) return '暂无错过任务。'; return [ '错过任务:', ...missed.map( (m) => `- ${m.taskId} · ${m.taskName} · ${m.reason === 'overlap' ? '运行重叠' : m.reason === 'binding_unavailable' ? '会话绑定失效' : '宿主离线'}跳过 ${m.missedCount} 次 · 计划 ${formatDateTime(m.scheduledFor)} · ${m.actionPreview}`, ), ].join('\n'); } async function formatTaskList(tasks: CronTask[]): Promise { if (tasks.length === 0) return '暂无 cron 任务。'; const missed = await listMissed(1); const header = missed.length > 0 ? `提示:有错过任务,可用 /cron missed 查看。\n\n` : ''; const body = await Promise.all(tasks.map(formatTask)); return `${header}${body.join('\n\n')}`; } async function formatTask(task: CronTask): Promise { const action = task.action.type === 'workflow' ? `/workflow ${task.action.command}` : task.action.prompt; const runs = await recentRuns(task.id, 1); const recent = runs[0] ? `${runs[0].status}${runs[0].error ? ` · ${runs[0].error}` : ''}` : '-'; return [ `${task.id} · ${task.name}`, `状态:${task.status === 'active' ? '活跃' : task.status === 'completed' ? '已完成' : '暂停'}`, `类型:${task.kind === 'once' ? '一次性' : task.maxRuns ? `限 ${task.maxRuns} 次` : '重复'}`, `下次运行:${formatDateTime(task.schedule.nextRunAt)}`, `上次运行时间:${formatDateTime(task.stats.lastRunAt)}`, `详情:${task.description ?? '-'}`, `运行环境:${task.runtime.environment}`, `项目:${task.runtime.cwd}`, `重复次数:${task.stats.runCount}${task.maxRuns ? `/${task.maxRuns}(跑满自动完成)` : ''}`, `跳过次数:${task.stats.skippedCount}`, `会话:${task.runtime.sessionMode === 'fresh' ? '每次全新' : '持续会话'}`, `模型:${task.runtime.model ?? '-'}`, `最近结果:${recent}`, `计划:${task.schedule.human} (${task.schedule.type === 'cron' ? `${task.schedule.cron}, ${task.schedule.timezone}` : task.schedule.type === 'once' ? task.schedule.at : `锚点 ${formatDateTime(task.schedule.anchorAt)}`})`, `动作:${action}`, ].join('\n'); } function helpText(): string { return [ '用法:', '/cron 120m 整理最近 AI 新闻', '/cron 1d 整理每日国际新闻 /workflow research 今天的国际 AI 大事', '/cron 1m 检查学生作业 workflow plan 摄像头画面在 camera.jpg', '/cron 每天 6:07 写国际 AI 晨间简报', '/cron 工作日 6:07 写过去 48 小时国际 AI 大事', '/cron 每周一 6:07 整理国际 AI 超级个体创业案例', '/cron create --name "晨间简报" --cron "7 6 * * 2-6,0" --prompt "写国际 AI 简报"', '/cron create --name "提醒" --cron "5 13 * * *" --prompt "执行提醒" --once', '/cron create --name "周报" --cron "7 6 * * 1" --workflow "plan \\"整理周报\\"" --permanent', '/cron create --name "定时调研" --cron "0 */2 * * *" --workflow "research 竞品动态" --max-runs 5', '/cron create --name "独立日报" --cron "7 6 * * *" --workflow "research 今日要闻" --fresh-session', '/cron create --name "提醒" --at "2027-01-01T09:00:00+08:00" --prompt "执行提醒" --fresh-session', '/cron create --name "巡检" --interval 2h --prompt "检查服务" --catch-up latest --fresh-session', '高级参数:--timezone Asia/Shanghai --session <会话ID> --notifications all|failures', '/cron list', '/cron pause ', '/cron resume ', '/cron run ', '/cron stop ', '/cron show ', '/cron missed', '/cron delete ', ].join('\n'); } function tokenize(input: string): string[] { const out: string[] = []; let cur = ''; let quote: '"' | "'" | null = null; for (let i = 0; i < input.length; i++) { const ch = input[i]!; if (quote) { if ( ch === '\\' && i + 1 < input.length && (input[i + 1] === quote || input[i + 1] === '\\') ) { cur += input[++i]!; } else if (ch === quote) { quote = null; } else { cur += ch; } continue; } if (ch === '"' || ch === "'") { quote = ch; continue; } if (/\s/.test(ch)) { if (cur) { out.push(cur); cur = ''; } continue; } cur += ch; } if (quote) throw new Error('命令引号未闭合'); if (cur) out.push(cur); return out; } function parseOptions(argv: string[]): Record { const map: Record = {}; for (let i = 0; i < argv.length; i++) { const key = argv[i]!; if (!key.startsWith('--')) throw new Error(`无效参数:${key}`); const allowed = [ 'name', 'description', 'cron', 'at', 'interval', 'prompt', 'workflow', 'timezone', 'session', 'catchUp', 'notifications', 'model', 'maxTurns', 'once', 'permanent', 'expiresAt', 'maxRuns', 'freshSession', ]; const name = toCamel(key.slice(2)); if (!allowed.includes(name) || name in map) throw new Error(`未知或重复参数:${key}`); const value = argv[i + 1]; if (!value || value.startsWith('--')) { if (!['once', 'permanent', 'freshSession'].includes(name)) throw new Error(`参数缺少值:${key}`); map[toCamel(key.slice(2))] = 'true'; continue; } map[toCamel(key.slice(2))] = value; i++; } if (map.catchUp && !['skip', 'latest'].includes(map.catchUp)) throw new Error('catch-up 必须是 skip 或 latest'); if (map.notifications && !['all', 'failures'].includes(map.notifications)) throw new Error('notifications 必须是 all 或 failures'); if (map.session && map.freshSession) throw new Error('session 与 fresh-session 不能同时指定'); return map; } function toCamel(s: string): string { return s.replace(/-([a-z])/g, (_, c: string) => c.toUpperCase()); }