@dibssoftware/dibs 0.0.0-stage → 0.0.178
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 +577 -0
- package/LICENSE +670 -0
- package/README.md +234 -2
- package/bin/dibs-guard.mjs +7 -0
- package/bin/dibs.mjs +526 -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/relay.md +196 -0
- package/docs/releasing.md +25 -0
- package/docs/scheduling.md +163 -0
- package/docs/simulators.md +17 -0
- package/package.json +44 -4
- package/skills/dibs/SKILL.md +162 -0
- package/src/acquire.mjs +697 -0
- package/src/admin.mjs +145 -0
- package/src/agents.mjs +145 -0
- package/src/alerts.mjs +437 -0
- package/src/answers.mjs +65 -0
- package/src/board.mjs +202 -0
- package/src/broker.mjs +369 -0
- package/src/commands.mjs +801 -0
- package/src/config.mjs +320 -0
- package/src/connect.mjs +106 -0
- package/src/cool.mjs +160 -0
- package/src/diskwarn.mjs +161 -0
- package/src/events.mjs +94 -0
- package/src/files.mjs +1100 -0
- package/src/guard.mjs +583 -0
- package/src/history.mjs +247 -0
- package/src/hogs.mjs +214 -0
- package/src/later.mjs +487 -0
- package/src/measure.mjs +262 -0
- package/src/nodecheck.mjs +17 -0
- package/src/notices.mjs +121 -0
- package/src/ondemand.mjs +572 -0
- package/src/overlap.mjs +151 -0
- package/src/override.mjs +351 -0
- package/src/owner.mjs +30 -0
- package/src/plain.mjs +467 -0
- package/src/platform.mjs +357 -0
- package/src/preempt.mjs +438 -0
- package/src/primer.mjs +61 -0
- package/src/proc.mjs +98 -0
- package/src/progress.mjs +158 -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 +995 -0
- package/src/scratch.mjs +61 -0
- package/src/serve.mjs +736 -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 +523 -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 +1117 -0
- package/src/worker.mjs +318 -0
package/src/acquire.mjs
ADDED
|
@@ -0,0 +1,697 @@
|
|
|
1
|
+
// Getting in line and waiting for a turn. Shared by `dibs run` and `dibs hold`.
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { spawn } from 'node:child_process';
|
|
5
|
+
import { resCfg, machine, paths, HOME, loadConfig } from './config.mjs';
|
|
6
|
+
import { identity, pstart, tag } from './proc.mjs';
|
|
7
|
+
import { processes, parent, OS } from './platform.mjs';
|
|
8
|
+
import { withState, history, KEEP_PLACE } from './state.mjs';
|
|
9
|
+
import { preempt } from './preempt.mjs';
|
|
10
|
+
import { isFiles, short, shellRes, projectKey } from './files.mjs';
|
|
11
|
+
import { jobSize } from './simpool.mjs';
|
|
12
|
+
import { sized, grewLine, grewPlain, treeOf } from './measure.mjs';
|
|
13
|
+
import { isQuota, quotaProblem, quotaBlock, takeQuota } from './quota.mjs';
|
|
14
|
+
import { capWaiter } from './override.mjs';
|
|
15
|
+
import { verdict, forecast, expected, remaining, byRank, holdingOf, PRIORITY_SHIFT, PRIORITIES, NEEDS_REASON, used, overBy, STALL, neverFits, explicitAsk, capToMachine } from './schedule.mjs';
|
|
16
|
+
import { event } from './events.mjs';
|
|
17
|
+
import { startLine } from './overlap.mjs';
|
|
18
|
+
import { dur, clock, die, say, sleep, now, ms, gb, SIGNALS, signalExit, KEY_SPLIT, noSpace, OFF_LIMITS, callerPid } from './util.mjs';
|
|
19
|
+
import { plainBoard, startPhrase, askFirst, named, andList, lower, ordinal, moves, stuckFor, STUCK_AFTER } from './plain.mjs';
|
|
20
|
+
import { quoted, wrap, width } from './style.mjs';
|
|
21
|
+
import { noticeScan } from './notices.mjs';
|
|
22
|
+
import { notify } from './talk.mjs';
|
|
23
|
+
import { mayShip, loadShipTarget } from './remote.mjs';
|
|
24
|
+
|
|
25
|
+
const BIN = path.join(path.dirname(new URL(import.meta.url).pathname), '..', 'bin', 'dibs.mjs');
|
|
26
|
+
|
|
27
|
+
// How long dibs run waits in line outside Claude Code, where nothing moves a
|
|
28
|
+
// long call to the background and the tool may kill it.
|
|
29
|
+
const DEFAULT_MAX_WAIT = 8 * 6e4;
|
|
30
|
+
|
|
31
|
+
export const POLL = 1500;
|
|
32
|
+
// A wait past its first minute checks less often, unless the state file
|
|
33
|
+
// changes (a job ends, someone joins or leaves the line): then it checks at
|
|
34
|
+
// the next POLL as before. What only the machine's readings change (swap,
|
|
35
|
+
// disk) is seen within QUIET_POLL. Dozens of waiters polling every 1.5 s for
|
|
36
|
+
// an hour kept the CPU and their own heaps busy.
|
|
37
|
+
const QUIET_AFTER = 6e4;
|
|
38
|
+
const QUIET_POLL = 5e3;
|
|
39
|
+
const stateTime = () => { try { return fs.statSync(paths.state).mtimeMs; } catch { return 0; } };
|
|
40
|
+
async function nextPoll(started) {
|
|
41
|
+
const since = now(), was = stateTime();
|
|
42
|
+
do await sleep(POLL);
|
|
43
|
+
while (now() - started > QUIET_AFTER && now() - since < QUIET_POLL && stateTime() === was);
|
|
44
|
+
}
|
|
45
|
+
// A full disk seldom clears in seconds. Backing off to this keeps a line of
|
|
46
|
+
// waiters from retrying it constantly, and still starts soon after space is back.
|
|
47
|
+
const FULL_POLL_MAX = 15e3;
|
|
48
|
+
// With nothing new to say, a waiter hears from dibs this often: often enough
|
|
49
|
+
// to know it's alive, rare enough not to fill an agent's log.
|
|
50
|
+
const REPEAT_STATUS = 2 * 6e4;
|
|
51
|
+
// A new kind of wait is said once it has held for this many polls in a row
|
|
52
|
+
// (3 seconds): memory pressure and an over-budget reading take turns every
|
|
53
|
+
// few seconds in one crunch, and each turn used to print a line.
|
|
54
|
+
const STEADY = 3;
|
|
55
|
+
// A change of place is said at most this often, so a busy line doesn't print every start.
|
|
56
|
+
const MOVE_EVERY = 30e3;
|
|
57
|
+
const IDLE_AFTER = 5 * 6e4;
|
|
58
|
+
const HOLD_FOR = 20 * 6e4; // a hold's length when --for doesn't say
|
|
59
|
+
export const HOLD_CAP = 60 * 6e4; // the most --for gets, and the most a hold lasts from its start while others wait
|
|
60
|
+
export const holdUntil = o => now() + Math.min(o.for ?? HOLD_FOR, HOLD_CAP);
|
|
61
|
+
|
|
62
|
+
const on = v => /^(1|true|yes|on)$/i.test(v || '');
|
|
63
|
+
// Claude Code doesn't kill a Bash command at its timeout: it moves it to the
|
|
64
|
+
// background and tells the agent when it exits ("Foreground commands that move
|
|
65
|
+
// to the background" in its tools reference). So a wait there needs no limit,
|
|
66
|
+
// unless background tasks are off (that setting, or bare mode). CLAUDECODE is
|
|
67
|
+
// also set in IDE terminals; CLAUDE_CODE_CHILD_SESSION only in the tool's own.
|
|
68
|
+
export const backgroundable = (env = process.env) =>
|
|
69
|
+
env.CLAUDE_CODE_CHILD_SESSION === '1' && !on(env.CLAUDE_CODE_DISABLE_BACKGROUND_TASKS) && !on(env.CLAUDE_CODE_SIMPLE);
|
|
70
|
+
// How long a wait lasts when no flag says: forever where nothing kills it, else
|
|
71
|
+
// short enough for a tool call. DIBS_MAX_WAIT lets tests shorten the limit.
|
|
72
|
+
export const defaultMaxWait = () =>
|
|
73
|
+
backgroundable() ? Infinity : process.env.DIBS_MAX_WAIT ? ms(process.env.DIBS_MAX_WAIT) : DEFAULT_MAX_WAIT;
|
|
74
|
+
|
|
75
|
+
// Said once, when the wait starts, so nobody has to guess what happens at the end of it.
|
|
76
|
+
function waitTerms(w) {
|
|
77
|
+
if (w.maxWait === Infinity)
|
|
78
|
+
return !w.info.waitSet
|
|
79
|
+
? "No time limit. If this tool call times out, Claude Code moves it to the background and tells you when it ends: don't run it again, or it runs twice."
|
|
80
|
+
: 'No time limit (--wait).';
|
|
81
|
+
return `Gives up at ${clock(w.started + w.maxWait)} if it's still waiting (exit 75: your command won't have run). To wait as long as it takes, add --wait.`;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
// The command as the agent typed it, to paste back.
|
|
85
|
+
const again = () => `dibs ${quoted(process.argv.slice(2))}`;
|
|
86
|
+
|
|
87
|
+
// Note run leases whose whole process tree has used no CPU for a while. Called
|
|
88
|
+
// inside withState, so the first-seen time is kept between calls.
|
|
89
|
+
// Every process group the run spans counts: a test runner's workers split off
|
|
90
|
+
// into groups of their own, and a run whose own group sleeps while they work isn't idle.
|
|
91
|
+
// A simulator the run is using counts too (src/measure.mjs treeOf): its work runs there.
|
|
92
|
+
export function markIdle(s, procs) {
|
|
93
|
+
const runs = s.leases.filter(l => l.kind === 'run' && l.pgid && !l.pausedAt); // a paused job is quiet on purpose
|
|
94
|
+
if (!runs.length) return;
|
|
95
|
+
procs ||= processes();
|
|
96
|
+
const cpu = new Map(procs.map(p => [p.pid, p.cpu]));
|
|
97
|
+
for (const l of runs) {
|
|
98
|
+
let used = 0;
|
|
99
|
+
for (const pid of treeOf(l, s, procs)) used += cpu.get(pid) || 0;
|
|
100
|
+
if (used < 1) l.idleSince ||= now();
|
|
101
|
+
else delete l.idleSince;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
// Runs idle STUCK_AFTER or more while someone waits: likely orphaned, so the
|
|
105
|
+
// board marks them and the hook can tell their holder. Nothing is ended for them.
|
|
106
|
+
// Read straight off state.json too: a run lease whose idleSince is older than
|
|
107
|
+
// STUCK_AFTER, with a live waiter in queue.
|
|
108
|
+
export const stuckLeases = (s, t = now()) => (s.queue.some(q => q.pid) ? s.leases.filter(l => stuckFor(l, t)) : []);
|
|
109
|
+
export { STUCK_AFTER };
|
|
110
|
+
export const idleFor = (l, t = now()) => (l.idleSince && t - l.idleSince > IDLE_AFTER ? t - l.idleSince : 0);
|
|
111
|
+
|
|
112
|
+
export function describeLease(l, hist, t = now()) {
|
|
113
|
+
const left = remaining(l, hist, t);
|
|
114
|
+
const idle = idleFor(l, t);
|
|
115
|
+
return `${tag(l)} for ${dur(t - l.start)}${l.purpose ? ` ("${l.purpose}")` : ''}${l.cmd ? `: ${l.cmd.slice(0, 60)}` : ' (hold)'}`
|
|
116
|
+
+ `${left != null ? `, ~${dur(left)} left` : ''}${idle ? `, but its command has used no CPU for ${dur(idle)}` : ''}`
|
|
117
|
+
+ `${overBy(l) ? `, using ${gb(l.use.mem)} of the ${gb(l.mem)} it asked for` : ''}`;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// Where a waiter stands, in plain words: { head, why, ask }. head says the
|
|
121
|
+
// place and start; why, what it's waiting for; ask, who could let it go first.
|
|
122
|
+
// prev: the place, line and jobs ahead when it was last said, so a move can say why.
|
|
123
|
+
function waitLine(s, me, v, cfg, hist, prev) {
|
|
124
|
+
const t = now();
|
|
125
|
+
const p = plainBoard(s, cfg, hist, t, undefined, me);
|
|
126
|
+
const w = p.waiting.get(me.id);
|
|
127
|
+
const eta = forecast(s, cfg, hist, t).get(me.id);
|
|
128
|
+
const head = `You're ${lower(w.headline)}, ${startPhrase(w)}.`;
|
|
129
|
+
let why = `Waiting for ${w.waitingFor}.${w.advice ? ` ${w.advice}.` : ''}`;
|
|
130
|
+
if (me.by && eta && eta + expected(me, hist) > me.by) why += ` Your deadline, ${clock(me.by)}, is at risk.`;
|
|
131
|
+
// Nobody holds a rate limit's tokens: they come back with time, so there's nobody to ask.
|
|
132
|
+
return { head, why, ask: v.rule === 'quota' ? '' : askFirst(s, p, me), key: `${w.family}|${w.res}`, place: w.place, res: w.res, ahead: w.ahead,
|
|
133
|
+
moved: prev && movedText(s, me, w, prev, cfg, hist, t) };
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// What a waiter says on this poll, given its wait line: 'full' (the first
|
|
137
|
+
// time), 'change' (a new kind of wait that has held STEADY polls), 'moved'
|
|
138
|
+
// (its place changed, at most every MOVE_EVERY), 'repeat' (nothing new for
|
|
139
|
+
// REPEAT_STATUS) or null. One per wait; it keeps what was last said. seed is
|
|
140
|
+
// what save() gave, for a wait that carries on in another process (src/broker.mjs).
|
|
141
|
+
export function talker(seed) {
|
|
142
|
+
let lastSaid = seed?.lastSaid || 0, lastKey = seed?.lastKey || '', pending = null;
|
|
143
|
+
const out = { told: seed?.told ? { ...seed.told, ahead: new Set(seed.told.ahead) } : null };
|
|
144
|
+
out.save = () => ({ lastSaid, lastKey, told: out.told && { ...out.told, ahead: [...out.told.ahead] } });
|
|
145
|
+
out.step = (l, t = now()) => {
|
|
146
|
+
pending = l.key === lastKey ? null : pending?.key === l.key ? { key: l.key, n: pending.n + 1 } : { key: l.key, n: 1 };
|
|
147
|
+
let what = null;
|
|
148
|
+
if (!lastSaid) what = 'full';
|
|
149
|
+
else if (pending?.n >= STEADY) what = 'change';
|
|
150
|
+
else if (l.moved && t - out.told.at >= MOVE_EVERY) what = 'moved';
|
|
151
|
+
else if (t - lastSaid > REPEAT_STATUS) what = 'repeat';
|
|
152
|
+
if (!what) return null;
|
|
153
|
+
if (what !== 'repeat') out.told = { place: l.place, res: l.res, ahead: new Set(l.ahead), at: t };
|
|
154
|
+
if (what === 'full' || what === 'change') { lastKey = l.key; pending = null; }
|
|
155
|
+
lastSaid = t;
|
|
156
|
+
return what;
|
|
157
|
+
};
|
|
158
|
+
return out;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// "moved up from 4th to 2nd in the test queue", or, losing places, who went
|
|
162
|
+
// ahead and why: a job sinking from 8th to 19th with no word looks broken.
|
|
163
|
+
export function movedText(s, me, w, prev, cfg, hist, t) {
|
|
164
|
+
if (w.place == null || prev.place == null || w.res !== prev.res || w.place === prev.place) return '';
|
|
165
|
+
const where = `${ordinal(prev.place)} to ${ordinal(w.place)} in ${named(cfg, w.res).queue}`;
|
|
166
|
+
if (w.place < prev.place) return `moved up from ${where}.`;
|
|
167
|
+
const came = w.ahead.filter(id => !prev.ahead.has(id)).map(id => s.queue.find(q => q.id === id)).filter(Boolean);
|
|
168
|
+
const names = andList(came.length > 2 ? [...came.slice(0, 2).map(q => q.agent || q.who), `${came.length - 2} more`] : came.map(q => q.agent || q.who));
|
|
169
|
+
const x = came[0];
|
|
170
|
+
const low = me.prio === 'low' || me.prio === 'idle';
|
|
171
|
+
const because = !x ? ''
|
|
172
|
+
: low && !(x.prio === 'low' || x.prio === 'idle') ? `: you're ${me.prio} priority, so normal jobs that arrive later go ahead of you`
|
|
173
|
+
: (() => { const m = moves(x, hist, t, cfg).find(m => m.dir === 'up'); return m ? `: ${m.reason}` : ': they ranked ahead of you'; })();
|
|
174
|
+
return `moved back from ${where}${names ? `. ${names} went ahead${because}` : ''}.`;
|
|
175
|
+
}
|
|
176
|
+
// Several lines from dibs on stderr, each wrapped to fit, under one "dibs:".
|
|
177
|
+
export const saidText = (...lines) => `${lines.filter(Boolean).map((l, i) => wrap(`${i ? ' ' : 'dibs: '}${l}`, ' ', width(process.stderr))).join('\n')}\n`;
|
|
178
|
+
const said = (...lines) => process.stderr.write(saidText(...lines));
|
|
179
|
+
|
|
180
|
+
// The dibs run this process is nested in, or null. DIBS_LEASE names it, and
|
|
181
|
+
// its process must be one of ours: the variable alone can't borrow someone
|
|
182
|
+
// else's lease to skip the line.
|
|
183
|
+
export function outerLease() {
|
|
184
|
+
const id = process.env.DIBS_LEASE;
|
|
185
|
+
if (!id) return null;
|
|
186
|
+
const up = new Set();
|
|
187
|
+
for (let pid = callerPid(), i = 0; pid > 1 && i < 25; i++) { up.add(pid); pid = parent(pid)?.ppid; }
|
|
188
|
+
// A plain read, with no lock to take, so a full disk can't stop a nested run here.
|
|
189
|
+
// The state file is replaced whole, never written in place.
|
|
190
|
+
let s;
|
|
191
|
+
try { s = JSON.parse(fs.readFileSync(paths.state, 'utf8')); } catch { return null; }
|
|
192
|
+
const l = (s.leases || []).find(x => String(x.id) === id && x.kind === 'run');
|
|
193
|
+
return l && up.has(l.pid) && (!l.pstart || pstart(l.pid) === l.pstart) ? l : null;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// What history is kept under: the program and its words that aren't flags, up
|
|
197
|
+
// to KEY_WORDS, each cut to its last path part so a temp folder doesn't make
|
|
198
|
+
// every run new. npm test and npm run lint, or a build and a test of one
|
|
199
|
+
// project, learn their run times and sizes apart. xcodebuild's words are
|
|
200
|
+
// mostly flag values, so it's keyed by its first, its scheme, its
|
|
201
|
+
// configuration and its actions. The first word stays where it was, before
|
|
202
|
+
// KEY_SPLIT, so history from before still counts (util.mjs runsOf).
|
|
203
|
+
const KEY_WORDS = 3; // enough for npm run lint or node --test a.test.mjs b.test.mjs; more and a message or file list makes every run new
|
|
204
|
+
const XCODE_ACTIONS = new Set(['build', 'build-for-testing', 'test', 'test-without-building', 'analyze', 'archive', 'docbuild', 'install', 'installsrc', 'clean']);
|
|
205
|
+
export function commandKey(cmd) {
|
|
206
|
+
const word = a => path.basename(a).slice(0, 40);
|
|
207
|
+
const prog = path.basename(cmd[0]);
|
|
208
|
+
const bare = cmd.slice(1).filter(a => !a.startsWith('-')).map(word);
|
|
209
|
+
const after = f => { const i = cmd.indexOf(f); return i > 0 && cmd[i + 1] ? word(cmd[i + 1]) : null; };
|
|
210
|
+
const more = (prog === 'xcodebuild'
|
|
211
|
+
? [after('-scheme'), after('-configuration'), ...cmd.slice(1).filter(a => XCODE_ACTIONS.has(a))]
|
|
212
|
+
: bare.slice(1, KEY_WORDS)).filter(Boolean);
|
|
213
|
+
const first = [prog, bare[0]].filter(Boolean).join(' ');
|
|
214
|
+
return more.length ? `${first}${KEY_SPLIT}${more.join(' ')}` : first;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
// Where a waiter's messages go. Here, stderr; a waiter of another process
|
|
219
|
+
// passes its own (src/broker.mjs), so one step serves both.
|
|
220
|
+
export const stderrOut = { say, said, raw: text => process.stderr.write(text), die, exit: code => process.exit(code) };
|
|
221
|
+
|
|
222
|
+
// One wait, between polls: what the request asked for that its queue entry
|
|
223
|
+
// doesn't keep (info), and what has been said so far. me is the entry. A thin
|
|
224
|
+
// waiter's info is its entry's wake, which carries on where its _enqueue left
|
|
225
|
+
// off (maxWait Infinity is null there, as JSON has no Infinity).
|
|
226
|
+
export function waiter(info, cfg, hist, out) {
|
|
227
|
+
return { info, cfg, hist, out, me: null, started: info.started, maxWait: info.maxWait ?? Infinity, talk: talker(info.talk),
|
|
228
|
+
blocked: !!info.blocked, warnedHolding: !!info.warnedHolding, saidAhead: !!info.saidAhead, full: false };
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// A wait is recorded once it's blocked. One that ends any way but starting or
|
|
232
|
+
// timing out (a signal, a full disk, the owner) is closed in the history too,
|
|
233
|
+
// or dibs history would miss the waits agents gave up on.
|
|
234
|
+
const note = (w, what, extra) => event({ kind: what, id: w.me.id, res: w.me.res, who: w.me.who, prio: w.me.prio || 'normal', type: w.me.kind, ...extra });
|
|
235
|
+
const left = (w, why) => { if (w.blocked) note(w, 'left', { ms: now() - w.me.enq, why }); };
|
|
236
|
+
|
|
237
|
+
// On a full disk the place stays on record under this pid, and the next
|
|
238
|
+
// state read drops it once this process is gone.
|
|
239
|
+
function leave(w, keep) {
|
|
240
|
+
try {
|
|
241
|
+
withState(s => {
|
|
242
|
+
const q = s.queue.find(x => x.id === w.me.id);
|
|
243
|
+
if (keep && q) Object.assign(q, { pid: null, keepUntil: now() + KEEP_PLACE });
|
|
244
|
+
else s.queue = s.queue.filter(x => x.id !== w.me.id);
|
|
245
|
+
});
|
|
246
|
+
} catch (e) { if (!noSpace(e)) throw e; }
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// A wait ended from outside it: leaves the line, closes it in the history, says why.
|
|
250
|
+
export function abandon(w, why, code, text) {
|
|
251
|
+
left(w, why);
|
|
252
|
+
leave(w, false);
|
|
253
|
+
return w.out.die(text, code);
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
// A disk too full to save the state is waited out like any low-disk wait,
|
|
257
|
+
// until the wait limit (exit 74). Called each time a save fails.
|
|
258
|
+
export function full(w) {
|
|
259
|
+
const free = machine().diskFree;
|
|
260
|
+
const room = free != null ? ` (${gb(free).replace(/G$/, ' GB')} free)` : '';
|
|
261
|
+
if (now() - w.started >= w.maxWait) {
|
|
262
|
+
left(w, 'disk full');
|
|
263
|
+
return w.out.die(`the disk is still too full for dibs to save its state${room}.`
|
|
264
|
+
+ ` Your command did NOT run (exit 74). Free some disk space, then run it again:\n ${w.info.again}\n ${OFF_LIMITS}`, 74);
|
|
265
|
+
}
|
|
266
|
+
if (!w.full) {
|
|
267
|
+
w.full = true;
|
|
268
|
+
w.out.said(`the disk is too full for dibs to save your place in line${room}. Waiting for space and trying again.`,
|
|
269
|
+
w.maxWait === Infinity ? 'No time limit.' : `Gives up at ${clock(w.started + w.maxWait)} if the disk is still full (exit 74: your command won't have run).`);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// withState, retried less often the longer the disk stays full.
|
|
274
|
+
async function saved(w, fn) {
|
|
275
|
+
for (let pause = POLL; ; pause = Math.min(pause * 2, FULL_POLL_MAX)) {
|
|
276
|
+
try {
|
|
277
|
+
const out = withState(fn);
|
|
278
|
+
if (w.full) { w.full = false; say("there's disk space again; back in line."); }
|
|
279
|
+
return out;
|
|
280
|
+
} catch (e) { if (!noSpace(e)) throw e; }
|
|
281
|
+
full(w);
|
|
282
|
+
await sleep(pause);
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// One poll's part under the state lock: leave if the owner took this wait out
|
|
287
|
+
// of line, take the lease if the gates allow, else work out why not.
|
|
288
|
+
// Its size again from what its command has used, as dibs learns now: on
|
|
289
|
+
// 2026-10-20 nine browser runs sized when one run had read 15 GB still waited,
|
|
290
|
+
// two hours on, for the whole budget the new rule no longer planned.
|
|
291
|
+
const POLLED_EVERY = 60e3;
|
|
292
|
+
function resize(cur, w) {
|
|
293
|
+
if (cur.sent) return;
|
|
294
|
+
const base = { mem: cur.asked ?? cur.mem, cpu: cur.cpu, disk: cur.disk };
|
|
295
|
+
const n = sized(base, w.hist, cur.key, w.cfg);
|
|
296
|
+
if (n.mem === cur.mem && n.usual === cur.usual) return;
|
|
297
|
+
cur.mem = n.mem;
|
|
298
|
+
if (n.usual != null) cur.usual = n.usual; else delete cur.usual;
|
|
299
|
+
Object.assign(w.info.size, { mem: n.mem, usual: n.usual });
|
|
300
|
+
}
|
|
301
|
+
export function decide(s, w) {
|
|
302
|
+
const { me, cfg, hist, info } = w;
|
|
303
|
+
const cur = s.queue.find(x => x.id === me.id) || me;
|
|
304
|
+
if (cur.ownerStop) { s.queue = s.queue.filter(x => x.id !== me.id); return { stopped: true, by: cur.stopBy, reason: cur.stopReason }; }
|
|
305
|
+
// Kept current here, so it lapses when the hold ages out or ends.
|
|
306
|
+
const holding = holdingOf(s, cur, cfg);
|
|
307
|
+
if (holding) cur.holding = holding; else delete cur.holding;
|
|
308
|
+
resize(cur, w);
|
|
309
|
+
// When its dibs last looked, so the board can tell a waiter that could start from one nobody
|
|
310
|
+
// is deciding for. Once a minute at most: a poll that changes nothing leaves the state file alone.
|
|
311
|
+
if (!(now() - (cur.polledAt || 0) < POLLED_EVERY)) cur.polledAt = now();
|
|
312
|
+
let v = verdict(s, cur, cfg, hist);
|
|
313
|
+
// A rate limit that would stop it anyway is checked before pausing anyone for it.
|
|
314
|
+
if (!v.ok && v.rule === 'slot') v = quotaBlock(s, cur, cfg, hist) || preempt(s, cur, cfg, hist) || v;
|
|
315
|
+
if (v.ok) v = quotaBlock(s, cur, cfg, hist) || v;
|
|
316
|
+
// What held it and for how long, for its start event: on 2026-10-24 a 2-second test waited
|
|
317
|
+
// 3 minutes with 11 GB of disk free, and the log said only that it waited. Kept in the
|
|
318
|
+
// waiter's memory, so a poll that changes nothing still leaves the state file alone.
|
|
319
|
+
const t = now();
|
|
320
|
+
if (w.heldRule) w.heldBy = { ...w.heldBy, [w.heldRule]: (w.heldBy?.[w.heldRule] || 0) + t - w.heldAt };
|
|
321
|
+
w.heldRule = v.ok ? null : v.rule || 'other';
|
|
322
|
+
w.heldAt = t;
|
|
323
|
+
// For the stall breaker (schedule.mjs): whether the machine, not the line, holds this one back.
|
|
324
|
+
if (!v.ok && v.machine) cur.machineHeld = true; else delete cur.machineHeld;
|
|
325
|
+
// When the load ceiling alone started holding it: after LOAD_STARVE it starts anyway (schedule.mjs).
|
|
326
|
+
if (!v.ok && v.rule === 'load') cur.loadSince ??= v.since; else if (!v.ok) delete cur.loadSince;
|
|
327
|
+
// And when the machine started holding it (any of HELD_BY), for step's move to an on-demand
|
|
328
|
+
// machine. One clock for all: a crunch flips between load, memory and swap.
|
|
329
|
+
if (machineHold(v)) v.shipSince = cur.shipSince ??= now(); else delete cur.shipSince;
|
|
330
|
+
// Waiting its turn in line: how long until it starts here, at most once per SHIP_EVERY
|
|
331
|
+
// (the forecast walks the whole queue), for step's choice to send it elsewhere.
|
|
332
|
+
if (!v.ok && LINE_WAITS.has(v.rule) && now() - (w.forecastAt || 0) >= SHIP_EVERY) {
|
|
333
|
+
w.forecastAt = now();
|
|
334
|
+
const at = forecast(s, cfg, hist).get(cur.id);
|
|
335
|
+
if (at != null) v.wait = at - now();
|
|
336
|
+
}
|
|
337
|
+
// Bigger than this machine's budget, lowered since it joined: asked for in so
|
|
338
|
+
// many words, it would wait forever, so it leaves the line and says why. A
|
|
339
|
+
// size dibs chose is booked down to what the machine hands out instead.
|
|
340
|
+
const never = !v.ok && neverFits(cfg, cur) && neverFits(cfg, explicitAsk(cur));
|
|
341
|
+
if (never) { s.queue = s.queue.filter(x => x.id !== me.id); return { never }; }
|
|
342
|
+
// The lease is made from info.size, so it's booked down too.
|
|
343
|
+
if (!v.ok && neverFits(cfg, cur) && capToMachine(cfg, cur)) Object.assign(info.size, { mem: cur.mem, cpu: cur.cpu });
|
|
344
|
+
if (!v.ok) {
|
|
345
|
+
// Sitting on one resource while waiting for another wastes it for everyone.
|
|
346
|
+
// A file lease doesn't count: it keeps edits off files while you work, and a job waiting for a test slot doesn't change that.
|
|
347
|
+
const sitting = s.leases.filter(l => l.kind === 'hold' && me.spid && l.pid === me.spid && !l.res.some(x => me.res.includes(x)) && !l.res.every(isFiles));
|
|
348
|
+
return { v, line: waitLine(s, cur, v, cfg, hist, w.talk.told), idle: !s.leases.length, sitting, holding: cur.holding };
|
|
349
|
+
}
|
|
350
|
+
s.queue = s.queue.filter(x => x.id !== me.id);
|
|
351
|
+
takeQuota(s, cur, cfg);
|
|
352
|
+
const lease = { id: me.id, res: me.res, ...info.size, kind: me.kind, who: me.who, agent: me.agent, label: me.label, spid: me.spid,
|
|
353
|
+
purpose: cur.purpose, cmd: me.cmd, key: me.key, est: info.est, prio: cur.prio, by: cur.by,
|
|
354
|
+
cwd: info.cwd, ppid: info.ppid, start: now(), waited: now() - cur.enq, agentId: info.agentId, sessionId: info.sessionId,
|
|
355
|
+
owner: cur.owner, askedPrio: cur.askedPrio };
|
|
356
|
+
if (w.heldBy) lease.held = Object.fromEntries(Object.entries(w.heldBy).map(([k, x]) => [k, Math.round(x)]));
|
|
357
|
+
if (v.covered.length) lease.covered = v.covered;
|
|
358
|
+
if (v.alongside) lease.alongside = v.alongside;
|
|
359
|
+
if (v.trial) lease.trial = true;
|
|
360
|
+
if (cur.repo) lease.repo = cur.repo;
|
|
361
|
+
if (v.loadPast) Object.assign(lease, { loadPast: true, loadWaited: v.loadWaited });
|
|
362
|
+
// The stall breaker's clock (schedule.mjs) runs from the last start the gates allowed.
|
|
363
|
+
if (v.breaker) lease.breaker = true;
|
|
364
|
+
else if (v.gated && me.kind === 'run') { lease.gated = true; s.lastStart = lease.start; }
|
|
365
|
+
if (cur.outer) lease.outer = cur.outer;
|
|
366
|
+
if (cur.requeues) lease.requeues = cur.requeues; // stopped before for using far more than it booked (src/preempt.mjs)
|
|
367
|
+
if (cur.disk) lease.disk = cur.disk; // its share of the disk's fall is weighed by it (src/measure.mjs shareDisk)
|
|
368
|
+
if (me.kind === 'hold') Object.assign(lease, { pid: me.spid, pstart: info.sstart, expires: holdUntil(info) });
|
|
369
|
+
else Object.assign(lease, { pid: me.pid, pstart: me.pstart });
|
|
370
|
+
// A thin hold's shell becomes the dibs hold that reports it (hold --lease).
|
|
371
|
+
if (info.path) lease.shell = me.pid;
|
|
372
|
+
s.leases.push(lease);
|
|
373
|
+
return { lease, paused: v.paused };
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// The rest of a poll, after the lock: what to say, and whether the wait ends.
|
|
377
|
+
// Returns { lease } on this waiter's turn, null to poll again. An ending goes
|
|
378
|
+
// through w.out (exit 74, 75, or the owner's stop).
|
|
379
|
+
export function step(r, w) {
|
|
380
|
+
const { me, cfg, out } = w;
|
|
381
|
+
if (r.stopped) {
|
|
382
|
+
left(w, 'owner stop');
|
|
383
|
+
return out.die(`stopped by ${r.by || 'the owner (the person at this machine)'} on purpose (dibs stop)${r.reason ? `: "${r.reason}"` : ''}. This was taken out of line and your command did not run.`
|
|
384
|
+
+ `${r.reason ? '' : ' Find out why before trying again: dibs history, or ask whoever stopped it.'}`, signalExit('SIGTERM'));
|
|
385
|
+
}
|
|
386
|
+
if (r.never) {
|
|
387
|
+
left(w, 'never fits');
|
|
388
|
+
const text = neverText(r.never, me, cfg, null);
|
|
389
|
+
// Through the hook too: an agent that only reads its tool's result hears why its job left the line.
|
|
390
|
+
notify({ sessionId: w.info.sessionId, who: me.who, agentId: w.info.agentId }, `never:${me.id}`, `#${me.id} ${text}`);
|
|
391
|
+
return out.die(text, 2);
|
|
392
|
+
}
|
|
393
|
+
if (r.lease) {
|
|
394
|
+
if (now() - w.started > 2000) out.say(`your turn, after ${dur(now() - w.started)} in the queue.`);
|
|
395
|
+
if (r.lease.alongside) out.say(startLine(r.lease.alongside, cfg));
|
|
396
|
+
if (r.lease.breaker) out.say(`starting although the machine is short of disk or memory: nothing had started for ${STALL / 6e4} min, so dibs lets the smallest waiter in, one at a time. The rest wait until yours ends or its memory holds steady.`);
|
|
397
|
+
for (const p of r.paused || []) out.say(`paused ${p.who}'s ${p.prio} priority job on ${andList(p.res.map(x => named(cfg, x).the))} so you could start. It picks up again when you're done.`);
|
|
398
|
+
return { lease: r.lease };
|
|
399
|
+
}
|
|
400
|
+
// A wait is a request that couldn't start at once; one that starts on its first try isn't one.
|
|
401
|
+
if (!w.blocked) { w.blocked = true; note(w, 'wait', { rule: r.v.rule || 'other' }); }
|
|
402
|
+
if (r.holding && !w.saidAhead) {
|
|
403
|
+
w.saidAhead = true;
|
|
404
|
+
out.say(`you already have ${andList(r.holding.res.map(x => named(cfg, x).the))}, so you go ahead of anyone who has nothing yet (urgent work still goes first).`);
|
|
405
|
+
}
|
|
406
|
+
if (w.warnedHolding && !r.sitting.length) {
|
|
407
|
+
w.warnedHolding = false;
|
|
408
|
+
out.say('you gave back what you were keeping, so nothing sits unused while you wait. Still in line.');
|
|
409
|
+
}
|
|
410
|
+
if (r.sitting.length && !w.warnedHolding) {
|
|
411
|
+
w.warnedHolding = true;
|
|
412
|
+
const kept = r.sitting.flatMap(l => l.res).filter(x => !isFiles(x));
|
|
413
|
+
out.say(`you're keeping ${andList(kept.map(x => named(cfg, x).the))} reserved while you wait, so nobody else can use it.`
|
|
414
|
+
+ ` Give it back (dibs release ${kept[0]}) or ask for everything at once: dibs run ${[...new Set([...kept, ...me.res])].join(',')} -- <command>`);
|
|
415
|
+
}
|
|
416
|
+
// Waiting can't free disk when nothing else is running.
|
|
417
|
+
if (r.v.disk && (r.idle || r.v.alone)) {
|
|
418
|
+
left(w, 'not enough disk');
|
|
419
|
+
leave(w, false);
|
|
420
|
+
return out.die(`not enough free disk: ${gb(r.v.free).replace(/G$/, ' GB')} free, it needs ${gb(r.v.need).replace(/G$/, ' GB')}, and nothing running will free any.`
|
|
421
|
+
+ ` Your command did NOT run (exit 74). Free some space, or pass --disk with what this job really needs if that's less, then run it again:\n ${w.info.again}\n ${OFF_LIMITS}`, 74);
|
|
422
|
+
}
|
|
423
|
+
if (now() - w.started >= w.maxWait) {
|
|
424
|
+
note(w, 'timeout', { ms: now() - me.enq });
|
|
425
|
+
leave(w, w.maxWait > 0);
|
|
426
|
+
if (!w.maxWait)
|
|
427
|
+
return out.die(`not free yet. ${r.line.why} --no-wait doesn't wait, so your command did NOT run (exit 75).`
|
|
428
|
+
+ ` See when it frees up: dibs when ${shellRes(me.res.map(x => short(x)))}`, 75);
|
|
429
|
+
out.said(`gave up after ${dur(now() - w.started)} in the queue. Your command did NOT run (exit 75, not a failure).`,
|
|
430
|
+
r.line.head, `Your place is kept until ${clock(now() + KEEP_PLACE)}. To keep it, run the same command again before then:`);
|
|
431
|
+
// The command on a line of its own, unwrapped, so it can be pasted as is.
|
|
432
|
+
out.raw(` ${w.info.again}\n`);
|
|
433
|
+
out.raw(`${wrap(' Or wait as long as it takes: add --wait (in a background shell if your tool call has a time limit).', ' ', width(process.stderr))}\n`);
|
|
434
|
+
return out.exit(75);
|
|
435
|
+
}
|
|
436
|
+
// Held by the machine SHIP_AFTER, and able to run elsewhere: try an on-demand machine (the
|
|
437
|
+
// waiter's loop below does, since asking the coordinator takes a round trip).
|
|
438
|
+
// A job that usually uses more than this machine's whole budget prefers a machine it fits, at once.
|
|
439
|
+
const held = machineHold(r.v);
|
|
440
|
+
const after = r.v.rule === 'memory' && me.usual != null ? 0 : held ? SHIP_AFTER : null;
|
|
441
|
+
if (after != null && now() - (r.v.shipSince ?? now()) >= after && now() - (w.shipAt || 0) >= SHIP_EVERY && mayShip(me, cfg, w.info.cwd)) {
|
|
442
|
+
w.shipAt = now();
|
|
443
|
+
w.loadFrom = r.v.shipSince;
|
|
444
|
+
return { ship: held };
|
|
445
|
+
}
|
|
446
|
+
// Its turn here is further off than sending it and running it there: it goes now.
|
|
447
|
+
if (r.v.wait != null && r.v.wait > SHIP_OVERHEAD + expected(me, w.hist) && now() - (w.shipAt || 0) >= SHIP_EVERY && mayShip(me, cfg, w.info.cwd)) {
|
|
448
|
+
w.shipAt = now();
|
|
449
|
+
w.lineWait = r.v.wait;
|
|
450
|
+
return { ship: 'line' };
|
|
451
|
+
}
|
|
452
|
+
// The whole picture once. After that a line when the kind of wait really
|
|
453
|
+
// changes (and has held for STEADY polls), when the place moves (at most
|
|
454
|
+
// every MOVE_EVERY), or now and then.
|
|
455
|
+
const l = r.line;
|
|
456
|
+
const what = w.talk.step(l);
|
|
457
|
+
if (what === 'full') out.said(`queued for ${andList(me.res.map(x => named(cfg, x).the))}.${me.kind === 'hold' ? ' dibs hold waits for its turn like dibs run, then returns.' : ''}`, l.head, l.why, l.ask, w.maxWait > 0 ? waitTerms(w) : '');
|
|
458
|
+
else if (what === 'change') out.said(`still queued (${dur(now() - w.started)}). ${l.head}`, l.why);
|
|
459
|
+
else if (what === 'moved') out.say(`still queued (${dur(now() - w.started)}). You ${l.moved}`);
|
|
460
|
+
else if (what === 'repeat') out.say(`still queued (${dur(now() - w.started)}). ${l.head}`);
|
|
461
|
+
return null;
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
// A wait the machine causes (its load, the budgets, memory, the disk swap grows
|
|
465
|
+
// on, a job ahead reserving memory) moves to an on-demand machine after
|
|
466
|
+
// SHIP_AFTER, asking at most every SHIP_EVERY. Two minutes: by then the jobs
|
|
467
|
+
// ahead aren't about to finish, and waking boat-1 takes 15 to 40 s. On
|
|
468
|
+
// 2026-10-20 ten jobs waited on the Mac at load 48 while boat-1 sat idle.
|
|
469
|
+
// The 20-minute start at background priority (schedule.mjs LOAD_STARVE) is
|
|
470
|
+
// the fallback when no machine will take it.
|
|
471
|
+
const SHIP_AFTER = (Number(process.env.DIBS_SHIP_AFTER) * 1000) || 2 * 6e4, SHIP_EVERY = 6e4;
|
|
472
|
+
// Waits that are the line's, not the machine's: whose length the forecast knows.
|
|
473
|
+
const LINE_WAITS = new Set(['slot', 'ahead', 'together']);
|
|
474
|
+
// Waking boat-1 and copying the project there: 15 to 40 s to wake, a few more to send.
|
|
475
|
+
const SHIP_OVERHEAD = 90e3;
|
|
476
|
+
const HELD_BY = {
|
|
477
|
+
load: "the machine's load", cpu: 'the cores dibs shares out on this machine', memory: 'the memory dibs shares out on this machine',
|
|
478
|
+
ram: "this machine's free memory", oversize: "this machine's free memory", pressure: "this machine's memory pressure",
|
|
479
|
+
swap: "this machine's swapping", swaproom: 'the free disk swap needs here', drain: 'free disk falling here',
|
|
480
|
+
ahead: 'a job ahead of it waiting for memory',
|
|
481
|
+
};
|
|
482
|
+
// The waits on memory: those may also go to a VM made beside a full boat-1.
|
|
483
|
+
// The rest go to boat-1 only when it has room.
|
|
484
|
+
const MEMORY_HELD = new Set(['memory', 'ram', 'oversize', 'pressure', 'swap']);
|
|
485
|
+
// Its reason, when the machine is what holds it, else null.
|
|
486
|
+
const machineHold = v => (v.ok ? null : v.rule === 'ahead' ? (v.starved ? 'ahead' : null) : HELD_BY[v.rule] ? v.rule : null);
|
|
487
|
+
// Give up this place and run the same command with --on <machine>, as this
|
|
488
|
+
// same process where Node allows it (src/commands.mjs runAgain does the same):
|
|
489
|
+
// remoteRun checks the project's rules and the home folder again and sends it.
|
|
490
|
+
function shipTo(w, to, bail, why = 'load') {
|
|
491
|
+
left(w, 'sent to ' + to);
|
|
492
|
+
leave(w, false);
|
|
493
|
+
for (const sig of SIGNALS) process.removeListener(sig, bail);
|
|
494
|
+
w.out.say(why === 'line'
|
|
495
|
+
? `its turn here is about ${dur(w.lineWait)} off, longer than sending it and running it there, so it goes to ${to}, an on-demand machine with room.`
|
|
496
|
+
: `${HELD_BY[why] || HELD_BY.load} has held this job for ${dur(now() - (w.loadFrom ?? w.started))}, so it goes to ${to}, an on-demand machine with room, instead of waiting here.`);
|
|
497
|
+
const args = process.argv.slice(2);
|
|
498
|
+
const dd = args.indexOf('--');
|
|
499
|
+
args.splice(dd < 0 ? args.length : dd, 0, '--on', to);
|
|
500
|
+
if (process.execve && OS !== 'windows') process.execve('/bin/sh', ['/bin/sh', BIN, ...args], process.env);
|
|
501
|
+
const child = spawn(process.execPath, [BIN, ...args], { stdio: 'inherit' });
|
|
502
|
+
for (const sig of SIGNALS) process.on(sig, () => child.kill(sig));
|
|
503
|
+
child.on('exit', (code, sig) => process.exit(code ?? signalExit(sig)));
|
|
504
|
+
return new Promise(() => {});
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
const codeNow = () => { try { return fs.readFileSync(path.join(path.dirname(BIN), '..', 'src', 'version.mjs'), 'utf8'); } catch { return null; } };
|
|
508
|
+
// Keep this place and run the same command again, as this same process where Node allows it.
|
|
509
|
+
function rerun(w, bail) {
|
|
510
|
+
leave(w, true);
|
|
511
|
+
w.out.say('dibs was updated while this waited, so it carries on as the new dibs, in the same place.');
|
|
512
|
+
for (const sig of SIGNALS) process.removeListener(sig, bail);
|
|
513
|
+
const args = process.argv.slice(2);
|
|
514
|
+
if (process.execve && OS !== 'windows') process.execve('/bin/sh', ['/bin/sh', BIN, ...args], process.env);
|
|
515
|
+
const child = spawn(process.execPath, [BIN, ...args], { stdio: 'inherit' });
|
|
516
|
+
for (const sig of SIGNALS) process.on(sig, () => child.kill(sig));
|
|
517
|
+
child.on('exit', (code, sig) => process.exit(code ?? signalExit(sig)));
|
|
518
|
+
return new Promise(() => {});
|
|
519
|
+
}
|
|
520
|
+
|
|
521
|
+
// A thin waiter's turn (src/thin.sh): the broker wrote this lease for the
|
|
522
|
+
// shell, which has since become this process, with the same pid and start time.
|
|
523
|
+
function ownLease(id, kind) {
|
|
524
|
+
let s = {};
|
|
525
|
+
try { s = JSON.parse(fs.readFileSync(paths.state, 'utf8')); } catch {}
|
|
526
|
+
const l = (s.leases || []).find(x => x.id === id && (kind === 'run' ? x.pid : x.shell) === process.pid);
|
|
527
|
+
if (!l) die('your turn was taken back before your command started, so it did NOT run (exit 75). Run it again.', 75);
|
|
528
|
+
return l;
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
// o.thin: getting a thin waiter in line for its shell (src/broker.mjs
|
|
532
|
+
// thinCall), which waits once this hands it over. o.lease: that shell's turn.
|
|
533
|
+
const configAt = () => { try { return fs.statSync(paths.config).mtimeMs; } catch { return 0; } };
|
|
534
|
+
// The config as it is now, or null while it's half written (someone saving it).
|
|
535
|
+
function freshConfig() {
|
|
536
|
+
try { JSON.parse(fs.readFileSync(paths.config, 'utf8')); return loadConfig(); } catch { return null; }
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
// A job that asks for more than this machine ever hands out: what to say.
|
|
540
|
+
// others: machines in the group with a budget it fits, when known.
|
|
541
|
+
export function neverText(nf, me, cfg, others) {
|
|
542
|
+
const where = others == null ? (remoteConfigured() ? ' Or send it to a machine in your group with room for it: --anywhere, or --on <machine> (dibs machines lists them).' : '')
|
|
543
|
+
: others.length ? ` Or send it where it fits: --on ${others[0]}${others.length > 1 ? ` (${others.slice(1).join(', ')} would fit too)` : ''}, or --anywhere.` : '';
|
|
544
|
+
return `this job books ${nf.unit(nf.need)} of ${nf.what}, and dibs hands out at most ${nf.unit(nf.most)} at once on this machine`
|
|
545
|
+
+ ` (${nf.whole ? 'all the machine has' : `${nf.what === 'memory' ? 'budget' : 'cores'} in ~/.dibs/config.json`}), so it could never start here. Your command did not run (exit 2).`
|
|
546
|
+
+ ` Ask for ${nf.flag} ${nf.unit(nf.most)} or less.${where}`;
|
|
547
|
+
}
|
|
548
|
+
const remoteConfigured = () => fs.existsSync(path.join(HOME, 'remote.json'));
|
|
549
|
+
|
|
550
|
+
// Machines in the group whose budget the job fits, or null if the coordinator
|
|
551
|
+
// can't say in time. Asked only when a job is refused, so plain runs never wait on the network.
|
|
552
|
+
async function fitsElsewhere(need) {
|
|
553
|
+
if (!remoteConfigured()) return [];
|
|
554
|
+
try {
|
|
555
|
+
const { remoteConf, call } = await import('./remote.mjs');
|
|
556
|
+
const rc = remoteConf(() => null);
|
|
557
|
+
if (!rc) return [];
|
|
558
|
+
const r = await call(rc, 'GET', '/machines', undefined, { timeout: ELSEWHERE_WAIT });
|
|
559
|
+
return r.machines.filter(m => !m.lost && m.name !== rc.name && (m.board?.memBudget ?? m.memTotal ?? 0) >= need.mem && (m.board?.cores ?? m.cores ?? 0) >= need.cpu).map(m => m.name);
|
|
560
|
+
} catch { return null; }
|
|
561
|
+
}
|
|
562
|
+
// Plain dibs gives other machines 1.5 s (AGENTS.md); a refusal can afford as much.
|
|
563
|
+
const ELSEWHERE_WAIT = 1500;
|
|
564
|
+
|
|
565
|
+
export async function acquire(o, kind, cfg) {
|
|
566
|
+
if (o.lease) return ownLease(o.lease, kind);
|
|
567
|
+
if (!o.res.length) die('which resource? Name it, like dibs hold sim. The list: dibs help all');
|
|
568
|
+
if (o.prio && !(o.prio in PRIORITY_SHIFT)) die(`priority is one of ${PRIORITIES.join(', ')} (or 1-5)`);
|
|
569
|
+
if (NEEDS_REASON.has(o.prio) && !o.purpose) die(`${o.prio} priority needs a reason everyone can see: -m "why"`);
|
|
570
|
+
const id = identity(o);
|
|
571
|
+
const res = [...new Set(o.res)];
|
|
572
|
+
const cmd = o.cmd ? o.cmd.join(' ') : '';
|
|
573
|
+
// A shard's runs are a part of the suite's: learned apart, so the whole suite's time stays its own (src/shard.mjs).
|
|
574
|
+
const key = `${res.join(',')}|${kind === 'hold' ? 'hold' : commandKey(o.cmd)}${process.env.DIBS_SHARD ? ' (shard)' : ''}`;
|
|
575
|
+
const hist = history();
|
|
576
|
+
// Planned at what this command really used last time, when that's more than it asked for.
|
|
577
|
+
const sent = !!process.env.DIBS_REMOTE_JOB;
|
|
578
|
+
const size = { ...sized(jobSize(cfg, res, o), hist, key, cfg), sent, declared: o.mem != null, cpuDeclared: o.cpu != null, ...(o.disk != null && { diskDeclared: true }) };
|
|
579
|
+
// More than this machine ever hands out, asked for in so many words: it would
|
|
580
|
+
// wait forever, and as the oldest waiter hold others back. Refused now, unless
|
|
581
|
+
// an outer run or hold already has the resources (it runs inside what that
|
|
582
|
+
// reserved). A size dibs chose is booked at what the machine hands out instead.
|
|
583
|
+
const outer = 'outer' in o ? o.outer : outerLease();
|
|
584
|
+
const nested = !!outer && res.every(r => outer.res?.includes(r));
|
|
585
|
+
const never = !nested && neverFits(cfg, explicitAsk(size));
|
|
586
|
+
if (never) die(neverText(never, null, cfg, await fitsElsewhere(explicitAsk(size))));
|
|
587
|
+
if (!nested) capToMachine(cfg, size);
|
|
588
|
+
const { mem, cpu, disk, asked, askedCpu, usual } = size;
|
|
589
|
+
const grew = grewPlain({ mem, cpu, asked, askedCpu, usual }, key.split('|')[1]);
|
|
590
|
+
if (grew) {
|
|
591
|
+
say(grew);
|
|
592
|
+
// Once per command per agent, through the hook too: an agent that reads only
|
|
593
|
+
// its tool's result still learns that its --mem was overruled, and why its job waits.
|
|
594
|
+
notify({ sessionId: process.env.CLAUDE_CODE_SESSION_ID, who: id.who, agentId: o.agentId }, `sized:${key}:${Math.round(mem / 2 ** 30)}`,
|
|
595
|
+
`${grew} dibs booked it at that, not at what you asked for. To have your own number match, pass --mem ${Math.ceil((usual ?? mem) / 2 ** 30)}G${askedCpu != null ? ` --cpu ${cpu}` : ''}.`);
|
|
596
|
+
}
|
|
597
|
+
// Running the same request again soon after a timed-out wait keeps your place.
|
|
598
|
+
const ticket = `${id.spid || id.who}|${res.join(',')}|${cmd}`;
|
|
599
|
+
const maxWait = o.maxWait ?? defaultMaxWait();
|
|
600
|
+
const pid = o.thin?.shell ?? process.pid;
|
|
601
|
+
const myStart = pstart(pid);
|
|
602
|
+
|
|
603
|
+
const quotaWrong = quotaProblem(cfg, res, o.cost);
|
|
604
|
+
if (quotaWrong) die(quotaWrong);
|
|
605
|
+
const unknown = res.filter(r => !isQuota(r) && !isFiles(r) && !cfg.resources[r] && !hist.some(h => h.key.split('|')[0].split(',').includes(r)));
|
|
606
|
+
if (unknown.length)
|
|
607
|
+
said(`note: ${unknown.join(', ')} isn't a resource dibs knows, so this starts a new queue for it: one job at a time, planned at ${resCfg(cfg, unknown[0]).mem} of memory.`
|
|
608
|
+
+ ` Known: ${Object.keys(cfg.resources).join(', ')}. Use the same name as the other agents, or you'll each have your own queue for one thing.`);
|
|
609
|
+
if (machine().diskFree == null) say("couldn't read free disk space, so the disk check is off for this request.");
|
|
610
|
+
|
|
611
|
+
const started = now();
|
|
612
|
+
const w = waiter({ started, maxWait, waitSet: o.maxWait != null, for: o.for, est: o.est, agentId: o.agentId, sessionId: process.env.CLAUDE_CODE_SESSION_ID,
|
|
613
|
+
cwd: process.cwd(), ppid: callerPid(), sstart: id.sstart, size: { mem, cpu, asked, askedCpu, usual }, again: again(), path: o.thin?.fifo,
|
|
614
|
+
notify: o.notify ? path.resolve(o.notify) : undefined, follow: process.env.DIBS_REMOTE_JOB ? { pid: callerPid(), pstart: pstart(callerPid()) } : undefined }, cfg, hist, stderrOut);
|
|
615
|
+
// A signal while getting in line is held until there's a place to give up,
|
|
616
|
+
// instead of killing this process with its place still on record.
|
|
617
|
+
let early = null;
|
|
618
|
+
// On a full disk the place isn't saved yet, so there's nothing to give up: go at once.
|
|
619
|
+
const hold = sig => { early ||= sig; if (w.full) process.exit(signalExit(sig)); };
|
|
620
|
+
for (const sig of SIGNALS) process.on(sig, hold);
|
|
621
|
+
w.me = await saved(w, s => {
|
|
622
|
+
// Only a place someone left behind can be picked up again, never a live waiter's.
|
|
623
|
+
let q = s.queue.find(x => x.ticket === ticket && !x.pid);
|
|
624
|
+
if (q) { Object.assign(q, { pid, pstart: myStart, keepUntil: null }); delete q.wake; delete q.keptFor; }
|
|
625
|
+
else {
|
|
626
|
+
q = { id: ++s.seq, ticket, res, mem, cpu, disk, asked, askedCpu, usual, pid, pstart: myStart, enq: now(), polledAt: now(),
|
|
627
|
+
who: id.who, agent: id.agent, label: id.label, spid: id.spid, purpose: o.purpose || '', cmd, key, kind,
|
|
628
|
+
agentId: o.agentId, sessionId: process.env.CLAUDE_CODE_SESSION_ID, cwd: process.cwd(), ppid: callerPid(),
|
|
629
|
+
// Its project, for resources one at a time per project (deploys): a job sent from another machine
|
|
630
|
+
// carries its sender's (DIBS_REPO, src/worker.mjs), since its copy here has no .git.
|
|
631
|
+
repo: process.env.DIBS_REPO || projectKey(process.cwd()) };
|
|
632
|
+
if (outer) q.outer = outer.id;
|
|
633
|
+
if (sent) q.sent = true; // placed here by the coordinator for its size (neverFits)
|
|
634
|
+
s.queue.push(q);
|
|
635
|
+
}
|
|
636
|
+
// Without -m, a wait for the rest of what a ship needs says what the ship is for.
|
|
637
|
+
if (!q.purpose) q.purpose = holdingOf(s, q, cfg)?.purpose || '';
|
|
638
|
+
if (o.prio && !q.owner) q.prio = o.prio; // a place picked up again keeps the owner's word on it
|
|
639
|
+
capWaiter(s, q);
|
|
640
|
+
if (o.by) q.by = o.by;
|
|
641
|
+
if (o.est) q.est = o.est;
|
|
642
|
+
if (o.cost != null) q.cost = o.cost;
|
|
643
|
+
if (o.mem != null) q.declared = true; // a size to go on before dibs has measured it (src/overlap.mjs)
|
|
644
|
+
if (o.cpu != null) q.cpuDeclared = true; // asked for in so many words, which alone can make it never fit (neverFits)
|
|
645
|
+
if (o.disk != null) q.diskDeclared = true; // its own word on the disk it writes beats what earlier runs seemed to eat
|
|
646
|
+
return { ...q };
|
|
647
|
+
});
|
|
648
|
+
const me = w.me;
|
|
649
|
+
|
|
650
|
+
if (me.owner?.act === 'cap') say(`the person at this machine capped ${me.agent || me.who}'s work at ${me.prio} priority, so this waits and runs at ${me.prio}, not ${me.askedPrio}.`);
|
|
651
|
+
|
|
652
|
+
const bail = sig => { left(w, sig); leave(w, false); process.exit(signalExit(sig)); };
|
|
653
|
+
for (const sig of SIGNALS) { process.removeListener(sig, hold); process.on(sig, bail); }
|
|
654
|
+
if (early) bail(early);
|
|
655
|
+
|
|
656
|
+
let cfgAt = configAt(), first = true;
|
|
657
|
+
const code = codeNow();
|
|
658
|
+
for (;;) {
|
|
659
|
+
// A release changed the code: this wait carries on as the new dibs, in its
|
|
660
|
+
// place, as a thin waiter's broker does (src/broker.mjs). On 2026-10-20
|
|
661
|
+
// waiters started before 0.0.134 kept judging memory by the old rules for
|
|
662
|
+
// hours, while every fix went out.
|
|
663
|
+
if (code && codeNow() !== code) return rerun(w, bail);
|
|
664
|
+
// The first look skips reading the process table (ps, 30 to 60 ms on a busy Mac,
|
|
665
|
+
// twice for a thin wait): it's for marking idle runs and noticing stuck ones, which
|
|
666
|
+
// matter to a job that waits, and a job that can start now doesn't. The next poll does both.
|
|
667
|
+
const alone = first;
|
|
668
|
+
first = false;
|
|
669
|
+
if (!alone) {
|
|
670
|
+
processes(); // read the process table before taking the lock, not while holding it
|
|
671
|
+
noticeScan(); // a waiter is who notices a job ahead of it is stuck: tell that job's agent (src/notices.mjs)
|
|
672
|
+
}
|
|
673
|
+
// A budget changed while this waits counts, as it does for the broker's waiters.
|
|
674
|
+
const at = configAt();
|
|
675
|
+
if (at !== cfgAt) { cfgAt = at; w.cfg = freshConfig() || w.cfg; }
|
|
676
|
+
const r = await saved(w, s => { if (!alone) markIdle(s); return decide(s, w); });
|
|
677
|
+
const x = step(r, w);
|
|
678
|
+
if (x?.ship) {
|
|
679
|
+
// A thin call can't wait on the coordinator: the shell waits in Node instead, keeping its place, and asks there.
|
|
680
|
+
// One already in Node (src/broker.mjs inlineCall) just carries on here.
|
|
681
|
+
if (o.thin?.inline) o.thin = null;
|
|
682
|
+
if (o.thin) return o.thin.fat();
|
|
683
|
+
const to = await loadShipTarget(me, cfg, w.info.cwd, { temp: MEMORY_HELD.has(x.ship) });
|
|
684
|
+
if (to) return shipTo(w, to, bail, x.ship);
|
|
685
|
+
} else if (x) {
|
|
686
|
+
for (const sig of SIGNALS) process.removeListener(sig, bail);
|
|
687
|
+
if (o.thin) o.thin.go(x.lease);
|
|
688
|
+
return x.lease;
|
|
689
|
+
}
|
|
690
|
+
if (o.thin) {
|
|
691
|
+
const r = o.thin.wait(w);
|
|
692
|
+
if (r !== 'stay') return r;
|
|
693
|
+
o.thin = null; // couldn't go back to the shell: wait here, in Node
|
|
694
|
+
}
|
|
695
|
+
await nextPoll(started);
|
|
696
|
+
}
|
|
697
|
+
}
|