@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/admin.mjs ADDED
@@ -0,0 +1,145 @@
1
+ // dibs invite, kick and limit: run on the coordinator's machine, which is the
2
+ // only one whose token may change who is in the group. An invited machine
3
+ // runs commands for every other one, so each change is logged with who made it.
4
+ import fs from 'node:fs';
5
+ import { remoteConf, call, LOST, REMOTE } from './remote.mjs';
6
+ import { logChange } from './owner.mjs';
7
+ import { NAME, loadRegistry } from './trust.mjs';
8
+ import { removeService } from './service.mjs';
9
+ import { die, dur, now } from './util.mjs';
10
+
11
+ // ok: whether the reply is what a dibs coordinator sends. Anything else on the
12
+ // port (another program, an older dibs) is said plainly, not printed as "undefined".
13
+ async function admin(route, body, ok) {
14
+ const rc = remoteConf();
15
+ if (!rc) die('this machine runs no coordinator. Run this on the machine that does (dibs service install serve)');
16
+ let r;
17
+ try { r = await call(rc, 'POST', route, body, { timeout: 8000 }); }
18
+ catch (e) { die(e.status ? e.message : `can't reach the coordinator at ${rc.url} (${e.message}). Is it running? dibs service status`, e.status ? 2 : LOST); }
19
+ if (!r || typeof r !== 'object' || !ok(r)) die(`${rc.url} answered, but not as a dibs coordinator of this version would. Is the coordinator running there, and up to date? dibs service status`, LOST);
20
+ return r;
21
+ }
22
+
23
+ // dibs invite <name>
24
+ export async function invite(o) {
25
+ const [name] = o.res;
26
+ if (!name || o.res.length > 1) die('dibs invite <name> (the name the machine will go by)');
27
+ const r = await admin('/admin/invite', { name }, r => typeof r.token === 'string' && r.token.length > 0);
28
+ logChange('invite', { machine: name });
29
+ if (r.replaced) console.log(`${name} had a token already. That one stopped working now${r.lost ? `, and ${r.lost} job${r.lost > 1 ? 's' : ''} running there ${r.lost > 1 ? 'were' : 'was'} stopped` : ''}.`);
30
+ console.log(`On ${name}, run:\n\n dibs join ${r.url || remoteConf().url} ${r.token} --name ${name}\n dibs service install worker\n`);
31
+ if (!r.url) console.log(`This coordinator has no Tailscale address yet, so swap ${remoteConf().url} for an address ${name} can reach.`);
32
+ console.log(`Anyone with that line can run commands on your machines as you. Send it only to ${name}. dibs kick ${name} takes it back.`);
33
+ }
34
+
35
+ // dibs kick <name>
36
+ export async function kick(o) {
37
+ const [name] = o.res;
38
+ if (!name || o.res.length > 1) die('dibs kick <name> (dibs machines lists them)');
39
+ const r = await admin('/admin/kick', { name }, r => Number.isInteger(r.lost) && Number.isInteger(r.cancelled));
40
+ logChange('kick', { machine: name });
41
+ const n = (k, what) => `${k} job${k === 1 ? '' : 's'} ${what}`;
42
+ console.log(`removed ${name}: its token no longer works. ${n(r.lost, 'running there')} reported lost to the sender, ${n(r.cancelled, 'it sent')} stopped.`);
43
+ }
44
+
45
+ // dibs limit <name> --only test,heavy | --sends test|none | --any
46
+ export async function limit(o) {
47
+ const [name] = o.res;
48
+ const set = o.only || o.sends;
49
+ if (!name || o.res.length > 1 || (!set === !o.any)) die('dibs limit <machine> --only test,heavy (what it takes) and/or --sends test|none (what it may send) (or --any to lift both)');
50
+ const body = o.any ? { name, only: null, sends: null } : { name, ...(o.only && { only: o.only }), ...(o.sends && { sends: o.sends }) };
51
+ // An older coordinator ignores sends; its reply has no sends field to show it.
52
+ const r = await admin('/admin/limit', body, r => r.name === name && (!('sends' in body) || 'sends' in r));
53
+ logChange('limit', { machine: name, only: r.only || null, sends: r.sends || null });
54
+ if (!r.only && !r.sends) return console.log(`${name} takes any job again, and may send any job`);
55
+ const takes = r.only ? `only takes ${r.only.join(', ')} jobs from other machines` : 'takes any job from other machines';
56
+ const sends = !r.sends ? 'may send any job' : r.sends.length ? `may only send ${r.sends.join(', ')} jobs to other machines` : 'may send no jobs to other machines';
57
+ console.log(`${name} now ${takes}, and ${sends}`);
58
+ }
59
+
60
+ // dibs pair --machine [--name <name>] [--json]: a one-time code a new machine joins with,
61
+ // in one step on that machine: dibs join <code>.
62
+ export async function pairMachine(args) {
63
+ let name = null, json = false;
64
+ for (let i = 0; i < args.length; i++) {
65
+ if (args[i] === '--name') name = args[++i] ?? die('--name needs the name the machine will go by');
66
+ else if (args[i] === '--json') json = true;
67
+ else die(`unknown ${args[i]}. dibs pair --machine [--name <name>]`);
68
+ }
69
+ if (name != null && !NAME.test(name)) die('a machine name is letters, digits, dots, dashes and underscores');
70
+ const r = await admin('/admin/pair', { name }, r => typeof r.code === 'string' && Array.isArray(r.urls));
71
+ logChange('pair machine', { code: r.id, ...(name && { machine: name }) }); // never the code itself
72
+ if (json) return console.log(JSON.stringify(r));
73
+ const out = [r.code, '', `On the new machine${name ? ` (it joins as ${name})` : ''}:`, '', ` dibs join ${r.code}`, ' dibs service install worker', '',
74
+ `One use, good for ${Math.round((r.exp - now()) / 6e4)} minutes. dibs join finds this coordinator on the same network or through Tailscale${r.urls.length ? ` (${r.urls.join(', ')})` : ''};`
75
+ + ' if it can\'t, add --at <this machine\'s address>.'];
76
+ if (!r.urls.length) out.push('This coordinator listens only on this machine for now, so no other machine can reach it. Bring Tailscale up here (it starts listening on it within 30 seconds),'
77
+ + ' or run the coordinator on this machine\'s network address: dibs serve --bind <address>.');
78
+ out.push(`Whoever joins with it can run commands on every machine in the group. dibs pair --list shows it; dibs pair --revoke ${name || '<machine>'} removes a machine that joined.`);
79
+ console.log(out.join('\n'));
80
+ }
81
+
82
+ // The coordinator's open machine codes and its machines, for dibs pair --list and
83
+ // --revoke. null when this machine runs no coordinator; { error } when it can't be reached.
84
+ export async function machinePairs() {
85
+ const rc = remoteConf(() => null);
86
+ if (!rc || !/^http:\/\/(127\.0\.0\.1|localhost)(:|$)/.test(rc.url)) return null;
87
+ try { return await call(rc, 'GET', '/admin/pairs', undefined, { timeout: 3000 }); }
88
+ catch (e) { return { error: e.status ? e.message : `the coordinator at ${rc.url} isn't answering (${e.message})` }; }
89
+ }
90
+ export function pairLines(p) {
91
+ if (!p) return [];
92
+ if (p.error) return [`Machines: ${p.error}`];
93
+ const t = p.now;
94
+ return [
95
+ ...p.codes.map(c => `${c.id} machine code${c.name ? ` for ${c.name}` : ''}, open ${dur(c.exp - t)} more`),
96
+ ...p.machines.map(m => `${m.name.padEnd(8)} machine${m.online ? ', taking jobs' : ''}, ${m.paired ? `joined with a code ${new Date(m.paired).toLocaleString()}` : `invited ${new Date(m.invited).toLocaleString()}`}`),
97
+ ];
98
+ }
99
+ // --revoke <which>: an open code by id, or a machine by name (kicked). all voids every open code
100
+ // and leaves machines in the group: removing them all at once is dibs kick, one by one.
101
+ export async function unpairMachine(which, p) {
102
+ if (!p || p.error) return 0;
103
+ if (which === 'all') return p.codes.length ? (await admin('/admin/unpair', { id: 'all' }, r => Number.isInteger(r.removed))).removed : 0;
104
+ const c = p.codes.find(x => x.id.startsWith(which));
105
+ if (c) return (await admin('/admin/unpair', { id: c.id }, r => Number.isInteger(r.removed))).removed;
106
+ if (p.machines.some(m => m.name === which)) { await kick({ res: [which] }); return 1; }
107
+ return 0;
108
+ }
109
+
110
+ // Whether this machine's remote.json is the coordinator's own: on loopback, and holding the
111
+ // token only the coordinator's machine has (an admin route answers it). A loopback address alone
112
+ // isn't enough: machines joined to a coordinator on the same host (tests, a second DIBS_HOME) have one too.
113
+ // A coordinator that's down can't be asked: on loopback it's taken to be this one.
114
+ async function isCoordinator(rc) {
115
+ if (!/^http:\/\/(127\.0\.0\.1|localhost)(:|$)/.test(rc.url)) return false;
116
+ try { await call(rc, 'GET', '/admin/pairs', undefined, { timeout: 3000 }); return true; }
117
+ catch (e) { return !e.status; }
118
+ }
119
+
120
+ // dibs leave: this machine out of its group. A machine that joined drops its remote.json and
121
+ // stops taking jobs (the worker service, or a worker started by hand). The coordinator only
122
+ // once no other machine is in the group: leaving under them would strand their jobs.
123
+ // Before this, only dibs serve --force got a machine out of a group.
124
+ export async function leave() {
125
+ const rc = remoteConf();
126
+ if (!rc) die("this machine isn't in a group, so there's nothing to leave.", 1);
127
+ const coordinator = await isCoordinator(rc);
128
+ if (coordinator) {
129
+ // Machines it knows by token, and any reporting to it now (one joined with the coordinator's own token isn't in the registry).
130
+ const reg = loadRegistry();
131
+ const names = new Set(Object.entries(reg.machines).filter(([, m]) => m.joined).map(([n]) => n));
132
+ try { for (const m of (await call(rc, 'GET', '/machines', undefined, { timeout: 3000 })).machines || []) names.add(m.name); } catch {}
133
+ // One just kicked can still be listed until its worker next calls in.
134
+ for (const n of [rc.name, ...Object.keys(reg.removed)]) names.delete(n);
135
+ const others = [...names].sort();
136
+ if (others.length) die(`this machine is the group's coordinator, and ${others.join(', ')} ${others.length === 1 ? 'is' : 'are'} still in the group. `
137
+ + `Remove ${others.length === 1 ? 'it' : 'each'} first (${others.map(n => `dibs kick ${n}`).join(', ')}), then dibs leave again. Nothing changed.`);
138
+ }
139
+ logChange('leave', { group: rc.url, as: coordinator ? 'coordinator' : 'member' });
140
+ for (const k of coordinator ? ['worker', 'serve'] : ['worker']) removeService(k);
141
+ fs.rmSync(REMOTE, { force: true });
142
+ console.log(coordinator
143
+ ? "left: this machine is no longer a coordinator, and takes no jobs from other machines. A dibs serve started by hand in a terminal keeps running until you stop it."
144
+ : `left the group at ${rc.url}: this machine takes no more jobs from it. On the coordinator, dibs kick ${rc.name} takes it off the list.`);
145
+ }
package/src/agents.mjs ADDED
@@ -0,0 +1,145 @@
1
+ // How many subagents run at once across every Claude Code session on this
2
+ // machine. Fan-outs that start together hit the account's usage limit together
3
+ // and die mid-edit; with a limit, the spawn past it comes back to the agent as
4
+ // a denied tool call while its other work carries on.
5
+ //
6
+ // The guard hook feeds it three events (https://code.claude.com/docs/en/hooks):
7
+ // PreToolUse on Agent a spawn is coming: keep a slot for it, or deny it
8
+ // SubagentStart the subagent runs: the kept slot becomes its own
9
+ // SubagentStop it finished: its slot frees
10
+ // It keeps its own small file and lock, not state.json's: the hook runs inside
11
+ // a tool call and must not wait behind a busy queue.
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ import { HOME } from './config.mjs';
15
+ import { identity, makeAlive } from './proc.mjs';
16
+ import { now, sleepSync, fakeFull } from './util.mjs';
17
+
18
+ const FILE = path.join(HOME, 'agents.json');
19
+ const LOCK = path.join(HOME, 'agents.lock');
20
+
21
+ // Fan-outs of 5 to 10 at once are what ran into the usage limit together.
22
+ // Eight is the owner's pick: one big fan-out runs nearly whole, and a second
23
+ // session still gets its one (a session with none running always may).
24
+ // A kept slot whose subagent never started (the spawn was refused at a
25
+ // permission prompt, or failed) frees after this.
26
+ const PENDING_FOR = 2 * 6e4;
27
+ // A subagent whose transcript hasn't changed in this long is taken as gone: it
28
+ // was interrupted, and Claude Code sent no stop event. Long enough for a
29
+ // subagent sitting in one long tool call, like a build.
30
+ const QUIET_FOR = 60 * 6e4;
31
+ // The hook gives up on the lock after this and lets the spawn through.
32
+ const LOCK_WAIT = 1000;
33
+ // A lock this old belongs to a hook that died holding it.
34
+ const LOCK_STALE = 5000;
35
+
36
+ // The Agent tool was called Task in older Claude Code.
37
+ const SPAWN_TOOLS = new Set(['Agent', 'Task']);
38
+
39
+ // Off unless the person sets a limit: a cap nobody asked for blocks fan-outs that were fine.
40
+ export const agentSlots = cfg => (Number(cfg?.agents?.slots) > 0 ? Number(cfg.agents.slots) : null);
41
+
42
+ function locked(fn) {
43
+ fs.mkdirSync(HOME, { recursive: true });
44
+ const t0 = now();
45
+ for (;;) {
46
+ try { fs.mkdirSync(LOCK); break; } catch (e) {
47
+ if (e.code !== 'EEXIST') throw e;
48
+ try { if (now() - fs.statSync(LOCK).mtimeMs > LOCK_STALE) fs.rmSync(LOCK, { recursive: true, force: true }); } catch {}
49
+ if (now() - t0 > LOCK_WAIT) throw new Error(`${LOCK} stayed locked for ${LOCK_WAIT} ms`);
50
+ sleepSync(5 + Math.random() * 10);
51
+ }
52
+ }
53
+ try {
54
+ let list = [];
55
+ try { list = JSON.parse(fs.readFileSync(FILE, 'utf8')).agents || []; } catch (e) { if (e.code !== 'ENOENT' && !(e instanceof SyntaxError)) throw e; }
56
+ const before = JSON.stringify(list);
57
+ list = reap(list);
58
+ const out = fn(list);
59
+ if (JSON.stringify(list) !== before) {
60
+ fakeFull('state');
61
+ fs.writeFileSync(`${FILE}.tmp`, JSON.stringify({ agents: list }, null, 1));
62
+ fs.renameSync(`${FILE}.tmp`, FILE);
63
+ }
64
+ return out;
65
+ } finally {
66
+ fs.rmSync(LOCK, { recursive: true, force: true });
67
+ }
68
+ }
69
+
70
+ // Drop kept slots nobody took, subagents of a session that has exited, and
71
+ // ones gone quiet. Changes the list in place.
72
+ function reap(list) {
73
+ const t = now();
74
+ const alive = makeAlive(list.map(a => a.spid));
75
+ const quiet = a => {
76
+ try { return t - fs.statSync(a.transcript).mtimeMs > QUIET_FOR; } catch { return false; }
77
+ };
78
+ const kept = list.filter(a => (a.pending ? t - a.since < PENDING_FOR : true) && (!a.spid || alive(a.spid, a.sstart)) && !(a.transcript && quiet(a)));
79
+ list.splice(0, list.length, ...kept);
80
+ return list;
81
+ }
82
+
83
+ // "web-app x3, you x2"
84
+ function owners(list, session) {
85
+ const n = new Map();
86
+ for (const a of list) {
87
+ const name = a.session === session ? 'you' : a.who;
88
+ n.set(name, (n.get(name) || 0) + 1);
89
+ }
90
+ return [...n].map(([who, k]) => (k > 1 ? `${who} x${k}` : who)).join(', ');
91
+ }
92
+
93
+ function deny(why) {
94
+ return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: why } };
95
+ }
96
+
97
+ // A session may always run one subagent, so a big fan-out elsewhere can't
98
+ // starve it. Past that, spawns wait until the machine is under its limit.
99
+ export function agentHook(input, cfg) {
100
+ const slots = agentSlots(cfg);
101
+ if (slots == null || !input?.session_id) return null;
102
+ const session = input.session_id;
103
+ const event = input.hook_event_name;
104
+ if (event === 'SubagentStop') return locked(list => {
105
+ const i = list.findIndex(a => a.id === input.agent_id);
106
+ if (i >= 0) list.splice(i, 1);
107
+ return null;
108
+ });
109
+ const id = identity();
110
+ const me = { session, spid: id.spid, sstart: id.sstart, who: id.agent || path.basename(input.cwd || '') || 'a session' };
111
+ if (event === 'SubagentStart') {
112
+ // Internal agents (prompt suggestions, /btw) have no type; they were never counted.
113
+ if (!input.agent_id || !input.agent_type) return null;
114
+ return locked(list => {
115
+ const kept = list.findIndex(a => a.pending && a.session === session);
116
+ if (kept >= 0) list.splice(kept, 1);
117
+ const at = list.findIndex(a => a.id === input.agent_id);
118
+ if (at >= 0) list.splice(at, 1);
119
+ const transcript = input.transcript_path && `${input.transcript_path.replace(/\.jsonl$/, '')}/subagents/agent-${input.agent_id}.jsonl`;
120
+ list.push({ ...me, id: input.agent_id, type: input.agent_type, since: now(), ...(transcript ? { transcript } : {}) });
121
+ return null;
122
+ });
123
+ }
124
+ if (!SPAWN_TOOLS.has(input.tool_name)) return null;
125
+ return locked(list => {
126
+ const mine = list.filter(a => a.session === session).length;
127
+ if (list.length >= slots && mine > 0)
128
+ return deny(`dibs: ${list.length} subagents are running on this machine and the limit is ${slots} (${owners(list, session)}). `
129
+ + `Nothing was started. ${mine} of them ${mine === 1 ? 'is' : 'are'} yours: wait until one reports back, then spawn this one again, or do this part yourself. `
130
+ + 'Too many at once hit the account\'s usage limit together and die mid-edit. See them all with: dibs');
131
+ const ti = input.tool_input || {};
132
+ list.push({ ...me, id: input.tool_use_id || `spawn-${now()}`, pending: true, type: ti.subagent_type || null,
133
+ desc: String(ti.description || '').slice(0, 60), since: now() });
134
+ return null;
135
+ });
136
+ }
137
+
138
+ // For the board: who runs how many subagents, and the limit.
139
+ export function agentsNow(cfg) {
140
+ const slots = agentSlots(cfg);
141
+ if (slots == null) return null;
142
+ let list = [];
143
+ try { list = locked(l => [...l]); } catch {}
144
+ return { slots, running: list.map(a => ({ who: a.who, type: a.type || null, for: now() - a.since, starting: !!a.pending })) };
145
+ }