@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
package/src/config.mjs ADDED
@@ -0,0 +1,324 @@
1
+ // Where dibs keeps its files, what each resource costs, and how loaded the machine is.
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { pressure, memPressure, dibsMem } from './platform.mjs';
6
+ import { isFiles, FILES_COST } from './files.mjs';
7
+ import { die, ms, now, bytes } from './util.mjs';
8
+
9
+ export const HOME = process.env.DIBS_HOME || path.join(os.homedir(), '.dibs');
10
+ export const paths = {
11
+ state: path.join(HOME, 'state.json'),
12
+ lock: path.join(HOME, 'lock'),
13
+ history: path.join(HOME, 'history.jsonl'),
14
+ config: path.join(HOME, 'config.json'),
15
+ seen: path.join(HOME, 'seen.json'),
16
+ ctl: path.join(HOME, 'ctl'), // the broker's control FIFO (src/broker.mjs)
17
+ };
18
+
19
+ // A pool resource's settings when its config leaves them out. perSim: memory
20
+ // one booted simulator costs. erase: when a device is wiped before the next
21
+ // lease: other-agent (the last user was someone else), always, never.
22
+ export const POOL_DEFAULTS = { deviceType: null, runtime: null, perSim: '2G', erase: 'other-agent' };
23
+
24
+ export const DEFAULT_CONFIG = {
25
+ budget: '8G', // memory dibs hands out at once across running jobs
26
+ cores: 6, // CPU cores running jobs may use at once: what each was last measured using, or asked for until then. Lower means a quieter fan and slower queues
27
+ minFreeMem: 15, // jobs of 2G+ wait while the OS reports less than this % of memory free
28
+ minDisk: '5G', // nothing starts below this much free disk
29
+ starveAfter: '3m', // after this long at the head of the line, nobody jumps it
30
+ quickUnder: '15s', // a command that runs under this goes in the quick lane: it starts at once (src/schedule.mjs quickPass)
31
+ roomyMemFree: 35, // with at least this % of memory free...
32
+ roomyLoad: 0.6, // ...and load under this share of the cores, the memory and CPU budgets don't apply
33
+ coolLoad: 8, // `dibs throttle` acts when the 1-minute load average is above this
34
+ maxLoad: null, // normal, low and idle work waits while the 1-minute load is above this. null: no ceiling
35
+ // Past this much swap, work below urgent waits while swap is still growing (src/config.mjs swapGrowth)
36
+ // and anything else is running. A Mac keeps a gigabyte or two of swap in normal use and leaves it
37
+ // allocated long after a crunch, so the total alone says nothing; past 4G and growing, it's paging hard
38
+ // enough that the person feels it, and on macOS swap grows on the startup disk. null: no limit.
39
+ maxSwap: '4G',
40
+ // While the machine swaps (past maxSwap, or growing), work below urgent also keeps this much free disk
41
+ // on top of minDisk, for swap to grow into. macOS adds swap files on the startup disk as it pages and
42
+ // keeps them; on 2026-10-15 swap took free disk from 15 GB to 0.4 GB in ten minutes. null: off.
43
+ swapRoom: '3G',
44
+ pace: null, // quiet, normal or max: sets cores, budget, maxLoad, coolLoad and the roomy rule for this machine (dibs pace)
45
+ overlap: null, // off, fit or squeeze: whether a job may start on top of a full resource when the machine has room (src/overlap.mjs). null: the pace decides
46
+ squeezeUnder: '60s', // with overlap squeeze, jobs that usually take less than this may squeeze in whatever the load
47
+ maintainer: null, // agent name `dibs ask` points people to for a faster answer
48
+ hours: null, // the person's working hours, {"start": "09:00", "end": "23:00"}: outside them, questions below urgent wait. null: any time
49
+ agents: false, // no limit; { slots: 8 } caps subagents running at once across every Claude Code session here (dibs guard install)
50
+ // thin: dibs run and dibs hold wait as a 1.5 MB shell, and one broker process decides for every
51
+ // waiter (src/thin.sh, src/broker.mjs). fat: each waits in a Node process of its own, as before
52
+ // 0.0.95 ("node" means the same). DIBS_THIN=0 in a caller's environment makes its waits fat.
53
+ // Read by bin/dibs.mjs's first lines, with grep.
54
+ waits: 'thin',
55
+ quotas: {}, // rate-limit buckets for dibs run quota:<name>, e.g. "asc": { "per": "1h", "limit": 300 }
56
+ enforce: false, // Linux: run each job in a systemd scope that throttles it past its memory and cores (never kills). Skipped where systemd-run --user doesn't work
57
+ resources: {
58
+ // pausable: low and idle runs on it may be paused for urgent work or memory
59
+ // pressure. Not a deploy (half-done, with remote timeouts running) or the
60
+ // simulator (the app in it isn't in the job's process tree).
61
+ // exclusive: never two at once, however much room the machine has (overlap).
62
+ // The one booted simulator has one screen; two deploys of one project race each other.
63
+ // rerun: a job here can be stopped and run again from the start without harm,
64
+ // so a run paused for low disk whose memory is going to swap can be stopped
65
+ // and put back at the front of its line (src/preempt.mjs diskRequeue). Not a
66
+ // deploy or anything else that changes the world half way.
67
+ sim: { slots: 1, mem: '3G', cpu: 1, disk: '8G', os: 'macos', pausable: false, exclusive: true },
68
+ // Each lease gets its own simulator from a pool (src/simpool.mjs). mem counts the
69
+ // simulator and the job driving it; free memory decides how many boot at once.
70
+ 'sim-own': { slots: Math.max(1, Math.min(4, Math.floor(hardware().mem / 4 / 1024 ** 3))), mem: '3G', cpu: 2, disk: '6G', os: 'macos',
71
+ pool: { ...POOL_DEFAULTS }, pausable: false },
72
+ // An incremental build grows DerivedData by 1-2.5G and an archive by about
73
+ // 0.5G. 10G here once held every build back on a Mac with 9-11G free.
74
+ 'xcode-build': { slots: 2, mem: '4G', cpu: 4, disk: '4G', os: 'macos', pausable: false, rerun: true },
75
+ playwright: { slots: 2, mem: '3G', cpu: 2, disk: '3G', pausable: true, rerun: true },
76
+ test: { slots: 3, mem: '2G', cpu: 3, pausable: true, rerun: true },
77
+ // One deploy at a time per project, up to across at once (exclusiveBy: src/schedule.mjs roomFor):
78
+ // two projects' deploys don't touch each other, and a 6-second web deploy waited behind another
79
+ // project's TestFlight upload (2026-11-03). slots is per project, so a config's slots: 1 reads so too. A quick deploy of
80
+ // another project may go past across (quickAlongside).
81
+ deploy: { slots: 1, mem: '0.5G', cpu: 1, pausable: false, exclusive: true, exclusiveBy: 'repo', across: 3, quickAlongside: 'other-repo' },
82
+ heavy: { slots: 1, mem: '4G', cpu: 4, disk: '10G', pausable: true, rerun: true },
83
+ },
84
+ // A name dibs doesn't know is often someone's lock ("one migration at a time"), so it never overlaps.
85
+ unknown: { slots: 1, mem: '1G', cpu: 1, pausable: false, exclusive: true },
86
+ };
87
+
88
+ // The user's file only needs the keys they change. Resources merge one level deep,
89
+ // so overriding sim's slots keeps sim's memory cost.
90
+ export function loadConfig() {
91
+ fs.mkdirSync(HOME, { recursive: true });
92
+ if (!fs.existsSync(paths.config)) writeDefault();
93
+ let c;
94
+ try { c = JSON.parse(fs.readFileSync(paths.config, 'utf8')); } catch { die(`${paths.config} isn't valid JSON`); }
95
+ const merged = { ...DEFAULT_CONFIG, ...c, resources: { ...DEFAULT_CONFIG.resources } };
96
+ for (const [k, v] of Object.entries(c.resources || {})) merged.resources[k] = { ...(DEFAULT_CONFIG.resources[k] || {}), ...v };
97
+ if (c.pace != null && !PACES[c.pace]) die(`pace in ${paths.config} is one of ${Object.keys(PACES).join(', ')}, or null`);
98
+ if (merged.maxLoad != null && !(merged.maxLoad > 0)) die(`maxLoad in ${paths.config} is a load average above 0, or null for no ceiling`);
99
+ if (c.overlap != null && !OVERLAP_MODES.includes(c.overlap)) die(`overlap in ${paths.config} is one of ${OVERLAP_MODES.join(', ')}, or null to let the pace decide`);
100
+ ms(merged.squeezeUnder);
101
+ // Read here so a bad value names its key, instead of every dibs run failing on "can't read size".
102
+ if (!isSize(merged.budget)) die(`budget in ${paths.config} is a size like 8G (the memory dibs hands out at once), not ${JSON.stringify(merged.budget)}`);
103
+ // null means no floor, as it does for maxSwap and swapRoom. The watcher still pauses jobs under its own 3G line.
104
+ if (merged.minDisk == null) merged.minDisk = '0';
105
+ if (!isSize(merged.minDisk)) die(`minDisk in ${paths.config} is a size like 5G, or null for no floor, not ${JSON.stringify(merged.minDisk)}`);
106
+ if (!['thin', 'fat', 'node'].includes(merged.waits)) die(`waits in ${paths.config} is "thin" or "fat", not ${JSON.stringify(merged.waits)}`);
107
+ if (merged.maxSwap != null) bytes(merged.maxSwap);
108
+ if (merged.swapRoom != null) bytes(merged.swapRoom);
109
+ for (const [k, v] of Object.entries(merged.resources)) {
110
+ if (v.onRelease != null && typeof v.onRelease !== 'string') die(`resources.${k}.onRelease in ${paths.config} is a shell command, as a string`);
111
+ if (v.onReleaseTimeout != null) ms(v.onReleaseTimeout);
112
+ if (v.exclusiveBy != null && v.exclusiveBy !== 'repo') die(`resources.${k}.exclusiveBy in ${paths.config} is "repo" (one at a time per project), or null`);
113
+ if (v.across != null && !(Number.isInteger(v.across) && v.across > 0)) die(`resources.${k}.across in ${paths.config} is how many projects may use it at once, a whole number above 0`);
114
+ if (v.quickAlongside != null && v.quickAlongside !== 'other-repo') die(`resources.${k}.quickAlongside in ${paths.config} is "other-repo" (a quick job of another repo starts beside this one's jobs), or null`);
115
+ }
116
+ if (merged.quickUnder != null && !(ms(merged.quickUnder) >= 0)) die(`quickUnder in ${paths.config} is a duration like 15s, or null for no quick lane`);
117
+ merged.profiles = checkProfiles(c.profiles, merged.resources);
118
+ if (c.pace) Object.assign(merged, paced(c).knobs);
119
+ // The person's own word wins; else the pace's; else one job per slot.
120
+ merged.overlap = c.overlap ?? PACE_OVERLAP[c.pace] ?? 'off';
121
+ return merged;
122
+ }
123
+
124
+ // Named profiles: a resource with the ports, memory and cores a project's
125
+ // suite always needs, defined once instead of in a wrapper script:
126
+ // "profiles": { "playwright:atlas": { "res": "playwright", "ports": ["WEB", "API"], "mem": "3G", "cpu": 2 } }
127
+ // then dibs run playwright:atlas -- npm run e2e. Checked here, so a typo
128
+ // fails every call with the key named instead of queueing for a resource
129
+ // nobody else uses.
130
+ const PROFILE_KEYS = new Set(['res', 'ports', 'mem', 'cpu', 'disk', 'est']);
131
+ // The shapes util's bytes() and ms() read, tested first so a bad value can name its key.
132
+ const isSize = v => (typeof v === 'number' && v >= 0) || /^([\d.]+)\s*([KMGT]?)B?$/i.test(String(v ?? '').trim());
133
+ const isDur = v => (typeof v === 'number' && v >= 0) || /^([\d.]+)\s*(ms|s|m|h)?$/.test(String(v ?? '').trim());
134
+ function checkProfiles(profiles, resources) {
135
+ if (profiles == null) return {};
136
+ const where = `in ${paths.config}`;
137
+ if (typeof profiles !== 'object' || Array.isArray(profiles)) die(`profiles ${where} is an object of names, like { "playwright:web": { "res": "playwright", "ports": ["WEB"] } }`);
138
+ const out = {};
139
+ for (const [name, p] of Object.entries(profiles)) {
140
+ const key = `profiles["${name}"] ${where}`;
141
+ if (!/^[\w.-]+(:[\w.-]+)?$/.test(name) || /^(files|quota):/.test(name)) die(`${key}: a profile name is letters, digits, dots and dashes, with at most one colon, like playwright:web. It can't start with files: or quota:`);
142
+ if (resources[name]) die(`${key}: ${name} is already a resource. Give the profile its own name, like ${name}:web`);
143
+ if (!p || typeof p !== 'object') die(`${key} is an object, like { "res": "playwright", "ports": ["WEB"] }`);
144
+ const extra = Object.keys(p).filter(k => !PROFILE_KEYS.has(k));
145
+ if (extra.length) die(`${key}: unknown ${extra.join(', ')}. A profile sets ${[...PROFILE_KEYS].join(', ')}`);
146
+ const res = typeof p.res === 'string' ? p.res.split(',').filter(Boolean) : p.res;
147
+ if (!Array.isArray(res) || !res.length || !res.every(r => typeof r === 'string' && r && !profiles[r])) die(`${key}: res names the resources it takes, like "playwright" or ["playwright", "test"] (not another profile)`);
148
+ const ports = p.ports ?? [];
149
+ if (!Array.isArray(ports) || !ports.every(x => typeof x === 'string' && /^[A-Za-z_]\w*$/.test(x))) die(`${key}: ports is a list of variable names, like ["WEB", "API"]`);
150
+ const sized = k => { if (p[k] == null) return undefined; if (!isSize(p[k])) die(`${key}: ${k} is a size like 3G, not ${JSON.stringify(p[k])}`); return bytes(p[k]); };
151
+ if (p.cpu != null && !(typeof p.cpu === 'number' && p.cpu >= 0)) die(`${key}: cpu is a number of cores, like 2`);
152
+ if (p.est != null && !isDur(p.est)) die(`${key}: est is a time like 5m, not ${JSON.stringify(p.est)}`);
153
+ out[name] = { res, ports, mem: sized('mem'), cpu: p.cpu, disk: sized('disk'), est: p.est != null ? ms(p.est) : undefined };
154
+ }
155
+ return out;
156
+ }
157
+
158
+ // A request naming a profile gets its resources, its ports, and its sizes
159
+ // wherever the command line didn't give one.
160
+ export function profiled(o, cfg) {
161
+ const ps = cfg.profiles || {};
162
+ if (!o.res.some(r => ps[r])) return o;
163
+ const out = { ...o, res: [], ports: [...(o.ports || [])] };
164
+ for (const r of o.res) {
165
+ const p = ps[r];
166
+ if (!p) { out.res.push(r); continue; }
167
+ out.res.push(...p.res);
168
+ for (const x of p.ports) if (!out.ports.includes(x)) out.ports.push(x);
169
+ for (const k of ['mem', 'cpu', 'disk', 'est']) if (o[k] == null && p[k] != null) out[k] = Math.max(out[k] ?? 0, p[k]);
170
+ }
171
+ out.res = [...new Set(out.res)];
172
+ return out;
173
+ }
174
+
175
+ // One word for how hard dibs drives the machine, so nobody tunes six numbers.
176
+ // Each preset is a share of this machine's cores and memory:
177
+ // cores CPU cores running jobs may use at once, as measured
178
+ // budget memory handed out at once
179
+ // maxLoad load ceiling for normal, low and idle work
180
+ // coolLoad load where dibs throttle moves outside work to background priority
181
+ // roomyLoad the budgets are skipped below this share of the cores (0: never),
182
+ // with roomyMemFree % of memory free
183
+ // quiet keeps the load at half the cores, where the fan stays slow and the
184
+ // person at the Mac doesn't feel a thing, and never skips the budgets. normal
185
+ // is the stock numbers (on a 10-core 16 GB Mac) plus a ceiling at one runnable
186
+ // job per core, past which the person starts to feel it. max hands out three
187
+ // quarters of memory and stops at 1.5 jobs per core: past that, jobs only
188
+ // slow each other down. Its CPU budget is that same 1.5 per core, since the
189
+ // budget counts the cores jobs are measured using, and it never skips the
190
+ // memory budget: in docs/benchmarks.md, skipping it when the machine looked
191
+ // roomy made max no faster and was the only setting that swapped.
192
+ export const PACES = {
193
+ quiet: { cores: 0.4, budget: 0.4, maxLoad: 0.5, coolLoad: 0.5, roomyLoad: 0, roomyMemFree: 35 },
194
+ normal: { cores: 0.6, budget: 0.5, maxLoad: 1, coolLoad: 0.8, roomyLoad: 0.6, roomyMemFree: 35 },
195
+ max: { cores: 1.5, budget: 0.75, maxLoad: 1.5, coolLoad: 1.2, roomyLoad: 0, roomyMemFree: 25 },
196
+ };
197
+
198
+ // Whether jobs may run on top of a full resource (src/overlap.mjs), by pace.
199
+ // quiet promises the person never feels dibs, so it keeps one job per slot.
200
+ // normal lets one on top when it fits. max also takes the load hit of quick
201
+ // jobs squeezing in.
202
+ export const OVERLAP_MODES = ['off', 'fit', 'squeeze'];
203
+ export const PACE_OVERLAP = { quiet: 'off', normal: 'fit', max: 'squeeze' };
204
+
205
+ // Cores and total memory, from DIBS_FAKE_MACHINE when it says.
206
+ export function hardware() {
207
+ const f = process.env.DIBS_FAKE_MACHINE && JSON.parse(process.env.DIBS_FAKE_MACHINE);
208
+ return { cores: f?.cores ?? (f ? 8 : os.cpus().length), mem: f?.memTotal ?? os.totalmem() };
209
+ }
210
+
211
+ const half = x => Math.round(x * 2) / 2;
212
+ export function paceKnobs(pace, hw = hardware()) {
213
+ const p = PACES[pace];
214
+ return {
215
+ cores: Math.max(1, Math.round(hw.cores * p.cores)), budget: `${half(hw.mem * p.budget / 1024 ** 3)}G`,
216
+ maxLoad: half(hw.cores * p.maxLoad), coolLoad: half(hw.cores * p.coolLoad), roomyLoad: p.roomyLoad, roomyMemFree: p.roomyMemFree,
217
+ };
218
+ }
219
+
220
+ // What a pace sets, and which of its knobs the user's file pins instead. Every
221
+ // config.json dibs wrote holds the stock values, so a knob still at its stock
222
+ // value counts as unset: only one someone changed wins over the pace.
223
+ export function paced(c, hw = hardware()) {
224
+ const knobs = paceKnobs(c.pace, hw);
225
+ const pinned = Object.keys(knobs).filter(k => c[k] != null && c[k] !== DEFAULT_CONFIG[k]);
226
+ for (const k of pinned) delete knobs[k];
227
+ return { knobs, pinned };
228
+ }
229
+
230
+ // dibs pace: set or clear the pace in the user's file, leaving the rest as written.
231
+ export function writePace(pace) {
232
+ loadConfig();
233
+ const c = JSON.parse(fs.readFileSync(paths.config, 'utf8'));
234
+ c.pace = pace;
235
+ const tmp = `${paths.config}.${process.pid}`;
236
+ fs.writeFileSync(tmp, JSON.stringify(c, null, 2) + '\n');
237
+ fs.renameSync(tmp, paths.config);
238
+ }
239
+
240
+ // Two first calls can race here. Written aside and linked into place, so a
241
+ // reader never sees half a file and a config that appeared meanwhile is kept.
242
+ function writeDefault() {
243
+ const tmp = `${paths.config}.${process.pid}`;
244
+ fs.writeFileSync(tmp, JSON.stringify(DEFAULT_CONFIG, null, 2) + '\n');
245
+ try { fs.linkSync(tmp, paths.config); } catch (e) { if (e.code !== 'EEXIST') throw e; }
246
+ finally { fs.rmSync(tmp, { force: true }); }
247
+ }
248
+
249
+ // A quota (src/quota.mjs) is limited by its bucket, not by slots, and costs no
250
+ // memory or cores. Its slots only need to never run out; finite, so the
251
+ // forecast can list them.
252
+ const QUOTA_RES = { slots: 1000, mem: 0, cpu: 0, disk: 0, pausable: false };
253
+ export const resCfg = (cfg, r) => (r.startsWith('quota:') ? QUOTA_RES : isFiles(r) ? { ...FILES_COST } : { ...cfg.unknown, ...(cfg.resources[r] || {}) });
254
+
255
+ // How much swap grew and free disk fell lately. macOS leaves swap allocated
256
+ // long after the memory crunch that filled it, so what counts is swap growing
257
+ // now; and swap files grow on the startup disk, so free disk falling fast is
258
+ // the same crunch seen from the disk's side. Readings go in a small file so
259
+ // every dibs process sees the same history: one every SWAP_SAMPLE_EVERY is
260
+ // plenty to see five minutes of change and keeps writes rare, though waiters
261
+ // read the machine every few seconds.
262
+ const SWAP_FILE = path.join(HOME, 'swap.json');
263
+ export const SWAP_WINDOW = 5 * 6e4;
264
+ const SWAP_SAMPLE_EVERY = 30e3;
265
+ // The last stretch of the window, which says whether swap is still growing
266
+ // and free disk still falling now (measured from the newest reading before it). The 5-minute totals keep an old low swap
267
+ // reading (or high disk one) for five minutes after things stop moving, so
268
+ // on their own they'd hold work back, and pause jobs, long after the crunch.
269
+ // Readings are 30s apart, so this sees two or three of them.
270
+ export const RECENT = 90e3;
271
+ // Over the last SWAP_WINDOW: bytes swap grew (from its lowest reading to now),
272
+ // bytes free disk fell (from its highest reading to now) and over how long
273
+ // (drainMs, for the rate). swapRecent and drainRecent: the same over the last
274
+ // RECENT. A missing or unreadable file means neither.
275
+ export function trends(used, disk, t = now()) {
276
+ const has = v => Number.isFinite(v);
277
+ if (!has(used) && !has(disk)) return { swapGrowth: 0, diskDrain: 0, drainMs: 0, swapRecent: 0, drainRecent: 0 };
278
+ let xs = [];
279
+ try { xs = JSON.parse(fs.readFileSync(SWAP_FILE, 'utf8')).filter(x => has(x?.at) && t - x.at <= SWAP_WINDOW && (has(x.used) || has(x.disk))); } catch {}
280
+ const grew = ys => { const u = ys.map(x => x.used).filter(has); return has(used) && u.length ? Math.max(0, used - Math.min(...u)) : 0; };
281
+ const fell = ys => { const d = ys.map(x => x.disk).filter(has); return has(disk) && d.length ? Math.max(0, Math.max(...d) - disk) : 0; };
282
+ const withDisk = xs.filter(x => has(x.disk));
283
+ const top = has(disk) && withDisk.length ? withDisk.reduce((a, x) => (x.disk >= a.disk ? x : a)) : null;
284
+ // The newest reading from before that stretch counts too, as its starting point: readings come
285
+ // only while some dibs runs, so a gap of minutes mustn't read as nothing moving.
286
+ const before = xs.filter(x => t - x.at > RECENT).sort((a, b) => b.at - a.at)[0];
287
+ const lately = [...xs.filter(x => t - x.at <= RECENT), ...(before ? [before] : [])];
288
+ const out = {
289
+ swapGrowth: grew(xs),
290
+ diskDrain: top ? Math.max(0, top.disk - disk) : 0,
291
+ drainMs: top ? t - top.at : 0,
292
+ swapRecent: grew(lately),
293
+ drainRecent: fell(lately),
294
+ };
295
+ if (!xs.length || t - Math.max(...xs.map(x => x.at)) >= SWAP_SAMPLE_EVERY) {
296
+ // Two processes may both write; the loser's reading is lost, which costs nothing.
297
+ const tmp = `${SWAP_FILE}.${process.pid}`;
298
+ const x = { at: t, ...(has(used) && { used }), ...(has(disk) && { disk }) };
299
+ try { fs.writeFileSync(tmp, JSON.stringify([...xs, x])); fs.renameSync(tmp, SWAP_FILE); } catch { try { fs.rmSync(tmp, { force: true }); } catch {} }
300
+ }
301
+ return out;
302
+ }
303
+ export const swapGrowth = (used, t = now()) => trends(used, null, t).swapGrowth;
304
+
305
+ // Free disk and how fast it falls, swap and how fast it grows, memory
306
+ // pressure, OS-reported free memory and load. Cached for 3s because waiters
307
+ // poll and each reading costs a process spawn. DIBS_FAKE_MACHINE may give
308
+ // swapGrowth, diskDrain, drainMs, swapRecent and drainRecent; otherwise they
309
+ // come from the readings file, with the fake swapUsed and diskFree.
310
+ let cache = null;
311
+ export function machine() {
312
+ if (process.env.DIBS_FAKE_MACHINE) {
313
+ const m = { at: now(), load: 0, cores: 8, dibsMem: 0, ...JSON.parse(process.env.DIBS_FAKE_MACHINE) };
314
+ // A fake that gives the 5-minute totals but not the recent ones is still moving.
315
+ if (m.swapGrowth != null && m.diskDrain != null) return { drainMs: SWAP_WINDOW, swapRecent: m.swapGrowth, drainRecent: m.diskDrain, ...m };
316
+ const t = trends(m.swapUsed, m.diskFree, m.at);
317
+ return { ...m, swapGrowth: m.swapGrowth ?? t.swapGrowth, diskDrain: m.diskDrain ?? t.diskDrain, drainMs: m.drainMs ?? t.drainMs,
318
+ swapRecent: m.swapRecent ?? (m.swapGrowth != null ? m.swapGrowth : t.swapRecent), drainRecent: m.drainRecent ?? (m.diskDrain != null ? m.diskDrain : t.drainRecent) };
319
+ }
320
+ if (cache && now() - cache.at < 3000) return cache;
321
+ // dibsMem, the full process table, only when swap is in question (schedule.mjs swapNotOurs).
322
+ const m = { at: now(), ...pressure(HOME), vmPressure: memPressure() };
323
+ return (cache = { ...m, ...trends(m.swapUsed, m.diskFree, m.at) });
324
+ }
@@ -0,0 +1,106 @@
1
+ // dibs connect: one front door for everything that connects to dibs on this Mac. With no
2
+ // arguments it explains the choices (and on a terminal, asks which); each choice runs the flow
3
+ // that already exists for it. dibs pair stays as it was, an alias for the code flows.
4
+ import readline from 'node:readline';
5
+ import { die } from './util.mjs';
6
+
7
+ const CHOICES = [
8
+ ['browser', 'this browser', 'a one-time code for the page at http://127.0.0.1:7421', 'dibs connect --browser'],
9
+ ['phone', 'a phone or another browser', 'a link and QR code, end-to-end encrypted through the relay', 'dibs connect --phone [--allow-actions]'],
10
+ ['account', 'your dibs account', 'every browser you sign in with at app.dibs.cc opens this Mac', 'dibs connect --account [--allow-actions]'],
11
+ ['mcp', 'another Claude account', 'its connector reads dibs (or acts) over MCP at mcp.dibs.cc', 'dibs connect --mcp [--allow-actions]'],
12
+ ['machine', 'another machine', 'it takes jobs from this one and sends its own', 'dibs connect --machine [--name <name>]'],
13
+ ];
14
+
15
+ function menu() {
16
+ console.log('Connect something to dibs on this Mac:\n');
17
+ CHOICES.forEach(([, what, why, cmd], i) => console.log(` ${i + 1} ${what.padEnd(27)} ${why}\n ${cmd}\n`));
18
+ console.log('dibs connect --list shows everything connected, dibs connect --remove <id> disconnects one,');
19
+ console.log('and dibs connect --approve <code> lets a new browser of your account in.');
20
+ }
21
+
22
+ const clockOf = t => new Date(t).toLocaleTimeString([], { hour: 'numeric', minute: '2-digit' });
23
+
24
+ const ask = q => new Promise(resolve => {
25
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
26
+ rl.question(q, a => { rl.close(); resolve(a.trim()); });
27
+ });
28
+
29
+ // The accounts this Mac is on and the browsers waiting on it, for the Mac app and the page.
30
+ // Never the codes: the person reads those off the browser, which is the point of them.
31
+ export async function accountsJson() {
32
+ const r = await import('./relay.mjs');
33
+ return {
34
+ accounts: Object.entries(r.load().accounts).map(([aid, a]) => ({ id: aid.slice(0, 8), label: a.label || null, joined: a.joined })),
35
+ waiting: r.waitingApprovals().map(a => ({ id: a.id, account: a.aid.slice(0, 8), label: a.label, expires: a.exp })),
36
+ };
37
+ }
38
+
39
+ export async function connect(args) {
40
+ const [first, ...rest] = args;
41
+ const web = () => import('./web.mjs');
42
+ const relay = () => import('./relay.mjs');
43
+ const flags = rest.filter(a => a.startsWith('--'));
44
+ if (!first) {
45
+ menu();
46
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return;
47
+ const a = await ask('\nWhich one? (1-5, or Enter to stop) ');
48
+ const pick = CHOICES[Number(a) - 1];
49
+ if (!pick) return;
50
+ console.log('');
51
+ return connect([`--${pick[0]}`]);
52
+ }
53
+ if (first === '--browser') return (await web()).pair([]);
54
+ if (first === '--phone') return (await web()).pair(['--remote', ...flags]);
55
+ if (first === '--account') {
56
+ if (rest.some(a => a !== '--allow-actions')) die('dibs connect --account [--allow-actions]');
57
+ return (await relay()).pairAccount({ act: rest.includes('--allow-actions') });
58
+ }
59
+ if (first === '--mcp') {
60
+ const r = await relay();
61
+ if (!r.load().mcp) await r.relay(['mcp', 'on']);
62
+ console.log('');
63
+ return (await web()).pair(flags);
64
+ }
65
+ if (first === '--machine') return (await web()).pair(['--machine', ...rest]);
66
+ if (first === '--list') return (await web()).pair(['--list']);
67
+ if (first === '--remove') {
68
+ const which = rest[0] || die('remove which? dibs connect --list shows them, or --remove all');
69
+ const n = (await relay()).removeAccount(which);
70
+ if (n) console.log(`Took this Mac off ${n === 1 ? 'that dibs account' : `${n} dibs accounts`}: its browsers no longer reach it, and it can't approve new ones.`);
71
+ return (await web()).pair(['--revoke', which]);
72
+ }
73
+ if (first === '--accounts') {
74
+ const { accounts, waiting } = await accountsJson();
75
+ if (rest.includes('--json')) return console.log(JSON.stringify({ accounts, waiting }));
76
+ if (!accounts.length) return console.log('This Mac isn\'t on a dibs account. dibs connect --account adds it.');
77
+ for (const a of accounts) console.log(`${a.id} dibs account, joined ${new Date(a.joined).toLocaleString()}`);
78
+ for (const a of waiting) console.log(`${a.id} ${a.label} is waiting, until ${clockOf(a.expires)}`);
79
+ return;
80
+ }
81
+ if (first === '--refuse') {
82
+ const hit = (await relay()).refuseApproval(rest[0] || die('refuse which? dibs connect --accounts lists the waiting browsers'));
83
+ if (!hit) die('No browser with that id is waiting. dibs connect --accounts lists them.', 1);
84
+ return console.log(`Refused ${hit.label}. It hears so within a few seconds.`);
85
+ }
86
+ if (first === '--approve') {
87
+ const r = await relay();
88
+ const json = rest.includes('--json');
89
+ const code = (rest.find(a => a !== '--json') || '').replace(/\D/g, '');
90
+ if (!code) {
91
+ const w = r.waitingApprovals();
92
+ if (!w.length) return console.log('No browser is waiting for approval. A browser signed in to your dibs account by email shows a 6-digit code when it asks.');
93
+ for (const a of w) console.log(`${a.label} is waiting, until ${clockOf(a.exp)}.`);
94
+ return console.log('\nType the 6-digit code that browser shows: dibs connect --approve <code>. A code that doesn\'t match lets nothing in.');
95
+ }
96
+ if (code.length !== 6) die('the code is the 6 digits the browser shows: dibs connect --approve 123456');
97
+ const hit = r.approve(code);
98
+ if (!hit) die('No waiting browser shows that code. Check the digits on the browser, or ask again from it: codes last 10 minutes.', 1);
99
+ if (hit.stale) die(`That's ${hit.label}'s code, but this Mac's relay connection restarted since it asked, and the key it would send went with it. Ask again from that browser.`, 1);
100
+ if (hit.ambiguous) die(`${hit.ambiguous} waiting browsers show that code, which almost never happens by chance: something between your browser and this Mac may be guessing. Refused them all. Ask again from your browser.`, 1);
101
+ if (json) return console.log(JSON.stringify({ approved: { id: hit.id, label: hit.label, confirm: hit.confirm } }));
102
+ console.log(`Approved ${hit.label}. Now type this code into that browser:\n\n ${hit.confirm.replace(/(\d{3})(\d{3})/, '$1 $2')}\n`);
103
+ return console.log('It opens your account\'s key only with this code, so a key that didn\'t come from this Mac is never used.');
104
+ }
105
+ die(`unknown ${first}. dibs connect, or: ${CHOICES.map(c => `--${c[0]}`).join(', ')}, --list, --remove <id>, --accounts, --approve <code>, --refuse <id>`);
106
+ }
package/src/cool.mjs ADDED
@@ -0,0 +1,160 @@
1
+ // dibs throttle. dibs budgets the work that goes through it; this catches the
2
+ // work that doesn't. When the machine is busy, build and test processes that
3
+ // keep a core hot outside any lease are moved to background priority (the
4
+ // efficiency cores on Apple silicon, nice 10 on Linux, below normal on
5
+ // Windows). Nothing is killed. The watcher also pauses idle and low leases
6
+ // while the machine is short on memory, and leases below high while swap fills
7
+ // the disk (src/preempt.mjs), and replaces a broker that has stopped beating
8
+ // (src/broker.mjs).
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+ import { HOME, machine, loadConfig } from './config.mjs';
12
+ import { withState, history, peek } from './state.mjs';
13
+ import { singleInstance } from './proc.mjs';
14
+ import { processes, lower, memPressure, isDibs } from './platform.mjs';
15
+ import { hogsOnce, hogHint } from './hogs.mjs';
16
+ import { pressureStep, pressurePause, pressureResume, diskStep, diskPause, diskPausesPerPass, diskLine, diskCritical, adoptPauses, diskRequeue, measured } from './preempt.mjs';
17
+ import { swapGrowing } from './schedule.mjs';
18
+ import { event } from './events.mjs';
19
+ import { notify } from './talk.mjs';
20
+ import { watchBroker } from './broker.mjs';
21
+ import { progressScan } from './notices.mjs';
22
+ import { scan as scanAlerts } from './alerts.mjs';
23
+ import { say, sleep, now, noSpace, gb } from './util.mjs';
24
+
25
+ const PIDFILE = path.join(HOME, 'cool.pid');
26
+ const LOG = path.join(HOME, 'cool.log');
27
+ // Only tools that build, test or crunch. Apps, editors and the agents themselves are left alone.
28
+ const TOOLS = /^(node|bun|deno|python3?(\.\d+)?|ruby|java|swift-frontend|swiftc|clang(\+\+)?|ld|ld64|xcodebuild|cargo|rustc|go|gcc|g\+\+|cc1(plus)?|make|ninja|tsc|esbuild|vite|vitest|jest|headless_shell|msbuild|dotnet)$/i;
29
+ const HOT = 50; // % of a core
30
+ const INTERVAL = 10e3;
31
+ // dibs history shows load by the hour; a reading a minute is plenty for that and costs one line.
32
+ const SAMPLE_EVERY = 60e3;
33
+
34
+ const toolName = args => path.basename(args.split(/\s+/)[0]).replace(/\.exe$/i, '');
35
+
36
+ // One pass. A process must be hot on two passes in a row, so short bursts are
37
+ // left alone. Returns the processes it moved.
38
+ function throttleOnce(cfg, seen = new Map()) {
39
+ const load = machine().load;
40
+ const leased = new Set(withState(s => s.leases.flatMap(l => [l.pgid, ...(l.groups || [])]).filter(Boolean)));
41
+ const moved = [];
42
+ const next = new Map();
43
+ for (const p of processes()) {
44
+ // dibs itself never: a broker moved to the slow cores slows every waiter's turn.
45
+ if (p.cpu < HOT || p.pid === process.pid || leased.has(p.pgid) || !TOOLS.test(toolName(p.args)) || isDibs(p)) continue;
46
+ const prev = seen.get(p.pid);
47
+ if (prev === 'done') { next.set(p.pid, 'done'); continue; }
48
+ if (prev && load > cfg.coolLoad && lower(p.pid)) {
49
+ moved.push({ ...p, name: toolName(p.args) });
50
+ next.set(p.pid, 'done');
51
+ fs.appendFileSync(LOG, `${new Date().toISOString()} load ${load.toFixed(1)}: background ${toolName(p.args)} ${p.pid} (${p.cpu}% cpu)\n`);
52
+ } else next.set(p.pid, prev || 'hot');
53
+ }
54
+ seen.clear();
55
+ for (const [k, v] of next) seen.set(k, v);
56
+ return moved;
57
+ }
58
+
59
+ // One memory pressure reading. Under sustained critical pressure, pause the
60
+ // next idle or low lease; once it's been normal for a while, resume one.
61
+ // Returns { act, leases } when it did something.
62
+ export function pressureOnce(cfg, track, read = memPressure) {
63
+ const act = pressureStep(track, read());
64
+ if (!act) return null;
65
+ const ls = withState(s => (act === 'pause' ? [pressurePause(s, cfg, now(), history())].filter(Boolean) : pressureResume(s)));
66
+ for (const l of ls)
67
+ fs.appendFileSync(LOG, `${new Date().toISOString()} memory pressure ${act === 'pause' ? 'critical: paused' : 'eased: resumed'} ${l.who} ${l.res.join(',')} (${l.prio || 'normal'}${l.alongside ? ', on top' : ''}): ${l.cmd.slice(0, 60)}\n`);
68
+ return ls.length ? { act, leases: ls } : null;
69
+ }
70
+
71
+ // One disk reading. While free disk is under minDisk and still falling, pause
72
+ // one more lease each pass (two when it's falling fast); once there's room
73
+ // again, resume one a minute.
74
+ // Returns { act, leases } when it did something.
75
+ export function diskOnce(cfg, track, m = machine()) {
76
+ const act = diskStep(track, m, cfg);
77
+ if (!act) return null;
78
+ // Swap still growing with jobs already paused: their memory is what's going to swap.
79
+ // Stopping one of them (it requeues itself) comes before pausing anything more.
80
+ if (act === 'pause' && swapGrowing(m)) {
81
+ const l = withState(s => diskRequeue(s, cfg, now(), history()));
82
+ if (l) {
83
+ const why = `free disk is low (${(m.diskFree / 1024 ** 3).toFixed(1)}G, under ${(diskLine(cfg) / 1024 ** 3).toFixed(1)}G) and swap is still growing`;
84
+ const over = l.requeue.why === 'over', used = measured(l);
85
+ fs.appendFileSync(LOG, `${new Date().toISOString()} ${why}: stopped ${l.who} ${l.res.join(',')} (${l.prio || 'normal'}), `
86
+ + `${over ? `using ${gb(used)} of the ${gb(l.mem)} it booked` : 'paused for the disk'}, to run again at the front of its line: ${l.cmd.slice(0, 60)}\n`);
87
+ event({ kind: 'requeue', id: l.id, res: l.res, who: l.who, agent: l.agent, prio: l.prio || 'normal', why: l.requeue.why, mem: used || l.mem, booked: l.mem, diskFree: m.diskFree });
88
+ const job = `your job #${l.id} (${l.purpose ? `"${l.purpose}", ` : ''}${l.cmd.slice(0, 60)})`;
89
+ notify(l, `requeue:#${l.id}`, (over
90
+ ? `${job} was using ${gb(used)} of memory, far more than the ${gb(l.mem)} it booked, while swap filled the disk, so dibs stopped it.`
91
+ + ` Its dibs run put it back at the front of its line booked at what it really used, and runs it again from the start once that much memory is really free.`
92
+ : `${job} was paused for low disk, and while it sat paused its memory was going to swap and filling the disk it was waiting for, so dibs stopped it.`
93
+ + ` Its dibs run put it back at the front of its line and runs it again from the start when there's room.`)
94
+ + ` Don't run it again yourself, and don't end it: the same tool call carries on.`);
95
+ return { act: 'requeue', leases: [l] };
96
+ }
97
+ }
98
+ const n = act === 'pause' ? diskPausesPerPass(m) : 0;
99
+ const hist = n ? history() : [];
100
+ const ls = withState(s => (n ? Array.from({ length: n }, () => diskPause(s, cfg, now(), m, hist)).filter(Boolean) : pressureResume(s, false, true)));
101
+ for (const l of ls) {
102
+ fs.appendFileSync(LOG, `${new Date().toISOString()} disk ${act === 'pause' ? `low (${(m.diskFree / 1024 ** 3).toFixed(1)}G free, under ${(diskLine(cfg) / 1024 ** 3).toFixed(1)}G and filling): paused` : 'has room again, or has held still: resumed'} ${l.who} ${l.res.join(',')} (${l.prio || 'normal'}): ${l.cmd.slice(0, 60)}\n`);
103
+ // Its agent hears it now, through the hook, not only when the tool call returns: it may need to save work or free space.
104
+ if (act === 'pause') notify(l, `diskpause:#${l.id}:${l.pausedAt}`, `your job #${l.id} (${l.purpose ? `"${l.purpose}", ` : ''}${l.cmd.slice(0, 60)}) is paused: free disk is low `
105
+ + `(${(m.diskFree / 1024 ** 3).toFixed(1)} GB) and still falling${hogHint()}. It keeps its lease and its place and resumes once there's room. `
106
+ + "Free what you can of your own: build output, scratch folders and merged worktrees your session made. Don't end the job or run it again.");
107
+ }
108
+ return ls.length ? { act, leases: ls } : null;
109
+ }
110
+
111
+ export async function throttle(o, cfg) {
112
+ if (!o.watch) {
113
+ const seen = new Map();
114
+ throttleOnce(cfg, seen);
115
+ await sleep(6000); // past the process-table cache, so the second pass sees fresh numbers
116
+ const moved = throttleOnce(cfg, seen);
117
+ console.log(moved.length ? moved.map(p => `moved ${p.name} ${p.pid} (${p.cpu}%) to background priority`).join('\n')
118
+ : `nothing to throttle (load ${machine().load.toFixed(1)}, acts above ${cfg.coolLoad})`);
119
+ return;
120
+ }
121
+ await singleInstance(PIDFILE, 'already watching');
122
+ say(`throttling: when load is over ${cfg.coolLoad}, build and test processes outside dibs go to background priority.`
123
+ + ` Under heavy memory pressure, idle and low dibs jobs pause until it eases; when swap fills the disk, jobs below high pause until there's room. Log: ${LOG}`);
124
+ const seen = new Map(), track = { high: 0, low: 0, diskOk: 0, diskStill: 0 };
125
+ let sampled = 0, nudged = 0;
126
+ // Disk pauses stay while the disk is still critical: the next watcher adopts them (src/preempt.mjs settle).
127
+ const stop = () => {
128
+ try { withState(s => pressureResume(s, diskCritical(machine(), cfg) ? 'memory' : true)); } catch {}
129
+ try { fs.rmSync(PIDFILE); } catch {}
130
+ process.exit(0);
131
+ };
132
+ // A stuck broker can be stopped while holding the state lock, and the lock is only taken from
133
+ // a live holder after 30 s. So replace it before this watcher's first locked step: watchBroker
134
+ // takes no lock, and once the stuck one is killed its lock is taken over in 3 s, not 30.
135
+ const early = watchBroker();
136
+ if (early) fs.appendFileSync(LOG, `${new Date().toISOString()} ${early}\n`);
137
+ try { const n = withState(s => adoptPauses(s)); if (n) fs.appendFileSync(LOG, `${new Date().toISOString()} took over ${n} disk pause${n > 1 ? 's' : ''} from the last watcher\n`); } catch (e) { if (!noSpace(e)) throw e; }
138
+ process.on('SIGINT', stop); process.on('SIGTERM', stop);
139
+ for (;;) {
140
+ cfg = loadConfig(); // so dibs pace reaches a running watcher
141
+ // A full disk skips this pass instead of stopping the watcher.
142
+ // Thin waiters (src/broker.mjs) can't tell a stuck broker from a busy one; this can.
143
+ // First, without the lock: a broker stuck while holding it would hold up this pass too.
144
+ const fixed = watchBroker();
145
+ if (fixed) fs.appendFileSync(LOG, `${new Date().toISOString()} ${fixed}\n`);
146
+ try { throttleOnce(cfg, seen); pressureOnce(cfg, track); diskOnce(cfg, track); } catch (e) { if (!noSpace(e)) throw e; }
147
+ // Not awaited: measuring a full temp folder can take a minute, and this loop keeps the machine's pace meanwhile.
148
+ hogsOnce(cfg, machine());
149
+ // Alerts open and close even while nobody looks at the board (src/alerts.mjs); the scan itself keeps its pace.
150
+ scanAlerts({ s: peek(), cfg, hist: history() });
151
+ // Open progress tasks gone quiet or past their ETA: their agents hear about it (src/notices.mjs).
152
+ if (now() - nudged >= SAMPLE_EVERY) { nudged = now(); progressScan(); }
153
+ if (now() - sampled >= SAMPLE_EVERY) {
154
+ sampled = now();
155
+ const m = machine();
156
+ event({ kind: 'sample', load: m.load, memFree: m.memFree ?? null, diskFree: m.diskFree ?? null });
157
+ }
158
+ await sleep(INTERVAL);
159
+ }
160
+ }