@dibssoftware/dibs 0.0.0-stage → 0.0.179

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/CHANGELOG.md +594 -0
  2. package/LICENSE +670 -0
  3. package/README.md +85 -2
  4. package/bin/dibs-guard.mjs +7 -0
  5. package/bin/dibs.mjs +548 -0
  6. package/docs/benchmarks.md +193 -0
  7. package/docs/files.md +30 -0
  8. package/docs/guard.md +91 -0
  9. package/docs/later.md +43 -0
  10. package/docs/machines.md +147 -0
  11. package/docs/questions.md +78 -0
  12. package/docs/reference.md +157 -0
  13. package/docs/relay.md +196 -0
  14. package/docs/releasing.md +27 -0
  15. package/docs/scheduling.md +163 -0
  16. package/docs/simulators.md +17 -0
  17. package/package.json +45 -4
  18. package/skills/dibs/SKILL.md +183 -0
  19. package/src/acquire.mjs +700 -0
  20. package/src/admin.mjs +145 -0
  21. package/src/agents.mjs +145 -0
  22. package/src/alerts.mjs +499 -0
  23. package/src/answers.mjs +65 -0
  24. package/src/board.mjs +202 -0
  25. package/src/broker.mjs +369 -0
  26. package/src/commands.mjs +810 -0
  27. package/src/config.mjs +324 -0
  28. package/src/connect.mjs +106 -0
  29. package/src/cool.mjs +160 -0
  30. package/src/diskwarn.mjs +154 -0
  31. package/src/events.mjs +96 -0
  32. package/src/files.mjs +1123 -0
  33. package/src/guard.mjs +613 -0
  34. package/src/history.mjs +247 -0
  35. package/src/hogs.mjs +227 -0
  36. package/src/later.mjs +487 -0
  37. package/src/measure.mjs +262 -0
  38. package/src/news.mjs +101 -0
  39. package/src/nodecheck.mjs +17 -0
  40. package/src/notes.mjs +171 -0
  41. package/src/notices.mjs +160 -0
  42. package/src/ondemand.mjs +572 -0
  43. package/src/overlap.mjs +151 -0
  44. package/src/override.mjs +360 -0
  45. package/src/owner.mjs +30 -0
  46. package/src/plain.mjs +470 -0
  47. package/src/platform.mjs +357 -0
  48. package/src/preempt.mjs +438 -0
  49. package/src/primer.mjs +89 -0
  50. package/src/proc.mjs +99 -0
  51. package/src/progress.mjs +187 -0
  52. package/src/qr.mjs +204 -0
  53. package/src/questions.mjs +389 -0
  54. package/src/quota.mjs +81 -0
  55. package/src/reads.mjs +54 -0
  56. package/src/relay.mjs +779 -0
  57. package/src/remote.mjs +584 -0
  58. package/src/reset.mjs +127 -0
  59. package/src/schedule.mjs +1020 -0
  60. package/src/scratch.mjs +61 -0
  61. package/src/serve.mjs +742 -0
  62. package/src/service.mjs +221 -0
  63. package/src/shard.mjs +59 -0
  64. package/src/simctl.mjs +42 -0
  65. package/src/simpool.mjs +258 -0
  66. package/src/state.mjs +201 -0
  67. package/src/stats.mjs +328 -0
  68. package/src/style.mjs +44 -0
  69. package/src/talk.mjs +702 -0
  70. package/src/thin.sh +130 -0
  71. package/src/trust.mjs +152 -0
  72. package/src/util.mjs +184 -0
  73. package/src/version.mjs +2 -0
  74. package/src/web.mjs +1119 -0
  75. package/src/worker.mjs +318 -0
