pi-durable-subagents 1.6.0 → 1.7.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.
@@ -26,6 +26,7 @@ import { retryWinSharing } from "../kernel/fsx.js";
26
26
  import { captureStart } from "./proctable.js";
27
27
  import { execTarget, findOnPath } from "./launch.js";
28
28
  import { prepareJob, spawnInJob } from "./job.js";
29
+ import { probeKernelLimits, wrapLinuxScope } from "./limits.js";
29
30
  import { DWORD_MAX, comspec, envValue, helperEnv, IS_WINDOWS, mergeEnv, normalizeEnv, systemRoot, winTagArg } from "./windows.js";
30
31
  export const COMMAND_LOG = "output.log";
31
32
  export const COMMAND_EXIT = "exit";
@@ -136,6 +137,22 @@ function windowsPlan(spec) {
136
137
  * then the group owner compiled (bounded and cancellable: `signal` ends the compiler, removes what it wrote and rejects
137
138
  * with a cancelled preparation). Nothing is started, so a crash here leaves no intent and no process: the attempt is
138
139
  * unambiguously prelaunch. POSIX prepares nothing (the wrapper is /bin/sh). */
140
+ /** Commit headroom reserved for Windows wrapper.mjs (Node.js) inside the Job Object so a tight memoryMb limit never
141
+ * OOM-kills the wrapper before it can run the user command or write its exit record; Layer 1 enforces exact memoryMb. */
142
+ const WIN_WRAPPER_MEMORY_OVERHEAD_MB = 64;
143
+ function winJobLimits(limits) {
144
+ if (!limits)
145
+ return undefined;
146
+ const { memoryMb, maxProcesses, cpuPercent } = limits;
147
+ if (memoryMb === undefined && maxProcesses === undefined && cpuPercent === undefined)
148
+ return undefined;
149
+ return {
150
+ ...(memoryMb !== undefined ? { memoryMb: memoryMb + WIN_WRAPPER_MEMORY_OVERHEAD_MB } : {}),
151
+ // Account for wrapper.mjs (1 Node process) running inside the Job Object alongside the user command.
152
+ ...(maxProcesses !== undefined ? { maxProcesses: maxProcesses + 1 } : {}),
153
+ ...(cpuPercent !== undefined ? { cpuPercent } : {}),
154
+ };
155
+ }
139
156
  export async function prepareCommand(spec) {
140
157
  if (!IS_WINDOWS)
141
158
  return undefined;
@@ -144,8 +161,9 @@ export async function prepareCommand(spec) {
144
161
  const plan = windowsPlan(spec);
145
162
  await writeFile(join(spec.dir, COMMAND_SPEC), JSON.stringify({ command: plan.command, cwd: spec.cwd, env: plan.env, ...(plan.verbatim ? { verbatim: true } : {}) }));
146
163
  await writeFile(join(spec.dir, COMMAND_WRAPPER), COMMAND_WRAPPER_SOURCE);
164
+ const limits = winJobLimits(spec.limits);
147
165
  return prepareJob(spec.dir, { exe: process.execPath, env: helperEnv({ SystemRoot: systemRoot() }), cwd: spec.cwd, log: join(spec.dir, COMMAND_LOG),
148
- args: plan.args, ...(spec.exec ? { exec: spec.exec } : {}) }, { ...(spec.signal ? { signal: spec.signal } : {}) });
166
+ args: plan.args, ...(spec.exec ? { exec: spec.exec } : {}), ...(limits ? { limits } : {}) }, { ...(spec.signal ? { signal: spec.signal } : {}) });
149
167
  }
