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
package/dist/cli/hold.js CHANGED
@@ -3,9 +3,13 @@
3
3
  import { spawn } from "node:child_process";
4
4
  import { watch } from "node:fs";
5
5
  import { constants } from "node:os";
6
+ import path from "node:path";
6
7
  import { dsaHome } from "../paths.js";
8
+ import { prepareCancelled, prepareJob, readGroupEndSync, readGroupRecord, readStartErrorSync, requestJobStop, spawnInJob, startError } from "../platform/job.js";
7
9
  import { captureStart } from "../platform/proctable.js";
8
- import { blockers, endLeaseProcesses, enqueue, grantQueued, holdDetail, holdTag, tryGrant, leaseDir, liveTickets, orphaned, rank, removeTicket, RESOURCE, who, writeTicket } from "../platform/lease.js";
10
+ import { executableFile, execTarget } from "../platform/launch.js";
11
+ import { comspec, envValue, IS_WINDOWS, isWinStart, mergeEnv, normalizeEnv } from "../platform/windows.js";
12
+ import { blockers, endLeaseProcesses, enqueue, grantQueued, holdDetail, holdTag, leaseDir, leaseJobDir, liveTickets, orphaned, rank, removeTicket, RESOURCE, tryGrant, who, writeTicket, writeTicketSync } from "../platform/lease.js";
9
13
  export const HOLD_USAGE = "usage: pi-durable-subagents hold <resource> [--shared | --slots <n>] [--priority <n>] [--yield] [--expect <duration>] [--max-wait <seconds> | --no-wait] [--note <text>] -- <command> [args…]";
10
14
  /** Exit status when the command did not run or was stopped to yield (EX_TEMPFAIL). */
11
15
  export const WAIT_EXPIRED = 75;
@@ -75,21 +79,49 @@ export function parseHold(args) {
75
79
  ...(maxWaitMs !== undefined ? { maxWaitMs } : {}), ...(note !== undefined ? { note } : {}), argv };
76
80
  }
77
81
  const age = (ms) => ms < 60_000 ? `${Math.max(0, Math.round(ms / 1000))}s` : ms < 3_600_000 ? `${Math.round(ms / 60_000)}m` : `${(ms / 3_600_000).toFixed(1)}h`;
78
- const SIGNALS = ["SIGINT", "SIGTERM", "SIGHUP"];
82
+ const SIGNALS = (IS_WINDOWS ? ["SIGINT", "SIGTERM", "SIGBREAK"] : ["SIGINT", "SIGTERM", "SIGHUP"]);
83
+ export function resolveWinHoldTarget(command, args, cwd, env) {
84
+ const isAbs = path.isAbsolute(command) || path.win32.isAbsolute(command);
85
+ if (isAbs || /[\\/]/.test(command)) {
86
+ const candidate = isAbs ? command : path.resolve(cwd, command);
87
+ if (executableFile(candidate, "win32"))
88
+ return execTarget(candidate, args, { env, platform: "win32" });
89
+ if (!path.win32.extname(candidate)) {
90
+ const exts = (envValue(env, "PATHEXT") ?? ".COM;.EXE;.BAT;.CMD").split(";");
91
+ for (const rawExt of exts) {
92
+ const ext = rawExt.trim();
93
+ if (!ext)
94
+ continue;
95
+ const lower = ext.toLowerCase();
96
+ if (executableFile(candidate + lower, "win32"))
97
+ return execTarget(candidate + lower, args, { env, platform: "win32" });
98
+ if (lower !== ext && executableFile(candidate + ext, "win32"))
99
+ return execTarget(candidate + ext, args, { env, platform: "win32" });
100
+ }
101
+ }
102
+ }
103
+ return execTarget(command, args, { env, platform: "win32" });
104
+ }
79
105
  /** Run one held command; resolves only after its command tree has been ended and its lease released. */