@@ -0,0 +1,389 @@
1
+ // Questions for the person who runs the agents. Their attention is the
2
+ // scarcest thing on the machine, so agents queue for it like any resource:
3
+ // `dibs question` records one, the person answers when they get to it, and an
4
+ // agent that can't go on without the answer waits for it with --wait.
5
+ //
6
+ // Only one-way doors reach the person. Every question carries the asker's
7
+ // recommendation and why (--recommend, -m). Without --one-way "what can't be
8
+ // undone", it's a two-way door: dibs answers at once with the recommendation,
9
+ // logs the decision, and shows it to the person as done, to overrule with a
10
+ // message if they like. The person's standing rule: walk through two-way
11
+ // doors, bring them only what can't be undone.
12
+ //
13
+ // Questions keep their own file and lock, not state.json's: the Mac app polls
14
+ // them often, and they never decide who runs next, so there's no reason to
15
+ // queue behind every waiter's lock.
16
+ import fs from 'node:fs';
17
+ import path from 'node:path';
18
+ import { HOME, paths, loadConfig } from './config.mjs';
19
+ import { identity, isMine, makeAlive, pstart, tag } from './proc.mjs';
20
+ import { actor, logChange } from './owner.mjs';
21
+ import { KEEP_PLACE } from './state.mjs';
22
+ import { PRIORITY_SHIFT, PRIORITIES, priority } from './schedule.mjs';
23
+ import { defaultMaxWait } from './acquire.mjs';
24
+ import { event } from './events.mjs';
25
+ import { takeAgent, talkKey } from './files.mjs';
26
+ import { messageAsker } from './talk.mjs';
27
+ import { clock, die, dur, ms, now, say, sleep, sleepSync, fakeFull } from './util.mjs';
28
+ import { bold, dim, amber, wrap } from './style.mjs';
29
+
30
+ const FILE = path.join(HOME, 'questions.json');
31
+ const LOCK = path.join(HOME, 'questions.lock');
32
+ // Writes take milliseconds, so a lock this old belongs to a dibs that died holding it.
33
+ const LOCK_STALE = 5000;
34
+ const LOCK_WAIT = 15e3;
35
+ // A waiting asker looks for its answer this often. A person reads the answer
36
+ // back slower than this, and each look is one small file read.
37
+ const POLL = 1000;
38
+ // Answered, dismissed and expired questions stay this long for the app's
39
+ // list, up to KEEP_DONE of them.
40
+ const DONE_FOR = 7 * 24 * 36e5;
41
+ const KEEP_DONE = 200;
42
+ // The plain list shows this many of the most recent closed questions.
43
+ const RECENT = 5;
44
+
45
+ const OPEN = 'open';
46
+ const DECIDED = 'decided';
47
+
48
+ function locked(fn) {
49
+ fs.mkdirSync(HOME, { recursive: true });
50
+ const t0 = now();
51
+ for (;;) {
52
+ try { fs.mkdirSync(LOCK); break; } catch (e) {
53
+ if (e.code !== 'EEXIST') throw e;
54
+ try { if (now() - fs.statSync(LOCK).mtimeMs > LOCK_STALE) fs.rmSync(LOCK, { recursive: true, force: true }); } catch {}
55
+ if (now() - t0 > LOCK_WAIT) die(`${LOCK} stayed locked for ${LOCK_WAIT / 1000}s; remove it if no dibs is running. Nothing was changed.`, 75);
56
+ sleepSync(5 + Math.random() * 10);
57
+ }
58
+ }
59
+ try {
60
+ const s = load();
61
+ const before = JSON.stringify(s);
62
+ reap(s);
63
+ const out = fn(s);
64
+ if (JSON.stringify(s) !== before) {
65
+ fakeFull('state');
66
+ fs.writeFileSync(`${FILE}.tmp`, JSON.stringify(s, null, 1));
67
+ fs.renameSync(`${FILE}.tmp`, FILE);
68
+ }
69
+ return out;
70
+ } finally {
71
+ fs.rmSync(LOCK, { recursive: true, force: true });
72
+ }
73
+ }
74
+
75
+ // Writes are renames, so reading without the lock always sees a whole file.
76
+ function load() {
77
+ let s = {};
78
+ try { s = JSON.parse(fs.readFileSync(FILE, 'utf8')); } catch (e) {
79
+ if (e.code !== 'ENOENT') say(`${FILE} was unreadable (${e.message}); starting with no questions.`);
80
+ }
81
+ s.seq ||= 0; s.questions ||= [];
82
+ return s;
83
+ }
84
+
85
+ // Close questions nobody is left to read the answer of. One asked with --wait
86
+ // belongs to its waiting process, and expires when that dies. A wait that gave
87
+ // up at its limit keeps the question open KEEP_PLACE for the same command to
88
+ // pick back up, as a waiter's place in line does. One asked without --wait
89
+ // belongs to the agent session that asked, and lasts until --timeout if it says.
90
+ function reap(s, t = now()) {
91
+ const open = s.questions.filter(q => q.state === OPEN);
92
+ const alive = makeAlive(open.flatMap(q => [q.pid, q.spid]).filter(Boolean));
93
+ for (const q of open) {
94
+ if (q.pid && !alive(q.pid, q.pstart)) q.pid = null;
95
+ const gone = q.waits ? !q.pid && !(q.keepUntil && t < q.keepUntil)
96
+ : (q.spid && !alive(q.spid, q.sstart)) || (!q.pid && q.due && t >= q.due);
97
+ if (gone) Object.assign(q, { state: 'expired', answeredAt: t });
98
+ }
99
+ const done = s.questions.filter(q => q.state !== OPEN && t - (q.answeredAt || q.asked) < DONE_FOR).slice(-KEEP_DONE);
100
+ s.questions = s.questions.filter(q => q.state === OPEN || done.includes(q));
101
+ }
102
+
103
+ // "09:00" -> minutes since midnight, or null.
104
+ function readTime(hhmm) {
105
+ const m = String(hhmm).match(/^(\d{1,2}):(\d{2})$/);
106
+ return m && Number(m[1]) <= 23 && Number(m[2]) <= 59 ? Number(m[1]) * 60 + Number(m[2]) : null;
107
+ }
108
+ function minutes(hhmm) {
109
+ return readTime(hhmm) ?? die(`hours in config.json are {"start": "09:00", "end": "23:00"}; can't read "${hhmm}". Fix them: dibs hours 09:00-23:00`);
110
+ }
111
+
112
+ // The person's working hours from config, or null when every hour is.
113
+ export function hours(cfg) {
114
+ if (!cfg.hours) return null;
115
+ minutes(cfg.hours.start); minutes(cfg.hours.end);
116
+ return { start: cfg.hours.start, end: cfg.hours.end };
117
+ }
118
+
119
+ // Outside working hours, questions below urgent are held for the morning:
120
+ // they're kept, just not counted as needing the person now. A window whose end
121
+ // comes before its start runs past midnight.
122
+ export function offHours(cfg, t = now()) {
123
+ const h = hours(cfg);
124
+ if (!h) return false;
125
+ const d = new Date(t), at = d.getHours() * 60 + d.getMinutes();
126
+ const a = minutes(h.start), b = minutes(h.end);
127
+ return a <= b ? at < a || at >= b : at < a && at >= b;
128
+ }
129
+ const held = (q, cfg, t) => q.state === OPEN && q.prio !== 'urgent' && offHours(cfg, t);
130
+
131
+ // The same idea as the queue's rank: arrival time, moved by priority.
132
+ const rank = q => q.asked - (PRIORITY_SHIFT[q.prio] || 0);
133
+ // Open ones first, the ones for now before the held ones, then the closed ones newest first.
134
+ function ordered(list, cfg, t) {
135
+ const open = list.filter(q => q.state === OPEN).sort((a, b) => held(a, cfg, t) - held(b, cfg, t) || rank(a) - rank(b) || a.id - b.id);
136
+ const closed = list.filter(q => q.state !== OPEN).sort((a, b) => (b.answeredAt || 0) - (a.answeredAt || 0));
137
+ return [...open, ...closed];
138
+ }
139
+
140
+ // What the app and `dibs questions --json` see: no pids, and held as a flag.
141
+ const shown = (q, cfg, t) => ({
142
+ id: q.id, who: q.who, agent: q.agent, session: q.session, text: q.text, options: q.options, prio: q.prio, purpose: q.purpose,
143
+ asked: q.asked, due: q.due, state: q.state, answer: q.answer, answeredAt: q.answeredAt, answeredBy: q.answeredBy, waiting: !!q.pid, held: held(q, cfg, t),
144
+ recommend: q.recommend ?? null, why: q.purpose || null, oneWay: !!q.oneWay, cantUndo: q.cantUndo ?? null, freeText: !!q.freeText,
145
+ });
146
+
147
+ // What `dibs questions --json` prints. dibs web reads it without the lock, as forYou does.
148
+ export function questionsJson(cfg, t = now(), list = ordered(asked(t).map(q => ({ ...q })), cfg, t)) {
149
+ return { questions: list.map(q => shown(q, cfg, t)), hours: hours(cfg), open: list.filter(q => q.state === OPEN).length };
150
+ }
151
+
152
+ // For the board: open questions the person should look at now. Read without
153
+ // the lock, so plain `dibs` never waits on it; the reaping here isn't saved.
154
+ export function forYou(cfg, t = now()) {
155
+ return asked(t).filter(q => q.state === OPEN && !held(q, cfg, t)).length;
156
+ }
157
+
158
+ // Every question kept, read the same way: for the agents' threads (src/talk.mjs).
159
+ export function asked(t = now()) {
160
+ const s = load();
161
+ reap(s, t);
162
+ return s.questions;
163
+ }
164
+
165
+ function parseAsk(args) {
166
+ const o = { words: [] };
167
+ for (let i = 0; i < args.length; i++) {
168
+ const a = args[i], next = () => args[++i] ?? die(`${a} needs a value`);
169
+ if (a === '--options') { o.options = next().split(',').map(x => x.trim()).filter(Boolean); if (o.options.length < 2) die('--options takes two or more choices, e.g. --options yes,no'); }
170
+ else if (a === '-p' || a === '--priority') { o.prio = priority(next()); if (!(o.prio in PRIORITY_SHIFT)) die(`priority is one of ${PRIORITIES.join(', ')} (or 1-5)`); }
171
+ else if (a === '-m' || a === '--msg') o.purpose = next();
172
+ else if (a === '--recommend') o.recommend = next().trim();
173
+ else if (a === '--one-way') o.oneWay = next().trim();
174
+ else if (a === '--timeout') o.timeout = ms(next());
175
+ else if (a === '--wait') o.wait = true;
176
+ else if (a === '--as') o.as = next();
177
+ else if (a.startsWith('-') && a.length > 1) die(`unknown flag ${a}. Every flag: dibs help all`);
178
+ else o.words.push(a);
179
+ }
180
+ o.text = o.words.join(' ').trim();
181
+ return o;
182
+ }
183
+
184
+ // Real words: a short sentence, not "2" or "ok". On 2026-10-18 a question that
185
+ // read, in full, "2" reached the person.
186
+ const MIN_WORDS = 3;
187
+ const realWords = text => text.split(/\s+/).filter(w => /\p{L}{2,}/u.test(w)).length >= MIN_WORDS;
188
+ const USE = 'dibs question "Ship build 123 to TestFlight now?" --options yes,no --recommend yes -m "tests pass, notes written" --one-way "a TestFlight build can\'t be pulled from testers" --wait';
189
+
190
+ // What's wrong with a question as asked, or null. Refused before anything is recorded.
191
+ function junk(o) {
192
+ if (!o.text) return `ask what? ${USE}`;
193
+ if (!realWords(o.text)) return `"${o.text}" isn't a question anyone can answer: write it out in a short sentence of at least ${MIN_WORDS} words. Nothing was asked. ${USE}`;
194
+ if (!o.recommend) return `say what you'd do: --recommend <option>, with -m "why". Without --one-way that's what happens, at once. Nothing was asked. ${USE}`;
195
+ if (!o.purpose) return `say why you recommend ${o.recommend}: -m "why". Nothing was asked.`;
196
+ if (o.options) {
197
+ const seen = new Set(o.options.map(x => x.toLowerCase()));
198
+ if (seen.size !== o.options.length) return `--options has the same choice twice (${o.options.join(', ')}). Nothing was asked.`;
199
+ if (!seen.has(o.recommend.toLowerCase())) return `--recommend ${o.recommend} isn't one of the --options (${o.options.join(', ')}). Nothing was asked.`;
200
+ }
201
+ if (o.oneWay != null && !realWords(o.oneWay)) return `--one-way says what can't be undone, in a short sentence ("deleting the branch loses 3 unmerged commits"), not "${o.oneWay}". Nothing was asked.`;
202
+ return null;
203
+ }
204
+
205
+ // dibs question "text" --recommend <option> -m why [--one-way "what can't be undone"] [--options a,b] [-p prio] [--wait] [--timeout 2h]
206
+ export async function question(args, cfg) {
207
+ const o = parseAsk(args);
208
+ const bad = junk(o);
209
+ if (bad) die(bad);
210
+ if (o.options) o.recommend = o.options.find(x => x.toLowerCase() === o.recommend.toLowerCase());
211
+ const id = identity(o);
212
+ const limit = o.wait ? o.timeout ?? defaultMaxWait() : o.timeout ?? Infinity;
213
+ const t = now();
214
+ const due = limit === Infinity ? null : t + limit;
215
+ // The same question from the same asker, still open or with an answer it
216
+ // hasn't read, is that one again: asking without --wait and later with it
217
+ // collects the answer, and a wait that gave up picks its question back up.
218
+ const q = locked(s => {
219
+ let q = s.questions.find(x => x.text === o.text && isMine(x, id) && (x.state === OPEN || x.state === DECIDED || (!x.collected && x.state !== 'expired')));
220
+ if (!q) {
221
+ // Which of the session's agents asked, when the guard saw it, so the question lands in that agent's thread.
222
+ const by = process.env.CLAUDE_CODE_SESSION_ID ? takeAgent('question', [], talkKey('question', args)) : null;
223
+ q = { id: ++s.seq, who: id.who, agent: id.agent, label: id.label || by?.agentType || '', session: process.env.CLAUDE_CODE_SESSION_ID || null,
224
+ agentId: by?.agentId || null,
225
+ spid: id.spid, sstart: id.sstart, text: o.text, options: o.options || null, prio: o.prio || 'normal', purpose: o.purpose || '',
226
+ asked: t, due, state: OPEN, answer: null, answeredAt: null, waits: !!o.wait, recommend: o.recommend,
227
+ oneWay: o.oneWay != null, cantUndo: o.oneWay ?? null };
228
+ // A two-way door: nobody is asked. The recommendation is the answer, now.
229
+ if (!q.oneWay) Object.assign(q, { state: DECIDED, answer: o.recommend, answeredAt: t, decidedBy: id.agent || id.who, collected: true });
230
+ s.questions.push(q);
231
+ } else if (q.state === OPEN) {
232
+ if (o.prio) q.prio = o.prio;
233
+ if (o.options) q.options = o.options;
234
+ if (o.purpose) q.purpose = o.purpose;
235
+ // A session's question keeps its own --timeout; a later wait's limit is only the wait's.
236
+ // (It once took the wait's --timeout as its own, so asking, then collecting with --wait
237
+ // --timeout 1m, expired the question the moment that wait gave up.)
238
+ if ((!o.wait && o.timeout != null) || (o.wait && q.waits)) q.due = due;
239
+ }
240
+ if (o.wait && q.state === OPEN) Object.assign(q, { pid: process.pid, pstart: pstart(process.pid), keepUntil: null });
241
+ return { ...q };
242
+ });
243
+ if (q.state === DECIDED) {
244
+ if (q.asked === t) event({ kind: 'override', act: 'decided', question: q.id, who: tag(q), answer: q.answer, why: q.purpose, by: q.decidedBy, byAgent: true });
245
+ say(`decided by ${q.decidedBy}: two-way door, so nobody was asked. Go ahead with ${q.answer}. It's logged, and the person sees it as done; they'll message you if they want it otherwise.`
246
+ + ' Bring a question to the person only when it can\'t be undone: --one-way "what can\'t be undone".');
247
+ console.log(q.answer);
248
+ return;
249
+ }
250
+ if (!o.wait) {
251
+ console.log(q.id);
252
+ if (q.state === OPEN)
253
+ say(`question ${q.id} is queued for the person${heldNote(q, cfg)}. Keep working; to get the answer, run the same command with --wait.`);
254
+ else say(`question ${q.id} was already ${q.state}${q.answer != null ? `: ${q.answer}` : ''}. Run the same command with --wait to read the answer.`);
255
+ return;
256
+ }
257
+ say(`waiting for the person to answer question ${q.id}${heldNote(q, cfg)}. ${waitTerms(o, limit, t)}`);
258
+ for (;;) {
259
+ const cur = load().questions.find(x => x.id === q.id);
260
+ if (cur?.state === 'answered') {
261
+ locked(s => { const x = s.questions.find(x => x.id === q.id); if (x) x.collected = true; });
262
+ // stdout stays the bare answer; who gave it goes beside it.
263
+ if (cur.answeredBy) say(`answered by ${cur.answeredBy}, an agent, not the person.`);
264
+ console.log(cur.answer);
265
+ return;
266
+ }
267
+ if (!cur || cur.state !== OPEN) {
268
+ locked(s => { const x = s.questions.find(x => x.id === q.id); if (x) x.collected = true; });
269
+ die(`question ${q.id} was ${cur ? cur.state : 'removed'} without an answer. Nothing was decided: carry on without it, or ask differently.`, 75);
270
+ }
271
+ if (due && now() >= due) {
272
+ // Let go, but keep the question open long enough for a rerun to find it.
273
+ locked(s => { const x = s.questions.find(x => x.id === q.id && x.pid === process.pid); if (x) Object.assign(x, { pid: null, keepUntil: now() + KEEP_PLACE }); });
274
+ die(`no answer to question ${q.id} by ${clock(due)} (exit 75: nothing was decided). ${q.waits ? 'It stays open 2 minutes' : 'It stays open for the person'}: run the same command again to keep waiting.`, 75);
275
+ }
276
+ await sleep(POLL);
277
+ }
278
+ }
279
+
280
+ const heldNote = (q, cfg) => (held(q, cfg, now()) ? ` (it's outside the person's hours, ${cfg.hours.start} to ${cfg.hours.end}, so it waits for ${cfg.hours.start} unless it's urgent)` : '');
281
+
282
+ function waitTerms(o, limit, t) {
283
+ if (limit === Infinity)
284
+ return o.timeout == null
285
+ ? "No time limit. If this tool call reaches its timeout, Claude Code moves it to the background and tells you when the answer comes. Don't ask again meanwhile."
286
+ : 'No time limit.';
287
+ return `This wait gives up at ${clock(t + limit)} with exit 75.`;
288
+ }
289
+
290
+ // dibs questions [--json] | dibs questions dismiss <id>
291
+ export function questions(args, cfg) {
292
+ if (args[0] === 'dismiss') return dismiss(args.slice(1));
293
+ const json = args.includes('--json');
294
+ const bad = args.find(a => a !== '--json');
295
+ if (bad) die(`unknown ${bad.startsWith('-') ? 'flag' : 'word'} ${bad}. Try: dibs questions [--json], dibs questions dismiss <id>`);
296
+ const t = now();
297
+ const list = ordered(locked(s => s.questions.map(q => ({ ...q }))), cfg, t);
298
+ if (json) return console.log(JSON.stringify(questionsJson(cfg, t, list), null, 1));
299
+ const open = list.filter(q => q.state === OPEN);
300
+ const later = open.filter(q => held(q, cfg, t)).length;
301
+ const out = [bold(open.length ? `${open.length} open question${open.length > 1 ? 's' : ''}${later ? ` (${later} held until ${cfg.hours.start})` : ''}, most urgent first.` : 'No open questions.')];
302
+ for (const q of open) {
303
+ const flags = [q.prio !== 'normal' ? q.prio : '', q.pid ? 'an agent is waiting on it' : '', held(q, cfg, t) ? 'for tomorrow' : ''].filter(Boolean).join(', ');
304
+ out.push('', ` #${q.id} ${tag(q)} asked ${dur(t - q.asked)} ago${flags ? amber(` [${flags}]`) : ''}`);
305
+ out.push(wrap(` ${q.text}${q.options ? ` (${q.options.join(' / ')})` : ''}`, ' '));
306
+ if (q.recommend) out.push(wrap(` They recommend ${q.recommend}${q.purpose ? `: ${q.purpose}` : ''}`, ' '));
307
+ else if (q.purpose) out.push(dim(wrap(` ${q.purpose}`, ' ')));
308
+ if (q.cantUndo) out.push(amber(wrap(` Can't be undone: ${q.cantUndo}`, ' ')));
309
+ }
310
+ if (open.length) {
311
+ const q = open[0];
312
+ out.push('', `Answer: dibs answer ${q.id} ${q.recommend || (q.options ? q.options[0] : '"..."')} (or your own words) Dismiss: dibs questions dismiss ${q.id}`);
313
+ }
314
+ const closed = list.filter(q => q.state !== OPEN).slice(0, RECENT);
315
+ if (closed.length) out.push('', 'Recently closed');
316
+ for (const q of closed)
317
+ out.push(dim(` #${q.id} ${q.state}${q.answer != null ? ` "${q.answer}"` : ''} ${dur(t - q.answeredAt)} ago, ${tag(q)}: ${q.text}`));
318
+ console.log(out.join('\n'));
319
+ }
320
+
321
+ // Close an open question as the person: answer or dismiss it. change returns
322
+ // a reason the answer won't do, if it won't. Refusals die after the lock is
323
+ // let go: process.exit skips the finally that would let it go.
324
+ function close(idArg, verb, change) {
325
+ const n = Number(idArg);
326
+ if (!idArg || !Number.isInteger(n)) die(`which question? dibs ${verb} <id> (the ids: dibs questions)`);
327
+ const who = actor();
328
+ const r = locked(s => {
329
+ const q = s.questions.find(x => x.id === n);
330
+ if (!q) return { no: [`no question ${n}. See them: dibs questions`, 1] };
331
+ if (q.state !== OPEN) return { no: [`question ${n} is already ${q.state}${q.answer != null ? ` ("${q.answer}")` : ''}`, 1] };
332
+ const no = change(q);
333
+ if (no) return { no: [no, 2] };
334
+ q.answeredAt = now();
335
+ if (who.agent && q.state === 'answered') q.answeredBy = who.name;
336
+ return { q: { ...q } };
337
+ });
338
+ if (r.no) die(...r.no);
339
+ // The history shows these decisions next to the other overrides, with who made them.
340
+ event({ kind: 'override', act: verb.split(' ').pop(), question: n, who: tag(r.q), answer: r.q.answer, by: who.name, byAgent: who.agent });
341
+ return r.q;
342
+ }
343
+
344
+ // dibs answer <id> <text>: one of its options, or any words. Words that pick
345
+ // no option are the answer too, and reach the asker as a message as well, so
346
+ // the person can reply in words instead of picking.
347
+ export function answer(args) {
348
+ const [idArg, ...rest] = args;
349
+ const text = rest.join(' ').trim();
350
+ if (!text) die('answer with what? dibs answer <id> <text>');
351
+ const q = close(idArg, 'answer', q => {
352
+ const a = q.options?.find(x => x.toLowerCase() === text.toLowerCase());
353
+ Object.assign(q, { state: 'answered', answer: a ?? text, ...(a == null && { freeText: true }) });
354
+ });
355
+ if (q.freeText) messageAsker(q, q.answer);
356
+ console.log(`answered question ${q.id} for ${tag(q)}: ${q.answer}${q.pid ? '' : q.freeText ? '. It reaches them as a message too, with their next tool call.' : ". They aren't waiting on it now; they'll get it when they ask again."}`);
357
+ }
358
+
359
+ function dismiss(args) {
360
+ const q = close(args[0], 'questions dismiss', q => { q.state = 'dismissed'; });
361
+ console.log(`dismissed question ${q.id} from ${tag(q)}`);
362
+ }
363
+
364
+ // dibs hours [09:00-23:00 | off] [--json]: show or set the person's working hours.
365
+ export function hoursCmd(args, cfg) {
366
+ const json = args.includes('--json');
367
+ const word = args.find(a => a !== '--json');
368
+ if (args.some(a => a.startsWith('-') && a !== '--json')) die('dibs hours takes 09:00-23:00, off, or --json');
369
+ if (word) {
370
+ let set = null;
371
+ if (word !== 'off') {
372
+ const [start, end, extra] = word.split('-');
373
+ if (extra != null || readTime(start) == null || readTime(end) == null || readTime(start) === readTime(end))
374
+ die(`can't read hours "${word}". Use: dibs hours 09:00-23:00 (an end before the start runs past midnight), or dibs hours off`);
375
+ set = { start: start.padStart(5, '0'), end: end.padStart(5, '0') };
376
+ }
377
+ const c = JSON.parse(fs.readFileSync(paths.config, 'utf8'));
378
+ c.hours = set;
379
+ const tmp = `${paths.config}.${process.pid}`;
380
+ fs.writeFileSync(tmp, JSON.stringify(c, null, 2) + '\n');
381
+ fs.renameSync(tmp, paths.config);
382
+ logChange('hours', { hours: set, from: cfg.hours || null });
383
+ cfg = loadConfig();
384
+ }
385
+ const h = hours(cfg);
386
+ if (json) return console.log(JSON.stringify(h));
387
+ console.log(h ? `hours ${h.start} to ${h.end}: outside them, questions below urgent wait for ${h.start}. Clear: dibs hours off`
388
+ : 'no hours set: questions reach you any time. Set: dibs hours 09:00-23:00');
389
+ }
package/src/quota.mjs ADDED
@@ -0,0 +1,81 @@
1
+ // Rate-limit budgets shared machine-wide. `dibs run quota:asc --cost 3 -- cmd`
2
+ // takes 3 tokens from the asc bucket when cmd starts, and waits in line while
3
+ // there aren't enough, so scripts calling one API wait their turn instead of
4
+ // getting 429s. config.json: "quotas": { "asc": { "per": "1h", "limit": 300 } }.
5
+ // A bucket holds at most `limit` tokens and refills `limit` every `per`,
6
+ // smoothly. Buckets live in state.json under quotas: { name: { tokens, at } }.
7
+ import { byRank, sum } from './schedule.mjs';
8
+ import { dur, now } from './util.mjs';
9
+
10
+ export const QUOTA = 'quota:';
11
+ export const isQuota = r => r.startsWith(QUOTA);
12
+ const names = res => res.filter(isQuota).map(r => r.slice(QUOTA.length));
13
+
14
+ // A bucket's settings, or a sentence saying what's wrong with them.
15
+ export function bucketCfg(cfg, name) {
16
+ const q = cfg.quotas?.[name];
17
+ if (!q) return { error: `quota:${name} isn't configured. Add it to config.json: "quotas": { "${name}": { "per": "1h", "limit": 300 } }` };
18
+ const m = String(q.per ?? '').trim().match(/^([\d.]+)\s*(ms|s|m|h|d)$/);
19
+ const per = typeof q.per === 'number' ? q.per : m && parseFloat(m[1]) * { ms: 1, s: 1e3, m: 6e4, h: 3.6e6, d: 8.64e7 }[m[2]];
20
+ if (!(per > 0) || !(q.limit > 0)) return { error: `quotas.${name} in config.json needs "per" (like "1h" or "60s") and a "limit" above 0` };
21
+ return { per, limit: q.limit };
22
+ }
23
+
24
+ // Tokens in a bucket at t. A bucket nobody has used yet is full.
25
+ export function level(b, q, t = now()) {
26
+ if (!b) return q.limit;
27
+ return Math.min(q.limit, b.tokens + Math.max(0, t - b.at) * q.limit / q.per);
28
+ }
29
+
30
+ // How long until a bucket holding `have` tokens holds `need`.
31
+ export const refillIn = (have, need, q) => (have >= need ? 0 : Math.ceil((need - have) * q.per / q.limit));
32
+
33
+ const cost = x => x.cost ?? 1;
34
+ const round = n => Math.floor(n * 10) / 10;
35
+
36
+ // Checked before a request waits at all: a quota that can't be read, or a cost
37
+ // the bucket can never hold, would wait forever.
38
+ export function quotaProblem(cfg, res, c = 1) {
39
+ for (const name of names(res)) {
40
+ const q = bucketCfg(cfg, name);
41
+ if (q.error) return q.error;
42
+ if (c > q.limit) return `--cost ${c} is more than quota:${name} ever holds (${q.limit})`;
43
+ }
44
+ return null;
45
+ }
46
+
47
+ // Why a waiter can't take its tokens yet, or null. Waiters ahead of it for the
48
+ // same bucket are served first, so a big request isn't passed forever by small ones.
49
+ export function quotaBlock(s, me, cfg, hist, t = now()) {
50
+ const before = byRank(hist, t);
51
+ for (const name of names(me.res)) {
52
+ const q = bucketCfg(cfg, name);
53
+ if (q.error) continue;
54
+ const have = level(s.quotas?.[name], q, t);
55
+ const ahead = s.queue.filter(x => x.pid && x.id !== me.id && x.res.includes(QUOTA + name) && before(x, me) < 0);
56
+ const need = cost(me) + sum(ahead, cost);
57
+ if (have >= need) continue;
58
+ return { ok: false, rule: 'quota', on: QUOTA + name, in: refillIn(have, need, q), have: round(have), limit: q.limit,
59
+ why: `quota:${name} has ${round(have)} of ${q.limit} left (refills ${q.limit} per ${dur(q.per)}), you need ${cost(me)}`
60
+ + `${ahead.length ? ` after ${need - cost(me)} for ${ahead.length} ahead of you` : ''}: enough in ~${dur(refillIn(have, need, q))}` };
61
+ }
62
+ return null;
63
+ }
64
+
65
+ // Take a starting request's tokens. Called in the same state change that gives it the lease.
66
+ export function takeQuota(s, me, cfg, t = now()) {
67
+ for (const name of names(me.res)) {
68
+ const q = bucketCfg(cfg, name);
69
+ if (q.error) continue;
70
+ s.quotas ||= {};
71
+ s.quotas[name] = { tokens: level(s.quotas[name], q, t) - cost(me), at: t };
72
+ }
73
+ }
74
+
75
+ // For the board: every configured bucket and what's left in it.
76
+ export function quotasNow(s, cfg, t = now()) {
77
+ return Object.keys(cfg.quotas || {}).map(name => {
78
+ const q = bucketCfg(cfg, name);
79
+ return q.error ? { name, error: q.error } : { name, left: round(level(s.quotas?.[name], q, t)), limit: q.limit, per: q.per };
80
+ });
81
+ }
package/src/reads.mjs ADDED
@@ -0,0 +1,54 @@
1
+ // dibs _reads: the Mac app's reader. The app polls the board, the questions and
2
+ // the threads every few seconds; as a new `dibs ... --json` each, under load
3
+ // most of every read was node starting up (seconds, against milliseconds for
4
+ // the read). Here one process stays up for the app's lifetime and answers each
5
+ // read in turn: one JSON request per line on stdin, {"id", "args"}, and one
6
+ // JSON answer per line on stdout, {"id", "code", "out", "err"}, where out is
7
+ // exactly what `dibs <args>` would have printed and code its exit code.
8
+ // bin/dibs.mjs readOne() decides which verbs it answers: only the read-only ones.
9
+ //
10
+ // It ends when the app closes its stdin, or after an answer once dibs on disk
11
+ // is a new version, so the next read starts the new code.
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
14
+ import util from 'node:util';
15
+ import readline from 'node:readline';
16
+ import { fileURLToPath } from 'node:url';
17
+ import { inProcessAsync } from './util.mjs';
18
+
19
+ const VERSION_FILE = path.join(path.dirname(fileURLToPath(import.meta.url)), 'version.mjs');
20
+ const stamp = () => { try { return fs.statSync(VERSION_FILE).mtimeMs; } catch { return 0; } };
21
+
22
+ export async function reads(readOne) {
23
+ const started = stamp();
24
+ const write = process.stdout.write.bind(process.stdout);
25
+ const log = console.log;
26
+ const lines = readline.createInterface({ input: process.stdin, crlfDelay: Infinity });
27
+ for await (const line of lines) {
28
+ let req;
29
+ try { req = JSON.parse(line); } catch { continue; }
30
+ if (!Array.isArray(req?.args) || !req.args.every(a => typeof a === 'string')) {
31
+ write(`${JSON.stringify({ id: req?.id ?? null, code: 2, out: '', err: 'args is a list of strings' })}\n`);
32
+ continue;
33
+ }
34
+ // What the read prints is its answer. One read at a time, so nothing else writes meanwhile.
35
+ const out = [];
36
+ console.log = (...a) => { out.push(`${util.format(...a)}\n`); };
37
+ process.stdout.write = chunk => { out.push(String(chunk)); return true; };
38
+ process.exitCode = 0;
39
+ let code = 0, err = '';
40
+ try {
41
+ await inProcessAsync(() => readOne(req.args));
42
+ code = Number(process.exitCode) || 0;
43
+ } catch (e) {
44
+ code = e.exitCode ?? 70;
45
+ err = e.exitCode != null ? e.message : `dibs itself crashed (a bug in dibs; exit 70). Report it: dibs ask "..."\n${e.stack || e.message}`;
46
+ } finally {
47
+ console.log = log;
48
+ process.stdout.write = write;
49
+ process.exitCode = 0;
50
+ }
51
+ write(`${JSON.stringify({ id: req.id ?? null, code, out: out.join(''), err })}\n`);
52
+ if (stamp() !== started) process.exit(0);
53
+ }
54
+ }