@cydm/pie 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.
- package/README.md +51 -27
- package/dist/builtin/extensions/ask-user/index.js +4 -4
- package/dist/builtin/extensions/cron/index.js +906 -158
- package/dist/builtin/extensions/im-forward/README.md +4 -2
- package/dist/builtin/extensions/im-forward/index.js +6822 -3951
- package/dist/builtin/extensions/memory/index.js +76 -28
- package/dist/builtin/extensions/pie-ipc/README.md +2 -2
- package/dist/builtin/extensions/pie-ipc/index.js +282 -58
- package/dist/builtin/extensions/pie-proc/README.md +7 -7
- package/dist/builtin/extensions/pie-proc/index.js +227 -75
- package/dist/builtin/extensions/plan-mode/index.js +5 -5
- package/dist/builtin/extensions/subagent/index.js +8 -8
- package/dist/builtin/extensions/todo/index.js +4 -4
- package/dist/builtin/skills/chrome-devtools-axi/SKILL.md +26 -24
- package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +199 -121
- package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
- package/dist/builtin/skills/chrome-devtools-axi/chunk-HAUDUMDO.js +795 -0
- package/dist/builtin/skills/chrome-devtools-axi/{cli-ZE754CTH.js → cli-K7ESY3XD.js} +433 -255
- package/dist/builtin/skills/computer-use-axi/SKILL.md +25 -8
- package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +293 -64
- package/dist/builtin/skills/computer-use-axi/computer-use-axi-runtime.js +2 -2
- package/dist/builtin/skills/tui-use/tui-use-daemon.cjs +451 -43
- package/dist/chunks/{chunk-3W3SXVPB.js → chunk-4UIUMTHG.js} +993 -371
- package/dist/chunks/chunk-6WKBQZWM.js +19 -0
- package/dist/chunks/{chunk-5KI4Y4LA.js → chunk-BA4Z27XT.js} +4 -3
- package/dist/chunks/{chunk-BLDI2GRF.js → chunk-DBDU3RRN.js} +1364 -446
- package/dist/chunks/{chunk-LAJXWOKS.js → chunk-EEC5PJTC.js} +11 -9
- package/dist/chunks/chunk-IZKHSUNQ.js +30 -0
- package/dist/chunks/{chunk-Y3I2UV5Y.js → chunk-LRHNAG4V.js} +349 -288
- package/dist/chunks/chunk-OU33ROFD.js +717 -0
- package/dist/chunks/{chunk-Z2FKA2ZH.js → chunk-PN6B54VT.js} +104 -22
- package/dist/chunks/{chunk-NHV2CALB.js → chunk-WYXUF4MP.js} +388 -32
- package/dist/chunks/{chunk-4PR34UZF.js → chunk-Z5KL6AO2.js} +159 -145
- package/dist/chunks/{host-image-fallback-N7RHNPYN.js → host-image-fallback-RASJSVZY.js} +1 -1
- package/dist/chunks/{manager-cli-NEZA46M5.js → manager-cli-Y6HM3MHA.js} +5 -5
- package/dist/chunks/{model-registry-3XAHXXTA.js → model-registry-5TLYILYR.js} +2 -2
- package/dist/chunks/{read-file-understanding-FMPXR6EJ.js → read-file-understanding-VPKDBV23.js} +5 -5
- package/dist/chunks/{src-B44QWSGM.js → src-2XI5P62J.js} +2 -2
- package/dist/chunks/{src-EGXFJ3WA.js → src-6QGGDHIW.js} +3 -3
- package/dist/chunks/{src-Q7LU27C2.js → src-CCEENRKC.js} +31 -1
- package/dist/chunks/{src-CLE5ILN4.js → src-DI4MCAGT.js} +20 -4
- package/dist/chunks/{test-stream-OR3EJBNF.js → test-stream-SYVWIPPW.js} +2 -2
- package/dist/cli.js +1890 -1489
- package/models.schema.json +271 -0
- package/package.json +2 -2
- package/dist/builtin/skills/chrome-devtools-axi/chunk-Z2A5LA5A.js +0 -407
- package/dist/chunks/chunk-EGZ5TZRM.js +0 -1444
- package/dist/chunks/{chunk-CGSFBWOM.js → chunk-WBL73KRI.js} +3 -3
- package/dist/chunks/{manager-upgrade-CTU3ISCW.js → manager-upgrade-LSTOHBUV.js} +3 -3
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "node:module"; const require = __createRequire(import.meta.url);
|
|
2
|
+
import {
|
|
3
|
+
registerCronPanelBridge
|
|
4
|
+
} from "../../../chunks/chunk-IZKHSUNQ.js";
|
|
2
5
|
import {
|
|
3
6
|
Type
|
|
4
7
|
} from "../../../chunks/chunk-XXGYUYXI.js";
|
|
5
8
|
import "../../../chunks/chunk-LZQXQOPJ.js";
|
|
6
9
|
|
|
7
10
|
// builtin/extensions/cron/index.ts
|
|
8
|
-
import * as
|
|
9
|
-
import * as
|
|
10
|
-
import { homedir } from "node:os";
|
|
11
|
+
import * as path6 from "node:path";
|
|
12
|
+
import * as fs6 from "node:fs";
|
|
11
13
|
|
|
12
14
|
// builtin/extensions/cron/store.ts
|
|
13
15
|
import * as fs from "node:fs";
|
|
@@ -56,6 +58,9 @@ function validateSchedule(value) {
|
|
|
56
58
|
throw new Error("invalid schedule (every: integer seconds 60..31536000; at: ISO timestamp with timezone; count: integer 1..1000 for every/cron)");
|
|
57
59
|
}
|
|
58
60
|
function nextTime(s, after) {
|
|
61
|
+
if (!Number.isSafeInteger(after) || after < -8e15 || after > 8e15) {
|
|
62
|
+
throw new Error("invalid schedule reference timestamp");
|
|
63
|
+
}
|
|
59
64
|
if ("at" in s) return Date.parse(s.at) > after ? Date.parse(s.at) : null;
|
|
60
65
|
if ("every" in s) return after + s.every * 1e3;
|
|
61
66
|
const f = fields(s.cron), parts = s.cron.trim().split(/\s+/);
|
|
@@ -129,11 +134,13 @@ function sweepStaleOwners(state, dir, opts = {}) {
|
|
|
129
134
|
return reaped;
|
|
130
135
|
}
|
|
131
136
|
var Store = class {
|
|
132
|
-
constructor(dir) {
|
|
137
|
+
constructor(dir, opts) {
|
|
133
138
|
this.dir = dir;
|
|
134
|
-
|
|
139
|
+
this.verifyDir = opts?.verifyDir;
|
|
140
|
+
if (opts?.createDir !== false) fs.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
135
141
|
}
|
|
136
142
|
dir;
|
|
143
|
+
verifyDir;
|
|
137
144
|
/** Durable, append-only audit trail for operator-visible cron decisions.
|
|
138
145
|
*
|
|
139
146
|
* Why a file and not `ctx.log`: ctx.log only prints when PIE_VERBOSE is set
|
|
@@ -146,9 +153,26 @@ var Store = class {
|
|
|
146
153
|
* failed audit write can never leave an unlogged change behind. A failure
|
|
147
154
|
* therefore refuses the mutation (fail-closed, like the rest of the store). */
|
|
148
155
|
audit(record) {
|
|
149
|
-
|
|
156
|
+
this.verifyDir?.();
|
|
157
|
+
const auditPath = path.join(this.dir, "audit.log");
|
|
158
|
+
if (fs.existsSync(auditPath)) {
|
|
159
|
+
const st = fs.lstatSync(auditPath);
|
|
160
|
+
if (st.isSymbolicLink() || !st.isFile()) {
|
|
161
|
+
throw new Error("refusing to write audit log to non-regular file");
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
const flags = fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_APPEND | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0);
|
|
165
|
+
const fd = fs.openSync(auditPath, flags, 384);
|
|
166
|
+
try {
|
|
167
|
+
const fdStat = fs.fstatSync(fd);
|
|
168
|
+
if (!fdStat.isFile() || fdStat.nlink !== 1) throw new Error("audit log target is not a single-link regular file");
|
|
169
|
+
this.verifyDir?.();
|
|
170
|
+
const line = `${JSON.stringify({ at: Date.now(), ...record })}
|
|
150
171
|
`;
|
|
151
|
-
|
|
172
|
+
fs.writeFileSync(fd, line);
|
|
173
|
+
} finally {
|
|
174
|
+
fs.closeSync(fd);
|
|
175
|
+
}
|
|
152
176
|
}
|
|
153
177
|
/** Serialized bytes of the state currently on disk; undefined until the
|
|
154
178
|
* first save. A poll transaction that leaves the state byte-identical
|
|
@@ -171,9 +195,11 @@ var Store = class {
|
|
|
171
195
|
/** Run fn under the cross-process write mutex. Also used for coordinator
|
|
172
196
|
* election/release, which never nest a state transaction. */
|
|
173
197
|
withWriteLock(fn) {
|
|
198
|
+
this.verifyDir?.();
|
|
174
199
|
const lock = path.join(this.dir, "write.lock");
|
|
175
200
|
const token = this.acquireWriteLock(lock);
|
|
176
201
|
try {
|
|
202
|
+
this.verifyDir?.();
|
|
177
203
|
return fn();
|
|
178
204
|
} finally {
|
|
179
205
|
this.releaseWriteLock(lock, token);
|
|
@@ -205,19 +231,63 @@ var Store = class {
|
|
|
205
231
|
acquireWriteLock(lock) {
|
|
206
232
|
const token = randomUUID();
|
|
207
233
|
const candidate = path.join(this.dir, `write.lock.acquire.${token}`);
|
|
234
|
+
const holderPath = path.join(candidate, `held.${token}`);
|
|
235
|
+
let candDev;
|
|
236
|
+
let candIno;
|
|
237
|
+
let holderDev;
|
|
238
|
+
let holderIno;
|
|
239
|
+
let holderContent;
|
|
240
|
+
const cleanupCandidate = () => {
|
|
241
|
+
try {
|
|
242
|
+
this.verifyDir?.();
|
|
243
|
+
if (candDev === void 0 || candIno === void 0) return;
|
|
244
|
+
const st = fs.lstatSync(candidate, { bigint: true });
|
|
245
|
+
if (st.isSymbolicLink() || !st.isDirectory() || st.dev !== candDev || st.ino !== candIno) return;
|
|
246
|
+
fs.rmSync(candidate, { recursive: true, force: true });
|
|
247
|
+
} catch {
|
|
248
|
+
}
|
|
249
|
+
};
|
|
250
|
+
const assertCandidateIntact = () => {
|
|
251
|
+
this.verifyDir?.();
|
|
252
|
+
const st = fs.lstatSync(candidate, { bigint: true });
|
|
253
|
+
if (st.isSymbolicLink() || !st.isDirectory() || st.dev !== candDev || st.ino !== candIno) {
|
|
254
|
+
throw new Error("lock candidate substituted during contention");
|
|
255
|
+
}
|
|
256
|
+
const entries = fs.readdirSync(candidate);
|
|
257
|
+
if (entries.length !== 1 || entries[0] !== `held.${token}`) {
|
|
258
|
+
throw new Error("lock candidate entries modified during contention");
|
|
259
|
+
}
|
|
260
|
+
const hst = fs.lstatSync(holderPath, { bigint: true });
|
|
261
|
+
if (hst.isSymbolicLink() || !hst.isFile() || hst.nlink !== 1n || hst.dev !== holderDev || hst.ino !== holderIno) {
|
|
262
|
+
throw new Error("lock holder entry substituted during contention");
|
|
263
|
+
}
|
|
264
|
+
const raw = this.readRegularText(holderPath, 4096);
|
|
265
|
+
if (raw !== holderContent) {
|
|
266
|
+
throw new Error("lock holder metadata modified during contention");
|
|
267
|
+
}
|
|
268
|
+
};
|
|
208
269
|
try {
|
|
270
|
+
this.verifyDir?.();
|
|
209
271
|
fs.mkdirSync(candidate, { mode: 448 });
|
|
272
|
+
const candStat = fs.lstatSync(candidate, { bigint: true });
|
|
273
|
+
if (candStat.isSymbolicLink() || !candStat.isDirectory()) throw new Error("lock candidate is not a directory");
|
|
274
|
+
candDev = candStat.dev;
|
|
275
|
+
candIno = candStat.ino;
|
|
210
276
|
try {
|
|
211
|
-
this.writeHolderEntry(candidate, token);
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
} catch {
|
|
277
|
+
holderContent = this.writeHolderEntry(candidate, token);
|
|
278
|
+
const holderStat = fs.lstatSync(holderPath, { bigint: true });
|
|
279
|
+
if (holderStat.isSymbolicLink() || !holderStat.isFile() || holderStat.nlink !== 1n) {
|
|
280
|
+
throw new Error("lock holder entry is not a single-link regular file");
|
|
216
281
|
}
|
|
282
|
+
holderDev = holderStat.dev;
|
|
283
|
+
holderIno = holderStat.ino;
|
|
284
|
+
} catch (error) {
|
|
285
|
+
cleanupCandidate();
|
|
217
286
|
throw error;
|
|
218
287
|
}
|
|
219
288
|
const deadline = Date.now() + 2e3;
|
|
220
289
|
for (let spin = 0; ; spin++) {
|
|
290
|
+
assertCandidateIntact();
|
|
221
291
|
try {
|
|
222
292
|
fs.renameSync(candidate, lock);
|
|
223
293
|
return token;
|
|
@@ -233,16 +303,20 @@ var Store = class {
|
|
|
233
303
|
}
|
|
234
304
|
}
|
|
235
305
|
} finally {
|
|
236
|
-
|
|
237
|
-
fs.rmSync(candidate, { recursive: true, force: true });
|
|
238
|
-
} catch {
|
|
239
|
-
}
|
|
306
|
+
cleanupCandidate();
|
|
240
307
|
}
|
|
241
308
|
}
|
|
242
309
|
writeHolderEntry(dir, token) {
|
|
243
|
-
|
|
310
|
+
const content = JSON.stringify({ version: 1, pid: process.pid, createdAt: Date.now() });
|
|
311
|
+
fs.writeFileSync(path.join(dir, `held.${token}`), content, { mode: 384, flag: "wx" });
|
|
312
|
+
return content;
|
|
244
313
|
}
|
|
245
314
|
releaseWriteLock(lock, token) {
|
|
315
|
+
try {
|
|
316
|
+
this.verifyDir?.();
|
|
317
|
+
} catch {
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
246
320
|
try {
|
|
247
321
|
fs.unlinkSync(path.join(lock, `held.${token}`));
|
|
248
322
|
} catch {
|
|
@@ -264,6 +338,21 @@ var Store = class {
|
|
|
264
338
|
/** Remove the stale canonical lock so an install can proceed. Returns true
|
|
265
339
|
* when the canonical path is now free for a rename. */
|
|
266
340
|
retireWriteLock(lock) {
|
|
341
|
+
let lockDev, lockIno;
|
|
342
|
+
const verifyLockDir = () => {
|
|
343
|
+
try {
|
|
344
|
+
this.verifyDir?.();
|
|
345
|
+
const st = fs.lstatSync(lock, { bigint: true });
|
|
346
|
+
if (st.isSymbolicLink() || !st.isDirectory()) return false;
|
|
347
|
+
if (lockDev !== void 0 && (st.dev !== lockDev || st.ino !== lockIno)) return false;
|
|
348
|
+
lockDev = st.dev;
|
|
349
|
+
lockIno = st.ino;
|
|
350
|
+
return true;
|
|
351
|
+
} catch {
|
|
352
|
+
return false;
|
|
353
|
+
}
|
|
354
|
+
};
|
|
355
|
+
if (!verifyLockDir()) return false;
|
|
267
356
|
let entries;
|
|
268
357
|
try {
|
|
269
358
|
entries = fs.readdirSync(lock);
|
|
@@ -273,6 +362,7 @@ var Store = class {
|
|
|
273
362
|
const holders = entries.filter((name) => name.startsWith("held."));
|
|
274
363
|
if (holders.length === 0) {
|
|
275
364
|
if (entries.length !== 0) return false;
|
|
365
|
+
if (!verifyLockDir()) return false;
|
|
276
366
|
try {
|
|
277
367
|
fs.rmdirSync(lock);
|
|
278
368
|
return true;
|
|
@@ -283,7 +373,10 @@ var Store = class {
|
|
|
283
373
|
for (const name of holders) {
|
|
284
374
|
let pid;
|
|
285
375
|
try {
|
|
286
|
-
|
|
376
|
+
if (!verifyLockDir()) return false;
|
|
377
|
+
const raw = this.readRegularText(path.join(lock, name), 4096);
|
|
378
|
+
if (raw === void 0) return false;
|
|
379
|
+
const parsed = JSON.parse(raw);
|
|
287
380
|
if (parsed?.version !== 1 || !Number.isInteger(parsed.pid) || parsed.pid <= 0) return false;
|
|
288
381
|
pid = parsed.pid;
|
|
289
382
|
} catch {
|
|
@@ -297,6 +390,7 @@ var Store = class {
|
|
|
297
390
|
}
|
|
298
391
|
}
|
|
299
392
|
for (const name of holders) {
|
|
393
|
+
if (!verifyLockDir()) return false;
|
|
300
394
|
try {
|
|
301
395
|
fs.unlinkSync(path.join(lock, name));
|
|
302
396
|
} catch (error) {
|
|
@@ -304,6 +398,7 @@ var Store = class {
|
|
|
304
398
|
return false;
|
|
305
399
|
}
|
|
306
400
|
}
|
|
401
|
+
if (!verifyLockDir()) return false;
|
|
307
402
|
try {
|
|
308
403
|
fs.rmdirSync(lock);
|
|
309
404
|
return true;
|
|
@@ -319,7 +414,7 @@ var Store = class {
|
|
|
319
414
|
const file = path.join(this.dir, "state.json");
|
|
320
415
|
let raw;
|
|
321
416
|
try {
|
|
322
|
-
raw =
|
|
417
|
+
raw = this.readRegularText(file, 4e6);
|
|
323
418
|
} catch {
|
|
324
419
|
this.lastSavedContent = void 0;
|
|
325
420
|
return;
|
|
@@ -331,20 +426,40 @@ var Store = class {
|
|
|
331
426
|
* transaction callback can repair an invalid field value (write it back
|
|
332
427
|
* valid) instead of dead-ending the store. save() still enforces the
|
|
333
428
|
* storage budgets. */
|
|
429
|
+
readRegularText(file, maxBytes) {
|
|
430
|
+
this.verifyDir?.();
|
|
431
|
+
const flags = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0);
|
|
432
|
+
let fd;
|
|
433
|
+
try {
|
|
434
|
+
fd = fs.openSync(file, flags);
|
|
435
|
+
} catch (error) {
|
|
436
|
+
if (error?.code === "ENOENT") return void 0;
|
|
437
|
+
throw error;
|
|
438
|
+
}
|
|
439
|
+
try {
|
|
440
|
+
const st = fs.fstatSync(fd);
|
|
441
|
+
if (!st.isFile()) throw new Error("cron state is not a regular file");
|
|
442
|
+
if (maxBytes !== void 0 && st.size > maxBytes) throw new Error("cron state exceeds size limit");
|
|
443
|
+
const text = fs.readFileSync(fd, "utf8");
|
|
444
|
+
this.verifyDir?.();
|
|
445
|
+
return text;
|
|
446
|
+
} finally {
|
|
447
|
+
fs.closeSync(fd);
|
|
448
|
+
}
|
|
449
|
+
}
|
|
334
450
|
readForRepair() {
|
|
335
|
-
const
|
|
336
|
-
if (
|
|
337
|
-
const s = JSON.parse(
|
|
451
|
+
const raw = this.readRegularText(path.join(this.dir, "state.json"), 4e6);
|
|
452
|
+
if (raw === void 0) return { version: 1, jobs: [], owners: {} };
|
|
453
|
+
const s = JSON.parse(raw);
|
|
338
454
|
if (s.version !== 1 || !Array.isArray(s.jobs) || !s.owners || typeof s.owners !== "object" || Array.isArray(s.owners)) {
|
|
339
455
|
throw new Error("invalid cron state; manual recovery required");
|
|
340
456
|
}
|
|
341
457
|
return s;
|
|
342
458
|
}
|
|
343
459
|
read() {
|
|
344
|
-
const
|
|
345
|
-
if (
|
|
346
|
-
|
|
347
|
-
const s = JSON.parse(fs.readFileSync(file, "utf8"));
|
|
460
|
+
const raw = this.readRegularText(path.join(this.dir, "state.json"), 4e6);
|
|
461
|
+
if (raw === void 0) return { version: 1, jobs: [], owners: {} };
|
|
462
|
+
const s = JSON.parse(raw);
|
|
348
463
|
this.validateState(s);
|
|
349
464
|
return s;
|
|
350
465
|
}
|
|
@@ -359,7 +474,7 @@ var Store = class {
|
|
|
359
474
|
throw new Error("invalid managed schedule intent; manual recovery required");
|
|
360
475
|
const ids = /* @__PURE__ */ new Set();
|
|
361
476
|
for (const j of s.jobs) {
|
|
362
|
-
if (!j || typeof j.id !== "string" || ids.has(j.id) || typeof j.sessionId !== "string" || !j.sessionId || j.sessionId.length > 256 || typeof j.cwd !== "string" || !path.isAbsolute(j.cwd) || typeof j.prompt !== "string" || !j.prompt.trim() || j.prompt.length > 16e3 || typeof j.enabled !== "boolean" || !["ready", "running", "blocked"].includes(j.state) || j.remaining !== void 0 && (!Number.isSafeInteger(j.remaining) || j.remaining < 0 || j.remaining > 1e3) || j.next !== null && !Number.isSafeInteger(j.next) || j.authorization !== void 0 && !["dialog", "yolo", "unattended"].includes(j.authorization) || j.retriedOnce !== void 0 && typeof j.retriedOnce !== "boolean" || j.noticedError !== void 0 && typeof j.noticedError !== "string") throw new Error("invalid cron job; manual recovery required");
|
|
477
|
+
if (!j || typeof j.id !== "string" || ids.has(j.id) || typeof j.sessionId !== "string" || !j.sessionId || j.sessionId.length > 256 || typeof j.cwd !== "string" || !path.isAbsolute(j.cwd) || typeof j.prompt !== "string" || !j.prompt.trim() || j.prompt.length > 16e3 || typeof j.enabled !== "boolean" || !["ready", "running", "blocked"].includes(j.state) || j.remaining !== void 0 && (!Number.isSafeInteger(j.remaining) || j.remaining < 0 || j.remaining > 1e3) || j.next !== null && !Number.isSafeInteger(j.next) || j.authorization !== void 0 && !["dialog", "yolo", "unattended"].includes(j.authorization) || j.occurrence !== void 0 && !Number.isSafeInteger(j.occurrence) || j.target !== void 0 && typeof j.target !== "string" || j.deliveryStarted !== void 0 && typeof j.deliveryStarted !== "boolean" || j.retriedOnce !== void 0 && typeof j.retriedOnce !== "boolean" || j.error !== void 0 && typeof j.error !== "string" || j.noticedError !== void 0 && typeof j.noticedError !== "string" || j.pendingAction !== void 0 && j.pendingAction !== "remove" && j.pendingAction !== "pause" || j.consecutiveFailures !== void 0 && (!Number.isSafeInteger(j.consecutiveFailures) || j.consecutiveFailures < 0 || j.consecutiveFailures > 1e3)) throw new Error("invalid cron job; manual recovery required");
|
|
363
478
|
if (j.sessionId === PROCESS_SESSION_ID) {
|
|
364
479
|
if (!parseProcessCommand(j)) throw new Error("invalid process cron job; manual recovery required");
|
|
365
480
|
}
|
|
@@ -385,10 +500,13 @@ var Store = class {
|
|
|
385
500
|
occurrence: -Number.MAX_SAFE_INTEGER,
|
|
386
501
|
target: "x".repeat(64),
|
|
387
502
|
deliveryStarted: false,
|
|
503
|
+
pendingAction: "remove",
|
|
504
|
+
consecutiveFailures: 1e3,
|
|
388
505
|
error: "".repeat(500)
|
|
389
506
|
}))
|
|
390
507
|
};
|
|
391
508
|
if (state.jobs.length > 100 || Object.keys(state.owners).length > 1e3 || Buffer.byteLength(content, "utf8") > 4e6 || Buffer.byteLength(JSON.stringify(projected, null, 2), "utf8") > 4e6) throw new Error("cron state exceeds storage budget; no changes saved");
|
|
509
|
+
this.verifyDir?.();
|
|
392
510
|
const temp = path.join(this.dir, `state.${randomUUID()}.tmp`), dest = path.join(this.dir, "state.json");
|
|
393
511
|
const fd = fs.openSync(temp, "wx", 384);
|
|
394
512
|
try {
|
|
@@ -397,7 +515,17 @@ var Store = class {
|
|
|
397
515
|
} finally {
|
|
398
516
|
fs.closeSync(fd);
|
|
399
517
|
}
|
|
400
|
-
|
|
518
|
+
try {
|
|
519
|
+
this.verifyDir?.();
|
|
520
|
+
fs.renameSync(temp, dest);
|
|
521
|
+
} catch (err) {
|
|
522
|
+
try {
|
|
523
|
+
this.verifyDir?.();
|
|
524
|
+
fs.unlinkSync(temp);
|
|
525
|
+
} catch {
|
|
526
|
+
}
|
|
527
|
+
throw err;
|
|
528
|
+
}
|
|
401
529
|
if (process.platform !== "win32") {
|
|
402
530
|
const dir = fs.openSync(this.dir, "r");
|
|
403
531
|
try {
|
|
@@ -445,6 +573,23 @@ var Store = class {
|
|
|
445
573
|
ensureProcess(command, managedBy, cwd, schedule, now = Date.now()) {
|
|
446
574
|
return this.registerProcess(command, managedBy, cwd, schedule, now, { onlyIfAbsent: true });
|
|
447
575
|
}
|
|
576
|
+
/** Safe in-place command migration for an existing ready, enabled managed
|
|
577
|
+
* process job (e.g. pinning `--sessions-dir` on upgrade). Preserves job id,
|
|
578
|
+
* schedule, next run, and user pause/block/running reservations. */
|
|
579
|
+
syncProcessCommand(managedBy, command) {
|
|
580
|
+
this.disabledMarker(managedBy);
|
|
581
|
+
if (!Array.isArray(command) || command.length === 0 || !command.every((c) => typeof c === "string" && c.length > 0))
|
|
582
|
+
throw new Error("process command must be a non-empty string array");
|
|
583
|
+
return this.transaction((s) => {
|
|
584
|
+
const existing = s.jobs.find((j) => j.sessionId === PROCESS_SESSION_ID && parseProcessCommand(j)?.managedBy === managedBy);
|
|
585
|
+
if (!existing) return "unchanged";
|
|
586
|
+
const current = parseProcessCommand(existing)?.command ?? [];
|
|
587
|
+
if (current.length === command.length && current.every((v, i) => v === command[i])) return "unchanged";
|
|
588
|
+
if (existing.state === "running" || existing.state === "blocked" || !existing.enabled) return "deferred";
|
|
589
|
+
existing.prompt = JSON.stringify({ command, managedBy });
|
|
590
|
+
return "updated";
|
|
591
|
+
});
|
|
592
|
+
}
|
|
448
593
|
/** Opt-out and removal share the state writer mutex with on/default registration. */
|
|
449
594
|
disableProcess(managedBy) {
|
|
450
595
|
this.disabledMarker(managedBy);
|
|
@@ -455,11 +600,34 @@ var Store = class {
|
|
|
455
600
|
s.jobs = s.jobs.filter((j) => j !== existing);
|
|
456
601
|
return !!existing;
|
|
457
602
|
});
|
|
603
|
+
this.writeDisabledMarker(managedBy);
|
|
604
|
+
return removed;
|
|
605
|
+
}
|
|
606
|
+
/** Atomically replace the compatibility marker without following symlinks. */
|
|
607
|
+
writeDisabledMarker(managedBy) {
|
|
458
608
|
try {
|
|
459
|
-
|
|
609
|
+
this.verifyDir?.();
|
|
610
|
+
const dest = this.disabledMarker(managedBy);
|
|
611
|
+
const temp = path.join(this.dir, `.${managedBy}-disabled.${randomUUID()}.tmp`);
|
|
612
|
+
const fd = fs.openSync(temp, "wx", 384);
|
|
613
|
+
try {
|
|
614
|
+
fs.writeFileSync(fd, (/* @__PURE__ */ new Date()).toISOString());
|
|
615
|
+
} finally {
|
|
616
|
+
fs.closeSync(fd);
|
|
617
|
+
}
|
|
618
|
+
try {
|
|
619
|
+
this.verifyDir?.();
|
|
620
|
+
fs.renameSync(temp, dest);
|
|
621
|
+
} catch (err) {
|
|
622
|
+
try {
|
|
623
|
+
this.verifyDir?.();
|
|
624
|
+
fs.unlinkSync(temp);
|
|
625
|
+
} catch {
|
|
626
|
+
}
|
|
627
|
+
throw err;
|
|
628
|
+
}
|
|
460
629
|
} catch {
|
|
461
630
|
}
|
|
462
|
-
return removed;
|
|
463
631
|
}
|
|
464
632
|
validManagedKey(key) {
|
|
465
633
|
return /^[a-zA-Z0-9_-]{1,64}$/.test(key) && !["__proto__", "constructor", "prototype"].includes(key);
|
|
@@ -517,26 +685,73 @@ var Store = class {
|
|
|
517
685
|
findProcess(managedBy) {
|
|
518
686
|
return this.read().jobs.find((j) => j.sessionId === PROCESS_SESSION_ID && parseProcessCommand(j)?.managedBy === managedBy);
|
|
519
687
|
}
|
|
520
|
-
change(id, action, now = Date.now()) {
|
|
521
|
-
|
|
688
|
+
change(id, action, now = Date.now(), opts) {
|
|
689
|
+
let disabledManaged;
|
|
690
|
+
const outcome = this.transaction((s) => {
|
|
522
691
|
const j = s.jobs.find((j2) => j2.id === id);
|
|
523
692
|
if (!j) throw new Error("unknown job");
|
|
524
|
-
if (j.
|
|
693
|
+
if (opts?.expectedSessionId && j.sessionId !== opts.expectedSessionId) {
|
|
694
|
+
throw new Error("job does not belong to target worker session");
|
|
695
|
+
}
|
|
696
|
+
const rawManagedBy = opts?.disableManagedOnRemove ? parseProcessCommand(j)?.managedBy : void 0;
|
|
697
|
+
const managedBy = rawManagedBy && this.validManagedKey(rawManagedBy) ? rawManagedBy : void 0;
|
|
698
|
+
if (j.state === "running") {
|
|
699
|
+
if (action === "remove" || action === "pause") {
|
|
700
|
+
if (j.pendingAction === "remove" && action === "pause") {
|
|
701
|
+
throw new Error("job is already pending removal; cannot pause");
|
|
702
|
+
}
|
|
703
|
+
j.pendingAction = action;
|
|
704
|
+
if (action === "remove" && managedBy) {
|
|
705
|
+
s.managedEnabled = { ...s.managedEnabled, [managedBy]: false };
|
|
706
|
+
disabledManaged = managedBy;
|
|
707
|
+
}
|
|
708
|
+
return "deferred";
|
|
709
|
+
}
|
|
710
|
+
throw new Error("job is running; wait for completion or recover offline");
|
|
711
|
+
}
|
|
712
|
+
delete j.pendingAction;
|
|
525
713
|
if (action === "remove") {
|
|
714
|
+
if (managedBy) {
|
|
715
|
+
s.managedEnabled = { ...s.managedEnabled, [managedBy]: false };
|
|
716
|
+
disabledManaged = managedBy;
|
|
717
|
+
}
|
|
526
718
|
s.jobs = s.jobs.filter((j2) => j2.id !== id);
|
|
527
|
-
return;
|
|
719
|
+
return "applied";
|
|
528
720
|
}
|
|
529
|
-
|
|
530
|
-
if (j.enabled) {
|
|
721
|
+
if (action === "resume") {
|
|
531
722
|
if (j.remaining !== void 0 && j.remaining <= 0) throw new Error("job exhausted its execution count; create a new job");
|
|
532
|
-
j.
|
|
533
|
-
|
|
723
|
+
if (j.occurrence !== void 0 && !Number.isSafeInteger(j.occurrence)) throw new Error("invalid job occurrence; manual recovery required");
|
|
724
|
+
const next = nextTime(j.schedule, Math.max(now, j.occurrence ?? now));
|
|
725
|
+
if (next === null) throw new Error("one-shot expired; create a new job");
|
|
726
|
+
j.enabled = true;
|
|
727
|
+
j.next = next;
|
|
534
728
|
j.state = "ready";
|
|
535
729
|
delete j.error;
|
|
730
|
+
if (opts?.authorization !== void 0) j.authorization = opts.authorization;
|
|
731
|
+
} else {
|
|
732
|
+
j.enabled = false;
|
|
536
733
|
}
|
|
734
|
+
return "applied";
|
|
537
735
|
});
|
|
736
|
+
if (disabledManaged) {
|
|
737
|
+
this.writeDisabledMarker(disabledManaged);
|
|
738
|
+
}
|
|
739
|
+
return outcome;
|
|
538
740
|
}
|
|
539
741
|
};
|
|
742
|
+
function settleJob(state, job, error, now = Date.now(), opts) {
|
|
743
|
+
const pending = job.pendingAction;
|
|
744
|
+
delete job.pendingAction;
|
|
745
|
+
if (pending === "remove") {
|
|
746
|
+
state.jobs = state.jobs.filter((item) => item !== job);
|
|
747
|
+
return true;
|
|
748
|
+
}
|
|
749
|
+
if (opts?.interrupted && error !== void 0) completeInterrupted(job, error, now);
|
|
750
|
+
else if (opts?.retryable && error !== void 0) completeRetryable(job, error, now);
|
|
751
|
+
else complete(job, error, now);
|
|
752
|
+
if (pending === "pause") job.enabled = false;
|
|
753
|
+
return false;
|
|
754
|
+
}
|
|
540
755
|
function complete(job, error, now = Date.now()) {
|
|
541
756
|
delete job.target;
|
|
542
757
|
delete job.deliveryStarted;
|
|
@@ -547,6 +762,7 @@ function complete(job, error, now = Date.now()) {
|
|
|
547
762
|
}
|
|
548
763
|
job.state = "ready";
|
|
549
764
|
delete job.error;
|
|
765
|
+
delete job.consecutiveFailures;
|
|
550
766
|
if (job.remaining !== void 0) {
|
|
551
767
|
job.remaining -= 1;
|
|
552
768
|
if (job.remaining <= 0) {
|
|
@@ -558,6 +774,31 @@ function complete(job, error, now = Date.now()) {
|
|
|
558
774
|
job.next = "at" in job.schedule ? null : nextTime(job.schedule, Math.max(now, job.occurrence ?? now));
|
|
559
775
|
if (job.next === null) job.enabled = false;
|
|
560
776
|
}
|
|
777
|
+
function completeRetryable(job, error, now = Date.now()) {
|
|
778
|
+
const cmd = parseProcessCommand(job);
|
|
779
|
+
if (!cmd || cmd.managedBy !== "memory" || "at" in job.schedule) {
|
|
780
|
+
complete(job, error, now);
|
|
781
|
+
return;
|
|
782
|
+
}
|
|
783
|
+
delete job.target;
|
|
784
|
+
delete job.deliveryStarted;
|
|
785
|
+
const prevFailures = typeof job.consecutiveFailures === "number" && Number.isSafeInteger(job.consecutiveFailures) && job.consecutiveFailures >= 0 ? job.consecutiveFailures : 0;
|
|
786
|
+
const failures = Math.min(1e3, prevFailures + 1);
|
|
787
|
+
job.consecutiveFailures = failures;
|
|
788
|
+
const nextScheduled = nextTime(job.schedule, Math.max(now, job.occurrence ?? now));
|
|
789
|
+
if (nextScheduled === null) {
|
|
790
|
+
job.state = "ready";
|
|
791
|
+
job.enabled = false;
|
|
792
|
+
job.next = null;
|
|
793
|
+
job.error = `transient failure #${failures}: ${error.slice(0, 400)}`;
|
|
794
|
+
return;
|
|
795
|
+
}
|
|
796
|
+
const backoffMinutes = Math.min(240, 15 * Math.pow(2, Math.min(failures - 1, 4)));
|
|
797
|
+
const retryAt = Math.min(nextScheduled, Math.trunc(now) + backoffMinutes * 6e4);
|
|
798
|
+
job.state = "ready";
|
|
799
|
+
job.next = retryAt;
|
|
800
|
+
job.error = `degraded (transient failure #${failures}, auto-retry at ${new Date(retryAt).toISOString()}): ${error.slice(0, 350)}`;
|
|
801
|
+
}
|
|
561
802
|
function completeInterrupted(job, error, now = Date.now()) {
|
|
562
803
|
if (!isProcessJob(job)) {
|
|
563
804
|
complete(job, error, now);
|
|
@@ -574,20 +815,71 @@ function completeInterrupted(job, error, now = Date.now()) {
|
|
|
574
815
|
}
|
|
575
816
|
|
|
576
817
|
// builtin/extensions/cron/runtime.ts
|
|
577
|
-
import * as
|
|
578
|
-
import * as
|
|
818
|
+
import * as fs4 from "node:fs";
|
|
819
|
+
import * as path4 from "node:path";
|
|
579
820
|
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
580
821
|
|
|
822
|
+
// builtin/extensions/cron/managed-memory.ts
|
|
823
|
+
import * as path2 from "node:path";
|
|
824
|
+
import * as fs2 from "node:fs";
|
|
825
|
+
import { homedir } from "node:os";
|
|
826
|
+
function configPath() {
|
|
827
|
+
const env = process.env.PIE_CODING_AGENT_DIR;
|
|
828
|
+
return path2.resolve(env === "~" ? homedir() : env?.startsWith("~/") ? path2.join(homedir(), env.slice(2)) : env || path2.join(homedir(), ".pie"));
|
|
829
|
+
}
|
|
830
|
+
function localTimeToCronUtc(time) {
|
|
831
|
+
const m = /^(\d{1,2}):(\d{2})$/.exec(time);
|
|
832
|
+
if (!m) return { error: "time must be HH:MM" };
|
|
833
|
+
const hour = Number(m[1]), minute = Number(m[2]);
|
|
834
|
+
if (hour > 23 || minute > 59) return { error: "time out of range" };
|
|
835
|
+
const local = /* @__PURE__ */ new Date();
|
|
836
|
+
local.setHours(hour, minute, 0, 0);
|
|
837
|
+
const utcHour = local.getUTCHours(), utcMinute = local.getUTCMinutes();
|
|
838
|
+
return { cron: `${utcMinute} ${utcHour} * * *` };
|
|
839
|
+
}
|
|
840
|
+
function resolvedSessionsDirOverride() {
|
|
841
|
+
const override = process.env.PIE_SESSIONS_DIR;
|
|
842
|
+
if (!override) return void 0;
|
|
843
|
+
if (override === "~") return path2.join(homedir(), "sessions");
|
|
844
|
+
if (override.startsWith("~/")) return path2.join(homedir(), override.slice(2));
|
|
845
|
+
if (!path2.isAbsolute(override)) return void 0;
|
|
846
|
+
return path2.resolve(override);
|
|
847
|
+
}
|
|
848
|
+
function managedMemoryCommand() {
|
|
849
|
+
const entry = process.argv[1] ? path2.resolve(process.argv[1]) : path2.join(configPath(), "..", "cli.js");
|
|
850
|
+
const resolved = fs2.existsSync(entry) ? entry : path2.join(configPath(), "cli.js");
|
|
851
|
+
const loaderArgs = [];
|
|
852
|
+
for (let i = 0; i < process.execArgv.length; i++) {
|
|
853
|
+
const arg = process.execArgv[i];
|
|
854
|
+
if (/^--(?:import|loader|experimental-loader)=/.test(arg)) loaderArgs.push(arg);
|
|
855
|
+
else if (/^--(?:import|loader|experimental-loader)$/.test(arg) && i + 1 < process.execArgv.length)
|
|
856
|
+
loaderArgs.push(arg, process.execArgv[++i]);
|
|
857
|
+
}
|
|
858
|
+
const sessionsDir = resolvedSessionsDirOverride();
|
|
859
|
+
return [
|
|
860
|
+
process.execPath,
|
|
861
|
+
...loaderArgs,
|
|
862
|
+
resolved,
|
|
863
|
+
"memory",
|
|
864
|
+
"distill",
|
|
865
|
+
"--worker",
|
|
866
|
+
"--auto",
|
|
867
|
+
"--memory-root",
|
|
868
|
+
path2.join(configPath(), "memory"),
|
|
869
|
+
...sessionsDir ? ["--sessions-dir", sessionsDir] : []
|
|
870
|
+
];
|
|
871
|
+
}
|
|
872
|
+
|
|
581
873
|
// builtin/extensions/cron/worker.ts
|
|
582
874
|
import { spawn } from "node:child_process";
|
|
583
875
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
584
|
-
import * as
|
|
585
|
-
import * as
|
|
876
|
+
import * as fs3 from "node:fs";
|
|
877
|
+
import * as path3 from "node:path";
|
|
586
878
|
import { StringDecoder } from "node:string_decoder";
|
|
587
879
|
function runWorker(job, signal, cli = process.argv[1], configDir) {
|
|
588
880
|
if (signal.aborted) return Promise.reject(new Error("worker interrupted before launch"));
|
|
589
881
|
return new Promise((resolve3, reject) => {
|
|
590
|
-
const child = spawn(process.execPath, [
|
|
882
|
+
const child = spawn(process.execPath, [path3.resolve(cli), "--json-events", "--session-id", job.sessionId, "--resume-required"], {
|
|
591
883
|
cwd: job.cwd,
|
|
592
884
|
// R5-P2: a cron worker is an INDEPENDENT session — strip the manager
|
|
593
885
|
// identity/model quartet so it never inherits the manager's model or
|
|
@@ -690,7 +982,7 @@ function runWorker(job, signal, cli = process.argv[1], configDir) {
|
|
|
690
982
|
});
|
|
691
983
|
}
|
|
692
984
|
function processJobEnv(configDir) {
|
|
693
|
-
const allow = ["PATH", "PATHEXT", "SYSTEMROOT", "SYSTEMDRIVE", "COMSPEC", "LANG", "LC_ALL", "TERM", "TMPDIR", "TEMP", "TMP", "HOME", "USERPROFILE", "XDG_CONFIG_HOME", "XDG_CACHE_HOME"];
|
|
985
|
+
const allow = ["PATH", "PATHEXT", "SYSTEMROOT", "SYSTEMDRIVE", "COMSPEC", "LANG", "LC_ALL", "TZ", "TERM", "TMPDIR", "TEMP", "TMP", "HOME", "USERPROFILE", "XDG_CONFIG_HOME", "XDG_CACHE_HOME"];
|
|
694
986
|
const env = {};
|
|
695
987
|
for (const key of allow) {
|
|
696
988
|
const value = process.env[key];
|
|
@@ -700,6 +992,7 @@ function processJobEnv(configDir) {
|
|
|
700
992
|
if (configDir) env.PIE_CODING_AGENT_DIR = configDir;
|
|
701
993
|
return env;
|
|
702
994
|
}
|
|
995
|
+
var PROCESS_WORKER_RETRYABLE_EXIT_CODE = 75;
|
|
703
996
|
var ProcessWorkerCancelled = class extends Error {
|
|
704
997
|
aborted = true;
|
|
705
998
|
constructor(message) {
|
|
@@ -707,24 +1000,31 @@ var ProcessWorkerCancelled = class extends Error {
|
|
|
707
1000
|
this.name = "ProcessWorkerCancelled";
|
|
708
1001
|
}
|
|
709
1002
|
};
|
|
1003
|
+
var ProcessWorkerRetryable = class extends Error {
|
|
1004
|
+
retryable = true;
|
|
1005
|
+
constructor(message) {
|
|
1006
|
+
super(message);
|
|
1007
|
+
this.name = "ProcessWorkerRetryable";
|
|
1008
|
+
}
|
|
1009
|
+
};
|
|
710
1010
|
function runProcessWorker(job, command, cwd, deadlineMs = 30 * 60 * 1e3, logDir, signal, configDir) {
|
|
711
1011
|
return new Promise((resolve3, reject) => {
|
|
712
|
-
const dir = logDir ??
|
|
713
|
-
const logFile =
|
|
1012
|
+
const dir = logDir ?? path3.join(process.cwd(), "cron");
|
|
1013
|
+
const logFile = path3.join(dir, "process.log");
|
|
714
1014
|
try {
|
|
715
|
-
|
|
1015
|
+
fs3.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
716
1016
|
} catch {
|
|
717
1017
|
}
|
|
718
1018
|
const stamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
719
1019
|
const header = `[${stamp}] job=${job.id} cwd=${cwd} cmd=${JSON.stringify(command.command)}
|
|
720
1020
|
`;
|
|
721
1021
|
try {
|
|
722
|
-
|
|
1022
|
+
fs3.appendFileSync(logFile, header);
|
|
723
1023
|
} catch {
|
|
724
1024
|
}
|
|
725
1025
|
let out;
|
|
726
1026
|
try {
|
|
727
|
-
out =
|
|
1027
|
+
out = fs3.openSync(logFile, "a");
|
|
728
1028
|
} catch {
|
|
729
1029
|
}
|
|
730
1030
|
let child;
|
|
@@ -789,7 +1089,7 @@ function runProcessWorker(job, command, cwd, deadlineMs = 30 * 60 * 1e3, logDir,
|
|
|
789
1089
|
} catch (error) {
|
|
790
1090
|
if (out !== void 0) {
|
|
791
1091
|
try {
|
|
792
|
-
|
|
1092
|
+
fs3.closeSync(out);
|
|
793
1093
|
} catch {
|
|
794
1094
|
}
|
|
795
1095
|
}
|
|
@@ -801,7 +1101,7 @@ function runProcessWorker(job, command, cwd, deadlineMs = 30 * 60 * 1e3, logDir,
|
|
|
801
1101
|
signal?.removeEventListener("abort", stop);
|
|
802
1102
|
if (out !== void 0) {
|
|
803
1103
|
try {
|
|
804
|
-
|
|
1104
|
+
fs3.closeSync(out);
|
|
805
1105
|
} catch {
|
|
806
1106
|
}
|
|
807
1107
|
}
|
|
@@ -837,7 +1137,7 @@ function runProcessWorker(job, command, cwd, deadlineMs = 30 * 60 * 1e3, logDir,
|
|
|
837
1137
|
settled = true;
|
|
838
1138
|
if (cleanupFailure) failure = `process cleanup failed: ${String(cleanupFailure)}`;
|
|
839
1139
|
try {
|
|
840
|
-
|
|
1140
|
+
fs3.appendFileSync(logFile, `[${(/* @__PURE__ */ new Date()).toISOString()}] job=${job.id} exit=${code}${failure ? ` error=${failure}` : ""}
|
|
841
1141
|
`);
|
|
842
1142
|
} catch {
|
|
843
1143
|
}
|
|
@@ -845,6 +1145,10 @@ function runProcessWorker(job, command, cwd, deadlineMs = 30 * 60 * 1e3, logDir,
|
|
|
845
1145
|
reject(new ProcessWorkerCancelled(failure ?? `cancelled (exit ${code})`));
|
|
846
1146
|
return;
|
|
847
1147
|
}
|
|
1148
|
+
if (!failure && !cleanupFailure && command.managedBy === "memory" && code === PROCESS_WORKER_RETRYABLE_EXIT_CODE) {
|
|
1149
|
+
reject(new ProcessWorkerRetryable(`transient memory distillation failure (exit ${code})`));
|
|
1150
|
+
return;
|
|
1151
|
+
}
|
|
848
1152
|
if (failure || code !== 0) reject(new Error(failure ?? `process exited ${code}`));
|
|
849
1153
|
else resolve3();
|
|
850
1154
|
});
|
|
@@ -871,7 +1175,7 @@ var Runtime = class {
|
|
|
871
1175
|
this.execute = execute;
|
|
872
1176
|
this.processAlive = processAlive;
|
|
873
1177
|
this.executeProcess = executeProcess;
|
|
874
|
-
this.cwd =
|
|
1178
|
+
this.cwd = fs4.realpathSync(ctx.cwd);
|
|
875
1179
|
}
|
|
876
1180
|
ctx;
|
|
877
1181
|
store;
|
|
@@ -937,14 +1241,42 @@ var Runtime = class {
|
|
|
937
1241
|
void this.ensureMemoryDistillationDefault();
|
|
938
1242
|
}
|
|
939
1243
|
/** Default daily distillation at 03:00 local. Idempotent: an existing
|
|
940
|
-
* managed job
|
|
1244
|
+
* managed job is left untouched unless PIE_SESSIONS_DIR is set and the
|
|
1245
|
+
* persisted command lacks/mismatches `--sessions-dir` (safe in-place
|
|
1246
|
+
* upgrade for ready/enabled jobs; running/paused/blocked intent preserved). */
|
|
941
1247
|
async ensureMemoryDistillationDefault() {
|
|
942
1248
|
try {
|
|
943
1249
|
const existing = this.store.findProcess("memory");
|
|
944
|
-
if (existing)
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
1250
|
+
if (existing) {
|
|
1251
|
+
if (process.env.PIE_SESSIONS_DIR) {
|
|
1252
|
+
const command2 = managedMemoryCommand();
|
|
1253
|
+
if (command2.includes("--sessions-dir")) {
|
|
1254
|
+
const currentCmd = (() => {
|
|
1255
|
+
try {
|
|
1256
|
+
return JSON.parse(existing.prompt).command ?? [];
|
|
1257
|
+
} catch {
|
|
1258
|
+
return [];
|
|
1259
|
+
}
|
|
1260
|
+
})();
|
|
1261
|
+
const curIdx = currentCmd.indexOf("--sessions-dir");
|
|
1262
|
+
const wantIdx = command2.indexOf("--sessions-dir");
|
|
1263
|
+
const curDir = curIdx >= 0 ? currentCmd[curIdx + 1] : void 0;
|
|
1264
|
+
const wantDir = wantIdx >= 0 ? command2[wantIdx + 1] : void 0;
|
|
1265
|
+
if (curDir !== wantDir) {
|
|
1266
|
+
const outcome = this.store.syncProcessCommand("memory", command2);
|
|
1267
|
+
if (outcome === "updated") {
|
|
1268
|
+
this.ctx.log(`cron: migrated managed memory distillation command to pin --sessions-dir ${wantDir}`);
|
|
1269
|
+
} else if (outcome === "deferred") {
|
|
1270
|
+
this.ctx.log(`cron: managed memory distillation job needs repair to pin --sessions-dir ${wantDir} (currently ${existing.state === "running" ? "running" : !existing.enabled ? "paused" : existing.state}; run 'pie memory schedule on' when ready)`);
|
|
1271
|
+
}
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
}
|
|
1275
|
+
return;
|
|
1276
|
+
}
|
|
1277
|
+
await new Promise((resolve3) => setImmediate(resolve3));
|
|
1278
|
+
const command = managedMemoryCommand();
|
|
1279
|
+
const cronSpec = localTimeToCronUtc("03:00");
|
|
948
1280
|
if ("error" in cronSpec) throw new Error(cronSpec.error);
|
|
949
1281
|
if (this.store.ensureProcess(command, "memory", process.cwd(), cronSpec))
|
|
950
1282
|
this.ctx.log("cron: registered the default daily memory distillation (03:00)");
|
|
@@ -955,19 +1287,19 @@ var Runtime = class {
|
|
|
955
1287
|
}
|
|
956
1288
|
}
|
|
957
1289
|
markUnsafe() {
|
|
958
|
-
|
|
1290
|
+
fs4.mkdirSync(path4.join(this.store.dir, "unsafe.lock"), { recursive: true, mode: 448 });
|
|
959
1291
|
}
|
|
960
1292
|
coordinatorDir() {
|
|
961
|
-
return
|
|
1293
|
+
return path4.join(this.store.dir, "scheduler.lock");
|
|
962
1294
|
}
|
|
963
1295
|
coordinatorOwnerFile() {
|
|
964
|
-
return
|
|
1296
|
+
return path4.join(this.coordinatorDir(), COORDINATOR_OWNER_FILE);
|
|
965
1297
|
}
|
|
966
1298
|
readCoordinatorOwner() {
|
|
967
1299
|
try {
|
|
968
|
-
const file = this.coordinatorOwnerFile(), stat =
|
|
1300
|
+
const file = this.coordinatorOwnerFile(), stat = fs4.lstatSync(file);
|
|
969
1301
|
if (!stat.isFile() || stat.size > 4096) return void 0;
|
|
970
|
-
const raw =
|
|
1302
|
+
const raw = fs4.readFileSync(file, "utf8"), value = JSON.parse(raw);
|
|
971
1303
|
if (value?.version !== 1 || !Number.isSafeInteger(value.pid) || value.pid <= 0 || typeof value.instanceId !== "string" || !value.instanceId || value.instanceId.length > 128 || !Number.isSafeInteger(value.createdAt)) return void 0;
|
|
972
1304
|
return { value, raw };
|
|
973
1305
|
} catch {
|
|
@@ -992,17 +1324,17 @@ var Runtime = class {
|
|
|
992
1324
|
}
|
|
993
1325
|
acquireCoordinator() {
|
|
994
1326
|
const dir = this.coordinatorDir();
|
|
995
|
-
|
|
1327
|
+
fs4.mkdirSync(dir, { mode: 448 });
|
|
996
1328
|
const owner = { version: 1, pid: process.pid, instanceId: this.id, createdAt: Date.now() };
|
|
997
1329
|
try {
|
|
998
|
-
|
|
1330
|
+
fs4.writeFileSync(this.coordinatorOwnerFile(), JSON.stringify(owner), { mode: 384, flag: "wx" });
|
|
999
1331
|
} catch (error) {
|
|
1000
1332
|
try {
|
|
1001
|
-
|
|
1333
|
+
fs4.unlinkSync(this.coordinatorOwnerFile());
|
|
1002
1334
|
} catch {
|
|
1003
1335
|
}
|
|
1004
1336
|
try {
|
|
1005
|
-
|
|
1337
|
+
fs4.rmdirSync(dir);
|
|
1006
1338
|
} catch {
|
|
1007
1339
|
}
|
|
1008
1340
|
throw error;
|
|
@@ -1030,16 +1362,16 @@ var Runtime = class {
|
|
|
1030
1362
|
const latest = this.readCoordinatorOwner();
|
|
1031
1363
|
if (!latest || latest.raw !== held.raw) return false;
|
|
1032
1364
|
try {
|
|
1033
|
-
|
|
1034
|
-
|
|
1365
|
+
fs4.unlinkSync(this.coordinatorOwnerFile());
|
|
1366
|
+
fs4.rmdirSync(this.coordinatorDir());
|
|
1035
1367
|
return true;
|
|
1036
1368
|
} catch {
|
|
1037
1369
|
return false;
|
|
1038
1370
|
}
|
|
1039
1371
|
}
|
|
1040
1372
|
releaseCoordinator() {
|
|
1041
|
-
|
|
1042
|
-
|
|
1373
|
+
fs4.rmSync(this.coordinatorOwnerFile(), { force: true });
|
|
1374
|
+
fs4.rmdirSync(this.coordinatorDir());
|
|
1043
1375
|
this.leader = false;
|
|
1044
1376
|
}
|
|
1045
1377
|
persistOwner(sessionId) {
|
|
@@ -1048,14 +1380,14 @@ var Runtime = class {
|
|
|
1048
1380
|
state.owners[this.id] = { sessionId, cwd: this.cwd, busy: !this.ctx.isIdle(), registeredAt: Date.now() };
|
|
1049
1381
|
});
|
|
1050
1382
|
try {
|
|
1051
|
-
const livenessDir =
|
|
1052
|
-
|
|
1053
|
-
const liveness =
|
|
1383
|
+
const livenessDir = path4.join(this.store.dir, "owners-liveness");
|
|
1384
|
+
fs4.mkdirSync(livenessDir, { recursive: true });
|
|
1385
|
+
const liveness = path4.join(livenessDir, `${this.id}.json`);
|
|
1054
1386
|
try {
|
|
1055
|
-
|
|
1387
|
+
fs4.unlinkSync(liveness);
|
|
1056
1388
|
} catch {
|
|
1057
1389
|
}
|
|
1058
|
-
|
|
1390
|
+
fs4.writeFileSync(liveness, JSON.stringify({ pid: process.pid, at: Date.now() }), { mode: 384 });
|
|
1059
1391
|
} catch {
|
|
1060
1392
|
}
|
|
1061
1393
|
this.sessionId = sessionId;
|
|
@@ -1107,7 +1439,13 @@ var Runtime = class {
|
|
|
1107
1439
|
* conservative block; only a human can decide (double execution is worse
|
|
1108
1440
|
* than a stalled schedule).
|
|
1109
1441
|
*/
|
|
1110
|
-
handleBlock(job, error, executed) {
|
|
1442
|
+
handleBlock(state, job, error, executed) {
|
|
1443
|
+
const pending = job.pendingAction;
|
|
1444
|
+
delete job.pendingAction;
|
|
1445
|
+
if (pending === "remove") {
|
|
1446
|
+
state.jobs = state.jobs.filter((item) => item !== job);
|
|
1447
|
+
return;
|
|
1448
|
+
}
|
|
1111
1449
|
const repeating = !("at" in job.schedule);
|
|
1112
1450
|
if (!executed && repeating && !isProcessJob(job) && !job.retriedOnce) {
|
|
1113
1451
|
job.retriedOnce = true;
|
|
@@ -1115,12 +1453,13 @@ var Runtime = class {
|
|
|
1115
1453
|
delete job.target;
|
|
1116
1454
|
delete job.deliveryStarted;
|
|
1117
1455
|
job.next = nextTime(job.schedule, Math.max(Date.now(), job.occurrence ?? Date.now()));
|
|
1118
|
-
if (job.next === null) job.enabled = false;
|
|
1456
|
+
if (job.next === null || pending === "pause") job.enabled = false;
|
|
1119
1457
|
job.error = `retried automatically after a block that never executed: ${error}`.slice(0, 500);
|
|
1120
1458
|
this.auditQuiet({ kind: "auto-retry", jobId: job.id, sessionId: job.sessionId, cwd: job.cwd, detail: error });
|
|
1121
1459
|
return;
|
|
1122
1460
|
}
|
|
1123
1461
|
complete(job, error);
|
|
1462
|
+
if (pending === "pause") job.enabled = false;
|
|
1124
1463
|
this.auditQuiet({ kind: "blocked", jobId: job.id, sessionId: job.sessionId, cwd: job.cwd, detail: error });
|
|
1125
1464
|
}
|
|
1126
1465
|
notify(job, owners) {
|
|
@@ -1184,16 +1523,15 @@ Tell the user in one short message and wait for their decision. Do not resume or
|
|
|
1184
1523
|
}
|
|
1185
1524
|
flushCompletions() {
|
|
1186
1525
|
for (const [id, entry] of this.completions) {
|
|
1187
|
-
const { error, cancelled } = entry;
|
|
1526
|
+
const { error, cancelled, retryable } = entry;
|
|
1188
1527
|
try {
|
|
1189
1528
|
this.store.transaction((state) => {
|
|
1190
1529
|
const job = state.jobs.find((item) => item.id === id);
|
|
1191
1530
|
if (job?.state === "running") {
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
}
|
|
1531
|
+
settleJob(state, job, error, Date.now(), {
|
|
1532
|
+
interrupted: cancelled === true && error !== void 0 && isProcessJob(job) && job.target === "worker",
|
|
1533
|
+
retryable: retryable === true && error !== void 0 && isProcessJob(job) && job.target === "worker"
|
|
1534
|
+
});
|
|
1197
1535
|
}
|
|
1198
1536
|
});
|
|
1199
1537
|
this.completions.delete(id);
|
|
@@ -1203,14 +1541,14 @@ Tell the user in one short message and wait for their decision. Do not resume or
|
|
|
1203
1541
|
}
|
|
1204
1542
|
}
|
|
1205
1543
|
}
|
|
1206
|
-
finish(id, error, cancelled) {
|
|
1207
|
-
this.completions.set(id, { error, cancelled });
|
|
1544
|
+
finish(id, error, cancelled, retryable) {
|
|
1545
|
+
this.completions.set(id, { error, cancelled, retryable });
|
|
1208
1546
|
this.flushCompletions();
|
|
1209
1547
|
}
|
|
1210
1548
|
async poll(now = Date.now()) {
|
|
1211
1549
|
if (this.stopped || this.polling || !this.initialized) return;
|
|
1212
1550
|
if (this.pollRetryAt !== void 0 && Date.now() < this.pollRetryAt) return;
|
|
1213
|
-
if (
|
|
1551
|
+
if (fs4.existsSync(path4.join(this.store.dir, "unsafe.lock"))) {
|
|
1214
1552
|
this.abort.abort();
|
|
1215
1553
|
this.processAbort.abort();
|
|
1216
1554
|
this.ctx.ui.setStatus?.("cron", void 0);
|
|
@@ -1242,31 +1580,31 @@ Tell the user in one short message and wait for their decision. Do not resume or
|
|
|
1242
1580
|
let processLaunch;
|
|
1243
1581
|
this.store.transaction((state2) => {
|
|
1244
1582
|
if (this.recovering) {
|
|
1245
|
-
for (const job of state2.jobs) {
|
|
1583
|
+
for (const job of [...state2.jobs]) {
|
|
1246
1584
|
if (job.state === "running" && (job.target === "worker" || !job.target || !state2.owners[job.target])) {
|
|
1247
|
-
this.handleBlock(job, "coordinator restarted; outcome uncertain", true);
|
|
1585
|
+
this.handleBlock(state2, job, "coordinator restarted; outcome uncertain", true);
|
|
1248
1586
|
}
|
|
1249
1587
|
}
|
|
1250
1588
|
}
|
|
1251
1589
|
state2.owners[this.id] = { sessionId: this.sessionId, cwd: this.cwd, busy: !this.ctx.isIdle() };
|
|
1252
|
-
for (const job of state2.jobs) {
|
|
1590
|
+
for (const job of [...state2.jobs]) {
|
|
1253
1591
|
if (isProcessJob(job)) continue;
|
|
1254
1592
|
const owners = Object.entries(state2.owners).filter(([, owner]) => owner.sessionId === job.sessionId);
|
|
1255
1593
|
if (this.leader && job.state === "running" && job.target === "worker" && owners.length) this.abort.abort();
|
|
1256
|
-
if (job.enabled && owners.length > 1 && job.state !== "running") this.handleBlock(job, "duplicate participating session owners; close duplicate and resume job", false);
|
|
1594
|
+
if (job.enabled && owners.length > 1 && job.state !== "running") this.handleBlock(state2, job, "duplicate participating session owners; close duplicate and resume job", false);
|
|
1257
1595
|
if (job.state === "running" && job.target === this.id && this.accepted?.id === job.id) {
|
|
1258
1596
|
if (!this.accepted.consumed) {
|
|
1259
1597
|
for (const message of this.ctx.getMessages?.() ?? []) this.onMessage(message);
|
|
1260
1598
|
}
|
|
1261
1599
|
if (owners.length !== 1 || this.sessionId !== job.sessionId) {
|
|
1262
|
-
this.handleBlock(job, "owner changed or duplicate during delivery", !this.accepted.consumed);
|
|
1600
|
+
this.handleBlock(state2, job, "owner changed or duplicate during delivery", !this.accepted.consumed);
|
|
1263
1601
|
this.accepted = void 0;
|
|
1264
1602
|
this.acceptedIdlePolls = 0;
|
|
1265
1603
|
} else if (this.accepted.consumed && this.accepted.busy) {
|
|
1266
1604
|
if (this.ctx.isIdle()) {
|
|
1267
1605
|
this.acceptedIdlePolls += 1;
|
|
1268
1606
|
if (this.acceptedIdlePolls >= 2) {
|
|
1269
|
-
|
|
1607
|
+
settleJob(state2, job, this.accepted.error);
|
|
1270
1608
|
this.accepted = void 0;
|
|
1271
1609
|
this.acceptedIdlePolls = 0;
|
|
1272
1610
|
}
|
|
@@ -1274,14 +1612,14 @@ Tell the user in one short message and wait for their decision. Do not resume or
|
|
|
1274
1612
|
this.acceptedIdlePolls = 0;
|
|
1275
1613
|
}
|
|
1276
1614
|
} else if (!this.accepted.consumed && now - this.accepted.at > 6e4) {
|
|
1277
|
-
this.handleBlock(job, "input accepted but execution not observed; inspect before resuming", true);
|
|
1615
|
+
this.handleBlock(state2, job, "input accepted but execution not observed; inspect before resuming", true);
|
|
1278
1616
|
this.accepted = void 0;
|
|
1279
1617
|
this.acceptedIdlePolls = 0;
|
|
1280
1618
|
}
|
|
1281
1619
|
}
|
|
1282
1620
|
if (job.state === "running" && job.target === this.id && !job.deliveryStarted && this.ctx.isIdle()) {
|
|
1283
1621
|
if (owners.length !== 1 || owners[0][0] !== this.id || this.sessionId !== job.sessionId || this.cwd !== job.cwd) {
|
|
1284
|
-
this.handleBlock(job, "owner changed or duplicate; delivery blocked", false);
|
|
1622
|
+
this.handleBlock(state2, job, "owner changed or duplicate; delivery blocked", false);
|
|
1285
1623
|
} else {
|
|
1286
1624
|
job.deliveryStarted = true;
|
|
1287
1625
|
delivery = { ...job };
|
|
@@ -1320,7 +1658,7 @@ Tell the user in one short message and wait for their decision. Do not resume or
|
|
|
1320
1658
|
this.recovering = false;
|
|
1321
1659
|
if (delivery) {
|
|
1322
1660
|
const job = delivery;
|
|
1323
|
-
const scope = this.ctx.beginUserInput?.(() => !this.stopped && this.ready && this.sessionId === job.sessionId && !
|
|
1661
|
+
const scope = this.ctx.beginUserInput?.(() => !this.stopped && this.ready && this.sessionId === job.sessionId && !fs4.existsSync(path4.join(this.store.dir, "unsafe.lock")) && Object.values(this.store.read().owners).filter((owner) => owner.sessionId === job.sessionId).length === 1);
|
|
1324
1662
|
let error;
|
|
1325
1663
|
const content = `[Cron job=${job.id} scheduledAt=${job.occurrence}]
|
|
1326
1664
|
${job.prompt}`;
|
|
@@ -1341,12 +1679,12 @@ ${job.prompt}`;
|
|
|
1341
1679
|
if (launch) {
|
|
1342
1680
|
const job = launch;
|
|
1343
1681
|
const latest = this.store.read();
|
|
1344
|
-
if (this.stopped ||
|
|
1682
|
+
if (this.stopped || fs4.existsSync(path4.join(this.store.dir, "unsafe.lock")) || Object.values(latest.owners).some((owner) => owner.sessionId === job.sessionId)) {
|
|
1345
1683
|
this.finish(job.id, "ownership changed before worker launch; inspect before resuming");
|
|
1346
1684
|
return;
|
|
1347
1685
|
}
|
|
1348
1686
|
this.abort = new AbortController();
|
|
1349
|
-
this.worker = this.execute(job, this.abort.signal, void 0,
|
|
1687
|
+
this.worker = this.execute(job, this.abort.signal, void 0, path4.dirname(this.store.dir)).then(() => this.finish(job.id), (error) => this.finish(job.id, String(error))).catch(() => {
|
|
1350
1688
|
try {
|
|
1351
1689
|
this.markUnsafe();
|
|
1352
1690
|
} catch {
|
|
@@ -1357,7 +1695,15 @@ ${job.prompt}`;
|
|
|
1357
1695
|
const job = processLaunch;
|
|
1358
1696
|
const command = parseProcessCommand(job);
|
|
1359
1697
|
this.processAbort = new AbortController();
|
|
1360
|
-
this.worker = this.executeProcess(job, command, job.cwd, 30 * 60 * 1e3, this.store.dir, this.processAbort.signal,
|
|
1698
|
+
this.worker = this.executeProcess(job, command, job.cwd, 30 * 60 * 1e3, this.store.dir, this.processAbort.signal, path4.dirname(this.store.dir)).then(
|
|
1699
|
+
() => this.finish(job.id),
|
|
1700
|
+
(error) => this.finish(
|
|
1701
|
+
job.id,
|
|
1702
|
+
String(error),
|
|
1703
|
+
error?.aborted === true,
|
|
1704
|
+
error?.retryable === true
|
|
1705
|
+
)
|
|
1706
|
+
).catch(() => {
|
|
1361
1707
|
try {
|
|
1362
1708
|
this.markUnsafe();
|
|
1363
1709
|
} catch {
|
|
@@ -1418,20 +1764,21 @@ ${job.prompt}`;
|
|
|
1418
1764
|
for (const [id, entry] of this.completions) {
|
|
1419
1765
|
const job = state.jobs.find((item) => item.id === id);
|
|
1420
1766
|
if (job?.state === "running") {
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
}
|
|
1767
|
+
settleJob(state, job, entry.error, Date.now(), {
|
|
1768
|
+
interrupted: entry.cancelled === true && entry.error !== void 0 && isProcessJob(job) && job.target === "worker",
|
|
1769
|
+
retryable: entry.retryable === true && entry.error !== void 0 && isProcessJob(job) && job.target === "worker"
|
|
1770
|
+
});
|
|
1426
1771
|
}
|
|
1427
1772
|
}
|
|
1428
1773
|
delete state.owners[this.id];
|
|
1429
|
-
for (const job of state.jobs) {
|
|
1430
|
-
if (job.state === "running" && job.target === this.id)
|
|
1774
|
+
for (const job of [...state.jobs]) {
|
|
1775
|
+
if (job.state === "running" && job.target === this.id) {
|
|
1776
|
+
settleJob(state, job, "owner closed before delivery; inspect before resuming");
|
|
1777
|
+
}
|
|
1431
1778
|
}
|
|
1432
1779
|
});
|
|
1433
1780
|
try {
|
|
1434
|
-
|
|
1781
|
+
fs4.rmSync(path4.join(this.store.dir, "owners-liveness", `${this.id}.json`), { force: true });
|
|
1435
1782
|
} catch {
|
|
1436
1783
|
}
|
|
1437
1784
|
this.completions.clear();
|
|
@@ -1480,33 +1827,278 @@ ${job.prompt}`;
|
|
|
1480
1827
|
}
|
|
1481
1828
|
};
|
|
1482
1829
|
|
|
1483
|
-
// builtin/extensions/cron/
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1830
|
+
// builtin/extensions/cron/panel-bridge.ts
|
|
1831
|
+
import * as fs5 from "node:fs";
|
|
1832
|
+
import * as path5 from "node:path";
|
|
1833
|
+
var SAFE_WORKER_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,47}$/;
|
|
1834
|
+
var SAFE_JOB_ID = /^[A-Za-z0-9-]{8,64}$/;
|
|
1835
|
+
function isContainedNonSymlink(rootDir, targetPath, kind) {
|
|
1836
|
+
try {
|
|
1837
|
+
if (!fs5.existsSync(rootDir) || !fs5.existsSync(targetPath)) return false;
|
|
1838
|
+
const st = fs5.lstatSync(targetPath);
|
|
1839
|
+
if (st.isSymbolicLink()) return false;
|
|
1840
|
+
if (kind === "dir" ? !st.isDirectory() : !st.isFile()) return false;
|
|
1841
|
+
const canonicalRoot = fs5.realpathSync(rootDir);
|
|
1842
|
+
const canonicalTarget = fs5.realpathSync(targetPath);
|
|
1843
|
+
const rel = path5.relative(canonicalRoot, canonicalTarget);
|
|
1844
|
+
return Boolean(rel && !rel.startsWith("..") && !path5.isAbsolute(rel));
|
|
1845
|
+
} catch {
|
|
1846
|
+
return false;
|
|
1847
|
+
}
|
|
1487
1848
|
}
|
|
1488
|
-
function
|
|
1489
|
-
|
|
1490
|
-
if (
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
const local = /* @__PURE__ */ new Date();
|
|
1494
|
-
local.setHours(hour, minute, 0, 0);
|
|
1495
|
-
const utcHour = local.getUTCHours(), utcMinute = local.getUTCMinutes();
|
|
1496
|
-
return { cron: `${utcMinute} ${utcHour} * * *` };
|
|
1849
|
+
function formatEverySeconds(seconds) {
|
|
1850
|
+
if (seconds % 86400 === 0) return `${seconds / 86400}d`;
|
|
1851
|
+
if (seconds % 3600 === 0) return `${seconds / 3600}h`;
|
|
1852
|
+
if (seconds % 60 === 0) return `${seconds / 60}m`;
|
|
1853
|
+
return `${seconds}s`;
|
|
1497
1854
|
}
|
|
1498
|
-
function
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1855
|
+
function summarizeSchedule(schedule) {
|
|
1856
|
+
if ("at" in schedule) {
|
|
1857
|
+
return { kind: "at", text: `at ${schedule.at}` };
|
|
1858
|
+
}
|
|
1859
|
+
if ("every" in schedule) {
|
|
1860
|
+
return {
|
|
1861
|
+
kind: "every",
|
|
1862
|
+
text: `every ${formatEverySeconds(schedule.every)}`,
|
|
1863
|
+
...schedule.count !== void 0 ? { count: schedule.count } : {}
|
|
1864
|
+
};
|
|
1507
1865
|
}
|
|
1508
|
-
return
|
|
1866
|
+
return {
|
|
1867
|
+
kind: "cron",
|
|
1868
|
+
text: `cron ${schedule.cron}`,
|
|
1869
|
+
...schedule.count !== void 0 ? { count: schedule.count } : {}
|
|
1870
|
+
};
|
|
1871
|
+
}
|
|
1872
|
+
function toJobView(job, storeKey, storeOwnerLabel) {
|
|
1873
|
+
const processCmd = parseProcessCommand(job);
|
|
1874
|
+
const isProc = isProcessJob(job);
|
|
1875
|
+
const managedBy = processCmd?.managedBy;
|
|
1876
|
+
const summary = managedBy ? managedBy : isProc ? processCmd?.command.slice(0, 3).join(" ") ?? "process" : job.prompt.replace(/\s+/g, " ").trim().slice(0, 80);
|
|
1877
|
+
const ownerLabel = storeOwnerLabel ?? (isProc ? "system" : void 0);
|
|
1878
|
+
return {
|
|
1879
|
+
id: job.id,
|
|
1880
|
+
storeKey,
|
|
1881
|
+
...ownerLabel ? { ownerLabel } : {},
|
|
1882
|
+
sessionId: job.sessionId,
|
|
1883
|
+
cwd: job.cwd,
|
|
1884
|
+
isProcess: isProc,
|
|
1885
|
+
...managedBy ? { managedBy } : {},
|
|
1886
|
+
summary,
|
|
1887
|
+
schedule: summarizeSchedule(job.schedule),
|
|
1888
|
+
enabled: job.enabled,
|
|
1889
|
+
state: job.state,
|
|
1890
|
+
next: job.next,
|
|
1891
|
+
...job.remaining !== void 0 ? { remaining: job.remaining } : {},
|
|
1892
|
+
...job.pendingAction ? { pendingAction: job.pendingAction } : {},
|
|
1893
|
+
...typeof job.error === "string" && job.error ? { error: job.error.slice(0, 200) } : {}
|
|
1894
|
+
};
|
|
1895
|
+
}
|
|
1896
|
+
function stateSortRank(job) {
|
|
1897
|
+
if (job.state === "running") return 0;
|
|
1898
|
+
if (job.state === "blocked") return 1;
|
|
1899
|
+
if (job.enabled) return 2;
|
|
1900
|
+
return 3;
|
|
1901
|
+
}
|
|
1902
|
+
function sortJobs(jobs) {
|
|
1903
|
+
return jobs.sort((a, b) => {
|
|
1904
|
+
if (a.isProcess !== b.isProcess) return a.isProcess ? 1 : -1;
|
|
1905
|
+
const rankDiff = stateSortRank(a) - stateSortRank(b);
|
|
1906
|
+
if (rankDiff !== 0) return rankDiff;
|
|
1907
|
+
const aNext = a.next ?? Number.MAX_SAFE_INTEGER;
|
|
1908
|
+
const bNext = b.next ?? Number.MAX_SAFE_INTEGER;
|
|
1909
|
+
if (aNext !== bNext) return aNext - bNext;
|
|
1910
|
+
return a.id.localeCompare(b.id);
|
|
1911
|
+
});
|
|
1912
|
+
}
|
|
1913
|
+
function pinContainedDir(parentDir, targetDir) {
|
|
1914
|
+
if (!isContainedNonSymlink(parentDir, targetDir, "dir")) return void 0;
|
|
1915
|
+
try {
|
|
1916
|
+
const st = fs5.lstatSync(targetDir, { bigint: true });
|
|
1917
|
+
if (st.isSymbolicLink() || !st.isDirectory()) return void 0;
|
|
1918
|
+
return { path: targetDir, dev: st.dev, ino: st.ino };
|
|
1919
|
+
} catch {
|
|
1920
|
+
return void 0;
|
|
1921
|
+
}
|
|
1922
|
+
}
|
|
1923
|
+
function assertPinnedChain(configRoot, chain) {
|
|
1924
|
+
let parent = configRoot;
|
|
1925
|
+
for (const node of chain) {
|
|
1926
|
+
if (!isContainedNonSymlink(parent, node.path, "dir")) {
|
|
1927
|
+
throw new Error("worker cron store containment check failed");
|
|
1928
|
+
}
|
|
1929
|
+
const st = fs5.lstatSync(node.path, { bigint: true });
|
|
1930
|
+
if (st.isSymbolicLink() || !st.isDirectory() || st.dev !== node.dev || st.ino !== node.ino) {
|
|
1931
|
+
throw new Error("worker cron store directory identity changed");
|
|
1932
|
+
}
|
|
1933
|
+
parent = node.path;
|
|
1934
|
+
}
|
|
1935
|
+
}
|
|
1936
|
+
function resolveVerifiedAgentsDir(configRoot) {
|
|
1937
|
+
const pieProcDir = path5.join(configRoot, "pie-proc");
|
|
1938
|
+
const pinnedPieProc = pinContainedDir(configRoot, pieProcDir);
|
|
1939
|
+
if (!pinnedPieProc) return void 0;
|
|
1940
|
+
const agentsDir = path5.join(pieProcDir, "agents");
|
|
1941
|
+
const pinnedAgents = pinContainedDir(pieProcDir, agentsDir);
|
|
1942
|
+
if (!pinnedAgents) return void 0;
|
|
1943
|
+
return { agentsDir, prefixChain: [pinnedPieProc, pinnedAgents] };
|
|
1944
|
+
}
|
|
1945
|
+
function resolveVerifiedWorkerStore(configRoot, resolvedAgents, name) {
|
|
1946
|
+
if (!SAFE_WORKER_NAME.test(name)) return void 0;
|
|
1947
|
+
const agentDir = path5.join(resolvedAgents.agentsDir, name);
|
|
1948
|
+
const pinnedAgent = pinContainedDir(resolvedAgents.agentsDir, agentDir);
|
|
1949
|
+
if (!pinnedAgent) return void 0;
|
|
1950
|
+
const cronDir = path5.join(agentDir, "cron");
|
|
1951
|
+
const pinnedCron = pinContainedDir(agentDir, cronDir);
|
|
1952
|
+
if (!pinnedCron) return void 0;
|
|
1953
|
+
const stateFile = path5.join(cronDir, "state.json");
|
|
1954
|
+
if (!isContainedNonSymlink(cronDir, stateFile, "file")) return void 0;
|
|
1955
|
+
const fullChain = [...resolvedAgents.prefixChain, pinnedAgent, pinnedCron];
|
|
1956
|
+
return {
|
|
1957
|
+
storeKey: `worker:${name}`,
|
|
1958
|
+
ownerLabel: name,
|
|
1959
|
+
store: new Store(cronDir, {
|
|
1960
|
+
createDir: false,
|
|
1961
|
+
verifyDir: () => assertPinnedChain(configRoot, fullChain)
|
|
1962
|
+
})
|
|
1963
|
+
};
|
|
1964
|
+
}
|
|
1965
|
+
function enumerateVerifiedStores(primaryStore, configRoot) {
|
|
1966
|
+
const stores = [{ storeKey: "host", store: primaryStore }];
|
|
1967
|
+
const resolvedAgents = resolveVerifiedAgentsDir(configRoot);
|
|
1968
|
+
if (!resolvedAgents) return stores;
|
|
1969
|
+
let entries;
|
|
1970
|
+
try {
|
|
1971
|
+
entries = fs5.readdirSync(resolvedAgents.agentsDir).sort();
|
|
1972
|
+
} catch {
|
|
1973
|
+
return stores;
|
|
1974
|
+
}
|
|
1975
|
+
for (const name of entries) {
|
|
1976
|
+
const verified = resolveVerifiedWorkerStore(configRoot, resolvedAgents, name);
|
|
1977
|
+
if (verified) stores.push(verified);
|
|
1978
|
+
}
|
|
1979
|
+
return stores;
|
|
1980
|
+
}
|
|
1981
|
+
function resolveStoresForKey(primaryStore, configRoot, storeKey) {
|
|
1982
|
+
if (!storeKey) return enumerateVerifiedStores(primaryStore, configRoot);
|
|
1983
|
+
if (storeKey === "host") return [{ storeKey: "host", store: primaryStore }];
|
|
1984
|
+
if (storeKey.startsWith("worker:")) {
|
|
1985
|
+
const resolvedAgents = resolveVerifiedAgentsDir(configRoot);
|
|
1986
|
+
if (!resolvedAgents) return [];
|
|
1987
|
+
const verified = resolveVerifiedWorkerStore(configRoot, resolvedAgents, storeKey.slice("worker:".length));
|
|
1988
|
+
return verified ? [verified] : [];
|
|
1989
|
+
}
|
|
1990
|
+
return [];
|
|
1991
|
+
}
|
|
1992
|
+
function createCronPanelBridge(params) {
|
|
1993
|
+
const { primaryStore, configRoot, getAuthorization, getStartupError } = params;
|
|
1994
|
+
return {
|
|
1995
|
+
listJobs(opts) {
|
|
1996
|
+
const stores = enumerateVerifiedStores(primaryStore, configRoot);
|
|
1997
|
+
const jobs = [];
|
|
1998
|
+
const warnings = [];
|
|
1999
|
+
let hostJobMatched = false;
|
|
2000
|
+
for (const entry of stores) {
|
|
2001
|
+
try {
|
|
2002
|
+
const state = entry.store.read();
|
|
2003
|
+
let invalidIdCount = 0;
|
|
2004
|
+
for (const job of state.jobs) {
|
|
2005
|
+
if (opts?.sessionId && job.sessionId !== opts.sessionId) continue;
|
|
2006
|
+
if (!SAFE_JOB_ID.test(job.id)) {
|
|
2007
|
+
invalidIdCount++;
|
|
2008
|
+
continue;
|
|
2009
|
+
}
|
|
2010
|
+
if (entry.storeKey === "host") hostJobMatched = true;
|
|
2011
|
+
jobs.push(toJobView(job, entry.storeKey, entry.ownerLabel));
|
|
2012
|
+
}
|
|
2013
|
+
if (invalidIdCount > 0) {
|
|
2014
|
+
warnings.push(`${entry.storeKey}: skipped ${invalidIdCount} job(s) with invalid id`);
|
|
2015
|
+
}
|
|
2016
|
+
} catch (error) {
|
|
2017
|
+
warnings.push(`${entry.storeKey}: ${error instanceof Error ? error.message : String(error)}`);
|
|
2018
|
+
}
|
|
2019
|
+
}
|
|
2020
|
+
const hostStartupErr = getStartupError?.();
|
|
2021
|
+
if (hostStartupErr && (!opts?.sessionId || hostJobMatched)) {
|
|
2022
|
+
warnings.push(`host: cron unavailable (${hostStartupErr}); see docs/cron.md recovery`);
|
|
2023
|
+
}
|
|
2024
|
+
return {
|
|
2025
|
+
jobs: sortJobs(jobs),
|
|
2026
|
+
...warnings.length > 0 ? { warnings } : {}
|
|
2027
|
+
};
|
|
2028
|
+
},
|
|
2029
|
+
mutateJob(jobId, action, opts) {
|
|
2030
|
+
if (!SAFE_JOB_ID.test(jobId)) {
|
|
2031
|
+
return { ok: false, detail: "invalid job id" };
|
|
2032
|
+
}
|
|
2033
|
+
const stores = resolveStoresForKey(primaryStore, configRoot, opts?.storeKey);
|
|
2034
|
+
const candidates = [];
|
|
2035
|
+
for (const entry2 of stores) {
|
|
2036
|
+
try {
|
|
2037
|
+
const found = entry2.store.read().jobs.find((j) => j.id === jobId);
|
|
2038
|
+
if (found) candidates.push({ entry: entry2, job: found });
|
|
2039
|
+
} catch {
|
|
2040
|
+
}
|
|
2041
|
+
}
|
|
2042
|
+
if (candidates.length === 0) {
|
|
2043
|
+
return { ok: false, detail: "unknown job (already removed or not found)" };
|
|
2044
|
+
}
|
|
2045
|
+
if (candidates.length > 1) {
|
|
2046
|
+
return { ok: false, detail: "ambiguous job id across multiple stores" };
|
|
2047
|
+
}
|
|
2048
|
+
const { entry, job: before } = candidates[0];
|
|
2049
|
+
if (opts?.sessionId && before.sessionId !== opts.sessionId) {
|
|
2050
|
+
return { ok: false, detail: "job does not belong to target worker session" };
|
|
2051
|
+
}
|
|
2052
|
+
const beforeView = toJobView(before, entry.storeKey, entry.ownerLabel);
|
|
2053
|
+
if (entry.storeKey === "host") {
|
|
2054
|
+
const hostStartupErr = getStartupError?.();
|
|
2055
|
+
if (hostStartupErr) {
|
|
2056
|
+
return {
|
|
2057
|
+
ok: false,
|
|
2058
|
+
detail: `cron unavailable: ${hostStartupErr}; see docs/cron.md recovery`,
|
|
2059
|
+
job: beforeView
|
|
2060
|
+
};
|
|
2061
|
+
}
|
|
2062
|
+
}
|
|
2063
|
+
const authorization = getAuthorization();
|
|
2064
|
+
const actor = opts?.senderId ? `im-panel:${opts.senderId}` : "im-panel";
|
|
2065
|
+
try {
|
|
2066
|
+
const outcome = entry.store.change(jobId, action, Date.now(), {
|
|
2067
|
+
...action === "resume" ? { authorization } : {},
|
|
2068
|
+
...opts?.sessionId ? { expectedSessionId: opts.sessionId } : {},
|
|
2069
|
+
...action === "remove" ? { disableManagedOnRemove: true } : {}
|
|
2070
|
+
});
|
|
2071
|
+
const after = entry.store.read().jobs.find((j) => j.id === jobId);
|
|
2072
|
+
const afterView = after ? toJobView(after, entry.storeKey, entry.ownerLabel) : beforeView;
|
|
2073
|
+
try {
|
|
2074
|
+
entry.store.audit({
|
|
2075
|
+
kind: action,
|
|
2076
|
+
jobId,
|
|
2077
|
+
sessionId: before.sessionId,
|
|
2078
|
+
cwd: before.cwd,
|
|
2079
|
+
authorization,
|
|
2080
|
+
detail: outcome === "deferred" ? `${actor} (deferred until running occurrence settles)` : actor
|
|
2081
|
+
});
|
|
2082
|
+
} catch {
|
|
2083
|
+
}
|
|
2084
|
+
return {
|
|
2085
|
+
ok: true,
|
|
2086
|
+
outcome,
|
|
2087
|
+
detail: outcome === "deferred" ? `${action} queued until current run finishes` : `${action} applied`,
|
|
2088
|
+
job: afterView
|
|
2089
|
+
};
|
|
2090
|
+
} catch (error) {
|
|
2091
|
+
return {
|
|
2092
|
+
ok: false,
|
|
2093
|
+
detail: error instanceof Error ? error.message : String(error),
|
|
2094
|
+
job: beforeView
|
|
2095
|
+
};
|
|
2096
|
+
}
|
|
2097
|
+
}
|
|
2098
|
+
};
|
|
1509
2099
|
}
|
|
2100
|
+
|
|
2101
|
+
// builtin/extensions/cron/index.ts
|
|
1510
2102
|
function cron(ctx) {
|
|
1511
2103
|
if (process.env.PIE_CRON_ROLE === "worker") return;
|
|
1512
2104
|
const capabilities = ctx.capabilities;
|
|
@@ -1522,16 +2114,26 @@ function cron(ctx) {
|
|
|
1522
2114
|
WARNING: change applied but the audit log could not be written (${String(e)})`;
|
|
1523
2115
|
}
|
|
1524
2116
|
};
|
|
1525
|
-
const
|
|
2117
|
+
const configRoot = configPath();
|
|
2118
|
+
const store = new Store(path6.join(configRoot, "cron"));
|
|
1526
2119
|
const runtime = new Runtime(ctx, store);
|
|
1527
|
-
ctx.log(`cron: starting (store=${
|
|
2120
|
+
ctx.log(`cron: starting (store=${path6.join(configRoot, "cron")})`);
|
|
1528
2121
|
let startupError;
|
|
1529
2122
|
try {
|
|
1530
2123
|
runtime.start();
|
|
1531
2124
|
} catch (e) {
|
|
1532
2125
|
startupError = String(e);
|
|
1533
2126
|
}
|
|
1534
|
-
|
|
2127
|
+
const unregisterPanelBridge = registerCronPanelBridge(createCronPanelBridge({
|
|
2128
|
+
primaryStore: store,
|
|
2129
|
+
configRoot,
|
|
2130
|
+
getAuthorization: authorizationNow,
|
|
2131
|
+
getStartupError: () => startupError
|
|
2132
|
+
}));
|
|
2133
|
+
ctx.registerCleanup?.(() => {
|
|
2134
|
+
unregisterPanelBridge();
|
|
2135
|
+
return runtime.stop();
|
|
2136
|
+
});
|
|
1535
2137
|
ctx.on("agent:start", () => runtime.onStart());
|
|
1536
2138
|
ctx.on("message:end", (e) => runtime.onMessage(e.message));
|
|
1537
2139
|
ctx.on("turn:failed", () => runtime.onFailure());
|
|
@@ -1545,14 +2147,14 @@ WARNING: change applied but the audit log could not be written (${String(e)})`;
|
|
|
1545
2147
|
}
|
|
1546
2148
|
});
|
|
1547
2149
|
ctx.on("terminal:input", (e) => {
|
|
1548
|
-
if (/^\/tools\/cron(?:\s|$)/.test(e.text)) return;
|
|
2150
|
+
if (/^\/(?:tools\/cron(?:\/|\s|$)|cron(?:\s|$))/.test(e.text)) return;
|
|
1549
2151
|
let unsafe = false, duplicates = false, worker = false;
|
|
1550
2152
|
try {
|
|
1551
2153
|
const state = store.read();
|
|
1552
2154
|
if (!state.jobs.some((j) => j.sessionId === runtime.sessionId && (j.enabled || j.state === "running"))) return;
|
|
1553
2155
|
duplicates = Object.values(state.owners).filter((o) => o.sessionId === runtime.sessionId).length > 1;
|
|
1554
2156
|
worker = state.jobs.some((j) => j.sessionId === runtime.sessionId && j.state === "running" && j.target === "worker");
|
|
1555
|
-
unsafe =
|
|
2157
|
+
unsafe = fs6.existsSync(path6.join(store.dir, "unsafe.lock"));
|
|
1556
2158
|
if (!startupError && runtime.ready && !duplicates && !worker && !unsafe) return;
|
|
1557
2159
|
} catch {
|
|
1558
2160
|
}
|
|
@@ -1574,25 +2176,37 @@ WARNING: change applied but the audit log could not be written (${String(e)})`;
|
|
|
1574
2176
|
return { cancel: true };
|
|
1575
2177
|
}
|
|
1576
2178
|
});
|
|
2179
|
+
const blockedReviewInfo = (j, now) => {
|
|
2180
|
+
const exhausted = j.remaining !== void 0 && j.remaining <= 0;
|
|
2181
|
+
const invalidOccurrence = j.occurrence !== void 0 && !Number.isSafeInteger(j.occurrence);
|
|
2182
|
+
const oneShotExpired = !invalidOccurrence && nextTime(j.schedule, Math.max(now, j.occurrence ?? now)) === null;
|
|
2183
|
+
const canResume = !exhausted && !invalidOccurrence && !oneShotExpired;
|
|
2184
|
+
const executionTrail = isProcessJob(j) ? `${store.dir}/process.log (if a run started)` : `${store.dir}/audit.log (if any audit event fired)`;
|
|
2185
|
+
const lastOccurrence = j.occurrence ? new Date(j.occurrence).toISOString() : "(none)";
|
|
2186
|
+
const error = j.error ?? "(no error recorded)";
|
|
2187
|
+
const resolution = exhausted ? "execution count exhausted: remove (and optionally recreate) \u2014 resume is impossible" : invalidOccurrence ? "invalid job occurrence: manual recovery required before resume" : oneShotExpired ? 'one-shot expired: cron_manage {action:"remove", id} (then optionally re-create); resume is impossible for a past `at`' : 'cron_manage {action:"resume"|"remove", id} \u2014 inspect the trail first';
|
|
2188
|
+
return { id: j.id, error, lastOccurrence, executionTrail, cwd: j.cwd, resolution, canResume, exhausted, oneShotExpired, invalidOccurrence };
|
|
2189
|
+
};
|
|
1577
2190
|
const run = (action, id, prompt, schedule) => {
|
|
1578
2191
|
if (startupError && action !== "list") throw new Error(`cron unavailable: ${startupError}; see docs/cron.md recovery`);
|
|
1579
2192
|
if (action === "list") {
|
|
1580
2193
|
const state = store.read();
|
|
2194
|
+
const now = Date.now();
|
|
1581
2195
|
const blocked = state.jobs.filter((j) => j.state === "blocked").map((j) => {
|
|
1582
|
-
const
|
|
2196
|
+
const info = blockedReviewInfo(j, now);
|
|
1583
2197
|
return {
|
|
1584
|
-
id:
|
|
1585
|
-
error:
|
|
1586
|
-
lastOccurrence:
|
|
1587
|
-
executionTrail:
|
|
1588
|
-
cwd:
|
|
1589
|
-
resolution:
|
|
2198
|
+
id: info.id,
|
|
2199
|
+
error: info.error,
|
|
2200
|
+
lastOccurrence: info.lastOccurrence,
|
|
2201
|
+
executionTrail: info.executionTrail,
|
|
2202
|
+
cwd: info.cwd,
|
|
2203
|
+
resolution: info.resolution
|
|
1590
2204
|
};
|
|
1591
2205
|
});
|
|
1592
2206
|
return JSON.stringify({
|
|
1593
2207
|
...state,
|
|
1594
|
-
recoveryRequired:
|
|
1595
|
-
coordinatorPresent:
|
|
2208
|
+
recoveryRequired: fs6.existsSync(path6.join(store.dir, "unsafe.lock")),
|
|
2209
|
+
coordinatorPresent: fs6.existsSync(path6.join(store.dir, "scheduler.lock")),
|
|
1596
2210
|
...blocked.length > 0 ? { blockedReview: blocked } : {}
|
|
1597
2211
|
}, null, 2);
|
|
1598
2212
|
}
|
|
@@ -1603,21 +2217,17 @@ WARNING: change applied but the audit log could not be written (${String(e)})`;
|
|
|
1603
2217
|
const note = auditNote({ kind: "add", jobId: job.id, sessionId: job.sessionId, cwd: job.cwd, authorization });
|
|
1604
2218
|
return JSON.stringify({
|
|
1605
2219
|
job,
|
|
1606
|
-
note: "Saved. every/cron schedules repeat until removed unless count limits total executions. Delivery resumes THIS session and each delivered turn runs the prompt once; a running
|
|
2220
|
+
note: "Saved. every/cron schedules repeat until removed unless count limits total executions. Delivery resumes THIS session and each delivered turn runs the prompt once; pause/remove requested while a delivery is running is queued and applied automatically as soon as the turn settles. Keep at least one cron-enabled Pie open; no execution while all are closed or the computer sleeps." + note
|
|
1607
2221
|
});
|
|
1608
2222
|
}
|
|
1609
2223
|
if (action === "pause" || action === "resume" || action === "remove") {
|
|
1610
2224
|
const jobId = id ?? "";
|
|
1611
2225
|
const authorization = authorizationNow();
|
|
1612
|
-
|
|
1613
|
-
|
|
1614
|
-
|
|
1615
|
-
|
|
1616
|
-
|
|
1617
|
-
store.change(jobId, action);
|
|
1618
|
-
const job = store.read().jobs.find((j) => j.id === jobId);
|
|
1619
|
-
const note = auditNote({ kind: action, jobId, sessionId: job?.sessionId, cwd: job?.cwd, authorization });
|
|
1620
|
-
return `${action}: ${jobId}${note}`;
|
|
2226
|
+
const before = store.read().jobs.find((j) => j.id === jobId);
|
|
2227
|
+
const outcome = store.change(jobId, action, Date.now(), action === "resume" ? { authorization } : void 0);
|
|
2228
|
+
const job = store.read().jobs.find((j) => j.id === jobId) ?? before;
|
|
2229
|
+
const note = auditNote({ kind: action, jobId, sessionId: job?.sessionId, cwd: job?.cwd, authorization, ...outcome === "deferred" ? { detail: "deferred until running occurrence settles" } : {} });
|
|
2230
|
+
return outcome === "deferred" ? `${action} (deferred until current run settles): ${jobId}${note}` : `${action}: ${jobId}${note}`;
|
|
1621
2231
|
}
|
|
1622
2232
|
if (action === "reap-owners") {
|
|
1623
2233
|
const warnings = [];
|
|
@@ -1627,20 +2237,158 @@ WARNING: change applied but the audit log could not be written (${String(e)})`;
|
|
|
1627
2237
|
}
|
|
1628
2238
|
throw new Error('Usage: /tools/cron list | reap-owners | add {"prompt":"...","schedule":{"every":3600}} | pause|resume|remove <id>');
|
|
1629
2239
|
};
|
|
1630
|
-
|
|
2240
|
+
const formatScheduleLabel = (schedule) => "every" in schedule ? `every ${schedule.every}s${schedule.count ? ` (x${schedule.count})` : ""}` : "cron" in schedule ? `cron "${schedule.cron}"${schedule.count ? ` (x${schedule.count})` : ""}` : `at ${schedule.at}`;
|
|
2241
|
+
const runCommandAction = (action, rest) => {
|
|
1631
2242
|
try {
|
|
1632
|
-
const match = (args ?? "").trim().match(/^(\S+)(?:\s+([\s\S]*))?$/);
|
|
1633
|
-
const action = match?.[1] ?? "list", rest = match?.[2];
|
|
1634
2243
|
const data = action === "add" ? JSON.parse(rest ?? "{}") : void 0;
|
|
1635
2244
|
ctx.ui.notify(run(action, rest, data?.prompt, data?.schedule), "info");
|
|
1636
2245
|
} catch (e) {
|
|
1637
2246
|
ctx.ui.notify(String(e), "warning");
|
|
1638
2247
|
}
|
|
2248
|
+
};
|
|
2249
|
+
const openInteractiveMenu = async (commandCtx) => {
|
|
2250
|
+
const select = commandCtx.ui?.select;
|
|
2251
|
+
if (!commandCtx.hasUI || !select) {
|
|
2252
|
+
runCommandAction("list");
|
|
2253
|
+
return;
|
|
2254
|
+
}
|
|
2255
|
+
let jobs = [];
|
|
2256
|
+
try {
|
|
2257
|
+
jobs = store.read().jobs;
|
|
2258
|
+
} catch (e) {
|
|
2259
|
+
commandCtx.ui.notify(String(e), "warning");
|
|
2260
|
+
return;
|
|
2261
|
+
}
|
|
2262
|
+
const visibleJobs = jobs.slice(0, 20);
|
|
2263
|
+
const jobRows = visibleJobs.map((job) => {
|
|
2264
|
+
const status = job.state === "running" ? "running" : job.state === "blocked" ? "blocked" : job.enabled ? "on" : "paused";
|
|
2265
|
+
const rawSummary = isProcessJob(job) ? `[process:${parseProcessCommand(job)?.managedBy ?? "managed"}]` : job.prompt.replace(/\s+/g, " ").trim();
|
|
2266
|
+
const summary = rawSummary.length > 48 ? `${rawSummary.slice(0, 47)}\u2026` : rawSummary;
|
|
2267
|
+
return {
|
|
2268
|
+
jobId: job.id,
|
|
2269
|
+
label: `[${status}] ${job.id} \xB7 ${formatScheduleLabel(job.schedule)} \xB7 ${summary}`
|
|
2270
|
+
};
|
|
2271
|
+
});
|
|
2272
|
+
const LIST_OPT = "List jobs (JSON)";
|
|
2273
|
+
const REAP_OPT = "Reap stale owners";
|
|
2274
|
+
const menuTitle = jobs.length > visibleJobs.length ? `Cron jobs (showing ${visibleJobs.length} of ${jobs.length}; use "${LIST_OPT}" for all)` : "Cron jobs";
|
|
2275
|
+
const choice = await select(menuTitle, [...jobRows.map((r) => r.label), LIST_OPT, REAP_OPT]);
|
|
2276
|
+
if (!choice) return;
|
|
2277
|
+
if (choice === LIST_OPT) {
|
|
2278
|
+
runCommandAction("list");
|
|
2279
|
+
return;
|
|
2280
|
+
}
|
|
2281
|
+
if (choice === REAP_OPT) {
|
|
2282
|
+
runCommandAction("reap-owners");
|
|
2283
|
+
return;
|
|
2284
|
+
}
|
|
2285
|
+
const pickedId = jobRows.find((r) => r.label === choice)?.jobId;
|
|
2286
|
+
if (!pickedId) return;
|
|
2287
|
+
let latest;
|
|
2288
|
+
try {
|
|
2289
|
+
latest = store.read().jobs.find((j) => j.id === pickedId);
|
|
2290
|
+
} catch (e) {
|
|
2291
|
+
commandCtx.ui.notify(String(e), "warning");
|
|
2292
|
+
return;
|
|
2293
|
+
}
|
|
2294
|
+
if (!latest) {
|
|
2295
|
+
commandCtx.ui.notify(`Cron job ${pickedId} no longer exists.`, "info");
|
|
2296
|
+
return;
|
|
2297
|
+
}
|
|
2298
|
+
const RESUME_REVIEW_OPT = "Resume (after reviewing trail)";
|
|
2299
|
+
let actions;
|
|
2300
|
+
let actionTitle = `Cron job ${latest.id}`;
|
|
2301
|
+
if (latest.state === "blocked") {
|
|
2302
|
+
const review = blockedReviewInfo(latest, Date.now());
|
|
2303
|
+
commandCtx.ui.notify(
|
|
2304
|
+
`Blocked cron job ${review.id}
|
|
2305
|
+
error: ${review.error}
|
|
2306
|
+
lastOccurrence: ${review.lastOccurrence}
|
|
2307
|
+
trail: ${review.executionTrail}
|
|
2308
|
+
resolution: ${review.resolution}`,
|
|
2309
|
+
"warning"
|
|
2310
|
+
);
|
|
2311
|
+
actions = review.canResume ? [RESUME_REVIEW_OPT, "Remove"] : ["Remove"];
|
|
2312
|
+
actionTitle = review.canResume ? `Blocked cron job ${latest.id} \u2014 inspect trail before resuming` : `Blocked cron job ${latest.id} (cannot resume: ${review.exhausted ? "count exhausted" : review.oneShotExpired ? "one-shot expired" : "manual recovery required"})`;
|
|
2313
|
+
} else if (latest.enabled) {
|
|
2314
|
+
actions = ["Pause", "Remove"];
|
|
2315
|
+
} else {
|
|
2316
|
+
const review = blockedReviewInfo(latest, Date.now());
|
|
2317
|
+
actions = review.canResume ? ["Resume", "Remove"] : ["Remove"];
|
|
2318
|
+
}
|
|
2319
|
+
const actionChoice = await select(actionTitle, actions);
|
|
2320
|
+
if (!actionChoice) return;
|
|
2321
|
+
let current;
|
|
2322
|
+
try {
|
|
2323
|
+
current = store.read().jobs.find((j) => j.id === pickedId);
|
|
2324
|
+
} catch (e) {
|
|
2325
|
+
commandCtx.ui.notify(String(e), "warning");
|
|
2326
|
+
return;
|
|
2327
|
+
}
|
|
2328
|
+
if (!current) {
|
|
2329
|
+
commandCtx.ui.notify(`Cron job ${pickedId} no longer exists.`, "info");
|
|
2330
|
+
return;
|
|
2331
|
+
}
|
|
2332
|
+
if (actionChoice === "Remove") {
|
|
2333
|
+
const ok = await commandCtx.ui.confirm("Remove cron job", `Remove scheduled job ${current.id}?`);
|
|
2334
|
+
if (!ok) return;
|
|
2335
|
+
runCommandAction("remove", current.id);
|
|
2336
|
+
return;
|
|
2337
|
+
}
|
|
2338
|
+
if (actionChoice === "Pause") {
|
|
2339
|
+
runCommandAction("pause", current.id);
|
|
2340
|
+
return;
|
|
2341
|
+
}
|
|
2342
|
+
if (actionChoice === "Resume" || actionChoice === RESUME_REVIEW_OPT) {
|
|
2343
|
+
const freshReview = blockedReviewInfo(current, Date.now());
|
|
2344
|
+
if (!freshReview.canResume) {
|
|
2345
|
+
commandCtx.ui.notify(`Cannot resume ${current.id}: ${freshReview.resolution}`, "warning");
|
|
2346
|
+
return;
|
|
2347
|
+
}
|
|
2348
|
+
if (current.state === "blocked") {
|
|
2349
|
+
const ok = await commandCtx.ui.confirm(
|
|
2350
|
+
"Resume blocked cron job",
|
|
2351
|
+
`Job ${freshReview.id} is blocked after an uncertain occurrence.
|
|
2352
|
+
Error: ${freshReview.error}
|
|
2353
|
+
Last occurrence: ${freshReview.lastOccurrence}
|
|
2354
|
+
Trail: ${freshReview.executionTrail}
|
|
2355
|
+
|
|
2356
|
+
Confirm you have inspected the execution trail and want to resume scheduling from now?`
|
|
2357
|
+
);
|
|
2358
|
+
if (!ok) return;
|
|
2359
|
+
}
|
|
2360
|
+
runCommandAction("resume", current.id);
|
|
2361
|
+
}
|
|
2362
|
+
};
|
|
2363
|
+
ctx.registerCommand({ path: ["tools", "cron", "list"], description: "List cron jobs, owners, and blocked review items", handler: async () => {
|
|
2364
|
+
runCommandAction("list");
|
|
2365
|
+
} });
|
|
2366
|
+
ctx.registerCommand({ path: ["tools", "cron", "pause"], description: "Pause a cron job by id", handler: async (_ctx, args) => {
|
|
2367
|
+
runCommandAction("pause", (args ?? "").trim());
|
|
2368
|
+
} });
|
|
2369
|
+
ctx.registerCommand({ path: ["tools", "cron", "resume"], description: "Resume a paused or reviewed blocked cron job by id", handler: async (_ctx, args) => {
|
|
2370
|
+
runCommandAction("resume", (args ?? "").trim());
|
|
2371
|
+
} });
|
|
2372
|
+
ctx.registerCommand({ path: ["tools", "cron", "remove"], description: "Remove a cron job by id", handler: async (_ctx, args) => {
|
|
2373
|
+
runCommandAction("remove", (args ?? "").trim());
|
|
2374
|
+
} });
|
|
2375
|
+
ctx.registerCommand({ path: ["tools", "cron", "reap-owners"], description: "Reap provably dead/stale cron session owner rows", handler: async () => {
|
|
2376
|
+
runCommandAction("reap-owners");
|
|
2377
|
+
} });
|
|
2378
|
+
ctx.registerCommand({ path: ["tools", "cron"], description: "Cron menu & schedules (UTC): list/add/pause/resume/remove", handler: async (commandCtx, args) => {
|
|
2379
|
+
const trimmed = (args ?? "").trim();
|
|
2380
|
+
if (!trimmed) {
|
|
2381
|
+
await openInteractiveMenu(commandCtx);
|
|
2382
|
+
return;
|
|
2383
|
+
}
|
|
2384
|
+
const match = trimmed.match(/^(\S+)(?:\s+([\s\S]*))?$/);
|
|
2385
|
+
const action = match?.[1] ?? "list", rest = match?.[2];
|
|
2386
|
+
runCommandAction(action, rest);
|
|
1639
2387
|
} });
|
|
1640
2388
|
ctx.registerTool({
|
|
1641
2389
|
name: "cron_manage",
|
|
1642
2390
|
label: "Cron",
|
|
1643
|
-
description: 'Manage persistent scheduled prompts bound to THIS existing session and cwd (creation is prompt-only; sessionless process jobs are managed by their owning commands, e.g. pie memory schedule, but list/pause/resume/remove apply to every job). Actions list/add/pause/resume/remove. every is seconds (minimum 60) and REPEATS FOREVER until removed; at is one-shot; cron is five numeric UTC fields. Add optional count (integer 1..1000) to every/cron to auto-disable after that many executions \u2014 prefer {"every":60,"count":5} over manual removal for N-time notifications. Missed intervals coalesce; blocked/uncertain tasks require human review before resume. remove/pause
|
|
2391
|
+
description: 'Manage persistent scheduled prompts bound to THIS existing session and cwd (creation is prompt-only; sessionless process jobs are managed by their owning commands, e.g. pie memory schedule, but list/pause/resume/remove apply to every job). Actions list/add/pause/resume/remove. every is seconds (minimum 60) and REPEATS FOREVER until removed; at is one-shot; cron is five numeric UTC fields. Add optional count (integer 1..1000) to every/cron to auto-disable after that many executions \u2014 prefer {"every":60,"count":5} over manual removal for N-time notifications. Missed intervals coalesce; blocked/uncertain tasks require human review before resume. remove/pause on a running job (including self-removal during its own turn) are queued and applied automatically as soon as the delivered turn settles.',
|
|
1644
2392
|
parameters: Type.Object({ action: Type.Union(["list", "add", "pause", "resume", "remove"].map((s) => Type.Literal(s))), id: Type.Optional(Type.String()), prompt: Type.Optional(Type.String({ maxLength: 16e3 })), schedule: Type.Optional(Type.Union([Type.Object({ at: Type.String() }), Type.Object({ every: Type.Integer({ minimum: 60, maximum: 31536e3 }), count: Type.Optional(Type.Integer({ minimum: 1, maximum: 1e3 })) }), Type.Object({ cron: Type.String({ maxLength: 256 }), count: Type.Optional(Type.Integer({ minimum: 1, maximum: 1e3 })) })])) }),
|
|
1645
2393
|
risk: { riskClass: "external_side_effect", permissionScope: "host", availableInPlanMode: false, requiresPermission: true, externalSideEffect: true, allowedForSubagentByDefault: false, concurrencySafe: false },
|
|
1646
2394
|
execute: async (args) => {
|