pi-durable-subagents 1.5.1 → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +69 -14
  3. package/dist/agent/capabilities.js +19 -11
  4. package/dist/agent/child/live.js +10 -2
  5. package/dist/agent/child.js +1 -1
  6. package/dist/agent/exact/capture.js +22 -2
  7. package/dist/agent/exact/child.js +8 -1
  8. package/dist/agent/exact/session.js +4 -2
  9. package/dist/agent/extension.js +13 -0
  10. package/dist/agent/main/snapshots.js +10 -9
  11. package/dist/agent/main.js +2 -1
  12. package/dist/cli/chaos/stack.js +53 -21
  13. package/dist/cli/control.js +4 -3
  14. package/dist/cli/doctor.js +3 -1
  15. package/dist/cli/drill/index.js +35 -17
  16. package/dist/cli/hold.js +221 -16
  17. package/dist/cli/main.js +7 -2
  18. package/dist/cli/restart.js +14 -2
  19. package/dist/cli/service.js +77 -2
  20. package/dist/cli/smoke.js +10 -6
  21. package/dist/compat/agents.js +47 -13
  22. package/dist/events/log.js +33 -11
  23. package/dist/kernel/cache.js +3 -2
  24. package/dist/kernel/fsx.js +203 -0
  25. package/dist/kernel/ids.js +11 -0
  26. package/dist/kernel/journal.js +42 -25
  27. package/dist/kernel/mailbox.js +7 -4
  28. package/dist/orchestrator/engine.js +49 -46
  29. package/dist/orchestrator/evaluator-client.js +11 -3
  30. package/dist/orchestrator/executor/command.js +21 -6
  31. package/dist/orchestrator/executor/digest.js +2 -2
  32. package/dist/orchestrator/executor/effects/gate.js +291 -56
  33. package/dist/orchestrator/executor/effects/index.js +3 -4
  34. package/dist/orchestrator/executor/effects/output.js +9 -5
  35. package/dist/orchestrator/executor/effects/prepare.js +34 -32
  36. package/dist/orchestrator/executor/effects/worktree-path.js +102 -0
  37. package/dist/orchestrator/executor/ended.js +7 -3
  38. package/dist/orchestrator/executor/index.js +216 -62
  39. package/dist/orchestrator/executor/memory.js +15 -0
  40. package/dist/orchestrator/executor/observe.js +6 -1
  41. package/dist/orchestrator/executor/session.js +10 -4
  42. package/dist/orchestrator/executor/sweep.js +34 -1
  43. package/dist/orchestrator/executor/usage.js +19 -5
  44. package/dist/orchestrator/executor/worktree.js +1 -1
  45. package/dist/orchestrator/main.js +4 -2
  46. package/dist/orchestrator/reader-ledger.js +3 -2
  47. package/dist/orchestrator/settled.js +2 -1
  48. package/dist/orchestrator/snapshot.js +24 -19
  49. package/dist/orchestrator/stats.js +2 -1
  50. package/dist/orchestrator/store.js +3 -2
  51. package/dist/platform/cmdline.js +3 -0
  52. package/dist/platform/command.js +184 -20
  53. package/dist/platform/containment.js +204 -40
  54. package/dist/platform/job.js +1404 -0
  55. package/dist/platform/launch.js +262 -29
  56. package/dist/platform/lease.js +351 -32
  57. package/dist/platform/lock.js +464 -16
  58. package/dist/platform/proctable.js +31 -2
  59. package/dist/platform/windows.js +642 -0
  60. package/dist/requests.js +1 -1
  61. package/dist/types.js +1 -0
  62. package/dist/ui/data.js +7 -6
  63. package/dist/ui/session.js +6 -5
  64. package/package.json +3 -3
@@ -14,6 +14,7 @@ import { cliInitiator } from "./restart.js";
14
14
  import { restartInputError } from "../orchestrator/restart.js";
15
15
  import { JT } from "../types.js";
16
16
  import { RequestsBusy, sendIdentified } from "../requests.js";
