import { randomUUID } from 'node:crypto'; import { existsSync } from 'node:fs'; import { join } from 'node:path'; import type { PluginRuntimeContext } from '../../../src/plugin-sdk.js'; import { resolveSessionFile, createSessionState, disposeDetachedSessionState, } from '../../../src/plugin-sdk.js'; import { releaseSchedulerLock, tryAcquireSchedulerLock } from './lock.js'; import { countScheduleSlots, latestScheduleRunMs, nextScheduleRunMs, } from './scheduleEngine.js'; import { appendMissed, activeRuns, appendRun, cronDataRoot, cronLockFile, getTask, listTasks, recentRuns, subscribeTaskChanges, updateTask, } from './store.js'; import { listRunTaskIds } from './runs.js'; import { enqueueRun, requestRun, requestStop, stopRequested, } from './requests.js'; import type { CronRunRecord, CronTask } from './types.js'; import { taskTransaction } from './transaction.js'; import { executionOutcome } from '../../../src/session/executionOutcome.js'; import { backgroundCompletionFields } from '../../../src/runtime/backgroundCompletion.js'; export const RECONCILE_MS = 1_000; export function boundedWakeDelay(at: number, now = Date.now()): number { return Math.min(RECONCILE_MS, Math.max(0, at - now)); } /** One owner per state root; all hosts submit the same durable requests. */ export class Scheduler { private dueTimer: ReturnType | null = null; private reconcileTimer: ReturnType | null = null; private unsubscribeStore: (() => void) | null = null; private readonly executions = new Map>(); private readonly controllers = new Map(); private readonly activeRuns = new Map(); private executionController = new AbortController(); private readonly owner = `cron-runner-${process.pid}-${randomUUID()}`; private ownsLock = false; private started = false; private stopping = false; private tick: Promise | null = null; private stopPromise: Promise | null = null; constructor( private readonly ctx: PluginRuntimeContext, private readonly limits = { concurrency: 4, timeoutMs: 10 * 60_000 }, ) { if ( !Number.isInteger(limits.concurrency) || limits.concurrency < 1 || !Number.isFinite(limits.timeoutMs) || limits.timeoutMs < 1 ) throw new Error('无效的调度并发或超时限制'); } start(): void { if (this.started) return; this.started = true; this.stopping = false; this.stopPromise = null; this.executionController = new AbortController(); this.unsubscribeStore = subscribeTaskChanges(() => this.wake()); this.reconcileTimer = setInterval(() => this.wake(), RECONCILE_MS); this.reconcileTimer.unref?.(); this.wake(); } async stop(): Promise { if (this.stopPromise) return this.stopPromise; this.started = false; this.stopping = true; this.executionController.abort('调度宿主停止'); if (this.dueTimer) clearTimeout(this.dueTimer); if (this.reconcileTimer) clearInterval(this.reconcileTimer); this.unsubscribeStore?.(); this.stopPromise = (async () => { await this.tick; await Promise.allSettled([...this.executions.values()]); if (this.ownsLock) await releaseSchedulerLock(cronLockFile(), this.owner); this.ownsLock = false; })(); return this.stopPromise; } async runTaskNow(id: string): Promise { if (this.stopping) throw new Error('调度器正在停止'); const temporary = !this.started; try { await requestRun(id); await this.reconcile(); await this.executions.get(id); } finally { if (temporary) { await Promise.allSettled([...this.executions.values()]); if (this.dueTimer) clearTimeout(this.dueTimer); if (this.ownsLock) await releaseSchedulerLock(cronLockFile(), this.owner); this.ownsLock = false; } } } async stopTaskNow(id: string): Promise { await requestStop(id); this.controllers.get(id)?.abort('用户停止本次执行'); this.wake(); } async isActiveScheduler(): Promise { return this.ownsLock; } wake(): void { if (this.stopping) return; void this.reconcile().catch((error) => console.error('[cron-runner] 调度失败,保留状态并等待重试:', error), ); } private reconcile(): Promise { if (this.tick) return this.tick; this.tick = this.reconcileOnce().finally(() => { this.tick = null; }); return this.tick; } private async reconcileOnce(): Promise { if (this.stopping) return; // Deleted schedules no longer appear in listTasks, but their stop requests still apply. for (const [id, run] of this.activeRuns) if (await stopRequested(run.id)) this.controllers.get(id)?.abort('用户停止本次执行'); if (!this.ownsLock) { this.ownsLock = await tryAcquireSchedulerLock( cronLockFile(), this.owner, () => { this.ownsLock = false; this.executionController.abort('调度租约丢失'); // Never reacquire while old work may still be executing. void this.stop(); }, ); if (!this.ownsLock) return; await this.recover(); await this.recordMissedTasks(); } if (this.stopping) return; const tasks = await listTasks(); for (const task of tasks) { await this.processDueTask(task, Date.now()); const runs = await activeRuns(task.id); for (const run of runs) { if (run.status === 'running' && (await stopRequested(run.id))) this.controllers.get(task.id)?.abort('用户停止本次执行'); } if (this.executions.has(task.id)) continue; const queued = runs.filter((r) => r.status === 'queued').at(-1); if (queued && this.executions.size < this.limits.concurrency) this.launchTask(task, queued); } const ids = new Set(tasks.map((t) => t.id)); for (const id of await listRunTaskIds(join(cronDataRoot(), 'runs'))) if (!ids.has(id)) { for (const run of await activeRuns(id)) if (run.status === 'queued') await appendRun({ ...run, status: 'cancelled', finishedAt: new Date().toISOString(), error: '计划已删除', }); } await this.armNextTimer(); } private async recover(): Promise { for (const id of await listRunTaskIds(join(cronDataRoot(), 'runs'))) { for (const run of await recentRuns(id, Infinity)) { if (run.status === 'running') await appendRun({ ...run, status: 'interrupted', finishedAt: new Date().toISOString(), attentionReason: 'failure', error: '上次宿主退出,执行结果未知。请检查会话和产物后决定是否重跑。', }); else if (run.status === 'queued' && !(await getTask(id))) await appendRun({ ...run, status: 'cancelled', finishedAt: new Date().toISOString(), error: '计划已删除', }); } const task = await getTask(id); if (task) { const runs = await recentRuns(id, Infinity); const successes = runs.filter((r) => r.status === 'success').length; const failures = runs.filter( (r) => r.status === 'failure' && r.owner, ).length; const currentPlanFinished = runs.some( (r) => (r.planId ?? r.snapshot?.planId ?? r.taskId) === (task.planId ?? task.id) && (r.status === 'success' || (r.status === 'failure' && r.owner)), ); if ( successes > task.stats.successCount || failures > task.stats.failureCount ) await updateTask(id, (t) => { const successCount = Math.max(t.stats.successCount, successes); const failureCount = Math.max(t.stats.failureCount, failures); const runCount = Math.max( t.stats.runCount, successCount + failureCount, ); return { ...t, ...((t.planId === task.planId && t.kind === 'once' && currentPlanFinished) || (t.planId === task.planId && t.maxRuns && runCount >= t.maxRuns) ? { status: 'completed' as const } : {}), stats: { ...t.stats, runCount, successCount, failureCount }, }; }); } } } private lastProcessedMs(task: CronTask): number { return Date.parse(task.schedule.lastScheduledFor ?? task.createdAt); } private async processDueTask(task: CronTask, now: number): Promise { return taskTransaction(cronDataRoot(), task.id, async () => { const current = await getTask(task.id); if ( !current || (current.planId ?? current.id) !== (task.planId ?? task.id) ) return; task = current; if (task.status !== 'active' || task.runtime.bindingStatus !== 'bound') return; if ( task.expiresAt && !task.permanent && Date.parse(task.expiresAt) <= now ) return; const latest = latestScheduleRunMs( task.schedule, now - (task.schedule.jitterMs ?? 0), ); const base = this.lastProcessedMs(task); if (latest === null || latest <= base) return; const count = countScheduleSlots(task.schedule, base, latest); const busy = this.executions.has(task.id) || (await activeRuns(task.id)).some( (r) => r.status === 'queued' || r.status === 'running', ); if (busy) { await this.markMissed(task, latest, count, 'overlap'); return; } // Persist before advancing the cursor. A crash in between deduplicates by slot ID. await enqueueRun(task, undefined, new Date(latest).toISOString()); if (count > 1) await this.appendMissed(task, latest, count - 1, 'offline'); await updateTask(task.id, (current) => ({ ...current, schedule: { ...current.schedule, lastScheduledFor: new Date(latest).toISOString(), lastFiredAt: new Date().toISOString(), }, stats: { ...current.stats, skippedCount: current.stats.skippedCount + Math.max(0, count - 1), }, })); }); } private async recordMissedTasks(): Promise { const now = Date.now(); for (const snapshot of await listTasks()) { await taskTransaction(cronDataRoot(), snapshot.id, async () => { const task = await getTask(snapshot.id); if (!task || task.status !== 'active' || task.catchUp === 'latest') return; const latest = latestScheduleRunMs( task.schedule, now - (task.schedule.jitterMs ?? 0), ); if (latest === null || latest <= this.lastProcessedMs(task)) return; // Do not discard a slot already durably queued before a crash. if ( (await recentRuns(task.id, Infinity)).some( (r) => r.scheduledFor === new Date(latest).toISOString() && (r.planId ?? r.snapshot?.planId ?? task.id) === (task.planId ?? task.id), ) ) { await updateTask(task.id, (t) => ({ ...t, schedule: { ...t.schedule, lastScheduledFor: new Date(latest).toISOString(), }, })); return; } await this.markMissed( task, latest, countScheduleSlots(task.schedule, this.lastProcessedMs(task), latest), 'offline', ); }); } } private async markMissed( task: CronTask, latest: number, count: number, reason: 'offline' | 'overlap', ): Promise { return taskTransaction(cronDataRoot(), task.id, async () => { const current = await getTask(task.id); if ( !current || current.planId !== task.planId || current.status !== 'active' ) return; await this.appendMissed(task, latest, count, reason); await updateTask(task.id, (t) => ({ ...t, ...(t.kind === 'once' ? { status: 'paused' as const } : {}), schedule: { ...t.schedule, lastScheduledFor: new Date(latest).toISOString(), }, stats: { ...t.stats, skippedCount: t.stats.skippedCount + count }, })); }); } private async appendMissed( task: CronTask, latest: number, count: number, reason: 'offline' | 'overlap', ): Promise { await appendMissed({ id: `missed-${task.id}-${latest}`, taskId: task.id, taskName: task.name, scheduledFor: new Date(latest).toISOString(), detectedAt: new Date().toISOString(), actionPreview: task.action.type === 'prompt' ? task.action.prompt : `/workflow ${task.action.command}`, reason, missedCount: count, }); } private async armNextTimer(): Promise { if (this.stopping) return; if (this.dueTimer) clearTimeout(this.dueTimer); let earliest = Date.now() + RECONCILE_MS; for (const t of await listTasks()) if (t.status === 'active' && t.runtime.bindingStatus === 'bound') { const next = nextScheduleRunMs(t.schedule, this.lastProcessedMs(t)); if (next !== null) earliest = Math.min(earliest, next + (t.schedule.jitterMs ?? 0)); } this.dueTimer = setTimeout( () => this.wake(), Math.max(25, boundedWakeDelay(earliest)), ); this.dueTimer.unref?.(); } private launchTask(task: CronTask, run: CronRunRecord): void { const controller = new AbortController(); this.controllers.set(task.id, controller); this.activeRuns.set(task.id, run); const promise = this.runTask(task, run, controller) .catch((error) => { console.error(`[cron-runner] 无法持久化执行 ${run.id}:`, error); }) .finally(() => { this.controllers.delete(task.id); this.executions.delete(task.id); this.activeRuns.delete(task.id); }); this.executions.set(task.id, promise); } private async runTask( task: CronTask, run: CronRunRecord, controller: AbortController, ): Promise { const claimed = await taskTransaction(cronDataRoot(), task.id, async () => { if ( !(await getTask(task.id)) || (await stopRequested(run.id)) || !run.snapshot ) { await appendRun({ ...run, status: 'cancelled', finishedAt: new Date().toISOString(), error: !run.snapshot ? '旧队列缺少执行快照,请核实后重新运行' : '计划已删除或执行已停止', }); return false; } run = { ...run, owner: this.owner, status: 'running' }; await appendRun(run); return true; }); if (!claimed) return; task = run.snapshot!; if (await stopRequested(run.id)) { await appendRun({ ...run, status: 'cancelled', finishedAt: new Date().toISOString(), }); return; } if ( task.runtime.sessionMode !== 'fresh' && !existsSync( await resolveSessionFile(task.runtime.cwd, task.runtime.sessionId), ) ) { await updateTask(task.id, (t) => t.planId !== task.planId ? t : { ...t, status: 'paused', runtime: { ...t.runtime, bindingStatus: 'needs_binding' }, }, ); await appendMissed({ id: `missing-${run.id}`, taskId: task.id, taskName: task.name, scheduledFor: run.scheduledFor ?? run.startedAt, detectedAt: new Date().toISOString(), actionPreview: '绑定会话不存在', reason: 'binding_unavailable', missedCount: 1, }); await appendRun({ ...run, status: 'failure', error: '绑定会话不存在,请重新绑定', attentionReason: 'failure', finishedAt: new Date().toISOString(), }); return; } const timeout = new AbortController(); const timer = setTimeout( () => timeout.abort('计划执行超时'), this.limits.timeoutMs, ); const signal = AbortSignal.any([ controller.signal, timeout.signal, this.executionController.signal, ...(this.ctx.signal ? [this.ctx.signal] : []), ]); const started = Date.now(); this.notify( `定时任务开始:${task.name} · ${run.id} · 会话 ${run.sessionId}`, ); let result = ''; let error: string | undefined; let ok = false; let outcome = executionOutcome([]); const executionState = createSessionState(); try { const response = await this.ctx.runAgentTurn({ executionId: run.id, input: task.action.type === 'workflow' ? `/workflow ${task.action.command}` : task.action.prompt, provider: this.ctx.provider, cwd: run.cwd, sessionId: run.sessionId, maxTurns: task.runtime.maxTurns, model: task.runtime.model, signal, sessionState: executionState, }); result = response.result; outcome = executionOutcome(response.events); const background = backgroundCompletionFields( executionState.backgroundTasks, ); if (background.pendingBackground?.length) { outcome = { ...outcome, completionStatus: 'delivery_incomplete', error: '仍有后台任务未收口;定时回合结束时将停止残留进程,请在任务内等待并核实结果', }; } error = response.error ?? outcome.error; ok = response.ok && !error; } catch (cause) { error = cause instanceof Error ? cause.message : String(cause); } finally { clearTimeout(timer); await disposeDetachedSessionState(executionState); } const status = timeout.signal.aborted ? 'failure' : signal.aborted ? 'cancelled' : ok ? 'success' : 'failure'; const finishedAt = new Date().toISOString(); await appendRun({ ...run, status, finishedAt, durationMs: Date.now() - started, result, resultPreview: result.slice(0, 1000), completionStatus: outcome.completionStatus, managedStatus: outcome.managedStatus, error: signal.aborted ? String(signal.reason) : error, ...(status === 'failure' ? { attentionReason: 'failure' as const } : {}), }); if (task.notifications === 'all' || status !== 'success') this.notify( `定时任务${status === 'success' ? '完成' : status === 'cancelled' ? '已取消' : '需要处理'}:${task.name} · ${run.id}。/cron show ${task.id} 查看结果${error ? `:${error}` : ''}`, ); // Persistence failures cannot re-enter the execution catch and double-count an attempt. await updateTask(task.id, (t) => ({ ...t, ...(status !== 'cancelled' && (t.planId ?? t.id) === (task.planId ?? task.id) && (t.kind === 'once' || (t.maxRuns && t.stats.runCount + 1 >= t.maxRuns)) ? { status: 'completed' as const } : {}), stats: { ...t.stats, runCount: t.stats.runCount + (status === 'cancelled' ? 0 : 1), successCount: t.stats.successCount + (status === 'success' ? 1 : 0), failureCount: t.stats.failureCount + (status === 'failure' ? 1 : 0), lastRunAt: finishedAt, ...(status === 'success' ? { lastSuccessAt: finishedAt } : status === 'failure' ? { lastFailureAt: finishedAt } : {}), }, })); } private notify(message: string): void { try { this.ctx.notify?.(message); } catch { /* Presentation cannot change execution outcome. */ } } }