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
@@ -0,0 +1,642 @@
1
+ // Native Windows support: PowerShell is the process observer (Win32_Process through CIM) and executes handle-verified
2
+ // process termination (OpenProcess + GetProcessTimes + TerminateProcess; never bare-PID taskkill /T, which ignores
3
+ // creation times across exit/PID reuse and non-reparented boot/system orphans). Environment variables of other processes
4
+ // are not readable on Windows, so process identity is (pid, creation time) and live creation-ordered process trees replace
5
+ // the inherited DSA_EXEC tag.
6
+ import { execFile, execFileSync } from "node:child_process";
7
+ import { existsSync } from "node:fs";
8
+ import { homedir, tmpdir } from "node:os";
9
+ import { join } from "node:path";
10
+ import { promisify } from "node:util";
11
+ const exec = promisify(execFile);
12
+ export const IS_WINDOWS = process.platform === "win32";
13
+ /** The Windows directory holding powershell.exe and cmd.exe. */
14
+ export function systemRoot(env = process.env) { return envValue(env, "SystemRoot") || envValue(env, "windir") || "C:\\Windows"; }
15
+ /** A variable of a Windows environment block. Names compare case-insensitively (`Path` is `PATH`, `ComSpec` is `COMSPEC`)
16
+ * and the last definition wins, exactly as `process.env` behaves on Windows; the value is the key's own spelling's. */
17
+ export function envValue(env, name) {
18
+ const lower = name.toLowerCase();
19
+ let value;
20
+ for (const key of Object.keys(env))
21
+ if (key.toLowerCase() === lower)
22
+ value = env[key];
23
+ return value;
24
+ }
25
+ /** One environment from `base` and the overrides applied in order. An override replaces every definition of its name under
26
+ * any spelling instead of adding a second one, so a block never carries `Path` beside `PATH`: Windows finds one variable
27
+ * per name, and a second definition is at best ignored (the wrapper's child would see the inherited PATH, not the
28
+ * command's). Keys keep the spelling of whichever definition won. */
29
+ export function mergeEnv(base, ...overrides) {
30
+ const env = { ...base };
31
+ for (const override of overrides) {
32
+ if (!override)
33
+ continue;
34
+ for (const [key, value] of Object.entries(override)) {
35
+ if (value === undefined)
36
+ continue;
37
+ const lower = key.toLowerCase();
38
+ for (const existing of Object.keys(env))
39
+ if (existing.toLowerCase() === lower)
40
+ delete env[existing];
41
+ env[key] = value;
42
+ }
43
+ }
44
+ return env;
45
+ }
46
+ /** An environment block with one definition per name (the later spelling wins): what a Windows child reads unambiguously. */
47
+ export const normalizeEnv = (env) => mergeEnv({}, env);
48
+ /** The whole 32-bit code of a Windows process status. Node hands the kernel's exit code back as a JS number whose bit
49
+ * pattern is that DWORD, on some paths and versions as a signed int32 (0xC0000005 reads -1073741819), so every status
50
+ * this package records, reads back or reports is normalized here: a negative number is not an exit status at all.
51
+ * (The Windows command wrapper, a standalone file, spells the same normalization itself; `>>> 0`.) */
52
+ export const dword = (status) => status >>> 0;
53
+ /** The largest status a Windows process can end with: its exit code is one DWORD. */
54
+ export const DWORD_MAX = 0xffffffff;
55
+ /** Supply OS defaults to helpers launched from deliberately isolated environments. */
56
+ export function helperEnv(base = process.env) {
57
+ // A derivation that fails must not take the helper down with it: a variable that stays unset is what it had before.
58
+ const attempt = (read, fallback) => { try {
59
+ return read() || fallback;
60
+ }
61
+ catch {
62
+ return fallback;
63
+ } };
64
+ const root = systemRoot(base), temp = envValue(base, "TEMP") || envValue(base, "TMP") || attempt(tmpdir, join(root, "Temp"));
65
+ const home = envValue(base, "USERPROFILE") || attempt(homedir, join(root, "Users", "Default"));
66
+ const system32 = join(root, "System32");
67
+ /** A default for a variable the caller lacks, under one Windows name: a caller that spelled it `Path` or `COMSPEC`
68
+ * keeps its own definition (and its own spelling) instead of getting a second one beside it. */
69
+ const missing = (name, value) => envValue(base, name) ? {} : { [name]: value };
70
+ return mergeEnv(base, {
71
+ ...missing("SystemRoot", root), ...missing("windir", root), ...missing("SystemDrive", root.slice(0, 2)),
72
+ ...missing("ComSpec", join(system32, "cmd.exe")),
73
+ ...missing("PATHEXT", ".COM;.EXE;.BAT;.CMD"),
74
+ ...missing("PSModulePath", join(system32, "WindowsPowerShell", "v1.0", "Modules")),
75
+ ...missing("TEMP", temp), ...missing("TMP", temp), ...missing("USERPROFILE", home),
76
+ ...missing("APPDATA", join(home, "AppData", "Roaming")),
77
+ ...missing("LOCALAPPDATA", join(home, "AppData", "Local")),
78
+ ...missing("PATH", [system32, root].join(";"))
79
+ });
80
+ }
81
+ /** Windows PowerShell 5.1 by its absolute path: every supported Windows has it. */
82
+ export function powershellPath() {
83
+ const local = join(systemRoot(), "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
84
+ return existsSync(local) ? local : "powershell.exe";
85
+ }
86
+ /** The command processor a string command runs through (`command calls` keep their shell semantics). */
87
+ export function comspec(env = process.env) {
88
+ return envValue(env, "ComSpec") || join(systemRoot(env), "System32", "cmd.exe");
89
+ }
90
+ function winTimeoutError(message) {
91
+ const error = new Error(message);
92
+ error.code = "ETIMEDOUT";
93
+ return error;
94
+ }
95
+ /** Whether an error from an async Windows helper/kill step represents deadline or abort expiry rather than a Win32 refusal. */
96
+ export function isWinKillTimeout(error) {
97
+ if (!error || typeof error !== "object")
98
+ return false;
99
+ const e = error;
100
+ if (e.name === "AbortError" || e.code === "ABORT_ERR" || e.code === "ETIMEDOUT")
101
+ return true;
102
+ return e.killed === true && e.code !== "ERR_CHILD_PROCESS_STDIO_MAXBUFFER";
103
+ }
104
+ const PS_PREAMBLE = "$ErrorActionPreference = 'Stop'; ";
105
+ const PS_FLAGS = ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command"];
106
+ /** Run a PowerShell script; rejects with its stderr. */
107
+ export async function powershell(script, options = {}) {
108
+ options.signal?.throwIfAborted();
109
+ const timeout = options.timeout ?? 15_000;
110
+ if (!Number.isFinite(timeout) || timeout <= 0)
111
+ throw winTimeoutError(`PowerShell timed out after ${timeout} ms`);
112
+ const { stdout } = await exec(powershellPath(), [...PS_FLAGS, PS_PREAMBLE + script], { signal: options.signal, timeout: Math.max(1, Math.ceil(timeout)), maxBuffer: 64 * 1024 * 1024, windowsHide: true, env: helperEnv() });
113
+ return stdout;
114
+ }
115
+ export function powershellSync(script, options = {}) {
116
+ const timeout = options.timeout ?? 15_000;
117
+ if (!Number.isFinite(timeout) || timeout <= 0)
118
+ throw winTimeoutError(`PowerShell timed out after ${timeout} ms`);
119
+ return execFileSync(powershellPath(), [...PS_FLAGS, PS_PREAMBLE + script], { timeout: Math.max(1, Math.ceil(timeout)), maxBuffer: 64 * 1024 * 1024, windowsHide: true, encoding: "utf8", env: helperEnv() });
120
+ }
121
+ const MAX_WIN_TICKS = 3155378975999999999n; // System.DateTime.MaxValue.Ticks
122
+ /** Valid Windows creation-time token: positive decimal .NET ticks within DateTime range. */
123
+ export function isWinStart(start) {
124
+ if (typeof start !== "string" || !/^\d{1,19}$/.test(start))
125
+ return false;
126
+ const ticks = BigInt(start);
127
+ return ticks > 0n && ticks <= MAX_WIN_TICKS;
128
+ }
129
+ /** Whether an observed start token names the same Windows process instance as a recorded creation time.
130
+ * GetProcessTimes truncates to whole microseconds ((creation / 10) * 10) and Win32_Process DMTF CreationDate carries
131
+ * whole microseconds as well; they agree within one microsecond unit (10 ticks), whereas any recycled pid is created
132
+ * at least a process lifetime later. Empty or malformed tokens fail closed (`false`). */
133
+ export function sameCreation(observed, recorded) {
134
+ if (!isWinStart(observed) || !isWinStart(recorded))
135
+ return false;
136
+ if (observed === recorded)
137
+ return true;
138
+ const a = BigInt(observed), b = BigInt(recorded);
139
+ return (a >= b ? a - b : b - a) <= 10n;
140
+ }
141
+ /** Whether a live row `child` can be a genuine child of a live row `parent` in the same process-table snapshot.
142
+ * Windows never reparents orphaned processes when their parent exits, so a recycled PID (`parent`) can match the static
143
+ * `ParentProcessId` of a long-running system/user process created before `parent` existed (e.g. a critical system
144
+ * process created at boot). Requiring `child.start >= parent.start` while `parent` is live excludes all pre-existing
145
+ * orphans on that PID, and because `parent` is still live no later incarnation of `parent.pid` has existed yet. */
146
+ export function isOwnedWinChild(parent, child) {
147
+ if (child.pid === parent.pid || child.ppid !== parent.pid)
148
+ return false;
149
+ if (!isWinStart(parent.start) || !isWinStart(child.start))
150
+ return false;
151
+ return BigInt(child.start) >= BigInt(parent.start);
152
+ }
153
+ /** Proven-owned live descendants of `roots` in a single snapshot `rows`. Only roots that are themselves live with a
154
+ * matching creation time in `rows` may expand `ParentProcessId` edges: once a parent exits, its numeric PID can be
155
+ * recycled by an unrelated process whose children share that numeric `ppid` and have later creation times. */
156
+ export function winLiveDescendants(roots, rows) {
157
+ const byPid = new Map(), byParent = new Map();
158
+ for (const row of rows) {
159
+ if (!Number.isInteger(row.pid) || row.pid <= 0 || !isWinStart(row.start))
160
+ continue;
161
+ byPid.set(row.pid, row);
162
+ const list = byParent.get(row.ppid);
163
+ if (list)
164
+ list.push(row);
165
+ else
166
+ byParent.set(row.ppid, [row]);
167
+ }
168
+ const rootPids = new Set(), seen = new Set(), queue = [], out = [];
169
+ for (const root of roots) {
170
+ if (!Number.isInteger(root.pid) || root.pid <= 0 || !isWinStart(root.start))
171
+ continue;
172
+ const live = byPid.get(root.pid);
173
+ if (live && sameCreation(live.start, root.start) && !seen.has(live.pid)) {
174
+ rootPids.add(live.pid);
175
+ seen.add(live.pid);
176
+ queue.push(live);
177
+ }
178
+ }
179
+ for (let i = 0; i < queue.length; i++) {
180
+ const parent = queue[i];
181
+ for (const child of byParent.get(parent.pid) ?? []) {
182
+ if (seen.has(child.pid) || !isOwnedWinChild(parent, child))
183
+ continue;
184
+ seen.add(child.pid);
185
+ queue.push(child);
186
+ if (!rootPids.has(child.pid))
187
+ out.push(child);
188
+ }
189
+ }
190
+ return out;
191
+ }
192
+ /** One line per process: pid, ppid, creation ticks, CPU (100ns -> ms) and command line (tabs/newlines replaced by
193
+ * spaces so a line stays one row). */
194
+ const creationTicks = "[System.Management.ManagementDateTimeConverter]::ToDateTime($p.CreationDate).Ticks";
195
+ function processQuery(fields, body, pid) {
196
+ const where = pid === undefined ? "" : ` WHERE ProcessId=${pid}`;
197
+ return `$s = [wmisearcher]'SELECT ${fields} FROM Win32_Process${where}'; foreach ($p in $s.Get()) { ${body} }`;
198
+ }
199
+ export const PROCESS_ROWS_SCRIPT = processQuery("ProcessId,ParentProcessId,CreationDate,UserModeTime,KernelModeTime,CommandLine", `if (!$p.CreationDate) { continue }; $t = ${creationTicks}; ` +
200
+ '$c = ([string]$p.CommandLine) -replace "[`t`r`n]", " "; ' +
201
+ '"{0}`t{1}`t{2}`t{3}`t{4}" -f $p.ProcessId, $p.ParentProcessId, $t, ([uint64]$p.UserModeTime + [uint64]$p.KernelModeTime), $c');
202
+ export function parseProcessRows(stdout) {
203
+ const rows = [];
204
+ for (const line of stdout.split(/\r?\n/)) {
205
+ if (!line)
206
+ continue;
207
+ const [pid, ppid, start, cpu, ...rest] = line.split("\t");
208
+ const id = Number(pid), parent = Number(ppid), ticks = Number(cpu);
209
+ if (!Number.isInteger(id) || id <= 0 || !Number.isInteger(parent) || parent < 0 || !isWinStart(start))
210
+ continue;
211
+ rows.push({ pid: id, ppid: parent, start, ...(Number.isFinite(ticks) ? { cpuMs: ticks / 10_000 } : {}),
212
+ ...(rest.length ? { command: rest.join(" ") } : {}) });
213
+ }
214
+ return rows;
215
+ }
216
+ /** One full process-table observation (about 0.5 s: PowerShell startup plus the CIM query). */
217
+ export async function winProcessRows(options = {}) {
218
+ return parseProcessRows(await powershell(PROCESS_ROWS_SCRIPT, options));
219
+ }
220
+ let snapshot;
221
+ /** Test helper: clear the short-lived synchronous Windows snapshot cache. */
222
+ export function resetWinSnapshotCache() {
223
+ snapshot = undefined;
224
+ }
225
+ function readWinSnapshotSync(maxAgeMs = 250, options) {
226
+ const clock = options?.now ?? Date.now;
227
+ const now = clock();
228
+ if (!snapshot || now < snapshot.at || now - snapshot.at > maxAgeMs) {
229
+ const runSync = options?.runSync ?? powershellSync;
230
+ const rows = parseProcessRows(runSync(PROCESS_ROWS_SCRIPT));
231
+ snapshot = { at: clock(), rows: new Map(rows.map(row => [row.pid, row])) };
232
+ return { rows: snapshot.rows, fresh: true };
233
+ }
234
+ return { rows: snapshot.rows, fresh: false };
235
+ }
236
+ /** A short-lived synchronous snapshot for lease readers and liveness checks. Propagates query failures instead of
237
+ * returning an empty table (missing rows are not proof of death, and an error must never look like every process exited). */
238
+ export function winSnapshotSync(maxAgeMs = 250, options) {
239
+ return readWinSnapshotSync(maxAgeMs, options).rows;
240
+ }
241
+ /** Probe whether a PID exists in the kernel while distinguishing accessible processes (`"alive"`) from protected or
242
+ * cross-user processes (`"eperm"`) and absent PIDs (`"dead"`). */
243
+ export function probeKernelPid(pid, kill = process.kill) {
244
+ if (!Number.isInteger(pid) || pid <= 0)
245
+ return "dead";
246
+ try {
247
+ kill(pid, 0);
248
+ return "alive";
249
+ }
250
+ catch (error) {
251
+ return error.code === "EPERM" ? "eperm" : "dead";
252
+ }
253
+ }
254
+ /** Whether a Windows process still runs, verifying `expectedStart` when provided.
255
+ * - Without `expectedStart`, `"alive"` and `"eperm"` both return `true` (PID exists).
256
+ * - With `expectedStart`, a protected process (`"eperm"`) absent from a successful snapshot (e.g. empty
257
+ * `CreationDate` filtered out by `parseProcessRows`) fails closed (`false`) instead of assuming PID reuse matches.
258
+ * - Transient snapshot query errors never crash callers or silently turn live accessible processes into dead. */
259
+ export function winProcessAlive(pid, expectedStart, options = {}) {
260
+ const probe = (options.probePid ?? probeKernelPid)(pid);
261
+ if (probe === "dead")
262
+ return false;
263
+ if (!expectedStart)
264
+ return true;
265
+ if (!isWinStart(expectedStart))
266
+ return false;
267
+ let rows;
268
+ let fresh = false;
269
+ try {
270
+ if (options.snapshotWin) {
271
+ rows = options.snapshotWin();
272
+ }
273
+ else {
274
+ const snap = readWinSnapshotSync();
275
+ rows = snap.rows;
276
+ fresh = snap.fresh;
277
+ }
278
+ }
279
+ catch {
280
+ return probe === "alive";
281
+ }
282
+ const row = rows.get(pid);
283
+ if (row)
284
+ return sameCreation(row.start, expectedStart);
285
+ if (probe === "eperm")
286
+ return false;
287
+ if (options.startWinSync) {
288
+ try {
289
+ const direct = options.startWinSync(pid);
290
+ return direct ? sameCreation(direct, expectedStart) : false;
291
+ }
292
+ catch {
293
+ return true;
294
+ }
295
+ }
296
+ if (fresh)
297
+ return false;
298
+ try {
299
+ const refreshed = options.snapshotWin ? options.snapshotWin(0) : readWinSnapshotSync(0).rows;
300
+ const freshRow = refreshed.get(pid);
301
+ return freshRow ? sameCreation(freshRow.start, expectedStart) : false;
302
+ }
303
+ catch {
304
+ return true;
305
+ }
306
+ }
307
+ /** The creation-time token of one process ("" when it has already gone; rejects when the observer itself fails). */
308
+ export async function winStart(pid, options = {}) {
309
+ if (!Number.isInteger(pid) || pid <= 0)
310
+ return "";
311
+ const out = (await powershell(processQuery("CreationDate", `if ($p.CreationDate) { ${creationTicks} }`, pid), options)).trim();
312
+ if (!out)
313
+ return "";
314
+ if (!isWinStart(out))
315
+ throw new Error(`Invalid Windows creation time for pid ${pid}: ${String(out).slice(0, 80)}`);
316
+ return out;
317
+ }
318
+ export function winStartSync(pid) {
319
+ if (!Number.isInteger(pid) || pid <= 0)
320
+ return "";
321
+ try {
322
+ const out = powershellSync(processQuery("CreationDate", `if ($p.CreationDate) { ${creationTicks} }`, pid)).trim();
323
+ return isWinStart(out) ? out : "";
324
+ }
325
+ catch {
326
+ return "";
327
+ }
328
+ }
329
+ /** Normalize and bound a diagnostic Windows command line (EX1: at most 200 characters, single-spaced). */
330
+ export function clipWinCommandLine(command) {
331
+ return command.trim().replace(/\s+/g, " ").slice(0, 200);
332
+ }
333
+ const SCANNED_COMMAND = Symbol("dsa.win.scannedCommand");
334
+ /** Attach a diagnostic command line observed during a fresh Windows process-table scan without adding an enumerable
335
+ * field (so `gate-tracked`/`eval-tracked` journal serialization and `ProcInfo` shape remain unchanged). */
336
+ export function attachScannedCommand(proc, command) {
337
+ if (typeof command === "string") {
338
+ Object.defineProperty(proc, SCANNED_COMMAND, { value: clipWinCommandLine(command), enumerable: false, configurable: true });
339
+ }
340
+ return proc;
341
+ }
342
+ /** Read a diagnostic command line already observed on a scanned process row, if present. */
343
+ export function scannedCommand(proc) {
344
+ if (!proc || typeof proc !== "object")
345
+ return undefined;
346
+ const carrier = proc;
347
+ if (typeof carrier[SCANNED_COMMAND] === "string")
348
+ return carrier[SCANNED_COMMAND];
349
+ if (typeof carrier.command === "string")
350
+ return clipWinCommandLine(carrier.command);
351
+ return undefined;
352
+ }
353
+ /** A diagnostic command line (never evidence of identity or death). */
354
+ export async function winCommandLine(pid, signal) {
355
+ if (!Number.isInteger(pid) || pid <= 0 || signal?.aborted)
356
+ return "";
357
+ try {
358
+ const out = await powershell(processQuery("CommandLine", "$p.CommandLine", pid), { signal, timeout: 1000 });
359
+ return clipWinCommandLine(out);
360
+ }
361
+ catch {
362
+ return "";
363
+ }
364
+ }
365
+ export function winCommandLineSync(pid) {
366
+ if (!Number.isInteger(pid) || pid <= 0)
367
+ return "";
368
+ try {
369
+ return clipWinCommandLine(powershellSync(processQuery("CommandLine", "$p.CommandLine", pid), { timeout: 1000 }));
370
+ }
371
+ catch {
372
+ return "";
373
+ }
374
+ }
375
+ /** Prefix of versioned Windows command-line tags: base64url UTF-8 so spaces, quotes, `&`, `%` and arbitrary Unicode
376
+ * travel as one unquoted ASCII token and cannot collide with legacy ids or `DSA_HOLD` (`<resource>:<seq>`). */
377
+ export const WIN_TAG_PREFIX = "v1~";
378
+ /** Encode `<name>=<value>` as one ASCII command-line token safe for CreateProcess argv and cmd.exe without quoting. */
379
+ export function winTagArg(name, value) {
380
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name))
381
+ throw new Error(`Invalid Windows tag name: ${name}`);
382
+ if (!value)
383
+ throw new Error(`Invalid Windows tag value for ${name}`);
384
+ return `${name}=${WIN_TAG_PREFIX}${Buffer.from(value, "utf8").toString("base64url")}`;
385
+ }
386
+ function decodeWinTag(raw) {
387
+ const payload = raw.slice(WIN_TAG_PREFIX.length);
388
+ if (!/^[A-Za-z0-9_-]+$/.test(payload))
389
+ return undefined;
390
+ const bytes = Buffer.from(payload, "base64url");
391
+ if (!bytes.length || bytes.toString("base64url") !== payload)
392
+ return undefined;
393
+ const decoded = bytes.toString("utf8");
394
+ return decoded && Buffer.from(decoded, "utf8").equals(bytes) ? decoded : undefined;
395
+ }
396
+ /** A tag carried in a command line (`DSA_EXEC=v1~<base64url>`, with legacy `DSA_EXEC=<id>` read compatibility), the
397
+ * Windows substitute for an unreadable environment: a launcher we control writes it into its own argv so a crash
398
+ * before the identity is journaled still finds the process. */
399
+ export function winTag(command, name) {
400
+ if (!command || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(name))
401
+ return undefined;
402
+ const pattern = new RegExp(`(?:^|\\s)"?${name}=([^\\s&"')]+)`, "g");
403
+ const versioned = new Set(), legacy = new Set();
404
+ let sawVersioned = false;
405
+ for (const match of command.matchAll(pattern)) {
406
+ const raw = match[1];
407
+ if (raw.startsWith(WIN_TAG_PREFIX)) {
408
+ sawVersioned = true;
409
+ const decoded = decodeWinTag(raw);
410
+ if (decoded !== undefined)
411
+ versioned.add(decoded);
412
+ }
413
+ else
414
+ legacy.add(raw);
415
+ }
416
+ if (sawVersioned)
417
+ return versioned.size === 1 ? versioned.values().next().value : undefined;
418
+ return legacy.size === 1 ? legacy.values().next().value : undefined;
419
+ }
420
+ export const KILL_BATCH_SIZE = 128;
421
+ /** Validate and deduplicate Windows `(pid, start)` targets. Fails closed on any missing or malformed identity. */
422
+ export function normalizeWinTargets(targets) {
423
+ const list = Array.isArray(targets) ? targets : [targets];
424
+ const deduped = new Map();
425
+ for (const target of list) {
426
+ if (!target || !Number.isInteger(target.pid) || target.pid <= 0 || target.pid > DWORD_MAX || !isWinStart(target.start)) {
427
+ throw new Error(`Refusing to end Windows process without verified identity (pid=${String(target?.pid)}, start=${JSON.stringify(target?.start)})`);
428
+ }
429
+ deduped.set(`${target.pid}:${target.start}`, { pid: target.pid, start: target.start });
430
+ }
431
+ return [...deduped.values()];
432
+ }
433
+ /** Build the in-memory Win32 handle-verified termination script (never uses bare-PID `taskkill /T`).
434
+ * Each target handle is verified via `GetProcessTimes` before `TerminateProcess` on that same handle, and verified
435
+ * parent handles stay open until descendant discovery completes so Windows cannot recycle a parent PID mid-sweep. */
436
+ export function buildWinKillScript(targets, includeDescendants) {
437
+ const checked = normalizeWinTargets(targets);
438
+ const spec = checked.map(t => `${t.pid}:${t.start}`).join(";");
439
+ return [
440
+ "if (!('DsaWin32.Kernel' -as [type])) {",
441
+ " $ab = [System.Reflection.Emit.AssemblyBuilder]::DefineDynamicAssembly((New-Object System.Reflection.AssemblyName 'DsaWin32'), [System.Reflection.Emit.AssemblyBuilderAccess]::Run)",
442
+ " $mb = $ab.DefineDynamicModule('DsaWin32')",
443
+ " $tb = $mb.DefineType('DsaWin32.Kernel', 'Public,Abstract,Sealed')",
444
+ " $ctor = [System.Runtime.InteropServices.DllImportAttribute].GetConstructor(@([string]))",
445
+ " $sle = [System.Runtime.InteropServices.DllImportAttribute].GetField('SetLastError')",
446
+ " $attr = New-Object System.Reflection.Emit.CustomAttributeBuilder($ctor, @('kernel32.dll'), @($sle), @($true))",
447
+ " $add = { param([string]$n, [type]$r, [type[]]$p); $m = $tb.DefineMethod($n, 'Public,Static,PinvokeImpl', $r, $p); $m.SetCustomAttribute($attr) }",
448
+ " & $add 'OpenProcess' ([IntPtr]) ([type[]]@([uint32], [bool], [uint32]))",
449
+ " & $add 'GetProcessTimes' ([bool]) ([type[]]@([IntPtr], [int64].MakeByRefType(), [int64].MakeByRefType(), [int64].MakeByRefType(), [int64].MakeByRefType()))",
450
+ " & $add 'IsProcessCritical' ([bool]) ([type[]]@([IntPtr], [bool].MakeByRefType()))",
451
+ " & $add 'TerminateProcess' ([bool]) ([type[]]@([IntPtr], [uint32]))",
452
+ " & $add 'CloseHandle' ([bool]) ([type[]]@([IntPtr]))",
453
+ " [void]$tb.CreateType()",
454
+ "}",
455
+ "$QUERY = [uint32]0x1000; $TERM = [uint32]0x1001; $selfPid = [uint32]$PID",
456
+ "$held = New-Object 'System.Collections.Generic.List[IntPtr]'",
457
+ "$seen = New-Object 'System.Collections.Generic.HashSet[uint32]'",
458
+ "$step = {",
459
+ " param([uint32]$targetPid, [int64]$expectedTicks, [int64]$minCreationFt)",
460
+ " if ($targetPid -eq 0 -or $targetPid -eq $selfPid -or $seen.Contains($targetPid)) { return $null }",
461
+ " $hQuery = [DsaWin32.Kernel]::OpenProcess($QUERY, $false, $targetPid)",
462
+ " if ($hQuery -eq [IntPtr]::Zero) {",
463
+ " $err = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()",
464
+ " if ($err -eq 87) { return $null }",
465
+ " if ($err -eq 5) {",
466
+ " $rows = @(([wmisearcher]\"SELECT CreationDate FROM Win32_Process WHERE ProcessId=$targetPid\").Get())",
467
+ " if ($rows.Count -eq 0) { return $null }",
468
+ " foreach ($r in $rows) {",
469
+ " if (!$r.CreationDate) { throw \"Unverifiable process identity for pid $targetPid (OpenProcess denied)\" }",
470
+ " $wt = [int64][System.Management.ManagementDateTimeConverter]::ToDateTime($r.CreationDate).Ticks",
471
+ " $wd = if ($wt -ge $expectedTicks) { $wt - $expectedTicks } else { $expectedTicks - $wt }",
472
+ " if ($wd -le [int64]10) { throw \"OpenProcess denied for verified live pid $targetPid\" }",
473
+ " }",
474
+ " return $null",
475
+ " }",
476
+ " throw \"OpenProcess($targetPid) failed with Win32 error $err\"",
477
+ " }",
478
+ " $keepQuery = $false",
479
+ " try {",
480
+ " [int64]$creation = 0; [int64]$exit = 0; [int64]$k = 0; [int64]$u = 0",
481
+ " if (![DsaWin32.Kernel]::GetProcessTimes($hQuery, [ref]$creation, [ref]$exit, [ref]$k, [ref]$u) -or $creation -le 0) {",
482
+ " $err = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()",
483
+ " throw \"GetProcessTimes($targetPid) failed with Win32 error $err\"",
484
+ " }",
485
+ " if ($minCreationFt -gt 0 -and $creation -lt $minCreationFt) { return $null }",
486
+ " $obsTicks = [int64][System.DateTime]::FromFileTime($creation - ($creation % [int64]10)).Ticks",
487
+ " $diff = if ($obsTicks -ge $expectedTicks) { $obsTicks - $expectedTicks } else { $expectedTicks - $obsTicks }",
488
+ " if ($diff -gt [int64]10) { return $null }",
489
+ " [void]$seen.Add($targetPid)",
490
+ " $held.Add($hQuery); $keepQuery = $true",
491
+ " $node = [pscustomobject]@{ Pid = $targetPid; CreationFt = $creation; Ticks = $obsTicks }",
492
+ " if ($exit -ne 0) { return $node }",
493
+ " $hTerm = [DsaWin32.Kernel]::OpenProcess($TERM, $false, $targetPid)",
494
+ " if ($hTerm -eq [IntPtr]::Zero) {",
495
+ " $err = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()",
496
+ " if ($err -eq 87) { return $node }",
497
+ " [int64]$c2 = 0; [int64]$e2 = 0; [int64]$k2 = 0; [int64]$u2 = 0",
498
+ " if ([DsaWin32.Kernel]::GetProcessTimes($hQuery, [ref]$c2, [ref]$e2, [ref]$k2, [ref]$u2) -and $e2 -ne 0) { return $node }",
499
+ " throw \"OpenProcess(PROCESS_TERMINATE, $targetPid) failed with Win32 error $err\"",
500
+ " }",
501
+ " try {",
502
+ " [int64]$tc = 0; [int64]$te = 0; [int64]$tk = 0; [int64]$tu = 0",
503
+ " if (![DsaWin32.Kernel]::GetProcessTimes($hTerm, [ref]$tc, [ref]$te, [ref]$tk, [ref]$tu) -or $tc -ne $creation) { return $null }",
504
+ " if ($te -ne 0) { return $node }",
505
+ " [bool]$critical = $false",
506
+ " if (![DsaWin32.Kernel]::IsProcessCritical($hTerm, [ref]$critical) -or $critical) { throw \"Refusing to end critical or unverified process $targetPid\" }",
507
+ " if (![DsaWin32.Kernel]::TerminateProcess($hTerm, [uint32]1)) {",
508
+ " $err = [System.Runtime.InteropServices.Marshal]::GetLastWin32Error()",
509
+ " [int64]$c3 = 0; [int64]$e3 = 0; [int64]$k3 = 0; [int64]$u3 = 0",
510
+ " if (!([DsaWin32.Kernel]::GetProcessTimes($hTerm, [ref]$c3, [ref]$e3, [ref]$k3, [ref]$u3) -and $e3 -ne 0)) {",
511
+ " throw \"TerminateProcess($targetPid) failed with Win32 error $err\"",
512
+ " }",
513
+ " }",
514
+ " return $node",
515
+ " } finally { [void][DsaWin32.Kernel]::CloseHandle($hTerm) }",
516
+ " } finally { if (!$keepQuery) { [void][DsaWin32.Kernel]::CloseHandle($hQuery) } }",
517
+ "}",
518
+ "try {",
519
+ " $inv = [Globalization.CultureInfo]::InvariantCulture",
520
+ " $parents = New-Object 'System.Collections.Generic.Dictionary[uint32, object]'",
521
+ ` foreach ($entry in ('${spec}' -split ';')) {`,
522
+ " if (!$entry) { continue }",
523
+ " $parts = $entry -split ':'",
524
+ " $res = & $step ([uint32]::Parse($parts[0], $inv)) ([int64]::Parse($parts[1], $inv)) ([int64]0)",
525
+ " if ($null -ne $res) { $parents[$res.Pid] = $res }",
526
+ " }",
527
+ ...(includeDescendants ? [
528
+ " while ($parents.Count -gt 0) {",
529
+ " $next = New-Object 'System.Collections.Generic.Dictionary[uint32, object]'",
530
+ " $scan = ([wmisearcher]'SELECT ProcessId,ParentProcessId,CreationDate FROM Win32_Process').Get()",
531
+ " foreach ($p in $scan) {",
532
+ " $ppid = [uint32]$p.ParentProcessId; $cpid = [uint32]$p.ProcessId",
533
+ " if (!$parents.ContainsKey($ppid) -or $cpid -eq 0 -or $cpid -eq $selfPid -or $seen.Contains($cpid) -or !$p.CreationDate) { continue }",
534
+ " $pInfo = $parents[$ppid]",
535
+ " $ct = [int64][System.Management.ManagementDateTimeConverter]::ToDateTime($p.CreationDate).Ticks",
536
+ " if ($ct + [int64]10 -lt [int64]$pInfo.Ticks) { continue }",
537
+ " $res = & $step $cpid $ct ([int64]$pInfo.CreationFt)",
538
+ " if ($null -ne $res) { $next[$res.Pid] = $res }",
539
+ " }",
540
+ " $parents = $next",
541
+ " }",
542
+ ] : []),
543
+ "} finally { foreach ($h in $held) { [void][DsaWin32.Kernel]::CloseHandle($h) } }",
544
+ ].join("\n");
545
+ }
546
+ async function runWinKill(targets, includeDescendants, options = {}) {
547
+ const checked = normalizeWinTargets(targets);
548
+ const name = includeDescendants ? "killTree" : "killProcess";
549
+ if ((options.platform ?? process.platform) !== "win32" && !options.run) {
550
+ throw new Error(`${name} is Windows-only`);
551
+ }
552
+ if (!checked.length)
553
+ return;
554
+ const budget = options.timeout ?? 10_000;
555
+ if (!Number.isFinite(budget) || budget < 0)
556
+ throw new Error(`Invalid ${name} timeout`);
557
+ options.signal?.throwIfAborted();
558
+ if (budget === 0)
559
+ throw winTimeoutError(`${name} timed out after 0 ms`);
560
+ const deadline = performance.now() + budget;
561
+ const controller = new AbortController();
562
+ let timer;
563
+ let onAbort;
564
+ const run = options.run ?? ((script, opts) => powershell(script, opts));
565
+ try {
566
+ const interrupted = new Promise((_, reject) => {
567
+ onAbort = () => {
568
+ const reason = options.signal?.reason ?? new DOMException("The operation was aborted", "AbortError");
569
+ reject(reason);
570
+ controller.abort(reason);
571
+ };
572
+ options.signal?.addEventListener("abort", onAbort, { once: true });
573
+ timer = setTimeout(() => {
574
+ const err = winTimeoutError(`${name} timed out after ${budget} ms`);
575
+ reject(err);
576
+ controller.abort(err);
577
+ }, budget);
578
+ });
579
+ void interrupted.catch(() => { });
580
+ for (let i = 0; i < checked.length; i += KILL_BATCH_SIZE) {
581
+ options.signal?.throwIfAborted();
582
+ if (controller.signal.aborted)
583
+ throw controller.signal.reason;
584
+ const remaining = deadline - performance.now();
585
+ if (remaining <= 0) {
586
+ const err = winTimeoutError(`${name} timed out after ${budget} ms`);
587
+ controller.abort(err);
588
+ throw err;
589
+ }
590
+ const batch = checked.slice(i, i + KILL_BATCH_SIZE);
591
+ const pending = Promise.resolve().then(() => run(buildWinKillScript(batch, includeDescendants), {
592
+ timeout: Math.max(1, Math.ceil(remaining)),
593
+ signal: controller.signal,
594
+ }));
595
+ void pending.catch(() => { });
596
+ await Promise.race([pending, interrupted]);
597
+ }
598
+ }
599
+ finally {
600
+ clearTimeout(timer);
601
+ if (onAbort)
602
+ options.signal?.removeEventListener("abort", onAbort);
603
+ controller.abort();
604
+ }
605
+ }
606
+ function runWinKillSync(targets, includeDescendants, options = {}) {
607
+ const checked = normalizeWinTargets(targets);
608
+ const name = includeDescendants ? "killTreeSync" : "killProcessSync";
609
+ if ((options.platform ?? process.platform) !== "win32" && !options.runSync) {
610
+ throw new Error(`${name} is Windows-only`);
611
+ }
612
+ if (!checked.length)
613
+ return;
614
+ const budget = options.timeout ?? 10_000;
615
+ if (!Number.isFinite(budget) || budget < 0)
616
+ throw new Error(`Invalid ${name} timeout`);
617
+ if (budget === 0)
618
+ throw winTimeoutError(`${name} timed out after 0 ms`);
619
+ const deadline = performance.now() + budget;
620
+ const runSync = options.runSync ?? ((script, opts) => powershellSync(script, opts));
621
+ for (let i = 0; i < checked.length; i += KILL_BATCH_SIZE) {
622
+ const remaining = deadline - performance.now();
623
+ if (remaining <= 0)
624
+ throw winTimeoutError(`${name} timed out after ${budget} ms`);
625
+ const batch = checked.slice(i, i + KILL_BATCH_SIZE);
626
+ runSync(buildWinKillScript(batch, includeDescendants), { timeout: Math.max(1, Math.ceil(remaining)) });
627
+ }
628
+ }
629
+ /** End verified Windows process(es) without touching descendants (e.g. an orchestrator host whose command calls outlive it). */
630
+ export async function killProcess(targets, options = {}) {
631
+ await runWinKill(targets, false, options);
632
+ }
633
+ export function killProcessSync(targets, options = {}) {
634
+ runWinKillSync(targets, false, options);
635
+ }
636
+ /** End verified Windows process(es) and their proven-owned live descendants. Vanished or reused PIDs are untouched. */
637
+ export async function killTree(targets, options = {}) {
638
+ await runWinKill(targets, true, options);
639
+ }
640
+ export function killTreeSync(targets, options = {}) {
641
+ runWinKillSync(targets, true, options);
642
+ }
package/dist/requests.js CHANGED
@@ -126,7 +126,7 @@ export class RequestsBusy extends Error {
126
126
  * stall its sender's sequence). Same content: the recorded envelope stands (republished when it is this sender's and
127
127
  * pending; `sent` false). */
128
128
  export async function sendIdentified(home, outbox, sender, rid, kind, body, cond) {
129
- const digest = specDigest({ kind, body, cond }), path = join(home, 'requests.lock'), locker = new OsLock(), deadline = performance.now() + 10_000;
129
+ const digest = specDigest({ kind, body, cond }), path = join(home, 'requests.lock'), locker = new OsLock(), deadline = performance.now() + (process.platform === "win32" ? 30_000 : 10_000);
130
130
  let lock = await locker.tryAcquire(path);
131
131
  while (!lock && performance.now() < deadline) {
132
132
  await delay(25);