17
+ import { fileId } from "../kernel/ids.js";
17
18
  /** P1: Start the detached orchestrator only after probing its OS lock (platform/launch.ts: pi resolved here, its own
18
19
  * scope). Throws PiNotFound, starting nothing, when this environment has no pi: an orchestrator started here could
19
20
  * launch no subagent, and a request already published stays pending for the next starter that has pi. A replaced
@@ -125,11 +126,11 @@ export async function submitIdentified(home, rid, kind, body, cond, env = proces
125
126
  async function withSender(home, fn) {
126
127
  await mkdir(home, { recursive: true });
127
128
  const sender = `cli:${userInfo().username}@${hostname()}`;
128
- const locker = new OsLock(), deadline = performance.now() + 10_000;
129
- let lock = await locker.tryAcquire(join(home, `${sender}.lock`));
129
+ const locker = new OsLock(), deadline = performance.now() + (process.platform === "win32" ? 30_000 : 10_000), lockPath = join(home, `${fileId(sender)}.lock`);
130
+ let lock = await locker.tryAcquire(lockPath);
130
131
  while (!lock && performance.now() < deadline) {
131
132
  await delay(50);
132
- lock = await locker.tryAcquire(join(home, `${sender}.lock`));
133
+ lock = await locker.tryAcquire(lockPath);
133
134
  }
134
135
  if (!lock)
135
136
  throw new RequestsBusy("CLI sender is busy; retry the command");
@@ -44,7 +44,9 @@ async function lockHeld(home) {
44
44
  }
45
45
  }
46
46
  /** C2: The command that lists the processes still tagged with an execution identity. */
47
- const stuckProcesses = (exec) => process.platform === "linux" ? `grep -lsz ${quote(`DSA_EXEC=${exec}`)} /proc/*/environ` : `ps -Eww -o pid,command | grep -F ${quote(`DSA_EXEC=${exec}`)}`;
47
+ const stuckProcesses = (exec) => process.platform === "linux" ? `grep -lsz ${quote(`DSA_EXEC=${exec}`)} /proc/*/environ`
48
+ : process.platform === "win32" ? `powershell -NoProfile -Command "Get-CimInstance Win32_Process | Where-Object { $_.CommandLine -like '*${exec}*' } | Select-Object ProcessId,CommandLine"`
49
+ : `ps -Eww -o pid,command | grep -F ${quote(`DSA_EXEC=${exec}`)}`;
48
50
  /** Housekeeping: Collect DSA_HOME health facts read-only; `findings` lists only actionable ones, one command each. */
49
51
  export async function doctor(home, env = process.env, now = Date.now()) {
50
52
  const ledger = readJournalSnapshot(orchLedger(home));
@@ -12,6 +12,7 @@ import { readJournalSnapshot } from "../../kernel/journal.js";
12
12
  import { journalPath, orchLedger } from "../../paths.js";
13
13
  import { captureStart, ProcessTable } from "../../platform/proctable.js";
14
14
  import { Containment } from "../../platform/containment.js";
15
+ import { IS_WINDOWS, isWinStart, killProcess, sameCreation } from "../../platform/windows.js";
15
16
  import { JT } from "../../types.js";
16
17
  const A = "drill-a", B = "drill-b", POOL = "failover";
17
18
  /** Steps 1-3 (about 5 s here) must finish before it; 25 s leaves room for a loaded or several times slower machine
@@ -24,6 +25,9 @@ const STEPS = [
24
25
  `${A} answers again; after the probe interval the next call probes it and it is marked available`,
25
26
  `the third call (the probe) starts on ${A} and ends ok there`,
26
27
  ];
28
+ /** The drill's own settings: its two offline providers as one pool, and the probe interval the machine must meet
29
+ * (orchestrator/config.ts validates both). */
30
+ export const drillConfig = (probeMs = DRILL_PROBE_MS) => ({ pools: { [POOL]: [`${A}/m`, `${B}/m`] }, k: { probeMs } });
27
31
  /** Validate drill arguments before allocating a temporary root or starting anything. */
28
32
  export function parseDrill(args) {
29
33
  if (args[0] !== "failover")
@@ -58,10 +62,13 @@ export async function drill(args, inherited = process.env, write = console.log)
58
62
  // pi's retries stay on (a used-up window is noticed while pi retries, as on a real setup), with a short backoff.
59
63
  retry: { enabled: true, baseDelayMs: 200 }, compaction: { enabled: false }, defaultProjectTrust: "always" }));
60
64
  writeFileSync(join(cwd, ".pi/agents/worker.md"), "---\nname: worker\ndescription: Failover drill worker\ntools: bash\n---\nAnswer the task.\n");
61
- writeFileSync(join(home, "config.json"), JSON.stringify({ pools: { [POOL]: [`${A}/m`, `${B}/m`] }, k: { probeMs: DRILL_PROBE_MS } }));
65
+ writeFileSync(join(home, "config.json"), JSON.stringify(drillConfig()));
62
66
  writeFileSync(join(root, "a-exhausted"), "");
63
67
  const env = { PATH: inherited.PATH, HOME: join(root, "home"), TMPDIR: root, PI_CODING_AGENT_DIR: agent,
64
- PI_OFFLINE: "1", PI_SKIP_VERSION_CHECK: "1", PI_TELEMETRY: "0", DSA_HOME: home, DSA_DRILL_ROOT: root };
68
+ PI_OFFLINE: "1", PI_SKIP_VERSION_CHECK: "1", PI_TELEMETRY: "0", DSA_HOME: home, DSA_DRILL_ROOT: root,
69
+ // The drill exists to be diagnosable: keep what the detached orchestrator it starts says, for --keep and for a
70
+ // step that fails (the report names the root).
71
+ DSA_ORCHESTRATOR_LOG: join(root, "orchestrator.log") };
65
72
  const entry = sibling("../main");
