@babylonjs-toolkit/agent 1.2.1 → 1.2.3
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/README.md +34 -21
- package/lib/claude-settings.js +146 -1
- package/lib/doctor.js +21 -4
- package/lib/install.js +67 -4
- package/package.json +1 -1
- package/scripts/hooks/block-sleep.js +138 -0
- package/skills/bt-execute/SKILL.md +99 -117
- package/skills/bt-execute/scripts/dashboard.mjs +441 -24
- package/skills/bt-execute/templates/dashboard/data-schema.md +43 -16
- package/skills/bt-plan/SKILL.md +52 -62
package/README.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# Babylon Toolkit Desktop Agent (1.2.
|
|
1
|
+
# Babylon Toolkit Desktop Agent (1.2.3)
|
|
2
2
|
|
|
3
3
|
The desktop agent owns the entire pipeline end to end — frontend and UI design, gameplay code, shaders, generated art and audio, 3D models in headless Blender, whole game levels and prefabs in a terminal-driven Unity Editor, the interactive glTF export, the web build, the dev server, and visual QA by screenshotting both Unity and the running browser.
|
|
4
4
|
|
|
@@ -72,7 +72,9 @@ copy at all, the skills and persona keep the GitHub addresses and agents read th
|
|
|
72
72
|
The persona names the local folder and keeps GitHub as the fallback for any file that is missing.
|
|
73
73
|
Claude Code asks before reading outside the project, so a global install adds one read-only rule —
|
|
74
74
|
`Read(~/.claude/toolkit/reference/**)` — to `~/.claude/settings.json` (uninstall removes it, and only if
|
|
75
|
-
the installer added it).
|
|
75
|
+
the installer added it). It also adds a Claude Code `PreToolUse` hook on `Bash` that blocks a `sleep N` of 3 seconds
|
|
76
|
+
or more — inside `until` / `while` loops too — and points the agent at the Agent Reference's `wait.mjs`, which waits
|
|
77
|
+
for a port, URL, file, log line or command output instead; uninstall removes only that hook. `bt-agent doctor` checks that every local link resolves and says when GitHub has a
|
|
76
78
|
newer Reference.
|
|
77
79
|
|
|
78
80
|
### Disk usage report
|
|
@@ -301,7 +303,7 @@ start without a spec:
|
|
|
301
303
|
documents/<slug>_plan.md the plan (bt-plan)
|
|
302
304
|
documents/<slug>_autopilot.md the run log (bt-execute)
|
|
303
305
|
documents/<slug>_dashboard.js the dashboard's data, updated task by task
|
|
304
|
-
documents/<slug>_live.js what is happening this minute,
|
|
306
|
+
documents/<slug>_live.js what is happening this minute, written by the helper (git-ignored)
|
|
305
307
|
snapshots/ meaningful snapshots of the build
|
|
306
308
|
tests/ every test the plan's tasks write
|
|
307
309
|
```
|
|
@@ -309,19 +311,24 @@ start without a spec:
|
|
|
309
311
|
`dashboard.html` is a live dashboard for the whole feature. `bt-plan` writes it as a roadmap (every
|
|
310
312
|
phase and task pending, with the time estimate); `bt-execute` updates it **task by task**, not phase
|
|
311
313
|
by phase: a *Now* banner says which task is being worked on and what is happening this minute (the
|
|
312
|
-
|
|
313
|
-
|
|
314
|
+
dashboard helper rewrites a small live-status file each time a task starts, is built, is being verified
|
|
315
|
+
or is done — no agent spends time on it), and each task's result appears the moment it is built. An open tab keeps itself current: it
|
|
314
316
|
re-reads its data in the background (every 10 s during a run, every 30 s otherwise) and refreshes
|
|
315
317
|
only when something changed — a task result, a finished run, the next run starting, or a plan
|
|
316
318
|
reopened because you added a task after it was complete (the dashboard drops back to *paused* and
|
|
317
|
-
the After Action Report is revised when the new work is done). A
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
319
|
+
the After Action Report is revised when the new work is done). A `check` at every phase boundary and
|
|
320
|
+
at run end fails if anything was skipped — a plan without its dashboard, tasks that differ from the plan,
|
|
321
|
+
a *complete* that is not, a visual task with no snapshot, frames saved to `snapshots/` that never reached
|
|
322
|
+
the page, a ticked task with no verifier result. Phase by
|
|
323
|
+
phase and task by task it shows what was actually done, files, tests, verifier verdicts, attempts,
|
|
324
|
+
decisions, deferrals and follow-ups. The snapshots tell the story of the build, taken from the captures
|
|
325
|
+
the work already makes (never an extra session just for a picture): a plan-wide "before" ahead of T1;
|
|
326
|
+
for every visual task a **progression** from the same camera as each meaningful layer lands (a terrain:
|
|
327
|
+
heightmap → textures → roads → trees → foliage → lighting) — the builder's before, milestone and built
|
|
328
|
+
frames, then the verifier's verified frames — played back as a storyboard, plus before/after sliders and
|
|
329
|
+
stills where those prove the point, and one plan-wide before/after in the After Action Report. They reach
|
|
330
|
+
the page while the task is being built: the helper refuses to mark a task built while a frame saved for it
|
|
331
|
+
is not on the dashboard, or a visual task built with no frame at all. When later work
|
|
325
332
|
revises an earlier result, the earlier entry is marked **Updated** with who changed it and why —
|
|
326
333
|
nothing is rewritten silently.
|
|
327
334
|
|
|
@@ -361,13 +368,19 @@ same way.
|
|
|
361
368
|
Execution time is dominated by verification, not by the code edits, so the loop is sized to the
|
|
362
369
|
feature. `bt-spec` records a `size` (small / medium / large); `bt-plan` uses it to set the task
|
|
363
370
|
budget (a small feature is 1–3 tasks in one phase), groups tasks into phases, marks each task's
|
|
364
|
-
`Verify level` (`standard` or `live`), and never pins absolute test counts. By default
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
+
`Verify level` (`standard` or `live`), and never pins absolute test counts. By default every task
|
|
372
|
+
is checked once: the builder writes and runs the task's named tests (in the feature folder's `tests/`)
|
|
373
|
+
and takes one quick look — one capture or one scripted probe, never the full live proof — then **one
|
|
374
|
+
independent verifier per phase** checks it with a scoped charter (Acceptance, the Verify commands, the
|
|
375
|
+
tests re-run and judged for coverage, a diff review for real defects). The verifier is the only live
|
|
376
|
+
checker: it does Unity/browser QA on any task whose correctness shows only at runtime (rendering,
|
|
377
|
+
visuals, interaction, Unity↔Babylon parity) plus one end-to-end check at the end. A failed task goes
|
|
378
|
+
back to the builder that wrote it, and the same verifier — resumed, not a fresh one — re-checks only
|
|
379
|
+
what failed. A queue of three tasks or fewer is built inline, with one verifier at the end; when the
|
|
380
|
+
plan gives tasks `Track:` letters, one builder per track works in parallel on its own files, and a
|
|
381
|
+
phase's verifier starts once all its tracks are built. Agents wait with the Agent Reference's
|
|
382
|
+
`wait.mjs` (never a shell `sleep`) and drive the browser with its `bt-cdp.mjs` — their own headless
|
|
383
|
+
Chrome, never yours.
|
|
371
384
|
Docs are read once by the orchestrator and handed to subagents as a brief instead of every
|
|
372
385
|
subagent re-fetching the Agent Reference.
|
|
373
386
|
|
|
@@ -389,7 +402,7 @@ thresholds, repeats, every engine on every criterion) are opt-in: `/bt-spec --pa
|
|
|
389
402
|
oracles, re-deriving from the plan as it sees fit), live QA on every task with a rendered or
|
|
390
403
|
exported surface, a full fresh re-verify on each fix attempt, and a 5-attempt fix loop. It
|
|
391
404
|
combines with `--auto-pilot`. There is no separate testing subagent in either mode — the
|
|
392
|
-
|
|
405
|
+
builder writes the tests and the independent verifier judges them.
|
|
393
406
|
|
|
394
407
|
### Unattended runs (`/bt-execute --auto-pilot`)
|
|
395
408
|
|
package/lib/claude-settings.js
CHANGED
|
@@ -8,8 +8,20 @@ const path = require('path');
|
|
|
8
8
|
* lives in the home folder, so without an allow rule every session would stop at its first read.
|
|
9
9
|
* This adds one read-only rule for that folder to Claude Code's settings — and removes only that
|
|
10
10
|
* rule on uninstall.
|
|
11
|
+
*
|
|
12
|
+
* It also adds the no-sleep `PreToolUse` hook on `Bash` (`scripts/hooks/block-sleep.js`) the same way:
|
|
13
|
+
* once, in an entry of its own, and on uninstall only that hook is removed.
|
|
11
14
|
*/
|
|
12
15
|
|
|
16
|
+
/** The no-sleep hook script shipped in this package. */
|
|
17
|
+
const BLOCK_SLEEP_SOURCE = path.join(__dirname, '..', 'scripts', 'hooks', 'block-sleep.js');
|
|
18
|
+
|
|
19
|
+
/** Claude Code hook event that runs before every tool call. */
|
|
20
|
+
const PRE_TOOL_USE = 'PreToolUse';
|
|
21
|
+
|
|
22
|
+
/** Tool the no-sleep hook watches. */
|
|
23
|
+
const BASH_MATCHER = 'Bash';
|
|
24
|
+
|
|
13
25
|
function readSettings(file) {
|
|
14
26
|
if (!fs.existsSync(file)) return { settings: {}, exists: false };
|
|
15
27
|
const text = fs.readFileSync(file, 'utf8');
|
|
@@ -74,4 +86,137 @@ function hasAllowRule(file, rule) {
|
|
|
74
86
|
}
|
|
75
87
|
}
|
|
76
88
|
|
|
77
|
-
|
|
89
|
+
/**
|
|
90
|
+
* Where the no-sleep hook lives once installed, and the settings command that runs it. The script is
|
|
91
|
+
* copied to `<claude home>/toolkit/hooks/` — a stable folder beside (never inside) the Agent Reference,
|
|
92
|
+
* which is replaced wholesale on update, and never the npm / npx package folder, which can vanish.
|
|
93
|
+
* @param {string} claudeHome - Claude Code's folder, e.g. `~/.claude`.
|
|
94
|
+
* @returns {{ source: string, script: string, command: string }} The shipped script, its installed
|
|
95
|
+
* copy, and `node "<installed copy>"` with forward slashes on every platform.
|
|
96
|
+
*/
|
|
97
|
+
function blockSleepHook(claudeHome) {
|
|
98
|
+
const script = path.join(claudeHome, 'toolkit', 'hooks', path.basename(BLOCK_SLEEP_SOURCE));
|
|
99
|
+
const command = `node "${script.split(path.sep).join('/')}"`;
|
|
100
|
+
return { source: BLOCK_SLEEP_SOURCE, script, command };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* The `hooks` object and the event's entry list, when both have the shape Claude Code expects.
|
|
105
|
+
* @param {object} settings - Parsed settings.
|
|
106
|
+
* @param {string} event - Hook event name, e.g. `PreToolUse`.
|
|
107
|
+
* @returns {{ hooks: object, entries: object[] }|null} Missing containers come back empty; null when a
|
|
108
|
+
* container holds something else, so the user's settings are never overwritten.
|
|
109
|
+
*/
|
|
110
|
+
function hookEntries(settings, event) {
|
|
111
|
+
const hooks = settings.hooks === undefined ? {} : settings.hooks;
|
|
112
|
+
if (!hooks || typeof hooks !== 'object' || Array.isArray(hooks)) return null;
|
|
113
|
+
const entries = hooks[event] === undefined ? [] : hooks[event];
|
|
114
|
+
if (!Array.isArray(entries)) return null;
|
|
115
|
+
return { hooks, entries };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* Whether one matcher entry runs `command`.
|
|
120
|
+
* @param {object} entry - One `{ matcher, hooks: [...] }` entry.
|
|
121
|
+
* @param {string} command - The hook command to look for.
|
|
122
|
+
* @returns {boolean} True when one of its command hooks is exactly `command`.
|
|
123
|
+
*/
|
|
124
|
+
function entryRuns(entry, command) {
|
|
125
|
+
return Boolean(entry) && Array.isArray(entry.hooks) && entry.hooks.some((hook) => hook && hook.type === 'command' && hook.command === command);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Whether an entry list already runs `command` for `matcher`.
|
|
130
|
+
* @param {object[]} entries - The event's matcher entries.
|
|
131
|
+
* @param {string} matcher - Tool matcher, e.g. `Bash`.
|
|
132
|
+
* @param {string} command - The hook command.
|
|
133
|
+
* @returns {boolean} True when an entry for that matcher runs the command.
|
|
134
|
+
*/
|
|
135
|
+
function entriesRun(entries, matcher, command) {
|
|
136
|
+
return entries.some((entry) => entry && entry.matcher === matcher && entryRuns(entry, command));
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* Add a command hook in an entry of its own (a user's existing entries are never merged into).
|
|
141
|
+
* A settings file that is not valid JSON, or whose `hooks` has another shape, is left alone.
|
|
142
|
+
* @param {string} file - Claude Code `settings.json`.
|
|
143
|
+
* @param {string} command - The hook command, e.g. `node "/abs/block-sleep.js"`.
|
|
144
|
+
* @param {{ event?: string, matcher?: string, dryRun?: boolean }} [options] - Event (default
|
|
145
|
+
* `PreToolUse`), tool matcher (default `Bash`), and dry run (report only).
|
|
146
|
+
* @returns {{ file: string, command: string, action: string, backup?: string|null, note?: string }}
|
|
147
|
+
* `action` is `created`, `updated`, `unchanged` or `skipped`. Side effect: writes the file and a `.bak`.
|
|
148
|
+
*/
|
|
149
|
+
function addHook(file, command, { event = PRE_TOOL_USE, matcher = BASH_MATCHER, dryRun = false } = {}) {
|
|
150
|
+
let current;
|
|
151
|
+
try {
|
|
152
|
+
current = readSettings(file);
|
|
153
|
+
} catch (error) {
|
|
154
|
+
return { file, command, action: 'skipped', note: `not valid JSON (${error.message}) — add the ${event} ${matcher} hook ${command} yourself` };
|
|
155
|
+
}
|
|
156
|
+
const { settings, exists } = current;
|
|
157
|
+
const found = hookEntries(settings, event);
|
|
158
|
+
if (!found) return { file, command, action: 'skipped', note: `hooks.${event} is not in Claude Code's shape — add the ${matcher} hook ${command} yourself` };
|
|
159
|
+
if (entriesRun(found.entries, matcher, command)) return { file, command, action: 'unchanged' };
|
|
160
|
+
const action = exists ? 'updated' : 'created';
|
|
161
|
+
if (dryRun) return { file, command, action };
|
|
162
|
+
const entry = { matcher, hooks: [{ type: 'command', command }] };
|
|
163
|
+
settings.hooks = { ...found.hooks, [event]: [...found.entries, entry] };
|
|
164
|
+
const backup = writeSettings(file, settings, exists);
|
|
165
|
+
return { file, command, action, backup };
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* Remove the command hook, and nothing else: other hooks in its entry stay, and only the entry,
|
|
170
|
+
* event list and `hooks` object that this removal emptied are tidied away.
|
|
171
|
+
* @param {string} file - Claude Code `settings.json`.
|
|
172
|
+
* @param {string} command - The hook command to remove.
|
|
173
|
+
* @param {{ event?: string, dryRun?: boolean }} [options] - Event (default `PreToolUse`) and dry run.
|
|
174
|
+
* @returns {{ file: string, command: string, action: string, backup?: string|null }} `action` is
|
|
175
|
+
* `removed`, `absent` or `skipped`. Side effect: writes the file and a `.bak`.
|
|
176
|
+
*/
|
|
177
|
+
function removeHook(file, command, { event = PRE_TOOL_USE, dryRun = false } = {}) {
|
|
178
|
+
let current;
|
|
179
|
+
try {
|
|
180
|
+
current = readSettings(file);
|
|
181
|
+
} catch {
|
|
182
|
+
return { file, command, action: 'skipped' };
|
|
183
|
+
}
|
|
184
|
+
const { settings, exists } = current;
|
|
185
|
+
const found = hookEntries(settings, event);
|
|
186
|
+
if (!exists || !found || !found.entries.some((entry) => entryRuns(entry, command))) return { file, command, action: 'absent' };
|
|
187
|
+
if (dryRun) return { file, command, action: 'removed' };
|
|
188
|
+
|
|
189
|
+
const entries = [];
|
|
190
|
+
for (const entry of found.entries) {
|
|
191
|
+
if (!entryRuns(entry, command)) {
|
|
192
|
+
entries.push(entry);
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
const remaining = entry.hooks.filter((hook) => !(hook && hook.type === 'command' && hook.command === command));
|
|
196
|
+
if (remaining.length > 0) entries.push({ ...entry, hooks: remaining });
|
|
197
|
+
}
|
|
198
|
+
if (entries.length > 0) settings.hooks[event] = entries;
|
|
199
|
+
else delete settings.hooks[event];
|
|
200
|
+
if (Object.keys(settings.hooks).length === 0) delete settings.hooks;
|
|
201
|
+
|
|
202
|
+
const backup = writeSettings(file, settings, exists);
|
|
203
|
+
return { file, command, action: 'removed', backup };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Whether the settings run `command` as a hook.
|
|
208
|
+
* @param {string} file - Claude Code `settings.json`.
|
|
209
|
+
* @param {string} command - The hook command.
|
|
210
|
+
* @param {{ event?: string, matcher?: string }} [options] - Event (default `PreToolUse`) and matcher (default `Bash`).
|
|
211
|
+
* @returns {boolean} True when an entry for the matcher runs the command; false for a missing or invalid file.
|
|
212
|
+
*/
|
|
213
|
+
function hasHook(file, command, { event = PRE_TOOL_USE, matcher = BASH_MATCHER } = {}) {
|
|
214
|
+
try {
|
|
215
|
+
const found = hookEntries(readSettings(file).settings, event);
|
|
216
|
+
return Boolean(found) && entriesRun(found.entries, matcher, command);
|
|
217
|
+
} catch {
|
|
218
|
+
return false;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
module.exports = { addAllowRule, removeAllowRule, hasAllowRule, blockSleepHook, addHook, removeHook, hasHook };
|
package/lib/doctor.js
CHANGED
|
@@ -7,7 +7,7 @@ const { resolveTargets } = require('./targets');
|
|
|
7
7
|
const { listSkills } = require('./payload');
|
|
8
8
|
const { hasPersona } = require('./persona');
|
|
9
9
|
const { hasCodexNetwork } = require('./codex-config');
|
|
10
|
-
const { hasAllowRule } = require('./claude-settings');
|
|
10
|
+
const { hasAllowRule, blockSleepHook, hasHook } = require('./claude-settings');
|
|
11
11
|
const reference = require('./reference');
|
|
12
12
|
const { resolveTargetPath } = require('./paths');
|
|
13
13
|
const { readSettings } = require('./bridge/config');
|
|
@@ -105,7 +105,8 @@ function doctor(opts = {}) {
|
|
|
105
105
|
/**
|
|
106
106
|
* The local Agent Reference — informational, never part of `ok`: without it agents read the Reference
|
|
107
107
|
* from GitHub. Reports the copy, every local link that does not resolve, a missing Claude Code allow
|
|
108
|
-
* rule,
|
|
108
|
+
* rule, the no-sleep hook (`hook`, with a warning when it is missing), and (for `bt-agent doctor`)
|
|
109
|
+
* whether GitHub has moved on since the copy was made.
|
|
109
110
|
*/
|
|
110
111
|
function checkReference({ mode, projectRoot, resolved, skills, checkSkills, checkRemote }) {
|
|
111
112
|
const dir = reference.referenceDir(mode, projectRoot);
|
|
@@ -117,10 +118,14 @@ function checkReference({ mode, projectRoot, resolved, skills, checkSkills, chec
|
|
|
117
118
|
const links = reference.checkLinks(dir, folders);
|
|
118
119
|
const warnings = links.broken.map((entry) => `broken link: ${entry}`);
|
|
119
120
|
|
|
121
|
+
let hook = null;
|
|
120
122
|
const claude = resolved.selected.find((target) => target.id === 'claude');
|
|
121
123
|
if (claude && mode === 'global') {
|
|
122
|
-
const
|
|
124
|
+
const claudeHome = path.dirname(resolveTargetPath(claude.global.instructions, mode, projectRoot));
|
|
125
|
+
const settingsFile = path.join(claudeHome, 'settings.json');
|
|
123
126
|
if (!hasAllowRule(settingsFile, reference.CLAUDE_READ_RULE)) warnings.push(`${settingsFile} has no ${reference.CLAUDE_READ_RULE} — Claude Code will ask before each read`);
|
|
127
|
+
hook = checkSleepHook(claudeHome, settingsFile);
|
|
128
|
+
if (!hook.present) warnings.push(`${settingsFile} has no working no-sleep hook (${hook.command}) — agents can sleep-poll; run \`bt-agent update\``);
|
|
124
129
|
}
|
|
125
130
|
|
|
126
131
|
let latest = null;
|
|
@@ -128,7 +133,19 @@ function checkReference({ mode, projectRoot, resolved, skills, checkSkills, chec
|
|
|
128
133
|
latest = reference.latestCommit();
|
|
129
134
|
if (latest && latest !== metadata.commit) warnings.push(`GitHub has a newer Agent Reference (${latest.slice(0, 7)}) — run \`bt-agent update\``);
|
|
130
135
|
}
|
|
131
|
-
return { dir, present: true, commit: metadata.commit, installedAt: metadata.installedAt, files: metadata.files, links, latest, warnings };
|
|
136
|
+
return { dir, present: true, commit: metadata.commit, installedAt: metadata.installedAt, files: metadata.files, links, latest, hook, warnings };
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* The no-sleep `PreToolUse` hook: present when the settings run it and its copied script exists.
|
|
141
|
+
* @param {string} claudeHome - Claude Code's folder, e.g. `~/.claude`.
|
|
142
|
+
* @param {string} settingsFile - Its `settings.json`.
|
|
143
|
+
* @returns {{ settingsFile: string, script: string, command: string, present: boolean }} The check.
|
|
144
|
+
*/
|
|
145
|
+
function checkSleepHook(claudeHome, settingsFile) {
|
|
146
|
+
const { script, command } = blockSleepHook(claudeHome);
|
|
147
|
+
const present = hasHook(settingsFile, command) && fs.existsSync(script);
|
|
148
|
+
return { settingsFile, script, command, present };
|
|
132
149
|
}
|
|
133
150
|
|
|
134
151
|
module.exports = { doctor };
|
package/lib/install.js
CHANGED
|
@@ -7,7 +7,7 @@ const { resolveTargets } = require('./targets');
|
|
|
7
7
|
const { listSkills, copyDir } = require('./payload');
|
|
8
8
|
const { applyPersona, removePersona, personaText } = require('./persona');
|
|
9
9
|
const { applyCodexConfig } = require('./codex-config');
|
|
10
|
-
const { addAllowRule, removeAllowRule } = require('./claude-settings');
|
|
10
|
+
const { addAllowRule, removeAllowRule, blockSleepHook, addHook, removeHook } = require('./claude-settings');
|
|
11
11
|
const reference = require('./reference');
|
|
12
12
|
const manifest = require('./manifest');
|
|
13
13
|
const { manifestPath, resolveTargetPath } = require('./paths');
|
|
@@ -61,6 +61,7 @@ function install(opts = {}) {
|
|
|
61
61
|
pruned: [],
|
|
62
62
|
reference: null,
|
|
63
63
|
permissions: [],
|
|
64
|
+
hooks: [],
|
|
64
65
|
manifest: manifestPath(mode, projectRoot),
|
|
65
66
|
};
|
|
66
67
|
|
|
@@ -112,12 +113,15 @@ function install(opts = {}) {
|
|
|
112
113
|
: null;
|
|
113
114
|
}
|
|
114
115
|
|
|
115
|
-
// Claude Code asks before reading outside the project; the global copy gets one read-only allow rule
|
|
116
|
+
// Claude Code asks before reading outside the project; the global copy gets one read-only allow rule,
|
|
117
|
+
// and the no-sleep hook that points agents at the copy's wait.mjs.
|
|
116
118
|
if (localReference && mode === 'global') {
|
|
117
119
|
const claude = resolved.selected.find((target) => target.id === 'claude');
|
|
118
120
|
if (claude) {
|
|
119
|
-
const
|
|
121
|
+
const claudeHome = path.dirname(resolveTargetPath(claude.global.instructions, mode, projectRoot));
|
|
122
|
+
const settingsFile = path.join(claudeHome, 'settings.json');
|
|
120
123
|
report.permissions.push(addAllowRule(settingsFile, reference.CLAUDE_READ_RULE, { dryRun }));
|
|
124
|
+
report.hooks.push(installSleepHook(claudeHome, settingsFile, { dryRun }));
|
|
121
125
|
}
|
|
122
126
|
}
|
|
123
127
|
|
|
@@ -147,6 +151,7 @@ function install(opts = {}) {
|
|
|
147
151
|
: (previous && previous.reference) || undefined,
|
|
148
152
|
// Kept across runs so uninstall can remove a rule an earlier install added.
|
|
149
153
|
permissions: mergePermissions(previous && previous.permissions, report.permissions),
|
|
154
|
+
hooks: mergeHooks(previous && previous.hooks, report.hooks),
|
|
150
155
|
});
|
|
151
156
|
}
|
|
152
157
|
|
|
@@ -162,7 +167,7 @@ function uninstall(opts = {}) {
|
|
|
162
167
|
const { mode = 'global', projectRoot = process.cwd(), dryRun = false, persona = true } = opts;
|
|
163
168
|
|
|
164
169
|
const previous = manifest.read(mode, projectRoot);
|
|
165
|
-
const report = { mode, dryRun, removed: [], persona: [], permissions: [], manifestFound: Boolean(previous) };
|
|
170
|
+
const report = { mode, dryRun, removed: [], persona: [], permissions: [], hooks: [], manifestFound: Boolean(previous) };
|
|
166
171
|
|
|
167
172
|
if (!previous) return report;
|
|
168
173
|
|
|
@@ -194,6 +199,9 @@ function uninstall(opts = {}) {
|
|
|
194
199
|
for (const entry of previous.permissions || []) {
|
|
195
200
|
report.permissions.push(removeAllowRule(entry.file, entry.rule, { dryRun }));
|
|
196
201
|
}
|
|
202
|
+
for (const entry of previous.hooks || []) {
|
|
203
|
+
report.hooks.push(uninstallSleepHook(entry, { dryRun }));
|
|
204
|
+
}
|
|
197
205
|
|
|
198
206
|
if (!dryRun) manifest.remove(mode, projectRoot);
|
|
199
207
|
return report;
|
|
@@ -208,4 +216,59 @@ function mergePermissions(previous, current) {
|
|
|
208
216
|
return [...merged.values()];
|
|
209
217
|
}
|
|
210
218
|
|
|
219
|
+
/**
|
|
220
|
+
* Add the no-sleep hook to Claude Code's settings and copy its script to the stable path the hook runs.
|
|
221
|
+
* The script is refreshed on every install; when the settings cannot be changed it is not copied at all.
|
|
222
|
+
* @param {string} claudeHome - Claude Code's folder, e.g. `~/.claude`.
|
|
223
|
+
* @param {string} settingsFile - Its `settings.json`.
|
|
224
|
+
* @param {{ dryRun?: boolean }} [options] - Dry run: report only, write nothing.
|
|
225
|
+
* @returns {{ file: string, command: string, script: string, action: string }} The `addHook` result
|
|
226
|
+
* plus the installed script path.
|
|
227
|
+
*/
|
|
228
|
+
function installSleepHook(claudeHome, settingsFile, { dryRun = false } = {}) {
|
|
229
|
+
const hook = blockSleepHook(claudeHome);
|
|
230
|
+
const result = { ...addHook(settingsFile, hook.command, { dryRun }), script: hook.script };
|
|
231
|
+
if (result.action === 'skipped' || dryRun) return result;
|
|
232
|
+
fs.mkdirSync(path.dirname(hook.script), { recursive: true });
|
|
233
|
+
fs.copyFileSync(hook.source, hook.script);
|
|
234
|
+
return result;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Remove the no-sleep hook from the settings, delete its copied script, and drop the hooks folder
|
|
239
|
+
* only if that emptied it.
|
|
240
|
+
* @param {{ file: string, command: string, script: string }} entry - What the manifest recorded.
|
|
241
|
+
* @param {{ dryRun?: boolean }} [options] - Dry run: report only, delete nothing.
|
|
242
|
+
* @returns {{ file: string, command: string, script: string, action: string }} The `removeHook`
|
|
243
|
+
* result plus the script path.
|
|
244
|
+
*/
|
|
245
|
+
function uninstallSleepHook(entry, { dryRun = false } = {}) {
|
|
246
|
+
const result = { ...removeHook(entry.file, entry.command, { dryRun }), script: entry.script };
|
|
247
|
+
// Settings that could not be changed still run the hook, so its script stays.
|
|
248
|
+
if (dryRun || result.action === 'skipped' || !entry.script) return result;
|
|
249
|
+
fs.rmSync(entry.script, { force: true });
|
|
250
|
+
try {
|
|
251
|
+
fs.rmdirSync(path.dirname(entry.script));
|
|
252
|
+
} catch {
|
|
253
|
+
/* the folder holds something else — keep it */
|
|
254
|
+
}
|
|
255
|
+
return result;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* The hooks this tool added, by settings file and command, so uninstall removes exactly those.
|
|
260
|
+
* Unlike an allow rule, an `unchanged` hook is ours too: its command runs the script bt-agent copies.
|
|
261
|
+
* @param {object[]|undefined} previous - Hooks recorded by earlier installs.
|
|
262
|
+
* @param {object[]} current - This install's `installSleepHook` results.
|
|
263
|
+
* @returns {{ file: string, command: string, script: string }[]} Deduplicated records.
|
|
264
|
+
*/
|
|
265
|
+
function mergeHooks(previous, current) {
|
|
266
|
+
const merged = new Map();
|
|
267
|
+
const recorded = current.filter((entry) => entry.action !== 'skipped');
|
|
268
|
+
for (const entry of [...(previous || []), ...recorded]) {
|
|
269
|
+
merged.set(`${entry.file}\n${entry.command}`, { file: entry.file, command: entry.command, script: entry.script });
|
|
270
|
+
}
|
|
271
|
+
return [...merged.values()];
|
|
272
|
+
}
|
|
273
|
+
|
|
211
274
|
module.exports = { install, uninstall };
|
package/package.json
CHANGED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Claude Code `PreToolUse` hook on `Bash`: blocks a shell command that sleeps for 3 seconds or more and
|
|
6
|
+
* tells the agent to wait on the condition with `wait.mjs` instead. A blind `sleep 30` (alone, chained,
|
|
7
|
+
* or inside an `until` / `while` / `for` poll loop) is the slowest way to wait: it always costs the full
|
|
8
|
+
* time, even when the server, file or log line was ready a second in.
|
|
9
|
+
*
|
|
10
|
+
* Contract (Claude Code hooks): the tool call arrives as JSON on stdin —
|
|
11
|
+
* `{ "tool_name": "Bash", "tool_input": { "command": "…" } }`. Exit code 2 blocks the call and shows
|
|
12
|
+
* stderr to the agent; exit code 0 lets it run. Anything this hook cannot read exits 0 silently, so a
|
|
13
|
+
* broken hook never blocks work.
|
|
14
|
+
*
|
|
15
|
+
* `sleep` counts only as a command word — at the start of the command or right after `;`, `&&`, `||`,
|
|
16
|
+
* `|`, `&`, `(`, `{`, `$(`, a backtick, a newline, or the keywords `do` / `then` / `else` — so
|
|
17
|
+
* `grep "sleep 30" notes.md` and `node wait.mjs …` are not blocked.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
const fs = require('fs');
|
|
21
|
+
|
|
22
|
+
/** Sleeps of this many seconds or more are blocked; shorter pauses are allowed. */
|
|
23
|
+
const MINIMUM_BLOCKED_SECONDS = 3;
|
|
24
|
+
|
|
25
|
+
/** Exit code that tells Claude Code to block the tool call and show stderr to the agent. */
|
|
26
|
+
const BLOCK_EXIT_CODE = 2;
|
|
27
|
+
|
|
28
|
+
/** Seconds per GNU `sleep` unit suffix; no suffix means seconds. */
|
|
29
|
+
const SECONDS_PER_UNIT = { '': 1, s: 1, m: 60, h: 3600, d: 86400 };
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* `sleep` in command position, with its arguments up to the next shell separator. The argument text is
|
|
33
|
+
* capture group 1.
|
|
34
|
+
*/
|
|
35
|
+
const SLEEP_COMMAND_PATTERN = /(?:^|[;&|({\n`]|\b(?:do|then|else)\s)\s*(?:[\w./-]*\/)?sleep\s+([^;&|(){}\n`]*)/g;
|
|
36
|
+
|
|
37
|
+
/** One `sleep` duration: a whole or decimal number with an optional `s` / `m` / `h` / `d` suffix. */
|
|
38
|
+
const DURATION_PATTERN = /^(\d+(?:\.\d*)?|\.\d+)([smhd]?)$/;
|
|
39
|
+
|
|
40
|
+
/** The installed wait helper, as the agent should run it. */
|
|
41
|
+
const WAIT_SCRIPT = 'node ~/.claude/toolkit/reference/references/scripts/wait.mjs';
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Seconds one `sleep` argument stands for.
|
|
45
|
+
* @param {string} argument - One word after `sleep`, e.g. `30`, `3.5`, `5s`, `1m`, `infinity`.
|
|
46
|
+
* @returns {number|null} Seconds (Infinity for `infinity`), or null when the word is not a duration
|
|
47
|
+
* (an option, a redirect, a `$VARIABLE` whose value cannot be known).
|
|
48
|
+
*/
|
|
49
|
+
function argumentSeconds(argument) {
|
|
50
|
+
if (argument === 'infinity') return Infinity;
|
|
51
|
+
const match = DURATION_PATTERN.exec(argument);
|
|
52
|
+
if (!match) return null;
|
|
53
|
+
const [, amount, unit] = match;
|
|
54
|
+
return Number(amount) * SECONDS_PER_UNIT[unit];
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Total seconds one `sleep` invocation waits. GNU `sleep` adds up several durations (`sleep 1 2` is
|
|
59
|
+
* 3 seconds), so the words are summed until the first one that is not a duration.
|
|
60
|
+
* @param {string} argumentText - Everything after `sleep` up to the next shell separator.
|
|
61
|
+
* @returns {number} Seconds; 0 when no duration can be read.
|
|
62
|
+
*/
|
|
63
|
+
function invocationSeconds(argumentText) {
|
|
64
|
+
let total = 0;
|
|
65
|
+
for (const argument of argumentText.trim().split(/\s+/)) {
|
|
66
|
+
const seconds = argumentSeconds(argument);
|
|
67
|
+
if (seconds === null) break;
|
|
68
|
+
total += seconds;
|
|
69
|
+
}
|
|
70
|
+
return total;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* The longest single `sleep` a shell command runs.
|
|
75
|
+
* @param {string} command - The shell command a Bash tool call would run.
|
|
76
|
+
* @returns {number} Seconds of the longest `sleep` in command position; 0 when there is none.
|
|
77
|
+
*/
|
|
78
|
+
function longestSleepSeconds(command) {
|
|
79
|
+
if (typeof command !== 'string') return 0;
|
|
80
|
+
let longest = 0;
|
|
81
|
+
for (const match of command.matchAll(SLEEP_COMMAND_PATTERN)) {
|
|
82
|
+
longest = Math.max(longest, invocationSeconds(match[1]));
|
|
83
|
+
}
|
|
84
|
+
return longest;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Whether the hook blocks this command.
|
|
89
|
+
* @param {string} command - The shell command a Bash tool call would run.
|
|
90
|
+
* @returns {boolean} True when it runs `sleep` for {@link MINIMUM_BLOCKED_SECONDS} seconds or more.
|
|
91
|
+
*/
|
|
92
|
+
function isBlockedSleep(command) {
|
|
93
|
+
return longestSleepSeconds(command) >= MINIMUM_BLOCKED_SECONDS;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* The message the agent sees when a command is blocked: why, and the `wait.mjs` call for each kind of wait.
|
|
98
|
+
* @param {number} seconds - The blocked sleep's length in seconds.
|
|
99
|
+
* @returns {string} Multi-line stderr text ending in a newline.
|
|
100
|
+
*/
|
|
101
|
+
function blockMessage(seconds) {
|
|
102
|
+
const length = Number.isFinite(seconds) ? `${seconds}s` : 'an endless';
|
|
103
|
+
return [
|
|
104
|
+
`Blocked: a ${length} shell sleep waits blind. Wait on the condition with wait.mjs instead (it polls inside Node,`,
|
|
105
|
+
'exits 0 as soon as the condition holds and 1 with a reason on timeout):',
|
|
106
|
+
` ${WAIT_SCRIPT} port <n> --timeout <s>`,
|
|
107
|
+
` ${WAIT_SCRIPT} url <url> [--status 200] --timeout <s>`,
|
|
108
|
+
` ${WAIT_SCRIPT} file <path> --timeout <s>`,
|
|
109
|
+
` ${WAIT_SCRIPT} log <path> <regex> --timeout <s>`,
|
|
110
|
+
` ${WAIT_SCRIPT} cmd "<command>" --match <regex> [--fail <regex>] [--interval <s>] --timeout <s>`,
|
|
111
|
+
`Long-running commands: run them in the foreground with a generous timeout. Pauses under ${MINIMUM_BLOCKED_SECONDS}s are allowed.`,
|
|
112
|
+
'',
|
|
113
|
+
].join('\n');
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Entry point: read the tool call from stdin and block a long sleep. Unreadable input exits 0.
|
|
118
|
+
* @returns {void} Sets `process.exitCode` (never calls `process.exit`, so stderr is flushed first).
|
|
119
|
+
*/
|
|
120
|
+
function main() {
|
|
121
|
+
let toolCall;
|
|
122
|
+
try {
|
|
123
|
+
toolCall = JSON.parse(fs.readFileSync(0, 'utf8'));
|
|
124
|
+
} catch {
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
if (!toolCall || typeof toolCall !== 'object') return;
|
|
128
|
+
if (toolCall.tool_name !== undefined && toolCall.tool_name !== 'Bash') return;
|
|
129
|
+
const command = toolCall.tool_input && toolCall.tool_input.command;
|
|
130
|
+
const seconds = longestSleepSeconds(command);
|
|
131
|
+
if (seconds < MINIMUM_BLOCKED_SECONDS) return;
|
|
132
|
+
process.stderr.write(blockMessage(seconds));
|
|
133
|
+
process.exitCode = BLOCK_EXIT_CODE;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
if (require.main === module) main();
|
|
137
|
+
|
|
138
|
+
module.exports = { MINIMUM_BLOCKED_SECONDS, BLOCK_EXIT_CODE, longestSleepSeconds, isBlockedSleep, blockMessage };
|