// The scheduler (lab 09): a clock that turns due jobs into turns. // // A timer is just another event source. When a job is due, the scheduler sends its prompt // through the gateway into the job's OWN session ("steward:cron:"), so scheduled work never // clutters your main conversation, and the per-session queue still applies. The answer is // delivered to you through the outbox and every channel. // // Downtime: on start, a job that came due while Steward was off runs once if it is less than // `catchUpHours` late; older misses are skipped to the next run. import type { Gateway } from '../gateway/gateway.ts'; import { firstRun, type Job, type JobStore } from './job-store.ts'; export interface SchedulerOptions { store: JobStore; gateway: Gateway; timezone: string; catchUpHours: number; now?: () => Date; log?: (line: string) => void; } const MAX_SLEEP_MS = 60_000; export class Scheduler { private readonly options: SchedulerOptions; private readonly now: () => Date; private timer: NodeJS.Timeout | undefined; private running = false; private stopped = false; lastTick: Date | undefined; constructor(options: SchedulerOptions) { this.options = options; this.now = options.now ?? (() => new Date()); } /** Applies the catch-up rule, then starts the timer. */ async start(): Promise { const now = this.now(); const windowMs = this.options.catchUpHours * 3_600_000; const jobs = await this.options.store.list(); let changed = false; for (const job of jobs) { if (!job.enabled || !job.nextRun) continue; const late = now.getTime() - Date.parse(job.nextRun); if (late > windowMs) { changed = true; job.lastStatus = `skipped: missed by ${Math.round(late / 3_600_000)}h while offline`; if (job.cron) Object.assign(job, firstRun(job, now, this.options.timezone)); else { delete job.nextRun; job.enabled = false; } } } if (changed) await this.options.store.save(jobs); this.stopped = false; this.schedule(); } stop(): void { this.stopped = true; if (this.timer) clearTimeout(this.timer); this.timer = undefined; } /** Runs every due job once. Public so tests (and `steward jobs run`) can drive the clock. */ async tick(now: Date = this.now()): Promise { if (this.running) return []; this.running = true; this.lastTick = now; const ran: string[] = []; try { const due = (await this.options.store.list()).filter( (job) => job.enabled && job.nextRun && Date.parse(job.nextRun) <= now.getTime(), ); for (const job of due) { ran.push(job.id); await this.runJob(job, now); } } finally { this.running = false; } return ran; } /** * Runs one job now, whatever its schedule (`steward jobs run `). Other due jobs wait for * their turn, and the job keeps its enabled flag: a recurring job is rescheduled from now, a * one-off job is used up. Returns false when there is no such job. */ async runNow(id: string, now: Date = this.now()): Promise { if (this.running) throw new Error('the scheduler is running jobs right now; try again'); const job = await this.options.store.get(id); if (!job) return false; this.running = true; try { await this.runJob(job, now); } finally { this.running = false; } return true; } /** When the next job is due, if any. */ async nextDue(): Promise { const times = (await this.options.store.list()) .filter((j) => j.enabled && j.nextRun) .map((j) => Date.parse(j.nextRun!)); return times.length > 0 ? new Date(Math.min(...times)) : undefined; } private async runJob(job: Job, now: Date): Promise { const { gateway, store, timezone, log } = this.options; log?.(`scheduler: running ${job.id}`); let status: string; try { const result = await gateway.runInSession( `steward:cron:${job.id}`, 'scheduler', `[scheduled job "${job.id}"] ${job.prompt}`, ); let text = result.text.trim() || '(no text)'; if (result.approvals?.length) { const ids = result.approvals.map((a) => `[${a.approvalId}] ${a.summary}`).join('; '); text += `\nWaiting for your approval: ${ids}`; } await gateway.deliver({ kind: 'scheduled', source: `job:${job.id}`, text }); status = `ok (${result.stop})`; } catch (err) { status = `error: ${(err as Error).message}`; await gateway.deliver({ kind: 'notice', source: `job:${job.id}`, text: `Scheduled job "${job.id}" failed: ${(err as Error).message}`, }); } // Re-read: the job may have been changed or cancelled while it ran. const current = await store.get(job.id); if (!current) return; current.lastRun = now.toISOString(); current.lastStatus = status; if (current.cron) { const next = firstRun(current, now, timezone); if (next.nextRun) current.nextRun = next.nextRun; else delete current.nextRun; } else { // One-off jobs run once. delete current.nextRun; current.enabled = false; } await store.put(current); } private schedule(): void { if (this.stopped) return; void this.nextDue().then((due) => { if (this.stopped) return; const wait = due ? Math.max(0, due.getTime() - this.now().getTime()) : MAX_SLEEP_MS; this.timer = setTimeout( () => { void this.tick().finally(() => this.schedule()); }, Math.min(wait, MAX_SLEEP_MS), ); this.timer.unref(); }); } }