lean-agents 0.0.0-stage → 1.0.0
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 +407 -0
- package/LICENSE +21 -0
- package/README.es.md +560 -0
- package/README.md +559 -2
- package/core/AGENTS.es.md +60 -0
- package/core/AGENTS.md +60 -0
- package/core/README.md +8 -0
- package/core/agents/debug.md +14 -0
- package/core/agents/explore.md +13 -0
- package/core/agents/planner.md +14 -0
- package/core/agents/research.md +13 -0
- package/core/agents/review.md +13 -0
- package/core/copilot-usage-tui.js +189 -0
- package/core/mcp.json +38 -0
- package/core/pins.json +39 -0
- package/core/tiers.json +4 -0
- package/node_modules/@clack/core/LICENSE +9 -0
- package/node_modules/@clack/core/README.md +22 -0
- package/node_modules/@clack/core/dist/index.d.mts +503 -0
- package/node_modules/@clack/core/dist/index.mjs +1003 -0
- package/node_modules/@clack/core/package.json +63 -0
- package/node_modules/@clack/prompts/LICENSE +9 -0
- package/node_modules/@clack/prompts/README.md +396 -0
- package/node_modules/@clack/prompts/dist/index.d.mts +949 -0
- package/node_modules/@clack/prompts/dist/index.mjs +1423 -0
- package/node_modules/@clack/prompts/package.json +67 -0
- package/node_modules/fast-string-truncated-width/dist/index.d.ts +4 -0
- package/node_modules/fast-string-truncated-width/dist/index.js +111 -0
- package/node_modules/fast-string-truncated-width/dist/types.d.ts +19 -0
- package/node_modules/fast-string-truncated-width/dist/types.js +2 -0
- package/node_modules/fast-string-truncated-width/dist/utils.d.ts +4 -0
- package/node_modules/fast-string-truncated-width/dist/utils.js +20 -0
- package/node_modules/fast-string-truncated-width/license +21 -0
- package/node_modules/fast-string-truncated-width/package.json +35 -0
- package/node_modules/fast-string-truncated-width/readme.md +59 -0
- package/node_modules/fast-string-width/dist/index.d.ts +4 -0
- package/node_modules/fast-string-width/dist/index.js +14 -0
- package/node_modules/fast-string-width/license +21 -0
- package/node_modules/fast-string-width/package.json +34 -0
- package/node_modules/fast-string-width/readme.md +42 -0
- package/node_modules/fast-wrap-ansi/LICENSE +23 -0
- package/node_modules/fast-wrap-ansi/README.md +26 -0
- package/node_modules/fast-wrap-ansi/lib/main.d.ts +6 -0
- package/node_modules/fast-wrap-ansi/lib/main.js +218 -0
- package/node_modules/fast-wrap-ansi/package.json +51 -0
- package/node_modules/jsonc-parser/CHANGELOG.md +76 -0
- package/node_modules/jsonc-parser/LICENSE.md +21 -0
- package/node_modules/jsonc-parser/README.md +364 -0
- package/node_modules/jsonc-parser/SECURITY.md +41 -0
- package/node_modules/jsonc-parser/lib/esm/impl/edit.js +185 -0
- package/node_modules/jsonc-parser/lib/esm/impl/format.js +261 -0
- package/node_modules/jsonc-parser/lib/esm/impl/parser.js +659 -0
- package/node_modules/jsonc-parser/lib/esm/impl/scanner.js +443 -0
- package/node_modules/jsonc-parser/lib/esm/impl/string-intern.js +29 -0
- package/node_modules/jsonc-parser/lib/esm/main.d.ts +351 -0
- package/node_modules/jsonc-parser/lib/esm/main.js +178 -0
- package/node_modules/jsonc-parser/lib/umd/impl/edit.js +201 -0
- package/node_modules/jsonc-parser/lib/umd/impl/format.js +275 -0
- package/node_modules/jsonc-parser/lib/umd/impl/parser.js +682 -0
- package/node_modules/jsonc-parser/lib/umd/impl/scanner.js +456 -0
- package/node_modules/jsonc-parser/lib/umd/impl/string-intern.js +42 -0
- package/node_modules/jsonc-parser/lib/umd/main.d.ts +351 -0
- package/node_modules/jsonc-parser/lib/umd/main.js +194 -0
- package/node_modules/jsonc-parser/package.json +37 -0
- package/node_modules/sisteransi/license +21 -0
- package/node_modules/sisteransi/package.json +34 -0
- package/node_modules/sisteransi/readme.md +113 -0
- package/node_modules/sisteransi/src/index.js +58 -0
- package/node_modules/sisteransi/src/sisteransi.d.ts +35 -0
- package/package.json +30 -4
- package/profiles/README.md +10 -0
- package/profiles/anthropic-api/gsd-defaults.json +26 -0
- package/profiles/anthropic-api.json +18 -0
- package/profiles/antigravity.json +12 -0
- package/profiles/claude-subscription/gsd-defaults.json +26 -0
- package/profiles/claude-subscription.json +17 -0
- package/profiles/github-copilot/gsd-defaults.json +26 -0
- package/profiles/github-copilot.json +17 -0
- package/profiles/openai-api/gsd-defaults.json +26 -0
- package/profiles/openai-api.json +17 -0
- package/profiles/opencode-go/gsd-defaults.json +26 -0
- package/profiles/opencode-go.json +17 -0
- package/profiles/vertex-gemini/gsd-defaults.json +26 -0
- package/profiles/vertex-gemini.json +18 -0
- package/scripts/adhd-skill.mjs +12 -0
- package/scripts/behavior-diff.sh +47 -0
- package/scripts/bump-pins.mjs +115 -0
- package/scripts/check-private.sh +52 -0
- package/scripts/check-readme.mjs +131 -0
- package/scripts/ci-download.sh +20 -0
- package/scripts/ci-install-opencode-v2.sh +6 -0
- package/scripts/ci-latest-report.mjs +38 -0
- package/scripts/ci-timing.mjs +61 -0
- package/scripts/copilot-context-mode.mjs +33 -0
- package/scripts/labels.sh +56 -0
- package/scripts/lean.mjs +1319 -0
- package/scripts/lib/adapters/antigravity.mjs +83 -0
- package/scripts/lib/adapters/claude.mjs +127 -0
- package/scripts/lib/adapters/copilot-cli.mjs +82 -0
- package/scripts/lib/adapters/cursor.mjs +60 -0
- package/scripts/lib/adapters/opencode-v1.mjs +79 -0
- package/scripts/lib/adapters/opencode-v2.mjs +216 -0
- package/scripts/lib/adapters/vscode-copilot.mjs +56 -0
- package/scripts/lib/adhd.mjs +28 -0
- package/scripts/lib/adopt.mjs +619 -0
- package/scripts/lib/agent-lifecycle.mjs +280 -0
- package/scripts/lib/backup-stamp.mjs +25 -0
- package/scripts/lib/copilot-usage.mjs +49 -0
- package/scripts/lib/doctor.mjs +279 -0
- package/scripts/lib/feedback.mjs +48 -0
- package/scripts/lib/fsops.mjs +319 -0
- package/scripts/lib/gsd.mjs +42 -0
- package/scripts/lib/inventory.mjs +196 -0
- package/scripts/lib/lean-update.mjs +30 -0
- package/scripts/lib/logins.mjs +28 -0
- package/scripts/lib/migrate.mjs +407 -0
- package/scripts/lib/network.mjs +119 -0
- package/scripts/lib/node-runtime.mjs +85 -0
- package/scripts/lib/opencode-backup.mjs +204 -0
- package/scripts/lib/opencode-upgrade.mjs +441 -0
- package/scripts/lib/opencode1.mjs +203 -0
- package/scripts/lib/parallel.mjs +270 -0
- package/scripts/lib/pins-diff.mjs +33 -0
- package/scripts/lib/pins.mjs +52 -0
- package/scripts/lib/plugin-health.mjs +191 -0
- package/scripts/lib/prereqs.mjs +203 -0
- package/scripts/lib/project.mjs +38 -0
- package/scripts/lib/redact.mjs +30 -0
- package/scripts/lib/render.mjs +101 -0
- package/scripts/lib/shell-path.mjs +22 -0
- package/scripts/lib/summary-data.mjs +30 -0
- package/scripts/lib/summary-html.mjs +159 -0
- package/scripts/lib/system.mjs +269 -0
- package/scripts/lib/terminals.mjs +316 -0
- package/scripts/lib/ui.mjs +34 -0
- package/scripts/lib/unverified.mjs +49 -0
- package/scripts/lib/update-plan.mjs +60 -0
- package/scripts/lib/upgrade.mjs +231 -0
- package/scripts/lib/verify-commit.mjs +16 -0
- package/scripts/lib/verify-prompt.mjs +46 -0
- package/scripts/lib/verify-sha256.mjs +20 -0
- package/scripts/lint-workflows.mjs +25 -0
- package/scripts/models-refresh.mjs +58 -0
- package/scripts/parallel.mjs +59 -0
- package/scripts/pins-latest.mjs +66 -0
- package/scripts/release.mjs +71 -0
- package/scripts/verify-pins.mjs +36 -0
- package/scripts/version-watch.mjs +124 -0
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
// OpenCode plugin health (#212): a plugin listed in config is not proof it loads. Read-only: findings with a suggested fix, never a repair.
|
|
2
|
+
// Cache layout (VERIFY, upstream source not readable when written, 2026-11): `<cache>/packages/<pkg>@<spec>/node_modules/<pkg>` with the
|
|
3
|
+
// wrapper's package.json and lockfile beside it; older docs say `<cache>/node_modules/<pkg>`. Both are searched.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import net from 'node:net';
|
|
8
|
+
import { spawn, spawnSync } from 'node:child_process';
|
|
9
|
+
import { parse } from 'jsonc-parser';
|
|
10
|
+
import { configHome, envDir } from './system.mjs';
|
|
11
|
+
import { configPath } from './adapters/opencode-v2.mjs';
|
|
12
|
+
import { PINS } from './pins.mjs';
|
|
13
|
+
|
|
14
|
+
// Plugins whose slash command proves they registered on a fresh server.
|
|
15
|
+
export const COMMANDS = { '@tarquinen/opencode-dcp': 'dcp-compress' };
|
|
16
|
+
|
|
17
|
+
export function splitSpec(spec) {
|
|
18
|
+
const at = spec.lastIndexOf('@');
|
|
19
|
+
return at > 0 ? { name: spec.slice(0, at), version: spec.slice(at + 1) } : { name: spec, version: '' };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const readJson = (file, fsx) => { try { return parse(fsx.readFileSync(file, 'utf8'), [], { allowTrailingComma: true }) ?? null; } catch { return null; } };
|
|
23
|
+
const cacheDir = (home) => path.join(envDir(home, 'XDG_CACHE_HOME', path.join(home, '.cache')), 'opencode');
|
|
24
|
+
|
|
25
|
+
// npm plugin specs per config file: `plugin` / `plugins` entries, string or [spec, options]. Local paths are not packages.
|
|
26
|
+
export function readSpecs(home, fsx = fs) {
|
|
27
|
+
const dir = path.join(configHome(home), 'opencode');
|
|
28
|
+
const out = [];
|
|
29
|
+
for (const [file, keys] of [[configPath(dir), ['plugin', 'plugins']], [path.join(dir, 'tui.json'), ['plugin']], [path.join(dir, 'tui.jsonc'), ['plugin']]]) {
|
|
30
|
+
const cfg = readJson(file, fsx);
|
|
31
|
+
for (const k of keys) for (const e of Array.isArray(cfg?.[k]) ? cfg[k] : []) {
|
|
32
|
+
const spec = String(Array.isArray(e) ? e[0] : e);
|
|
33
|
+
if (/^(file:|\.|\/|~|[A-Za-z]:[\\/])/.test(spec)) continue;
|
|
34
|
+
out.push({ file: path.basename(file), ...splitSpec(spec), spec });
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Same package with different version specs in the server config and tui.json. Each process reads its own file, so neither spec "wins".
|
|
41
|
+
export function reconcileSpecs(entries, pins = {}) {
|
|
42
|
+
const byName = new Map();
|
|
43
|
+
for (const e of entries) byName.set(e.name, [...(byName.get(e.name) ?? []), e]);
|
|
44
|
+
const out = [];
|
|
45
|
+
for (const [name, list] of byName) {
|
|
46
|
+
if (new Set(list.map((e) => e.version)).size < 2) continue;
|
|
47
|
+
const seen = list.map((e) => `${e.file} ${e.version || 'unpinned'}`).join(' vs ');
|
|
48
|
+
const want = pins[name] ? `${name}@${pins[name]}` : 'one exact version';
|
|
49
|
+
out.push({ id: 'spec-mismatch', plugin: name, line: `${name}: ${seen}; the server and the TUI each load their own spec, so they can run different versions`,
|
|
50
|
+
fix: `set both files to ${want} by hand (your pin stays yours); then restart OpenCode` });
|
|
51
|
+
}
|
|
52
|
+
return out;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Dependencies of a package that do not resolve from it, the way Node walks node_modules up to the cache root. Optional and peer dependencies are the host's or the user's business.
|
|
56
|
+
function missingDeps(pkgDir, root, fsx, seen = new Set(), depth = 0) {
|
|
57
|
+
const pkg = readJson(path.join(pkgDir, 'package.json'), fsx);
|
|
58
|
+
if (!pkg || depth > 4) return [];
|
|
59
|
+
const miss = [];
|
|
60
|
+
for (const dep of Object.keys(pkg.dependencies ?? {})) {
|
|
61
|
+
let found = null;
|
|
62
|
+
for (let d = pkgDir; ; d = path.dirname(d)) {
|
|
63
|
+
const cand = path.join(d, 'node_modules', dep);
|
|
64
|
+
if (fsx.existsSync(path.join(cand, 'package.json'))) { found = cand; break; }
|
|
65
|
+
if (d === root || d === path.dirname(d)) break;
|
|
66
|
+
}
|
|
67
|
+
if (!found) { miss.push(dep); continue; }
|
|
68
|
+
if (!seen.has(found)) { seen.add(found); miss.push(...missingDeps(found, root, fsx, seen, depth + 1)); }
|
|
69
|
+
}
|
|
70
|
+
return [...new Set(miss)];
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// Cached wrapper folders of a package: flat `packages/<name>@<spec>` or, for a scoped name, `packages/<scope>/<base>@<spec>` (VERIFY which one OpenCode writes).
|
|
74
|
+
function wrapperDirs(root, name, fsx) {
|
|
75
|
+
const [scope, base] = name.startsWith('@') ? name.split('/') : [null, name];
|
|
76
|
+
const out = [];
|
|
77
|
+
for (const [dir, prefix] of [[path.join(root, 'packages'), `${name}@`], ...(scope ? [[path.join(root, 'packages', scope), `${base}@`]] : [])]) {
|
|
78
|
+
try {
|
|
79
|
+
for (const e of fsx.readdirSync(dir, { withFileTypes: true })) if (e.isDirectory() && e.name.startsWith(prefix)) out.push(path.join(dir, e.name));
|
|
80
|
+
} catch { /* no such folder */ }
|
|
81
|
+
}
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// Cached wrapper(s) of `name` whose dependency tree is incomplete. No cached copy: nothing to report.
|
|
86
|
+
// A name from config is joined into a path: no `..` segment and nothing absolute (POSIX or drive letter).
|
|
87
|
+
export const safePluginName = (name) => !path.posix.isAbsolute(name) && !path.win32.isAbsolute(name) && !name.split(/[\\/]/).includes('..');
|
|
88
|
+
|
|
89
|
+
// `specs`: the versions the config asks for ('' = unpinned = the `latest` folder). Given, only the wrapper folders OpenCode loads for
|
|
90
|
+
// them are checked: a leftover folder of an older spec (for example `@latest` after the user pinned an exact version) is not loaded.
|
|
91
|
+
export function checkDepTree(home, name, fsx = fs, specs = null) {
|
|
92
|
+
if (!safePluginName(name)) return [];
|
|
93
|
+
const root = cacheDir(home);
|
|
94
|
+
const wanted = specs && new Set([...specs].map((v) => v || 'latest'));
|
|
95
|
+
const used = (d) => !wanted || wanted.has(path.basename(d).slice(path.basename(d).indexOf('@') + 1));
|
|
96
|
+
const wrappers = [path.join(root, 'node_modules'), ...wrapperDirs(root, name, fsx).filter(used).map((d) => path.join(d, 'node_modules'))];
|
|
97
|
+
const out = [];
|
|
98
|
+
for (const nm of wrappers) {
|
|
99
|
+
const pkgDir = path.join(nm, ...name.split('/'));
|
|
100
|
+
const pkg = readJson(path.join(pkgDir, 'package.json'), fsx);
|
|
101
|
+
if (!pkg) continue;
|
|
102
|
+
const miss = missingDeps(pkgDir, root, fsx);
|
|
103
|
+
if (miss.length) out.push({ id: 'deps-incomplete', plugin: name, line: `${name}@${pkg.version ?? '?'} cached in ${path.relative(root, path.dirname(nm)) || '.'}: missing ${miss.join(', ')}; the plugin cannot load even though config lists it`,
|
|
104
|
+
fix: 'close OpenCode, move that cache folder aside (do not delete it yet), start OpenCode so it installs again; or pin an exact version in both config files' });
|
|
105
|
+
}
|
|
106
|
+
return out;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// Static findings (no process started) for every npm plugin in the user's OpenCode config.
|
|
110
|
+
const PIN_VERSIONS = Object.fromEntries(Object.values(PINS).filter((p) => p.kind === 'npm').map((p) => [p.source, p.version]));
|
|
111
|
+
|
|
112
|
+
export function pluginHealth(home, { pins = PIN_VERSIONS, fsx = fs } = {}) {
|
|
113
|
+
const entries = readSpecs(home, fsx);
|
|
114
|
+
const names = [...new Set(entries.map((e) => e.name))];
|
|
115
|
+
return [...reconcileSpecs(entries, pins), ...names.flatMap((n) => checkDepTree(home, n, fsx, entries.filter((e) => e.name === n).map((e) => e.version)))];
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const freePort = () => new Promise((resolve, reject) => {
|
|
119
|
+
const s = net.createServer().on('error', reject).listen(0, '127.0.0.1', () => { const { port } = s.address(); s.close(() => resolve(port)); });
|
|
120
|
+
});
|
|
121
|
+
|
|
122
|
+
// Copies of the user's config and cache are capped: a runaway node_modules must not fill the disk of a read-only check.
|
|
123
|
+
const COPY_CAP_BYTES = 256 * 1024 * 1024;
|
|
124
|
+
const capped = (fsx) => { let bytes = 0; return (src) => { try { bytes += fsx.lstatSync(src).size; } catch { /* the copy reports it */ } if (bytes > COPY_CAP_BYTES) throw new Error('copy exceeds the size cap'); return true; }; };
|
|
125
|
+
|
|
126
|
+
// Windows children need these to start at all; the rest points at the throwaway dir. SystemRoot and ComSpec are the OS's, not the user's.
|
|
127
|
+
const winEnv = (tmp, env) => ({ SystemRoot: env.SystemRoot, ComSpec: env.ComSpec, APPDATA: tmp, LOCALAPPDATA: tmp, TEMP: tmp, TMP: tmp });
|
|
128
|
+
|
|
129
|
+
// Opt-in (--probe-plugins): a short-lived `opencode serve` on loopback with a throwaway state dir. It gets COPIES of the user's OpenCode config and
|
|
130
|
+
// of the cached wrapper of each plugin we know a command for, so nothing of the user's is written. GET /command (1.x) or /api/command (2.x) must list it.
|
|
131
|
+
// Windows: `cmd /c` runs an npm `.cmd` shim, and taskkill /T ends the grandchildren that child.kill() would leave.
|
|
132
|
+
export async function probePlugins(home, { bin = 'opencode', fsx = fs, spawnFn = spawn, spawnSyncFn = spawnSync, fetchFn = fetch, timeoutMs = 30000, env = process.env, platform = process.platform } = {}) {
|
|
133
|
+
const wanted = [...new Set(readSpecs(home, fsx).map((e) => e.name))].filter((n) => COMMANDS[n]);
|
|
134
|
+
if (!wanted.length) return [];
|
|
135
|
+
const win = platform === 'win32';
|
|
136
|
+
const tmp = fsx.mkdtempSync(path.join(os.tmpdir(), 'lean-probe-'));
|
|
137
|
+
const xdg = { XDG_CONFIG_HOME: path.join(tmp, 'config'), XDG_CACHE_HOME: path.join(tmp, 'cache'), XDG_DATA_HOME: path.join(tmp, 'data'), XDG_STATE_HOME: path.join(tmp, 'state') };
|
|
138
|
+
const stop = (c) => {
|
|
139
|
+
if (win && c.pid) { try { const r = spawnSyncFn('taskkill', ['/pid', String(c.pid), '/T', '/F'], { stdio: 'ignore' }); if (!r?.error && !r?.status) return; } catch { /* fall back to kill */ } }
|
|
140
|
+
c.kill();
|
|
141
|
+
};
|
|
142
|
+
let child;
|
|
143
|
+
try {
|
|
144
|
+
try {
|
|
145
|
+
const filter = capped(fsx);
|
|
146
|
+
fsx.cpSync(path.join(configHome(home), 'opencode'), path.join(xdg.XDG_CONFIG_HOME, 'opencode'), { recursive: true, filter });
|
|
147
|
+
const root = cacheDir(home);
|
|
148
|
+
for (const n of wanted) for (const d of wrapperDirs(root, n, fsx)) fsx.cpSync(d, path.join(xdg.XDG_CACHE_HOME, 'opencode', path.relative(root, d)), { recursive: true, filter });
|
|
149
|
+
} catch (e) {
|
|
150
|
+
return [{ id: 'probe-failed', plugin: '', line: `could not copy the config or plugin cache for the probe (${e.code ?? e.message}), so the command check was skipped`, fix: 'check for broken symlinks or a very large node_modules in the OpenCode cache; then run --doctor --probe-plugins again' }];
|
|
151
|
+
}
|
|
152
|
+
const port = await freePort();
|
|
153
|
+
const password = `probe-${process.pid}-${port}`;
|
|
154
|
+
const serve = ['serve', '--hostname', '127.0.0.1', '--port', String(port)];
|
|
155
|
+
child = spawnFn(win ? env.ComSpec ?? 'cmd.exe' : bin, win ? ['/d', '/c', bin, ...serve] : serve, {
|
|
156
|
+
cwd: tmp, stdio: 'ignore', env: { PATH: env.PATH, HOME: tmp, USERPROFILE: tmp, ...(win ? winEnv(tmp, env) : {}), ...xdg, OPENCODE_SERVER_PASSWORD: password },
|
|
157
|
+
});
|
|
158
|
+
let spawnError = null;
|
|
159
|
+
child.on?.('error', (e) => { spawnError = e; }); // opencode not on PATH: a finding, not a crash
|
|
160
|
+
const auth = `Basic ${Buffer.from(`opencode:${password}`).toString('base64')}`;
|
|
161
|
+
const names = async () => {
|
|
162
|
+
for (const route of ['/command', '/api/command']) {
|
|
163
|
+
try {
|
|
164
|
+
const r = await fetchFn(`http://127.0.0.1:${port}${route}`, { headers: { authorization: auth } });
|
|
165
|
+
if (!r.ok) continue;
|
|
166
|
+
const j = await r.json();
|
|
167
|
+
return (Array.isArray(j) ? j : j.data ?? []).map((c) => c.name);
|
|
168
|
+
} catch { /* not up yet, or the other route */ }
|
|
169
|
+
}
|
|
170
|
+
return null;
|
|
171
|
+
};
|
|
172
|
+
// The first answer can come before plugins register, so keep asking until every command is listed or the deadline passes.
|
|
173
|
+
const end = Date.now() + timeoutMs;
|
|
174
|
+
let got = null;
|
|
175
|
+
for (;;) {
|
|
176
|
+
const now = await names();
|
|
177
|
+
if (now !== null) got = now;
|
|
178
|
+
if ((got !== null && wanted.every((n) => got.includes(COMMANDS[n]))) || spawnError || Date.now() >= end) break;
|
|
179
|
+
await new Promise((r) => setTimeout(r, 500));
|
|
180
|
+
}
|
|
181
|
+
if (got === null) return [{ id: 'probe-failed', plugin: '', line: spawnError ? `could not start ${bin}: ${spawnError.code ?? spawnError.message}, so the command check was skipped` : 'a short-lived `opencode serve` did not answer in time, so the command check was skipped', fix: 'run --doctor --probe-plugins again; if it repeats, start `opencode serve` by hand and GET /command' }];
|
|
182
|
+
return wanted.filter((n) => !got.includes(COMMANDS[n])).map((n) => ({ id: 'command-missing', plugin: n, line: `${n}: a fresh server does not list /${COMMANDS[n]}; the plugin is configured but not operational`,
|
|
183
|
+
fix: 'check the dependency finding above, or pin an exact older version in both config files; then restart OpenCode' }));
|
|
184
|
+
} finally {
|
|
185
|
+
// wait for the exit so the server cannot write into the folder while it is removed
|
|
186
|
+
if (child?.on && child.exitCode === null && child.signalCode === null) {
|
|
187
|
+
await new Promise((r) => { child.on('exit', r); setTimeout(r, 3000); try { stop(child); } catch { r(); } });
|
|
188
|
+
} else { try { if (child) stop(child); } catch { /* already gone */ } }
|
|
189
|
+
try { fsx.rmSync(tmp, { recursive: true, force: true }); } catch { /* best effort */ }
|
|
190
|
+
}
|
|
191
|
+
}
|
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
// Prerequisite planner for a fresh machine (#179, PR1). Pure: from an injected probe it returns the ordered steps a fresh
|
|
2
|
+
// Mac, Windows or Linux needs (Xcode CLT, Homebrew, git, nvm, Node 24, uv, rtk, bun). It never runs a command, never reads
|
|
3
|
+
// the real env or disk; the caller (the engine, later PRs) probes, shows the plan, asks once and runs `commands`.
|
|
4
|
+
// Every URL, flag and version without a pin in core/pins.json is marked VERIFY and listed in docs/compatibility.md.
|
|
5
|
+
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import { fileURLToPath } from 'node:url';
|
|
8
|
+
import { PINS } from './pins.mjs';
|
|
9
|
+
import { bunInstall, rtkInstall } from './system.mjs';
|
|
10
|
+
import { satisfies, compare, minVersion, nvmInstallArgv } from './node-runtime.mjs';
|
|
11
|
+
|
|
12
|
+
const VERIFY_SHA = fileURLToPath(new URL('./verify-sha256.mjs', import.meta.url));
|
|
13
|
+
|
|
14
|
+
// nvm-sh install script and nvm-windows setup: versions and the setup hash come from tests/ci-downloads.json (checked 2026-11-11).
|
|
15
|
+
// The install.sh hash is not pinned anywhere yet. VERIFY
|
|
16
|
+
const NVM_VERSION = 'v0.41.0';
|
|
17
|
+
const NVM_INSTALL_URL = `https://raw.githubusercontent.com/nvm-sh/nvm/${NVM_VERSION}/install.sh`;
|
|
18
|
+
const NVM_WIN = {
|
|
19
|
+
url: 'https://github.com/coreybutler/nvm-windows/releases/download/v2.0.1/nvm-2.0.1-x64-setup.exe',
|
|
20
|
+
sha256: '2ba6ab6290fdc7d1e608e76c97577ca6e1df772b2d59ab8ebc01e10788de8e57',
|
|
21
|
+
};
|
|
22
|
+
// The setup just ran, so this process has no nvm on PATH: read NVM_HOME and NVM_SYMLINK from the saved user or machine environment (nightly fresh-machine, 2026-11-20).
|
|
23
|
+
const NVM_WIN_INSTALL_24 = ['powershell', '-NoProfile', '-NonInteractive', '-Command',
|
|
24
|
+
"foreach ($n in 'NVM_HOME', 'NVM_SYMLINK') { $v = [Environment]::GetEnvironmentVariable($n, 'User'); if (-not $v) { $v = [Environment]::GetEnvironmentVariable($n, 'Machine') }; if ($v) { Set-Item \"env:$n\" $v } }; " +
|
|
25
|
+
"if (-not $env:NVM_HOME) { Write-Error 'NVM_HOME is not set: nvm-windows did not install'; exit 1 }; & (Join-Path $env:NVM_HOME 'nvm.exe') install 24; exit $LASTEXITCODE"];
|
|
26
|
+
// Homebrew installer: commit and sha256 pinned in core/pins.json. VERIFY (unattended behaviour).
|
|
27
|
+
// The uv installer is unpinned (current script). VERIFY
|
|
28
|
+
const BREW = PINS['homebrew-installer'];
|
|
29
|
+
const UV_INSTALL_URL = 'https://astral.sh/uv/install.sh';
|
|
30
|
+
|
|
31
|
+
// Newest `engines.node` floor among the pinned tools; Node 24 is installed under nvm only when nothing meets it.
|
|
32
|
+
const toolFloor = () => ['context-mode', 'gsd-core'].map((k) => PINS[k]?.node).filter(Boolean)
|
|
33
|
+
.reduce((a, b) => (compare(minVersion(b), minVersion(a)) > 0 ? b : a));
|
|
34
|
+
const floorText = (range) => minVersion(range).join('.');
|
|
35
|
+
|
|
36
|
+
// nvm's undo is planned only when ~/.nvm did not exist before this run (`nvmDirExisted`), and runs later: it removes exactly the ~/.nvm
|
|
37
|
+
// of the home the state recorded, and only when every Node under it is one lean-agents installs (the floor's major, v24) and none
|
|
38
|
+
// holds a global package beyond npm, corepack and the npm tools lean-agents installs; otherwise it stays and says why. The Node is a
|
|
39
|
+
// placeholder the engine swaps for the Node running it at undo time (`undoArgv`): no bare `node` on PATH, no path stored.
|
|
40
|
+
export const UNDO_NODE = '<lean-node>';
|
|
41
|
+
export const undoArgv = (argv, execPath = process.execPath) => (argv[0] === UNDO_NODE ? [execPath, ...argv.slice(1)] : argv);
|
|
42
|
+
// Did ~/.nvm exist before this run? A resumed run still owns a ~/.nvm that an earlier, unfinished nvm step created (its recorded
|
|
43
|
+
// undo is not empty); one an earlier run recorded with an empty undo existed before lean-agents and stays the user's.
|
|
44
|
+
export const nvmDirExistedBefore = (savedCommands, dirExists) => !(savedCommands ?? []).some((c) => c.resumeKey === 'prereq:nvm' && c.undo?.length) && dirExists;
|
|
45
|
+
// Runs under `node -e`: argv is [dir, home, major, recorded packages as JSON].
|
|
46
|
+
const NVM_UNDO = [
|
|
47
|
+
"const fs=require('fs'),p=require('path'),[d,h,m,a]=process.argv.slice(1),ok=new Set(['npm','corepack',...JSON.parse(a)]);",
|
|
48
|
+
"const keep=w=>{console.log('kept '+d+': '+w);process.exit()};",
|
|
49
|
+
"if(p.resolve(d)!==p.resolve(h,'.nvm'))keep('it is not the .nvm of the home this install recorded');",
|
|
50
|
+
"let s;try{s=fs.lstatSync(d)}catch{process.exit()}",
|
|
51
|
+
"if(!s.isDirectory())keep('it is not a plain directory');",
|
|
52
|
+
"const ls=x=>{try{return fs.readdirSync(x,{withFileTypes:true})}catch{return[]}},v=p.join(d,'versions','node'),vs=ls(v).filter(e=>e.isDirectory()).map(e=>e.name);",
|
|
53
|
+
"const o=vs.filter(n=>!new RegExp('^v'+m+'[.]').test(n));",
|
|
54
|
+
"if(o.length)keep('it holds Node versions lean-agents did not install ('+o.join(', ')+')');",
|
|
55
|
+
"const g=[];for(const n of vs){const nm=p.join(v,n,'lib','node_modules');for(const e of ls(nm).filter(e=>e.name[0]!=='.')){const q=e.name.startsWith('@')?ls(p.join(nm,e.name)).map(c=>e.name+'/'+c.name):[e.name];for(const x of q)if(!ok.has(x))g.push(x+' ('+n+')')}}",
|
|
56
|
+
"if(g.length)keep('a Node under it has global packages lean-agents did not install ('+g.join(', ')+')');",
|
|
57
|
+
'fs.rmSync(d,{recursive:true,force:true})',
|
|
58
|
+
].join('');
|
|
59
|
+
// The npm tools lean-agents may install globally under that Node (CI-only agent pins excluded).
|
|
60
|
+
const recordedPackages = () => Object.values(PINS).filter((p) => p.kind === 'npm' && !p.ciOnly).map((p) => p.source);
|
|
61
|
+
const nvmUndo = (dir, home, major) => [[UNDO_NODE, '-e', NVM_UNDO, dir, home, String(major), JSON.stringify(recordedPackages())]];
|
|
62
|
+
|
|
63
|
+
// The agents --everything configures: Claude Code and OpenCode 2 everywhere; on Windows the team preset adds the ones found
|
|
64
|
+
// (Copilot CLI, VS Code Copilot, Antigravity) and lists the missing ones so the plan says what it skipped.
|
|
65
|
+
export const TEAM_AGENTS = ['copilot-cli', 'vscode-copilot', 'antigravity'];
|
|
66
|
+
export function everythingAgents({ platform, detected = {}, project = false }) {
|
|
67
|
+
const base = ['claude', 'opencode-v2'];
|
|
68
|
+
if (platform !== 'win32') return { agents: base, skipped: [] };
|
|
69
|
+
const team = TEAM_AGENTS.filter((a) => !(project && a === 'antigravity')); // Antigravity has no project scope
|
|
70
|
+
return { agents: [...base, ...team.filter((a) => detected[a])], skipped: team.filter((a) => !detected[a]) };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// winget ids, brew formulas `rtk` and `uv`, and `--scope user` for Git.Git are unverified on a fresh machine. VERIFY
|
|
74
|
+
const WINGET = (id) => ['winget', 'install', '--id', id, '-e', '--scope', 'user', '--accept-source-agreements', '--accept-package-agreements'];
|
|
75
|
+
|
|
76
|
+
// probe: { platform, arch, home, tmp, execPath, has: { brew, winget, uv, rtk, bun, git, clt, nvm, jq }, nodeActive: '22.20.0' | null,
|
|
77
|
+
// nvmNodes: ['24.15.0'], nvmDirExisted: true (~/.nvm was there before this run, so its undo is empty), proxyEnv: ['HTTPS_PROXY'] (names only), needsGit: false, done: ['prereq:nvm'] (resume stamps), bunInstall, rtkInstall: stubs for tests }
|
|
78
|
+
export function planPrereqs(probe) {
|
|
79
|
+
const { platform, arch = 'x64', home, has = {}, nodeActive = null, nvmNodes = [], nvmDirExisted = false, proxyEnv = [], needsGit = false, done = [], terminals = [], agents = [] } = probe;
|
|
80
|
+
const win = platform === 'win32', mac = platform === 'darwin';
|
|
81
|
+
const P = win ? path.win32 : path.posix;
|
|
82
|
+
const tmp = probe.tmp ?? P.join(home, '.cache', 'lean-agents');
|
|
83
|
+
const node = probe.execPath ?? 'node';
|
|
84
|
+
const nvmDir = P.join(home, '.nvm');
|
|
85
|
+
const floor = toolFloor();
|
|
86
|
+
const fetch = (url, file) => [win ? 'curl.exe' : 'curl', '-fsSL', '--create-dirs', '-o', file, url];
|
|
87
|
+
const steps = [];
|
|
88
|
+
const add = (s) => steps.push({ needsConsent: true, undo: null, skipIf: null, ...s, resumeKey: `prereq:${s.id}` });
|
|
89
|
+
|
|
90
|
+
if (mac) {
|
|
91
|
+
add({
|
|
92
|
+
id: 'xcode-clt', label: 'Xcode Command Line Tools', why: 'Provides git and the compilers Homebrew needs on a fresh Mac.',
|
|
93
|
+
commands: [['xcode-select', '--install']], // opens a system dialog; headless route via softwareupdate VERIFY
|
|
94
|
+
skipIf: has.clt ? 'Command Line Tools are installed' : null,
|
|
95
|
+
});
|
|
96
|
+
add({
|
|
97
|
+
id: 'homebrew', label: 'Homebrew', why: 'Package manager lean-agents uses for rtk, uv and bun on macOS.',
|
|
98
|
+
commands: [fetch(BREW.url, P.join(tmp, 'brew-install.sh')), [node, VERIFY_SHA, P.join(tmp, 'brew-install.sh'), BREW.sha256], ['env', 'NONINTERACTIVE=1', '/bin/bash', P.join(tmp, 'brew-install.sh')]],
|
|
99
|
+
skipIf: has.brew ? 'brew is on PATH' : null, // undo: Homebrew's uninstaller is interactive, so none
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
if (win && needsGit) {
|
|
104
|
+
add({
|
|
105
|
+
id: 'git', label: 'Git', why: 'A selected tool needs git (the release itself does not).',
|
|
106
|
+
commands: has.winget ? [WINGET('Git.Git')] : [], manual: has.winget ? undefined : 'https://git-scm.com/downloads',
|
|
107
|
+
undo: has.winget ? [['winget', 'uninstall', '--id', 'Git.Git', '-e']] : null,
|
|
108
|
+
skipIf: has.git ? 'git is on PATH' : null,
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
if (platform === 'linux') {
|
|
113
|
+
// -E: apt needs the proxy variables, which sudo drops by default. A user with no sudo gets the manual link.
|
|
114
|
+
const sudo = probe.root ? [] : ['sudo', '-E'];
|
|
115
|
+
const aptOk = has.apt && (probe.root || has.sudo);
|
|
116
|
+
const apt = (pkg) => aptOk ? {
|
|
117
|
+
commands: [[...sudo, 'apt-get', 'update', '-qq'], [...sudo, 'apt-get', 'install', '-y', '-qq', '--no-install-recommends', pkg]],
|
|
118
|
+
undo: [[...sudo, 'apt-get', 'remove', '-y', '-qq', pkg]],
|
|
119
|
+
} : { commands: [] };
|
|
120
|
+
|
|
121
|
+
if (needsGit) {
|
|
122
|
+
add({
|
|
123
|
+
id: 'git', label: 'Git', why: "The agents' plugin and skill installs clone with git.",
|
|
124
|
+
...apt('git'), manual: aptOk ? undefined : 'https://git-scm.com/downloads',
|
|
125
|
+
skipIf: has.git ? 'git is on PATH' : null,
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
if (!has.bun) {
|
|
129
|
+
add({
|
|
130
|
+
id: 'unzip', label: 'unzip', why: 'Unpacks the pinned Bun zip.',
|
|
131
|
+
...apt('unzip'), manual: aptOk ? undefined : 'https://infozip.sourceforge.net/UnZip.html',
|
|
132
|
+
skipIf: has.unzip ? 'unzip is on PATH' : null,
|
|
133
|
+
});
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// The brew-based steps below run after the Homebrew step, so a planned brew counts.
|
|
138
|
+
const pm = mac && (has.brew || steps.some((s) => s.id === 'homebrew')) ? 'brew' : win && has.winget ? 'winget' : null;
|
|
139
|
+
|
|
140
|
+
if (win) {
|
|
141
|
+
const setup = P.join(tmp, 'nvm-setup.exe');
|
|
142
|
+
add({
|
|
143
|
+
id: 'nvm', label: 'nvm-windows', why: 'Node manager: lets the tools get Node 24 without touching your Node.',
|
|
144
|
+
commands: [fetch(NVM_WIN.url, setup), [node, VERIFY_SHA, setup, NVM_WIN.sha256], [setup, '/VERYSILENT', '/SUPPRESSMSGBOXES', '/NORESTART']], // admin-free path VERIFY
|
|
145
|
+
skipIf: has.nvm ? 'nvm is installed' : null,
|
|
146
|
+
});
|
|
147
|
+
} else {
|
|
148
|
+
const script = P.join(tmp, 'nvm-install.sh');
|
|
149
|
+
add({
|
|
150
|
+
id: 'nvm', label: 'nvm', why: 'Node manager: lets the tools get Node 24 without touching your Node.',
|
|
151
|
+
// PROFILE=/dev/null keeps the installer away from the shell profile; the engine finds $NVM_DIR itself. Script hash VERIFY.
|
|
152
|
+
commands: [fetch(NVM_INSTALL_URL, script), ['env', `NVM_DIR=${nvmDir}`, 'PROFILE=/dev/null', 'bash', script]],
|
|
153
|
+
undo: nvmDirExisted ? [] : nvmUndo(nvmDir, home, minVersion(floor)[0]),
|
|
154
|
+
skipIf: has.nvm ? 'nvm is installed' : null,
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
const haveFloor = (nodeActive && satisfies(nodeActive, floor)) || nvmNodes.some((v) => satisfies(v, floor));
|
|
159
|
+
add({
|
|
160
|
+
id: 'node-24', label: 'Node 24 (under nvm)', why: `Context Mode and GSD need Node ${floorText(floor)}+; your own Node stays the default.`,
|
|
161
|
+
commands: [win ? NVM_WIN_INSTALL_24 : ['env', `NVM_DIR=${nvmDir}`, ...nvmInstallArgv(24)]], // nvm-windows `install 24` accepts a major: VERIFY
|
|
162
|
+
skipIf: haveFloor ? `Node ${floorText(floor)}+ is already available` : null,
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
const route = (brew, wingetId, manual) => (pm === 'brew' && brew ? [brew] : pm === 'winget' && wingetId ? [WINGET(wingetId)] : null) ?? { manual };
|
|
166
|
+
const tool = (id, label, why, has_, r, extra = {}) => add({
|
|
167
|
+
id, label, why, skipIf: has_ ? `${id} is on PATH` : null, ...extra,
|
|
168
|
+
...(Array.isArray(r) ? { commands: r } : { commands: [], manual: r.manual }),
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
const uvScript = P.join(tmp, 'uv-install.sh');
|
|
172
|
+
tool('uv', 'uv', 'Runs Serena (uvx).', has.uv,
|
|
173
|
+
!win && !pm ? [fetch(UV_INSTALL_URL, uvScript), ['sh', uvScript]] : route(['brew', 'install', 'uv'], 'astral-sh.uv', 'https://docs.astral.sh/uv/getting-started/installation/'), // direct script unpinned: VERIFY
|
|
174
|
+
pm === 'brew' ? { undo: [['brew', 'uninstall', 'uv']] } : pm === 'winget' ? { undo: [['winget', 'uninstall', '--id', 'astral-sh.uv', '-e']] } : {});
|
|
175
|
+
const rtk = !win && !pm ? (probe.rtkInstall ?? rtkInstall)(home, tmp, platform, arch) : null;
|
|
176
|
+
tool('rtk', 'RTK', 'Compresses command output for the agents.', has.rtk,
|
|
177
|
+
rtk ? rtk.run : route(['brew', 'install', 'rtk'], 'rtk-ai.rtk', 'https://github.com/rtk-ai/rtk#installation'),
|
|
178
|
+
rtk ? { undo: rtk.undo } : pm === 'brew' ? { undo: [['brew', 'uninstall', 'rtk']] } : pm === 'winget' ? { undo: [['winget', 'uninstall', '--id', 'rtk-ai.rtk', '-e']] } : {});
|
|
179
|
+
|
|
180
|
+
if (terminals.includes('warp') && agents.includes('claude')) {
|
|
181
|
+
tool('jq', 'jq', 'The Warp plugin for Claude Code reads hook JSON with jq.', has.jq,
|
|
182
|
+
route(['brew', 'install', 'jq'], 'jqlang.jq', 'https://jqlang.org/download/'),
|
|
183
|
+
pm === 'brew' ? { undo: [['brew', 'uninstall', 'jq']] } : pm === 'winget' ? { undo: [['winget', 'uninstall', '--id', 'jqlang.jq', '-e']] } : {});
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const bun = (probe.bunInstall ?? bunInstall)(home, tmp, platform, pm, arch); // probe.bunInstall: tests only
|
|
187
|
+
add({
|
|
188
|
+
id: 'bun', label: 'Bun', why: 'Lets Context Mode run JS and TS.', skipIf: has.bun ? 'bun is installed' : null,
|
|
189
|
+
// the zip lands in tmp
|
|
190
|
+
commands: bun ? [...(mac ? [] : [[node, '-e', 'require("fs").mkdirSync(process.argv[1], { recursive: true })', tmp]]), ...bun.run] : [],
|
|
191
|
+
undo: bun?.undo ?? null,
|
|
192
|
+
...(bun ? {} : { manual: 'https://bun.sh/docs/installation' }),
|
|
193
|
+
});
|
|
194
|
+
|
|
195
|
+
return steps.map((s) => {
|
|
196
|
+
const out = { ...s, skipIf: s.skipIf ?? (done.includes(s.resumeKey) ? 'finished in an earlier run' : null) };
|
|
197
|
+
if (proxyEnv.length && out.commands.length) out.proxyEnv = proxyEnv;
|
|
198
|
+
return out;
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// What is left to run: steps with no skipIf.
|
|
203
|
+
export const pendingPrereqs = (steps) => steps.filter((s) => !s.skipIf);
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// --project mode: the shared setup inside one repository, so a team gets it through git.
|
|
2
|
+
// Rules live once in AGENTS.md; the Copilot and Cursor files only point to it.
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { OWNED_MARK, sha } from './fsops.mjs';
|
|
5
|
+
import { loadCore, renderRules, loadProfile } from './render.mjs';
|
|
6
|
+
import { renderCopilotAgent } from './adapters/copilot-cli.mjs';
|
|
7
|
+
import { vscodeServers } from './adapters/vscode-copilot.mjs';
|
|
8
|
+
import { cursorServers, renderCursorAgent } from './adapters/cursor.mjs';
|
|
9
|
+
|
|
10
|
+
const POINTER = 'Follow the shared rules in `AGENTS.md` at the repository root.';
|
|
11
|
+
|
|
12
|
+
// State holds absolute paths, so it stays in the user's home, never in the repository.
|
|
13
|
+
export function projectStateDir(home, dir) {
|
|
14
|
+
return path.join(home, '.config', 'lean-agents', 'projects', sha(dir).slice(0, 12));
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export function projectPlan(root, dir, o) {
|
|
18
|
+
const core = loadCore(root);
|
|
19
|
+
const profile = loadProfile(root, 'github-copilot');
|
|
20
|
+
const actions = [
|
|
21
|
+
{ kind: 'block', path: path.join(dir, 'AGENTS.md'), body: renderRules(root, o) },
|
|
22
|
+
{ kind: 'block', path: path.join(dir, '.github', 'copilot-instructions.md'), body: `${POINTER}\n` },
|
|
23
|
+
{
|
|
24
|
+
kind: 'file',
|
|
25
|
+
path: path.join(dir, '.cursor', 'rules', 'lean-agents.mdc'),
|
|
26
|
+
content: ['---', 'description: Shared team rules from lean-agents', 'alwaysApply: true', '---', `<!-- ${OWNED_MARK} -->`, POINTER, ''].join('\n'),
|
|
27
|
+
},
|
|
28
|
+
];
|
|
29
|
+
for (const agent of core.agents) {
|
|
30
|
+
actions.push({ kind: 'file', path: path.join(dir, '.github', 'agents', `${agent.name}.agent.md`), content: renderCopilotAgent(agent, profile, o.network.outbound !== 'off') });
|
|
31
|
+
actions.push({ kind: 'file', path: path.join(dir, '.cursor', 'agents', `${agent.name}.md`), content: renderCursorAgent(agent) });
|
|
32
|
+
}
|
|
33
|
+
const vscode = vscodeServers(core, o.tools);
|
|
34
|
+
if (vscode.length) actions.push({ kind: 'json', path: path.join(dir, '.vscode', 'mcp.json'), edits: vscode });
|
|
35
|
+
const cursor = cursorServers(core, o.tools);
|
|
36
|
+
if (cursor.length) actions.push({ kind: 'json', path: path.join(dir, '.cursor', 'mcp.json'), edits: cursor });
|
|
37
|
+
return { actions, commands: [] };
|
|
38
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// Redaction of free text that may reach a public issue or a log.
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import { PROXY_VARS, CA_VARS, SECRET_NAME } from './network.mjs';
|
|
4
|
+
|
|
5
|
+
const esc = (v) => v.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
6
|
+
|
|
7
|
+
// Home paths, the user and host names, proxy and CA values, secret env values, emails and tokens never get through.
|
|
8
|
+
export function redactText(text, { home, env = process.env, user = env.USER || env.USERNAME, host = os.hostname() } = {}) {
|
|
9
|
+
let out = String(text);
|
|
10
|
+
const named = [...PROXY_VARS, ...CA_VARS].flatMap((n) => [env[n], env[n.toLowerCase()]]).filter((v) => v && v.length > 3);
|
|
11
|
+
const secrets = Object.entries(env).filter(([k, v]) => SECRET_NAME.test(k) && v && v.length >= 8).map(([, v]) => v);
|
|
12
|
+
for (const v of new Set([...named, ...secrets])) out = out.replace(new RegExp(esc(v), 'g'), '<redacted>');
|
|
13
|
+
out = out.replace(/\b[a-z][a-z0-9+.-]*:\/\/[^\s/@]*@[^\s]*/gi, '<redacted-url>');
|
|
14
|
+
for (const h of [home].flat().filter(Boolean)) out = out.replace(new RegExp(`${esc(h).replace(/\\\\|\//g, '[\\\\/]')}(?=[\\\\/]|$|[^\\w.-])`, 'gi'), '~');
|
|
15
|
+
out = out
|
|
16
|
+
.replace(/(\/Users\/|\/home\/|[A-Za-z]:[\\/]Users[\\/])[^\/\\\s]+/gi, '$1<user>')
|
|
17
|
+
.replace(/(^|[\s"'=:(])\/root(?=[\/\s"')]|$)/g, '$1/<user>')
|
|
18
|
+
.replace(/(\/private)?\/var\/folders\/[^\/\s]+\/[^\/\s]+/g, '/var/folders/<tmp>')
|
|
19
|
+
.replace(/\/private\/var\/[^\/\s]+/g, '/private/var/<tmp>');
|
|
20
|
+
if (user && user.length > 1) out = out.replace(new RegExp(`\\b${esc(user)}\\b`, 'g'), '<user>');
|
|
21
|
+
if (host && host.length > 2) out = out.replace(new RegExp(`\\b${esc(host)}\\b`, 'gi'), '<host>');
|
|
22
|
+
return out
|
|
23
|
+
.replace(/[\w.+-]+@[\w-]+(\.[\w-]+)+/g, '<email>')
|
|
24
|
+
.replace(/\bAuthorization(["']?\s*[:=]\s*["']?)(Basic|Bearer|Token)\s+[^\s"',;]+/gi, 'Authorization$1$2 <token>')
|
|
25
|
+
.replace(/\beyJ[\w-]+\.eyJ[\w-]+\.[\w-]+/g, '<token>')
|
|
26
|
+
.replace(/\b(gh[pousr]_|github_pat_|sk-|xox[bp]-|glpat-|ya29\.|(?:sk|rk)_(?:live|test)_)[\w-]{8,}|\bnpm_[A-Za-z0-9]{8,}\b|\bhf_[A-Za-z0-9]{8,}\b|\bAKIA[0-9A-Z]{12,}|\bAIza[\w-]{20,}/g, '<token>')
|
|
27
|
+
.replace(/(aws_secret_access_key["']?\s*[:=]\s*["']?)[A-Za-z0-9/+=]{40}/gi, '$1<token>')
|
|
28
|
+
.replace(/\b(Bearer|token)\s+[\w.~+/=-]{8,}/gi, '$1 <token>')
|
|
29
|
+
.replace(/\b([\w-]*(?:api[_-]?key|password|passwd|secret|token)["']?\s*[:=]\s*["']?)[^\s"',;&]+/gi, '$1<redacted>');
|
|
30
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// Renders core/ (rules, neutral subagents) and resolves model tiers from profiles/.
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { pinSpec } from './pins.mjs';
|
|
5
|
+
|
|
6
|
+
export function loadCore(root) {
|
|
7
|
+
const agentsDir = path.join(root, 'core', 'agents');
|
|
8
|
+
const agents = fs
|
|
9
|
+
.readdirSync(agentsDir)
|
|
10
|
+
.filter((f) => f.endsWith('.md'))
|
|
11
|
+
.sort()
|
|
12
|
+
.map((f) => parseAgent(fs.readFileSync(path.join(agentsDir, f), 'utf8')));
|
|
13
|
+
const mcp = JSON.parse(fs.readFileSync(path.join(root, 'core', 'mcp.json'), 'utf8')).servers;
|
|
14
|
+
// "{pin:key}" in a command stands for source@version from core/pins.json.
|
|
15
|
+
for (const s of Object.values(mcp)) s.command = s.command.map((a) => a.replace(/^\{pin:([\w-]+)\}$/, (_, k) => pinSpec(k)));
|
|
16
|
+
return { agents, mcp };
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// Registers a tool's absolute `node_command` (the plugin-less form) instead of its npx command; {node} and {modules} come from the toolNode.
|
|
20
|
+
// `nvmDir` (the nvm lean-agents may use, even when no tool needs it now) adds the absolute shapes lean-agents itself writes there to `legacy`,
|
|
21
|
+
// so a rerun flips an entry either way; only those exact shapes (any digits version) are replaced, never one the user wrote.
|
|
22
|
+
export function useToolNode(core, toolNode, nvm) {
|
|
23
|
+
const s = core.mcp['context-mode'];
|
|
24
|
+
if (nvm && s?.node_command) {
|
|
25
|
+
const v = nvm.win ? path.join(nvm.dir, 'v{semver}') : path.join(nvm.dir, 'versions', 'node', 'v{semver}');
|
|
26
|
+
const node = nvm.win ? path.join(v, 'node.exe') : path.join(v, 'bin', 'node');
|
|
27
|
+
const cli = path.join(nvm.win ? path.join(v, 'node_modules') : path.join(v, 'lib', 'node_modules'), 'context-mode', 'cli.mjs');
|
|
28
|
+
s.legacy = [...(s.legacy ?? []), [node, cli, 'server']];
|
|
29
|
+
}
|
|
30
|
+
if (!toolNode || !s?.node_command) return core;
|
|
31
|
+
s.command = s.node_command.map((a) => a.replace('{node}', toolNode.node).replace(/^\{modules\}\/(.*)$/, (_, rest) => path.join(toolNode.modules, rest)));
|
|
32
|
+
return core;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function parseAgent(text) {
|
|
36
|
+
const m = text.match(/^---\n([\s\S]*?)\n---\n([\s\S]*)$/);
|
|
37
|
+
if (!m) throw new Error('agent file needs YAML frontmatter');
|
|
38
|
+
const meta = {};
|
|
39
|
+
for (const line of m[1].split('\n')) {
|
|
40
|
+
const kv = line.match(/^(\w+):\s*(.*?)\s*(#.*)?$/);
|
|
41
|
+
if (kv) meta[kv[1]] = kv[2];
|
|
42
|
+
}
|
|
43
|
+
return { ...meta, body: m[2].trim() };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
const TEXT = {
|
|
47
|
+
en: {
|
|
48
|
+
lang: 'Always reply in English.',
|
|
49
|
+
serena: ', Serena symbol tools',
|
|
50
|
+
contextMode: '- Output that may pass 20 lines or that you will filter (logs, test runs, CI, API responses): use Context Mode (`ctx_batch_execute`, `ctx_execute`) and print only the answer you derive. RTK compression does not replace this.\n- Web pages: `ctx_fetch_and_index`, then `ctx_search`.\n- Short output you only read, and commands that change state (git, installs): plain shell.\n',
|
|
51
|
+
playwright: '- Real browser actions (clicks, forms, screenshots): Playwright.\n',
|
|
52
|
+
load: '- If one of these tools is deferred or not loaded, load it first (Claude Code: `ToolSearch`). Do not fall back to the shell for that reason.\n',
|
|
53
|
+
},
|
|
54
|
+
es: {
|
|
55
|
+
lang: 'Responde siempre en español.',
|
|
56
|
+
serena: ', símbolos con Serena',
|
|
57
|
+
contextMode: '- Salidas que puedan pasar de 20 líneas o que vayas a filtrar (logs, tests, CI, respuestas de API): usa Context Mode (`ctx_batch_execute`, `ctx_execute`) e imprime solo la respuesta derivada. La compresión de RTK no reemplaza esto.\n- Páginas web: `ctx_fetch_and_index`, luego `ctx_search`.\n- Salidas cortas que solo vas a leer y comandos que cambian estado (git, instalaciones): shell normal.\n',
|
|
58
|
+
playwright: '- Acciones reales en el navegador (clics, formularios, capturas): Playwright.\n',
|
|
59
|
+
load: '- Si una de estas herramientas está diferida o sin cargar, cárgala primero (Claude Code: `ToolSearch`). No vuelvas al shell por esa razón.\n',
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
export function renderRules(root, { lang, tools, agents = [] }) {
|
|
64
|
+
const file = lang === 'es' ? 'AGENTS.es.md' : 'AGENTS.md';
|
|
65
|
+
const t = TEXT[lang] ?? TEXT.en;
|
|
66
|
+
// Claude Code has Claude in Chrome, so playwright-extension alone adds nothing for a Claude-only install.
|
|
67
|
+
const effective = agents.length === 1 && agents[0] === 'claude' ? tools.filter((n) => n !== 'playwright-extension') : tools;
|
|
68
|
+
const hasTool = (...names) => names.some((name) => effective.includes(name));
|
|
69
|
+
const toolRules =
|
|
70
|
+
(hasTool('context-mode') ? t.contextMode : '') +
|
|
71
|
+
(hasTool('playwright', 'playwright-extension') ? t.playwright : '') +
|
|
72
|
+
(hasTool('context-mode', 'playwright', 'playwright-extension', 'serena') ? t.load : '');
|
|
73
|
+
const header = `<!-- ${'managed by lean-agents'}: edit core/AGENTS.md upstream or add your own rules in a separate file -->\n`;
|
|
74
|
+
return (
|
|
75
|
+
header +
|
|
76
|
+
fs
|
|
77
|
+
.readFileSync(path.join(root, 'core', file), 'utf8')
|
|
78
|
+
.replace('{{LANG_RULE}}', t.lang)
|
|
79
|
+
.replace('{{SERENA_HINT}}', tools.includes('serena') ? t.serena : '')
|
|
80
|
+
.replace('{{TOOL_RULES}}', toolRules)
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export function loadProfile(root, name) {
|
|
85
|
+
if (!name) return null;
|
|
86
|
+
const file = path.join(root, 'profiles', `${name}.json`);
|
|
87
|
+
if (!fs.existsSync(file)) {
|
|
88
|
+
const known = fs.readdirSync(path.join(root, 'profiles')).filter((f) => f.endsWith('.json')).map((f) => f.slice(0, -5));
|
|
89
|
+
throw new Error(`unknown profile "${name}". Available: ${known.join(', ')}`);
|
|
90
|
+
}
|
|
91
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Tier for an agent name, honoring per-profile overrides (e.g. review on fast for Claude).
|
|
95
|
+
export function tierFor(profile, agentName, defaultTier) {
|
|
96
|
+
return profile?.overrides?.[agentName] ?? defaultTier;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export function modelFor(profile, tier) {
|
|
100
|
+
return profile?.tiers?.[tier] ?? null;
|
|
101
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Shell rc files and the marked PATH block a POSIX install writes into them, so a new terminal finds what it installed (#335).
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
|
|
5
|
+
// An existing .zshrc, .bashrc or .bash_profile, else .zshrc for a zsh user, else .profile.
|
|
6
|
+
export const rcFiles = (home, shell, fsx = fs) => {
|
|
7
|
+
const have = ['.zshrc', '.bashrc', '.bash_profile'].filter((f) => fsx.existsSync(path.join(home, f)));
|
|
8
|
+
return (have.length ? have : [/zsh$/.test(shell ?? '') ? '.zshrc' : '.profile']).map((f) => path.join(home, f));
|
|
9
|
+
};
|
|
10
|
+
|
|
11
|
+
// dirs: folders under home (e.g. '.local/bin'); brew: the Homebrew prefix this run installs; privateNode: install.sh's own Node.
|
|
12
|
+
// The private Node goes last, so a Node the user already has stays the default.
|
|
13
|
+
export function posixPathBlock({ home, platform, envPath = '', dirs = [], brew = null, privateNode = false, shell, fsx = fs }) {
|
|
14
|
+
if (platform === 'win32') return [];
|
|
15
|
+
const have = new Set(envPath.split(':').map((d) => d.replace(/\/+$/, '')));
|
|
16
|
+
const lines = [];
|
|
17
|
+
if (brew && !have.has(`${brew}/bin`)) lines.push(`[ -x ${brew}/bin/brew ] && eval "$(${brew}/bin/brew shellenv)"`); // a failed Homebrew install must not break every shell
|
|
18
|
+
const add = dirs.filter((d) => !have.has(path.join(home, d)));
|
|
19
|
+
if (add.length) lines.push(`export PATH="${add.map((d) => `$HOME/${d}`).join(':')}:$PATH"`);
|
|
20
|
+
if (privateNode) lines.push('export PATH="$PATH:$HOME/.config/lean-agents/node/bin"');
|
|
21
|
+
return lines.length ? rcFiles(home, shell, fsx).map((p) => ({ kind: 'block', id: 'path', path: p, body: lines.join('\n') })) : [];
|
|
22
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// Data model of the finish-step summary page (#181). Pure: the page (PR3) only renders this object.
|
|
2
|
+
import { redactText } from './redact.mjs';
|
|
3
|
+
|
|
4
|
+
const BAD = new Set(['error', 'missing']);
|
|
5
|
+
|
|
6
|
+
// state: state.json (or null); rows: doctor rows `{ item, status, detail }`; applied: the `printApplied` shape
|
|
7
|
+
// `{ ok, files, commands, errors, version }`; logins: loginRows(); updated: names the update step changed (default none).
|
|
8
|
+
export function buildSummary({ state = null, rows = [], applied = {}, logins = [], updated = [], home, env, lang = 'en' } = {}) {
|
|
9
|
+
const t = (v) => redactText(v, { home, env });
|
|
10
|
+
const list = (a) => (a ?? []).map(t);
|
|
11
|
+
const problems = rows.filter((r) => BAD.has(r.status));
|
|
12
|
+
return {
|
|
13
|
+
lang,
|
|
14
|
+
version: t(applied.version ?? state?.version ?? ''),
|
|
15
|
+
ok: (applied.ok ?? true) && !problems.length,
|
|
16
|
+
action: { logins: logins.map((l) => ({ tool: l.tool, command: t(l.login), state: l.state })) },
|
|
17
|
+
summary: {
|
|
18
|
+
installed: list([...(applied.files ?? []), ...(applied.commands ?? []).filter((c) => c.ok).map((c) => c.desc)]),
|
|
19
|
+
kept: list(rows.filter((r) => r.status === 'changed').map((r) => r.item)),
|
|
20
|
+
updated: list(updated),
|
|
21
|
+
skipped: list(rows.filter((r) => r.status === 'skipped').map((r) => r.item)),
|
|
22
|
+
errors: list(applied.errors),
|
|
23
|
+
doctor: {
|
|
24
|
+
ok: !problems.length,
|
|
25
|
+
counts: rows.reduce((n, r) => ({ ...n, [r.status]: (n[r.status] ?? 0) + 1 }), {}),
|
|
26
|
+
problems: problems.map((r) => ({ item: t(r.item), status: r.status, detail: t(r.detail ?? '') })),
|
|
27
|
+
},
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
}
|