150
168
  export async function spawnCommand(spec) {
151
169
  await mkdir(spec.dir, { recursive: true });
@@ -164,8 +182,9 @@ export async function spawnCommand(spec) {
164
182
  if (spec.proceed && !spec.proceed())
165
183
  return undefined;
166
184
  // Start the internal Node wrapper with OS defaults. It reads the command's environment from command.json.
185
+ const limits = winJobLimits(spec.limits);
167
186
  return await spawnInJob(spec.dir, { exe: process.execPath, env: helperEnv({ SystemRoot: systemRoot() }), cwd: spec.cwd, log: join(spec.dir, COMMAND_LOG),
168
- args: plan.args, ...(spec.exec ? { exec: spec.exec } : {}) }, { ...(spec.proceed ? { proceed: spec.proceed } : {}),
187
+ args: plan.args, ...(spec.exec ? { exec: spec.exec } : {}), ...(limits ? { limits } : {}) }, { ...(spec.proceed ? { proceed: spec.proceed } : {}),
169
188
  ...(spec.prepared ? { prepared: spec.prepared } : {}), ...(spec.signal ? { signal: spec.signal } : {}) });
170
189
  }
171
190
  // POSIX: the wrapper's stdout and stderr are this descriptor, which it inherits and this process closes after the
@@ -175,13 +194,17 @@ export async function spawnCommand(spec) {
175
194
  const mv = resolveMv(), argv = commandArgv(spec.command);
176
195
  if (spec.proceed && !spec.proceed())
177
196
  return undefined;
178
- const child = spawn("/bin/sh", ["-c", WRAPPER, "dsa-command", spec.dir, mv, ...argv], { cwd: spec.cwd, env: spec.env, detached: true, stdio: ["ignore", fd, fd] });
197
+ const baseArgs = ["-c", WRAPPER, "dsa-command", spec.dir, mv, ...argv];
198
+ const wrapped = spec.limits && process.platform === "linux"
199
+ ? wrapLinuxScope(spec.exec ?? `cmd-${Date.now()}`, "/bin/sh", baseArgs, spec.limits, probeKernelLimits({ platform: "linux", env: spec.env, kind: "command" }))
200
+ : { command: "/bin/sh", args: baseArgs };
201
+ const child = spawn(wrapped.command, wrapped.args, { cwd: spec.cwd, env: spec.env, detached: true, stdio: ["ignore", fd, fd] });
179
202
  const exited = new Promise(resolve => { child.once("exit", () => resolve()); child.once("error", () => resolve()); });
180
203
  await new Promise((resolve, reject) => { child.once("spawn", resolve); child.once("error", reject); });
181
204
  child.unref();
182
205
  const pid = child.pid;
183
206
  const start = child.exitCode !== null || child.signalCode !== null ? "" : await captureStart(pid).catch(() => "");
184
- return { pid, start, exited };
207
+ return { pid, start, ...(wrapped.unit ? { scopeUnit: wrapped.unit } : {}), exited };
185
208
  }
186
209
  finally {
187
210
  closeSync(fd);
@@ -2,7 +2,7 @@ import { spawn } from "node:child_process";
2
2
  import { PassThrough } from "node:stream";
3
3
  import { setTimeout as delay } from "node:timers/promises";
4
4
  import { performance } from "node:perf_hooks";
5
- import { captureStart, ProcessTable } from "./proctable.js";
5
+ import { attachCapturedAt, captureStart, ProcessTable, snapshotCapturedAt } from "./proctable.js";
6
6
  import { DWORD_MAX, isOwnedWinChild, isWinKillTimeout, isWinStart, KILL_BATCH_SIZE, killTree, normalizeWinTargets, sameCreation } from "./windows.js";
7
7
  // One table per orchestrator process, including evaluator and gate observers.
8
8
  const sharedTable = new ProcessTable();
@@ -77,6 +77,7 @@ export class Containment {
77
77
  const windows = this.platform === "win32";
78
78
  const execs = new Set([...known.keys(), ...this.launched.keys()]);
79
79
  const all = await this.table.list(execs, options);
80
+ const capturedAt = snapshotCapturedAt(all);
80
81
  for (const p of all)
81
82
  if (p.tag !== undefined)
82
83
  execs.add(p.tag);
@@ -142,7 +143,8 @@ export class Containment {
142
143
  }
143
144
  }
144
145
  }
145
- result.set(exec, [...selected.values()]);
146
+ const list = [...selected.values()];
147
+ result.set(exec, capturedAt !== undefined ? attachCapturedAt(list, capturedAt) : list);
146
148
  }
147
149
  return result;
148
150
  }
@@ -58,6 +58,7 @@ import { join } from "node:path";
58
58
  import { setTimeout as delay } from "node:timers/promises";
59
59
  import { retryWinSharing, retryWinSharingSync, writeFileAtomic } from "../kernel/fsx.js";
60
60
  import { dword, helperEnv, isWinStart, killProcess, sameCreation, systemRoot, winProcessRows, winTag, winTagArg } from "./windows.js";
61
+ import { clampMemoryBytes, winCpuRate } from "./limits.js";
61
62
  export { sameCreation };
62
63
  /** The owner type: exported for the packaging check (the compiled name carries it; nothing separate is shipped). */
63
64
  export const JOB_HOST_MARKER = "DsaJob";
@@ -80,8 +81,15 @@ public static class DsaJob
80
81
  const uint EXTENDED_STARTUPINFO_PRESENT = 0x00080000;
81
82
  const int PROC_THREAD_ATTRIBUTE_HANDLE_LIST = 0x00020002;
82
83
  const int JobObjectBasicAccountingInformation = 1;
84
+ const int JobObjectAssociateCompletionPortInformation = 7;
83
85
  const int JobObjectExtendedLimitInformation = 9;
86
+ const int JobObjectCpuRateControlInformation = 15;
87
+ const uint JOB_OBJECT_MSG_JOB_MEMORY_LIMIT = 10;
88
+ const uint JOB_OBJECT_LIMIT_ACTIVE_PROCESS = 0x00000008;
89
+ const uint JOB_OBJECT_LIMIT_JOB_MEMORY = 0x00000200;
84
90
  const uint JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000;
91
+ const uint JOB_OBJECT_CPU_RATE_CONTROL_ENABLE = 0x00000001;
92
+ const uint JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP = 0x00000004;
85
93
  const int STD_INPUT_HANDLE = -10;
86
94
  const int STD_OUTPUT_HANDLE = -11;
87
95
  const int STD_ERROR_HANDLE = -12;
@@ -187,6 +195,20 @@ public static class DsaJob
187
195
  public UIntPtr PeakJobMemoryUsed;
188
196
  }
189
197
 
198
+ [StructLayout(LayoutKind.Sequential)]
199
+ struct JOBOBJECT_CPU_RATE_CONTROL_INFORMATION
200
+ {
201
+ public uint ControlFlags;
202
+ public uint CpuRate;
203
+ }
204
+
205
+ [StructLayout(LayoutKind.Sequential)]
206
+ struct JOBOBJECT_ASSOCIATE_COMPLETION_PORT
207
+ {
208
+ public IntPtr CompletionKey;
209
+ public IntPtr CompletionPort;
210
+ }
211
+
190
212
  [StructLayout(LayoutKind.Sequential)]
191
213
  struct JOBOBJECT_BASIC_ACCOUNTING_INFORMATION
