UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

268 lines (267 loc) • 11.5 kB
import { SchedulerError } from "./scheduler.js"; import { foldToOneLine, inlineUntrusted } from "./untrusted-text.js"; const MAX_EXPR_LENGTH = 100; const CRON_ALPHABET = /^[0-9*/,\-\s]+$/; export const CRON_FIELD_SEPARATOR = /\s+/; const CRON_FIELDS = [ { name: "minute", min: 0, max: 59 }, { name: "hour", min: 0, max: 23 }, { name: "day-of-month", min: 1, max: 31 }, { name: "month", min: 1, max: 12 }, { name: "day-of-week", min: 0, max: 6 }, ]; function expandCronField(field, { min, max }) { const out = new Set(); const isDow = min === 0 && max === 6; for (const part of field.split(",")) { const star = part.match(/^\*(?:\/(\d+))?$/); if (star) { const n = star[1] ? parseInt(star[1], 10) : 1; if (n < 1) return null; for (let i = min; i <= max; i += n) out.add(i); continue; } const range = part.match(/^(\d+)-(\d+)(?:\/(\d+))?$/); if (range) { const lo = parseInt(range[1] ?? "", 10); const hi = parseInt(range[2] ?? "", 10); const n = range[3] ? parseInt(range[3], 10) : 1; const top = isDow ? 7 : max; if (lo > hi || n < 1 || lo < min || hi > top) return null; for (let i = lo; i <= hi; i += n) out.add(isDow && i === 7 ? 0 : i); continue; } if (/^\d+$/.test(part)) { let n = parseInt(part, 10); if (isDow && n === 7) n = 0; if (n < min || n > max) return null; out.add(n); continue; } return null; } return out.size > 0 ? [...out] : null; } function foldedAwayClause(text) { const parts = [ ...(foldToOneLine(text) !== text.trim().replace(/ +/g, " ") ? ["control or non-printing characters, shown folded"] : []), ...(/^\s|\s$/u.test(text) ? ["white space at its start or end"] : []), ]; return parts.length === 0 ? "" : ` (the text given holds ${parts.join(", and ")})`; } function quoted(expr) { return expr.length <= MAX_EXPR_LENGTH ? `${JSON.stringify(inlineUntrusted(expr, MAX_EXPR_LENGTH))}${foldedAwayClause(expr)}` : `(${expr.length} characters)`; } function parseCron(expr) { if (typeof expr !== "string") return { ok: false, reason: `it is ${expr === null ? "null" : typeof expr}, not a string.` }; const trimmed = expr.trim(); if (trimmed.length === 0) return { ok: false, reason: "it is empty — expected 5 fields (minute hour day-of-month month day-of-week)." }; if (trimmed.length > MAX_EXPR_LENGTH) return { ok: false, reason: `it is ${trimmed.length} characters long; at most ${MAX_EXPR_LENGTH} are read.` }; if (!CRON_ALPHABET.test(trimmed)) { return { ok: false, reason: "only 5 space-separated cron fields of digits and * / , - are allowed (no names, no @ shorthands, no seconds field)." }; } const fields = trimmed.split(CRON_FIELD_SEPARATOR); if (fields.length === 6) { return { ok: false, reason: `its leading seconds field is not supported — cron here fires on 5 fields, so one minute is the finest ` + `granularity available. Pass "${fields.slice(1).join(" ")}" if that cadence works.`, }; } if (fields.length !== 5) return { ok: false, reason: `expected 5 fields (minute hour day-of-month month day-of-week), got ${fields.length}.` }; const values = []; for (let i = 0; i < 5; i++) { const range = CRON_FIELDS[i]; const field = fields[i]; const expanded = expandCronField(field, range); if (expanded === null) { const sunday = range.name === "day-of-week" ? " (7 is Sunday too)" : ""; return { ok: false, reason: `invalid ${range.name} field "${field}" — allowed ${range.min}-${range.max}${sunday} (syntax: N, N-M, */N, N-M/S, comma lists).` }; } values.push(expanded); } const [minutes, hours, daysOfMonth, months, daysOfWeek] = values; return { ok: true, schedule: { minutes: new Set(minutes), hours: new Set(hours), daysOfMonth: new Set(daysOfMonth), months: new Set(months), daysOfWeek: new Set(daysOfWeek), anyDayOfMonth: daysOfMonth.length === 31, anyDayOfWeek: daysOfWeek.length === 7, }, }; } export function isValidCronExpr(expr) { return parseCron(expr).ok; } const MINUTE_MS = 60_000; const HOUR_MS = 3_600_000; const DAY_MS = 86_400_000; const MAX_INSTANT_MS = 8.64e15; const MAX_WALK_STEPS = 527_040; function daysFromCivil(year, month, day) { const y = month <= 2 ? year - 1 : year; const era = Math.floor(y / 400); const yoe = y - era * 400; const doy = Math.floor((153 * (month + (month > 2 ? -3 : 9)) + 2) / 5) + day - 1; const doe = yoe * 365 + Math.floor(yoe / 4) - Math.floor(yoe / 100) + doy; return era * 146_097 + doe - 719_468; } function daysInMonth(year, month) { if (month === 2) return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0 ? 29 : 28; return month === 4 || month === 6 || month === 9 || month === 11 ? 30 : 31; } function wallAsUtcMs(w) { return daysFromCivil(w.year, w.month, w.day) * DAY_MS + w.hour * HOUR_MS + w.minute * MINUTE_MS; } function nextMonth(w) { return w.month === 12 ? { year: w.year + 1, month: 1, day: 1, hour: 0, minute: 0 } : { year: w.year, month: w.month + 1, day: 1, hour: 0, minute: 0 }; } function nextDay(w) { return w.day >= daysInMonth(w.year, w.month) ? nextMonth(w) : { year: w.year, month: w.month, day: w.day + 1, hour: 0, minute: 0 }; } function nextHour(w) { return w.hour === 23 ? nextDay(w) : { year: w.year, month: w.month, day: w.day, hour: w.hour + 1, minute: 0 }; } function nextMinute(w) { return w.minute === 59 ? nextHour(w) : { year: w.year, month: w.month, day: w.day, hour: w.hour, minute: w.minute + 1 }; } function dayMatches(s, w) { if (s.anyDayOfMonth && s.anyDayOfWeek) return true; if (s.anyDayOfWeek) return s.daysOfMonth.has(w.day); const dow = (((daysFromCivil(w.year, w.month, w.day) + 4) % 7) + 7) % 7; if (s.anyDayOfMonth) return s.daysOfWeek.has(dow); return s.daysOfMonth.has(w.day) || s.daysOfWeek.has(dow); } function wallMatches(s, w) { return s.months.has(w.month) && dayMatches(s, w) && s.hours.has(w.hour) && s.minutes.has(w.minute); } function zoneClock(timeZone) { let format; try { format = new Intl.DateTimeFormat("en-US", { timeZone, hourCycle: "h23", year: "numeric", month: "numeric", day: "numeric", hour: "numeric", minute: "numeric", second: "numeric", }); } catch { return undefined; } const fieldsOf = (instantMs) => { const at = {}; for (const p of format.formatToParts(instantMs)) if (p.type !== "literal") at[p.type] = parseInt(p.value, 10); return { w: { year: at.year ?? NaN, month: at.month ?? NaN, day: at.day ?? NaN, hour: at.hour ?? NaN, minute: at.minute ?? NaN }, second: at.second ?? NaN }; }; const offsetAt = (instantMs) => { const whole = Math.floor(instantMs / 1000) * 1000; const { w, second } = fieldsOf(whole); return wallAsUtcMs(w) + second * 1000 - whole; }; return { wallOf: (instantMs) => fieldsOf(instantMs).w, instantsOf: (w) => { const wall = wallAsUtcMs(w); const found = new Set(); for (const offset of [offsetAt(Math.max(wall - DAY_MS, -MAX_INSTANT_MS)), offsetAt(Math.min(wall + DAY_MS, MAX_INSTANT_MS))]) { const t = wall - offset; if (Math.abs(t) <= MAX_INSTANT_MS && offsetAt(t) === offset) found.add(t); } return [...found].sort((a, b) => a - b); }, }; } function invalid(message) { return { ok: false, error: new SchedulerError("invalid_schedule", message) }; } export function nextCronFireTime(expr, opts) { const parsed = parseCron(expr); if (!parsed.ok) return invalid(`invalid cron expression${typeof expr === "string" ? ` ${quoted(expr)}` : ""} — ${parsed.reason}`); const given = (opts ?? {}); const { after, timeZone, recurring } = given; if (typeof after !== "number" || !Number.isFinite(after) || after < 0 || after > MAX_INSTANT_MS) { return invalid(`invalid base instant: \`after\` must be a number of epoch milliseconds from 0 to ${MAX_INSTANT_MS}, got ${typeof after === "number" ? String(after) : typeof after}.`); } if (recurring !== undefined && typeof recurring !== "boolean") { return invalid(`invalid \`recurring\`: it must be a boolean when given, got ${recurring === null ? "null" : typeof recurring}.`); } if (typeof timeZone !== "string" || timeZone.trim() === "") { return invalid(`invalid time zone: \`timeZone\` must name a time zone such as "Asia/Tokyo", got ${typeof timeZone === "string" ? "an empty string" : typeof timeZone}.`); } const clock = zoneClock(timeZone); if (clock === undefined) return invalid(`invalid time zone ${quoted(timeZone)} — the runtime knows no time zone by that name (an IANA name such as "Asia/Tokyo" is expected).`); const s = parsed.schedule; const oneShot = recurring === false; let at = Math.floor(after / MINUTE_MS) * MINUTE_MS + MINUTE_MS; if (at > MAX_INSTANT_MS) return { ok: true, value: null }; if (oneShot) { const here = clock.instantsOf(clock.wallOf(at)); if (here.length === 2) { const end = Math.min(at + 2 * (here[1] - here[0]), MAX_INSTANT_MS + MINUTE_MS); for (; at < end; at += MINUTE_MS) if (wallMatches(s, clock.wallOf(at))) return { ok: true, value: at }; if (at > MAX_INSTANT_MS) return { ok: true, value: null }; } } let w = clock.wallOf(at); for (let step = 0; step < MAX_WALK_STEPS; step++) { if (wallAsUtcMs(w) > MAX_INSTANT_MS + DAY_MS) return { ok: true, value: null }; if (!s.months.has(w.month)) w = nextMonth(w); else if (!dayMatches(s, w)) w = nextDay(w); else if (!s.hours.has(w.hour)) w = nextHour(w); else if (!s.minutes.has(w.minute)) w = nextMinute(w); else { const instants = clock.instantsOf(w); const pick = oneShot ? instants.find((t) => t > after) : instants[0] !== undefined && instants[0] > after ? instants[0] : undefined; if (pick !== undefined) return { ok: true, value: pick }; w = nextMinute(w); } } return { ok: true, value: null }; } export function cronIntakeRefusal(expr, at) { const next = nextCronFireTime(expr, at); if (!next.ok) return next.error.message; if (next.value === null) { return (`cron expression ${quoted(expr)} — it never fires — no calendar date matches its day-of-month and month fields ` + `(e.g. February has at most 29 days). Pick a real calendar date.`); } return null; }