@celljs/ta-cron 4.8.0 → 4.9.0

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.
@@ -1,55 +0,0 @@
1
- import { describe, expect, it } from 'bun:test';
2
- import { CommandParser, CronText } from './commands';
3
- import type { Task } from './cron-protocol';
4
-
5
- describe('CommandParser', () => {
6
- const now = new Date('2026-11-11T10:00:00');
7
-
8
- it('reads /loop: a duration, a nickname or a quoted cron expression, then the prompt and its flags', () => {
9
- expect(CommandParser.repeating('30m check CI status')).toEqual({ schedule: { kind: 'interval', every: '30m' }, prompt: 'check CI status' });
10
- expect(CommandParser.repeating('@daily sum up "yesterday" --notify always --model=openai/gpt-5')).toEqual({
11
- schedule: { kind: 'cron', expression: '@daily' },
12
- prompt: 'sum up "yesterday"',
13
- notify: 'always',
14
- model: 'openai/gpt-5',
15
- });
16
- expect(CommandParser.repeating('"0 9 * * 1-5" write the report --name daily-report').schedule).toEqual({ kind: 'cron', expression: '0 9 * * 1-5' });
17
- expect(() => CommandParser.repeating('check CI')).toThrow('Start with when');
18
- expect(() => CommandParser.repeating('30m')).toThrow('the prompt');
19
- });
20
-
21
- it('reads /remind: in a while, or at a time', () => {
22
- expect(CommandParser.reminder('in 45m review the release', now)).toEqual({
23
- schedule: { kind: 'once', at: new Date(now.getTime() + 45 * 60_000).toISOString() },
24
- prompt: 'review the release',
25
- });
26
- expect(CommandParser.reminder('at 15:30 check production', now).schedule).toEqual({ kind: 'once', at: new Date('2026-11-11T15:30:00').toISOString() });
27
- // A time that passed today is tomorrow.
28
- expect(CommandParser.reminder('at 9:00 stand up', now).schedule).toEqual({ kind: 'once', at: new Date('2026-11-12T09:00:00').toISOString() });
29
- expect(CommandParser.reminder('at 2026-12-01 08:15 renew it', now)).toMatchObject({
30
- schedule: { at: new Date('2026-12-01T08:15:00').toISOString() },
31
- prompt: 'renew it',
32
- });
33
- expect(() => CommandParser.reminder('later do it', now)).toThrow('Say when');
34
- });
35
-
36
- it('reads /schedule actions and the flags of set, where - clears', () => {
37
- expect(CommandParser.action('')).toEqual({ action: 'list', rest: '' });
38
- expect(CommandParser.action('delete task_1234')).toEqual({ action: 'remove', rest: 'task_1234' });
39
- expect(() => CommandParser.action('frobnicate')).toThrow('does not know');
40
- expect(CommandParser.patch('task_1234 --model - --thinking high')).toEqual({ ref: 'task_1234', patch: { model: '', thinking: 'high' } });
41
- expect(() => CommandParser.patch('task_1234')).toThrow('what changes');
42
- });
43
-
44
- it('offers actions, then tasks', () => {
45
- const tasks = [{ id: 'task_abcd1234', name: 'ci' }] as Task[];
46
- expect(CommandParser.completions('ru', tasks).map(item => item.label)).toEqual(['runs', 'run']);
47
- expect(CommandParser.completions('run task_a', tasks)).toEqual([{ value: 'run task_abcd1234 ', label: 'task_abcd1234', description: 'ci' }]);
48
- expect(CommandParser.loopCompletions('@d').map(item => item.label)).toEqual(['@daily']);
49
- });
50
-
51
- it('answers in plain text for the terminal', () => {
52
- expect(CronText.reply({ kind: 'list', tasks: [] })).toContain('No scheduled tasks');
53
- expect(CronText.reply({ kind: 'help' })).toContain('/remind in');
54
- });
55
- });
@@ -1,259 +0,0 @@
1
- import { NICKNAMES } from './cron-expression';
2
- import type { NotifyLevel, Reply, Run, Schedule, Task, TaskInput, TaskPatch } from './cron-protocol';
3
- import { Duration, ScheduleUtil } from './schedule-util';
4
-
5
- /** The flags that may end a command: `--notify always`, `--model=anthropic/claude-sonnet-4-5`. */
6
- export interface Flags {
7
- name?: string;
8
- notify?: string;
9
- model?: string;
10
- thinking?: string;
11
- cwd?: string;
12
- }
13
-
14
- const FLAG_NAMES = ['name', 'notify', 'model', 'thinking', 'cwd'] as const;
15
- const TRAILING_FLAG = new RegExp(`(?:^|\\s)--(${FLAG_NAMES.join('|')})(?:=|\\s+)("[^"]*"|'[^']*'|\\S*)\\s*$`);
16
-
17
- export const ACTIONS = ['add', 'list', 'show', 'runs', 'run', 'enable', 'disable', 'set', 'remove', 'clear', 'help'] as const;
18
- export type Action = (typeof ACTIONS)[number];
19
-
20
- export const HELP = `Scheduled tasks: each run is a conversation of its own in the Ta service, which runs them while it runs.
21
-
22
- /loop <when> <prompt> repeat: 30m, 2h, @daily, @hourly, or a cron expression in quotes ("0 9 * * 1-5")
23
- /remind in <duration> <prompt> once, after a while: in 45m
24
- /remind at <time> <prompt> once, at a time: at 15:30, at 2026-11-12 09:00
25
- /schedule add <when> <prompt> as /loop
26
- /schedule list the tasks
27
- /schedule show <task> a task and its last runs
28
- /schedule run <task> run it now; its schedule stays
29
- /schedule enable|disable <task>
30
- /schedule set <task> [flags] change it; a value of - clears the flag
31
- /schedule remove <task>
32
- /schedule clear remove the tasks of this directory
33
-
34
- A task is its id, the start of it, or its name. Flags at the end of a prompt:
35
- --name <name> --notify always|error|never --model <provider/model> --thinking <level> --cwd <directory>`;
36
-
37
- /** The arguments of the commands, read: what is wrong throws with a message for the user. */
38
- export namespace CommandParser {
39
- /** The flags at the end, and the text before them as it was typed. */
40
- export function splitFlags(text: string): { rest: string; flags: Flags } {
41
- const flags: Flags = {};
42
- let rest = text.trim();
43
- for (let match = TRAILING_FLAG.exec(rest); match; match = TRAILING_FLAG.exec(rest)) {
44
- const key = match[1] as keyof Flags;
45
- if (flags[key] === undefined) {
46
- flags[key] = unquote(match[2]);
47
- }
48
- rest = rest.slice(0, match.index).trimEnd();
49
- }
50
- return { rest, flags };
51
- }
52
-
53
- /** `<when> <prompt>`: a duration, a nickname, or a cron expression in quotes, then the prompt. */
54
- export function repeating(text: string): TaskInput {
55
- const { rest, flags } = splitFlags(text);
56
- const { schedule, remainder } = leadingSchedule(rest);
57
- return input(schedule, remainder, flags);
58
- }
59
-
60
- /** `in <duration> <prompt>`, `<duration> <prompt>` or `at <time> <prompt>`. */
61
- export function reminder(text: string, now: Date): TaskInput {
62
- const { rest, flags } = splitFlags(text);
63
- const words = rest.split(/\s+/);
64
- let at: Date | undefined;
65
- let used = 0;
66
- if (words[0] === 'at') {
67
- const time = clockTime(words.slice(1, 3), now);
68
- at = time?.date;
69
- used = 1 + (time?.words ?? 0);
70
- } else {
71
- const offset = words[0] === 'in' ? 1 : 0;
72
- const ms = Duration.parse(words[offset] ?? '');
73
- at = ms === undefined ? undefined : new Date(now.getTime() + ms);
74
- used = offset + 1;
75
- }
76
- if (!at) {
77
- throw new Error('Say when: /remind in 45m <prompt>, or /remind at 15:30 <prompt>.');
78
- }
79
- return input({ kind: 'once', at: at.toISOString() }, words.slice(used).join(' '), flags);
80
- }
81
-
82
- /** The first word, as an action of /schedule, and the rest. */
83
- export function action(text: string): { action: Action; rest: string } {
84
- const trimmed = text.trim();
85
- const first = trimmed.split(/\s+/, 1)[0] || 'list';
86
- const action = (first === 'delete' ? 'remove' : first === 'ls' ? 'list' : first) as Action;
87
- if (!ACTIONS.includes(action)) {
88
- throw new Error(`/schedule does not know ${JSON.stringify(first)}. It takes: ${ACTIONS.join(', ')}.`);
89
- }
90
- return { action, rest: trimmed.slice(trimmed ? first.length : 0).trim() };
91
- }
92
-
93
- /** The task and the flags of `/schedule set`; `-` (or nothing after `=`) clears a flag. */
94
- export function patch(text: string): { ref: string; patch: TaskPatch } {
95
- const { rest, flags } = splitFlags(text);
96
- if (!rest) {
97
- throw new Error('Name the task: /schedule set <task> --model <provider/model>.');
98
- }
99
- const value = (flag: string | undefined) => (flag === undefined ? undefined : flag === '-' ? '' : flag);
100
- const patch: TaskPatch = {};
101
- if (flags.name !== undefined) {
102
- patch.name = value(flags.name);
103
- }
104
- if (flags.cwd !== undefined) {
105
- patch.cwd = value(flags.cwd);
106
- }
107
- if (flags.model !== undefined) {
108
- patch.model = value(flags.model);
109
- }
110
- if (flags.thinking !== undefined) {
111
- patch.thinking = value(flags.thinking);
112
- }
113
- if (flags.notify !== undefined) {
114
- patch.notify = value(flags.notify) as NotifyLevel | '';
115
- }
116
- if (Object.keys(patch).length === 0) {
117
- throw new Error('Say what changes: --name, --notify, --model, --thinking or --cwd.');
118
- }
119
- return { ref: rest, patch };
120
- }
121
-
122
- export function leadingSchedule(text: string): { schedule: Schedule; remainder: string } {
123
- const trimmed = text.trim();
124
- const quote = trimmed[0];
125
- if (quote === '"' || quote === "'") {
126
- const end = trimmed.indexOf(quote, 1);
127
- if (end < 0) {
128
- throw new Error('The cron expression has no closing quote.');
129
- }
130
- return { schedule: ScheduleUtil.check({ kind: 'cron', expression: trimmed.slice(1, end) }), remainder: trimmed.slice(end + 1) };
131
- }
132
- const [first = ''] = trimmed.split(/\s+/, 1);
133
- const remainder = trimmed.slice(first.length);
134
- if (first.startsWith('@')) {
135
- return { schedule: ScheduleUtil.check({ kind: 'cron', expression: first }), remainder };
136
- }
137
- if (Duration.parse(first) !== undefined) {
138
- return { schedule: ScheduleUtil.check({ kind: 'interval', every: first }), remainder };
139
- }
140
- throw new Error('Start with when: 30m, 2h, @daily, or a cron expression in quotes such as "0 9 * * 1-5".');
141
- }
142
-
143
- /** `15:30` (today, or tomorrow once it passed), `2026-11-12 09:00`, or an ISO time; how many words it took. */
144
- export function clockTime(words: string[], now: Date): { date: Date; words: number } | undefined {
145
- const [first = '', second = ''] = words;
146
- const hm = /^(\d{1,2}):(\d{2})$/;
147
- const day = /^(\d{4})-(\d{1,2})-(\d{1,2})$/;
148
- const time = hm.exec(first);
149
- if (time) {
150
- const date = new Date(now.getTime());
151
- date.setHours(Number(time[1]), Number(time[2]), 0, 0);
152
- if (date.getTime() <= now.getTime()) {
153
- date.setDate(date.getDate() + 1);
154
- }
155
- return valid(date, Number(time[1]) < 24 && Number(time[2]) < 60) ? { date, words: 1 } : undefined;
156
- }
157
- const date = day.exec(first);
158
- const later = hm.exec(second);
159
- if (date) {
160
- const at = new Date(Number(date[1]), Number(date[2]) - 1, Number(date[3]), later ? Number(later[1]) : 9, later ? Number(later[2]) : 0);
161
- return valid(at, true) ? { date: at, words: later ? 2 : 1 } : undefined;
162
- }
163
- const iso = /^\d{4}-\d{2}-\d{2}T/.test(first) ? new Date(first) : undefined;
164
- return iso && valid(iso, true) ? { date: iso, words: 1 } : undefined;
165
- }
166
-
167
- function valid(date: Date, ok: boolean): boolean {
168
- return ok && !Number.isNaN(date.getTime());
169
- }
170
-
171
- function input(schedule: Schedule, prompt: string, flags: Flags): TaskInput {
172
- const text = prompt.trim();
173
- if (!text) {
174
- throw new Error('Then say what Ta should do: the prompt of the task.');
175
- }
176
- return {
177
- schedule,
178
- prompt: text,
179
- ...(flags.name ? { name: flags.name } : {}),
180
- ...(flags.cwd ? { cwd: flags.cwd } : {}),
181
- ...(flags.model ? { model: flags.model } : {}),
182
- ...(flags.thinking ? { thinking: flags.thinking } : {}),
183
- ...(flags.notify ? { notify: flags.notify as NotifyLevel } : {}),
184
- };
185
- }
186
-
187
- function unquote(value: string): string {
188
- return /^(["']).*\1$/.test(value) ? value.slice(1, -1) : value;
189
- }
190
-
191
- /** What to offer after `/schedule `: the actions, then the tasks. */
192
- export function completions(prefix: string, tasks: Task[]): { value: string; label: string; description?: string }[] {
193
- const parts = prefix.split(/\s+/);
194
- if (parts.length <= 1) {
195
- return ACTIONS.filter(action => action.startsWith(parts[0] ?? '')).map(action => ({ value: `${action} `, label: action }));
196
- }
197
- const [action, ref] = parts;
198
- if (!['show', 'runs', 'run', 'enable', 'disable', 'set', 'remove'].includes(action) || parts.length > 2) {
199
- return [];
200
- }
201
- return tasks
202
- .filter(task => task.id.startsWith(ref) || task.name.startsWith(ref))
203
- .map(task => ({ value: `${action} ${task.id} `, label: task.id, description: task.name }));
204
- }
205
-
206
- /** What to offer after `/loop `: the nicknames and a few durations. */
207
- export function loopCompletions(prefix: string): { value: string; label: string }[] {
208
- if (/\s/.test(prefix)) {
209
- return [];
210
- }
211
- return [...Object.keys(NICKNAMES), '5m', '30m', '1h', '1d'].filter(item => item.startsWith(prefix)).map(item => ({ value: `${item} `, label: item }));
212
- }
213
- }
214
-
215
- /** The answers of the commands and the tool in plain text: for the terminal and the model. */
216
- export namespace CronText {
217
- export function task(task: Task, now = new Date()): string {
218
- const state = !task.enabled
219
- ? 'off'
220
- : task.lastStatus === 'running'
221
- ? 'running'
222
- : task.nextRunAt
223
- ? `next ${ScheduleUtil.clock(new Date(task.nextRunAt), now)}`
224
- : 'done';
225
- const last = task.lastStatus && task.lastStatus !== 'running' ? `, last ${task.lastStatus}` : '';
226
- return `${task.id} ${task.name} (${ScheduleUtil.describe(task.schedule, 'en', now)}; ${state}${last}) in ${task.cwd}`;
227
- }
228
-
229
- export function run(run: Run, now = new Date()): string {
230
- const time = ScheduleUtil.clock(new Date(run.startedAt), now);
231
- const took = run.endedAt ? ` in ${Duration.format(new Date(run.endedAt).getTime() - new Date(run.startedAt).getTime())}` : '';
232
- const what = run.error ?? run.summary ?? '';
233
- const file = run.sessionFile ? `\n conversation: ${run.sessionFile}` : '';
234
- return `${run.id} ${time} ${run.status}${took}${run.trigger === 'manual' ? ' (by hand)' : ''}${what ? `\n ${what.replace(/\n/g, '\n ')}` : ''}${file}`;
235
- }
236
-
237
- export function reply(reply: Reply): string {
238
- switch (reply.kind) {
239
- case 'task':
240
- return `${capital(reply.event)}: ${task(reply.task)}`;
241
- case 'removed':
242
- return reply.tasks.length ? `Removed ${reply.tasks.map(item => item.name).join(', ')}.` : 'No tasks to remove.';
243
- case 'started':
244
- return `Started ${reply.task.name} (${reply.run.id}); it runs in a conversation of its own.`;
245
- case 'list':
246
- return reply.tasks.length ? reply.tasks.map(item => task(item)).join('\n') : 'No scheduled tasks. Make one with /loop or /remind.';
247
- case 'show':
248
- return `${task(reply.task)}\nprompt: ${reply.task.prompt}\n${reply.runs.length ? reply.runs.map(item => run(item)).join('\n') : 'No runs yet.'}`;
249
- case 'help':
250
- return HELP;
251
- case 'error':
252
- return reply.message;
253
- }
254
- }
255
-
256
- function capital(text: string): string {
257
- return text[0].toUpperCase() + text.slice(1);
258
- }
259
- }
@@ -1,41 +0,0 @@
1
- import { describe, expect, it } from 'bun:test';
2
- import { CronExpression } from './cron-expression';
3
-
4
- const at = (text: string) => new Date(text);
5
- const next = (expression: string, after: string) => CronExpression.parse(expression).next(at(after))?.toString();
6
-
7
- describe('CronExpression', () => {
8
- it('finds the next minute of simple rules, in local time', () => {
9
- expect(next('0 9 * * *', '2026-11-11T08:30:00')).toBe(at('2026-11-11T09:00:00').toString());
10
- expect(next('0 9 * * *', '2026-11-11T09:00:00')).toBe(at('2026-11-12T09:00:00').toString());
11
- expect(next('*/15 * * * *', '2026-11-11T10:07:42')).toBe(at('2026-11-11T10:15:00').toString());
12
- expect(next('@hourly', '2026-11-11T10:59:59')).toBe(at('2026-11-11T11:00:00').toString());
13
- });
14
-
15
- it('reads ranges, lists, steps and names', () => {
16
- // 2026-11-13 is a Friday, 11-14 a Saturday.
17
- expect(next('30 18 * * mon-fri', '2026-11-13T19:00:00')).toBe(at('2026-11-16T18:30:00').toString());
18
- expect(next('0 8,20 * * *', '2026-11-11T09:00:00')).toBe(at('2026-11-11T20:00:00').toString());
19
- expect(next('0 0 1 jan,jul *', '2026-11-11T00:00:00')).toBe(at('2027-01-01T00:00:00').toString());
20
- expect(next('5/20 * * * *', '2026-11-11T10:06:00')).toBe(at('2026-11-11T10:25:00').toString());
21
- expect(next('0 12 * * 7', '2026-11-11T00:00:00')).toBe(at('2026-11-15T12:00:00').toString());
22
- });
23
-
24
- it('matches either day when both are restricted, as cron does', () => {
25
- // The 20th, or a Monday (2026-11-16).
26
- expect(next('0 0 20 * 1', '2026-11-11T00:00:00')).toBe(at('2026-11-16T00:00:00').toString());
27
- });
28
-
29
- it('has no next time for a day that never comes', () => {
30
- expect(CronExpression.parse('0 0 30 2 *').next(at('2026-11-11T00:00:00'))).toBeUndefined();
31
- });
32
-
33
- it('says what is wrong', () => {
34
- expect(() => CronExpression.parse('0 9 * *')).toThrow('five fields');
35
- expect(() => CronExpression.parse('61 * * * *')).toThrow('minute');
36
- expect(() => CronExpression.parse('0 9 * * 1-8')).toThrow('day of week');
37
- expect(() => CronExpression.parse('0 5-1 * * *')).toThrow('backwards');
38
- expect(() => CronExpression.parse('*/0 * * * *')).toThrow('step');
39
- expect(CronExpression.isValid('@weekly')).toBe(true);
40
- });
41
- });
@@ -1,150 +0,0 @@
1
- /** A field of a cron expression: its range and the names it takes. */
2
- interface Field {
3
- name: string;
4
- min: number;
5
- max: number;
6
- names?: readonly string[];
7
- }
8
-
9
- const FIELDS: readonly Field[] = [
10
- { name: 'minute', min: 0, max: 59 },
11
- { name: 'hour', min: 0, max: 23 },
12
- { name: 'day of month', min: 1, max: 31 },
13
- { name: 'month', min: 1, max: 12, names: ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'] },
14
- // 7 is Sunday too.
15
- { name: 'day of week', min: 0, max: 7, names: ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'] },
16
- ];
17
-
18
- export const NICKNAMES: Readonly<Record<string, string>> = {
19
- '@yearly': '0 0 1 1 *',
20
- '@annually': '0 0 1 1 *',
21
- '@monthly': '0 0 1 * *',
22
- '@weekly': '0 0 * * 0',
23
- '@daily': '0 0 * * *',
24
- '@midnight': '0 0 * * *',
25
- '@hourly': '0 * * * *',
26
- };
27
-
28
- /** Minutes looked at for the next time, at most: past four years a rule such as `0 0 30 2 *` never matches. */
29
- const MAX_STEPS = 200_000;
30
-
31
- /**
32
- * A cron expression of five fields (minute, hour, day of month, month, day of week), as cron reads it, in
33
- * the local time of the Ta service: `*`, numbers, ranges `a-b`, lists `a,b`, steps `*\/n` and `a-b/n`, the
34
- * names of months and days (`jan`, `mon`), and the nicknames `@daily` and the like. When both days are
35
- * restricted, a day that matches either one matches, as in cron.
36
- */
37
- export class CronExpression {
38
- protected constructor(
39
- readonly source: string,
40
- protected readonly minutes: Set<number>,
41
- protected readonly hours: Set<number>,
42
- protected readonly days: Set<number>,
43
- protected readonly months: Set<number>,
44
- protected readonly weekdays: Set<number>,
45
- /** Whether each day field is `*`. */
46
- protected readonly anyDay: boolean,
47
- protected readonly anyWeekday: boolean,
48
- ) {}
49
-
50
- /** Throws with what is wrong. */
51
- static parse(text: string): CronExpression {
52
- const source = text.trim().replace(/\s+/g, ' ');
53
- const expanded = NICKNAMES[source.toLowerCase()] ?? source;
54
- const parts = expanded.split(' ');
55
- if (parts.length !== 5) {
56
- throw new Error(
57
- `A cron expression has five fields (minute hour day month weekday), or is one of ${Object.keys(NICKNAMES).join(', ')}: ${JSON.stringify(text)} has ${parts.length}.`,
58
- );
59
- }
60
- const sets = parts.map((part, index) => CronExpression.field(part, FIELDS[index]));
61
- const weekdays = sets[4];
62
- if (weekdays.delete(7)) {
63
- weekdays.add(0);
64
- }
65
- return new CronExpression(source, sets[0], sets[1], sets[2], sets[3], weekdays, parts[2] === '*', parts[4] === '*');
66
- }
67
-
68
- /** Whether the text is a valid expression. */
69
- static isValid(text: string): boolean {
70
- try {
71
- CronExpression.parse(text);
72
- return true;
73
- } catch {
74
- return false;
75
- }
76
- }
77
-
78
- protected static field(text: string, field: Field): Set<number> {
79
- const values = new Set<number>();
80
- for (const item of text.toLowerCase().split(',')) {
81
- const [range, stepText, extra] = item.split('/');
82
- const step = stepText === undefined ? 1 : Number(stepText);
83
- if (extra !== undefined || !Number.isInteger(step) || step < 1) {
84
- throw new Error(`${JSON.stringify(item)} is not a valid ${field.name}: a step is a whole number from 1.`);
85
- }
86
- let from: number;
87
- let to: number;
88
- if (range === '*') {
89
- from = field.min;
90
- to = field.max;
91
- } else {
92
- const [first, last, more] = range.split('-');
93
- if (more !== undefined) {
94
- throw new Error(`${JSON.stringify(item)} is not a valid ${field.name}.`);
95
- }
96
- from = CronExpression.value(first, field);
97
- // `5/15` is from 5 to the end, by 15.
98
- to = last === undefined ? (stepText === undefined ? from : field.max) : CronExpression.value(last, field);
99
- }
100
- if (from > to) {
101
- throw new Error(`${JSON.stringify(item)} is not a valid ${field.name}: the range goes backwards.`);
102
- }
103
- for (let value = from; value <= to; value += step) {
104
- values.add(value);
105
- }
106
- }
107
- return values;
108
- }
109
-
110
- protected static value(text: string, field: Field): number {
111
- const named = field.names?.indexOf(text) ?? -1;
112
- const value = named >= 0 ? named + (field.min === 1 ? 1 : 0) : /^\d+$/.test(text) ? Number(text) : Number.NaN;
113
- if (!(value >= field.min && value <= field.max)) {
114
- throw new Error(`${JSON.stringify(text)} is not a valid ${field.name}: from ${field.min} to ${field.max}.`);
115
- }
116
- return value;
117
- }
118
-
119
- /** The first time after `after` (a minute later at least) that matches; undefined when none comes in four years. */
120
- next(after: Date): Date | undefined {
121
- const time = new Date(after.getTime());
122
- time.setSeconds(0, 0);
123
- time.setMinutes(time.getMinutes() + 1);
124
- for (let step = 0; step < MAX_STEPS; step++) {
125
- if (!this.months.has(time.getMonth() + 1)) {
126
- time.setMonth(time.getMonth() + 1, 1);
127
- time.setHours(0, 0, 0, 0);
128
- } else if (!this.matchesDay(time)) {
129
- time.setDate(time.getDate() + 1);
130
- time.setHours(0, 0, 0, 0);
131
- } else if (!this.hours.has(time.getHours())) {
132
- time.setHours(time.getHours() + 1, 0, 0, 0);
133
- } else if (!this.minutes.has(time.getMinutes())) {
134
- time.setMinutes(time.getMinutes() + 1, 0, 0);
135
- } else {
136
- return time;
137
- }
138
- }
139
- return undefined;
140
- }
141
-
142
- protected matchesDay(time: Date): boolean {
143
- const day = this.days.has(time.getDate());
144
- const weekday = this.weekdays.has(time.getDay());
145
- if (this.anyDay || this.anyWeekday) {
146
- return day && weekday;
147
- }
148
- return day || weekday;
149
- }
150
- }
@@ -1,151 +0,0 @@
1
- /** The name of the package: of its data, its host and the group of the conversations of its runs. */
2
- export const NAME = '@celljs/ta-cron';
3
-
4
- /** TA_HOST_EVENT of @celljs/ta-protocol, which the bundle of the pi extension does not import. */
5
- export const TA_HOST_EVENT = 'ta:host';
6
-
7
- /** The custom message by which the commands answer: shown in the conversation, never read by the model. */
8
- export const REPLY_TYPE = 'ta-cron';
9
-
10
- /**
11
- * The start of what a run adds to the system prompt: the pi extension finds it there and keeps its tool
12
- * and commands out of the run, so that a scheduled run never schedules more work.
13
- */
14
- export const RUN_MARK = '<ta-cron-run>';
15
-
16
- /** When a task runs: once at a time, every so often, or when a cron expression of five fields says (local time). */
17
- export type Schedule = { kind: 'once'; at: string } | { kind: 'interval'; every: string } | { kind: 'cron'; expression: string };
18
-
19
- /** When a run says so in the pages of Ta: `always`, `error` (when it failed) or `never`. */
20
- export type NotifyLevel = 'always' | 'error' | 'never';
21
-
22
- export type RunStatus = 'running' | 'success' | 'error' | 'missed';
23
-
24
- /** A prompt and a time rule: what runs, where, and when it ran. */
25
- export interface Task {
26
- /** `task_` and 8 hexadecimal digits. */
27
- id: string;
28
- name: string;
29
- prompt: string;
30
- schedule: Schedule;
31
- /** Where its runs work: a path of the machine of the Ta service or an `ssh://` location. */
32
- cwd: string;
33
- /** `<provider>/<model id>`; default: the settings. */
34
- model?: string;
35
- thinking?: string;
36
- /** Default: `always` for a task that runs once, `error` for one that repeats. */
37
- notify?: NotifyLevel;
38
- enabled: boolean;
39
- /** ISO time of the next run; none once a task that ran once is done, or when its rule has no next time. */
40
- nextRunAt?: string;
41
- lastRunAt?: string;
42
- lastStatus?: RunStatus;
43
- runCount: number;
44
- failCount: number;
45
- createdAt: string;
46
- updatedAt: string;
47
- }
48
-
49
- /** One run of a task, in a conversation of its own. */
50
- export interface Run {
51
- /** `run_` and 8 hexadecimal digits. */
52
- id: string;
53
- taskId: string;
54
- /** `schedule`: its time came; `manual`: the user ran it, and its schedule stays as it was. */
55
- trigger: 'schedule' | 'manual';
56
- status: RunStatus;
57
- startedAt: string;
58
- endedAt?: string;
59
- /** The last answer of the run, cut to SUMMARY_MAX characters; the conversation holds all of it. */
60
- summary?: string;
61
- error?: string;
62
- /** Why it failed, when the Ta service knows: it stopped during the run, or the run took too long. */
63
- reason?: 'interrupted' | 'timeout';
64
- cwd: string;
65
- /** The conversation of the run, which the page opens. */
66
- sessionFile?: string;
67
- }
68
-
69
- /** The latest run that ended, for the pages that tell the user (the key LATEST_KEY). */
70
- export interface FinishedRun {
71
- run: Run;
72
- taskName: string;
73
- /** Whether the notify level of the task says to tell the user. */
74
- notify: boolean;
75
- }
76
-
77
- /** What makes a task; the rest has defaults. */
78
- export interface TaskInput {
79
- prompt: string;
80
- schedule: Schedule;
81
- name?: string;
82
- cwd?: string;
83
- model?: string;
84
- thinking?: string;
85
- notify?: NotifyLevel;
86
- enabled?: boolean;
87
- }
88
-
89
- /** What changes a task: a field left out stays; `''` (or `null`) clears model, thinking and notify. */
90
- export interface TaskPatch {
91
- name?: string;
92
- prompt?: string;
93
- schedule?: Schedule;
94
- cwd?: string;
95
- model?: string | null;
96
- thinking?: string | null;
97
- notify?: NotifyLevel | '' | null;
98
- enabled?: boolean;
99
- }
100
-
101
- /**
102
- * The scheduler in the Ta service (`pi.host`): the only writer of the tasks and their runs. Its pi
103
- * extension calls it in the process, its web extension with `callHost`; a task is named by its id, a
104
- * prefix of it, or its name.
105
- */
106
- export interface CronService {
107
- list(): Promise<Task[]>;
108
- get(ref: string): Promise<Task>;
109
- /** Newest first. */
110
- runs(ref: string, limit?: number): Promise<Run[]>;
111
- add(input: TaskInput): Promise<Task>;
112
- update(ref: string, patch: TaskPatch): Promise<Task>;
113
- setEnabled(ref: string, enabled: boolean): Promise<Task>;
114
- remove(ref: string): Promise<Task>;
115
- /** The tasks of a directory, or all of them without one; their runs go too. */
116
- clear(cwd?: string): Promise<Task[]>;
117
- /** Runs a task now, leaving its schedule as it is; resolves with the run once it started. */
118
- run(ref: string): Promise<Run>;
119
- }
120
-
121
- /** What a command answered, in `details` of its REPLY_TYPE message: the page shows it in its language. */
122
- export type Reply =
123
- | { kind: 'task'; event: 'created' | 'updated' | 'enabled' | 'disabled'; task: Task }
124
- | { kind: 'removed'; tasks: Task[] }
125
- | { kind: 'started'; task: Task; run: Run }
126
- | { kind: 'list'; tasks: Task[] }
127
- | { kind: 'show'; task: Task; runs: Run[] }
128
- | { kind: 'help' }
129
- | { kind: 'error'; message: string };
130
-
131
- export namespace Keys {
132
- export const TASKS = 'tasks';
133
- export const LATEST = 'latest';
134
- export function runs(taskId: string): string {
135
- return `runs/${taskId}`;
136
- }
137
- }
138
-
139
- export namespace Limits {
140
- /** The runs kept per task, newest first. */
141
- export const RUNS_KEPT = 20;
142
- export const SUMMARY_MAX = 4000;
143
- /** The shortest interval. */
144
- export const MIN_INTERVAL_MS = 60_000;
145
- /** A run that takes longer is stopped and fails. */
146
- export const RUN_TIMEOUT_MS = 30 * 60_000;
147
- /** A task that runs once and whose time passed by more than this while the Ta service was not running is missed, not run. */
148
- export const GRACE_MS = 5 * 60_000;
149
- /** Runs at the same time; the others wait for one to end. */
150
- export const PARALLEL_RUNS = 3;
151
- }