@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/talk.mjs
ADDED
|
@@ -0,0 +1,523 @@
|
|
|
1
|
+
// Talking with the agents. Each agent has a thread: its questions (from
|
|
2
|
+
// src/questions.mjs) and answers, notes it leaves the person (dibs say), and
|
|
3
|
+
// messages the person sends it (dibs tell). A message reaches the agent
|
|
4
|
+
// through the guard hook (https://code.claude.com/docs/en/hooks):
|
|
5
|
+
// PreToolUse added to the call as additionalContext, the call itself unchanged
|
|
6
|
+
// Stop, SubagentStop the documented "block" decision with the message as the reason,
|
|
7
|
+
// so the agent keeps going and reads it instead of ending its turn
|
|
8
|
+
// Each message is handed over once, marked under the lock, so a block can't repeat.
|
|
9
|
+
//
|
|
10
|
+
// dibs itself also leaves agents notices this way (notify): a job of theirs
|
|
11
|
+
// that sits idle, used more memory than it asked for, was paused, or was
|
|
12
|
+
// started twice. Each is handed over once, beside the call, never on a stop.
|
|
13
|
+
//
|
|
14
|
+
// Messages keep their own file and lock (messages.json), like questions: the
|
|
15
|
+
// hook must never queue behind the state lock. inbox.json lists only who has
|
|
16
|
+
// something waiting, rewritten with every change and gone when nothing is, so
|
|
17
|
+
// the hook's check on every tool call is one read of a tiny or missing file.
|
|
18
|
+
import fs from 'node:fs';
|
|
19
|
+
import path from 'node:path';
|
|
20
|
+
import { HOME, paths, loadConfig } from './config.mjs';
|
|
21
|
+
import { identity, makeAlive, pstart, sessionFiles } from './proc.mjs';
|
|
22
|
+
import { actor, logChange } from './owner.mjs';
|
|
23
|
+
import { takeAgent, talkKey } from './files.mjs';
|
|
24
|
+
import { asked, forYou } from './questions.mjs';
|
|
25
|
+
import { named, minutes, lower } from './plain.mjs';
|
|
26
|
+
import { bold, dim, columns } from './style.mjs';
|
|
27
|
+
import { die, now, say as note, sleepSync, fakeFull } from './util.mjs';
|
|
28
|
+
|
|
29
|
+
const FILE = path.join(HOME, 'messages.json');
|
|
30
|
+
const LOCK = path.join(HOME, 'messages.lock');
|
|
31
|
+
export const INBOX = path.join(HOME, 'inbox.json');
|
|
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
|
+
// The hook gives up on the lock sooner and hands the message over on a later call.
|
|
36
|
+
const HOOK_LOCK_WAIT = 1000;
|
|
37
|
+
// A week of talk is plenty to scroll back through, and keeps the file small.
|
|
38
|
+
const KEEP_FOR = 7 * 24 * 36e5;
|
|
39
|
+
const PER_THREAD = 200;
|
|
40
|
+
// A message is a few sentences. This stops one paste from filling the file.
|
|
41
|
+
const MAX_TEXT = 4000;
|
|
42
|
+
// The plain list shows this many recent lines of a thread.
|
|
43
|
+
const RECENT = 20;
|
|
44
|
+
// A notice is about a job running now. One that hasn't reached its agent in
|
|
45
|
+
// an hour is stale advice, and it would keep inbox.json around for nothing.
|
|
46
|
+
const NOTICE_LIFE = 36e5;
|
|
47
|
+
|
|
48
|
+
const STOPS = new Set(['Stop', 'SubagentStop']);
|
|
49
|
+
const MAIN = 'main';
|
|
50
|
+
|
|
51
|
+
function locked(fn, wait = LOCK_WAIT) {
|
|
52
|
+
fs.mkdirSync(HOME, { recursive: true });
|
|
53
|
+
const t0 = now();
|
|
54
|
+
for (;;) {
|
|
55
|
+
try { fs.mkdirSync(LOCK); break; } catch (e) {
|
|
56
|
+
if (e.code !== 'EEXIST') throw e;
|
|
57
|
+
try { if (now() - fs.statSync(LOCK).mtimeMs > LOCK_STALE) fs.rmSync(LOCK, { recursive: true, force: true }); } catch {}
|
|
58
|
+
if (now() - t0 > wait) {
|
|
59
|
+
if (wait === HOOK_LOCK_WAIT) throw new Error(`${LOCK} stayed locked for ${wait} ms`);
|
|
60
|
+
die(`${LOCK} stayed locked for ${wait / 1000}s; remove it if no dibs is running. Nothing was changed.`, 75);
|
|
61
|
+
}
|
|
62
|
+
sleepSync(5 + Math.random() * 10);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
try {
|
|
66
|
+
const s = load();
|
|
67
|
+
const before = JSON.stringify(s);
|
|
68
|
+
reap(s);
|
|
69
|
+
const out = fn(s);
|
|
70
|
+
if (JSON.stringify(s) !== before) save(s);
|
|
71
|
+
return out;
|
|
72
|
+
} finally {
|
|
73
|
+
fs.rmSync(LOCK, { recursive: true, force: true });
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Writes are renames, so reading without the lock always sees a whole file.
|
|
78
|
+
function load() {
|
|
79
|
+
let s = {};
|
|
80
|
+
try { s = JSON.parse(fs.readFileSync(FILE, 'utf8')); } catch (e) {
|
|
81
|
+
if (e.code !== 'ENOENT') note(`${FILE} was unreadable (${e.message}); starting with no messages.`);
|
|
82
|
+
}
|
|
83
|
+
s.seq ||= 0; s.threads ||= []; s.messages ||= [];
|
|
84
|
+
return s;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function save(s) {
|
|
88
|
+
fakeFull('state');
|
|
89
|
+
fs.writeFileSync(`${FILE}.tmp`, JSON.stringify(s, null, 1));
|
|
90
|
+
fs.renameSync(`${FILE}.tmp`, FILE);
|
|
91
|
+
const box = {};
|
|
92
|
+
for (const m of s.messages) {
|
|
93
|
+
if (m.state !== 'queued' || !(m.session || m.to)) continue;
|
|
94
|
+
// A caller outside Claude Code has no hook: its next dibs command looks under "@who".
|
|
95
|
+
const k = m.session || `@${m.to}`;
|
|
96
|
+
box[k] ||= [];
|
|
97
|
+
if (!box[k].includes(m.agentId)) box[k].push(m.agentId);
|
|
98
|
+
}
|
|
99
|
+
if (!Object.keys(box).length) return fs.rmSync(INBOX, { force: true });
|
|
100
|
+
fs.writeFileSync(`${INBOX}.tmp`, JSON.stringify(box));
|
|
101
|
+
fs.renameSync(`${INBOX}.tmp`, INBOX);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// A week's messages, the last PER_THREAD of each thread, and threads with
|
|
105
|
+
// anything left in them or any activity in the week.
|
|
106
|
+
function reap(s, t = now()) {
|
|
107
|
+
for (const m of s.messages) if (m.kind === 'notice' && m.state === 'queued' && t - m.at > NOTICE_LIFE) m.state = 'expired';
|
|
108
|
+
const recent = s.messages.filter(m => t - m.at < KEEP_FOR);
|
|
109
|
+
const count = new Map();
|
|
110
|
+
const kept = [];
|
|
111
|
+
for (const m of recent.reverse()) {
|
|
112
|
+
const n = (count.get(m.key) || 0) + 1;
|
|
113
|
+
count.set(m.key, n);
|
|
114
|
+
if (n <= PER_THREAD) kept.push(m);
|
|
115
|
+
}
|
|
116
|
+
s.messages = kept.reverse();
|
|
117
|
+
s.threads = s.threads.filter(th => count.has(th.key) || t - th.last < KEEP_FOR);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const keyOf = (session, who, agentId) => `${session || who}|${agentId || MAIN}`;
|
|
121
|
+
|
|
122
|
+
// What the person types to reach a thread: the session name for its main
|
|
123
|
+
// agent, name/label for a subagent (name/label#id when two share a label).
|
|
124
|
+
function names(threads) {
|
|
125
|
+
const out = new Map();
|
|
126
|
+
for (const th of threads) {
|
|
127
|
+
if (th.agentId === MAIN) { out.set(th.key, th.who); continue; }
|
|
128
|
+
const base = `${th.who}/${th.label || th.agentId.slice(0, 8)}`;
|
|
129
|
+
const twins = threads.filter(x => x.agentId !== MAIN && x.who === th.who && (x.label || x.agentId.slice(0, 8)) === (th.label || th.agentId.slice(0, 8)));
|
|
130
|
+
out.set(th.key, twins.length > 1 ? `${base}#${th.agentId.slice(0, 6)}` : base);
|
|
131
|
+
}
|
|
132
|
+
return out;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Is anyone left to read the thread: its session's process is running and,
|
|
136
|
+
// for a subagent, it hasn't finished. Unknown (no process to check) counts as alive.
|
|
137
|
+
// A session's live process comes first: a resumed session runs under a new pid,
|
|
138
|
+
// and the thread's own pid is the one it had when the thread began.
|
|
139
|
+
function liveness(threads) {
|
|
140
|
+
const files = sessionFiles();
|
|
141
|
+
const up = makeAlive([...files.map(f => f.pid), ...threads.map(th => th.spid)].filter(Boolean));
|
|
142
|
+
const live = new Set(files.filter(f => up(f.pid)).map(f => f.sessionId));
|
|
143
|
+
const known = new Set(files.map(f => f.sessionId));
|
|
144
|
+
// A main session's thread marked ended is alive again once its session runs again; a finished subagent stays finished.
|
|
145
|
+
return th => (th.agentId === MAIN && live.has(th.session))
|
|
146
|
+
|| (!th.ended && (live.has(th.session) || (th.spid ? up(th.spid, th.sstart) : !known.has(th.session))));
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// The caller's own thread, made if it's new. o.as labels a subagent's thread.
|
|
150
|
+
function mine(s, verb, words, o) {
|
|
151
|
+
const id = identity(o);
|
|
152
|
+
const session = process.env.CLAUDE_CODE_SESSION_ID || sessionFiles().find(f => f.pid === id.spid)?.sessionId || null;
|
|
153
|
+
const by = session ? takeAgent(verb, [], talkKey(verb, words)) : null;
|
|
154
|
+
const agentId = by?.agentId || MAIN;
|
|
155
|
+
const key = keyOf(session, id.who, agentId);
|
|
156
|
+
let th = s.threads.find(x => x.key === key);
|
|
157
|
+
if (!th) s.threads.push(th = { key, who: id.who, session, agentId, label: '', spid: id.spid, sstart: id.sstart, readAt: 0, last: now() });
|
|
158
|
+
const label = id.label || by?.agentType || '';
|
|
159
|
+
if (label) th.label = label;
|
|
160
|
+
Object.assign(th, { who: id.who, spid: id.spid || th.spid, sstart: id.sstart || th.sstart, ended: null });
|
|
161
|
+
return th;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function parse(args) {
|
|
165
|
+
const o = { words: [] };
|
|
166
|
+
for (let i = 0; i < args.length; i++) {
|
|
167
|
+
const a = args[i];
|
|
168
|
+
if (a === '--as') o.as = args[++i] ?? die('--as needs a value');
|
|
169
|
+
else if (a === '--to') { o.to = args[++i] ?? die('--to needs a value: dibs say --to person "..."'); if (o.to !== 'person') die(`dibs say goes to the person: --to person, not --to ${o.to}. To reach an agent: dibs tell <agent> "..."`); }
|
|
170
|
+
else if (a === '--json') o.json = true;
|
|
171
|
+
else if (a.startsWith('-') && a.length > 1) die(`unknown flag ${a}. Try: dibs help`);
|
|
172
|
+
else o.words.push(a);
|
|
173
|
+
}
|
|
174
|
+
o.text = o.words.join(' ').trim();
|
|
175
|
+
if (o.text.length > MAX_TEXT) die(`that's ${o.text.length} characters; keep it under ${MAX_TEXT}, or point to a file with the details. Nothing was sent.`);
|
|
176
|
+
return o;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// dibs say "text" [--as label] [--to person]: a note to the person in the
|
|
180
|
+
// agent's own thread. The person reads notes as FYI; --to person marks a
|
|
181
|
+
// reply to something they said (the desk's answers, a reply to a message).
|
|
182
|
+
export function say(args) {
|
|
183
|
+
const o = parse(args);
|
|
184
|
+
if (!o.text) die('say what? dibs say "migration done, tests pass"');
|
|
185
|
+
const r = locked(s => {
|
|
186
|
+
const th = mine(s, 'say', args, o);
|
|
187
|
+
const t = now();
|
|
188
|
+
s.messages.push({ id: ++s.seq, key: th.key, at: t, from: 'agent', kind: 'note', text: o.text, ...(o.to && { reply: true }) });
|
|
189
|
+
th.last = t;
|
|
190
|
+
// Without the guard hook nothing else hands messages over: this is the agent reading its thread.
|
|
191
|
+
const waiting = s.messages.filter(m => m.key === th.key && m.state === 'queued' && m.kind !== 'notice');
|
|
192
|
+
for (const m of waiting) handOver(s, m, 'say', t);
|
|
193
|
+
return waiting.map(m => ({ ...m }));
|
|
194
|
+
});
|
|
195
|
+
console.log(`Sent to the person. They see it in dibs threads.${r.map(m => `\nMessage from ${sender(m)}: ${m.text}`).join('')}`);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
// A note in an agent's thread on its behalf, as if it had run dibs say: how
|
|
199
|
+
// a job it scheduled with dibs later ended. by: { who, session, agentId,
|
|
200
|
+
// label, spid, sstart }, as the agent was when it scheduled it. Throws rather
|
|
201
|
+
// than exit when the lock stays taken, since its caller may be a service.
|
|
202
|
+
export function noteAs(by, text) {
|
|
203
|
+
locked(s => {
|
|
204
|
+
const key = keyOf(by.session, by.who, by.agentId);
|
|
205
|
+
let th = s.threads.find(x => x.key === key);
|
|
206
|
+
if (!th) s.threads.push(th = { key, who: by.who, session: by.session || null, agentId: by.agentId || MAIN, label: by.label || '',
|
|
207
|
+
spid: by.spid || null, sstart: by.sstart || null, readAt: 0, last: now() });
|
|
208
|
+
const t = now();
|
|
209
|
+
s.messages.push({ id: ++s.seq, key, at: t, from: 'agent', kind: 'note', text: text.slice(0, MAX_TEXT) });
|
|
210
|
+
th.last = t;
|
|
211
|
+
}, HOOK_LOCK_WAIT);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// The thread the person means by name: a live one, else a running session
|
|
215
|
+
// by that name (a new thread), else the newest one that has ended.
|
|
216
|
+
function target(s, name) {
|
|
217
|
+
const named = names(s.threads);
|
|
218
|
+
const alive = liveness(s.threads);
|
|
219
|
+
const found = s.threads.filter(th => named.get(th.key) === name).sort((a, b) => b.last - a.last);
|
|
220
|
+
const live = found.find(alive);
|
|
221
|
+
if (live) return live;
|
|
222
|
+
const files = sessionFiles().filter(f => f.name === name);
|
|
223
|
+
const running = files.filter(f => makeAlive([f.pid])(f.pid));
|
|
224
|
+
const f = running[0] || (!found.length && files[0]);
|
|
225
|
+
if (f) {
|
|
226
|
+
const key = keyOf(f.sessionId, name, MAIN);
|
|
227
|
+
let th = s.threads.find(x => x.key === key);
|
|
228
|
+
if (!th) s.threads.push(th = { key, who: name, session: f.sessionId, agentId: MAIN, label: '', spid: f.pid, sstart: pstart(f.pid), readAt: 0, last: now() });
|
|
229
|
+
// The session's thread under the name and process it has now: a session renamed or
|
|
230
|
+
// resumed keeps its thread, which still named the old ones (2026-11-02: "dibs tell
|
|
231
|
+
// alex-a4" answered "queued for alex-8e, but its session has ended").
|
|
232
|
+
else if (running.includes(f)) Object.assign(th, { who: name, spid: f.pid, sstart: pstart(f.pid), ended: null });
|
|
233
|
+
return th;
|
|
234
|
+
}
|
|
235
|
+
if (found.length) return found[0];
|
|
236
|
+
return null;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
const nobody = (s, name) => {
|
|
240
|
+
const known = [...new Set(names(s.threads).values())];
|
|
241
|
+
const running = sessionFiles().filter(f => f.name && makeAlive([f.pid])(f.pid)).map(f => f.name);
|
|
242
|
+
return `no agent called ${name}. ${known.length ? `Threads: ${known.join(', ')}. ` : ''}${running.length ? `Running sessions: ${[...new Set(running)].join(', ')}. ` : ''}See them: dibs threads`;
|
|
243
|
+
};
|
|
244
|
+
|
|
245
|
+
// dibs tell <agent> "text": the person, or another agent, queues a message for an agent.
|
|
246
|
+
// An agent's message says which agent sent it, never that the person did.
|
|
247
|
+
export function tell(args) {
|
|
248
|
+
let [name, ...rest] = args;
|
|
249
|
+
// "desk" is whichever agent config.json names to answer the person (the app's chat).
|
|
250
|
+
if (name === 'desk') name = loadConfig().desk || die('no desk agent is set. Name one in ~/.dibs/config.json: "desk": "<agent name>" (names: dibs threads)');
|
|
251
|
+
const o = parse(rest);
|
|
252
|
+
if (!name || !o.text) die('tell whom what? dibs tell <agent> "use the staging database" (names: dibs threads)');
|
|
253
|
+
const who = actor();
|
|
254
|
+
const r = locked(s => {
|
|
255
|
+
const th = target(s, name);
|
|
256
|
+
if (!th) return { no: nobody(s, name) };
|
|
257
|
+
const t = now();
|
|
258
|
+
s.messages.push({ id: ++s.seq, key: th.key, at: t, from: 'person', kind: 'message', text: o.text, state: 'queued',
|
|
259
|
+
session: th.session, agentId: th.agentId, ...(who.agent && { by: who.name }) });
|
|
260
|
+
th.last = t;
|
|
261
|
+
return { th: { ...th }, alive: liveness([th])(th) };
|
|
262
|
+
});
|
|
263
|
+
if (r.no) die(r.no, 1);
|
|
264
|
+
const to = names([r.th]).get(r.th.key);
|
|
265
|
+
logChange('tell', { to });
|
|
266
|
+
if (!r.th.session) console.log(`queued for ${to}, which isn't a Claude Code session: the hook can't hand it over. It gets it the next time it runs dibs say.`);
|
|
267
|
+
else if (!r.alive) console.log(`queued for ${to}, but ${r.th.agentId === MAIN ? 'its session has ended' : 'that subagent has finished'}. It stays queued, shown as not delivered, in case it comes back.`);
|
|
268
|
+
else console.log(`queued for ${to}: it gets it with its next tool call, or as it finishes its turn.`);
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
// Mark one queued message handed over, with a line in the thread saying how.
|
|
272
|
+
const VIA = { tool: 'got it with its next tool call', stop: 'got it as it was finishing, and kept going', say: 'got it when it ran dibs say',
|
|
273
|
+
command: 'got it with its next dibs command' };
|
|
274
|
+
function handOver(s, m, via, t) {
|
|
275
|
+
Object.assign(m, { state: 'delivered', deliveredAt: t, via });
|
|
276
|
+
if (m.kind === 'notice') return;
|
|
277
|
+
s.messages.push({ id: ++s.seq, key: m.key, at: t, from: 'agent', kind: 'delivered', text: VIA[via], about: m.id });
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// dibs leaving an agent a notice about one of its jobs, handed over on its next
|
|
281
|
+
// tool call by the hook (or, outside Claude Code, its next dibs command). to is
|
|
282
|
+
// the lease or queue entry the notice is about: { sessionId, agentId, who }.
|
|
283
|
+
// once names the event ("idle:#12"): a notice already left under that name
|
|
284
|
+
// isn't left again, so a producer can call this on every pass. Best effort:
|
|
285
|
+
// a busy lock or a full disk only means the agent doesn't hear about it.
|
|
286
|
+
export function notify(to, once, text) {
|
|
287
|
+
const session = to.sessionId || to.session || null;
|
|
288
|
+
if (!session && !to.who) return false;
|
|
289
|
+
const agentId = to.agentId || MAIN;
|
|
290
|
+
try {
|
|
291
|
+
return locked(s => {
|
|
292
|
+
const same = m => m.kind === 'notice' && m.once === once && m.session === session && m.agentId === agentId && (session || m.to === to.who);
|
|
293
|
+
if (s.messages.some(same)) return false;
|
|
294
|
+
s.messages.push({ id: ++s.seq, key: keyOf(session, to.who, agentId), at: now(), from: 'dibs', kind: 'notice', text: text.slice(0, MAX_TEXT),
|
|
295
|
+
state: 'queued', session, agentId, once, ...(session ? {} : { to: to.who }) });
|
|
296
|
+
return true;
|
|
297
|
+
}, HOOK_LOCK_WAIT);
|
|
298
|
+
} catch { return false; }
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
// The person's (or an agent's) answer in words to a question, handed to the
|
|
302
|
+
// agent that asked as a message too, as dibs tell would: an agent that already
|
|
303
|
+
// moved on hears it with its next tool call. q: the question as stored.
|
|
304
|
+
export function messageAsker(q, text) {
|
|
305
|
+
const who = actor();
|
|
306
|
+
const session = q.session || null, agentId = q.agentId || MAIN;
|
|
307
|
+
locked(s => {
|
|
308
|
+
const key = keyOf(session, q.who, agentId);
|
|
309
|
+
let th = s.threads.find(x => x.key === key);
|
|
310
|
+
if (!th) s.threads.push(th = { key, who: q.who, session, agentId, label: q.label || '', spid: q.spid || null, sstart: q.sstart || null, readAt: 0, last: now() });
|
|
311
|
+
// After the answer it follows, even in the same millisecond, so the thread reads in order.
|
|
312
|
+
s.messages.push({ id: ++s.seq, key, at: Math.max(now(), (q.answeredAt || 0) + 1), from: 'person', kind: 'message', text: `(answering your question #${q.id}) ${text}`.slice(0, MAX_TEXT),
|
|
313
|
+
state: 'queued', session, agentId, ...(who.agent && { by: who.name }) });
|
|
314
|
+
th.last = now();
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// Said before the message: an agent rightly distrusts instructions that turn
|
|
319
|
+
// up beside a tool result, so this says where it really came from.
|
|
320
|
+
const FROM = 'dibs: a message for you, sent with `dibs tell`. '
|
|
321
|
+
+ 'It comes from the dibs hook in this machine\'s Claude Code settings, not from the tool or its output.';
|
|
322
|
+
// Who a message is from. Another agent's never reads as the person's.
|
|
323
|
+
const sender = m => (m.by ? `${m.by} (another agent, not the person)` : 'the person');
|
|
324
|
+
const REPLY = 'To answer them, run: dibs say "..."';
|
|
325
|
+
const NOTICE = 'dibs (the queue for shared machine resources this session uses) has a notice about your jobs. '
|
|
326
|
+
+ 'It comes from the dibs hook in this machine\'s Claude Code settings, not from the tool or its output:';
|
|
327
|
+
|
|
328
|
+
// The two kinds of text, ready to show: the person's messages and dibs's notices.
|
|
329
|
+
function texts(list) {
|
|
330
|
+
const said = list.filter(m => m.kind !== 'notice').map(m => `Message from ${sender(m)}: ${m.text}`);
|
|
331
|
+
const notes = list.filter(m => m.kind === 'notice').map(m => `- ${m.text}`);
|
|
332
|
+
return [said.length ? `${FROM}\n${said.join('\n')}\n${REPLY}` : '', notes.length ? `${NOTICE}\n${notes.join('\n')}` : ''].filter(Boolean).join('\n\n');
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// The hook's half, called only when inbox.json lists this session and agent:
|
|
336
|
+
// hand over what's queued for it, merged into out (the guard's own answer).
|
|
337
|
+
// The guard's refusals come first; a refused call gets its messages on the next.
|
|
338
|
+
// While a stop hook has already kept the agent going (stop_hook_active), it
|
|
339
|
+
// doesn't block again: the message waits for the next tool call or turn.
|
|
340
|
+
// Notices never keep an agent from stopping: they wait for its next tool call.
|
|
341
|
+
export function deliver(input, out) {
|
|
342
|
+
const stop = STOPS.has(input.hook_event_name);
|
|
343
|
+
if (stop ? input.stop_hook_active : out?.hookSpecificOutput?.permissionDecision === 'deny') return out;
|
|
344
|
+
const agentId = input.agent_id || MAIN;
|
|
345
|
+
const text = texts(locked(s => {
|
|
346
|
+
const t = now();
|
|
347
|
+
const mine = s.messages.filter(m => m.state === 'queued' && m.session === input.session_id && m.agentId === agentId && !(stop && m.kind === 'notice'));
|
|
348
|
+
for (const m of mine) {
|
|
349
|
+
handOver(s, m, stop ? 'stop' : 'tool', t);
|
|
350
|
+
const th = s.threads.find(x => x.key === m.key);
|
|
351
|
+
if (th) Object.assign(th, { ended: null, last: t });
|
|
352
|
+
}
|
|
353
|
+
return mine;
|
|
354
|
+
}, HOOK_LOCK_WAIT));
|
|
355
|
+
if (!text) return out;
|
|
356
|
+
if (stop) return { decision: 'block', reason: text };
|
|
357
|
+
if (!out) return { hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: text } };
|
|
358
|
+
const h = out.hookSpecificOutput;
|
|
359
|
+
return { ...out, hookSpecificOutput: { ...h, additionalContext: [h.additionalContext, text].filter(Boolean).join('\n\n') } };
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
// For a caller with no hook (a terminal, Codex, a script): notices left for
|
|
363
|
+
// it, handed over by its next dibs command. Cheap when there are none: one
|
|
364
|
+
// read of inbox.json, which is absent when nothing is queued for anyone.
|
|
365
|
+
export function noticesFor(who) {
|
|
366
|
+
try { if (!JSON.parse(fs.readFileSync(INBOX, 'utf8'))[`@${who}`]) return ''; } catch { return ''; }
|
|
367
|
+
try {
|
|
368
|
+
return texts(locked(s => {
|
|
369
|
+
const mine = s.messages.filter(m => m.state === 'queued' && m.kind === 'notice' && !m.session && m.to === who);
|
|
370
|
+
for (const m of mine) handOver(s, m, 'command', now());
|
|
371
|
+
return mine;
|
|
372
|
+
}, HOOK_LOCK_WAIT)).replace(/^dibs \(.*\n/, 'dibs has a notice about your jobs:\n');
|
|
373
|
+
} catch { return ''; }
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// A subagent that finished: its thread shows it can't be reached until it runs again.
|
|
377
|
+
export function finished(input) {
|
|
378
|
+
if (!input.agent_id || !fs.existsSync(FILE)) return;
|
|
379
|
+
const key = keyOf(input.session_id, null, input.agent_id);
|
|
380
|
+
if (!load().threads.some(th => th.key === key && !th.ended)) return;
|
|
381
|
+
locked(s => { const th = s.threads.find(x => x.key === key); if (th) th.ended = now(); }, HOOK_LOCK_WAIT);
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
// What each thread's agent is doing now, from the state file read without its
|
|
385
|
+
// lock: the lease it holds or the request it waits on, or null when idle.
|
|
386
|
+
function doing(th, st) {
|
|
387
|
+
const ours = x => x.who === th.who && (th.agentId === MAIN ? !x.agentId || x.agentId === MAIN : x.agentId === th.agentId);
|
|
388
|
+
const l = (st.leases || []).find(ours);
|
|
389
|
+
if (l) return { using: true, res: l.res, purpose: l.purpose };
|
|
390
|
+
const q = (st.queue || []).find(ours);
|
|
391
|
+
return q ? { using: false, res: q.res, purpose: q.purpose } : null;
|
|
392
|
+
}
|
|
393
|
+
const why = d => (d.purpose ? ` for "${d.purpose}"` : '');
|
|
394
|
+
// For --json, by resource id, which the Mac app reads: "using sim for "snapshots"", "waiting for xcode-build".
|
|
395
|
+
const workingId = d => (d ? `${d.using ? 'using' : 'waiting for'} ${d.res.join(', ')}${why(d)}` : 'idle');
|
|
396
|
+
// For the terminal, in the board's words: "using the simulator for "snapshots"", "deploying", "waiting in the Xcode build queue".
|
|
397
|
+
const workingPlain = (d, cfg) => (!d ? 'idle' : d.using ? `${d.res.map(r => lower(named(cfg, r).doing)).join(' and ')}${why(d)}`
|
|
398
|
+
: `waiting in ${d.res.map(r => named(cfg, r).queue).join(' and ')}${why(d)}`);
|
|
399
|
+
|
|
400
|
+
// Every thread as the app and dibs threads --json see it, newest activity first.
|
|
401
|
+
function view(s, t = now()) {
|
|
402
|
+
let st = {};
|
|
403
|
+
try { st = JSON.parse(fs.readFileSync(paths.state, 'utf8')); } catch {}
|
|
404
|
+
const threads = [...s.threads];
|
|
405
|
+
const byKey = new Map(threads.map(th => [th.key, th]));
|
|
406
|
+
// dibs's notices (bookings, stuck jobs, --mem advice) are for the agent's hook only, never the person's threads.
|
|
407
|
+
const lines = new Map(threads.map(th => [th.key, s.messages.filter(m => m.key === th.key && m.kind !== 'notice').map(m => ({
|
|
408
|
+
id: `m${m.id}`, at: m.at, from: m.from, kind: m.kind, text: m.text, options: null, questionId: null,
|
|
409
|
+
state: m.kind === 'message' ? m.state : null, ...(m.about ? { about: `m${m.about}` } : {}),
|
|
410
|
+
...(m.kind === 'note' && (m.reply ? { reply: true } : { fyi: true })), ...(m.by ? { by: m.by } : {}) }))]));
|
|
411
|
+
// Questions join their asker's thread, made here if it has said nothing yet.
|
|
412
|
+
for (const q of asked(t)) {
|
|
413
|
+
const key = keyOf(q.session, q.who, q.agentId);
|
|
414
|
+
if (!byKey.has(key)) {
|
|
415
|
+
const th = { key, who: q.who, session: q.session, agentId: q.agentId || MAIN, label: q.agentId ? q.label || '' : '', spid: q.spid, sstart: q.sstart, readAt: 0, last: q.asked };
|
|
416
|
+
byKey.set(key, th); threads.push(th); lines.set(key, []);
|
|
417
|
+
}
|
|
418
|
+
const th = byKey.get(key);
|
|
419
|
+
th.last = Math.max(th.last, q.answeredAt || q.asked);
|
|
420
|
+
const about = { recommend: q.recommend ?? null, why: q.purpose || null, oneWay: !!q.oneWay, cantUndo: q.cantUndo ?? null };
|
|
421
|
+
// A two-way door the agent walked through itself: shown as done, not asked.
|
|
422
|
+
if (q.state === 'decided') { lines.get(key).push({ id: `q${q.id}`, at: q.asked, from: 'agent', kind: 'decided', text: q.text, options: q.options, questionId: q.id, state: q.state, answer: q.answer, ...about }); continue; }
|
|
423
|
+
lines.get(key).push({ id: `q${q.id}`, at: q.asked, from: 'agent', kind: 'question', text: q.text, options: q.options, questionId: q.id, state: q.state, ...about });
|
|
424
|
+
if (q.state === 'answered') lines.get(key).push({ id: `q${q.id}a`, at: q.answeredAt, from: 'person', kind: 'answer', text: q.answer, options: null, questionId: q.id, state: null,
|
|
425
|
+
...(q.freeText && { freeText: true }), ...(q.answeredBy && { by: q.answeredBy }) });
|
|
426
|
+
}
|
|
427
|
+
const named = names(threads);
|
|
428
|
+
const alive = liveness(threads);
|
|
429
|
+
const desk = deskName();
|
|
430
|
+
return threads.map(th => {
|
|
431
|
+
const messages = lines.get(th.key).sort((a, b) => a.at - b.at);
|
|
432
|
+
return { agent: th.who, label: th.label || '', session: th.session, agentId: th.agentId, to: named.get(th.key), alive: alive(th),
|
|
433
|
+
...(desk && named.get(th.key) === desk && { desk: true }),
|
|
434
|
+
working: workingId(doing(th, st)), doing: doing(th, st), unread: messages.filter(m => m.from === 'agent' && m.kind !== 'delivered' && m.at > (th.readAt || 0)).length,
|
|
435
|
+
last: th.last, messages };
|
|
436
|
+
}).sort((a, b) => b.last - a.last);
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
// What `dibs threads --json` prints. dibs web reads it without the lock; the reaping isn't saved.
|
|
440
|
+
export function threadsJson(t = now(), list = null) {
|
|
441
|
+
if (!list) {
|
|
442
|
+
const s = load();
|
|
443
|
+
reap(s);
|
|
444
|
+
list = view(s, t);
|
|
445
|
+
}
|
|
446
|
+
return { threads: list.map(({ doing, ...th }) => th), desk: deskName(), needsYou: forYou(loadConfig(), t) };
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
// For the board: notes the person hasn't read. Read without the lock; the reaping isn't saved.
|
|
450
|
+
export function notesForYou() {
|
|
451
|
+
if (!fs.existsSync(FILE)) return 0;
|
|
452
|
+
const s = load();
|
|
453
|
+
reap(s);
|
|
454
|
+
const readAt = new Map(s.threads.map(th => [th.key, th.readAt || 0]));
|
|
455
|
+
return s.messages.filter(m => m.kind === 'note' && m.at > (readAt.get(m.key) ?? 0)).length;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
// The agent config.json names to answer the person ("desk"), or null.
|
|
459
|
+
function deskName() { try { return loadConfig().desk || null; } catch { return null; } }
|
|
460
|
+
|
|
461
|
+
const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
|
|
462
|
+
const ago = (t, at) => (t - at < 6e4 ? 'just now' : `${minutes(t - at)} ago`);
|
|
463
|
+
|
|
464
|
+
// dibs threads [--json] | dibs threads read <agent>
|
|
465
|
+
export function threads(args) {
|
|
466
|
+
if (args[0] === 'read') return read(args.slice(1));
|
|
467
|
+
const json = args.includes('--json');
|
|
468
|
+
const bad = args.find(a => a !== '--json');
|
|
469
|
+
if (bad) die(`unknown ${bad.startsWith('-') ? 'flag' : 'word'} ${bad}. Try: dibs threads [--json], dibs threads read <agent>`);
|
|
470
|
+
const t = now();
|
|
471
|
+
const list = view(locked(s => s), t);
|
|
472
|
+
if (json) return console.log(JSON.stringify(threadsJson(t, list), null, 1));
|
|
473
|
+
const cfg = loadConfig();
|
|
474
|
+
const unread = list.reduce((n, th) => n + th.unread, 0);
|
|
475
|
+
if (!list.length) return console.log('No threads yet. Agents start one with dibs say or dibs question.');
|
|
476
|
+
const out = [bold(`${plural(list.length, 'thread')}${unread ? `, ${unread} unread` : ', nothing unread'}.`), ''];
|
|
477
|
+
out.push(...columns(list.map(th => {
|
|
478
|
+
const lastLine = th.messages.filter(m => m.kind !== 'delivered').at(-1);
|
|
479
|
+
const flags = [th.unread ? `${th.unread} unread` : '', th.messages.some(m => m.state === 'queued') ? 'your message is not delivered yet' : ''].filter(Boolean).join(', ');
|
|
480
|
+
return [th.to, `${th.alive ? workingPlain(th.doing, cfg) : 'not running'}, last heard ${ago(t, th.last)}${flags ? ` (${flags})` : ''}.`,
|
|
481
|
+
lastLine ? dim(`${lastLine.from === 'person' ? 'You' : lastLine.from === 'dibs' ? 'dibs' : 'They'}: ${lastLine.text}`) : ''];
|
|
482
|
+
})));
|
|
483
|
+
out.push('', dim('Read one: dibs threads read <agent>. Write to one: dibs tell <agent> "..."'));
|
|
484
|
+
console.log(out.join('\n'));
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
// dibs threads read <agent>: the conversation, and its agent's messages marked seen.
|
|
488
|
+
function read(args) {
|
|
489
|
+
const name = args[0];
|
|
490
|
+
if (!name || args.length > 1) die('which thread? dibs threads read <agent> (names: dibs threads)');
|
|
491
|
+
const t = now();
|
|
492
|
+
const r = locked(s => {
|
|
493
|
+
const list = view(s, t).filter(th => th.to === name);
|
|
494
|
+
if (!list.length) return { no: nobody(s, name) };
|
|
495
|
+
const keys = new Set(list.map(th => keyOf(th.session, th.agent, th.agentId)));
|
|
496
|
+
for (const th of s.threads) if (keys.has(th.key)) th.readAt = t;
|
|
497
|
+
// A thread that holds only questions so far gets a record, so it remembers being read.
|
|
498
|
+
for (const th of list) {
|
|
499
|
+
const key = keyOf(th.session, th.agent, th.agentId);
|
|
500
|
+
if (!s.threads.some(x => x.key === key))
|
|
501
|
+
s.threads.push({ key, who: th.agent, session: th.session, agentId: th.agentId, label: th.label, readAt: t, last: th.last });
|
|
502
|
+
}
|
|
503
|
+
return { list };
|
|
504
|
+
});
|
|
505
|
+
if (r.no) die(r.no, 1);
|
|
506
|
+
const out = [];
|
|
507
|
+
for (const th of r.list) {
|
|
508
|
+
out.push(bold(`${th.to}: ${th.alive ? workingPlain(th.doing, loadConfig()) : 'not running (your messages wait for it)'}.`));
|
|
509
|
+
for (const m of th.messages.slice(-RECENT)) {
|
|
510
|
+
const who = m.from === 'person' ? 'you' : m.from === 'dibs' ? 'dibs told them' : 'them';
|
|
511
|
+
const what = m.kind === 'question' ? `asked (#${m.questionId}, ${m.state}): ${m.text}${m.options ? ` (${m.options.join(' / ')})` : ''}`
|
|
512
|
+
+ `${m.recommend ? ` they recommend ${m.recommend}${m.why ? `: ${m.why}` : ''}` : ''}${m.cantUndo ? `. Can't be undone: ${m.cantUndo}` : ''}`
|
|
513
|
+
: m.kind === 'decided' ? `decided it themselves, a two-way door (#${m.questionId}): ${m.text} -> ${m.answer}${m.why ? ` (${m.why})` : ''}. To change it, tell them`
|
|
514
|
+
: m.kind === 'note' && m.fyi ? `FYI: ${m.text}`
|
|
515
|
+
: m.kind === 'answer' ? `answered #${m.questionId}: ${m.text}`
|
|
516
|
+
: m.kind === 'delivered' ? `(${m.text})`
|
|
517
|
+
: `${m.text}${m.state === 'queued' ? ' (not delivered yet)' : ''}`;
|
|
518
|
+
out.push(` ${ago(t, m.at)}, ${who}: ${what}`);
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
out.push(dim(`Write to ${name}: dibs tell ${name} "..."${r.list.some(th => th.messages.some(m => m.kind === 'question' && m.state === 'open')) ? '. Answer a question: dibs answer <id> <text>' : ''}`));
|
|
522
|
+
console.log(out.join('\n'));
|
|
523
|
+
}
|
package/src/thin.sh
ADDED
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
# dibs run and dibs hold, waiting without Node. bin/dibs.mjs starts this as
|
|
2
|
+
# /bin/sh thin.sh <bin/dibs.mjs> run|hold <args>
|
|
3
|
+
# when config.json has "waits": "thin". Node gets in line as this process and
|
|
4
|
+
# runs a job that can start at once; a waiting one comes back here, gets in line
|
|
5
|
+
# again (_enqueue, picking up its place), and this shell blocks on a read from its own FIFO,
|
|
6
|
+
# which costs no CPU and about 1.5 MB, and the broker (src/broker.mjs) writes
|
|
7
|
+
# to it: "out <line>" to print, "go" when it's this waiter's turn, "exit N".
|
|
8
|
+
# On go it execs Node for the run itself, so the pid and start time the lease
|
|
9
|
+
# names stay this process's. Keep it small and POSIX: it runs under dash too.
|
|
10
|
+
B=$1
|
|
11
|
+
shift
|
|
12
|
+
D=${DIBS_HOME:-$HOME/.dibs}
|
|
13
|
+
# How bin/dibs.mjs starts Node (LEAN in src/util.mjs); keep them in step.
|
|
14
|
+
N="node --max-semi-space-size=1"
|
|
15
|
+
F=$D/w/$$
|
|
16
|
+
# First, Node gets in line as this same process (exec): a job that can start now
|
|
17
|
+
# runs in it, Node started once. One that must wait keeps its place and comes
|
|
18
|
+
# back here with DIBS_THIN_RESUME set, to wait as below. On 2026-10-21 starting
|
|
19
|
+
# Node twice (once to get in line, once to run) was 90 ms of every run.
|
|
20
|
+
if [ -z "${DIBS_THIN_RESUME:-}" ]; then
|
|
21
|
+
exec $N "$B" _enqueue $$ "$PPID" "$F" "$@"
|
|
22
|
+
fi
|
|
23
|
+
unset DIBS_THIN_RESUME
|
|
24
|
+
# No FIFO, no thin wait: wait the old way instead.
|
|
25
|
+
{ mkdir -p "$D/w" && rm -f "$F" && mkfifo -m 600 "$F"; } 2>/dev/null || exec $N "$B" "$@"
|
|
26
|
+
# Opening the read end blocks until there's a writer, so open a writer of our own first.
|
|
27
|
+
exec 4<>"$F" 3<"$F"
|
|
28
|
+
gone() { exec 3<&- 4>&-; rm -f "$F"; }
|
|
29
|
+
# Anything that goes wrong with a thin wait leaves an event (kind thin) in the
|
|
30
|
+
# history, so it can be found later. why is always one of the words below.
|
|
31
|
+
note() { printf '{"at":%s000,"kind":"thin","why":"%s","id":%s,"shell":%s}\n' "$(date +%s)" "$1" "${id:-0}" $$ >>"$D/events.jsonl" 2>/dev/null; }
|
|
32
|
+
|
|
33
|
+
# Set before getting in line: a signal that comes while Node is at it is
|
|
34
|
+
# acted on once Node is done, and leaves whatever place it made. Its answer,
|
|
35
|
+
# if it gave one, is already in the FIFO: read without our own writer, an
|
|
36
|
+
# empty FIFO is end of file at once rather than a wait.
|
|
37
|
+
id=
|
|
38
|
+
leave() {
|
|
39
|
+
# A signal during `IFS= read` runs this with IFS still empty in bash, and $N
|
|
40
|
+
# would then be one word, "node --max...", which isn't a command.
|
|
41
|
+
unset IFS
|
|
42
|
+
[ -z "$id" ] && { exec 4>&-; IFS= read -r r <&3; case $r in go\ *|wait\ *) id=${r#* } ;; esac; }
|
|
43
|
+
$N "$B" _leave "${id:-0}" $$ "$1"
|
|
44
|
+
gone
|
|
45
|
+
exit "$2"
|
|
46
|
+
}
|
|
47
|
+
trap 'leave SIGINT 130' INT
|
|
48
|
+
trap 'leave SIGTERM 143' TERM
|
|
49
|
+
trap 'leave SIGHUP 129' HUP
|
|
50
|
+
|
|
51
|
+
$N "$B" _enqueue $$ "$PPID" "$F" "$@" || { code=$?; trap - INT TERM HUP; [ $code = 70 ] && note 'getting in line crashed'; gone; exit $code; }
|
|
52
|
+
IFS= read -r r <&3
|
|
53
|
+
# From here on only the broker writes, so end of file means it isn't here.
|
|
54
|
+
exec 4>&-
|
|
55
|
+
case $r in
|
|
56
|
+
go\ *|wait\ *) id=${r#* } ;;
|
|
57
|
+
exit\ *) trap - INT TERM HUP; gone; exit "${r#exit }" ;;
|
|
58
|
+
fat) trap - INT TERM HUP; gone; exec $N "$B" "$@" ;;
|
|
59
|
+
*) trap - INT TERM HUP; note 'no answer from getting in line'; gone; exit 70 ;;
|
|
60
|
+
esac
|
|
61
|
+
|
|
62
|
+
# End of file: no broker has this FIFO open. One that's alive hasn't reached
|
|
63
|
+
# us yet (it opens every waiter's FIFO on its next tick), so read again after
|
|
64
|
+
# a pause. One that's dead crashed or was replaced by a release. Only one
|
|
65
|
+
# waiter starts the next, whoever makes the broker.starting folder; the rest
|
|
66
|
+
# wait for it, so 50 waiters don't start 50 Nodes at once. A broker that
|
|
67
|
+
# couldn't be started (broker.broken, less than a minute old), found dead three
|
|
68
|
+
# times in a minute, or missing for GIVE_UP seconds is broken: give the place
|
|
69
|
+
# up for the in-process wait, which picks it up again.
|
|
70
|
+
GIVE_UP=${DIBS_THIN_GIVE_UP:-15}
|
|
71
|
+
broken() { [ -n "$(find "$D/broker.broken" -mmin -1 2>/dev/null)" ]; }
|
|
72
|
+
gap=1 dead= t1= t2=
|
|
73
|
+
nobroker() {
|
|
74
|
+
p=
|
|
75
|
+
read -r p <"$D/broker.pid" 2>/dev/null
|
|
76
|
+
# A liveness hint only: kill -0 sends nothing.
|
|
77
|
+
if [ -n "$p" ] && kill -0 "$p" 2>/dev/null; then
|
|
78
|
+
dead=
|
|
79
|
+
sleep $((gap / 10)).$((gap % 10))
|
|
80
|
+
[ $gap -lt 20 ] && gap=$((gap * 2))
|
|
81
|
+
return 0
|
|
82
|
+
fi
|
|
83
|
+
t=$(date +%s)
|
|
84
|
+
if [ -z "$dead" ]; then
|
|
85
|
+
dead=$t
|
|
86
|
+
[ -n "$t1" ] && [ $((t - t1)) -lt 60 ] && { gaveup='broker died three times in a minute'; return 1; }
|
|
87
|
+
t1=$t2 t2=$t
|
|
88
|
+
fi
|
|
89
|
+
[ $((t - dead)) -ge "$GIVE_UP" ] && { gaveup='no broker for too long'; return 1; }
|
|
90
|
+
broken && { gaveup='no broker could be started'; return 1; }
|
|
91
|
+
if mkdir "$D/broker.starting" 2>/dev/null; then
|
|
92
|
+
echo $$ >"$D/broker.starting/pid"
|
|
93
|
+
note 'broker gone, starting another'
|
|
94
|
+
$N "$B" _rewait
|
|
95
|
+
code=$?
|
|
96
|
+
rm -rf "$D/broker.starting"
|
|
97
|
+
return $code
|
|
98
|
+
fi
|
|
99
|
+
# A starter killed before it finished would hold the folder for good.
|
|
100
|
+
s=
|
|
101
|
+
read -r s <"$D/broker.starting/pid" 2>/dev/null
|
|
102
|
+
[ -n "$s" ] && ! kill -0 "$s" 2>/dev/null && rm -rf "$D/broker.starting"
|
|
103
|
+
sleep 0.$(($$ % 9 + 1))
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
[ "${r%% *}" = go ] || while :; do
|
|
107
|
+
if IFS= read -r line <&3; then
|
|
108
|
+
gap=1 dead=
|
|
109
|
+
case $line in
|
|
110
|
+
go) break ;;
|
|
111
|
+
out\ *) printf '%s\n' "${line#out }" >&2 ;;
|
|
112
|
+
exit\ *) gone; exit "${line#exit }" ;;
|
|
113
|
+
# No broker could be started: Node waits instead, and picks the kept place up.
|
|
114
|
+
fat) trap - INT TERM HUP; gone; exec $N "$B" "$@" ;;
|
|
115
|
+
esac
|
|
116
|
+
else
|
|
117
|
+
nobroker && continue
|
|
118
|
+
trap - INT TERM HUP
|
|
119
|
+
note "$gaveup: waiting in Node"
|
|
120
|
+
$N "$B" _leave "$id" $$ keep
|
|
121
|
+
gone
|
|
122
|
+
exec $N "$B" "$@"
|
|
123
|
+
fi
|
|
124
|
+
done
|
|
125
|
+
|
|
126
|
+
gone
|
|
127
|
+
trap - INT TERM HUP
|
|
128
|
+
v=$1
|
|
129
|
+
shift
|
|
130
|
+
exec $N "$B" "$v" --lease "$id" "$@"
|