pi-durable-subagents 1.5.0 → 1.6.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 (55) hide show
  1. package/CHANGELOG.md +38 -0
  2. package/README.md +69 -14
  3. package/dist/agent/capabilities.js +5 -4
  4. package/dist/agent/child/live.js +2 -1
  5. package/dist/agent/exact/capture.js +3 -2
  6. package/dist/agent/main/snapshots.js +10 -9
  7. package/dist/agent/main.js +2 -1
  8. package/dist/cli/chaos/stack.js +53 -21
  9. package/dist/cli/control.js +4 -3
  10. package/dist/cli/doctor.js +3 -1
  11. package/dist/cli/drill/index.js +35 -17
  12. package/dist/cli/hold.js +221 -16
  13. package/dist/cli/restart.js +14 -2
  14. package/dist/cli/service.js +77 -2
  15. package/dist/cli/smoke.js +10 -6
  16. package/dist/compat/agents.js +46 -13
  17. package/dist/events/log.js +33 -11
  18. package/dist/kernel/cache.js +3 -2
  19. package/dist/kernel/fsx.js +203 -0
  20. package/dist/kernel/ids.js +11 -0
  21. package/dist/kernel/journal.js +42 -25
  22. package/dist/kernel/mailbox.js +7 -4
  23. package/dist/orchestrator/engine.js +49 -46
  24. package/dist/orchestrator/evaluator-client.js +11 -3
  25. package/dist/orchestrator/executor/command.js +21 -6
  26. package/dist/orchestrator/executor/effects/gate.js +291 -56
  27. package/dist/orchestrator/executor/effects/index.js +3 -4
  28. package/dist/orchestrator/executor/effects/output.js +9 -5
  29. package/dist/orchestrator/executor/effects/prepare.js +69 -35
  30. package/dist/orchestrator/executor/effects/worktree-path.js +102 -0
  31. package/dist/orchestrator/executor/ended.js +7 -3
  32. package/dist/orchestrator/executor/index.js +221 -63
  33. package/dist/orchestrator/executor/memory.js +15 -0
  34. package/dist/orchestrator/executor/session.js +4 -3
  35. package/dist/orchestrator/executor/sweep.js +34 -1
  36. package/dist/orchestrator/executor/worktree.js +7 -1
  37. package/dist/orchestrator/main.js +4 -2
  38. package/dist/orchestrator/reader-ledger.js +3 -2
  39. package/dist/orchestrator/settled.js +2 -1
  40. package/dist/orchestrator/snapshot.js +29 -22
  41. package/dist/orchestrator/stats.js +2 -1
  42. package/dist/orchestrator/store.js +3 -2
  43. package/dist/platform/cmdline.js +3 -0
  44. package/dist/platform/command.js +184 -20
  45. package/dist/platform/containment.js +204 -40
  46. package/dist/platform/job.js +1404 -0
  47. package/dist/platform/launch.js +157 -23
  48. package/dist/platform/lease.js +351 -32
  49. package/dist/platform/lock.js +464 -16
  50. package/dist/platform/proctable.js +31 -2
  51. package/dist/platform/windows.js +642 -0
  52. package/dist/requests.js +1 -1
  53. package/dist/ui/data.js +7 -6
  54. package/dist/ui/session.js +6 -5
  55. package/package.json +3 -3
@@ -5,28 +5,54 @@
5
5
  // earlier request, so the old FIFO lock-free grant argument no longer applies. No lock is held while commands run or
6
6
  // their processes are ended. A ticket stays live while its wrapper, command, group or exact DSA_HOLD tag lives;
7
7
  // waiters reclaim orphaned command trees before granting the next request. No orchestrator is involved.
