@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.
Files changed (75) hide show
  1. package/CHANGELOG.md +594 -0
  2. package/LICENSE +670 -0
  3. package/README.md +85 -2
  4. package/bin/dibs-guard.mjs +7 -0
  5. package/bin/dibs.mjs +548 -0
  6. package/docs/benchmarks.md +193 -0
  7. package/docs/files.md +30 -0
  8. package/docs/guard.md +91 -0
  9. package/docs/later.md +43 -0
  10. package/docs/machines.md +147 -0
  11. package/docs/questions.md +78 -0
  12. package/docs/reference.md +157 -0
  13. package/docs/relay.md +196 -0
  14. package/docs/releasing.md +27 -0
  15. package/docs/scheduling.md +163 -0
  16. package/docs/simulators.md +17 -0
  17. package/package.json +45 -4
  18. package/skills/dibs/SKILL.md +183 -0
  19. package/src/acquire.mjs +700 -0
  20. package/src/admin.mjs +145 -0
  21. package/src/agents.mjs +145 -0
  22. package/src/alerts.mjs +499 -0
  23. package/src/answers.mjs +65 -0
  24. package/src/board.mjs +202 -0
  25. package/src/broker.mjs +369 -0
  26. package/src/commands.mjs +810 -0
  27. package/src/config.mjs +324 -0
  28. package/src/connect.mjs +106 -0
  29. package/src/cool.mjs +160 -0
  30. package/src/diskwarn.mjs +154 -0
  31. package/src/events.mjs +96 -0
  32. package/src/files.mjs +1123 -0
  33. package/src/guard.mjs +613 -0
  34. package/src/history.mjs +247 -0
  35. package/src/hogs.mjs +227 -0
  36. package/src/later.mjs +487 -0
  37. package/src/measure.mjs +262 -0
  38. package/src/news.mjs +101 -0
  39. package/src/nodecheck.mjs +17 -0
  40. package/src/notes.mjs +171 -0
  41. package/src/notices.mjs +160 -0
  42. package/src/ondemand.mjs +572 -0
  43. package/src/overlap.mjs +151 -0
  44. package/src/override.mjs +360 -0
  45. package/src/owner.mjs +30 -0
  46. package/src/plain.mjs +470 -0
  47. package/src/platform.mjs +357 -0
  48. package/src/preempt.mjs +438 -0
  49. package/src/primer.mjs +89 -0
  50. package/src/proc.mjs +99 -0
  51. package/src/progress.mjs +187 -0
  52. package/src/qr.mjs +204 -0
  53. package/src/questions.mjs +389 -0
  54. package/src/quota.mjs +81 -0
  55. package/src/reads.mjs +54 -0
  56. package/src/relay.mjs +779 -0
  57. package/src/remote.mjs +584 -0
  58. package/src/reset.mjs +127 -0
  59. package/src/schedule.mjs +1020 -0
  60. package/src/scratch.mjs +61 -0
  61. package/src/serve.mjs +742 -0
  62. package/src/service.mjs +221 -0
  63. package/src/shard.mjs +59 -0
  64. package/src/simctl.mjs +42 -0
  65. package/src/simpool.mjs +258 -0
  66. package/src/state.mjs +201 -0
  67. package/src/stats.mjs +328 -0
  68. package/src/style.mjs +44 -0
  69. package/src/talk.mjs +702 -0
  70. package/src/thin.sh +130 -0
  71. package/src/trust.mjs +152 -0
  72. package/src/util.mjs +184 -0
  73. package/src/version.mjs +2 -0
  74. package/src/web.mjs +1119 -0
  75. package/src/worker.mjs +318 -0
