@dibssoftware/dibs 0.0.180 → 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.
- package/CHANGELOG.md +111 -1
- package/README.md +10 -8
- package/bin/dibs.mjs +379 -74
- package/docs/agents.md +303 -0
- package/docs/council.md +88 -0
- package/docs/files.md +3 -3
- package/docs/guard.md +86 -11
- package/docs/json.md +211 -0
- package/docs/later.md +5 -5
- package/docs/machines.md +6 -6
- package/docs/questions.md +104 -3
- package/docs/reference.md +124 -30
- package/docs/relay.md +135 -11
- package/docs/releasing.md +7 -1
- package/docs/scheduling.md +28 -6
- package/docs/secrets.md +53 -0
- package/docs/simulators.md +3 -3
- package/docs/windows.md +3 -3
- package/package.json +1 -1
- package/skills/dibs/SKILL.md +79 -149
- package/src/about.mjs +341 -0
- package/src/acquire.mjs +113 -28
- package/src/after.mjs +127 -0
- package/src/agents.mjs +2 -1
- package/src/alerts.mjs +109 -48
- package/src/answers.mjs +2 -2
- package/src/board.mjs +21 -16
- package/src/broker.mjs +23 -7
- package/src/carry.mjs +287 -0
- package/src/codex.mjs +132 -0
- package/src/commands.mjs +254 -86
- package/src/config.mjs +85 -14
- package/src/connect.mjs +4 -2
- package/src/cool.mjs +28 -12
- package/src/council.mjs +482 -0
- package/src/cwd.mjs +9 -0
- package/src/decisions.mjs +250 -0
- package/src/declare.mjs +96 -0
- package/src/diskreport.mjs +306 -0
- package/src/diskuse.mjs +420 -0
- package/src/diskwarn.mjs +68 -13
- package/src/doctor.mjs +149 -0
- package/src/doors.mjs +547 -0
- package/src/durable.mjs +143 -0
- package/src/envs.mjs +372 -0
- package/src/events.mjs +7 -2
- package/src/files.mjs +121 -7
- package/src/guard.mjs +288 -105
- package/src/guardd.mjs +8 -1
- package/src/halt.mjs +63 -0
- package/src/handoffs.mjs +362 -0
- package/src/history.mjs +34 -4
- package/src/hogs.mjs +36 -8
- package/src/jobprogress.mjs +283 -0
- package/src/later.mjs +21 -10
- package/src/lock.mjs +51 -11
- package/src/measure.mjs +60 -14
- package/src/media.mjs +240 -0
- package/src/news.mjs +31 -0
- package/src/notes.mjs +49 -8
- package/src/notices.mjs +126 -43
- package/src/ondemand.mjs +25 -2
- package/src/outcome.mjs +163 -0
- package/src/overlap.mjs +2 -2
- package/src/override.mjs +149 -79
- package/src/owner.mjs +15 -2
- package/src/people.mjs +236 -0
- package/src/pickup.mjs +72 -0
- package/src/picture.mjs +321 -0
- package/src/plain.mjs +84 -18
- package/src/platform.mjs +29 -7
- package/src/preempt.mjs +123 -15
- package/src/primer.mjs +91 -20
- package/src/prints.mjs +99 -0
- package/src/proc.mjs +11 -1
- package/src/progress.mjs +49 -3
- package/src/proof.mjs +102 -0
- package/src/push.mjs +271 -0
- package/src/questions.mjs +328 -57
- package/src/quota.mjs +1 -1
- package/src/recap.mjs +205 -0
- package/src/relay.mjs +262 -26
- package/src/remote.mjs +23 -10
- package/src/reviewgate.mjs +268 -0
- package/src/reviews.mjs +377 -0
- package/src/route.mjs +263 -0
- package/src/rules.mjs +216 -0
- package/src/schedule.mjs +238 -44
- package/src/schema.mjs +62 -0
- package/src/scratch.mjs +2 -2
- package/src/serve.mjs +3 -2
- package/src/service.mjs +5 -1
- package/src/signed.mjs +97 -0
- package/src/simpool.mjs +46 -1
- package/src/spend.mjs +375 -0
- package/src/state.mjs +43 -17
- package/src/talk.mjs +1082 -134
- package/src/thin.sh +2 -0
- package/src/trail.mjs +290 -0
- package/src/trailnote.mjs +209 -0
- package/src/util.mjs +7 -0
- package/src/vault.mjs +435 -0
- package/src/vendors.mjs +327 -0
- package/src/version.mjs +1 -1
- package/src/web.mjs +354 -60
- package/src/work.mjs +487 -0
- package/src/worker.mjs +7 -1
package/src/carry.mjs
ADDED
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
// Work outlives the session. Agents stop all the time (a full context, a crash, a closed window),
|
|
2
|
+
// and their work stops with them. When dibs finds a Claude Code session gone with work still open
|
|
3
|
+
// (its last progress post wasn't --done, or it had taken a handoff or work item), it packs up what
|
|
4
|
+
// it knows: where the work is and what git says of it (uncommitted files, unpushed commits, read
|
|
5
|
+
// only), the open task and its last posts, what the trail saw it do (src/trail.mjs, once merged),
|
|
6
|
+
// questions it asked that nobody answered, the files it held leases on, its session's title and
|
|
7
|
+
// what it was asked. That becomes an open handoff (src/handoffs.mjs), from the agent that stopped:
|
|
8
|
+
// - offered first to an agent listening (dibs listen) in the same project, the best fit first;
|
|
9
|
+
// - else, or when that one doesn't take it, the person sees it on the page and the phone, and
|
|
10
|
+
// gives it to an agent (dibs handoff give) or drops it (dibs handoff cancel).
|
|
11
|
+
// The taker hears it as dibs's own message (kind carry in src/talk.mjs), never as the person's.
|
|
12
|
+
//
|
|
13
|
+
// Nothing tells dibs a session ended: Claude Code fires no hook for a crash or a closed window. So
|
|
14
|
+
// it's found on a later look, by whoever looks (the throttle watcher every minute, the relay
|
|
15
|
+
// connector, the page, dibs listen, dibs handoff list): a session with no live process, whose
|
|
16
|
+
// transcript has been still for GRACE. A session that comes back takes its work back: an open
|
|
17
|
+
// carry of it is dropped.
|
|
18
|
+
import fs from 'node:fs';
|
|
19
|
+
import path from 'node:path';
|
|
20
|
+
import { execFile } from 'node:child_process';
|
|
21
|
+
import { HOME } from './config.mjs';
|
|
22
|
+
import { sessionFiles, makeAlive } from './proc.mjs';
|
|
23
|
+
import { read as readPosts, tasks } from './progress.mjs';
|
|
24
|
+
import { lastSeen } from './about.mjs';
|
|
25
|
+
import { projectKey, gitRoot, isFiles, FILES } from './files.mjs';
|
|
26
|
+
import { locked, load, find, hid, OPEN, TAKEN } from './handoffs.mjs';
|
|
27
|
+
import { carryTo, listenersNow } from './talk.mjs';
|
|
28
|
+
import { asked } from './questions.mjs';
|
|
29
|
+
import { peek } from './state.mjs';
|
|
30
|
+
import { EVENTS } from './events.mjs';
|
|
31
|
+
import { minutes } from './plain.mjs';
|
|
32
|
+
import { now, clock } from './util.mjs';
|
|
33
|
+
|
|
34
|
+
// When dibs started watching (carry.json). Only work posted after that counts: the first look on
|
|
35
|
+
// a machine would otherwise turn every session that ended in the last day into a handoff at once.
|
|
36
|
+
const FILE = path.join(HOME, 'carry.json');
|
|
37
|
+
// A session whose last post is older than this ended long ago, and its task with it.
|
|
38
|
+
const WINDOW = 12 * 36e5;
|
|
39
|
+
// A session's transcript still this long before it's taken as ended: a resume starts a new
|
|
40
|
+
// process for the same session within seconds, and its transcript moves again.
|
|
41
|
+
const GRACE = process.env.DIBS_CARRY_GRACE ? Number(process.env.DIBS_CARRY_GRACE) : 2 * 6e4;
|
|
42
|
+
// The long-running lookers (the throttle watcher, the relay connector, dibs listen) look this often.
|
|
43
|
+
const SWEEP_EVERY = 30e3;
|
|
44
|
+
// A listener with a task posted this recently, not closed, is busy with its own work.
|
|
45
|
+
const BUSY_FOR = 3 * 36e5;
|
|
46
|
+
// Git gets this long per call; a repo on a sleeping network volume isn't worth waiting on.
|
|
47
|
+
const GIT_WAIT = 5000;
|
|
48
|
+
// The end of the event log that's read for the file leases a session held: about a day here.
|
|
49
|
+
const EVENTS_TAIL = 1024 * 1024;
|
|
50
|
+
// What the package lists at most of each thing, and its length: it's a message, and a handoff's
|
|
51
|
+
// context is at most 4000 characters (src/handoffs.mjs).
|
|
52
|
+
const POSTS_SHOWN = 4, FILES_SHOWN = 8, TRAIL_SHOWN = 5, QUESTIONS_SHOWN = 4;
|
|
53
|
+
const ASKED_SHOWN = 400;
|
|
54
|
+
const MAX_TEXT = 3800;
|
|
55
|
+
|
|
56
|
+
const cut = (s, n) => { const x = String(s ?? '').replace(/\s+/g, ' ').trim(); return x.length > n ? `${x.slice(0, n - 3).trimEnd()}...` : x; };
|
|
57
|
+
const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
|
|
58
|
+
|
|
59
|
+
let lastAt = 0, running = null;
|
|
60
|
+
// Look for sessions that ended with work open, and hand their work on. Returns the handoffs made.
|
|
61
|
+
// One look at a time per process; force skips the wait between looks.
|
|
62
|
+
export function sweep({ force = false, t = now() } = {}) {
|
|
63
|
+
if (running) return running;
|
|
64
|
+
if (!force && t - lastAt < SWEEP_EVERY) return Promise.resolve([]);
|
|
65
|
+
lastAt = t;
|
|
66
|
+
running = look(t).finally(() => { running = null; });
|
|
67
|
+
return running;
|
|
68
|
+
}
|
|
69
|
+
// For the loops that can't wait on git: a look started, not waited for. A look that fails is
|
|
70
|
+
// tried again on the next one, and the work stays where it was meanwhile.
|
|
71
|
+
export const sweepSoon = () => { sweep().catch(() => {}); };
|
|
72
|
+
|
|
73
|
+
function watchingSince(t) {
|
|
74
|
+
try { return JSON.parse(fs.readFileSync(FILE, 'utf8')).since; } catch {}
|
|
75
|
+
fs.mkdirSync(HOME, { recursive: true });
|
|
76
|
+
const tmp = `${FILE}.${process.pid}`;
|
|
77
|
+
fs.writeFileSync(tmp, JSON.stringify({ since: t }));
|
|
78
|
+
fs.renameSync(tmp, FILE);
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
async function look(t) {
|
|
83
|
+
const files = sessionFiles();
|
|
84
|
+
// No Claude Code session on record at all: dibs can't tell an ended session from one it can't see.
|
|
85
|
+
if (!files.length) return [];
|
|
86
|
+
const up = makeAlive(files.map(f => f.pid));
|
|
87
|
+
const live = new Set(files.filter(f => up(f.pid)).map(f => f.sessionId));
|
|
88
|
+
const since = watchingSince(t);
|
|
89
|
+
if (since == null) return [];
|
|
90
|
+
const st = load();
|
|
91
|
+
if (st.handoffs.some(x => x.state === OPEN && x.carry && live.has(x.carry.session))) takeBack(live, t);
|
|
92
|
+
const made = [];
|
|
93
|
+
for (const c of candidates(st, live, since, t)) {
|
|
94
|
+
const x = await handOn(c, files, t);
|
|
95
|
+
if (x) made.push(x);
|
|
96
|
+
}
|
|
97
|
+
return made;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// A session that runs again takes its work back: an open handoff made of it is dropped, and an
|
|
101
|
+
// item it had taken loses the package and stays open, as it was.
|
|
102
|
+
function takeBack(live, t) {
|
|
103
|
+
locked(s => {
|
|
104
|
+
for (const x of s.handoffs) {
|
|
105
|
+
if (x.state !== OPEN || !x.carry || !live.has(x.carry.session)) continue;
|
|
106
|
+
if (x.from?.session === x.carry.session) Object.assign(x, { state: 'cancelled', closedAt: t, cancelledBy: `dibs: ${x.carry.who}'s session is running again` });
|
|
107
|
+
else delete x.carry;
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// Sessions gone, with work open: { session, posts, item, seen, quiet }.
|
|
113
|
+
function candidates(st, live, since, t) {
|
|
114
|
+
const by = new Map();
|
|
115
|
+
const add = session => { if (!by.has(session)) by.set(session, { session, posts: [], item: null }); return by.get(session); };
|
|
116
|
+
for (const p of readPosts({ since: Math.max(since, t - WINDOW) })) if (p.session && !live.has(p.session)) add(p.session).posts.push(p);
|
|
117
|
+
for (const [session, c] of by) {
|
|
118
|
+
// Its last word (its lead's, when it has subagents) closed its work: it ended cleanly.
|
|
119
|
+
const main = c.posts.filter(p => !p.agentId);
|
|
120
|
+
if ((main.length ? main : c.posts).at(-1).state === 'done') by.delete(session);
|
|
121
|
+
}
|
|
122
|
+
// A handoff or work item it had taken: still marked taken, or opened again by an earlier read.
|
|
123
|
+
for (const x of st.handoffs) {
|
|
124
|
+
const gone = x.state === TAKEN ? x.taker?.session : x.state === OPEN && !x.carry ? x.returns?.at(-1)?.session : null;
|
|
125
|
+
const at = x.state === TAKEN ? x.takenAt : x.returns?.at(-1)?.at;
|
|
126
|
+
if (gone && !live.has(gone) && at >= since) add(gone).item = x;
|
|
127
|
+
}
|
|
128
|
+
const out = [];
|
|
129
|
+
for (const c of by.values()) {
|
|
130
|
+
c.seen = lastSeen(c.session);
|
|
131
|
+
// No transcript here: not a Claude Code session on this machine, so nothing says it ended.
|
|
132
|
+
if (!c.seen) continue;
|
|
133
|
+
c.quiet = Math.max(c.seen.touched, c.posts.at(-1)?.at || 0);
|
|
134
|
+
if (t - c.quiet < GRACE) continue;
|
|
135
|
+
if (st.handoffs.some(x => x.carry?.session === c.session && x.carry.upTo >= c.quiet)) continue;
|
|
136
|
+
out.push(c);
|
|
137
|
+
}
|
|
138
|
+
return out;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
async function handOn(c, files, t) {
|
|
142
|
+
const p = await pack(c, files, t);
|
|
143
|
+
const offer = p.key ? bestListener(p, c.session, t) : null;
|
|
144
|
+
const x = locked(s => {
|
|
145
|
+
if (s.handoffs.some(y => y.carry?.session === c.session && y.carry.upTo >= c.quiet)) return null;
|
|
146
|
+
const carry = { session: c.session, who: p.name, at: t, stoppedAt: c.quiet, upTo: c.quiet, project: p.project, branch: p.branch, cwd: p.cwd,
|
|
147
|
+
git: p.git ? { changed: p.git.changed.length, unpushed: p.git.unpushed } : null, text: p.text,
|
|
148
|
+
...(offer && { offered: { name: offer.name, at: t } }) };
|
|
149
|
+
// The item it had taken is what's handed on (the read that took this lock opened it again); else its task, as a new handoff.
|
|
150
|
+
let x = c.item && find(s, c.item.id);
|
|
151
|
+
// Still taken: its taker's process looked alive to this read. The next look settles it.
|
|
152
|
+
if (x?.state === TAKEN) return null;
|
|
153
|
+
if (x?.state === OPEN && !x.carry) Object.assign(x, { carry, to: null });
|
|
154
|
+
else if (!c.posts.length) return null;
|
|
155
|
+
else s.handoffs.push(x = { id: ++s.seq, title: p.title, context: p.text, from: { name: p.name, who: p.who, session: c.session, agentId: 'main' },
|
|
156
|
+
to: null, state: OPEN, at: t, carry });
|
|
157
|
+
return { ...x };
|
|
158
|
+
});
|
|
159
|
+
if (x && offer) {
|
|
160
|
+
carryTo(offer, `${p.name} stopped mid-task, and you're listening in the same project, so dibs offers its work to you first: ${hid(x)} "${x.title}".\n${p.text}\n`
|
|
161
|
+
+ `Take it: dibs handoff take ${hid(x)}. If you're in the middle of your own work, or it isn't yours to do: dibs handoff back ${hid(x)} "why", and the person decides.`);
|
|
162
|
+
}
|
|
163
|
+
return x;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// What dibs knows of the work: { name, who, title, project, branch, cwd, key, git, text }.
|
|
167
|
+
async function pack(c, files, t) {
|
|
168
|
+
const posts = c.posts;
|
|
169
|
+
const name = files.find(f => f.sessionId === c.session)?.name || posts.at(-1)?.who || c.item?.taker?.name || c.item?.returns?.at(-1)?.by || 'an agent';
|
|
170
|
+
const cwd = c.seen.cwd;
|
|
171
|
+
const git = cwd ? await gitState(cwd) : null;
|
|
172
|
+
const open = tasks(posts, t).filter(k => k.state !== 'done').sort((a, b) => b.last - a.last);
|
|
173
|
+
const task = open.find(k => !k.agentId) || open[0] || null;
|
|
174
|
+
const project = posts.at(-1)?.project || (cwd ? path.basename(gitRoot(cwd) || cwd) : null);
|
|
175
|
+
const branch = git?.branch || c.seen.branch || task?.branch || null;
|
|
176
|
+
const title = cut(c.item?.title || task?.task || c.seen.title || task?.text || 'its unfinished work', 120);
|
|
177
|
+
|
|
178
|
+
const lines = [`${name} stopped mid-task: its Claude Code session ended, last heard from ${minutes(t - c.quiet)} ago, with work still open.`];
|
|
179
|
+
if (c.seen.title) lines.push(`Its session was called "${cut(c.seen.title, 120)}".`);
|
|
180
|
+
if (c.seen.asked) lines.push(`What it was asked (the person's words to ${name}, not to you): "${cut(c.seen.asked, ASKED_SHOWN)}"`);
|
|
181
|
+
lines.push(where(cwd, git, branch));
|
|
182
|
+
if (c.item) lines.push(`It had taken ${hid(c.item)} ("${cut(c.item.title, 120)}")${c.item.from?.name ? ` from ${c.item.from.name}` : ''}; that's what's handed on.`);
|
|
183
|
+
if (task) {
|
|
184
|
+
const due = task.eta ? (task.eta < t ? `, due ${clock(task.eta)} and overdue` : `, expected by ${clock(task.eta)}`) : '';
|
|
185
|
+
lines.push(`Its task${task.task ? ` "${task.task}"` : ''} (${task.state === 'blocked' ? 'blocked' : 'not done'}${due}). Its last posts:`);
|
|
186
|
+
const mine = posts.filter(p => (p.task || null) === task.task && (p.agentId || null) === (task.agentId || null));
|
|
187
|
+
for (const p of mine.slice(-POSTS_SHOWN)) lines.push(`- ${clock(p.at)} ${cut(p.text, 300)}`);
|
|
188
|
+
}
|
|
189
|
+
const others = open.filter(k => k !== task).slice(0, 3);
|
|
190
|
+
if (others.length) lines.push(`Also open: ${others.map(k => `"${k.task || cut(k.text, 60)}"`).join(', ')}.`);
|
|
191
|
+
const qs = asked(t).filter(q => q.session === c.session && q.state === 'open').slice(-QUESTIONS_SHOWN);
|
|
192
|
+
if (qs.length) lines.push(`Its questions nobody answered (dibs answer <id> "..." answers one for it): ${qs.map(q => `#${q.id} ${cut(q.text, 120)}`).join('; ')}.`);
|
|
193
|
+
const held = heldFiles(c.session, cwd);
|
|
194
|
+
if (held.length) lines.push(`Files it held leases on: ${held.slice(0, FILES_SHOWN).join(', ')}${held.length > FILES_SHOWN ? ` and ${held.length - FILES_SHOWN} more` : ''}.`);
|
|
195
|
+
const trail = await trailOf(c.session, c.quiet - WINDOW, t);
|
|
196
|
+
if (trail.length) lines.push(`What dibs saw it do: ${trail.join('; ')}.`);
|
|
197
|
+
let text = lines.join('\n');
|
|
198
|
+
if (text.length > MAX_TEXT) text = `${text.slice(0, MAX_TEXT - 3)}...`;
|
|
199
|
+
return { name, who: posts.at(-1)?.who || name, title, project, branch, cwd, key: cwd ? projectKey(cwd) : null, git, text };
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
function where(cwd, git, branch) {
|
|
203
|
+
if (!cwd) return 'Where: its transcript names no folder.';
|
|
204
|
+
if (!git) return `Where: ${cwd} (not a git checkout, or git couldn't read it).`;
|
|
205
|
+
const parts = [`Where: ${cwd}${branch ? `, branch ${branch}` : ''}.`];
|
|
206
|
+
const n = git.changed.length;
|
|
207
|
+
parts.push(n ? `Not committed: ${plural(n, 'file')} (${git.changed.slice(0, FILES_SHOWN).join(', ')}${n > FILES_SHOWN ? ', ...' : ''}).` : 'Nothing uncommitted.');
|
|
208
|
+
if (git.unpushed > 0) parts.push(`Not pushed: ${plural(git.unpushed, 'commit')}.`);
|
|
209
|
+
else if (git.unpushed === 0) parts.push('Every commit is pushed.');
|
|
210
|
+
else parts.push('No remote to push to.');
|
|
211
|
+
if (git.head) parts.push(`Last commit: ${git.head}.`);
|
|
212
|
+
return parts.join(' ');
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// Read-only: --no-optional-locks keeps git status from refreshing the index, which takes a lock
|
|
216
|
+
// the agent picking this up might want.
|
|
217
|
+
const git = (cwd, args) => new Promise(resolve => execFile('git', ['--no-optional-locks', '-C', cwd, ...args],
|
|
218
|
+
{ timeout: GIT_WAIT, maxBuffer: 4 * 1024 ** 2, env: { ...process.env, GIT_OPTIONAL_LOCKS: '0' } }, (e, out) => resolve(e ? null : out)));
|
|
219
|
+
|
|
220
|
+
// { branch, changed: [paths], unpushed (null: nowhere to push), head: "abc1234 subject" }, or null outside git.
|
|
221
|
+
export async function gitState(cwd) {
|
|
222
|
+
const st = await git(cwd, ['status', '--porcelain=v1', '-b']);
|
|
223
|
+
if (st == null) return null;
|
|
224
|
+
const [top = '', ...rest] = st.split('\n').filter(Boolean);
|
|
225
|
+
const [mine, upstream] = top.replace(/^## (No commits yet on )?/, '').split('...');
|
|
226
|
+
const branch = mine && !mine.startsWith('HEAD') ? mine.trim() : null;
|
|
227
|
+
const changed = rest.map(l => l.slice(3).replace(/^.* -> /, '').replace(/^"(.*)"$/, '$1'));
|
|
228
|
+
let unpushed = null;
|
|
229
|
+
if (upstream) unpushed = Number(upstream.match(/ahead (\d+)/)?.[1] || 0);
|
|
230
|
+
else if ((await git(cwd, ['remote']))?.trim()) {
|
|
231
|
+
const n = await git(cwd, ['rev-list', '--count', 'HEAD', '--not', '--remotes']);
|
|
232
|
+
if (n != null) unpushed = Number(n.trim()) || 0;
|
|
233
|
+
}
|
|
234
|
+
const head = (await git(cwd, ['log', '-1', '--format=%h %s']))?.trim() || null;
|
|
235
|
+
return { branch, changed, unpushed, head: head && cut(head, 100) };
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
// The paths a session held leases on: those still on the books, and those whose end the event
|
|
239
|
+
// log tied to it (src/events.mjs). Shown relative to its folder when they're under it.
|
|
240
|
+
function heldFiles(session, cwd) {
|
|
241
|
+
const res = [];
|
|
242
|
+
for (const l of peek().leases || []) if (l.sessionId === session) res.push(...(l.res || []));
|
|
243
|
+
let tail = '';
|
|
244
|
+
try {
|
|
245
|
+
const size = fs.statSync(EVENTS).size, from = Math.max(0, size - EVENTS_TAIL);
|
|
246
|
+
const fd = fs.openSync(EVENTS, 'r');
|
|
247
|
+
try { const buf = Buffer.alloc(size - from); fs.readSync(fd, buf, 0, buf.length, from); tail = buf.toString('utf8'); } finally { fs.closeSync(fd); }
|
|
248
|
+
} catch {}
|
|
249
|
+
for (const l of tail.split('\n')) {
|
|
250
|
+
if (!l.includes(session)) continue;
|
|
251
|
+
try { const e = JSON.parse(l); if (e.kind === 'end' && e.session === session) res.push(...(e.res || [])); } catch {}
|
|
252
|
+
}
|
|
253
|
+
const root = cwd && (gitRoot(cwd) || cwd);
|
|
254
|
+
const shown = res.filter(isFiles).map(r => r.slice(FILES.length)).map(p => (root && p.startsWith(`${root}/`) ? p.slice(root.length + 1) : p));
|
|
255
|
+
return [...new Set(shown)];
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// The trail's last few items for the session: what it committed, pushed, merged and ran. The
|
|
259
|
+
// trail is another branch's (src/trail.mjs); until it's merged there's none, and nothing is lost.
|
|
260
|
+
async function trailOf(session, since, t) {
|
|
261
|
+
let trail;
|
|
262
|
+
try { trail = await import('./trail.mjs'); } catch { return []; }
|
|
263
|
+
try {
|
|
264
|
+
return trail.trailNow({ since, t }).filter(x => x.session === session).slice(-TRAIL_SHOWN)
|
|
265
|
+
.map(x => `${cut(x.text, 120)}${x.ok === false ? ' (failed)' : ''}`);
|
|
266
|
+
} catch { return []; }
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// The listening agent the work fits best: same project (any worktree or clone of its repo) or none
|
|
270
|
+
// at all; then one with no open task of its own; then on the work's branch; then the newest listener.
|
|
271
|
+
function bestListener(p, session, t) {
|
|
272
|
+
const files = new Map(sessionFiles().map(f => [f.sessionId, f]));
|
|
273
|
+
const busy = new Set();
|
|
274
|
+
const last = new Map();
|
|
275
|
+
for (const x of readPosts({ since: t - BUSY_FOR })) if (x.session && !x.agentId) last.set(x.session, x);
|
|
276
|
+
for (const [s, x] of last) if (x.state !== 'done') busy.add(s);
|
|
277
|
+
const fits = [];
|
|
278
|
+
for (const l of listenersNow()) {
|
|
279
|
+
if (!l.session || l.session === session || (l.agentId || 'main') !== 'main') continue;
|
|
280
|
+
const seen = lastSeen(l.session);
|
|
281
|
+
const cwd = seen?.cwd || files.get(l.session)?.cwd;
|
|
282
|
+
if (!cwd || projectKey(cwd) !== p.key) continue;
|
|
283
|
+
fits.push({ ...l, rank: [!busy.has(l.session), !!p.branch && seen?.branch === p.branch, l.at || 0] });
|
|
284
|
+
}
|
|
285
|
+
const ahead = (a, b) => { for (let i = 0; i < a.rank.length; i++) if (a.rank[i] !== b.rank[i]) return a.rank[i] > b.rank[i] ? -1 : 1; return 0; };
|
|
286
|
+
return fits.sort(ahead)[0] || null;
|
|
287
|
+
}
|
package/src/codex.mjs
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
// What a Codex agent says about its own work, read from Codex's session files
|
|
2
|
+
// (~/.codex/sessions/YYYY/MM/DD/rollout-<time>-<thread id>.jsonl), the same way src/about.mjs
|
|
3
|
+
// reads Claude Code's: only the file's tail, kept until it grows. A Codex agent is found by
|
|
4
|
+
// the thread id Codex puts in its commands' environment (CODEX_THREAD_ID), which dibs keeps on
|
|
5
|
+
// its posts and runs.
|
|
6
|
+
import fs from 'node:fs';
|
|
7
|
+
import os from 'node:os';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { planItems, runIds } from './about.mjs';
|
|
10
|
+
import { outcomeOf, firstSentence } from './outcome.mjs';
|
|
11
|
+
|
|
12
|
+
const SESSIONS = process.env.DIBS_CODEX_SESSIONS || path.join(os.homedir(), '.codex', 'sessions');
|
|
13
|
+
// The newest file's tail holds the plan and the last turns; its head the folder and first prompt.
|
|
14
|
+
const TAIL = 256 * 1024;
|
|
15
|
+
const HEAD = 32 * 1024;
|
|
16
|
+
// A thread is looked for among this many of the newest days' folders: older ones aren't at work.
|
|
17
|
+
const DAYS_LOOKED = 14;
|
|
18
|
+
const RUNS_KEPT = 20;
|
|
19
|
+
const PROMPT_SHOWN = 600;
|
|
20
|
+
|
|
21
|
+
const kept = new Map();
|
|
22
|
+
let days = null, daysAt = 0;
|
|
23
|
+
|
|
24
|
+
const cut = (s, n) => (s.length > n ? `${s.slice(0, n - 3).trimEnd()}...` : s);
|
|
25
|
+
const subdirs = d => { try { return fs.readdirSync(d).filter(x => /^\d+$/.test(x)).sort().reverse(); } catch { return []; } };
|
|
26
|
+
|
|
27
|
+
function fileOf(thread) {
|
|
28
|
+
if (!/^[\w-]{8,64}$/.test(thread || '')) return null;
|
|
29
|
+
const hit = kept.get(`path:${thread}`);
|
|
30
|
+
if (hit && fs.existsSync(hit)) return hit;
|
|
31
|
+
if (!days || Date.now() - daysAt > 30e3) {
|
|
32
|
+
days = [];
|
|
33
|
+
for (const y of subdirs(SESSIONS)) for (const m of subdirs(path.join(SESSIONS, y))) for (const d of subdirs(path.join(SESSIONS, y, m))) {
|
|
34
|
+
if (days.length >= DAYS_LOOKED) break;
|
|
35
|
+
days.push(path.join(SESSIONS, y, m, d));
|
|
36
|
+
}
|
|
37
|
+
daysAt = Date.now();
|
|
38
|
+
}
|
|
39
|
+
for (const d of days) {
|
|
40
|
+
let names = [];
|
|
41
|
+
try { names = fs.readdirSync(d); } catch {}
|
|
42
|
+
const f = names.find(n => n.endsWith(`-${thread}.jsonl`));
|
|
43
|
+
if (f) { kept.set(`path:${thread}`, path.join(d, f)); return path.join(d, f); }
|
|
44
|
+
}
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function slice(file, from, length) {
|
|
49
|
+
const fd = fs.openSync(file, 'r');
|
|
50
|
+
try {
|
|
51
|
+
const buf = Buffer.alloc(length);
|
|
52
|
+
return buf.subarray(0, fs.readSync(fd, buf, 0, length, from)).toString('utf8');
|
|
53
|
+
} finally { fs.closeSync(fd); }
|
|
54
|
+
}
|
|
55
|
+
function parse(text, dropFirst, dropLast) {
|
|
56
|
+
const parts = text.split('\n');
|
|
57
|
+
if (dropFirst) parts.shift();
|
|
58
|
+
if (dropLast) parts.pop();
|
|
59
|
+
const out = [];
|
|
60
|
+
for (const l of parts) { if (!l) continue; try { out.push(JSON.parse(l)); } catch {} }
|
|
61
|
+
return out;
|
|
62
|
+
}
|
|
63
|
+
const json = s => { if (s && typeof s === 'object') return s; try { return JSON.parse(s); } catch { return null; } };
|
|
64
|
+
const outputOf = o => (typeof o === 'string' ? (json(o)?.output ?? o) : Array.isArray(o) ? o.map(x => x?.text || '').join('\n') : '');
|
|
65
|
+
|
|
66
|
+
function head(entries) {
|
|
67
|
+
const out = {};
|
|
68
|
+
for (const e of entries) {
|
|
69
|
+
const p = e.payload || {};
|
|
70
|
+
if (e.type === 'session_meta') { out.cwd = p.cwd || out.cwd; if (p.git?.branch) out.branch = p.git.branch; }
|
|
71
|
+
if (!out.asked && e.type === 'event_msg' && p.type === 'user_message' && typeof p.message === 'string' && p.message.trim()) out.asked = cut(p.message.trim(), PROMPT_SHOWN);
|
|
72
|
+
}
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function tail(entries) {
|
|
77
|
+
const out = { runs: [] };
|
|
78
|
+
const calls = new Map();
|
|
79
|
+
let order = 0, after = null;
|
|
80
|
+
for (const e of entries) {
|
|
81
|
+
const at = Date.parse(e.timestamp) || null;
|
|
82
|
+
const p = e.payload || {};
|
|
83
|
+
if (e.type === 'turn_context' && p.model) out.model = p.model;
|
|
84
|
+
if (e.type === 'event_msg' && p.type === 'thread_settings_applied' && p.thread_settings?.model) out.model = p.thread_settings.model;
|
|
85
|
+
if (e.type === 'event_msg' && p.type === 'user_message') out.prompt = at;
|
|
86
|
+
if (e.type === 'event_msg' && p.type === 'agent_message' && p.message?.trim()) {
|
|
87
|
+
out.said = { text: p.message.trim(), at, order: ++order };
|
|
88
|
+
if (after && after.reading === undefined) after.reading = firstSentence(p.message);
|
|
89
|
+
}
|
|
90
|
+
if (e.type === 'event_msg' && p.type === 'task_complete' && p.last_agent_message) out.complete = { text: String(p.last_agent_message), at };
|
|
91
|
+
if (e.type === 'response_item' && (p.type === 'function_call' || p.type === 'custom_tool_call')) {
|
|
92
|
+
out.tool = { at, order: ++order };
|
|
93
|
+
const args = json(p.arguments ?? p.input) || {};
|
|
94
|
+
const cmd = Array.isArray(args.command) ? args.command.join(' ') : String(args.cmd || args.command || p.input || '');
|
|
95
|
+
calls.set(p.call_id, { at, dibs: /(^|[\s;&|("])dibs\s+(run|hold)\b/.test(cmd) });
|
|
96
|
+
if (p.name === 'update_plan') out.plan = { from: 'codex', at, items: planItems(args.plan, x => x.step) };
|
|
97
|
+
if (after) after = null;
|
|
98
|
+
}
|
|
99
|
+
const done = e.type === 'event_msg' && p.type === 'exec_command_end' ? { id: p.call_id, text: p.aggregated_output ?? [p.stdout, p.stderr].filter(Boolean).join('\n'), code: p.exit_code }
|
|
100
|
+
: e.type === 'response_item' && (p.type === 'function_call_output' || p.type === 'custom_tool_call_output') ? { id: p.call_id, text: outputOf(p.output) } : null;
|
|
101
|
+
if (done && calls.has(done.id)) {
|
|
102
|
+
const call = calls.get(done.id);
|
|
103
|
+
calls.delete(done.id);
|
|
104
|
+
const ids = runIds(done.text || '');
|
|
105
|
+
if (!ids.length && !call.dibs) continue;
|
|
106
|
+
after = { at: call.at, doneAt: at, ids, outcome: outcomeOf(done.text || '', done.code ?? null) };
|
|
107
|
+
out.runs.push(after);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
if (out.plan && !out.plan.items.length) delete out.plan;
|
|
111
|
+
out.runs = out.runs.slice(-RUNS_KEPT);
|
|
112
|
+
return out;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// { project, branch, model, asked, ...work } for one Codex thread, or null.
|
|
116
|
+
export function codexWork(thread) {
|
|
117
|
+
const file = fileOf(thread);
|
|
118
|
+
if (!file) return null;
|
|
119
|
+
let st;
|
|
120
|
+
try { st = fs.statSync(file); } catch { return null; }
|
|
121
|
+
const hit = kept.get(file);
|
|
122
|
+
if (hit && hit.size === st.size && hit.mtime === st.mtimeMs) return hit.v;
|
|
123
|
+
let v = null;
|
|
124
|
+
try {
|
|
125
|
+
const from = Math.max(0, st.size - TAIL);
|
|
126
|
+
const h = hit?.h || head(parse(slice(file, 0, Math.min(HEAD, st.size)), false, st.size > HEAD));
|
|
127
|
+
v = { ...h, project: h.cwd ? path.basename(h.cwd) : null, ...tail(parse(slice(file, from, st.size - from), from > 0, false)) };
|
|
128
|
+
delete v.cwd;
|
|
129
|
+
kept.set(file, { size: st.size, mtime: st.mtimeMs, v, h });
|
|
130
|
+
} catch { v = null; }
|
|
131
|
+
return v;
|
|
132
|
+
}
|