8
- import { chmodSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
8
+ import { chmodSync, mkdirSync, readdirSync, readFileSync, rmSync, rmdirSync, statSync, unlinkSync, writeFileSync } from "node:fs";
9
9
  import { readFile, unlink, writeFile } from "node:fs/promises";
10
10
  import path from "node:path";
11
+ import { replacePath, replacePathSync } from "../kernel/fsx.js";
12
+ import { readBeginIdentitySync, readGroupEndSync, readGroupRecordStateSync } from "./job.js";
11
13
  import { OsLock } from "./lock.js";
12
14
  import { ProcessTable } from "./proctable.js";
15
+ import { IS_WINDOWS, isWinStart, killProcessSync, killTreeSync, probeKernelPid, sameCreation, winLiveDescendants, winProcessAlive, winSnapshotSync, winStartSync, winTag } from "./windows.js";
13
16
  export const RESOURCE = /^[A-Za-z0-9._-]{1,64}$/;
14
17
  export const leasesRoot = (home) => path.join(home, "leases");
15
18
  export const leaseDir = (home, resource) => path.join(leasesRoot(home), resource);
19
+ export const leaseJobDir = (home, resource, seq) => path.join(leaseDir(home, resource), ".jobs", String(seq).padStart(12, "0"));
16
20
  const ticketName = (seq) => `${String(seq).padStart(12, "0")}.json`;
17
21
  const TICKET = /^\d{12}\.json$/;
18
- /** Whether a process still runs; on Linux the start token also tells it from a later process with the same pid. */
19
- export function alive(p) {
22
+ const checkOpts = (options) => options && typeof options === "object" ? options : undefined;
23
+ function resolveProbePid(opts) {
24
+ if (opts?.probePid)
25
+ return opts.probePid;
26
+ if (opts?.processAlive)
27
+ return pid => (opts.processAlive(pid) ? "alive" : "dead");
28
+ return probeKernelPid;
29
+ }
30
+ /** Proven-owned live descendants of `(pid, start)` in the current snapshot. Requires a valid `start` token and a live
31
+ * matching parent in the snapshot: once a parent exits on Windows, its numeric PID can be reused by an unrelated
32
+ * process whose children share that `ParentProcessId`, and pre-existing boot/system orphans have `child.start < start`. */
33
+ function winDescendants(pid, start, rows) {
34
+ if (!isWinStart(start))
35
+ return [];
36
+ const table = rows ?? winSnapshotSync();
37
+ return winLiveDescendants([{ pid, start }], table.values());
38
+ }
39
+ /** Whether a process still runs; on Linux/Windows the start token also tells it from a later process with the same pid. */
40
+ export function alive(p, options) {
20
41
  if (!p)
21
42
  return false;
22
- try {
23
- process.kill(p.pid, 0);
43
+ const opts = checkOpts(options);
44
+ const probePid = resolveProbePid(opts);
45
+ const platform = opts?.platform ?? (IS_WINDOWS ? "win32" : process.platform);
46
+ if (platform === "win32") {
47
+ return winProcessAlive(p.pid, p.start, {
48
+ probePid,
49
+ ...(opts?.snapshotWin ? { snapshotWin: opts.snapshotWin } : {}),
50
+ ...(opts?.startWinSync ? { startWinSync: opts.startWinSync } : {}),
51
+ });
24
52
  }
25
- catch (error) {
26
- if (error.code !== "EPERM")
27
- return false;
28
- }
29
- if (!p.start || process.platform !== "linux")
53
+ if (probePid(p.pid) === "dead")
54
+ return false;
55
+ if (!p.start || platform !== "linux")
30
56
  return true;
31
57
  try {
32
58
  const fields = readFileSync(`/proc/${p.pid}/stat`, "utf8");
@@ -39,6 +65,16 @@ export function alive(p) {
39
65
  }
40
66
  /** Whether process group `pgid` still has a member that can run (Linux: zombies, which no signal ends, do not count). */
41
67
  export function groupAlive(pgid) {
68
+ if (IS_WINDOWS) {
69
+ try {
70
+ process.kill(pgid, 0);
71
+ return true;
72
+ }
73
+ catch (e) {
74
+ if (e.code !== "EPERM")
75
+ return winDescendants(pgid).length > 0;
76
+ }
77
+ }
42
78
  try {
43
79
  process.kill(-pgid, 0);
44
80
  }
@@ -78,6 +114,18 @@ function leftoverGroup(t) {
78
114
  const c = t.command;
79
115
  if (!c)
80
116
  return false;
117
+ if (IS_WINDOWS) {
118
+ // The command's pid is the root of its tree, not a process group. Live leader: no leftovers (alive() checks the
119
+ // creation token). Dead leader: its children keep the parent pid, so they are its leftovers.
120
+ if (alive(c))
121
+ return false;
122
+ try {
123
+ return winDescendants(c.pid, c.start).length > 0;
124
+ }
125
+ catch {
126
+ return false;
127
+ }
128
+ }
81
129
  if (process.platform === "linux") {
82
130
  try {
83
131
  const fields = readFileSync(`/proc/${c.pid}/stat`, "utf8");
@@ -108,13 +156,260 @@ function leftoverGroup(t) {
108
156
  const holdTable = new ProcessTable({ tagName: "DSA_HOLD" });
109
157
  export const holdTag = (t) => `${t.resource}:${t.seq}`;
110
158
  export const tagged = (t) => holdTable.tagged(holdTag(t));
111
- /** An orphan may retain its tag even after its leader and entire original process group have gone. */
112
- export const orphaned = (t) => !alive(t.wrapper) && !alive(t.command) && (leftoverGroup(t) || tagged(t).length > 0);
113
- /** A ticket is live while its wrapper, command, process group or exact inherited tag can still act. */
114
- export const live = (t) => alive(t.wrapper) || alive(t.command) || orphaned(t);
159
+ const isWinJobTicket = (t) => Boolean(t.jobDir || t.group);
160
+ /** Inspect a Windows Job-backed ticket after its wrapper has exited:
161
+ * - "running": the Job Object owner and the command root are live (retains the lease until the command finishes);
162
+ * - "orphaned": the wrapper and command root are gone (or the wrapper died mid-launch before `group`), while the
163
+ * Job Object owner or a verified root is still alive (retains the lease until a waiter or the owner finishes draining);
164
+ * - "dead": the Job Object owner is gone, so its non-inherited KILL_ON_JOB_CLOSE handle is closed and nothing remains. */
165
+ function inspectWinJob(t, opts) {
166
+ const probePid = resolveProbePid(opts);
167
+ const snap = opts?.snapshotWin ?? winSnapshotSync;
168
+ const startOf = opts?.startWinSync ?? winStartSync;
169
+ // Fresh snapshot AFTER observing the wrapper gone, before reading the job directory: never uses a pre-spawn cache.
170
+ let rows;
171
+ try {
172
+ rows = snap(0);
173
+ }
174
+ catch {
175
+ rows = undefined;
176
+ }
177
+ const groupState = t.jobDir ? readGroupRecordStateSync(t.jobDir) : { state: "absent" };
178
+ const groupRec = groupState.state === "ready" ? groupState.record : undefined;
179
+ const began = t.jobDir ? readBeginIdentitySync(t.jobDir) : undefined;
180
+ const groupEnded = Boolean(t.jobDir && readGroupEndSync(t.jobDir) !== undefined);
181
+ const recordedOwner = (groupRec?.group && isWinStart(groupRec.group.start) ? groupRec.group : undefined)
182
+ ?? (t.group && isWinStart(t.group.start) ? { pid: t.group.pid, start: t.group.start } : undefined)
183
+ ?? (began && isWinStart(began.start) ? began : undefined);
184
+ const tag = holdTag(t);
185
+ let ownerAlive = false;
186
+ if (recordedOwner) {
187
+ const ownerProbe = probePid(recordedOwner.pid);
188
+ if (ownerProbe !== "dead") {
189
+ if (!rows) {
190
+ ownerAlive = ownerProbe === "alive";
191
+ }
192
+ else {
193
+ const ownerRow = rows.get(recordedOwner.pid);
194
+ ownerAlive = ownerRow ? sameCreation(ownerRow.start, recordedOwner.start)
195
+ : ownerProbe === "alive" && sameCreation(startOf(recordedOwner.pid), recordedOwner.start);
196
+ }
197
+ }
198
+ }
199
+ else if (!rows) {
200
+ return "running";
201
+ }
202
+ else {
203
+ const taggedOwner = [...rows.values()].find(r => isWinStart(r.start) && winTag(r.command, "DSA_HOLD") === tag);
204
+ if (taggedOwner && probePid(taggedOwner.pid) !== "dead")
205
+ ownerAlive = true;
206
+ }
207
+ const cmd = (groupRec && isWinStart(groupRec.start) ? { pid: groupRec.pid, start: groupRec.start } : undefined)
208
+ ?? (t.command && isWinStart(t.command.start) ? { pid: t.command.pid, start: t.command.start } : undefined);
209
+ let cmdAlive = false;
210
+ if (!groupEnded && cmd) {
211
+ const cmdProbe = probePid(cmd.pid);
212
+ if (cmdProbe !== "dead") {
213
+ if (!rows) {
214
+ cmdAlive = cmdProbe === "alive";
215
+ }
216
+ else {
217
+ const cmdRow = rows.get(cmd.pid);
218
+ cmdAlive = cmdRow ? sameCreation(cmdRow.start, cmd.start)
219
+ : cmdProbe === "alive" && sameCreation(startOf(cmd.pid), cmd.start);
220
+ }
221
+ }
222
+ }
223
+ if (ownerAlive && (cmdAlive || groupState.state === "transient"))
224
+ return "running";
225
+ if (ownerAlive || cmdAlive)
226
+ return "orphaned";
227
+ return "dead";
228
+ }
229
+ /** An orphan may retain its tag or job even after its wrapper and command leader have gone. */
230
+ export const orphaned = (t, options) => {
231
+ const opts = checkOpts(options);
232
+ const platform = opts?.platform ?? (IS_WINDOWS ? "win32" : process.platform);
233
+ if (alive(t.wrapper, opts))
234
+ return false;
235
+ if (platform === "win32" && isWinJobTicket(t))
236
+ return inspectWinJob(t, opts) === "orphaned";
237
+ if (alive(t.command, opts))
238
+ return false;
239
+ if (platform === "win32") {
240
+ const snap = opts?.snapshotWin ?? winSnapshotSync;
241
+ try {
242
+ const rows = snap(0);
243
+ return (t.command ? winDescendants(t.command.pid, t.command.start, rows).length > 0 : false)
244
+ || winDescendants(t.wrapper.pid, t.wrapper.start, rows).length > 0;
245
+ }
246
+ catch {
247
+ return false;
248
+ }
249
+ }
250
+ return leftoverGroup(t) || tagged(t).length > 0;
251
+ };
252
+ /** A ticket is live while its wrapper, command, job/process group or exact inherited tag can still act. */
253
+ export const live = (t, options) => {
254
+ const opts = checkOpts(options);
255
+ const platform = opts?.platform ?? (IS_WINDOWS ? "win32" : process.platform);
256
+ if (alive(t.wrapper, opts))
257
+ return true;
258
+ if (platform === "win32" && isWinJobTicket(t))
259
+ return inspectWinJob(t, opts) !== "dead";
260
+ return alive(t.command, opts) || orphaned(t, opts);
261
+ };
115
262
  /** End the group and escaped tagged descendants, rescanning for forks. Release is bounded even for unkillable tasks. */
116
- export async function endLeaseProcesses(t, graceMs, say) {
263
+ export async function endLeaseProcesses(t, graceMs, say, options = {}) {
117
264
  const started = Date.now(), until = started + 5000;
265
+ if ((options.platform ?? process.platform) === "win32") {
266
+ const snap = options.snapshotWin ?? winSnapshotSync;
267
+ const trySnap = () => {
268
+ try {
269
+ return snap(0);
270
+ }
271
+ catch {
272
+ return undefined;
273
+ }
274
+ };
275
+ if (isWinJobTicket(t)) {
276
+ // Terminating the verified Job Object owner closes the job's sole handle (JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE),
277
+ // so the kernel ends the command root and every surviving child/grandchild without walking dead parent PIDs.
278
+ const killOwner = options.killOwnerWinSync ?? options.killWinSync ?? (targets => killProcessSync(targets));
279
+ const probe = resolveProbePid(options);
280
+ const tag = holdTag(t);
281
+ const proven = new Map();
282
+ const addProvenCmd = (cmd, ...snapshots) => {
283
+ proven.set(`${cmd.pid}:${cmd.start}`, cmd);
284
+ for (const snapshot of snapshots) {
285
+ if (!snapshot)
286
+ continue;
287
+ for (const d of winLiveDescendants([cmd], snapshot.values())) {
288
+ proven.set(`${d.pid}:${d.start}`, { pid: d.pid, start: d.start });
289
+ }
290
+ }
291
+ };
292
+ let checkedOwnerHandle = false;
293
+ for (;;) {
294
+ const rows = trySnap();
295
+ const groupState = t.jobDir ? readGroupRecordStateSync(t.jobDir) : { state: "absent" };
296
+ const groupRec = groupState.state === "ready" ? groupState.record : undefined;
297
+ const began = t.jobDir ? readBeginIdentitySync(t.jobDir) : undefined;
298
+ const recordedOwner = (groupRec?.group && isWinStart(groupRec.group.start) ? groupRec.group : undefined)
299
+ ?? (t.group && isWinStart(t.group.start) ? { pid: t.group.pid, start: t.group.start } : undefined)
300
+ ?? (began && isWinStart(began.start) ? began : undefined);
301
+ const taggedRow = recordedOwner || !rows ? undefined
302
+ : [...rows.values()].find(r => isWinStart(r.start) && winTag(r.command, "DSA_HOLD") === tag);
303
+ const owner = recordedOwner
304
+ ?? (taggedRow ? { pid: taggedRow.pid, start: taggedRow.start } : undefined);
305
+ const cmd = (groupRec && isWinStart(groupRec.start) ? { pid: groupRec.pid, start: groupRec.start } : undefined)
306
+ ?? (t.command && isWinStart(t.command.start) ? { pid: t.command.pid, start: t.command.start } : undefined);
307
+ if (owner)
308
+ proven.set(`${owner.pid}:${owner.start}`, owner);
309
+ if (cmd)
310
+ addProvenCmd(cmd, rows);
311
+ const ownerLiveInRows = Boolean(owner && rows && rows.get(owner.pid) && sameCreation(rows.get(owner.pid).start, owner.start));
312
+ const shouldKillOwner = Boolean(owner && (ownerLiveInRows || (recordedOwner !== undefined && (!checkedOwnerHandle || !rows) && probe(owner.pid) !== "dead")));
313
+ if (rows)
314
+ checkedOwnerHandle = true;
315
+ if (shouldKillOwner && owner) {
316
+ try {
317
+ killOwner([owner]);
318
+ }
319
+ catch { /* retry until deadline when a verified owner resists termination */ }
320
+ }
321
+ const checkRows = shouldKillOwner ? trySnap() : rows;
322
+ let transientGroup = groupState.state === "transient";
323
+ let effectiveCmd = cmd;
324
+ if (!groupRec && t.jobDir && shouldKillOwner) {
325
+ const lateGroupState = readGroupRecordStateSync(t.jobDir);
326
+ transientGroup = lateGroupState.state === "transient";
327
+ if (lateGroupState.state === "ready") {
328
+ const late = lateGroupState.record;
329
+ if (late.group && isWinStart(late.group.start)) {
330
+ proven.set(`${late.group.pid}:${late.group.start}`, late.group);
331
+ }
332
+ if (isWinStart(late.start)) {
333
+ effectiveCmd = { pid: late.pid, start: late.start };
334
+ addProvenCmd(effectiveCmd, rows, checkRows);
335
+ }
336
+ }
337
+ }
338
+ if (effectiveCmd)
339
+ addProvenCmd(effectiveCmd, checkRows);
340
+ const remaining = checkRows
341
+ ? [...proven.values()].filter(p => {
342
+ const row = checkRows.get(p.pid);
343
+ return row !== undefined && sameCreation(row.start, p.start);
344
+ }).length
345
+ : Math.max(1, proven.size);
346
+ if (checkRows && !remaining && !transientGroup)
347
+ break;
348
+ if (Date.now() >= until) {
349
+ say(`hold: ${remaining || 1} processes of ${who(t)} survived; releasing`);
350
+ break;
351
+ }
352
+ await new Promise(r => setTimeout(r, 25));
353
+ }
354
+ return;
355
+ }
356
+ // Legacy/non-job Windows ticket fallback: handle-verified tree termination on `t.command`.
357
+ if (!t.command)
358
+ return;
359
+ if (!isWinStart(t.command.start)) {
360
+ say(`hold: refusing to end pid ${t.command.pid} of ${who(t)} without verified start identity; releasing`);
361
+ return;
362
+ }
363
+ const killWin = options.killWinSync ?? (targets => killTreeSync(targets));
364
+ const rootIdentity = { pid: t.command.pid, start: t.command.start };
365
+ const proven = new Map([[`${rootIdentity.pid}:${rootIdentity.start}`, rootIdentity]]);
366
+ let checkedRootHandle = false;
367
+ for (;;) {
368
+ const rows = trySnap();
369
+ if (rows) {
370
+ for (const d of winLiveDescendants([...proven.values()], rows.values())) {
371
+ proven.set(`${d.pid}:${d.start}`, { pid: d.pid, start: d.start });
372
+ }
373
+ }
374
+ const liveTargets = rows
375
+ ? [...proven.values()].filter(p => {
376
+ const row = rows.get(p.pid);
377
+ return row !== undefined && sameCreation(row.start, p.start);
378
+ })
379
+ : [rootIdentity];
380
+ if (!checkedRootHandle && !liveTargets.some(p => p.pid === rootIdentity.pid)) {
381
+ liveTargets.unshift(rootIdentity);
382
+ }
383
+ if (rows)
384
+ checkedRootHandle = true;
385
+ if (rows && !liveTargets.length)
386
+ break;
387
+ try {
388
+ killWin(liveTargets);
389
+ }
390
+ catch { /* retry until deadline when a verified owned process resists termination */ }
391
+ const after = trySnap();
392
+ if (after) {
393
+ for (const d of winLiveDescendants([...proven.values()], after.values())) {
394
+ proven.set(`${d.pid}:${d.start}`, { pid: d.pid, start: d.start });
395
+ }
396
+ }
397
+ const remaining = after
398
+ ? [...proven.values()].filter(p => {
399
+ const row = after.get(p.pid);
400
+ return row !== undefined && sameCreation(row.start, p.start);
401
+ }).length
402
+ : Math.max(1, proven.size);
403
+ if (after && !remaining)
404
+ break;
405
+ if (Date.now() >= until) {
406
+ say(`hold: ${remaining} processes of ${who(t)} survived; releasing`);
407
+ break;
408
+ }
409
+ await new Promise(r => setTimeout(r, 25));
410
+ }
411
+ return;
412
+ }
118
413
  for (;;) {
119
414
  const members = tagged(t), group = t.command && (alive(t.command) || leftoverGroup(t));
120
415
  const signal = Date.now() - started >= graceMs ? "SIGKILL" : "SIGTERM";
@@ -166,15 +461,28 @@ export function readTickets(home, resource) {
166
461
  }
167
462
  return out;
168
463
  }
464
+ function removeTicketJobDir(home, t) {
465
+ const dir = t.jobDir || leaseJobDir(home, t.resource, t.seq);
466
+ try {
467
+ rmSync(dir, { recursive: true, force: true });
468
+ }
469
+ catch { /* still held or already gone */ }
470
+ try {
471
+ rmdirSync(path.join(leaseDir(home, t.resource), ".jobs"));
472
+ }
473
+ catch { /* non-empty or absent */ }
474
+ }
169
475
  /** Live tickets; dead ones are deleted (their numbers are never reused, so a stale reader cannot delete a newer one). */
170
- export function liveTickets(home, resource) {
476
+ export function liveTickets(home, resource, options) {
477
+ const opts = checkOpts(options);
171
478
  return readTickets(home, resource).filter(t => {
172
- if (live(t))
479
+ if (live(t, opts))
173
480
  return true;
174
481
  try {
175
482
  unlinkSync(path.join(leaseDir(home, resource), ticketName(t.seq)));
176
483
  }
177
484
  catch { /* already gone */ }
485
+ removeTicketJobDir(home, t);
178
486
  return false;
179
487
  });
180
488
  }
@@ -198,7 +506,7 @@ export function replaceFileSync(file, content, mode) {
198
506
  writeFileSync(tmp, content);
199
507
  if (mode !== undefined)
200
508
  chmodSync(tmp, mode);
201
- renameSync(tmp, file);
509
+ replacePathSync(tmp, file);
202
510
  }
203
511
  catch (error) {
204
512
  try {
@@ -212,7 +520,7 @@ async function replaceFile(file, content) {
212
520
  const tmp = `${file}.${process.pid}.tmp`;
213
521
  try {
214
522
  await writeFile(tmp, content);
215
- renameSync(tmp, file);
523
+ await replacePath(tmp, file);
216
524
  }
217
525
  catch (error) {
218
526
  await unlink(tmp).catch(() => { });
@@ -241,7 +549,7 @@ export function removeStaleTemps(dir, maxAgeMs, now = Date.now()) {
241
549
  }
242
550
  return removed;
243
551
  }
244
- function writeTicketSync(home, t) {
552
+ export function writeTicketSync(home, t) {
245
553
  replaceFileSync(path.join(leaseDir(home, t.resource), ticketName(t.seq)), JSON.stringify(t));
246
554
  }
247
555
  export async function writeTicket(home, t) {
@@ -252,14 +560,15 @@ export function removeTicket(home, t) {
252
560
  unlinkSync(path.join(leaseDir(home, t.resource), ticketName(t.seq)));
253
561
  }
254
562
  catch { /* already gone */ }
563
+ removeTicketJobDir(home, t);
255
564
  }
256
565
  /** Queue a request under the same lock used by queued and no-wait grants. */
257
- export async function enqueue(home, ticket, lock = new OsLock()) {
258
- return (await numbered(home, ticket, false, lock));
566
+ export async function enqueue(home, ticket, lock = new OsLock(), options) {
567
+ return (await numbered(home, ticket, false, lock, options));
259
568
  }
260
569
  /** Take the lease now or not at all. Refusal never creates a waiter; the synthetic sequence ranks after equal priority. */
261
- export async function tryGrant(home, ticket, lock = new OsLock()) {
262
- return numbered(home, ticket, true, lock);
570
+ export async function tryGrant(home, ticket, lock = new OsLock(), options) {
571
+ return numbered(home, ticket, true, lock, options);
263
572
  }
264
573
  async function locked(home, resource, lock, action) {
265
574
  const dir = leaseDir(home, resource);
@@ -277,9 +586,9 @@ async function locked(home, resource, lock, action) {
277
586
  }
278
587
  }
279
588
  /** Recheck and commit a queued grant under the resource lock. No awaits separate the final read and ticket write. */
280
- export async function grantQueued(home, t, lock = new OsLock()) {
589
+ export async function grantQueued(home, t, lock = new OsLock(), options) {
281
590
  return locked(home, t.resource, lock, () => {
282
- const busy = blockers(t, liveTickets(home, t.resource));
591
+ const busy = blockers(t, liveTickets(home, t.resource, options));
283
592
  if (!busy.length) {
284
593
  t.grantedAt = Date.now();
285
594
  writeTicketSync(home, t);
@@ -287,14 +596,14 @@ export async function grantQueued(home, t, lock = new OsLock()) {
287
596
  return busy;
288
597
  });
289
598
  }
290
- async function numbered(home, ticket, now, lock) {
599
+ async function numbered(home, ticket, now, lock, options) {
291
600
  return locked(home, ticket.resource, lock, async () => {
292
601
  const dir = leaseDir(home, ticket.resource), counter = path.join(dir, ".seq");
293
602
  const last = Number.parseInt(await readFile(counter, "utf8").catch(() => "0"), 10) || 0;
294
603
  const highest = readTickets(home, ticket.resource).reduce((m, t) => Math.max(m, t.seq), last);
295
604
  const t = { ...ticket, seq: highest + 1 };
296
605
  if (now) {
297
- const busy = blockers(t, liveTickets(home, ticket.resource));
606
+ const busy = blockers(t, liveTickets(home, ticket.resource, options));
298
607
  if (busy.length)
299
608
  return { busy };
300
609
  t.grantedAt = Date.now();
@@ -304,7 +613,7 @@ async function numbered(home, ticket, now, lock) {
304
613
  return t;
305
614
  });
306
615
  }
307
- export function leaseState(home) {
616
+ export function leaseState(home, options) {
308
617
  let resources;
309
618
  try {
310
619
  resources = readdirSync(leasesRoot(home)).filter(r => RESOURCE.test(r)).sort();
@@ -313,7 +622,7 @@ export function leaseState(home) {
313
622
  return [];
314
623
  }
315
624
  return resources.map(resource => {
316
- const tickets = liveTickets(home, resource), holders = tickets.filter(t => t.grantedAt !== undefined), waiters = tickets.filter(t => t.grantedAt === undefined).sort(rank);
625
+ const tickets = liveTickets(home, resource, options), holders = tickets.filter(t => t.grantedAt !== undefined), waiters = tickets.filter(t => t.grantedAt === undefined).sort(rank);
317
626
  const slots = slotCount(tickets);
318
627
  return { resource, holders, waiters, ...(slots !== undefined ? { slots, held: holders.length } : {}) };
319
628
  }).filter(r => r.holders.length || r.waiters.length);
@@ -360,10 +669,20 @@ export function leaseCalls(state, now = Date.now()) {
360
669
  return out;
361
670
  }
362
671
  const quote = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
363
- /** The `pi-durable-subagents` command for subagents: `<dir>/pi-durable-subagents` runs this node with the CLI entry of
364
- * the running orchestrator, so children can `hold` without the package on their PATH. Rewritten at every start. */
672
+ /** A cmd.exe shim: paths quoted, percent signs doubled so batch does not expand them. */
673
+ const batchQuote = (s) => `"${s.replace(/%/g, "%%")}"`;
674
+ /** The `pi-durable-subagents` command for subagents: `<dir>/pi-durable-subagents` (a `.cmd` on Windows) runs this node
675
+ * with the CLI entry of the running orchestrator, so children can `hold` without the package on their PATH. Rewritten
676
+ * at every start. */
365
677
  export function writeShim(dir, node, entry) {
366
678
  mkdirSync(dir, { recursive: true });
679
+ if (IS_WINDOWS) {
680
+ const file = path.join(dir, "pi-durable-subagents.cmd");
681
+ replaceFileSync(file, `@echo off\r\n${batchQuote(node)} ${batchQuote(entry)} %*\r\n`);
682
+ // Git Bash (pi's bash tool) does not run a .cmd by bare name; the same shim as a POSIX script sits beside it.
683
+ replaceFileSync(path.join(dir, "pi-durable-subagents"), `#!/bin/sh\nexec ${quote(node)} ${quote(entry)} "$@"\n`, 0o755);
684
+ return file;
685
+ }
367
686
  const file = path.join(dir, "pi-durable-subagents");
368
687
  replaceFileSync(file, `#!/bin/sh\nexec ${quote(node)} ${quote(entry)} "$@"\n`, 0o755);
369
688
  return file;