192
214
  {
@@ -205,8 +227,18 @@ public static class DsaJob
205
227
  [DllImport("kernel32.dll", SetLastError = true)]
206
228
  static extern bool SetInformationJobObject(IntPtr job, int infoClass, ref JOBOBJECT_EXTENDED_LIMIT_INFORMATION info, uint length);
207
229
  [DllImport("kernel32.dll", SetLastError = true)]
230
+ static extern bool SetInformationJobObject(IntPtr job, int infoClass, ref JOBOBJECT_CPU_RATE_CONTROL_INFORMATION info, uint length);
231
+ [DllImport("kernel32.dll", SetLastError = true)]
232
+ static extern bool SetInformationJobObject(IntPtr job, int infoClass, ref JOBOBJECT_ASSOCIATE_COMPLETION_PORT info, uint length);
233
+ [DllImport("kernel32.dll", SetLastError = true)]
234
+ static extern IntPtr CreateIoCompletionPort(IntPtr fileHandle, IntPtr existingPort, UIntPtr completionKey, uint concurrentThreads);
235
+ [DllImport("kernel32.dll", SetLastError = true)]
236
+ static extern bool GetQueuedCompletionStatus(IntPtr port, out uint bytesTransferred, out UIntPtr completionKey, out IntPtr overlapped, uint timeoutMs);
237
+ [DllImport("kernel32.dll", SetLastError = true)]
208
238
  static extern bool QueryInformationJobObject(IntPtr job, int infoClass, out JOBOBJECT_BASIC_ACCOUNTING_INFORMATION info, uint length, IntPtr returnLength);
209
239
  [DllImport("kernel32.dll", SetLastError = true)]
240
+ static extern bool QueryInformationJobObject(IntPtr job, int infoClass, out JOBOBJECT_EXTENDED_LIMIT_INFORMATION info, uint length, IntPtr returnLength);
241
+ [DllImport("kernel32.dll", SetLastError = true)]
210
242
  static extern bool TerminateJobObject(IntPtr job, uint exitCode);
211
243
  [DllImport("kernel32.dll", SetLastError = true)]
212
244
  static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
@@ -262,7 +294,9 @@ public static class DsaJob
262
294
  try { WriteAtomic(Path.Combine(dir, "helper-begin"), ProcessIdentity(unchecked((int)GetCurrentProcessId()), GetCurrentProcess())); } catch (Exception) { }
263
295
  string application, workingDirectory, logPath;
264
296
  string[] arguments, environment;
265
- try { ReadSpec(dir, out application, out workingDirectory, out logPath, out arguments, out environment); }
297
+ ulong memoryBytes;
298
+ uint maxProcesses, cpuRate;
299
+ try { ReadSpec(dir, out application, out workingDirectory, out logPath, out arguments, out environment, out memoryBytes, out maxProcesses, out cpuRate); }
266
300
  catch (Exception failure)
267
301
  {
268
302
  Fail(dir, "job spec", 0, failure.GetType().Name + ": " + failure.Message);
@@ -272,23 +306,39 @@ public static class DsaJob
272
306
  // instead of turning into this host's own failure code. 125/126 are only ever written by a host that recorded
273
307
  // why it did not get to run (or did not get) the wrapper, so a caller can tell the two apart.
274
308
  uint status;
275
- return Run(dir, application, arguments, workingDirectory, logPath, environment, out status) ? unchecked((int)status) : 125;
309
+ return Run(dir, application, arguments, workingDirectory, logPath, environment, memoryBytes, maxProcesses, cpuRate, out status) ? unchecked((int)status) : 125;
276
310
  }
277
311
 
278
312
  /** The attempt's spec: ASCII lines, one base64-encoded UTF-16LE field each, so no code page, quoting rule or
279
- * surrogate can change it (Field decodes each one to its exact code units). DSAJOB1, exe, cwd, log, argument count,
280
- * arguments, environment count, NAME=value entries. */
281
- static void ReadSpec(string dir, out string application, out string workingDirectory, out string logPath, out string[] arguments, out string[] environment)
313
+ * surrogate can change it (Field decodes each one to its exact code units). DSAJOB1/DSAJOB2, exe, cwd, log,
314
+ * argument count, arguments, environment count, NAME=value entries, plus optional DSAJOB2 limit lines
315
+ * (memoryBytes, maxProcesses, cpuRate). */
316
+ static void ReadSpec(string dir, out string application, out string workingDirectory, out string logPath, out string[] arguments, out string[] environment, out ulong memoryBytes, out uint maxProcesses, out uint cpuRate)
282
317
  {
283
318
  string path = Path.Combine(dir, "job.json");
284
319
  string[] lines = File.ReadAllLines(path, Encoding.ASCII);
285
320
  int at = 0;
286
- if (lines.Length < 5 || lines[at++] != "DSAJOB1") throw new FormatException("unknown job spec header");
321
+ if (lines.Length < 5) throw new FormatException("unknown job spec header");
322
+ string header = lines[at++];
323
+ if (header != "DSAJOB1" && header != "DSAJOB2") throw new FormatException("unknown job spec header");
287
324
  application = Field(lines[at++]);
288
325
  workingDirectory = Field(lines[at++]);
289
326
  logPath = Field(lines[at++]);
290
327
  arguments = Fields(lines, ref at);
291
328
  environment = Fields(lines, ref at);
329
+ memoryBytes = 0;
330
+ maxProcesses = 0;
331
+ cpuRate = 0;
332
+ if (header == "DSAJOB2")
333
+ {
334
+ if (lines.Length - at < 3) throw new FormatException("truncated job spec limits");
335
+ if (!UInt64.TryParse(lines[at++], NumberStyles.Integer, CultureInfo.InvariantCulture, out memoryBytes))
336
+ throw new FormatException("bad job memory limit");
337
+ if (!UInt32.TryParse(lines[at++], NumberStyles.Integer, CultureInfo.InvariantCulture, out maxProcesses))
338
+ throw new FormatException("bad job process limit");
339
+ if (!UInt32.TryParse(lines[at++], NumberStyles.Integer, CultureInfo.InvariantCulture, out cpuRate))
340
+ throw new FormatException("bad job cpu rate limit");
341
+ }
292
342
  if (at != lines.Length) throw new FormatException("trailing job spec fields");
293
343
  try { File.Delete(path); } catch (Exception) { }
294
344
  }
@@ -325,10 +375,10 @@ public static class DsaJob
325
375
 
326
376
  /** Run the wrapper inside a new group. True means the wrapper ran and the returned status is the full exit code the
327
377
  * kernel gave it; false means this host failed, wrote start-error and started nothing (or killed what it started). */
328
- static bool Run(string dir, string application, string[] arguments, string workingDirectory, string logPath, string[] environment, out uint status)
378
+ static bool Run(string dir, string application, string[] arguments, string workingDirectory, string logPath, string[] environment, ulong memoryBytes, uint maxProcesses, uint cpuRate, out uint status)
329
379
  {
330
380
  status = 0;
331
- IntPtr job = IntPtr.Zero, output = IntPtr.Zero, errorHandle = IntPtr.Zero, input = IntPtr.Zero, block = IntPtr.Zero;
381
+ IntPtr job = IntPtr.Zero, iocp = IntPtr.Zero, output = IntPtr.Zero, errorHandle = IntPtr.Zero, input = IntPtr.Zero, block = IntPtr.Zero;
332
382
  IntPtr list = IntPtr.Zero, inheritable = IntPtr.Zero;
333
383
  // DeleteProcThreadAttributeList takes only a list InitializeProcThreadAttributeList produced.
334
384
  bool listReady = false;
@@ -339,9 +389,44 @@ public static class DsaJob
339
389
  job = CreateJobObjectW(IntPtr.Zero, null);
340
390
  if (job == IntPtr.Zero) return Fail(dir, "CreateJobObject", Marshal.GetLastWin32Error());
341
391
  JOBOBJECT_EXTENDED_LIMIT_INFORMATION limits = new JOBOBJECT_EXTENDED_LIMIT_INFORMATION();
342
- limits.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
392
+ uint limitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
393
+ if (memoryBytes > 0)
394
+ {
395
+ limitFlags |= JOB_OBJECT_LIMIT_JOB_MEMORY;
396
+ ulong capped = IntPtr.Size == 4 && memoryBytes > UInt32.MaxValue ? (ulong)UInt32.MaxValue : memoryBytes;
397
+ limits.JobMemoryLimit = new UIntPtr(capped);
398
+ }
399
+ if (maxProcesses > 0)
400
+ {
401
+ limitFlags |= JOB_OBJECT_LIMIT_ACTIVE_PROCESS;
402
+ limits.BasicLimitInformation.ActiveProcessLimit = maxProcesses;
403
+ }
404
+ limits.BasicLimitInformation.LimitFlags = limitFlags;
343
405
  if (!SetInformationJobObject(job, JobObjectExtendedLimitInformation, ref limits, (uint)Marshal.SizeOf(typeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION))))
344
406
  return Fail(dir, "SetInformationJobObject", Marshal.GetLastWin32Error());
407
+ if (memoryBytes > 0)
408
+ {
409
+ iocp = CreateIoCompletionPort(INVALID_HANDLE_VALUE, IntPtr.Zero, UIntPtr.Zero, 1);
410
+ if (iocp != IntPtr.Zero)
411
+ {
412
+ JOBOBJECT_ASSOCIATE_COMPLETION_PORT assoc = new JOBOBJECT_ASSOCIATE_COMPLETION_PORT();
413
+ assoc.CompletionKey = job;
414
+ assoc.CompletionPort = iocp;
415
+ if (!SetInformationJobObject(job, JobObjectAssociateCompletionPortInformation, ref assoc, (uint)Marshal.SizeOf(typeof(JOBOBJECT_ASSOCIATE_COMPLETION_PORT))))
416
+ {
417
+ CloseHandle(iocp);
418
+ iocp = IntPtr.Zero;
419
+ }
420
+ }
421
+ }
422
+ if (cpuRate > 0)
423
+ {
424
+ JOBOBJECT_CPU_RATE_CONTROL_INFORMATION cpuLimits = new JOBOBJECT_CPU_RATE_CONTROL_INFORMATION();
425
+ cpuLimits.ControlFlags = JOB_OBJECT_CPU_RATE_CONTROL_ENABLE | JOB_OBJECT_CPU_RATE_CONTROL_HARD_CAP;
426
+ cpuLimits.CpuRate = cpuRate > 10000u ? 10000u : cpuRate;
427
+ if (!SetInformationJobObject(job, JobObjectCpuRateControlInformation, ref cpuLimits, (uint)Marshal.SizeOf(typeof(JOBOBJECT_CPU_RATE_CONTROL_INFORMATION))))
428
+ return Fail(dir, "SetInformationJobObject(CpuRate)", Marshal.GetLastWin32Error());
429
+ }
345
430
 
346
431
  SECURITY_ATTRIBUTES inherit = new SECURITY_ATTRIBUTES();
347
432
  inherit.nLength = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES));
