@cydm/pie 2.7.20 → 2.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +18 -0
  2. package/dist/builtin/extensions/ask-user/README.md +117 -0
  3. package/dist/builtin/extensions/ask-user/index.js +4 -3
  4. package/dist/builtin/extensions/cron/index.js +299 -39
  5. package/dist/builtin/extensions/im-forward/README.md +297 -0
  6. package/dist/builtin/extensions/im-forward/index.js +315 -27
  7. package/dist/builtin/extensions/mcp-adapter/README.md +27 -0
  8. package/dist/builtin/extensions/memory/index.js +515 -0
  9. package/dist/builtin/extensions/memory/package.json +19 -0
  10. package/dist/builtin/extensions/pie-ipc/README.md +21 -0
  11. package/dist/builtin/extensions/plan-mode/METHOD.md +70 -0
  12. package/dist/builtin/extensions/plan-mode/index.js +150 -82
  13. package/dist/builtin/extensions/subagent/README.md +315 -0
  14. package/dist/builtin/extensions/subagent/index.js +8 -5
  15. package/dist/builtin/extensions/todo/index.js +4 -3
  16. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +1 -1
  17. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
  18. package/dist/builtin/skills/chrome-devtools-axi/{chunk-U75F4DPF.js → chunk-BNSAEVRT.js} +201 -77
  19. package/dist/builtin/skills/chrome-devtools-axi/{cli-4ITIR57L.js → cli-AO2ZTPRM.js} +57 -202
  20. package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +6 -1
  21. package/dist/builtin/skills/computer-use-axi/computer-use-axi-runtime.js +6 -1
  22. package/dist/chunks/auth-storage-3EGM3VTK.js +13 -0
  23. package/dist/chunks/{chunk-X7UO6BA6.js → chunk-3BC5KGDQ.js} +451 -162
  24. package/dist/chunks/chunk-3NHP7HK5.js +298 -0
  25. package/dist/chunks/chunk-6DNYGVZP.js +278 -0
  26. package/dist/chunks/{chunk-TGCI5M6R.js → chunk-GDIYSMTS.js} +22 -142
  27. package/dist/chunks/{chunk-2H2DD22Z.js → chunk-GH4VW2OT.js} +1 -1
  28. package/dist/chunks/chunk-ILUHTKF3.js +149 -0
  29. package/dist/chunks/{chunk-UDCGB3LZ.js → chunk-PK72LVWQ.js} +11841 -16501
  30. package/dist/chunks/chunk-RSL7E4R7.js +9634 -0
  31. package/dist/chunks/chunk-YRR6C43W.js +1740 -0
  32. package/dist/chunks/config-74AUVDLT.js +46 -0
  33. package/dist/chunks/model-registry-LI5THXV4.js +17 -0
  34. package/dist/chunks/src-66XSMIAM.js +134 -0
  35. package/dist/chunks/src-BPSQMSSC.js +431 -0
  36. package/dist/chunks/src-OPPYTPWG.js +285 -0
  37. package/dist/chunks/{src-GX4UBAYF.js → src-YG5M2H44.js} +2 -2
  38. package/dist/chunks/{test-stream-AKIZNFCM.js → test-stream-JBWXKOQA.js} +1 -1
  39. package/dist/cli.js +986 -2292
  40. package/package.json +3 -3
@@ -6,7 +6,7 @@ import "../../../chunks/chunk-LZQXQOPJ.js";
6
6
 
7
7
  // builtin/extensions/cron/index.ts
8
8
  import * as path4 from "node:path";
9
- import * as fs3 from "node:fs";
9
+ import * as fs4 from "node:fs";
10
10
  import { homedir } from "node:os";
11
11
 
12
12
  // builtin/extensions/cron/store.ts
@@ -35,18 +35,25 @@ function fields(expression) {
35
35
  });
36
36
  }
