@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.
- package/CHANGELOG.md +594 -0
- package/LICENSE +670 -0
- package/README.md +85 -2
- package/bin/dibs-guard.mjs +7 -0
- package/bin/dibs.mjs +548 -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/reference.md +157 -0
- package/docs/relay.md +196 -0
- package/docs/releasing.md +27 -0
- package/docs/scheduling.md +163 -0
- package/docs/simulators.md +17 -0
- package/package.json +45 -4
- package/skills/dibs/SKILL.md +183 -0
- package/src/acquire.mjs +700 -0
- package/src/admin.mjs +145 -0
- package/src/agents.mjs +145 -0
- package/src/alerts.mjs +499 -0
- package/src/answers.mjs +65 -0
- package/src/board.mjs +202 -0
- package/src/broker.mjs +369 -0
- package/src/commands.mjs +810 -0
- package/src/config.mjs +324 -0
- package/src/connect.mjs +106 -0
- package/src/cool.mjs +160 -0
- package/src/diskwarn.mjs +154 -0
- package/src/events.mjs +96 -0
- package/src/files.mjs +1123 -0
- package/src/guard.mjs +613 -0
- package/src/history.mjs +247 -0
- package/src/hogs.mjs +227 -0
- package/src/later.mjs +487 -0
- package/src/measure.mjs +262 -0
- package/src/news.mjs +101 -0
- package/src/nodecheck.mjs +17 -0
- package/src/notes.mjs +171 -0
- package/src/notices.mjs +160 -0
- package/src/ondemand.mjs +572 -0
- package/src/overlap.mjs +151 -0
- package/src/override.mjs +360 -0
- package/src/owner.mjs +30 -0
- package/src/plain.mjs +470 -0
- package/src/platform.mjs +357 -0
- package/src/preempt.mjs +438 -0
- package/src/primer.mjs +89 -0
- package/src/proc.mjs +99 -0
- package/src/progress.mjs +187 -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 +1020 -0
- package/src/scratch.mjs +61 -0
- package/src/serve.mjs +742 -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 +702 -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 +1119 -0
- package/src/worker.mjs +318 -0
package/src/talk.mjs
ADDED
|
@@ -0,0 +1,702 @@
|
|
|
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, ms, dur, SIGNALS, signalExit } from './util.mjs';
|
|
28
|
+
import { VERSION } from './version.mjs';
|
|
29
|
+
import { newer, since, seenBy, markSeen, diskVersion, latest, toldOf, tell as toldRelease, UPGRADE } from './news.mjs';
|
|
30
|
+
|
|
31
|
+
const FILE = path.join(HOME, 'messages.json');
|
|
32
|
+
const LOCK = path.join(HOME, 'messages.lock');
|
|
33
|
+
export const INBOX = path.join(HOME, 'inbox.json');
|
|
34
|
+
// Who's running dibs listen, by thread key: { pid, pstart, at }. Its own small file, written under
|
|
35
|
+
// this lock, so the guard hook can tell at a stop whether a session is still listening (one read).
|
|
36
|
+
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;
|
|
39
|
+
const LOCK_WAIT = 15e3;
|
|
40
|
+
// The hook gives up on the lock sooner and hands the message over on a later call.
|
|
41
|
+
const HOOK_LOCK_WAIT = 1000;
|
|
42
|
+
// A week of talk is plenty to scroll back through, and keeps the file small.
|
|
43
|
+
const KEEP_FOR = 7 * 24 * 36e5;
|
|
44
|
+
const PER_THREAD = 200;
|
|
45
|
+
// A message is a few sentences. This stops one paste from filling the file.
|
|
46
|
+
const MAX_TEXT = 4000;
|
|
47
|
+
// The plain list shows this many recent lines of a thread.
|
|
48
|
+
const RECENT = 20;
|
|
49
|
+
// A notice is about a job running now. One that hasn't reached its agent in
|
|
50
|
+
// an hour is stale advice, and it would keep inbox.json around for nothing.
|
|
51
|
+
const NOTICE_LIFE = 36e5;
|
|
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).
|
|
58
|
+
export const LISTEN_TIMEOUT = 3;
|
|
59
|
+
|
|
60
|
+
const STOPS = new Set(['Stop', 'SubagentStop']);
|
|
61
|
+
const MAIN = 'main';
|
|
62
|
+
|
|
63
|
+
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 {
|
|
78
|
+
const s = load();
|
|
79
|
+
const before = JSON.stringify(s);
|
|
80
|
+
reap(s);
|
|
81
|
+
const out = fn(s);
|
|
82
|
+
if (JSON.stringify(s) !== before) save(s);
|
|
83
|
+
return out;
|
|
84
|
+
} finally {
|
|
85
|
+
fs.rmSync(LOCK, { recursive: true, force: true });
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// Writes are renames, so reading without the lock always sees a whole file.
|
|
90
|
+
function load() {
|
|
91
|
+
let s = {};
|
|
92
|
+
try { s = JSON.parse(fs.readFileSync(FILE, 'utf8')); } catch (e) {
|
|
93
|
+
if (e.code !== 'ENOENT') note(`${FILE} was unreadable (${e.message}); starting with no messages.`);
|
|
94
|
+
}
|
|
95
|
+
s.seq ||= 0; s.threads ||= []; s.messages ||= [];
|
|
96
|
+
return s;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
function save(s) {
|
|
100
|
+
fakeFull('state');
|
|
101
|
+
fs.writeFileSync(`${FILE}.tmp`, JSON.stringify(s, null, 1));
|
|
102
|
+
fs.renameSync(`${FILE}.tmp`, FILE);
|
|
103
|
+
const box = {};
|
|
104
|
+
for (const m of s.messages) {
|
|
105
|
+
if (m.state !== 'queued' || !(m.session || m.to)) continue;
|
|
106
|
+
// A caller outside Claude Code has no hook: its next dibs command looks under "@who".
|
|
107
|
+
const k = m.session || `@${m.to}`;
|
|
108
|
+
box[k] ||= [];
|
|
109
|
+
if (!box[k].includes(m.agentId)) box[k].push(m.agentId);
|
|
110
|
+
}
|
|
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);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// A week's messages, the last PER_THREAD of each thread, and threads with
|
|
117
|
+
// anything left in them or any activity in the week.
|
|
118
|
+
function reap(s, t = now()) {
|
|
119
|
+
for (const m of s.messages) if (m.kind === 'notice' && m.state === 'queued' && t - m.at > NOTICE_LIFE) m.state = 'expired';
|
|
120
|
+
const recent = s.messages.filter(m => t - m.at < KEEP_FOR);
|
|
121
|
+
const count = new Map();
|
|
122
|
+
const kept = [];
|
|
123
|
+
for (const m of recent.reverse()) {
|
|
124
|
+
const n = (count.get(m.key) || 0) + 1;
|
|
125
|
+
count.set(m.key, n);
|
|
126
|
+
if (n <= PER_THREAD) kept.push(m);
|
|
127
|
+
}
|
|
128
|
+
s.messages = kept.reverse();
|
|
129
|
+
s.threads = s.threads.filter(th => count.has(th.key) || t - th.last < KEEP_FOR);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const keyOf = (session, who, agentId) => `${session || who}|${agentId || MAIN}`;
|
|
133
|
+
|
|
134
|
+
// What the person types to reach a thread: the session name for its main
|
|
135
|
+
// agent, name/label for a subagent (name/label#id when two share a label).
|
|
136
|
+
function names(threads) {
|
|
137
|
+
const out = new Map();
|
|
138
|
+
for (const th of threads) {
|
|
139
|
+
if (th.agentId === MAIN) { out.set(th.key, th.who); continue; }
|
|
140
|
+
const base = `${th.who}/${th.label || th.agentId.slice(0, 8)}`;
|
|
141
|
+
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)));
|
|
142
|
+
out.set(th.key, twins.length > 1 ? `${base}#${th.agentId.slice(0, 6)}` : base);
|
|
143
|
+
}
|
|
144
|
+
return out;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// Is anyone left to read the thread: its session's process is running and,
|
|
148
|
+
// for a subagent, it hasn't finished. Unknown (no process to check) counts as alive.
|
|
149
|
+
// A session's live process comes first: a resumed session runs under a new pid,
|
|
150
|
+
// and the thread's own pid is the one it had when the thread began.
|
|
151
|
+
function liveness(threads) {
|
|
152
|
+
const files = sessionFiles();
|
|
153
|
+
const up = makeAlive([...files.map(f => f.pid), ...threads.map(th => th.spid)].filter(Boolean));
|
|
154
|
+
const live = new Set(files.filter(f => up(f.pid)).map(f => f.sessionId));
|
|
155
|
+
const known = new Set(files.map(f => f.sessionId));
|
|
156
|
+
// A main session's thread marked ended is alive again once its session runs again; a finished subagent stays finished.
|
|
157
|
+
return th => (th.agentId === MAIN && live.has(th.session))
|
|
158
|
+
|| (!th.ended && (live.has(th.session) || (th.spid ? up(th.spid, th.sstart) : !known.has(th.session))));
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// The caller's own thread, made if it's new. o.as labels a subagent's thread.
|
|
162
|
+
function mine(s, verb, words, o) {
|
|
163
|
+
const id = identity(o);
|
|
164
|
+
const session = process.env.CLAUDE_CODE_SESSION_ID || sessionFiles().find(f => f.pid === id.spid)?.sessionId || null;
|
|
165
|
+
const by = session ? takeAgent(verb, [], talkKey(verb, words)) : null;
|
|
166
|
+
const agentId = by?.agentId || MAIN;
|
|
167
|
+
const key = keyOf(session, id.who, agentId);
|
|
168
|
+
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() });
|
|
170
|
+
const label = id.label || by?.agentType || '';
|
|
171
|
+
if (label) th.label = label;
|
|
172
|
+
Object.assign(th, { who: id.who, spid: id.spid || th.spid, sstart: id.sstart || th.sstart, ended: null });
|
|
173
|
+
return th;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function parse(args) {
|
|
177
|
+
const o = { words: [] };
|
|
178
|
+
for (let i = 0; i < args.length; i++) {
|
|
179
|
+
const a = args[i];
|
|
180
|
+
if (a === '--as') o.as = args[++i] ?? die('--as needs a value');
|
|
181
|
+
else if (a === '--to') o.to = args[++i] ?? die('--to needs a value: dibs say --to person "...", or an agent\'s name');
|
|
182
|
+
else if (a === '--json') o.json = true;
|
|
183
|
+
else if (a.startsWith('-') && a.length > 1) die(`unknown flag ${a}. Try: dibs help`);
|
|
184
|
+
else o.words.push(a);
|
|
185
|
+
}
|
|
186
|
+
o.text = o.words.join(' ').trim();
|
|
187
|
+
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.`);
|
|
188
|
+
return o;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// dibs say "text" [--as label] [--to person]: a note to the person in the
|
|
192
|
+
// agent's own thread. The person reads notes as FYI; --to person marks a
|
|
193
|
+
// reply to something they said (the desk's answers, a reply to a message).
|
|
194
|
+
export function say(args) {
|
|
195
|
+
const o = parse(args);
|
|
196
|
+
if (!o.text) die('say what? dibs say "migration done, tests pass"');
|
|
197
|
+
// dibs say --to <agent> is what people and agents write to reach an agent (2026-11-03): it's a tell.
|
|
198
|
+
if (o.to && o.to !== 'person') {
|
|
199
|
+
const r = send(o.to, o.text);
|
|
200
|
+
{ const d = delivery(r); return console.log(`Sent as a message to ${r.to} (dibs tell ${r.to})${d.startsWith('but ') ? ', ' : ': '}${d}`); }
|
|
201
|
+
}
|
|
202
|
+
const r = locked(s => {
|
|
203
|
+
const th = mine(s, 'say', args, o);
|
|
204
|
+
const t = now();
|
|
205
|
+
s.messages.push({ id: ++s.seq, key: th.key, at: t, from: 'agent', kind: 'note', text: o.text, ...(o.to && { reply: true }) });
|
|
206
|
+
th.last = t;
|
|
207
|
+
// Without the guard hook nothing else hands messages over: this is the agent reading its thread.
|
|
208
|
+
const waiting = s.messages.filter(m => m.key === th.key && m.state === 'queued' && m.kind !== 'notice');
|
|
209
|
+
for (const m of waiting) handOver(s, m, 'say', t);
|
|
210
|
+
return waiting.map(m => ({ ...m }));
|
|
211
|
+
});
|
|
212
|
+
console.log(`Sent to the person. They see it in dibs threads.${r.map(m => `\nMessage from ${sender(m)}: ${m.text}`).join('')}`);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// A note in an agent's thread on its behalf, as if it had run dibs say: how
|
|
216
|
+
// a job it scheduled with dibs later ended. by: { who, session, agentId,
|
|
217
|
+
// label, spid, sstart }, as the agent was when it scheduled it. Throws rather
|
|
218
|
+
// than exit when the lock stays taken, since its caller may be a service.
|
|
219
|
+
export function noteAs(by, text) {
|
|
220
|
+
locked(s => {
|
|
221
|
+
const key = keyOf(by.session, by.who, by.agentId);
|
|
222
|
+
let th = s.threads.find(x => x.key === key);
|
|
223
|
+
if (!th) s.threads.push(th = { key, who: by.who, session: by.session || null, agentId: by.agentId || MAIN, label: by.label || '',
|
|
224
|
+
spid: by.spid || null, sstart: by.sstart || null, readAt: 0, last: now() });
|
|
225
|
+
const t = now();
|
|
226
|
+
s.messages.push({ id: ++s.seq, key, at: t, from: 'agent', kind: 'note', text: text.slice(0, MAX_TEXT) });
|
|
227
|
+
th.last = t;
|
|
228
|
+
}, HOOK_LOCK_WAIT);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
// The thread the person means by name: the running Claude Code session by that name first
|
|
232
|
+
// (the most recently active, if two share it), then a live thread, then the newest that ended.
|
|
233
|
+
// A session's own record outranks an old thread: 2026-11-03, "dibs tell alex-2e" went to
|
|
234
|
+
// a thread with no session while session 8176ff00 by that name was running, and earlier tells
|
|
235
|
+
// went to sessions long dead (a4 to 8e, 30 to b1).
|
|
236
|
+
function target(s, name) {
|
|
237
|
+
const named = names(s.threads);
|
|
238
|
+
const alive = liveness(s.threads);
|
|
239
|
+
const found = s.threads.filter(th => named.get(th.key) === name).sort((a, b) => b.last - a.last);
|
|
240
|
+
const files = sessionFiles().filter(f => f.name === name);
|
|
241
|
+
const up = makeAlive(files.map(f => f.pid));
|
|
242
|
+
const running = files.filter(f => up(f.pid)).sort((a, b) => b.updated - a.updated);
|
|
243
|
+
// A live thread (a subagent's, or a caller's outside Claude Code) only when no session by that name runs.
|
|
244
|
+
const live = found.find(alive);
|
|
245
|
+
if (live && !running.length) return live;
|
|
246
|
+
const f = running[0] || (!found.length && files[0]);
|
|
247
|
+
if (f) {
|
|
248
|
+
const key = keyOf(f.sessionId, name, MAIN);
|
|
249
|
+
let th = s.threads.find(x => x.key === key);
|
|
250
|
+
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() });
|
|
251
|
+
// The session's thread under the name and process it has now: a session renamed or
|
|
252
|
+
// resumed keeps its thread, which still named the old ones (2026-11-02: "dibs tell
|
|
253
|
+
// alex-a4" answered "queued for alex-8e, but its session has ended").
|
|
254
|
+
else if (running.includes(f)) Object.assign(th, { who: name, spid: f.pid, sstart: pstart(f.pid), ended: null });
|
|
255
|
+
return th;
|
|
256
|
+
}
|
|
257
|
+
if (found.length) return found[0];
|
|
258
|
+
return null;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
const nobody = (s, name) => {
|
|
262
|
+
const known = [...new Set(names(s.threads).values())];
|
|
263
|
+
const running = sessionFiles().filter(f => f.name && makeAlive([f.pid])(f.pid)).map(f => f.name);
|
|
264
|
+
return `no agent called ${name}. ${known.length ? `Threads: ${known.join(', ')}. ` : ''}${running.length ? `Running sessions: ${[...new Set(running)].join(', ')}. ` : ''}See them: dibs threads`;
|
|
265
|
+
};
|
|
266
|
+
|
|
267
|
+
// dibs tell <agent> "text": the person, or another agent, queues a message for an agent.
|
|
268
|
+
// An agent's message says which agent sent it, never that the person did.
|
|
269
|
+
export function tell(args) {
|
|
270
|
+
const [name, ...rest] = args;
|
|
271
|
+
const o = parse(rest);
|
|
272
|
+
if (o.to) die('--to goes with dibs say. dibs tell <agent> "..." already names who it\'s for');
|
|
273
|
+
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}`); }
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// 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."
|
|
281
|
+
: !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
|
+
: r.listening ? "it's listening (dibs listen), so it gets it within seconds."
|
|
283
|
+
// An idle agent makes no tool call and no stop, so nothing hands it over until it works again
|
|
284
|
+
// (2026-11-03: two of the owner's messages sat unread for hours in an idle session).
|
|
285
|
+
: 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
|
+
: 'it gets it with its next tool call, or as it finishes its turn.');
|
|
287
|
+
|
|
288
|
+
// Queue text for the agent called name, from whoever is calling, on the record.
|
|
289
|
+
function send(name, text) {
|
|
290
|
+
// "desk" is whichever agent config.json names to answer the person (the app's chat).
|
|
291
|
+
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
|
+
const who = actor();
|
|
293
|
+
const r = locked(s => {
|
|
294
|
+
const th = target(s, name);
|
|
295
|
+
if (!th) return { no: nobody(s, name) };
|
|
296
|
+
const t = now();
|
|
297
|
+
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 }) });
|
|
299
|
+
th.last = t;
|
|
300
|
+
// Claude Code's own word for whether the session is working now (its session file).
|
|
301
|
+
const status = th.agentId === MAIN ? sessionFiles().find(f => f.sessionId === th.session)?.status || null : null;
|
|
302
|
+
return { th: { ...th }, alive: liveness([th])(th), listening: listening().has(th.key), idle: status === 'idle' };
|
|
303
|
+
});
|
|
304
|
+
if (r.no) die(r.no, 1);
|
|
305
|
+
const to = names([r.th]).get(r.th.key);
|
|
306
|
+
logChange('tell', { to });
|
|
307
|
+
return { ...r, to };
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// Mark one queued message handed over, with a line in the thread saying how.
|
|
311
|
+
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',
|
|
312
|
+
command: 'got it with its next dibs command', listen: 'got it while listening' };
|
|
313
|
+
function handOver(s, m, via, t) {
|
|
314
|
+
Object.assign(m, { state: 'delivered', deliveredAt: t, via });
|
|
315
|
+
if (m.kind === 'notice') return;
|
|
316
|
+
s.messages.push({ id: ++s.seq, key: m.key, at: t, from: 'agent', kind: 'delivered', text: VIA[via], about: m.id });
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
// dibs leaving an agent a notice about one of its jobs, handed over on its next
|
|
320
|
+
// tool call by the hook (or, outside Claude Code, its next dibs command). to is
|
|
321
|
+
// the lease or queue entry the notice is about: { sessionId, agentId, who }.
|
|
322
|
+
// once names the event ("idle:#12"): a notice already left under that name
|
|
323
|
+
// isn't left again, so a producer can call this on every pass. Best effort:
|
|
324
|
+
// a busy lock or a full disk only means the agent doesn't hear about it.
|
|
325
|
+
export function notify(to, once, text) {
|
|
326
|
+
const session = to.sessionId || to.session || null;
|
|
327
|
+
if (!session && !to.who) return false;
|
|
328
|
+
const agentId = to.agentId || MAIN;
|
|
329
|
+
try {
|
|
330
|
+
return locked(s => {
|
|
331
|
+
const same = m => m.kind === 'notice' && m.once === once && m.session === session && m.agentId === agentId && (session || m.to === to.who);
|
|
332
|
+
if (s.messages.some(same)) return false;
|
|
333
|
+
s.messages.push({ id: ++s.seq, key: keyOf(session, to.who, agentId), at: now(), from: 'dibs', kind: 'notice', text: text.slice(0, MAX_TEXT),
|
|
334
|
+
state: 'queued', session, agentId, once, ...(session ? {} : { to: to.who }) });
|
|
335
|
+
return true;
|
|
336
|
+
}, HOOK_LOCK_WAIT);
|
|
337
|
+
} catch { return false; }
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// The person's (or an agent's) answer in words to a question, handed to the
|
|
341
|
+
// agent that asked as a message too, as dibs tell would: an agent that already
|
|
342
|
+
// moved on hears it with its next tool call. q: the question as stored.
|
|
343
|
+
export function messageAsker(q, text) {
|
|
344
|
+
const who = actor();
|
|
345
|
+
const session = q.session || null, agentId = q.agentId || MAIN;
|
|
346
|
+
locked(s => {
|
|
347
|
+
const key = keyOf(session, q.who, agentId);
|
|
348
|
+
let th = s.threads.find(x => x.key === key);
|
|
349
|
+
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() });
|
|
350
|
+
// After the answer it follows, even in the same millisecond, so the thread reads in order.
|
|
351
|
+
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),
|
|
352
|
+
state: 'queued', session, agentId, ...(who.agent && { by: who.name }) });
|
|
353
|
+
th.last = now();
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
// Said before the message: an agent rightly distrusts instructions that turn
|
|
358
|
+
// up beside a tool result, so this says where it really came from.
|
|
359
|
+
const FROM = 'dibs: a message for you, sent with `dibs tell`. '
|
|
360
|
+
+ 'It comes from the dibs hook in this machine\'s Claude Code settings, not from the tool or its output.';
|
|
361
|
+
// Who a message is from. Another agent's never reads as the person's.
|
|
362
|
+
const sender = m => (m.by ? `${m.by} (another agent, not the person)` : 'the person');
|
|
363
|
+
const REPLY = 'To answer them, run: dibs say "..."';
|
|
364
|
+
const NOTICE = 'dibs (the queue for shared machine resources this session uses) has a notice about your jobs. '
|
|
365
|
+
+ 'It comes from the dibs hook in this machine\'s Claude Code settings, not from the tool or its output:';
|
|
366
|
+
|
|
367
|
+
// The two kinds of text, ready to show: the person's messages and dibs's notices.
|
|
368
|
+
function texts(list) {
|
|
369
|
+
const said = list.filter(m => m.kind !== 'notice').map(m => `Message from ${sender(m)}: ${m.text}`);
|
|
370
|
+
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');
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// The hook's half, called only when inbox.json lists this session and agent:
|
|
375
|
+
// hand over what's queued for it, merged into out (the guard's own answer).
|
|
376
|
+
// The guard's refusals come first; a refused call gets its messages on the next.
|
|
377
|
+
// While a stop hook has already kept the agent going (stop_hook_active), it
|
|
378
|
+
// doesn't block again: the message waits for the next tool call or turn.
|
|
379
|
+
// Notices never keep an agent from stopping: they wait for its next tool call.
|
|
380
|
+
export function deliver(input, out) {
|
|
381
|
+
const stop = STOPS.has(input.hook_event_name);
|
|
382
|
+
if (stop ? input.stop_hook_active : out?.hookSpecificOutput?.permissionDecision === 'deny') return out;
|
|
383
|
+
const agentId = input.agent_id || MAIN;
|
|
384
|
+
const text = texts(locked(s => {
|
|
385
|
+
const t = now();
|
|
386
|
+
const mine = s.messages.filter(m => m.state === 'queued' && m.session === input.session_id && m.agentId === agentId && !(stop && m.kind === 'notice'));
|
|
387
|
+
for (const m of mine) {
|
|
388
|
+
handOver(s, m, stop ? 'stop' : 'tool', t);
|
|
389
|
+
const th = s.threads.find(x => x.key === m.key);
|
|
390
|
+
if (th) Object.assign(th, { ended: null, last: t });
|
|
391
|
+
}
|
|
392
|
+
return mine;
|
|
393
|
+
}, HOOK_LOCK_WAIT));
|
|
394
|
+
if (!text) return out;
|
|
395
|
+
// additionalContext keeps the agent going with the message as hook feedback.
|
|
396
|
+
// decision: 'block' did too, but Claude Code shows its reason as a "Stop hook
|
|
397
|
+
// blocking error", and agents read the person's message as a failure (2026-11-03).
|
|
398
|
+
if (stop) return { hookSpecificOutput: { hookEventName: input.hook_event_name, additionalContext: text } };
|
|
399
|
+
if (!out) return { hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: text } };
|
|
400
|
+
const h = out.hookSpecificOutput;
|
|
401
|
+
return { ...out, hookSpecificOutput: { ...h, additionalContext: [h.additionalContext, text].filter(Boolean).join('\n\n') } };
|
|
402
|
+
}
|
|
403
|
+
|
|
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.
|
|
407
|
+
export function noticesFor(who) {
|
|
408
|
+
try { if (!JSON.parse(fs.readFileSync(INBOX, 'utf8'))[`@${who}`]) return ''; } catch { return ''; }
|
|
409
|
+
try {
|
|
410
|
+
return texts(locked(s => {
|
|
411
|
+
const mine = s.messages.filter(m => m.state === 'queued' && m.kind === 'notice' && !m.session && m.to === who);
|
|
412
|
+
for (const m of mine) handOver(s, m, 'command', now());
|
|
413
|
+
return mine;
|
|
414
|
+
}, HOOK_LOCK_WAIT)).replace(/^dibs \(.*\n/, 'dibs has a notice about your jobs:\n');
|
|
415
|
+
} catch { return ''; }
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// dibs listen [--for 60m] [--json]: for an agent whose turn is over. The hook hands messages over
|
|
419
|
+
// only with a tool call or at a stop, so an idle agent never hears one; this waits until
|
|
420
|
+
// something is queued for it (a message, an answer in words, a notice about its jobs), hands it
|
|
421
|
+
// over under the lock exactly as the hook would, prints it and exits 0. Run with Claude Code's
|
|
422
|
+
// 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.
|
|
424
|
+
// listeners.json says who listens, for the board, dibs threads and the hook's reminder at a stop.
|
|
425
|
+
const readListeners = () => { try { return JSON.parse(fs.readFileSync(LISTENERS, 'utf8')); } catch { return {}; } };
|
|
426
|
+
function writeListeners(l) {
|
|
427
|
+
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);
|
|
430
|
+
}
|
|
431
|
+
// Said when it hands messages over: listening stops with this run, and the hook reminds the
|
|
432
|
+
// agent at its next stop if it doesn't start again (src/guard.mjs rearm).
|
|
433
|
+
const AGAIN = 'To keep listening, start dibs listen again with run_in_background.';
|
|
434
|
+
export async function listen(args) {
|
|
435
|
+
const o = { for: LISTEN_FOR, json: false, words: [] };
|
|
436
|
+
for (let i = 0; i < args.length; i++) {
|
|
437
|
+
const a = args[i];
|
|
438
|
+
if (a === '--for') o.for = ms(args[++i] ?? die('--for needs a time: dibs listen --for 30m'));
|
|
439
|
+
else if (a === '--json') o.json = true;
|
|
440
|
+
else if (a === '--as') o.as = args[++i] ?? die('--as needs a value');
|
|
441
|
+
else die(`unknown ${a}. dibs listen [--for 60m] [--json]`);
|
|
442
|
+
}
|
|
443
|
+
if (!(o.for > 0)) die('--for needs a time above zero: dibs listen --for 30m');
|
|
444
|
+
const me = { pid: process.pid, pstart: pstart(process.pid), at: now() };
|
|
445
|
+
const th = locked(s => {
|
|
446
|
+
const t = mine(s, 'listen', args, o);
|
|
447
|
+
// The key the what's-new line knows this agent by (bin/dibs.mjs announce).
|
|
448
|
+
t.seenKey = String(identity(o).spid || identity(o).who);
|
|
449
|
+
const l = readListeners();
|
|
450
|
+
const up = makeAlive(Object.values(l).map(x => x.pid));
|
|
451
|
+
// Dead ones stay until a new listener for the same thread replaces them: the hook's reminder
|
|
452
|
+
// at a stop needs to know this session listened before.
|
|
453
|
+
for (const [k, x] of Object.entries(l)) if (!up(x.pid, x.pstart) && now() - x.at > KEEP_FOR) delete l[k];
|
|
454
|
+
l[t.key] = me;
|
|
455
|
+
writeListeners(l);
|
|
456
|
+
return { ...t };
|
|
457
|
+
});
|
|
458
|
+
// Queued for this thread: by session and agent inside Claude Code (as the hook matches), by
|
|
459
|
+
// thread outside it, plus notices left for the name when there's no session.
|
|
460
|
+
const ours = m => m.state === 'queued' && (th.session ? m.session === th.session && m.agentId === th.agentId
|
|
461
|
+
: m.key === th.key || (m.kind === 'notice' && !m.session && m.to === th.who));
|
|
462
|
+
const still = () => readListeners()[th.key]?.pid === me.pid;
|
|
463
|
+
// Gone from the list only when killed: one that ran its course stays, so the hook can tell
|
|
464
|
+
// 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 {} };
|
|
466
|
+
// Killed (the agent stopped its background task): no listener left behind on the board.
|
|
467
|
+
for (const sig of SIGNALS) process.on(sig, () => { leave(); process.exit(signalExit(sig)); });
|
|
468
|
+
const end = now() + o.for;
|
|
469
|
+
const r = await new Promise(resolve => {
|
|
470
|
+
let watcher = null, done = false;
|
|
471
|
+
const finish = x => {
|
|
472
|
+
if (done) return;
|
|
473
|
+
done = true;
|
|
474
|
+
watcher?.close();
|
|
475
|
+
clearInterval(poll);
|
|
476
|
+
clearTimeout(stop);
|
|
477
|
+
resolve(x);
|
|
478
|
+
};
|
|
479
|
+
// A look without the lock first, then the lock only when there's something to take.
|
|
480
|
+
const check = () => {
|
|
481
|
+
if (done) return;
|
|
482
|
+
if (!still()) return finish({ replaced: true });
|
|
483
|
+
if (load().messages.some(ours)) {
|
|
484
|
+
const got = locked(s2 => {
|
|
485
|
+
if (!still()) return { replaced: true };
|
|
486
|
+
const list = s2.messages.filter(ours);
|
|
487
|
+
if (!list.length) return null;
|
|
488
|
+
const t = now();
|
|
489
|
+
for (const m of list) {
|
|
490
|
+
handOver(s2, m, 'listen', t);
|
|
491
|
+
const x = s2.threads.find(y => y.key === m.key);
|
|
492
|
+
if (x) Object.assign(x, { ended: null, last: t });
|
|
493
|
+
}
|
|
494
|
+
return { got: list.map(m => ({ ...m })) };
|
|
495
|
+
});
|
|
496
|
+
if (got) return finish(got);
|
|
497
|
+
}
|
|
498
|
+
// dibs itself changed under this listener: what's on disk is what the agent's next call runs.
|
|
499
|
+
// Once per agent and version: seen.json, which the what's-new line shares, says what it heard.
|
|
500
|
+
const v = diskVersion();
|
|
501
|
+
if (v && newer(v, VERSION) && newer(v, seenBy(th.seenKey) || VERSION)) return finish({ updated: v });
|
|
502
|
+
const out = latest();
|
|
503
|
+
if (out && newer(out, VERSION) && toldOf(th.key) !== out) return finish({ release: out });
|
|
504
|
+
if (now() >= end) finish({ timeout: true });
|
|
505
|
+
};
|
|
506
|
+
try { watcher = fs.watch(HOME, (ev, name) => { if (!name || name === 'messages.json' || name === 'listeners.json') check(); }); } catch {}
|
|
507
|
+
const poll = setInterval(check, LISTEN_POLL);
|
|
508
|
+
const stop = setTimeout(check, o.for + 50);
|
|
509
|
+
check();
|
|
510
|
+
});
|
|
511
|
+
if (r.replaced) {
|
|
512
|
+
if (o.json) return console.log(JSON.stringify({ replaced: true, messages: [] }));
|
|
513
|
+
return console.log('Another dibs listen for this agent took over, so this one stopped. Nothing was handed over here.');
|
|
514
|
+
}
|
|
515
|
+
// Heard here, so not again from the what's-new line on the agent's next dibs call.
|
|
516
|
+
if (r.updated) {
|
|
517
|
+
const changes = since(seenBy(th.seenKey) || VERSION, r.updated);
|
|
518
|
+
markSeen(th.seenKey, r.updated);
|
|
519
|
+
if (o.json) return console.log(JSON.stringify({ updated: r.updated, changes, again: AGAIN }));
|
|
520
|
+
return console.log(`dibs was updated to ${r.updated}. What changed for you:\n\n${changes.map(c => `${c.version}\n${c.body}`).join('\n\n') || '(no notes)'}\n\n${AGAIN}`);
|
|
521
|
+
}
|
|
522
|
+
if (r.release) {
|
|
523
|
+
toldRelease(th.key, r.release);
|
|
524
|
+
if (o.json) return console.log(JSON.stringify({ release: r.release, have: VERSION, upgrade: UPGRADE, again: AGAIN }));
|
|
525
|
+
return console.log(`dibs ${r.release} is out (you have ${VERSION}). The person upgrades with: ${UPGRADE}\nDon't upgrade it yourself; mention it to the person if it matters to your work.\n\n${AGAIN}`);
|
|
526
|
+
}
|
|
527
|
+
if (r.timeout) {
|
|
528
|
+
if (o.json) console.log(JSON.stringify({ timeout: true, messages: [] }));
|
|
529
|
+
else console.log(`no messages in ${dur(o.for)}; run it again to keep listening`);
|
|
530
|
+
process.exit(LISTEN_TIMEOUT);
|
|
531
|
+
}
|
|
532
|
+
if (o.json) return console.log(JSON.stringify({ messages: r.got.map(m => ({ from: m.kind === 'notice' ? 'dibs' : m.by ? 'agent' : 'person', ...(m.by && { by: m.by }), kind: m.kind, text: m.text, at: m.at })), again: AGAIN }));
|
|
533
|
+
console.log(`${texts(r.got)}\n\n${AGAIN}`);
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
// Who's listening now, by thread key, read without the lock: for the board and dibs threads.
|
|
537
|
+
export function listening() {
|
|
538
|
+
const l = Object.entries(readListeners());
|
|
539
|
+
if (!l.length) return new Map();
|
|
540
|
+
const up = makeAlive(l.map(([, x]) => x.pid));
|
|
541
|
+
return new Map(l.filter(([, x]) => up(x.pid, x.pstart)));
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
// The names listening, for the board: as dibs tell takes them.
|
|
545
|
+
export function listeners() {
|
|
546
|
+
if (!fs.existsSync(FILE)) return [];
|
|
547
|
+
const on = listening();
|
|
548
|
+
if (!on.size) return [];
|
|
549
|
+
const s = load();
|
|
550
|
+
const named = names(s.threads);
|
|
551
|
+
return s.threads.filter(th => on.has(th.key)).map(th => named.get(th.key));
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
// A subagent that finished: its thread shows it can't be reached until it runs again.
|
|
555
|
+
export function finished(input) {
|
|
556
|
+
if (!input.agent_id || !fs.existsSync(FILE)) return;
|
|
557
|
+
const key = keyOf(input.session_id, null, input.agent_id);
|
|
558
|
+
if (!load().threads.some(th => th.key === key && !th.ended)) return;
|
|
559
|
+
locked(s => { const th = s.threads.find(x => x.key === key); if (th) th.ended = now(); }, HOOK_LOCK_WAIT);
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
// What each thread's agent is doing now, from the state file read without its
|
|
563
|
+
// lock: the lease it holds or the request it waits on, or null when idle.
|
|
564
|
+
function doing(th, st) {
|
|
565
|
+
const ours = x => x.who === th.who && (th.agentId === MAIN ? !x.agentId || x.agentId === MAIN : x.agentId === th.agentId);
|
|
566
|
+
const l = (st.leases || []).find(ours);
|
|
567
|
+
if (l) return { using: true, res: l.res, purpose: l.purpose };
|
|
568
|
+
const q = (st.queue || []).find(ours);
|
|
569
|
+
return q ? { using: false, res: q.res, purpose: q.purpose } : null;
|
|
570
|
+
}
|
|
571
|
+
const why = d => (d.purpose ? ` for "${d.purpose}"` : '');
|
|
572
|
+
// For --json, by resource id, which the Mac app reads: "using sim for "snapshots"", "waiting for xcode-build".
|
|
573
|
+
const workingId = d => (d ? `${d.using ? 'using' : 'waiting for'} ${d.res.join(', ')}${why(d)}` : 'idle');
|
|
574
|
+
// For the terminal, in the board's words: "using the simulator for "snapshots"", "deploying", "waiting in the Xcode build queue".
|
|
575
|
+
const workingPlain = (d, cfg) => (!d ? 'idle' : d.using ? `${d.res.map(r => lower(named(cfg, r).doing)).join(' and ')}${why(d)}`
|
|
576
|
+
: `waiting in ${d.res.map(r => named(cfg, r).queue).join(' and ')}${why(d)}`);
|
|
577
|
+
|
|
578
|
+
// Every thread as the app and dibs threads --json see it, newest activity first.
|
|
579
|
+
function view(s, t = now()) {
|
|
580
|
+
let st = {};
|
|
581
|
+
try { st = JSON.parse(fs.readFileSync(paths.state, 'utf8')); } catch {}
|
|
582
|
+
const threads = [...s.threads];
|
|
583
|
+
const byKey = new Map(threads.map(th => [th.key, th]));
|
|
584
|
+
// 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 => ({
|
|
586
|
+
id: `m${m.id}`, at: m.at, from: m.from, kind: m.kind, text: m.text, options: null, questionId: null,
|
|
587
|
+
state: m.kind === 'message' ? m.state : null, ...(m.about ? { about: `m${m.about}` } : {}),
|
|
588
|
+
...(m.kind === 'note' && (m.reply ? { reply: true } : { fyi: true })), ...(m.by ? { by: m.by } : {}) }))]));
|
|
589
|
+
// Questions join their asker's thread, made here if it has said nothing yet.
|
|
590
|
+
for (const q of asked(t)) {
|
|
591
|
+
const key = keyOf(q.session, q.who, q.agentId);
|
|
592
|
+
if (!byKey.has(key)) {
|
|
593
|
+
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 };
|
|
594
|
+
byKey.set(key, th); threads.push(th); lines.set(key, []);
|
|
595
|
+
}
|
|
596
|
+
const th = byKey.get(key);
|
|
597
|
+
th.last = Math.max(th.last, q.answeredAt || q.asked);
|
|
598
|
+
const about = { recommend: q.recommend ?? null, why: q.purpose || null, oneWay: !!q.oneWay, cantUndo: q.cantUndo ?? null };
|
|
599
|
+
// A two-way door the agent walked through itself: shown as done, not asked.
|
|
600
|
+
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; }
|
|
601
|
+
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 });
|
|
602
|
+
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,
|
|
603
|
+
...(q.freeText && { freeText: true }), ...(q.answeredBy && { by: q.answeredBy }) });
|
|
604
|
+
}
|
|
605
|
+
const named = names(threads);
|
|
606
|
+
const alive = liveness(threads);
|
|
607
|
+
const desk = deskName();
|
|
608
|
+
const on = listening();
|
|
609
|
+
return threads.map(th => {
|
|
610
|
+
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),
|
|
612
|
+
...(desk && named.get(th.key) === desk && { desk: true }),
|
|
613
|
+
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
|
+
last: th.last, messages };
|
|
615
|
+
}).sort((a, b) => b.last - a.last);
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
// 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();
|
|
622
|
+
reap(s);
|
|
623
|
+
list = view(s, t);
|
|
624
|
+
}
|
|
625
|
+
return { threads: list.map(({ doing, ...th }) => th), desk: deskName(), needsYou: forYou(loadConfig(), t) };
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
// For the board: notes the person hasn't read. Read without the lock; the reaping isn't saved.
|
|
629
|
+
export function notesForYou() {
|
|
630
|
+
if (!fs.existsSync(FILE)) return 0;
|
|
631
|
+
const s = load();
|
|
632
|
+
reap(s);
|
|
633
|
+
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;
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
// The agent config.json names to answer the person ("desk"), or null.
|
|
638
|
+
function deskName() { try { return loadConfig().desk || null; } catch { return null; } }
|
|
639
|
+
|
|
640
|
+
const plural = (n, word) => `${n} ${word}${n === 1 ? '' : 's'}`;
|
|
641
|
+
const ago = (t, at) => (t - at < 6e4 ? 'just now' : `${minutes(t - at)} ago`);
|
|
642
|
+
|
|
643
|
+
// dibs threads [--json] | dibs threads read <agent>
|
|
644
|
+
export function threads(args) {
|
|
645
|
+
if (args[0] === 'read') return read(args.slice(1));
|
|
646
|
+
const json = args.includes('--json');
|
|
647
|
+
const bad = args.find(a => a !== '--json');
|
|
648
|
+
if (bad) die(`unknown ${bad.startsWith('-') ? 'flag' : 'word'} ${bad}. Try: dibs threads [--json], dibs threads read <agent>`);
|
|
649
|
+
const t = now();
|
|
650
|
+
const list = view(locked(s => s), t);
|
|
651
|
+
if (json) return console.log(JSON.stringify(threadsJson(t, list), null, 1));
|
|
652
|
+
const cfg = loadConfig();
|
|
653
|
+
const unread = list.reduce((n, th) => n + th.unread, 0);
|
|
654
|
+
if (!list.length) return console.log('No threads yet. Agents start one with dibs say or dibs question.');
|
|
655
|
+
const out = [bold(`${plural(list.length, 'thread')}${unread ? `, ${unread} unread` : ', nothing unread'}.`), ''];
|
|
656
|
+
out.push(...columns(list.map(th => {
|
|
657
|
+
const lastLine = th.messages.filter(m => m.kind !== 'delivered').at(-1);
|
|
658
|
+
const flags = [th.unread ? `${th.unread} unread` : '', th.messages.some(m => m.state === 'queued') ? 'your message is not delivered yet' : ''].filter(Boolean).join(', ');
|
|
659
|
+
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}`) : ''];
|
|
661
|
+
})));
|
|
662
|
+
out.push('', dim('Read one: dibs threads read <agent>. Write to one: dibs tell <agent> "..."'));
|
|
663
|
+
console.log(out.join('\n'));
|
|
664
|
+
}
|
|
665
|
+
|
|
666
|
+
// dibs threads read <agent>: the conversation, and its agent's messages marked seen.
|
|
667
|
+
function read(args) {
|
|
668
|
+
const name = args[0];
|
|
669
|
+
if (!name || args.length > 1) die('which thread? dibs threads read <agent> (names: dibs threads)');
|
|
670
|
+
const t = now();
|
|
671
|
+
const r = locked(s => {
|
|
672
|
+
const list = view(s, t).filter(th => th.to === name);
|
|
673
|
+
if (!list.length) return { no: nobody(s, name) };
|
|
674
|
+
const keys = new Set(list.map(th => keyOf(th.session, th.agent, th.agentId)));
|
|
675
|
+
for (const th of s.threads) if (keys.has(th.key)) th.readAt = t;
|
|
676
|
+
// A thread that holds only questions so far gets a record, so it remembers being read.
|
|
677
|
+
for (const th of list) {
|
|
678
|
+
const key = keyOf(th.session, th.agent, th.agentId);
|
|
679
|
+
if (!s.threads.some(x => x.key === key))
|
|
680
|
+
s.threads.push({ key, who: th.agent, session: th.session, agentId: th.agentId, label: th.label, readAt: t, last: th.last });
|
|
681
|
+
}
|
|
682
|
+
return { list };
|
|
683
|
+
});
|
|
684
|
+
if (r.no) die(r.no, 1);
|
|
685
|
+
const out = [];
|
|
686
|
+
for (const th of r.list) {
|
|
687
|
+
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
|
+
for (const m of th.messages.slice(-RECENT)) {
|
|
689
|
+
const who = m.from === 'person' ? 'you' : m.from === 'dibs' ? 'dibs told them' : 'them';
|
|
690
|
+
const what = m.kind === 'question' ? `asked (#${m.questionId}, ${m.state}): ${m.text}${m.options ? ` (${m.options.join(' / ')})` : ''}`
|
|
691
|
+
+ `${m.recommend ? ` they recommend ${m.recommend}${m.why ? `: ${m.why}` : ''}` : ''}${m.cantUndo ? `. Can't be undone: ${m.cantUndo}` : ''}`
|
|
692
|
+
: 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`
|
|
693
|
+
: m.kind === 'note' && m.fyi ? `FYI: ${m.text}`
|
|
694
|
+
: m.kind === 'answer' ? `answered #${m.questionId}: ${m.text}`
|
|
695
|
+
: m.kind === 'delivered' ? `(${m.text})`
|
|
696
|
+
: `${m.text}${m.state === 'queued' ? ' (not delivered yet)' : ''}`;
|
|
697
|
+
out.push(` ${ago(t, m.at)}, ${who}: ${what}`);
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
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>' : ''}`));
|
|
701
|
+
console.log(out.join('\n'));
|
|
702
|
+
}
|