@dibssoftware/dibs 0.0.0-stage → 0.0.179
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/CHANGELOG.md +594 -0
- package/LICENSE +670 -0
- package/README.md +85 -2
- package/bin/dibs-guard.mjs +7 -0
- package/bin/dibs.mjs +548 -0
- package/docs/benchmarks.md +193 -0
- package/docs/files.md +30 -0
- package/docs/guard.md +91 -0
- package/docs/later.md +43 -0
- package/docs/machines.md +147 -0
- package/docs/questions.md +78 -0
- package/docs/reference.md +157 -0
- package/docs/relay.md +196 -0
- package/docs/releasing.md +27 -0
- package/docs/scheduling.md +163 -0
- package/docs/simulators.md +17 -0
- package/package.json +45 -4
- package/skills/dibs/SKILL.md +183 -0
- package/src/acquire.mjs +700 -0
- package/src/admin.mjs +145 -0
- package/src/agents.mjs +145 -0
- package/src/alerts.mjs +499 -0
- package/src/answers.mjs +65 -0
- package/src/board.mjs +202 -0
- package/src/broker.mjs +369 -0
- package/src/commands.mjs +810 -0
- package/src/config.mjs +324 -0
- package/src/connect.mjs +106 -0
- package/src/cool.mjs +160 -0
- package/src/diskwarn.mjs +154 -0
- package/src/events.mjs +96 -0
- package/src/files.mjs +1123 -0
- package/src/guard.mjs +613 -0
- package/src/history.mjs +247 -0
- package/src/hogs.mjs +227 -0
- package/src/later.mjs +487 -0
- package/src/measure.mjs +262 -0
- package/src/news.mjs +101 -0
- package/src/nodecheck.mjs +17 -0
- package/src/notes.mjs +171 -0
- package/src/notices.mjs +160 -0
- package/src/ondemand.mjs +572 -0
- package/src/overlap.mjs +151 -0
- package/src/override.mjs +360 -0
- package/src/owner.mjs +30 -0
- package/src/plain.mjs +470 -0
- package/src/platform.mjs +357 -0
- package/src/preempt.mjs +438 -0
- package/src/primer.mjs +89 -0
- package/src/proc.mjs +99 -0
- package/src/progress.mjs +187 -0
- package/src/qr.mjs +204 -0
- package/src/questions.mjs +389 -0
- package/src/quota.mjs +81 -0
- package/src/reads.mjs +54 -0
- package/src/relay.mjs +779 -0
- package/src/remote.mjs +584 -0
- package/src/reset.mjs +127 -0
- package/src/schedule.mjs +1020 -0
- package/src/scratch.mjs +61 -0
- package/src/serve.mjs +742 -0
- package/src/service.mjs +221 -0
- package/src/shard.mjs +59 -0
- package/src/simctl.mjs +42 -0
- package/src/simpool.mjs +258 -0
- package/src/state.mjs +201 -0
- package/src/stats.mjs +328 -0
- package/src/style.mjs +44 -0
- package/src/talk.mjs +702 -0
- package/src/thin.sh +130 -0
- package/src/trust.mjs +152 -0
- package/src/util.mjs +184 -0
- package/src/version.mjs +2 -0
- package/src/web.mjs +1119 -0
- package/src/worker.mjs +318 -0
package/src/platform.mjs
ADDED
|
@@ -0,0 +1,357 @@
|
|
|
1
|
+
// Everything that differs between macOS, Linux and Windows lives here, so the
|
|
2
|
+
// rest of dibs never checks the platform.
|
|
3
|
+
//
|
|
4
|
+
// macOS and Linux use ps and process groups. Windows uses PowerShell's CIM
|
|
5
|
+
// process table and taskkill /T, since it has neither.
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import os from 'node:os';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { spawn, spawnSync, execFileSync } from 'node:child_process';
|
|
10
|
+
|
|
11
|
+
export const OS = process.platform === 'win32' ? 'windows' : process.platform === 'darwin' ? 'macos' : 'linux';
|
|
12
|
+
const WIN = OS === 'windows';
|
|
13
|
+
|
|
14
|
+
// Output of a command, or null when it couldn't run at all (spawn failed under
|
|
15
|
+
// memory pressure, killed by a signal). Callers must not read null as "nothing".
|
|
16
|
+
function tryRun(cmd, args) {
|
|
17
|
+
try { return execFileSync(cmd, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true }); }
|
|
18
|
+
catch (e) { return typeof e.status === 'number' ? e.stdout || '' : null; } // ps exits 1 when any pid is gone
|
|
19
|
+
}
|
|
20
|
+
const run = (cmd, args) => tryRun(cmd, args) ?? '';
|
|
21
|
+
const ps = script => tryRun('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script]);
|
|
22
|
+
|
|
23
|
+
// pid -> start time string. Comparing start times keeps a recycled pid from
|
|
24
|
+
// passing as a live holder. null when the process table couldn't be read.
|
|
25
|
+
// The highest pid each system hands out (macOS's PID_MAX, Linux's PID_MAX_LIMIT).
|
|
26
|
+
// ps refuses a list with anything past it and prints nothing for the rest.
|
|
27
|
+
const PID_MAX = OS === 'macos' ? 99999 : OS === 'linux' ? 4194304 : Infinity;
|
|
28
|
+
export function starts(pids) {
|
|
29
|
+
const out = new Map();
|
|
30
|
+
// One bad number in the state file mustn't make every holder look dead.
|
|
31
|
+
pids = [...new Set(pids.filter(p => Number.isInteger(p) && p > 0 && p <= PID_MAX))];
|
|
32
|
+
if (!pids.length) return out;
|
|
33
|
+
if (WIN) {
|
|
34
|
+
const txt = ps(`Get-CimInstance Win32_Process -Filter "${pids.map(p => `ProcessId=${p}`).join(' OR ')}" | ForEach-Object { "$($_.ProcessId) $($_.CreationDate.ToFileTimeUtc())" }`);
|
|
35
|
+
if (txt == null) return null;
|
|
36
|
+
for (const line of txt.split(/\r?\n/)) { const m = line.trim().match(/^(\d+)\s+(\d+)$/); if (m) out.set(Number(m[1]), m[2]); }
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
// ps exits 1 with no output when every pid is gone, and also when it refuses
|
|
40
|
+
// the list (it says why on stderr). The second is "can't tell", not "all dead".
|
|
41
|
+
const r = spawnSync('ps', ['-o', 'pid=,lstart=', '-p', pids.join(',')], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
|
|
42
|
+
if (r.status == null || (r.status !== 0 && !r.stdout && r.stderr.trim())) return null;
|
|
43
|
+
const txt = r.stdout;
|
|
44
|
+
for (const line of txt.split('\n')) {
|
|
45
|
+
const m = line.trim().match(/^(\d+)\s+(.*)$/);
|
|
46
|
+
if (m) out.set(Number(m[1]), m[2].trim());
|
|
47
|
+
}
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
// Parent pid and executable name, for walking up to the owning agent.
|
|
52
|
+
export function parent(pid) {
|
|
53
|
+
if (WIN) {
|
|
54
|
+
const m = (ps(`$p = Get-CimInstance Win32_Process -Filter "ProcessId=${pid}"; "$($p.ParentProcessId) $($p.Name)"`) ?? '').trim().match(/^(\d+)\s+(.*)$/);
|
|
55
|
+
return m ? { ppid: Number(m[1]), name: m[2].replace(/\.exe$/i, '') } : null;
|
|
56
|
+
}
|
|
57
|
+
const m = run('ps', ['-o', 'ppid=,comm=', '-p', String(pid)]).trim().match(/^(\d+)\s+(.*)$/);
|
|
58
|
+
if (!m) return null;
|
|
59
|
+
let name = path.basename(m[2]);
|
|
60
|
+
// Linux's comm is a thread name, and Node (22 and later) names its main
|
|
61
|
+
// thread MainThread: a Claude Code run under node, or anything else in Node,
|
|
62
|
+
// would never show its own name. The program it was started as does.
|
|
63
|
+
if (OS === 'linux' && !AGENTS.test(name)) try { name = path.basename(fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8').split('\0')[0]) || name; } catch {}
|
|
64
|
+
return { ppid: Number(m[1]), name };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
// Every process: pid, parent, process group, % of one core, resident bytes
|
|
68
|
+
// (not on Windows), command line. The group is the pid on Windows, which has
|
|
69
|
+
// no process groups.
|
|
70
|
+
let procCache = null;
|
|
71
|
+
export function processes() {
|
|
72
|
+
if (procCache && Date.now() - procCache.at < 5000) return procCache.list;
|
|
73
|
+
return (procCache = { at: Date.now(), list: readProcesses() }).list;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function readProcesses() {
|
|
77
|
+
if (WIN) {
|
|
78
|
+
// Two samples of total processor time, a second apart, give a CPU %.
|
|
79
|
+
const txt = ps(`$a = @{}; Get-Process | ForEach-Object { $a[$_.Id] = $_.TotalProcessorTime.TotalMilliseconds }; Start-Sleep -Milliseconds 1000;`
|
|
80
|
+
+ ` Get-CimInstance Win32_Process | ForEach-Object { $p = Get-Process -Id $_.ProcessId -ErrorAction SilentlyContinue;`
|
|
81
|
+
+ ` if ($p -and $a[$p.Id] -ne $null) { "$($_.ProcessId)\`t$($_.ParentProcessId)\`t$([math]::Round(($p.TotalProcessorTime.TotalMilliseconds - $a[$p.Id]) / 10, 1))\`t$($_.CommandLine)" } }`);
|
|
82
|
+
return (txt ?? '').split(/\r?\n/).map(l => l.split('\t')).filter(f => f.length === 4 && f[3])
|
|
83
|
+
.map(([pid, ppid, cpu, args]) => ({ pid: Number(pid), ppid: Number(ppid), pgid: Number(pid), cpu: Number(cpu), args }));
|
|
84
|
+
}
|
|
85
|
+
return run('ps', ['-Ao', 'pid=,ppid=,pgid=,pcpu=,rss=,args=']).split('\n')
|
|
86
|
+
.map(l => l.trim().match(/^(\d+)\s+(\d+)\s+(\d+)\s+([\d.]+)\s+(\d+)\s+(.*)$/)).filter(Boolean)
|
|
87
|
+
.map(m => ({ pid: Number(m[1]), ppid: Number(m[2]), pgid: Number(m[3]), cpu: Number(m[4]), rss: Number(m[5]) * 1024, args: m[6] }));
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Resident memory of every dibs on the machine: waiters, supervisors, holds,
|
|
91
|
+
// services, the broker. A node whose script is bin/dibs or dibs.mjs, flags or
|
|
92
|
+
// not, or a thin waiter's shell (src/thin.sh).
|
|
93
|
+
const DIBS_PROC = /^\S*\bnode\s+(?:-\S+\s+)*\S*(?:\/bin\/dibs|\/dibs\.mjs)(?:\s|$)|^\S*\bsh\s+\S*\/src\/thin\.sh(?:\s|$)/;
|
|
94
|
+
export const isDibs = p => DIBS_PROC.test(p.args);
|
|
95
|
+
export const dibsMem = (procs = processes()) => procs.reduce((a, p) => a + (isDibs(p) ? p.rss || 0 : 0), 0);
|
|
96
|
+
|
|
97
|
+
// Every process group that has a process in it right now.
|
|
98
|
+
export function liveGroups() {
|
|
99
|
+
procCache = null;
|
|
100
|
+
return new Set(processes().map(p => p.pgid));
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// The pids in these process groups right now.
|
|
104
|
+
export function pidsIn(groups) {
|
|
105
|
+
procCache = null;
|
|
106
|
+
return processes().filter(p => groups.includes(p.pgid)).map(p => p.pid);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// Process groups of everything descended from pid (its own included). Children
|
|
110
|
+
// that start their own group (browsers, dev servers) are found this way.
|
|
111
|
+
export function descendants(pid) {
|
|
112
|
+
procCache = null;
|
|
113
|
+
const kids = new Map();
|
|
114
|
+
for (const p of processes()) { if (!kids.has(p.ppid)) kids.set(p.ppid, []); kids.get(p.ppid).push(p); }
|
|
115
|
+
const groups = new Set(), stack = [pid];
|
|
116
|
+
while (stack.length) for (const p of kids.get(stack.pop()) || []) { groups.add(p.pgid); stack.push(p.pid); }
|
|
117
|
+
return groups;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// pid -> physical footprint in bytes, or null when it can't be read (callers
|
|
121
|
+
// fall back to RSS). RSS counts shared libraries in every process and leaves
|
|
122
|
+
// out compressed memory, so a tree's RSS sum can be off either way by gigabytes.
|
|
123
|
+
// macOS: one top call reads every process (about 0.3s of CPU, whatever the
|
|
124
|
+
// count), the same number Activity Monitor shows. Linux: PSS from
|
|
125
|
+
// smaps_rollup, which splits shared pages between the processes sharing them.
|
|
126
|
+
// Windows: null. DIBS_FAKE_FOOTPRINT names a JSON file of { pid: bytes } for tests.
|
|
127
|
+
const UNITS = { B: 1, K: 1024, M: 1024 ** 2, G: 1024 ** 3, T: 1024 ** 4 };
|
|
128
|
+
// Every process's memory, the way Activity Monitor's Memory column adds it up
|
|
129
|
+
// on macOS: top's MEM plus CMPRS, what it holds in RAM plus what the system
|
|
130
|
+
// squeezed of it. For telling the person what to close (src/alerts.mjs), so
|
|
131
|
+
// all processes, not only dibs's. Linux: resident memory. DIBS_FAKE_MEMORY,
|
|
132
|
+
// a JSON file of { pid: bytes }, stands in for tests.
|
|
133
|
+
export function memoryUse() {
|
|
134
|
+
if (process.env.DIBS_FAKE_MEMORY) {
|
|
135
|
+
try { return new Map(Object.entries(JSON.parse(fs.readFileSync(process.env.DIBS_FAKE_MEMORY, 'utf8'))).map(([p, b]) => [Number(p), b])); } catch { return new Map(); }
|
|
136
|
+
}
|
|
137
|
+
if (OS !== 'macos') return new Map(processes().map(p => [p.pid, p.rss || 0]));
|
|
138
|
+
const txt = tryRun('top', ['-l', '1', '-o', 'mem', '-stats', 'pid,mem,cmprs']);
|
|
139
|
+
const out = new Map();
|
|
140
|
+
const size = x => { const m = x?.match(/^([\d.]+)([BKMGT])[+-]?$/); return m ? Number(m[1]) * UNITS[m[2]] : 0; };
|
|
141
|
+
for (const line of (txt || '').split('\n')) {
|
|
142
|
+
const f = line.trim().split(/\s+/);
|
|
143
|
+
if (f.length === 3 && /^\d+$/.test(f[0])) out.set(Number(f[0]), size(f[1]) + size(f[2]));
|
|
144
|
+
}
|
|
145
|
+
return out;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function footprints(pids) {
|
|
149
|
+
if (process.env.DIBS_FAKE_FOOTPRINT) {
|
|
150
|
+
let f = {};
|
|
151
|
+
try { f = JSON.parse(fs.readFileSync(process.env.DIBS_FAKE_FOOTPRINT, 'utf8')); } catch {}
|
|
152
|
+
return new Map(pids.map(p => [p, f[p] ?? 0]));
|
|
153
|
+
}
|
|
154
|
+
if (OS === 'linux') {
|
|
155
|
+
const out = new Map();
|
|
156
|
+
for (const pid of pids) {
|
|
157
|
+
try { const m = fs.readFileSync(`/proc/${pid}/smaps_rollup`, 'utf8').match(/^Pss:\s+(\d+) kB/m); if (m) out.set(pid, Number(m[1]) * 1024); } catch {}
|
|
158
|
+
}
|
|
159
|
+
return out;
|
|
160
|
+
}
|
|
161
|
+
if (OS !== 'macos') return null;
|
|
162
|
+
const txt = tryRun('top', ['-l', '1', '-stats', 'pid,mem']);
|
|
163
|
+
if (txt == null) return null;
|
|
164
|
+
const out = new Map();
|
|
165
|
+
for (const line of txt.split('\n')) {
|
|
166
|
+
const m = line.trim().match(/^(\d+)\s+([\d.]+)([BKMGT])[+-]?$/);
|
|
167
|
+
if (m) out.set(Number(m[1]), Number(m[2]) * UNITS[m[3]]);
|
|
168
|
+
}
|
|
169
|
+
return out;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Linux, with enforce: true in config.json: run the job in a systemd user
|
|
173
|
+
// scope with MemoryHigh at its memory budget (past it the kernel throttles and
|
|
174
|
+
// reclaims; it never kills) and CPUQuota at its cores. No root needed where a
|
|
175
|
+
// systemd user session runs. Where there's none (containers, WSL1, ssh
|
|
176
|
+
// without lingering) the command runs as it is.
|
|
177
|
+
export function scoped(argv, { mem, cpu }, { os: on = OS, works = scopeWorks } = {}) {
|
|
178
|
+
if (on !== 'linux' || !works()) return argv;
|
|
179
|
+
return ['systemd-run', '--user', '--scope', '--quiet', '--collect', '-p', `MemoryHigh=${Math.round(mem)}`,
|
|
180
|
+
...(cpu > 0 ? ['-p', `CPUQuota=${Math.round(cpu * 100)}%`] : []), '--', ...argv];
|
|
181
|
+
}
|
|
182
|
+
const scopeWorks = () => !!which('systemd-run')
|
|
183
|
+
&& spawnSync('systemd-run', ['--user', '--scope', '--quiet', '--collect', '--', 'true'], { stdio: 'ignore', timeout: 5000 }).status === 0;
|
|
184
|
+
|
|
185
|
+
// Where a command would be found on PATH, or null. Checked before launching,
|
|
186
|
+
// so a missing command is reported as one even behind a wrapper (systemd-run, cmd.exe).
|
|
187
|
+
export function which(cmd, env = process.env) {
|
|
188
|
+
const exts = WIN ? (env.PATHEXT || '.EXE;.CMD;.BAT;.COM').split(';').map(e => e.toLowerCase()) : [''];
|
|
189
|
+
const ok = f => { try { return fs.statSync(f).isFile() && (WIN || (fs.accessSync(f, fs.constants.X_OK), true)); } catch { return false; } };
|
|
190
|
+
// On Windows an extensionless file (npm's sh script next to npm.cmd) can't be run, so PATHEXT comes first.
|
|
191
|
+
const tryAll = base => (WIN ? (path.extname(base) ? [''] : exts) : ['']).map(e => base + e).find(ok) || null;
|
|
192
|
+
if (cmd.includes('/') || (WIN && cmd.includes('\\'))) return tryAll(path.resolve(cmd));
|
|
193
|
+
for (const d of (env.PATH || env.Path || '').split(path.delimiter)) if (d) { const f = tryAll(path.join(d, cmd)); if (f) return f; }
|
|
194
|
+
return null;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// Windows runs .cmd shims (npm, npx) only through cmd.exe, which needs its own quoting.
|
|
198
|
+
const winQuote = a => (/^[\w@%+=:,./\\-]+$/.test(a) ? a : `"${a.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\+)$/, '$1$1')}"`);
|
|
199
|
+
|
|
200
|
+
// Start a command so the whole tree it spawns can be stopped together.
|
|
201
|
+
// Background priority keeps it off the fast cores (macOS) or below normal work.
|
|
202
|
+
// With gate, the command waits until child.go(): the caller records the
|
|
203
|
+
// process group first, so a caller killed in between leaves nothing untracked.
|
|
204
|
+
// If the caller dies before go(), the pipe closes and the command never starts.
|
|
205
|
+
const GATE = 'IFS= read -r _ <&3 || exit 125; exec 3<&-; exec "$@"';
|
|
206
|
+
export function launch(argv, { env, background = false, gate = false }) {
|
|
207
|
+
let cmd = argv;
|
|
208
|
+
if (WIN && /\.(cmd|bat)$/i.test(which(argv[0], env) || '')) cmd = ['cmd.exe', '/d', '/s', '/c', `"${argv.map(winQuote).join(' ')}"`];
|
|
209
|
+
const gated = gate && !WIN;
|
|
210
|
+
if (gated) cmd = ['/bin/sh', '-c', GATE, 'dibs', ...cmd];
|
|
211
|
+
const child = spawn(cmd[0], cmd.slice(1), { stdio: gated ? ['inherit', 'inherit', 'inherit', 'pipe'] : 'inherit',
|
|
212
|
+
detached: !WIN, env, windowsHide: false, windowsVerbatimArguments: cmd[0] === 'cmd.exe' });
|
|
213
|
+
// Lowered from outside, as the throttle watcher does, so dibs boost can raise it again: on macOS
|
|
214
|
+
// a process started under `taskpolicy -b` keeps background QoS whatever `taskpolicy -B -p` says.
|
|
215
|
+
// Its children inherit it. Gated, the command doesn't start until it's lowered.
|
|
216
|
+
if (background && child.pid) lower(child.pid);
|
|
217
|
+
child.go = () => { if (gated) child.stdio[3].end('go\n'); };
|
|
218
|
+
return child;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// dibs killed outright (kill -9) can't stop its job, which would run on until
|
|
222
|
+
// the next dibs call reaped it. So a small shell, in a group of its own, holds
|
|
223
|
+
// a pipe from dibs: "g N" adds a process group, "r N" removes one that has
|
|
224
|
+
// emptied, "done" means dibs is cleaning up itself. If the pipe closes without
|
|
225
|
+
// "done", dibs died, and the shell kills every group it was told about.
|
|
226
|
+
const WATCH = 'while read -r w g; do case $w in done) exit 0;; g) gs="$gs $g ";; r) gs=$(printf %s "$gs" | sed "s/ $g / /");; esac; done; '
|
|
227
|
+
+ 'for g in $gs; do kill -KILL -"$g" 2>/dev/null; done';
|
|
228
|
+
export function watchdog() {
|
|
229
|
+
const none = { add() {}, drop() {}, done() {} };
|
|
230
|
+
if (WIN) return none;
|
|
231
|
+
let p;
|
|
232
|
+
try { p = spawn('/bin/sh', ['-c', WATCH], { stdio: ['pipe', 'ignore', 'ignore'], detached: true }); } catch { return none; }
|
|
233
|
+
p.on('error', () => {});
|
|
234
|
+
p.stdin.on('error', () => {});
|
|
235
|
+
p.unref();
|
|
236
|
+
const send = line => { if (!p.stdin.destroyed) p.stdin.write(`${line}\n`); };
|
|
237
|
+
return { add: g => send(`g ${g}`), drop: g => send(`r ${g}`), done: () => { if (!p.stdin.destroyed) p.stdin.end('done\n'); } };
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// Stop a tree started by launch(). On macOS and Linux the tree is the process
|
|
241
|
+
// group; on Windows taskkill walks the children.
|
|
242
|
+
export function stopTree(id, signal = 'SIGTERM') {
|
|
243
|
+
if (!id) return;
|
|
244
|
+
if (WIN) { run('taskkill', ['/PID', String(id), '/T', ...(signal === 'SIGKILL' ? ['/F'] : [])]); return; }
|
|
245
|
+
try { process.kill(-id, signal); } catch {}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Pids in these process groups that are still running: not stopped (T), not
|
|
249
|
+
// a zombie (Z, an exited child its stopped parent hasn't reaped), and not in
|
|
250
|
+
// the kernel (D on Linux, U on macOS): a SIGSTOP already sent stops it before it
|
|
251
|
+
// runs any of its own code again. On Linux dash's loop shell sits in D while it
|
|
252
|
+
// waits on a vfork child the stop caught (2026-10-19). On macOS a low job's
|
|
253
|
+
// writes are throttled while other work writes, and it sits in U: a third of the
|
|
254
|
+
// time beside two dd loops, and long enough under a DMG build that a pause read as
|
|
255
|
+
// never landing (2026-11-03). One ps call for all of them. Windows can't stop a
|
|
256
|
+
// tree, so there's nothing to check.
|
|
257
|
+
export const inKernelOrStopped = stat => /[TZDU]/.test(stat || '');
|
|
258
|
+
export function runningIn(groups) {
|
|
259
|
+
if (WIN || !groups.length) return [];
|
|
260
|
+
const want = new Set(groups.map(Number));
|
|
261
|
+
return run('ps', ['-A', '-o', 'pid=,pgid=,stat=']).split('\n').map(l => l.trim().split(/\s+/))
|
|
262
|
+
.filter(([pid, pgid, stat]) => pid && want.has(Number(pgid)) && !inKernelOrStopped(stat)).map(([pid]) => Number(pid));
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
// Lower a running process's priority: background QoS on macOS (efficiency
|
|
266
|
+
// cores on Apple silicon), nice 10 on Linux, below normal on Windows.
|
|
267
|
+
export function lower(pid) {
|
|
268
|
+
try {
|
|
269
|
+
if (OS === 'macos') execFileSync('taskpolicy', ['-b', '-p', String(pid)], { stdio: 'ignore' });
|
|
270
|
+
else os.setPriority(pid, WIN ? os.constants.priority.PRIORITY_BELOW_NORMAL : 10);
|
|
271
|
+
return true;
|
|
272
|
+
} catch { return false; }
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// Undo lower(), for work the owner moved up (dibs boost). Linux lets only root
|
|
276
|
+
// lower a nice value, so there it usually fails.
|
|
277
|
+
export function raise(pid) {
|
|
278
|
+
try {
|
|
279
|
+
if (OS === 'macos') execFileSync('taskpolicy', ['-B', '-p', String(pid)], { stdio: 'ignore' });
|
|
280
|
+
else os.setPriority(pid, 0);
|
|
281
|
+
return true;
|
|
282
|
+
} catch { return false; }
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
// Free bytes on the volume holding dir, or null when it can't be read. Null,
|
|
286
|
+
// not Infinity: a failed reading must not pass as plenty of room.
|
|
287
|
+
export function freeDisk(dir) {
|
|
288
|
+
try { const st = fs.statfsSync(dir); return st.bavail * st.bsize; } catch { return null; }
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
// Free disk where dibs lives, swap in use, % of memory free, 1-minute load.
|
|
292
|
+
// Windows has no load average, so CPU busy % across all cores stands in for it.
|
|
293
|
+
export function pressure(dir) {
|
|
294
|
+
const diskFree = freeDisk(OS === 'macos' ? '/System/Volumes/Data' : dir);
|
|
295
|
+
let swapUsed = 0, swapFiles = null, memFree = Math.round(100 * os.freemem() / os.totalmem()), memAvail = null;
|
|
296
|
+
if (OS === 'macos') {
|
|
297
|
+
const sw = run('sysctl', ['-n', 'vm.swapusage']).match(/used = ([\d.]+)M/);
|
|
298
|
+
if (sw) swapUsed = parseFloat(sw[1]) * 1024 ** 2;
|
|
299
|
+
// The swap files' total size, which is what swap takes from the disk: macOS adds them a gigabyte at a time, ahead of what's used.
|
|
300
|
+
const tot = run('sysctl', ['-n', 'vm.swapusage']).match(/total = ([\d.]+)M/);
|
|
301
|
+
if (tot) swapFiles = parseFloat(tot[1]) * 1024 ** 2;
|
|
302
|
+
const lvl = Number(run('sysctl', ['-n', 'kern.memorystatus_level']));
|
|
303
|
+
if (lvl) memFree = lvl; // counts reclaimable cache as free, unlike os.freemem
|
|
304
|
+
memAvail = vmAvail(run('vm_stat', []));
|
|
305
|
+
} else if (OS === 'linux') {
|
|
306
|
+
try {
|
|
307
|
+
const mi = Object.fromEntries(fs.readFileSync('/proc/meminfo', 'utf8').split('\n')
|
|
308
|
+
.map(l => l.match(/^(\w+):\s+(\d+)/)).filter(Boolean).map(m => [m[1], Number(m[2]) * 1024]));
|
|
309
|
+
memFree = Math.round(100 * mi.MemAvailable / mi.MemTotal);
|
|
310
|
+
memAvail = mi.MemAvailable ?? null;
|
|
311
|
+
swapUsed = (mi.SwapTotal || 0) - (mi.SwapFree || 0);
|
|
312
|
+
} catch {}
|
|
313
|
+
}
|
|
314
|
+
let load = os.loadavg()[0];
|
|
315
|
+
if (WIN) {
|
|
316
|
+
const pct = Number(ps('(Get-CimInstance Win32_Processor | Measure-Object -Property LoadPercentage -Average).Average'));
|
|
317
|
+
load = (pct || 0) / 100 * os.cpus().length;
|
|
318
|
+
}
|
|
319
|
+
// Cores actually in use. The load average also counts processes waiting on
|
|
320
|
+
// disk, so heavy swapping can read 20 on a machine that's nearly idle.
|
|
321
|
+
// Just the CPU column (13 ms) unless the full table is fresh anyway: the full one,
|
|
322
|
+
// with every command line, took 60 ms of each dibs run's start on a busy Mac.
|
|
323
|
+
let busy = null;
|
|
324
|
+
if (!WIN) {
|
|
325
|
+
const cpus = procCache && Date.now() - procCache.at < 5000 ? procCache.list.map(p => p.cpu || 0)
|
|
326
|
+
: run('ps', ['-Ao', 'pcpu=']).split('\n').map(Number).filter(x => !isNaN(x));
|
|
327
|
+
if (cpus.length) busy = cpus.reduce((a, c) => a + c, 0) / 100;
|
|
328
|
+
}
|
|
329
|
+
return { diskFree, swapUsed, ...(swapFiles != null && { swapFiles }), memFree, memAvail, load, busy, cores: os.cpus().length, os: OS };
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// Memory a new job can take without anything going to swap, from vm_stat: pages
|
|
333
|
+
// free, inactive, speculative or purgeable. Not kern.memorystatus_level, which
|
|
334
|
+
// counts the compressor's pages as room: on 2026-10-22 it read 65% free while
|
|
335
|
+
// the compressor held 22 GB of pages in 4 GB and swap was eating the disk.
|
|
336
|
+
export function vmAvail(text) {
|
|
337
|
+
const size = Number(String(text).match(/page size of (\d+) bytes/)?.[1]);
|
|
338
|
+
if (!size) return null;
|
|
339
|
+
const pages = k => Number(String(text).match(new RegExp(`Pages ${k}:\\s+(\\d+)`))?.[1] || 0);
|
|
340
|
+
return (pages('free') + pages('inactive') + pages('speculative') + pages('purgeable')) * size;
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
// Memory pressure: 0 normal, 1 warning, 2 critical (swapping hard), or null
|
|
344
|
+
// when the OS doesn't say. One sysctl on macOS; PSI on Linux, where a tenth of
|
|
345
|
+
// the last 10s fully stalled on memory counts as critical. Windows: null.
|
|
346
|
+
export function memPressure() {
|
|
347
|
+
if (OS === 'macos') return { 1: 0, 2: 1, 4: 2 }[Number(run('sysctl', ['-n', 'kern.memorystatus_vm_pressure_level']))] ?? null;
|
|
348
|
+
if (OS !== 'linux') return null;
|
|
349
|
+
try {
|
|
350
|
+
const t = fs.readFileSync('/proc/pressure/memory', 'utf8');
|
|
351
|
+
const avg = kind => Number(t.match(new RegExp(`^${kind} avg10=([\\d.]+)`, 'm'))?.[1] || 0);
|
|
352
|
+
return avg('full') >= 10 ? 2 : avg('some') >= 10 ? 1 : 0;
|
|
353
|
+
} catch { return null; }
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// Name of the agent program a process belongs to (claude, codex, cursor...).
|
|
357
|
+
export const AGENTS = /^(claude|codex|cursor-agent|aider|gemini|opencode|amp)$/i;
|