@@ -436,15 +521,46 @@ public static class DsaJob
436
521
  }
437
522
  string stopPath = Path.Combine(dir, "stop");
438
523
  bool stopped = false;
524
+ bool memoryLimitNotified = false;
439
525
  for (;;)
440
526
  {
527
+ if (iocp != IntPtr.Zero)
528
+ {
529
+ uint msg; UIntPtr key; IntPtr ov;
530
+ while (GetQueuedCompletionStatus(iocp, out msg, out key, out ov, 0))
531
+ {
532
+ if (msg == JOB_OBJECT_MSG_JOB_MEMORY_LIMIT) memoryLimitNotified = true;
533
+ }
534
+ }
441
535
  uint waited = WaitForSingleObject(child.hProcess, 50);
442
536
  if (waited == WAIT_OBJECT_0) break;
443
537
  if (waited != WAIT_TIMEOUT) return Fail(dir, "WaitForSingleObject", Marshal.GetLastWin32Error());
444
538
  if (File.Exists(stopPath)) { stopped = true; break; }
445
539
  }
540
+ if (iocp != IntPtr.Zero)
541
+ {
542
+ uint msg; UIntPtr key; IntPtr ov;
543
+ while (GetQueuedCompletionStatus(iocp, out msg, out key, out ov, 0))
544
+ {
545
+ if (msg == JOB_OBJECT_MSG_JOB_MEMORY_LIMIT) memoryLimitNotified = true;
546
+ }
547
+ }
446
548
  uint code = 1;
