@dibssoftware/dibs 0.0.0-stage → 0.0.179
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +594 -0
- package/LICENSE +670 -0
- package/README.md +85 -2
- package/bin/dibs-guard.mjs +7 -0
- package/bin/dibs.mjs +548 -0
- package/docs/benchmarks.md +193 -0
- package/docs/files.md +30 -0
- package/docs/guard.md +91 -0
- package/docs/later.md +43 -0
- package/docs/machines.md +147 -0
- package/docs/questions.md +78 -0
- package/docs/reference.md +157 -0
- package/docs/relay.md +196 -0
- package/docs/releasing.md +27 -0
- package/docs/scheduling.md +163 -0
- package/docs/simulators.md +17 -0
- package/package.json +45 -4
- package/skills/dibs/SKILL.md +183 -0
- package/src/acquire.mjs +700 -0
- package/src/admin.mjs +145 -0
- package/src/agents.mjs +145 -0
- package/src/alerts.mjs +499 -0
- package/src/answers.mjs +65 -0
- package/src/board.mjs +202 -0
- package/src/broker.mjs +369 -0
- package/src/commands.mjs +810 -0
- package/src/config.mjs +324 -0
- package/src/connect.mjs +106 -0
- package/src/cool.mjs +160 -0
- package/src/diskwarn.mjs +154 -0
- package/src/events.mjs +96 -0
- package/src/files.mjs +1123 -0
- package/src/guard.mjs +613 -0
- package/src/history.mjs +247 -0
- package/src/hogs.mjs +227 -0
- package/src/later.mjs +487 -0
- package/src/measure.mjs +262 -0
- package/src/news.mjs +101 -0
- package/src/nodecheck.mjs +17 -0
- package/src/notes.mjs +171 -0
- package/src/notices.mjs +160 -0
- package/src/ondemand.mjs +572 -0
- package/src/overlap.mjs +151 -0
- package/src/override.mjs +360 -0
- package/src/owner.mjs +30 -0
- package/src/plain.mjs +470 -0
- package/src/platform.mjs +357 -0
- package/src/preempt.mjs +438 -0
- package/src/primer.mjs +89 -0
- package/src/proc.mjs +99 -0
- package/src/progress.mjs +187 -0
- package/src/qr.mjs +204 -0
- package/src/questions.mjs +389 -0
- package/src/quota.mjs +81 -0
- package/src/reads.mjs +54 -0
- package/src/relay.mjs +779 -0
- package/src/remote.mjs +584 -0
- package/src/reset.mjs +127 -0
- package/src/schedule.mjs +1020 -0
- package/src/scratch.mjs +61 -0
- package/src/serve.mjs +742 -0
- package/src/service.mjs +221 -0
- package/src/shard.mjs +59 -0
- package/src/simctl.mjs +42 -0
- package/src/simpool.mjs +258 -0
- package/src/state.mjs +201 -0
- package/src/stats.mjs +328 -0
- package/src/style.mjs +44 -0
- package/src/talk.mjs +702 -0
- package/src/thin.sh +130 -0
- package/src/trust.mjs +152 -0
- package/src/util.mjs +184 -0
- package/src/version.mjs +2 -0
- package/src/web.mjs +1119 -0
- package/src/worker.mjs +318 -0
package/src/guard.mjs
ADDED
|
@@ -0,0 +1,613 @@
|
|
|
1
|
+
// dibs guard: a Claude Code PreToolUse hook that catches heavy Bash commands
|
|
2
|
+
// run outside dibs, and either wraps them in `dibs run` or sends the agent back
|
|
3
|
+
// with the exact command to use. It reads the shell command, never runs it, and
|
|
4
|
+
// takes no lock. Anything it can't read, or any error, lets the command through
|
|
5
|
+
// unchanged: blocking legit work is worse than missing a build. It also turns
|
|
6
|
+
// away edits to paths another session holds a file lease on (src/files.mjs).
|
|
7
|
+
import fs from 'node:fs';
|
|
8
|
+
import os from 'node:os';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { fileURLToPath } from 'node:url';
|
|
11
|
+
import { tmpGuard, fileGuard, resList, subagentState } from './files.mjs';
|
|
12
|
+
|
|
13
|
+
const ROOT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
14
|
+
const HOOK_BIN = path.join(ROOT, 'bin', 'dibs-guard.mjs');
|
|
15
|
+
// The same folder as config.mjs's HOME, worked out here because the hook loads no other module.
|
|
16
|
+
const DIBS_HOME = process.env.DIBS_HOME || path.join(os.homedir(), '.dibs');
|
|
17
|
+
const CONFIG = path.join(DIBS_HOME, 'config.json');
|
|
18
|
+
const STATE = path.join(DIBS_HOME, 'state.json');
|
|
19
|
+
const LOG = path.join(DIBS_HOME, 'guard.log');
|
|
20
|
+
// Who has a message from the person waiting: { session_id: [agent ids] }, or
|
|
21
|
+
// no file at all. src/talk.mjs keeps it; the hook only reads it.
|
|
22
|
+
const INBOX = path.join(DIBS_HOME, 'inbox.json');
|
|
23
|
+
// dibs listen's list of who listens (src/talk.mjs), and the listeners already reminded about.
|
|
24
|
+
const LISTENERS = path.join(DIBS_HOME, 'listeners.json');
|
|
25
|
+
const REMINDED = path.join(DIBS_HOME, 'listen-reminded.json');
|
|
26
|
+
// Sessions remembered in REMINDED: enough for every session a machine runs in a day or two.
|
|
27
|
+
const REMIND_KEEP = 200;
|
|
28
|
+
// The threads themselves, which the hook only searches for a subagent's id.
|
|
29
|
+
const MESSAGES = path.join(DIBS_HOME, 'messages.json');
|
|
30
|
+
const SETTINGS = process.env.DIBS_CLAUDE_SETTINGS || path.join(os.homedir(), '.claude', 'settings.json');
|
|
31
|
+
|
|
32
|
+
// What counts as heavy: the command's first words, once env, npx, time, cd and
|
|
33
|
+
// friends are peeled off, and the resource it needs. A word may use * and the
|
|
34
|
+
// first is matched by its basename; $ means "and nothing after". Any argument in
|
|
35
|
+
// `unless` makes it a quick read, as does `reads` returning true for the
|
|
36
|
+
// arguments; `with` needs one of its arguments present.
|
|
37
|
+
// Add or switch these off in ~/.dibs/config.json under guard.rules.
|
|
38
|
+
// A command aimed at a pool simulator ($SIM, a dibs-pool-N name, or the udid of
|
|
39
|
+
// one) belongs to sim-own. Queueing it for the shared sim would wait on a
|
|
40
|
+
// device it never touches.
|
|
41
|
+
const POOL_REF = /\$\{?SIM(_NAME)?\b|\bdibs-pool-\d+/;
|
|
42
|
+
let udids = null;
|
|
43
|
+
function poolUdids() {
|
|
44
|
+
try { udids ??= (JSON.parse(fs.readFileSync(STATE, 'utf8')).pool || []).map(d => d.udid).filter(Boolean); } catch { udids = []; }
|
|
45
|
+
return udids;
|
|
46
|
+
}
|
|
47
|
+
const ownSim = argv => argv.some(a => POOL_REF.test(a) || poolUdids().some(u => a.includes(u)));
|
|
48
|
+
const sim = argv => (ownSim(argv) ? 'sim-own' : 'sim');
|
|
49
|
+
// simctl subcommands that need no simulator turn: reads, and managing devices
|
|
50
|
+
// that aren't running (create, delete, erase, which refuses a booted one, and
|
|
51
|
+
// runtimes). Queueing those behind the shared sim and its disk floor would stop
|
|
52
|
+
// an agent deleting simulators to free disk until disk is free. Some read or
|
|
53
|
+
// write by their arguments: `ui <device> appearance` reads, with a value it sets.
|
|
54
|
+
const SIMCTL_READS = new Set(['list', 'help', '--help', '-h', '--version', 'getenv', 'get_app_container', 'listapps', 'appinfo', 'pbpaste',
|
|
55
|
+
'create', 'delete', 'erase', 'runtime']);
|
|
56
|
+
function simctlRead(rest) {
|
|
57
|
+
const i = rest[0] === '--set' ? 2 : 0; // --set <path> picks a device set and comes first
|
|
58
|
+
const [sub, a, b, c] = rest.slice(i);
|
|
59
|
+
if (SIMCTL_READS.has(sub)) return true;
|
|
60
|
+
if (sub === 'ui') return c == null;
|
|
61
|
+
if (sub === 'status_bar') return b === 'list';
|
|
62
|
+
if (sub === 'io') return b === 'enumerate';
|
|
63
|
+
if (sub === 'bootstatus') return !rest.includes('-b'); // -b boots it first
|
|
64
|
+
return false;
|
|
65
|
+
}
|
|
66
|
+
// A simulator named by its udid alone (-destination id=<udid>) is a simulator
|
|
67
|
+
// too. Real devices' ids aren't shaped 8-4-4-4-12.
|
|
68
|
+
const SIM_ID = /(^|,)id=[0-9A-F]{8}-([0-9A-F]{4}-){3}[0-9A-F]{12}\b/i;
|
|
69
|
+
const simTest = argv => argv.some(a => a === 'test' || a === 'test-without-building') && (ownSim(argv) || argv.some(a => /Simulator/.test(a) || SIM_ID.test(a)));
|
|
70
|
+
const RULES = {
|
|
71
|
+
xcodebuild: { match: 'xcodebuild', res: argv => (simTest(argv) ? `${sim(argv)},xcode-build` : 'xcode-build'),
|
|
72
|
+
unless: ['-version', '-showsdks', '-list', '-showBuildSettings', '-showdestinations', '-showTestPlans', '-help', '-usage',
|
|
73
|
+
'-license', '-checkFirstLaunchStatus', '-runFirstLaunch', '-find-executable', '-find-library', '-showComponent'] },
|
|
74
|
+
simctl: { match: 'simctl', res: sim, reads: simctlRead },
|
|
75
|
+
'swift-test': { match: 'swift test', res: 'test', unless: ['--help', '-h', '--list-tests'] },
|
|
76
|
+
playwright: { match: ['playwright test', 'pnpm playwright test', 'yarn playwright test'], res: 'playwright', unless: ['--help', '-h', '--list'] },
|
|
77
|
+
vitest: { match: ['vitest', 'pnpm vitest', 'yarn vitest'], res: 'test', unless: ['--version', '-v', '--help', '-h', 'list', 'init'] },
|
|
78
|
+
jest: { match: ['jest', 'pnpm jest', 'yarn jest'], res: 'test', unless: ['--version', '-v', '--help', '-h', '--listTests', '--showConfig'] },
|
|
79
|
+
'npm-test': { match: ['npm test', 'npm t', 'npm run test*', 'npm run-script test*', 'pnpm test', 'pnpm t', 'pnpm run test*',
|
|
80
|
+
'yarn test', 'yarn run test*', 'bun test', 'bun run test*'], res: 'test' },
|
|
81
|
+
'node-test': { match: 'node', with: ['--test'], res: 'test' },
|
|
82
|
+
// A type check of a big app takes 1.5 GB: on 2026-10-22 six at once, outside
|
|
83
|
+
// dibs, put 9 GB into swap and took free disk to 1.4 GB. Not --watch, which
|
|
84
|
+
// never ends, and not the quick ones.
|
|
85
|
+
tsc: { match: ['tsc', 'vue-tsc', 'npm run typecheck*', 'npm run type-check*', 'pnpm typecheck*', 'pnpm run typecheck*', 'pnpm type-check*',
|
|
86
|
+
'yarn typecheck*', 'yarn run typecheck*', 'bun run typecheck*'], res: 'test',
|
|
87
|
+
unless: ['--version', '-v', '--help', '-h', '--init', '--showConfig', '--watch', '-w', '--listFiles', '--listFilesOnly', '--all'] },
|
|
88
|
+
wrangler: { match: ['wrangler deploy', 'wrangler publish', 'wrangler pages deploy', 'wrangler versions deploy'], res: 'deploy', unless: ['--help', '-h', '--dry-run'] },
|
|
89
|
+
vercel: { match: ['vercel deploy', 'vercel --prod', 'vercel --yes', 'vercel -y', 'vercel $'], res: 'deploy', unless: ['--version', '-v', '--help', '-h'] },
|
|
90
|
+
'deploy-script': { match: ['ship*.sh', 'deploy*.sh', 'npm run deploy*', 'pnpm run deploy*', 'yarn deploy', 'yarn run deploy*', 'bun run deploy*'], res: 'deploy' },
|
|
91
|
+
};
|
|
92
|
+
|
|
93
|
+
// Words that come before the command and stay before dibs.
|
|
94
|
+
const KEYWORDS = new Set(['then', 'do', 'else', 'elif', 'if', 'while', 'until', '!', 'time', 'command', 'exec']);
|
|
95
|
+
const ASSIGN = /^[A-Za-z_][A-Za-z0-9_]*=/;
|
|
96
|
+
// DIBS_GUARD=off in front of a command, as a real assignment: in a quoted
|
|
97
|
+
// message or a file name it's only words.
|
|
98
|
+
const OFF = /^DIBS_GUARD=(0|off|false|no)$/;
|
|
99
|
+
|
|
100
|
+
// Commands that run another command: dibs goes in front of them, and the
|
|
101
|
+
// command they run is what gets matched. Each returns the index of that
|
|
102
|
+
// command, or null when the word isn't acting as a wrapper here.
|
|
103
|
+
const flags = (words, j, takesValue = []) => {
|
|
104
|
+
while (words[j]?.startsWith('-')) j += takesValue.includes(words[j]) ? 2 : 1;
|
|
105
|
+
return j;
|
|
106
|
+
};
|
|
107
|
+
const runner = (words, i) => { const j = flags(words, i + 1, ['-p', '--package']); return words[j] === '--' ? j + 1 : j; };
|
|
108
|
+
const PREFIX = {
|
|
109
|
+
env: (w, i) => { let j = flags(w, i + 1, ['-u', '--unset', '-C', '--chdir']); while (ASSIGN.test(w[j] || '')) j++; return j; },
|
|
110
|
+
nice: (w, i) => flags(w, i + 1, ['-n']),
|
|
111
|
+
caffeinate: (w, i) => flags(w, i + 1, ['-t', '-w']),
|
|
112
|
+
timeout: (w, i) => flags(w, i + 1, ['-s', '-k', '--signal', '--kill-after']) + 1,
|
|
113
|
+
gtimeout: (w, i) => PREFIX.timeout(w, i),
|
|
114
|
+
nohup: (w, i) => i + 1,
|
|
115
|
+
time: (w, i) => flags(w, i + 1, ['-o']), // /usr/bin/time; the shell's own time is a keyword
|
|
116
|
+
sudo: (w, i) => flags(w, i + 1, ['-u', '-g', '-C', '-D', '-h', '-p', '-U', '-r', '-t', '-T']),
|
|
117
|
+
xcrun: (w, i) => {
|
|
118
|
+
let j = i + 1;
|
|
119
|
+
while (['-sdk', '--sdk', '-toolchain', '--toolchain'].includes(w[j])) j += 2; // not --find: xcrun --find xcodebuild is a lookup
|
|
120
|
+
return ['xcodebuild', 'simctl'].includes(w[j]) ? j : null;
|
|
121
|
+
},
|
|
122
|
+
npx: runner,
|
|
123
|
+
bunx: runner,
|
|
124
|
+
bun: (w, i) => (w[i + 1] === 'x' ? runner(w, i + 1) : null),
|
|
125
|
+
npm: (w, i) => (w[i + 1] === 'exec' ? runner(w, i + 1) : null),
|
|
126
|
+
pnpm: (w, i) => (['exec', 'dlx'].includes(w[i + 1]) ? runner(w, i + 1) : null),
|
|
127
|
+
yarn: (w, i) => (['exec', 'dlx'].includes(w[i + 1]) ? runner(w, i + 1) : null),
|
|
128
|
+
// bash -x deploy.sh runs the script; -c and -s run text we can't see as a command.
|
|
129
|
+
bash: (w, i) => {
|
|
130
|
+
const j = flags(w, i + 1, ['-o', '+o', '-O', '+O']);
|
|
131
|
+
return w[j] && !w.slice(i + 1, j).some(f => /^-[a-zA-Z]*[cs]/.test(f)) ? j : null;
|
|
132
|
+
},
|
|
133
|
+
sh: (w, i) => PREFIX.bash(w, i),
|
|
134
|
+
zsh: (w, i) => PREFIX.bash(w, i),
|
|
135
|
+
};
|
|
136
|
+
// Package managers' own flags before the script name (npm --prefix web test).
|
|
137
|
+
const PM = new Set(['npm', 'pnpm', 'yarn', 'bun']);
|
|
138
|
+
const PM_VALUE = ['--prefix', '-C', '--cwd', '--dir', '--filter', '-F', '-w', '--workspace'];
|
|
139
|
+
|
|
140
|
+
const base = s => s.slice(s.lastIndexOf('/') + 1);
|
|
141
|
+
|
|
142
|
+
// The shell command split into simple commands, each a list of words with
|
|
143
|
+
// where they start. Quotes are removed; $(...), backticks and $VARS mark a word
|
|
144
|
+
// opaque; redirect targets are marked; heredoc bodies are skipped. Each list
|
|
145
|
+
// also says how many ( ) subshells it's in (depth), so a cd inside one ends
|
|
146
|
+
// with it, and whether its input is piped from the one before (pipe). Null when
|
|
147
|
+
// it can't be read (an open quote, an unterminated heredoc).
|
|
148
|
+
export function split(src) {
|
|
149
|
+
const segs = [], docs = [];
|
|
150
|
+
let seg = [], w = null, redir = false, depth = 0, pipe = false;
|
|
151
|
+
const word = i => (w ||= { text: '', start: i, quoted: false, opaque: false });
|
|
152
|
+
const end = () => {
|
|
153
|
+
if (!w) return;
|
|
154
|
+
// A group's brace ends the simple command before it. The word is dropped
|
|
155
|
+
// before cutting: cut() ends the current word first, and ending this one
|
|
156
|
+
// again called cut() again, without end (every { ...; } overflowed the stack
|
|
157
|
+
// until 0.0.178, and the hook let those commands through unguarded).
|
|
158
|
+
if (!w.quoted && (w.text === '{' || w.text === '}')) { w = null; cut(); return; }
|
|
159
|
+
w.redir = redir; redir = false;
|
|
160
|
+
seg.push(w); w = null;
|
|
161
|
+
};
|
|
162
|
+
const cut = () => { w && end(); if (seg.length) { segs.push(Object.assign(seg, { depth, pipe })); pipe = false; } seg = []; w = null; };
|
|
163
|
+
for (let i = 0; i < src.length; i++) {
|
|
164
|
+
const c = src[i], d = src[i + 1];
|
|
165
|
+
if (c === ' ' || c === '\t') end();
|
|
166
|
+
else if (c === '\n') {
|
|
167
|
+
cut();
|
|
168
|
+
if (docs.length) { i = bodies(src, i + 1, docs) - 1; if (i < 0) return null; docs.length = 0; }
|
|
169
|
+
}
|
|
170
|
+
else if (c === '#' && !w) { while (i + 1 < src.length && src[i + 1] !== '\n') i++; }
|
|
171
|
+
else if (c === '\\') { if (d !== '\n') { word(i).text += d ?? ''; w.quoted = true; } i++; }
|
|
172
|
+
else if (c === "'") {
|
|
173
|
+
const j = src.indexOf("'", i + 1);
|
|
174
|
+
if (j < 0) return null;
|
|
175
|
+
word(i).text += src.slice(i + 1, j); w.quoted = true; i = j;
|
|
176
|
+
}
|
|
177
|
+
else if (c === '"') {
|
|
178
|
+
word(i).quoted = true;
|
|
179
|
+
let j = i + 1;
|
|
180
|
+
for (; src[j] !== '"'; j++) {
|
|
181
|
+
if (j >= src.length) return null;
|
|
182
|
+
if (src[j] === '\\') w.text += src[++j];
|
|
183
|
+
else if (src[j] === '`' || (src[j] === '$' && src[j + 1] === '(')) {
|
|
184
|
+
const k = src[j] === '`' ? src.indexOf('`', j + 1) : close(src, j + 1);
|
|
185
|
+
if (k < 0) return null;
|
|
186
|
+
w.opaque = true; w.text += src.slice(j, k + 1); j = k;
|
|
187
|
+
}
|
|
188
|
+
else { if (src[j] === '$') w.opaque = true; w.text += src[j]; }
|
|
189
|
+
}
|
|
190
|
+
i = j;
|
|
191
|
+
}
|
|
192
|
+
else if (c === '`' || (c === '$' && d === '(') || ((c === '<' || c === '>') && d === '(')) {
|
|
193
|
+
const k = c === '`' ? src.indexOf('`', i + 1) : close(src, i + 1);
|
|
194
|
+
if (k < 0) return null;
|
|
195
|
+
word(i).opaque = true; w.text += src.slice(i, k + 1); i = k;
|
|
196
|
+
}
|
|
197
|
+
else if (c === '$') { word(i).opaque = true; w.text += c; }
|
|
198
|
+
else if (c === '(' || c === ')' || c === ';') { cut(); depth = Math.max(0, depth + (c === '(') - (c === ')')); }
|
|
199
|
+
else if (c === '|') { cut(); if (d === '|') i++; else { pipe = true; if (d === '&') i++; } }
|
|
200
|
+
else if (c === '&' && d !== '>') { cut(); if (d === '&') i++; }
|
|
201
|
+
else if (c === '<' || c === '>' || c === '&') {
|
|
202
|
+
if (w && /^\d+$/.test(w.text) && !w.quoted) w = null; // the fd in 2>&1
|
|
203
|
+
else end();
|
|
204
|
+
if (c === '<' && d === '<' && src[i + 2] !== '<') {
|
|
205
|
+
i += 2;
|
|
206
|
+
const dash = src[i] === '-';
|
|
207
|
+
if (dash) i++;
|
|
208
|
+
while (src[i] === ' ' || src[i] === '\t') i++;
|
|
209
|
+
let delim = '';
|
|
210
|
+
for (; i < src.length && !/[\s;&|<>()]/.test(src[i]); i++) if (!`'"\\`.includes(src[i])) delim += src[i];
|
|
211
|
+
i--;
|
|
212
|
+
docs.push({ delim, dash });
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
while ('<>&|'.includes(src[i + 1]) && src[i + 1] !== undefined) i++;
|
|
216
|
+
redir = true;
|
|
217
|
+
}
|
|
218
|
+
else word(i).text += c;
|
|
219
|
+
}
|
|
220
|
+
if (docs.length) return null;
|
|
221
|
+
cut();
|
|
222
|
+
return segs;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
// Index of the ")" closing the "(" at i, or -1.
|
|
226
|
+
function close(src, i) {
|
|
227
|
+
for (let depth = 0; i < src.length; i++) {
|
|
228
|
+
const c = src[i];
|
|
229
|
+
if (c === '\\') i++;
|
|
230
|
+
else if (c === "'") { i = src.indexOf("'", i + 1); if (i < 0) return -1; }
|
|
231
|
+
else if (c === '(') depth++;
|
|
232
|
+
else if (c === ')' && --depth === 0) return i;
|
|
233
|
+
}
|
|
234
|
+
return -1;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// Where the line after the last heredoc body starts, or -1 if one never ends.
|
|
238
|
+
function bodies(src, pos, docs) {
|
|
239
|
+
for (const doc of docs) {
|
|
240
|
+
for (;;) {
|
|
241
|
+
if (pos > src.length) return -1;
|
|
242
|
+
let nl = src.indexOf('\n', pos);
|
|
243
|
+
if (nl < 0) nl = src.length;
|
|
244
|
+
const line = src.slice(pos, nl);
|
|
245
|
+
pos = nl + 1;
|
|
246
|
+
if ((doc.dash ? line.replace(/^\t+/, '') : line) === doc.delim) break;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return pos;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// One simple command: where dibs would go, and the words of what it runs.
|
|
253
|
+
// Null when it starts with something opaque or a form we don't follow.
|
|
254
|
+
function peel(seg) {
|
|
255
|
+
const words = seg.filter(w => !w.redir);
|
|
256
|
+
const t = words.map(w => w.text);
|
|
257
|
+
let i = 0, at = null;
|
|
258
|
+
for (;;) {
|
|
259
|
+
const w = words[i];
|
|
260
|
+
if (!w || w.opaque || (OFF.test(w.text) && at === null)) return null;
|
|
261
|
+
if (!w.quoted && KEYWORDS.has(w.text) && at === null) {
|
|
262
|
+
i++;
|
|
263
|
+
if (w.text === 'time') i = flags(t, i);
|
|
264
|
+
if (w.text === 'command' && t[i]?.startsWith('-')) return null; // command -v is a lookup
|
|
265
|
+
continue;
|
|
266
|
+
}
|
|
267
|
+
if (ASSIGN.test(w.text) && at === null) { i++; continue; }
|
|
268
|
+
at ??= w.start;
|
|
269
|
+
const next = PREFIX[w.quoted ? '' : base(w.text)]?.(t, i);
|
|
270
|
+
if (next == null) break;
|
|
271
|
+
// env DIBS_GUARD=off xcodebuild switches it off too
|
|
272
|
+
if (t.slice(i, next).some(a => OFF.test(a))) return null;
|
|
273
|
+
i = next;
|
|
274
|
+
}
|
|
275
|
+
let argv = t.slice(i);
|
|
276
|
+
if (PM.has(base(argv[0]))) {
|
|
277
|
+
argv = [argv[0], ...argv.slice(flags(argv, 1, PM_VALUE))];
|
|
278
|
+
if (argv[1] === 'workspace') argv = [argv[0], ...argv.slice(3)]; // yarn workspace web test
|
|
279
|
+
}
|
|
280
|
+
return { at, argv };
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const globs = new Map();
|
|
284
|
+
function glob(p) {
|
|
285
|
+
if (!globs.has(p)) globs.set(p, new RegExp(`^${p.split('*').map(s => s.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*')}$`));
|
|
286
|
+
return globs.get(p);
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// The arguments after a rule's words, or null if it doesn't match.
|
|
290
|
+
function after(pattern, argv) {
|
|
291
|
+
const pat = pattern.trim().split(/\s+/);
|
|
292
|
+
for (let k = 0; k < pat.length; k++) {
|
|
293
|
+
if (pat[k] === '$') return argv.length === k ? [] : null;
|
|
294
|
+
const word = k === 0 ? base(argv[0]) : argv[k];
|
|
295
|
+
if (word === undefined || !glob(pat[k]).test(word)) return null;
|
|
296
|
+
}
|
|
297
|
+
return argv.slice(pat.length);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// The resource a command needs, or null.
|
|
301
|
+
function resourceFor(argv, rules) {
|
|
302
|
+
for (const rule of Object.values(rules)) {
|
|
303
|
+
if (!rule || !rule.res) continue;
|
|
304
|
+
const rest = [].concat(rule.match).map(p => after(p, argv)).find(Boolean);
|
|
305
|
+
if (!rest) continue;
|
|
306
|
+
if (rule.unless?.some(u => rest.includes(u)) || rule.reads?.(rest)) continue;
|
|
307
|
+
if (rule.with && !rule.with.some(a => argv.includes(a))) continue;
|
|
308
|
+
return typeof rule.res === 'function' ? rule.res(argv) : String(rule.res);
|
|
309
|
+
}
|
|
310
|
+
return null;
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
// The rules after ~/.dibs/config.json's guard.rules: a name set to false
|
|
314
|
+
// switches a built-in off, anything else adds or replaces one.
|
|
315
|
+
export function rulesFrom(guardCfg) {
|
|
316
|
+
return { ...RULES, ...(guardCfg?.rules || {}) };
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const quote = s => (/^[\w@%+=:,./-]+$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
|
|
320
|
+
|
|
321
|
+
// What to do with a command: null to leave it alone, or the rewritten command
|
|
322
|
+
// and what was caught.
|
|
323
|
+
export function check(cmd, { rules = RULES, dibs = 'dibs' } = {}) {
|
|
324
|
+
if (typeof cmd !== 'string') return null;
|
|
325
|
+
const segs = split(cmd);
|
|
326
|
+
if (!segs) return null;
|
|
327
|
+
// dibs calls themselves are left alone, and what a `dibs hold` on this line
|
|
328
|
+
// takes covers the commands after it. Anything else heavy on the line, before
|
|
329
|
+
// or after a dibs call, still needs its turn.
|
|
330
|
+
const held = new Set();
|
|
331
|
+
const hits = [];
|
|
332
|
+
for (const c of segs.map(peel).filter(Boolean)) {
|
|
333
|
+
if (c.argv[0] === 'export' && c.argv.some(a => OFF.test(a))) break; // export DIBS_GUARD=off: the rest of the line
|
|
334
|
+
if (['dibs', 'dibs.mjs', 'dibs-guard.mjs'].includes(base(c.argv[0] || ''))) {
|
|
335
|
+
if (c.argv[1] === 'hold') for (const r of c.argv.slice(2).filter(a => !a.startsWith('-'))) resList(r).forEach(x => held.add(x));
|
|
336
|
+
continue;
|
|
337
|
+
}
|
|
338
|
+
const res = resourceFor(c.argv, rules);
|
|
339
|
+
if (res && !res.split(',').every(r => held.has(r))) hits.push({ at: c.at, res, what: c.argv.slice(0, 3).join(' ') });
|
|
340
|
+
}
|
|
341
|
+
if (!hits.length) return null;
|
|
342
|
+
// $SIM is only set inside the run, so a command that reads it goes to sh -c
|
|
343
|
+
// whole, under one lease for everything it needs.
|
|
344
|
+
if (/\$\{?SIM(_NAME)?\b/.test(cmd)) {
|
|
345
|
+
const res = [...new Set(hits.flatMap(h => h.res.split(',')))].join(',');
|
|
346
|
+
const why = `guard: ${hits[0].what}`.replace(/[^\w .:/=@,+-]/g, '').slice(0, 50).trim();
|
|
347
|
+
return { command: `${dibs} run ${res} -m ${quote(why)} -- sh -c ${quote(cmd)}`, hits };
|
|
348
|
+
}
|
|
349
|
+
let out = cmd;
|
|
350
|
+
for (const h of [...hits].sort((a, b) => b.at - a.at)) {
|
|
351
|
+
const why = `guard: ${h.what}`.replace(/[^\w .:/=@,+-]/g, '').slice(0, 50).trim();
|
|
352
|
+
out = `${out.slice(0, h.at)}${dibs} run ${h.res} -m ${quote(why)} -- ${out.slice(h.at)}`;
|
|
353
|
+
}
|
|
354
|
+
return { command: out, hits };
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
// The hook never stops a session over its own failure, but leaves one line
|
|
358
|
+
// here so the failure isn't invisible. Writing it may fail too; nothing to do then.
|
|
359
|
+
// Where in dibs it broke and on what kind of call, never the command itself
|
|
360
|
+
// (it can hold secrets): enough to find the bug, as `dibs alerts` reports it.
|
|
361
|
+
function logError(e, input) {
|
|
362
|
+
const at = String(e?.stack || '').split('\n').find(l => l.includes('/src/'))?.match(/\/(src\/[\w.]+:\d+)/)?.[1];
|
|
363
|
+
const on = input?.hook_event_name ? ` [${input.hook_event_name}${input.tool_name ? ` ${input.tool_name}` : ''}]` : '';
|
|
364
|
+
try { fs.appendFileSync(LOG, `${new Date().toISOString()} ${String(e?.message || e).split('\n')[0]}${at ? ` at ${at}` : ''}${on}\n`); } catch {}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
function dibsConfig() {
|
|
368
|
+
try { return JSON.parse(fs.readFileSync(CONFIG, 'utf8')); }
|
|
369
|
+
catch (e) { if (e.code !== 'ENOENT') logError(`${CONFIG}: ${e.message}`); return {}; }
|
|
370
|
+
}
|
|
371
|
+
const guardConfig = () => dibsConfig().guard ?? {};
|
|
372
|
+
|
|
373
|
+
// Subagent spawns, starts and stops go to the subagent limit (src/agents.mjs),
|
|
374
|
+
// loaded only for those: a Bash call still pays for this module alone.
|
|
375
|
+
const AGENT_EVENT = input => ['Agent', 'Task'].includes(input?.tool_name) || ['SubagentStart', 'SubagentStop'].includes(input?.hook_event_name);
|
|
376
|
+
|
|
377
|
+
// `dibs` when it's on PATH, so the rewritten command reads the way agents
|
|
378
|
+
// write it; otherwise this copy's full path.
|
|
379
|
+
function dibsCommand() {
|
|
380
|
+
for (const dir of (process.env.PATH || '').split(path.delimiter))
|
|
381
|
+
if (dir && fs.existsSync(path.join(dir, 'dibs'))) return 'dibs';
|
|
382
|
+
return quote(path.join(ROOT, 'bin', 'dibs.mjs'));
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// Rewrite only where "allow" approves nothing the session wouldn't have run
|
|
386
|
+
// anyway (bypassPermissions), unless guard.rewrite says always or never.
|
|
387
|
+
// Everywhere else, deny with the exact command, so the agent's retry goes
|
|
388
|
+
// through the normal permission checks.
|
|
389
|
+
// "guard": false in config.json (or guard.commands false) switches off only
|
|
390
|
+
// the heavy-command half; file leases stay enforced unless guard.files is false.
|
|
391
|
+
export function respond(input, guardCfg = {}, dibs = 'dibs') {
|
|
392
|
+
// Another session's file lease (src/files.mjs) turns a write away before anything else.
|
|
393
|
+
// So does a delete in another session's temp folder, whatever the config says: it's the person's rule.
|
|
394
|
+
const leased = tmpGuard(input, split) || (guardCfg?.files === false ? null : fileGuard(input, split));
|
|
395
|
+
if (leased || input?.tool_name !== 'Bash' || guardCfg === false || guardCfg?.commands === false) return leased;
|
|
396
|
+
const ti = input.tool_input || {};
|
|
397
|
+
const plan = check(ti.command, { rules: rulesFrom(guardCfg), dibs });
|
|
398
|
+
if (!plan) return null;
|
|
399
|
+
const mode = guardCfg.rewrite || 'bypass';
|
|
400
|
+
const what = [...new Set(plan.hits.map(h => h.what.split(' ')[0]))].join(', ');
|
|
401
|
+
if (mode === 'always' || (mode === 'bypass' && input.permission_mode === 'bypassPermissions')) {
|
|
402
|
+
return { hookSpecificOutput: {
|
|
403
|
+
hookEventName: 'PreToolUse',
|
|
404
|
+
permissionDecision: 'allow',
|
|
405
|
+
permissionDecisionReason: `dibs guard wrapped ${what} in dibs run`,
|
|
406
|
+
updatedInput: { ...ti, command: plan.command },
|
|
407
|
+
additionalContext: `dibs guard ran this through dibs because ${what} wasn't wrapped: ${plan.command}\n` +
|
|
408
|
+
'Wrap builds, simulator use, test suites and deploys in dibs run yourself. If this call reaches its timeout while waiting in the queue, Claude Code moves it to the background and tells you when it ends: don\'t run it again.',
|
|
409
|
+
} };
|
|
410
|
+
}
|
|
411
|
+
return { hookSpecificOutput: {
|
|
412
|
+
hookEventName: 'PreToolUse',
|
|
413
|
+
permissionDecision: 'deny',
|
|
414
|
+
permissionDecisionReason: `dibs guard: ${what} has to take its turn through dibs, or it collides with other agents. Run this instead:\n ${plan.command}\n` +
|
|
415
|
+
'If it really is a quick read that builds, boots, tests and deploys nothing, put DIBS_GUARD=off in front of it.',
|
|
416
|
+
} };
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
const STOP_EVENT = input => ['Stop', 'SubagentStop'].includes(input?.hook_event_name);
|
|
420
|
+
const START_EVENT = input => ['SessionStart', 'SubagentStart'].includes(input?.hook_event_name);
|
|
421
|
+
|
|
422
|
+
// Whether the person has a message waiting for the agent making this call
|
|
423
|
+
// (src/talk.mjs). With none queued anywhere the file doesn't exist.
|
|
424
|
+
function queuedFor(input) {
|
|
425
|
+
if (typeof input?.session_id !== 'string' || input.hook_event_name === 'SubagentStart') return false;
|
|
426
|
+
try { return (JSON.parse(fs.readFileSync(INBOX, 'utf8'))[input.session_id] || []).includes(input.agent_id || 'main'); }
|
|
427
|
+
catch { return false; }
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
// Whether a stopping subagent has a thread to mark ended. Most never talked,
|
|
431
|
+
// and talk.mjs loads most of dibs, so look for its id in the file first.
|
|
432
|
+
function talked(input) {
|
|
433
|
+
if (typeof input.agent_id !== 'string' || !input.agent_id) return false;
|
|
434
|
+
try { return fs.readFileSync(MESSAGES, 'utf8').includes(JSON.stringify(input.agent_id)); } catch { return false; }
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// A main agent ending its turn after its dibs listen ended (it handed messages over, ran out of
|
|
438
|
+
// time or was killed) is kept going once, for that listener, to start it again: without one, a
|
|
439
|
+
// message sent while it waits sits until its next tool call. Only a session that listened
|
|
440
|
+
// before; one that never did hears about it at its start (src/primer.mjs). One read, and one
|
|
441
|
+
// small write when it reminds.
|
|
442
|
+
function rearm(input) {
|
|
443
|
+
if (input?.hook_event_name !== 'Stop' || input.stop_hook_active || typeof input.session_id !== 'string') return null;
|
|
444
|
+
let l;
|
|
445
|
+
try { l = JSON.parse(fs.readFileSync(LISTENERS, 'utf8'))[`${input.session_id}|main`]; } catch { return null; }
|
|
446
|
+
if (!Number.isInteger(l?.pid)) return null;
|
|
447
|
+
try { process.kill(l.pid, 0); return null; } catch (e) { if (e.code !== 'ESRCH') return null; }
|
|
448
|
+
let told = {};
|
|
449
|
+
try { told = JSON.parse(fs.readFileSync(REMINDED, 'utf8')); } catch {}
|
|
450
|
+
if (told[input.session_id] === l.pid) return null;
|
|
451
|
+
delete told[input.session_id];
|
|
452
|
+
told[input.session_id] = l.pid;
|
|
453
|
+
const keys = Object.keys(told);
|
|
454
|
+
for (const k of keys.slice(0, Math.max(0, keys.length - REMIND_KEEP))) delete told[k];
|
|
455
|
+
fs.writeFileSync(`${REMINDED}.${process.pid}`, JSON.stringify(told));
|
|
456
|
+
fs.renameSync(`${REMINDED}.${process.pid}`, REMINDED);
|
|
457
|
+
return { decision: 'block', reason: 'dibs: re-arm: your dibs listen has ended. Start it again with run_in_background (dibs listen) before you end your turn, so a message sent while you wait wakes you. dibs reminds you once each time it ends.' };
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
// The hook itself: Claude Code's JSON on stdin, a decision on stdout. Any
|
|
461
|
+
// failure prints nothing, which leaves the command to the normal permission flow.
|
|
462
|
+
export async function hook() {
|
|
463
|
+
let out = null, input = null;
|
|
464
|
+
try {
|
|
465
|
+
input = JSON.parse(fs.readFileSync(0, 'utf8'));
|
|
466
|
+
subagentState(input);
|
|
467
|
+
if (AGENT_EVENT(input)) out = (await import('./agents.mjs')).agentHook(input, dibsConfig());
|
|
468
|
+
else if (!STOP_EVENT(input) && !START_EVENT(input)) out = respond(input, guardConfig(), dibsCommand());
|
|
469
|
+
} catch (e) { logError(e, input); }
|
|
470
|
+
// A new session, or a subagent's first start, hears the few rules that keep it out of trouble (src/primer.mjs).
|
|
471
|
+
try { if (START_EVENT(input)) out = (await import('./primer.mjs')).primer(input, out); } catch (e) { logError(e, input); }
|
|
472
|
+
try {
|
|
473
|
+
if (queuedFor(input)) out = (await import('./talk.mjs')).deliver(input, out);
|
|
474
|
+
else if (input?.hook_event_name === 'SubagentStop' && talked(input)) (await import('./talk.mjs')).finished(input);
|
|
475
|
+
} catch (e) { logError(e, input); }
|
|
476
|
+
try { if (!out) out = rearm(input); } catch (e) { logError(e, input); }
|
|
477
|
+
if (out) process.stdout.write(JSON.stringify(out) + '\n');
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
const isGuard = h => h?.type === 'command' && /dibs-guard\.mjs['"]?$|\bdibs(\.mjs)?['"]? guard['"]?$/.test(String(h.command || '').trim());
|
|
481
|
+
|
|
482
|
+
function readSettings(file) {
|
|
483
|
+
if (!fs.existsSync(file)) return {};
|
|
484
|
+
const text = fs.readFileSync(file, 'utf8');
|
|
485
|
+
if (!text.trim()) return {};
|
|
486
|
+
try { return JSON.parse(text); } catch { throw new Error(`${file} isn't valid JSON; not touching it`); }
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
// Back up the old file once per change, then swap the new one in whole.
|
|
490
|
+
// Returns where the backup went, if there was a file to back up.
|
|
491
|
+
function writeSettings(file, s) {
|
|
492
|
+
const had = fs.existsSync(file);
|
|
493
|
+
const real = had ? fs.realpathSync(file) : file;
|
|
494
|
+
fs.mkdirSync(path.dirname(real), { recursive: true });
|
|
495
|
+
if (had) fs.copyFileSync(real, `${file}.dibs-backup`);
|
|
496
|
+
const tmp = `${real}.dibs-${process.pid}`;
|
|
497
|
+
fs.writeFileSync(tmp, JSON.stringify(s, null, 2) + '\n', { mode: had ? fs.statSync(real).mode & 0o777 : 0o600 });
|
|
498
|
+
fs.renameSync(tmp, real);
|
|
499
|
+
return had ? `${file}.dibs-backup` : null;
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
// Where the hook goes: Bash and the edit tools for the guard and file leases;
|
|
503
|
+
// the Agent tool (Task in older Claude Code) and subagent starts and stops for
|
|
504
|
+
// the subagent limit. No matcher on those two: agents.mjs sorts out which
|
|
505
|
+
// subagents count.
|
|
506
|
+
// Stop (no matcher: it takes none) hands the person's messages to an agent
|
|
507
|
+
// about to end its turn; SubagentStop does the same for subagents.
|
|
508
|
+
// SessionStart (no matcher: startup, resume, clear and compact all need it) tells a session the rules.
|
|
509
|
+
const ENTRIES = [['PreToolUse', 'Bash|Edit|Write|MultiEdit|NotebookEdit'], ['PreToolUse', 'Agent|Task'], ['SubagentStart', null], ['SubagentStop', null], ['Stop', null],
|
|
510
|
+
['SessionStart', null]];
|
|
511
|
+
const EVENTS = [...new Set(ENTRIES.map(e => e[0]))];
|
|
512
|
+
|
|
513
|
+
// Take our hook out of every event, dropping groups and lists it leaves empty.
|
|
514
|
+
function strip(s) {
|
|
515
|
+
let found = false;
|
|
516
|
+
for (const ev of EVENTS) {
|
|
517
|
+
const groups = s.hooks?.[ev];
|
|
518
|
+
if (!Array.isArray(groups)) continue;
|
|
519
|
+
const kept = [];
|
|
520
|
+
for (const g of groups) {
|
|
521
|
+
const hs = Array.isArray(g?.hooks) ? g.hooks.filter(h => !isGuard(h)) : g?.hooks;
|
|
522
|
+
if (Array.isArray(g?.hooks) && hs.length !== g.hooks.length) found = true;
|
|
523
|
+
if (!Array.isArray(hs) || hs.length) kept.push(Array.isArray(g?.hooks) ? { ...g, hooks: hs } : g);
|
|
524
|
+
}
|
|
525
|
+
if (kept.length) s.hooks[ev] = kept;
|
|
526
|
+
else delete s.hooks[ev];
|
|
527
|
+
}
|
|
528
|
+
if (s.hooks && !Object.keys(s.hooks).length) delete s.hooks;
|
|
529
|
+
return found;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
export const MATCHER = ENTRIES[0][1];
|
|
533
|
+
|
|
534
|
+
// Our groups in one event.
|
|
535
|
+
const ours = (s, ev = 'PreToolUse') => (s.hooks?.[ev] || []).filter(g => Array.isArray(g?.hooks) && g.hooks.some(isGuard));
|
|
536
|
+
// Every entry there with this command, and nothing else of ours: an older
|
|
537
|
+
// install (Bash alone, or no subagent events) is replaced, not added to.
|
|
538
|
+
const complete = (s, command) => EVENTS.every(ev => ours(s, ev).length === ENTRIES.filter(e => e[0] === ev).length)
|
|
539
|
+
&& ENTRIES.every(([ev, matcher]) => ours(s, ev).some(g => (g.matcher ?? null) === matcher && g.hooks.some(h => isGuard(h) && h.command === command)));
|
|
540
|
+
|
|
541
|
+
export function installed(file = SETTINGS) {
|
|
542
|
+
return ours(readSettings(file)).flatMap(g => g.hooks).find(isGuard) || null;
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
export function install(file = SETTINGS, command = quote(HOOK_BIN)) {
|
|
546
|
+
const s = readSettings(file);
|
|
547
|
+
const had = installed(file);
|
|
548
|
+
if (complete(s, command)) return `already installed in ${file}`;
|
|
549
|
+
strip(s);
|
|
550
|
+
s.hooks ||= {};
|
|
551
|
+
for (const [ev, matcher] of ENTRIES)
|
|
552
|
+
(s.hooks[ev] ||= []).push({ ...(matcher ? { matcher } : {}), hooks: [{ type: 'command', command, timeout: 5 }] });
|
|
553
|
+
const backup = writeSettings(file, s);
|
|
554
|
+
return `${had ? 'updated' : 'installed'} in ${file}${backup ? ` (old file in ${backup})` : ''}`;
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
export function remove(file = SETTINGS) {
|
|
558
|
+
const s = readSettings(file);
|
|
559
|
+
if (!strip(s)) return null;
|
|
560
|
+
writeSettings(file, s);
|
|
561
|
+
return `removed from ${file} (old file in ${file}.dibs-backup)`;
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
const USAGE = `dibs guard: catch heavy commands an agent runs outside dibs, turn away edits to files another session leased, cap subagents running at once when you set a limit, and hand agents the person's messages (dibs tell) (a Claude Code hook)
|
|
565
|
+
dibs guard install [--settings file] add the hook to ~/.claude/settings.json (backup kept)
|
|
566
|
+
dibs guard remove [--settings file] take it out again
|
|
567
|
+
dibs guard status [--settings file] [--json] is it installed (exit 1 if not; --json always exits 0)
|
|
568
|
+
dibs guard check "<command>" what the hook would do with a command
|
|
569
|
+
The hook reads Claude Code's JSON on stdin: dibs guard < input.json`;
|
|
570
|
+
|
|
571
|
+
// What `dibs guard status --json` prints, for dibs web too.
|
|
572
|
+
export function guardJson(file = SETTINGS) {
|
|
573
|
+
const h = installed(file);
|
|
574
|
+
const s = readSettings(file);
|
|
575
|
+
const agents = dibsConfig().agents;
|
|
576
|
+
return { installed: !!h, file, command: h?.command ?? null, complete: !!h && complete(s, h.command),
|
|
577
|
+
matchers: EVENTS.flatMap(ev => ours(s, ev).map(g => ({ event: ev, matcher: g.matcher ?? null }))), rewrite: guardConfig().rewrite || 'bypass',
|
|
578
|
+
subagents: Number(agents?.slots) > 0 ? { slots: Number(agents.slots) } : null };
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
// dibs guard [install|remove|status|check]. With no verb and JSON piped in, be the hook.
|
|
582
|
+
export function guard(args) {
|
|
583
|
+
const reply = (msg, code = 0) => { (code ? process.stderr : process.stdout).write(`${msg}\n`); process.exitCode = code; };
|
|
584
|
+
const at = args.indexOf('--settings');
|
|
585
|
+
const file = at >= 0 ? args[at + 1] : SETTINGS;
|
|
586
|
+
if (at >= 0 && !file) return reply('--settings needs a path', 2);
|
|
587
|
+
const verb = args[0];
|
|
588
|
+
try {
|
|
589
|
+
if (!verb) return process.stdin.isTTY ? reply(USAGE) : hook();
|
|
590
|
+
if (verb === 'install') return reply(`dibs guard: ${install(file)}`);
|
|
591
|
+
if (verb === 'remove') { const r = remove(file); return r ? reply(`dibs guard: ${r}`) : reply(`dibs guard: not installed in ${file}`, 1); }
|
|
592
|
+
if (verb === 'status') {
|
|
593
|
+
const h = installed(file);
|
|
594
|
+
const mode = guardConfig().rewrite || 'bypass';
|
|
595
|
+
const agents = dibsConfig().agents;
|
|
596
|
+
// For the Mac app: the same facts as an object, exit 0 either way.
|
|
597
|
+
if (args.includes('--json')) return reply(JSON.stringify(guardJson(file), null, 1));
|
|
598
|
+
if (!h) return reply(`dibs guard is off: it isn't in ${file}. Turn it on: dibs guard install`, 1);
|
|
599
|
+
return reply([`dibs guard is on (in ${file}).`,
|
|
600
|
+
` Heavy commands an agent runs outside dibs: ${guardConfig() === false || guardConfig().commands === false ? 'let through (switched off in config.json)' : mode === 'bypass' ? 'run through dibs in bypassPermissions sessions, turned away in others' : `run through dibs in "${mode}" sessions, turned away in others`}.`,
|
|
601
|
+
` Edits to files another agent reserved: ${guardConfig().files === false ? 'let through (guard.files is false in config.json)' : 'turned away'}.`,
|
|
602
|
+
' New sessions and subagents: told in a few lines how to use dibs. Messages from the person (dibs tell) and notices about their own jobs: handed over on their next tool call.',
|
|
603
|
+
` Subagents: ${Number(agents?.slots) > 0 ? `at most ${agents.slots} at once across every session` : 'no limit (set agents.slots in config.json to add one)'}.`,
|
|
604
|
+
...(complete(readSettings(file), h.command) ? [] : [' This is an older install without the file checks, the subagent limit, messages from the person or the new-session primer. Add them: dibs guard install']),
|
|
605
|
+
` The hook: ${h.command}`].join('\n'));
|
|
606
|
+
}
|
|
607
|
+
if (verb === 'check') {
|
|
608
|
+
const plan = check(args.slice(1).join(' '), { rules: rulesFrom(guardConfig()) });
|
|
609
|
+
return reply(plan ? `${plan.hits.map(h => h.res).join(' + ')}: ${plan.command}` : 'leave alone');
|
|
610
|
+
}
|
|
611
|
+
return reply(USAGE, 2);
|
|
612
|
+
} catch (e) { return reply(`dibs guard: ${e.message}`, 1); }
|
|
613
|
+
}
|