@dibssoftware/dibs 0.0.181 → 0.0.195

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 (105) hide show
  1. package/CHANGELOG.md +103 -1
  2. package/README.md +10 -8
  3. package/bin/dibs.mjs +370 -73
  4. package/docs/agents.md +303 -0
  5. package/docs/council.md +88 -0
  6. package/docs/files.md +3 -3
  7. package/docs/guard.md +86 -11
  8. package/docs/json.md +211 -0
  9. package/docs/later.md +5 -5
  10. package/docs/machines.md +6 -6
  11. package/docs/questions.md +104 -3
  12. package/docs/reference.md +124 -30
  13. package/docs/relay.md +120 -9
  14. package/docs/releasing.md +7 -1
  15. package/docs/scheduling.md +28 -6
  16. package/docs/secrets.md +53 -0
  17. package/docs/simulators.md +3 -3
  18. package/package.json +1 -1
  19. package/skills/dibs/SKILL.md +79 -149
  20. package/src/about.mjs +341 -0
  21. package/src/acquire.mjs +111 -27
  22. package/src/after.mjs +127 -0
  23. package/src/agents.mjs +2 -1
  24. package/src/alerts.mjs +95 -42
  25. package/src/answers.mjs +2 -2
  26. package/src/board.mjs +21 -16
  27. package/src/broker.mjs +23 -7
  28. package/src/carry.mjs +287 -0
  29. package/src/codex.mjs +132 -0
  30. package/src/commands.mjs +243 -82
  31. package/src/config.mjs +85 -14
  32. package/src/connect.mjs +4 -2
  33. package/src/cool.mjs +27 -11
  34. package/src/council.mjs +482 -0
  35. package/src/cwd.mjs +9 -0
  36. package/src/decisions.mjs +250 -0
  37. package/src/declare.mjs +96 -0
  38. package/src/diskreport.mjs +306 -0
  39. package/src/diskuse.mjs +420 -0
  40. package/src/diskwarn.mjs +68 -13
  41. package/src/doctor.mjs +149 -0
  42. package/src/doors.mjs +547 -0
  43. package/src/durable.mjs +143 -0
  44. package/src/envs.mjs +372 -0
  45. package/src/events.mjs +7 -2
  46. package/src/files.mjs +118 -6
  47. package/src/guard.mjs +239 -86
  48. package/src/guardd.mjs +8 -1
  49. package/src/halt.mjs +63 -0
  50. package/src/handoffs.mjs +362 -0
  51. package/src/history.mjs +34 -4
  52. package/src/hogs.mjs +36 -8
  53. package/src/jobprogress.mjs +283 -0
  54. package/src/later.mjs +21 -10
  55. package/src/lock.mjs +33 -9
  56. package/src/measure.mjs +42 -11
  57. package/src/media.mjs +240 -0
  58. package/src/news.mjs +31 -0
  59. package/src/notes.mjs +49 -8
  60. package/src/notices.mjs +126 -43
  61. package/src/ondemand.mjs +25 -2
  62. package/src/outcome.mjs +163 -0
  63. package/src/overlap.mjs +2 -2
  64. package/src/override.mjs +149 -79
  65. package/src/owner.mjs +15 -2
  66. package/src/people.mjs +236 -0
  67. package/src/pickup.mjs +72 -0
  68. package/src/picture.mjs +321 -0
  69. package/src/plain.mjs +84 -18
  70. package/src/platform.mjs +19 -0
  71. package/src/preempt.mjs +123 -15
  72. package/src/primer.mjs +91 -20
  73. package/src/prints.mjs +99 -0
  74. package/src/proc.mjs +1 -1
  75. package/src/progress.mjs +49 -3
  76. package/src/proof.mjs +102 -0
  77. package/src/push.mjs +271 -0
  78. package/src/questions.mjs +328 -57
  79. package/src/quota.mjs +1 -1
  80. package/src/recap.mjs +205 -0
  81. package/src/relay.mjs +139 -20
  82. package/src/remote.mjs +23 -10
  83. package/src/reviewgate.mjs +268 -0
  84. package/src/reviews.mjs +377 -0
  85. package/src/route.mjs +263 -0
  86. package/src/rules.mjs +216 -0
  87. package/src/schedule.mjs +238 -44
  88. package/src/schema.mjs +62 -0
  89. package/src/scratch.mjs +2 -2
  90. package/src/serve.mjs +3 -2
  91. package/src/signed.mjs +97 -0
  92. package/src/simpool.mjs +46 -1
  93. package/src/spend.mjs +375 -0
  94. package/src/state.mjs +43 -17
  95. package/src/talk.mjs +1078 -133
  96. package/src/thin.sh +2 -0
  97. package/src/trail.mjs +290 -0
  98. package/src/trailnote.mjs +209 -0
  99. package/src/util.mjs +7 -0
  100. package/src/vault.mjs +435 -0
  101. package/src/vendors.mjs +327 -0
  102. package/src/version.mjs +1 -1
  103. package/src/web.mjs +353 -60
  104. package/src/work.mjs +487 -0
  105. package/src/worker.mjs +7 -1