37
37
  function validateSchedule(value) {
38
- if (!value || typeof value !== "object" || Object.keys(value).length !== 1) throw new Error("provide exactly one of at, every, cron");
38
+ if (!value || typeof value !== "object") throw new Error("provide exactly one of at, every, cron");
39
39
  const s = value;
40
+ const scheduleKeys = ["at", "every", "cron"].filter((k) => k in s);
41
+ if (scheduleKeys.length !== 1) throw new Error("provide exactly one of at, every, cron");
42
+ if (Object.keys(value).length - scheduleKeys.length > 1) throw new Error("only the optional count may accompany at/every/cron");
43
+ const count = s.count;
44
+ const countValid = count === void 0 || typeof count === "number" && Number.isSafeInteger(count) && count >= 1 && count <= 1e3;
45
+ if (!countValid) throw new Error("count must be an integer 1..1000 (total executions)");
40
46
  if ("at" in s && typeof s.at === "string") {
47
+ if (count !== void 0) throw new Error("at is one-shot; count applies only to every/cron");
41
48
  const m = s.at.match(/^(\d{4})-(\d\d)-(\d\d)T(\d\d):(\d\d)(?::(\d\d)(?:\.\d{1,3})?)?(?:Z|[+-]\d\d:\d\d)$/);
42
49
  if (m && +m[1] >= 1970 && +m[2] >= 1 && +m[2] <= 12 && +m[3] >= 1 && +m[3] <= new Date(Date.UTC(+m[1], +m[2], 0)).getUTCDate() && +m[4] < 24 && +m[5] < 60 && +(m[6] ?? 0) < 60 && Number.isFinite(Date.parse(s.at))) return s;
43
50
  }
44
- if ("every" in s && Number.isSafeInteger(s.every) && s.every >= 60 && s.every <= 31536e3) return s;
45
- if ("cron" in s && typeof s.cron === "string" && s.cron.length <= 256) {
51
+ if ("every" in s && Number.isSafeInteger(s.every) && s.every >= 60 && s.every <= 31536e3 && countValid) return s;
52
+ if ("cron" in s && typeof s.cron === "string" && s.cron.length <= 256 && countValid) {
46
53
  fields(s.cron);
47
54
  return s;
48
55
  }
49
- throw new Error("invalid schedule (every: integer seconds 60..31536000; at: ISO timestamp with timezone)");
56
+ throw new Error("invalid schedule (every: integer seconds 60..31536000; at: ISO timestamp with timezone; count: integer 1..1000 for every/cron)");
50
57
  }
51
58
  function nextTime(s, after) {
52
59
  if ("at" in s) return Date.parse(s.at) > after ? Date.parse(s.at) : null;
@@ -63,6 +70,20 @@ function nextTime(s, after) {
63
70
  }
64
71
 
65
72
  // builtin/extensions/cron/store.ts
73
+ var PROCESS_SESSION_ID = "process";
74
+ function parseProcessCommand(job) {
75
+ if (job.sessionId !== PROCESS_SESSION_ID) return null;
76
+ try {
77
+ const parsed = JSON.parse(job.prompt);
78
+ if (!parsed || !Array.isArray(parsed.command) || parsed.command.length === 0 || !parsed.command.every((part) => typeof part === "string" && part.length > 0) || parsed.command.length > 32 || parsed.command.some((part) => part.length > 4096) || parsed.managedBy !== void 0 && (typeof parsed.managedBy !== "string" || parsed.managedBy.length > 64)) return null;
79
+ return parsed;
80
+ } catch {
81
+ return null;
82
+ }
83
+ }
84
+ function isProcessJob(job) {
85
+ return job.sessionId === PROCESS_SESSION_ID && parseProcessCommand(job) !== null;
86
+ }
66
87
  var Store = class {
67
88
  constructor(dir) {
68
89
  this.dir = dir;
@@ -115,7 +136,10 @@ var Store = class {
115
136
  if (Array.isArray(s.owners) || s.jobs.length > 100 || Object.keys(s.owners).length > 1e3) throw new Error("cron state exceeds record limit");
116
137
  const ids = /* @__PURE__ */ new Set();
117
138
  for (const j of s.jobs) {
118
- 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.next !== null && !Number.isSafeInteger(j.next)) throw new Error("invalid cron job; manual recovery required");
139
+ 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)) throw new Error("invalid cron job; manual recovery required");
140
+ if (j.sessionId === PROCESS_SESSION_ID) {
141
+ if (!parseProcessCommand(j)) throw new Error("invalid process cron job; manual recovery required");
142
+ }
119
143
  ids.add(j.id);
120
144
  validateSchedule(j.schedule);
121
145
  }
@@ -163,16 +187,65 @@ var Store = class {
163
187
  }
164
188
  add(sessionId, cwd, prompt, schedule, now = Date.now()) {
165
189
  if (!sessionId || sessionId.length > 256) throw new Error("an existing session is required");
190
+ if (sessionId === PROCESS_SESSION_ID) throw new Error("session id is reserved for process jobs");
166
191
  if (typeof prompt !== "string" || !prompt.trim() || prompt.length > 16e3) throw new Error("prompt must contain 1..16000 characters");
167
192
  const validated = validateSchedule(schedule), next = nextTime(validated, now);
168
193
  if (next === null) throw new Error("at must be in the future");
169
- const job = { id: randomUUID(), sessionId, cwd: fs.realpathSync(cwd), prompt, schedule: validated, enabled: true, next, state: "ready" };
194
+ const count = validated.count;
195
+ const job = {
196
+ id: randomUUID(),
197
+ sessionId,
198
+ cwd: fs.realpathSync(cwd),
199
+ prompt,
200
+ schedule: validated,
201
+ enabled: true,
202
+ next,
203
+ state: "ready",
204
+ ...count !== void 0 ? { remaining: count } : {}
205
+ };
206
+ return this.transaction((s) => {
207
+ if (s.jobs.length >= 100) throw new Error("maximum 100 jobs");
208
+ s.jobs.push(job);
209
+ return job;
210
+ });
211
+ }
212
+ /** Register a process job: detached command execution, no session binding.
213
+ * Replaces any existing job from the same manager so `schedule on` is
214
+ * idempotent (one managed job per manager). A RUNNING job is never
215
+ * replaced: removing its reservation would let another execution start
216
+ * while the original worker is still alive (single-outstanding invariant). */
217
+ addProcess(command, managedBy, cwd, schedule, now = Date.now()) {
218
+ const validated = validateSchedule(schedule), next = nextTime(validated, now);
219
+ if (next === null) throw new Error("at must be in the future");
220
+ const count = validated.count;
221
+ const probe = {
222
+ id: randomUUID(),
223
+ sessionId: PROCESS_SESSION_ID,
224
+ cwd: fs.realpathSync(cwd),
225
+ prompt: JSON.stringify({ command, managedBy }),
226
+ schedule: validated,
227
+ enabled: true,
228
+ next,
229
+ state: "ready",
230
+ ...count !== void 0 ? { remaining: count } : {}
231
+ };
232
+ if (!parseProcessCommand(probe)) throw new Error("invalid process command (1..32 args, each 1..4096 chars, no NUL bytes)");
233
+ if (command.some((part) => part.includes("\0"))) throw new Error("process command arguments must not contain NUL bytes");
234
+ if (probe.prompt.length > 16e3) throw new Error("process command exceeds the 16000-character job budget");
235
+ const job = { ...probe };
170
236
  return this.transaction((s) => {
237
+ const existing = s.jobs.find((j) => j.sessionId === PROCESS_SESSION_ID && parseProcessCommand(j)?.managedBy === managedBy);
238
+ if (existing?.state === "running") throw new Error("managed job is currently running; try again after it finishes");
239
+ s.jobs = s.jobs.filter((j) => j !== existing);
171
240
  if (s.jobs.length >= 100) throw new Error("maximum 100 jobs");
172
241
  s.jobs.push(job);
173
242
  return job;
174
243
  });
175
244
  }
245
+ /** Find the managed process job for a manager identity, if present. */
246
+ findProcess(managedBy) {
247
+ return this.read().jobs.find((j) => j.sessionId === PROCESS_SESSION_ID && parseProcessCommand(j)?.managedBy === managedBy);
248
+ }
176
249
  change(id, action, now = Date.now()) {
177
250
  this.transaction((s) => {
178
251
  const j = s.jobs.find((j2) => j2.id === id);
@@ -202,18 +275,41 @@ function complete(job, error, now = Date.now()) {
202
275
  }
203
276
  job.state = "ready";
204
277
  delete job.error;
278
+ if (job.remaining !== void 0) {
279
+ job.remaining -= 1;
280
+ if (job.remaining <= 0) {
281
+ job.enabled = false;
282
+ job.next = "at" in job.schedule ? null : job.next;
283
+ return;
284
+ }
285
+ }
205
286
  job.next = "at" in job.schedule ? null : nextTime(job.schedule, Math.max(now, job.occurrence ?? now));
206
287
  if (job.next === null) job.enabled = false;
207
288
  }
289
+ function completeInterrupted(job, error, now = Date.now()) {
290
+ if (!isProcessJob(job)) {
291
+ complete(job, error, now);
292
+ return;
293
+ }
294
+ if ("at" in job.schedule) {
295
+ complete(job, `interrupted at shutdown; one-shot outcome uncertain \u2014 ${error}`.slice(0, 500), now);
296
+ return;
297
+ }
298
+ job.state = "ready";
299
+ job.error = `interrupted at shutdown; retried automatically: ${error.slice(0, 400)}`;
300
+ job.next = nextTime(job.schedule, Math.max(now, job.occurrence ?? now));
301
+ if (job.next === null) job.enabled = false;
302
+ }
208
303
 
209
304
  // builtin/extensions/cron/runtime.ts
210
- import * as fs2 from "node:fs";
305
+ import * as fs3 from "node:fs";
211
306
  import * as path3 from "node:path";
212
307
  import { randomUUID as randomUUID3 } from "node:crypto";
213
308
 
214
309
  // builtin/extensions/cron/worker.ts
215
310
  import { spawn } from "node:child_process";
216
311
  import { randomUUID as randomUUID2 } from "node:crypto";
312
+ import * as fs2 from "node:fs";
217
313
  import * as path2 from "node:path";
218
314
  import { StringDecoder } from "node:string_decoder";
219
315
  function runWorker(job, signal, cli = process.argv[1], configDir) {
@@ -315,6 +411,128 @@ function runWorker(job, signal, cli = process.argv[1], configDir) {
315
411
  if (signal.aborted) stop();
316
412
  });
317
413
  }
414
+ function processJobEnv(configDir) {
415
+ const allow = ["PATH", "PATHEXT", "SYSTEMROOT", "SYSTEMDRIVE", "COMSPEC", "LANG", "LC_ALL", "TERM", "TMPDIR", "TEMP", "TMP", "HOME", "USERPROFILE", "XDG_CONFIG_HOME", "XDG_CACHE_HOME"];
416
+ const env = {};
417
+ for (const key of allow) {
418
+ const value = process.env[key];
419
+ if (value !== void 0) env[key] = value;
420
+ }
421
+ env.PIE_CRON_ROLE = "worker";
422
+ if (configDir) env.PIE_CODING_AGENT_DIR = configDir;
423
+ return env;
424
+ }
425
+ var ProcessWorkerCancelled = class extends Error {
426
+ aborted = true;
427
+ constructor(message) {
428
+ super(message);
429
+ this.name = "ProcessWorkerCancelled";
430
+ }
431
+ };
432
+ function runProcessWorker(job, command, cwd, deadlineMs = 30 * 60 * 1e3, logDir, signal, configDir) {
433
+ return new Promise((resolve3, reject) => {
434
+ const dir = logDir ?? path2.join(process.cwd(), "cron");
435
+ const logFile = path2.join(dir, "process.log");
436
+ try {
437
+ fs2.mkdirSync(dir, { recursive: true, mode: 448 });
438
+ } catch {
439
+ }
440
+ const stamp = (/* @__PURE__ */ new Date()).toISOString();
441
+ const header = `[${stamp}] job=${job.id} cwd=${cwd} cmd=${JSON.stringify(command.command)}
442
+ `;
443
+ try {
444
+ fs2.appendFileSync(logFile, header);
445
+ } catch {
446
+ }
447
+ let out;
448
+ try {
449
+ out = fs2.openSync(logFile, "a");
450
+ } catch {
451
+ }
452
+ let child;
453
+ let settled = false;
454
+ let failure;
455
+ let hostCancelled = false;
456
+ let killTimer;
457
+ let deadlineTimer;
458
+ const ABORT_FAILURE = "worker interrupted; outcome uncertain";
459
+ const terminate = () => {
460
+ if (settled) return;
461
+ try {
462
+ child?.kill();
463
+ } catch {
464
+ }
465
+ killTimer ??= setTimeout(() => {
466
+ try {
467
+ child?.kill("SIGKILL");
468
+ } catch {
469
+ }
470
+ }, 5e3);
471
+ killTimer.unref();
472
+ };
473
+ const stop = () => {
474
+ if (settled) return;
475
+ hostCancelled = true;
476
+ failure ??= ABORT_FAILURE;
477
+ terminate();
478
+ };
479
+ try {
480
+ child = spawn(command.command[0], command.command.slice(1), {
481
+ cwd,
482
+ env: processJobEnv(configDir),
483
+ stdio: ["ignore", out ?? "ignore", out ?? "ignore"],
484
+ windowsHide: true
485
+ });
486
+ } catch (error) {
487
+ if (out !== void 0) {
488
+ try {
489
+ fs2.closeSync(out);
490
+ } catch {
491
+ }
492
+ }
493
+ reject(error instanceof Error ? error : new Error(String(error)));
494
+ return;
495
+ }
496
+ const cleanup = () => {
497
+ if (deadlineTimer !== void 0) clearTimeout(deadlineTimer);
498
+ if (killTimer !== void 0) clearTimeout(killTimer);
499
+ signal?.removeEventListener("abort", stop);
500
+ if (out !== void 0) {
501
+ try {
502
+ fs2.closeSync(out);
503
+ } catch {
504
+ }
505
+ }
506
+ };
507
+ deadlineTimer = setTimeout(() => {
508
+ if (settled) return;
509
+ failure = `process job exceeded ${deadlineMs}ms`;
510
+ terminate();
511
+ }, deadlineMs);
512
+ deadlineTimer.unref();
513
+ if (signal?.aborted) stop();
514
+ else signal?.addEventListener("abort", stop, { once: true });
515
+ child.on("error", (error) => {
516
+ failure = error.message;
517
+ });
518
+ child.on("close", (code) => {
519
+ if (settled) return;
520
+ settled = true;
521
+ cleanup();
522
+ try {
523
+ fs2.appendFileSync(logFile, `[${(/* @__PURE__ */ new Date()).toISOString()}] job=${job.id} exit=${code}${failure ? ` error=${failure}` : ""}
524
+ `);
525
+ } catch {
526
+ }
527
+ if (hostCancelled) {
528
+ reject(new ProcessWorkerCancelled(failure ?? `cancelled (exit ${code})`));
529
+ return;
530
+ }
531
+ if (failure || code !== 0) reject(new Error(failure ?? `process exited ${code}`));
532
+ else resolve3();
533
+ });
534
+ });
535
+ }
318
536
 
319
537
  // builtin/extensions/cron/runtime.ts
320
538
  var delay = (ms) => new Promise((resolve3) => setTimeout(resolve3, ms));
@@ -330,17 +548,19 @@ function defaultProcessAlive(pid) {
330
548
  }
331
549
  }
332
550
  var Runtime = class {
333
- constructor(ctx, store, execute = runWorker, processAlive = defaultProcessAlive) {
551
+ constructor(ctx, store, execute = runWorker, processAlive = defaultProcessAlive, executeProcess = runProcessWorker) {
334
552
  this.ctx = ctx;
335
553
  this.store = store;
336
554
  this.execute = execute;
337
555
  this.processAlive = processAlive;
338
- this.cwd = fs2.realpathSync(ctx.cwd);
556
+ this.executeProcess = executeProcess;
557
+ this.cwd = fs3.realpathSync(ctx.cwd);
339
558
  }
340
559
  ctx;
341
560
  store;
342
561
  execute;
343
562
  processAlive;
563
+ executeProcess;
344
564
  id = randomUUID3();
345
565
  sessionId = null;
346
566
  leader = false;
@@ -351,6 +571,7 @@ var Runtime = class {
351
571
  polling = false;
352
572
  timer;
353
573
  abort = new AbortController();
574
+ processAbort = new AbortController();
354
575
  worker;
355
576
  cwd;
356
577
  notices = /* @__PURE__ */ new Set();
@@ -384,7 +605,7 @@ var Runtime = class {
384
605
  this.timer.unref();
385
606
  }
386
607
  markUnsafe() {
387
- fs2.mkdirSync(path3.join(this.store.dir, "unsafe.lock"), { recursive: true, mode: 448 });
608
+ fs3.mkdirSync(path3.join(this.store.dir, "unsafe.lock"), { recursive: true, mode: 448 });
388
609
  }
389
610
  coordinatorDir() {
390
611
  return path3.join(this.store.dir, "scheduler.lock");
@@ -394,9 +615,9 @@ var Runtime = class {
394
615
  }
395
616
  readCoordinatorOwner() {
396
617
  try {
397
- const file = this.coordinatorOwnerFile(), stat = fs2.lstatSync(file);
618
+ const file = this.coordinatorOwnerFile(), stat = fs3.lstatSync(file);
398
619
  if (!stat.isFile() || stat.size > 4096) return void 0;
399
- const raw = fs2.readFileSync(file, "utf8"), value = JSON.parse(raw);
620
+ const raw = fs3.readFileSync(file, "utf8"), value = JSON.parse(raw);
400
621
  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;
401
622
  return { value, raw };
402
623
  } catch {
@@ -418,26 +639,26 @@ var Runtime = class {
418
639
  }
419
640
  withCoordinatorMutex(fn) {
420
641
  const lock = path3.join(this.store.dir, "write.lock");
421
- fs2.mkdirSync(lock, { mode: 448 });
642
+ fs3.mkdirSync(lock, { mode: 448 });
422
643
  try {
423
644
  return fn();
424
645
  } finally {
425
- fs2.rmdirSync(lock);
646
+ fs3.rmdirSync(lock);
426
647
  }
427
648
  }
428
649
  acquireCoordinator() {
429
650
  const dir = this.coordinatorDir();
430
- fs2.mkdirSync(dir, { mode: 448 });
651
+ fs3.mkdirSync(dir, { mode: 448 });
431
652
  const owner = { version: 1, pid: process.pid, instanceId: this.id, createdAt: Date.now() };
432
653
  try {
433
- fs2.writeFileSync(this.coordinatorOwnerFile(), JSON.stringify(owner), { mode: 384, flag: "wx" });
654
+ fs3.writeFileSync(this.coordinatorOwnerFile(), JSON.stringify(owner), { mode: 384, flag: "wx" });
434
655
  } catch (error) {
435
656
  try {
436
- fs2.unlinkSync(this.coordinatorOwnerFile());
657
+ fs3.unlinkSync(this.coordinatorOwnerFile());
437
658
  } catch {
438
659
  }
439
660
  try {
440
- fs2.rmdirSync(dir);
661
+ fs3.rmdirSync(dir);
441
662
  } catch {
442
663
  }
443
664
  throw error;
@@ -465,16 +686,16 @@ var Runtime = class {
465
686
  const latest = this.readCoordinatorOwner();
466
687
  if (!latest || latest.raw !== held.raw) return false;
467
688
  try {
468
- fs2.unlinkSync(this.coordinatorOwnerFile());
469
- fs2.rmdirSync(this.coordinatorDir());
689
+ fs3.unlinkSync(this.coordinatorOwnerFile());
690
+ fs3.rmdirSync(this.coordinatorDir());
470
691
  return true;
471
692
  } catch {
472
693
  return false;
473
694
  }
474
695
  }
475
696
  releaseCoordinator() {
476
- fs2.rmSync(this.coordinatorOwnerFile(), { force: true });
477
- fs2.rmdirSync(this.coordinatorDir());
697
+ fs3.rmSync(this.coordinatorOwnerFile(), { force: true });
698
+ fs3.rmdirSync(this.coordinatorDir());
478
699
  this.leader = false;
479
700
  }
480
701
  persistOwner(sessionId) {
@@ -508,6 +729,7 @@ var Runtime = class {
508
729
  if (!this.stopped && generation === this.binding) this.register(sessionId);
509
730
  }
510
731
  notify(job) {
732
+ if (isProcessJob(job)) return;
511
733
  if (job.sessionId !== this.sessionId || !job.error) return;
512
734
  const key = job.id + job.error;
513
735
  if (!this.notices.has(key)) {
@@ -516,11 +738,18 @@ var Runtime = class {
516
738
  }
517
739
  }
518
740
  flushCompletions() {
519
- for (const [id, error] of this.completions) {
741
+ for (const [id, entry] of this.completions) {
742
+ const { error, cancelled } = entry;
520
743
  try {
521
744
  this.store.transaction((state) => {
522
745
  const job = state.jobs.find((item) => item.id === id);
523
- if (job?.state === "running") complete(job, error);
746
+ if (job?.state === "running") {
747
+ if (cancelled && error !== void 0 && isProcessJob(job) && job.target === "worker") {
748
+ completeInterrupted(job, error);
749
+ } else {
750
+ complete(job, error);
751
+ }
752
+ }
524
753
  });
525
754
  this.completions.delete(id);
526
755
  } catch (failure) {
@@ -529,14 +758,15 @@ var Runtime = class {
529
758
  }
530
759
  }
531
760
  }
532
- finish(id, error) {
533
- this.completions.set(id, error);
761
+ finish(id, error, cancelled) {
762
+ this.completions.set(id, { error, cancelled });
534
763
  this.flushCompletions();
535
764
  }
536
765
  async poll(now = Date.now()) {
537
766
  if (this.stopped || this.polling || !this.initialized) return;
538
- if (fs2.existsSync(path3.join(this.store.dir, "unsafe.lock"))) {
767
+ if (fs3.existsSync(path3.join(this.store.dir, "unsafe.lock"))) {
539
768
  this.abort.abort();
769
+ this.processAbort.abort();
540
770
  this.ctx.ui.setStatus?.("cron", void 0);
541
771
  return;
542
772
  }
@@ -559,6 +789,7 @@ var Runtime = class {
559
789
  }
560
790
  });
561
791
  let delivery, launch;
792
+ let processLaunch;
562
793
  this.store.transaction((state2) => {
563
794
  if (this.recovering) {
564
795
  for (const job of state2.jobs) {
@@ -569,6 +800,7 @@ var Runtime = class {
569
800
  }
570
801
  state2.owners[this.id] = { sessionId: this.sessionId, cwd: this.cwd, busy: !this.ctx.isIdle() };
571
802
  for (const job of state2.jobs) {
803
+ if (isProcessJob(job)) continue;
572
804
  const owners = Object.entries(state2.owners).filter(([, owner]) => owner.sessionId === job.sessionId);
573
805
  if (this.leader && job.state === "running" && job.target === "worker" && owners.length) this.abort.abort();
574
806
  if (job.enabled && owners.length > 1 && job.state !== "running") complete(job, "duplicate participating session owners; close duplicate and resume job");
@@ -599,6 +831,13 @@ var Runtime = class {
599
831
  if (this.leader && !state2.jobs.some((job) => job.state === "running")) {
600
832
  const due = state2.jobs.filter((job) => job.enabled && job.state === "ready" && job.next !== null && job.next <= now).sort((a, b) => a.next - b.next);
601
833
  for (const job of due) {
834
+ if (isProcessJob(job)) {
835
+ job.state = "running";
836
+ job.occurrence = job.next;
837
+ job.target = "worker";
838
+ processLaunch = job;
839
+ break;
840
+ }
602
841
  if (state2.jobs.some((other) => other.enabled && other.sessionId === job.sessionId && other.state === "blocked")) continue;
603
842
  const owners = Object.entries(state2.owners).filter(([, owner]) => owner.sessionId === job.sessionId);
604
843
  if (owners.length > 1) {
@@ -621,7 +860,7 @@ var Runtime = class {
621
860
  this.recovering = false;
622
861
  if (delivery) {
623
862
  const job = delivery;
624
- const scope = this.ctx.beginUserInput?.(() => !this.stopped && this.ready && this.sessionId === job.sessionId && !fs2.existsSync(path3.join(this.store.dir, "unsafe.lock")) && Object.values(this.store.read().owners).filter((owner) => owner.sessionId === job.sessionId).length === 1);
863
+ const scope = this.ctx.beginUserInput?.(() => !this.stopped && this.ready && this.sessionId === job.sessionId && !fs3.existsSync(path3.join(this.store.dir, "unsafe.lock")) && Object.values(this.store.read().owners).filter((owner) => owner.sessionId === job.sessionId).length === 1);
625
864
  let error;
626
865
  const content = `[Cron job=${job.id} scheduledAt=${job.occurrence}]
627
866
  ${job.prompt}`;
@@ -641,7 +880,7 @@ ${job.prompt}`;
641
880
  if (launch) {
642
881
  const job = launch;
643
882
  const latest = this.store.read();
644
- if (this.stopped || fs2.existsSync(path3.join(this.store.dir, "unsafe.lock")) || Object.values(latest.owners).some((owner) => owner.sessionId === job.sessionId)) {
883
+ if (this.stopped || fs3.existsSync(path3.join(this.store.dir, "unsafe.lock")) || Object.values(latest.owners).some((owner) => owner.sessionId === job.sessionId)) {
645
884
  this.finish(job.id, "ownership changed before worker launch; inspect before resuming");
646
885
  return;
647
886
  }
@@ -653,8 +892,19 @@ ${job.prompt}`;
653
892
  }
654
893
  });
655
894
  }
895
+ if (processLaunch) {
896
+ const job = processLaunch;
897
+ const command = parseProcessCommand(job);
898
+ this.processAbort = new AbortController();
899
+ this.worker = this.executeProcess(job, command, job.cwd, 30 * 60 * 1e3, this.store.dir, this.processAbort.signal, path3.dirname(this.store.dir)).then(() => this.finish(job.id), (error) => this.finish(job.id, String(error), error?.aborted === true)).catch(() => {
900
+ try {
901
+ this.markUnsafe();
902
+ } catch {
903
+ }
904
+ });
905
+ }
656
906
  const state = this.store.read(), enabled = state.jobs.filter((job) => job.enabled);
657
- this.ctx.ui.setStatus?.("cron", this.leader && enabled.some((job) => job.sessionId === this.sessionId) ? `cron: ${enabled.length} enabled, ${enabled.filter((job) => job.state === "blocked").length} blocked` : void 0);
907
+ this.ctx.ui.setStatus?.("cron", this.leader && enabled.some((job) => job.sessionId === this.sessionId || isProcessJob(job)) ? `cron: ${enabled.length} enabled, ${enabled.filter((job) => job.state === "blocked").length} blocked` : void 0);
658
908
  for (const job of state.jobs) this.notify(job);
659
909
  } catch {
660
910
  this.ctx.ui.setStatus?.("cron", void 0);
@@ -666,14 +916,21 @@ ${job.prompt}`;
666
916
  this.stopped = true;
667
917
  clearInterval(this.timer);
668
918
  this.abort.abort();
919
+ this.processAbort.abort();
669
920
  await this.worker;
670
921
  while (this.polling) await delay(10);
671
922
  for (let attempt = 0; ; attempt++) {
672
923
  try {
673
924
  this.store.transaction((state) => {
674
- for (const [id, error] of this.completions) {
925
+ for (const [id, entry] of this.completions) {
675
926
  const job = state.jobs.find((item) => item.id === id);
676
- if (job?.state === "running") complete(job, error);
927
+ if (job?.state === "running") {
928
+ if (entry.cancelled && entry.error !== void 0 && isProcessJob(job) && job.target === "worker") {
929
+ completeInterrupted(job, entry.error);
930
+ } else {
931
+ complete(job, entry.error);
932
+ }
933
+ }
677
934
  }
678
935
  delete state.owners[this.id];
679
936
  for (const job of state.jobs) {
@@ -737,7 +994,7 @@ function cron(ctx) {
737
994
  if (!state.jobs.some((j) => j.sessionId === runtime.sessionId && (j.enabled || j.state === "running"))) return;
738
995
  const duplicates = Object.values(state.owners).filter((o) => o.sessionId === runtime.sessionId).length > 1;
739
996
  const worker = state.jobs.some((j) => j.sessionId === runtime.sessionId && j.state === "running" && j.target === "worker");
740
- if (!startupError && runtime.ready && !duplicates && !worker && !fs3.existsSync(path4.join(store.dir, "unsafe.lock"))) return;
997
+ if (!startupError && runtime.ready && !duplicates && !worker && !fs4.existsSync(path4.join(store.dir, "unsafe.lock"))) return;
741
998
  } catch {
742
999
  }
743
1000
  ctx.ui.notify("cron: session ownership is uncertain or duplicated; input blocked. Close the duplicate/worker and inspect /tools/cron.", "warning");
@@ -758,12 +1015,12 @@ function cron(ctx) {
758
1015
  });
759
1016
  const run = (action, id, prompt, schedule) => {
760
1017
  if (startupError && action !== "list") throw new Error(`cron unavailable: ${startupError}; see docs/cron.md recovery`);
761
- if (action === "list") return JSON.stringify({ ...store.read(), recoveryRequired: fs3.existsSync(path4.join(store.dir, "unsafe.lock")), coordinatorPresent: fs3.existsSync(path4.join(store.dir, "scheduler.lock")) }, null, 2);
1018
+ if (action === "list") return JSON.stringify({ ...store.read(), recoveryRequired: fs4.existsSync(path4.join(store.dir, "unsafe.lock")), coordinatorPresent: fs4.existsSync(path4.join(store.dir, "scheduler.lock")) }, null, 2);
762
1019
  if (action === "add") {
763
1020
  if (!runtime.ready || !runtime.sessionId) throw new Error("wait for an existing session to load and register");
764
1021
  return JSON.stringify({
765
1022
  job: store.add(runtime.sessionId, ctx.cwd, prompt, schedule),
766
- note: "Saved. The original session/cwd will be resumed automatically. Keep at least one cron-enabled Pie open; no execution while all are closed or the computer sleeps."
1023
+ 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 delivery cannot be paused/removed until its turn settles (next poll after idle). Keep at least one cron-enabled Pie open; no execution while all are closed or the computer sleeps."
767
1024
  });
768
1025
  }
769
1026
  if (action === "pause" || action === "resume" || action === "remove") {
@@ -785,8 +1042,8 @@ function cron(ctx) {
785
1042
  ctx.registerTool({
786
1043
  name: "cron_manage",
787
1044
  label: "Cron",
788
- description: "Manage persistent scheduled prompts bound to THIS existing session and cwd. No new sessions. Actions list/add/pause/resume/remove. every is seconds (minimum 60), at is ISO with timezone, cron is five numeric UTC fields. Missed intervals coalesce; blocked/uncertain tasks require human review before resume.",
789
- 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 }) }), Type.Object({ cron: Type.String({ maxLength: 256 }) })])) }),
1045
+ 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 fail with "job is running" while a delivery is in flight; retry after the delivered turn settles.',
1046
+ 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 })) })])) }),
790
1047
  risk: { riskClass: "external_side_effect", permissionScope: "host", availableInPlanMode: false, requiresPermission: true, externalSideEffect: true, allowedForSubagentByDefault: false, concurrencySafe: false },
791
1048
  execute: async (args) => {
792
1049
  try {
@@ -809,6 +1066,9 @@ function cron(ctx) {
809
1066
  });
810
1067
  }
811
1068
  export {
1069
+ PROCESS_SESSION_ID,
1070
+ Store,
812
1071
  configPath,
813
- cron as default
1072
+ cron as default,
1073
+ parseProcessCommand
814
1074
  };