src/scheduler/schedule-tools.ts
6 KB - Ver o arquivo original
// Tools that let the assistant manage its own schedule (lab 09): "remind me Friday at 9 to take
// a mock exam" becomes a one-off job; "quiz me every weekday morning" becomes a cron job.
//
// Guards: at most 20 assistant jobs, no recurring job more often than every 30 minutes, one-off
// times must be in the future, and the assistant can only cancel jobs it created (your jobs from
// config are yours). The default policy asks you before schedule_task runs.
import { z } from 'zod';
import { defineTool, type Tool } from '../tools/tool.ts';
import { localParts, nextRun, parseCron, type CronSchedule } from './cron.ts';
import { firstRun, type JobStore } from './job-store.ts';
const MAX_ASSISTANT_JOBS = 20;
const MIN_INTERVAL_MS = 30 * 60_000;
/** Converts a local date and time in a time zone to an instant. */
export function localToInstant(date: string, time: string, timezone: string): Date {
const [y, mo, d] = date.split('-').map(Number) as [number, number, number];
const [h, mi] = time.split(':').map(Number) as [number, number];
const wanted = Date.UTC(y, mo - 1, d, h, mi);
// Guess, then correct by the zone's offset at that moment (twice, for DST edges).
let guess = wanted;
for (let i = 0; i < 2; i++) {
const p = localParts(new Date(guess), timezone);
const asLocal = Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute);
guess += wanted - asLocal;
}
return new Date(guess);
}
function formatLocal(iso: string, timezone: string): string {
return new Intl.DateTimeFormat('en-US', {
timeZone: timezone,
dateStyle: 'medium',
timeStyle: 'short',
}).format(new Date(iso));
}
export function scheduleTools(store: JobStore, timezone: string, now: () => Date): Tool[] {
const scheduleTask = defineTool({
name: 'schedule_task',
description:
'Schedules a job: at a time, a prompt is sent to you in a separate session and your answer ' +
'is delivered to the owner. Give either "cron" (five fields, owner time zone, for example ' +
'"30 7 * * 1-5") or "at" (one-off, "YYYY-MM-DD HH:MM" in the owner time zone).',
input: z.object({
id: z
.string()
.regex(/^[a-z0-9][a-z0-9-]{0,40}$/, 'lowercase letters, digits, and dashes')
.describe('Short name, for example "mock-exam-friday"'),
prompt: z.string().min(3).max(1000).describe('What to do when the job runs'),
cron: z.string().optional(),
at: z
.string()
.regex(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}$/, 'use "YYYY-MM-DD HH:MM"')
.optional(),
}),
summarize: (i) => `schedule_task ${i.id} (${i.cron ? `cron "${i.cron}"` : `at ${i.at}`})`,
run: async ({ id, prompt, cron, at }) => {
if (Boolean(cron) === Boolean(at)) throw new Error('give exactly one of "cron" or "at"');
const jobs = await store.list();
const existing = jobs.find((j) => j.id === id);
if (existing?.createdBy === 'owner') throw new Error(`"${id}" is one of the owner's jobs`);
if (
!existing &&
jobs.filter((j) => j.createdBy === 'assistant').length >= MAX_ASSISTANT_JOBS
) {
throw new Error(`too many scheduled jobs (${MAX_ASSISTANT_JOBS}); cancel some first`);
}
const current = now();
let schedule: { cron: string } | { at: string };
if (cron) {
const parsed = parseCron(cron);
if (!nextRun(parsed, current, timezone)) throw new Error('this schedule never runs');
if (shortestGapMs(parsed, current, timezone) < MIN_INTERVAL_MS) {
throw new Error('recurring jobs may run at most every 30 minutes');
}
schedule = { cron };
} else {
const [date = '', time = ''] = at!.split(' ');
const instant = localToInstant(date, time, timezone);
if (instant.getTime() <= current.getTime()) throw new Error(`${at} is in the past`);
schedule = { at: instant.toISOString() };
}
const job = {
id,
...schedule,
prompt,
enabled: true,
createdBy: 'assistant' as const,
createdAt: current.toISOString(),
...firstRun(schedule, current, timezone),
};
await store.put(job);
return `Scheduled "${id}". Next run: ${job.nextRun ? formatLocal(job.nextRun, timezone) : 'never'}.`;
},
});
const listTasks = defineTool({
name: 'list_tasks',
description: 'Lists scheduled jobs with their next run time and last result.',
input: z.object({}),
run: async () => {
const jobs = await store.list();
if (jobs.length === 0) return 'No scheduled jobs.';
return jobs
.map((j) => {
const when = j.cron ? `cron "${j.cron}"` : `once`;
const next = j.enabled && j.nextRun ? formatLocal(j.nextRun, timezone) : 'not scheduled';
return `- ${j.id} (${j.createdBy}, ${when}): next ${next}; last ${j.lastStatus ?? 'never ran'}\n prompt: ${j.prompt}`;
})
.join('\n');
},
});
const cancelTask = defineTool({
name: 'cancel_task',
description:
'Cancels a job you scheduled. Jobs the owner set up in the config cannot be cancelled.',
input: z.object({ id: z.string() }),
summarize: ({ id }) => `cancel_task ${id}`,
run: async ({ id }) => {
const job = await store.get(id);
if (!job) throw new Error(`no job "${id}"`);
if (job.createdBy === 'owner') throw new Error(`"${id}" belongs to the owner's config`);
await store.remove(id);
return `Cancelled "${id}".`;
},
});
return [scheduleTask, listTasks, cancelTask];
}
/**
* The shortest time between two runs over the next eight days (every weekday, both sides of
* midnight). Comparing only the first two runs is not enough: "0,59 * * * *" runs at :59 and
* then at :00, one minute apart, but from 10:01 its first two runs are 58 minutes apart.
*/
export function shortestGapMs(schedule: CronSchedule, from: Date, timezone: string): number {
const end = from.getTime() + 8 * 24 * 3_600_000;
let shortest = Number.POSITIVE_INFINITY;
let previous = nextRun(schedule, from, timezone);
for (let i = 0; previous && previous.getTime() < end && i < 2_000; i++) {
const next = nextRun(schedule, previous, timezone);
if (!next) break;
shortest = Math.min(shortest, next.getTime() - previous.getTime());
if (shortest < MIN_INTERVAL_MS) break;
previous = next;
}
return shortest;
}