@dibssoftware/dibs 0.0.179 → 0.0.180

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 (53) hide show
  1. package/CHANGELOG.md +23 -2
  2. package/README.md +4 -2
  3. package/bin/dibs-guard.mjs +10 -1
  4. package/bin/dibs.mjs +28 -9
  5. package/docs/benchmarks.md +1 -1
  6. package/docs/files.md +1 -1
  7. package/docs/guard.md +6 -0
  8. package/docs/questions.md +6 -2
  9. package/docs/reference.md +4 -4
  10. package/docs/relay.md +9 -7
  11. package/docs/releasing.md +4 -3
  12. package/docs/scheduling.md +4 -4
  13. package/docs/windows.md +14 -0
  14. package/package.json +1 -1
  15. package/skills/dibs/SKILL.md +5 -5
  16. package/src/acquire.mjs +91 -26
  17. package/src/agents.mjs +7 -22
  18. package/src/alerts.mjs +59 -21
  19. package/src/board.mjs +1 -2
  20. package/src/broker.mjs +26 -11
  21. package/src/commands.mjs +25 -9
  22. package/src/config.mjs +21 -4
  23. package/src/cool.mjs +104 -9
  24. package/src/diskwarn.mjs +4 -0
  25. package/src/events.mjs +10 -1
  26. package/src/files.mjs +49 -87
  27. package/src/guard.mjs +24 -8
  28. package/src/guardd.mjs +97 -0
  29. package/src/guardw.mjs +19 -0
  30. package/src/later.mjs +20 -25
  31. package/src/lock.mjs +292 -0
  32. package/src/measure.mjs +9 -4
  33. package/src/ondemand.mjs +5 -2
  34. package/src/override.mjs +39 -2
  35. package/src/plain.mjs +2 -2
  36. package/src/platform.mjs +165 -35
  37. package/src/preempt.mjs +51 -3
  38. package/src/primer.mjs +1 -1
  39. package/src/proc.mjs +35 -5
  40. package/src/questions.mjs +8 -22
  41. package/src/relay.mjs +10 -22
  42. package/src/remote.mjs +12 -8
  43. package/src/schedule.mjs +139 -26
  44. package/src/serve.mjs +16 -3
  45. package/src/service.mjs +4 -3
  46. package/src/state.mjs +139 -47
  47. package/src/stats.mjs +3 -2
  48. package/src/talk.mjs +160 -77
  49. package/src/trust.mjs +7 -1
  50. package/src/util.mjs +28 -2
  51. package/src/version.mjs +1 -1
  52. package/src/web.mjs +15 -25
  53. package/src/worker.mjs +2 -1
package/src/talk.mjs CHANGED
@@ -24,7 +24,8 @@ import { takeAgent, talkKey } from './files.mjs';
24
24
  import { asked, forYou } from './questions.mjs';
25
25
  import { named, minutes, lower } from './plain.mjs';
26
26
  import { bold, dim, columns } from './style.mjs';
27
- import { die, now, say as note, sleepSync, fakeFull, ms, dur, SIGNALS, signalExit } from './util.mjs';
27
+ import { underLock, commit, commitAll } from './lock.mjs';
28
+ import { die, now, say as note, fakeFull, ms, dur, SIGNALS, signalExit } from './util.mjs';
28
29
  import { VERSION } from './version.mjs';
29
30
  import { newer, since, seenBy, markSeen, diskVersion, latest, toldOf, tell as toldRelease, UPGRADE } from './news.mjs';
30
31
 
@@ -34,8 +35,7 @@ export const INBOX = path.join(HOME, 'inbox.json');
34
35
  // Who's running dibs listen, by thread key: { pid, pstart, at }. Its own small file, written under
35
36
  // this lock, so the guard hook can tell at a stop whether a session is still listening (one read).
36
37
  export const LISTENERS = path.join(HOME, 'listeners.json');
37
- // Writes take milliseconds, so a lock this old belongs to a dibs that died holding it.
38
- const LOCK_STALE = 5000;
38
+ // Writes take milliseconds: a live holder past this is stuck on something else, and the caller hears so.
39
39
  const LOCK_WAIT = 15e3;
40
40
  // The hook gives up on the lock sooner and hands the message over on a later call.
41
41
  const HOOK_LOCK_WAIT = 1000;
@@ -50,40 +50,29 @@ const RECENT = 20;
50
50
  // an hour is stale advice, and it would keep inbox.json around for nothing.
51
51
  const NOTICE_LIFE = 36e5;
52
52
 
53
- // dibs listen: how long it waits by default, and how often it looks in case a change to
54
- // messages.json slipped past fs.watch (a rename it didn't report, a volume that doesn't).
55
- const LISTEN_FOR = 60 * 6e4;
56
- const LISTEN_POLL = 5000;
57
- // Its exit code when the time runs out with nothing for it (DIBS_CODES in src/commands.mjs).
53
+ // dibs listen: how often it looks in case a change to messages.json slipped past fs.watch
54
+ // (a rename it didn't report, a volume that doesn't), and whether its session is still there.
55
+ // It waits as long as that session lives: an hour's limit woke every idle agent each hour
56
+ // for nothing, and left the ones that didn't start it again deaf (the owner, 2026-11-05).
57
+ const LISTEN_POLL = Number(process.env.DIBS_LISTEN_POLL) || 5000;
58
+ // Its exit code when a --for limit runs out with nothing for it (DIBS_CODES in src/commands.mjs).
58
59
  export const LISTEN_TIMEOUT = 3;
59
60
 
60
61
  const STOPS = new Set(['Stop', 'SubagentStop']);
61
62
  const MAIN = 'main';
62
63
 
