@dibssoftware/dibs 0.0.179 → 0.0.181
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 +31 -2
- package/README.md +4 -2
- package/bin/dibs-guard.mjs +10 -1
- package/bin/dibs.mjs +37 -10
- 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 +24 -9
- 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 +6 -6
- package/src/acquire.mjs +93 -27
- package/src/agents.mjs +7 -22
- package/src/alerts.mjs +75 -29
- package/src/board.mjs +1 -2
- package/src/broker.mjs +26 -11
- package/src/commands.mjs +37 -14
- package/src/config.mjs +21 -4
- package/src/cool.mjs +105 -10
- package/src/diskwarn.mjs +4 -0
- package/src/events.mjs +10 -1
- package/src/files.mjs +52 -88
- package/src/guard.mjs +76 -30
- package/src/guardd.mjs +97 -0
- package/src/guardw.mjs +19 -0
- package/src/later.mjs +20 -25
- package/src/lock.mjs +308 -0
- package/src/measure.mjs +27 -7
- package/src/ondemand.mjs +5 -2
- package/src/override.mjs +39 -2
- package/src/plain.mjs +2 -2
- package/src/platform.mjs +175 -42
- package/src/preempt.mjs +51 -3
- package/src/primer.mjs +1 -1
- package/src/proc.mjs +45 -5
- package/src/questions.mjs +8 -22
- package/src/relay.mjs +137 -32
- package/src/remote.mjs +12 -8
- package/src/schedule.mjs +139 -26
- package/src/serve.mjs +16 -3
- package/src/service.mjs +9 -4
- package/src/state.mjs +139 -47
- package/src/stats.mjs +3 -2
- package/src/talk.mjs +169 -83
- package/src/trust.mjs +7 -1
- package/src/util.mjs +28 -2
- package/src/version.mjs +1 -1
- package/src/web.mjs +17 -26
- package/src/worker.mjs +2 -1
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');
|
|
@@ -20,11 +24,17 @@ const LOG = path.join(DIBS_HOME, 'guard.log');
|
|
|
20
24
|
// Who has a message from the person waiting: { session_id: [agent ids] }, or
|
|
21
25
|
// no file at all. src/talk.mjs keeps it; the hook only reads it.
|
|
22
26
|
const INBOX = path.join(DIBS_HOME, 'inbox.json');
|
|
23
|
-
// dibs listen's list of who listens (src/talk.mjs), and the
|
|
27
|
+
// dibs listen's list of who listens (src/talk.mjs), and the sessions kept going at a stop to start one.
|
|
24
28
|
const LISTENERS = path.join(DIBS_HOME, 'listeners.json');
|
|
25
|
-
const
|
|
26
|
-
// Sessions remembered in
|
|
29
|
+
const REARMED = path.join(DIBS_HOME, 'rearm.json');
|
|
30
|
+
// Sessions remembered in REARMED: enough for every session a machine runs in a day or two.
|
|
27
31
|
const REMIND_KEEP = 200;
|
|
32
|
+
// Stops in a row a session is kept going with no listener starting in between. A listen that
|
|
33
|
+
// can't start (dibs broken, no background tasks here) would otherwise wake the agent, fail, and
|
|
34
|
+
// keep it going again at every stop, for ever; after this many it's left alone until one starts.
|
|
35
|
+
const REARM_MAX = 3;
|
|
36
|
+
// A Bash background task running dibs listen, however dibs was named: dibs, ~/bin/dibs, dibs.mjs.
|
|
37
|
+
const LISTEN_CMD = /(^|[\s;&|(/'"])dibs(\.mjs)?['"]?\s+listen\b/;
|
|
28
38
|
// The threads themselves, which the hook only searches for a subagent's id.
|
|
29
39
|
const MESSAGES = path.join(DIBS_HOME, 'messages.json');
|
|
30
40
|
const SETTINGS = process.env.DIBS_CLAUDE_SETTINGS || path.join(os.homedir(), '.claude', 'settings.json');
|
|
@@ -316,7 +326,8 @@ export function rulesFrom(guardCfg) {
|
|
|
316
326
|
return { ...RULES, ...(guardCfg?.rules || {}) };
|
|
317
327
|
}
|
|
318
328
|
|
|
319
|
-
|
|
329
|
+
// A ~ inside a word stays as typed (Windows short names: C:/Users/RUNNER~1); only a leading one expands.
|
|
330
|
+
const quote = s => (/^[\w@%+=:,./-][\w@%+=:,./~-]*$/.test(s) ? s : `'${s.replace(/'/g, `'\\''`)}'`);
|
|
320
331
|
|
|
321
332
|
// What to do with a command: null to leave it alone, or the rewritten command
|
|
322
333
|
// and what was caught.
|
|
@@ -359,6 +370,8 @@ export function check(cmd, { rules = RULES, dibs = 'dibs' } = {}) {
|
|
|
359
370
|
// Where in dibs it broke and on what kind of call, never the command itself
|
|
360
371
|
// (it can hold secrets): enough to find the bug, as `dibs alerts` reports it.
|
|
361
372
|
function logError(e, input) {
|
|
373
|
+
// A full disk is no bug in dibs: the call goes through, and the board already says the disk is full.
|
|
374
|
+
if (e?.code === 'ENOSPC' || e?.code === 'EDQUOT') return;
|
|
362
375
|
const at = String(e?.stack || '').split('\n').find(l => l.includes('/src/'))?.match(/\/(src\/[\w.]+:\d+)/)?.[1];
|
|
363
376
|
const on = input?.hook_event_name ? ` [${input.hook_event_name}${input.tool_name ? ` ${input.tool_name}` : ''}]` : '';
|
|
364
377
|
try { fs.appendFileSync(LOG, `${new Date().toISOString()} ${String(e?.message || e).split('\n')[0]}${at ? ` at ${at}` : ''}${on}\n`); } catch {}
|
|
@@ -379,7 +392,7 @@ const AGENT_EVENT = input => ['Agent', 'Task'].includes(input?.tool_name) || ['S
|
|
|
379
392
|
function dibsCommand() {
|
|
380
393
|
for (const dir of (process.env.PATH || '').split(path.delimiter))
|
|
381
394
|
if (dir && fs.existsSync(path.join(dir, 'dibs'))) return 'dibs';
|
|
382
|
-
return
|
|
395
|
+
return viaNode(path.join(ROOT, 'bin', 'dibs.mjs'));
|
|
383
396
|
}
|
|
384
397
|
|
|
385
398
|
// Rewrite only where "allow" approves nothing the session wouldn't have run
|
|
@@ -434,36 +447,67 @@ function talked(input) {
|
|
|
434
447
|
try { return fs.readFileSync(MESSAGES, 'utf8').includes(JSON.stringify(input.agent_id)); } catch { return false; }
|
|
435
448
|
}
|
|
436
449
|
|
|
437
|
-
// A main agent ending its turn
|
|
438
|
-
//
|
|
439
|
-
//
|
|
440
|
-
//
|
|
441
|
-
//
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
450
|
+
// A main agent ending its turn with no dibs listen running is kept going to start one, so it
|
|
451
|
+
// never has to remember: a message sent while it waits wakes it. Claude Code (2.1.3xx) lists the
|
|
452
|
+
// session's running background tasks at a stop, which says it outright; older versions don't,
|
|
453
|
+
// so then listeners.json does. Never for a subagent or teammate (agent_id: Stop is the main
|
|
454
|
+
// thread's, but a stray one costs nothing to skip), never on the continuation a stop hook caused
|
|
455
|
+
// (stop_hook_active: at most once a turn), never for Codex (turn_id) or the SDK and -p (their
|
|
456
|
+
// background tasks die with the run), and at most REARM_MAX stops in a row with no listener
|
|
457
|
+
// starting in between. Claude Code fires no Stop for an interrupt or a session that's ending.
|
|
458
|
+
// Returns the line to keep the agent going with, or null.
|
|
459
|
+
function rearm(input, env = process.env) {
|
|
460
|
+
if (input?.hook_event_name !== 'Stop' || input.stop_hook_active || input.agent_id || 'turn_id' in input) return null;
|
|
461
|
+
const sid = input.session_id;
|
|
462
|
+
if (typeof sid !== 'string' || !sid) return null;
|
|
463
|
+
if (/^sdk-/.test(env.CLAUDE_CODE_ENTRYPOINT || '') || /^(1|true|yes|on)$/i.test(env.CLAUDE_CODE_DISABLE_BACKGROUND_TASKS || '')) return null;
|
|
464
|
+
let l = null;
|
|
465
|
+
try { l = JSON.parse(fs.readFileSync(LISTENERS, 'utf8'))[`${sid}|main`] || null; } catch {}
|
|
466
|
+
if (Array.isArray(input.background_tasks)) {
|
|
467
|
+
if (input.background_tasks.some(t => LISTEN_CMD.test(String(t?.command || '')))) return null;
|
|
468
|
+
} else if (Number.isInteger(l?.pid)) {
|
|
469
|
+
try { process.kill(l.pid, 0); return null; } catch (e) { if (e.code !== 'ESRCH') return null; }
|
|
470
|
+
}
|
|
448
471
|
let told = {};
|
|
449
|
-
try { told = JSON.parse(fs.readFileSync(
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
472
|
+
try { told = JSON.parse(fs.readFileSync(REARMED, 'utf8')); } catch {}
|
|
473
|
+
const last = told[sid];
|
|
474
|
+
// A listener that started since the last time counts the stops from zero again.
|
|
475
|
+
const n = last && !(l?.at > last.at) ? last.n : 0;
|
|
476
|
+
if (n >= REARM_MAX) return null;
|
|
477
|
+
delete told[sid];
|
|
478
|
+
told[sid] = { n: n + 1, at: Date.now() };
|
|
453
479
|
const keys = Object.keys(told);
|
|
454
480
|
for (const k of keys.slice(0, Math.max(0, keys.length - REMIND_KEEP))) delete told[k];
|
|
455
|
-
fs.
|
|
456
|
-
fs.
|
|
457
|
-
|
|
481
|
+
fs.mkdirSync(DIBS_HOME, { recursive: true });
|
|
482
|
+
fs.writeFileSync(`${REARMED}.${process.pid}`, JSON.stringify(told));
|
|
483
|
+
fs.renameSync(`${REARMED}.${process.pid}`, REARMED);
|
|
484
|
+
return 'dibs: no dibs listen is running for you, so a message sent while you wait can\'t wake you. ' +
|
|
485
|
+
'Before you end your turn, start it with the Bash tool and run_in_background: dibs listen';
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
// The re-arm line added to a stop's answer: alone, or after the messages handed over at that stop.
|
|
489
|
+
// additionalContext keeps the agent going without the "blocking error" a decision: 'block' shows.
|
|
490
|
+
function withRearm(input, out) {
|
|
491
|
+
const line = rearm(input);
|
|
492
|
+
if (!line) return out;
|
|
493
|
+
const prev = out?.hookSpecificOutput?.additionalContext;
|
|
494
|
+
return { ...out, hookSpecificOutput: { ...out?.hookSpecificOutput, hookEventName: 'Stop', additionalContext: [prev, line].filter(Boolean).join('\n\n') } };
|
|
458
495
|
}
|
|
459
496
|
|
|
460
497
|
// The hook itself: Claude Code's JSON on stdin, a decision on stdout. Any
|
|
461
498
|
// failure prints nothing, which leaves the command to the normal permission flow.
|
|
462
499
|
export async function hook() {
|
|
463
|
-
let
|
|
500
|
+
let input;
|
|
501
|
+
try { input = JSON.parse(fs.readFileSync(0, 'utf8')); } catch (e) { return logError(e, null); }
|
|
502
|
+
const out = await decide(input);
|
|
503
|
+
if (out) process.stdout.write(JSON.stringify(out) + '\n');
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
// What the hook answers for one event, or null to say nothing. The resident
|
|
507
|
+
// guard (src/guardd.mjs) runs this too, in a fresh worker per call.
|
|
508
|
+
export async function decide(input) {
|
|
509
|
+
let out = null;
|
|
464
510
|
try {
|
|
465
|
-
input = JSON.parse(fs.readFileSync(0, 'utf8'));
|
|
466
|
-
subagentState(input);
|
|
467
511
|
if (AGENT_EVENT(input)) out = (await import('./agents.mjs')).agentHook(input, dibsConfig());
|
|
468
512
|
else if (!STOP_EVENT(input) && !START_EVENT(input)) out = respond(input, guardConfig(), dibsCommand());
|
|
469
513
|
} catch (e) { logError(e, input); }
|
|
@@ -473,8 +517,8 @@ export async function hook() {
|
|
|
473
517
|
if (queuedFor(input)) out = (await import('./talk.mjs')).deliver(input, out);
|
|
474
518
|
else if (input?.hook_event_name === 'SubagentStop' && talked(input)) (await import('./talk.mjs')).finished(input);
|
|
475
519
|
} catch (e) { logError(e, input); }
|
|
476
|
-
try {
|
|
477
|
-
|
|
520
|
+
try { out = withRearm(input, out); } catch (e) { logError(e, input); }
|
|
521
|
+
return out;
|
|
478
522
|
}
|
|
479
523
|
|
|
480
524
|
const isGuard = h => h?.type === 'command' && /dibs-guard\.mjs['"]?$|\bdibs(\.mjs)?['"]? guard['"]?$/.test(String(h.command || '').trim());
|
|
@@ -542,7 +586,7 @@ export function installed(file = SETTINGS) {
|
|
|
542
586
|
return ours(readSettings(file)).flatMap(g => g.hooks).find(isGuard) || null;
|
|
543
587
|
}
|
|
544
588
|
|
|
545
|
-
export function install(file = SETTINGS, command =
|
|
589
|
+
export function install(file = SETTINGS, command = viaNode(HOOK_BIN)) {
|
|
546
590
|
const s = readSettings(file);
|
|
547
591
|
const had = installed(file);
|
|
548
592
|
if (complete(s, command)) return `already installed in ${file}`;
|
|
@@ -566,6 +610,7 @@ const USAGE = `dibs guard: catch heavy commands an agent runs outside dibs, turn
|
|
|
566
610
|
dibs guard remove [--settings file] take it out again
|
|
567
611
|
dibs guard status [--settings file] [--json] is it installed (exit 1 if not; --json always exits 0)
|
|
568
612
|
dibs guard check "<command>" what the hook would do with a command
|
|
613
|
+
dibs guard serve answer the hook from one running process (dibs service install guard keeps it up)
|
|
569
614
|
The hook reads Claude Code's JSON on stdin: dibs guard < input.json`;
|
|
570
615
|
|
|
571
616
|
// What `dibs guard status --json` prints, for dibs web too.
|
|
@@ -587,6 +632,7 @@ export function guard(args) {
|
|
|
587
632
|
const verb = args[0];
|
|
588
633
|
try {
|
|
589
634
|
if (!verb) return process.stdin.isTTY ? reply(USAGE) : hook();
|
|
635
|
+
if (verb === 'serve') return import('./guardd.mjs').then(m => m.serveGuard());
|
|
590
636
|
if (verb === 'install') return reply(`dibs guard: ${install(file)}`);
|
|
591
637
|
if (verb === 'remove') { const r = remove(file); return r ? reply(`dibs guard: ${r}`) : reply(`dibs guard: not installed in ${file}`, 1); }
|
|
592
638
|
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}`); }
|