@babylonjs-toolkit/agent 1.1.64 → 1.1.68

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.
Files changed (33) hide show
  1. package/README.md +35 -5
  2. package/bin/bt-agent.js +64 -4
  3. package/lib/claude-settings.js +77 -0
  4. package/lib/doctor.js +36 -0
  5. package/lib/install.js +59 -3
  6. package/lib/persona.js +21 -2
  7. package/lib/reference.js +400 -0
  8. package/package.json +1 -1
  9. package/persona.md +1 -1
  10. package/scripts/postinstall.js +6 -0
  11. package/skills/bt-design/references/3d-hero-scroll.md +2 -2
  12. package/skills/bt-execute/SKILL.md +7 -7
  13. package/skills/bt-execute/templates/dashboard/dashboard.html +96 -21
  14. package/skills/bt-execute/templates/dashboard/data-schema.md +4 -3
  15. package/skills/bt-gauntlet/SKILL.md +2 -2
  16. package/skills/bt-gauntlet/references/unity-pipeline.md +1 -1
  17. package/skills/bt-gauntlet/references/workspace.md +1 -1
  18. package/skills/bt-plan/SKILL.md +2 -2
  19. package/skills/bt-profile/SKILL.md +275 -0
  20. package/skills/bt-profile/scripts/analyze.mjs +683 -0
  21. package/skills/bt-profile/scripts/compare.mjs +87 -0
  22. package/skills/bt-profile/scripts/lib/probe.mjs +225 -0
  23. package/skills/bt-profile/scripts/lib/progress-panel.mjs +275 -0
  24. package/skills/bt-profile/scripts/lib/symbolize.mjs +356 -0
  25. package/skills/bt-profile/scripts/package.json +10 -0
  26. package/skills/bt-profile/scripts/profile.mjs +517 -0
  27. package/skills/bt-profile/scripts/progress.mjs +385 -0
  28. package/skills/bt-profile/scripts/report.mjs +611 -0
  29. package/skills/bt-profile/templates/census.template.mjs +76 -0
  30. package/skills/bt-profile/templates/scenario.template.mjs +69 -0
  31. package/skills/bt-prototype/SKILL.md +1 -1
  32. package/skills/bt-recon/SKILL.md +2 -2
  33. package/skills/bt-spec/SKILL.md +2 -2
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # Babylon Toolkit Desktop Agent (1.1.64)
1
+ # Babylon Toolkit Desktop Agent (1.1.68)
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
 