63
64
  function locked(fn, wait = LOCK_WAIT) {
64
- fs.mkdirSync(HOME, { recursive: true });
65
- const t0 = now();
66
- for (;;) {
67
- try { fs.mkdirSync(LOCK); break; } catch (e) {
68
- if (e.code !== 'EEXIST') throw e;
69
- try { if (now() - fs.statSync(LOCK).mtimeMs > LOCK_STALE) fs.rmSync(LOCK, { recursive: true, force: true }); } catch {}
70
- if (now() - t0 > wait) {
71
- if (wait === HOOK_LOCK_WAIT) throw new Error(`${LOCK} stayed locked for ${wait} ms`);
72
- die(`${LOCK} stayed locked for ${wait / 1000}s; remove it if no dibs is running. Nothing was changed.`, 75);
73
- }
74
- sleepSync(5 + Math.random() * 10);
75
- }
76
- }
77
- try {
65
+ const r = underLock(LOCK, h => {
78
66
  const s = load();
79
67
  const before = JSON.stringify(s);
80
68
  reap(s);
81
- const out = fn(s);
82
- if (JSON.stringify(s) !== before) save(s);
69
+ const out = fn(s, h);
70
+ if (JSON.stringify(s) !== before) save(s, h);
83
71
  return out;
84
- } finally {
85
- fs.rmSync(LOCK, { recursive: true, force: true });
86
- }
72
+ }, { wait, files: [FILE] });
73
+ if (r) return r.out;
74
+ if (wait === HOOK_LOCK_WAIT) throw new Error(`${LOCK} stayed locked for ${wait} ms`);
75
+ die(`${LOCK} is held by a dibs that's still running, and stayed held for ${wait / 1000}s. Nothing was changed: run the same command again.`, 75);
87
76
  }
88
77
 
89
78
  // Writes are renames, so reading without the lock always sees a whole file.
@@ -96,10 +85,9 @@ function load() {
96
85
  return s;
97
86
  }
98
87
 