package/src/people.mjs ADDED
@@ -0,0 +1,236 @@
1
+ // More than one person. Until someone runs dibs people add twice, dibs knows one person, "the
2
+ // person", and nothing here changes a word it says. With two or more in config.json's "people",
3
+ // dibs knows them by name: which agents are whose, whose phone a question buzzes, who answered
4
+ // it and who a message came from.
5
+ //
6
+ // "people": { "sam": { "users": ["sam"], "devices": ["<paired device id>"], "hours": {...}, "notify": "all" } }
7
+ //
8
+ // An agent's owner, first match wins: DIBS_PERSON in its environment (two people on one macOS
9
+ // account each export their own), the project's .dibs.json ("owner": "sam", or "owners":
10
+ // {"ios-app": "sam"} in a folder above several repos), the macOS user running it, and with one
11
+ // person configured, that person. A person typing a command is known by DIBS_PERSON (the page
12
+ // sets it from the paired phone a call came through) or their macOS user; a project's owner says
13
+ // nothing about who's typing.
14
+ //
15
+ // Read without a lock, straight from config.json: actor() calls this on every change it records,
16
+ // and loadConfig() would die on a config another field broke.
17
+ import fs from 'node:fs';
18
+ import os from 'node:os';
19
+ import path from 'node:path';
20
+ import { paths } from './config.mjs';
21
+ import { rulesAbove } from './trust.mjs';
22
+
23
+ export const NOTIFY = ['all', 'asks', 'off'];
24
+ // Words that already mean something where a person's name goes (dibs tell, dibs say --to).
25
+ const RESERVED = new Set(['person', 'people', 'everyone', 'all', 'desk', 'me', 'nobody', 'someone']);
26
+ const NAME = /^[A-Za-z][\w.-]{0,31}$/;
27
+
28
+ export function readPeople(file = paths.config) {
29
+ try {
30
+ const p = JSON.parse(fs.readFileSync(file, 'utf8')).people;
31
+ return p && typeof p === 'object' && !Array.isArray(p) ? p : {};
32
+ } catch { return {}; }
33
+ }
34
+
35
+ // Two or more: the only time names show.
36
+ export const several = (p = readPeople()) => Object.keys(p).length > 1;
37
+ export const find = (p, name) => (name ? Object.keys(p).find(k => k.toLowerCase() === String(name).toLowerCase()) || null : null);
38
+
39
+ export function checkName(name, p) {
40
+ if (!NAME.test(name || '')) return `a person's name is a word of letters, digits, dots, dashes and underscores, starting with a letter: dibs people add sam. Not "${name}".`;
41
+ if (RESERVED.has(name.toLowerCase())) return `"${name}" already means something to dibs (dibs say --to person, dibs tell --all). Pick another name.`;
42
+ if (find(p, name)) return `${find(p, name)} is already here. Change them: dibs people set ${find(p, name)} ...`;
43
+ return null;
44
+ }
45
+
46
+ export function macUser() {
47
+ try { return os.userInfo().username; } catch { return process.env.USER || null; }
48
+ }
49
+ const byUser = (p, user) => Object.keys(p).find(k => Array.isArray(p[k].users) && p[k].users.includes(user)) || null;
50
+ export const byDevice = (p, did) => (did ? Object.keys(p).find(k => Array.isArray(p[k].devices) && p[k].devices.includes(did)) || null : null);
51
+ const only = p => (Object.keys(p).length === 1 ? Object.keys(p)[0] : null);
52
+
53
+ // The project's named owner for a folder: the nearest .dibs.json that names one. A name nobody
54
+ // here goes by (the repo is shared with people on other machines) is passed over.
55
+ export function projectOwner(cwd, p) {
56
+ for (const f of rulesAbove(cwd)) {
57
+ let r;
58
+ try { r = JSON.parse(fs.readFileSync(f, 'utf8')); } catch { continue; }
59
+ const dir = path.dirname(f);
60
+ if (r.owners && typeof r.owners === 'object') {
61
+ for (const [sub, who] of Object.entries(r.owners)) {
62
+ const root = path.resolve(dir, sub);
63
+ const rel = path.relative(root, path.resolve(cwd));
64
+ if (!rel.startsWith('..') && !path.isAbsolute(rel) && find(p, who)) return { name: find(p, who), why: `${f} names ${who} for ${sub}` };
65
+ }
66
+ }
67
+ if (typeof r.owner === 'string' && find(p, r.owner)) return { name: find(p, r.owner), why: `${f} names ${r.owner}` };
68
+ }
69
+ return null;
70
+ }
71
+
72
+ // Whose agent this is: { name, why }, or null when dibs can't tell.
73
+ export function ownerOf({ cwd = process.cwd(), env = process.env, p = readPeople(), user = macUser() } = {}) {
74
+ const set = find(p, env.DIBS_PERSON);
75
+ if (set) return { name: set, why: `DIBS_PERSON is ${env.DIBS_PERSON}` };
76
+ const proj = projectOwner(cwd, p);
77
+ if (proj) return proj;
78
+ const u = byUser(p, user);
79
+ if (u) return { name: u, why: `macOS user ${user} is ${u}'s` };
80
+ if (only(p)) return { name: only(p), why: 'the only person here' };
81
+ return null;
82
+ }
83
+
84
+ // Which person is typing (not an agent): { name, why }, or null.
85
+ export function personOf({ env = process.env, p = readPeople(), user = macUser() } = {}) {
86
+ const set = find(p, env.DIBS_PERSON);
87
+ if (set) return { name: set, why: `DIBS_PERSON is ${env.DIBS_PERSON}` };
88
+ const u = byUser(p, user);
89
+ if (u) return { name: u, why: `macOS user ${user} is ${u}'s` };
90
+ if (only(p)) return { name: only(p), why: 'the only person here' };
91
+ return null;
92
+ }
93
+
94
+ // A person's hours, or everyone's (dibs hours) when they set none: a config-shaped object for offHours().
95
+ export const hoursCfg = (cfg, name, p = readPeople()) => {
96
+ const h = name && p[name]?.hours;
97
+ return h ? { ...cfg, hours: h } : cfg;
98
+ };
99
+
100
+ // A phone paired for a person (dibs connect --phone --for sam) is theirs from its first connection.
101
+ // Taken from whoever had it; nothing happens if that person was removed meanwhile.
102
+ export function giveDevice(name, did) {
103
+ const p = readPeople();
104
+ const who = find(p, name);
105
+ if (!who) return false;
106
+ for (const k of Object.keys(p)) p[k] = { ...p[k], devices: (p[k].devices || []).filter(d => d !== did) };
107
+ p[who].devices.push(did);
108
+ writePeople(p);
109
+ return true;
110
+ }
111
+
112
+ function writePeople(p) {
113
+ const c = JSON.parse(fs.readFileSync(paths.config, 'utf8'));
114
+ c.people = p;
115
+ const tmp = `${paths.config}.${process.pid}`;
116
+ fs.writeFileSync(tmp, JSON.stringify(c, null, 2) + '\n');
117
+ fs.renameSync(tmp, paths.config);
118
+ }
119
+
120
+ const USE = 'dibs people [--json] | add <name> | set <name> | remove <name> | me [--json]. add and set take --user <macOS user>, --device <paired device id>, --hours 09:00-18:00|off, --notify all|asks|off; set also --forget-user, --forget-device';
121
+
122
+ function parseFlags(args, die) {
123
+ const o = { users: [], devices: [], forgetUsers: [], forgetDevices: [], words: [] };
124
+ for (let i = 0; i < args.length; i++) {
125
+ const a = args[i], next = () => args[++i] ?? die(`${a} needs a value. ${USE}`);
126
+ if (a === '--user') o.users.push(next());
127
+ else if (a === '--device') o.devices.push(next());
128
+ else if (a === '--forget-user') o.forgetUsers.push(next());
129
+ else if (a === '--forget-device') o.forgetDevices.push(next());
130
+ else if (a === '--hours') o.hours = next();
131
+ else if (a === '--notify') { o.notify = next(); if (!NOTIFY.includes(o.notify)) die(`--notify is all (questions, notes, finished and stuck tasks), asks (only questions that need them) or off, not ${o.notify}`); }
132
+ else if (a === '--json') o.json = true;
133
+ else if (a.startsWith('-')) die(`unknown flag ${a}. ${USE}`);
134
+ else o.words.push(a);
135
+ }
136
+ return o;
137
+ }
138
+
139
+ const userText = x => (x.users?.length ? `macOS user ${x.users.join(', ')}` : 'no macOS user (DIBS_PERSON or a project\'s .dibs.json only)');
140
+ const notifyText = x => ({ all: 'everything', asks: 'questions only', off: 'no notifications' }[x.notify || 'all']);
141
+
142
+ // dibs people: who's here, and whose agents are whose.
143
+ export async function peopleCmd(args) {
144
+ const { die, say } = await import('./util.mjs');
145
+ const { logChange, actor } = await import('./owner.mjs');
146
+ const [verb, ...rest] = args;
147
+ const o = parseFlags(verb && !verb.startsWith('-') ? rest : args, die);
148
+ let p = readPeople();
149
+ if (!verb || verb.startsWith('-')) return list(p, o, actor);
150
+ if (verb === 'me') return me(p, o, actor);
151
+ const name = o.words[0] || die(`which person? ${USE}`);
152
+ if (o.words.length > 1) die(`one name at a time, not ${o.words.join(' ')}. ${USE}`);
153
+ if (verb === 'add') {
154
+ const bad = checkName(name, p);
155
+ if (bad) die(bad);
156
+ // The first person is usually whoever is setting dibs up, at their own Mac.
157
+ const users = o.users.length || Object.keys(p).length ? o.users : [macUser()].filter(Boolean);
158
+ p = { ...p, [name]: { users: [], devices: [], hours: null, notify: 'all', added: Date.now() } };
159
+ await change(p, name, { ...o, users }, die);
160
+ writePeople(p);
161
+ logChange('people add', { person: name });
162
+ console.log(`Added ${name}: ${userText(p[name])}${p[name].devices.length ? `, ${p[name].devices.length} paired device${p[name].devices.length > 1 ? 's' : ''}` : ''}.`);
163
+ if (Object.keys(p).length === 2) say('two people now: dibs names who asked, answered and sent each message, and sends each question to its agent\'s owner. dibs people lists them.');
164
+ else if (Object.keys(p).length === 1) say('one person: dibs still says "the person" everywhere. A second (dibs people add <name>) is when names start to show.');
165
+ return;
166
+ }
167
+ const who = find(p, name) || die(`nobody called ${name} here. ${Object.keys(p).length ? `People: ${Object.keys(p).join(', ')}` : 'Add them: dibs people add ' + name}`, 1);
168
+ if (verb === 'remove') {
169
+ const { [who]: gone, ...left } = p;
170
+ writePeople(left);
171
+ logChange('people remove', { person: who });
172
+ return console.log(`Removed ${who}. Their agents' questions go to ${Object.keys(left).length === 1 ? Object.keys(left)[0] : 'whoever answers'} now.`);
173
+ }
174
+ if (verb === 'set') {
175
+ p = { ...p, [who]: { ...p[who] } };
176
+ await change(p, who, o, die);
177
+ writePeople(p);
178
+ logChange('people set', { person: who });
179
+ return list(p, { json: false }, actor, who);
180
+ }
181
+ die(`unknown ${verb}. ${USE}`);
182
+ }
183
+
184
+ // Apply add's and set's flags to p[name], in place.
185
+ async function change(p, name, o, die) {
186
+ const x = p[name];
187
+ x.users = [...new Set([...(x.users || []).filter(u => !o.forgetUsers.includes(u)), ...o.users])];
188
+ for (const u of o.users) {
189
+ const other = byUser(p, u);
190
+ if (other && other !== name) die(`macOS user ${u} is ${other}'s already: dibs people set ${other} --forget-user ${u}, then try again. Nothing was changed.`);
191
+ }
192
+ if (o.devices.length || o.forgetDevices.length) {
193
+ const { devices } = await import('./relay.mjs');
194
+ const all = devices();
195
+ const pick = id => {
196
+ const hits = all.filter(d => d.id.startsWith(id));
197
+ if (hits.length !== 1) die(`${hits.length ? `${hits.length} paired devices start with ${id}` : `no paired device starts with ${id}`}. Their ids: dibs connect --list. Nothing was changed.`);
198
+ return hits[0].id;
199
+ };
200
+ const add = o.devices.map(pick), forget = new Set(o.forgetDevices.map(id => (x.devices || []).find(d => d.startsWith(id)) || pick(id)));
201
+ // A phone is one person's: giving it to someone takes it from whoever had it.
202
+ for (const k of Object.keys(p)) if (k !== name && p[k].devices?.some(d => add.includes(d))) p[k] = { ...p[k], devices: p[k].devices.filter(d => !add.includes(d)) };
203
+ x.devices = [...new Set([...(x.devices || []).filter(d => !forget.has(d)), ...add])];
204
+ }
205
+ if (o.hours != null) {
206
+ const { parseHours } = await import('./questions.mjs');
207
+ const h = parseHours(o.hours);
208
+ if (h == null) die(`can't read hours "${o.hours}". Use --hours 09:00-18:00, or --hours off for everyone's (dibs hours)`);
209
+ x.hours = h || null;
210
+ }
211
+ if (o.notify) x.notify = o.notify;
212
+ }
213
+
214
+ function list(p, o, actor, only = null) {
215
+ const names = only ? [only] : Object.keys(p);
216
+ const you = actor();
217
+ if (o.json) return console.log(JSON.stringify({ people: names.map(n => ({ name: n, users: p[n].users || [], devices: p[n].devices || [], hours: p[n].hours || null, notify: p[n].notify || 'all' })), you: you.agent ? null : you.person ?? personOf({ p })?.name ?? null }));
218
+ if (!names.length) return console.log('Nobody is named here, so dibs speaks of "the person". Two people sharing this Mac: dibs people add <name> for each.');
219
+ if (!only) console.log(names.length === 1 ? `1 person, ${names[0]}: dibs still says "the person" everywhere until there are two.` : `${names.length} people. Each agent's questions go to its owner, and messages say who sent them.`);
220
+ for (const n of names) {
221
+ const x = p[n];
222
+ const hours = x.hours ? `hours ${x.hours.start} to ${x.hours.end}` : 'everyone\'s hours';
223
+ const ds = x.devices || [];
224
+ const devices = ds.length ? `paired device${ds.length > 1 ? 's' : ''} ${ds.map(d => d.slice(0, 8)).join(', ')}` : 'no paired device';
225
+ console.log(` ${n.padEnd(12)} ${userText(x)}, ${devices}, ${hours}, ${notifyText(x)}`);
226
+ }
227
+ }
228
+
229
+ function me(p, o, actor) {
230
+ const a = actor();
231
+ const r = a.agent ? ownerOf({ p }) : personOf({ p });
232
+ if (o.json) return console.log(JSON.stringify({ agent: a.agent, person: r?.name || null, why: r?.why || null, several: several(p) }));
233
+ if (!Object.keys(p).length) return console.log(a.agent ? 'You work for the person: nobody else is named here.' : 'You\'re the person: nobody else is named here.');
234
+ if (!r) return console.log(`dibs can't tell ${a.agent ? 'whose agent you are' : 'who you are'}. ${a.agent ? 'Your questions reach everyone.' : ''} Set DIBS_PERSON=<name>, or dibs people set <name> --user ${macUser()}. People: ${Object.keys(p).join(', ')}`);
235
+ console.log(a.agent ? `You work for ${r.name} (${r.why}).` : `You're ${r.name} (${r.why}).`);
236
+ }
package/src/pickup.mjs ADDED
@@ -0,0 +1,72 @@
1
+ // Idle agents pick up work items. An agent listening (dibs listen) with no progress task open,
2
+ // no item claimed and no dibs job running or waiting has nothing on; when an item it could claim
3
+ // is waiting, dibs offers it: a notice from dibs (never the person or another agent) that wakes
4
+ // its listener with the item, its goal and the lines to claim it or give it back.
5
+ //
6
+ // Only within a project: an item goes to agents that said they're on the project of whoever made
7
+ // it (dibs project, src/talk.mjs), so an agent on another product is never pulled off it, and an
8
+ // agent on no project is offered nothing. Off until the person (or an agent, on the record)
9
+ // turns it on: dibs work pickup on. An item made with --no-pickup is never offered.
10
+ //
11
+ // There's no service doing this: each listener looks for its own agent (src/talk.mjs listen),
12
+ // and the offer is written under the items' lock, so two listeners never offer one item at once.
13
+ import { loadConfig } from './config.mjs';
14
+ import { peek } from './state.mjs';
15
+ import { notify, threadOf } from './talk.mjs';
16
+ import { locked, load, blockedWhy, fromName, liveOffer, OFFER_FOR, OPEN, TAKEN } from './handoffs.mjs';
17
+ import { read as readPosts, tasks } from './progress.mjs';
18
+ import { filesTaken, liveLeases } from './work.mjs';
19
+ import { now } from './util.mjs';
20
+
21
+ const MAIN = 'main';
22
+ // Progress posts this old can't be an open task any more (progress.mjs lets them go well before).
23
+ const POSTS_FOR = 864e5;
24
+ // The names an item was offered to, newest last: it goes to someone new before anyone twice.
25
+ const OFFERED_KEEP = 20;
26
+
27
+ export const pickupOn = (cfg = null) => { try { return (cfg || loadConfig()).pickup === true; } catch { return false; } };
28
+
29
+ // Whether this record (a progress task, a lease, a taker) is the thread's agent's.
30
+ const ofThread = th => x => (th.session && (x.session || x.sessionId)
31
+ ? (x.session || x.sessionId) === th.session && (x.agentId || MAIN) === th.agentId
32
+ : x.who === th.who || x.name === th.name);
33
+
34
+ // The listener's look for its agent: when it has nothing on and an item it could claim is
35
+ // waiting, offer it the oldest one (one addressed to it first). Returns whether it offered one.
36
+ // The item's goal and context are its maker's words: their lines are indented, so none reads as a
37
+ // message of its own ("Message from the person: ...") to the agent offered it.
38
+ const under = text => String(text).replace(/\r\n?|[\n\u2028\u2029]/g, '\n ');
39
+ export function offer(listener, t = now()) {
40
+ if (!pickupOn()) return false;
41
+ const th = threadOf(listener.key);
42
+ if (!th?.project) return false;
43
+ const mine = ofThread(th);
44
+ if (tasks(readPosts({ since: t - POSTS_FOR }), t).some(k => (k.state === 'doing' || k.state === 'blocked') && mine(k))) return false;
45
+ const st = peek();
46
+ if ([...(st.leases || []), ...(st.queue || []).filter(q => q.pid)].some(mine)) return false;
47
+ const fits = (s, x) => x.state === OPEN && x.pickup !== false && x.project === th.project && (!x.to || x.to === th.name)
48
+ && x.from?.name !== th.name && !(x.offered || []).includes(th.name) && !liveOffer(x, t) && !blockedWhy(s, x);
49
+ const busy = s => s.handoffs.some(x => (x.state === TAKEN && x.taker && mine(x.taker)) || liveOffer(x, t)?.key === th.key);
50
+ // A look without the lock first: most of the time there's nothing to offer.
51
+ const first = load();
52
+ if (busy(first) || !first.handoffs.some(x => fits(first, x))) return false;
53
+ const live = liveLeases();
54
+ const me = { name: th.name, who: th.who };
55
+ const x = locked(s => {
56
+ if (busy(s)) return null;
57
+ const pick = s.handoffs.filter(y => fits(s, y) && !filesTaken(s, y, me, live))
58
+ .sort((a, b) => Number(b.to === th.name) - Number(a.to === th.name) || a.id - b.id)[0];
59
+ if (!pick) return null;
60
+ pick.offer = { to: th.name, key: th.key, at: t };
61
+ pick.offered = [...(pick.offered || []).filter(n => n !== th.name), th.name].slice(-OFFERED_KEEP);
62
+ return { ...pick };
63
+ });
64
+ if (!x) return false;
65
+ const id = `w${x.id}`;
66
+ return notify({ sessionId: th.session, agentId: th.agentId, who: th.who }, `offer:${id}:${t}`,
67
+ `${id} "${x.title}"${x.to ? ', for you' : ''}, from ${fromName(x)}, in ${x.project}.${x.goal ? ` Done when: ${under(x.goal)}` : ''}`
68
+ + `${x.context ? `\n ${under(x.context)}` : ''}${x.paths?.length ? `\nFiles: ${x.paths.join(', ')}` : ''}\n`
69
+ + `Claim it: dibs work claim ${id}. Post as you go: dibs progress "..." --task ${id}. Close it: dibs work done ${id} "what you did". `
70
+ + `If you claim it and can't finish: dibs work back ${id} "why".\n`
71
+ + `Not for you? Leave it: in ${OFFER_FOR / 6e4} minutes it's offered to another idle agent on ${x.project}.`, { offer: true });
72
+ }
@@ -0,0 +1,321 @@
1
+ // The person's picture of each agent: what it's for, what it needs from them, what blocks it,
2
+ // what it's doing now, its plan, what it finished, and its newest words. Never a command, a pid
3
+ // or a tool call: the person reads agents, not processes (2026-11-26: "If I'm looking at my poker
4
+ // agent, what's it actually doing?").
5
+ //
6
+ // Every field is the agent's own words or a fact dibs has, nothing generated: its session title,
7
+ // the person's prompt, its dibs progress posts and questions, its plan and wrap-up tool calls and
8
+ // newest words in its transcript (src/about.mjs, src/codex.mjs), the -m of its jobs, and what its
9
+ // runs meant, parsed from their output (src/outcome.mjs). Each field says which source won (from).
10
+ //
11
+ // dibs agents [--json] prints it, dibs web serves it as /api/agents, and plain dibs run by the
12
+ // person opens with it. One run's details are /api/runs/<id> (runJson).
13
+ import fs from 'node:fs';
14
+ import { loadConfig } from './config.mjs';
15
+ import { peek } from './state.mjs';
16
+ import { EVENTS, OLDER, readEvents } from './events.mjs';
17
+ import { threadsJson } from './talk.mjs';
18
+ import { sessionFiles } from './proc.mjs';
19
+ import { read as readPosts, tasks } from './progress.mjs';
20
+ import { workFor, about } from './about.mjs';
21
+ import { codexWork } from './codex.mjs';
22
+ import { firstSentence } from './outcome.mjs';
23
+ import { named, minutes, ordinal, doneText, about as aboutTime } from './plain.mjs';
24
+ import { progressOf } from './jobprogress.mjs';
25
+ import { short } from './files.mjs';
26
+ import { now, die } from './util.mjs';
27
+ import { bold, dim, wrap } from './style.mjs';
28
+
29
+ const MIN = 6e4, HOUR = 36e5, DAY = 864e5;
30
+ const MAIN = 'main';
31
+ // Now is what the agent said it's doing, if it said so this recently.
32
+ const NOW_FRESH = 30 * MIN;
33
+ // Working this long with nothing said about it: "No update for 20 min".
34
+ export const QUIET_AFTER = 20 * MIN;
35
+ // At work: a tool call this recent. A session Claude Code calls busy may have stopped hours ago.
36
+ const ACTIVE_WITHIN = 5 * MIN;
37
+ // Nothing at all for this long reads idle, whatever Claude Code's session file says.
38
+ const IDLE_AFTER = 30 * MIN;
39
+ // A plan with every item done, untouched this long, is finished, not "5 of 5".
40
+ const PLAN_FINISHED = HOUR;
41
+ // Results: the last day's, at most this many, newest first.
42
+ const RESULTS = 5;
43
+ // The event log's tail holds a day of runs on all but the busiest machine (about 300 bytes a run).
44
+ const EVENTS_TAIL = 2 * 1024 ** 2;
45
+ // Ended agents stay in the list this long after they last did anything.
46
+ const ENDED_SHOWN = DAY;
47
+ // A run's tool call starts before its lease and ends after it; transcript times are to the millisecond, but clocks drift.
48
+ const SLACK = 2000;
49
+ // A sentence on a screen: the agent's words, cut.
50
+ const SHOWN = 140;
51
+ const PROMPT_FOR = 60;
52
+
53
+ const one = s => String(s ?? '').replace(/\s+/g, ' ').trim();
54
+ const cut = (s, n = SHOWN) => { const x = one(s); return x.length > n ? `${x.slice(0, n - 3).trimEnd()}...` : x; };
55
+ // One line of what an agent wrote: its first sentence, else its start.
56
+ const line = s => firstSentence(s, SHOWN) || cut(s);
57
+
58
+ // The run ends of the last day, from the event log's tail only, kept until the file changes.
59
+ let ends = null;
60
+ function recentEnds(t) {
61
+ let st;
62
+ try { st = fs.statSync(EVENTS); } catch { st = null; }
63
+ const sig = st ? `${st.size}:${st.mtimeMs}` : 'none';
64
+ if (ends?.sig === sig && t - ends.at < HOUR) return ends.list;
65
+ const out = [];
66
+ const take = (file, bytes) => {
67
+ let text = '';
68
+ try {
69
+ const size = fs.statSync(file).size, from = Math.max(0, size - bytes);
70
+ const fd = fs.openSync(file, 'r');
71
+ try { const buf = Buffer.alloc(size - from); fs.readSync(fd, buf, 0, buf.length, from); text = buf.toString('utf8'); } finally { fs.closeSync(fd); }
72
+ if (from > 0) text = text.slice(text.indexOf('\n') + 1);
73
+ return { text, whole: from === 0, size };
74
+ } catch { return { text: '', whole: true, size: 0 }; }
75
+ };
76
+ const cur = take(EVENTS, EVENTS_TAIL);
77
+ // The current file started less than a day ago: the day's start is in the one before.
78
+ const parts = [cur.text];
79
+ const firstAt = Number(/^\{"at":(\d+)/.exec(cur.text)?.[1]);
80
+ if (cur.whole && !(firstAt <= t - DAY) && cur.size < EVENTS_TAIL) parts.unshift(take(OLDER, EVENTS_TAIL - cur.size).text);
81
+ for (const text of parts) for (const l of text.split('\n')) {
82
+ if (!l.includes('"kind":"end"')) continue;
83
+ try { const e = JSON.parse(l); if (e.type === 'run' && e.at > t - DAY) out.push(e); } catch {}
84
+ }
85
+ ends = { sig, at: t, list: out };
86
+ return out;
87
+ }
88
+
89
+ const SUBJECT = { test: ['Tests', 'passed', 'failed'], playwright: ['Browser tests', 'passed', 'failed'], 'xcode-build': ['The build', 'worked', 'failed'],
90
+ deploy: ['The deploy', 'worked', 'failed'], sim: ['The simulator run', 'worked', 'failed'], 'sim-own': ['The simulator run', 'worked', 'failed'] };
91
+
92
+ // The transcript's record of the tool call that ran this job: by the id on dibs run's last line,
93
+ // else by time (the call began before the lease and its result came after it ended).
94
+ function callOf(e) {
95
+ const w = e.session ? workFor(e.session, e.agentId) : e.codex ? codexWork(e.codex) : null;
96
+ if (!w?.runs?.length) return null;
97
+ const start = e.at - (e.ms || 0);
98
+ return w.runs.find(r => r.ids.includes(e.id))
99
+ || w.runs.findLast(r => !r.ids.length && r.at != null && r.doneAt != null && r.at <= start + SLACK && r.doneAt >= e.at - SLACK) || null;
100
+ }
101
+
102
+ // What one finished run meant, in a sentence: parsed from its output, else the agent's own
103
+ // reading of it, else its -m and whether it worked. { text, ok, from }.
104
+ export function outcome(e) {
105
+ const call = callOf(e);
106
+ if (call?.outcome) return { ...call.outcome, from: 'output' };
107
+ const ok = e.code === 0;
108
+ if (call?.reading) return { text: call.reading, ok, from: 'said' };
109
+ const res = (e.res || []).map(r => short(r));
110
+ const [what, good, bad] = SUBJECT[res.find(r => SUBJECT[r])] || ['The job', 'worked', 'failed'];
111
+ const subject = e.purpose ? cut(e.purpose, 90) : what;
112
+ // Under a minute in seconds: minutes() rounds up to 1 min, and every quick test run read "passed in 1 min".
113
+ const took = (e.ms || 0) < 59.5e3 ? `${Math.max(1, Math.round((e.ms || 0) / 1000))}s` : minutes(e.ms);
114
+ const verdict = ok ? `${good} in ${took}` : e.code == null ? `ended after ${took}` : e.code >= 128 ? `was stopped after ${took}` : `${bad} after ${took}`;
115
+ return { text: `${subject}${e.purpose ? ':' : ''} ${verdict}`, ok, from: 'plain' };
116
+ }
117
+
118
+ // GET /api/runs/<id>: one run's details, finished or not. null when dibs has no record of it.
119
+ export function runJson(id, t = now()) {
120
+ const n = Number(id);
121
+ const s = peek();
122
+ const live = (s.leases || []).find(l => l.id === n) || (s.queue || []).find(q => q.id === n);
123
+ if (live) {
124
+ const running = (s.leases || []).includes(live);
125
+ return { id: n, state: running ? 'running' : 'waiting', outcome: null, ok: null, purpose: live.purpose || null, cmd: live.cmd || null, res: live.res,
126
+ waitedMs: running ? live.waited ?? null : t - (live.enq || t), ranMs: running ? t - live.start : null, code: null, at: running ? live.start : live.enq, who: live.agent || live.who };
127
+ }
128
+ const e = recentEnds(t).findLast(x => x.id === n) || readEvents(t).findLast(x => x.kind === 'end' && x.id === n);
129
+ if (!e) return null;
130
+ const started = e.waited == null ? readEvents(t).findLast(x => x.kind === 'start' && x.id === n) : null;
131
+ const o = e.type === 'run' ? outcome(e) : null;
132
+ return { id: n, state: 'ended', outcome: o?.text || null, ok: o ? o.ok : e.code === 0, from: o?.from || null, purpose: e.purpose || null, cmd: e.cmd || null,
133
+ res: e.res, waitedMs: e.waited ?? started?.ms ?? null, ranMs: e.ms ?? null, code: e.code ?? null, at: e.at, who: e.who };
134
+ }
135
+
136
+ // "Waiting for the simulator, 2nd in line"
137
+ function waitText(q, s, cfg) {
138
+ const ahead = (s.queue || []).filter(x => x !== q && x.pid && x.enq < q.enq && x.res.some(r => q.res.includes(r))).length;
139
+ return `Waiting for ${q.res.map(r => named(cfg, r).the).join(' and ')}, ${ordinal(ahead + 1)} in line`;
140
+ }
141
+ function pausedText(l) {
142
+ const w = (l.pauses || []).filter(p => p.watcher && !p.gone);
143
+ if (w.length) return `Paused: the Mac is low on ${w.some(p => p.disk) ? 'disk' : 'memory'}`;
144
+ return 'Paused to let a more urgent job go first';
145
+ }
146
+
147
+ // The plan as the screens show it: from the newest list the agent wrote, else its progress tasks.
148
+ function planOf(work, own, t) {
149
+ if (work?.plan?.items?.length) {
150
+ const items = work.plan.items;
151
+ const done = items.filter(x => x.status === 'done').length;
152
+ return { done, total: items.length, from: work.plan.from, at: work.plan.at, items,
153
+ ...(done === items.length && t - (work.plan.at || 0) > PLAN_FINISHED && { finished: true }) };
154
+ }
155
+ const ks = own.filter(k => k.task && k.state !== 'expired').sort((a, b) => a.started - b.started);
156
+ if (!ks.length) return null;
157
+ const items = ks.map(k => ({ text: cut(k.task, 120), status: k.state === 'done' ? 'done' : 'doing' }));
158
+ return { done: items.filter(x => x.status === 'done').length, total: items.length, from: 'progress', at: Math.max(...ks.map(k => k.last)), items };
159
+ }
160
+
161
+ // How far a running job says it is (src/jobprogress.mjs), to follow what it does: ", 40% done, about 2 hr left".
162
+ function jobAlong(l, t) {
163
+ const pr = progressOf(l, t);
164
+ return pr ? `, ${doneText(pr)}${pr.left ? `, ${aboutTime(pr.left)} left` : ''}` : '';
165
+ }
166
+
167
+ function picture(th, ctx, t) {
168
+ const { s, cfg, ks, runs, codexOf } = ctx;
169
+ const main = th.agentId === MAIN;
170
+ const mineL = x => (th.session ? x.sessionId === th.session && (x.agentId || MAIN) === th.agentId : x.who === th.agent && main);
171
+ const leases = (s.leases || []).filter(mineL), waits = (s.queue || []).filter(q => q.pid && mineL(q));
172
+ const own = ks.filter(k => (th.session ? k.session === th.session && (k.agentId || MAIN) === th.agentId : k.who === th.agent && !k.agentId));
173
+ const codex = !th.session && main ? codexOf(th.agent) : null;
174
+ const work = th.session ? workFor(th.session, th.agentId) : codex ? codexWork(codex) : null;
175
+ const ab = th.about || (codex && work ? { project: work.project, branch: work.branch, model: work.model, asked: work.asked } : null) || {};
176
+ const fresh = at => at != null && t - at < NOW_FRESH;
177
+ const prompt = work?.prompt || 0;
178
+ // The wrap-up counts until the person answers it (their next prompt).
179
+ const wrap = work?.wrap && (work.wrap.at || 0) >= prompt ? work.wrap : null;
180
+
181
+ const forText = ab.title ? { text: cut(ab.title, 90), from: 'title' } : ab.brief ? { text: cut(ab.brief, 90), from: 'brief' }
182
+ : ab.asked ? { text: cut(ab.asked.split('\n').find(x => x.trim()) || ab.asked, PROMPT_FOR), from: 'prompt' } : { text: th.to, from: 'name' };
183
+
184
+ const needs = th.messages.filter(m => m.kind === 'question' && m.state === 'open' && m.oneWay)
185
+ .map(m => ({ kind: 'question', id: String(m.questionId), text: cut(m.needsYou || m.text, 300), options: m.options || null, recommend: m.recommend ?? null, at: m.at }));
186
+ if (wrap?.ask && wrap.options.length) needs.push({ kind: 'ask', text: cut(wrap.ask, 300), options: wrap.options, at: wrap.at, from: 'wrapup' });
187
+
188
+ const stuck = own.filter(k => k.state === 'blocked').sort((a, b) => b.last - a.last)[0];
189
+ const paused = leases.find(l => l.pausedAt);
190
+ const blocked = stuck ? { text: line(stuck.text), from: 'progress', since: stuck.last }
191
+ : wrap?.blocked ? { text: line(wrap.ask || wrap.recap || 'Blocked'), from: 'wrapup', since: wrap.at }
192
+ : waits.length ? { text: waitText(waits[0], s, cfg), from: 'line', since: waits[0].enq, job: waits[0].id, ...(waits[0].purpose && { purpose: cut(waits[0].purpose, 120) }) }
193
+ : paused ? { text: pausedText(paused), from: 'paused', since: paused.pausedAt, job: paused.id, ...(paused.purpose && { purpose: cut(paused.purpose, 120) }) }
194
+ : null;
195
+
196
+ const plan = planOf(work, own, t);
197
+ const doingItem = work?.plan?.items?.find(x => x.status === 'doing');
198
+ const post = own.filter(k => k.state === 'doing').sort((a, b) => b.last - a.last)[0];
199
+ const said = work?.said && (!work.tool || work.said.order > work.tool.order) ? firstSentence(work.said.text, SHOWN) : null;
200
+ const running = leases.filter(l => l.kind === 'run' || l.kind === 'hold').sort((a, b) => b.start - a.start)[0];
201
+ const nowText = doingItem && fresh(work.plan.at) ? { text: cut(doingItem.active || doingItem.text), from: 'plan', at: work.plan.at }
202
+ : post && fresh(post.last) ? { text: line(post.text), from: 'progress', at: post.last }
203
+ : said && /\.$/.test(said) && fresh(work.said.at) ? { text: said, from: 'said', at: work.said.at }
204
+ : running ? { text: `${running.purpose ? cut(running.purpose) : named(cfg, running.res[0]).doing}${jobAlong(running, t)}`, from: 'job', at: running.start, job: running.id }
205
+ : null;
206
+
207
+ const results = [];
208
+ for (const e of runs.filter(e => (th.session ? e.session === th.session && (e.agentId || MAIN) === th.agentId
209
+ : e.codex ? e.codex === codex : !e.session && e.who === th.agent && main))) {
210
+ const o = outcome(e);
211
+ results.push({ text: o.text, ok: o.ok, at: e.at, from: 'run', run: e.id, how: o.from });
212
+ }
213
+ for (const k of own.filter(k => k.state === 'done' && k.doneAt > t - DAY)) results.push({ text: line(k.text), ok: true, at: k.doneAt, from: 'progress' });
214
+ if (work?.plan && t - (work.plan.at || 0) < DAY) for (const x of work.plan.items.filter(x => x.status === 'done').slice(-2)) results.push({ text: cut(x.text), ok: true, at: work.plan.at, from: 'plan' });
215
+ if (work?.wrap?.recap && t - (work.wrap.at || 0) < DAY) results.push({ text: line(work.wrap.recap), ok: !work.wrap.blocked, at: work.wrap.at, from: 'wrapup' });
216
+ if (work?.complete && t - (work.complete.at || 0) < DAY) results.push({ text: line(work.complete.text), ok: true, at: work.complete.at, from: 'codex' });
217
+ for (const m of th.messages.filter(m => m.from === 'agent' && m.kind === 'done' && m.at > t - DAY)) results.push({ text: line(m.summary || m.text), ok: true, at: m.at, from: 'message' });
218
+ const seen = new Set();
219
+ const shown = results.sort((a, b) => b.at - a.at).filter(r => !seen.has(r.text) && seen.add(r.text)).slice(0, RESULTS);
220
+
221
+ const note = th.messages.filter(m => m.from === 'agent' && (m.kind === 'note' || m.kind === 'done')).at(-1);
222
+ const latest = note ? { text: line(note.summary || note.text), at: note.at } : null;
223
+
224
+ // "Working" by its reach, yet nothing in its transcript or the queue for this long: it stopped and nobody said so.
225
+ const stale = work?.tool?.at && t - Math.max(work.tool.at, work.said?.at || 0, th.last || 0) > IDLE_AFTER && !leases.length && !waits.length;
226
+ const state = !th.alive ? 'ended' : th.reach === 'listening' ? 'ready' : th.reach === 'idle' || stale ? 'idle' : 'working';
227
+ const lastWord = Math.max(prompt, post?.last || 0, work?.plan?.at || 0, work?.said?.at || 0, latest?.at || 0, th.started || 0);
228
+ // Quiet only while it's really at work (a job, or a tool call lately): a session left "working" for hours isn't.
229
+ const busy = state === 'working' && (running || (work?.tool?.at && t - work.tool.at < ACTIVE_WITHIN));
230
+ const quiet = busy && !nowText && !needs.length && !blocked && lastWord && t - lastWord >= QUIET_AFTER ? { since: lastWord } : null;
231
+ const decisions = th.messages.filter(m => m.kind === 'decided' && !m.cleared && m.at > t - DAY).length;
232
+ const last = Math.max(th.last || 0, work?.tool?.at || 0, work?.said?.at || 0, running?.start || 0, post?.last || 0);
233
+
234
+ return {
235
+ to: th.to, parent: null, helpers: [],
236
+ for: forText, state, needs, blocked, now: nowText, plan, results: shown, latest, quiet, decisions,
237
+ unread: th.unread || 0, last,
238
+ details: { folder: ab.project || null, branch: ab.branch || null, model: ab.model || null, asked: ab.asked || null, started: ab.started || th.started || null,
239
+ lastStep: ab.now ? { text: ab.now.text, at: ab.now.at } : null, jobs: [...leases, ...waits].map(x => x.id), ...(codex && { app: 'codex' }) },
240
+ _session: th.session, _agentId: th.agentId,
241
+ };
242
+ }
243
+
244
+ // Claude Code sessions running now that have no thread yet (they never said anything): they're agents too.
245
+ function quietSessions(list) {
246
+ const known = new Set(list.filter(th => th.agentId === MAIN).map(th => th.session).filter(Boolean));
247
+ const names = new Set(list.map(th => th.to));
248
+ const alive = pid => { try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; } };
249
+ return sessionFiles().filter(f => f.name && !known.has(f.sessionId) && !names.has(f.name) && alive(f.pid)).map(f => ({
250
+ agent: f.name, to: f.name, session: f.sessionId, agentId: MAIN, alive: true, reach: f.status === 'idle' ? 'idle' : 'working',
251
+ unread: 0, last: f.updated || f.started || 0, started: f.started, messages: [], about: about(f.sessionId, MAIN, { started: f.started }) || undefined,
252
+ }));
253
+ }
254
+
255
+ // { now, agents: [...] }: every agent, main sessions and their helpers, needs-you first, then by last activity.
256
+ export function agentsJson(t = now()) {
257
+ const cfg = loadConfig();
258
+ const s = peek();
259
+ const posts = readPosts({ since: t - DAY });
260
+ const ks = tasks(posts, t);
261
+ const runs = recentEnds(t);
262
+ // A Codex agent's thread id, from its newest post or run that carries one.
263
+ const codexIds = new Map();
264
+ for (const x of [...posts, ...runs, ...(s.leases || [])]) if (x.codex) codexIds.set(x.who, x.codex);
265
+ const ctx = { s, cfg, ks, runs, codexOf: who => codexIds.get(who) || null };
266
+ const j = threadsJson(t, null, { described: true });
267
+ const list = [...j.threads, ...quietSessions(j.threads)];
268
+ const out = list.map(th => picture(th, ctx, t)).filter(a => a.state !== 'ended' || t - a.last < ENDED_SHOWN);
269
+ // Helpers under their lead: a subagent's thread shares its session.
270
+ const leads = new Map(out.filter(a => a._agentId === MAIN && a._session).map(a => [a._session, a]));
271
+ for (const a of out) {
272
+ if (a._agentId === MAIN || !a._session) continue;
273
+ const lead = leads.get(a._session);
274
+ if (!lead) continue;
275
+ a.parent = lead.to;
276
+ if (a.state !== 'ended') { lead.helpers.push(a.to); lead.unread += a.unread; }
277
+ }
278
+ for (const a of out) { delete a._session; delete a._agentId; }
279
+ const urgent = a => (a.needs.length ? 1 : 0);
280
+ return { now: t, agents: out.sort((a, b) => urgent(b) - urgent(a) || b.last - a.last) };
281
+ }
282
+
283
+ // One agent in two lines, for the person's terminal: "Parsing hand histories (3 of 5). Tests pass, 212 of 212, 4 min ago."
284
+ export function agentLine(a, t = now()) {
285
+ const plan = a.plan && !a.plan.finished ? ` (${a.plan.done} of ${a.plan.total})` : '';
286
+ const what = a.needs.length ? `Needs you: ${a.needs[0].text}` : a.blocked ? a.blocked.text : a.now ? `${a.now.text.replace(/[.!?]$/, '')}${plan}`
287
+ : a.quiet ? `No update for ${minutes(t - a.quiet.since)}` : a.latest && a.state !== 'working' ? a.latest.text : a.state === 'ready' ? 'Ready for a message' : a.state === 'idle' ? 'Idle' : a.state === 'ended' ? 'Ended' : 'Working';
288
+ const r = a.results[0];
289
+ const ago = r ? (t - r.at < MIN ? 'just now' : `${minutes(t - r.at)} ago`) : '';
290
+ return `${what.replace(/[.!?]$/, '')}.${r ? ` ${r.text.replace(/[.!?]$/, '')}, ${ago}.` : ''}`;
291
+ }
292
+
293
+ // The agents at work, for the top of the person's board: lead agents that haven't ended.
294
+ // Each in two lines: its name and what it's for, then what it's doing and its newest result.
295
+ const NAME_COLUMN = 18;
296
+ export function agentLines(t = now()) {
297
+ let list = [];
298
+ try { list = agentsJson(t).agents.filter(a => !a.parent && a.state !== 'ended'); } catch { return []; }
299
+ const w = Math.min(Math.max(0, ...list.map(a => a.to.length)), NAME_COLUMN) + 2;
300
+ const pad = ' '.repeat(w);
301
+ return list.flatMap(a => [
302
+ a.for.from === 'name' || a.for.text === a.to ? bold(a.to) : `${bold(a.to)}${' '.repeat(Math.max(w - a.to.length, 2))}${a.for.text}`,
303
+ wrap(`${pad}${agentLine(a, t)}`, pad),
304
+ ]);
305
+ }
306
+
307
+ // dibs agents [--json]
308
+ export function agents(args) {
309
+ const json = args.includes('--json');
310
+ const bad = args.find(a => a !== '--json');
311
+ if (bad) die(`dibs agents takes --json, not ${bad}`);
312
+ const t = now();
313
+ const j = agentsJson(t);
314
+ if (json) return console.log(JSON.stringify(j, null, 1));
315
+ const live = j.agents.filter(a => !a.parent && a.state !== 'ended');
316
+ if (!live.length) return console.log('No agents at work. They show here once they run something through dibs or say something.');
317
+ console.log(agentLines(t).join('\n'));
318
+ const ended = j.agents.filter(a => !a.parent && a.state === 'ended').length;
319
+ if (ended) console.log(dim(`\n${ended} ended in the last day: dibs agents --json`));
320
+ }
321
+