@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,249 +0,0 @@
1
- import type { Task } from './cron-protocol';
2
- import { FormUtil, type RepeatKind, type TaskForm, type Unit } from './form-util';
3
- import type { Words } from './i18n';
4
- import { ModelPicker, useModels } from './model-picker';
5
- import { basename, type CronClient, message, pi, t } from './page';
6
- import { React } from './react';
7
- import { ScheduleUtil, THINKING_LEVELS } from './schedule-util';
8
-
9
- /** A task being made (`task` none) or changed, in a dialog over the page. */
10
- export interface Editing {
11
- task?: Task;
12
- /** What a new one starts with, as an example fills it. */
13
- prompt?: string;
14
- repeat?: RepeatKind;
15
- }
16
-
17
- const REPEATS: RepeatKind[] = ['every', 'daily', 'weekdays', 'weekly', 'custom'];
18
- const UNITS: [Unit, keyof Words][] = [
19
- ['m', 'minutes'],
20
- ['h', 'hours'],
21
- ['d', 'days'],
22
- ];
23
- const NOTIFY: [TaskForm['notify'], keyof Words][] = [
24
- ['', 'notifyDefault'],
25
- ['always', 'notifyAlways'],
26
- ['error', 'notifyError'],
27
- ['never', 'notifyNever'],
28
- ];
29
-
30
- function weekdayNames(): string[] {
31
- const format = new Intl.DateTimeFormat(pi.ui.language === 'zh-CN' ? 'zh-CN' : 'en', { weekday: 'short' });
32
- // 2023-01-01 was a Sunday.
33
- return Array.from({ length: 7 }, (_, day) => format.format(new Date(2023, 0, 1 + day)));
34
- }
35
-
36
- function Segments<T extends string>({ value, options, onChange }: { value: T; options: [T, string][]; onChange(value: T): void }) {
37
- return (
38
- <div className="tcr-segments">
39
- {options.map(([key, label]) => (
40
- <button key={key} type="button" aria-pressed={value === key} className="tcr-segment" onClick={() => onChange(key)}>
41
- {label}
42
- </button>
43
- ))}
44
- </div>
45
- );
46
- }
47
-
48
- /** The model and the thinking level of the runs; the default is that of the settings. */
49
- function ModelFields({ form, set, cwd }: { form: TaskForm; set(change: Partial<TaskForm>): void; cwd: string }) {
50
- const models = useModels(cwd);
51
- return (
52
- <div className="tcr-grid">
53
- <div className="tcr-field">
54
- <span className="tcr-label">{t('model')}</span>
55
- <ModelPicker models={models} value={form.model} onChange={model => set({ model })} />
56
- </div>
57
- <label className="tcr-field">
58
- <span className="tcr-label">{t('thinking')}</span>
59
- <select className="tcr-input" name="thinking" value={form.thinking} onChange={event => set({ thinking: event.target.value })}>
60
- <option value="">{t('notifyDefault')}</option>
61
- {THINKING_LEVELS.map(level => (
62
- <option key={level} value={level}>
63
- {level}
64
- </option>
65
- ))}
66
- </select>
67
- </label>
68
- </div>
69
- );
70
- }
71
-
72
- /** The controls of when a task runs, with the next time it would. */
73
- function When({ form, set }: { form: TaskForm; set(change: Partial<TaskForm>): void }) {
74
- const preview = FormUtil.preview(form, new Date());
75
- const days = weekdayNames();
76
- let rule: React.ReactNode = null;
77
- if (form.mode === 'once') {
78
- rule = <input className="tcr-input" type="datetime-local" value={form.at} onChange={event => set({ at: event.target.value })} />;
79
- } else if (form.repeat === 'every') {
80
- rule = (
81
- <div className="tcr-row">
82
- <input
83
- className="tcr-input tcr-amount"
84
- type="number"
85
- min={1}
86
- value={form.amount}
87
- onChange={event => set({ amount: Number(event.target.value) })}
88
- />
89
- <select className="tcr-input" value={form.unit} onChange={event => set({ unit: event.target.value as Unit })}>
90
- {UNITS.map(([unit, word]) => (
91
- <option key={unit} value={unit}>
92
- {t(word)}
93
- </option>
94
- ))}
95
- </select>
96
- </div>
97
- );
98
- } else if (form.repeat === 'custom') {
99
- rule = <input className="tcr-input tcr-mono" value={form.cron} placeholder="0 9 * * 1-5" onChange={event => set({ cron: event.target.value })} />;
100
- } else {
101
- rule = (
102
- <div className="tcr-row">
103
- {form.repeat === 'weekly' && (
104
- <select className="tcr-input" value={form.weekday} onChange={event => set({ weekday: Number(event.target.value) })}>
105
- {days.map((day, index) => (
106
- <option key={day} value={index}>
107
- {day}
108
- </option>
109
- ))}
110
- </select>
111
- )}
112
- <input className="tcr-input" type="time" value={form.time} onChange={event => set({ time: event.target.value })} />
113
- </div>
114
- );
115
- }
116
- return (
117
- <div className="tcr-field">
118
- <div className="tcr-label">{t('when')}</div>
119
- <Segments
120
- value={form.mode}
121
- options={[
122
- ['repeat', t('repeat')],
123
- ['once', t('once')],
124
- ]}
125
- onChange={mode => set({ mode })}
126
- />
127
- {form.mode === 'repeat' && <Segments value={form.repeat} options={REPEATS.map(kind => [kind, t(kind)])} onChange={repeat => set({ repeat })} />}
128
- {rule}
129
- <div className={`tcr-preview${preview.error === undefined ? '' : ' tcr-bad'}`}>
130
- {preview.next ? t('preview', { time: ScheduleUtil.clock(preview.next) }) : preview.error || t('noNext')}
131
- </div>
132
- </div>
133
- );
134
- }
135
-
136
- /** The dialog of a task: what Ta does, when, where, and when it tells the user. */
137
- export function TaskEditor({ client, editing, onClose }: { client: CronClient; editing: Editing; onClose(): void }) {
138
- const Dialog = pi.ui.Dialog;
139
- const FolderPicker = pi.ui.FolderPicker;
140
- const cwd = pi.ui.useCwd();
141
- const [form, setForm] = React.useState<TaskForm>(() => {
142
- const now = new Date();
143
- if (editing.task) {
144
- return FormUtil.fromTask(editing.task, now);
145
- }
146
- const empty = FormUtil.empty(cwd, now);
147
- return { ...empty, prompt: editing.prompt ?? '', repeat: editing.repeat ?? empty.repeat };
148
- });
149
- const [picking, setPicking] = React.useState(false);
150
- const [more, setMore] = React.useState(!!(form.name && editing.task) || !!form.notify);
151
- const [saving, setSaving] = React.useState(false);
152
- const set = (change: Partial<TaskForm>) => setForm(current => ({ ...current, ...change }));
153
- const valid = form.prompt.trim().length > 0 && !!FormUtil.preview(form, new Date()).next;
154
- const save = async () => {
155
- if (!valid || saving) {
156
- return;
157
- }
158
- setSaving(true);
159
- try {
160
- const input = FormUtil.input(form);
161
- if (editing.task) {
162
- await client.call('update', editing.task.id, { ...input, name: form.name, model: form.model, thinking: form.thinking, notify: form.notify });
163
- } else {
164
- await client.call('add', input);
165
- // Asked once, on a click: the page tells of runs that end while it is hidden.
166
- if (typeof Notification !== 'undefined' && Notification.permission === 'default') {
167
- void Notification.requestPermission().catch(() => undefined);
168
- }
169
- }
170
- onClose();
171
- } catch (error) {
172
- pi.ui.notify(t('failedAction', { message: message(error) }), 'error');
173
- } finally {
174
- setSaving(false);
175
- }
176
- };
177
- return (
178
- <Dialog title={editing.task ? t('editTask') : t('newTask')} onClose={onClose}>
179
- <div className="tcr-form">
180
- <label className="tcr-field">
181
- <span className="tcr-label">{t('prompt')}</span>
182
- <textarea
183
- className="tcr-input tcr-prompt"
184
- rows={4}
185
- value={form.prompt}
186
- placeholder={t('promptPlaceholder')}
187
- autoFocus
188
- onChange={event => set({ prompt: event.target.value })}
189
- onKeyDown={event => (event.metaKey || event.ctrlKey) && event.key === 'Enter' && void save()}
190
- />
191
- </label>
192
- <When form={form} set={set} />
193
- <div className="tcr-field">
194
- <span className="tcr-label">{t('directory')}</span>
195
- <button type="button" className="tcr-input tcr-folder" title={form.cwd} onClick={() => setPicking(true)}>
196
- {basename(form.cwd || cwd)}
197
- <span className="tcr-folder-path">{form.cwd || cwd}</span>
198
- </button>
199
- </div>
200
- <ModelFields form={form} set={set} cwd={form.cwd || cwd} />
201
- {more ? (
202
- <div className="tcr-grid">
203
- <label className="tcr-field">
204
- <span className="tcr-label">{t('name')}</span>
205
- <input
206
- className="tcr-input"
207
- value={form.name}
208
- placeholder={t('namePlaceholder')}
209
- onChange={event => set({ name: event.target.value })}
210
- />
211
- </label>
212
- <label className="tcr-field">
213
- <span className="tcr-label">{t('notify')}</span>
214
- <select className="tcr-input" value={form.notify} onChange={event => set({ notify: event.target.value as TaskForm['notify'] })}>
215
- {NOTIFY.map(([level, word]) => (
216
- <option key={level} value={level}>
217
- {t(word)}
218
- </option>
219
- ))}
220
- </select>
221
- </label>
222
- </div>
223
- ) : (
224
- <button type="button" className="tcr-link" onClick={() => setMore(true)}>
225
- {t('more')}
226
- </button>
227
- )}
228
- <div className="tcr-actions">
229
- <button type="button" className="tcr-button" onClick={onClose}>
230
- {t('cancel')}
231
- </button>
232
- <button type="button" className="tcr-button tcr-primary" disabled={!valid || saving} onClick={() => void save()}>
233
- {editing.task ? t('save') : t('create')}
234
- </button>
235
- </div>
236
- </div>
237
- {picking && (
238
- <FolderPicker
239
- initial={form.cwd || cwd}
240
- onPick={path => {
241
- set({ cwd: path });
242
- setPicking(false);
243
- }}
244
- onClose={() => setPicking(false)}
245
- />
246
- )}
247
- </Dialog>
248
- );
249
- }
@@ -1,187 +0,0 @@
1
- import type { TaExtensionHost } from '@celljs/ta-protocol';
2
- import { CommandParser, CronText } from './commands';
3
- import { NAME, REPLY_TYPE, type Reply, RUN_MARK, TA_HOST_EVENT, type TaskInput } from './cron-protocol';
4
- import type { CronScheduler } from './scheduler';
5
- import { CronServerTexts } from './server-texts';
6
- import { CronTool } from './tool';
7
-
8
- /** Under the Ta service the host answers at once; `ta` alone has nobody to answer. */
9
- const HOST_WAIT_MS = 1000;
10
-
11
- export const NO_SERVER = 'Scheduled tasks need the Ta service, which runs them: start it with `ta serve` (or open Ta Desktop) and talk to Ta in its page.';
12
- export const NO_SCHEDULER = 'The scheduler did not start in the Ta service; its log says why.';
13
- export const NOT_IN_RUN = 'This is a scheduled run: it does not schedule more work. Say in your summary what should be scheduled.';
14
-
15
- /** The little of pi's extension API this uses. */
16
- interface Context {
17
- hasUI: boolean;
18
- getSystemPrompt(): string;
19
- sessionManager: { getSessionId(): string };
20
- ui: { confirm(title: string, message: string): Promise<boolean> };
21
- }
22
- interface Message {
23
- role: string;
24
- customType?: string;
25
- }
26
- interface Pi {
27
- events: { emit(event: string, data: unknown): void };
28
- on(event: string, handler: (event: never, ctx: never) => unknown): unknown;
29
- registerTool(tool: never): unknown;
30
- registerCommand(name: string, options: never): void;
31
- getActiveTools(): string[];
32
- setActiveTools(names: string[]): void;
33
- sendMessage(message: { customType: string; content: string; display: boolean; details: unknown }): void;
34
- }
35
- interface Reached {
36
- answered: boolean;
37
- host?: TaExtensionHost;
38
- scheduler?: CronScheduler;
39
- }
40
-
41
- /**
42
- * The pi extension: `/loop`, `/remind` and `/schedule`, and the tool `schedule_task`, for every
43
- * conversation but those of runs. They work with the scheduler of the Ta service (host.ts); without it
44
- * they say so. Their answers are messages the page shows and the model never reads.
45
- */
46
- export default function activate(pi: Pi): void {
47
- let reached: Promise<Reached> | undefined;
48
- const reach = () =>
49
- (reached ??= new Promise(resolve => {
50
- const timer = setTimeout(() => resolve({ answered: false }), HOST_WAIT_MS);
51
- pi.events.emit(TA_HOST_EVENT, {
52
- name: NAME,
53
- resolve: (answer: { host?: TaExtensionHost; service?: unknown }) => {
54
- clearTimeout(timer);
55
- resolve({ answered: true, host: answer.host, scheduler: answer.service as CronScheduler | undefined });
56
- },
57
- });
58
- }));
59
- const isRun = (ctx: Context) => ctx.getSystemPrompt().includes(RUN_MARK);
60
- const scheduler = async (ctx: Context): Promise<{ scheduler: CronScheduler; cwd: () => Promise<string | undefined> }> => {
61
- if (isRun(ctx)) {
62
- throw new Error(NOT_IN_RUN);
63
- }
64
- const found = await reach();
65
- if (!found.scheduler || !found.host) {
66
- throw new Error(found.answered ? NO_SCHEDULER : NO_SERVER);
67
- }
68
- const host = found.host;
69
- // Where this conversation works, as the clients name it (a path or an ssh:// location).
70
- const cwd = async () => (await host.listSessions()).find(info => info.piSessionId === ctx.sessionManager.getSessionId())?.cwd;
71
- return { scheduler: found.scheduler, cwd };
72
- };
73
-
74
- pi.on('session_start', () => {
75
- void reach();
76
- });
77
- pi.on('before_agent_start', (_event: unknown, ctx: Context) => {
78
- if (isRun(ctx)) {
79
- pi.setActiveTools(pi.getActiveTools().filter(name => name !== CronTool.NAME));
80
- }
81
- });
82
- // The answers of the commands are for the user.
83
- pi.on('context', (event: { messages: Message[] }) => {
84
- const messages = event.messages.filter(message => !(message.role === 'custom' && message.customType === REPLY_TYPE));
85
- return messages.length === event.messages.length ? undefined : { messages };
86
- });
87
-
88
- pi.registerTool(<never>{
89
- ...CronTool.DEFINITION,
90
- execute: async (_id: string, params: Record<string, unknown>, _signal: unknown, _update: unknown, ctx: Context) => {
91
- const found = await scheduler(ctx);
92
- const text = await CronTool.run(found.scheduler, params ?? {}, {
93
- cwd: found.cwd,
94
- confirm: (title, message) => (ctx.hasUI ? ctx.ui.confirm(title, message) : Promise.resolve(false)),
95
- });
96
- return { content: [{ type: 'text', text }], details: undefined };
97
- },
98
- });
99
-
100
- const reply = (answer: Reply) => pi.sendMessage({ customType: REPLY_TYPE, content: CronText.reply(answer), display: true, details: answer });
101
- const command = (
102
- name: string,
103
- description: string,
104
- handle: (args: string, found: Awaited<ReturnType<typeof scheduler>>, ctx: Context) => Promise<Reply>,
105
- completions?: (prefix: string) => unknown,
106
- ) =>
107
- pi.registerCommand(name, <never>{
108
- description,
109
- getArgumentCompletions: completions,
110
- handler: async (args: string, ctx: Context) => {
111
- try {
112
- reply(await handle(args, await scheduler(ctx), ctx));
113
- } catch (error) {
114
- reply({ kind: 'error', message: error instanceof Error ? error.message : String(error) });
115
- }
116
- },
117
- });
118
- const create = async (input: TaskInput, found: Awaited<ReturnType<typeof scheduler>>): Promise<Reply> => {
119
- const cwd = input.cwd ?? (await found.cwd());
120
- return { kind: 'task', event: 'created', task: await found.scheduler.add({ ...input, ...(cwd ? { cwd } : {}) }) };
121
- };
122
-
123
- command(
124
- 'loop',
125
- 'Run a prompt on a schedule: /loop 30m <prompt>, /loop @daily <prompt>, /loop "0 9 * * 1-5" <prompt>',
126
- (args, found) => create(CommandParser.repeating(args), found),
127
- prefix => CommandParser.loopCompletions(prefix),
128
- );
129
- command('remind', 'Run a prompt once: /remind in 45m <prompt>, /remind at 15:30 <prompt>', (args, found) =>
130
- create(CommandParser.reminder(args, new Date()), found),
131
- );
132
- let known: Awaited<ReturnType<CronScheduler['list']>> = [];
133
- command(
134
- 'schedule',
135
- 'Scheduled tasks: list, show, run, enable, disable, set, remove, clear, help',
136
- async (args, found, ctx) => {
137
- const { action, rest } = CommandParser.action(args);
138
- const { scheduler } = found;
139
- switch (action) {
140
- case 'add':
141
- return create(CommandParser.repeating(rest), found);
142
- case 'list':
143
- known = await scheduler.list();
144
- return { kind: 'list', tasks: known };
145
- case 'show':
146
- case 'runs': {
147
- const task = await scheduler.get(rest);
148
- return { kind: 'show', task, runs: await scheduler.runs(task.id, 10) };
149
- }
150
- case 'run': {
151
- const task = await scheduler.get(rest);
152
- return { kind: 'started', task, run: await scheduler.run(task.id) };
153
- }
154
- case 'enable':
155
- case 'disable':
156
- return { kind: 'task', event: `${action}d`, task: await scheduler.setEnabled(rest, action === 'enable') };
157
- case 'set': {
158
- const { ref, patch } = CommandParser.patch(rest);
159
- return { kind: 'task', event: 'updated', task: await scheduler.update(ref, patch) };
160
- }
161
- case 'remove': {
162
- const task = await scheduler.get(rest);
163
- if (ctx.hasUI && !(await ctx.ui.confirm(...CronServerTexts.removeTask(task.name)))) {
164
- return { kind: 'removed', tasks: [] };
165
- }
166
- return { kind: 'removed', tasks: [await scheduler.remove(task.id)] };
167
- }
168
- case 'clear': {
169
- const cwd = await found.cwd();
170
- const tasks = (await scheduler.list()).filter(task => task.cwd === cwd);
171
- if (tasks.length === 0 || (ctx.hasUI && !(await ctx.ui.confirm(...CronServerTexts.removeTasks(tasks.length))))) {
172
- return { kind: 'removed', tasks: [] };
173
- }
174
- return { kind: 'removed', tasks: await scheduler.clear(cwd) };
175
- }
176
- case 'help':
177
- return { kind: 'help' };
178
- }
179
- },
180
- prefix => {
181
- void reach().then(async found => {
182
- known = (await found.scheduler?.list()) ?? known;
183
- });
184
- return CommandParser.completions(prefix, known);
185
- },
186
- );
187
- }
@@ -1,33 +0,0 @@
1
- import { describe, expect, it } from 'bun:test';
2
- import type { Task } from './cron-protocol';
3
- import { FormUtil } from './form-util';
4
-
5
- describe('FormUtil', () => {
6
- const now = new Date('2026-11-11T10:20:00');
7
-
8
- it('makes rules from the controls, and shows the next run', () => {
9
- const form = FormUtil.empty('/work', now);
10
- expect(FormUtil.schedule(form)).toEqual({ kind: 'cron', expression: '0 9 * * *' });
11
- expect(FormUtil.schedule({ ...form, repeat: 'weekly', weekday: 5, time: '18:30' })).toEqual({ kind: 'cron', expression: '30 18 * * 5' });
12
- expect(FormUtil.schedule({ ...form, repeat: 'every', amount: 2, unit: 'h' })).toEqual({ kind: 'interval', every: '2h' });
13
- expect(FormUtil.preview(form, now).next).toEqual(new Date('2026-11-12T09:00:00'));
14
- expect(FormUtil.preview({ ...form, repeat: 'custom', cron: '0 9 *' }, now).error).toContain('five fields');
15
- expect(FormUtil.schedule({ ...form, mode: 'once' })).toEqual({ kind: 'once', at: new Date('2026-11-11T11:00:00').toISOString() });
16
- });
17
-
18
- it('reads a task back into the controls that say its rule', () => {
19
- const task = { prompt: 'p', name: 'n', cwd: '/w', schedule: { kind: 'cron', expression: '15 8 * * 1-5' } } as Task;
20
- expect(FormUtil.fromTask(task, now)).toMatchObject({ mode: 'repeat', repeat: 'weekdays', time: '08:15' });
21
- expect(FormUtil.fromTask({ ...task, schedule: { kind: 'interval', every: '2h' } }, now)).toMatchObject({ repeat: 'every', amount: 2, unit: 'h' });
22
- expect(FormUtil.fromTask({ ...task, model: 'openai/gpt-5', thinking: 'high' }, now)).toMatchObject({ model: 'openai/gpt-5', thinking: 'high' });
23
- expect(FormUtil.input({ ...FormUtil.empty('/w', now), prompt: 'p', model: 'openai/gpt-5', thinking: 'low' })).toMatchObject({
24
- model: 'openai/gpt-5',
25
- thinking: 'low',
26
- });
27
- expect(FormUtil.input({ ...FormUtil.empty('/w', now), prompt: 'p' })).toMatchObject({ model: undefined, thinking: undefined });
28
- expect(FormUtil.fromTask({ ...task, schedule: { kind: 'cron', expression: '0 0 1,15 * *' } }, now)).toMatchObject({
29
- repeat: 'custom',
30
- cron: '0 0 1,15 * *',
31
- });
32
- });
33
- });
@@ -1,141 +0,0 @@
1
- import { NICKNAMES } from './cron-expression';
2
- import type { NotifyLevel, Schedule, Task, TaskInput } from './cron-protocol';
3
- import { Duration, ScheduleUtil } from './schedule-util';
4
-
5
- export type RepeatKind = 'every' | 'daily' | 'weekdays' | 'weekly' | 'custom';
6
- export type Unit = 'm' | 'h' | 'd';
7
-
8
- /** What the dialog of a task holds, as the user fills it in. */
9
- export interface TaskForm {
10
- prompt: string;
11
- name: string;
12
- mode: 'repeat' | 'once';
13
- repeat: RepeatKind;
14
- amount: number;
15
- unit: Unit;
16
- /** `09:00`. */
17
- time: string;
18
- /** 0 is Sunday. */
19
- weekday: number;
20
- cron: string;
21
- /** As an input of type datetime-local holds it: `2026-11-12T09:00`, local time. */
22
- at: string;
23
- cwd: string;
24
- notify: NotifyLevel | '';
25
- model: string;
26
- thinking: string;
27
- }
28
-
29
- function pad(value: number): string {
30
- return String(value).padStart(2, '0');
31
- }
32
-
33
- export namespace FormUtil {
34
- export function localTime(date: Date): string {
35
- return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
36
- }
37
-
38
- export function empty(cwd: string, now: Date): TaskForm {
39
- const soon = new Date(now.getTime() + 60 * 60_000);
40
- soon.setMinutes(0, 0, 0);
41
- return {
42
- prompt: '',
43
- name: '',
44
- mode: 'repeat',
45
- repeat: 'daily',
46
- amount: 30,
47
- unit: 'm',
48
- time: '09:00',
49
- weekday: 1,
50
- cron: '0 9 * * *',
51
- at: localTime(soon),
52
- cwd,
53
- notify: '',
54
- model: '',
55
- thinking: '',
56
- };
57
- }
58
-
59
- /** The form of a task, its rule in the controls that say it. */
60
- export function fromTask(task: Task, now: Date): TaskForm {
61
- const form: TaskForm = {
62
- ...empty(task.cwd, now),
63
- prompt: task.prompt,
64
- name: task.name,
65
- cwd: task.cwd,
66
- notify: task.notify ?? '',
67
- model: task.model ?? '',
68
- thinking: task.thinking ?? '',
69
- };
70
- return { ...form, ...ruleOf(task.schedule) };
71
- }
72
-
73
- function ruleOf(schedule: Schedule): Partial<TaskForm> {
74
- if (schedule.kind === 'once') {
75
- return { mode: 'once', at: localTime(new Date(schedule.at)) };
76
- }
77
- if (schedule.kind === 'interval') {
78
- const ms = Duration.parse(schedule.every) ?? 30 * 60_000;
79
- const [amount, unit]: [number, Unit] =
80
- ms % 86_400_000 === 0 ? [ms / 86_400_000, 'd'] : ms % 3_600_000 === 0 ? [ms / 3_600_000, 'h'] : [Math.round(ms / 60_000), 'm'];
81
- return { mode: 'repeat', repeat: 'every', amount, unit };
82
- }
83
- const [minute, hour, day, month, weekday] = (NICKNAMES[schedule.expression.toLowerCase()] ?? schedule.expression).split(' ');
84
- const simple = /^\d+$/.test(minute) && /^\d+$/.test(hour) && day === '*' && month === '*';
85
- const time = `${pad(Number(hour))}:${pad(Number(minute))}`;
86
- if (simple && weekday === '*') {
87
- return { mode: 'repeat', repeat: 'daily', time, cron: schedule.expression };
88
- }
89
- if (simple && weekday === '1-5') {
90
- return { mode: 'repeat', repeat: 'weekdays', time, cron: schedule.expression };
91
- }
92
- if (simple && /^[0-7]$/.test(weekday)) {
93
- return { mode: 'repeat', repeat: 'weekly', time, weekday: Number(weekday) % 7, cron: schedule.expression };
94
- }
95
- return { mode: 'repeat', repeat: 'custom', cron: schedule.expression };
96
- }
97
-
98
- /** The rule the form says; throws with what is wrong. */
99
- export function schedule(form: TaskForm): Schedule {
100
- if (form.mode === 'once') {
101
- return ScheduleUtil.check({ kind: 'once', at: form.at });
102
- }
103
- const time = /^(\d{1,2}):(\d{2})$/.exec(form.time);
104
- const [hour, minute] = time ? [Number(time[1]), Number(time[2])] : [9, 0];
105
- switch (form.repeat) {
106
- case 'every':
107
- return ScheduleUtil.check({ kind: 'interval', every: `${Math.max(1, Math.floor(form.amount || 0))}${form.unit}` });
108
- case 'daily':
109
- return ScheduleUtil.check({ kind: 'cron', expression: `${minute} ${hour} * * *` });
110
- case 'weekdays':
111
- return ScheduleUtil.check({ kind: 'cron', expression: `${minute} ${hour} * * 1-5` });
112
- case 'weekly':
113
- return ScheduleUtil.check({ kind: 'cron', expression: `${minute} ${hour} * * ${form.weekday}` });
114
- case 'custom':
115
- return ScheduleUtil.check({ kind: 'cron', expression: form.cron });
116
- }
117
- }
118
-
119
- /** The next run of the form, or the reason there is none. */
120
- export function preview(form: TaskForm, now: Date): { next?: Date; error?: string } {
121
- try {
122
- const next = ScheduleUtil.next(schedule(form), now);
123
- return next ? { next } : { error: '' };
124
- } catch (error) {
125
- return { error: error instanceof Error ? error.message : String(error) };
126
- }
127
- }
128
-
129
- /** What the scheduler takes to make or change the task. */
130
- export function input(form: TaskForm): TaskInput {
131
- return {
132
- prompt: form.prompt,
133
- name: form.name.trim() || undefined,
134
- schedule: schedule(form),
135
- cwd: form.cwd || undefined,
136
- model: form.model || undefined,
137
- thinking: form.thinking || undefined,
138
- notify: form.notify || undefined,
139
- };
140
- }
141
- }
package/web-src/host.ts DELETED
@@ -1,12 +0,0 @@
1
- import type { TaExtensionHost, TaPackageService } from '@celljs/ta-protocol';
2
- import { CronScheduler } from './scheduler';
3
-
4
- /**
5
- * The server side of the package (`pi.host`): the Ta service runs it once, and it runs the tasks while the
6
- * service runs, with no page open. Its pi extension and its web extension reach the same scheduler.
7
- */
8
- export default async function activate(host: TaExtensionHost): Promise<TaPackageService> {
9
- const scheduler = new CronScheduler(host);
10
- await scheduler.start();
11
- return scheduler;
12
- }