-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.ts
More file actions
288 lines (265 loc) · 8.85 KB
/
Copy pathindex.ts
File metadata and controls
288 lines (265 loc) · 8.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
// Cron — scheduled agent tasks. Stores jobs in ~/.deepcode/cron.json and matches
// 5-field cron expressions. The CronCreate/CronList/CronDelete tools CRUD the
// store; a separate `deepcode scheduler run` (CLI) executes due jobs.
// Spec: docs/DEVELOPMENT_PLAN.md §3.15.4 / §0.1 (CronCreate family)
import { promises as fs } from 'node:fs';
import type { TriggerProfile } from './profile.js';
import {
isTriggerDue,
resolveTrigger,
type TriggerSource,
type TriggerVerdict,
} from './triggers.js';
import { homedir } from 'node:os';
import { dirname, join } from 'node:path';
/**
* What an unattended run does when a tool call resolves to `ask`.
*
* `deny` (default, and the pre-existing behaviour) refuses that one call and
* lets the run continue. `abort` stops the whole run instead — the right choice
* when a half-executed job is worse than no job, since a denied first call
* otherwise leaves the agent looping against a wall while it burns tokens.
*/
export type UnattendedApprovalPolicy = 'deny' | 'abort';
export interface CronJob {
id: string;
/**
* 5-field cron expression: "min hour day-of-month month day-of-week".
*
* Still the source when `trigger` is absent, which is every job written
* before triggers existed. Kept rather than migrated: a store nobody has to
* rewrite is a store that cannot be rewritten wrongly.
*/
schedule: string;
/**
* Where this job's events come from. Absent means the `schedule` above.
*/
trigger?: TriggerSource;
/** Prompt to run headlessly when the job fires. */
prompt: string;
/** Working directory to run in. */
cwd: string;
createdAt: string;
lastRunAt?: string;
enabled: boolean;
/**
* Unattended approval policy for this job. Absent on jobs created before this
* field existed, which is why every read goes through
* `resolveUnattendedApproval` instead of touching the field directly.
*/
onApprovalRequired?: UnattendedApprovalPolicy;
/**
* Permission posture for this job, independent of the interactive settings it
* would otherwise inherit. Absent means "use the ambient settings, clamped" —
* see `resolveTriggerMode`.
*/
profile?: TriggerProfile;
}
/** The effective policy for a job, defaulting to the historical `deny`. */
export function resolveUnattendedApproval(
job: Pick<CronJob, 'onApprovalRequired'>,
): UnattendedApprovalPolicy {
return job.onApprovalRequired === 'abort' ? 'abort' : 'deny';
}
export interface CronStore {
jobs: CronJob[];
}
export function cronStorePath(home: string = homedir()): string {
return join(home, '.deepcode', 'cron.json');
}
export async function loadCronStore(home: string = homedir()): Promise<CronStore> {
try {
const raw = await fs.readFile(cronStorePath(home), 'utf8');
const parsed = JSON.parse(raw) as CronStore;
return { jobs: Array.isArray(parsed.jobs) ? parsed.jobs : [] };
} catch (err) {
if ((err as NodeJS.ErrnoException).code === 'ENOENT') return { jobs: [] };
throw err;
}
}
export async function saveCronStore(store: CronStore, home: string = homedir()): Promise<void> {
const path = cronStorePath(home);
await fs.mkdir(dirname(path), { recursive: true });
await fs.writeFile(path, JSON.stringify(store, null, 2) + '\n', 'utf8');
}
let cronSeq = 0;
function newCronId(): string {
return `cron-${Date.now().toString(36)}-${(cronSeq++).toString(36)}`;
}
export async function addCronJob(
job: {
schedule: string;
prompt: string;
cwd: string;
onApprovalRequired?: UnattendedApprovalPolicy;
profile?: TriggerProfile;
},
home: string = homedir(),
): Promise<CronJob> {
const invalid = validateCronExpr(job.schedule);
if (invalid) throw new Error(invalid);
const store = await loadCronStore(home);
const created: CronJob = {
id: newCronId(),
schedule: job.schedule.trim(),
prompt: job.prompt,
cwd: job.cwd,
createdAt: new Date().toISOString(),
enabled: true,
...(job.onApprovalRequired ? { onApprovalRequired: job.onApprovalRequired } : {}),
...(job.profile ? { profile: job.profile } : {}),
};
store.jobs.push(created);
await saveCronStore(store, home);
return created;
}
export async function removeCronJob(id: string, home: string = homedir()): Promise<boolean> {
const store = await loadCronStore(home);
const before = store.jobs.length;
store.jobs = store.jobs.filter((j) => j.id !== id);
if (store.jobs.length === before) return false;
await saveCronStore(store, home);
return true;
}
export async function listCronJobs(home: string = homedir()): Promise<CronJob[]> {
return (await loadCronStore(home)).jobs;
}
// ── Cron expression matching ────────────────────────────────────────────
// 5 fields: minute(0-59) hour(0-23) day-of-month(1-31) month(1-12) day-of-week(0-6, 0=Sun).
// Each supports: * a a-b a,b,c */n a-b/n
const FIELD_RANGES: Array<[number, number]> = [
[0, 59],
[0, 23],
[1, 31],
[1, 12],
[0, 6],
];
/** Returns an error message if `expr` is not a valid 5-field cron, else null. */
export function validateCronExpr(expr: string): string | null {
const fields = expr.trim().split(/\s+/);
if (fields.length !== 5) {
return `cron expression must have 5 fields (got ${fields.length}): "${expr}"`;
}
for (let i = 0; i < 5; i++) {
try {
matchField(fields[i]!, FIELD_RANGES[i]![0], FIELD_RANGES[i]![1], FIELD_RANGES[i]![0]);
} catch (err) {
return `invalid cron field "${fields[i]}": ${(err as Error).message}`;
}
}
return null;
}
/** Whether a single field matches `value` within [min,max]. Throws on bad syntax. */
function matchField(field: string, min: number, max: number, value: number): boolean {
return field.split(',').some((part) => {
let step = 1;
let range = part;
const slash = part.indexOf('/');
if (slash !== -1) {
step = Number(part.slice(slash + 1));
range = part.slice(0, slash);
if (!Number.isInteger(step) || step <= 0) throw new Error(`bad step "${part}"`);
}
let lo = min;
let hi = max;
if (range !== '*') {
const dash = range.indexOf('-');
if (dash !== -1) {
lo = Number(range.slice(0, dash));
hi = Number(range.slice(dash + 1));
} else {
lo = hi = Number(range);
}
if (!Number.isInteger(lo) || !Number.isInteger(hi) || lo < min || hi > max || lo > hi) {
throw new Error(`out of range [${min}-${max}]`);
}
}
if (value < lo || value > hi) return false;
return (value - lo) % step === 0;
});
}
/** Is `date` a firing time for `schedule`? (minute granularity.) */
export function isCronDue(schedule: string, date: Date): boolean {
const fields = schedule.trim().split(/\s+/);
if (fields.length !== 5) return false;
const values = [
date.getMinutes(),
date.getHours(),
date.getDate(),
date.getMonth() + 1,
date.getDay(),
];
try {
for (let i = 0; i < 5; i++) {
if (!matchField(fields[i]!, FIELD_RANGES[i]![0], FIELD_RANGES[i]![1], values[i]!)) {
return false;
}
}
} catch {
return false;
}
return true;
}
/**
* Enabled jobs due to run at `now`.
*
* Synchronous and cron-only. Kept because it is the shape every existing caller
* and test uses, and because a clock trigger needs nothing but the clock — but
* a job with a non-cron trigger is not decidable here, so it is skipped rather
* than guessed at. Use `dueJobsWithTriggers` to evaluate all of them.
*/
export function dueJobs(jobs: CronJob[], now: Date): CronJob[] {
return jobs.filter(
(j) => j.enabled && resolveTrigger(j).kind === 'cron' && isCronDue(j.schedule, now),
);
}
export interface DueJob {
job: CronJob;
verdict: TriggerVerdict;
}
/**
* Every enabled job whose trigger has fired, whatever kind it is.
*
* Async because a calendar has to be read and a watched file has to be stat'd.
* Diagnostics ride along on the verdict so the scheduler can log "this
* calendar has an RRULE I cannot express" next to the job it belongs to,
* instead of on nobody's behalf.
*/
export async function dueJobsWithTriggers(jobs: CronJob[], now: Date): Promise<DueJob[]> {
const out: DueJob[] = [];
for (const job of jobs) {
if (!job.enabled) continue;
const verdict = await isTriggerDue(
resolveTrigger(job),
{ now, cwd: job.cwd, lastRunAt: job.lastRunAt },
isCronDue,
);
if (verdict.due) out.push({ job, verdict });
}
return out;
}
export {
describeTrigger,
isTriggerDue,
resolveTrigger,
validateTrigger,
type TriggerContext,
type TriggerSource,
type TriggerVerdict,
} from './triggers.js';
export {
matchingEvents,
occursAt,
parseIcs,
type IcsCalendar,
type IcsEvent,
type IcsRecurrence,
} from './ics.js';
export {
describeClamp,
resolveTriggerMode,
tightenPermissions,
tightenSandbox,
type ResolvedTriggerMode,
type TriggerProfile,
} from './profile.js';