@cydm/pie 2.8.0 → 3.0.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.
Files changed (41) hide show
  1. package/README.md +18 -0
  2. package/dist/builtin/extensions/ask-user/index.js +4 -3
  3. package/dist/builtin/extensions/changelog/index.js +2 -2
  4. package/dist/builtin/extensions/cron/index.js +430 -43
  5. package/dist/builtin/extensions/document-attachments/index.js +1 -1
  6. package/dist/builtin/extensions/herdr-agent-state/index.js +2 -2
  7. package/dist/builtin/extensions/im-forward/index.js +13 -2
  8. package/dist/builtin/extensions/memory/index.js +277 -83
  9. package/dist/builtin/extensions/memory/package.json +2 -1
  10. package/dist/builtin/extensions/plan-mode/index.js +4 -3
  11. package/dist/builtin/extensions/subagent/index.js +7 -6
  12. package/dist/builtin/extensions/todo/index.js +4 -3
  13. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-bridge.js +106 -2
  14. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-cli.js +1 -0
  15. package/dist/builtin/skills/chrome-devtools-axi/chrome-devtools-axi-runtime.js +1 -1
  16. package/dist/builtin/skills/chrome-devtools-axi/{chunk-BNSAEVRT.js → chunk-WOGAQ4P5.js} +2 -2
  17. package/dist/builtin/skills/chrome-devtools-axi/{cli-AO2ZTPRM.js → cli-CHC7XYFU.js} +27 -3
  18. package/dist/builtin/skills/computer-use-axi/computer-use-axi-broker.js +8 -3
  19. package/dist/builtin/skills/computer-use-axi/computer-use-axi-cli.js +1 -0
  20. package/dist/builtin/skills/computer-use-axi/computer-use-axi-runtime.js +6 -1
  21. package/dist/builtin/skills/computer-use-axi/scripts/setup-helper.mjs +6 -2
  22. package/dist/builtin/skills/tui-use/tui-use-daemon.cjs +130 -9
  23. package/dist/chunks/auth-storage-3EGM3VTK.js +13 -0
  24. package/dist/chunks/{chunk-JNOFHHLZ.js → chunk-3BC5KGDQ.js} +383 -185
  25. package/dist/chunks/chunk-3FRKOFSP.js +9667 -0
  26. package/dist/chunks/chunk-6DNYGVZP.js +278 -0
  27. package/dist/chunks/{chunk-LJXHECZ7.js → chunk-7FEPQHYX.js} +13867 -19759
  28. package/dist/chunks/{chunk-NEES4EBX.js → chunk-BUDXV3TR.js} +28 -18
  29. package/dist/chunks/{chunk-HGC25NYB.js → chunk-GH4VW2OT.js} +1 -1
  30. package/dist/chunks/{chunk-5353DEEC.js → chunk-ILUHTKF3.js} +20 -1
  31. package/dist/chunks/chunk-OEQYEYB3.js +299 -0
  32. package/dist/chunks/chunk-YRR6C43W.js +1740 -0
  33. package/dist/chunks/config-74AUVDLT.js +46 -0
  34. package/dist/chunks/model-registry-LI5THXV4.js +17 -0
  35. package/dist/chunks/src-66XSMIAM.js +134 -0
  36. package/dist/chunks/src-AE3OCAE6.js +431 -0
  37. package/dist/chunks/src-RVTDUSPJ.js +293 -0
  38. package/dist/chunks/{src-5XOKRS6F.js → src-YG5M2H44.js} +2 -2
  39. package/dist/chunks/{test-stream-5SDHKKDB.js → test-stream-JBWXKOQA.js} +1 -1
  40. package/dist/cli.js +1455 -2358
  41. package/package.json +4 -4
@@ -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
@@ -70,6 +70,20 @@ function nextTime(s, after) {
70
70
  }
71
71
 