@@ -18,9 +18,10 @@ npx @babylonjs-toolkit/agent install
18
18
  ```
19
19
 
20
20
  That installs **every skill** into every skills directory and the **Agent Persona** into every
21
- global instruction file, on macOS, Linux and Windows. Codex targets also enable outbound
22
- network access in their workspace-write configuration. Restart your agent session to pick
23
- up the skills, instructions and configuration.
21
+ global instruction file, on macOS, Linux and Windows, and downloads the **Agent Reference** with
22
+ all its sub-documents into `~/.claude/toolkit/reference/` (see *The local Agent Reference* below).
23
+ Codex targets also enable outbound network access in their workspace-write configuration.
24
+ Restart your agent session to pick up the skills, instructions and configuration.
24
25
 
25
26
  ### Commands
26
27
 
@@ -43,9 +44,37 @@ up the skills, instructions and configuration.
43
44
  | `--no-persona` | Install skills only; leave instruction files alone |
44
45
  | `--persona-only` | Install/refresh the Agent Persona only; do not copy skills |
45
46
  | `--no-self-update` | `update` only: reinstall the bundled files; do not fetch npm |
47
+ | `--no-reference` | Do not download the Agent Reference; agents read it from GitHub |
48
+ | `--reference-from <dir>` | Install the Agent Reference from a local checkout instead of GitHub (offline, or to try unpublished Reference edits) |
46
49
  | `--dry-run` | Print what would happen and change nothing |
47
50
  | `--json` | Machine-readable output |
48
51
 
52
+ ### The local Agent Reference
53
+
54
+ Agents read the [Agent Reference](https://github.com/babylontoolkit/agent) before any Babylon work.
55
+ `bt-agent install` and `bt-agent update` download it — `reference.md`, every sub-document, the training
56
+ examples and the 2.7 MB API declarations — into `~/.claude/toolkit/reference/`, beside the Unity helper
57
+ scripts the Reference keeps in `~/.claude/toolkit/` (a `--project` install uses `.claude/toolkit/reference/`
58
+ in the project). Every link into the Reference repo is rewritten to the local file — in the copy and in the
59
+ installed skills — and the Reference's `curl … -o ~/.claude/toolkit/…` download commands become `cp`
60
+ from the copy, so agents read files instead of fetching pages:
61
+
62
+ - **Faster and more reliable** — no network round trip per document, and no failed fetch stopping a run.
63
+ - **Fewer tokens** — an agent searches a large document and reads only the section it needs, where a
64
+ fetch is all or nothing (`unity-exporter-cli.md` and `unity-authoring-recipes.md` are about 30k tokens
65
+ each); and nothing reaches it summarized or cut short.
66
+ - **The same in every agent** — Claude Code, Codex, Copilot, Gemini CLI and Antigravity all read files.
67
+ - **In step with the skills** — the copy is the one the installed skills were written against.
68
+
69
+ The copy comes from GitHub at install time, not from the npm package, so a Reference edit reaches agents
70
+ with `bt-agent update` — no npm release needed. If the download fails, an existing copy is kept; with no
71
+ copy at all, the skills and persona keep the GitHub addresses and agents read the Reference from there.
72
+ The persona names the local folder and keeps GitHub as the fallback for any file that is missing.
73
+ Claude Code asks before reading outside the project, so a global install adds one read-only rule —
74
+ `Read(~/.claude/toolkit/reference/**)` — to `~/.claude/settings.json` (uninstall removes it, and only if
75
+ the installer added it). `bt-agent doctor` checks that every local link resolves and says when GitHub has a
76
+ newer Reference.
77
+
49
78
  ### Disk usage report
50
79
 
51
80
  ```bash
@@ -252,6 +281,7 @@ pair or schedule the bridge.
252
281
  | [`bt-hero`](skills/bt-hero/SKILL.md) | `/bt-hero` | Create smooth cinematic 3D scrolling hero sections. |
253
282
  | [`bt-atlas`](skills/bt-atlas/SKILL.md) | `/bt-atlas` | Generate texture atlas skin variations. |
254
283
  | [`bt-optimize`](skills/bt-optimize/SKILL.md) | `/bt-optimize` | Make an exported Unity scene run fast in the browser: profile the BabylonJS frame (draw calls per pass, lights, shadows, post-processing, resolution, materials, textures), fix the causes on a copy of the scene — runtime lights, shadows, post, exporter settings, static / lightmap / mirrored unlocks — and merge static meshes and LOD groups (packed lightmap UVs, LOD clusters); then re-bake, export and verify frame rate and look against the original. `--no-combine`, `--combine-only`. |
284
+ | [`bt-profile`](skills/bt-profile/SKILL.md) | `/bt-profile` | Find and fix what makes a BabylonJS / Babylon Toolkit web game slow: drive the running game in Chrome through a repeatable scenario (a cold load, a level start, a countdown), record the CPU profile, allocations and every frame, map each millisecond to its source line and owner (your code, the toolkit runtime, BabylonJS, Havok, React), then fix the bottlenecks one at a time and re-measure each. Writes `.agents/profile/<slug>/dashboard.html`. `--analyze`, `--snapshots`, `--project`, `--slug`. |
255
285
 
256
286
  Every tool derives the slash-command from the **folder name** (`bt-spec/` → `/bt-spec`) and reads
257
287
  the frontmatter `name` + `description` to decide when the skill applies. The `allowed-tools`
@@ -416,7 +446,7 @@ Where each tool looks for PROJECT-LOCAL skills (only when the user explicitly re
416
446
  > for everything else (Codex, Copilot, Gemini CLI, Antigravity). By default use the
417
447
  > GLOBAL (per-user home) locations; use the project-local locations only when the user
418
448
  > explicitly asks for a project install. Copy **whole folders** into each — the
419
- > `bt-atlas/scripts/` and `bt-optimize/scripts/` assets must be present in every location.
449
+ > `bt-atlas/scripts/`, `bt-optimize/scripts/` and `bt-profile/scripts/` + `bt-profile/templates/` assets must be present in every location.
420
450
 
421
451
 
422
452
  # Babylon Toolkit Loop Engineering (Gauntlet Loop)
package/bin/bt-agent.js CHANGED
@@ -12,7 +12,8 @@ const USAGE = `
12
12
  @babylonjs-toolkit/agent ${version}
13
13
 
14
14
  Installs the Babylon Toolkit agent skills and Agent Persona for every
15
- supported AI client, on macOS, Linux and Windows. Codex targets also
15
+ supported AI client, on macOS, Linux and Windows, with a local copy of
16
+ the Agent Reference in ~/.claude/toolkit/reference. Codex targets also
16
17
  enable outbound network access in their workspace-write configuration.
17
18
 
18
19
  Usage
@@ -36,6 +37,8 @@ Options
36
37
  --persona-only Install/refresh the Agent Persona only; do not copy skills
37
38
  --no-migrate Leave a legacy unmarked persona in place, do not convert it
38
39
  --no-self-update update: reinstall the bundled files only; do not fetch npm
40
+ --no-reference Do not download the Agent Reference; agents read it from GitHub
41
+ --reference-from d Install the Agent Reference from a local checkout instead of GitHub
39
42
  --dry-run Print what would happen; change nothing
40
43
  --json Machine-readable output
41
44
  -h, --help Show this help
@@ -63,6 +66,8 @@ function parseArgs(argv) {
63
66
  skills: true,
64
67
  migrate: true,
65
68
  selfUpdate: true,
69
+ reference: true,
70
+ referenceFrom: null,
66
71
  dryRun: false,
67
72
  json: false,
68
73
  help: false,
@@ -98,6 +103,13 @@ function parseArgs(argv) {
98
103
  case '--no-self-update':
99
104
  opts.selfUpdate = false;
100
105
  break;
106
+ case '--no-reference':
107
+ opts.reference = false;
108
+ break;
109
+ case '--reference-from':
110
+ opts.referenceFrom = argv[++i] || null;
111
+ if (!opts.referenceFrom) throw new Error('--reference-from needs a folder');
112
+ break;
101
113
  case '--dry-run':
102
114
  opts.dryRun = true;
103
115
  break;
@@ -108,7 +120,9 @@ function parseArgs(argv) {
108
120
  opts.ids = String(argv[++i] || '').split(',').map((s) => s.trim()).filter(Boolean);
109
121
  break;
110
122
  default:
111
- if (arg.startsWith('--targets=')) {
123
+ if (arg.startsWith('--reference-from=')) {
124
+ opts.referenceFrom = arg.slice('--reference-from='.length);
125
+ } else if (arg.startsWith('--targets=')) {
112
126
  opts.ids = arg.slice('--targets='.length).split(',').map((s) => s.trim()).filter(Boolean);
113
127
  } else if (arg.startsWith('-')) {
114
128
  throw new Error(`Unknown option: ${arg}`);
@@ -150,6 +164,8 @@ function printInstall(report) {
150
164
  if (entry.backup) console.log(` backup: ${prettyPath(entry.backup)}`);
151
165
  }
152
166
 
167
+ printReference(report);
168
+
153
169
  if (report.pruned.length) {
154
170
  console.log('');
155
171
  for (const p of report.pruned) console.log(` pruned ${prettyPath(p)} (no longer shipped)`);
@@ -166,6 +182,39 @@ function printInstall(report) {
166
182
  }
167
183
  }
168
184
 
185
+ function printReference(report) {
186
+ const entry = report.reference;
187
+ if (!entry) return;
188
+ const commit = entry.commit ? entry.commit.slice(0, 7) : 'unknown commit';
189
+ const where = ` reference ${prettyPath(entry.dir)}`;
190
+ switch (entry.status) {
191
+ case 'installed':
192
+ console.log(`${where} — ${entry.source}, ${commit}: ${entry.files} files, ${entry.rewrittenLinks + entry.rewrittenDownloads} links now local`);
193
+ break;
194
+ case 'kept':
195
+ console.log(`${where} — kept the existing copy (${commit}); could not refresh it: ${entry.reason}`);
196
+ break;
197
+ case 'unavailable':
198
+ console.log(`${where} — not installed: ${entry.reason}`);
199
+ console.log(' agents will read the Agent Reference from GitHub until `bt-agent update` succeeds');
200
+ break;
201
+ case 'would-install':
202
+ console.log(`${where} — would download ${entry.source}`);
203
+ break;
204
+ default:
205
+ console.log(`${where} — ${commit}`);
206
+ }
207
+ if (entry.links && entry.links.broken.length) {
208
+ console.log(` ${entry.links.broken.length} local link(s) do not resolve:`);
209
+ for (const broken of entry.links.broken) console.log(` ${broken}`);
210
+ }
211
+ for (const permission of report.permissions || []) {
212
+ if (permission.action === 'unchanged') continue;
213
+ console.log(` allow ${prettyPath(permission.file)} — ${permission.rule} ${permission.action}`);
214
+ if (permission.note) console.log(` ${permission.note}`);
215
+ }
216
+ }
217
+
169
218
  function printSelfUpdate(result) {
170
219
  switch (result.status) {
171
220
  case 'upgraded':
@@ -225,6 +274,14 @@ function printDoctor(result) {
225
274
  console.log('INSTALL FAILED — missing:');
226
275
  for (const m of result.missing) console.log(` ${prettyPath(m)}`);
227
276
  }
277
+ const ref = result.reference;
278
+ if (ref && ref.present) {
279
+ const freshness = ref.latest ? (ref.latest === ref.commit ? ', current with GitHub' : '') : '';
280
+ console.log(`\n reference ${prettyPath(ref.dir)} — ${ref.commit ? ref.commit.slice(0, 7) : 'unknown commit'}, ${ref.files} files, ${ref.links.checked} local links checked${freshness}`);
281
+ } else if (ref) {
282
+ console.log(`\n reference ${prettyPath(ref.dir)}`);
283
+ }
284
+ for (const warning of (ref && ref.warnings) || []) console.log(` ${warning}`);
228
285
  }
229
286
 
230
287
  function targetsJson(mode, projectRoot) {
@@ -295,6 +352,8 @@ function main() {
295
352
  persona: opts.persona,
296
353
  skills: opts.skills,
297
354
  migrate: opts.migrate,
355
+ reference: opts.reference,
356
+ referenceFrom: opts.referenceFrom,
298
357
  dryRun: opts.dryRun,
299
358
  };
300
359
 
@@ -384,7 +443,8 @@ function main() {
384
443
  } else if (!report.manifestFound) {
385
444
  console.log('\nNothing to uninstall — no install manifest found.\n');
386
445
  } else {
387
- console.log(`\n${opts.dryRun ? 'Would remove' : 'Removed'} ${report.removed.length} skill folder(s).`);
446
+ console.log(`\n${opts.dryRun ? 'Would remove' : 'Removed'} ${report.removed.length} folder(s) (skills and the local Agent Reference).`);
447
+ for (const p of report.permissions) if (p.action === 'removed') console.log(` allow ${prettyPath(p.file)} — ${p.rule} removed`);
388
448
  for (const p of report.persona) console.log(` persona ${prettyPath(p.file)} — ${p.action}`);
389
449
  console.log('');
390
450
  }
@@ -392,7 +452,7 @@ function main() {
392
452
  }
393
453
 
394
454
  case 'doctor': {
395
- const result = doctor(common);
455
+ const result = doctor({ ...common, checkRemote: true });
396
456
  if (opts.json) console.log(JSON.stringify(result, null, 2));
397
457
  else {
398
458
  printDoctor(result);
@@ -0,0 +1,77 @@
1
+ 'use strict';
2
+
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+
6
+ /**
7
+ * Claude Code asks before reading a file outside the session's project. The local Agent Reference
8
+ * lives in the home folder, so without an allow rule every session would stop at its first read.
9
+ * This adds one read-only rule for that folder to Claude Code's settings — and removes only that
10
+ * rule on uninstall.
11
+ */
12
+
13
+ function readSettings(file) {
14
+ if (!fs.existsSync(file)) return { settings: {}, exists: false };
15
+ const text = fs.readFileSync(file, 'utf8');
16
+ if (text.trim() === '') return { settings: {}, exists: true };
17
+ const settings = JSON.parse(text);
18
+ if (!settings || typeof settings !== 'object' || Array.isArray(settings)) throw new Error('settings are not a JSON object');
19
+ return { settings, exists: true };
20
+ }
21
+
22
+ function writeSettings(file, settings, exists) {
23
+ let backup = null;
24
+ if (exists) {
25
+ backup = `${file}.bak`;
26
+ fs.copyFileSync(file, backup);
27
+ }
28
+ fs.mkdirSync(path.dirname(file), { recursive: true });
29
+ fs.writeFileSync(file, JSON.stringify(settings, null, 2) + '\n', 'utf8');
30
+ return backup;
31
+ }
32
+
33
+ /** Add `rule` to `permissions.allow`. A settings file that is not valid JSON is left alone. */
34
+ function addAllowRule(file, rule, { dryRun = false } = {}) {
35
+ let current;
36
+ try {
37
+ current = readSettings(file);
38
+ } catch (error) {
39
+ return { file, rule, action: 'skipped', note: `not valid JSON (${error.message}) — add ${rule} to permissions.allow yourself` };
40
+ }
41
+ const { settings, exists } = current;
42
+ const permissions = settings.permissions && typeof settings.permissions === 'object' ? settings.permissions : {};
43
+ const allow = Array.isArray(permissions.allow) ? permissions.allow : [];
44
+ if (allow.includes(rule)) return { file, rule, action: 'unchanged' };
45
+ if (dryRun) return { file, rule, action: exists ? 'updated' : 'created' };
46
+ settings.permissions = { ...permissions, allow: [...allow, rule] };
47
+ const backup = writeSettings(file, settings, exists);
48
+ return { file, rule, action: exists ? 'updated' : 'created', backup };
49
+ }
50
+
51
+ /** Remove `rule` from `permissions.allow`, and nothing else. */
52
+ function removeAllowRule(file, rule, { dryRun = false } = {}) {
53
+ let current;
54
+ try {
55
+ current = readSettings(file);
56
+ } catch {
57
+ return { file, rule, action: 'skipped' };
58
+ }
59
+ const { settings, exists } = current;
60
+ const allow = settings.permissions && Array.isArray(settings.permissions.allow) ? settings.permissions.allow : [];
61
+ if (!exists || !allow.includes(rule)) return { file, rule, action: 'absent' };
62
+ if (dryRun) return { file, rule, action: 'removed' };
63
+ settings.permissions.allow = allow.filter((entry) => entry !== rule);
64
+ const backup = writeSettings(file, settings, exists);
65
+ return { file, rule, action: 'removed', backup };
66
+ }
67
+
68
+ function hasAllowRule(file, rule) {
69
+ try {
70
+ const allow = (readSettings(file).settings.permissions || {}).allow;
71
+ return Array.isArray(allow) && allow.includes(rule);
72
+ } catch {
73
+ return false;
74
+ }
75
+ }
76
+
77
+ module.exports = { addAllowRule, removeAllowRule, hasAllowRule };
package/lib/doctor.js CHANGED
@@ -7,6 +7,9 @@ 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');
11
+ const reference = require('./reference');
12
+ const { resolveTargetPath } = require('./paths');
10
13
  const { readSettings } = require('./bridge/config');
11
14
  const { serviceStatus, hostDeps } = require('./bridge/service');
12
15
  const { discoverUnity } = require('./bridge/unity/discover');
@@ -28,6 +31,7 @@ function doctor(opts = {}) {
28
31
  legacyCodex = false,
29
32
  persona = true,
30
33
  skills: checkSkills = true,
34
+ checkRemote = false,
31
35
  } = opts;
32
36
 
33
37
  const resolved = resolveTargets({ mode, projectRoot, ids, legacyCodex });
@@ -53,6 +57,8 @@ function doctor(opts = {}) {
53
57
  if (!hasCodexNetwork(file)) missing.push(`${file} (sandbox_workspace_write.network_access = true)`);
54
58
  }
55
59
 
60
+ const referenceReport = checkReference({ mode, projectRoot, resolved, skills, checkSkills, checkRemote });
61
+
56
62
  // Informational only (D46): a user who only wants skills must still get INSTALL OK.
57
63
  const { servers } = readSettings();
58
64
  let unityCli = false;
@@ -83,6 +89,7 @@ function doctor(opts = {}) {
83
89
  instructionFiles: resolved.instructionFiles.map((f) => f.file),
84
90
  configFiles: resolved.configFiles.map((f) => f.file),
85
91
  },
92
+ reference: referenceReport,
86
93
  bridge: {
87
94
  paired: servers.length > 0,
88
95
  server: servers.length ? servers[0].server : null,
@@ -95,4 +102,33 @@ function doctor(opts = {}) {
95
102
  };
96
103
  }
97
104
 
105
+ /**
106
+ * The local Agent Reference — informational, never part of `ok`: without it agents read the Reference
107
+ * from GitHub. Reports the copy, every local link that does not resolve, a missing Claude Code allow
108
+ * rule, and (for `bt-agent doctor`) whether GitHub has moved on since the copy was made.
109
+ */
110
+ function checkReference({ mode, projectRoot, resolved, skills, checkSkills, checkRemote }) {
111
+ const dir = reference.referenceDir(mode, projectRoot);
112
+ const metadata = reference.readMetadata(dir);
113
+ if (!metadata || !reference.isUsable(dir)) {
114
+ return { dir, present: false, warnings: ['not installed — agents read the Agent Reference from GitHub; run `bt-agent update`'] };
115
+ }
116
+ const folders = [dir, ...(checkSkills ? resolved.skillDirs.flatMap(({ dir: skillsDir }) => skills.map((skill) => path.join(skillsDir, skill.name))) : [])];
117
+ const links = reference.checkLinks(dir, folders);
118
+ const warnings = links.broken.map((entry) => `broken link: ${entry}`);
119
+
120
+ const claude = resolved.selected.find((target) => target.id === 'claude');
121
+ if (claude && mode === 'global') {
122
+ const settingsFile = path.join(path.dirname(resolveTargetPath(claude.global.instructions, mode, projectRoot)), 'settings.json');
123
+ if (!hasAllowRule(settingsFile, reference.CLAUDE_READ_RULE)) warnings.push(`${settingsFile} has no ${reference.CLAUDE_READ_RULE} — Claude Code will ask before each read`);
124
+ }
125
+
126
+ let latest = null;
127
+ if (checkRemote && metadata.commit) {
128
+ latest = reference.latestCommit();
129
+ if (latest && latest !== metadata.commit) warnings.push(`GitHub has a newer Agent Reference (${latest.slice(0, 7)}) — run \`bt-agent update\``);
130
+ }
131
+ return { dir, present: true, commit: metadata.commit, installedAt: metadata.installedAt, files: metadata.files, links, latest, warnings };
132
+ }
133
+
98
134
  module.exports = { doctor };
package/lib/install.js CHANGED
@@ -7,8 +7,10 @@ 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');
11
+ const reference = require('./reference');
10
12
  const manifest = require('./manifest');
11
- const { manifestPath } = require('./paths');
13
+ const { manifestPath, resolveTargetPath } = require('./paths');
12
14
 
13
15
  const { version } = require('../package.json');
14
16
 
@@ -16,6 +18,10 @@ const { version } = require('../package.json');
16
18
  * Copy every shipped skill into every target skills directory, refresh the Agent
17
19
  * Persona in every target instruction file, and record the result.
18
20
  *
21
+ * With skills, the Agent Reference is downloaded into `~/.claude/toolkit/reference/` (see
22
+ * reference.js) and the installed skills and the persona point at that local copy. Without a
23
+ * usable copy they keep the GitHub addresses, so agents still work.
24
+ *
19
25
  * Each skill folder is replaced wholesale (delete-then-copy) so files removed
20
26
  * upstream do not linger, but only folder names this package ships are ever
21
27
  * deleted — a user's own `bt-*` skill is untouched.
@@ -31,6 +37,8 @@ function install(opts = {}) {
31
37
  migrate = true,
32
38
  dryRun = false,
33
39
  prune = true,
40
+ reference: installLocalReference = true,
41
+ referenceFrom = null,
34
42
  } = opts;
35
43
 
36
44
  if (!installSkills && !persona) {
@@ -51,9 +59,20 @@ function install(opts = {}) {
51
59
  persona: [],
52
60
  config: [],
53
61
  pruned: [],
62
+ reference: null,
63
+ permissions: [],
54
64
  manifest: manifestPath(mode, projectRoot),
55
65
  };
56
66
 
67
+ // The Reference first: the skills and persona written below point at it only when it is usable.
68
+ const referenceDir = reference.referenceDir(mode, projectRoot);
69
+ if (installLocalReference && installSkills) {
70
+ report.reference = reference.installReference({ mode, projectRoot, from: referenceFrom, dryRun });
71
+ } else if (installLocalReference && reference.isUsable(referenceDir)) {
72
+ report.reference = { dir: referenceDir, status: 'unchanged', ...reference.readMetadata(referenceDir) };
73
+ }
74
+ const localReference = installLocalReference && !dryRun && reference.isUsable(referenceDir) ? referenceDir : null;
75
+
57
76
  // Preflight every merge before changing installed skills or instructions.
58
77
  for (const { file } of resolved.configFiles) applyCodexConfig(file, { dryRun: true });
59
78
  for (const { file, targets } of resolved.configFiles) {
@@ -68,6 +87,7 @@ function install(opts = {}) {
68
87
  if (!dryRun) {
69
88
  fs.rmSync(dest, { recursive: true, force: true });
70
89
  copyDir(skill.src, dest);
90
+ if (localReference) reference.rewriteFolder(dest, localReference);
71
91
  }
72
92
  }
73
93
 
@@ -86,8 +106,23 @@ function install(opts = {}) {
86
106
  report.skillDirs.push({ dir, targets, skills: skills.map((s) => s.name) });
87
107
  }
88
108
 
109
+ if (report.reference) {
110
+ report.reference.links = localReference
111
+ ? reference.checkLinks(localReference, [localReference, ...report.skillDirs.flatMap(({ dir }) => report.skills.map((name) => path.join(dir, name)))])
112
+ : null;
113
+ }
114
+
115
+ // Claude Code asks before reading outside the project; the global copy gets one read-only allow rule.
116
+ if (localReference && mode === 'global') {
117
+ const claude = resolved.selected.find((target) => target.id === 'claude');
118
+ if (claude) {
119
+ const settingsFile = path.join(path.dirname(resolveTargetPath(claude.global.instructions, mode, projectRoot)), 'settings.json');
120
+ report.permissions.push(addAllowRule(settingsFile, reference.CLAUDE_READ_RULE, { dryRun }));
121
+ }
122
+ }
123
+
89
124
  if (persona) {
90
- const text = personaText();
125
+ const text = personaText({ referenceDir: localReference });
91
126
  for (const { file, targets } of resolved.instructionFiles) {
92
127
  const result = applyPersona(file, { text, dryRun, migrate });
93
128
  report.persona.push({ ...result, targets });
@@ -107,6 +142,11 @@ function install(opts = {}) {
107
142
  skillDirs,
108
143
  config: report.config,
109
144
  persona: report.persona.map(({ file, action }) => ({ file, action })),
145
+ reference: report.reference && report.reference.status !== 'unavailable'
146
+ ? { dir: report.reference.dir, commit: report.reference.commit || null, source: report.reference.source || null }
147
+ : (previous && previous.reference) || undefined,
148
+ // Kept across runs so uninstall can remove a rule an earlier install added.
149
+ permissions: mergePermissions(previous && previous.permissions, report.permissions),
110
150
  });
111
151
  }
112
152
 
@@ -122,7 +162,7 @@ function uninstall(opts = {}) {
122
162
  const { mode = 'global', projectRoot = process.cwd(), dryRun = false, persona = true } = opts;
123
163
 
124
164
  const previous = manifest.read(mode, projectRoot);
125
- const report = { mode, dryRun, removed: [], persona: [], manifestFound: Boolean(previous) };
165
+ const report = { mode, dryRun, removed: [], persona: [], permissions: [], manifestFound: Boolean(previous) };
126
166
 
127
167
  if (!previous) return report;
128
168
 
@@ -148,8 +188,24 @@ function uninstall(opts = {}) {
148
188
  }
149
189
  }
150
190
 
191
+ if (previous.reference && reference.removeReference(previous.reference.dir, { dryRun })) {
192
+ report.removed.push(previous.reference.dir);
193
+ }
194
+ for (const entry of previous.permissions || []) {
195
+ report.permissions.push(removeAllowRule(entry.file, entry.rule, { dryRun }));
196
+ }
197
+
151
198
  if (!dryRun) manifest.remove(mode, projectRoot);
152
199
  return report;
153
200
  }
154
201
 
202
+ /** The allow rules this tool added, by file and rule, so uninstall removes exactly those. */
203
+ function mergePermissions(previous, current) {
204
+ const merged = new Map();
205
+ // A rule that was already there is the user's own (`unchanged`), so it is never recorded as ours.
206
+ const added = current.filter((entry) => ['created', 'updated'].includes(entry.action));
207
+ for (const entry of [...(previous || []), ...added]) merged.set(`${entry.file}\n${entry.rule}`, { file: entry.file, rule: entry.rule });
208
+ return [...merged.values()];
209
+ }
210
+
155
211
  module.exports = { install, uninstall };
package/lib/persona.js CHANGED
@@ -12,8 +12,27 @@ const END = '<!-- END BABYLON TOOLKIT PERSONA -->';
12
12
  const LEGACY_SENTINEL = 'babylontoolkit/agent/main/reference.md';
13
13
  const LEGACY_HEADING = '# Babylon Toolkit Agent Persona';
14
14
 
15
- function personaText() {
16
- return fs.readFileSync(personaFile(), 'utf8').trim();
15
+ /**
16
+ * The persona as installed. With a local Agent Reference its links point at the local copy, and a
17
+ * paragraph after the opening one says so — keeping the GitHub address as the fallback, which is
18
+ * also what `hasPersona` recognises.
19
+ */
20
+ function personaText({ referenceDir = null } = {}) {
21
+ const text = fs.readFileSync(personaFile(), 'utf8').trim();
22
+ if (!referenceDir) return text;
23
+ const { rewriteText, linkRoot, REFERENCE_URL_PREFIX } = require('./reference');
24
+ const root = linkRoot(referenceDir);
25
+ const localNote =
26
+ `The Agent Reference and every one of its sub-documents are installed locally in \`${root}/\` by bt-agent, ` +
27
+ 'and every Agent Reference link — in the Reference itself and in the bt-* skills — points at a file there. ' +
28
+ 'Read those files directly, never fetch them; search a large one (the API declarations in ' +
29
+ `\`${root}/training/declarations/babylon.toolkit.d.ts\` are 2.7 MB) and read only the part you need. ` +
30
+ `Only if a file there is missing, fetch the same path from ${REFERENCE_URL_PREFIX} instead ` +
31
+ `(the Reference itself is ${REFERENCE_URL_PREFIX}reference.md) and tell the user to run \`bt-agent update\`.`;
32
+ // After the heading and the opening paragraph, which names the Reference.
33
+ const blocks = rewriteText(text, referenceDir).text.split('\n\n');
34
+ const insertAt = blocks[0].startsWith('#') ? 2 : 1;
35
+ return [...blocks.slice(0, insertAt), localNote, ...blocks.slice(insertAt)].join('\n\n');
17
36
  }
18
37
 
19
38
  function renderBlock(text, eol) {