66
73
  const cli = (argv) => new Promise((resolve, reject) => {
67
74
  const child = spawn(process.execPath, [entry, ...argv], { cwd, env, stdio: ["ignore", "pipe", "pipe"] });
@@ -259,23 +266,34 @@ export async function drill(args, inherited = process.env, write = console.log)
259
266
  async function cleanup(home) {
260
267
  const ledger = () => readJournalSnapshot(orchLedger(home));
261
268
  const hosts = ledger().filter(e => e.type === "orchestrator" && e.pid).map(e => ({ pid: Number(e.pid), start: e.start ? String(e.start) : undefined }));
262
- const same = async (h) => { const now = await captureStart(h.pid); return now !== "" && (h.start === undefined || now === h.start); };
263
- for (const h of hosts)
264
- if (await same(h)) {
265
- try {
266
- process.kill(h.pid, "SIGTERM");
269
+ if (IS_WINDOWS) {
270
+ // Fail closed against unverified PIDs: only end hosts with a recorded creation token, through handle verification.
271
+ for (const h of hosts)
272
+ if (isWinStart(h.start))
273
+ await killProcess({ pid: h.pid, start: h.start }).catch(() => { });
274
+ }
275
+ else {
276
+ const same = async (h) => {
277
+ const now = await captureStart(h.pid).catch(() => "");
278
+ return now !== "" && (h.start === undefined || (h.start !== "" && now === h.start));
279
+ };
280
+ for (const h of hosts)
281
+ if (await same(h)) {
282
+ try {
283
+ process.kill(h.pid, "SIGTERM");
284
+ }
285
+ catch { }
267
286
  }
268
- catch { }
269
- }
270
- const end = Date.now() + 15_000;
271
- for (const h of hosts) {
272
- while (await same(h) && Date.now() < end)
273
- await delay(100);
274
- if (await same(h)) {
275
- try {
276
- process.kill(h.pid, "SIGKILL");
287
+ const end = Date.now() + 15_000;
288
+ for (const h of hosts) {
289
+ while (await same(h) && Date.now() < end)
290
+ await delay(100);
291
+ if (await same(h)) {
292
+ try {
293
+ process.kill(h.pid, "SIGKILL");
294
+ }
295
+ catch { }
277
296
  }
278
- catch { }
279
297
  }
280
298
  }
281
299
  const containment = new Containment(new ProcessTable());
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);
package/dist/cli/main.js CHANGED
@@ -14,7 +14,7 @@ import { doctor, renderDoctor, size } from "./doctor.js";
14
14
  import { smoke } from "./smoke.js";
15
15
  import { serviceFiles, manageService } from "./service.js";
16
16
  import { leaseLines, leaseState } from "../platform/lease.js";
17
- import { resolvePi } from "../platform/launch.js";
17
+ import { resolveNode, resolvePi } from "../platform/launch.js";
18
18
  import { currentOrchestrator, decidedBy, legacyRestart, cliInitiator, waitExit, waitSuccessor } from "./restart.js";
19
19
  import { restartInputError } from "../orchestrator/restart.js";
20
20
  import { packageVersion } from "../version.js";
@@ -331,7 +331,12 @@ export async function main(args = process.argv.slice(2), options = {}) {
331
331
  const pi = command === "install-service" ? resolvePi(env) : {};
332
332
  if (command === "install-service" && !pi.path)
333
333
  write(`note: ${pi.problem}; the service can start an orchestrator only once DSA_PI_BIN is set in it`);
334
- const files = serviceFiles(env.HOME ?? homedir(), home, entry, process.platform, process.execPath, pi.path);
334
+ const nodeRes = resolveNode(env, { piPath: pi.path });
335
+ if (command === "install-service" && !nodeRes.path) {
336
+ (options.write ?? (line => console.error(line)))(`cannot install starter service: ${nodeRes.problem}. Set DSA_NODE_BIN to the absolute path of Node.js 22.19+, or put node on PATH`);
337
+ return 1;
338
+ }
339
+ const files = serviceFiles(env.HOME ?? homedir(), home, entry, process.platform, nodeRes.path ?? process.execPath, pi.path);
335
340
  await manageService(files, command === "install-service", { dryRun, runner: options.serviceRunner, write });
336
341
  files.forEach(f => write(`${command}: ${f.path}`));
337
342
  return 0;
@@ -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; });