80
106
  export async function hold(args, options = {}) {
81
107
  const env = options.env ?? process.env, home = dsaHome(env), say = options.stderr ?? (l => process.stderr.write(`${l}\n`));
82
108
  const pollMs = options.pollMs ?? 250, graceMs = options.graceMs ?? 2000;
109
+ const winHold = (options.platform ?? (IS_WINDOWS ? "win32" : process.platform)) === "win32";
110
+ const leaseOpts = options.lease ?? (options.platform ? { platform: options.platform } : undefined);
111
+ const getStart = options.captureWrapperStart ?? captureStart;
112
+ const wrapperStart = (await getStart(process.pid).catch(() => "")) || undefined;
113
+ if (winHold && !isWinStart(wrapperStart))
114
+ throw new Error(`hold: cannot verify wrapper start identity for pid ${process.pid}`);
83
115
  const request = {
84
116
  resource: args.resource, mode: args.mode, ...(args.slots !== undefined ? { slots: args.slots } : {}),
85
117
  ...(args.priority !== undefined ? { priority: args.priority } : {}), ...(args.yield ? { yield: args.yield } : {}),
86
118
  ...(args.expectMs !== undefined ? { expectMs: args.expectMs } : {}),
87
- wrapper: { pid: process.pid, start: (await captureStart(process.pid)) || undefined },
119
+ wrapper: { pid: process.pid, start: wrapperStart },
88
120
  argv: args.argv.map(a => a.length > 200 ? `${a.slice(0, 199)}…` : a).slice(0, 32), cwd: process.cwd(),
89
121
  ...(args.note ? { note: args.note.slice(0, 300) } : {}), since: Date.now(),
90
122
  ...(env.DSA_EXEC ? { exec: env.DSA_EXEC } : {}), ...(env.DSA_CALL ? { call: env.DSA_CALL } : {}),
91
123
  };
92
- const granted = args.maxWaitMs === 0 ? await tryGrant(home, request) : undefined;
124
+ const granted = args.maxWaitMs === 0 ? await tryGrant(home, request, undefined, leaseOpts) : undefined;
93
125
  if (granted && "busy" in granted) {
94
126
  const now = Date.now(), by = granted.busy.map(t => `${who(t)} (${t.grantedAt === undefined
95
127
  ? `${t.mode === "counted" ? "slot" : t.mode}, waiting, ${age(now - t.since)}${t.expectMs !== undefined ? `, expects ${age(t.expectMs)}` : ""}`
@@ -97,10 +129,42 @@ export async function hold(args, options = {}) {
97
129
  say(`hold: ${args.resource} is not free now (${by}); not running the command (exit ${WAIT_EXPIRED})`);
98
130
  return WAIT_EXPIRED;
99
131
  }
100
- const ticket = granted ?? await enqueue(home, request);
132
+ const ticket = granted ?? await enqueue(home, request, undefined, leaseOpts);
101
133
  let child, interrupted, wake = () => { }, cleaned = false;
134
+ let winJobActive = false, activeJobDir;
135
+ let activeJob;
136
+ const prepAbort = new AbortController();
137
+ const stopWinJob = async () => {
138
+ const stopBudgetMs = Math.min(Math.max(graceMs, 250), 2000);
139
+ if (activeJob) {
140
+ await activeJob.requestStop?.();
141
+ let timer;
142
+ try {
143
+ await Promise.race([
144
+ activeJob.exited,
145
+ new Promise(resolve => { timer = setTimeout(resolve, stopBudgetMs); }),
146
+ ]);
147
+ }
148
+ finally {
149
+ clearTimeout(timer);
150
+ }
151
+ }
152
+ else if (activeJobDir) {
153
+ await requestJobStop(activeJobDir);
154
+ }
155
+ await endLeaseProcesses(ticket, graceMs, say, leaseOpts);
156
+ };
102
157
  const onSignal = (signal) => {
103
- if (child?.pid) {
158
+ if (winHold) {
159
+ interrupted = signal;
160
+ prepAbort.abort();
161
+ if (activeJob?.requestStop)
162
+ void activeJob.requestStop();
163
+ else if (activeJobDir)
164
+ void requestJobStop(activeJobDir);
165
+ wake();
166
+ }
167
+ else if (child?.pid) {
104
168
  try {
105
169
  process.kill(-child.pid, signal);
106
170
  }
@@ -129,18 +193,18 @@ export async function hold(args, options = {}) {
129
193
  while (ticket.grantedAt === undefined) {
130
194
  if (interrupted)
131
195
  return 128 + (constants.signals[interrupted] ?? 1);
132
- const all = liveTickets(home, args.resource);
196
+ const all = liveTickets(home, args.resource, leaseOpts);
133
197
  let ahead = blockers(ticket, all);
134
198
  // A lock-free observation is only a hint. Priority can change while the lock is being acquired.
135
199
  if (!ahead.length) {
136
- ahead = await grantQueued(home, ticket);
200
+ ahead = await grantQueued(home, ticket, undefined, leaseOpts);
137
201
  if (ticket.grantedAt !== undefined)
138
202
  break;
139
203
  }
140
- const leftovers = ahead.filter(orphaned);
204
+ const leftovers = ahead.filter(t => orphaned(t, leaseOpts));
141
205
  for (const t of leftovers) {
142
206
  say(`hold: ending processes left by ${who(t)} (its hold process is gone)`);
143
- await endLeaseProcesses(t, graceMs, say);
207
+ await endLeaseProcesses(t, graceMs, say, leaseOpts);
144
208
  removeTicket(home, t);
145
209
  }
146
210
  if (leftovers.length)
@@ -166,9 +230,149 @@ export async function hold(args, options = {}) {
166
230
  return 128 + (constants.signals[interrupted] ?? 1);
167
231
  if (shown)
168
232
  say(`hold: ${args.resource} granted after ${age(ticket.grantedAt - ticket.since)}`);
233
+ if (winHold) {
234
+ const cwd = process.cwd();
235
+ const childEnv = mergeEnv(normalizeEnv(env), {
236
+ ComSpec: envValue(env, "ComSpec") || comspec(env),
237
+ PATHEXT: envValue(env, "PATHEXT") || ".COM;.EXE;.BAT;.CMD",
238
+ DSA_HOLD: holdTag(ticket),
239
+ });
240
+ const target = resolveWinHoldTarget(args.argv[0], args.argv.slice(1), cwd, childEnv);
241
+ const jobDir = leaseJobDir(home, ticket.resource, ticket.seq);
242
+ const launch = {
243
+ exe: target.command,
244
+ args: target.args,
245
+ cwd,
246
+ log: "",
247
+ env: childEnv,
248
+ hold: holdTag(ticket),
249
+ ...(env.DSA_EXEC ? { exec: env.DSA_EXEC } : {}),
250
+ };
251
+ let prepared;
252
+ try {
253
+ prepared = await prepareJob(jobDir, launch, {
254
+ signal: prepAbort.signal,
255
+ ...(options.job?.compiler ? { compiler: options.job.compiler } : {}),
256
+ ...(options.job?.compileMs ? { compileMs: options.job.compileMs } : {}),
257
+ ...(options.job?.publish ? { publish: options.job.publish } : {}),
258
+ });
259
+ }
260
+ catch (error) {
261
+ if (interrupted || prepareCancelled(error)) {
262
+ cleaned = true;
263
+ return 128 + (constants.signals[interrupted ?? "SIGINT"] ?? 1);
264
+ }
265
+ cleaned = true;
266
+ throw error;
267
+ }
268
+ if (interrupted) {
269
+ await prepared.release();
270
+ cleaned = true;
271
+ return 128 + (constants.signals[interrupted] ?? 1);
272
+ }
273
+ // Persist the job handshake directory on the ticket BEFORE spawning the Job Object owner: if this wrapper is
274
+ // hard-killed at any instant during or after launch, readers recover the job owner and command from `jobDir`.
275
+ ticket.jobDir = jobDir;
276
+ writeTicketSync(home, ticket);
277
+ activeJobDir = jobDir;
278
+ winJobActive = true;
279
+ let spawned;
280
+ try {
281
+ spawned = await spawnInJob(jobDir, launch, {
282
+ prepared,
283
+ proceed: () => !interrupted,
284
+ stdio: options.job?.stdio ?? [process.stdin.isTTY ? "ignore" : "inherit", "inherit", "inherit"],
285
+ unref: false,
286
+ onOwnerSpawned: () => {
287
+ if (interrupted)
288
+ void requestJobStop(jobDir);
289
+ options.onJobOwnerSpawned?.();
290
+ },
291
+ ...(options.job?.timeoutMs !== undefined ? { timeoutMs: options.job.timeoutMs } : {}),
292
+ ...(options.job?.observeMs !== undefined ? { observeMs: options.job.observeMs } : {}),
293
+ ...(options.job?.endMs !== undefined ? { endMs: options.job.endMs } : {}),
294
+ ...(options.job?.observe ? { observe: options.job.observe } : {}),
295
+ ...(options.job?.endHelper ? { endHelper: options.job.endHelper } : {}),
296
+ });
297
+ }
298
+ catch (error) {
299
+ if (interrupted) {
300
+ await stopWinJob();
301
+ cleaned = true;
302
+ return 128 + (constants.signals[interrupted] ?? 1);
303
+ }
304
+ const recordedErr = readStartErrorSync(jobDir);
305
+ if (recordedErr?.startsWith("CreateProcess ")) {
306
+ say(`hold: cannot run ${args.argv[0]}: ${recordedErr}`);
307
+ cleaned = true;
308
+ return 127;
309
+ }
310
+ cleaned = true;
311
+ throw error;
312
+ }
313
+ if (!spawned) {
314
+ await prepared.release();
315
+ cleaned = true;
316
+ return 128 + (constants.signals[interrupted ?? "SIGINT"] ?? 1);
317
+ }
318
+ activeJob = spawned;
319
+ let jobEnded = false;
320
+ void spawned.exited.then(() => { jobEnded = true; wake(); });
321
+ if (interrupted)
322
+ void spawned.requestStop?.();
323
+ if (spawned.uncertain) {
324
+ if (isWinStart(spawned.start)) {
325
+ ticket.group = { pid: spawned.pid, start: spawned.start };
326
+ await writeTicket(home, ticket).catch(() => { });
327
+ }
328
+ throw new Error(`hold: ${spawned.uncertain}`);
329
+ }
330
+ const groupRec = await readGroupRecord(jobDir);
331
+ if (!groupRec || !isWinStart(groupRec.start) || !groupRec.group || !isWinStart(groupRec.group.start)) {
332
+ await stopWinJob();
333
+ cleaned = true;
334
+ throw new Error(`hold: cannot verify command start identity for pid ${spawned.pid}`);
335
+ }
336
+ if (options.beforeRecordCommand)
337
+ await options.beforeRecordCommand();
338
+ ticket.command = { pid: groupRec.pid, start: groupRec.start };
339
+ ticket.group = { pid: groupRec.group.pid, start: groupRec.group.start };
340
+ await writeTicket(home, ticket).catch(() => { });
341
+ if (!jobEnded && readGroupEndSync(jobDir))
342
+ jobEnded = true;
343
+ while (!jobEnded) {
344
+ if (interrupted)
345
+ break;
346
+ if (args.yield) {
347
+ const all = liveTickets(home, args.resource, leaseOpts);
348
+ const waiter = all.filter(t => t.grantedAt === undefined && blockers(t, all).some(b => b.seq === ticket.seq)).sort(rank)[0];
349
+ if (waiter) {
350
+ await stopWinJob();
351
+ cleaned = true;
352
+ say(`hold: yielded ${args.resource} to ${who(waiter)} after ${age(Date.now() - ticket.grantedAt)}; the command was stopped (exit ${WAIT_EXPIRED})`);
353
+ return WAIT_EXPIRED;
354
+ }
355
+ }
356
+ await pause();
357
+ }
358
+ if (interrupted) {
359
+ await stopWinJob();
360
+ cleaned = true;
361
+ return 128 + (constants.signals[interrupted] ?? 1);
362
+ }
363
+ await spawned.exited;
364
+ const groupEnd = readGroupEndSync(jobDir);
365
+ if (!groupEnd) {
366
+ const detail = await startError(jobDir);
367
+ throw new Error(`hold: command job host ended without recording exit status${detail}`);
368
+ }
369
+ cleaned = true;
370
+ return groupEnd.status;
371
+ }
169
372
  // stdin stays attached only when it is not a terminal: a background group reading the terminal stops.
170
- const c = spawn(args.argv[0], args.argv.slice(1), { stdio: [process.stdin.isTTY ? "ignore" : "inherit", "inherit", "inherit"], detached: true,
171
- env: { ...env, DSA_HOLD: holdTag(ticket) } });
373
+ const target = execTarget(args.argv[0], args.argv.slice(1), { env });
374
+ const c = spawn(target.command, target.args, { stdio: [process.stdin.isTTY ? "ignore" : "inherit", "inherit", "inherit"], detached: true,
375
+ env: { ...env, DSA_HOLD: holdTag(ticket) }, windowsHide: true });
172
376
  child = c;
173
377
  let status;
174
378
  const exit = new Promise(resolve => {
@@ -177,8 +381,7 @@ export async function hold(args, options = {}) {
177
381
  });
178
382
  void exit.then(value => { status = value; wake(); });
179
383
  if (c.pid) {
180
- ticket.command = { pid: c.pid };
181
- ticket.command.start = (await captureStart(c.pid)) || undefined;
384
+ ticket.command = { pid: c.pid, start: (await captureStart(c.pid).catch(() => "")) || undefined };
182
385
  await writeTicket(home, ticket).catch(() => { });
183
386
  }
184
387
  while (status === undefined) {
@@ -200,8 +403,10 @@ export async function hold(args, options = {}) {
200
403
  watcher?.close();
201
404
  // Also covers errors during launch/capture/write and forwarded signals followed by command exit.
202
405
  try {
203
- if (child && !cleaned)
204
- await endLeaseProcesses(ticket, graceMs, say);
406
+ if (winJobActive && !cleaned)
407
+ await stopWinJob();
408
+ else if (child && !cleaned)
409
+ await endLeaseProcesses(ticket, graceMs, say, leaseOpts);
205
410
  }
206
411
  finally {
207
412
  removeTicket(home, ticket);
@@ -11,6 +11,7 @@ import { setTimeout as delay } from "node:timers/promises";
11
11
  import { readJournalSnapshot } from "../kernel/journal.js";
12
12
  import { journalPath, orchLedger } from "../paths.js";
13
13
  import { PS } from "../platform/proctable.js";
14
+ import { isWinStart, killProcessSync, winCommandLineSync } from "../platform/windows.js";
14
15
  import { JT } from "../types.js";
15
16
  import { restartInputError, restartRefusal } from "../orchestrator/restart.js";
16
17
  import { readerLedger } from "../orchestrator/reader-ledger.js";
@@ -27,7 +28,8 @@ export function cliInitiator(env) {
27
28
  let parent = "";
28
29
  try {
29
30
  parent = process.platform === "linux" ? readFileSync(`/proc/${process.ppid}/cmdline`, "utf8").replace(/\0/g, " ").trim()
30
- : process.platform === "darwin" ? execFileSync(PS, ["-o", "command=", "-p", String(process.ppid)], { encoding: "utf8", timeout: 1000, maxBuffer: 64 * 1024 }).trim() : "";
31
+ : process.platform === "darwin" ? execFileSync(PS, ["-o", "command=", "-p", String(process.ppid)], { encoding: "utf8", timeout: 1000, maxBuffer: 64 * 1024 }).trim()
32
+ : process.platform === "win32" ? winCommandLineSync(process.ppid) : "";
31
33
  }
32
34
  catch { /* Parent may have exited or /proc may be unavailable. */ }
33
35
  return { cli: { user: userInfo().username, host: hostname(), ppid: process.ppid, parent: parent.slice(0, 200) } };
@@ -50,8 +52,18 @@ export function legacyRestart(home, old, body, options = {}) {
50
52
  const reason = restartInputError(body, options.subagent) ?? restartRefusal(home, journalLiveCalls(home), body, options.tool);
51
53
  if (reason)
52
54
  return { applied: false, reason };
55
+ if ((options.platform ?? process.platform) === "win32") {
56
+ if (!isWinStart(old.start)) {
57
+ return { applied: false, reason: `cannot verify orchestrator identity for pid ${old.pid} (missing start token)` };
58
+ }
59
+ (options.killWinSync ?? killProcessSync)({ pid: old.pid, start: old.start });
60
+ return { applied: true };
61
+ }
53
62
  try {
54
- process.kill(old.pid, "SIGTERM");
63
+ if (options.killPosix)
64
+ options.killPosix(old.pid);
65
+ else
66
+ process.kill(old.pid, "SIGTERM");
55
67
  }
56
68
  catch (error) {
57
69
  if (error.code !== "ESRCH")
@@ -20,17 +20,48 @@ export function serviceFiles(home, dsa, entry, platform = process.platform, node
20
20
  }
21
21
  if (platform === "darwin")
22
22
  return [{ path: join(home, "Library/LaunchAgents", `${name}.plist`), content: `<?xml version="1.0" encoding="UTF-8"?>\n<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">\n<plist version="1.0"><dict>\n<key>Label</key><string>${name}</string>\n<key>ProgramArguments</key><array>${[node, entry, "start"].map(s => `<string>${xml(s)}</string>`).join("")}</array>\n<key>EnvironmentVariables</key><dict><key>DSA_HOME</key><string>${xml(dsa)}</string>${pi ? `<key>DSA_PI_BIN</key><string>${xml(pi)}</string>` : ""}</dict>\n<key>RunAtLoad</key><true/>\n<!-- Keep the detached orchestrator alive after the starter exits. -->\n<key>AbandonProcessGroup</key><true/>\n<key>StartInterval</key><integer>30</integer>\n</dict></plist>\n` }];
23
+ if (platform === "win32") {
24
+ // Task Scheduler launches wscript.exe (GUI subsystem) on start.vbs every minute, which runs start.cmd with
25
+ // SW_HIDE (window style 0) so interactive Windows desktops never flash a console window. The orchestrator itself
26
+ // runs detached and survives the starter exiting.
27
+ const dir = join(home, ".pi", "durable-subagents-service");
28
+ const cmdPath = join(dir, "start.cmd");
29
+ const vbsPath = join(dir, "start.vbs");
30
+ const bat = (s) => s.replace(/%/g, "%%").replace(/"/g, '""');
31
+ const vbs = (s) => s.replace(/"/g, '""');
32
+ return [
33
+ { path: cmdPath, content: `@echo off\r\nsetlocal\r\nset "DSA_HOME=${bat(dsa)}"\r\n${pi ? `set "DSA_PI_BIN=${bat(pi)}"\r\n` : ""}"${bat(node)}" "${bat(entry)}" start\r\n` },
34
+ { path: vbsPath, content: `CreateObject("WScript.Shell").Run "cmd.exe /d /s /c if 1==1 """ & "${vbs(cmdPath)}" & """", 0, False\r\n` },
35
+ ];
36
+ }
23
37
  throw new Error(`Starter service unavailable on ${platform}`);
24
38
  }
25
- /** P1: Invoke the platform service manager, surfacing the exact failed command. */
39
+ /** P1: Invoke the platform service manager, surfacing the exact failed command and execFile metadata. */
26
40
  export async function runServiceCommand(command, args) {
27
41
  try {
28
42
  await promisify(execFile)(command, args, { timeout: 10_000 });
29
43
  }
30
44
  catch (error) {
31
- throw new Error(`${command} ${args.join(" ")}: ${error.stderr || String(error)}`);
45
+ const e = error;
46
+ const wrapped = new Error(`${command} ${args.join(" ")}: ${e.stderr || String(error)}`);
47
+ if (e.code !== undefined)
48
+ wrapped.code = e.code;
49
+ if (e.killed)
50
+ wrapped.killed = true;
51
+ if (e.signal)
52
+ wrapped.signal = e.signal;
53
+ throw wrapped;
32
54
  }
33
55
  }
56
+ /** Whether a `schtasks /Query` failure reflects an execution/permission error rather than an absent task. */
57
+ function isSchtasksHardError(error) {
58
+ const e = error;
59
+ if (e?.killed || e?.signal)
60
+ return true;
61
+ if (typeof e?.code === "string" && ["ENOENT", "EACCES", "EPERM", "ETIMEDOUT", "EPIPE"].includes(e.code))
62
+ return true;
63
+ return /access is denied|denied|拒绝访问|zugriff verweigert|アクセスが拒否|accès refusé|acceso denegado|timed? ?out/i.test(String(error));
64
+ }
34
65
  /** P1: Activate or deactivate the optional starter; injected runners isolate service tests. */
35
66
  export async function manageService(files, install, options = {}) {
36
67
  const platform = options.platform ?? process.platform, write = options.write ?? console.log;
@@ -60,6 +91,50 @@ export async function manageService(files, install, options = {}) {
60
91
  const domain = `gui/${options.uid ?? process.getuid?.() ?? 0}`;
61
92
  await run("launchctl", install ? ["bootstrap", domain, files[0].path] : ["bootout", `${domain}/${name}`], install ? /already (bootstrapped|loaded)|service already exists/i : /not loaded|could not find service|no such process/i);
62
93
  }
94
+ else if (platform === "win32") {
95
+ const launcher = files.find(f => f.path.endsWith(".vbs"))?.path ?? files[0].path;
96
+ const command = launcher.endsWith(".vbs")
97
+ ? `wscript.exe //B //NoLogo "${launcher}"`
98
+ : `${process.env.ComSpec ?? "cmd.exe"} /d /s /c if 1==1 "${launcher}"`;
99
+ if (install) {
100
+ await run("schtasks", ["/Create", "/F", "/SC", "MINUTE", "/MO", "1", "/TN", name, "/TR", command]);
101
+ await run("schtasks", ["/Run", "/TN", name], /already running/i);
102
+ }
103
+ else if (options.dryRun) {
104
+ await run("schtasks", ["/Delete", "/F", "/TN", name]);
105
+ }
106
+ else {
107
+ // Locale-independent absence check: /Query exits non-zero when the task does not exist in any Windows UI language,
108
+ // while spawn/timeout/access-denied failures propagate instead of silently leaving a scheduled task behind.
109
+ let exists = true;
110
+ try {
111
+ await run("schtasks", ["/Query", "/TN", name]);
112
+ }
113
+ catch (queryError) {
114
+ if (isSchtasksHardError(queryError))
115
+ throw queryError;
116
+ exists = false;
117
+ }
118
+ if (exists) {
119
+ try {
120
+ await run("schtasks", ["/Delete", "/F", "/TN", name]);
121
+ }
122
+ catch (error) {
123
+ let stillExists = false;
124
+ try {
125
+ await run("schtasks", ["/Query", "/TN", name]);
126
+ stillExists = true;
127
+ }
128
+ catch (recheckError) {
129
+ if (isSchtasksHardError(recheckError))
130
+ throw error;
131
+ }
132
+ if (stillExists)
133
+ throw error;
134
+ }
135
+ }
136
+ }
137
+ }
63
138
  else
64
139
  throw new Error(`Starter service unavailable on ${platform}`);
65
140
  if (!install && !options.dryRun)
package/dist/cli/smoke.js CHANGED
@@ -6,6 +6,8 @@ import { tmpdir } from "node:os";
6
6
  import { join } from "node:path";
7
7
  import { promisify } from "node:util";
8
8
  import { ProcessTable } from "../platform/proctable.js";
9
+ import { execTarget } from "../platform/launch.js";
10
+ import { IS_WINDOWS } from "../platform/windows.js";
9
11
  import { Containment } from "../platform/containment.js";
10
12
  import { OsLock } from "../platform/lock.js";
11
13
  import { publishFile } from "../kernel/mailbox.js";
@@ -31,11 +33,11 @@ export async function smoke(env = process.env, tty = Boolean(process.stdin.isTTY
31
33
  child.stdin.on("error", () => { });
32
34
  try {
33
35
  const rows = await new ProcessTable().list(new Set([exec]));
34
- if (!rows.some(p => p.pid === child.pid && p.tag === exec && p.start === child.start))
35
- throw new Error("Child tag/start token not visible");
36
+ if (!rows.some(p => p.pid === child.pid && (IS_WINDOWS || p.tag === exec) && p.start === child.start))
37
+ throw new Error("Child start token not visible");
36
38
  await containment.fence(exec, [], { timeoutMs: 5000 });
37
39
  await child.exited;
38
- return "tag visible; tagged child fenced";
40
+ return IS_WINDOWS ? "start token visible; child tree fenced" : "tag visible; tagged child fenced";
39
41
  }
40
42
  finally {
41
43
  child.stdin.end();
@@ -70,7 +72,8 @@ export async function smoke(env = process.env, tty = Boolean(process.stdin.isTTY
70
72
  return "fsync and no-replace publication";
71
73
  });
72
74
  await check("pi-version", async () => {
73
- const { stdout } = await promisify(execFile)(env.DSA_PI_BIN ?? "pi", ["--version"], { env: { ...env, HOME: root, PI_CODING_AGENT_DIR: join(root, "agent"), PI_OFFLINE: "1", PI_SKIP_VERSION_CHECK: "1" }, cwd: root, timeout: 10_000, maxBuffer: 64 * 1024 });
75
+ const target = execTarget(env.DSA_PI_BIN ?? "pi", ["--version"], { env });
76
+ const { stdout } = await promisify(execFile)(target.command, target.args, { env: { ...env, HOME: root, PI_CODING_AGENT_DIR: join(root, "agent"), PI_OFFLINE: "1", PI_SKIP_VERSION_CHECK: "1" }, cwd: root, timeout: 10_000, maxBuffer: 64 * 1024, ...(target.verbatim ? { windowsVerbatimArguments: true } : {}) });
74
77
  if (!stdout.trim())
75
78
  throw new Error("pi returned no version");
76
79
  return stdout.trim();
@@ -95,8 +98,9 @@ export async function smoke(env = process.env, tty = Boolean(process.stdin.isTTY
95
98
  async function probe(env, root) {
96
99
  const report = join(root, "capabilities.json");
97
100
  const extension = fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "../agent/extension.ts" : "../agent/extension.js", import.meta.url));
98
- const child = spawn(env.DSA_PI_BIN ?? "pi", ["--mode", "rpc", "--no-session", "--no-extensions", "-e", extension], {
99
- cwd: root, stdio: ["pipe", "ignore", "pipe"], env: { ...env, DSA_PROBE: report, HOME: root, PI_CODING_AGENT_DIR: join(root, "agent"), PI_OFFLINE: "1", PI_SKIP_VERSION_CHECK: "1" }
101
+ const target = execTarget(env.DSA_PI_BIN ?? "pi", ["--mode", "rpc", "--no-session", "--no-extensions", "-e", extension], { env });
102
+ const child = spawn(target.command, target.args, {
103
+ cwd: root, stdio: ["pipe", "ignore", "pipe"], ...(target.verbatim ? { windowsVerbatimArguments: true } : {}), env: { ...env, DSA_PROBE: report, HOME: root, PI_CODING_AGENT_DIR: join(root, "agent"), PI_OFFLINE: "1", PI_SKIP_VERSION_CHECK: "1" }
100
104
  });
101
105
  let stderr = "", failed;
102
106
  child.stderr.on("data", chunk => { stderr += chunk; });
@@ -4,6 +4,8 @@ import { homedir } from "node:os";
4
4
  import { execFileSync } from "node:child_process";
5
5
  import { fileURLToPath } from "node:url";
6
6
  import { parseFrontmatter, parseFrontmatterList } from "./frontmatter.js";
7
+ import { shimScript } from "../platform/launch.js";
8
+ import { comspec } from "../platform/windows.js";
7
9
  import { cacheDir, dsaHome } from "../paths.js";
8
10
  const stamp = (p) => { if (!p)
9
11
  return null; try {
@@ -13,9 +15,10 @@ const stamp = (p) => { if (!p)
13
15
  catch {
14
16
  return `${p}@-`;
15
17
  } };
16
- /** The first `name` on PATH, resolved, with its stamp: what execFileSync would start. */
17
- function onPath(name, env) {
18
- const exts = process.platform === "win32" ? (env.PATHEXT ?? ".EXE;.CMD;.BAT").split(";").filter(Boolean).concat("") : [""];
18
+ /** The first `name` on PATH, resolved, with its stamp: what execFileSync would start. Windows has no extensionless
19
+ * executable (`npm` beside `npm.cmd` is a POSIX script, which Node refuses to run), so only PATHEXT names count. */
20
+ function onPath(name, env, platform) {
21
+ const exts = platform === "win32" ? (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean) : [""];
19
22
  for (const dir of (env.PATH ?? env.Path ?? "").split(path.delimiter)) {
20
23
  if (!dir)
21
24
  continue;
@@ -30,19 +33,44 @@ function onPath(name, env) {
30
33
  }
31
34
  return null;
32
35
  }
36
+ function npmLayout(npm, platform) {
37
+ if (platform !== "win32")
38
+ return { builtin: path.join(path.dirname(path.dirname(npm)), "npmrc"), fixed: /[\\/]npm[\\/]bin[\\/]npm(-cli\.js)?$/.test(npm) };
39
+ if (!/\.(?:cmd|bat)$/i.test(npm))
40
+ return { fixed: false };
41
+ const install = path.join(path.dirname(npm), "node_modules", "npm", "bin", "npm-cli.js");
42
+ const fixed = fs.existsSync(install);
43
+ const cli = fixed ? install : shimScript(npm);
44
+ return { cli, builtin: cli ? path.join(path.dirname(path.dirname(cli)), "npmrc") : undefined, fixed };
45
+ }
46
+ /** The `npm root -g` process. POSIX runs `npm` from PATH. Windows runs the script behind `npm.cmd` under the node PATH
47
+ * selects (npm takes its global prefix from the node running it, exactly as npm.cmd's own node would), else a PE
48
+ * `npm.exe`; a batch file that names no npm package script (a generated `npm.cmd` shim) runs through the command
49
+ * processor as a shell would, in the `"..."` form cmd /s unquotes at either end. */
50
+ function npmCommand(npm, node, env, platform) {
51
+ if (platform !== "win32")
52
+ return { command: "npm", args: ["root", "-g"] };
53
+ const { cli } = npmLayout(npm, platform);
54
+ if (cli)
55
+ return { command: node ?? process.execPath, args: [cli, "root", "-g"] };
56
+ if (!/\.(?:cmd|bat)$/i.test(npm))
57
+ return { command: npm, args: ["root", "-g"] };
58
+ return { command: comspec(env), args: ["/d", "/s", "/c", `""${npm}" root -g"`], verbatim: true };
59
+ }
33
60
  /** Everything `npm root -g` reads to decide its answer, except npm's own code: which npm and node PATH selects, the
34
61
  * prefix environment, and the user, global and builtin npmrc files. -g ignores the project's .npmrc, so cwd is not
35
62
  * part of it, unless `npm` is a version manager's shim (asdf, mise, Volta) rather than npm itself: the shim picks a
36
63
  * node per directory from files this key does not see, so its answer is only `fixed` for a few seconds. */
37
- function npmRootKey(env) {
38
- const npm = onPath("npm", env), node = onPath("node", env);
64
+ function npmRootKey(env, platform) {
65
+ const npm = onPath("npm", env, platform), node = onPath("node", env, platform);
66
+ const layout = npm ? npmLayout(npm, platform) : undefined;
39
67
  const vars = Object.keys(env).filter(k => /^(npm_config_(prefix|userconfig|globalconfig)|PREFIX|DESTDIR)$/i.test(k)).sort().map(k => `${k}=${env[k]}`);
40
68
  const userconfig = Object.entries(env).find(([k]) => /^npm_config_userconfig$/i.test(k))?.[1] ?? path.join(env.HOME || env.USERPROFILE || homedir(), ".npmrc");
41
- const prefix = env.PREFIX ?? (node ? (process.platform === "win32" ? path.dirname(node) : path.dirname(path.dirname(node))) : undefined);
69
+ const prefix = env.PREFIX ?? (node ? (platform === "win32" ? path.dirname(node) : path.dirname(path.dirname(node))) : undefined);
42
70
  const globalconfig = Object.entries(env).find(([k]) => /^npm_config_globalconfig$/i.test(k))?.[1] ?? (prefix && path.join(prefix, "etc", "npmrc"));
43
- const builtin = npm ? path.join(path.dirname(path.dirname(npm)), "npmrc") : undefined;
44
- const fixed = !!npm && /[\\/]npm[\\/]bin[\\/]npm(-cli\.js)?$/.test(npm);
45
- return { npm, fixed, key: JSON.stringify([stamp(npm ?? undefined), stamp(node ?? undefined), vars, stamp(userconfig), stamp(globalconfig), stamp(builtin), process.platform === "win32" ? null : stamp("/etc/npmrc"), fixed ? null : process.cwd()]) };
71
+ const builtin = layout?.builtin;
72
+ const fixed = layout?.fixed ?? false;
73
+ return { npm, node, fixed, key: JSON.stringify([stamp(npm ?? undefined), stamp(node ?? undefined), vars, stamp(userconfig), stamp(globalconfig), stamp(builtin), platform === "win32" ? null : stamp("/etc/npmrc"), fixed ? null : process.cwd()]) };
46
74
  }
47
75
  const NPM_ROOT_ENTRIES = 8, NPM_ROOT_RETRY_MS = 60_000, NPM_ROOT_SHIM_MS = 10_000;
48
76
  let npmRootMemo;
@@ -50,10 +78,11 @@ let npmRootMemo;
50
78
  * a busy machine, while every pi start, run admission and CLI request discovers agents. The answer is kept in this
51
79
  * process and in a small rebuildable cache file, keyed on npmRootKey; a changed input asks npm again. A failed answer
52
80
  * is null and is retried after a minute, never written to disk. A shim's answer stays in this process for ten seconds
53
- * and is never written to disk. No npm on PATH is null without starting anything. */
81
+ * and is never written to disk. No npm on PATH is null without starting anything. Windows runs the CLI behind `npm.cmd`
82
+ * under the node PATH selects, and a real npm install's answer is cached like npm itself's (npmCommand). */
54
83
  export function globalNpmRoot(options = {}) {
55
- const env = options.env ?? process.env;
56
- const { key, npm, fixed } = npmRootKey(env);
84
+ const env = options.env ?? process.env, platform = options.platform ?? process.platform;
85
+ const { key, npm, node, fixed } = npmRootKey(env, platform);
57
86
  if (!npm)
58
87
  return null;
59
88
  const now = Date.now();
@@ -75,8 +104,12 @@ export function globalNpmRoot(options = {}) {
75
104
  }
76
105
  }
77
106
  let root = null;
107
+ const ask = () => {
108
+ const { command, args, verbatim } = npmCommand(npm, node, env, platform);
109
+ return execFileSync(command, args, { encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "ignore"], env, ...(verbatim ? { windowsVerbatimArguments: true } : {}) });
110
+ };
78
111
  try {
79
- root = (options.run ?? (() => execFileSync("npm", ["root", "-g"], { encoding: "utf8", timeout: 5000, stdio: ["ignore", "pipe", "ignore"], env })))().trim() || null;
112
+ root = (options.run ?? ask)().trim() || null;
80
113
  }
81
114
  catch {
82
115
  root = null;