447
549
  if (!stopped && !GetExitCodeProcess(child.hProcess, out code)) return Fail(dir, "GetExitCodeProcess", Marshal.GetLastWin32Error());
550
+ if (!stopped && memoryBytes > 0 && code != 0)
551
+ {
552
+ // Require an actual kernel memory-limit notification or OOM NTSTATUS so unrelated non-zero exits
553
+ // are never misclassified as OOM merely because peak memory touched the ceiling earlier.
554
+ bool hit = memoryLimitNotified || code == 0xC000012Du || code == 0xC0000017u;
555
+ if (hit)
556
+ {
557
+ ulong peak = 0;
558
+ JOBOBJECT_EXTENDED_LIMIT_INFORMATION info;
559
+ if (QueryInformationJobObject(job, JobObjectExtendedLimitInformation, out info, (uint)Marshal.SizeOf(typeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION)), IntPtr.Zero))
560
+ peak = info.PeakJobMemoryUsed.ToUInt64();
561
+ try { WriteAtomic(Path.Combine(dir, "limit-exceeded"), @"{""kind"":""memory"",""peakBytes"":" + peak.ToString(CultureInfo.InvariantCulture) + "}"); } catch (Exception) { }
562
+ }
563
+ }
448
564
  DrainJob(job);
449
565
  if (!stopped)
450
566
  {
@@ -472,6 +588,7 @@ public static class DsaJob
472
588
  if (block != IntPtr.Zero) Marshal.FreeHGlobal(block);
473
589
  // The group's only handle (non-inherited): closing it kills every process the command left behind.
474
590
  if (job != IntPtr.Zero) CloseHandle(job);
591
+ if (iocp != IntPtr.Zero) CloseHandle(iocp);
475
592
  }
476
593
  }
477
594
 
@@ -674,6 +791,8 @@ export const JOB_HOST_EXIT = "host-exit";
674
791
  export const JOB_SPEC = "job.json";
675
792
  /** The spec's first line: the owner refuses a file it does not recognize. */
676
793
  export const JOB_SPEC_HEADER = "DSAJOB1";
794
+ /** Spec header when OS kernel Job Object resource limits are attached. */
795
+ export const JOB_SPEC_HEADER_V2 = "DSAJOB2";
677
796
  /** Written (atomically) after the wrapper is in the group and before it may run: `{"pid":<wrapper pid>}`. */
678
797
  export const JOB_GROUP = "group";
679
798
  /** Written when the owner saw the wrapper end: `{"status":<wrapper exit status>}`. */
@@ -682,6 +801,8 @@ export const JOB_END = "group-end";
682
801
  export const JOB_ERROR = "start-error";
683
802
  /** Written (atomically) by a caller requesting a controlled stop so the owner calls DrainJob and exits without `group-end`. */
684
803
  export const JOB_STOP = "stop";
804
+ /** Written (atomically) when the Windows Job Object kernel memory hard cap was hit before the wrapper exited. */
805
+ export const JOB_LIMIT_EXCEEDED = "limit-exceeded";
685
806
  /** Written by the owner's first statement: its absence proves the program never ran (a launcher problem, not a failure
686
807
  * of this attempt), which is what a bare "the owner ended" otherwise hides. */
687
808
  export const JOB_BEGIN = "helper-begin";
