@dibssoftware/dibs 0.0.179 → 0.0.180
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +23 -2
- package/README.md +4 -2
- package/bin/dibs-guard.mjs +10 -1
- package/bin/dibs.mjs +28 -9
- package/docs/benchmarks.md +1 -1
- package/docs/files.md +1 -1
- package/docs/guard.md +6 -0
- package/docs/questions.md +6 -2
- package/docs/reference.md +4 -4
- package/docs/relay.md +9 -7
- package/docs/releasing.md +4 -3
- package/docs/scheduling.md +4 -4
- package/docs/windows.md +14 -0
- package/package.json +1 -1
- package/skills/dibs/SKILL.md +5 -5
- package/src/acquire.mjs +91 -26
- package/src/agents.mjs +7 -22
- package/src/alerts.mjs +59 -21
- package/src/board.mjs +1 -2
- package/src/broker.mjs +26 -11
- package/src/commands.mjs +25 -9
- package/src/config.mjs +21 -4
- package/src/cool.mjs +104 -9
- package/src/diskwarn.mjs +4 -0
- package/src/events.mjs +10 -1
- package/src/files.mjs +49 -87
- package/src/guard.mjs +24 -8
- package/src/guardd.mjs +97 -0
- package/src/guardw.mjs +19 -0
- package/src/later.mjs +20 -25
- package/src/lock.mjs +292 -0
- package/src/measure.mjs +9 -4
- package/src/ondemand.mjs +5 -2
- package/src/override.mjs +39 -2
- package/src/plain.mjs +2 -2
- package/src/platform.mjs +165 -35
- package/src/preempt.mjs +51 -3
- package/src/primer.mjs +1 -1
- package/src/proc.mjs +35 -5
- package/src/questions.mjs +8 -22
- package/src/relay.mjs +10 -22
- package/src/remote.mjs +12 -8
- package/src/schedule.mjs +139 -26
- package/src/serve.mjs +16 -3
- package/src/service.mjs +4 -3
- package/src/state.mjs +139 -47
- package/src/stats.mjs +3 -2
- package/src/talk.mjs +160 -77
- package/src/trust.mjs +7 -1
- package/src/util.mjs +28 -2
- package/src/version.mjs +1 -1
- package/src/web.mjs +15 -25
- package/src/worker.mjs +2 -1
package/src/files.mjs
CHANGED
|
@@ -6,9 +6,22 @@
|
|
|
6
6
|
// but util.mjs, reads state.json without the lock (it's written by rename) and
|
|
7
7
|
// spawns nothing unless another session's lease covers the path.
|
|
8
8
|
import fs from 'node:fs';
|
|
9
|
-
import
|
|
10
|
-
import
|
|
9
|
+
import nodeOs from 'node:os';
|
|
10
|
+
import nodePath from 'node:path';
|
|
11
11
|
import { execFileSync } from 'node:child_process';
|
|
12
|
+
|
|
13
|
+
// Every path in this file is written with /, Windows too (C:/Users/x/src/a.ts, as
|
|
14
|
+
// git writes them): lease keys, globs and the hook's comparisons all split on /.
|
|
15
|
+
// path and os here hand back paths that way; macOS and Linux are unchanged.
|
|
16
|
+
const WIN = process.platform === 'win32';
|
|
17
|
+
const slash = p => (WIN && typeof p === 'string' ? p.replace(/\\/g, '/') : p);
|
|
18
|
+
const path = !WIN ? nodePath : {
|
|
19
|
+
...nodePath, sep: '/',
|
|
20
|
+
resolve: (...a) => slash(nodePath.resolve(...a)), join: (...a) => slash(nodePath.join(...a)), dirname: p => slash(nodePath.dirname(p)),
|
|
21
|
+
relative: (a, b) => slash(nodePath.relative(a, b)), normalize: p => slash(nodePath.normalize(p)),
|
|
22
|
+
};
|
|
23
|
+
const os = !WIN ? nodeOs : { ...nodeOs, homedir: () => slash(nodeOs.homedir()), tmpdir: () => slash(nodeOs.tmpdir()) };
|
|
24
|
+
const cwdNow = () => slash(process.cwd());
|
|
12
25
|
import { dur, clock, fakeFull, callerPid } from './util.mjs';
|
|
13
26
|
|
|
14
27
|
export const FILES = 'files:';
|
|
@@ -87,12 +100,11 @@ function guessedOthers(prefix, session) {
|
|
|
87
100
|
return null;
|
|
88
101
|
}
|
|
89
102
|
|
|
90
|
-
//
|
|
91
|
-
//
|
|
92
|
-
//
|
|
93
|
-
// (
|
|
94
|
-
//
|
|
95
|
-
const UNTRACKED_MAX = 20; // files: an older folder this small is cheap to lose, one bigger may be someone's work
|
|
103
|
+
// dibs remembers which agent first wrote into each folder at the top of a
|
|
104
|
+
// session's scratchpad (scratch/<session>/<folder> in DIBS_HOME, made with wx so
|
|
105
|
+
// the first one wins without a lock), so the disk watcher can tell whose it is
|
|
106
|
+
// (src/hogs.mjs). It never decides who may delete: every agent of a session may
|
|
107
|
+
// delete anything in its own scratchpad short of all of it.
|
|
96
108
|
const makersDir = session => path.join(dibsHome(), 'scratch', session);
|
|
97
109
|
const agentOf = input => input.agent_id || 'main';
|
|
98
110
|
|
|
@@ -106,73 +118,25 @@ function inSession(p) {
|
|
|
106
118
|
return null;
|
|
107
119
|
}
|
|
108
120
|
|
|
109
|
-
// Subagents of a session that have stopped (SubagentStop), so the main thread may clear
|
|
110
|
-
// what they left in the scratchpad. A teammate that takes another message starts again
|
|
111
|
-
// and loses the mark. The name can't be a folder's: encodeURIComponent never makes a bare %.
|
|
112
|
-
const stopMark = (session, agent) => path.join(makersDir(session), '%stopped', encodeURIComponent(agent));
|
|
113
|
-
export function subagentState(input) {
|
|
114
|
-
if (typeof input?.session_id !== 'string' || typeof input.agent_id !== 'string' || !input.agent_id) return;
|
|
115
|
-
const f = stopMark(input.session_id, input.agent_id);
|
|
116
|
-
try {
|
|
117
|
-
if (input.hook_event_name === 'SubagentStop') { fs.mkdirSync(path.dirname(f), { recursive: true }); fs.writeFileSync(f, String(Date.now())); }
|
|
118
|
-
else if (input.hook_event_name === 'SubagentStart') fs.rmSync(f, { force: true });
|
|
119
|
-
} catch {}
|
|
120
|
-
}
|
|
121
|
-
const stopped = (session, agent) => fs.existsSync(stopMark(session, agent));
|
|
122
|
-
|
|
123
|
-
// Folders that rebuild themselves: a browser profile's caches, Xcode's and Swift's build
|
|
124
|
-
// output, a bundler's. Any agent of the session may clear them in its own scratchpad
|
|
125
|
-
// (on 2026-11-03 an agent had to ask a teammate to delete Chrome caches in its own session).
|
|
126
|
-
const CACHES = new Set(['Cache', 'Caches', 'Code Cache', 'GPUCache', 'DerivedData', '.build', 'build', 'dist', '.next', '.turbo', '.cache']);
|
|
127
|
-
|
|
128
121
|
export function maker(session, name) {
|
|
129
122
|
try { return JSON.parse(fs.readFileSync(path.join(makersDir(session), encodeURIComponent(name)), 'utf8')); } catch { return null; }
|
|
130
123
|
}
|
|
131
124
|
|
|
132
|
-
// Whether the folder at dir holds more than max files, stopping as soon as it does.
|
|
133
|
-
function bigger(dir, max) {
|
|
134
|
-
const stack = [dir];
|
|
135
|
-
let n = 0;
|
|
136
|
-
while (stack.length) {
|
|
137
|
-
let list;
|
|
138
|
-
try { list = fs.readdirSync(stack.pop(), { withFileTypes: true }); } catch { continue; }
|
|
139
|
-
for (const e of list) {
|
|
140
|
-
if (e.isDirectory()) stack.push(path.join(e.parentPath ?? e.path, e.name));
|
|
141
|
-
else if (++n > max) return true;
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
return false;
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
const agentName = m => (m.agent === 'main' ? 'the main thread' : m.type ? `${m.type} (${m.agent})` : m.agent);
|
|
148
|
-
|
|
149
125
|
// Why a recursive delete of p, in the caller's own session folder, would take
|
|
150
|
-
// what
|
|
126
|
+
// the whole of what every agent of the session shares, or null when it's fine.
|
|
151
127
|
function ownDelete(p, t, input) {
|
|
152
128
|
const at = inSession(p);
|
|
153
129
|
if (!at) return null;
|
|
154
130
|
const [folder, rest] = at, pad = path.join(folder, 'scratchpad');
|
|
155
131
|
const whole = what => `${p} is ${what}, which every agent of your session keeps its scratch files in, so ${t.why} can't delete all of it.\n`
|
|
156
|
-
+ 'Delete the folders in it
|
|
132
|
+
+ 'Delete the folders in it you are done with instead. If it really must all go, have the person delete it.';
|
|
157
133
|
if (!rest.length) return whole("your session's temp folder");
|
|
158
134
|
if (!overlap(path.join(folder, rest[0]), pad)) return null;
|
|
159
135
|
if (rest.length === 1) return whole("your session's scratchpad");
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
}
|
|
165
|
-
for (const n of names) {
|
|
166
|
-
const m = maker(input.session_id, n), dir = path.join(pad, n);
|
|
167
|
-
// The main thread may clear what a subagent of its own left, once that subagent has stopped.
|
|
168
|
-
if (m && m.agent !== agentOf(input) && !(agentOf(input) === 'main' && m.agent !== 'main' && stopped(input.session_id, m.agent)))
|
|
169
|
-
return `${dir} in your session's scratchpad was made by ${agentName(m)}, another agent of your session, so ${t.why} can't delete it.\n`
|
|
170
|
-
+ `Ask ${m.agent === 'main' ? 'the main thread' : m.type || m.agent} whether it's done with it, or have the person delete it. Deleting single files in it is fine, `
|
|
171
|
-
+ `and so is a cache or build folder in it (${[...CACHES].join(', ')})${agentOf(input) === 'main' ? '. Once that subagent has finished, you may delete the folder' : ''}.`;
|
|
172
|
-
if (!m && !namedBy(input.session_id, n, agentOf(input)) && bigger(names.length > 1 || rest.length === 2 ? dir : p, UNTRACKED_MAX))
|
|
173
|
-
return `${dir} in your session's scratchpad holds more than ${UNTRACKED_MAX} files, and dibs can't tell which agent of your session made it (it's older than dibs's record), so ${t.why} can't delete it all.\n`
|
|
174
|
-
+ 'Ask the agents of your session whose it is, or have the person delete it. Deleting single files in it is fine.';
|
|
175
|
-
}
|
|
136
|
+
// A glob of only wildcards at the top (scratchpad/*, scratchpad/.*) is the whole scratchpad by another name.
|
|
137
|
+
if (rest.length === 2 && /^[*?.]+$/.test(rest[1])) return whole("your session's scratchpad");
|
|
138
|
+
// Anything under it is the session's own, whoever of the session made it and however
|
|
139
|
+
// old: 2e had to ask a teammate to delete 850 MB of browser profiles at 4.9 GB free (2026-11-04).
|
|
176
140
|
return null;
|
|
177
141
|
}
|
|
178
142
|
|
|
@@ -180,10 +144,9 @@ function ownDelete(p, t, input) {
|
|
|
180
144
|
// A program can make a scratchpad folder dibs doesn't see it write
|
|
181
145
|
// (xcodebuild -derivedDataPath scratchpad/dd made fix-app's 0.5 GB of derived
|
|
182
146
|
// data on 2026-10-18), so a folder that doesn't exist yet and is named
|
|
183
|
-
// anywhere in a command counts as made by whoever ran it.
|
|
184
|
-
// command named a folder dibs has no record of may delete it, whatever its size.
|
|
147
|
+
// anywhere in a command counts as made by whoever ran it.
|
|
185
148
|
function noteMakers(input, split, written) {
|
|
186
|
-
const made = new Set(),
|
|
149
|
+
const made = new Set(), gone = new Set();
|
|
187
150
|
const top = p => {
|
|
188
151
|
const at = inSession(real(p));
|
|
189
152
|
return at && at[1][0] === 'scratchpad' && at[1].length >= 2 && !GLOB.test(at[1][1]) && path.basename(at[0]) === input.session_id
|
|
@@ -198,12 +161,10 @@ function noteMakers(input, split, written) {
|
|
|
198
161
|
}
|
|
199
162
|
for (const p of namedPaths(input, split)) {
|
|
200
163
|
const f = top(p);
|
|
201
|
-
if (!f)
|
|
202
|
-
named.add(f[0]);
|
|
203
|
-
if (!fs.existsSync(f[1])) made.add(f[0]);
|
|
164
|
+
if (f && !fs.existsSync(f[1])) made.add(f[0]);
|
|
204
165
|
}
|
|
205
|
-
for (const n of gone)
|
|
206
|
-
if (!made.size && !
|
|
166
|
+
for (const n of gone) made.delete(n);
|
|
167
|
+
if (!made.size && !gone.size) return;
|
|
207
168
|
// Best effort: a full disk or a race costs only a record, never the call.
|
|
208
169
|
try {
|
|
209
170
|
const dir = makersDir(input.session_id);
|
|
@@ -217,19 +178,16 @@ function noteMakers(input, split, written) {
|
|
|
217
178
|
try { fs.writeFileSync(path.join(dir, encodeURIComponent(n)), JSON.stringify({ agent: agentOf(input), type: input.agent_type || null, at: Date.now() }), { flag: 'wx' }); fresh = true; }
|
|
218
179
|
catch {}
|
|
219
180
|
}
|
|
220
|
-
// name@agent: encodeURIComponent turns any @ into %40, so these never meet a folder's own record.
|
|
221
|
-
for (const n of named) fs.writeFileSync(path.join(dir, `${encodeURIComponent(n)}@${encodeURIComponent(agentOf(input))}`), '');
|
|
222
181
|
if (fresh) pruneMakers();
|
|
223
182
|
} catch {}
|
|
224
183
|
}
|
|
225
|
-
const namedBy = (session, name, agent) => fs.existsSync(path.join(makersDir(session), `${encodeURIComponent(name)}@${encodeURIComponent(agent)}`));
|
|
226
184
|
|
|
227
185
|
// Every word of a Bash command that could be a path in this session's folder,
|
|
228
186
|
// absolute: arguments anywhere (after dibs run's --, too), and --out=<path> values.
|
|
229
187
|
function namedPaths(input, split) {
|
|
230
188
|
const cmd = input.tool_name === 'Bash' && input.tool_input?.command;
|
|
231
189
|
if (typeof cmd !== 'string' || !(cmd.includes(input.session_id) || String(input.cwd).includes(input.session_id))) return [];
|
|
232
|
-
return namedIn(cmd, typeof input.cwd === 'string' ? input.cwd :
|
|
190
|
+
return namedIn(cmd, typeof input.cwd === 'string' ? slash(input.cwd) : cwdNow(), input.session_id, split, 0);
|
|
233
191
|
}
|
|
234
192
|
// A script handed to a shell with -c is read the same way, from the folder the shell starts in:
|
|
235
193
|
// dibs run xcode-build -- sh -c '... -derivedDataPath <scratchpad>/dd-test' made 177 MB on
|
|
@@ -274,7 +232,7 @@ function mkdirs(input, split) {
|
|
|
274
232
|
const segs = input.tool_name === 'Bash' && typeof input.tool_input?.command === 'string' && /\bmkdir\b/.test(input.tool_input.command) && split(input.tool_input.command);
|
|
275
233
|
if (!segs) return [];
|
|
276
234
|
const out = [];
|
|
277
|
-
for (const { name, args, dir } of commands(segs, typeof input.cwd === 'string' ? input.cwd :
|
|
235
|
+
for (const { name, args, dir } of commands(segs, typeof input.cwd === 'string' ? slash(input.cwd) : cwdNow()))
|
|
278
236
|
if (name === 'mkdir') for (const w of operands(args, new Set(['-m', '--mode']))) { const f = from(dir, w); if (f) out.push({ path: f.text, why: 'mkdir' }); }
|
|
279
237
|
return out;
|
|
280
238
|
}
|
|
@@ -321,7 +279,7 @@ function real(abs) {
|
|
|
321
279
|
let k = segs.findIndex(s => GLOB.test(s));
|
|
322
280
|
if (k < 0) k = segs.length;
|
|
323
281
|
for (let i = k; i > 1; i--) {
|
|
324
|
-
try { return [fs.realpathSync.native(segs.slice(0, i).join('/')), ...segs.slice(i)].join('/'); } catch {}
|
|
282
|
+
try { return [slash(fs.realpathSync.native(segs.slice(0, i).join('/'))), ...segs.slice(i)].join('/'); } catch {}
|
|
325
283
|
}
|
|
326
284
|
return abs;
|
|
327
285
|
}
|
|
@@ -377,12 +335,12 @@ function mainOf(dir) {
|
|
|
377
335
|
if (path.basename(path.dirname(gitdir)) !== 'worktrees') return null;
|
|
378
336
|
common = path.dirname(path.dirname(gitdir));
|
|
379
337
|
}
|
|
380
|
-
if (path.basename(common) === '.git') return fs.realpathSync(path.dirname(common));
|
|
338
|
+
if (path.basename(common) === '.git') return slash(fs.realpathSync(path.dirname(common)));
|
|
381
339
|
// A submodule's own worktrees: its checkout is core.worktree. A bare repo has none, so the repo itself stands in.
|
|
382
340
|
let config = '';
|
|
383
341
|
try { config = fs.readFileSync(path.join(common, 'config'), 'utf8'); } catch {}
|
|
384
342
|
const w = /^\s*worktree\s*=\s*(.+?)\s*$/m.exec(config);
|
|
385
|
-
return fs.realpathSync(w ? path.resolve(common, w[1]) : common);
|
|
343
|
+
return slash(fs.realpathSync(w ? path.resolve(common, w[1]) : common));
|
|
386
344
|
} catch { return null; }
|
|
387
345
|
}
|
|
388
346
|
|
|
@@ -405,10 +363,10 @@ export const fileKey = r => (isFiles(r) ? FILES + canon(r.slice(FILES.length)) :
|
|
|
405
363
|
|
|
406
364
|
// ' in another copy of this repo (wt-trust)' when lease l was taken from a
|
|
407
365
|
// different worktree of the repo cwd is in, else ''.
|
|
408
|
-
export function elsewhere(l, cwd =
|
|
366
|
+
export function elsewhere(l, cwd = cwdNow()) {
|
|
409
367
|
try {
|
|
410
368
|
if (typeof l?.cwd !== 'string') return '';
|
|
411
|
-
const mine = worktreeOf(real(path.resolve(cwd))), theirs = worktreeOf(real(l.cwd));
|
|
369
|
+
const mine = worktreeOf(real(path.resolve(cwd))), theirs = worktreeOf(real(path.resolve(l.cwd)));
|
|
412
370
|
if (!mine || !theirs || mine[1] !== theirs[1] || mine[0] === theirs[0]) return '';
|
|
413
371
|
return ` in another copy of this repo (${path.basename(theirs[0])})`;
|
|
414
372
|
} catch { return ''; }
|
|
@@ -457,7 +415,7 @@ function braces(r) {
|
|
|
457
415
|
return parts.flatMap(p => braces(r.slice(0, open) + p + r.slice(close + 1))).slice(0, BRACES);
|
|
458
416
|
}
|
|
459
417
|
|
|
460
|
-
export function fileRes(r, cwd =
|
|
418
|
+
export function fileRes(r, cwd = cwdNow()) {
|
|
461
419
|
if (!isFiles(r)) return r;
|
|
462
420
|
const p = r.slice(FILES.length).trim();
|
|
463
421
|
if (!p) return null;
|
|
@@ -465,7 +423,7 @@ export function fileRes(r, cwd = process.cwd()) {
|
|
|
465
423
|
}
|
|
466
424
|
|
|
467
425
|
// How a lease reads to a person: relative to the git root you're in, else from ~.
|
|
468
|
-
export function short(r, cwd =
|
|
426
|
+
export function short(r, cwd = cwdNow()) {
|
|
469
427
|
if (!isFiles(r)) return r;
|
|
470
428
|
const p = r.slice(FILES.length);
|
|
471
429
|
const root = gitRoot(cwd) && real(gitRoot(cwd));
|
|
@@ -504,7 +462,7 @@ function walk(a, i, b, j) {
|
|
|
504
462
|
// Unsure counts as yes. Both are keyed by the main worktree first (canon), so
|
|
505
463
|
// a lease an older dibs stored under a worktree's own path still counts.
|
|
506
464
|
export function overlap(a, b) {
|
|
507
|
-
const segs = p => folded(canon(p.replace(FILES, ''))).split('/').filter(Boolean);
|
|
465
|
+
const segs = p => folded(canon(slash(p.replace(FILES, '')))).split('/').filter(Boolean);
|
|
508
466
|
return walk(segs(a), 0, segs(b), 0);
|
|
509
467
|
}
|
|
510
468
|
|
|
@@ -536,7 +494,11 @@ let above = null;
|
|
|
536
494
|
function ancestors() {
|
|
537
495
|
if (above) return above;
|
|
538
496
|
const up = new Map();
|
|
539
|
-
|
|
497
|
+
// Windows has no ps: one CIM read of the table, about a second, once per hook.
|
|
498
|
+
const table = WIN
|
|
499
|
+
? execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', 'Get-CimInstance Win32_Process -Property ProcessId,ParentProcessId | ForEach-Object { "$($_.ProcessId) $($_.ParentProcessId)" }'], { encoding: 'utf8', timeout: 10000, windowsHide: true })
|
|
500
|
+
: execFileSync('ps', ['-A', '-o', 'pid=,ppid='], { encoding: 'utf8', timeout: 2000 });
|
|
501
|
+
for (const line of table.trim().split(/\r?\n/)) {
|
|
540
502
|
const [pid, ppid] = line.trim().split(/\s+/).map(Number);
|
|
541
503
|
up.set(pid, ppid);
|
|
542
504
|
}
|
|
@@ -1019,7 +981,7 @@ export function dibsCalls(cmd, split, cwd) {
|
|
|
1019
981
|
|
|
1020
982
|
function noteAgent(input, split) {
|
|
1021
983
|
if (input.tool_name !== 'Bash' || typeof input.session_id !== 'string') return;
|
|
1022
|
-
const calls = dibsCalls(input.tool_input?.command, split, typeof input.cwd === 'string' ? input.cwd :
|
|
984
|
+
const calls = dibsCalls(input.tool_input?.command, split, typeof input.cwd === 'string' ? slash(input.cwd) : cwdNow());
|
|
1023
985
|
if (!calls.length) return;
|
|
1024
986
|
// Only a nicety (naming the subagent): a full disk must not cost the lease check after it.
|
|
1025
987
|
try {
|
|
@@ -1080,7 +1042,7 @@ export const shellRes = rs => {
|
|
|
1080
1042
|
// The paths a tool call would write, absolute.
|
|
1081
1043
|
function targets(input, split, guesses = false) {
|
|
1082
1044
|
const ti = input.tool_input || {};
|
|
1083
|
-
const cwd = typeof input.cwd === 'string' ? input.cwd :
|
|
1045
|
+
const cwd = typeof input.cwd === 'string' ? slash(input.cwd) : cwdNow();
|
|
1084
1046
|
if (input.tool_name === 'Bash') return bashWrites(ti.command, split, cwd, guesses);
|
|
1085
1047
|
const p = ti.file_path ?? ti.notebook_path;
|
|
1086
1048
|
return typeof p === 'string' && p ? [{ path: path.resolve(cwd, expand(p)), why: input.tool_name }] : [];
|
|
@@ -1094,7 +1056,7 @@ export function fileGuard(input, split) {
|
|
|
1094
1056
|
noteAgent(input, split);
|
|
1095
1057
|
const live = leases();
|
|
1096
1058
|
if (!live.length) return null;
|
|
1097
|
-
const cwd = typeof input.cwd === 'string' ? input.cwd :
|
|
1059
|
+
const cwd = typeof input.cwd === 'string' ? slash(input.cwd) : cwdNow();
|
|
1098
1060
|
const t = Date.now();
|
|
1099
1061
|
for (const target of targets(input, split)) {
|
|
1100
1062
|
if (target.guess != null) continue;
|
package/src/guard.mjs
CHANGED
|
@@ -8,10 +8,14 @@ import fs from 'node:fs';
|
|
|
8
8
|
import os from 'node:os';
|
|
9
9
|
import path from 'node:path';
|
|
10
10
|
import { fileURLToPath } from 'node:url';
|
|
11
|
-
import { tmpGuard, fileGuard, resList
|
|
11
|
+
import { tmpGuard, fileGuard, resList } from './files.mjs';
|
|
12
12
|
|
|
13
13
|
const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
14
14
|
const HOOK_BIN = path.join(ROOT, 'bin', 'dibs-guard.mjs');
|
|
15
|
+
// Claude Code runs hooks and Bash commands through Git Bash on Windows, where a
|
|
16
|
+
// .mjs doesn't run by name: there node runs it, from a path written with /.
|
|
17
|
+
const WIN = process.platform === 'win32';
|
|
18
|
+
const viaNode = file => (WIN ? `node ${quote(file.replace(/\\/g, '/'))}` : quote(file));
|
|
15
19
|
// The same folder as config.mjs's HOME, worked out here because the hook loads no other module.
|
|
16
20
|
const DIBS_HOME = process.env.DIBS_HOME || path.join(os.homedir(), '.dibs');
|
|
17
21
|
const CONFIG = path.join(DIBS_HOME, 'config.json');
|
|
@@ -316,7 +320,8 @@ export function rulesFrom(guardCfg) {
|
|
|
316
320
|
return { ...RULES, ...(guardCfg?.rules || {}) };
|
|
317
321
|
}
|
|
318
322
|
|
|
319
|
-
|
|
323
|
+
// A ~ inside a word stays as typed (Windows short names: C:/Users/RUNNER~1); only a leading one expands.
|
|
324
|
+
const quote = s => (/^[\w@%+=:,./-][\w@%+=:,./~-]*$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
|
|
320
325
|
|
|
321
326
|
// What to do with a command: null to leave it alone, or the rewritten command
|
|
322
327
|
// and what was caught.
|
|
@@ -359,6 +364,8 @@ export function check(cmd, { rules = RULES, dibs = 'dibs' } = {}) {
|
|
|
359
364
|
// Where in dibs it broke and on what kind of call, never the command itself
|
|
360
365
|
// (it can hold secrets): enough to find the bug, as `dibs alerts` reports it.
|
|
361
366
|
function logError(e, input) {
|
|
367
|
+
// A full disk is no bug in dibs: the call goes through, and the board already says the disk is full.
|
|
368
|
+
if (e?.code === 'ENOSPC' || e?.code === 'EDQUOT') return;
|
|
362
369
|
const at = String(e?.stack || '').split('\n').find(l => l.includes('/src/'))?.match(/\/(src\/[\w.]+:\d+)/)?.[1];
|
|
363
370
|
const on = input?.hook_event_name ? ` [${input.hook_event_name}${input.tool_name ? ` ${input.tool_name}` : ''}]` : '';
|
|
364
371
|
try { fs.appendFileSync(LOG, `${new Date().toISOString()} ${String(e?.message || e).split('\n')[0]}${at ? ` at ${at}` : ''}${on}\n`); } catch {}
|
|
@@ -379,7 +386,7 @@ const AGENT_EVENT = input => ['Agent', 'Task'].includes(input?.tool_name) || ['S
|
|
|
379
386
|
function dibsCommand() {
|
|
380
387
|
for (const dir of (process.env.PATH || '').split(path.delimiter))
|
|
381
388
|
if (dir && fs.existsSync(path.join(dir, 'dibs'))) return 'dibs';
|
|
382
|
-
return
|
|
389
|
+
return viaNode(path.join(ROOT, 'bin', 'dibs.mjs'));
|
|
383
390
|
}
|
|
384
391
|
|
|
385
392
|
// Rewrite only where "allow" approves nothing the session wouldn't have run
|
|
@@ -460,10 +467,17 @@ function rearm(input) {
|
|
|
460
467
|
// The hook itself: Claude Code's JSON on stdin, a decision on stdout. Any
|
|
461
468
|
// failure prints nothing, which leaves the command to the normal permission flow.
|
|
462
469
|
export async function hook() {
|
|
463
|
-
let
|
|
470
|
+
let input;
|
|
471
|
+
try { input = JSON.parse(fs.readFileSync(0, 'utf8')); } catch (e) { return logError(e, null); }
|
|
472
|
+
const out = await decide(input);
|
|
473
|
+
if (out) process.stdout.write(JSON.stringify(out) + '\n');
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
// What the hook answers for one event, or null to say nothing. The resident
|
|
477
|
+
// guard (src/guardd.mjs) runs this too, in a fresh worker per call.
|
|
478
|
+
export async function decide(input) {
|
|
479
|
+
let out = null;
|
|
464
480
|
try {
|
|
465
|
-
input = JSON.parse(fs.readFileSync(0, 'utf8'));
|
|
466
|
-
subagentState(input);
|
|
467
481
|
if (AGENT_EVENT(input)) out = (await import('./agents.mjs')).agentHook(input, dibsConfig());
|
|
468
482
|
else if (!STOP_EVENT(input) && !START_EVENT(input)) out = respond(input, guardConfig(), dibsCommand());
|
|
469
483
|
} catch (e) { logError(e, input); }
|
|
@@ -474,7 +488,7 @@ export async function hook() {
|
|
|
474
488
|
else if (input?.hook_event_name === 'SubagentStop' && talked(input)) (await import('./talk.mjs')).finished(input);
|
|
475
489
|
} catch (e) { logError(e, input); }
|
|
476
490
|
try { if (!out) out = rearm(input); } catch (e) { logError(e, input); }
|
|
477
|
-
|
|
491
|
+
return out;
|
|
478
492
|
}
|
|
479
493
|
|
|
480
494
|
const isGuard = h => h?.type === 'command' && /dibs-guard\.mjs['"]?$|\bdibs(\.mjs)?['"]? guard['"]?$/.test(String(h.command || '').trim());
|
|
@@ -542,7 +556,7 @@ export function installed(file = SETTINGS) {
|
|
|
542
556
|
return ours(readSettings(file)).flatMap(g => g.hooks).find(isGuard) || null;
|
|
543
557
|
}
|
|
544
558
|
|
|
545
|
-
export function install(file = SETTINGS, command =
|
|
559
|
+
export function install(file = SETTINGS, command = viaNode(HOOK_BIN)) {
|
|
546
560
|
const s = readSettings(file);
|
|
547
561
|
const had = installed(file);
|
|
548
562
|
if (complete(s, command)) return `already installed in ${file}`;
|
|
@@ -566,6 +580,7 @@ const USAGE = `dibs guard: catch heavy commands an agent runs outside dibs, turn
|
|
|
566
580
|
dibs guard remove [--settings file] take it out again
|
|
567
581
|
dibs guard status [--settings file] [--json] is it installed (exit 1 if not; --json always exits 0)
|
|
568
582
|
dibs guard check "<command>" what the hook would do with a command
|
|
583
|
+
dibs guard serve answer the hook from one running process (dibs service install guard keeps it up)
|
|
569
584
|
The hook reads Claude Code's JSON on stdin: dibs guard < input.json`;
|
|
570
585
|
|
|
571
586
|
// What `dibs guard status --json` prints, for dibs web too.
|
|
@@ -587,6 +602,7 @@ export function guard(args) {
|
|
|
587
602
|
const verb = args[0];
|
|
588
603
|
try {
|
|
589
604
|
if (!verb) return process.stdin.isTTY ? reply(USAGE) : hook();
|
|
605
|
+
if (verb === 'serve') return import('./guardd.mjs').then(m => m.serveGuard());
|
|
590
606
|
if (verb === 'install') return reply(`dibs guard: ${install(file)}`);
|
|
591
607
|
if (verb === 'remove') { const r = remove(file); return r ? reply(`dibs guard: ${r}`) : reply(`dibs guard: not installed in ${file}`, 1); }
|
|
592
608
|
if (verb === 'status') {
|
package/src/guardd.mjs
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
// dibs guard serve: the resident guard. The Claude Code hook runs on every
|
|
2
|
+
// tool call, about 30,000 a day here, and starting Node for each was nearly
|
|
3
|
+
// all of its time (100 to 400 ms on a busy Mac, against 3 to 20 ms of the
|
|
4
|
+
// hook's own work). bin/dibs-guard.mjs is also a small sh script that sends
|
|
5
|
+
// the call down GUARD_SOCK when this is running, and starts Node as before
|
|
6
|
+
// when it isn't, or when it doesn't answer.
|
|
7
|
+
//
|
|
8
|
+
// Each call runs in a worker thread loaded before the call comes, with the
|
|
9
|
+
// hook's own environment and parent pid (src/guardw.mjs), and the worker ends
|
|
10
|
+
// with it, so a call here is the same as a call in its own Node.
|
|
11
|
+
//
|
|
12
|
+
// On the socket, an HTTP POST from the client (curl): its parent pid, its
|
|
13
|
+
// folder, its environment (env -0), an empty field, the hook's JSON, each
|
|
14
|
+
// ending in a NUL. Back: "ok", then the hook's answer on the next line if it
|
|
15
|
+
// has one. Anything but "ok" and the client runs the hook itself.
|
|
16
|
+
import fs from 'node:fs';
|
|
17
|
+
import http from 'node:http';
|
|
18
|
+
import path from 'node:path';
|
|
19
|
+
import { Worker } from 'node:worker_threads';
|
|
20
|
+
import { fileURLToPath } from 'node:url';
|
|
21
|
+
import { HOME } from './config.mjs';
|
|
22
|
+
import { singleInstance } from './proc.mjs';
|
|
23
|
+
import { log } from './util.mjs';
|
|
24
|
+
|
|
25
|
+
export const GUARD_SOCK = path.join(HOME, 'guard.sock');
|
|
26
|
+
const PIDFILE = path.join(HOME, 'guard.pid');
|
|
27
|
+
const WORKER = path.join(path.dirname(fileURLToPath(import.meta.url)), 'guardw.mjs');
|
|
28
|
+
// Workers kept loaded and waiting: calls come in bursts when several agents work
|
|
29
|
+
// at once, and one takes 20 to 45 ms to load on a busy Mac.
|
|
30
|
+
const READY = 2;
|
|
31
|
+
// A call that takes longer is answered with nothing (allow), as a failing hook
|
|
32
|
+
// is, inside the client's 2 s: the subagent ledger's lock gives up at 1 s. A
|
|
33
|
+
// client that gets no answer then starts Node, which must still fit in Claude
|
|
34
|
+
// Code's 5 s hook timeout.
|
|
35
|
+
const CALL_LIMIT = 1500;
|
|
36
|
+
// No hook input comes near this; a client sending more is cut off.
|
|
37
|
+
const MAX_FRAME = 8 * 1024 ** 2;
|
|
38
|
+
|
|
39
|
+
// The fields of a whole frame, or null while more is still to come.
|
|
40
|
+
export function frame(buf) {
|
|
41
|
+
const parts = buf.toString('utf8').split('\0');
|
|
42
|
+
const end = parts.indexOf('', 2); // the empty field after the environment
|
|
43
|
+
// Complete once the JSON after it has its own NUL: parts then ends with ''.
|
|
44
|
+
if (end < 0 || parts.length < end + 3) return null;
|
|
45
|
+
const env = {};
|
|
46
|
+
for (const kv of parts.slice(2, end)) { const i = kv.indexOf('='); if (i > 0) env[kv.slice(0, i)] = kv.slice(i + 1); }
|
|
47
|
+
return { ppid: Number(parts[0]) || null, cwd: parts[1], env, input: parts[end + 1] };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export async function serveGuard() {
|
|
51
|
+
await singleInstance(PIDFILE, 'a resident guard is already running here');
|
|
52
|
+
const ready = [], waiting = [];
|
|
53
|
+
const warm = () => {
|
|
54
|
+
const w = new Worker(WORKER, { execArgv: [] });
|
|
55
|
+
w.once('message', () => { const next = waiting.shift(); next ? next(w) : ready.push(w); });
|
|
56
|
+
w.once('error', e => log(`a guard worker failed to load: ${e.message}`));
|
|
57
|
+
};
|
|
58
|
+
const take = () => new Promise(r => { warm(); const w = ready.shift(); w ? r(w) : waiting.push(r); });
|
|
59
|
+
for (let i = 0; i < READY; i++) warm();
|
|
60
|
+
|
|
61
|
+
function call(f) {
|
|
62
|
+
let input;
|
|
63
|
+
try { input = JSON.parse(f.input); } catch { return null; } // the hook says nothing for input it can't read
|
|
64
|
+
return new Promise(resolve => {
|
|
65
|
+
let w = null, over = false;
|
|
66
|
+
const done = out => { if (over) return; over = true; clearTimeout(timer); w?.terminate(); resolve(out); };
|
|
67
|
+
const timer = setTimeout(() => { log(`a hook call took over ${CALL_LIMIT} ms and was let through: ${input?.hook_event_name} ${input?.tool_name || ''}`); done(null); }, CALL_LIMIT);
|
|
68
|
+
take().then(got => {
|
|
69
|
+
if (over) return got.terminate();
|
|
70
|
+
w = got;
|
|
71
|
+
w.once('message', m => done(m.out ?? null));
|
|
72
|
+
w.once('exit', () => done(null));
|
|
73
|
+
w.postMessage({ input, env: f.env, ppid: f.ppid });
|
|
74
|
+
});
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
try { fs.unlinkSync(GUARD_SOCK); } catch {}
|
|
79
|
+
// HTTP over the socket, because curl is the client every Mac and Linux box has
|
|
80
|
+
// that waits for an answer: macOS nc hangs up as soon as its input ends.
|
|
81
|
+
const server = http.createServer((req, res) => {
|
|
82
|
+
const chunks = [];
|
|
83
|
+
let size = 0;
|
|
84
|
+
req.on('data', d => { size += d.length; if (size > MAX_FRAME) req.destroy(); else chunks.push(d); });
|
|
85
|
+
req.on('end', async () => {
|
|
86
|
+
const f = frame(Buffer.concat(chunks));
|
|
87
|
+
const out = f ? await call(f) : null;
|
|
88
|
+
res.end(f ? `ok\n${out ? `${JSON.stringify(out)}\n` : ''}` : 'bad frame\n');
|
|
89
|
+
});
|
|
90
|
+
});
|
|
91
|
+
server.listen(GUARD_SOCK, () => {
|
|
92
|
+
fs.chmodSync(GUARD_SOCK, 0o600);
|
|
93
|
+
log(`answering the Claude Code hook on ${GUARD_SOCK}`);
|
|
94
|
+
});
|
|
95
|
+
const stop = () => { server.close(); try { fs.unlinkSync(GUARD_SOCK); } catch {} try { fs.rmSync(PIDFILE); } catch {} process.exit(0); };
|
|
96
|
+
process.on('SIGINT', stop); process.on('SIGTERM', stop);
|
|
97
|
+
}
|
package/src/guardw.mjs
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
// One hook call in the resident guard (src/guardd.mjs): a worker thread that
|
|
2
|
+
// loads the hook's modules before its call comes, answers that one call as
|
|
3
|
+
// the hook process would, and ends. A fresh worker per call keeps every call
|
|
4
|
+
// as fresh as its own Node process was: the modules keep caches (the pool's
|
|
5
|
+
// simulators, the processes above the hook) that are only right for one call.
|
|
6
|
+
import { parentPort } from 'node:worker_threads';
|
|
7
|
+
import { decide } from './guard.mjs';
|
|
8
|
+
import { setCaller } from './util.mjs';
|
|
9
|
+
|
|
10
|
+
parentPort.once('message', async ({ input, env, ppid }) => {
|
|
11
|
+
// The hook's own environment and parent, as the client saw them.
|
|
12
|
+
for (const k of Object.keys(process.env)) delete process.env[k];
|
|
13
|
+
Object.assign(process.env, env);
|
|
14
|
+
setCaller(ppid);
|
|
15
|
+
let out = null;
|
|
16
|
+
try { out = await decide(input); } catch {}
|
|
17
|
+
parentPort.postMessage({ out });
|
|
18
|
+
});
|
|
19
|
+
parentPort.postMessage({ ready: true });
|
package/src/later.mjs
CHANGED
|
@@ -24,7 +24,8 @@ import { short, takeAgent, talkKey } from './files.mjs';
|
|
|
24
24
|
import { noteAs } from './talk.mjs';
|
|
25
25
|
import { named, about, minutes } from './plain.mjs';
|
|
26
26
|
import { bold, dim, columns } from './style.mjs';
|
|
27
|
-
import {
|
|
27
|
+
import { underLock, commit } from './lock.mjs';
|
|
28
|
+
import { clock, deadline, die, dur, log, ms, now, say, sleep, fakeFull, LEAN } from './util.mjs';
|
|
28
29
|
|
|
29
30
|
const BIN = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'bin', 'dibs.mjs');
|
|
30
31
|
export const DIR = path.join(HOME, 'later');
|
|
@@ -41,8 +42,7 @@ const MAX_AHEAD = 7 * 864e5;
|
|
|
41
42
|
const TICK = 1000;
|
|
42
43
|
// Started this long after its time, a job says it ran late (the machine was asleep, or no runner was up).
|
|
43
44
|
const LATE = 60e3;
|
|
44
|
-
// Writes take milliseconds
|
|
45
|
-
const LOCK_STALE = 5000;
|
|
45
|
+
// Writes take milliseconds: a live holder past this is stuck on something else, and the caller hears so.
|
|
46
46
|
const LOCK_WAIT = 15e3;
|
|
47
47
|
// Finished jobs and their logs stay a week for dibs later list, up to KEEP_DONE of them.
|
|
48
48
|
const KEEP_FOR = 7 * 864e5;
|
|
@@ -50,7 +50,14 @@ const KEEP_DONE = 200;
|
|
|
50
50
|
// What a scheduled command gets from the scheduler's environment. TMPDIR, USER
|
|
51
51
|
// and SHELL too, since Xcode and many scripts break without them. Anything
|
|
52
52
|
// else (a token, say) only with --env, by name.
|
|
53
|
-
const ENV_KEEP = ['PATH', 'HOME', 'LANG', 'LC_ALL', 'USER', 'SHELL', 'TMPDIR']
|
|
53
|
+
const ENV_KEEP = ['PATH', 'HOME', 'LANG', 'LC_ALL', 'USER', 'SHELL', 'TMPDIR']
|
|
54
|
+
// Windows itself: without SystemRoot and the rest, PowerShell, cmd.exe and
|
|
55
|
+
// os.tmpdir() break or crawl. Without PSModuleAnalysisCachePath, where a
|
|
56
|
+
// machine set one, every PowerShell dibs starts rebuilds its module cache, and
|
|
57
|
+
// on a GitHub runner the scheduled run never got past its first (2026-11-03).
|
|
58
|
+
.concat(OS === 'windows' ? ['SystemRoot', 'SystemDrive', 'windir', 'ComSpec', 'PATHEXT', 'TEMP', 'TMP', 'USERPROFILE', 'USERNAME',
|
|
59
|
+
'HOMEDRIVE', 'HOMEPATH', 'APPDATA', 'LOCALAPPDATA', 'ProgramData', 'ProgramFiles', 'ProgramFiles(x86)', 'CommonProgramFiles',
|
|
60
|
+
'NUMBER_OF_PROCESSORS', 'PROCESSOR_ARCHITECTURE', 'OS', 'PSModulePath', 'PSModuleAnalysisCachePath'] : []);
|
|
54
61
|
// dibs's own settings reach the run from the runner (DIBS_HOME above all);
|
|
55
62
|
// these say who is calling, and the run sets its own.
|
|
56
63
|
const DIBS_WHO = new Set(['DIBS_AGENT', 'DIBS_AS', 'DIBS_REMOTE_JOB', 'DIBS_LEASE', 'DIBS_OWNER', 'DIBS_LATER_JOB']);
|
|
@@ -61,31 +68,17 @@ const notEnv = k => k.startsWith('DIBS_') || k.startsWith('CLAUDE_CODE_') || AGE
|
|
|
61
68
|
const ACTIVE = new Set(['scheduled', 'started']);
|
|
62
69
|
|
|
63
70
|
function locked(fn) {
|
|
64
|
-
|
|
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 > LOCK_WAIT) throw Object.assign(new Error(`${LOCK} stayed locked for ${LOCK_WAIT / 1000}s; remove it if no dibs is running. Nothing was changed.`), { exit: 75 });
|
|
71
|
-
sleepSync(5 + Math.random() * 10);
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
try {
|
|
71
|
+
const r = underLock(LOCK, h => {
|
|
75
72
|
const s = load();
|
|
76
73
|
const before = JSON.stringify(s);
|
|
77
74
|
reap(s);
|
|
78
75
|
const out = fn(s);
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
fakeFull('state');
|
|
82
|
-
fs.writeFileSync(`${FILE}.tmp`, JSON.stringify(s, null, 1), { mode: 0o600 });
|
|
83
|
-
fs.renameSync(`${FILE}.tmp`, FILE);
|
|
84
|
-
}
|
|
76
|
+
// --env values may be tokens: only this user reads the file.
|
|
77
|
+
if (JSON.stringify(s) !== before) commit(h, FILE, JSON.stringify(s, null, 1), { mode: 0o600, fake: () => fakeFull('state') });
|
|
85
78
|
return out;
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
|
|
79
|
+
}, { wait: LOCK_WAIT, files: [FILE] });
|
|
80
|
+
if (!r) throw Object.assign(new Error(`${LOCK} is held by a dibs that's still running, and stayed held for ${LOCK_WAIT / 1000}s. Nothing was changed: run the same command again.`), { exit: 75 });
|
|
81
|
+
return r.out;
|
|
89
82
|
}
|
|
90
83
|
|
|
91
84
|
function load() {
|
|
@@ -213,7 +206,9 @@ function start(j) {
|
|
|
213
206
|
if (!fs.existsSync(j.cwd)) return fail(`its folder ${j.cwd} is gone`);
|
|
214
207
|
let fd;
|
|
215
208
|
try {
|
|
216
|
-
|
|
209
|
+
// Each job's log is new here. On Windows an append handle has no plain write
|
|
210
|
+
// access, and Git Bash's programs (echo, printf) fail to write through it.
|
|
211
|
+
fd = fs.openSync(logOf(j.id), OS === 'windows' ? 'w' : 'a', 0o600);
|
|
217
212
|
fs.writeSync(fd, `dibs later ${j.id}: ${j.cmd.join(' ')} in ${j.cwd}, ${trigger(j)}, started ${new Date(j.fired).toISOString()}`
|
|
218
213
|
+ `${j.late ? `; ran late by ${dur(j.late)} (the machine was asleep or no runner was up)` : ''}\n`);
|
|
219
214
|
} catch (e) { return fail(`couldn't write its log: ${e.message}`); }
|