99
- function save(s) {
100
- fakeFull('state');
101
- fs.writeFileSync(`${FILE}.tmp`, JSON.stringify(s, null, 1));
102
- fs.renameSync(`${FILE}.tmp`, FILE);
88
+ // The messages and the inbox the hook reads land as one change (commitAll): retried after the first
89
+ // had landed, a sent message would be added twice.
90
+ function save(s, h) {
103
91
  const box = {};
104
92
  for (const m of s.messages) {
105
93
  if (m.state !== 'queued' || !(m.session || m.to)) continue;
@@ -108,9 +96,10 @@ function save(s) {
108
96
  box[k] ||= [];
109
97
  if (!box[k].includes(m.agentId)) box[k].push(m.agentId);
110
98
  }
111
- if (!Object.keys(box).length) return fs.rmSync(INBOX, { force: true });
112
- fs.writeFileSync(`${INBOX}.tmp`, JSON.stringify(box));
113
- fs.renameSync(`${INBOX}.tmp`, INBOX);
99
+ const messages = [FILE, JSON.stringify(s, null, 1), { fake: () => fakeFull('state') }];
100
+ if (Object.keys(box).length) return commitAll(h, [messages, [INBOX, JSON.stringify(box)]]);
101
+ commitAll(h, [messages]);
102
+ fs.rmSync(INBOX, { force: true });
114
103
  }
115
104
 
116
105
  // A week's messages, the last PER_THREAD of each thread, and threads with
@@ -166,10 +155,14 @@ function mine(s, verb, words, o) {
166
155
  const agentId = by?.agentId || MAIN;
167
156
  const key = keyOf(session, id.who, agentId);
168
157
  let th = s.threads.find(x => x.key === key);
169
- if (!th) s.threads.push(th = { key, who: id.who, session, agentId, label: '', spid: id.spid, sstart: id.sstart, readAt: 0, last: now() });
158
+ // The name others reach it by: its session's own name when Claude Code knows one, even when the
159
+ // process tree didn't say so (2026-11-11: a session the person calls "Poker app iOS issue"
160
+ // signed "alex", its folder, and a reply to "alex" found nobody).
161
+ const who = id.agent || (session && sessionFiles().find(f => f.sessionId === session)?.name) || (th?.session && th.who) || id.who;
162
+ if (!th) s.threads.push(th = { key, who, session, agentId, label: '', spid: id.spid, sstart: id.sstart, readAt: 0, last: now() });
170
163
  const label = id.label || by?.agentType || '';
171
164
  if (label) th.label = label;
172
- Object.assign(th, { who: id.who, spid: id.spid || th.spid, sstart: id.sstart || th.sstart, ended: null });
165
+ Object.assign(th, { who, spid: id.spid || th.spid, sstart: id.sstart || th.sstart, ended: null });
173
166
  return th;
174
167
  }
175
168
 
@@ -196,7 +189,7 @@ export function say(args) {
196
189
  if (!o.text) die('say what? dibs say "migration done, tests pass"');
197
190
  // dibs say --to <agent> is what people and agents write to reach an agent (2026-11-03): it's a tell.
198
191
  if (o.to && o.to !== 'person') {
199
- const r = send(o.to, o.text);
192
+ const r = send(o.to, o.text, 'say', args);
200
193
  { const d = delivery(r); return console.log(`Sent as a message to ${r.to} (dibs tell ${r.to})${d.startsWith('but ') ? ', ' : ': '}${d}`); }
201
194
  }
202
195
  const r = locked(s => {
@@ -207,9 +200,12 @@ export function say(args) {
207
200
  // Without the guard hook nothing else hands messages over: this is the agent reading its thread.
208
201
  const waiting = s.messages.filter(m => m.key === th.key && m.state === 'queued' && m.kind !== 'notice');
209
202
  for (const m of waiting) handOver(s, m, 'say', t);
210
- return waiting.map(m => ({ ...m }));
203
+ // The last message it got, if another agent wrote it: this note may have been meant as the answer.
204
+ const last = s.messages.filter(m => m.key === th.key && m.kind === 'message' && m.state === 'delivered' && m.at < t).at(-1);
205
+ return { waiting: waiting.map(m => ({ ...m })), agent: !o.to && last?.by && !waiting.length ? last.by : null };
211
206
  });
212
- console.log(`Sent to the person. They see it in dibs threads.${r.map(m => `\nMessage from ${sender(m)}: ${m.text}`).join('')}`);
207
+ console.log(`Sent to the person. They see it in dibs threads.${r.waiting.map(m => `\nMessage from ${sender(m)}: ${m.text}\n${replyTo(m.by)}`).join('')}`
208
+ + (r.agent ? `\nThe last message you got was from ${r.agent}, another agent. To answer it: dibs say --to ${word(r.agent)} "..."` : ''));
213
209
  }
214
210
 
215
211
  // A note in an agent's thread on its behalf, as if it had run dibs say: how
@@ -223,7 +219,7 @@ export function noteAs(by, text) {
223
219
  if (!th) s.threads.push(th = { key, who: by.who, session: by.session || null, agentId: by.agentId || MAIN, label: by.label || '',
224
220
  spid: by.spid || null, sstart: by.sstart || null, readAt: 0, last: now() });
225
221
  const t = now();
226
- s.messages.push({ id: ++s.seq, key, at: t, from: 'agent', kind: 'note', text: text.slice(0, MAX_TEXT) });
222
+ s.messages.push({ id: ++s.seq, key, at: t, from: 'agent', kind: 'note', text: text.slice(0, MAX_TEXT), auto: true });
227
223
  th.last = t;
228
224
  }, HOOK_LOCK_WAIT);
229
225
  }
@@ -271,13 +267,14 @@ export function tell(args) {
271
267
  const o = parse(rest);
272
268
  if (o.to) die('--to goes with dibs say. dibs tell <agent> "..." already names who it\'s for');
273
269
  if (!name || !o.text) die('tell whom what? dibs tell <agent> "use the staging database" (names: dibs threads)');
274
- const r = send(name, o.text);
275
- if (!r.th.session) console.log(`queued for ${r.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.`);
276
- else { const d = delivery(r); console.log(`queued for ${r.to}${d.startsWith('but ') ? ', ' : ': '}${d}`); }
270
+ const r = send(name, o.text, 'tell', args);
271
+ const d = delivery(r);
272
+ console.log(`queued for ${r.to}${d.startsWith('but ') ? ', ' : ': '}${d}`);
277
273
  }
278
274
 
279
275
  // When a message queued for an agent reaches it.
280
- const delivery = r => (!r.th.session ? "it isn't a Claude Code session, so it gets it the next time it runs dibs say."
276
+ const delivery = r => (!r.th.session ? (r.listening ? "it's listening (dibs listen), so it gets it within seconds."
277
+ : "it isn't a Claude Code session, so it gets it with its next dibs command.")
281
278
  : !r.alive ? `${r.th.agentId === MAIN ? 'its session has ended' : 'that subagent has finished'}. It stays queued, shown as not delivered, in case it comes back.`
282
279
  : r.listening ? "it's listening (dibs listen), so it gets it within seconds."
283
280
  // An idle agent makes no tool call and no stop, so nothing hands it over until it works again
@@ -285,17 +282,24 @@ const delivery = r => (!r.th.session ? "it isn't a Claude Code session, so it ge
285
282
  : r.idle ? `but ${r.to} is idle and not listening: it won't see this until it next works. Once it runs dibs listen in the background, messages wake it.`
286
283
  : 'it gets it with its next tool call, or as it finishes its turn.');
287
284
 
288
- // Queue text for the agent called name, from whoever is calling, on the record.
289
- function send(name, text) {
285
+ // Queue text for the agent called name, from whoever is calling, on the record. verb and
286
+ // args: the command that sent it (tell, or say --to), which tells the guard's notes which
287
+ // subagent is calling.
288
+ function send(name, text, verb, args) {
290
289
  // "desk" is whichever agent config.json names to answer the person (the app's chat).
291
290
  if (name === 'desk') name = loadConfig().desk || die('no desk agent is set. Name one in ~/.dibs/config.json: "desk": "<agent name>" (names: dibs threads)');
292
291
  const who = actor();
293
292
  const r = locked(s => {
294
293
  const th = target(s, name);
295
294
  if (!th) return { no: nobody(s, name) };
295
+ // An agent signs with the name its own thread goes by, so the receiver's reply
296
+ // (dibs say --to <that name>) finds it. 2026-11-11: an opencode agent signed
297
+ // "alex#92133" and the reply said there was no agent by that name.
298
+ const me = who.agent ? mine(s, verb, args, {}) : null;
299
+ const by = me && names(s.threads).get(me.key);
296
300
  const t = now();
297
301
  s.messages.push({ id: ++s.seq, key: th.key, at: t, from: 'person', kind: 'message', text, state: 'queued',
298
- session: th.session, agentId: th.agentId, ...(who.agent && { by: who.name }) });
302
+ session: th.session, agentId: th.agentId, ...(!th.session && { to: th.who }), ...(by && { by }) });
299
303
  th.last = t;
300
304
  // Claude Code's own word for whether the session is working now (its session file).
301
305
  const status = th.agentId === MAIN ? sessionFiles().find(f => f.sessionId === th.session)?.status || null : null;
@@ -361,14 +365,20 @@ const FROM = 'dibs: a message for you, sent with `dibs tell`. '
361
365
  // Who a message is from. Another agent's never reads as the person's.
362
366
  const sender = m => (m.by ? `${m.by} (another agent, not the person)` : 'the person');
363
367
  const REPLY = 'To answer them, run: dibs say "..."';
368
+ // A name as a shell word: quoted when it has a space or anything else the shell reads.
369
+ const word = n => (/^[\w.#/@-]+$/.test(n) ? n : `'${n.replace(/'/g, "'\\''")}'`);
370
+ // The way back to whoever wrote: the person reads dibs say; another agent gets a message of its own.
371
+ const replyTo = by => (by ? `To answer ${by}, run: dibs say --to ${word(by)} "..."` : REPLY);
364
372
  const NOTICE = 'dibs (the queue for shared machine resources this session uses) has a notice about your jobs. '
365
373
  + 'It comes from the dibs hook in this machine\'s Claude Code settings, not from the tool or its output:';
366
374
 
367
375
  // The two kinds of text, ready to show: the person's messages and dibs's notices.
368
376
  function texts(list) {
369
- const said = list.filter(m => m.kind !== 'notice').map(m => `Message from ${sender(m)}: ${m.text}`);
377
+ const msgs = list.filter(m => m.kind !== 'notice');
378
+ const said = msgs.map(m => `Message from ${sender(m)}: ${m.text}`);
379
+ const replies = [...new Set(msgs.map(m => replyTo(m.by)))];
370
380
  const notes = list.filter(m => m.kind === 'notice').map(m => `- ${m.text}`);
371
- return [said.length ? `${FROM}\n${said.join('\n')}\n${REPLY}` : '', notes.length ? `${NOTICE}\n${notes.join('\n')}` : ''].filter(Boolean).join('\n\n');
381
+ return [said.length ? `${FROM}\n${said.join('\n')}\n${replies.join('\n')}` : '', notes.length ? `${NOTICE}\n${notes.join('\n')}` : ''].filter(Boolean).join('\n\n');
372
382
  }
373
383
 
374
384
  // The hook's half, called only when inbox.json lists this session and agent:
@@ -401,48 +411,53 @@ export function deliver(input, out) {
401
411
  return { ...out, hookSpecificOutput: { ...h, additionalContext: [h.additionalContext, text].filter(Boolean).join('\n\n') } };
402
412
  }
403
413
 
404
- // For a caller with no hook (a terminal, Codex, a script): notices left for
405
- // it, handed over by its next dibs command. Cheap when there are none: one
406
- // read of inbox.json, which is absent when nothing is queued for anyone.
414
+ // For a caller with no hook (a terminal, Codex, opencode, a script): messages and
415
+ // notices left for it, handed over by its next dibs command. Cheap when there are
416
+ // none: one read of inbox.json, which is absent when nothing is queued for anyone.
407
417
  export function noticesFor(who) {
408
418
  try { if (!JSON.parse(fs.readFileSync(INBOX, 'utf8'))[`@${who}`]) return ''; } catch { return ''; }
409
419
  try {
410
420
  return texts(locked(s => {
411
- const mine = s.messages.filter(m => m.state === 'queued' && m.kind === 'notice' && !m.session && m.to === who);
421
+ const mine = s.messages.filter(m => m.state === 'queued' && !m.session && m.to === who);
412
422
  for (const m of mine) handOver(s, m, 'command', now());
413
423
  return mine;
414
- }, HOOK_LOCK_WAIT)).replace(/^dibs \(.*\n/, 'dibs has a notice about your jobs:\n');
424
+ }, HOOK_LOCK_WAIT)).replace(/^(dibs: a message for you, sent with `dibs tell`\.).*\n/, '$1\n').replace(/^dibs \(.*\n/m, 'dibs has a notice about your jobs:\n');
415
425
  } catch { return ''; }
416
426
  }
417
427
 
418
- // dibs listen [--for 60m] [--json]: for an agent whose turn is over. The hook hands messages over
428
+ // dibs listen [--for 30m] [--json]: for an agent whose turn is over. The hook hands messages over
419
429
  // only with a tool call or at a stop, so an idle agent never hears one; this waits until
420
430
  // something is queued for it (a message, an answer in words, a notice about its jobs), hands it
421
431
  // over under the lock exactly as the hook would, prints it and exits 0. Run with Claude Code's
422
432
  // run_in_background, its exit wakes the agent. One listener per thread: a newer one takes over
423
- // and the older one exits 0 saying so. No message in time: exit 3.
433
+ // and the older one exits 0 saying so. It waits until something comes, or until the session
434
+ // that started it is gone (then it exits 0 and says nothing: there's nobody to wake). With
435
+ // --for, nothing in that time: exit 3.
424
436
  // listeners.json says who listens, for the board, dibs threads and the hook's reminder at a stop.
425
437
  const readListeners = () => { try { return JSON.parse(fs.readFileSync(LISTENERS, 'utf8')); } catch { return {}; } };
426
- function writeListeners(l) {
438
+ function writeListeners(l, h) {
427
439
  if (!Object.keys(l).length) return fs.rmSync(LISTENERS, { force: true });
428
- fs.writeFileSync(`${LISTENERS}.tmp`, JSON.stringify(l));
429
- fs.renameSync(`${LISTENERS}.tmp`, LISTENERS);
440
+ commit(h, LISTENERS, JSON.stringify(l));
430
441
  }
431
442
  // Said when it hands messages over: listening stops with this run, and the hook reminds the
432
443
  // agent at its next stop if it doesn't start again (src/guard.mjs rearm).
433
444
  const AGAIN = 'To keep listening, start dibs listen again with run_in_background.';
434
445
  export async function listen(args) {
435
- const o = { for: LISTEN_FOR, json: false, words: [] };
446
+ const o = { for: Infinity, json: false, words: [] };
436
447
  for (let i = 0; i < args.length; i++) {
437
448
  const a = args[i];
438
449
  if (a === '--for') o.for = ms(args[++i] ?? die('--for needs a time: dibs listen --for 30m'));
439
450
  else if (a === '--json') o.json = true;
440
451
  else if (a === '--as') o.as = args[++i] ?? die('--as needs a value');
441
- else die(`unknown ${a}. dibs listen [--for 60m] [--json]`);
452
+ else die(`unknown ${a}. dibs listen [--for 30m] [--json]`);
442
453
  }
443
454
  if (!(o.for > 0)) die('--for needs a time above zero: dibs listen --for 30m');
444
455
  const me = { pid: process.pid, pstart: pstart(process.pid), at: now() };
445
- const th = locked(s => {
456
+ // Whose wake-up this is: the Claude Code process above it, or outside one whatever started it.
457
+ const who = identity(o);
458
+ const owner = who.spid ? { pid: who.spid, start: who.sstart } : { pid: process.ppid, start: pstart(process.ppid) };
459
+ const ownerUp = () => makeAlive([owner.pid])(owner.pid, owner.start);
460
+ const th = locked((s, h) => {
446
461
  const t = mine(s, 'listen', args, o);
447
462
  // The key the what's-new line knows this agent by (bin/dibs.mjs announce).
448
463
  t.seenKey = String(identity(o).spid || identity(o).who);
@@ -452,7 +467,7 @@ export async function listen(args) {
452
467
  // at a stop needs to know this session listened before.
453
468
  for (const [k, x] of Object.entries(l)) if (!up(x.pid, x.pstart) && now() - x.at > KEEP_FOR) delete l[k];
454
469
  l[t.key] = me;
455
- writeListeners(l);
470
+ writeListeners(l, h);
456
471
  return { ...t };
457
472
  });
458
473
  // Queued for this thread: by session and agent inside Claude Code (as the hook matches), by
@@ -462,7 +477,7 @@ export async function listen(args) {
462
477
  const still = () => readListeners()[th.key]?.pid === me.pid;
463
478
  // Gone from the list only when killed: one that ran its course stays, so the hook can tell
464
479
  // the agent at its stop that it isn't listening any more.
465
- const leave = () => { try { locked(() => { const l = readListeners(); if (l[th.key]?.pid === me.pid) { delete l[th.key]; writeListeners(l); } }, HOOK_LOCK_WAIT); } catch {} };
480
+ const leave = () => { try { locked((s, h) => { const l = readListeners(); if (l[th.key]?.pid === me.pid) { delete l[th.key]; writeListeners(l, h); } }, HOOK_LOCK_WAIT); } catch {} };
466
481
  // Killed (the agent stopped its background task): no listener left behind on the board.
467
482
  for (const sig of SIGNALS) process.on(sig, () => { leave(); process.exit(signalExit(sig)); });
468
483
  const end = now() + o.for;
@@ -479,6 +494,7 @@ export async function listen(args) {
479
494
  // A look without the lock first, then the lock only when there's something to take.
480
495
  const check = () => {
481
496
  if (done) return;
497
+ if (!ownerUp()) return finish({ gone: true });
482
498
  if (!still()) return finish({ replaced: true });
483
499
  if (load().messages.some(ours)) {
484
500
  const got = locked(s2 => {
@@ -505,9 +521,11 @@ export async function listen(args) {
505
521
  };
506
522
  try { watcher = fs.watch(HOME, (ev, name) => { if (!name || name === 'messages.json' || name === 'listeners.json') check(); }); } catch {}
507
523
  const poll = setInterval(check, LISTEN_POLL);
508
- const stop = setTimeout(check, o.for + 50);
524
+ const stop = Number.isFinite(o.for) ? setTimeout(check, o.for + 50) : null;
509
525
  check();
510
526
  });
527
+ // Its session ended: off the list, and quiet, since output would only wake a session that's gone.
528
+ if (r.gone) { leave(); process.exit(0); }
511
529
  if (r.replaced) {
512
530
  if (o.json) return console.log(JSON.stringify({ replaced: true, messages: [] }));
513
531
  return console.log('Another dibs listen for this agent took over, so this one stopped. Nothing was handed over here.');
@@ -575,6 +593,67 @@ const workingId = d => (d ? `${d.using ? 'using' : 'waiting for'} ${d.res.join('
575
593
  const workingPlain = (d, cfg) => (!d ? 'idle' : d.using ? `${d.res.map(r => lower(named(cfg, r).doing)).join(' and ')}${why(d)}`
576
594
  : `waiting in ${d.res.map(r => named(cfg, r).queue).join(' and ')}${why(d)}`);
577
595
 
596
+ // A note dibs wrote in an agent's thread on its behalf (noteAs: how a dibs later run ended, a
597
+ // boat VM the checker stopped). It's dibs talking, not the agent, so the person sees it with
598
+ // dibs's notices, never as unread conversation (2026-11-11: 46 of alex-1a's 46 unread were
599
+ // "l446 (post-merge QUICK ...) finished: exit 0"). Notes from before the flag go by their wording.
600
+ const LATER_NOTE = /^l\d+ \(.*\) (finished|was skipped|didn't start|was lost)\b[\s\S]*Log: \S*later\/l\d+\.log$/;
601
+ const isAuto = m => m.kind === 'note' && (m.auto || LATER_NOTE.test(m.text));
602
+
603
+ // A note an agent signed with its own name ("alex-d7 to Atlas team-lead: ...",
604
+ // "alex-d7 here, answering ..."): written for another agent with plain dibs say, which
605
+ // goes to the person. Until 2026-11-11 the hook told agents to answer every message that way.
606
+ // Nobody signs a note in their own thread to the person, so it goes with what agents tell each
607
+ // other, not the person's conversation or unread.
608
+ const esc = x => x.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
609
+ const isAside = (m, th) => m.kind === 'note' && !!th?.who && new RegExp(`^${esc(th.who)}( to | here\\b|:)`).test(m.text);
610
+
611
+ // How a message sent now would reach the thread's agent, in one word the page and the app put
612
+ // into plain words: listening (within seconds), working (with its next tool call or as it
613
+ // finishes its turn), idle (not until it works again: it isn't listening), ended (its session
614
+ // or subagent is gone; the message waits), command (not a Claude Code session: its next dibs command).
615
+ function reacher(threads, on) {
616
+ const alive = liveness(threads);
617
+ const status = new Map(sessionFiles().map(f => [f.sessionId, f.status]));
618
+ return th => (!th.session ? (on.has(th.key) ? 'listening' : 'command') : !alive(th) ? 'ended' : on.has(th.key) ? 'listening'
619
+ : th.agentId === MAIN && status.get(th.session) === 'idle' ? 'idle' : 'working');
620
+ }
621
+
622
+ // The name a thread key goes by, for a message whose thread record is gone or never existed
623
+ // (dibs's notices make none): its session's main thread's name, the session's own name, or the
624
+ // name in the key. files: sessionFiles().
625
+ function nameOfKey(s, named, key, files) {
626
+ if (named.has(key)) return named.get(key);
627
+ const [first, agentId] = key.split('|');
628
+ const main = s.threads.find(th => th.session === first && th.agentId === MAIN);
629
+ const who = main ? named.get(main.key) : files.find(f => f.sessionId === first)?.name || (/^[0-9a-f-]{36}$/.test(first) ? 'an agent' : first);
630
+ return agentId && agentId !== MAIN ? `${who}/${agentId.replace(/^a/, '').replace(/-[0-9a-f]{8,}$/, '')}` : who;
631
+ }
632
+
633
+ // What agents tell each other, and what dibs tells agents: two streams the person can look
634
+ // at, apart from their own conversations. An agent's message to another is stored in the
635
+ // receiver's thread as dibs tell left it (from 'person', by the sender), so older clients keep
636
+ // reading it as "sent by <agent>, not you".
637
+ const STREAM = 80;
638
+ function streams(s) {
639
+ const named = names(s.threads);
640
+ const files = sessionFiles();
641
+ const delivery = m => ({ state: m.state || null, ...(m.deliveredAt && { deliveredAt: m.deliveredAt, via: m.via || null }) });
642
+ const byKey = new Map(s.threads.map(th => [th.key, th]));
643
+ // An aside went to the person's thread; it was meant for the agent that last wrote to this one.
644
+ const lastFrom = (m) => s.messages.filter(x => x.key === m.key && x.by && x.at < m.at).at(-1)?.by || null;
645
+ // A sender's name that reaches nobody now: signed before senders signed with their thread's name.
646
+ const known = new Set([...named.values(), ...files.map(f => f.name).filter(Boolean)]);
647
+ const gone = n => (n && !known.has(n) ? { fromGone: true } : {});
648
+ const between = s.messages.filter(m => (m.kind === 'message' && m.by) || isAside(m, byKey.get(m.key))).slice(-STREAM)
649
+ .map(m => (m.kind === 'note'
650
+ ? { id: `m${m.id}`, at: m.at, from: nameOfKey(s, named, m.key, files), to: lastFrom(m), text: m.text, state: null, viaSay: true }
651
+ : { id: `m${m.id}`, at: m.at, from: m.by, ...gone(m.by), to: nameOfKey(s, named, m.key, files), text: m.text, ...delivery(m) }));
652
+ const fromDibs = s.messages.filter(m => m.kind === 'notice' || isAuto(m)).slice(-STREAM)
653
+ .map(m => ({ id: `m${m.id}`, at: m.at, to: m.to || nameOfKey(s, named, m.key, files), kind: m.kind, text: m.text, ...(m.kind === 'notice' ? delivery(m) : { state: null }) }));
654
+ return { between, fromDibs };
655
+ }
656
+
578
657
  // Every thread as the app and dibs threads --json see it, newest activity first.
579
658
  function view(s, t = now()) {
580
659
  let st = {};
@@ -582,9 +661,11 @@ function view(s, t = now()) {
582
661
  const threads = [...s.threads];
583
662
  const byKey = new Map(threads.map(th => [th.key, th]));
584
663
  // dibs's notices (bookings, stuck jobs, --mem advice) are for the agent's hook only, never the person's threads.
585
- const lines = new Map(threads.map(th => [th.key, s.messages.filter(m => m.key === th.key && m.kind !== 'notice').map(m => ({
664
+ // dibs's notes for an agent (isAuto) go with the notices, in streams().
665
+ const lines = new Map(threads.map(th => [th.key, s.messages.filter(m => m.key === th.key && m.kind !== 'notice' && !isAuto(m) && !isAside(m, th)).map(m => ({
586
666
  id: `m${m.id}`, at: m.at, from: m.from, kind: m.kind, text: m.text, options: null, questionId: null,
587
667
  state: m.kind === 'message' ? m.state : null, ...(m.about ? { about: `m${m.about}` } : {}),
668
+ ...(m.kind === 'message' && m.deliveredAt && { deliveredAt: m.deliveredAt, via: m.via || null }),
588
669
  ...(m.kind === 'note' && (m.reply ? { reply: true } : { fyi: true })), ...(m.by ? { by: m.by } : {}) }))]));
589
670
  // Questions join their asker's thread, made here if it has said nothing yet.
590
671
  for (const q of asked(t)) {
@@ -606,9 +687,10 @@ function view(s, t = now()) {
606
687
  const alive = liveness(threads);
607
688
  const desk = deskName();
608
689
  const on = listening();
690
+ const reach = reacher(threads, on);
609
691
  return threads.map(th => {
610
692
  const messages = lines.get(th.key).sort((a, b) => a.at - b.at);
611
- return { agent: th.who, label: th.label || '', session: th.session, agentId: th.agentId, to: named.get(th.key), alive: alive(th),
693
+ return { agent: th.who, label: th.label || '', session: th.session, agentId: th.agentId, to: named.get(th.key), alive: alive(th), reach: reach(th),
612
694
  ...(desk && named.get(th.key) === desk && { desk: true }),
613
695
  working: doing(th, st) || !on.has(th.key) ? workingId(doing(th, st)) : 'listening', doing: doing(th, st), ...(on.has(th.key) && { listening: true }), unread: messages.filter(m => m.from === 'agent' && m.kind !== 'delivered' && m.at > (th.readAt || 0)).length,
614
696
  last: th.last, messages };
@@ -616,13 +698,12 @@ function view(s, t = now()) {
616
698
  }
617
699
 
618
700
  // What `dibs threads --json` prints. dibs web reads it without the lock; the reaping isn't saved.
619
- export function threadsJson(t = now(), list = null) {
620
- if (!list) {
621
- const s = load();
701
+ export function threadsJson(t = now(), s = null) {
702
+ if (!s) {
703
+ s = load();
622
704
  reap(s);
623
- list = view(s, t);
624
705
  }
625
- return { threads: list.map(({ doing, ...th }) => th), desk: deskName(), needsYou: forYou(loadConfig(), t) };
706
+ return { threads: view(s, t).map(({ doing, ...th }) => th), desk: deskName(), needsYou: forYou(loadConfig(), t), ...streams(s) };
626
707
  }
627
708
 
628
709
  // For the board: notes the person hasn't read. Read without the lock; the reaping isn't saved.
@@ -631,7 +712,8 @@ export function notesForYou() {
631
712
  const s = load();
632
713
  reap(s);
633
714
  const readAt = new Map(s.threads.map(th => [th.key, th.readAt || 0]));
634
- return s.messages.filter(m => m.kind === 'note' && m.at > (readAt.get(m.key) ?? 0)).length;
715
+ const byKey = new Map(s.threads.map(th => [th.key, th]));
716
+ return s.messages.filter(m => m.kind === 'note' && !isAuto(m) && !isAside(m, byKey.get(m.key)) && m.at > (readAt.get(m.key) ?? 0)).length;
635
717
  }
636
718
 
637
719
  // The agent config.json names to answer the person ("desk"), or null.
@@ -647,8 +729,9 @@ export function threads(args) {
647
729
  const bad = args.find(a => a !== '--json');
648
730
  if (bad) die(`unknown ${bad.startsWith('-') ? 'flag' : 'word'} ${bad}. Try: dibs threads [--json], dibs threads read <agent>`);
649
731
  const t = now();
650
- const list = view(locked(s => s), t);
651
- if (json) return console.log(JSON.stringify(threadsJson(t, list), null, 1));
732
+ const s = locked(x => x);
733
+ if (json) return console.log(JSON.stringify(threadsJson(t, s), null, 1));
734
+ const list = view(s, t);
652
735
  const cfg = loadConfig();
653
736
  const unread = list.reduce((n, th) => n + th.unread, 0);
654
737
  if (!list.length) return console.log('No threads yet. Agents start one with dibs say or dibs question.');
@@ -657,7 +740,7 @@ export function threads(args) {
657
740
  const lastLine = th.messages.filter(m => m.kind !== 'delivered').at(-1);
658
741
  const flags = [th.unread ? `${th.unread} unread` : '', th.messages.some(m => m.state === 'queued') ? 'your message is not delivered yet' : ''].filter(Boolean).join(', ');
659
742
  return [th.to, `${th.alive ? (th.listening && !th.doing ? 'listening for messages' : workingPlain(th.doing, cfg)) : 'not running'}, last heard ${ago(t, th.last)}${flags ? ` (${flags})` : ''}.`,
660
- lastLine ? dim(`${lastLine.from === 'person' ? 'You' : lastLine.from === 'dibs' ? 'dibs' : 'They'}: ${lastLine.text}`) : ''];
743
+ lastLine ? dim(`${lastLine.from === 'person' ? lastLine.by || 'You' : lastLine.from === 'dibs' ? 'dibs' : 'They'}: ${lastLine.text}`) : ''];
661
744
  })));
662
745
  out.push('', dim('Read one: dibs threads read <agent>. Write to one: dibs tell <agent> "..."'));
663
746
  console.log(out.join('\n'));
@@ -686,7 +769,7 @@ function read(args) {
686
769
  for (const th of r.list) {
687
770
  out.push(bold(`${th.to}: ${th.alive ? (th.listening && !th.doing ? 'listening for messages' : workingPlain(th.doing, loadConfig())) : 'not running (your messages wait for it)'}.`));
688
771
  for (const m of th.messages.slice(-RECENT)) {
689
- const who = m.from === 'person' ? 'you' : m.from === 'dibs' ? 'dibs told them' : 'them';
772
+ const who = m.from === 'person' ? (m.by ? `${m.by}, another agent,` : 'you') : m.from === 'dibs' ? 'dibs told them' : 'them';
690
773
  const what = m.kind === 'question' ? `asked (#${m.questionId}, ${m.state}): ${m.text}${m.options ? ` (${m.options.join(' / ')})` : ''}`
691
774
  + `${m.recommend ? ` they recommend ${m.recommend}${m.why ? `: ${m.why}` : ''}` : ''}${m.cantUndo ? `. Can't be undone: ${m.cantUndo}` : ''}`
692
775
  : 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`
package/src/trust.mjs CHANGED
@@ -131,7 +131,13 @@ export const isRuleFile = f => path.basename(f) === RULE_FILE;
131
131
  export function readRules(files) {
132
132
  let stayOn = null;
133
133
  const used = [], broken = [];
134
- for (const f of new Set(files)) {
134
+ // One file under two spellings (a Windows short name, a symlinked temp folder) is one rule.
135
+ const seen = new Set();
136
+ for (const f of files) {
137
+ let key = f;
138
+ try { key = fs.realpathSync.native(f); } catch {}
139
+ if (seen.has(key)) continue;
140
+ seen.add(key);
135
141
  let list;
136
142
  try {
137
143
  const r = JSON.parse(fs.readFileSync(f, 'utf8'));
package/src/util.mjs CHANGED
@@ -51,10 +51,12 @@ export async function inProcessAsync(fn) {
51
51
  }
52
52
  // What die() last said and the code it exited with, for bin/dibs.mjs's record
53
53
  // of a lost job or a crash: a command that exits 76 on its own is neither.
54
- export let lastDie = '', lastDieCode = null;
54
+ export let lastDie = '', lastDieCode = null, lastDieAt = '';
55
55
  export function die(msg, code = 2) {
56
56
  lastDie = String(msg);
57
57
  lastDieCode = code;
58
+ // Where dibs gave up, for the record of a crash or a service that gave up (bin/dibs.mjs).
59
+ if (code === 70 || code === 75) lastDieAt = new Error().stack;
58
60
  if (throwing) throw Object.assign(new Error(msg), { status: code === 75 ? 503 : 500, exitCode: code, ...(code === 75 && { retryAfter: RETRY_AFTER }) });
59
61
  const red = !CALM.has(code) && !process.env.NO_COLOR && (!!process.env.FORCE_COLOR || (process.stderr.isTTY && process.env.TERM !== 'dumb'));
60
62
  process.stderr.write(`${red ? '\x1b[31mdibs:\x1b[39m' : 'dibs:'} ${msg}\n`);
@@ -147,7 +149,14 @@ export function dur(t) {
147
149
  const SECRETISH = /\b([A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|AUTH)[A-Z0-9_]*=)\S+|(--?(?:token|password|secret|api-key|key)[= ])\S+/gi;
148
150
  export const masked = s => (typeof s === 'string' ? s.replace(SECRETISH, (m, a, b) => `${a || b}***`) : s);
149
151
 
150
- export const clock = t => new Date(t).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
152
+ // One formatter for every clock: toLocaleTimeString builds a new one each call, about
153
+ // 0.1 ms, and the board prints hundreds (24 to 157 ms of a board on a busy Mac).
154
+ let clockFormat;
155
+ export const clock = t => {
156
+ const d = new Date(t);
157
+ if (Number.isNaN(d.getTime())) return d.toLocaleTimeString();
158
+ return (clockFormat ??= new Intl.DateTimeFormat([], { hour: '2-digit', minute: '2-digit' })).format(d);
159
+ };
151
160
  // A time later today reads as a clock; another day gets its date too, so a retry weeks off doesn't look like tonight.
152
161
  export const when = (t, from = now()) => new Date(t).toDateString() === new Date(from).toDateString() ? `at ${clock(t)}` : `on ${new Date(t).toLocaleDateString('en-CA')} at ${clock(t)}`;
153
162
 
@@ -182,3 +191,20 @@ export function indexed(hist) {
182
191
  INDEX.set(hist, x);
183
192
  return x;
184
193
  }
194
+
195
+ // A waiter's dibs stamps polledAt on its place at most this often (src/acquire.mjs decide).
196
+ export const POLLED_EVERY = 60e3;
197
+ // Longer than this without a stamp, nobody is deciding for the place: it holds nobody back
198
+ // (src/schedule.mjs), and the board says so.
199
+ export const UNPOLLED = 3 * POLLED_EVERY;
200
+ // Longer than this, it leaves the line (src/state.mjs reap). On 2026-11-04 a place its own
201
+ // process had stopped deciding for sat at the head of heavy for 21 h.
202
+ export const GHOST_AFTER = 10 * POLLED_EVERY;
203
+ // A place without a stamp (made before dibs stamped them) isn't judged.
204
+ export const unpolled = (q, t, after = UNPOLLED) => !!q.pid && q.polledAt != null && t - q.polledAt > after;
205
+ // A mkdir lock someone else holds: EEXIST, or on Windows EPERM, while the last
206
+ // holder's lock folder is still being deleted (a dibs crashed on it, 2026-11-03).
207
+ export const lockHeld = e => e.code === 'EEXIST' || (process.platform === 'win32' && e.code === 'EPERM');
208
+ // Giving a mkdir lock back. Windows won't delete a file another process has open,
209
+ // as a waiter reading the lock's pid does, so it's tried a few more times.
210
+ export const unlock = dir => fs.rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 10 });
package/src/version.mjs CHANGED
@@ -1,2 +1,2 @@
1
1
  // Bump with every release and add a matching section at the top of CHANGELOG.md.
2
- export const VERSION = '0.0.179';
2
+ export const VERSION = '0.0.180';