pi-durable-subagents 1.6.1 → 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.
@@ -0,0 +1,205 @@
1
+ // OS-level kernel resource-limit detection and launch wrapping (Layer 2).
2
+ // Layer 1 (process-tree monitor + fence in orchestrator/executor/resources.ts) always runs on every platform;
3
+ // Layer 2 adds kernel-level hard limits where available:
4
+ // - Linux: transient user systemd scope under delegated unified cgroup v2 (MemoryMax, CPUQuota).
5
+ // (Linux cgroup pids.max / TasksMax counts OS threads, not processes, so maxProcesses stays in Layer 1.)
6
+ // - Windows: Job Object hard limits (JobMemoryLimit, ActiveProcessLimit, CpuRateControl) for command calls
7
+ // via DsaJob.exe (platform/job.ts).
8
+ // - macOS: no unprivileged kernel process-tree memory/CPU hard limit; Layer 1 monitor enforces limits.
9
+ import { execFile } from "node:child_process";
10
+ import { existsSync, readFileSync } from "node:fs";
11
+ import { cpus } from "node:os";
12
+ import { posix } from "node:path";
13
+ import { promisify } from "node:util";
14
+ import { contentHash } from "../kernel/ids.js";
15
+ import { findOnPath } from "./launch.js";
16
+ const exec = promisify(execFile);
17
+ /** Merge global config.json `limits` with per-call `spec.limits`. Returns undefined when no resource cap is active. */
18
+ export function mergeLimits(globalLimits, callLimits) {
19
+ if (!globalLimits && !callLimits)
20
+ return undefined;
21
+ const merged = { ...globalLimits, ...callLimits };
22
+ if (merged.memoryMb === undefined && merged.maxProcesses === undefined && merged.cpuPercent === undefined)
23
+ return undefined;
24
+ return merged;
25
+ }
26
+ /** Whether a limits object specifies at least one concrete resource cap. */
27
+ export const hasActiveLimits = (limits) => !!limits && (limits.memoryMb !== undefined || limits.maxProcesses !== undefined || limits.cpuPercent !== undefined);
28
+ /** Stable, systemd-safe transient scope unit name for one execution. */
29
+ export function linuxScopeUnit(exec) {
30
+ return `dsa-exec-${contentHash([exec]).slice(0, 16)}.scope`;
31
+ }
32
+ /** Convert MiB to a clamped positive safe integer byte count (avoids scientific notation or Infinity). */
33
+ export function clampMemoryBytes(memoryMb) {
34
+ if (!Number.isFinite(memoryMb) || memoryMb <= 0)
35
+ return 0;
36
+ const raw = memoryMb * 1024 * 1024;
37
+ if (!Number.isFinite(raw) || raw >= Number.MAX_SAFE_INTEGER)
38
+ return Number.MAX_SAFE_INTEGER;
39
+ return Math.max(1024 * 1024, Math.round(raw));
40
+ }
41
+ /** Convert cpuPercent (% of one CPU core, e.g. 200 = 2 cores) to Windows Job Object CpuRate (1..10000 = 0.01%..100% of machine). */
42
+ export function winCpuRate(cpuPercent, coreCount = Math.max(1, cpus().length)) {
43
+ const cores = Math.max(1, coreCount);
44
+ const ratio = (cpuPercent / (cores * 100)) * 10_000;
45
+ return Math.max(1, Math.min(10_000, Math.round(ratio)));
46
+ }
47
+ /** Fast, pure-fs capability probe for OS kernel hard limits. Safe to call in doctor and before launch. */
48
+ export function probeKernelLimits(options = {}) {
49
+ const platform = options.platform ?? process.platform;
50
+ const env = options.env ?? process.env;
51
+ const kind = options.kind ?? "agent";
52
+ if (platform === "darwin") {
53
+ return {
54
+ backend: "none", memory: false, cpu: false, processes: false,
55
+ reason: "macOS does not provide unprivileged OS kernel memory/CPU hard limits for process trees",
56
+ };
57
+ }
58
+ if (platform === "win32") {
59
+ if (kind === "command") {
60
+ return { backend: "windows-job", memory: true, cpu: true, processes: true };
61
+ }
62
+ return {
63
+ backend: "none", memory: false, cpu: false, processes: false,
64
+ reason: "Windows Job Object kernel hard limits currently apply to command calls; agent calls use process-tree monitoring",
65
+ };
66
+ }
67
+ if (platform !== "linux") {
68
+ return { backend: "none", memory: false, cpu: false, processes: false, reason: `no OS kernel resource limit backend on ${platform}` };
69
+ }
70
+ const exists = options.exists ?? existsSync;
71
+ const readText = options.readText ?? ((p) => readFileSync(p, "utf8"));
72
+ const findBin = options.findBin ?? ((name, pathEnv) => findOnPath(name, pathEnv, { platform: "linux" }));
73
+ const uid = options.uid ? options.uid() : process.getuid?.();
74
+ const systemdRun = findBin("systemd-run", env.PATH);
75
+ if (!systemdRun) {
76
+ return { backend: "none", memory: false, cpu: false, processes: false, reason: "systemd-run not found on PATH" };
77
+ }
78
+ const runtimeDir = env.XDG_RUNTIME_DIR;
79
+ const hasBus = Boolean(env.DBUS_SESSION_BUS_ADDRESS) || Boolean(runtimeDir && exists(posix.join(runtimeDir, "bus")));
80
+ if (!hasBus) {
81
+ return { backend: "none", memory: false, cpu: false, processes: false, reason: "no user systemd D-Bus session (XDG_RUNTIME_DIR/bus unavailable)" };
82
+ }
83
+ if (!exists("/sys/fs/cgroup/cgroup.controllers")) {
84
+ return {
85
+ backend: "none", memory: false, cpu: false, processes: false,
86
+ reason: "host is not running unified cgroup v2 (/sys/fs/cgroup/cgroup.controllers missing)",
87
+ };
88
+ }
89
+ const controllers = new Set();
90
+ let readAuthoritative = false;
91
+ if (uid !== undefined) {
92
+ // user@<uid>.service/cgroup.controllers is authoritative for systemd --user scopes:
93
+ // if it is readable and empty, controllers are NOT delegated (do not fall through to /proc/self/cgroup).
94
+ try {
95
+ const raw = readText(`/sys/fs/cgroup/user.slice/user-${uid}.slice/user@${uid}.service/cgroup.controllers`);
96
+ readAuthoritative = true;
97
+ for (const c of raw.trim().split(/\s+/).filter(Boolean))
98
+ controllers.add(c);
99
+ }
100
+ catch { /* not readable; fall back to /proc/self/cgroup below */ }
101
+ }
102
+ if (!readAuthoritative) {
103
+ try {
104
+ const selfCg = readText("/proc/self/cgroup");
105
+ const v2 = selfCg.split("\n").find(l => l.startsWith("0::"));
106
+ const rel = v2?.slice(3).trim();
107
+ // Never accept the root cgroup ("/") as proof of unprivileged user delegation.
108
+ if (rel && rel !== "/") {
109
+ const raw = readText(`/sys/fs/cgroup${rel}/cgroup.controllers`);
110
+ for (const c of raw.trim().split(/\s+/).filter(Boolean))
111
+ controllers.add(c);
112
+ }
113
+ }
114
+ catch { /* ignore */ }
115
+ }
116
+ const memory = controllers.has("memory");
117
+ const cpu = controllers.has("cpu");
118
+ if (!memory && !cpu) {
119
+ return {
120
+ backend: "none", memory: false, cpu: false, processes: false,
121
+ reason: "Linux user cgroup v2 delegation does not expose memory/cpu controllers (enable Delegate=cpu cpuset io memory pids on user@.service)",
122
+ };
123
+ }
124
+ return {
125
+ backend: "linux-cgroup-v2",
126
+ memory,
127
+ cpu,
128
+ // Linux cgroup pids.max / TasksMax counts OS threads, not processes; keep maxProcesses on process-tree monitor.
129
+ processes: false,
130
+ systemdRun,
131
+ ...(!memory || !cpu ? { reason: `Linux user cgroup v2 delegated controllers: ${[...controllers].sort().join(", ")}` } : {}),
132
+ };
133
+ }
134
+ /** Check whether `strict: true` is satisfied by the OS kernel backend for all requested limits. Returns error text or undefined. */
135
+ export function kernelLimitsSatisfied(limits, caps) {
136
+ if (!limits.strict)
137
+ return undefined;
138
+ const missing = [];
139
+ if (limits.memoryMb !== undefined && !caps.memory)
140
+ missing.push("memoryMb");
141
+ if (limits.cpuPercent !== undefined && !caps.cpu)
142
+ missing.push("cpuPercent");
143
+ if (limits.maxProcesses !== undefined && !caps.processes)
144
+ missing.push("maxProcesses");
145
+ if (!missing.length)
146
+ return undefined;
147
+ return `strict resource limits requested for ${missing.join(", ")}, but OS kernel enforcement is unavailable${caps.reason ? `: ${caps.reason}` : ""}`;
148
+ }
149
+ /** Wrap a Linux spawn command in `systemd-run --user --scope` when cgroup v2 controllers cover at least one requested limit. */
150
+ export function wrapLinuxScope(exec, command, args, limits, caps) {
151
+ if (!limits || caps.backend !== "linux-cgroup-v2" || !caps.systemdRun) {
152
+ return { command, args: [...args] };
153
+ }
154
+ const props = [];
155
+ if (limits.memoryMb !== undefined && caps.memory) {
156
+ const bytes = clampMemoryBytes(limits.memoryMb);
157
+ if (bytes > 0)
158
+ props.push("-p", `MemoryMax=${bytes}`, "-p", "MemorySwapMax=0");
159
+ }
160
+ if (limits.cpuPercent !== undefined && caps.cpu) {
161
+ const pct = Math.max(1, Math.min(1_000_000, Math.round(limits.cpuPercent)));
162
+ props.push("-p", `CPUQuota=${pct}%`);
163
+ }
164
+ if (!props.length)
165
+ return { command, args: [...args] };
166
+ const unit = linuxScopeUnit(exec);
167
+ // Omit --collect so failed/oom-kill scopes retain their Result until checkLinuxScopeOom inspects and resets them
168
+ // (normal inactive scopes still unload automatically under systemd's default CollectMode=inactive).
169
+ return {
170
+ command: caps.systemdRun,
171
+ args: ["--user", "--scope", "--quiet", "--unit", unit, ...props, "--", command, ...args],
172
+ unit,
173
+ };
174
+ }
175
+ /** Check whether a transient Linux systemd scope ended because of cgroup OOM-kill. Best effort; never throws. */
176
+ export async function checkLinuxScopeOom(unit, env = process.env) {
177
+ if (!unit || process.platform !== "linux")
178
+ return false;
179
+ const systemctl = findOnPath("systemctl", env.PATH, { platform: "linux" });
180
+ if (!systemctl)
181
+ return false;
182
+ try {
183
+ const { stdout } = await exec(systemctl, ["--user", "show", "-p", "Result", "-p", "ActiveState", unit], { env, timeout: 1500 });
184
+ const result = /^Result=(.*)$/m.exec(stdout)?.[1]?.trim();
185
+ const active = /^ActiveState=(.*)$/m.exec(stdout)?.[1]?.trim();
186
+ if (active === "failed" || result === "oom-kill") {
187
+ await exec(systemctl, ["--user", "reset-failed", unit], { env, timeout: 1500 }).catch(() => { });
188
+ }
189
+ return result === "oom-kill";
190
+ }
191
+ catch {
192
+ return false;
193
+ }
194
+ }
195
+ /** Concise one-line description for `doctor` and diagnostics. */
196
+ export function describeKernelLimits(caps) {
197
+ if (caps.backend === "linux-cgroup-v2") {
198
+ const active = [caps.memory ? "memory" : "", caps.cpu ? "cpu" : ""].filter(Boolean).join(", ");
199
+ return `process-tree monitor + Linux cgroup v2 (${active})`;
200
+ }
201
+ if (caps.backend === "windows-job") {
202
+ return "process-tree monitor + Windows Job Object (memory, cpu, processes for command calls)";
203
+ }
204
+ return `process-tree monitor only (${caps.reason ?? "OS kernel hard limits unavailable"})`;
205
+ }
@@ -11,6 +11,16 @@ import { attachScannedCommand, scannedCommand, winProcessRows, winSnapshotSync,
11
11
  export const PS = existsSync("/bin/ps") ? "/bin/ps" : "ps";
12
12
  const exec = promisify(execFile);
13
13
  const vanished = (error) => ["ENOENT", "ESRCH", "EACCES", "EPERM"].includes(error.code ?? "");
14
+ const CAPTURED_AT = Symbol("dsa.capturedAt");
15
+ /** Monotonic capture timestamp (performance.now) of a ProcessTable snapshot, if attached. */
16
+ export function snapshotCapturedAt(procs) {
17
+ return procs[CAPTURED_AT];
18
+ }
19
+ /** Attach a non-enumerable snapshot capture timestamp so downstream consumers can deduplicate cached scans. */
20
+ export function attachCapturedAt(procs, at) {
21
+ Object.defineProperty(procs, CAPTURED_AT, { value: at, enumerable: false, configurable: true });
22
+ return procs;
23
+ }
14
24
  // /proc/<pid>/stat is one short line: one open/read/close into a reused buffer, not readFileSync's fstat, sized read
15
25
  // and EOF read (a scan reads it for every process of the machine every second).
16
26
  const statBuffer = Buffer.alloc(4096);
@@ -62,6 +72,7 @@ export class ProcessTable {
62
72
  scans = 0;
63
73
  tags = new Map();
64
74
  ticks;
75
+ pageSize;
65
76
  platform;
66
77
  ps;
67
78
  winRows;
@@ -71,7 +82,7 @@ export class ProcessTable {
71
82
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(this.tagName))
72
83
  throw new Error("Invalid process tag name");
73
84
  this.platform = options.platform ?? process.platform;
74
- this.ps = options.ps ?? (async () => (await exec(PS, ["-axEww", "-o", "pid=,ppid=,lstart=,time=,stat=,command="],
85
+ this.ps = options.ps ?? (async () => (await exec(PS, ["-axEww", "-o", "pid=,ppid=,lstart=,time=,rss=,stat=,command="],
75
86
  // The whole table with environments is large; 2 s proved too short on loaded macOS machines.
76
87
  { env: { ...process.env, LC_ALL: "C" }, timeout: 10_000, maxBuffer: 32 * 1024 * 1024 })).stdout);
77
88
  this.winRows = options.winRows ?? (() => winProcessRows());
@@ -123,14 +134,14 @@ export class ProcessTable {
123
134
  }
124
135
  /** C2, F1: Concurrent observations share a scan; fences wait out all pre-request work. */
125
136
  async list(knownExecs = new Set(), options = {}) {
126
- const value = await this.listRaw(options);
137
+ const { started, value } = await this.listRaw(options);
127
138
  if (typeof value === "string")
128
- return this.mac(value, knownExecs);
139
+ return attachCapturedAt(this.mac(value, knownExecs), started);
129
140
  // A Windows tag comes from a command line, so a known-id filter keeps unrelated text from becoming an execution.
130
141
  if (this.platform === "win32")
131
- return value.map(p => p.tag !== undefined && !knownExecs.has(p.tag)
132
- ? attachScannedCommand({ ...p, tag: undefined }, scannedCommand(p)) : p);
133
- return value;
142
+ return attachCapturedAt(value.map(p => p.tag !== undefined && !knownExecs.has(p.tag)
143
+ ? attachScannedCommand({ ...p, tag: undefined }, scannedCommand(p)) : p), started);
144
+ return attachCapturedAt(value, started);
134
145
  }
135
146
  async listRaw(options) {
136
147
  if (options.fresh && this.pending)
@@ -138,10 +149,10 @@ export class ProcessTable {
138
149
  if (this.pending)
139
150
  return this.pending;
140
151
  if (!options.fresh && this.snapshot && performance.now() - this.snapshot.started < (options.maxAgeMs ?? 0))
141
- return this.snapshot.value;
152
+ return this.snapshot;
142
153
  const started = performance.now();
143
154
  this.scans++;
144
- const promise = this.read().then(value => { this.snapshot = { started, value }; return value; });
155
+ const promise = this.read().then(value => { const snap = { started, value }; this.snapshot = snap; return snap; });
145
156
  this.pending = promise;
146
157
  try {
147
158
  return await promise;
@@ -157,6 +168,7 @@ export class ProcessTable {
157
168
  const tag = winTag(row.command, this.tagName);
158
169
  return attachScannedCommand({ pid: row.pid, ppid: row.ppid, start: row.start,
159
170
  ...(row.cpuMs !== undefined ? { cpuMs: row.cpuMs } : {}),
171
+ ...(row.rssBytes !== undefined ? { rssBytes: row.rssBytes } : {}),
160
172
  ...(tag ? { tag } : {}) }, row.command);
161
173
  });
162
174
  if (this.platform === "darwin")
@@ -169,7 +181,11 @@ export class ProcessTable {
169
181
  throw new Error("C2: invalid CLK_TCK");
170
182
  return value;
171
183
  });
172
- const ticks = await this.ticks;
184
+ this.pageSize ??= exec("getconf", ["PAGESIZE"], { timeout: 2000 }).then(({ stdout }) => {
185
+ const value = Number(stdout.trim());
186
+ return value > 0 ? value : 4096;
187
+ }).catch(() => 4096);
188
+ const [ticks, pageSize] = await Promise.all([this.ticks, this.pageSize]);
173
189
  const result = [];
174
190
  const cache = new Map();
175
191
  for (const name of await readdir("/proc")) {
@@ -200,8 +216,10 @@ export class ProcessTable {
200
216
  continue;
201
217
  }
202
218
  cache.set(key, tag);
219
+ const rssPages = Number(fields[21]);
203
220
  result.push({ pid: Number(name), ppid: Number(fields[1]), start, tag,
204
- cpuMs: (Number(fields[11]) + Number(fields[12])) * 1000 / ticks });
221
+ cpuMs: (Number(fields[11]) + Number(fields[12])) * 1000 / ticks,
222
+ ...(Number.isFinite(rssPages) && rssPages >= 0 ? { rssBytes: rssPages * pageSize } : {}) });
205
223
  }
206
224
  catch (error) {
207
225
  if (!vanished(error))
@@ -214,15 +232,19 @@ export class ProcessTable {
214
232
  mac(stdout, knownExecs) {
215
233
  const result = [];
216
234
  for (const line of stdout.split("\n")) {
217
- const match = line.match(/^\s*(\d+)\s+(\d+)\s+(\w+\s+\w+\s+\d+\s+[\d:]+\s+\d+)\s+([\d:.-]+)\s+(\S+)\s+(.*)$/);
218
- if (!match || match[5].startsWith("Z"))
235
+ // Matches both `rss=,stat=,command=` (current ps invocation) and legacy `stat=,command=` test fixtures
236
+ // (macOS stat always starts with a process-state letter, never a digit).
237
+ const match = line.match(/^\s*(\d+)\s+(\d+)\s+(\w+\s+\w+\s+\d+\s+[\d:]+\s+\d+)\s+([\d:.-]+)(?:\s+(\d+))?\s+([A-Za-z]\S*)\s+(.*)$/);
238
+ if (!match || match[6].startsWith("Z"))
219
239
  continue;
220
240
  const parts = match[4].split(":").map(Number);
221
241
  const seconds = parts.reduce((total, part) => total * 60 + part, 0);
222
- const tags = new Set([...match[6].matchAll(new RegExp(`(?:^|\\s)${this.tagName}=([^\\s]*)`, "g"))]
242
+ const rssKb = match[5] !== undefined ? Number(match[5]) : undefined;
243
+ const tags = new Set([...match[7].matchAll(new RegExp(`(?:^|\\s)${this.tagName}=([^\\s]*)`, "g"))]
223
244
  .map(token => token[1]).filter(tag => knownExecs.has(tag)));
224
245
  result.push({ pid: Number(match[1]), ppid: Number(match[2]), start: match[3].replace(/\s+/g, " "),
225
246
  tag: tags.size === 1 ? tags.values().next().value : undefined, cpuMs: seconds * 1000,
247
+ ...(rssKb !== undefined && Number.isFinite(rssKb) ? { rssBytes: rssKb * 1024 } : {}),
226
248
  ...(tags.size > 1 ? { ambiguous: true } : {}) });
227
249
  }
228
250
  return result;
@@ -196,19 +196,26 @@ function processQuery(fields, body, pid) {
196
196
  const where = pid === undefined ? "" : ` WHERE ProcessId=${pid}`;
197
197
  return `$s = [wmisearcher]'SELECT ${fields} FROM Win32_Process${where}'; foreach ($p in $s.Get()) { ${body} }`;
198
198
  }
199
- export const PROCESS_ROWS_SCRIPT = processQuery("ProcessId,ParentProcessId,CreationDate,UserModeTime,KernelModeTime,CommandLine", `if (!$p.CreationDate) { continue }; $t = ${creationTicks}; ` +
199
+ export const PROCESS_ROWS_SCRIPT = processQuery("ProcessId,ParentProcessId,CreationDate,UserModeTime,KernelModeTime,WorkingSetSize,CommandLine", `if (!$p.CreationDate) { continue }; $t = ${creationTicks}; ` +
200
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');
201
+ '"{0}`t{1}`t{2}`t{3}`t{4}`t{5}" -f $p.ProcessId, $p.ParentProcessId, $t, ([uint64]$p.UserModeTime + [uint64]$p.KernelModeTime), ([uint64]$p.WorkingSetSize), $c');
202
202
  export function parseProcessRows(stdout) {
203
203
  const rows = [];
204
204
  for (const line of stdout.split(/\r?\n/)) {
205
205
  if (!line)
206
206
  continue;
207
- const [pid, ppid, start, cpu, ...rest] = line.split("\t");
207
+ const parts = line.split("\t");
208
+ // 6+ columns (current PROCESS_ROWS_SCRIPT): pid, ppid, start, cpu, rssBytes, command...
209
+ // 5 columns (legacy fixtures): pid, ppid, start, cpu, command
210
+ const hasRss = parts.length >= 6 && /^\d+$/.test(parts[4]);
211
+ const [pid, ppid, start, cpu] = parts;
212
+ const rss = hasRss ? Number(parts[4]) : undefined;
213
+ const rest = hasRss ? parts.slice(5) : parts.slice(4);
208
214
  const id = Number(pid), parent = Number(ppid), ticks = Number(cpu);
209
215
  if (!Number.isInteger(id) || id <= 0 || !Number.isInteger(parent) || parent < 0 || !isWinStart(start))
210
216
  continue;
211
217
  rows.push({ pid: id, ppid: parent, start, ...(Number.isFinite(ticks) ? { cpuMs: ticks / 10_000 } : {}),
218
+ ...(rss !== undefined && Number.isFinite(rss) ? { rssBytes: rss } : {}),
212
219
  ...(rest.length ? { command: rest.join(" ") } : {}) });
213
220
  }
214
221
  return rows;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-durable-subagents",
3
- "version": "1.6.1",
3
+ "version": "1.7.0",
4
4
  "description": "Subagents for pi that never lose work and never do it twice. Crash-safe workflows, automatic recovery, and a live view just like the main agent.",
5
5
  "type": "module",
6
6
  "license": "MIT",