@@ -0,0 +1,221 @@
1
+ // dibs service: keep the coordinator, the worker and the throttle watcher
2
+ // running across logins and reboots. launchd on macOS, systemd --user on
3
+ // Linux, Task Scheduler on Windows.
4
+ import fs from 'node:fs';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+ import { execFileSync } from 'node:child_process';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { HOME } from './config.mjs';
10
+ import { OS } from './platform.mjs';
11
+ import { makeAlive } from './proc.mjs';
12
+ import { die, sleepSync } from './util.mjs';
13
+ import { logChange } from './owner.mjs';
14
+ import { unpatched } from './nodecheck.mjs';
15
+
16
+ const BIN = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'bin', 'dibs.mjs');
17
+ const KINDS = {
18
+ serve: { args: ['serve'], what: 'the coordinator for your machines' },
19
+ worker: { args: ['worker'], what: 'takes jobs from the coordinator' },
20
+ throttle: { args: ['throttle', '--watch'], what: 'moves hot work outside dibs to background priority' },
21
+ web: { args: ['web'], what: 'the page and MCP server showing your agents\' work' },
22
+ relay: { args: ['relay'], what: 'reach the page from any browser through the encrypted relay (dibs pair --remote)' },
23
+ };
24
+ // Things started by hand before the service existed; stopped so the service can take over.
25
+ const PIDFILES = { worker: 'worker.pid', throttle: 'cool.pid' };
26
+
27
+ const label = k => `dev.dibs.${k}`;
28
+ // DIBS_LAUNCH_AGENTS and DIBS_LAUNCHCTL stand in for ~/Library/LaunchAgents and launchctl in tests.
29
+ const plist = k => path.join(process.env.DIBS_LAUNCH_AGENTS || path.join(os.homedir(), 'Library', 'LaunchAgents'), `${label(k)}.plist`);
30
+ const LAUNCHCTL = process.env.DIBS_LAUNCHCTL || 'launchctl';
31
+ const unit = k => path.join(process.env.DIBS_LAUNCH_AGENTS || path.join(os.homedir(), '.config', 'systemd', 'user'), `dibs-${k}.service`);
32
+ const logFile = k => path.join(HOME, `${k}.log`);
33
+ const sh = (cmd, args) => { try { return execFileSync(cmd, args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }); } catch (e) { return e.stdout || ''; } };
34
+ const esc = s => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
35
+ const uid = () => process.getuid?.() ?? 0;
36
+
37
+ function env() {
38
+ const e = { PATH: process.env.PATH, HOME: os.homedir() };
39
+ if (process.env.DIBS_HOME) e.DIBS_HOME = process.env.DIBS_HOME;
40
+ return e;
41
+ }
42
+
43
+ function stopManual(k) {
44
+ try {
45
+ const pid = Number(fs.readFileSync(path.join(HOME, PIDFILES[k]), 'utf8'));
46
+ if (pid && makeAlive([pid])(pid)) { process.kill(pid, 'SIGTERM'); console.log(` stopped the ${k} started by hand (pid ${pid})`); }
47
+ } catch {}
48
+ }
49
+
50
+ // The Node a service should start by: a link that follows upgrades, not the
51
+ // versioned folder this Node runs from. On 2026-10-21 `brew upgrade` replaced
52
+ // Cellar/node/25.9.0_2 with 26.12.0, and at the next release all three services
53
+ // failed to start again (EX_CONFIG). Homebrew's opt/node link, then the bin link, when
54
+ // either is this same Node; any other Node as it is.
55
+ const LINKS = ['/opt/homebrew/opt/node/bin/node', '/opt/homebrew/bin/node', '/usr/local/opt/node/bin/node', '/usr/local/bin/node'];
56
+ export function stableNode(exec = process.execPath, links = LINKS) {
57
+ if (!/\/Cellar\//.test(exec)) return exec;
58
+ let real = exec;
59
+ try { real = fs.realpathSync(exec); } catch {}
60
+ for (const l of links) { try { if (fs.realpathSync(l) === real) return l; } catch {} }
61
+ return exec;
62
+ }
63
+
64
+ // launchctl bootout returns before the service is gone, and a bootstrap then
65
+ // fails with "5: Input/output error": on 2026-10-22 reinstalling the services
66
+ // left the worker and the throttle down. So wait for it to go (UNLOAD_WAIT at
67
+ // most), and try the bootstrap again a few times.
68
+ const UNLOAD_WAIT = 10e3, BOOT_TRIES = 5;
69
+ const loaded = k => { try { execFileSync(LAUNCHCTL, ['print', `gui/${uid()}/${label(k)}`], { stdio: 'ignore' }); return true; } catch { return false; } };
70
+ function unload(k) {
71
+ if (!loaded(k)) return;
72
+ sh(LAUNCHCTL, ['bootout', `gui/${uid()}/${label(k)}`]);
73
+ for (const t0 = Date.now(); loaded(k) && Date.now() - t0 < UNLOAD_WAIT;) sleepSync(200);
74
+ }
75
+ function bootstrap(k) {
76
+ for (let i = 1; ; i++) {
77
+ try { execFileSync(LAUNCHCTL, ['bootstrap', `gui/${uid()}`, plist(k)], { stdio: ['ignore', 'pipe', 'pipe'] }); return; }
78
+ catch (e) { if (i >= BOOT_TRIES) die(`launchctl couldn't load ${label(k)}: ${String(e.stderr || e.message).trim()}. Try again: dibs service install ${k}`); }
79
+ sleepSync(1000);
80
+ }
81
+ }
82
+
83
+ function install(k) {
84
+ const argv = [stableNode(), BIN, ...KINDS[k].args];
85
+ fs.mkdirSync(HOME, { recursive: true });
86
+ // Out of launchd first, so the pidfile's process (if any is left) was started by hand.
87
+ if (OS === 'macos') unload(k);
88
+ if (PIDFILES[k]) stopManual(k);
89
+ if (OS === 'macos') {
90
+ // Jobs a worker runs inherit its scheduling class, so it can't be Background.
91
+ const type = { serve: 'Standard', worker: 'Interactive', throttle: 'Background', web: 'Standard', relay: 'Standard' }[k];
92
+ fs.mkdirSync(path.dirname(plist(k)), { recursive: true });
93
+ fs.writeFileSync(plist(k), `<?xml version="1.0" encoding="UTF-8"?>
94
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
95
+ <plist version="1.0">
96
+ <dict>
97
+ <key>Label</key><string>${label(k)}</string>
98
+ <key>ProgramArguments</key>
99
+ <array>${argv.map(a => `<string>${esc(a)}</string>`).join('')}</array>
100
+ <key>EnvironmentVariables</key>
101
+ <dict>${Object.entries(env()).map(([a, b]) => `<key>${esc(a)}</key><string>${esc(b)}</string>`).join('')}</dict>
102
+ <key>RunAtLoad</key><true/>
103
+ <key>KeepAlive</key><true/>
104
+ <key>ThrottleInterval</key><integer>10</integer>
105
+ <key>ProcessType</key><string>${type}</string>
106
+ <key>StandardOutPath</key><string>${esc(logFile(k))}</string>
107
+ <key>StandardErrorPath</key><string>${esc(logFile(k))}</string>
108
+ </dict>
109
+ </plist>
110
+ `);
111
+ bootstrap(k);
112
+ } else if (OS === 'linux') {
113
+ fs.mkdirSync(path.dirname(unit(k)), { recursive: true });
114
+ const q = a => `"${String(a).replace(/(["\\$`])/g, '\\$1')}"`;
115
+ fs.writeFileSync(unit(k), `[Unit]
116
+ Description=dibs ${k}: ${KINDS[k].what}
117
+
118
+ [Service]
119
+ ExecStart=${argv.map(q).join(' ')}
120
+ ${Object.entries(env()).map(([a, b]) => `Environment=${q(`${a}=${b}`)}`).join('\n')}
121
+ Restart=always
122
+ RestartSec=10
123
+ StandardOutput=append:${logFile(k)}
124
+ StandardError=append:${logFile(k)}
125
+
126
+ [Install]
127
+ WantedBy=default.target
128
+ `);
129
+ execFileSync('systemctl', ['--user', 'daemon-reload'], { stdio: 'inherit' });
130
+ execFileSync('systemctl', ['--user', 'enable', '--now', `dibs-${k}.service`], { stdio: 'inherit' });
131
+ console.log(` to keep it running while you're logged out: loginctl enable-linger ${os.userInfo().username}`);
132
+ } else {
133
+ const cmd = `cmd /c ""${argv[0]}" "${argv[1]}" ${KINDS[k].args.join(' ')} >> "${logFile(k)}" 2>&1"`;
134
+ execFileSync('schtasks', ['/Create', '/F', '/SC', 'ONLOGON', '/TN', `dibs ${k}`, '/TR', cmd], { stdio: 'inherit' });
135
+ execFileSync('schtasks', ['/Run', '/TN', `dibs ${k}`], { stdio: 'inherit' });
136
+ }
137
+ console.log(`installed dibs ${k}: ${KINDS[k].what}. Log: ${logFile(k)}`);
138
+ }
139
+
140
+ function remove(k) {
141
+ let had = false;
142
+ if (OS === 'macos') {
143
+ sh(LAUNCHCTL, ['bootout', `gui/${uid()}/${label(k)}`]);
144
+ if (fs.existsSync(plist(k))) { fs.rmSync(plist(k)); had = true; }
145
+ } else if (OS === 'linux') {
146
+ sh('systemctl', ['--user', 'disable', '--now', `dibs-${k}.service`]);
147
+ if (fs.existsSync(unit(k))) { fs.rmSync(unit(k)); had = true; sh('systemctl', ['--user', 'daemon-reload']); }
148
+ } else {
149
+ sh('schtasks', ['/End', '/TN', `dibs ${k}`]);
150
+ had = sh('schtasks', ['/Delete', '/F', '/TN', `dibs ${k}`]).length > 0;
151
+ }
152
+ console.log(had ? `removed dibs ${k}` : `dibs ${k} wasn't installed`);
153
+ }
154
+
155
+ // Out of launchd or systemd, and one started by hand stopped too (dibs leave). One that
156
+ // isn't installed is left alone: nothing to take out, and nothing touched that dibs didn't put there.
157
+ export function removeService(k) {
158
+ if (PIDFILES[k]) stopManual(k);
159
+ if (state(k) !== 'not installed') remove(k);
160
+ }
161
+
162
+ // Each installed service for the alerts (src/alerts.mjs): whether it runs, how
163
+ // many times launchd has started it, and how it last exited. Not installed: left out.
164
+ export function serviceHealth() {
165
+ const out = {};
166
+ for (const k of Object.keys(KINDS)) {
167
+ if (OS === 'macos') {
168
+ if (!fs.existsSync(plist(k))) continue;
169
+ const txt = sh(LAUNCHCTL, ['print', `gui/${uid()}/${label(k)}`]);
170
+ const exit = txt.match(/last exit code = (-?\d+)/)?.[1];
171
+ out[k] = { what: KINDS[k].what, running: /\bpid = \d+/.test(txt), runs: Number(txt.match(/\bruns = (\d+)/)?.[1] || 0), exit: exit == null ? null : Number(exit) };
172
+ } else if (OS === 'linux') {
173
+ if (!fs.existsSync(unit(k))) continue;
174
+ out[k] = { what: KINDS[k].what, running: sh('systemctl', ['--user', 'is-active', `dibs-${k}.service`]).trim() === 'active', runs: 0, exit: null };
175
+ }
176
+ }
177
+ return out;
178
+ }
179
+
180
+ function state(k) {
181
+ if (OS === 'macos') {
182
+ if (!fs.existsSync(plist(k))) return 'not installed';
183
+ const out = sh(LAUNCHCTL, ['print', `gui/${uid()}/${label(k)}`]);
184
+ const pid = out.match(/\bpid = (\d+)/)?.[1];
185
+ return pid ? `running (pid ${pid})` : `installed, not running${out.match(/last exit code = (.*)/) ? ` (last exit ${out.match(/last exit code = (.*)/)[1].trim()})` : ''}`;
186
+ }
187
+ if (OS === 'linux') {
188
+ if (!fs.existsSync(unit(k))) return 'not installed';
189
+ return sh('systemctl', ['--user', 'is-active', `dibs-${k}.service`]).trim() || 'unknown';
190
+ }
191
+ const out = sh('schtasks', ['/Query', '/TN', `dibs ${k}`, '/FO', 'LIST']);
192
+ return out ? (out.match(/Status:\s*(.*)/)?.[1]?.trim() || 'installed') : 'not installed';
193
+ }
194
+
195
+ const relayStatus = async () => { try { return (await import('./relay.mjs')).statusLine(); } catch { return null; } };
196
+
197
+ // dibs service install|remove|status [serve] [worker] [throttle] [web] [relay]
198
+ // What dibs service status says, as data, for dibs web.
199
+ export function servicesJson() {
200
+ return Object.entries(KINDS).map(([name, k]) => ({ name, state: state(name), what: k.what }));
201
+ }
202
+
203
+ export async function service(args) {
204
+ const [action = 'status', ...rest] = args.filter(a => !a.startsWith('-'));
205
+ const kinds = rest.length ? rest : action === 'status' ? Object.keys(KINDS) : [];
206
+ for (const k of kinds) if (!KINDS[k]) die(`no service called ${k}. Services: ${Object.keys(KINDS).join(', ')}`);
207
+ if (action === 'status') {
208
+ for (const k of kinds) console.log(`${k.padEnd(9)} ${state(k).padEnd(28)} ${KINDS[k].what}`);
209
+ // The relay's own view: connected or not, since when, how many devices.
210
+ if (kinds.includes('relay')) { const s = await relayStatus(); if (s) console.log(` relay: ${s}`); }
211
+ return;
212
+ }
213
+ if (!kinds.length) die(`which? dibs service ${action} serve|worker|throttle|web|relay (several at once is fine)`);
214
+ // A service runs for weeks and listens on the network: not on a Node with a known hole.
215
+ const hole = action === 'install' && !process.env.DIBS_ALLOW_UNPATCHED && unpatched();
216
+ if (hole) die(`${hole}. The service would run on that Node (${process.execPath}): put a fixed one first on your PATH and run this again.`);
217
+ if (action === 'install' || action === 'remove') logChange(`service ${action}`, { services: kinds });
218
+ if (action === 'install') kinds.forEach(install);
219
+ else if (action === 'remove') kinds.forEach(remove);
220
+ else die('dibs service install|remove|status [serve] [worker] [throttle] [web] [relay]');
221
+ }
package/src/shard.mjs ADDED
@@ -0,0 +1,59 @@
1
+ // Splitting a big test suite across machines: N runs of the same command, each
2
+ // with its runner's own shard flag, the first here and the rest wherever they'd
3
+ // start soonest (--anywhere), their output prefixed and their exit codes merged.
4
+ // --shards N asks for it. dibs does it on its own for a vitest or node --test
5
+ // suite that usually takes over AUTO_OVER, with an on-demand machine to send to:
6
+ // those runners take no ports, so two shards on one machine can't collide. A
7
+ // Playwright suite only with --shards: its webServer may want a fixed port.
8
+ import { spawn } from 'node:child_process';
9
+ import path from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { SIGNALS, signalExit, say } from './util.mjs';
12
+
13
+ const BIN = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'bin', 'dibs.mjs');
14
+ export const AUTO_OVER = 5 * 6e4;
15
+ export const AUTO_SHARDS = 2; // here and boat-1: a third would mean making a VM for it
16
+
17
+ // The command with its runner's shard flag for shard i of n, or null when the
18
+ // runner isn't one dibs knows how to split, or it's already split. which says
19
+ // whose flag: playwright, vitest or node.
20
+ export function sharder(cmd) {
21
+ if (cmd.some(a => /^--(test-)?shard(=|$)/.test(a))) return null;
22
+ const base = a => path.basename(a);
23
+ const pw = cmd.findIndex((a, i) => base(a) === 'playwright' && cmd[i + 1] === 'test');
24
+ if (pw >= 0) return { which: 'playwright', at: (i, n) => [...cmd.slice(0, pw + 2), `--shard=${i}/${n}`, ...cmd.slice(pw + 2)] };
25
+ const vt = cmd.findIndex(a => base(a) === 'vitest');
26
+ if (vt >= 0) {
27
+ const after = cmd[vt + 1] === 'run' ? vt + 2 : vt + 1;
28
+ return { which: 'vitest', at: (i, n) => [...cmd.slice(0, after), `--shard=${i}/${n}`, ...cmd.slice(after)] };
29
+ }
30
+ const nt = base(cmd[0]) === 'node' ? cmd.indexOf('--test') : -1;
31
+ if (nt > 0) return { which: 'node', at: (i, n) => [...cmd.slice(0, nt + 1), `--test-shard=${i}/${n}`, ...cmd.slice(nt + 1)] };
32
+ return null;
33
+ }
34
+
35
+ // Each shard is its own dibs run, so it waits its own turn and its own machine's
36
+ // rules apply. Exit: the first shard's non-zero code, else 0.
37
+ // to: the on-demand machine to wake for the rest, or null for --anywhere (which never
38
+ // wakes a sleeping one, so the pieces would all land here).
39
+ export function runShards(o, n, split, to = null) {
40
+ say(`splitting this ${split.which} run into ${n} shards: the first here, the rest ${to ? `on ${to}` : "wherever they'd start soonest"}.`);
41
+ const kids = [];
42
+ for (let i = 1; i <= n; i++) {
43
+ const args = ['run', o.res.join(','), '--no-shard', '-m', `${o.purpose || 'shard'} (shard ${i}/${n})`, ...(i > 1 ? (to ? ['--on', to] : ['--anywhere']) : []),
44
+ ...(o.maxWait === Infinity ? ['--wait'] : []), '--', ...split.at(i, n)];
45
+ const p = spawn(process.execPath, [BIN, ...args], { stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, DIBS_SHARD: `${i}/${n}` } });
46
+ for (const [from, to] of [[p.stdout, process.stdout], [p.stderr, process.stderr]]) {
47
+ let rest = '';
48
+ from.on('data', d => { const lines = (rest + d).split('\n'); rest = lines.pop(); for (const l of lines) to.write(`[${i}/${n}] ${l}\n`); });
49
+ from.on('end', () => { if (rest) to.write(`[${i}/${n}] ${rest}\n`); });
50
+ }
51
+ kids.push(new Promise(r => p.on('exit', (code, sig) => r(code ?? signalExit(sig)))));
52
+ for (const sig of SIGNALS) process.on(sig, () => p.kill(sig));
53
+ }
54
+ return Promise.all(kids).then(codes => {
55
+ const bad = codes.find(c => c !== 0) ?? 0;
56
+ say(`all ${n} shards done: ${codes.map((c, i) => `${i + 1}/${n} exit ${c}`).join(', ')}.`);
57
+ process.exit(bad);
58
+ });
59
+ }
package/src/simctl.mjs ADDED
@@ -0,0 +1,42 @@
1
+ // The few simctl calls the simulator pool makes, behind one small interface so
2
+ // tests can swap in a fake.
3
+ import { spawn, execFileSync } from 'node:child_process';
4
+
5
+ const BOOT_LIMIT = 5 * 6e4; // a boot that hasn't finished by now isn't going to
6
+
7
+ function xc(args, timeout = 6e4) {
8
+ return execFileSync('xcrun', ['simctl', ...args], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout, maxBuffer: 64 * 1024 ** 2 });
9
+ }
10
+ const quiet = args => { try { xc(args); return true; } catch { return false; } };
11
+
12
+ // Devices from `simctl list -j devices`, flattened: { udid, name, state, runtime, type, size }.
13
+ const flat = byRuntime => Object.entries(byRuntime).flatMap(([runtime, list]) => list.map(d =>
14
+ ({ udid: d.udid, name: d.name, state: d.state, runtime, type: d.deviceTypeIdentifier, size: d.dataPathSize ?? null })));
15
+
16
+ const real = {
17
+ runtimes: () => JSON.parse(xc(['list', '-j', 'runtimes'])).runtimes,
18
+ devices: () => flat(JSON.parse(xc(['list', '-j', 'devices'])).devices),
19
+ create: (name, type, runtime) => xc(['create', name, type, runtime]).trim(),
20
+ // Boot and wait until the device is usable. Already booted is fine.
21
+ boot: udid => new Promise((res, rej) => {
22
+ const p = spawn('xcrun', ['simctl', 'bootstatus', udid, '-b'], { stdio: ['ignore', 'ignore', 'pipe'] });
23
+ let err = '';
24
+ p.stderr.on('data', d => (err += d));
25
+ const t = setTimeout(() => p.kill('SIGKILL'), BOOT_LIMIT);
26
+ p.on('error', e => { clearTimeout(t); rej(e); });
27
+ p.on('exit', code => { clearTimeout(t); code === 0 ? res() : rej(new Error(err.trim().split('\n').pop() || `simctl bootstatus exited ${code}`)); });
28
+ }),
29
+ // True once the device is shut down, including when it already was.
30
+ shutdown: udid => quiet(['shutdown', udid]) || devState(real, udid) !== 'Booted',
31
+ // For cleanup inside the state lock: start the shutdown and don't wait.
32
+ shutdownLater: udid => { try { spawn('xcrun', ['simctl', 'shutdown', udid], { stdio: 'ignore', detached: true }).unref(); } catch {} },
33
+ erase: udid => { xc(['erase', udid]); },
34
+ remove: udid => { xc(['delete', udid]); },
35
+ };
36
+
37
+ const devState = (ctl, udid) => { try { return ctl.devices().find(d => d.udid === udid)?.state ?? null; } catch { return null; } };
38
+
39
+ // Tests point DIBS_FAKE_SIMCTL at a JSON file that plays CoreSimulator; the
40
+ // fake that reads it lives in test/, loaded only then.
41
+ const fake = process.env.DIBS_FAKE_SIMCTL ? (await import('../test/fake-simctl.mjs')).fakeSimctl : null;
42
+ export const simctl = () => (fake ? fake(process.env.DIBS_FAKE_SIMCTL) : real);
@@ -0,0 +1,258 @@
1
+ // The simulator pool: a resource with `pool` settings (sim-own by default)
2
+ // hands each lease its own simulator. dibs creates the devices, names them
3
+ // dibs-pool-N, keeps them between leases, and only ever deletes those.
4
+ //
5
+ // Devices live in the state file as s.pool, so taking one is atomic with the
6
+ // lease that uses it: { name, udid, res, type, runtime, lease, who, booted,
7
+ // lastWho, lastUsed, created }.
8
+ import fs from 'node:fs';
9
+ import os from 'node:os';
10
+ import path from 'node:path';
11
+ import { resCfg, machine, paths, HOME, POOL_DEFAULTS } from './config.mjs';
12
+ import { withState } from './state.mjs';
13
+ import { simctl } from './simctl.mjs';
14
+ import { bytes, gb, size, dur, die, say, now } from './util.mjs';
15
+
16
+ export const PREFIX = 'dibs-pool-';
17
+ const ERASE = new Set(['other-agent', 'always', 'never']);
18
+ // Device types tried in order when none is configured: an iPhone 17-class phone.
19
+ const PREFERRED = ['iPhone-17', 'iPhone-17-Pro', 'iPhone-16', 'iPhone-16-Pro'];
20
+
21
+ const poolOf = (cfg, r) => { const p = resCfg(cfg, r).pool; return p ? { ...POOL_DEFAULTS, ...p } : null; };
22
+ const poolRes = cfg => Object.keys(cfg.resources).filter(r => cfg.resources[r].pool);
23
+ const ours = name => typeof name === 'string' && name.startsWith(PREFIX);
24
+
25
+ // Every device this DIBS_HOME created, one udid a line. Another dibs on the
26
+ // same Mac (a second DIBS_HOME, a trial install) names its devices
27
+ // dibs-pool-N too, so a pool device the state doesn't know is adopted or
28
+ // pruned only if it's in this list. The first time, the list starts as the
29
+ // devices the state already tracks.
30
+ const MADE = path.join(HOME, 'pool-made');
31
+ function madeHere() {
32
+ try { return new Set(fs.readFileSync(MADE, 'utf8').split('\n').filter(Boolean)); } catch (e) { if (e.code !== 'ENOENT') return new Set(); }
33
+ let pool = [];
34
+ try { pool = JSON.parse(fs.readFileSync(paths.state, 'utf8')).pool || []; } catch {}
35
+ const seed = pool.map(d => d.udid).filter(Boolean);
36
+ try { fs.writeFileSync(MADE, seed.map(u => `${u}\n`).join('')); } catch {}
37
+ return new Set(seed);
38
+ }
39
+ const noteMade = udid => { madeHere(); try { fs.appendFileSync(MADE, `${udid}\n`); } catch {} };
40
+
41
+ const ver = v => String(v).split('.').map(Number);
42
+ const newer = (a, b) => { const x = ver(a), y = ver(b); for (let i = 0; i < 3; i++) if ((x[i] || 0) !== (y[i] || 0)) return (x[i] || 0) - (y[i] || 0); return 0; };
43
+ const isIOS = r => r.platform ? r.platform === 'iOS' : /^iOS /.test(r.name || '');
44
+
45
+ // The device type and runtime new devices get: what the config names, or the
46
+ // newest installed iOS runtime and an iPhone 17-class phone it supports.
47
+ export function spec(pool, ctl = simctl()) {
48
+ const rts = ctl.runtimes().filter(r => r.isAvailable !== false && isIOS(r));
49
+ const want = pool.runtime;
50
+ const rt = want ? rts.find(r => [r.identifier, r.name, r.version].includes(want)) : rts.sort((a, b) => newer(b.version, a.version))[0];
51
+ if (!rt) die(want ? `no installed iOS runtime matches "${want}". Installed: ${rts.map(r => r.name).join(', ') || 'none'}`
52
+ : 'no iOS simulator runtime is installed (Xcode > Settings > Components)');
53
+ const types = rt.supportedDeviceTypes || [];
54
+ const dt = pool.deviceType
55
+ ? types.find(t => [t.identifier, t.name].includes(pool.deviceType)) || { identifier: pool.deviceType, name: pool.deviceType }
56
+ : PREFERRED.map(p => types.find(t => t.identifier.endsWith(`.${p}`))).find(Boolean) || types.filter(t => t.productFamily === 'iPhone').pop();
57
+ if (!dt) die(`${rt.name} supports no iPhone device type; set pool.deviceType in the config`);
58
+ return { runtime: rt.identifier, runtimeName: rt.name, type: dt.identifier, typeName: dt.name };
59
+ }
60
+
61
+ // Pick a free device for a lease, or a name for a new one. Called inside
62
+ // withState. Prefers the device this agent used last (no erase needed), then
63
+ // one nobody has used, then the one idle longest.
64
+ export function claim(s, lease, res, sp, policy = 'other-agent') {
65
+ s.pool ||= [];
66
+ const fits = d => !d.lease && d.res === res && d.type === sp.type && d.runtime === sp.runtime;
67
+ const free = s.pool.filter(fits).sort((a, b) => (a.lastUsed || 0) - (b.lastUsed || 0));
68
+ let dev = free.find(d => d.lastWho === lease.who) || free.find(d => !d.lastWho) || free[0];
69
+ const create = !dev;
70
+ if (create) {
71
+ let n = 1;
72
+ while (s.pool.some(d => d.name === `${PREFIX}${n}`)) n++;
73
+ dev = { name: `${PREFIX}${n}`, udid: null, res, type: sp.type, runtime: sp.runtime, created: now() };
74
+ s.pool.push(dev);
75
+ }
76
+ const erase = !create && !!dev.lastWho && (policy === 'always' || (policy === 'other-agent' && dev.lastWho !== lease.who));
77
+ Object.assign(dev, { lease: lease.id, who: lease.who, since: now() });
78
+ return { dev: { ...dev }, create, erase };
79
+ }
80
+
81
+ // Free the devices of leases that are gone, and shut down any free device
82
+ // still booted. Called on every state read, inside the lock, so it only
83
+ // starts shutdowns and never waits for one.
84
+ export function reapPool(s, ctl = null) {
85
+ if (!s.pool?.length) return;
86
+ const live = new Set(s.leases.map(l => l.id));
87
+ for (const d of s.pool) {
88
+ if (d.lease && !live.has(d.lease)) {
89
+ Object.assign(d, { lease: null, lastWho: d.who, lastUsed: now() });
90
+ if (d.udid) d.booted = true; // it may have booted before its lease died
91
+ }
92
+ if (!d.lease && d.booted && d.udid) { (ctl ||= simctl()).shutdownLater(d.udid); d.booted = false; }
93
+ }
94
+ }
95
+
96
+ // Memory one more simulator needs, and how many fit now. Devices still
97
+ // booting haven't taken their memory yet, so they're counted here.
98
+ export function poolRoom(s, cfg, r, m = machine()) {
99
+ const per = bytes(poolOf(cfg, r).perSim);
100
+ const total = m.memTotal || os.totalmem();
101
+ const keep = total * cfg.minFreeMem / 100;
102
+ const booting = (s.pool || []).filter(d => d.res === r && d.lease && !d.booted).length;
103
+ const free = total * m.memFree / 100 - booting * per;
104
+ return { per, keep, free, booting, fits: Math.max(0, Math.floor((free - keep) / per)) };
105
+ }
106
+
107
+ // For verdict(): a pool resource waits while booting another simulator would
108
+ // push the machine under minFreeMem. Like the ram rule, it doesn't apply when
109
+ // nothing else holds anything, since then waiting can't free memory.
110
+ export function poolBlock(s, me, cfg, mine, m = machine()) {
111
+ if (!s.leases.length) return null;
112
+ for (const r of me.res) {
113
+ if (!resCfg(cfg, r).pool || mine.has(r)) continue;
114
+ const room = poolRoom(s, cfg, r, m);
115
+ if (room.fits < 1)
116
+ return { rule: 'ram', why: `${r}: ${gb(Math.max(room.free, 0))} memory free${room.booting ? ` (${room.booting} still booting)` : ''}, another simulator needs ${gb(room.per)} plus the ${gb(room.keep)} kept free`, on: r,
117
+ free: Math.max(room.free, 0), need: room.per + room.keep };
118
+ }
119
+ return null;
120
+ }
121
+
122
+ // Memory a pool lease adds on top of what the job itself asked for with --mem.
123
+ export const simMem = (cfg, res) => Math.max(0, ...res.map(r => (resCfg(cfg, r).pool ? bytes(poolOf(cfg, r).perSim) : 0)));
124
+
125
+ // What a job asks for: --mem, --cpu and --disk, or the most any of its
126
+ // resources costs. A resource's own mem already counts its simulator; --mem
127
+ // names the job's own need, so a pool simulator comes on top of it. Everything
128
+ // that sizes a job uses this: dibs run and hold, dibs when, and --anywhere.
129
+ export function jobSize(cfg, res, o = {}) {
130
+ const most = f => Math.max(...res.map(r => f(resCfg(cfg, r))));
131
+ return {
132
+ mem: o.mem != null ? o.mem + simMem(cfg, res) : most(c => bytes(c.mem)),
133
+ cpu: o.cpu ?? most(c => c.cpu ?? 1),
134
+ disk: o.disk ?? most(c => bytes(c.disk || 0)),
135
+ };
136
+ }
137
+
138
+ // Give a lease its simulator: claim one, create or erase it if needed, boot
139
+ // it. Returns { udid, name } or null when the lease has no pool resource. A
140
+ // run covered by its own session's hold uses the hold's device.
141
+ export async function checkout(lease, cfg, ctl = simctl()) {
142
+ const res = lease.res.find(r => resCfg(cfg, r).pool);
143
+ if (!res) return null;
144
+ if (lease.covered?.includes(res)) {
145
+ const d = withState(s => (s.pool || []).find(d => d.res === res && d.lease && s.leases.some(l => l.id === d.lease && l.kind === 'hold' && l.pid === lease.spid)));
146
+ if (d?.udid) return { udid: d.udid, name: d.name };
147
+ }
148
+ const pool = poolOf(cfg, res);
149
+ if (!ERASE.has(pool.erase)) die(`pool.erase is one of ${[...ERASE].join(', ')}`);
150
+ const sp = spec(pool, ctl);
151
+ const c = withState(s => claim(s, lease, res, sp, pool.erase));
152
+ const save = o => withState(s => { const d = (s.pool || []).find(x => x.name === c.dev.name); if (d && d.lease === lease.id) Object.assign(d, o); });
153
+ try {
154
+ let { udid } = c.dev, erase = c.erase;
155
+ const devs = ctl.devices();
156
+ if (!udid || !devs.some(d => d.udid === udid)) {
157
+ // A device of ours that the state file lost track of is adopted, and wiped since its last user is unknown.
158
+ const mine = madeHere();
159
+ const stray = devs.find(d => d.name === c.dev.name && d.type === sp.type && d.runtime === sp.runtime && mine.has(d.udid));
160
+ if (stray) { udid = stray.udid; erase = pool.erase !== 'never'; }
161
+ else { say(`${res}: creating ${c.dev.name} (${sp.typeName}, ${sp.runtimeName})`); udid = ctl.create(c.dev.name, sp.type, sp.runtime); noteMade(udid); }
162
+ save({ udid });
163
+ }
164
+ if (erase) {
165
+ say(`${res}: erasing ${c.dev.name}, last used by another agent`);
166
+ ctl.shutdown(udid);
167
+ ctl.erase(udid);
168
+ }
169
+ const t = now();
170
+ await ctl.boot(udid);
171
+ if (now() - t > 3000) say(`${res}: booted ${c.dev.name} in ${dur(now() - t)}`);
172
+ save({ booted: true });
173
+ return { udid, name: c.dev.name };
174
+ } catch (e) {
175
+ // Let it go; reapPool shuts it down if it got as far as booting.
176
+ withState(s => { const d = (s.pool || []).find(x => x.name === c.dev.name); if (d && d.lease === lease.id) Object.assign(d, { lease: null, lastWho: d.who, lastUsed: now(), booted: !!d.udid }); });
177
+ throw new Error(`couldn't get ${c.dev.name} ready: ${e.message}`);
178
+ }
179
+ }
180
+
181
+ // Shut a lease's simulator down and put it back in the pool. If the shutdown
182
+ // fails, the device stays marked booted and the next state read retries it.
183
+ export function checkin(lease, ctl = simctl()) {
184
+ const d = withState(s => (s.pool || []).find(x => x.lease === lease.id));
185
+ if (!d) return;
186
+ const down = !d.udid || ctl.shutdown(d.udid);
187
+ withState(s => {
188
+ const x = (s.pool || []).find(y => y.name === d.name);
189
+ if (x && x.lease === lease.id) Object.assign(x, { lease: null, lastWho: x.who, lastUsed: now(), booted: !down });
190
+ });
191
+ }
192
+
193
+ // dibs sims [prune]: the pool, and deleting its idle devices.
194
+ // The pool as the state last recorded it, for dibs web: no simctl call and no
195
+ // write, so a device's booted state is what dibs last saw, not a fresh look.
196
+ export function poolJson(s, cfg, m = machine()) {
197
+ const rows = (s.pool || []).map(d => ({ name: d.name, res: d.res, who: d.who || null, since: d.since || null, lastUsed: d.lastUsed || null, lastWho: d.lastWho || null, inUse: !!d.lease, creating: !d.udid }));
198
+ const room = Object.fromEntries(poolRes(cfg).map(r => [r, { ...poolRoom(s, cfg, r, m), max: resCfg(cfg, r).slots, inUse: rows.filter(d => d.res === r && d.inUse).length }]));
199
+ return { room, devices: rows };
200
+ }
201
+
202
+ export function sims(o, args, cfg, ctl = simctl()) {
203
+ const devs = ctl.devices();
204
+ const byUdid = new Map(devs.map(d => [d.udid, d]));
205
+ // Forget devices deleted behind dibs' back; shut down free ones left booted.
206
+ const s = withState(s => {
207
+ s.pool = (s.pool || []).filter(d => d.lease || !d.udid || byUdid.has(d.udid));
208
+ for (const d of s.pool) if (!d.lease && d.udid && byUdid.get(d.udid)?.state === 'Booted') { ctl.shutdownLater(d.udid); d.booted = false; }
209
+ return s;
210
+ });
211
+ const tracked = new Set(s.pool.map(d => d.udid));
212
+ const mine = madeHere();
213
+ const strays = devs.filter(d => ours(d.name) && !tracked.has(d.udid) && mine.has(d.udid));
214
+ const others = devs.filter(d => ours(d.name) && !tracked.has(d.udid) && !mine.has(d.udid));
215
+ if (args[0] === 'prune') return prune(ctl, byUdid, strays);
216
+ if (args[0]) die(`dibs sims lists the pool; dibs sims prune deletes its idle devices. Unknown: ${args[0]}`);
217
+ const t = now();
218
+ const rows = s.pool.map(d => {
219
+ const real = byUdid.get(d.udid) || {};
220
+ return { ...d, state: d.udid ? real.state || 'missing' : 'creating', disk: real.size ?? null };
221
+ });
222
+ if (o.json) {
223
+ const room = Object.fromEntries(poolRes(cfg).map(r => [r, { ...poolRoom(s, cfg, r), max: resCfg(cfg, r).slots, inUse: rows.filter(d => d.res === r && d.lease).length }]));
224
+ return console.log(JSON.stringify({ room, devices: rows, untracked: strays, otherDibs: others }, null, 1));
225
+ }
226
+ for (const r of poolRes(cfg)) {
227
+ const room = poolRoom(s, cfg, r);
228
+ const inUse = rows.filter(d => d.res === r && d.lease).length;
229
+ console.log(`${r}: ${inUse} in use, at most ${resCfg(cfg, r).slots} at once; memory fits ${room.fits} more now `
230
+ + `(${gb(Math.max(room.free, 0))} free, ${gb(room.keep)} kept free, ${gb(room.per)} each)`);
231
+ }
232
+ for (const d of others) console.log(` ${d.name.padEnd(13)} ${d.udid.padEnd(36)} ${d.state.padEnd(9)} not made by this dibs (${HOME}); another dibs on this Mac may be using it, so prune leaves it alone`);
233
+ if (!rows.length && !strays.length) return console.log('no pool devices yet. The first `dibs run sim-own -- <cmd>` creates one.');
234
+ for (const d of rows.sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true }))) {
235
+ const use = d.lease ? `in use by ${d.who} for ${dur(t - d.since)}` : d.lastUsed ? `idle ${dur(t - d.lastUsed)}, last used by ${d.lastWho}` : 'never used';
236
+ console.log(` ${d.name.padEnd(13)} ${String(d.udid || '').padEnd(36)} ${d.state.padEnd(9)} ${use}${d.disk != null ? `, ${size(d.disk)} on disk` : ''}`);
237
+ }
238
+ for (const d of strays) console.log(` ${d.name.padEnd(13)} ${d.udid.padEnd(36)} ${d.state.padEnd(9)} not tracked (left from an older state file); prune deletes it`);
239
+ console.log('dibs only creates and deletes devices named dibs-pool-*. Delete idle ones: dibs sims prune');
240
+ }
241
+
242
+ function prune(ctl, byUdid, strays) {
243
+ const gone = withState(s => {
244
+ const idle = (s.pool || []).filter(d => !d.lease);
245
+ s.pool = (s.pool || []).filter(d => d.lease);
246
+ return { idle, busy: s.pool.map(d => d.name) };
247
+ });
248
+ let freed = 0;
249
+ const done = [];
250
+ for (const d of [...gone.idle.filter(d => d.udid && byUdid.has(d.udid)), ...strays]) {
251
+ if (!ours(d.name)) continue; // never anything dibs didn't name
252
+ ctl.shutdown(d.udid);
253
+ try { ctl.remove(d.udid); done.push(d.name); freed += byUdid.get(d.udid)?.size || 0; }
254
+ catch (e) { say(`couldn't delete ${d.name}: ${e.message}`); process.exitCode = 1; }
255
+ }
256
+ console.log(done.length ? `deleted ${done.join(', ')}, about ${size(freed)} freed` : 'no idle pool devices to delete');
257
+ if (gone.busy.length) console.log(`kept ${gone.busy.join(', ')}: in use`);
258
+ }