@aidenhq/sdk 0.5.18 → 0.5.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -42,11 +42,32 @@ export declare function parseSchedule(text: string, fmt?: ClockFormat, opts?: {
42
42
  */
43
43
  export declare function nextRuns(crons: string[], tz: string, from: Date, count?: number): Date[];
44
44
  /**
45
- * The schedule phrase in a chat message ("please summarise my GitHub every weekday at 8" → "every weekday at 8"), or null when there
46
- * is none, it follows a negation in its clause ("don't do this every day at 8"), or it sits in quotes or a `>` quote line. The
47
- * longest run of words the parser accepts, starting at the first word that can begin a schedule.
45
+ * A repeat as the agent that read the owner's words states it, and the board checks it: `every` a cadence ("2 hours",
46
+ * "30 minutes", "1 hour"), `between` a window the repeats stay inside (the end excluded), `days` the days it runs on, and
47
+ * `timezone` the IANA zone its clock times are read in. `every` and `between` go together (a repeat with no window would run
48
+ * through the night); `days` and `timezone` may be left out (every day, the caller's zone). `at` is a time of day for a
49
+ * schedule without `every` ("every weekday at 08:00"). The board never reads the owner's prose: this shape is the schedule.
48
50
  */
49
- export declare function findSchedule(message: string, fmt?: ClockFormat): {
50
- text: string;
51
- parsed: Parsed;
52
- } | null;
51
+ export interface ScheduleSpec {
52
+ every?: string;
53
+ between?: [string, string];
54
+ days?: string[];
55
+ at?: string;
56
+ /** A five-field cron line (or several, one trigger each): the structured alternative to every/between/at. */
57
+ crons?: string[];
58
+ timezone?: string;
59
+ }
60
+ /** A validated spec: the same `Parsed` a plain-English schedule gives, its zone, and `english`, the canonical phrase that reads back
61
+ * to the same cron lines (what the board stores, so the owner can open and re-edit it later). */
62
+ export type SpecParsed = Parsed & {
63
+ timezone?: string;
64
+ english: string;
65
+ };
66
+ /** The shape a refusal names, with two examples that work (a tool error or a 400 is a string). */
67
+ export declare const SCHEDULE_SPEC_SHAPE = "a schedule like { every: \"2 hours\", between: [\"09:00\", \"17:00\"], days: [\"weekdays\"], timezone: \"Asia/Dubai\" }";
68
+ /**
69
+ * Validate a structured schedule and turn it into the same `{ crons, words }` a plain-English schedule gives: one cron line
70
+ * per group of times, window end excluded, day list in the weekday field. A repeat needs `between`; a field that isn't valid is
71
+ * refused with the accepted shape and two examples. No owner prose is read here: `timezone` is checked and returned as the zone.
72
+ */
73
+ export declare function scheduleSpec(spec: ScheduleSpec, fmt?: ClockFormat): SpecParsed | Refusal;
@@ -1,6 +1,7 @@
1
- // Plain-English schedules: the one parser every schedule surface uses (compile, the board's repeats and routine fields, the task
2
- // tools, Aiden's chat path). English or a five-field cron in, cron lines plus the schedule in words out. Deterministic and
3
- // dependency-free; the time zone stays outside it (callers pass it to Paperclip). The board imports @aidenhq/sdk/schedule;
1
+ // Schedules: one plain-English parser for the routine `schedules` config and the board's schedule fields and preview, and one
2
+ // validator for the structured schedule the chat path takes (an agent reads the owner's words; the board checks the object).
3
+ // English or a five-field cron in, cron lines plus the schedule in words out. Deterministic and dependency-free; for the
4
+ // plain-English parser the time zone stays outside it (callers pass it to Paperclip). The board imports @aidenhq/sdk/schedule;
4
5
  // compile and the kernel import this source.
5
6
  //
6
7
  // Paperclip's scheduler takes lists, ranges and steps, and a day of month AND a weekday must both match (the first Monday is days 1-7
@@ -312,6 +313,66 @@ function daysLabel(dow) {
312
313
  const list = dow.split(",").flatMap((p) => (/^\d-\d$/.test(p) ? Array.from({ length: Number(p[2]) - Number(p[0]) + 1 }, (_, i) => Number(p[0]) + i) : [Number(p)]));
313
314
  return list.length === 1 ? `Every ${LONG[list[0]]}` : andList(list.map((d) => SHORT[d]));
314
315
  }
316
+ /** The days as the parser reads them back: "weekdays", "weekends", or the weekday names it accepts. */
317
+ const englishDays = (list) => list.join(",") === "1,2,3,4,5" ? "weekdays" : list.join(",") === "0,6" ? "weekends" : andList(list.map((d) => LONG[d]));
318
+ /** A time of day as 24-hour "HH:MM": the form the parser reads back in either clock format. */
319
+ const h24 = (t) => `${String(Math.floor(t / 60)).padStart(2, "0")}:${String(t % 60).padStart(2, "0")}`;
320
+ /** A cron weekday field as the 0-6 days it means, through the parser's own expansion (steps, ranges, names); null if it isn't a weekday field. */
321
+ function expandCronDay(field) {
322
+ const days = expand(field, 4);
323
+ return days ? [...new Set(days.map((d) => d % 7))].sort((a, b) => a - b) : null;
324
+ }
325
+ /** A weekday field as its number field ("1-5"), names and lists alike; null for one that isn't weekday days. */
326
+ function cronDayField(field) {
327
+ const days = expandCronDay(field);
328
+ if (!days?.length)
329
+ return null;
330
+ const out = [];
331
+ for (let i = 0; i < days.length;) {
332
+ let j = i;
333
+ while (days[j + 1] === days[j] + 1)
334
+ j++;
335
+ if (j - i >= 2)
336
+ out.push(`${days[i]}-${days[j]}`);
337
+ else
338
+ for (let k = i; k <= j; k++)
339
+ out.push(String(days[k]));
340
+ i = j + 1;
341
+ }
342
+ return out.join(",");
343
+ }
344
+ /** Cron lines as one phrase the parser reads back to the same lines: one line is its own phrase; several must share their day fields. */
345
+ function editableEnglish(lines, fmt) {
346
+ if (lines.length === 1)
347
+ return lines[0];
348
+ // What the lines mean, not how they were spelled: "MON-FRI" is "1-5", and the caller's order is not the parser's.
349
+ const fields = lines.map((l) => (isRefusal(parseSchedule(l, fmt)) ? null : parseSchedule(l, fmt).crons)).flatMap((cs) => (cs?.length === 1 ? [cs[0].split(/\s+/)] : []));
350
+ if (fields.length !== lines.length)
351
+ return null;
352
+ // A day field by the dates it expands to, not its text: "01-07" is "1-7", and the order the caller wrote is not the parser's.
353
+ const dd = (f, i) => f === "*" ? "*" : (expand(f, i) ?? []).map(String).join(",");
354
+ const day = (f) => `${dd(f[2], 2)} ${dd(f[3], 3)} ${f[4] === "*" ? "*" : expandCronDay(f[4])?.join(",")}`;
355
+ if (fields.some((f) => day(f) !== day(fields[0])))
356
+ return null;
357
+ const times = [...new Set(lines.flatMap((l) => timesOf([l]) ?? []))].sort((a, b) => a - b);
358
+ const [, , dom = "*", mon = "*", dow = "*"] = fields[0];
359
+ const days = dow === "*" ? [0, 1, 2, 3, 4, 5, 6] : (expandCronDay(dow) ?? []);
360
+ // The first Monday is "the first Monday of every month", never "the 1st": a week of dates (1-7, 8-14, 15-21, 22-28) on one weekday
361
+ // is a weekday rule, by the dates the field expands to however it is spelled ("1-7", "1,2,3,4,5,6,7", "01-07").
362
+ const doms = expand(dom, 2) ?? [];
363
+ const week = doms.length === 7 && doms[0] <= 22 && (doms[0] - 1) % 7 === 0 && doms.every((d, i) => d === doms[0] + i) ? doms[0] : null;
364
+ const nthDay = week !== null && dow !== "*" && days.length === 1 ? `the ${NTH[(week - 1) / 7]} ${LONG[days[0]]} of every month` : null;
365
+ // A date ("every month on the 1st at 9:00 and 16:30") and a weekday set each read back; a no-day schedule is "every day".
366
+ const when = nthDay ?? (doms.length === 1 ? `every month on the ${ordinal(doms[0])}` : dom !== "*" ? null : mon !== "*" ? null : days.length === 7 ? "every day" : `on ${englishDays(days)}`);
367
+ if (!when)
368
+ return null;
369
+ const english = `${when} at ${times.map(h24).join(", ")}`;
370
+ const back = parseSchedule(english, fmt);
371
+ // The phrase must mean the same moments, whichever equivalent spelling the caller used: the day fields by the dates and days they
372
+ // expand to ("01-07" is "1-7"), never their text, so a leading zero doesn't make a schedule read back differently.
373
+ const signature = (cs) => cs.flatMap((c) => { const f = c.split(/\s+/); const d = f[4] === "*" ? ["*"] : (expandCronDay(f[4]) ?? []); return (timesOf([c]) ?? []).map((t) => `${dd(f[2], 2)} ${dd(f[3], 3)} ${d.join(",")}@${t}`); }).sort().join("|");
374
+ return !isRefusal(back) && signature(back.crons) === signature(lines) ? english : null;
375
+ }
315
376
  /**
316
377
  * Turn English (or a five-field cron) into cron lines. `fmt` is the owner's clock format for the words. A phrase the grammar can't say
317
378
  * exactly is refused with the reason and two examples that work.
@@ -523,131 +584,156 @@ export function nextRuns(crons, tz, from, count = 3) {
523
584
  }
524
585
  return out;
525
586
  }
526
- // ------------------------------------------------------------------ a schedule inside a message
527
- const ANCHOR = new RegExp(`^(?:every|each|daily|hourly|weekly|monthly|weekdays?|weekends?|${DAY}|the|on)$`, "i");
528
- const DAY_WORD = new RegExp(`^${DAY}$`, "i");
529
- /** Whether a word closes a sentence: "a.m." and "p.m." do only when a capitalised word follows ("at 5 p.m. Then ..."). */
530
- const endsSentence = (w, nextRaw) => /[;!?]$/.test(w) || (/\.$/.test(w) && (!/\b[ap]\.m\.$/i.test(w) || /^[A-Z]/.test(nextRaw ?? "")));
531
- /** Whether the words after a found schedule go on with it ("and 8:05", "at 9", "on Fridays"): then the schedule was cut short, not complete. */
532
- function continues(next) {
533
- const [n0, n1] = next;
534
- if (!n0)
535
- return false;
536
- // "every 2" before "weeks" is a repeat the grammar can't say, not the time 2:00.
537
- if (/^(?:days?|weeks?|months?|years?|minutes?|mins?|hours?|hrs?|fortnights?)$/.test(n0))
538
- return true;
539
- const more = (w) => /^(?:at|on|every|each|between|from|through|until|except|other|plus|weekdays?|weekends?|noon|midnight)$/.test(w) || DAY_WORD.test(w) || /^\d/.test(w);
540
- // "starting at 9am" cuts a repeat short ("every 2 hours" alone would be midnight-aligned); "starting Monday" does not: the cadence is complete, the start date is only where the owner wants it to begin.
541
- if (/^(?:starting|beginning)$/.test(n0 ?? ""))
542
- return n1 !== undefined && (/^\d/.test(n1) || /^(?:at|from|noon|midnight)$/.test(n1));
543
- return /^(?:and|or|&)$/.test(n0) ? n1 !== undefined && more(n1) : more(n0);
587
+ /** The shape a refusal names, with two examples that work (a tool error or a 400 is a string). */
588
+ export const SCHEDULE_SPEC_SHAPE = 'a schedule like { every: "2 hours", between: ["09:00", "17:00"], days: ["weekdays"], timezone: "Asia/Dubai" }';
589
+ const SPEC_EXAMPLES = [
590
+ '{ every: "2 hours", between: ["09:00","17:00"], days: ["weekdays"], timezone: "Asia/Dubai" }',
591
+ '{ every: "30 minutes", between: ["09:00","17:00"], days: ["weekdays"], timezone: "Asia/Dubai" }',
592
+ ];
593
+ const specRefusal = (error) => refuse(error, SPEC_EXAMPLES);
594
+ const DAY_NAMES = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
595
+ /** The names each weekday accepts, whole: a range or a typo is refused, never read as its first day. */
596
+ const DAY_ALIASES = [["sun", "sunday", "sundays"], ["mon", "monday", "mondays"], ["tue", "tues", "tuesday", "tuesdays"], ["wed", "wednesday", "wednesdays"], ["thu", "thur", "thurs", "thursday", "thursdays"], ["fri", "friday", "fridays"], ["sat", "saturday", "saturdays"]];
597
+ /** A day list in the structured spec: "weekdays", "weekends", "daily"/"every day", or one weekday's name. */
598
+ function specDay(day) {
599
+ const d = day.trim().toLowerCase();
600
+ if (d === "weekdays" || d === "weekday")
601
+ return -1;
602
+ if (d === "weekends" || d === "weekend")
603
+ return -2;
604
+ if (d === "daily" || d === "every day" || d === "everyday" || d === "day")
605
+ return -3;
606
+ const i = DAY_ALIASES.findIndex((names) => names.includes(d));
607
+ return i >= 0 ? i : null;
544
608
  }
545
- const MONTH_WORD = "(?:january|february|march|april|may|june|july|august|september|october|november|december|jan|feb|mar|apr|jun|jul|aug|sept?|oct|nov|dec)";
546
- const ZONE_ABBR = "(?:utc|gmt|[ecmp][sd]t|ist|cet|cest|bst|jst|gst|sgt|hkt|aest|aedt|eet|msk)";
547
- /**
548
- * Words after a found schedule that narrow it in a way the grammar can't say ("Pacific time", "only in December",
549
- * "for the next week"): the owner meant something narrower or elsewhere than what was found, so the match is refused, not
550
- * cut off. Plain trailing words ("summarise my PRs", "and send it to me") are not qualifiers.
551
- */
552
- const ZONE_WORD = "(?:pacific|eastern|central|mountain|atlantic|alaska|hawaii|local|standard|daylight|british|greenwich|gulf|india|indian|japan|singapore|dubai|london|paris|berlin|tokyo|sydney|new\\s+york|los\\s+angeles)";
553
- /** Places a schedule would silently ignore ("every weekday at 9 in London"): named cities and countries, not app or channel names. */
554
- const PLACE_WORD = "(?:london|paris|berlin|tokyo|sydney|melbourne|dubai|abu\\s+dhabi|singapore|new\\s+york|nyc|los\\s+angeles|san\\s+francisco|chicago|toronto|vancouver|boston|seattle|austin|denver|miami|mumbai|delhi|bangalore|bengaluru|hong\\s+kong|seoul|shanghai|beijing|amsterdam|madrid|barcelona|rome|milan|zurich|lisbon|dublin|stockholm|istanbul|cairo|johannesburg|nairobi|lagos|s[aã]o\\s+paulo|mexico\\s+city|india|japan|china|germany|france|spain|italy|canada|australia|brazil|ireland|the\\s+uk|the\\s+us|the\\s+usa|europe|asia|africa)";
555
- const QUALIFIER = new RegExp(`^(?:only\\s+(?:in|on|during|for|every|each|from|between|until|weekdays?|weekends?|${DAY}|${MONTH_WORD})\\b|except|excluding|unless|until|till|during` +
556
- `|for\\s+(?:the\\s+)?(?:next|first|rest|coming)\\b|for\\s+(?:an?|one|two|three|\\d+)\\s+(?:days?|weeks?|months?|years?|hours?)\\b` +
557
- `|in\\s+(?:the\\s+)?(?:morning|afternoon|evening|night|summer|winter|spring|fall|autumn|${MONTH_WORD}\\b)` +
558
- `|(?:in\\s+|at\\s+)?${ZONE_ABBR}\\b|(?:in\\s+|my\\s+|your\\s+|our\\s+)?${ZONE_WORD}(?:\\s+(?:standard|daylight))?\\s+(?:time\\b|zone\\b)|time\\s?zone\\b` +
559
- `|in\\s+(?:${ZONE_WORD}|${PLACE_WORD})\\b|(?:america|europe|asia|africa|australia|pacific|atlantic|indian)/[a-z_]+)`);
560
- /**
561
- * A conditional opening ("while keeping the report brief", "if anything changed", "only when it's a holiday") is an instruction for
562
- * the run unless what follows narrows the schedule ("while it's a holiday", "if the first Monday is busy"): then the match is
563
- * refused. `only` is read with the conditional, not as a qualifier on its own ("only include open PRs" is an instruction).
564
- */
565
- const CONDITIONAL = /^(?:only\s+)?(?:when|whenever|while|if|once|provided|as\s+long\s+as)\b/;
566
- const TIME_SCOPE = new RegExp(`\\b(?:${DAY}|${MONTH_WORD}|weekdays?|weekends?|business\\s+days?|holidays?|time|hour|noon|midnight|morning|afternoon|evening|night|summer|winter|spring|fall|autumn|${ZONE_ABBR}|${ZONE_WORD})\\b|\\d`, "i");
567
- const NEGATION = /\b(?:don['’]?t|do\s+not|doesn['’]?t|never|stop|stopping|cancel(?:l?ing)?|no\s+longer|not\s+anymore|without|remove|delete|disable|pause|instead\s+of)\b/i;
568
- /** A single quote that could open a quotation: at a word boundary, before a word, and not a closing curly one. */
569
- const opensQuote = (s, at) => s[at] !== "’" && /(?:^|[\s(\[{])/.test(s[at - 1] ?? " ") && /\S/.test(s[at + 1] ?? " ");
570
- /** A single quote that could close one: a closing curly apostrophe, or one before a space, punctuation or the end. */
571
- const closesQuote = (s, at) => s[at] === "’" || !/\S/.test(s[at + 1] ?? " ");
572
- /** The first single quote after `at` that could close one. */
573
- const closerAfter = (s, at) => {
574
- for (let k = at + 1; k < s.length; k++)
575
- if ("'‘’".includes(s[k]) && closesQuote(s, k))
576
- return k;
577
- return -1;
578
- };
579
609
  /**
580
- * Whether `before` ends inside a quotation: an odd count of `"`, more `“` than `”`, an odd count of backticks, or an unclosed single
581
- * quote. A single quote opens only when a closer follows it in the message, so a word-initial elision ("send 'em a digest", "'til
582
- * Friday") opens nothing, and neither does an apostrophe inside a word ("I'll", "don't").
610
+ * Validate a structured schedule and turn it into the same `{ crons, words }` a plain-English schedule gives: one cron line
611
+ * per group of times, window end excluded, day list in the weekday field. A repeat needs `between`; a field that isn't valid is
612
+ * refused with the accepted shape and two examples. No owner prose is read here: `timezone` is checked and returned as the zone.
583
613
  */
584
- function inQuote(before, body) {
585
- if ((before.match(/"/g) ?? []).length % 2 === 1)
586
- return true;
587
- if ((before.match(/`/g) ?? []).length % 2 === 1)
588
- return true;
589
- if ((before.match(/“/g) ?? []).length > (before.match(/”/g) ?? []).length)
590
- return true;
591
- let open = 0;
592
- for (let at = 0; at < before.length; at++) {
593
- if (!"'‘’".includes(before[at]))
594
- continue;
595
- if (opensQuote(before, at)) {
596
- if (closerAfter(body, at) > at)
597
- open++;
614
+ export function scheduleSpec(spec, fmt = "12h") {
615
+ if (!spec || typeof spec !== "object" || Array.isArray(spec))
616
+ return specRefusal(`a schedule is an object; give ${SCHEDULE_SPEC_SHAPE}`);
617
+ const extra = Object.keys(spec).filter((k) => !["every", "between", "days", "at", "crons", "timezone"].includes(k));
618
+ if (extra.length)
619
+ return specRefusal(`"${extra[0]}" isn't a schedule field (every, between, days, at, crons, timezone); give ${SCHEDULE_SPEC_SHAPE}`);
620
+ const zone = spec.timezone;
621
+ if (zone !== undefined) {
622
+ if (typeof zone !== "string" || !zone.trim())
623
+ return specRefusal("timezone must be an IANA name such as Asia/Dubai");
624
+ // Intl also takes a fixed offset ("+04:00"): the spec takes a named zone, which keeps its daylight-saving rules.
625
+ if (/^[+-]?\d/.test(zone.trim()) || /^(?:utc|gmt)?[+-]\d/.test(zone.trim().toLowerCase()))
626
+ return specRefusal(`"${zone}" is an offset, not a zone; use an IANA name such as Asia/Dubai or Europe/London`);
627
+ try {
628
+ new Intl.DateTimeFormat("en-US", { timeZone: zone.trim() });
629
+ }
630
+ catch {
631
+ return specRefusal(`"${zone}" isn't a time zone; use an IANA name such as Asia/Dubai or Europe/London`);
598
632
  }
599
- else if (open > 0 && closesQuote(before, at))
600
- open--;
601
633
  }
602
- return open > 0;
603
- }
604
- const SCHEDULE_SIGNAL = new RegExp(`\\b(?:every\\s+(?:\\d+|day|hour|week|month|weekday|weekend|${DAY})|each\\s+(?:day|hour|week|month|weekday|weekend|${DAY})|daily|hourly|weekly|monthly|weekdays?|weekends?|noon|midnight|at|between|from|${DAY})\\b|\\d\\s*(?:a\\.?m\\.?|p\\.?m\\.?)|\\d:\\d\\d`, "i");
605
- /**
606
- * The schedule phrase in a chat message ("please summarise my GitHub every weekday at 8" → "every weekday at 8"), or null when there
607
- * is none, it follows a negation in its clause ("don't do this every day at 8"), or it sits in quotes or a `>` quote line. The
608
- * longest run of words the parser accepts, starting at the first word that can begin a schedule.
609
- */
610
- export function findSchedule(message, fmt = "12h") {
611
- const body = message.split("\n").map((l) => (/^\s*>/.test(l) ? " ".repeat(l.length) : l)).join("\n");
612
- const tokens = [...body.matchAll(/\S+/g)].map((m) => ({ word: m[0], at: m.index }));
613
- for (let i = 0; i < tokens.length; i++) {
614
- if (!ANCHOR.test(tokens[i].word.replace(/^[("'`“]+|[,.;:!?)"'`”]+$/g, "")))
615
- continue;
616
- for (let j = Math.min(tokens.length, i + 24); j > i; j--) {
617
- const text = body.slice(tokens[i].at, tokens[j - 1].at + tokens[j - 1].word.length).replace(/[.,;:!?)"'`”]+$/, "");
618
- if (/[\n]/.test(text))
619
- continue;
620
- const word = (t) => (t?.word ?? "").toLowerCase().replace(/^[("'`“]+|[,.;:!?)"'`”]+$/g, "");
621
- if (/^(?:and|or|&|at|on|every|each|the|of|from|to|between|then)$/.test(word(tokens[j - 1])))
622
- continue; // a schedule doesn't end on a connector
623
- const parsed = parseSchedule(text, fmt);
624
- if (isRefusal(parsed))
625
- continue;
626
- // A bare number after "the" or "on" ("review the 3 open PRs") is a count, not a time of day: a schedule in a message says when with a cadence word, "at", a day, or a clock time (am/pm or a colon).
627
- if (!SCHEDULE_SIGNAL.test(text))
628
- continue;
629
- // A schedule cut short by one the parser refuses ("every other Monday at 9", "at 8am and 8:05am") is that refusal, never the shorter one.
630
- // The next words continue it only within the same sentence and line.
631
- const gap = j < tokens.length ? body.slice(tokens[j - 1].at + tokens[j - 1].word.length, tokens[j].at) : "";
632
- const next = tokens.slice(j, j + 2).map(word);
633
- // After a sentence end nothing continues it; after a line break only an explicit "and <time or day>" does.
634
- const closed = endsSentence(tokens[j - 1].word, tokens[j]?.word);
635
- const goesOn = closed ? false : /[\n]/.test(gap) ? /^(?:and|or|&)$/.test(next[0] ?? "") && continues(next) : continues(next);
636
- // What follows in the same sentence may narrow it past what the grammar says: refused whole, never cut off.
637
- const tail = body.slice(tokens[j - 1].at + tokens[j - 1].word.length).split(/(?<![ap]\.m)[.;!?\n]/i)[0].replace(/^[\s,:()\-–—]+/, "").toLowerCase();
638
- if (!closed && (QUALIFIER.test(tail) || (CONDITIONAL.test(tail) && TIME_SCOPE.test(tail))))
639
- return null;
640
- if (goesOn || tokens.slice(Math.max(0, i - 2), i).some((t) => /^(?:other|alternate|alternating|last)$/.test(word(t))) || (i > 0 && /^or$/.test(word(tokens[i - 1]))))
641
- return null;
642
- const before = body.slice(0, tokens[i].at);
643
- const clause = before.split(/[.;!?\n]|\bbut\b/i).at(-1) ?? "";
644
- if (NEGATION.test(clause))
645
- return null;
646
- // Inside a quote ('…', "…", “…”, `…`): the words are someone else's example, not the owner's request.
647
- if (inQuote(before, body))
648
- return null;
649
- return { text, parsed };
634
+ const clock = (t) => clockWords(Math.floor(t / 60), t % 60, fmt);
635
+ // Cron lines are structure too: exactly the five-field cron the shared parser reads, never English, and measured like a parsed phrase.
636
+ if (spec.crons !== undefined) {
637
+ if (spec.every !== undefined || spec.between !== undefined || spec.at !== undefined || spec.days !== undefined)
638
+ return specRefusal("give crons alone, or every/between/at and days, not both");
639
+ if (!Array.isArray(spec.crons) || !spec.crons.length || spec.crons.length > 12)
640
+ return specRefusal("crons is a list of one to twelve five-field cron lines");
641
+ const lines = [];
642
+ for (const c of spec.crons) {
643
+ // The parser's own grammar, not a narrower one: fields of letters and symbols, spaces between them collapsed.
644
+ const one = typeof c === "string" ? c.trim().split(/\s+/) : [];
645
+ if (one.length !== 5 || one.some((f) => !/^[\w*,/-]+$/.test(f)))
646
+ return specRefusal(`"${String(c)}" isn't a five-field cron line (minute hour day month weekday)`);
647
+ const p = parseSchedule(one.join(" "), fmt);
648
+ if (isRefusal(p))
649
+ return specRefusal(`"${c.trim()}" isn't a valid cron line: ${p.error}`);
650
+ // The parser's own spelling: the same line, however the caller wrote its day names or spacing.
651
+ const cron = p.crons[0];
652
+ const f = cron.split(/\s+/);
653
+ if (f[4] !== "*") {
654
+ // The parser echoes a named weekday as written ("MON-FRI"): store its number, so two spellings of one day set are one line.
655
+ const days = cronDayField(f[4]);
656
+ if (!days)
657
+ return specRefusal(`"${c.trim()}" isn't a valid cron line: its weekday isn't one`);
658
+ f[4] = days;
659
+ }
660
+ lines.push(f.join(" "));
661
+ }
662
+ // One trigger each: two that fire at the same instant are a double run, which the gap rule refuses everywhere else.
663
+ if (minGapOf(lines) === 0)
664
+ return specRefusal("two cron lines fire at the same instant; give one trigger per moment");
665
+ // What the board stores must read back to the same lines, so the owner can reopen and save it unchanged: one line is itself
666
+ // English to the parser; several are, only when they share their day fields (one "on <days> at <times>" phrase).
667
+ const english = editableEnglish(lines, fmt);
668
+ if (!english)
669
+ return specRefusal("crons that don't share their days can't be edited as one schedule; give one cron line");
670
+ return { ...measured(lines, lines.map((c) => describeCron(c, fmt)).join(" and ")), english, ...(zone ? { timezone: zone.trim() } : {}) };
671
+ }
672
+ // The days: every day when none are given.
673
+ let list = [0, 1, 2, 3, 4, 5, 6];
674
+ if (spec.days !== undefined) {
675
+ if (!Array.isArray(spec.days) || !spec.days.length)
676
+ return specRefusal("days is a list of weekdays, e.g. [\"weekdays\"] or [\"mon\",\"wed\",\"fri\"]");
677
+ const out = new Set();
678
+ for (const d of spec.days) {
679
+ const i = typeof d === "string" ? specDay(d) : null;
680
+ if (i === null)
681
+ return specRefusal(`"${String(d)}" isn't a day; use "weekdays", "weekends", "daily" or weekday names (mon … sun)`);
682
+ if (i === -1)
683
+ [1, 2, 3, 4, 5].forEach((x) => out.add(x));
684
+ else if (i === -2)
685
+ [0, 6].forEach((x) => out.add(x));
686
+ else if (i === -3)
687
+ [0, 1, 2, 3, 4, 5, 6].forEach((x) => out.add(x));
688
+ else
689
+ out.add(i);
650
690
  }
691
+ if (!out.size)
692
+ return specRefusal("days must name at least one day");
693
+ list = [...out].sort((a, b) => a - b);
694
+ }
695
+ const df = list.length === 7 ? "*" : dowField(list);
696
+ if (spec.every !== undefined) {
697
+ const raw = typeof spec.every === "string" ? spec.every.trim() : "";
698
+ const m = /^(?:every\s+)?(\d+)\s*(minutes?|mins?|hours?|hrs?|h)$/i.exec(raw);
699
+ if (!m)
700
+ return specRefusal(`every must be a cadence such as "2 hours" or "30 minutes"; give ${SCHEDULE_SPEC_SHAPE}`);
701
+ const n = Number(m[1]);
702
+ const unit = m[2].toLowerCase().startsWith("m") ? "min" : "hour";
703
+ if (unit === "min" && n < MIN_GAP_MINUTES)
704
+ return specRefusal(`a schedule runs at most every ${MIN_GAP_MINUTES} minutes, not every ${n}`);
705
+ if (unit === "min" && 60 % n !== 0)
706
+ return specRefusal(`every ${n} minutes doesn't divide the hour evenly; use 15, 20, 30 or 60`);
707
+ if (unit === "hour" && 24 % n !== 0)
708
+ return specRefusal(`every ${n} hours doesn't divide the day evenly; use 1, 2, 3, 4, 6, 8, 12 or 24`);
709
+ if (spec.at !== undefined)
710
+ return specRefusal("give either every (a repeat inside between) or at (a time of day), not both");
711
+ if (spec.between === undefined)
712
+ return specRefusal(`a repeat needs between: the window it stays inside, e.g. ${SCHEDULE_SPEC_SHAPE}`);
713
+ if (!Array.isArray(spec.between) || spec.between.length !== 2 || spec.between.some((x) => typeof x !== "string"))
714
+ return specRefusal('between is two times of day, e.g. ["09:00", "17:00"]');
715
+ const [a, b] = [clockOf(spec.between[0]), clockOf(spec.between[1])];
716
+ if (a === null || b === null)
717
+ return specRefusal(`between must be two times of day such as "09:00" and "17:00"`);
718
+ if (b <= a)
719
+ return specRefusal("between must end after it starts, both the same day (a window can't cross midnight)");
720
+ const step = unit === "min" ? n : n * 60;
721
+ const times = [];
722
+ for (let t = a; t < b; t += step)
723
+ times.push(t);
724
+ const lead = unit === "min" ? `Every ${n} min` : n === 1 ? "Every hour" : `Every ${n} hours`;
725
+ const where = [df === "*" ? "" : daysLabel(df), `${clock(a)} to ${clock(b)}`].filter(Boolean);
726
+ const english = [`every ${unit === "min" ? `${n} minutes` : n === 1 ? "hour" : `${n} hours`}`, df === "*" ? "" : `on ${englishDays(list)}`, `between ${h24(a)} and ${h24(b)}`].filter(Boolean).join(" ");
727
+ return { ...measured(cronLines(times, `* * ${df}`), [lead, ...where].join(", ")), english, ...(zone ? { timezone: zone.trim() } : {}) };
651
728
  }
652
- return null;
729
+ if (spec.between !== undefined)
730
+ return specRefusal("between goes with every: 'every 30 minutes between 9:00 and 17:00'");
731
+ if (spec.at === undefined)
732
+ return specRefusal(`say when it runs: every with between, or at a time of day; give ${SCHEDULE_SPEC_SHAPE}`);
733
+ const t = typeof spec.at === "string" ? clockOf(spec.at) : null;
734
+ if (t === null)
735
+ return specRefusal(`at must be a time of day such as "08:00" or "8am"`);
736
+ const when = `at ${clock(t)}`;
737
+ const english = `${df === "*" ? "every day" : `on ${englishDays(list)}`} at ${h24(t)}`;
738
+ return { ...measured(cronLines([t], `* * ${df}`), df === "*" ? `Every day ${when}` : `${daysLabel(df)} ${when}`), english, ...(zone ? { timezone: zone.trim() } : {}) };
653
739
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aidenhq/sdk",
3
- "version": "0.5.18",
3
+ "version": "0.5.20",
4
4
  "description": "The shared code of AidenHQ modules: contract types, engine IO, the caller check and fence, write executors, the reviewer side, the judges' models and call, the source writer and the vendor MCP pass-through.",
5
5
  "license": "MIT",
6
6
  "repository": {