@warlock.js/process 5.39.2 → 5.40.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.
package/cjs/index.cjs CHANGED
@@ -36,6 +36,176 @@ let node_fs_promises = require("node:fs/promises");
36
36
  let node_util = require("node:util");
37
37
  let node_net = require("node:net");
38
38
 
39
+ //#region ../../packages/process/src/platform.ts
40
+ /**
41
+ * Defaults per platform. Linux reads /proc directly, so it is cheap to poll
42
+ * often and a guardian reply is never awaited. Windows and macOS observe
43
+ * through helper programs and a named pipe, which need more time and a slower
44
+ * poll to stay out of the workload's way.
45
+ */
46
+ function defaultPollIntervalMs(platform) {
47
+ return platform === "win32" ? 1500 : platform === "darwin" ? 500 : 100;
48
+ }
49
+ function defaultObservationTimeoutMs(platform) {
50
+ return platform === "win32" || platform === "darwin" ? 15e3 : 2e3;
51
+ }
52
+ var UnsupportedProcessPlatformError = class extends Error {
53
+ platform;
54
+ constructor(platform) {
55
+ super(`Process supervision is unsupported on ${platform}`);
56
+ this.platform = platform;
57
+ this.name = "UnsupportedProcessPlatformError";
58
+ }
59
+ };
60
+ function supported(platform) {
61
+ if (![
62
+ "linux",
63
+ "darwin",
64
+ "win32"
65
+ ].includes(platform)) throw new UnsupportedProcessPlatformError(platform);
66
+ }
67
+ function validPid(pid) {
68
+ if (!Number.isSafeInteger(pid) || pid <= 1) throw new Error("Invalid process PID");
69
+ }
70
+ /** Apple ps(1): lstart uses strftime %c. LC_ALL=C gives %a %b %e %H:%M:%S %Y.
71
+ * https://github.com/apple-oss-distributions/adv_cmds/blob/main/ps/ps.1
72
+ * https://github.com/apple-oss-distributions/adv_cmds/blob/main/ps/print.c (lstarted)
73
+ * https://github.com/apple-oss-distributions/Libc/blob/main/stdtime/FreeBSD/timelocal.c (_C_time_locale)
74
+ */
75
+ function parseDarwinStart(source) {
76
+ const match = /^(Sun|Mon|Tue|Wed|Thu|Fri|Sat) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+(\d{1,2}) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/.exec(source.trim());
77
+ if (!match) throw new Error("Invalid macOS process start time");
78
+ const [, weekday, month, day, hour, minute, second, year] = match;
79
+ const monthIndex = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" ").indexOf(month ?? "");
80
+ const date = new Date(Date.UTC(Number(year), monthIndex, Number(day), Number(hour), Number(minute), Number(second)));
81
+ if (date.getUTCFullYear() !== Number(year) || date.getUTCMonth() !== monthIndex || date.getUTCDate() !== Number(day) || date.getUTCHours() !== Number(hour) || date.getUTCMinutes() !== Number(minute) || date.getUTCSeconds() !== Number(second) || "Sun Mon Tue Wed Thu Fri Sat".split(" ")[date.getUTCDay()] !== weekday) throw new Error("Invalid macOS process start time");
82
+ return String(date.getTime() / 1e3);
83
+ }
84
+ function darwinCommand(pid, tree = false) {
85
+ validPid(pid);
86
+ return {
87
+ file: "/bin/ps",
88
+ args: [
89
+ ...tree ? ["-ax"] : ["-p", String(pid)],
90
+ "-o",
91
+ "pid=,ppid=,pgid=,state=,rss=,lstart="
92
+ ],
93
+ env: {
94
+ LC_ALL: "C",
95
+ TZ: "UTC"
96
+ }
97
+ };
98
+ }
99
+ function parseDarwinRows(source) {
100
+ return source.trim() ? source.trim().split("\n").map((line) => {
101
+ const match = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\d+)\s+(.+?)\s*$/.exec(line);
102
+ if (!match) throw new Error("Invalid macOS process observation");
103
+ return {
104
+ pid: Number(match[1]),
105
+ parent: Number(match[2]),
106
+ group: Number(match[3]),
107
+ state: match[4] ?? "",
108
+ rss: Number(match[5]) * 1024,
109
+ start: parseDarwinStart(match[6] ?? "")
110
+ };
111
+ }) : [];
112
+ }
113
+ /** CIM CreationDate is a DateTime; serialize UTC ticks as text, never a locale date
114
+ * or JSON number (100ns ticks exceed Number's precision). WorkingSetSize is bytes.
115
+ * https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-process
116
+ */
117
+ function windowsCommand(pid, tree = false) {
118
+ validPid(pid);
119
+ return {
120
+ file: "powershell.exe",
121
+ args: [
122
+ "-NoLogo",
123
+ "-NoProfile",
124
+ "-NonInteractive",
125
+ "-Command",
126
+ [
127
+ "$ErrorActionPreference = 'Stop'",
128
+ `$rows = @(${`Get-CimInstance Win32_Process${tree ? "" : ` -Filter 'ProcessId=${pid}'`}`} | ForEach-Object {`,
129
+ `if ([int]$_.ProcessId -eq ${pid} -and $null -eq $_.CreationDate) { throw 'Cannot read process creation time' }`,
130
+ "if ($null -ne $_.CreationDate) {",
131
+ "[pscustomobject]@{ pid = [int]$_.ProcessId; parent = [int]$_.ParentProcessId; start = $_.CreationDate.ToUniversalTime().Ticks.ToString([Globalization.CultureInfo]::InvariantCulture); rss = [double]$_.WorkingSetSize }",
132
+ "}",
133
+ "})",
134
+ "ConvertTo-Json -InputObject $rows -Compress"
135
+ ].join("\n")
136
+ ]
137
+ };
138
+ }
139
+ function parseWindowsRows(source) {
140
+ return windowsRows(JSON.parse(source.replace(/^\uFEFF/, "")));
141
+ }
142
+ /** Validates rows decoded from PowerShell, whether one-shot or from the long-lived helper. */
143
+ function windowsRows(value) {
144
+ if (!Array.isArray(value)) throw new Error("Invalid Windows process observation");
145
+ return value.map((row) => {
146
+ if (!row || typeof row !== "object" || !("pid" in row) || typeof row.pid !== "number" || !Number.isSafeInteger(row.pid) || row.pid < 0 || !("parent" in row) || typeof row.parent !== "number" || !Number.isSafeInteger(row.parent) || row.parent < 0 || !("start" in row) || typeof row.start !== "string" || !/^\d{18}$/.test(row.start) || !("rss" in row) || typeof row.rss !== "number" || !Number.isFinite(row.rss) || row.rss < 0) throw new Error("Invalid Windows process observation");
147
+ return {
148
+ pid: row.pid,
149
+ parent: row.parent,
150
+ start: row.start,
151
+ rss: row.rss,
152
+ group: row.pid,
153
+ state: "R"
154
+ };
155
+ });
156
+ }
157
+ function taskkillCommand(pid) {
158
+ validPid(pid);
159
+ return {
160
+ file: "taskkill.exe",
161
+ args: [
162
+ "/PID",
163
+ String(pid),
164
+ "/T",
165
+ "/F"
166
+ ]
167
+ };
168
+ }
169
+ function treeMemory(rows, pid) {
170
+ const root = rows.find((row) => row.pid === pid);
171
+ if (!root) return 0;
172
+ const included = /* @__PURE__ */ new Map([[pid, root]]);
173
+ let changed = true;
174
+ while (changed) {
175
+ changed = false;
176
+ for (const row of rows) {
177
+ const parent = included.get(row.parent);
178
+ if (!included.has(row.pid) && parent && BigInt(row.start) >= BigInt(parent.start)) {
179
+ included.set(row.pid, row);
180
+ changed = true;
181
+ }
182
+ }
183
+ }
184
+ return [...included.values()].reduce((total, row) => total + row.rss, 0);
185
+ }
186
+ /** All OS effects are injected; foreign-platform specs never execute real commands. */
187
+ async function portableIdentity(platform, pid, token, execute, readProof, source, maxAgeMs = 0) {
188
+ validPid(pid);
189
+ const command = platform === "darwin" ? darwinCommand : windowsCommand;
190
+ const parse = platform === "darwin" ? parseDarwinRows : parseWindowsRows;
191
+ const read = source ?? (async (pids, tree) => parse(await execute(command(pids[0] ?? pid, tree))));
192
+ const rows = await read([pid], token, maxAgeMs);
193
+ const before = rows.find((row) => row.pid === pid);
194
+ if (!before || /^[ZX]/.test(before.state)) return void 0;
195
+ if (!token) return before;
196
+ const proof = await readProof(pid);
197
+ const after = (await read([pid], false, maxAgeMs)).find((row) => row.pid === pid);
198
+ if (!after || after.start !== before.start || after.group !== before.group || /^[ZX]/.test(after.state)) return void 0;
199
+ return {
200
+ start: after.start,
201
+ group: after.group,
202
+ state: proof?.pid === pid && proof.gated ? "T" : after.state,
203
+ rss: treeMemory(rows, pid),
204
+ token: proof?.pid === pid ? proof.token : void 0
205
+ };
206
+ }
207
+
208
+ //#endregion
39
209
  //#region ../../packages/process/src/resources.ts