@@ -729,8 +850,14 @@ export function jobEnv(env) {
729
850
  * code unit, and refuses a field that is not a whole number of them. */
730
851
  export function jobSpecText(launch) {
731
852
  const env = jobEnv(launch.env);
732
- const lines = [JOB_SPEC_HEADER, field(launch.exe), field(launch.cwd), field(launch.log), String(launch.args.length),
733
- ...launch.args.map(field), String(env.length), ...env.map(field)];
853
+ const lim = launch.limits;
854
+ const memBytes = lim?.memoryMb !== undefined ? clampMemoryBytes(lim.memoryMb) : 0;
855
+ const maxProcs = lim?.maxProcesses !== undefined && lim.maxProcesses >= 1 ? Math.floor(lim.maxProcesses) : 0;
856
+ const cpuRate = lim?.cpuPercent !== undefined && lim.cpuPercent > 0 ? winCpuRate(lim.cpuPercent) : 0;
857
+ const hasLimits = memBytes > 0 || maxProcs > 0 || cpuRate > 0;
858
+ const lines = [hasLimits ? JOB_SPEC_HEADER_V2 : JOB_SPEC_HEADER, field(launch.exe), field(launch.cwd), field(launch.log), String(launch.args.length),
859
+ ...launch.args.map(field), String(env.length), ...env.map(field),
860
+ ...(hasLimits ? [String(memBytes), String(maxProcs), String(cpuRate)] : [])];
734
861
  return `${lines.join("\n")}\n`;
735
862
  }
736
863
  const field = (text) => Buffer.from(text, "utf16le").toString("base64");
@@ -807,7 +934,7 @@ export const prepareCancelled = (error) => error instanceof JobPrepareCancelled
807
934
  * or a {@link JobPrepareCancelled} (nothing was recorded and nothing stays). */
808
935
  export async function prepareJob(dir, launch, options = {}) {
809
936
  // Evidence of an earlier attempt in the same directory must never be read as this attempt's.
810
- for (const name of [JOB_BEGIN, JOB_GROUP, JOB_END, JOB_ERROR, JOB_STOP, JOB_HOST_EXIT, JOB_HOST_LOG])
937
+ for (const name of [JOB_BEGIN, JOB_GROUP, JOB_END, JOB_ERROR, JOB_STOP, JOB_LIMIT_EXCEEDED, JOB_HOST_EXIT, JOB_HOST_LOG])
811
938
  await rm(join(dir, name), { force: true });
812
939
  const host = await compileJobHost(dir, { ...(options.compiler ? { compiler: options.compiler } : {}),
813
940
  ...(options.compileMs ? { timeoutMs: options.compileMs } : {}), ...(options.signal ? { signal: options.signal } : {}),
@@ -1002,6 +1129,17 @@ function parseGroupText(text) {
1002
1129
  return { pid: parsed.pid, ...(start ? { start } : {}), ...(group ? { group } : {}) };
1003
1130
  }
1004
1131
  /** The group record written before ResumeThread (with legacy `{"pid":<n>}` compatibility); undefined while not ready. */
1132
+ /** Read a Windows Job Object `limit-exceeded` marker written by DsaJob.exe, if present. Never throws. */
1133
+ export async function readJobLimitExceeded(dir, options = {}) {
1134
+ try {
1135
+ const text = await retryWinSharing(() => readFile(join(dir, JOB_LIMIT_EXCEEDED), "utf8"), { timeoutMs: 250, maxAttempts: 6, ...options });
1136
+ const raw = JSON.parse(text);
1137
+ if (typeof raw.kind === "string")
1138
+ return { kind: raw.kind, peakBytes: Number(raw.peakBytes) || 0 };
1139
+ }
1140
+ catch { /* absent or unreadable */ }
1141
+ return undefined;
1142
+ }
1005
1143
  export async function readGroupRecord(dir, options = {}) {
1006
1144
  const readFn = options.readFile ?? ((path) => readFile(path, "utf8"));
1007
1145
  let text;
@@ -7,9 +7,10 @@
7
7
  // end it. Without lingering the user manager stops its scopes at logout, while a plain detached process survives it
8
8
  // (KillUserProcesses=no, the usual default): it starts as a plain detached process then.
9
9
  import { spawn } from "node:child_process";
10
- import { accessSync, closeSync, constants, existsSync, mkdirSync, openSync, readFileSync, statSync } from "node:fs";
10
+ import { accessSync, closeSync, constants, existsSync, mkdirSync, openSync, readFileSync, realpathSync, statSync } from "node:fs";
11
11
  import { userInfo } from "node:os";
12
12
  import { delimiter, dirname, extname, isAbsolute, join, normalize, resolve, win32 } from "node:path";
13
+ import { ENV } from "../types.js";
13
14
  import { comspec, envValue, IS_WINDOWS, winTagArg } from "./windows.js";
14
15
  const WINDOWS_EXECUTABLE = new Set([".exe", ".com", ".cmd", ".bat"]);
15
16
  /** Whether `path` is a regular file this process may execute. On Windows only a PE image or a batch file is directly
@@ -94,8 +95,11 @@ export function execTarget(command, args, options = {}) {
94
95
  if (!/\.(cmd|bat)$/i.test(resolved))
95
96
  return { command: resolved, args: [...args] };
96
97
  const script = shimScript(resolved);
97
- if (script)
98
- return { command: process.execPath, args: [script, ...args] };
98
+ if (script) {
99
+ const node = resolveNode(env, { platform, peOnly: true }).path;
100
+ if (node)
101
+ return { command: node, args: [script, ...args] };
102
+ }
99
103
  // Outer quotes satisfy `cmd.exe /s /c`, which unconditionally strips the first and last `"` from the command string,
100
104
  // leaving `"path" "arg1" ...` intact for cmd.exe and batch `%*` forwarding. Callers pass `windowsVerbatimArguments: true`.
101
105
  const inner = [quoteCmdBatchArg(resolved), ...args.map(quoteCmdBatchArg)].join(" ");
@@ -134,19 +138,97 @@ export function shellTarget(command, exec, platform = process.platform) {
134
138
  ? { command: exec ? `(if 0==1 echo ${winTagArg("DSA_EXEC", exec)} ) & ${command}` : command, args: [], shell: true }
135
139
  : { command: "/bin/sh", args: ["-c", command] };
136
140
  }
137
- /** The PATH (and PATHEXT) of an environment under this platform's naming rules: a Windows environment spells it `Path`
138
- * as often as `PATH`, and both are the one variable. POSIX reads `PATH` exactly. */
139
- const envPath = (env) => IS_WINDOWS ? envValue(env, "PATH") : env.PATH;
141
+ const NODE_BASENAME = /^node(?:js)?(?:[-._]?v?\d[\d._-]*)?(?:\.exe)?$/i;
142
+ const NODE_SHIM_BASENAME = /^node(?:js)?(?:[-._]?v?\d[\d._-]*)?(?:\.(?:exe|com|cmd|bat))?$/i;
143
+ const SHIM_DISPATCHERS = new Set(["mise", "mise.exe", "volta", "volta.exe", "volta-shim", "volta-shim.exe", "asdf", "asdf.exe", "proto-shim", "proto-shim.exe", "rtx", "rtx.exe", "anyenv", "nodenv", "fnm", "fnm.exe"]);
144
+ const basenameOf = (filePath) => filePath.replace(/^.*[\\/]/, "");
145
+ const realPathOf = (filePath) => { try {
146
+ return (realpathSync.native ?? realpathSync)(filePath);
147
+ }
148
+ catch {
149
+ return filePath;
150
+ } };
151
+ const normFile = (filePath, platform) => platform === "win32" ? win32.normalize(filePath).toLowerCase() : filePath;
152
+ /** Whether this process itself is a standalone Node.js runtime (not a compiled Bun or SEA pi binary where
153
+ * process.execPath points to pi and running `execPath main.js` would open a recursive pi session, #11). */
154
+ export function isNodeProcess(options = {}) {
155
+ const versions = options.versions ?? process.versions;
156
+ if (versions.bun)
157
+ return false;
158
+ const releaseName = options.releaseName ?? process.release?.name;
159
+ if (releaseName !== "node")
160
+ return false;
161
+ const execPath = options.execPath ?? process.execPath;
162
+ return NODE_BASENAME.test(basenameOf(execPath));
163
+ }
164
+ /** Whether `nodePath` and `piPath` invoke the same program. Multi-call version-manager shims (mise, volta, asdf, ...)
165
+ * share one realpath dispatcher binary across `shims/node` and `shims/pi` and dispatch on argv[0]; allow distinct
166
+ * paths only when the shared target is a known shim dispatcher, so a symlink to a versioned `pi-real` binary is
167
+ * still refused. */
168
+ export function isSameProgram(nodePath, piPath, platform = process.platform) {
169
+ if (!piPath)
170
+ return false;
171
+ if (normFile(nodePath, platform) === normFile(piPath, platform))
172
+ return true;
173
+ const realNode = realPathOf(nodePath), realPi = realPathOf(piPath);
174
+ if (normFile(realNode, platform) !== normFile(realPi, platform))
175
+ return false;
176
+ const nodeName = basenameOf(nodePath), piName = basenameOf(piPath), targetName = basenameOf(realNode).toLowerCase();
177
+ if (NODE_SHIM_BASENAME.test(nodeName) && !NODE_SHIM_BASENAME.test(piName) && SHIM_DISPATCHERS.has(targetName))
178
+ return false;
179
+ return true;
180
+ }
181
+ /** Resolve a Node.js executable for launching the orchestrator and JS helpers (#11):
182
+ * 1. DSA_NODE_BIN when set (must be an absolute path to an executable file, and not pi itself);
183
+ * 2. process.execPath when this process is a real Node.js runtime (not a compiled Bun/standalone pi binary);
184
+ * 3. `node` (or `nodejs` on POSIX) on PATH, preferring PE binaries (.exe/.com) over .cmd/.bat shims on Windows. */
185
+ export function resolveNode(env, options = {}) {
186
+ const platform = options.platform ?? process.platform;
187
+ const isPe = (p) => /\.(?:exe|com)$/i.test(p);
188
+ const given = env.DSA_NODE_BIN;
189
+ if (given) {
190
+ if (!absolute(given, platform) || !executableFile(given, platform))
191
+ return { problem: `DSA_NODE_BIN=${given} is not an absolute path to an executable file` };
192
+ if (platform === "win32" && options.peOnly && !isPe(given))
193
+ return { problem: `DSA_NODE_BIN=${given} is not a Windows .exe/.com Node executable` };
194
+ if (isSameProgram(given, options.piPath, platform))
195
+ return { problem: `DSA_NODE_BIN=${given} resolves to the pi executable (${options.piPath})` };
196
+ return { path: given, source: "DSA_NODE_BIN" };
197
+ }
198
+ const execPath = options.execPath ?? process.execPath;
199
+ if (isNodeProcess({ execPath, versions: options.versions, releaseName: options.releaseName }) && !isSameProgram(execPath, options.piPath, platform)) {
200
+ return { path: execPath, source: "execPath" };
201
+ }
202
+ const PATH = platform === "win32" ? envValue(env, "PATH") : env.PATH;
203
+ const pathext = platform === "win32" ? envValue(env, "PATHEXT") : undefined;
204
+ const found = platform === "win32"
205
+ ? findOnPath("node", PATH, { platform, pathext: ".EXE;.COM" }) ?? (options.peOnly ? undefined : findOnPath("node", PATH, { platform, pathext }))
206
+ : findOnPath("node", PATH, { platform }) ?? findOnPath("nodejs", PATH, { platform });
207
+ if (found) {
208
+ if (isSameProgram(found, options.piPath, platform))
209
+ return { problem: `node on PATH (${found}) resolves to the pi executable (${options.piPath})` };
210
+ return { path: found, source: "PATH" };
211
+ }
212
+ return { problem: `node was not found on PATH (${PATH || "unset"}) and DSA_NODE_BIN is not set` };
213
+ }
214
+ /** The starter cannot start an orchestrator without a Node.js runtime (#11). */
215
+ export class NodeNotFound extends Error {
216
+ constructor(problem) {
217
+ super(`cannot start the orchestrator: ${problem}. Set DSA_NODE_BIN to the absolute path of Node.js 22.19+, or put node on PATH`);
218
+ this.name = "NodeNotFound";
219
+ }
220
+ }
140
221
  /** The `pi` the orchestrator launches subagents with: DSA_PI_BIN when set (it must be an executable file), else the
141
222
  * first `pi` on PATH. `problem` says why there is none. */
142
- export function resolvePi(env) {
223
+ export function resolvePi(env, platform = process.platform) {
143
224
  const given = env.DSA_PI_BIN;
144
225
  if (given) {
145
- if (isAbsolute(given) && executableFile(given))
226
+ if (absolute(given, platform) && executableFile(given, platform))
146
227
  return { path: given, source: "DSA_PI_BIN" };
147
228
  return { problem: `DSA_PI_BIN=${given} is not an absolute path to an executable file` };
148
229
  }
149
- const PATH = envPath(env), found = findOnPath("pi", PATH, { pathext: IS_WINDOWS ? envValue(env, "PATHEXT") : undefined });
230
+ const PATH = platform === "win32" ? envValue(env, "PATH") : env.PATH;
231
+ const found = findOnPath("pi", PATH, { platform, pathext: platform === "win32" ? envValue(env, "PATHEXT") : undefined });
150
232
  return found ? { path: found, source: "PATH" } : { problem: `pi was not found on PATH (${PATH || "unset"}) and DSA_PI_BIN is not set` };
151
233
  }
152
234
  /** The starter cannot start an orchestrator that could launch no subagent. */
@@ -224,7 +306,7 @@ function orchestratorStdio(env) {
224
306
  /** The variables the executor sets for one call's processes (a subagent, a command call, a gate). An orchestrator
225
307
  * started from inside a call (its CLI, a command that runs `start`) never carries them: with the call's DSA_EXEC it
226
308
  * would be one of that call's processes, and the call's fence (its end, a stop) would kill it. */
227
- export const PER_CALL_ENV = ["DSA_SESSION", "DSA_EXEC", "DSA_CALL", "DSA_INBOX", "DSA_JOURNAL", "DSA_SCHEMA", "DSA_BUDGET", "DSA_MODEL", "DSA_RESULT", "DSA_OUTPUT", "DSA_PROBE"];
309
+ export const PER_CALL_ENV = ["DSA_SESSION", "DSA_EXEC", "DSA_CALL", "DSA_INBOX", "DSA_JOURNAL", "DSA_SCHEMA", "DSA_BUDGET", "DSA_MODEL", "DSA_RESULT", "DSA_OUTPUT", "DSA_PROBE", ENV.orchestratorLaunch];
228
310
  /** `env` without PER_CALL_ENV. */
229
311
  export function orchestratorEnv(env) {
230
312
  const rest = { ...env };
@@ -236,11 +318,25 @@ export function orchestratorEnv(env) {
236
318
  * session) and every other per-call variable (PER_CALL_ENV) plus DSA_HOME and the resolved DSA_PI_BIN. In its own systemd scope when one is available (the scope execs
237
319
  * the command: same environment, and the pid is the orchestrator's), else a plain detached process. */
238
320
  export async function launchOrchestrator(entry, env, options) {
239
- const pi = resolvePi(env);
321
+ const platform = options.platform ?? process.platform;
322
+ const pi = resolvePi(env, platform);
240
323
  if (!pi.path && options.requirePi)
241
324
  throw new PiNotFound(pi.problem);
242
- const childEnv = { ...orchestratorEnv(env), DSA_HOME: options.home, ...(pi.path ? { DSA_PI_BIN: pi.path } : {}) };
243
- const node = options.node ?? process.execPath, run = options.spawn ?? spawn;
325
+ const piPath = pi.path ?? (isNodeProcess() ? undefined : process.execPath);
326
+ let node;
327
+ if (options.node !== undefined) {
328
+ if (isSameProgram(options.node, piPath, platform))
329
+ throw new NodeNotFound(`orchestrator runtime ${options.node} resolves to the pi executable (${piPath})`);
330
+ node = options.node;
331
+ }
332
+ else {
333
+ const resolved = resolveNode(env, { platform, piPath });
334
+ if (!resolved.path)
335
+ throw new NodeNotFound(resolved.problem);
336
+ node = resolved.path;
337
+ }
338
+ const childEnv = { ...orchestratorEnv(env), DSA_HOME: options.home, [ENV.orchestratorLaunch]: "1", ...(pi.path ? { DSA_PI_BIN: pi.path } : {}) };
339
+ const run = options.spawn ?? spawn;
244
340
  const runner = await scopeRunner(env, options);
245
341
  const diagnostic = orchestratorStdio(childEnv);
246
342
  // The child holds its own copies of the descriptors; ours are closed once it has started (a failed start closes them).
@@ -260,7 +356,10 @@ export async function launchOrchestrator(entry, env, options) {
260
356
  }
261
357
  catch { /* fall back to a plain detached process */ }
262
358
  }
263
- const child = run(node, [entry], { detached: true, stdio: diagnostic.stdio, env: childEnv });
359
+ const target = platform === "win32" && /\.(?:cmd|bat)$/i.test(node)
360
+ ? execTarget(node, [entry], { env: childEnv, platform })
361
+ : { command: node, args: [entry] };
362
+ const child = run(target.command, target.args, { detached: true, stdio: diagnostic.stdio, env: childEnv, ...(target.verbatim ? { windowsVerbatimArguments: true } : {}) });
264
363
  await started(child);
265
364
  child.unref();
266
365
  return { pid: child.pid, scope: false, ...(pi.path ? { pi: pi.path } : {}) };