@cydm/pie 4.7.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 +916 -162
- package/dist/builtin/extensions/im-forward/README.md +24 -7
- package/dist/builtin/extensions/im-forward/index.js +6823 -3683
- 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 +421 -27
- package/dist/builtin/extensions/pie-proc/README.md +7 -7
- package/dist/builtin/extensions/pie-proc/index.js +453 -97
- 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 +35 -24
- package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +391 -123
- 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-NLPMVDGG.js → cli-K7ESY3XD.js} +1437 -231
- package/dist/builtin/skills/computer-use-axi/SKILL.md +26 -8
- package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +465 -83
- package/dist/builtin/skills/computer-use-axi/computer-use-axi-runtime.js +75 -22
- 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 +1918 -1489
- package/models.schema.json +271 -0
- package/package.json +2 -2
- package/dist/builtin/skills/chrome-devtools-axi/chunk-WOGAQ4P5.js +0 -399
- package/dist/chunks/chunk-7UAUDXZW.js +0 -1425
- 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+/);
|
|
@@ -96,7 +101,12 @@ function sweepStaleOwners(state, dir, opts = {}) {
|
|
|
96
101
|
let sidecar;
|
|
97
102
|
try {
|
|
98
103
|
sidecar = fs.readFileSync(liveness, "utf8");
|
|
99
|
-
} catch {
|
|
104
|
+
} catch (error) {
|
|
105
|
+
const code = error.code;
|
|
106
|
+
if (code !== "ENOENT") {
|
|
107
|
+
opts.warn?.(`cron: keeping owner ${key}; liveness sidecar read failed (${code ?? "unknown error"})`);
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
100
110
|
}
|
|
101
111
|
if (sidecar === void 0) {
|
|
102
112
|
if (row.registeredAt === void 0 || now - row.registeredAt > legacyOrCrashWindowMs) {
|
|
@@ -124,11 +134,13 @@ function sweepStaleOwners(state, dir, opts = {}) {
|
|
|
124
134
|
return reaped;
|
|
125
135
|
}
|
|
126
136
|
var Store = class {
|
|
127
|
-
constructor(dir) {
|
|
137
|
+
constructor(dir, opts) {
|
|
128
138
|
this.dir = dir;
|
|
129
|
-
|
|
139
|
+
this.verifyDir = opts?.verifyDir;
|
|
140
|
+
if (opts?.createDir !== false) fs.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
130
141
|
}
|
|
131
142
|
dir;
|
|
143
|
+
verifyDir;
|
|
132
144
|
/** Durable, append-only audit trail for operator-visible cron decisions.
|
|
133
145
|
*
|
|
134
146
|
* Why a file and not `ctx.log`: ctx.log only prints when PIE_VERBOSE is set
|
|
@@ -141,9 +153,26 @@ var Store = class {
|
|
|
141
153
|
* failed audit write can never leave an unlogged change behind. A failure
|
|
142
154
|
* therefore refuses the mutation (fail-closed, like the rest of the store). */
|
|
143
155
|
audit(record) {
|
|
144
|
-
|
|
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 })}
|
|
145
171
|
`;
|
|
146
|
-
|
|
172
|
+
fs.writeFileSync(fd, line);
|
|
173
|
+
} finally {
|
|
174
|
+
fs.closeSync(fd);
|
|
175
|
+
}
|
|
147
176
|
}
|
|
148
177
|
/** Serialized bytes of the state currently on disk; undefined until the
|
|
149
178
|
* first save. A poll transaction that leaves the state byte-identical
|
|
@@ -166,9 +195,11 @@ var Store = class {
|
|
|
166
195
|
/** Run fn under the cross-process write mutex. Also used for coordinator
|
|
167
196
|
* election/release, which never nest a state transaction. */
|
|
168
197
|
withWriteLock(fn) {
|
|
198
|
+
this.verifyDir?.();
|
|
169
199
|
const lock = path.join(this.dir, "write.lock");
|
|
170
200
|
const token = this.acquireWriteLock(lock);
|
|
171
201
|
try {
|
|
202
|
+
this.verifyDir?.();
|
|
172
203
|
return fn();
|
|
173
204
|
} finally {
|
|
174
205
|
this.releaseWriteLock(lock, token);
|
|
@@ -200,19 +231,63 @@ var Store = class {
|
|
|
200
231
|
acquireWriteLock(lock) {
|
|
201
232
|
const token = randomUUID();
|
|
202
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
|
+
};
|
|
203
269
|
try {
|
|
270
|
+
this.verifyDir?.();
|
|
204
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;
|
|
205
276
|
try {
|
|
206
|
-
this.writeHolderEntry(candidate, token);
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
} 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");
|
|
211
281
|
}
|
|
282
|
+
holderDev = holderStat.dev;
|
|
283
|
+
holderIno = holderStat.ino;
|
|
284
|
+
} catch (error) {
|
|
285
|
+
cleanupCandidate();
|
|
212
286
|
throw error;
|
|
213
287
|
}
|
|
214
288
|
const deadline = Date.now() + 2e3;
|
|
215
289
|
for (let spin = 0; ; spin++) {
|
|
290
|
+
assertCandidateIntact();
|
|
216
291
|
try {
|
|
217
292
|
fs.renameSync(candidate, lock);
|
|
218
293
|
return token;
|
|
@@ -228,16 +303,20 @@ var Store = class {
|
|
|
228
303
|
}
|
|
229
304
|
}
|
|
230
305
|
} finally {
|
|
231
|
-
|
|
232
|
-
fs.rmSync(candidate, { recursive: true, force: true });
|
|
233
|
-
} catch {
|
|
234
|
-
}
|
|
306
|
+
cleanupCandidate();
|
|
235
307
|
}
|
|
236
308
|
}
|
|
237
309
|
writeHolderEntry(dir, token) {
|
|
238
|
-
|
|
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;
|
|
239
313
|
}
|
|
240
314
|
releaseWriteLock(lock, token) {
|
|
315
|
+
try {
|
|
316
|
+
this.verifyDir?.();
|
|
317
|
+
} catch {
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
241
320
|
try {
|
|
242
321
|
fs.unlinkSync(path.join(lock, `held.${token}`));
|
|
243
322
|
} catch {
|
|
@@ -259,6 +338,21 @@ var Store = class {
|
|
|
259
338
|
/** Remove the stale canonical lock so an install can proceed. Returns true
|
|
260
339
|
* when the canonical path is now free for a rename. */
|
|
261
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;
|
|
262
356
|
let entries;
|
|
263
357
|
try {
|
|
264
358
|
entries = fs.readdirSync(lock);
|
|
@@ -268,6 +362,7 @@ var Store = class {
|
|
|
268
362
|
const holders = entries.filter((name) => name.startsWith("held."));
|
|
269
363
|
if (holders.length === 0) {
|
|
270
364
|
if (entries.length !== 0) return false;
|
|
365
|
+
if (!verifyLockDir()) return false;
|
|
271
366
|
try {
|
|
272
367
|
fs.rmdirSync(lock);
|
|
273
368
|
return true;
|
|
@@ -278,7 +373,10 @@ var Store = class {
|
|
|
278
373
|
for (const name of holders) {
|
|
279
374
|
let pid;
|
|
280
375
|
try {
|
|
281
|
-
|
|
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);
|
|
282
380
|
if (parsed?.version !== 1 || !Number.isInteger(parsed.pid) || parsed.pid <= 0) return false;
|
|
283
381
|
pid = parsed.pid;
|
|
284
382
|
} catch {
|
|
@@ -292,6 +390,7 @@ var Store = class {
|
|
|
292
390
|
}
|
|
293
391
|
}
|
|
294
392
|
for (const name of holders) {
|
|
393
|
+
if (!verifyLockDir()) return false;
|
|
295
394
|
try {
|
|
296
395
|
fs.unlinkSync(path.join(lock, name));
|
|
297
396
|
} catch (error) {
|
|
@@ -299,6 +398,7 @@ var Store = class {
|
|
|
299
398
|
return false;
|
|
300
399
|
}
|
|
301
400
|
}
|
|
401
|
+
if (!verifyLockDir()) return false;
|
|
302
402
|
try {
|
|
303
403
|
fs.rmdirSync(lock);
|
|
304
404
|
return true;
|
|
@@ -314,7 +414,7 @@ var Store = class {
|
|
|
314
414
|
const file = path.join(this.dir, "state.json");
|
|
315
415
|
let raw;
|
|
316
416
|
try {
|
|
317
|
-
raw =
|
|
417
|
+
raw = this.readRegularText(file, 4e6);
|
|
318
418
|
} catch {
|
|
319
419
|
this.lastSavedContent = void 0;
|
|
320
420
|
return;
|
|
@@ -326,20 +426,40 @@ var Store = class {
|
|
|
326
426
|
* transaction callback can repair an invalid field value (write it back
|
|
327
427
|
* valid) instead of dead-ending the store. save() still enforces the
|
|
328
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
|
+
}
|
|
329
450
|
readForRepair() {
|
|
330
|
-
const
|
|
331
|
-
if (
|
|
332
|
-
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);
|
|
333
454
|
if (s.version !== 1 || !Array.isArray(s.jobs) || !s.owners || typeof s.owners !== "object" || Array.isArray(s.owners)) {
|
|
334
455
|
throw new Error("invalid cron state; manual recovery required");
|
|
335
456
|
}
|
|
336
457
|
return s;
|
|
337
458
|
}
|
|
338
459
|
read() {
|
|
339
|
-
const
|
|
340
|
-
if (
|
|
341
|
-
|
|
342
|
-
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);
|
|
343
463
|
this.validateState(s);
|
|
344
464
|
return s;
|
|
345
465
|
}
|
|
@@ -354,7 +474,7 @@ var Store = class {
|
|
|
354
474
|
throw new Error("invalid managed schedule intent; manual recovery required");
|
|
355
475
|
const ids = /* @__PURE__ */ new Set();
|
|
356
476
|
for (const j of s.jobs) {
|
|
357
|
-
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");
|
|
358
478
|
if (j.sessionId === PROCESS_SESSION_ID) {
|
|
359
479
|
if (!parseProcessCommand(j)) throw new Error("invalid process cron job; manual recovery required");
|
|
360
480
|
}
|
|
@@ -380,10 +500,13 @@ var Store = class {
|
|
|
380
500
|
occurrence: -Number.MAX_SAFE_INTEGER,
|
|
381
501
|
target: "x".repeat(64),
|
|
382
502
|
deliveryStarted: false,
|
|
503
|
+
pendingAction: "remove",
|
|
504
|
+
consecutiveFailures: 1e3,
|
|
383
505
|
error: "".repeat(500)
|
|
384
506
|
}))
|
|
385
507
|
};
|
|
386
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?.();
|
|
387
510
|
const temp = path.join(this.dir, `state.${randomUUID()}.tmp`), dest = path.join(this.dir, "state.json");
|
|
388
511
|
const fd = fs.openSync(temp, "wx", 384);
|
|
389
512
|
try {
|
|
@@ -392,7 +515,17 @@ var Store = class {
|
|
|
392
515
|
} finally {
|
|
393
516
|
fs.closeSync(fd);
|
|
394
517
|
}
|
|
395
|
-
|
|
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
|
+
}
|
|
396
529
|
if (process.platform !== "win32") {
|
|
397
530
|
const dir = fs.openSync(this.dir, "r");
|
|
398
531
|
try {
|
|
@@ -440,6 +573,23 @@ var Store = class {
|
|
|
440
573
|
ensureProcess(command, managedBy, cwd, schedule, now = Date.now()) {
|
|
441
574
|
return this.registerProcess(command, managedBy, cwd, schedule, now, { onlyIfAbsent: true });
|
|
442
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
|
+
}
|
|
443
593
|
/** Opt-out and removal share the state writer mutex with on/default registration. */
|
|
444
594
|
disableProcess(managedBy) {
|
|
445
595
|
this.disabledMarker(managedBy);
|
|
@@ -450,11 +600,34 @@ var Store = class {
|
|
|
450
600
|
s.jobs = s.jobs.filter((j) => j !== existing);
|
|
451
601
|
return !!existing;
|
|
452
602
|
});
|
|
603
|
+
this.writeDisabledMarker(managedBy);
|
|
604
|
+
return removed;
|
|
605
|
+
}
|
|
606
|
+
/** Atomically replace the compatibility marker without following symlinks. */
|
|
607
|
+
writeDisabledMarker(managedBy) {
|
|
453
608
|
try {
|
|
454
|
-
|
|
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
|
+
}
|
|
455
629
|
} catch {
|
|
456
630
|
}
|
|
457
|
-
return removed;
|
|
458
631
|
}
|
|
459
632
|
validManagedKey(key) {
|
|
460
633
|
return /^[a-zA-Z0-9_-]{1,64}$/.test(key) && !["__proto__", "constructor", "prototype"].includes(key);
|
|
@@ -512,26 +685,73 @@ var Store = class {
|
|
|
512
685
|
findProcess(managedBy) {
|
|
513
686
|
return this.read().jobs.find((j) => j.sessionId === PROCESS_SESSION_ID && parseProcessCommand(j)?.managedBy === managedBy);
|
|
514
687
|
}
|
|
515
|
-
change(id, action, now = Date.now()) {
|
|
516
|
-
|
|
688
|
+
change(id, action, now = Date.now(), opts) {
|
|
689
|
+
let disabledManaged;
|
|
690
|
+
const outcome = this.transaction((s) => {
|
|
517
691
|
const j = s.jobs.find((j2) => j2.id === id);
|
|
518
692
|
if (!j) throw new Error("unknown job");
|
|
519
|
-
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;
|
|
520
713
|
if (action === "remove") {
|
|
714
|
+
if (managedBy) {
|
|
715
|
+
s.managedEnabled = { ...s.managedEnabled, [managedBy]: false };
|
|
716
|
+
disabledManaged = managedBy;
|
|
717
|
+
}
|
|
521
718
|
s.jobs = s.jobs.filter((j2) => j2.id !== id);
|
|
522
|
-
return;
|
|
719
|
+
return "applied";
|
|
523
720
|
}
|
|
524
|
-
|
|
525
|
-
if (j.enabled) {
|
|
721
|
+
if (action === "resume") {
|
|
526
722
|
if (j.remaining !== void 0 && j.remaining <= 0) throw new Error("job exhausted its execution count; create a new job");
|
|
527
|
-
j.
|
|
528
|
-
|
|
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;
|
|
529
728
|
j.state = "ready";
|
|
530
729
|
delete j.error;
|
|
730
|
+
if (opts?.authorization !== void 0) j.authorization = opts.authorization;
|
|
731
|
+
} else {
|
|
732
|
+
j.enabled = false;
|
|
531
733
|
}
|
|
734
|
+
return "applied";
|
|
532
735
|
});
|
|
736
|
+
if (disabledManaged) {
|
|
737
|
+
this.writeDisabledMarker(disabledManaged);
|
|
738
|
+
}
|
|
739
|
+
return outcome;
|
|
533
740
|
}
|
|
534
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
|
+
}
|
|
535
755
|
function complete(job, error, now = Date.now()) {
|
|
536
756
|
delete job.target;
|
|
537
757
|
delete job.deliveryStarted;
|
|
@@ -542,6 +762,7 @@ function complete(job, error, now = Date.now()) {
|
|
|
542
762
|
}
|
|
543
763
|
job.state = "ready";
|
|
544
764
|
delete job.error;
|
|
765
|
+
delete job.consecutiveFailures;
|
|
545
766
|
if (job.remaining !== void 0) {
|
|
546
767
|
job.remaining -= 1;
|
|
547
768
|
if (job.remaining <= 0) {
|
|
@@ -553,6 +774,31 @@ function complete(job, error, now = Date.now()) {
|
|
|
553
774
|
job.next = "at" in job.schedule ? null : nextTime(job.schedule, Math.max(now, job.occurrence ?? now));
|
|
554
775
|
if (job.next === null) job.enabled = false;
|
|
555
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
|
+
}
|
|
556
802
|
function completeInterrupted(job, error, now = Date.now()) {
|
|
557
803
|
if (!isProcessJob(job)) {
|
|
558
804
|
complete(job, error, now);
|
|
@@ -569,20 +815,71 @@ function completeInterrupted(job, error, now = Date.now()) {
|
|
|
569
815
|
}
|
|
570
816
|
|
|
571
817
|
// builtin/extensions/cron/runtime.ts
|
|
572
|
-
import * as
|
|
573
|
-
import * as
|
|
818
|
+
import * as fs4 from "node:fs";
|
|
819
|
+
import * as path4 from "node:path";
|
|
574
820
|
import { randomUUID as randomUUID3 } from "node:crypto";
|
|
575
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
|
+
|
|
576
873
|
// builtin/extensions/cron/worker.ts
|
|
577
874
|
import { spawn } from "node:child_process";
|
|
578
875
|
import { randomUUID as randomUUID2 } from "node:crypto";
|
|
579
|
-
import * as
|
|
580
|
-
import * as
|
|
876
|
+
import * as fs3 from "node:fs";
|
|
877
|
+
import * as path3 from "node:path";
|
|
581
878
|
import { StringDecoder } from "node:string_decoder";
|
|
582
879
|
function runWorker(job, signal, cli = process.argv[1], configDir) {
|
|
583
880
|
if (signal.aborted) return Promise.reject(new Error("worker interrupted before launch"));
|
|
584
881
|
return new Promise((resolve3, reject) => {
|
|
585
|
-
const child = spawn(process.execPath, [
|
|
882
|
+
const child = spawn(process.execPath, [path3.resolve(cli), "--json-events", "--session-id", job.sessionId, "--resume-required"], {
|
|
586
883
|
cwd: job.cwd,
|
|
587
884
|
// R5-P2: a cron worker is an INDEPENDENT session — strip the manager
|
|
588
885
|
// identity/model quartet so it never inherits the manager's model or
|
|
@@ -685,7 +982,7 @@ function runWorker(job, signal, cli = process.argv[1], configDir) {
|
|
|
685
982
|
});
|
|
686
983
|
}
|
|
687
984
|
function processJobEnv(configDir) {
|
|
688
|
-
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"];
|
|
689
986
|
const env = {};
|
|
690
987
|
for (const key of allow) {
|
|
691
988
|
const value = process.env[key];
|
|
@@ -695,6 +992,7 @@ function processJobEnv(configDir) {
|
|
|
695
992
|
if (configDir) env.PIE_CODING_AGENT_DIR = configDir;
|
|
696
993
|
return env;
|
|
697
994
|
}
|
|
995
|
+
var PROCESS_WORKER_RETRYABLE_EXIT_CODE = 75;
|
|
698
996
|
var ProcessWorkerCancelled = class extends Error {
|
|
699
997
|
aborted = true;
|
|
700
998
|
constructor(message) {
|
|
@@ -702,24 +1000,31 @@ var ProcessWorkerCancelled = class extends Error {
|
|
|
702
1000
|
this.name = "ProcessWorkerCancelled";
|
|
703
1001
|
}
|
|
704
1002
|
};
|
|
1003
|
+
var ProcessWorkerRetryable = class extends Error {
|
|
1004
|
+
retryable = true;
|
|
1005
|
+
constructor(message) {
|
|
1006
|
+
super(message);
|
|
1007
|
+
this.name = "ProcessWorkerRetryable";
|
|
1008
|
+
}
|
|
1009
|
+
};
|
|
705
1010
|
function runProcessWorker(job, command, cwd, deadlineMs = 30 * 60 * 1e3, logDir, signal, configDir) {
|
|
706
1011
|
return new Promise((resolve3, reject) => {
|
|
707
|
-
const dir = logDir ??
|
|
708
|
-
const logFile =
|
|
1012
|
+
const dir = logDir ?? path3.join(process.cwd(), "cron");
|
|
1013
|
+
const logFile = path3.join(dir, "process.log");
|
|
709
1014
|
try {
|
|
710
|
-
|
|
1015
|
+
fs3.mkdirSync(dir, { recursive: true, mode: 448 });
|
|
711
1016
|
} catch {
|
|
712
1017
|
}
|
|
713
1018
|
const stamp = (/* @__PURE__ */ new Date()).toISOString();
|
|
714
1019
|
const header = `[${stamp}] job=${job.id} cwd=${cwd} cmd=${JSON.stringify(command.command)}
|
|
715
1020
|
`;
|
|
716
1021
|
try {
|
|
717
|
-
|
|
1022
|
+
fs3.appendFileSync(logFile, header);
|
|
718
1023
|
} catch {
|
|
719
1024
|
}
|
|
720
1025
|
let out;
|
|
721
1026
|
try {
|
|
722
|
-
out =
|
|
1027
|
+
out = fs3.openSync(logFile, "a");
|
|
723
1028
|
} catch {
|
|
724
1029
|
}
|
|
725
1030
|
let child;
|
|
@@ -784,7 +1089,7 @@ function runProcessWorker(job, command, cwd, deadlineMs = 30 * 60 * 1e3, logDir,
|
|
|
784
1089
|
} catch (error) {
|
|
785
1090
|
if (out !== void 0) {
|
|
786
1091
|
try {
|
|
787
|
-
|
|
1092
|
+
fs3.closeSync(out);
|
|
788
1093
|
} catch {
|
|
789
1094
|
}
|
|
790
1095
|
}
|
|
@@ -796,7 +1101,7 @@ function runProcessWorker(job, command, cwd, deadlineMs = 30 * 60 * 1e3, logDir,
|
|
|
796
1101
|
signal?.removeEventListener("abort", stop);
|
|
797
1102
|
if (out !== void 0) {
|
|
798
1103
|
try {
|
|
799
|
-
|
|
1104
|
+
fs3.closeSync(out);
|
|
800
1105
|
} catch {
|
|
801
1106
|
}
|
|
802
1107
|
}
|
|
@@ -832,7 +1137,7 @@ function runProcessWorker(job, command, cwd, deadlineMs = 30 * 60 * 1e3, logDir,
|
|
|
832
1137
|
settled = true;
|
|
833
1138
|
if (cleanupFailure) failure = `process cleanup failed: ${String(cleanupFailure)}`;
|
|
834
1139
|
try {
|
|
835
|
-
|
|
1140
|
+
fs3.appendFileSync(logFile, `[${(/* @__PURE__ */ new Date()).toISOString()}] job=${job.id} exit=${code}${failure ? ` error=${failure}` : ""}
|
|
836
1141
|
`);
|
|
837
1142
|
} catch {
|
|
838
1143
|
}
|
|
@@ -840,6 +1145,10 @@ function runProcessWorker(job, command, cwd, deadlineMs = 30 * 60 * 1e3, logDir,
|
|
|
840
1145
|
reject(new ProcessWorkerCancelled(failure ?? `cancelled (exit ${code})`));
|
|
841
1146
|
return;
|
|
842
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
|
+
}
|
|
843
1152
|
if (failure || code !== 0) reject(new Error(failure ?? `process exited ${code}`));
|
|
844
1153
|
else resolve3();
|
|
845
1154
|
});
|
|
@@ -866,7 +1175,7 @@ var Runtime = class {
|
|
|
866
1175
|
this.execute = execute;
|
|
867
1176
|
this.processAlive = processAlive;
|
|
868
1177
|
this.executeProcess = executeProcess;
|
|
869
|
-
this.cwd =
|
|
1178
|
+
this.cwd = fs4.realpathSync(ctx.cwd);
|
|
870
1179
|
}
|
|
871
1180
|
ctx;
|
|
872
1181
|
store;
|
|
@@ -932,14 +1241,42 @@ var Runtime = class {
|
|
|
932
1241
|
void this.ensureMemoryDistillationDefault();
|
|
933
1242
|
}
|
|
934
1243
|
/** Default daily distillation at 03:00 local. Idempotent: an existing
|
|
935
|
-
* 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). */
|
|
936
1247
|
async ensureMemoryDistillationDefault() {
|
|
937
1248
|
try {
|
|
938
1249
|
const existing = this.store.findProcess("memory");
|
|
939
|
-
if (existing)
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
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");
|
|
943
1280
|
if ("error" in cronSpec) throw new Error(cronSpec.error);
|
|
944
1281
|
if (this.store.ensureProcess(command, "memory", process.cwd(), cronSpec))
|
|
945
1282
|
this.ctx.log("cron: registered the default daily memory distillation (03:00)");
|
|
@@ -950,19 +1287,19 @@ var Runtime = class {
|
|
|
950
1287
|
}
|
|
951
1288
|
}
|
|
952
1289
|
markUnsafe() {
|
|
953
|
-
|
|
1290
|
+
fs4.mkdirSync(path4.join(this.store.dir, "unsafe.lock"), { recursive: true, mode: 448 });
|
|
954
1291
|
}
|
|
955
1292
|
coordinatorDir() {
|
|
956
|
-
return
|
|
1293
|
+
return path4.join(this.store.dir, "scheduler.lock");
|
|
957
1294
|
}
|
|
958
1295
|
coordinatorOwnerFile() {
|
|
959
|
-
return
|
|
1296
|
+
return path4.join(this.coordinatorDir(), COORDINATOR_OWNER_FILE);
|
|
960
1297
|
}
|
|
961
1298
|
readCoordinatorOwner() {
|
|
962
1299
|
try {
|
|
963
|
-
const file = this.coordinatorOwnerFile(), stat =
|
|
1300
|
+
const file = this.coordinatorOwnerFile(), stat = fs4.lstatSync(file);
|
|
964
1301
|
if (!stat.isFile() || stat.size > 4096) return void 0;
|
|
965
|
-
const raw =
|
|
1302
|
+
const raw = fs4.readFileSync(file, "utf8"), value = JSON.parse(raw);
|
|
966
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;
|
|
967
1304
|
return { value, raw };
|
|
968
1305
|
} catch {
|
|
@@ -987,17 +1324,17 @@ var Runtime = class {
|
|
|
987
1324
|
}
|
|
988
1325
|
acquireCoordinator() {
|
|
989
1326
|
const dir = this.coordinatorDir();
|
|
990
|
-
|
|
1327
|
+
fs4.mkdirSync(dir, { mode: 448 });
|
|
991
1328
|
const owner = { version: 1, pid: process.pid, instanceId: this.id, createdAt: Date.now() };
|
|
992
1329
|
try {
|
|
993
|
-
|
|
1330
|
+
fs4.writeFileSync(this.coordinatorOwnerFile(), JSON.stringify(owner), { mode: 384, flag: "wx" });
|
|
994
1331
|
} catch (error) {
|
|
995
1332
|
try {
|
|
996
|
-
|
|
1333
|
+
fs4.unlinkSync(this.coordinatorOwnerFile());
|
|
997
1334
|
} catch {
|
|
998
1335
|
}
|
|
999
1336
|
try {
|
|
1000
|
-
|
|
1337
|
+
fs4.rmdirSync(dir);
|
|
1001
1338
|
} catch {
|
|
1002
1339
|
}
|
|
1003
1340
|
throw error;
|
|
@@ -1025,32 +1362,32 @@ var Runtime = class {
|
|
|
1025
1362
|
const latest = this.readCoordinatorOwner();
|
|
1026
1363
|
if (!latest || latest.raw !== held.raw) return false;
|
|
1027
1364
|
try {
|
|
1028
|
-
|
|
1029
|
-
|
|
1365
|
+
fs4.unlinkSync(this.coordinatorOwnerFile());
|
|
1366
|
+
fs4.rmdirSync(this.coordinatorDir());
|
|
1030
1367
|
return true;
|
|
1031
1368
|
} catch {
|
|
1032
1369
|
return false;
|
|
1033
1370
|
}
|
|
1034
1371
|
}
|
|
1035
1372
|
releaseCoordinator() {
|
|
1036
|
-
|
|
1037
|
-
|
|
1373
|
+
fs4.rmSync(this.coordinatorOwnerFile(), { force: true });
|
|
1374
|
+
fs4.rmdirSync(this.coordinatorDir());
|
|
1038
1375
|
this.leader = false;
|
|
1039
1376
|
}
|
|
1040
1377
|
persistOwner(sessionId) {
|
|
1041
1378
|
this.store.transaction((state) => {
|
|
1042
|
-
sweepStaleOwners(state, this.store.dir, { sessionId, keepKey: this.id });
|
|
1379
|
+
sweepStaleOwners(state, this.store.dir, { sessionId, keepKey: this.id, warn: (message) => this.ctx.log(message) });
|
|
1043
1380
|
state.owners[this.id] = { sessionId, cwd: this.cwd, busy: !this.ctx.isIdle(), registeredAt: Date.now() };
|
|
1044
1381
|
});
|
|
1045
1382
|
try {
|
|
1046
|
-
const livenessDir =
|
|
1047
|
-
|
|
1048
|
-
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`);
|
|
1049
1386
|
try {
|
|
1050
|
-
|
|
1387
|
+
fs4.unlinkSync(liveness);
|
|
1051
1388
|
} catch {
|
|
1052
1389
|
}
|
|
1053
|
-
|
|
1390
|
+
fs4.writeFileSync(liveness, JSON.stringify({ pid: process.pid, at: Date.now() }), { mode: 384 });
|
|
1054
1391
|
} catch {
|
|
1055
1392
|
}
|
|
1056
1393
|
this.sessionId = sessionId;
|
|
@@ -1102,7 +1439,13 @@ var Runtime = class {
|
|
|
1102
1439
|
* conservative block; only a human can decide (double execution is worse
|
|
1103
1440
|
* than a stalled schedule).
|
|
1104
1441
|
*/
|
|
1105
|
-
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
|
+
}
|
|
1106
1449
|
const repeating = !("at" in job.schedule);
|
|
1107
1450
|
if (!executed && repeating && !isProcessJob(job) && !job.retriedOnce) {
|
|
1108
1451
|
job.retriedOnce = true;
|
|
@@ -1110,12 +1453,13 @@ var Runtime = class {
|
|
|
1110
1453
|
delete job.target;
|
|
1111
1454
|
delete job.deliveryStarted;
|
|
1112
1455
|
job.next = nextTime(job.schedule, Math.max(Date.now(), job.occurrence ?? Date.now()));
|
|
1113
|
-
if (job.next === null) job.enabled = false;
|
|
1456
|
+
if (job.next === null || pending === "pause") job.enabled = false;
|
|
1114
1457
|
job.error = `retried automatically after a block that never executed: ${error}`.slice(0, 500);
|
|
1115
1458
|
this.auditQuiet({ kind: "auto-retry", jobId: job.id, sessionId: job.sessionId, cwd: job.cwd, detail: error });
|
|
1116
1459
|
return;
|
|
1117
1460
|
}
|
|
1118
1461
|
complete(job, error);
|
|
1462
|
+
if (pending === "pause") job.enabled = false;
|
|
1119
1463
|
this.auditQuiet({ kind: "blocked", jobId: job.id, sessionId: job.sessionId, cwd: job.cwd, detail: error });
|
|
1120
1464
|
}
|
|
1121
1465
|
notify(job, owners) {
|
|
@@ -1179,16 +1523,15 @@ Tell the user in one short message and wait for their decision. Do not resume or
|
|
|
1179
1523
|
}
|
|
1180
1524
|
flushCompletions() {
|
|
1181
1525
|
for (const [id, entry] of this.completions) {
|
|
1182
|
-
const { error, cancelled } = entry;
|
|
1526
|
+
const { error, cancelled, retryable } = entry;
|
|
1183
1527
|
try {
|
|
1184
1528
|
this.store.transaction((state) => {
|
|
1185
1529
|
const job = state.jobs.find((item) => item.id === id);
|
|
1186
1530
|
if (job?.state === "running") {
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
}
|
|
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
|
+
});
|
|
1192
1535
|
}
|
|
1193
1536
|
});
|
|
1194
1537
|
this.completions.delete(id);
|
|
@@ -1198,14 +1541,14 @@ Tell the user in one short message and wait for their decision. Do not resume or
|
|
|
1198
1541
|
}
|
|
1199
1542
|
}
|
|
1200
1543
|
}
|
|
1201
|
-
finish(id, error, cancelled) {
|
|
1202
|
-
this.completions.set(id, { error, cancelled });
|
|
1544
|
+
finish(id, error, cancelled, retryable) {
|
|
1545
|
+
this.completions.set(id, { error, cancelled, retryable });
|
|
1203
1546
|
this.flushCompletions();
|
|
1204
1547
|
}
|
|
1205
1548
|
async poll(now = Date.now()) {
|
|
1206
1549
|
if (this.stopped || this.polling || !this.initialized) return;
|
|
1207
1550
|
if (this.pollRetryAt !== void 0 && Date.now() < this.pollRetryAt) return;
|
|
1208
|
-
if (
|
|
1551
|
+
if (fs4.existsSync(path4.join(this.store.dir, "unsafe.lock"))) {
|
|
1209
1552
|
this.abort.abort();
|
|
1210
1553
|
this.processAbort.abort();
|
|
1211
1554
|
this.ctx.ui.setStatus?.("cron", void 0);
|
|
@@ -1237,31 +1580,31 @@ Tell the user in one short message and wait for their decision. Do not resume or
|
|
|
1237
1580
|
let processLaunch;
|
|
1238
1581
|
this.store.transaction((state2) => {
|
|
1239
1582
|
if (this.recovering) {
|
|
1240
|
-
for (const job of state2.jobs) {
|
|
1583
|
+
for (const job of [...state2.jobs]) {
|
|
1241
1584
|
if (job.state === "running" && (job.target === "worker" || !job.target || !state2.owners[job.target])) {
|
|
1242
|
-
this.handleBlock(job, "coordinator restarted; outcome uncertain", true);
|
|
1585
|
+
this.handleBlock(state2, job, "coordinator restarted; outcome uncertain", true);
|
|
1243
1586
|
}
|
|
1244
1587
|
}
|
|
1245
1588
|
}
|
|
1246
1589
|
state2.owners[this.id] = { sessionId: this.sessionId, cwd: this.cwd, busy: !this.ctx.isIdle() };
|
|
1247
|
-
for (const job of state2.jobs) {
|
|
1590
|
+
for (const job of [...state2.jobs]) {
|
|
1248
1591
|
if (isProcessJob(job)) continue;
|
|
1249
1592
|
const owners = Object.entries(state2.owners).filter(([, owner]) => owner.sessionId === job.sessionId);
|
|
1250
1593
|
if (this.leader && job.state === "running" && job.target === "worker" && owners.length) this.abort.abort();
|
|
1251
|
-
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);
|
|
1252
1595
|
if (job.state === "running" && job.target === this.id && this.accepted?.id === job.id) {
|
|
1253
1596
|
if (!this.accepted.consumed) {
|
|
1254
1597
|
for (const message of this.ctx.getMessages?.() ?? []) this.onMessage(message);
|
|
1255
1598
|
}
|
|
1256
1599
|
if (owners.length !== 1 || this.sessionId !== job.sessionId) {
|
|
1257
|
-
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);
|
|
1258
1601
|
this.accepted = void 0;
|
|
1259
1602
|
this.acceptedIdlePolls = 0;
|
|
1260
1603
|
} else if (this.accepted.consumed && this.accepted.busy) {
|
|
1261
1604
|
if (this.ctx.isIdle()) {
|
|
1262
1605
|
this.acceptedIdlePolls += 1;
|
|
1263
1606
|
if (this.acceptedIdlePolls >= 2) {
|
|
1264
|
-
|
|
1607
|
+
settleJob(state2, job, this.accepted.error);
|
|
1265
1608
|
this.accepted = void 0;
|
|
1266
1609
|
this.acceptedIdlePolls = 0;
|
|
1267
1610
|
}
|
|
@@ -1269,14 +1612,14 @@ Tell the user in one short message and wait for their decision. Do not resume or
|
|
|
1269
1612
|
this.acceptedIdlePolls = 0;
|
|
1270
1613
|
}
|
|
1271
1614
|
} else if (!this.accepted.consumed && now - this.accepted.at > 6e4) {
|
|
1272
|
-
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);
|
|
1273
1616
|
this.accepted = void 0;
|
|
1274
1617
|
this.acceptedIdlePolls = 0;
|
|
1275
1618
|
}
|
|
1276
1619
|
}
|
|
1277
1620
|
if (job.state === "running" && job.target === this.id && !job.deliveryStarted && this.ctx.isIdle()) {
|
|
1278
1621
|
if (owners.length !== 1 || owners[0][0] !== this.id || this.sessionId !== job.sessionId || this.cwd !== job.cwd) {
|
|
1279
|
-
this.handleBlock(job, "owner changed or duplicate; delivery blocked", false);
|
|
1622
|
+
this.handleBlock(state2, job, "owner changed or duplicate; delivery blocked", false);
|
|
1280
1623
|
} else {
|
|
1281
1624
|
job.deliveryStarted = true;
|
|
1282
1625
|
delivery = { ...job };
|
|
@@ -1315,7 +1658,7 @@ Tell the user in one short message and wait for their decision. Do not resume or
|
|
|
1315
1658
|
this.recovering = false;
|
|
1316
1659
|
if (delivery) {
|
|
1317
1660
|
const job = delivery;
|
|
1318
|
-
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);
|
|
1319
1662
|
let error;
|
|
1320
1663
|
const content = `[Cron job=${job.id} scheduledAt=${job.occurrence}]
|
|
1321
1664
|
${job.prompt}`;
|
|
@@ -1336,12 +1679,12 @@ ${job.prompt}`;
|
|
|
1336
1679
|
if (launch) {
|
|
1337
1680
|
const job = launch;
|
|
1338
1681
|
const latest = this.store.read();
|
|
1339
|
-
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)) {
|
|
1340
1683
|
this.finish(job.id, "ownership changed before worker launch; inspect before resuming");
|
|
1341
1684
|
return;
|
|
1342
1685
|
}
|
|
1343
1686
|
this.abort = new AbortController();
|
|
1344
|
-
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(() => {
|
|
1345
1688
|
try {
|
|
1346
1689
|
this.markUnsafe();
|
|
1347
1690
|
} catch {
|
|
@@ -1352,7 +1695,15 @@ ${job.prompt}`;
|
|
|
1352
1695
|
const job = processLaunch;
|
|
1353
1696
|
const command = parseProcessCommand(job);
|
|
1354
1697
|
this.processAbort = new AbortController();
|
|
1355
|
-
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(() => {
|
|
1356
1707
|
try {
|
|
1357
1708
|
this.markUnsafe();
|
|
1358
1709
|
} catch {
|
|
@@ -1413,20 +1764,21 @@ ${job.prompt}`;
|
|
|
1413
1764
|
for (const [id, entry] of this.completions) {
|
|
1414
1765
|
const job = state.jobs.find((item) => item.id === id);
|
|
1415
1766
|
if (job?.state === "running") {
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
}
|
|
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
|
+
});
|
|
1421
1771
|
}
|
|
1422
1772
|
}
|
|
1423
1773
|
delete state.owners[this.id];
|
|
1424
|
-
for (const job of state.jobs) {
|
|
1425
|
-
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
|
+
}
|
|
1426
1778
|
}
|
|
1427
1779
|
});
|
|
1428
1780
|
try {
|
|
1429
|
-
|
|
1781
|
+
fs4.rmSync(path4.join(this.store.dir, "owners-liveness", `${this.id}.json`), { force: true });
|
|
1430
1782
|
} catch {
|
|
1431
1783
|
}
|
|
1432
1784
|
this.completions.clear();
|
|
@@ -1475,33 +1827,278 @@ ${job.prompt}`;
|
|
|
1475
1827
|
}
|
|
1476
1828
|
};
|
|
1477
1829
|
|
|
1478
|
-
// builtin/extensions/cron/
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
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
|
+
}
|
|
1482
1848
|
}
|
|
1483
|
-
function
|
|
1484
|
-
|
|
1485
|
-
if (
|
|
1486
|
-
|
|
1487
|
-
|
|
1488
|
-
const local = /* @__PURE__ */ new Date();
|
|
1489
|
-
local.setHours(hour, minute, 0, 0);
|
|
1490
|
-
const utcHour = local.getUTCHours(), utcMinute = local.getUTCMinutes();
|
|
1491
|
-
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`;
|
|
1492
1854
|
}
|
|
1493
|
-
function
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
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
|
+
};
|
|
1865
|
+
}
|
|
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;
|
|
1502
1921
|
}
|
|
1503
|
-
return [process.execPath, ...loaderArgs, resolved, "memory", "distill", "--worker", "--auto", "--memory-root", path4.join(configPath(), "memory")];
|
|
1504
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
|
+
};
|
|
2099
|
+
}
|
|
2100
|
+
|
|
2101
|
+
// builtin/extensions/cron/index.ts
|
|
1505
2102
|
function cron(ctx) {
|
|
1506
2103
|
if (process.env.PIE_CRON_ROLE === "worker") return;
|
|
1507
2104
|
const capabilities = ctx.capabilities;
|
|
@@ -1517,16 +2114,26 @@ function cron(ctx) {
|
|
|
1517
2114
|
WARNING: change applied but the audit log could not be written (${String(e)})`;
|
|
1518
2115
|
}
|
|
1519
2116
|
};
|
|
1520
|
-
const
|
|
2117
|
+
const configRoot = configPath();
|
|
2118
|
+
const store = new Store(path6.join(configRoot, "cron"));
|
|
1521
2119
|
const runtime = new Runtime(ctx, store);
|
|
1522
|
-
ctx.log(`cron: starting (store=${
|
|
2120
|
+
ctx.log(`cron: starting (store=${path6.join(configRoot, "cron")})`);
|
|
1523
2121
|
let startupError;
|
|
1524
2122
|
try {
|
|
1525
2123
|
runtime.start();
|
|
1526
2124
|
} catch (e) {
|
|
1527
2125
|
startupError = String(e);
|
|
1528
2126
|
}
|
|
1529
|
-
|
|
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
|
+
});
|
|
1530
2137
|
ctx.on("agent:start", () => runtime.onStart());
|
|
1531
2138
|
ctx.on("message:end", (e) => runtime.onMessage(e.message));
|
|
1532
2139
|
ctx.on("turn:failed", () => runtime.onFailure());
|
|
@@ -1540,14 +2147,14 @@ WARNING: change applied but the audit log could not be written (${String(e)})`;
|
|
|
1540
2147
|
}
|
|
1541
2148
|
});
|
|
1542
2149
|
ctx.on("terminal:input", (e) => {
|
|
1543
|
-
if (/^\/tools\/cron(?:\s|$)/.test(e.text)) return;
|
|
2150
|
+
if (/^\/(?:tools\/cron(?:\/|\s|$)|cron(?:\s|$))/.test(e.text)) return;
|
|
1544
2151
|
let unsafe = false, duplicates = false, worker = false;
|
|
1545
2152
|
try {
|
|
1546
2153
|
const state = store.read();
|
|
1547
2154
|
if (!state.jobs.some((j) => j.sessionId === runtime.sessionId && (j.enabled || j.state === "running"))) return;
|
|
1548
2155
|
duplicates = Object.values(state.owners).filter((o) => o.sessionId === runtime.sessionId).length > 1;
|
|
1549
2156
|
worker = state.jobs.some((j) => j.sessionId === runtime.sessionId && j.state === "running" && j.target === "worker");
|
|
1550
|
-
unsafe =
|
|
2157
|
+
unsafe = fs6.existsSync(path6.join(store.dir, "unsafe.lock"));
|
|
1551
2158
|
if (!startupError && runtime.ready && !duplicates && !worker && !unsafe) return;
|
|
1552
2159
|
} catch {
|
|
1553
2160
|
}
|
|
@@ -1569,25 +2176,37 @@ WARNING: change applied but the audit log could not be written (${String(e)})`;
|
|
|
1569
2176
|
return { cancel: true };
|
|
1570
2177
|
}
|
|
1571
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
|
+
};
|
|
1572
2190
|
const run = (action, id, prompt, schedule) => {
|
|
1573
2191
|
if (startupError && action !== "list") throw new Error(`cron unavailable: ${startupError}; see docs/cron.md recovery`);
|
|
1574
2192
|
if (action === "list") {
|
|
1575
2193
|
const state = store.read();
|
|
2194
|
+
const now = Date.now();
|
|
1576
2195
|
const blocked = state.jobs.filter((j) => j.state === "blocked").map((j) => {
|
|
1577
|
-
const
|
|
2196
|
+
const info = blockedReviewInfo(j, now);
|
|
1578
2197
|
return {
|
|
1579
|
-
id:
|
|
1580
|
-
error:
|
|
1581
|
-
lastOccurrence:
|
|
1582
|
-
executionTrail:
|
|
1583
|
-
cwd:
|
|
1584
|
-
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
|
|
1585
2204
|
};
|
|
1586
2205
|
});
|
|
1587
2206
|
return JSON.stringify({
|
|
1588
2207
|
...state,
|
|
1589
|
-
recoveryRequired:
|
|
1590
|
-
coordinatorPresent:
|
|
2208
|
+
recoveryRequired: fs6.existsSync(path6.join(store.dir, "unsafe.lock")),
|
|
2209
|
+
coordinatorPresent: fs6.existsSync(path6.join(store.dir, "scheduler.lock")),
|
|
1591
2210
|
...blocked.length > 0 ? { blockedReview: blocked } : {}
|
|
1592
2211
|
}, null, 2);
|
|
1593
2212
|
}
|
|
@@ -1598,43 +2217,178 @@ WARNING: change applied but the audit log could not be written (${String(e)})`;
|
|
|
1598
2217
|
const note = auditNote({ kind: "add", jobId: job.id, sessionId: job.sessionId, cwd: job.cwd, authorization });
|
|
1599
2218
|
return JSON.stringify({
|
|
1600
2219
|
job,
|
|
1601
|
-
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
|
|
1602
2221
|
});
|
|
1603
2222
|
}
|
|
1604
2223
|
if (action === "pause" || action === "resume" || action === "remove") {
|
|
1605
2224
|
const jobId = id ?? "";
|
|
1606
2225
|
const authorization = authorizationNow();
|
|
1607
|
-
|
|
1608
|
-
|
|
1609
|
-
|
|
1610
|
-
|
|
1611
|
-
|
|
1612
|
-
store.change(jobId, action);
|
|
1613
|
-
const job = store.read().jobs.find((j) => j.id === jobId);
|
|
1614
|
-
const note = auditNote({ kind: action, jobId, sessionId: job?.sessionId, cwd: job?.cwd, authorization });
|
|
1615
|
-
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}`;
|
|
1616
2231
|
}
|
|
1617
2232
|
if (action === "reap-owners") {
|
|
1618
|
-
const
|
|
2233
|
+
const warnings = [];
|
|
2234
|
+
const reaped = store.transaction((state) => sweepStaleOwners(state, store.dir, { warn: (message) => warnings.push(message) }));
|
|
1619
2235
|
const note = auditNote({ kind: "remove", detail: `reap-owners: ${reaped.length} owner row(s) reaped`, authorization: authorizationNow() });
|
|
1620
|
-
return JSON.stringify({ reaped, total: reaped.length }, null, 2) + note;
|
|
2236
|
+
return JSON.stringify({ reaped, total: reaped.length, ...warnings.length ? { warnings } : {} }, null, 2) + note;
|
|
1621
2237
|
}
|
|
1622
2238
|
throw new Error('Usage: /tools/cron list | reap-owners | add {"prompt":"...","schedule":{"every":3600}} | pause|resume|remove <id>');
|
|
1623
2239
|
};
|
|
1624
|
-
|
|
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) => {
|
|
1625
2242
|
try {
|
|
1626
|
-
const match = (args ?? "").trim().match(/^(\S+)(?:\s+([\s\S]*))?$/);
|
|
1627
|
-
const action = match?.[1] ?? "list", rest = match?.[2];
|
|
1628
2243
|
const data = action === "add" ? JSON.parse(rest ?? "{}") : void 0;
|
|
1629
2244
|
ctx.ui.notify(run(action, rest, data?.prompt, data?.schedule), "info");
|
|
1630
2245
|
} catch (e) {
|
|
1631
2246
|
ctx.ui.notify(String(e), "warning");
|
|
1632
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);
|
|
1633
2387
|
} });
|
|
1634
2388
|
ctx.registerTool({
|
|
1635
2389
|
name: "cron_manage",
|
|
1636
2390
|
label: "Cron",
|
|
1637
|
-
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.',
|
|
1638
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 })) })])) }),
|
|
1639
2393
|
risk: { riskClass: "external_side_effect", permissionScope: "host", availableInPlanMode: false, requiresPermission: true, externalSideEffect: true, allowedForSubagentByDefault: false, concurrencySafe: false },
|
|
1640
2394
|
execute: async (args) => {
|