72
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
+ }
73
87
  var Store = class {
74
88
  constructor(dir) {
75
89
  this.dir = dir;
@@ -86,16 +100,155 @@ var Store = class {
86
100
  * stale bytes over a newer foreign save. */
87
101
  lastSavedContent;
88
102
  transaction(fn) {
89
- const lock = path.join(this.dir, "write.lock");
90
- fs.mkdirSync(lock, { mode: 448 });
91
- try {
103
+ return this.withWriteLock(() => {
92
104
  this.calibrateCache();
93
105
  const state = this.read();
94
106
  const result = fn(state);
95
107
  this.save(state);
96
108
  return result;
109
+ });
110
+ }
111
+ /** Run fn under the cross-process write mutex. Also used for coordinator
112
+ * election/release, which never nest a state transaction. */
113
+ withWriteLock(fn) {
114
+ const lock = path.join(this.dir, "write.lock");
115
+ const token = this.acquireWriteLock(lock);
116
+ try {
117
+ return fn();
97
118
  } finally {
119
+ this.releaseWriteLock(lock, token);
120
+ }
121
+ }
122
+ /** Mutex protocol (generation-safe; no ABA / no TOCTOU on the canonical path):
123
+ * - Acquisition builds a fully-formed candidate dir `write.lock.acquire.<uuid>`
124
+ * containing our `held.<uuid>` entry (pid), then atomically RENAMES it onto
125
+ * the canonical `write.lock`. POSIX rename can displace an EMPTY existing
126
+ * directory (a releasing holder's post-unlink state, or manual debris); a
127
+ * non-empty target fails (ENOTEMPTY/EEXIST/EPERM). So the canonical path
128
+ * only ever transitions absent→held or empty→held, never live→replaced.
129
+ * - Empty-dir takeover is safe ONLY for release leftovers: a holder unlinks
130
+ * its entry only AFTER leaving its critical section. Manual/legacy empty
131
+ * locks are equally taken over — an empty dir proves no cooperative
132
+ * writer is inside — which replaces the old permanent-deadlock behavior
133
+ * with bounded manual-recovery documented in docs/cron.md (tests updated).
134
+ * - Release: unlink OUR entry, then rmdir if empty. A crash before unlink
135
+ * leaves a dead-pid entry (recoverable); after unlink it leaves an empty
136
+ * dir, which the next contender takes over legitimately.
137
+ * - Crash recovery on contention: every `held.*` entry must record a
138
+ * PROVABLY DEAD pid (ESRCH only); exactly those verified entries are
139
+ * unlinked and the emptied dir removed, then the install retried once.
140
+ * Entries have unique uuid names, so a delayed reclaimer only deletes
141
+ * names it verified — it can never touch a successor's fresh generation.
142
+ * Unreadable/malformed metadata or junk files: fail closed (contention).
143
+ * - `write.lock.acquire.*` debris can only appear from a crash mid-acquire
144
+ * (before the rename); it is inert — the protocol never consults it. */
145
+ acquireWriteLock(lock) {
146
+ const token = randomUUID();
147
+ const candidate = path.join(this.dir, `write.lock.acquire.${token}`);
148
+ try {
149
+ fs.mkdirSync(candidate, { mode: 448 });
150
+ try {
151
+ this.writeHolderEntry(candidate, token);
152
+ } catch (error) {
153
+ try {
154
+ fs.rmSync(candidate, { recursive: true, force: true });
155
+ } catch {
156
+ }
157
+ throw error;
158
+ }
159
+ const deadline = Date.now() + 2e3;
160
+ for (let spin = 0; ; spin++) {
161
+ try {
162
+ fs.renameSync(candidate, lock);
163
+ return token;
164
+ } catch (error) {
165
+ const code = error?.code;
166
+ if (code !== "EEXIST" && code !== "ENOTEMPTY" && code !== "EPERM" && code !== "ENOTDIR") throw error;
167
+ if (Date.now() > deadline) throw this.contentionError(lock);
168
+ try {
169
+ this.retireWriteLock(lock);
170
+ } catch {
171
+ }
172
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 1 + Math.floor(Math.random() * 3));
173
+ }
174
+ }
175
+ } finally {
176
+ try {
177
+ fs.rmSync(candidate, { recursive: true, force: true });
178
+ } catch {
179
+ }
180
+ }
181
+ }
182
+ writeHolderEntry(dir, token) {
183
+ fs.writeFileSync(path.join(dir, `held.${token}`), JSON.stringify({ version: 1, pid: process.pid, createdAt: Date.now() }), { mode: 384, flag: "wx" });
184
+ }
185
+ releaseWriteLock(lock, token) {
186
+ try {
187
+ fs.unlinkSync(path.join(lock, `held.${token}`));
188
+ } catch {
189
+ }
190
+ try {
191
+ const remaining = fs.readdirSync(lock);
192
+ if (remaining.length === 0) fs.rmdirSync(lock);
193
+ } catch {
194
+ }
195
+ }
196
+ contentionError(lock) {
197
+ const error = new Error(`EEXIST: file already exists, mkdir '${lock}'`);
198
+ error.code = "EEXIST";
199
+ error.errno = -17;
200
+ error.syscall = "mkdir";
201
+ error.path = lock;
202
+ return error;
203
+ }
204
+ /** Remove the stale canonical lock so an install can proceed. Returns true
205
+ * when the canonical path is now free for a rename. */
206
+ retireWriteLock(lock) {
207
+ let entries;
208
+ try {
209
+ entries = fs.readdirSync(lock);
210
+ } catch {
211
+ return false;
212
+ }
213
+ const holders = entries.filter((name) => name.startsWith("held."));
214
+ if (holders.length === 0) {
215
+ if (entries.length !== 0) return false;
216
+ try {
217
+ fs.rmdirSync(lock);
218
+ return true;
219
+ } catch {
220
+ return false;
221
+ }
222
+ }
223
+ for (const name of holders) {
224
+ let pid;
225
+ try {
226
+ const parsed = JSON.parse(fs.readFileSync(path.join(lock, name), "utf8"));
227
+ if (parsed?.version !== 1 || !Number.isInteger(parsed.pid) || parsed.pid <= 0) return false;
228
+ pid = parsed.pid;
229
+ } catch {
230
+ return false;
231
+ }
232
+ try {
233
+ process.kill(pid, 0);
234
+ return false;
235
+ } catch (error) {
236
+ if (error?.code !== "ESRCH") return false;
237
+ }
238
+ }
239
+ for (const name of holders) {
240
+ try {
241
+ fs.unlinkSync(path.join(lock, name));
242
+ } catch (error) {
243
+ if (error?.code === "ENOENT") continue;
244
+ return false;
245
+ }
246
+ }
247
+ try {
98
248
  fs.rmdirSync(lock);
249
+ return true;
250
+ } catch {
251
+ return false;
99
252
  }
100
253
  }
101
254
  /** Invalidate the write-skip cache when the on-disk file is not the exact
@@ -123,6 +276,9 @@ var Store = class {
123
276
  const ids = /* @__PURE__ */ new Set();
124
277
  for (const j of s.jobs) {
125
278
  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");
279
+ if (j.sessionId === PROCESS_SESSION_ID) {
280
+ if (!parseProcessCommand(j)) throw new Error("invalid process cron job; manual recovery required");
281
+ }
126
282
  ids.add(j.id);
127
283
  validateSchedule(j.schedule);
128
284
  }
@@ -170,6 +326,7 @@ var Store = class {
170
326
  }
171
327
  add(sessionId, cwd, prompt, schedule, now = Date.now()) {
172
328
  if (!sessionId || sessionId.length > 256) throw new Error("an existing session is required");
329
+ if (sessionId === PROCESS_SESSION_ID) throw new Error("session id is reserved for process jobs");
173
330
  if (typeof prompt !== "string" || !prompt.trim() || prompt.length > 16e3) throw new Error("prompt must contain 1..16000 characters");
174
331
  const validated = validateSchedule(schedule), next = nextTime(validated, now);
175
332
  if (next === null) throw new Error("at must be in the future");
@@ -191,6 +348,43 @@ var Store = class {
191
348
  return job;
192
349
  });
193
350
  }
351
+ /** Register a process job: detached command execution, no session binding.
352
+ * Replaces any existing job from the same manager so `schedule on` is
353
+ * idempotent (one managed job per manager). A RUNNING job is never
354
+ * replaced: removing its reservation would let another execution start
355
+ * while the original worker is still alive (single-outstanding invariant). */
356
+ addProcess(command, managedBy, cwd, schedule, now = Date.now()) {
357
+ const validated = validateSchedule(schedule), next = nextTime(validated, now);
358
+ if (next === null) throw new Error("at must be in the future");
359
+ const count = validated.count;
360
+ const probe = {
361
+ id: randomUUID(),
362
+ sessionId: PROCESS_SESSION_ID,
363
+ cwd: fs.realpathSync(cwd),
364
+ prompt: JSON.stringify({ command, managedBy }),
365
+ schedule: validated,
366
+ enabled: true,
367
+ next,
368
+ state: "ready",
369
+ ...count !== void 0 ? { remaining: count } : {}
370
+ };
371
+ if (!parseProcessCommand(probe)) throw new Error("invalid process command (1..32 args, each 1..4096 chars, no NUL bytes)");
372
+ if (command.some((part) => part.includes("\0"))) throw new Error("process command arguments must not contain NUL bytes");
373
+ if (probe.prompt.length > 16e3) throw new Error("process command exceeds the 16000-character job budget");
374
+ const job = { ...probe };
375
+ return this.transaction((s) => {
376
+ const existing = s.jobs.find((j) => j.sessionId === PROCESS_SESSION_ID && parseProcessCommand(j)?.managedBy === managedBy);
377
+ if (existing?.state === "running") throw new Error("managed job is currently running; try again after it finishes");
378
+ s.jobs = s.jobs.filter((j) => j !== existing);
379
+ if (s.jobs.length >= 100) throw new Error("maximum 100 jobs");
380
+ s.jobs.push(job);
381
+ return job;
382
+ });
383
+ }
384
+ /** Find the managed process job for a manager identity, if present. */
385
+ findProcess(managedBy) {
386
+ return this.read().jobs.find((j) => j.sessionId === PROCESS_SESSION_ID && parseProcessCommand(j)?.managedBy === managedBy);
387
+ }
194
388
  change(id, action, now = Date.now()) {
195
389
  this.transaction((s) => {
196
390
  const j = s.jobs.find((j2) => j2.id === id);
@@ -231,15 +425,30 @@ function complete(job, error, now = Date.now()) {
231
425
  job.next = "at" in job.schedule ? null : nextTime(job.schedule, Math.max(now, job.occurrence ?? now));
232
426
  if (job.next === null) job.enabled = false;
233
427
  }
428
+ function completeInterrupted(job, error, now = Date.now()) {
429
+ if (!isProcessJob(job)) {
430
+ complete(job, error, now);
431
+ return;
432
+ }
433
+ if ("at" in job.schedule) {
434
+ complete(job, `interrupted at shutdown; one-shot outcome uncertain \u2014 ${error}`.slice(0, 500), now);
435
+ return;
436
+ }
437
+ job.state = "ready";
438
+ job.error = `interrupted at shutdown; retried automatically: ${error.slice(0, 400)}`;
439
+ job.next = nextTime(job.schedule, Math.max(now, job.occurrence ?? now));
440
+ if (job.next === null) job.enabled = false;
441
+ }
234
442
 
235
443
  // builtin/extensions/cron/runtime.ts
236
- import * as fs2 from "node:fs";
444
+ import * as fs3 from "node:fs";
237
445
  import * as path3 from "node:path";
238
446
  import { randomUUID as randomUUID3 } from "node:crypto";
239
447
 
240
448
  // builtin/extensions/cron/worker.ts
241
449
  import { spawn } from "node:child_process";
242
450
  import { randomUUID as randomUUID2 } from "node:crypto";
451
+ import * as fs2 from "node:fs";
243
452
  import * as path2 from "node:path";
244
453
  import { StringDecoder } from "node:string_decoder";
245
454
  function runWorker(job, signal, cli = process.argv[1], configDir) {
@@ -341,6 +550,128 @@ function runWorker(job, signal, cli = process.argv[1], configDir) {
341
550
  if (signal.aborted) stop();
342
551
  });
343
552
  }
553
+ function processJobEnv(configDir) {
554
+ const allow = ["PATH", "PATHEXT", "SYSTEMROOT", "SYSTEMDRIVE", "COMSPEC", "LANG", "LC_ALL", "TERM", "TMPDIR", "TEMP", "TMP", "HOME", "USERPROFILE", "XDG_CONFIG_HOME", "XDG_CACHE_HOME"];
555
+ const env = {};
556
+ for (const key of allow) {
557
+ const value = process.env[key];
558
+ if (value !== void 0) env[key] = value;
559
+ }
560
+ env.PIE_CRON_ROLE = "worker";
561
+ if (configDir) env.PIE_CODING_AGENT_DIR = configDir;
562
+ return env;
563
+ }
564
+ var ProcessWorkerCancelled = class extends Error {
565
+ aborted = true;
566
+ constructor(message) {
567
+ super(message);
568
+ this.name = "ProcessWorkerCancelled";
569
+ }
570
+ };
571
+ function runProcessWorker(job, command, cwd, deadlineMs = 30 * 60 * 1e3, logDir, signal, configDir) {
572
+ return new Promise((resolve3, reject) => {
573
+ const dir = logDir ?? path2.join(process.cwd(), "cron");
574
+ const logFile = path2.join(dir, "process.log");
575
+ try {
576
+ fs2.mkdirSync(dir, { recursive: true, mode: 448 });
577
+ } catch {
578
+ }
579
+ const stamp = (/* @__PURE__ */ new Date()).toISOString();
580
+ const header = `[${stamp}] job=${job.id} cwd=${cwd} cmd=${JSON.stringify(command.command)}
581
+ `;
582
+ try {
583
+ fs2.appendFileSync(logFile, header);
584
+ } catch {
585
+ }
586
+ let out;
587
+ try {
588
+ out = fs2.openSync(logFile, "a");
589
+ } catch {
590
+ }
591
+ let child;
592
+ let settled = false;
593
+ let failure;
594
+ let hostCancelled = false;
595
+ let killTimer;
596
+ let deadlineTimer;
597
+ const ABORT_FAILURE = "worker interrupted; outcome uncertain";
598
+ const terminate = () => {
599
+ if (settled) return;
600
+ try {
601
+ child?.kill();
602
+ } catch {
603
+ }
604
+ killTimer ??= setTimeout(() => {
605
+ try {
606
+ child?.kill("SIGKILL");
607
+ } catch {
608
+ }
609
+ }, 5e3);
610
+ killTimer.unref();
611
+ };
612
+ const stop = () => {
613
+ if (settled) return;
614
+ hostCancelled = true;
615
+ failure ??= ABORT_FAILURE;
616
+ terminate();
617
+ };
618
+ try {
619
+ child = spawn(command.command[0], command.command.slice(1), {
620
+ cwd,
621
+ env: processJobEnv(configDir),
622
+ stdio: ["ignore", out ?? "ignore", out ?? "ignore"],
623
+ windowsHide: true
624
+ });
625
+ } catch (error) {
626
+ if (out !== void 0) {
627
+ try {
628
+ fs2.closeSync(out);
629
+ } catch {
630
+ }
631
+ }
632
+ reject(error instanceof Error ? error : new Error(String(error)));
633
+ return;
634
+ }
635
+ const cleanup = () => {
636
+ if (deadlineTimer !== void 0) clearTimeout(deadlineTimer);
637
+ if (killTimer !== void 0) clearTimeout(killTimer);
638
+ signal?.removeEventListener("abort", stop);
639
+ if (out !== void 0) {
640
+ try {
641
+ fs2.closeSync(out);
642
+ } catch {
643
+ }
644
+ }
645
+ };
646
+ deadlineTimer = setTimeout(() => {
647
+ if (settled) return;
648
+ failure = `process job exceeded ${deadlineMs}ms`;
649
+ terminate();
650
+ }, deadlineMs);
651
+ deadlineTimer.unref();
652
+ if (signal?.aborted) stop();
653
+ else signal?.addEventListener("abort", stop, { once: true });
654
+ child.on("error", (error) => {
655
+ failure = error.message;
656
+ });
657
+ child.on("close", (code) => {
658
+ if (settled) return;
659
+ settled = true;
660
+ cleanup();
661
+ try {
662
+ fs2.appendFileSync(logFile, `[${(/* @__PURE__ */ new Date()).toISOString()}] job=${job.id} exit=${code}${failure ? ` error=${failure}` : ""}
663
+ `);
664
+ } catch {
665
+ }
666
+ if (hostCancelled) {
667
+ reject(new ProcessWorkerCancelled(failure ?? `cancelled (exit ${code})`));
668
+ return;
669
+ }
670
+ if (failure || code !== 0) reject(new Error(failure ?? `process exited ${code}`));
671
+ else resolve3();
672
+ });
673
+ });
674
+ }
344
675
 
345
676
  // builtin/extensions/cron/runtime.ts
346
677
  var delay = (ms) => new Promise((resolve3) => setTimeout(resolve3, ms));
@@ -356,17 +687,19 @@ function defaultProcessAlive(pid) {
356
687
  }
357
688
  }
358
689
  var Runtime = class {
359
- constructor(ctx, store, execute = runWorker, processAlive = defaultProcessAlive) {
690
+ constructor(ctx, store, execute = runWorker, processAlive = defaultProcessAlive, executeProcess = runProcessWorker) {
360
691
  this.ctx = ctx;
361
692
  this.store = store;
362
693
  this.execute = execute;
363
694
  this.processAlive = processAlive;
364
- this.cwd = fs2.realpathSync(ctx.cwd);
695
+ this.executeProcess = executeProcess;
696
+ this.cwd = fs3.realpathSync(ctx.cwd);
365
697
  }
366
698
  ctx;
367
699
  store;
368
700
  execute;
369
701
  processAlive;
702
+ executeProcess;
370
703
  id = randomUUID3();
371
704
  sessionId = null;
372
705
  leader = false;
@@ -377,6 +710,7 @@ var Runtime = class {
377
710
  polling = false;
378
711
  timer;
379
712
  abort = new AbortController();
713
+ processAbort = new AbortController();
380
714
  worker;
381
715
  cwd;
382
716
  notices = /* @__PURE__ */ new Set();
@@ -410,7 +744,7 @@ var Runtime = class {
410
744
  this.timer.unref();
411
745
  }
412
746
  markUnsafe() {
413
- fs2.mkdirSync(path3.join(this.store.dir, "unsafe.lock"), { recursive: true, mode: 448 });
747
+ fs3.mkdirSync(path3.join(this.store.dir, "unsafe.lock"), { recursive: true, mode: 448 });
414
748
  }
415
749
  coordinatorDir() {
416
750
  return path3.join(this.store.dir, "scheduler.lock");
@@ -420,9 +754,9 @@ var Runtime = class {
420
754
  }
421
755
  readCoordinatorOwner() {
422
756
  try {
423
- const file = this.coordinatorOwnerFile(), stat = fs2.lstatSync(file);
757
+ const file = this.coordinatorOwnerFile(), stat = fs3.lstatSync(file);
424
758
  if (!stat.isFile() || stat.size > 4096) return void 0;
425
- const raw = fs2.readFileSync(file, "utf8"), value = JSON.parse(raw);
759
+ const raw = fs3.readFileSync(file, "utf8"), value = JSON.parse(raw);
426
760
  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;
427
761
  return { value, raw };
428
762
  } catch {
@@ -443,27 +777,21 @@ var Runtime = class {
443
777
  this.ctx.ui.notify("cron: coordinator lock metadata is missing or invalid; scheduling is paused. See docs/cron.md offline recovery.", "warning");
444
778
  }
445
779
  withCoordinatorMutex(fn) {
446
- const lock = path3.join(this.store.dir, "write.lock");
447
- fs2.mkdirSync(lock, { mode: 448 });
448
- try {
449
- return fn();
450
- } finally {
451
- fs2.rmdirSync(lock);
452
- }
780
+ return this.store.withWriteLock(() => fn());
453
781
  }
454
782
  acquireCoordinator() {
455
783
  const dir = this.coordinatorDir();
456
- fs2.mkdirSync(dir, { mode: 448 });
784
+ fs3.mkdirSync(dir, { mode: 448 });
457
785
  const owner = { version: 1, pid: process.pid, instanceId: this.id, createdAt: Date.now() };
458
786
  try {
459
- fs2.writeFileSync(this.coordinatorOwnerFile(), JSON.stringify(owner), { mode: 384, flag: "wx" });
787
+ fs3.writeFileSync(this.coordinatorOwnerFile(), JSON.stringify(owner), { mode: 384, flag: "wx" });
460
788
  } catch (error) {
461
789
  try {
462
- fs2.unlinkSync(this.coordinatorOwnerFile());
790
+ fs3.unlinkSync(this.coordinatorOwnerFile());
463
791
  } catch {
464
792
  }
465
793
  try {
466
- fs2.rmdirSync(dir);
794
+ fs3.rmdirSync(dir);
467
795
  } catch {
468
796
  }
469
797
  throw error;
@@ -491,16 +819,16 @@ var Runtime = class {
491
819
  const latest = this.readCoordinatorOwner();
492
820
  if (!latest || latest.raw !== held.raw) return false;
493
821
  try {
494
- fs2.unlinkSync(this.coordinatorOwnerFile());
495
- fs2.rmdirSync(this.coordinatorDir());
822
+ fs3.unlinkSync(this.coordinatorOwnerFile());
823
+ fs3.rmdirSync(this.coordinatorDir());
496
824
  return true;
497
825
  } catch {
498
826
  return false;
499
827
  }
500
828
  }
501
829
  releaseCoordinator() {
502
- fs2.rmSync(this.coordinatorOwnerFile(), { force: true });
503
- fs2.rmdirSync(this.coordinatorDir());
830
+ fs3.rmSync(this.coordinatorOwnerFile(), { force: true });
831
+ fs3.rmdirSync(this.coordinatorDir());
504
832
  this.leader = false;
505
833
  }
506
834
  persistOwner(sessionId) {
@@ -534,6 +862,7 @@ var Runtime = class {
534
862
  if (!this.stopped && generation === this.binding) this.register(sessionId);
535
863
  }
536
864
  notify(job) {
865
+ if (isProcessJob(job)) return;
537
866
  if (job.sessionId !== this.sessionId || !job.error) return;
538
867
  const key = job.id + job.error;
539
868
  if (!this.notices.has(key)) {
@@ -542,11 +871,18 @@ var Runtime = class {
542
871
  }
543
872
  }
544
873
  flushCompletions() {
545
- for (const [id, error] of this.completions) {
874
+ for (const [id, entry] of this.completions) {
875
+ const { error, cancelled } = entry;
546
876
  try {
547
877
  this.store.transaction((state) => {
548
878
  const job = state.jobs.find((item) => item.id === id);
549
- if (job?.state === "running") complete(job, error);
879
+ if (job?.state === "running") {
880
+ if (cancelled && error !== void 0 && isProcessJob(job) && job.target === "worker") {
881
+ completeInterrupted(job, error);
882
+ } else {
883
+ complete(job, error);
884
+ }
885
+ }
550
886
  });
551
887
  this.completions.delete(id);
552
888
  } catch (failure) {
@@ -555,14 +891,15 @@ var Runtime = class {
555
891
  }
556
892
  }
557
893
  }
558
- finish(id, error) {
559
- this.completions.set(id, error);
894
+ finish(id, error, cancelled) {
895
+ this.completions.set(id, { error, cancelled });
560
896
  this.flushCompletions();
561
897
  }
562
898
  async poll(now = Date.now()) {
563
899
  if (this.stopped || this.polling || !this.initialized) return;
564
- if (fs2.existsSync(path3.join(this.store.dir, "unsafe.lock"))) {
900
+ if (fs3.existsSync(path3.join(this.store.dir, "unsafe.lock"))) {
565
901
  this.abort.abort();
902
+ this.processAbort.abort();
566
903
  this.ctx.ui.setStatus?.("cron", void 0);
567
904
  return;
568
905
  }
@@ -585,6 +922,7 @@ var Runtime = class {
585
922
  }
586
923
  });
587
924
  let delivery, launch;
925
+ let processLaunch;
588
926
  this.store.transaction((state2) => {
589
927
  if (this.recovering) {
590
928
  for (const job of state2.jobs) {
@@ -595,6 +933,7 @@ var Runtime = class {
595
933
  }
596
934
  state2.owners[this.id] = { sessionId: this.sessionId, cwd: this.cwd, busy: !this.ctx.isIdle() };
597
935
  for (const job of state2.jobs) {
936
+ if (isProcessJob(job)) continue;
598
937
  const owners = Object.entries(state2.owners).filter(([, owner]) => owner.sessionId === job.sessionId);
599
938
  if (this.leader && job.state === "running" && job.target === "worker" && owners.length) this.abort.abort();
600
939
  if (job.enabled && owners.length > 1 && job.state !== "running") complete(job, "duplicate participating session owners; close duplicate and resume job");
@@ -625,6 +964,13 @@ var Runtime = class {
625
964
  if (this.leader && !state2.jobs.some((job) => job.state === "running")) {
626
965
  const due = state2.jobs.filter((job) => job.enabled && job.state === "ready" && job.next !== null && job.next <= now).sort((a, b) => a.next - b.next);
627
966
  for (const job of due) {
967
+ if (isProcessJob(job)) {
968
+ job.state = "running";
969
+ job.occurrence = job.next;
970
+ job.target = "worker";
971
+ processLaunch = job;
972
+ break;
973
+ }
628
974
  if (state2.jobs.some((other) => other.enabled && other.sessionId === job.sessionId && other.state === "blocked")) continue;
629
975
  const owners = Object.entries(state2.owners).filter(([, owner]) => owner.sessionId === job.sessionId);
630
976
  if (owners.length > 1) {
@@ -647,7 +993,7 @@ var Runtime = class {
647
993
  this.recovering = false;
648
994
  if (delivery) {
649
995
  const job = delivery;
650
- 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);
996
+ 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);
651
997
  let error;
652
998
  const content = `[Cron job=${job.id} scheduledAt=${job.occurrence}]
653
999
  ${job.prompt}`;
@@ -667,7 +1013,7 @@ ${job.prompt}`;
667
1013
  if (launch) {
668
1014
  const job = launch;
669
1015
  const latest = this.store.read();
670
- if (this.stopped || fs2.existsSync(path3.join(this.store.dir, "unsafe.lock")) || Object.values(latest.owners).some((owner) => owner.sessionId === job.sessionId)) {
1016
+ if (this.stopped || fs3.existsSync(path3.join(this.store.dir, "unsafe.lock")) || Object.values(latest.owners).some((owner) => owner.sessionId === job.sessionId)) {
671
1017
  this.finish(job.id, "ownership changed before worker launch; inspect before resuming");
672
1018
  return;
673
1019
  }
@@ -679,8 +1025,19 @@ ${job.prompt}`;
679
1025
  }
680
1026
  });
681
1027
  }
1028
+ if (processLaunch) {
1029
+ const job = processLaunch;
1030
+ const command = parseProcessCommand(job);
1031
+ this.processAbort = new AbortController();
1032
+ 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(() => {
1033
+ try {
1034
+ this.markUnsafe();
1035
+ } catch {
1036
+ }
1037
+ });
1038
+ }
682
1039
  const state = this.store.read(), enabled = state.jobs.filter((job) => job.enabled);
683
- 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);
1040
+ 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);
684
1041
  for (const job of state.jobs) this.notify(job);
685
1042
  } catch {
686
1043
  this.ctx.ui.setStatus?.("cron", void 0);
@@ -692,14 +1049,21 @@ ${job.prompt}`;
692
1049
  this.stopped = true;
693
1050
  clearInterval(this.timer);
694
1051
  this.abort.abort();
1052
+ this.processAbort.abort();
695
1053
  await this.worker;
696
1054
  while (this.polling) await delay(10);
697
1055
  for (let attempt = 0; ; attempt++) {
698
1056
  try {
699
1057
  this.store.transaction((state) => {
700
- for (const [id, error] of this.completions) {
1058
+ for (const [id, entry] of this.completions) {
701
1059
  const job = state.jobs.find((item) => item.id === id);
702
- if (job?.state === "running") complete(job, error);
1060
+ if (job?.state === "running") {
1061
+ if (entry.cancelled && entry.error !== void 0 && isProcessJob(job) && job.target === "worker") {
1062
+ completeInterrupted(job, entry.error);
1063
+ } else {
1064
+ complete(job, entry.error);
1065
+ }
1066
+ }
703
1067
  }
704
1068
  delete state.owners[this.id];
705
1069
  for (const job of state.jobs) {
@@ -709,8 +1073,12 @@ ${job.prompt}`;
709
1073
  this.completions.clear();
710
1074
  break;
711
1075
  } catch (error) {
712
- if (!isContention(error) || attempt >= 39) throw error;
713
- await delay(25 + Math.floor(Math.random() * 25));
1076
+ if (isContention(error) && attempt < 39) {
1077
+ await delay(25 + Math.floor(Math.random() * 25));
1078
+ continue;
1079
+ }
1080
+ this.noteShutdownDegradation(`cron: exit left session ownership uncommitted (${String(error)}). If input stays blocked, run /tools/cron list and remove the stale owner row.`);
1081
+ break;
714
1082
  }
715
1083
  }
716
1084
  if (this.leader) {
@@ -719,13 +1087,29 @@ ${job.prompt}`;
719
1087
  this.withCoordinatorMutex(() => this.releaseCoordinator());
720
1088
  break;
721
1089
  } catch (error) {
722
- if (!isContention(error) || attempt >= 39) throw error;
723
- await delay(25 + Math.floor(Math.random() * 25));
1090
+ if (isContention(error) && attempt < 39) {
1091
+ await delay(25 + Math.floor(Math.random() * 25));
1092
+ continue;
1093
+ }
1094
+ this.noteShutdownDegradation(`cron: coordinator lock not released (${String(error)}). Scheduling pauses until it is reclaimed; see docs/cron.md.`);
1095
+ break;
724
1096
  }
725
1097
  }
726
1098
  }
727
1099
  this.ctx.ui.setStatus?.("cron", void 0);
728
1100
  }
1101
+ /** Surface a best-effort shutdown degradation. Never throws: diagnostics
1102
+ * must not turn a contained skip into a failed exit. */
1103
+ noteShutdownDegradation(message) {
1104
+ try {
1105
+ this.ctx.log?.(message);
1106
+ } catch {
1107
+ }
1108
+ try {
1109
+ this.ctx.ui.notify?.(message, "warning");
1110
+ } catch {
1111
+ }
1112
+ }
729
1113
  };
730
1114
 
731
1115
  // builtin/extensions/cron/index.ts
@@ -763,7 +1147,7 @@ function cron(ctx) {
763
1147
  if (!state.jobs.some((j) => j.sessionId === runtime.sessionId && (j.enabled || j.state === "running"))) return;
764
1148
  const duplicates = Object.values(state.owners).filter((o) => o.sessionId === runtime.sessionId).length > 1;
765
1149
  const worker = state.jobs.some((j) => j.sessionId === runtime.sessionId && j.state === "running" && j.target === "worker");
766
- if (!startupError && runtime.ready && !duplicates && !worker && !fs3.existsSync(path4.join(store.dir, "unsafe.lock"))) return;
1150
+ if (!startupError && runtime.ready && !duplicates && !worker && !fs4.existsSync(path4.join(store.dir, "unsafe.lock"))) return;
767
1151
  } catch {
768
1152
  }
769
1153
  ctx.ui.notify("cron: session ownership is uncertain or duplicated; input blocked. Close the duplicate/worker and inspect /tools/cron.", "warning");
@@ -784,7 +1168,7 @@ function cron(ctx) {
784
1168
  });
785
1169
  const run = (action, id, prompt, schedule) => {
786
1170
  if (startupError && action !== "list") throw new Error(`cron unavailable: ${startupError}; see docs/cron.md recovery`);
787
- 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);
1171
+ 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);
788
1172
  if (action === "add") {
789
1173
  if (!runtime.ready || !runtime.sessionId) throw new Error("wait for an existing session to load and register");
790
1174
  return JSON.stringify({
@@ -811,7 +1195,7 @@ function cron(ctx) {
811
1195
  ctx.registerTool({
812
1196
  name: "cron_manage",
813
1197
  label: "Cron",
814
- 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) 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.',
1198
+ 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.',
815
1199
  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 })) })])) }),
816
1200
  risk: { riskClass: "external_side_effect", permissionScope: "host", availableInPlanMode: false, requiresPermission: true, externalSideEffect: true, allowedForSubagentByDefault: false, concurrencySafe: false },
817
1201
  execute: async (args) => {
@@ -835,6 +1219,9 @@ function cron(ctx) {
835
1219
  });
836
1220
  }
837
1221
  export {
1222
+ PROCESS_SESSION_ID,
1223
+ Store,
838
1224
  configPath,
839
- cron as default
1225
+ cron as default,
1226
+ parseProcessCommand
840
1227
  };