40
210
  function mountedCgroup(membership) {
41
211
  const mount = "/sys/fs/cgroup";
@@ -135,9 +305,7 @@ const address = process.platform === "win32"
135
305
  : "/tmp/warlock-process-" + process.getuid() + "-" + process.pid + ".sock";
136
306
  let gated = true;
137
307
  const finish = (code) => { server.close(); process.exit(code); };
138
- const start = () => {
139
- if (!gated) return;
140
- gated = false;
308
+ const launch = () => {
141
309
  const [command, ...args] = JSON.parse(process.env.WARLOCK_PROCESS_LAUNCH);
142
310
  const env = { ...process.env };
143
311
  for (const key of Object.keys(env)) {
@@ -163,8 +331,12 @@ const server = createServer((socket) => {
163
331
  const request = JSON.parse(input);
164
332
  if (!/^[a-f0-9]{64}$/.test(request.nonce)) { socket.destroy(); return; }
165
333
  const sign = (value) => createHmac("sha256", token).update(value).digest("hex");
166
- if (request.resume === sign(request.nonce + ":resume")) start();
334
+ const resume = gated && request.resume === sign(request.nonce + ":resume");
335
+ // Reply first, then start the workload: a slow program start must never
336
+ // eat into the client's observation timeout.
337
+ if (resume) gated = false;
167
338
  socket.end(JSON.stringify({ pid: process.pid, digest: sign(request.nonce + ":" + process.pid + ":" + gated), gated }) + "\n");
339
+ if (resume) setImmediate(launch);
168
340
  } catch { socket.destroy(); }
169
341
  });
170
342
  });
@@ -175,7 +347,7 @@ if (process.platform !== "win32") {
175
347
  }
176
348
  server.listen(address, () => { if (process.platform !== "win32") chmodSync(address, 0o600); });
177
349
  `;
178
- async function guardianProof(pid, resume, expectedToken = resume) {
350
+ async function guardianProof(pid, resume, expectedToken = resume, timeoutMs = defaultObservationTimeoutMs(process.platform)) {
179
351
  if (!expectedToken) return void 0;
180
352
  const token = expectedToken;
181
353
  const nonce = (0, node_crypto.randomBytes)(32).toString("hex");
@@ -188,7 +360,7 @@ async function guardianProof(pid, resume, expectedToken = resume) {
188
360
  socket.destroy();
189
361
  reject(error);
190
362
  };
191
- socket.setTimeout(2e3, () => fail(/* @__PURE__ */ new Error("Process ownership observation timed out")));
363
+ socket.setTimeout(timeoutMs, () => fail(/* @__PURE__ */ new Error(`Process ownership observation timed out after ${timeoutMs} ms; raise the observationTimeoutMs supervisor option`)));
192
364
  socket.on("connect", () => socket.write(JSON.stringify({
193
365
  nonce,
194
366
  resume: resume ? sign(nonce + ":resume") : void 0
@@ -198,10 +370,19 @@ async function guardianProof(pid, resume, expectedToken = resume) {
198
370
  if (data.length > 1024) fail(/* @__PURE__ */ new Error("Invalid process ownership response"));
199
371
  });
200
372
  socket.on("error", (error) => {
201
- if (["ENOENT", "ECONNREFUSED"].includes(error.code ?? "")) resolve(void 0);
373
+ if ([
374
+ "ENOENT",
375
+ "ECONNREFUSED",
376
+ "EPIPE",
377
+ "ECONNRESET"
378
+ ].includes(error.code ?? "")) resolve(void 0);
202
379
  else reject(error);
203
380
  });
204
381
  socket.on("end", () => {
382
+ if (!data) {
383
+ resolve(void 0);
384
+ return;
385
+ }
205
386
  try {
206
387
  resolve(parseGuardianProof(data, pid, nonce, token));
207
388
  } catch (error) {
@@ -243,160 +424,6 @@ function launchCommand(platform, node, command, args, limits, environment, token
243
424
  };
244
425
  }
245
426
 
246
- //#endregion
247
- //#region ../../packages/process/src/platform.ts
248
- var UnsupportedProcessPlatformError = class extends Error {
249
- platform;
250
- constructor(platform) {
251
- super(`Process supervision is unsupported on ${platform}`);
252
- this.platform = platform;
253
- this.name = "UnsupportedProcessPlatformError";
254
- }
255
- };
256
- function supported(platform) {
257
- if (![
258
- "linux",
259
- "darwin",
260
- "win32"
261
- ].includes(platform)) throw new UnsupportedProcessPlatformError(platform);
262
- }
263
- function validPid(pid) {
264
- if (!Number.isSafeInteger(pid) || pid <= 1) throw new Error("Invalid process PID");
265
- }
266
- /** Apple ps(1): lstart uses strftime %c. LC_ALL=C gives %a %b %e %H:%M:%S %Y.
267
- * https://github.com/apple-oss-distributions/adv_cmds/blob/main/ps/ps.1
268
- * https://github.com/apple-oss-distributions/adv_cmds/blob/main/ps/print.c (lstarted)
269
- * https://github.com/apple-oss-distributions/Libc/blob/main/stdtime/FreeBSD/timelocal.c (_C_time_locale)
270
- */
271
- function parseDarwinStart(source) {
272
- const match = /^(Sun|Mon|Tue|Wed|Thu|Fri|Sat) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)\s+(\d{1,2}) (\d{2}):(\d{2}):(\d{2}) (\d{4})$/.exec(source.trim());
273
- if (!match) throw new Error("Invalid macOS process start time");
274
- const [, weekday, month, day, hour, minute, second, year] = match;
275
- const monthIndex = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec".split(" ").indexOf(month ?? "");
276
- const date = new Date(Date.UTC(Number(year), monthIndex, Number(day), Number(hour), Number(minute), Number(second)));
277
- if (date.getUTCFullYear() !== Number(year) || date.getUTCMonth() !== monthIndex || date.getUTCDate() !== Number(day) || date.getUTCHours() !== Number(hour) || date.getUTCMinutes() !== Number(minute) || date.getUTCSeconds() !== Number(second) || "Sun Mon Tue Wed Thu Fri Sat".split(" ")[date.getUTCDay()] !== weekday) throw new Error("Invalid macOS process start time");
278
- return String(date.getTime() / 1e3);
279
- }
280
- function darwinCommand(pid, tree = false) {
281
- validPid(pid);
282
- return {
283
- file: "/bin/ps",
284
- args: [
285
- ...tree ? ["-ax"] : ["-p", String(pid)],
286
- "-o",
287
- "pid=,ppid=,pgid=,state=,rss=,lstart="
288
- ],
289
- env: {
290
- LC_ALL: "C",
291
- TZ: "UTC"
292
- }
293
- };
294
- }
295
- function parseDarwinRows(source) {
296
- return source.trim() ? source.trim().split("\n").map((line) => {
297
- const match = /^\s*(\d+)\s+(\d+)\s+(\d+)\s+(\S+)\s+(\d+)\s+(.+?)\s*$/.exec(line);
298
- if (!match) throw new Error("Invalid macOS process observation");
299
- return {
300
- pid: Number(match[1]),
301
- parent: Number(match[2]),
302
- group: Number(match[3]),
303
- state: match[4] ?? "",
304
- rss: Number(match[5]) * 1024,
305
- start: parseDarwinStart(match[6] ?? "")
306
- };
307
- }) : [];
308
- }
309
- /** CIM CreationDate is a DateTime; serialize UTC ticks as text, never a locale date
310
- * or JSON number (100ns ticks exceed Number's precision). WorkingSetSize is bytes.
311
- * https://learn.microsoft.com/en-us/windows/win32/cimwin32prov/win32-process
312
- */
313
- function windowsCommand(pid, tree = false) {
314
- validPid(pid);
315
- return {
316
- file: "powershell.exe",
317
- args: [
318
- "-NoLogo",
319
- "-NoProfile",
320
- "-NonInteractive",
321
- "-Command",
322
- [
323
- "$ErrorActionPreference = 'Stop'",
324
- `$rows = @(${`Get-CimInstance Win32_Process${tree ? "" : ` -Filter 'ProcessId=${pid}'`}`} | ForEach-Object {`,
325
- `if ([int]$_.ProcessId -eq ${pid} -and $null -eq $_.CreationDate) { throw 'Cannot read process creation time' }`,
326
- "if ($null -ne $_.CreationDate) {",
327
- "[pscustomobject]@{ pid = [int]$_.ProcessId; parent = [int]$_.ParentProcessId; start = $_.CreationDate.ToUniversalTime().Ticks.ToString([Globalization.CultureInfo]::InvariantCulture); rss = [double]$_.WorkingSetSize }",
328
- "}",
329
- "})",
330
- "ConvertTo-Json -InputObject $rows -Compress"
331
- ].join("\n")
332
- ]
333
- };
334
- }
335
- function parseWindowsRows(source) {
336
- const value = JSON.parse(source.replace(/^\uFEFF/, ""));
337
- if (!Array.isArray(value)) throw new Error("Invalid Windows process observation");
338
- return value.map((row) => {
339
- if (!row || typeof row !== "object" || !("pid" in row) || typeof row.pid !== "number" || !Number.isSafeInteger(row.pid) || row.pid < 0 || !("parent" in row) || typeof row.parent !== "number" || !Number.isSafeInteger(row.parent) || row.parent < 0 || !("start" in row) || typeof row.start !== "string" || !/^\d{18}$/.test(row.start) || !("rss" in row) || typeof row.rss !== "number" || !Number.isFinite(row.rss) || row.rss < 0) throw new Error("Invalid Windows process observation");
340
- return {
341
- pid: row.pid,
342
- parent: row.parent,
343
- start: row.start,
344
- rss: row.rss,
345
- group: row.pid,
346
- state: "R"
347
- };
348
- });
349
- }
350
- function taskkillCommand(pid) {
351
- validPid(pid);
352
- return {
353
- file: "taskkill.exe",
354
- args: [
355
- "/PID",
356
- String(pid),
357
- "/T",
358
- "/F"
359
- ]
360
- };
361
- }
362
- function treeMemory(rows, pid) {
363
- const root = rows.find((row) => row.pid === pid);
364
- if (!root) return 0;
365
- const included = /* @__PURE__ */ new Map([[pid, root]]);
366
- let changed = true;
367
- while (changed) {
368
- changed = false;
369
- for (const row of rows) {
370
- const parent = included.get(row.parent);
371
- if (!included.has(row.pid) && parent && BigInt(row.start) >= BigInt(parent.start)) {
372
- included.set(row.pid, row);
373
- changed = true;
374
- }
375
- }
376
- }
377
- return [...included.values()].reduce((total, row) => total + row.rss, 0);
378
- }
379
- /** All OS effects are injected; foreign-platform specs never execute real commands. */
380
- async function portableIdentity(platform, pid, token, execute, readProof) {
381
- validPid(pid);
382
- const command = platform === "darwin" ? darwinCommand : windowsCommand;
383
- const parse = platform === "darwin" ? parseDarwinRows : parseWindowsRows;
384
- const rows = parse(await execute(command(pid, token)));
385
- const before = rows.find((row) => row.pid === pid);
386
- if (!before || /^[ZX]/.test(before.state)) return void 0;
387
- if (!token) return before;
388
- const proof = await readProof(pid);
389
- const after = parse(await execute(command(pid))).find((row) => row.pid === pid);
390
- if (!after || after.start !== before.start || after.group !== before.group || /^[ZX]/.test(after.state)) return void 0;
391
- return {
392
- start: after.start,
393
- group: after.group,
394
- state: proof?.pid === pid && proof.gated ? "T" : after.state,
395
- rss: treeMemory(rows, pid),
396
- token: proof?.pid === pid ? proof.token : void 0
397
- };
398
- }
399
-
400
427
  //#endregion
401
428
  //#region ../../packages/process/src/identity.ts
402
429
  const execute = (0, node_util.promisify)(node_child_process.execFile);
@@ -425,7 +452,7 @@ function exiting(fields) {
425
452
  return ["Z", "X"].includes(fields[0] ?? "") || fields[20] === "0";
426
453
  }
427
454
  /** /proc fields: https://man7.org/linux/man-pages/man5/proc_pid_stat.5.html */
428
- async function identity(pid, token = false, expectedToken) {
455
+ async function identity(pid, token = false, expectedToken, observation = {}) {
429
456
  if (!Number.isSafeInteger(pid) || pid <= 1) return void 0;
430
457
  try {
431
458
  if (process.platform === "linux") {
@@ -454,7 +481,10 @@ async function identity(pid, token = false, expectedToken) {
454
481
  token: environment.split("\0").find((entry) => entry.startsWith(`${TOKEN_ENV}=`))?.slice(22)
455
482
  };
456
483
  }
457
- if (process.platform === "darwin" || process.platform === "win32") return await portableIdentity(process.platform, pid, token, executeCommand, (selected) => guardianProof(selected, void 0, expectedToken));
484
+ if (process.platform === "darwin" || process.platform === "win32") {
485
+ const { helper } = observation;
486
+ return await portableIdentity(process.platform, pid, token, executeCommand, (selected) => guardianProof(selected, void 0, expectedToken, observation.timeoutMs ?? defaultObservationTimeoutMs(process.platform)), process.platform === "win32" && helper ? (pids, tree, maxAgeMs) => helper.query(pids, tree, maxAgeMs) : void 0, observation.maxAgeMs);
487
+ }
458
488
  return;
459
489
  } catch (error) {
460
490
  const code = error.code;
@@ -470,8 +500,8 @@ var ProcessNotOwnedError = class extends Error {
470
500
  this.name = "ProcessNotOwnedError";
471
501
  }
472
502
  };
473
- async function owns(entry) {
474
- const current = await identity(entry.pid, true, entry.token);
503
+ async function owns(entry, observation) {
504
+ const current = await identity(entry.pid, true, entry.token, observation);
475
505
  return current?.start === entry.start && current.token === entry.token && current.group === entry.pid;
476
506
  }
477
507
 
@@ -507,18 +537,20 @@ function parseRegistry(source, owner) {
507
537
  var Registry = class {
508
538
  file;
509
539
  owner;
540
+ read;
510
541
  queue = Promise.resolve();
511
542
  locked = false;
512
- constructor(file, owner) {
543
+ constructor(file, owner, read = (pid) => identity(pid)) {
513
544
  this.file = file;
514
545
  this.owner = owner;
546
+ this.read = read;
515
547
  }
516
548
  async open() {
517
549
  await (0, node_fs_promises.mkdir)(node_path.default.dirname(this.file), {
518
550
  recursive: true,
519
551
  mode: 448
520
552
  });
521
- const self = await identity(process.pid);
553
+ const self = await this.read(process.pid);
522
554
  if (!self) throw new Error("Cannot verify registry writer identity");
523
555
  const lock = `${this.file}.lock`;
524
556
  try {
@@ -530,7 +562,7 @@ var Registry = class {
530
562
  try {
531
563
  const lease = JSON.parse(await (0, node_fs_promises.readFile)(node_path.default.join(lock, "writer.json"), "utf8"));
532
564
  if (!record(lease) || typeof lease.pid !== "number" || typeof lease.start !== "string") throw new Error("Invalid registry writer lease; inspect it manually");
533
- if ((await identity(lease.pid))?.start === lease.start) throw new Error("Process registry is already in use");
565
+ if ((await this.read(lease.pid))?.start === lease.start) throw new Error("Process registry is already in use");
534
566
  const stale = `${lock}.${(0, node_crypto.randomBytes)(8).toString("hex")}`;
535
567
  await (0, node_fs_promises.rename)(lock, stale);
536
568
  await (0, node_fs_promises.rm)(stale, { recursive: true });
@@ -586,6 +618,258 @@ var Registry = class {
586
618
  }
587
619
  };
588
620
 
621
+ //#endregion
622
+ //#region ../../packages/process/src/windows-helper.ts
623
+ /**
624
+ * One long-lived PowerShell per supervisor answers batched process queries over
625
+ * stdin/stdout, one JSON object per line:
626
+ *
627
+ * request {"id":1,"pids":[42,43],"all":false}
628
+ * response {"id":1,"rows":[{"pid":42,"parent":4,"start":"638...","rss":1024}]}
629
+ * failure {"id":1,"error":"message"}
630
+ *
631
+ * `all: true` returns the whole process table (needed to sum a process tree).
632
+ * Starting PowerShell costs about a second on Windows; paying that once instead
633
+ * of twice per observation is what keeps a busy machine responsive.
634
+ */
635
+ const helperScript = [
636
+ "$ErrorActionPreference = 'Stop'",
637
+ "[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding($false)",
638
+ "$reader = [Console]::In",
639
+ "while ($null -ne ($line = $reader.ReadLine())) {",
640
+ " $id = 0",
641
+ " try {",
642
+ " $request = $line | ConvertFrom-Json",
643
+ " $id = [int]$request.id",
644
+ " $wanted = @($request.pids | ForEach-Object { [int]$_ })",
645
+ " if ($request.all) { $found = @(Get-CimInstance Win32_Process) }",
646
+ " elseif ($wanted.Count -eq 0) { $found = @() }",
647
+ " else { $found = @(Get-CimInstance Win32_Process -Filter (($wanted | ForEach-Object { 'ProcessId=' + $_ }) -join ' OR ')) }",
648
+ " $rows = @($found | ForEach-Object {",
649
+ " if ($wanted -contains [int]$_.ProcessId -and $null -eq $_.CreationDate) { throw 'Cannot read process creation time' }",
650
+ " if ($null -ne $_.CreationDate) {",
651
+ " [pscustomobject]@{ pid = [int]$_.ProcessId; parent = [int]$_.ParentProcessId; start = $_.CreationDate.ToUniversalTime().Ticks.ToString([Globalization.CultureInfo]::InvariantCulture); rss = [double]$_.WorkingSetSize }",
652
+ " }",
653
+ " })",
654
+ " $reply = ConvertTo-Json -InputObject @{ id = $id; rows = $rows } -Compress -Depth 4",
655
+ " } catch {",
656
+ " $reply = ConvertTo-Json -InputObject @{ id = $id; error = [string]$_.Exception.Message } -Compress",
657
+ " }",
658
+ " [Console]::Out.WriteLine($reply)",
659
+ " [Console]::Out.Flush()",
660
+ "}"
661
+ ].join("\n");
662
+ function defaultHelperSpawn(file, args) {
663
+ const child = (0, node_child_process.spawn)(file, args, {
664
+ stdio: [
665
+ "pipe",
666
+ "pipe",
667
+ "ignore"
668
+ ],
669
+ windowsHide: true
670
+ });
671
+ child.unref();
672
+ child.stdin.unref?.();
673
+ child.stdout.unref?.();
674
+ return child;
675
+ }
676
+ function helperArguments() {
677
+ return [
678
+ "-NoLogo",
679
+ "-NoProfile",
680
+ "-NonInteractive",
681
+ "-EncodedCommand",
682
+ Buffer.from(helperScript, "utf16le").toString("base64")
683
+ ];
684
+ }
685
+ var WindowsProcessHelper = class {
686
+ child;
687
+ buffer = "";
688
+ flight;
689
+ batch;
690
+ scheduled = false;
691
+ nextId = 1;
692
+ closed = false;
693
+ last;
694
+ /** Number of PowerShell processes started; a restart shows up here. */
695
+ starts = 0;
696
+ /** Number of requests written to the helper. */
697
+ requests = 0;
698
+ spawn;
699
+ timeoutMs;
700
+ now;
701
+ constructor(options = {}) {
702
+ this.spawn = options.spawn ?? defaultHelperSpawn;
703
+ this.timeoutMs = options.timeoutMs ?? 15e3;
704
+ this.now = options.now ?? Date.now;
705
+ }
706
+ /**
707
+ * Rows for the given PIDs, or the whole table with `all`. Calls made while a
708
+ * request is in flight share the next request, so N concurrent observations
709
+ * cost one query. `maxAgeMs` accepts a snapshot at most that old.
710
+ */
711
+ query(pids, all = false, maxAgeMs = 0) {
712
+ if (this.closed) return Promise.reject(/* @__PURE__ */ new Error("Windows process helper is closed"));
713
+ const cached = this.last;
714
+ if (maxAgeMs > 0 && cached && this.now() - cached.at <= maxAgeMs && (cached.all || !all && pids.every((pid) => cached.pids.has(pid)))) return Promise.resolve(cached.rows);
715
+ return new Promise((resolve, reject) => {
716
+ const batch = this.batch ??= {
717
+ pids: /* @__PURE__ */ new Set(),
718
+ all: false,
719
+ waiters: []
720
+ };
721
+ for (const pid of pids) batch.pids.add(pid);
722
+ batch.all ||= all;
723
+ batch.waiters.push({
724
+ resolve,
725
+ reject,
726
+ pids
727
+ });
728
+ this.schedule();
729
+ });
730
+ }
731
+ /** Stops the helper; pending queries reject. Safe to call twice. */
732
+ async close() {
733
+ this.closed = true;
734
+ const error = /* @__PURE__ */ new Error("Windows process helper is closed");
735
+ this.failAll(error);
736
+ this.discard();
737
+ }
738
+ schedule() {
739
+ if (this.flight || this.scheduled) return;
740
+ this.scheduled = true;
741
+ setImmediate(() => {
742
+ this.scheduled = false;
743
+ this.dispatch();
744
+ });
745
+ }
746
+ dispatch() {
747
+ if (this.flight || !this.batch) return;
748
+ const batch = this.batch;
749
+ this.batch = void 0;
750
+ this.flight = {
751
+ id: this.nextId++,
752
+ pids: [...batch.pids],
753
+ all: batch.all,
754
+ waiters: batch.waiters,
755
+ attempts: 0
756
+ };
757
+ this.send(this.flight);
758
+ }
759
+ send(flight) {
760
+ flight.attempts += 1;
761
+ try {
762
+ const child = this.ensure();
763
+ this.requests += 1;
764
+ child.stdin.write(JSON.stringify({
765
+ id: flight.id,
766
+ pids: flight.pids,
767
+ all: flight.all
768
+ }) + "\n");
769
+ } catch (error) {
770
+ this.retryOrFail(flight, error);
771
+ return;
772
+ }
773
+ clearTimeout(flight.timer);
774
+ flight.timer = setTimeout(() => {
775
+ this.discard();
776
+ this.retryOrFail(flight, /* @__PURE__ */ new Error(`Windows process helper did not answer within ${this.timeoutMs} ms; raise the observationTimeoutMs supervisor option`));
777
+ }, this.timeoutMs);
778
+ flight.timer.unref?.();
779
+ }
780
+ ensure() {
781
+ if (this.child) return this.child;
782
+ const child = this.spawn("powershell.exe", helperArguments());
783
+ this.starts += 1;
784
+ this.child = child;
785
+ this.buffer = "";
786
+ child.stdout.setEncoding?.("utf8");
787
+ child.stdout.on("data", (chunk) => {
788
+ if (this.child !== child) return;
789
+ this.buffer += chunk.toString();
790
+ let newline = this.buffer.indexOf("\n");
791
+ while (newline >= 0) {
792
+ const line = this.buffer.slice(0, newline).replace(/^/, "").trim();
793
+ this.buffer = this.buffer.slice(newline + 1);
794
+ if (line) this.receive(line);
795
+ newline = this.buffer.indexOf("\n");
796
+ }
797
+ });
798
+ child.stdin.on("error", () => void 0);
799
+ const died = () => {
800
+ if (this.child !== child) return;
801
+ this.child = void 0;
802
+ const flight = this.flight;
803
+ if (flight) this.retryOrFail(flight, /* @__PURE__ */ new Error("Windows process helper exited unexpectedly"));
804
+ };
805
+ child.on("exit", died);
806
+ child.on("error", died);
807
+ return child;
808
+ }
809
+ receive(line) {
810
+ const flight = this.flight;
811
+ if (!flight) return;
812
+ let reply;
813
+ try {
814
+ reply = JSON.parse(line);
815
+ } catch {
816
+ return;
817
+ }
818
+ if (reply.id !== flight.id) return;
819
+ clearTimeout(flight.timer);
820
+ this.flight = void 0;
821
+ try {
822
+ if (typeof reply.error === "string") throw new Error(reply.error);
823
+ const rows = windowsRows(reply.rows);
824
+ this.last = {
825
+ at: this.now(),
826
+ all: flight.all,
827
+ pids: new Set(flight.pids),
828
+ rows
829
+ };
830
+ for (const waiter of flight.waiters) waiter.resolve(rows);
831
+ } catch (error) {
832
+ for (const waiter of flight.waiters) waiter.reject(error);
833
+ }
834
+ if (this.batch) this.schedule();
835
+ }
836
+ /** One automatic retry on a fresh helper; queries are read-only, so repeating is safe. */
837
+ retryOrFail(flight, error) {
838
+ clearTimeout(flight.timer);
839
+ if (this.closed || flight.attempts >= 2) {
840
+ if (this.flight === flight) this.flight = void 0;
841
+ for (const waiter of flight.waiters) waiter.reject(error);
842
+ if (this.batch && !this.closed) this.schedule();
843
+ return;
844
+ }
845
+ this.discard();
846
+ this.send(flight);
847
+ }
848
+ failAll(error) {
849
+ const flight = this.flight;
850
+ this.flight = void 0;
851
+ clearTimeout(flight?.timer);
852
+ const batch = this.batch;
853
+ this.batch = void 0;
854
+ for (const waiter of [...flight?.waiters ?? [], ...batch?.waiters ?? []]) waiter.reject(error);
855
+ }
856
+ discard() {
857
+ const child = this.child;
858
+ this.child = void 0;
859
+ this.last = void 0;
860
+ if (!child) return;
861
+ try {
862
+ child.stdin.end();
863
+ } catch {}
864
+ try {
865
+ child.kill();
866
+ } catch {}
867
+ }
868
+ };
869
+ function createWindowsHelper(options = {}) {
870
+ return new WindowsProcessHelper(options);
871
+ }
872
+
589
873
  //#endregion
590
874
  //#region ../../packages/process/src/supervisor.ts
591
875
  function info(entry) {
@@ -606,10 +890,44 @@ function supervisor(options) {
606
890
  ...options,
607
891
  defaults: { ...options.defaults }
608
892
  };
609
- const pollMs = options.pollIntervalMs ?? 100;
893
+ const pollMs = options.pollIntervalMs ?? defaultPollIntervalMs(process.platform);
610
894
  const graceMs = options.stopGraceMs ?? 1e3;
611
895
  if (!Number.isSafeInteger(pollMs) || pollMs < 10 || !Number.isSafeInteger(graceMs) || graceMs < 0) throw new Error("Invalid polling interval or stop grace period");
612
- const registry = new Registry(node_path.default.resolve(options.registry), options.owner);
896
+ const registryPath = node_path.default.resolve(options.registry);
897
+ const sameProcess = sameProcessSupervisors();
898
+ const live = sameProcess.get(registryPath);
899
+ if (live && live.owner === options.owner) return live.api;
900
+ const observationMs = options.observationTimeoutMs ?? defaultObservationTimeoutMs(process.platform);
901
+ if (!Number.isSafeInteger(observationMs) || observationMs < 100) throw new Error("Invalid observationTimeoutMs: expected an integer of at least 100");
902
+ let helper;
903
+ function observe() {
904
+ if (process.platform === "win32") helper ??= createWindowsHelper({ timeoutMs: observationMs });
905
+ return {
906
+ timeoutMs: observationMs,
907
+ helper
908
+ };
909
+ }
910
+ /** Polling tolerates a snapshot up to one interval old; signals never do. */
911
+ function polling() {
912
+ return {
913
+ ...observe(),
914
+ maxAgeMs: pollMs
915
+ };
916
+ }
917
+ /**
918
+ * Registry lease checks read identities too. Off Linux they go through the shared
919
+ * helper, and a transient failure (an exiting process reports no creation time) is
920
+ * retried instead of failing the whole operation.
921
+ */
922
+ async function lease(pid) {
923
+ for (let attempt = 1;; attempt++) try {
924
+ return await identity(pid, false, void 0, observe());
925
+ } catch (error) {
926
+ if (process.platform === "linux" || attempt >= 3) throw error;
927
+ await (0, node_timers_promises.setTimeout)(200);
928
+ }
929
+ }
930
+ const registry = new Registry(registryPath, options.owner, lease);
613
931
  const entries = /* @__PURE__ */ new Map();
614
932
  const active = /* @__PURE__ */ new Map();
615
933
  let ready;
@@ -634,9 +952,9 @@ function supervisor(options) {
634
952
  }
635
953
  const save = () => registry.save([...entries.values()]);
636
954
  async function signal(entry, value) {
637
- if (!await owns(entry)) throw new ProcessNotOwnedError(entry.pid);
955
+ if (!await owns(entry, observe())) throw new ProcessNotOwnedError(entry.pid);
638
956
  if (process.platform !== "linux" && value === "SIGCONT") {
639
- const proof = await guardianProof(entry.pid, entry.token);
957
+ const proof = await guardianProof(entry.pid, entry.token, entry.token, observationMs);
640
958
  if (!proof || proof.token !== entry.token || proof.gated) throw new ProcessNotOwnedError(entry.pid);
641
959
  return;
642
960
  }
@@ -644,7 +962,7 @@ function supervisor(options) {
644
962
  try {
645
963
  await executeCommand(taskkillCommand(entry.pid));
646
964
  } catch (error) {
647
- if (await owns(entry)) throw error;
965
+ if (await owns(entry, observe())) throw error;
648
966
  }
649
967
  return;
650
968
  }
@@ -654,22 +972,48 @@ function supervisor(options) {
654
972
  if (error.code !== "ESRCH") throw error;
655
973
  }
656
974
  }
975
+ /**
976
+ * A process that is exiting can still be listed for a moment after its guardian
977
+ * (and so its token) is gone. Read fresh a few times; only a process that has
978
+ * disappeared counts as gone, and a live one keeps its not-owned failure.
979
+ */
980
+ async function gone(pid) {
981
+ for (let attempt = 0; attempt < 5; attempt++) {
982
+ if (!await identity(pid, false, void 0, observe())) return true;
983
+ await (0, node_timers_promises.setTimeout)(100);
984
+ }
985
+ return false;
986
+ }
987
+ /**
988
+ * Right after SIGCONT the launcher is replacing itself with the workload
989
+ * (exec). For that instant the kernel reports an empty memory map and
990
+ * environment, so a live, owned process momentarily fails verification. A
991
+ * handle returned by launch() must always be stoppable, so wait that window
992
+ * out; a process that stays unverified is still refused.
993
+ */
994
+ async function ownsSettled(entry) {
995
+ for (let attempt = 0; attempt < 25; attempt++) {
996
+ if (await owns(entry, observe())) return true;
997
+ await (0, node_timers_promises.setTimeout)(20);
998
+ }
999
+ return false;
1000
+ }
657
1001
  async function stopEntry(entry, reason = "stopped") {
658
1002
  const tracked = active.get(entry.pid);
659
1003
  let running;
660
1004
  if (!tracked) {
661
- if (!await owns(entry)) throw new ProcessNotOwnedError(entry.pid);
1005
+ if (!await owns(entry, observe())) throw new ProcessNotOwnedError(entry.pid);
662
1006
  entry.cgroup = await recoveredCgroup(entry.pid, entry.token);
663
1007
  running = track(entry);
664
1008
  } else running = tracked;
665
1009
  if (running.finished) return running.finish(null, null);
666
1010
  if (running.stopping) return running.stopping;
667
1011
  const stopping = (async () => {
668
- if (!await owns(entry)) throw new ProcessNotOwnedError(entry.pid);
1012
+ if (!await ownsSettled(entry)) throw new ProcessNotOwnedError(entry.pid);
669
1013
  running.reason ??= reason;
670
1014
  await signal(entry, "SIGTERM");
671
1015
  const deadline = Date.now() + graceMs;
672
- while (await owns(entry)) {
1016
+ while (await owns(entry, observe())) {
673
1017
  if (Date.now() >= deadline) {
674
1018
  await signal(entry, "SIGKILL");
675
1019
  break;
@@ -677,7 +1021,7 @@ function supervisor(options) {
677
1021
  await (0, node_timers_promises.setTimeout)(20);
678
1022
  }
679
1023
  const killedDeadline = Date.now() + 5e3;
680
- while (await owns(entry)) {
1024
+ while (await owns(entry, observe())) {
681
1025
  if (Date.now() >= killedDeadline) throw new Error(`Process ${entry.pid} did not exit after SIGKILL`);
682
1026
  await (0, node_timers_promises.setTimeout)(20);
683
1027
  }
@@ -688,7 +1032,7 @@ function supervisor(options) {
688
1032
  await stopping;
689
1033
  } catch (error) {
690
1034
  running.stopping = void 0;
691
- if (error instanceof ProcessNotOwnedError && !await identity(entry.pid)) {
1035
+ if (error instanceof ProcessNotOwnedError && await gone(entry.pid)) {
692
1036
  await running.finish(null, null);
693
1037
  return;
694
1038
  }
@@ -766,7 +1110,13 @@ function supervisor(options) {
766
1110
  sampling = true;
767
1111
  try {
768
1112
  const entry = running.entry;
769
- const current = await identity(entry.pid, true, entry.token);
1113
+ let current = await identity(entry.pid, true, entry.token, polling());
1114
+ const matches = (value) => value?.start === entry.start && value.token === entry.token && value.group === entry.pid;
1115
+ for (let attempt = 0; current && !matches(current) && attempt < 3; attempt++) {
1116
+ if (running.finished) return;
1117
+ await (0, node_timers_promises.setTimeout)(50);
1118
+ current = await identity(entry.pid, true, entry.token, observe());
1119
+ }
770
1120
  if (running.finished) return;
771
1121
  if (current?.start !== entry.start || current.token !== entry.token || current.group !== entry.pid) {
772
1122
  if (!current) {
@@ -877,12 +1227,19 @@ function supervisor(options) {
877
1227
  let entry;
878
1228
  try {
879
1229
  const deadline = Date.now() + 5e3;
880
- let current = await identity(pid, true, token);
1230
+ const portable = process.platform !== "linux";
1231
+ const gate = async () => {
1232
+ if (portable) {
1233
+ if (!(await guardianProof(pid, void 0, token, observationMs))?.gated) return void 0;
1234
+ }
1235
+ return identity(pid, true, token, observe());
1236
+ };
1237
+ let current = await gate();
881
1238
  while (!current?.state.startsWith("T") || current.token !== token) {
882
1239
  if (spawnError) throw spawnError;
883
1240
  if (exit || Date.now() >= deadline) throw new Error("Child failed to reach the resource setup gate");
884
1241
  await (0, node_timers_promises.setTimeout)(10);
885
- current = await identity(pid, true, token);
1242
+ current = await gate();
886
1243
  }
887
1244
  if (current.group !== pid) throw new Error("Child did not create an isolated process group");
888
1245
  entry = {
@@ -919,14 +1276,14 @@ function supervisor(options) {
919
1276
  }
920
1277
  return running.handle;
921
1278
  } catch (error) {
922
- const current = await identity(pid, true, token);
1279
+ const current = await identity(pid, true, token, observe());
923
1280
  if (current?.token === token) {
924
1281
  const failed = {
925
1282
  pid,
926
1283
  token,
927
1284
  start: current.start
928
1285
  };
929
- if (await owns(failed)) try {
1286
+ if (await owns(failed, observe())) try {
930
1287
  if (process.platform === "win32") await executeCommand(taskkillCommand(pid));
931
1288
  else process.kill(-pid, "SIGKILL");
932
1289
  } catch {}
@@ -939,7 +1296,7 @@ function supervisor(options) {
939
1296
  throw error;
940
1297
  }
941
1298
  }
942
- return {
1299
+ const api = {
943
1300
  spawn: (input) => serial(() => launch(input, false)),
944
1301
  spawnPty: (input) => serial(async () => await launch(input, true)),
945
1302
  list: (filter = {}) => serial(async () => {
@@ -967,7 +1324,7 @@ function supervisor(options) {
967
1324
  };
968
1325
  for (const entry of [...entries.values()]) {
969
1326
  if (active.has(entry.pid)) continue;
970
- if (!await owns(entry)) {
1327
+ if (!await owns(entry, observe())) {
971
1328
  entries.delete(entry.pid);
972
1329
  result.cleared.push(entry.pid);
973
1330
  continue;
@@ -996,7 +1353,7 @@ function supervisor(options) {
996
1353
  try {
997
1354
  const errors = [];
998
1355
  for (const entry of [...entries.values()]) try {
999
- if (await owns(entry)) await stopEntry(entry);
1356
+ if (await owns(entry, observe())) await stopEntry(entry);
1000
1357
  else {
1001
1358
  const running = active.get(entry.pid);
1002
1359
  if (running) await running.finish(null, null);
@@ -1008,12 +1365,33 @@ function supervisor(options) {
1008
1365
  await save();
1009
1366
  if (errors.length) throw new AggregateError(errors, "Some owned processes could not be stopped");
1010
1367
  } finally {
1368
+ await helper?.close();
1011
1369
  await registry.close();
1012
1370
  }
1013
1371
  });
1014
1372
  return shutdown;
1015
1373
  }
1016
1374
  };
1375
+ const stopAll = api.stopAll;
1376
+ api.stopAll = () => {
1377
+ const stopping = stopAll();
1378
+ const forget = () => {
1379
+ if (sameProcess.get(registryPath)?.api === api) sameProcess.delete(registryPath);
1380
+ };
1381
+ stopping.then(forget, forget);
1382
+ return stopping;
1383
+ };
1384
+ sameProcess.set(registryPath, {
1385
+ owner: options.owner,
1386
+ api
1387
+ });
1388
+ return api;
1389
+ }
1390
+ const SUPERVISORS = Symbol.for("@warlock.js/process.supervisors");
1391
+ /** Live supervisors of this process by registry path; shared by every copy of this module. */
1392
+ function sameProcessSupervisors() {
1393
+ const holder = globalThis;
1394
+ return holder[SUPERVISORS] ??= /* @__PURE__ */ new Map();
1017
1395
  }
1018
1396
 
1019
1397
  //#endregion