@celljs/ta-cron 4.8.0 → 4.9.1

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,174 +0,0 @@
1
- import { Limits, type NotifyLevel, RUN_MARK, type Task, type TaskInput, type TaskPatch } from './cron-protocol';
2
- import { NOTIFY_LEVELS, ScheduleUtil, THINKING_LEVELS } from './schedule-util';
3
-
4
- const PROMPT_MAX = 20_000;
5
- const NAME_MAX = 80;
6
- /** A prefix of an id names a task from this many characters on. */
7
- const PREFIX_MIN = 4;
8
-
9
- /** Making, changing and finding tasks: what holds whatever runs them. */
10
- export namespace TaskUtil {
11
- export function newId(prefix: 'task' | 'run'): string {
12
- const bytes = new Uint8Array(4);
13
- crypto.getRandomValues(bytes);
14
- return `${prefix}_${Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('')}`;
15
- }
16
-
17
- /** A new task, checked; throws with what is wrong. `cwd` is where it runs when the input names none. */
18
- export function create(input: TaskInput, cwd: string, now: Date): Task {
19
- const prompt = checkPrompt(input?.prompt);
20
- const schedule = ScheduleUtil.check(input.schedule);
21
- const at = now.toISOString();
22
- const task: Task = {
23
- id: newId('task'),
24
- name: checkName(input.name) ?? defaultName(prompt),
25
- prompt,
26
- schedule,
27
- cwd: checkCwd(input.cwd) ?? cwd,
28
- enabled: input.enabled !== false,
29
- runCount: 0,
30
- failCount: 0,
31
- createdAt: at,
32
- updatedAt: at,
33
- };
34
- setOptional(task, input);
35
- return arm(task, now);
36
- }
37
-
38
- /** The task with the patch applied, its next run worked out again when its rule changed or it was turned on. */
39
- export function patch(task: Task, patch: TaskPatch, now: Date): Task {
40
- const next: Task = { ...task, updatedAt: now.toISOString() };
41
- if (patch.prompt !== undefined) {
42
- next.prompt = checkPrompt(patch.prompt);
43
- }
44
- if (patch.name !== undefined) {
45
- next.name = checkName(patch.name) ?? defaultName(next.prompt);
46
- }
47
- if (patch.cwd !== undefined) {
48
- next.cwd = checkCwd(patch.cwd) ?? task.cwd;
49
- }
50
- setOptional(next, patch);
51
- if (patch.enabled !== undefined) {
52
- next.enabled = patch.enabled === true;
53
- }
54
- if (patch.schedule !== undefined) {
55
- next.schedule = ScheduleUtil.check(patch.schedule);
56
- }
57
- const rearm = patch.schedule !== undefined || (next.enabled && !task.enabled);
58
- return rearm ? arm(next, now) : next;
59
- }
60
-
61
- /** Works out the next run of an enabled task from now; throws when its rule has none. */
62
- export function arm(task: Task, now: Date): Task {
63
- if (!task.enabled) {
64
- return task;
65
- }
66
- const next = ScheduleUtil.next(task.schedule, now);
67
- if (!next) {
68
- throw new Error(
69
- task.schedule.kind === 'once'
70
- ? `The time of ${task.name} (${task.schedule.at}) has passed: give it a time to come.`
71
- : `The rule of ${task.name} never comes round: check the cron expression.`,
72
- );
73
- }
74
- return { ...task, nextRunAt: next.toISOString() };
75
- }
76
-
77
- /** The task named by its id, a prefix of its id or its name; throws naming the tasks there are. */
78
- export function find(tasks: readonly Task[], ref: unknown): Task {
79
- const text = typeof ref === 'string' ? ref.trim() : '';
80
- const found =
81
- tasks.find(task => task.id === text) ??
82
- tasks.find(task => task.name === text) ??
83
- (text.length >= PREFIX_MIN ? only(tasks.filter(task => task.id.startsWith(text))) : undefined);
84
- if (!found) {
85
- const known = tasks.length ? tasks.map(task => `${task.id} (${task.name})`).join(', ') : 'none yet';
86
- throw new Error(`No task is ${JSON.stringify(text)}. The tasks: ${known}.`);
87
- }
88
- return found;
89
- }
90
-
91
- /** What a run adds to the system prompt: that nobody watches it, and that it ends with a summary. */
92
- export function systemPrompt(task: Task, now: Date): string {
93
- return [
94
- RUN_MARK,
95
- `This conversation is a scheduled run of the task "${task.name}" (${ScheduleUtil.describe(task.schedule, 'en', now)}), started by the Ta service at ${now.toISOString()}.`,
96
- 'Nobody watches it while it runs: do the work without asking the user anything, and end with a short summary of what you found or did, which the user reads first.',
97
- '</ta-cron-run>',
98
- ].join('\n');
99
- }
100
-
101
- function only(tasks: Task[]): Task | undefined {
102
- return tasks.length === 1 ? tasks[0] : undefined;
103
- }
104
-
105
- function setOptional(task: Task, input: TaskInput | TaskPatch): void {
106
- if (input.model !== undefined) {
107
- task.model = checkModel(input.model);
108
- }
109
- if (input.thinking !== undefined) {
110
- task.thinking = checkThinking(input.thinking);
111
- }
112
- if (input.notify !== undefined) {
113
- task.notify = checkNotify(input.notify);
114
- }
115
- for (const key of ['model', 'thinking', 'notify'] as const) {
116
- if (task[key] === undefined) {
117
- delete task[key];
118
- }
119
- }
120
- }
121
-
122
- function checkPrompt(value: unknown): string {
123
- const prompt = typeof value === 'string' ? value.trim() : '';
124
- if (!prompt) {
125
- throw new Error('A task needs a prompt: what Ta should do each time it runs.');
126
- }
127
- if (prompt.length > PROMPT_MAX) {
128
- throw new Error(`A prompt is at most ${PROMPT_MAX} characters; keep long instructions in a file and name it.`);
129
- }
130
- return prompt;
131
- }
132
-
133
- function checkName(value: unknown): string | undefined {
134
- const name = typeof value === 'string' ? value.trim() : '';
135
- return name ? name.slice(0, NAME_MAX) : undefined;
136
- }
137
-
138
- function defaultName(prompt: string): string {
139
- const line = prompt.split('\n')[0].trim();
140
- return line.length > 40 ? `${line.slice(0, 39)}…` : line;
141
- }
142
-
143
- function checkCwd(value: unknown): string | undefined {
144
- return typeof value === 'string' && value.trim() ? value.trim() : undefined;
145
- }
146
-
147
- function checkModel(value: unknown): string | undefined {
148
- const model = typeof value === 'string' ? value.trim() : '';
149
- return model || undefined;
150
- }
151
-
152
- function checkThinking(value: unknown): string | undefined {
153
- const level = typeof value === 'string' ? value.trim() : '';
154
- if (level && !THINKING_LEVELS.includes(level)) {
155
- throw new Error(`A thinking level is one of ${THINKING_LEVELS.join(', ')}; not ${JSON.stringify(level)}.`);
156
- }
157
- return level || undefined;
158
- }
159
-
160
- function checkNotify(value: unknown): NotifyLevel | undefined {
161
- if (value === '' || value === null) {
162
- return undefined;
163
- }
164
- if (!NOTIFY_LEVELS.includes(value as NotifyLevel)) {
165
- throw new Error(`notify is one of ${NOTIFY_LEVELS.join(', ')}; not ${JSON.stringify(value)}.`);
166
- }
167
- return value as NotifyLevel;
168
- }
169
-
170
- /** Whether a run of the task ended long enough ago, by its rule, to be called missed: a task that runs once, past its grace. */
171
- export function missed(task: Task, now: Date): boolean {
172
- return task.schedule.kind === 'once' && !!task.nextRunAt && now.getTime() - new Date(task.nextRunAt).getTime() > Limits.GRACE_MS;
173
- }
174
- }
@@ -1,279 +0,0 @@
1
- import type { Run, Task } from './cron-protocol';
2
- import { type Editing, TaskEditor } from './editor';
3
- import type { Words } from './i18n';
4
- import { basename, type CronClient, icon, message, openRun, pi, t, until } from './page';
5
- import { React } from './react';
6
- import { Duration, ScheduleUtil } from './schedule-util';
7
-
8
- function useClient(client: CronClient) {
9
- return React.useSyncExternalStore(
10
- listener => client.subscribe(listener),
11
- () => client.state,
12
- );
13
- }
14
-
15
- /** Seconds pass: what says "in 5 minutes" says it again. */
16
- function useMinute(): number {
17
- const [now, setNow] = React.useState(Date.now());
18
- React.useEffect(() => {
19
- const timer = setInterval(() => setNow(Date.now()), 30_000);
20
- return () => clearInterval(timer);
21
- }, []);
22
- return now;
23
- }
24
-
25
- async function guard(action: () => Promise<unknown>): Promise<void> {
26
- try {
27
- await action();
28
- } catch (error) {
29
- pi.ui.notify(t('failedAction', { message: message(error) }), 'error');
30
- }
31
- }
32
-
33
- function Dot({ status, enabled = true }: { status?: Run['status']; enabled?: boolean }) {
34
- return <span className={`tcr-dot tcr-${enabled ? (status ?? 'idle') : 'off'}`} />;
35
- }
36
-
37
- /** A clock whose hand goes round, for the page without tasks. */
38
- function Clock() {
39
- return (
40
- <svg className="tcr-clock" viewBox="0 0 120 120" aria-hidden="true">
41
- <circle cx="60" cy="60" r="44" className="tcr-clock-face" />
42
- {Array.from({ length: 12 }, (_, hour) => (
43
- <line key={hour} x1="60" y1="22" x2="60" y2={hour % 3 === 0 ? 29 : 26} className="tcr-clock-tick" transform={`rotate(${hour * 30} 60 60)`} />
44
- ))}
45
- <line x1="60" y1="60" x2="60" y2="38" className="tcr-clock-hour" />
46
- <line x1="60" y1="60" x2="60" y2="28" className="tcr-clock-hand" />
47
- <circle cx="60" cy="60" r="3.5" className="tcr-clock-pin" />
48
- </svg>
49
- );
50
- }
51
-
52
- const EXAMPLES: { text: keyof Words; repeat: Editing['repeat']; rule: string; icon: string }[] = [
53
- { text: 'example1', repeat: 'daily', rule: '0 9 * * *', icon: 'GitCommitHorizontal' },
54
- { text: 'example2', repeat: 'every', rule: '30m', icon: 'RefreshCw' },
55
- { text: 'example3', repeat: 'weekdays', rule: '0 18 * * 1-5', icon: 'FileText' },
56
- ];
57
-
58
- function Empty({ onPick }: { onPick(editing: Editing): void }) {
59
- return (
60
- <div className="tcr-empty">
61
- <Clock />
62
- <div className="tcr-empty-title">{t('emptyTitle')}</div>
63
- <div className="tcr-empty-hint">{t('emptyHint')}</div>
64
- <div className="tcr-examples">
65
- {EXAMPLES.map(example => {
66
- const Icon = icon(example.icon);
67
- const schedule =
68
- example.repeat === 'every'
69
- ? ({ kind: 'interval', every: example.rule } as const)
70
- : ({ kind: 'cron', expression: example.rule } as const);
71
- return (
72
- <button
73
- key={example.text}
74
- type="button"
75
- className="tcr-example"
76
- onClick={() => onPick({ prompt: t(example.text), repeat: example.repeat })}
77
- >
78
- <Icon size={18} />
79
- <span className="tcr-example-text">{t(example.text)}</span>
80
- <span className="tcr-chip">{ScheduleUtil.describe(schedule, pi.ui.language)}</span>
81
- </button>
82
- );
83
- })}
84
- </div>
85
- </div>
86
- );
87
- }
88
-
89
- /** What the end of a run says, in the language of the page when the service knows why it failed. */
90
- function outcome(run: Run): string | undefined {
91
- if (run.status === 'missed') {
92
- return t('missedText');
93
- }
94
- if (run.reason) {
95
- return t(run.reason);
96
- }
97
- return run.error ?? run.summary;
98
- }
99
-
100
- function RunRow({ run, now }: { run: Run; now: number }) {
101
- const [open, setOpen] = React.useState(false);
102
- const Markdown = pi.ui.Markdown;
103
- const Open = icon('MessageSquareText');
104
- const took = run.endedAt ? Duration.format(Math.max(1000, new Date(run.endedAt).getTime() - new Date(run.startedAt).getTime())) : undefined;
105
- const text = outcome(run);
106
- const label = run.status === 'running' ? t('running') : t(run.status as keyof Words);
107
- return (
108
- <div className={`tcr-run${open ? ' tcr-open' : ''}`}>
109
- <button type="button" className="tcr-run-head" onClick={() => setOpen(!open)}>
110
- <Dot status={run.status} />
111
- <span className="tcr-run-time">{ScheduleUtil.clock(new Date(run.startedAt), new Date(now))}</span>
112
- <span className="tcr-run-status">{label}</span>
113
- {took && <span className="tcr-muted">{took}</span>}
114
- {run.trigger === 'manual' && <span className="tcr-chip">{t('byHand')}</span>}
115
- {!open && text && <span className="tcr-run-line">{text.split('\n')[0]}</span>}
116
- </button>
117
- {open && (
118
- <div className="tcr-run-body">
119
- {text && (run.status === 'success' ? <Markdown text={text} /> : <div className="tcr-run-error">{text}</div>)}
120
- {run.sessionFile && (
121
- <button type="button" className="tcr-button" onClick={() => void openRun(run)}>
122
- <Open size={14} />
123
- {t('openChat')}
124
- </button>
125
- )}
126
- </div>
127
- )}
128
- </div>
129
- );
130
- }
131
-
132
- function Detail({ client, task, now }: { client: CronClient; task: Task; now: number }) {
133
- const { runs } = useClient(client);
134
- React.useEffect(() => {
135
- void client.loadRuns(task.id).catch(() => undefined);
136
- }, [client, task.id]);
137
- const list = runs[task.id];
138
- return (
139
- <div className="tcr-detail">
140
- <div className="tcr-prompt-text">{task.prompt}</div>
141
- <div className="tcr-label">{t('runs')}</div>
142
- {list && list.length === 0 && <div className="tcr-muted tcr-pad">{t('noRuns')}</div>}
143
- {list?.map(run => (
144
- <RunRow key={run.id} run={run} now={now} />
145
- ))}
146
- </div>
147
- );
148
- }
149
-
150
- function Menu({ items, onClose }: { items: { key: string; label: string; icon: string; danger?: boolean; run(): void }[]; onClose(): void }) {
151
- const ref = React.useRef<HTMLDivElement>(null);
152
- React.useEffect(() => {
153
- const close = (event: Event) => (event instanceof KeyboardEvent ? event.key === 'Escape' : !ref.current?.contains(event.target as Node)) && onClose();
154
- document.addEventListener('pointerdown', close, true);
155
- document.addEventListener('keydown', close);
156
- return () => {
157
- document.removeEventListener('pointerdown', close, true);
158
- document.removeEventListener('keydown', close);
159
- };
160
- }, [onClose]);
161
- return (
162
- <div className="tcr-menu" ref={ref} role="menu">
163
- {items.map(item => {
164
- const Icon = icon(item.icon);
165
- return (
166
- <button
167
- key={item.key}
168
- type="button"
169
- role="menuitem"
170
- className={`tcr-menu-item${item.danger ? ' tcr-danger' : ''}`}
171
- onClick={() => {
172
- onClose();
173
- item.run();
174
- }}
175
- >
176
- <Icon size={14} />
177
- {item.label}
178
- </button>
179
- );
180
- })}
181
- </div>
182
- );
183
- }
184
-
185
- function TaskRow({ client, task, now, onEdit }: { client: CronClient; task: Task; now: number; onEdit(task: Task): void }) {
186
- const [open, setOpen] = React.useState(false);
187
- const [menu, setMenu] = React.useState(false);
188
- const More = icon('Ellipsis');
189
- const running = task.lastStatus === 'running';
190
- const state = running
191
- ? t('running')
192
- : !task.enabled
193
- ? task.nextRunAt || ScheduleUtil.repeats(task.schedule)
194
- ? t('paused')
195
- : t('done')
196
- : task.nextRunAt
197
- ? t('next', { time: until(new Date(task.nextRunAt).getTime(), now) })
198
- : t('done');
199
- const remove = async () => {
200
- if (await pi.ui.confirm(t('confirmDelete', { name: task.name }), t('confirmDeleteMessage'), { confirmLabel: t('delete'), danger: true })) {
201
- await guard(() => client.call('remove', task.id));
202
- }
203
- };
204
- return (
205
- <div className={`tcr-task${open ? ' tcr-open' : ''}${menu ? ' tcr-menu-open' : ''}${task.enabled ? '' : ' tcr-disabled'}`}>
206
- <div className="tcr-task-row">
207
- <button type="button" className="tcr-task-main" onClick={() => setOpen(!open)} aria-expanded={open}>
208
- <Dot status={task.lastStatus} enabled={task.enabled || running} />
209
- <span className="tcr-task-name">{task.name}</span>
210
- <span className="tcr-chip">{ScheduleUtil.describe(task.schedule, pi.ui.language, new Date(now))}</span>
211
- <span className="tcr-task-dir" title={task.cwd}>
212
- {basename(task.cwd)}
213
- </span>
214
- <span
215
- className={`tcr-task-state${running ? ' tcr-pulse' : ''}`}
216
- title={task.nextRunAt ? t('nextAt', { time: ScheduleUtil.clock(new Date(task.nextRunAt)) }) : undefined}
217
- >
218
- {state}
219
- </span>
220
- </button>
221
- <label className="tcr-switch" title={t('enable')}>
222
- <input
223
- type="checkbox"
224
- checked={task.enabled}
225
- onChange={event => void guard(() => client.call('setEnabled', task.id, event.target.checked))}
226
- />
227
- <span />
228
- </label>
229
- <div className="tcr-more">
230
- <button type="button" className="tcr-icon" aria-label={t('more')} onClick={() => setMenu(!menu)}>
231
- <More size={16} />
232
- </button>
233
- {menu && (
234
- <Menu
235
- onClose={() => setMenu(false)}
236
- items={[
237
- { key: 'run', label: t('runNow'), icon: 'Play', run: () => void guard(() => client.call('run', task.id)) },
238
- { key: 'edit', label: t('edit'), icon: 'Pencil', run: () => onEdit(task) },
239
- { key: 'delete', label: t('delete'), icon: 'Trash2', danger: true, run: () => void remove() },
240
- ]}
241
- />
242
- )}
243
- </div>
244
- </div>
245
- {open && <Detail client={client} task={task} now={now} />}
246
- </div>
247
- );
248
- }
249
-
250
- /** The page of the tasks: each with its rule, its next run and its switch; opened, its prompt and runs. */
251
- export function TasksPage({ client }: { client: CronClient }) {
252
- const { tasks, loaded } = useClient(client);
253
- const now = useMinute();
254
- const [editing, setEditing] = React.useState<Editing>();
255
- const Plus = icon('Plus');
256
- const running = tasks.filter(task => task.lastStatus === 'running').length;
257
- const sorted = [...tasks].sort((a, b) => Number(b.enabled) - Number(a.enabled) || (a.nextRunAt ?? '~').localeCompare(b.nextRunAt ?? '~'));
258
- return (
259
- <div className="tcr-page">
260
- <div className="tcr-head">
261
- <div className="tcr-stat">
262
- {tasks.length > 0 && t('count', { count: tasks.length })}
263
- {running > 0 && <span className="tcr-pulse"> · {t('runningCount', { count: running })}</span>}
264
- </div>
265
- <button type="button" className="tcr-button tcr-primary" onClick={() => setEditing({})}>
266
- <Plus size={15} />
267
- {t('newTask')}
268
- </button>
269
- </div>
270
- {loaded && tasks.length === 0 && <Empty onPick={setEditing} />}
271
- <div className="tcr-list">
272
- {sorted.map(task => (
273
- <TaskRow key={task.id} client={client} task={task} now={now} onEdit={item => setEditing({ task: item })} />
274
- ))}
275
- </div>
276
- {editing && <TaskEditor client={client} editing={editing} onClose={() => setEditing(undefined)} />}
277
- </div>
278
- );
279
- }
package/web-src/tool.ts DELETED
@@ -1,135 +0,0 @@
1
- import { CronText } from './commands';
2
- import type { CronService, NotifyLevel, Schedule, TaskPatch } from './cron-protocol';
3
- import { NOTIFY_LEVELS, THINKING_LEVELS } from './schedule-util';
4
- import { CronServerTexts } from './server-texts';
5
-
6
- /** What the tool needs of the conversation that calls it. */
7
- export interface ToolContext {
8
- /** Where the conversation works: a new task runs there unless it names another directory. */
9
- cwd(): Promise<string | undefined>;
10
- /** Asks the user; false when nobody can answer. */
11
- confirm(title: string, message: string): Promise<boolean>;
12
- }
13
-
14
- const SCHEDULE = {
15
- type: 'object',
16
- description:
17
- 'When it runs, in the local time of the Ta service: { "kind": "once", "at": "2026-11-12T09:00" }, { "kind": "interval", "every": "30m" } (at least 1m), or { "kind": "cron", "expression": "0 9 * * 1-5" } (five fields, or @daily, @hourly, @weekly, @monthly).',
18
- properties: {
19
- kind: { type: 'string', enum: ['once', 'interval', 'cron'] },
20
- at: { type: 'string' },
21
- every: { type: 'string' },
22
- expression: { type: 'string' },
23
- },
24
- required: ['kind'],
25
- };
26
-
27
- /** The tool by which Ta schedules prompts for the user. */
28
- export namespace CronTool {
29
- export const NAME = 'schedule_task';
30
-
31
- export const DEFINITION = {
32
- name: NAME,
33
- label: 'Schedule task',
34
- description: `Schedules a prompt for Ta to run later, once or again and again (reminders, checks, reports), and manages those tasks. Each run is a new conversation of its own in the Ta service, in the task's directory, with no user watching; its last answer is the summary the user sees. Actions: add (prompt and schedule; name, cwd, model, thinking, notify optional), update (id and the fields to change; "" clears model, thinking or notify), list, show (with its last runs), enable, disable, delete, run (now, by hand), runs, clear (the tasks of this directory). Deleting and clearing ask the user first.`,
35
- parameters: {
36
- type: 'object',
37
- properties: {
38
- action: { type: 'string', enum: ['add', 'update', 'list', 'show', 'enable', 'disable', 'delete', 'run', 'runs', 'clear'] },
39
- id: { type: 'string', description: 'The task: its id, the start of it, or its name.' },
40
- name: { type: 'string', description: 'Short, for the list.' },
41
- prompt: { type: 'string', description: 'What Ta does each run, complete in itself: the run does not see this conversation.' },
42
- schedule: SCHEDULE,
43
- cwd: { type: 'string', description: "The directory it runs in; default: this conversation's." },
44
- model: { type: 'string', description: '<provider>/<model id>; default: the settings.' },
45
- thinking: { type: 'string', enum: [...THINKING_LEVELS, ''] },
46
- notify: {
47
- type: 'string',
48
- enum: [...NOTIFY_LEVELS, ''],
49
- description: 'When the pages of Ta tell the user a run ended; default always for once, error for repeating.',
50
- },
51
- enabled: { type: 'boolean' },
52
- limit: { type: 'number', description: 'How many runs to list; default 10.' },
53
- },
54
- required: ['action'],
55
- },
56
- };
57
-
58
- export async function run(service: CronService, params: Record<string, unknown>, context: ToolContext): Promise<string> {
59
- const id = typeof params.id === 'string' ? params.id : '';
60
- switch (params.action) {
61
- case 'add': {
62
- const cwd = typeof params.cwd === 'string' && params.cwd ? params.cwd : await context.cwd();
63
- const task = await service.add({
64
- prompt: String(params.prompt ?? ''),
65
- schedule: params.schedule as Schedule,
66
- name: optional(params.name),
67
- cwd,
68
- model: optional(params.model),
69
- thinking: optional(params.thinking),
70
- notify: optional(params.notify) as NotifyLevel | undefined,
71
- enabled: params.enabled === false ? false : undefined,
72
- });
73
- return `Scheduled: ${CronText.task(task)}`;
74
- }
75
- case 'update': {
76
- const patch: TaskPatch = {};
77
- for (const key of ['name', 'prompt', 'cwd', 'model', 'thinking', 'notify'] as const) {
78
- if (typeof params[key] === 'string') {
79
- (patch as Record<string, unknown>)[key] = params[key];
80
- }
81
- }
82
- if (params.schedule !== undefined) {
83
- patch.schedule = params.schedule as Schedule;
84
- }
85
- if (typeof params.enabled === 'boolean') {
86
- patch.enabled = params.enabled;
87
- }
88
- return `Updated: ${CronText.task(await service.update(id, patch))}`;
89
- }
90
- case 'list': {
91
- const tasks = await service.list();
92
- return tasks.length ? tasks.map(task => CronText.task(task)).join('\n') : 'No scheduled tasks.';
93
- }
94
- case 'show':
95
- case 'runs': {
96
- const task = await service.get(id);
97
- const runs = await service.runs(task.id, typeof params.limit === 'number' ? params.limit : 10);
98
- return CronText.reply({ kind: 'show', task, runs });
99
- }
100
- case 'enable':
101
- case 'disable':
102
- return `${params.action === 'enable' ? 'Enabled' : 'Disabled'}: ${CronText.task(await service.setEnabled(id, params.action === 'enable'))}`;
103
- case 'run': {
104
- const task = await service.get(id);
105
- const run = await service.run(task.id);
106
- return `Started ${task.name} (${run.id}). It runs in a conversation of its own; see its result later with action "show".`;
107
- }
108
- case 'delete': {
109
- const task = await service.get(id);
110
- if (!(await context.confirm(...CronServerTexts.removeTask(task.name)))) {
111
- return 'The user kept the task.';
112
- }
113
- await service.remove(task.id);
114
- return `Deleted ${task.name}.`;
115
- }
116
- case 'clear': {
117
- const cwd = await context.cwd();
118
- const tasks = (await service.list()).filter(task => task.cwd === cwd);
119
- if (tasks.length === 0) {
120
- return 'This directory has no scheduled tasks.';
121
- }
122
- if (!(await context.confirm(...CronServerTexts.removeTasks(tasks.length)))) {
123
- return 'The user kept the tasks.';
124
- }
125
- return `Deleted ${(await service.clear(cwd)).length} tasks.`;
126
- }
127
- default:
128
- throw new Error('action is one of add, update, list, show, enable, disable, delete, run, runs, clear.');
129
- }
130
- }
131
-
132
- function optional(value: unknown): string | undefined {
133
- return typeof value === 'string' && value ? value : undefined;
134
- }
135
- }