ceulen 0.10.1 → 0.11.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.
- package/CHANGELOG.md +56 -0
- package/README.md +56 -1
- package/extensions/lib/plan-bridge.ts +18 -0
- package/extensions/lib/registry.ts +14 -0
- package/extensions/modules/a2a/index.ts +4 -2
- package/extensions/modules/attachments/configPanel.ts +91 -0
- package/extensions/modules/attachments/index.ts +274 -0
- package/extensions/modules/attachments/lib/clipboard-files.ts +80 -0
- package/extensions/modules/attachments/lib/pastes.ts +45 -0
- package/extensions/modules/attachments/lib/paths.ts +74 -0
- package/extensions/modules/attachments/lib/registry.ts +70 -0
- package/extensions/modules/attachments/lib/settings.ts +99 -0
- package/extensions/modules/attachments/lib/tray.ts +74 -0
- package/extensions/modules/attachments/test/configPanel.test.ts +122 -0
- package/extensions/modules/attachments/test/index.test.ts +870 -0
- package/extensions/modules/attachments/test/module.test.ts +53 -0
- package/extensions/modules/composer/test/module.test.ts +2 -2
- package/extensions/modules/config/index.ts +3 -0
- package/extensions/modules/config/test/renderTools.test.ts +1 -1
- package/extensions/modules/cron/configPanel.ts +103 -0
- package/extensions/modules/cron/index.ts +638 -0
- package/extensions/modules/cron/lib/jobs.ts +201 -0
- package/extensions/modules/cron/lib/schedule.ts +161 -0
- package/extensions/modules/cron/test/cwd-repro.test.ts +98 -0
- package/extensions/modules/cron/test/index.test.ts +859 -0
- package/extensions/modules/cron/test/schedule.test.ts +93 -0
- package/extensions/modules/munin/index.ts +3 -1
- package/extensions/modules/permission/index.ts +567 -0
- package/extensions/modules/permission/test/permission.test.ts +789 -0
- package/extensions/modules/plan/index.ts +5 -0
- package/extensions/modules/repair/index.ts +134 -3
- package/extensions/modules/repair/test/freshness.test.ts +169 -0
- package/extensions/modules/subagent/index.ts +38 -5
- package/extensions/modules/subagent/lib/runner.ts +348 -12
- package/extensions/modules/subagent/test/worktree.test.ts +230 -0
- package/extensions/modules/usage/index.ts +193 -71
- package/extensions/modules/usage/test/context.test.ts +160 -120
- package/extensions/modules/web/index.ts +3 -1
- package/extensions/modules/web/test/a11y.test.ts +1 -1
- package/package.json +2 -2
- package/skills/cron/SKILL.md +58 -0
|
@@ -0,0 +1,638 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ceulen-cron — scheduled jobs for Pi.
|
|
3
|
+
*
|
|
4
|
+
* Jobs live in <agentDir>/cron/jobs.json. A 30s in-process timer fires due
|
|
5
|
+
* jobs by delivering a follow-up turn into the live session (the same rail
|
|
6
|
+
* pi-subagent uses for background completions). Past-due jobs catch up once
|
|
7
|
+
* on the next tick (Hermes semantics). `export` prints crontab lines so jobs
|
|
8
|
+
* can also run via system cron while pi is closed.
|
|
9
|
+
*
|
|
10
|
+
* Loop guard: for 30s after the last armed fire, mutating actions
|
|
11
|
+
* (add/remove/run/enable/disable) are refused. This is a time window, not
|
|
12
|
+
* in-flight immunity — a fired turn running longer than the window CAN
|
|
13
|
+
* mutate (Hermes disables cron tools in fired runs for the same reason this
|
|
14
|
+
* exists at all).
|
|
15
|
+
*
|
|
16
|
+
* No ExtensionContext is captured across time — the timer never touches ctx,
|
|
17
|
+
* so the stale-ctx crash class (pi-sub) cannot happen here.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
21
|
+
import { getAgentDir } from "@earendil-works/pi-coding-agent";
|
|
22
|
+
import { Type } from "typebox";
|
|
23
|
+
import { mkdirSync, readFileSync, appendFileSync, readdirSync, statSync } from "node:fs";
|
|
24
|
+
import { join } from "node:path";
|
|
25
|
+
import os from "node:os";
|
|
26
|
+
import { spawn } from "node:child_process";
|
|
27
|
+
import path from "node:path";
|
|
28
|
+
import { skillsRoot } from "../../lib/skill-path.js";
|
|
29
|
+
import { nextFires, validateSchedule } from "./lib/schedule.ts";
|
|
30
|
+
import {
|
|
31
|
+
addJob,
|
|
32
|
+
dueJobs,
|
|
33
|
+
findJob,
|
|
34
|
+
jobsDir,
|
|
35
|
+
loadJobs,
|
|
36
|
+
markFired,
|
|
37
|
+
removeJob,
|
|
38
|
+
saveJobs,
|
|
39
|
+
setJobEnabled,
|
|
40
|
+
setJobResult,
|
|
41
|
+
type CronJob,
|
|
42
|
+
} from "./lib/jobs.ts";
|
|
43
|
+
|
|
44
|
+
const DEFAULT_TICK_MS = 30_000;
|
|
45
|
+
const MUTATING_ACTIONS = new Set(["add", "remove", "run", "enable", "disable"]);
|
|
46
|
+
/** Loop guard is purely time-based: mutations are refused within this window
|
|
47
|
+
* after the last armed fire. SDK events carry no turn identity (AgentSettledEvent
|
|
48
|
+
* is payload-free; message_start fires at custom-message DELIVERY), so a settle-
|
|
49
|
+
* correlated counter is impossible — the window self-expires, over-arming (safe)
|
|
50
|
+
* rather than under-arming while cron turns are queued/running. */
|
|
51
|
+
const GUARD_LINGER_MS = 30_000;
|
|
52
|
+
export { GUARD_LINGER_MS };
|
|
53
|
+
|
|
54
|
+
// ---------------------------------------------------------------------------
|
|
55
|
+
|
|
56
|
+
export interface CronSettings {
|
|
57
|
+
enabled: boolean;
|
|
58
|
+
tickMs: number;
|
|
59
|
+
/** Hard cap for headless child runs. Default 10 min. */
|
|
60
|
+
timeoutMs: number;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Read the `cron` settings key (cwd/.pi → PI_CODING_AGENT_DIR|~/.pi/agent → ~/.pi/agents).
|
|
64
|
+
* The project scope is trust-gated: `project: false` skips cwd/.pi entirely, so
|
|
65
|
+
* settings.json in an untrusted checkout cannot re-enable the scheduler or
|
|
66
|
+
* shrink tickMs (same pattern as pi-references/pi-permission/pi-router). */
|
|
67
|
+
export function readCronSettings(cwd = process.cwd(), { project = true } = {}): CronSettings {
|
|
68
|
+
const home = os.homedir();
|
|
69
|
+
const dirs = [...(project ? [join(cwd, ".pi")] : []), process.env.PI_CODING_AGENT_DIR || join(home, ".pi", "agent"), join(home, ".pi", "agents")];
|
|
70
|
+
for (const dir of dirs) {
|
|
71
|
+
try {
|
|
72
|
+
const v = JSON.parse(readFileSync(join(dir, "settings.json"), "utf8"))?.cron;
|
|
73
|
+
if (v && typeof v === "object") {
|
|
74
|
+
const tickMs = Number(v.tickMs);
|
|
75
|
+
const timeoutMs = Number(v.timeoutMs);
|
|
76
|
+
return {
|
|
77
|
+
enabled: v.enabled !== false,
|
|
78
|
+
tickMs: Math.min(Math.max(Number.isFinite(tickMs) && tickMs > 0 ? tickMs : DEFAULT_TICK_MS, 5_000), 600_000),
|
|
79
|
+
timeoutMs: Math.min(Math.max(Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 600_000, 60_000), 86_400_000),
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
} catch {
|
|
83
|
+
// missing/unreadable settings.json — try next location
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
return { enabled: true, tickMs: DEFAULT_TICK_MS, timeoutMs: 600_000 };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Loop guard: mutating actions refused within GUARD_LINGER_MS of the last
|
|
91
|
+
* armed fire (lastArmAt=0 = never armed). Headless children (PI_CRON_DISABLED)
|
|
92
|
+
* are refused separately at the call site.
|
|
93
|
+
*/
|
|
94
|
+
export function isMutationRefused(lastFireArmAt: number, action: string, now = Date.now()): boolean {
|
|
95
|
+
return lastFireArmAt > 0 && now - lastFireArmAt < GUARD_LINGER_MS && MUTATING_ACTIONS.has(action);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function fireContent(job: CronJob): string {
|
|
99
|
+
return `⏰ Cron job '${job.name}' fired:\n${job.prompt}\n(cron job fired — do not create, modify, or trigger cron jobs from this turn)`;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export function shellQuote(s: string): string {
|
|
103
|
+
return `'${s.replace(/'/g, `'\\''`)}'`;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
function fmt(ms: number | undefined): string {
|
|
107
|
+
return ms === undefined ? "never" : new Date(ms).toLocaleString();
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function isPinned(job: Pick<CronJob, "model" | "thinking">): boolean {
|
|
111
|
+
return !!(job.model || job.thinking);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** CLI args for a pinned (headless) run — same flags a user would type. */
|
|
115
|
+
export function headlessArgs(job: Pick<CronJob, "model" | "thinking">): string[] {
|
|
116
|
+
const args = ["-p", "--no-session"];
|
|
117
|
+
if (job.model) args.push("--model", job.model);
|
|
118
|
+
if (job.thinking) args.push("--thinking", job.thinking);
|
|
119
|
+
return args;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** One line of `list` output. */
|
|
123
|
+
function renderJob(j: CronJob): string {
|
|
124
|
+
const pin = isPinned(j) ? ` pin: ${[j.model, j.thinking].filter(Boolean).join(":")}` : "";
|
|
125
|
+
const status = j.lastStatus === "fail" ? ` [FAIL: ${j.lastError ?? "unknown"}]` : j.lastStatus === "ok" ? " [ok]" : "";
|
|
126
|
+
return `${j.name.padEnd(20)} ${j.schedule.padEnd(15)} next: ${fmt(j.nextRun).padEnd(28)} last: ${fmt(j.lastRun).padEnd(28)} ${j.enabled ? "enabled" : "DISABLED"}${status}${pin}`;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function renderList(jobs: CronJob[]): string {
|
|
130
|
+
if (jobs.length === 0) {
|
|
131
|
+
return `No cron jobs. Add one: cron action:"add" name:"daily" schedule:"0 9 * * mon" prompt:"..."`;
|
|
132
|
+
}
|
|
133
|
+
return jobs.map(renderJob).join("\n");
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Escape crontab's special % (newline/stdin-end) — lexical, applies inside shell quotes too. */
|
|
137
|
+
export function cronEscape(s: string): string {
|
|
138
|
+
return s.replace(/%/g, "\\%");
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function renderExport(jobs: CronJob[], logsDir: string): string {
|
|
142
|
+
// The logs dir must exist before an installed crontab line first fires,
|
|
143
|
+
// or every run fails with "No such file or directory".
|
|
144
|
+
if (jobs.some((j) => j.enabled)) mkdirSync(logsDir, { recursive: true });
|
|
145
|
+
const lines = [
|
|
146
|
+
"# ceulen-cron export — install with: crontab -l | cat - cron.txt | crontab -",
|
|
147
|
+
"# Each line runs a headless `pi -p` (pi must be on cron's PATH); output lands under:",
|
|
148
|
+
`# ${logsDir}/`,
|
|
149
|
+
];
|
|
150
|
+
for (const j of jobs) {
|
|
151
|
+
if (!j.enabled) continue;
|
|
152
|
+
// Newlines are legal in prompts (multi-line prompts are natural) but not
|
|
153
|
+
// representable in a crontab line — a raw \n would terminate the command
|
|
154
|
+
// and turn the continuation into a live crontab entry. Skip, never emit.
|
|
155
|
+
if ([j.prompt, j.cwd, j.model ?? ""].some((s) => /[\n\r]/.test(s))) {
|
|
156
|
+
lines.push(`# job: ${j.name} skipped: prompt/cwd/model contains a newline (not representable in crontab)`);
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
const pin = `${j.model ? ` --model ${cronEscape(shellQuote(j.model))}` : ""}${j.thinking ? ` --thinking ${cronEscape(shellQuote(j.thinking))}` : ""}`;
|
|
160
|
+
lines.push(`# job: ${j.name}`);
|
|
161
|
+
lines.push(
|
|
162
|
+
`${j.schedule} cd ${cronEscape(shellQuote(j.cwd))} && pi -p --no-session${pin} ${cronEscape(shellQuote(j.prompt))} >> ${cronEscape(shellQuote(join(logsDir, `${j.name}.log`)))} 2>&1`,
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
if (!jobs.some((j) => j.enabled)) lines.push("# (no enabled jobs)");
|
|
166
|
+
return lines.join("\n");
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Deliver a fire as a follow-up turn. The loop guard arms ONLY on successful
|
|
171
|
+
* delivery: a throwing send never starts a turn, so agent_settled would never
|
|
172
|
+
* fire and the flag would stick, wedging future add/remove/run calls.
|
|
173
|
+
*/
|
|
174
|
+
export function deliverFire(
|
|
175
|
+
send: (...args: Parameters<ExtensionAPI["sendMessage"]>) => void,
|
|
176
|
+
state: { lastFireArmAt: number },
|
|
177
|
+
job: CronJob,
|
|
178
|
+
): boolean {
|
|
179
|
+
try {
|
|
180
|
+
send(
|
|
181
|
+
{
|
|
182
|
+
customType: "ceulen-cron-fire",
|
|
183
|
+
content: fireContent(job),
|
|
184
|
+
display: true,
|
|
185
|
+
details: { name: job.name, schedule: job.schedule, lastRun: job.lastRun },
|
|
186
|
+
},
|
|
187
|
+
{ triggerTurn: true, deliverAs: "followUp" },
|
|
188
|
+
);
|
|
189
|
+
state.lastFireArmAt = Date.now();
|
|
190
|
+
return true;
|
|
191
|
+
} catch {
|
|
192
|
+
// Delivery failed (e.g. session gone) — the job is already marked fired;
|
|
193
|
+
// next schedule continues and the guard stays disarmed.
|
|
194
|
+
return false;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Env for headless children: disables the cron scheduler inside the child so
|
|
199
|
+
* parent/child ticks never race on the shared jobs.json, and strips HERDR_ENV
|
|
200
|
+
* so the subagent runner auto-detect can't pick herdr — each herdr pane is a
|
|
201
|
+
* full pi host (A2A server + gateway registration), and an unattended job
|
|
202
|
+
* spawning panes multiplied into a 429 gateway-registration storm. An explicit
|
|
203
|
+
* runner:"herdr" pin still degrades to sdk on the missing env (pi-subagent
|
|
204
|
+
* resolveEffectiveRunner returns an error the agent can proceed on).
|
|
205
|
+
*
|
|
206
|
+
* The ProcessEnv annotation isn't cosmetic: a bare spread of process.env
|
|
207
|
+
* loses its index signature in the inferred literal type, so `delete
|
|
208
|
+
* env.HERDR_ENV` fails typecheck (CI failure 2026-09-16). */
|
|
209
|
+
export function childEnv(): NodeJS.ProcessEnv {
|
|
210
|
+
const env: NodeJS.ProcessEnv = { ...process.env, PI_CRON_DISABLED: "1" };
|
|
211
|
+
delete env.HERDR_ENV;
|
|
212
|
+
return env;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
export interface HeadlessDeps {
|
|
216
|
+
spawnFn: typeof spawn;
|
|
217
|
+
send: (...args: Parameters<ExtensionAPI["sendMessage"]>) => void;
|
|
218
|
+
state: { lastFireArmAt: number };
|
|
219
|
+
logsDir: string;
|
|
220
|
+
jobsDir: string;
|
|
221
|
+
/** Hard cap for the child run. Default 10 min. */
|
|
222
|
+
timeoutMs?: number;
|
|
223
|
+
/** Grace between SIGTERM and SIGKILL. Default 5s. */
|
|
224
|
+
escalateMs?: number;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/**
|
|
228
|
+
* Run a pinned job headless in its own pi process (Hermes-style fresh-session
|
|
229
|
+
* run): output is logged and the result is delivered back as a follow-up.
|
|
230
|
+
*/
|
|
231
|
+
export function runHeadless(job: CronJob, deps: HeadlessDeps): void {
|
|
232
|
+
const { spawnFn, send, state, logsDir, jobsDir } = deps;
|
|
233
|
+
const logPath = join(logsDir, `${job.name}-${new Date().toISOString().replace(/[:.]/g, "-")}.log`);
|
|
234
|
+
let out = "";
|
|
235
|
+
let done = false;
|
|
236
|
+
const finish = (code: number | null, errMsg?: string) => {
|
|
237
|
+
if (done) return;
|
|
238
|
+
done = true;
|
|
239
|
+
clearTimeout(killer);
|
|
240
|
+
if (escalate) clearTimeout(escalate);
|
|
241
|
+
try {
|
|
242
|
+
mkdirSync(logsDir, { recursive: true });
|
|
243
|
+
appendFileSync(logPath, out + (errMsg ? `\n[error] ${errMsg}\n` : ""));
|
|
244
|
+
} catch {
|
|
245
|
+
// log write is best-effort
|
|
246
|
+
}
|
|
247
|
+
const label = `⏰ Cron job '${job.name}' (headless${job.model ? `, model ${job.model}` : ""}${job.thinking ? `, thinking ${job.thinking}` : ""})`;
|
|
248
|
+
const ok = !errMsg && code === 0;
|
|
249
|
+
try {
|
|
250
|
+
setJobResult(jobsDir, job.name, ok ? "ok" : "fail", ok ? undefined : (errMsg ?? out.slice(-200)));
|
|
251
|
+
} catch {
|
|
252
|
+
// status persistence is best-effort — this runs in a deferred child
|
|
253
|
+
// callback where an uncaught throw would kill the host pi process
|
|
254
|
+
}
|
|
255
|
+
const body = errMsg
|
|
256
|
+
? `${label} failed to start: ${errMsg}`
|
|
257
|
+
: `${label} finished (exit ${code ?? "signal"}).\nOutput (tail):\n${out.slice(-4000) || "(none)"}\nLog: ${logPath}`;
|
|
258
|
+
deliverFire(send, state, { ...job, prompt: body });
|
|
259
|
+
};
|
|
260
|
+
// ponytail: timeoutMs cap (default 10min, cron.timeoutMs-configurable) —
|
|
261
|
+
// SIGTERM, then SIGKILL after the grace window; finish() is called at cap
|
|
262
|
+
// time so result/status happen even if close lags.
|
|
263
|
+
const timeoutMs = deps.timeoutMs ?? 600_000;
|
|
264
|
+
const escalateMs = deps.escalateMs ?? 5_000;
|
|
265
|
+
let escalate: NodeJS.Timeout | undefined;
|
|
266
|
+
const killer = setTimeout(
|
|
267
|
+
() => {
|
|
268
|
+
child?.kill("SIGTERM");
|
|
269
|
+
escalate = setTimeout(() => {
|
|
270
|
+
child?.kill("SIGKILL");
|
|
271
|
+
finish(null, `timed out after ${timeoutMs}ms`);
|
|
272
|
+
}, escalateMs);
|
|
273
|
+
escalate.unref?.();
|
|
274
|
+
},
|
|
275
|
+
timeoutMs,
|
|
276
|
+
);
|
|
277
|
+
killer.unref?.();
|
|
278
|
+
let child: ReturnType<typeof spawn>;
|
|
279
|
+
try {
|
|
280
|
+
child = spawnFn("pi", [...headlessArgs(job), job.prompt], {
|
|
281
|
+
cwd: job.cwd,
|
|
282
|
+
stdio: ["ignore", "pipe", "pipe"],
|
|
283
|
+
env: childEnv(),
|
|
284
|
+
});
|
|
285
|
+
} catch (err) {
|
|
286
|
+
clearTimeout(killer);
|
|
287
|
+
finish(null, String(err));
|
|
288
|
+
return;
|
|
289
|
+
}
|
|
290
|
+
child.stdout?.on("data", (d: Buffer) => {
|
|
291
|
+
if (out.length < 20_000) out += d.toString();
|
|
292
|
+
});
|
|
293
|
+
child.stderr?.on("data", (d: Buffer) => {
|
|
294
|
+
if (out.length < 20_000) out += d.toString();
|
|
295
|
+
});
|
|
296
|
+
child.on("error", (err: Error) => {
|
|
297
|
+
clearTimeout(killer);
|
|
298
|
+
finish(null, err.message);
|
|
299
|
+
});
|
|
300
|
+
child.on("close", (code) => {
|
|
301
|
+
clearTimeout(killer);
|
|
302
|
+
finish(code);
|
|
303
|
+
});
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** Newest log file for a job, or undefined. */
|
|
307
|
+
export function latestLog(logsDir: string, name: string): string | undefined {
|
|
308
|
+
let newest: string | undefined;
|
|
309
|
+
let newestMs = -1;
|
|
310
|
+
try {
|
|
311
|
+
for (const f of readdirSync(logsDir)) {
|
|
312
|
+
// `${name}-<ts>.log` = in-process headless runs; `${name}.log` = export-installed crontab runs.
|
|
313
|
+
// Require a digit right after `${name}-` so job "a" doesn't match job "a-b"'s logs.
|
|
314
|
+
if (
|
|
315
|
+
f !== `${name}.log` &&
|
|
316
|
+
(!f.startsWith(`${name}-`) || !/^\d/.test(f.slice(name.length + 1)) || !f.endsWith(".log"))
|
|
317
|
+
)
|
|
318
|
+
continue;
|
|
319
|
+
const p = join(logsDir, f);
|
|
320
|
+
// One vanished file (raced cleanup) must not abort the scan of the rest.
|
|
321
|
+
let ms: number;
|
|
322
|
+
try {
|
|
323
|
+
ms = statSync(p).mtimeMs;
|
|
324
|
+
} catch {
|
|
325
|
+
continue;
|
|
326
|
+
}
|
|
327
|
+
if (ms > newestMs) {
|
|
328
|
+
newestMs = ms;
|
|
329
|
+
newest = p;
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
} catch {
|
|
333
|
+
return undefined;
|
|
334
|
+
}
|
|
335
|
+
return newest;
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* Run one scheduler tick: fire all due jobs exactly once. Swallows everything —
|
|
340
|
+
* uncaught timer exceptions kill pi outright. Exported for tests.
|
|
341
|
+
*/
|
|
342
|
+
export function tickOnce(deps: {
|
|
343
|
+
dir: string;
|
|
344
|
+
enabled: boolean;
|
|
345
|
+
fire: (job: CronJob) => void;
|
|
346
|
+
now?: number;
|
|
347
|
+
}): void {
|
|
348
|
+
try {
|
|
349
|
+
if (!deps.enabled) return;
|
|
350
|
+
const jobs = loadJobs(deps.dir);
|
|
351
|
+
const now = deps.now ?? Date.now();
|
|
352
|
+
const due = dueJobs(jobs, now);
|
|
353
|
+
if (due.length === 0) return;
|
|
354
|
+
// Mark first, deliver second — a crashed delivery never re-fires in a loop.
|
|
355
|
+
for (const job of due) markFired(job, now);
|
|
356
|
+
try {
|
|
357
|
+
saveJobs(deps.dir, jobs);
|
|
358
|
+
} catch (e) {
|
|
359
|
+
// Persistence failed: firing now would re-fire every tick (lastRun never
|
|
360
|
+
// hits disk). Stay silent-ish, leave jobs due, and let them fire on the
|
|
361
|
+
// next tick once persistence recovers.
|
|
362
|
+
console.warn(`ceulen-cron: persisting lastRun failed, deferring ${due.length} due job(s):`, e);
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
for (const job of due) deps.fire(job);
|
|
366
|
+
} catch {
|
|
367
|
+
// never escape into the timer
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
export interface CronActionArgs {
|
|
372
|
+
dir: string;
|
|
373
|
+
state: { lastFireArmAt: number };
|
|
374
|
+
childMode: boolean;
|
|
375
|
+
send: (...args: Parameters<ExtensionAPI["sendMessage"]>) => void;
|
|
376
|
+
fire: (job: CronJob) => void;
|
|
377
|
+
params: { action: string; name?: string; schedule?: string; prompt?: string; cwd?: string; model?: string; thinking?: string; enabled?: boolean };
|
|
378
|
+
cwd: string;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
/** The cron tool's action dispatch. Exported for tests; throws on refused/failed actions. */
|
|
382
|
+
export function runCronAction(args: CronActionArgs): { content: { type: "text"; text: string }[]; details: unknown } {
|
|
383
|
+
const { dir, state, childMode, send, fire, cwd } = args;
|
|
384
|
+
const { action, name, schedule, prompt, cwd: paramCwd, model, thinking, enabled } = args.params;
|
|
385
|
+
|
|
386
|
+
if (childMode && MUTATING_ACTIONS.has(action)) {
|
|
387
|
+
throw new Error(
|
|
388
|
+
`cron: "${action}" is disabled in headless cron runs (PI_CRON_DISABLED) — fired jobs cannot create, remove, or trigger jobs.`,
|
|
389
|
+
);
|
|
390
|
+
}
|
|
391
|
+
if (isMutationRefused(state.lastFireArmAt, action)) {
|
|
392
|
+
throw new Error(
|
|
393
|
+
`cron: "${action}" is refused while a cron-fired turn is in progress (loop guard — fired jobs cannot create, remove, or trigger jobs).`,
|
|
394
|
+
);
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
switch (action) {
|
|
398
|
+
case "add": {
|
|
399
|
+
const job = addJob(dir, { name, schedule, prompt, cwd: paramCwd ?? cwd, model, thinking, enabled }, Date.now());
|
|
400
|
+
const pin = isPinned(job) ? ` Runs headless (${[job.model, job.thinking].filter(Boolean).join(", thinking ")}) — result arrives as a follow-up.` : "";
|
|
401
|
+
return {
|
|
402
|
+
content: [
|
|
403
|
+
{
|
|
404
|
+
type: "text" as const,
|
|
405
|
+
text: `Job '${job.name}' added (${job.schedule}). Next fire: ${fmt(job.nextRun)}.${pin} Fired turns cannot schedule further jobs. Use action:"remove" name:"${job.name}" to delete.`,
|
|
406
|
+
},
|
|
407
|
+
],
|
|
408
|
+
details: { action: "add", job },
|
|
409
|
+
};
|
|
410
|
+
}
|
|
411
|
+
case "remove": {
|
|
412
|
+
if (!name) throw new Error('name is required for action:"remove".');
|
|
413
|
+
if (!removeJob(dir, name)) throw new Error(`No job named '${name}'.`);
|
|
414
|
+
return { content: [{ type: "text" as const, text: `Job '${name}' removed.` }], details: { action: "remove", name } };
|
|
415
|
+
}
|
|
416
|
+
case "list": {
|
|
417
|
+
const jobs = loadJobs(dir);
|
|
418
|
+
return { content: [{ type: "text" as const, text: renderList(jobs) }], details: { action: "list", count: jobs.length } };
|
|
419
|
+
}
|
|
420
|
+
case "run": {
|
|
421
|
+
if (!name) throw new Error('name is required for action:"run".');
|
|
422
|
+
const jobs = loadJobs(dir);
|
|
423
|
+
const job = findJob(jobs, name);
|
|
424
|
+
if (!job) throw new Error(`No job named '${name}'.`);
|
|
425
|
+
if (!job.enabled) throw new Error(`Job '${name}' is disabled (enable with cron action:"enable" name:"${name}").`);
|
|
426
|
+
// Undelivered-manual-run guard: an unpinned job whose cwd mismatches this
|
|
427
|
+
// session can never deliver here, so don't burn the schedule slot — the
|
|
428
|
+
// same check fire() applies. fire() re-checks and records the failure.
|
|
429
|
+
if (!isPinned(job) && job.cwd !== cwd) {
|
|
430
|
+
setJobResult(dir, job.name, "fail", `cwd mismatch: job expects ${job.cwd}, session is ${cwd} — run from ${job.cwd}, or pin model/thinking to run headless`);
|
|
431
|
+
throw new Error(`cwd mismatch: job '${name}' expects ${job.cwd}, session is ${cwd} — run from ${job.cwd}, or pin model/thinking to run headless`);
|
|
432
|
+
}
|
|
433
|
+
markFired(job, Date.now());
|
|
434
|
+
saveJobs(dir, jobs);
|
|
435
|
+
fire(job);
|
|
436
|
+
return {
|
|
437
|
+
content: [{ type: "text" as const, text: `Job '${job.name}' fired manually — result arrives as a follow-up turn.` }],
|
|
438
|
+
details: { action: "run", name },
|
|
439
|
+
};
|
|
440
|
+
}
|
|
441
|
+
case "enable":
|
|
442
|
+
case "disable": {
|
|
443
|
+
if (!name) throw new Error(`name is required for action:"${action}".`);
|
|
444
|
+
const job = setJobEnabled(dir, name, action === "enable", Date.now());
|
|
445
|
+
const text =
|
|
446
|
+
action === "enable"
|
|
447
|
+
? `Job '${job.name}' enabled. Next fire: ${fmt(job.nextRun)}.`
|
|
448
|
+
: `Job '${job.name}' disabled — schedule kept; enable to resume.`;
|
|
449
|
+
return { content: [{ type: "text" as const, text }], details: { action, name, job } };
|
|
450
|
+
}
|
|
451
|
+
case "test": {
|
|
452
|
+
if (!schedule) throw new Error('schedule is required for action:"test".');
|
|
453
|
+
const err = validateSchedule(schedule);
|
|
454
|
+
if (err) throw new Error(`Invalid cron schedule '${schedule}': ${err}`);
|
|
455
|
+
const fires = nextFires(schedule, 5, new Date());
|
|
456
|
+
return {
|
|
457
|
+
content: [
|
|
458
|
+
{
|
|
459
|
+
type: "text" as const,
|
|
460
|
+
text: fires.length ? fires.map((d) => d.toLocaleString()).join("\n") : "No upcoming fire times.",
|
|
461
|
+
},
|
|
462
|
+
],
|
|
463
|
+
details: { action: "test", schedule, fires: fires.map((d) => d.toISOString()) },
|
|
464
|
+
};
|
|
465
|
+
}
|
|
466
|
+
case "logs": {
|
|
467
|
+
if (!name) throw new Error('name is required for action:"logs".');
|
|
468
|
+
const log = latestLog(join(dir, "logs"), name);
|
|
469
|
+
if (!log) {
|
|
470
|
+
return { content: [{ type: "text" as const, text: `No logs for '${name}'.` }], details: { action: "logs", name } };
|
|
471
|
+
}
|
|
472
|
+
// The log can vanish between latestLog() and the read (external cleanup,
|
|
473
|
+
// concurrent export run) — report it instead of throwing a raw ENOENT.
|
|
474
|
+
let tail: string;
|
|
475
|
+
try {
|
|
476
|
+
tail = readFileSync(log, "utf8").split("\n").slice(-40).join("\n");
|
|
477
|
+
} catch {
|
|
478
|
+
return {
|
|
479
|
+
content: [{ type: "text" as const, text: `Log for '${name}' is gone (${log}) — try again after its next run.` }],
|
|
480
|
+
details: { action: "logs", name, log, vanished: true },
|
|
481
|
+
};
|
|
482
|
+
}
|
|
483
|
+
return {
|
|
484
|
+
content: [{ type: "text" as const, text: `${log} (tail):\n${tail}` }],
|
|
485
|
+
details: { action: "logs", name, log },
|
|
486
|
+
};
|
|
487
|
+
}
|
|
488
|
+
case "export": {
|
|
489
|
+
const jobs = loadJobs(dir);
|
|
490
|
+
return {
|
|
491
|
+
content: [{ type: "text" as const, text: renderExport(jobs, join(dir, "logs")) }],
|
|
492
|
+
details: { action: "export", count: jobs.filter((j) => j.enabled).length },
|
|
493
|
+
};
|
|
494
|
+
}
|
|
495
|
+
default:
|
|
496
|
+
throw new Error(`Unknown action '${action}'.`);
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
// ---------------------------------------------------------------------------
|
|
501
|
+
|
|
502
|
+
// Module scope: a second factory invocation (/reload) must clear the previous
|
|
503
|
+
// interval instead of double-ticking — one tick interval per process.
|
|
504
|
+
let timer: NodeJS.Timeout | undefined;
|
|
505
|
+
|
|
506
|
+
export default function cronExtension(pi: ExtensionAPI) {
|
|
507
|
+
const dir = jobsDir(getAgentDir());
|
|
508
|
+
// Load-time read is global-only (no ctx yet — an untrusted cwd must not arm
|
|
509
|
+
// the scheduler); session_start re-reads with the trust gate below.
|
|
510
|
+
const settings = readCronSettings(process.cwd(), { project: false });
|
|
511
|
+
const state = { lastFireArmAt: 0 };
|
|
512
|
+
// Headless cron children: scheduler off, cron mutations refused (tool-level
|
|
513
|
+
// enforcement — the advisory line in fireContent is not enough there).
|
|
514
|
+
const childMode = process.env.PI_CRON_DISABLED === "1";
|
|
515
|
+
|
|
516
|
+
// The cron skill ships via its OWN resources_discover dir (munin/web
|
|
517
|
+
// pattern) so the kill-switch gates it: disabled module ⇒ factory never
|
|
518
|
+
// runs ⇒ no cron skill registered.
|
|
519
|
+
pi.on("resources_discover", () => ({
|
|
520
|
+
skillPaths: [path.join(skillsRoot(), "cron")],
|
|
521
|
+
}));
|
|
522
|
+
|
|
523
|
+
const send = pi.sendMessage.bind(pi);
|
|
524
|
+
|
|
525
|
+
function fire(job: CronJob): void {
|
|
526
|
+
if (isPinned(job)) {
|
|
527
|
+
runHeadless(job, { spawnFn: spawn, send, state, logsDir: join(dir, "logs"), jobsDir: dir, timeoutMs: settings.timeoutMs });
|
|
528
|
+
} else {
|
|
529
|
+
// ponytail: unpinned fires execute in THIS session — a session whose cwd
|
|
530
|
+
// differs from job.cwd would run the prompt against the wrong project.
|
|
531
|
+
// Skip + mark FAIL (visible in `cron list` / logs). Retry with
|
|
532
|
+
// action:"run" from the right cwd, or pin model/thinking to run headless
|
|
533
|
+
// in job.cwd no matter which session ticks first.
|
|
534
|
+
const sessionCwd = process.cwd();
|
|
535
|
+
if (job.cwd !== sessionCwd) {
|
|
536
|
+
setJobResult(dir, job.name, "fail", `cwd mismatch: job expects ${job.cwd}, session is ${sessionCwd}`);
|
|
537
|
+
return;
|
|
538
|
+
}
|
|
539
|
+
const delivered = deliverFire(send, state, job);
|
|
540
|
+
setJobResult(dir, job.name, delivered ? "ok" : "fail", delivered ? undefined : "delivery failed");
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
function tick(): void {
|
|
545
|
+
tickOnce({ dir, enabled: settings.enabled, fire });
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
function armTimer(): void {
|
|
549
|
+
if (childMode) return;
|
|
550
|
+
if (timer) clearInterval(timer);
|
|
551
|
+
timer = setInterval(tick, settings.tickMs);
|
|
552
|
+
timer.unref?.();
|
|
553
|
+
}
|
|
554
|
+
armTimer();
|
|
555
|
+
|
|
556
|
+
// ctx (and project trust) only exists from session_start on — re-read the
|
|
557
|
+
// repo scope there: a trusted repo may configure cron, an untrusted one is
|
|
558
|
+
// ignored (must not re-enable the scheduler or shrink tickMs).
|
|
559
|
+
pi.on("session_start", (_event, ctx) => {
|
|
560
|
+
Object.assign(
|
|
561
|
+
settings,
|
|
562
|
+
readCronSettings(ctx?.cwd, { project: ctx?.isProjectTrusted?.() === true }),
|
|
563
|
+
);
|
|
564
|
+
armTimer(); // pick up a changed tickMs
|
|
565
|
+
});
|
|
566
|
+
|
|
567
|
+
// (No agent_settled handling — the loop guard is purely time-based.)
|
|
568
|
+
|
|
569
|
+
pi.registerTool({
|
|
570
|
+
name: "cron",
|
|
571
|
+
label: "Cron",
|
|
572
|
+
description:
|
|
573
|
+
"Schedule recurring jobs (cron) that fire a prompt into this session while pi is running. Actions: add, remove, list, run (manual fire), enable/disable (toggle a job), test (preview fire times), logs (tail a job's newest log), export (crontab lines for 24/7).",
|
|
574
|
+
promptSnippet: "Schedule cron jobs: add/remove/list/run/enable/disable/test/logs/export.",
|
|
575
|
+
promptGuidelines: [
|
|
576
|
+
'Convert natural-language schedules to 5-field cron and verify with action:"test" before add.',
|
|
577
|
+
"Job prompts must be self-contained — fired turns have no conversation context.",
|
|
578
|
+
"Fired turns cannot create, remove, or trigger jobs (loop guard).",
|
|
579
|
+
'Pin model:"provider/id" and/or thinking:"high" to run a job headless in its own pi process — the result is delivered back as a follow-up.',
|
|
580
|
+
],
|
|
581
|
+
parameters: Type.Object({
|
|
582
|
+
action: Type.Union(
|
|
583
|
+
["add", "remove", "list", "run", "enable", "disable", "test", "logs", "export"].map((a) => Type.Literal(a)),
|
|
584
|
+
{ description: "Operation to perform." },
|
|
585
|
+
),
|
|
586
|
+
name: Type.Optional(Type.String({ description: "Job name (add/remove/run/enable/disable)." })),
|
|
587
|
+
enabled: Type.Optional(
|
|
588
|
+
Type.Boolean({ description: 'Create the job disabled (add, default true). Re-enable later with action:"enable".' }),
|
|
589
|
+
),
|
|
590
|
+
schedule: Type.Optional(
|
|
591
|
+
Type.String({ description: '5-field cron expression (add/test), e.g. "0 9 * * mon".' }),
|
|
592
|
+
),
|
|
593
|
+
prompt: Type.Optional(
|
|
594
|
+
Type.String({ description: 'Self-contained prompt fired as a turn (add), e.g. "Check CI status and summarize failures".' }),
|
|
595
|
+
),
|
|
596
|
+
cwd: Type.Optional(
|
|
597
|
+
Type.String({ description: "Working dir recorded for export lines (add). Defaults to current dir." }),
|
|
598
|
+
),
|
|
599
|
+
model: Type.Optional(
|
|
600
|
+
Type.String({
|
|
601
|
+
description:
|
|
602
|
+
'Model pattern for the fired run, e.g. "zai-anthropic/glm-5.3-flash" (optionally "model:high"). Set → job runs headless in its own pi process; result arrives as a follow-up (add).',
|
|
603
|
+
}),
|
|
604
|
+
),
|
|
605
|
+
thinking: Type.Optional(
|
|
606
|
+
Type.String({ description: "Thinking level for the fired run: off|minimal|low|medium|high|xhigh|max (add). Implies headless." }),
|
|
607
|
+
),
|
|
608
|
+
// logs shares `name` with remove/run
|
|
609
|
+
}),
|
|
610
|
+
async execute(_id, params, _signal, _onUpdate, ctx) {
|
|
611
|
+
return runCronAction({
|
|
612
|
+
dir,
|
|
613
|
+
state,
|
|
614
|
+
childMode,
|
|
615
|
+
send,
|
|
616
|
+
fire,
|
|
617
|
+
params: params as {
|
|
618
|
+
action: string;
|
|
619
|
+
name?: string;
|
|
620
|
+
schedule?: string;
|
|
621
|
+
prompt?: string;
|
|
622
|
+
cwd?: string;
|
|
623
|
+
model?: string;
|
|
624
|
+
thinking?: string;
|
|
625
|
+
enabled?: boolean;
|
|
626
|
+
},
|
|
627
|
+
cwd: ctx.cwd,
|
|
628
|
+
});
|
|
629
|
+
},
|
|
630
|
+
});
|
|
631
|
+
|
|
632
|
+
pi.registerCommand("cron", {
|
|
633
|
+
description: "List cron jobs",
|
|
634
|
+
handler: async (_args, ctx) => {
|
|
635
|
+
ctx.ui.notify(renderList(loadJobs(dir)), "info");
|
|
636
|
+
},
|
|
637
|
+
});
|
|
638
|
+
}
|