@dibssoftware/dibs 0.0.181 → 0.0.195
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +103 -1
- package/README.md +10 -8
- package/bin/dibs.mjs +370 -73
- 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 +120 -9
- 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/package.json +1 -1
- package/skills/dibs/SKILL.md +79 -149
- package/src/about.mjs +341 -0
- package/src/acquire.mjs +111 -27
- package/src/after.mjs +127 -0
- package/src/agents.mjs +2 -1
- package/src/alerts.mjs +95 -42
- 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 +243 -82
- package/src/config.mjs +85 -14
- package/src/connect.mjs +4 -2
- package/src/cool.mjs +27 -11
- 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 +118 -6
- package/src/guard.mjs +239 -86
- 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 +33 -9
- package/src/measure.mjs +42 -11
- 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 +19 -0
- package/src/preempt.mjs +123 -15
- package/src/primer.mjs +91 -20
- package/src/prints.mjs +99 -0
- package/src/proc.mjs +1 -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 +139 -20
- 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/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 +1078 -133
- 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 +353 -60
- package/src/work.mjs +487 -0
- package/src/worker.mjs +7 -1
package/src/guard.mjs
CHANGED
|
@@ -8,7 +8,7 @@ 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 } from './files.mjs';
|
|
11
|
+
import { tmpGuard, fileGuard, resList, sharedNudge } 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');
|
|
@@ -37,6 +37,13 @@ const REARM_MAX = 3;
|
|
|
37
37
|
const LISTEN_CMD = /(^|[\s;&|(/'"])dibs(\.mjs)?['"]?\s+listen\b/;
|
|
38
38
|
// The threads themselves, which the hook only searches for a subagent's id.
|
|
39
39
|
const MESSAGES = path.join(DIBS_HOME, 'messages.json');
|
|
40
|
+
// Fingerprints of stored secrets (src/prints.mjs). Absent when none is stored, and then the hook loads nothing more.
|
|
41
|
+
const PRINTS = path.join(DIBS_HOME, 'prints.json');
|
|
42
|
+
// Who has heard the rest of the rules (src/primer.mjs firstUse): read on a dibs call, and
|
|
43
|
+
// primer.mjs loaded only when this session and agent isn't in it yet.
|
|
44
|
+
const FIRST_USE = path.join(DIBS_HOME, 'firstuse.json');
|
|
45
|
+
// A Bash command that calls dibs, however it was named: dibs, ~/bin/dibs, dibs.mjs.
|
|
46
|
+
const DIBS_CALL = /(^|[\s;&|(/'"])dibs(\.mjs)?['"]?(\s|$)/;
|
|
40
47
|
const SETTINGS = process.env.DIBS_CLAUDE_SETTINGS || path.join(os.homedir(), '.claude', 'settings.json');
|
|
41
48
|
|
|
42
49
|
// What counts as heavy: the command's first words, once env, npx, time, cd and
|
|
@@ -329,8 +336,13 @@ export function rulesFrom(guardCfg) {
|
|
|
329
336
|
// A ~ inside a word stays as typed (Windows short names: C:/Users/RUNNER~1); only a leading one expands.
|
|
330
337
|
const quote = s => (/^[\w@%+=:,./-][\w@%+=:,./~-]*$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
|
|
331
338
|
|
|
332
|
-
//
|
|
333
|
-
//
|
|
339
|
+
// Where the agent's own words go in the line the hook hands back. dibs run takes
|
|
340
|
+
// only plain words a person can follow (src/declare.mjs), which the hook can't
|
|
341
|
+
// make up, and refuses this placeholder if it's sent as it is.
|
|
342
|
+
export const ASK = '<what this does and why, in plain words>';
|
|
343
|
+
|
|
344
|
+
// What to do with a command: null to leave it alone, or the command to run
|
|
345
|
+
// instead and what was caught.
|
|
334
346
|
export function check(cmd, { rules = RULES, dibs = 'dibs' } = {}) {
|
|
335
347
|
if (typeof cmd !== 'string') return null;
|
|
336
348
|
const segs = split(cmd);
|
|
@@ -354,14 +366,10 @@ export function check(cmd, { rules = RULES, dibs = 'dibs' } = {}) {
|
|
|
354
366
|
// whole, under one lease for everything it needs.
|
|
355
367
|
if (/\$\{?SIM(_NAME)?\b/.test(cmd)) {
|
|
356
368
|
const res = [...new Set(hits.flatMap(h => h.res.split(',')))].join(',');
|
|
357
|
-
|
|
358
|
-
return { command: `${dibs} run ${res} -m ${quote(why)} -- sh -c ${quote(cmd)}`, hits };
|
|
369
|
+
return { command: `${dibs} run ${res} -m ${quote(ASK)} -- sh -c ${quote(cmd)}`, hits };
|
|
359
370
|
}
|
|
360
371
|
let out = cmd;
|
|
361
|
-
for (const h of [...hits].sort((a, b) => b.at - a.at)) {
|
|
362
|
-
const why = `guard: ${h.what}`.replace(/[^\w .:/=@,+-]/g, '').slice(0, 50).trim();
|
|
363
|
-
out = `${out.slice(0, h.at)}${dibs} run ${h.res} -m ${quote(why)} -- ${out.slice(h.at)}`;
|
|
364
|
-
}
|
|
372
|
+
for (const h of [...hits].sort((a, b) => b.at - a.at)) out = `${out.slice(0, h.at)}${dibs} run ${h.res} -m ${quote(ASK)} -- ${out.slice(h.at)}`;
|
|
365
373
|
return { command: out, hits };
|
|
366
374
|
}
|
|
367
375
|
|
|
@@ -369,7 +377,7 @@ export function check(cmd, { rules = RULES, dibs = 'dibs' } = {}) {
|
|
|
369
377
|
// here so the failure isn't invisible. Writing it may fail too; nothing to do then.
|
|
370
378
|
// Where in dibs it broke and on what kind of call, never the command itself
|
|
371
379
|
// (it can hold secrets): enough to find the bug, as `dibs alerts` reports it.
|
|
372
|
-
function logError(e, input) {
|
|
380
|
+
export function logError(e, input) {
|
|
373
381
|
// A full disk is no bug in dibs: the call goes through, and the board already says the disk is full.
|
|
374
382
|
if (e?.code === 'ENOSPC' || e?.code === 'EDQUOT') return;
|
|
375
383
|
const at = String(e?.stack || '').split('\n').find(l => l.includes('/src/'))?.match(/\/(src\/[\w.]+:\d+)/)?.[1];
|
|
@@ -377,58 +385,91 @@ function logError(e, input) {
|
|
|
377
385
|
try { fs.appendFileSync(LOG, `${new Date().toISOString()} ${String(e?.message || e).split('\n')[0]}${at ? ` at ${at}` : ''}${on}\n`); } catch {}
|
|
378
386
|
}
|
|
379
387
|
|
|
380
|
-
function dibsConfig() {
|
|
388
|
+
export function dibsConfig() {
|
|
381
389
|
try { return JSON.parse(fs.readFileSync(CONFIG, 'utf8')); }
|
|
382
390
|
catch (e) { if (e.code !== 'ENOENT') logError(`${CONFIG}: ${e.message}`); return {}; }
|
|
383
391
|
}
|
|
384
|
-
const guardConfig = () => dibsConfig().guard ?? {};
|
|
392
|
+
export const guardConfig = () => dibsConfig().guard ?? {};
|
|
385
393
|
|
|
386
394
|
// Subagent spawns, starts and stops go to the subagent limit (src/agents.mjs),
|
|
387
395
|
// loaded only for those: a Bash call still pays for this module alone.
|
|
388
396
|
const AGENT_EVENT = input => ['Agent', 'Task'].includes(input?.tool_name) || ['SubagentStart', 'SubagentStop'].includes(input?.hook_event_name);
|
|
389
397
|
|
|
398
|
+
// A Bash command that may be a milestone for the trail (src/trailnote.mjs, loaded only for these):
|
|
399
|
+
// a commit, push, merge or tag, a GitHub release or pull request, an upload to App Store Connect,
|
|
400
|
+
// a publish. Loose on purpose: a near miss costs one small module, a miss costs the person a line.
|
|
401
|
+
const TRAIL_HINT = /\bgit\b[^\n;|&]*\b(commit|push|merge|tag)\b|\bgh\s+(release|pr)\s|-exportArchive|\baltool\b|\basc\s+(builds\s+upload|publish)\b|\bfastlane\b|\beas\s+submit\b|\b(npm|pnpm|yarn)\b[^\n;|&]*\bpublish\b/;
|
|
402
|
+
// A Bash command that may merge or push: the review gate (src/reviewgate.mjs, loaded only for these)
|
|
403
|
+
// checks whether the project asks for an approving review first. Loose on purpose: a near miss costs
|
|
404
|
+
// one small module and a few file reads, a miss lets an unreviewed change into main.
|
|
405
|
+
const MERGE_HINT = /\bgit\b[^\n;|&]*\b(merge|push)\b|\bgh\b[^\n;|&]*\bpr\s+merge\b/;
|
|
406
|
+
// A Bash command that may be a one-way door (src/doors.mjs, loaded only for these, and only when the
|
|
407
|
+
// person turned dibs doors on). Loose on purpose: a near miss costs one small module.
|
|
408
|
+
export const DOOR_HINT = /\bpush\b|deploy|publish|promote|altool|\basc\b|-exportArchive|fastlane|\beas\b|upload|\brm\b|drop|truncate|delete|reset|restore|destroy|\bbuy\b|purchase|register|--live|\brelease\b/i;
|
|
409
|
+
|
|
390
410
|
// `dibs` when it's on PATH, so the rewritten command reads the way agents
|
|
391
411
|
// write it; otherwise this copy's full path.
|
|
392
|
-
function dibsCommand() {
|
|
412
|
+
export function dibsCommand() {
|
|
393
413
|
for (const dir of (process.env.PATH || '').split(path.delimiter))
|
|
394
414
|
if (dir && fs.existsSync(path.join(dir, 'dibs'))) return 'dibs';
|
|
395
415
|
return viaNode(path.join(ROOT, 'bin', 'dibs.mjs'));
|
|
396
416
|
}
|
|
397
417
|
|
|
398
|
-
//
|
|
399
|
-
//
|
|
400
|
-
//
|
|
401
|
-
//
|
|
418
|
+
// A heavy command outside dibs is turned away with the dibs run line to send
|
|
419
|
+
// instead. Before 0.0.191 a bypassPermissions session's command was rewritten
|
|
420
|
+
// and let through, labelled "guard: <its command>"; now every run says in plain
|
|
421
|
+
// words what it does (src/declare.mjs), and only the agent knows that, so the
|
|
422
|
+
// hook never runs anything for it. A denial is an ordinary answer: the agent
|
|
423
|
+
// sends the line again with its own words, through the normal permission checks.
|
|
424
|
+
// guard.rewrite in config.json is no longer read.
|
|
402
425
|
// "guard": false in config.json (or guard.commands false) switches off only
|
|
403
426
|
// the heavy-command half; file leases stay enforced unless guard.files is false.
|
|
404
427
|
export function respond(input, guardCfg = {}, dibs = 'dibs') {
|
|
428
|
+
// Codex (and OpenCode) edit through one patch: each file it touches is checked as a Write.
|
|
429
|
+
if (input?.tool_name === 'apply_patch') {
|
|
430
|
+
for (const file of patchFiles(input.tool_input?.command)) {
|
|
431
|
+
const r = respond({ ...input, tool_name: 'Write', tool_input: { file_path: file } }, guardCfg, dibs);
|
|
432
|
+
if (r) return r;
|
|
433
|
+
}
|
|
434
|
+
return null;
|
|
435
|
+
}
|
|
405
436
|
// Another session's file lease (src/files.mjs) turns a write away before anything else.
|
|
406
437
|
// So does a delete in another session's temp folder, whatever the config says: it's the person's rule.
|
|
407
438
|
const leased = tmpGuard(input, split) || (guardCfg?.files === false ? null : fileGuard(input, split));
|
|
408
439
|
if (leased || input?.tool_name !== 'Bash' || guardCfg === false || guardCfg?.commands === false) return leased;
|
|
409
|
-
const
|
|
410
|
-
const plan = check(ti.command, { rules: rulesFrom(guardCfg), dibs });
|
|
440
|
+
const plan = check(input.tool_input?.command, { rules: rulesFrom(guardCfg), dibs });
|
|
411
441
|
if (!plan) return null;
|
|
412
|
-
const mode = guardCfg.rewrite || 'bypass';
|
|
413
442
|
const what = [...new Set(plan.hits.map(h => h.what.split(' ')[0]))].join(', ');
|
|
414
|
-
if (mode === 'always' || (mode === 'bypass' && input.permission_mode === 'bypassPermissions')) {
|
|
415
|
-
return { hookSpecificOutput: {
|
|
416
|
-
hookEventName: 'PreToolUse',
|
|
417
|
-
permissionDecision: 'allow',
|
|
418
|
-
permissionDecisionReason: `dibs guard wrapped ${what} in dibs run`,
|
|
419
|
-
updatedInput: { ...ti, command: plan.command },
|
|
420
|
-
additionalContext: `dibs guard ran this through dibs because ${what} wasn't wrapped: ${plan.command}\n` +
|
|
421
|
-
'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.',
|
|
422
|
-
} };
|
|
423
|
-
}
|
|
424
443
|
return { hookSpecificOutput: {
|
|
425
444
|
hookEventName: 'PreToolUse',
|
|
426
445
|
permissionDecision: 'deny',
|
|
427
|
-
permissionDecisionReason: `dibs guard: ${what} has to take its turn through dibs, or it collides with other agents. Run
|
|
428
|
-
|
|
446
|
+
permissionDecisionReason: `dibs guard: ${what} has to take its turn through dibs, or it collides with other agents. Run it through dibs, with -m in your own plain words`
|
|
447
|
+
+ ` saying what it does and why (the person reads them; "run the login tests after fixing the redirect", not "npm test"):\n ${plan.command}\n`
|
|
448
|
+
+ 'If it really is a quick read that builds, boots, tests and deploys nothing, put DIBS_GUARD=off in front of it.',
|
|
429
449
|
} };
|
|
430
450
|
}
|
|
431
451
|
|
|
452
|
+
// The files a patch in Codex's apply_patch format adds, changes, deletes or moves to.
|
|
453
|
+
const PATCH_FILE = /^\*\*\* (?:(?:Add|Update|Delete) File|Move to): (.+)$/;
|
|
454
|
+
export function patchFiles(text) {
|
|
455
|
+
if (typeof text !== 'string') return [];
|
|
456
|
+
return text.split(/\r?\n/).map(l => l.match(PATCH_FILE)?.[1].trim()).filter(Boolean);
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
// Which agent tool sent the call. Codex sends Claude Code's format (its calls carry
|
|
460
|
+
// turn_id, and it edits with apply_patch); Gemini CLI, Cursor and the OpenCode plugin
|
|
461
|
+
// are told apart by their own event names and fields (src/vendors.mjs reads them).
|
|
462
|
+
export function vendorOf(input, env = process.env) {
|
|
463
|
+
const ev = input?.hook_event_name;
|
|
464
|
+
if (typeof ev !== 'string') return 'claude';
|
|
465
|
+
if (ev.startsWith('opencode.')) return 'opencode';
|
|
466
|
+
if ('cursor_version' in input || /^[a-z]/.test(ev)) return 'cursor';
|
|
467
|
+
if (ev === 'BeforeTool' || ev === 'AfterTool' || (ev === 'SessionStart' && (env.GEMINI_SESSION_ID || 'timestamp' in input))) return 'gemini';
|
|
468
|
+
// Codex's SessionStart has no turn_id; its transcript is a rollout-*.jsonl (Codex 0.167.1, captured).
|
|
469
|
+
if ('turn_id' in input || input.tool_name === 'apply_patch' || /[\\/]rollout-[^\\/]*\.jsonl$/.test(String(input.transcript_path || ''))) return 'codex';
|
|
470
|
+
return 'claude';
|
|
471
|
+
}
|
|
472
|
+
|
|
432
473
|
const STOP_EVENT = input => ['Stop', 'SubagentStop'].includes(input?.hook_event_name);
|
|
433
474
|
const START_EVENT = input => ['SessionStart', 'SubagentStart'].includes(input?.hook_event_name);
|
|
434
475
|
|
|
@@ -463,9 +504,10 @@ function rearm(input, env = process.env) {
|
|
|
463
504
|
if (/^sdk-/.test(env.CLAUDE_CODE_ENTRYPOINT || '') || /^(1|true|yes|on)$/i.test(env.CLAUDE_CODE_DISABLE_BACKGROUND_TASKS || '')) return null;
|
|
464
505
|
let l = null;
|
|
465
506
|
try { l = JSON.parse(fs.readFileSync(LISTENERS, 'utf8'))[`${sid}|main`] || null; } catch {}
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
507
|
+
const listed = Array.isArray(input.background_tasks);
|
|
508
|
+
if (listed && input.background_tasks.some(t => LISTEN_CMD.test(String(t?.command || '')))) return null;
|
|
509
|
+
// A dibs listen --stream may run under a monitor, which the list of background tasks needn't name.
|
|
510
|
+
if ((!listed || l?.stream) && Number.isInteger(l?.pid)) {
|
|
469
511
|
try { process.kill(l.pid, 0); return null; } catch (e) { if (e.code !== 'ESRCH') return null; }
|
|
470
512
|
}
|
|
471
513
|
let told = {};
|
|
@@ -494,6 +536,16 @@ function withRearm(input, out) {
|
|
|
494
536
|
return { ...out, hookSpecificOutput: { ...out?.hookSpecificOutput, hookEventName: 'Stop', additionalContext: [prev, line].filter(Boolean).join('\n\n') } };
|
|
495
537
|
}
|
|
496
538
|
|
|
539
|
+
// Whether this Bash call is the session's first use of dibs that hasn't been told the rest of
|
|
540
|
+
// the rules yet: a dibs command, or a heavy command the guard turned away. Claude Code only:
|
|
541
|
+
// the other tools hear every rule at their start (src/vendors.mjs).
|
|
542
|
+
function firstUse(input, out) {
|
|
543
|
+
if (input?.tool_name !== 'Bash' || typeof input.session_id !== 'string' || !input.session_id) return false;
|
|
544
|
+
const turned = /has to take its turn through dibs/.test(out?.hookSpecificOutput?.permissionDecisionReason || '');
|
|
545
|
+
if (!turned && !DIBS_CALL.test(String(input.tool_input?.command || ''))) return false;
|
|
546
|
+
try { return !JSON.parse(fs.readFileSync(FIRST_USE, 'utf8')).includes(`${input.session_id}|${input.agent_id || 'main'}`); } catch { return true; }
|
|
547
|
+
}
|
|
548
|
+
|
|
497
549
|
// The hook itself: Claude Code's JSON on stdin, a decision on stdout. Any
|
|
498
550
|
// failure prints nothing, which leaves the command to the normal permission flow.
|
|
499
551
|
export async function hook() {
|
|
@@ -503,13 +555,62 @@ export async function hook() {
|
|
|
503
555
|
if (out) process.stdout.write(JSON.stringify(out) + '\n');
|
|
504
556
|
}
|
|
505
557
|
|
|
558
|
+
// A command or an edit that holds a stored secret's value would leave it in the transcript, the
|
|
559
|
+
// shell history or a file. Turned away with the way to use it unseen (src/vault.mjs).
|
|
560
|
+
const WRITES = { Bash: ti => [ti.command], Write: ti => [ti.content], Edit: ti => [ti.new_string], MultiEdit: ti => (ti.edits || []).map(e => e?.new_string),
|
|
561
|
+
NotebookEdit: ti => [ti.new_source] };
|
|
562
|
+
async function secretGuard(input) {
|
|
563
|
+
const texts = WRITES[input?.tool_name];
|
|
564
|
+
if (!texts || !fs.existsSync(PRINTS)) return null;
|
|
565
|
+
const { find } = await import('./prints.mjs');
|
|
566
|
+
const names = [...new Set(texts(input.tool_input || {}).filter(t => typeof t === 'string').flatMap(t => find(t).map(h => h.name)))];
|
|
567
|
+
if (!names.length) return null;
|
|
568
|
+
const n = names[0];
|
|
569
|
+
const why = input.tool_name === 'Bash'
|
|
570
|
+
? `this command has the value of the secret ${names.join(', ')} in it, so it would sit in your transcript and the shell's history. Use it without seeing it:\n dibs secret run ${names.join(',')} -- <the command, reading $${n}>`
|
|
571
|
+
: `this edit writes the value of the secret ${names.join(', ')} into ${input.tool_input?.file_path || input.tool_input?.notebook_path || 'a file'}. Read it at run time instead (dibs secret run ${n} -- <command reading $${n}>), or ask the person where it belongs.`;
|
|
572
|
+
return { hookSpecificOutput: { hookEventName: 'PreToolUse', permissionDecision: 'deny', permissionDecisionReason: `dibs guard: ${why}` } };
|
|
573
|
+
}
|
|
574
|
+
|
|
506
575
|
// What the hook answers for one event, or null to say nothing. The resident
|
|
507
576
|
// guard (src/guardd.mjs) runs this too, in a fresh worker per call.
|
|
508
577
|
export async function decide(input) {
|
|
578
|
+
const vendor = vendorOf(input);
|
|
579
|
+
// Gemini CLI, Cursor and OpenCode: the same rules, read from and answered in their own formats.
|
|
580
|
+
if (vendor !== 'claude' && vendor !== 'codex') {
|
|
581
|
+
try { return await (await import('./vendors.mjs')).decideFor(vendor, input); } catch (e) { logError(e, input); return null; }
|
|
582
|
+
}
|
|
509
583
|
let out = null;
|
|
584
|
+
// config.json, read once for the whole call.
|
|
585
|
+
let cfg = null;
|
|
586
|
+
const conf = () => (cfg ??= dibsConfig());
|
|
587
|
+
const gcfg = () => conf().guard ?? {};
|
|
588
|
+
try {
|
|
589
|
+
if (AGENT_EVENT(input)) out = (await import('./agents.mjs')).agentHook(input, conf());
|
|
590
|
+
else if (!STOP_EVENT(input) && !START_EVENT(input)) out = (await secretGuard(input)) || respond(input, gcfg(), dibsCommand());
|
|
591
|
+
} catch (e) { logError(e, input); }
|
|
592
|
+
const cmd = input?.tool_name === 'Bash' ? input.tool_input?.command || '' : '';
|
|
593
|
+
const denied = () => out?.hookSpecificOutput?.permissionDecision === 'deny';
|
|
594
|
+
// A merge into main, or a push to it, with no approving review, where the project asks for one, is turned away
|
|
595
|
+
// before it runs. A call already turned away stays as it is.
|
|
510
596
|
try {
|
|
511
|
-
if (
|
|
512
|
-
|
|
597
|
+
if (cmd && MERGE_HINT.test(cmd) && !denied() && gcfg().reviews !== false) out = (await import('./reviewgate.mjs')).gate(input, split) || out;
|
|
598
|
+
} catch (e) { logError(e, input); }
|
|
599
|
+
// A command that can't be undone waits for the person's yes, when they turned dibs doors on. Last of
|
|
600
|
+
// the checks, so a once-only yes is used up only by a command that goes ahead.
|
|
601
|
+
try {
|
|
602
|
+
if (cmd && conf().doors?.on === true && DOOR_HINT.test(cmd) && !denied()) out = (await import('./doors.mjs')).gate(input, split, conf(), { vendor }) || out;
|
|
603
|
+
} catch (e) { logError(e, input); }
|
|
604
|
+
// What may be a milestone goes on the trail, unless the guard turned the command away: then it never runs.
|
|
605
|
+
try {
|
|
606
|
+
if (cmd && TRAIL_HINT.test(cmd) && !denied() && gcfg().trail !== false) (await import('./trailnote.mjs')).note(input, split);
|
|
607
|
+
} catch (e) { logError(e, input); }
|
|
608
|
+
// A command that writes or deletes in a folder another agent wrote into lately hears who (src/files.mjs).
|
|
609
|
+
try {
|
|
610
|
+
if (out?.hookSpecificOutput?.permissionDecision !== 'deny' && guardConfig()?.files !== false) {
|
|
611
|
+
const nudge = sharedNudge(input, split);
|
|
612
|
+
if (nudge) out = { ...out, hookSpecificOutput: { hookEventName: 'PreToolUse', ...out?.hookSpecificOutput, additionalContext: [out?.hookSpecificOutput?.additionalContext, nudge].filter(Boolean).join('\n\n') } };
|
|
613
|
+
}
|
|
513
614
|
} catch (e) { logError(e, input); }
|
|
514
615
|
// A new session, or a subagent's first start, hears the few rules that keep it out of trouble (src/primer.mjs).
|
|
515
616
|
try { if (START_EVENT(input)) out = (await import('./primer.mjs')).primer(input, out); } catch (e) { logError(e, input); }
|
|
@@ -517,13 +618,18 @@ export async function decide(input) {
|
|
|
517
618
|
if (queuedFor(input)) out = (await import('./talk.mjs')).deliver(input, out);
|
|
518
619
|
else if (input?.hook_event_name === 'SubagentStop' && talked(input)) (await import('./talk.mjs')).finished(input);
|
|
519
620
|
} catch (e) { logError(e, input); }
|
|
621
|
+
// The first dibs call of a session (or a subagent) hears the rules it didn't need at its start.
|
|
622
|
+
try { if (vendor === 'claude' && firstUse(input, out)) out = (await import('./primer.mjs')).firstUse(input, out); } catch (e) { logError(e, input); }
|
|
520
623
|
try { out = withRearm(input, out); } catch (e) { logError(e, input); }
|
|
624
|
+
// A Codex session isn't one Claude Code knows, so its messages wait under its name, as for a terminal's.
|
|
625
|
+
try { if (vendor === 'codex') out = await (await import('./vendors.mjs')).codexAnswer(input, out); } catch (e) { logError(e, input); }
|
|
521
626
|
return out;
|
|
522
627
|
}
|
|
523
628
|
|
|
524
|
-
|
|
629
|
+
// Cursor's hooks.json leaves type out; it means a command there.
|
|
630
|
+
const isGuard = h => (h?.type ?? 'command') === 'command' && /dibs-guard\.mjs['"]?$|\bdibs(\.mjs)?['"]? guard['"]?$/.test(String(h?.command || '').trim());
|
|
525
631
|
|
|
526
|
-
function readSettings(file) {
|
|
632
|
+
export function readSettings(file) {
|
|
527
633
|
if (!fs.existsSync(file)) return {};
|
|
528
634
|
const text = fs.readFileSync(file, 'utf8');
|
|
529
635
|
if (!text.trim()) return {};
|
|
@@ -532,7 +638,7 @@ function readSettings(file) {
|
|
|
532
638
|
|
|
533
639
|
// Back up the old file once per change, then swap the new one in whole.
|
|
534
640
|
// Returns where the backup went, if there was a file to back up.
|
|
535
|
-
function writeSettings(file, s) {
|
|
641
|
+
export function writeSettings(file, s) {
|
|
536
642
|
const had = fs.existsSync(file);
|
|
537
643
|
const real = had ? fs.realpathSync(file) : file;
|
|
538
644
|
fs.mkdirSync(path.dirname(real), { recursive: true });
|
|
@@ -552,16 +658,23 @@ function writeSettings(file, s) {
|
|
|
552
658
|
// SessionStart (no matcher: startup, resume, clear and compact all need it) tells a session the rules.
|
|
553
659
|
const ENTRIES = [['PreToolUse', 'Bash|Edit|Write|MultiEdit|NotebookEdit'], ['PreToolUse', 'Agent|Task'], ['SubagentStart', null], ['SubagentStop', null], ['Stop', null],
|
|
554
660
|
['SessionStart', null]];
|
|
555
|
-
|
|
661
|
+
|
|
662
|
+
// A tool's hook file: its events and matchers, one handler, and whether its groups
|
|
663
|
+
// hold a list of handlers (Claude Code, Codex, Gemini CLI) or are the handler (Cursor).
|
|
664
|
+
// src/vendors.mjs has the others.
|
|
665
|
+
export const CLAUDE = { name: 'Claude Code', entries: ENTRIES, handler: command => ({ type: 'command', command, timeout: 5 }) };
|
|
666
|
+
const events = t => [...new Set(t.entries.map(e => e[0]))];
|
|
667
|
+
const handlers = (t, g) => (t.flat ? [g].filter(isGuard) : Array.isArray(g?.hooks) ? g.hooks.filter(isGuard) : []);
|
|
556
668
|
|
|
557
669
|
// Take our hook out of every event, dropping groups and lists it leaves empty.
|
|
558
|
-
function strip(s) {
|
|
670
|
+
function strip(s, t = CLAUDE) {
|
|
559
671
|
let found = false;
|
|
560
|
-
for (const ev of
|
|
672
|
+
for (const ev of events(t)) {
|
|
561
673
|
const groups = s.hooks?.[ev];
|
|
562
674
|
if (!Array.isArray(groups)) continue;
|
|
563
675
|
const kept = [];
|
|
564
676
|
for (const g of groups) {
|
|
677
|
+
if (t.flat) { if (isGuard(g)) found = true; else kept.push(g); continue; }
|
|
565
678
|
const hs = Array.isArray(g?.hooks) ? g.hooks.filter(h => !isGuard(h)) : g?.hooks;
|
|
566
679
|
if (Array.isArray(g?.hooks) && hs.length !== g.hooks.length) found = true;
|
|
567
680
|
if (!Array.isArray(hs) || hs.length) kept.push(Array.isArray(g?.hooks) ? { ...g, hooks: hs } : g);
|
|
@@ -576,84 +689,124 @@ function strip(s) {
|
|
|
576
689
|
export const MATCHER = ENTRIES[0][1];
|
|
577
690
|
|
|
578
691
|
// Our groups in one event.
|
|
579
|
-
const ours = (s, ev =
|
|
692
|
+
const ours = (s, ev, t = CLAUDE) => (Array.isArray(s.hooks?.[ev]) ? s.hooks[ev] : []).filter(g => handlers(t, g).length);
|
|
580
693
|
// Every entry there with this command, and nothing else of ours: an older
|
|
581
694
|
// install (Bash alone, or no subagent events) is replaced, not added to.
|
|
582
|
-
const complete = (s, command) =>
|
|
583
|
-
&&
|
|
695
|
+
const complete = (s, command, t = CLAUDE) => events(t).every(ev => ours(s, ev, t).length === t.entries.filter(e => e[0] === ev).length)
|
|
696
|
+
&& t.entries.every(([ev, matcher]) => ours(s, ev, t).some(g => (g.matcher ?? null) === matcher && handlers(t, g).some(h => h.command === command)));
|
|
584
697
|
|
|
585
|
-
export function installed(file = SETTINGS) {
|
|
586
|
-
return ours(readSettings(file)).flatMap(g => g
|
|
698
|
+
export function installed(file = SETTINGS, t = CLAUDE) {
|
|
699
|
+
return ours(readSettings(file), t.entries[0][0], t).flatMap(g => handlers(t, g))[0] || null;
|
|
587
700
|
}
|
|
588
701
|
|
|
589
|
-
export
|
|
702
|
+
export const HOOK_COMMAND = viaNode(HOOK_BIN);
|
|
703
|
+
|
|
704
|
+
export function install(file = SETTINGS, command = HOOK_COMMAND, t = CLAUDE) {
|
|
590
705
|
const s = readSettings(file);
|
|
591
|
-
const had = installed(file);
|
|
592
|
-
if (complete(s, command)) return `already installed in ${file}`;
|
|
593
|
-
strip(s);
|
|
706
|
+
const had = installed(file, t);
|
|
707
|
+
if (complete(s, command, t)) return `already installed in ${file}`;
|
|
708
|
+
strip(s, t);
|
|
709
|
+
Object.assign(s, { ...t.top, ...s });
|
|
594
710
|
s.hooks ||= {};
|
|
595
|
-
for (const [ev, matcher] of
|
|
596
|
-
|
|
711
|
+
for (const [ev, matcher] of t.entries) {
|
|
712
|
+
const m = matcher ? { matcher } : {};
|
|
713
|
+
(s.hooks[ev] ||= []).push(t.flat ? { ...m, ...t.handler(command) } : { ...m, hooks: [t.handler(command)] });
|
|
714
|
+
}
|
|
597
715
|
const backup = writeSettings(file, s);
|
|
598
716
|
return `${had ? 'updated' : 'installed'} in ${file}${backup ? ` (old file in ${backup})` : ''}`;
|
|
599
717
|
}
|
|
600
718
|
|
|
601
|
-
export function remove(file = SETTINGS) {
|
|
719
|
+
export function remove(file = SETTINGS, t = CLAUDE) {
|
|
602
720
|
const s = readSettings(file);
|
|
603
|
-
if (!strip(s)) return null;
|
|
721
|
+
if (!strip(s, t)) return null;
|
|
604
722
|
writeSettings(file, s);
|
|
605
723
|
return `removed from ${file} (old file in ${file}.dibs-backup)`;
|
|
606
724
|
}
|
|
607
725
|
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
726
|
+
// Whether the hook in file is this version's whole set of entries.
|
|
727
|
+
export const isComplete = (file, t = CLAUDE) => { const h = installed(file, t); return !!h && complete(readSettings(file), h.command, t); };
|
|
728
|
+
|
|
729
|
+
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 hook for Claude Code, Codex, Gemini CLI and Cursor, and a plugin for OpenCode
|
|
730
|
+
dibs guard install [--for tools] [--settings file] add the hook to ~/.claude/settings.json (backup kept)
|
|
731
|
+
--for codex,gemini,cursor,opencode (and claude): each tool's own hooks file instead, or OpenCode's plugins folder
|
|
732
|
+
dibs guard remove [--for tools] [--settings file] take it out again
|
|
733
|
+
dibs guard status [--for tools] [--settings file] [--json] which tools it covers (exit 1 if none; --json always exits 0)
|
|
612
734
|
dibs guard check "<command>" what the hook would do with a command
|
|
613
735
|
dibs guard serve answer the hook from one running process (dibs service install guard keeps it up)
|
|
614
|
-
The hook reads Claude Code's JSON on stdin: dibs guard < input.json`;
|
|
736
|
+
The hook reads Claude Code's JSON on stdin (or Codex's, Gemini CLI's, Cursor's): dibs guard < input.json`;
|
|
615
737
|
|
|
616
|
-
// What `dibs guard status --json` prints, for dibs web too.
|
|
617
|
-
export function guardJson(file = SETTINGS) {
|
|
738
|
+
// What `dibs guard status --json` prints, for dibs web too. tools: the other agent tools, when asked for.
|
|
739
|
+
export function guardJson(file = SETTINGS, tools = null) {
|
|
618
740
|
const h = installed(file);
|
|
619
741
|
const s = readSettings(file);
|
|
620
742
|
const agents = dibsConfig().agents;
|
|
621
743
|
return { installed: !!h, file, command: h?.command ?? null, complete: !!h && complete(s, h.command),
|
|
622
|
-
matchers:
|
|
623
|
-
|
|
744
|
+
matchers: events(CLAUDE).flatMap(ev => ours(s, ev).map(g => ({ event: ev, matcher: g.matcher ?? null }))),
|
|
745
|
+
// Always never since 0.0.191 (respond): kept because the Mac app reads it.
|
|
746
|
+
rewrite: 'never',
|
|
747
|
+
subagents: Number(agents?.slots) > 0 ? { slots: Number(agents.slots) } : null, ...(tools && { tools }) };
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
// The Claude Code half of dibs guard status.
|
|
751
|
+
function claudeStatus(file, h) {
|
|
752
|
+
const agents = dibsConfig().agents;
|
|
753
|
+
if (!h) return `dibs guard is off: it isn't in ${file}. Turn it on: dibs guard install`;
|
|
754
|
+
return [`dibs guard is on (in ${file}).`,
|
|
755
|
+
` Heavy commands an agent runs outside dibs: ${guardConfig() === false || guardConfig().commands === false ? 'let through (switched off in config.json)' : 'turned away, with the dibs run line to send instead'}.`,
|
|
756
|
+
` Edits to files another agent reserved: ${guardConfig().files === false ? 'let through (guard.files is false in config.json)' : 'turned away'}.`,
|
|
757
|
+
' 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.',
|
|
758
|
+
` Merges into main and pushes to it in a repo whose .dibs.json says "reviewBeforeMerge": ${guardConfig().reviews === false ? 'let through (guard.reviews is false in config.json)' : 'turned away until another agent approves that commit (dibs review)'}.`,
|
|
759
|
+
` 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)'}.`,
|
|
760
|
+
...(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']),
|
|
761
|
+
` The hook: ${h.command}`].join('\n');
|
|
624
762
|
}
|
|
625
763
|
|
|
764
|
+
// One line for each other tool.
|
|
765
|
+
const toolLine = st => (st.installed
|
|
766
|
+
? `${st.name}: on (in ${st.file}).${st.complete ? '' : ` An older install: dibs guard install --for ${st.tool}.`}${st.note ? ` ${st.note}.` : ''}`
|
|
767
|
+
: st.viaClaude ? `${st.name}: on through the Claude Code hook (cursor-agent runs the hooks in Claude Code's settings.json too). ${st.note}.`
|
|
768
|
+
: `${st.name}: off. Turn it on: dibs guard install --for ${st.tool}`);
|
|
769
|
+
|
|
626
770
|
// dibs guard [install|remove|status|check]. With no verb and JSON piped in, be the hook.
|
|
627
|
-
export function guard(args) {
|
|
771
|
+
export async function guard(args) {
|
|
628
772
|
const reply = (msg, code = 0) => { (code ? process.stderr : process.stdout).write(`${msg}\n`); process.exitCode = code; };
|
|
629
773
|
const at = args.indexOf('--settings');
|
|
630
|
-
const
|
|
631
|
-
if (at >= 0 && !
|
|
774
|
+
const given = at >= 0 ? args[at + 1] : null;
|
|
775
|
+
if (at >= 0 && !given) return reply('--settings needs a path', 2);
|
|
776
|
+
const fi = args.indexOf('--for');
|
|
777
|
+
const tools = fi >= 0 ? String(args[fi + 1] || '').split(',').filter(Boolean) : null;
|
|
632
778
|
const verb = args[0];
|
|
633
779
|
try {
|
|
634
780
|
if (!verb) return process.stdin.isTTY ? reply(USAGE) : hook();
|
|
635
781
|
if (verb === 'serve') return import('./guardd.mjs').then(m => m.serveGuard());
|
|
636
|
-
if (verb === 'install') return reply(`dibs guard: ${install(file)}`);
|
|
637
|
-
if (verb === 'remove') { const r = remove(file); return r ? reply(`dibs guard: ${r}`) : reply(`dibs guard: not installed in ${file}`, 1); }
|
|
638
|
-
if (verb === 'status') {
|
|
639
|
-
const h = installed(file);
|
|
640
|
-
const mode = guardConfig().rewrite || 'bypass';
|
|
641
|
-
const agents = dibsConfig().agents;
|
|
642
|
-
// For the Mac app: the same facts as an object, exit 0 either way.
|
|
643
|
-
if (args.includes('--json')) return reply(JSON.stringify(guardJson(file), null, 1));
|
|
644
|
-
if (!h) return reply(`dibs guard is off: it isn't in ${file}. Turn it on: dibs guard install`, 1);
|
|
645
|
-
return reply([`dibs guard is on (in ${file}).`,
|
|
646
|
-
` 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`}.`,
|
|
647
|
-
` Edits to files another agent reserved: ${guardConfig().files === false ? 'let through (guard.files is false in config.json)' : 'turned away'}.`,
|
|
648
|
-
' 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.',
|
|
649
|
-
` 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)'}.`,
|
|
650
|
-
...(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']),
|
|
651
|
-
` The hook: ${h.command}`].join('\n'));
|
|
652
|
-
}
|
|
653
782
|
if (verb === 'check') {
|
|
654
783
|
const plan = check(args.slice(1).join(' '), { rules: rulesFrom(guardConfig()) });
|
|
655
784
|
return reply(plan ? `${plan.hits.map(h => h.res).join(' + ')}: ${plan.command}` : 'leave alone');
|
|
656
785
|
}
|
|
657
|
-
return reply(USAGE, 2);
|
|
786
|
+
if (!['install', 'remove', 'status'].includes(verb)) return reply(USAGE, 2);
|
|
787
|
+
const v = await import('./vendors.mjs');
|
|
788
|
+
const known = ['claude', ...v.NAMES];
|
|
789
|
+
if (tools && (!tools.length || tools.some(x => !known.includes(x)))) return reply(`--for takes ${known.join(', ')}, or several with commas`, 2);
|
|
790
|
+
if (given && tools?.length > 1) return reply('--settings names one file: give --for one tool with it', 2);
|
|
791
|
+
const only = tools || ['claude'];
|
|
792
|
+
// --settings names Claude Code's file, or the one tool --for names.
|
|
793
|
+
const fileOf = x => (given && (tools ? tools[0] === x : x === 'claude') ? given : x === 'claude' ? SETTINGS : v.TOOLS[x].file());
|
|
794
|
+
if (verb === 'install') return reply(only.map(x => `dibs guard${x === 'claude' ? '' : ` for ${v.TOOLS[x].name}`}: ${x === 'claude' ? install(fileOf(x)) : v.installFor(x, fileOf(x))}`
|
|
795
|
+
+ (v.TOOLS[x]?.note ? `. ${v.TOOLS[x].note}` : '')).join('\n'));
|
|
796
|
+
if (verb === 'remove') {
|
|
797
|
+
const done = only.map(x => [x, x === 'claude' ? remove(fileOf(x)) : v.removeFor(x, fileOf(x))]);
|
|
798
|
+
const lines = done.map(([x, r]) => `dibs guard${x === 'claude' ? '' : ` for ${v.TOOLS[x].name}`}: ${r || `not installed in ${fileOf(x)}`}`);
|
|
799
|
+
return reply(lines.join('\n'), done.every(([, r]) => r) ? 0 : 1);
|
|
800
|
+
}
|
|
801
|
+
// status: Claude Code first, as before, then each other tool; with --for, only those.
|
|
802
|
+
const shown = tools || known;
|
|
803
|
+
const others = shown.filter(x => x !== 'claude').map(x => v.statusFor(x, fileOf(x)));
|
|
804
|
+
const file = fileOf('claude');
|
|
805
|
+
const h = installed(file);
|
|
806
|
+
if (args.includes('--json')) return reply(JSON.stringify(guardJson(file, others), null, 1));
|
|
807
|
+
const lines = [...(shown.includes('claude') ? [claudeStatus(file, h)] : []), ...others.map(st => (tools ? '' : ' ') + toolLine(st))];
|
|
808
|
+
if (!tools && others.length) lines.splice(1, 0, 'Other agent tools:');
|
|
809
|
+
const any = (shown.includes('claude') && h) || others.some(st => st.installed || st.viaClaude);
|
|
810
|
+
return reply(lines.join('\n'), any ? 0 : 1);
|
|
658
811
|
} catch (e) { return reply(`dibs guard: ${e.message}`, 1); }
|
|
659
812
|
}
|
package/src/guardd.mjs
CHANGED
|
@@ -33,6 +33,9 @@ const READY = 2;
|
|
|
33
33
|
// client that gets no answer then starts Node, which must still fit in Claude
|
|
34
34
|
// Code's 5 s hook timeout.
|
|
35
35
|
const CALL_LIMIT = 1500;
|
|
36
|
+
// Slots in the list of running workers that src/lock.mjs reads to tell a sibling's lock from a dead
|
|
37
|
+
// one's. Two wait loaded, and each call holds one for at most CALL_LIMIT: more than enough.
|
|
38
|
+
const THREAD_SLOTS = 64;
|
|
36
39
|
// No hook input comes near this; a client sending more is cut off.
|
|
37
40
|
const MAX_FRAME = 8 * 1024 ** 2;
|
|
38
41
|
|
|
@@ -50,8 +53,12 @@ export function frame(buf) {
|
|
|
50
53
|
export async function serveGuard() {
|
|
51
54
|
await singleInstance(PIDFILE, 'a resident guard is already running here');
|
|
52
55
|
const ready = [], waiting = [];
|
|
56
|
+
const threads = new Int32Array(new SharedArrayBuffer(4 * THREAD_SLOTS));
|
|
53
57
|
const warm = () => {
|
|
54
|
-
const w = new Worker(WORKER, { execArgv: [] });
|
|
58
|
+
const w = new Worker(WORKER, { execArgv: [], workerData: { threads } });
|
|
59
|
+
const slot = threads.indexOf(0);
|
|
60
|
+
if (slot >= 0) Atomics.store(threads, slot, w.threadId);
|
|
61
|
+
w.once('exit', () => { if (slot >= 0) Atomics.store(threads, slot, 0); });
|
|
55
62
|
w.once('message', () => { const next = waiting.shift(); next ? next(w) : ready.push(w); });
|
|
56
63
|
w.once('error', e => log(`a guard worker failed to load: ${e.message}`));
|
|
57
64
|
};
|
package/src/halt.mjs
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
// dibs halt: every agent here holds off starting new work for a while. On 2026-11-24 the person
|
|
2
|
+
// wanted every agent to stop for 7 minutes and had to ask one agent to relay that to each of the
|
|
3
|
+
// others in turn. Until it lifts, no new dibs job starts on this machine (src/schedule.mjs decide:
|
|
4
|
+
// a run or hold waits in line, as for any other wait); jobs already running go on. It's the
|
|
5
|
+
// state's optional halt field, { at, until, reason, by? }, dropped by the first state read past
|
|
6
|
+
// until (src/state.mjs reap), and every running agent hears of it in one message (src/talk.mjs tellAll).
|
|
7
|
+
import { withState, peek } from './state.mjs';
|
|
8
|
+
import { halted, haltUntil, haltBy } from './schedule.mjs';
|
|
9
|
+
import { actor, logChange } from './owner.mjs';
|
|
10
|
+
import { tellAll, toldLine } from './talk.mjs';
|
|
11
|
+
import { deadline, ms, die, now, dur } from './util.mjs';
|
|
12
|
+
|
|
13
|
+
const USAGE = 'dibs halt --for 7m -m "why" (or --until 14:30; with no time, until dibs halt off)';
|
|
14
|
+
|
|
15
|
+
// What an agent hears, and the person reads back, about a halt h.
|
|
16
|
+
const heldLine = h => `No new dibs job starts on this machine ${haltUntil(h)} (set by ${haltBy(h)}).`;
|
|
17
|
+
const heldText = h => `${heldLine(h)} Jobs already running go on. Anything you start now waits in line and starts by itself when it lifts.`;
|
|
18
|
+
|
|
19
|
+
export function halt(args) {
|
|
20
|
+
const o = { words: [] };
|
|
21
|
+
for (let i = 0; i < args.length; i++) {
|
|
22
|
+
const a = args[i], next = () => args[++i] ?? die(`${a} needs a value. Use: ${USAGE}`);
|
|
23
|
+
if (a === '-m' || a === '--msg') o.reason = next().trim();
|
|
24
|
+
else if (a === '--for') o.until = now() + ms(next());
|
|
25
|
+
else if (a === '--until') o.until = deadline(next());
|
|
26
|
+
else if (a === '--json') o.json = true;
|
|
27
|
+
else if (a.startsWith('-')) die(`unknown flag ${a}. Use: ${USAGE}`);
|
|
28
|
+
else o.words.push(a);
|
|
29
|
+
}
|
|
30
|
+
if (o.words[0] === 'off' && o.words.length === 1) return lift(args, o);
|
|
31
|
+
if (o.words.length) die(`dibs halt takes no words but off. Use: ${USAGE}, or dibs halt off`);
|
|
32
|
+
if (o.reason == null && o.until == null) return show(o);
|
|
33
|
+
if (o.until != null && !(o.until > now())) die(`that time has already passed. Use: ${USAGE}`);
|
|
34
|
+
const who = actor();
|
|
35
|
+
// Every agent here stops for it, so they hear why. The person may skip it.
|
|
36
|
+
if (who.agent && !o.reason) die(`say why with -m, which every agent sees: ${USAGE}`);
|
|
37
|
+
const h = { at: now(), until: o.until ?? null, ...(o.reason && { reason: o.reason }), ...((who.agent || who.via || who.person != null) && { by: who.name }), ...(who.person != null && { byPerson: true }) };
|
|
38
|
+
withState(s => { s.halt = h; });
|
|
39
|
+
logChange('halt', { until: h.until, ...(h.reason && { reason: h.reason }) });
|
|
40
|
+
const told = tellAll(heldText(h), 'halt', args);
|
|
41
|
+
if (o.json) return console.log(JSON.stringify({ halt: h, told }));
|
|
42
|
+
console.log(`${heldLine(h)}${h.until != null ? ` That's ${dur(h.until - now())} from now.` : ''} Jobs already running go on.`);
|
|
43
|
+
console.log(told.length ? toldLine(told) : 'No agent is running here now, so nobody was told.');
|
|
44
|
+
console.log('Lift it sooner: dibs halt off');
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function lift(args, o) {
|
|
48
|
+
const had = withState(s => { const h = halted(s); delete s.halt; return h; });
|
|
49
|
+
if (!had) {
|
|
50
|
+
if (o.json) return console.log(JSON.stringify({ halt: null, told: [] }));
|
|
51
|
+
die('No hold on new jobs is on, so there was nothing to lift.', 1);
|
|
52
|
+
}
|
|
53
|
+
logChange('halt off', o.reason ? { reason: o.reason } : {});
|
|
54
|
+
const told = tellAll(`The hold on new dibs jobs is lifted (by ${actor().name}${o.reason ? `: "${o.reason}"` : ''}). Jobs start again as usual.`, 'halt', args);
|
|
55
|
+
if (o.json) return console.log(JSON.stringify({ halt: null, lifted: had, told }));
|
|
56
|
+
console.log(`Lifted: new jobs start again. ${told.length ? toldLine(told) : 'No agent is running here now, so nobody was told.'}`);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function show(o) {
|
|
60
|
+
const h = halted(peek());
|
|
61
|
+
if (o.json) return console.log(JSON.stringify({ halt: h }));
|
|
62
|
+
console.log(h ? `${heldText(h)}\nLift it: dibs halt off` : `No hold on new jobs. Hold every new job for a while: ${USAGE}`);
|
|
63
|
+
}
|