lean-agents 0.8.0 → 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.
Files changed (44) hide show
  1. package/CHANGELOG.md +407 -0
  2. package/README.es.md +130 -24
  3. package/README.md +130 -24
  4. package/core/copilot-usage-tui.js +5 -2
  5. package/core/pins.json +18 -9
  6. package/package.json +3 -2
  7. package/scripts/behavior-diff.sh +47 -0
  8. package/scripts/bump-pins.mjs +14 -3
  9. package/scripts/ci-timing.mjs +61 -0
  10. package/scripts/labels.sh +1 -0
  11. package/scripts/lean.mjs +695 -76
  12. package/scripts/lib/adapters/antigravity.mjs +20 -9
  13. package/scripts/lib/adapters/claude.mjs +7 -2
  14. package/scripts/lib/adapters/copilot-cli.mjs +4 -3
  15. package/scripts/lib/adapters/opencode-v1.mjs +6 -13
  16. package/scripts/lib/adapters/opencode-v2.mjs +51 -3
  17. package/scripts/lib/adopt.mjs +172 -27
  18. package/scripts/lib/agent-lifecycle.mjs +140 -23
  19. package/scripts/lib/backup-stamp.mjs +25 -0
  20. package/scripts/lib/doctor.mjs +86 -14
  21. package/scripts/lib/feedback.mjs +22 -4
  22. package/scripts/lib/fsops.mjs +42 -14
  23. package/scripts/lib/inventory.mjs +5 -4
  24. package/scripts/lib/logins.mjs +28 -0
  25. package/scripts/lib/network.mjs +53 -13
  26. package/scripts/lib/opencode-backup.mjs +204 -0
  27. package/scripts/lib/opencode-upgrade.mjs +441 -0
  28. package/scripts/lib/opencode1.mjs +203 -0
  29. package/scripts/lib/parallel.mjs +7 -2
  30. package/scripts/lib/pins-diff.mjs +33 -0
  31. package/scripts/lib/pins.mjs +7 -2
  32. package/scripts/lib/plugin-health.mjs +191 -0
  33. package/scripts/lib/prereqs.mjs +203 -0
  34. package/scripts/lib/shell-path.mjs +22 -0
  35. package/scripts/lib/summary-data.mjs +30 -0
  36. package/scripts/lib/summary-html.mjs +159 -0
  37. package/scripts/lib/system.mjs +107 -16
  38. package/scripts/lib/terminals.mjs +101 -3
  39. package/scripts/lib/update-plan.mjs +60 -0
  40. package/scripts/lib/upgrade.mjs +112 -11
  41. package/scripts/lib/verify-prompt.mjs +46 -0
  42. package/scripts/pins-latest.mjs +27 -4
  43. package/scripts/release.mjs +26 -1
  44. package/scripts/version-watch.mjs +8 -2
@@ -0,0 +1,159 @@
1
+ // The finish-step summary page (#181): one self-contained HTML file, inline CSS and JS, no network and no external reference.
2
+ // Pure: renders the buildSummary() model; lean.mjs writes it as an owned file and asks before opening it.
3
+ import { redactText } from './redact.mjs';
4
+ import { verifyPrompt } from './verify-prompt.mjs';
5
+ import { feedbackAllowed } from './feedback.mjs';
6
+
7
+ const MAX_ITEMS = 5;
8
+ const RUN = 'npx -y lean-agents@latest';
9
+ const ISSUE_URL = /^https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/issues\/\d+$/;
10
+
11
+ const TEXT = {
12
+ en: {
13
+ title: 'lean-agents install',
14
+ action: 'Action needed',
15
+ login: 'Log in to each tool:',
16
+ state: { ok: 'done', needed: 'needed', unknown: 'not checked' },
17
+ fileOn: 'Then paste this prompt into your agent. It checks the install, fixes what fits the plan after your yes, and files an issue only after your yes.',
18
+ fileOff: 'Then paste this prompt into your agent. It checks the install and fixes what fits the plan after your yes. Nothing is filed.',
19
+ copy: 'Copy prompt', copied: 'Copied', show: 'Show prompt',
20
+ summary: 'Summary',
21
+ installed: (n) => `Installed: ${n} items`,
22
+ kept: 'Kept', updated: 'Updated', skipped: 'Skipped', errors: 'Errors', filed: 'Filed issues', none: 'none',
23
+ more: (n) => `+${n} more`,
24
+ doctorOk: 'Doctor: all checks ok',
25
+ doctorBad: (n) => `Doctor: ${n} to fix`,
26
+ next: 'Next steps',
27
+ steps: ['Restart your agents.', 'Log in to each tool above.', 'Paste the prompt.'],
28
+ how: 'How to use',
29
+ howIntro: `Your agent now has shared rules, cheap subagents and your tools. Run with \`${RUN}\`:`,
30
+ cmds: [['--doctor', 'check the install'], ['--summary', 'rebuild this page'], ['--update', 'update pinned tools'], ['--uninstall', 'undo everything']],
31
+ updates: 'Updates',
32
+ updatesText: 'Auto-update is off for every pinned tool, so versions stay the ones CI tested. A daily CI run checks newer versions and each release lists the changes. Update when you want with `--update`.',
33
+ },
34
+ es: {
35
+ title: 'Instalación de lean-agents',
36
+ action: 'Acción necesaria',
37
+ login: 'Inicia sesión en cada herramienta:',
38
+ state: { ok: 'hecho', needed: 'falta', unknown: 'sin comprobar' },
39
+ fileOn: 'Luego pega este prompt en tu agente. Revisa la instalación, arregla lo que cabe en el plan si dices sí, y crea un issue solo si dices sí.',
40
+ fileOff: 'Luego pega este prompt en tu agente. Revisa la instalación y arregla lo que cabe en el plan si dices sí. No crea nada.',
41
+ copy: 'Copiar prompt', copied: 'Copiado', show: 'Ver prompt',
42
+ summary: 'Resumen',
43
+ installed: (n) => `Instalado: ${n} elementos`,
44
+ kept: 'Conservado', updated: 'Actualizado', skipped: 'Omitido', errors: 'Errores', filed: 'Issues creados', none: 'nada',
45
+ more: (n) => `+${n} más`,
46
+ doctorOk: 'Doctor: todo ok',
47
+ doctorBad: (n) => `Doctor: ${n} por arreglar`,
48
+ next: 'Próximos pasos',
49
+ steps: ['Reinicia tus agentes.', 'Inicia sesión en cada herramienta.', 'Pega el prompt.'],
50
+ how: 'Cómo usarlo',
51
+ howIntro: `Tu agente ya tiene reglas compartidas, subagentes baratos y tus herramientas. Ejecuta con \`${RUN}\`:`,
52
+ cmds: [['--doctor', 'revisa la instalación'], ['--summary', 'rehace esta página'], ['--update', 'actualiza lo fijado'], ['--uninstall', 'deshace todo']],
53
+ updates: 'Actualizaciones',
54
+ updatesText: 'La actualización automática está apagada en cada herramienta fijada, así las versiones son las que probó CI. Un CI diario revisa versiones nuevas y cada release lista los cambios. Actualiza cuando quieras con `--update`.',
55
+ },
56
+ };
57
+
58
+ const CSS = `:root{color-scheme:light dark;--bg:#fff;--fg:#1a1a1a;--muted:#555;--line:#c9c9c9;--code:#f1f1f1;--red-bg:#fdecea;--red-line:#b3261e;--red-fg:#7a1510;--btn:#0b57d0;--btn-fg:#fff}
59
+ @media(prefers-color-scheme:dark){:root{--bg:#161616;--fg:#eee;--muted:#b0b0b0;--line:#444;--code:#262626;--red-bg:#3a1512;--red-line:#f2b8b5;--red-fg:#ffdad6;--btn:#a8c7fa;--btn-fg:#062e6f}}
60
+ body{margin:0;padding:1rem;background:var(--bg);color:var(--fg);font:16px/1.5 system-ui,sans-serif}
61
+ main{max-width:46rem;margin:0 auto}
62
+ h1{font-size:1.4rem}h2{font-size:1.15rem;margin:0 0 .5rem}
63
+ section{border:1px solid var(--line);border-radius:8px;padding:.75rem 1rem;margin:1rem 0}
64
+ section.action{background:var(--red-bg);border:2px solid var(--red-line);color:var(--red-fg)}
65
+ code,pre{background:var(--code);color:var(--fg);border-radius:4px;font:.9em ui-monospace,monospace}
66
+ code{padding:.1em .3em}pre{padding:.75rem;overflow-x:auto;white-space:pre-wrap}
67
+ ul{padding-left:1.25rem;margin:.25rem 0}
68
+ button{min-height:2.75rem;padding:0 1rem;border:0;border-radius:6px;background:var(--btn);color:var(--btn-fg);font:inherit;cursor:pointer}
69
+ button:focus-visible,summary:focus-visible,a:focus-visible{outline:3px solid var(--fg);outline-offset:2px}
70
+ .state{font-weight:600}`;
71
+
72
+ // The copy button: the Clipboard API on a secure page, a selection copy on file://.
73
+ const JS = `(function(){var b=document.getElementById('copy'),p=document.getElementById('prompt'),s=document.getElementById('copied');
74
+ if(!b||!p)return;b.addEventListener('click',function(){var t=p.textContent;
75
+ function done(){s.textContent=b.getAttribute('data-done')}
76
+ if(navigator.clipboard&&navigator.clipboard.writeText){navigator.clipboard.writeText(t).then(done,fallback)}else{fallback()}
77
+ function fallback(){var r=document.createRange();r.selectNodeContents(p);var g=window.getSelection();g.removeAllRanges();g.addRange(r);try{if(document.execCommand('copy'))done()}catch(e){}}})})();`;
78
+
79
+ const esc = (v) => String(v).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
80
+ // `code` spans in the strings above become <code>.
81
+ const md = (s) => esc(s).replace(/`([^`]+)`/g, '<code>$1</code>');
82
+
83
+ // `model` is buildSummary()'s result; `filed` is state.filedIssues; `network` decides whether the prompt may file issues.
84
+ export function renderSummary({ model, filed = [], network, home, env } = {}) {
85
+ const lang = TEXT[model.lang] ? model.lang : 'en';
86
+ const x = TEXT[lang];
87
+ const t = (v) => esc(redactText(v, { home, env }));
88
+ const allowFile = feedbackAllowed(network);
89
+ const prompt = redactText(verifyPrompt({ lang, network }), { home, env });
90
+ const { summary } = model;
91
+ const list = (items) => {
92
+ if (!items.length) return x.none;
93
+ const shown = items.slice(0, MAX_ITEMS).map(t).join(', ');
94
+ return items.length > MAX_ITEMS ? `${shown} ${x.more(items.length - MAX_ITEMS)}` : shown;
95
+ };
96
+ const rows = [`<li>${esc(x.installed(summary.installed.length))}</li>`];
97
+ for (const k of ['kept', 'updated', 'skipped']) rows.push(`<li>${esc(x[k])}: ${list(summary[k])}</li>`);
98
+ if (summary.errors.length) rows.push(`<li>${esc(x.errors)}: ${list(summary.errors)}</li>`);
99
+ const d = summary.doctor;
100
+ rows.push(`<li>${esc(d.ok ? x.doctorOk : x.doctorBad(d.problems.length))}</li>`);
101
+ for (const p of d.problems.slice(0, MAX_ITEMS)) rows.push(`<li><code>${t(p.item)}</code>: ${t(p.status)} ${t(p.detail)}</li>`);
102
+ const links = filed.filter((f) => ISSUE_URL.test(f.url));
103
+ if (links.length) rows.push(`<li>${esc(x.filed)}: ${links.map((f) => `<a href="${esc(f.url)}">${t(f.item)}</a>`).join(', ')}</li>`);
104
+ const logins = model.action.logins
105
+ .map((l) => `<li><code>${t(l.command)}</code> (${t(l.tool)}) <span class="state">${esc(x.state[l.state] ?? x.state.unknown)}</span></li>`)
106
+ .join('');
107
+ return `<!doctype html>
108
+ <!-- managed by lean-agents: rewritten by --summary, removed by --uninstall -->
109
+ <html lang="${lang}">
110
+ <head>
111
+ <meta charset="utf-8">
112
+ <meta name="viewport" content="width=device-width, initial-scale=1">
113
+ <meta name="color-scheme" content="light dark">
114
+ <title>${esc(x.title)}</title>
115
+ <style>${CSS}</style>
116
+ </head>
117
+ <body>
118
+ <main>
119
+ <h1>${esc(x.title)} ${t(model.version)}</h1>
120
+ <section class="action" aria-labelledby="h-action">
121
+ <h2 id="h-action">${esc(x.action)}</h2>
122
+ <p>${esc(x.login)}</p>
123
+ <ul>${logins}</ul>
124
+ <p>${esc(allowFile ? x.fileOn : x.fileOff)}</p>
125
+ <p><button type="button" id="copy" data-done="${esc(x.copied)}">${esc(x.copy)}</button> <span id="copied" role="status" aria-live="polite"></span></p>
126
+ <details><summary>${esc(x.show)}</summary><pre id="prompt">${esc(prompt)}</pre></details>
127
+ </section>
128
+ <section aria-labelledby="h-summary">
129
+ <h2 id="h-summary">${esc(x.summary)}</h2>
130
+ <ul>${rows.join('')}</ul>
131
+ </section>
132
+ <section aria-labelledby="h-next">
133
+ <h2 id="h-next">${esc(x.next)}</h2>
134
+ <ol>${x.steps.map((s) => `<li>${esc(s)}</li>`).join('')}</ol>
135
+ </section>
136
+ <section aria-labelledby="h-how">
137
+ <h2 id="h-how">${esc(x.how)}</h2>
138
+ <p>${md(x.howIntro)}</p>
139
+ <ul>${x.cmds.map(([c, d]) => `<li><code>${esc(c)}</code> ${esc(d)}</li>`).join('')}</ul>
140
+ </section>
141
+ <section aria-labelledby="h-updates">
142
+ <h2 id="h-updates">${esc(x.updates)}</h2>
143
+ <p>${md(x.updatesText)}</p>
144
+ </section>
145
+ </main>
146
+ <script>${JS}</script>
147
+ </body>
148
+ </html>
149
+ `;
150
+ }
151
+
152
+ // Opening the page is a question, never a default: not under CI, --no-open, --yes or --json, and not without a terminal.
153
+ export const canOffer = ({ noOpen, yes, json, env = process.env, tty }) => !noOpen && !yes && !json && !env.CI && !!tty;
154
+
155
+ export function openArgv(platform, file) {
156
+ if (platform === 'darwin') return ['open', file];
157
+ if (platform === 'win32') return ['cmd', '/c', 'start', '', file];
158
+ return ['xdg-open', file];
159
+ }
@@ -4,7 +4,7 @@ import fs from 'node:fs';
4
4
  import os from 'node:os';
5
5
  import path from 'node:path';
6
6
  import { fileURLToPath } from 'node:url';
7
- import { npmSpec, bunPin } from './pins.mjs';
7
+ import { npmSpec, bunPin, rtkPin } from './pins.mjs';
8
8
  import { allowedEnv } from './network.mjs';
9
9
 
10
10
  const isWin = process.platform === 'win32';
@@ -17,13 +17,16 @@ export function which(bin) {
17
17
  // Windows .cmd shims (npm, npx) need a shell; real .exe files must not get one, or paths with spaces split.
18
18
  const useShell = (bin) => isWin && !/\.exe$/i.test(bin) && !/\.exe$/i.test(which(bin) ?? '');
19
19
 
20
- export function version(bin, args = ['--version'], env = {}) {
21
- if (!which(bin)) return null;
20
+ // The version string as the binary prints it, pre-release tag included (2.0.1-beta): what an undo must reinstall.
21
+ export function versionFull(bin, args = ['--version'], env = {}) {
22
+ if (!path.isAbsolute(bin) && !which(bin)) return null;
22
23
  const r = spawnSync(bin, args, { encoding: 'utf8', shell: useShell(bin), timeout: 20000, env: { ...allowedEnv(), ...env } });
23
- const m = `${r.stdout}${r.stderr}`.match(/(\d+)\.(\d+)\.(\d+)/);
24
+ const m = `${r.stdout}${r.stderr}`.match(/\d+\.\d+\.\d+(?:-[0-9A-Za-z][0-9A-Za-z.-]*)?/);
24
25
  return m ? m[0] : 'unknown';
25
26
  }
26
27
 
28
+ export const version = (bin, args, env) => versionFull(bin, args, env)?.replace(/-.*/, '') ?? null;
29
+
27
30
  // A config dir from the environment counts only for the real home or inside --home:
28
31
  // a run with --home must never write outside it, even when the variable is set.
29
32
  export function envDir(home, name, fallback) {
@@ -46,6 +49,35 @@ export function isolate(home) {
46
49
  Object.assign(process.env, env, { HOME: home, USERPROFILE: home });
47
50
  }
48
51
 
52
+ // Where `agy` lives when it is not on PATH. install.sh: $HOME/.local/bin (--dir changes it, unknowable here);
53
+ // install.ps1: %LOCALAPPDATA%\agy\bin; ~/.gemini/bin/agy.exe was seen on Windows in #211 (who writes it: VERIFY).
54
+ export function agyCandidates(home, platform = process.platform, env = process.env) {
55
+ if (platform !== 'win32') return [path.posix.join(home, '.local', 'bin', 'agy')];
56
+ return [env.LOCALAPPDATA && path.win32.join(env.LOCALAPPDATA, 'agy', 'bin', 'agy.exe'), path.win32.join(home, '.gemini', 'bin', 'agy.exe')].filter(Boolean);
57
+ }
58
+
59
+ // PATH first, then the candidates above. Returns a command that can be spawned, or null.
60
+ export function findAgy(home, platform = process.platform, env = process.env) {
61
+ return which('agy') ? 'agy' : agyCandidates(home, platform, env).find(exists) ?? null;
62
+ }
63
+
64
+ // Antigravity IDE folders and the VS Code extension, by existence only (#216): nothing is read or written.
65
+ // The extension folder name is lowercase on disk (`google.google-antigravity-<version>`); Windows and Linux paths are VERIFY.
66
+ export function antigravityFootprint(home, fsx = fs) {
67
+ const found = [];
68
+ for (const d of ['antigravity-ide', 'antigravity-cli', 'antigravity']) {
69
+ const p = path.join(home, '.gemini', d);
70
+ if (fsx.existsSync(p)) found.push({ name: d === 'antigravity' ? 'antigravity (legacy)' : d, file: p });
71
+ }
72
+ const ext = path.join(home, '.vscode', 'extensions');
73
+ let names = [];
74
+ try { names = fsx.readdirSync(ext); } catch { /* no VS Code extensions folder */ }
75
+ for (const n of names.filter((x) => x.toLowerCase().startsWith('google.google-antigravity'))) found.push({ name: 'vscode extension Google.google-antigravity', file: path.join(ext, n) });
76
+ return found;
77
+ }
78
+
79
+ export const agyVersion = (home) => { const a = findAgy(home); return a && version(a); };
80
+
49
81
  export function detectAgents() {
50
82
  const found = {};
51
83
  const claude = version('claude');
@@ -54,7 +86,7 @@ export function detectAgents() {
54
86
  if (oc) found[oc.startsWith('1.') ? 'opencode-v1' : 'opencode-v2'] = oc;
55
87
  const copilot = version('copilot');
56
88
  if (copilot) found['copilot-cli'] = copilot;
57
- const agy = version('agy');
89
+ const agy = agyVersion(os.homedir());
58
90
  if (agy) found.antigravity = agy;
59
91
  const code = version('code');
60
92
  if (code) found['vscode-copilot'] = code;
@@ -106,12 +138,15 @@ export function gitHint(pm, present = which('git')) {
106
138
 
107
139
  // Antigravity CLI and app, only when the user picked Antigravity. Only ids checked upstream (2026-11-03) run;
108
140
  // the rest print the vendor link. Windows CLI: `Google.AntigravityCLI` has no documented scope, so install.ps1 stays manual.
141
+ // #147: Homebrew installs whatever version the cask has today; it cannot install an older one or a cask from a URL.
142
+ export const BREW_AGY_LIMIT = 'Homebrew cannot pin or verify this cask: you get its current version, unpinned by lean-agents. VERIFY';
143
+
109
144
  export function antigravityPrereqs(pm, platform, home, app = true) {
110
145
  const out = [];
111
146
  const winApp = pm === 'winget' && platform === 'win32';
112
- if (!which('agy')) {
147
+ if (!findAgy(home, platform)) {
113
148
  out.push(platform === 'darwin' && pm === 'brew'
114
- ? { desc: 'install agy', run: [['brew', 'install', '--cask', 'antigravity-cli']] }
149
+ ? { desc: `install agy (${BREW_AGY_LIMIT})`, run: [['brew', 'install', '--cask', 'antigravity-cli']] }
115
150
  : { desc: `agy is missing: install it from https://antigravity.google/docs/getting-started`, run: [], manual: true });
116
151
  }
117
152
  if (!app) return out;
@@ -130,6 +165,23 @@ export function antigravityPrereqs(pm, platform, home, app = true) {
130
165
  // Linux and Windows: the pinned release zip is downloaded to a file, checked against the pinned SHA256 and only then extracted,
131
166
  // so no upstream installer script runs. Linux: no shell profile edit (the engine finds ~/.bun/bin itself). Windows: ~\.bun\bin goes on the user PATH.
132
167
  const VERIFY = fileURLToPath(new URL('./verify-sha256.mjs', import.meta.url));
168
+ const psQ = (s) => s.replace(/'/g, "''"); // PowerShell single-quote escape for a profile path like O'Neil
169
+ const psRun = (script) => ['powershell', '-NoProfile', '-NonInteractive', '-Command', script];
170
+ const psAddPath = (bin) => `$p = [string][Environment]::GetEnvironmentVariable('Path', 'User'); if (($p -split ';').TrimEnd('\\') -notcontains '${psQ(bin)}'.TrimEnd('\\')) { [Environment]::SetEnvironmentVariable('Path', ($p.TrimEnd(';') + ';${psQ(bin)}'), 'User') }`;
171
+ const psRemovePath = (bin) => `$p = [string][Environment]::GetEnvironmentVariable('Path', 'User'); [Environment]::SetEnvironmentVariable('Path', (($p -split ';' | Where-Object { $_ -and $_.TrimEnd('\\') -ne '${psQ(bin)}'.TrimEnd('\\') }) -join ';'), 'User')`;
172
+
173
+ export function bunPathCommand(home) {
174
+ const bin = path.join(home, '.bun', 'bin');
175
+ return {
176
+ // tool bun-path, not bun: a moved Bun pin must not undo and re-record this PATH entry.
177
+ tool: 'bun-path', desc: 'put ~\\.bun\\bin on your user PATH (open a new terminal)', optional: true,
178
+ run: [psRun(psAddPath(bin))],
179
+ undo: [psRun(psRemovePath(bin))],
180
+ // Already in the saved user PATH (only this shell is stale): skip, so --uninstall never removes an entry the user made.
181
+ skipIfOutput: { cmd: psRun(`if (([string][Environment]::GetEnvironmentVariable('Path', 'User') -split ';').TrimEnd('\\') -contains '${psQ(bin)}'.TrimEnd('\\')) { exit 0 } else { exit 1 }`) },
182
+ };
183
+ }
184
+
133
185
  export function bunInstall(home, dir, platform, pm, arch = process.arch) {
134
186
  const bunDir = path.join(home, '.bun');
135
187
  if (platform === 'darwin') {
@@ -141,16 +193,16 @@ export function bunInstall(home, dir, platform, pm, arch = process.arch) {
141
193
  const zip = path.join(dir, `${name}-${version}.zip`);
142
194
  const download = [platform === 'win32' ? 'curl.exe' : 'curl', '-fsSL', '-o', zip, `https://github.com/oven-sh/bun/releases/download/bun-v${version}/${name}.zip`];
143
195
  const verify = [process.execPath, VERIFY, zip, sha256[name.slice(4)]];
144
- const rm = [process.execPath, '-e', 'require("fs").rmSync(process.argv[1], { recursive: true, force: true })', bunDir];
196
+ // Undo removes only the binary this install put there, then the dirs it made if they are empty: ~/.bun may hold the user's cache or global packages.
197
+ const exe = platform === 'win32' ? 'bun.exe' : 'bun';
198
+ const rm = [process.execPath, '-e', `const fs = require("fs"), p = require("path"), d = p.join(require("os").homedir(), ".bun"), b = p.join(d, "bin"); if (p.resolve(process.argv[1]) !== d) { console.error("refusing to remove under " + process.argv[1] + ": not the Bun dir lean-agents installed"); process.exit(1); } try { fs.unlinkSync(p.join(b, "${exe}")); } catch {} for (const x of [b, d]) try { fs.rmdirSync(x); } catch {}`, bunDir];
145
199
  if (platform === 'win32') {
146
200
  const bin = path.join(bunDir, 'bin');
147
201
  const tmp = path.join(dir, `${name}-${version}`);
148
- const q = (s) => s.replace(/'/g, "''"); // PowerShell single-quote escape for a profile path like O'Neil
149
- const ps = (script) => ['powershell', '-NoProfile', '-NonInteractive', '-Command', script];
150
202
  return {
151
203
  tool: 'bun', desc: `install bun ${version}`, optional: true,
152
- run: [download, verify, ps(`Expand-Archive -Force -LiteralPath '${q(zip)}' -DestinationPath '${q(tmp)}'; New-Item -ItemType Directory -Force '${q(bin)}' | Out-Null; Move-Item -Force '${q(path.join(tmp, name, 'bun.exe'))}' '${q(path.join(bin, 'bun.exe'))}'; Remove-Item -Recurse -Force '${q(tmp)}'; $p = [string][Environment]::GetEnvironmentVariable('Path', 'User'); if (($p -split ';') -notcontains '${q(bin)}') { [Environment]::SetEnvironmentVariable('Path', ($p.TrimEnd(';') + ';${q(bin)}'), 'User') }`)],
153
- undo: [rm, ps(`$p = [string][Environment]::GetEnvironmentVariable('Path', 'User'); [Environment]::SetEnvironmentVariable('Path', (($p -split ';' | Where-Object { $_ -and $_ -ne '${q(bin)}' }) -join ';'), 'User')`)],
204
+ run: [download, verify, psRun(`Expand-Archive -Force -LiteralPath '${psQ(zip)}' -DestinationPath '${psQ(tmp)}'; New-Item -ItemType Directory -Force '${psQ(bin)}' | Out-Null; Move-Item -Force '${psQ(path.join(tmp, name, 'bun.exe'))}' '${psQ(path.join(bin, 'bun.exe'))}'; Remove-Item -Recurse -Force '${psQ(tmp)}'; ${psAddPath(bin)}`)],
205
+ undo: [rm, psRun(psRemovePath(bin))],
154
206
  };
155
207
  }
156
208
  return {
@@ -160,19 +212,58 @@ export function bunInstall(home, dir, platform, pm, arch = process.arch) {
160
212
  };
161
213
  }
162
214
 
215
+ export function rtkInstall(home, dir, platform, arch = process.arch) {
216
+ if (platform !== 'linux') return null;
217
+ const P = path.posix; // Linux steps, even when planned (tests) on Windows
218
+ const { version, sha256 } = rtkPin();
219
+ const aarch = arch === 'arm64' || arch === 'aarch64' ? 'aarch64' : (arch === 'x64' || arch === 'x86_64' ? 'x64' : null);
220
+ if (!aarch) return null;
221
+ const hash = sha256?.[`linux-${aarch}`];
222
+ if (!hash) return null;
223
+ const triple = `${aarch === 'aarch64' ? 'aarch64' : 'x86_64'}-unknown-linux-musl`;
224
+ const tarball = P.join(dir, `rtk-${triple}-${version}.tar.gz`);
225
+ const download = ['curl', '-fsSL', '--create-dirs', '-o', tarball, `https://github.com/rtk-ai/rtk/releases/download/${version}/rtk-${triple}.tar.gz`];
226
+ const verify = [process.execPath, VERIFY, tarball, hash];
227
+ const binDir = P.join(home, '.local', 'bin');
228
+ const bin = P.join(binDir, 'rtk');
229
+ const rm = [process.execPath, '-e', 'require("fs").rmSync(process.argv[1], { force: true })', bin]; // only the binary: ~/.local/bin holds other tools
230
+ return {
231
+ tool: 'rtk', desc: `install rtk ${version}`, optional: true,
232
+ run: [download, verify, ['mkdir', '-p', binDir], ['tar', '-xzf', tarball, '-C', binDir, 'rtk']],
233
+ undo: [rm],
234
+ };
235
+ }
236
+
163
237
  export const bunPresent = (home) => Boolean(which('bun')) || fs.existsSync(path.join(home, '.bun', 'bin', isWin ? 'bun.exe' : 'bun'));
164
238
 
165
- export function run(argv, { dryRun, log, env }) {
239
+ // Node < 24.20 on Windows can abort on exit after the skills CLI finished (nodejs/node#56645); its "Done!" is the proof.
240
+ export const exitCrashAfterDone = (argv, status, out) => status !== 0 && argv.some((a) => /^skills@/.test(a)) && /Done!/.test(out) && /UV_HANDLE_CLOSING/.test(out);
241
+
242
+ // `codes` collects the exit status; `json` sends the child's stdout to stderr so stdout stays one JSON object.
243
+ export function run(argv, { dryRun, log, env, json, codes }) {
166
244
  log(` $ ${argv.join(' ')}`);
167
245
  if (dryRun) return true;
168
- const r = spawnSync(argv[0], argv.slice(1), { stdio: 'inherit', shell: useShell(argv[0]), env: { ...allowedEnv(), ...env } });
246
+ const isSkills = argv.some((a) => /^skills@/.test(a));
247
+ const r = isSkills
248
+ ? spawnSync(argv[0], argv.slice(1), { stdio: ['inherit', 'pipe', 'pipe'], encoding: 'utf8', shell: useShell(argv[0]), env: { ...allowedEnv(), ...env } })
249
+ : spawnSync(argv[0], argv.slice(1), { stdio: json ? ['inherit', 2, 2] : 'inherit', shell: useShell(argv[0]), env: { ...allowedEnv(), ...env } });
250
+ if (isSkills) {
251
+ (json ? process.stderr : process.stdout).write(r.stdout ?? '');
252
+ process.stderr.write(r.stderr ?? '');
253
+ }
254
+ codes?.push(r.status ?? -1);
255
+ if (exitCrashAfterDone(argv, r.status, `${r.stdout ?? ''}${r.stderr ?? ''}`)) {
256
+ log(' (the skills CLI finished, then Node crashed on exit: nodejs/node#56645, fixed in Node 24.20; counted as done)');
257
+ return true;
258
+ }
169
259
  return r.status === 0;
170
260
  }
171
261
 
172
262
  export function quiet(argv, timeout = 30000, env = {}) {
173
263
  const r = spawnSync(argv[0], argv.slice(1), { encoding: 'utf8', shell: useShell(argv[0]), timeout, env: { ...allowedEnv(), ...env } });
174
- return { ok: r.status === 0, out: `${r.stdout ?? ''}${r.stderr ?? ''}` };
264
+ // `failed`: the command did not finish (timeout, signal, not runnable), so a non-zero status says nothing about its answer.
265
+ return { ok: r.status === 0, failed: Boolean(r.error || r.signal), out: `${r.stdout ?? ''}${r.stderr ?? ''}` };
175
266
  }
176
267
 
177
- export const exists = (p) => fs.existsSync(p);
268
+ export const exists = (p) => Array.isArray(p) ? p.some(x => fs.existsSync(x)) : fs.existsSync(p);
178
269
 
@@ -1,10 +1,14 @@
1
1
  // Warp and Orca: detect the app, then plan the agent integrations for a user who already has it.
2
2
  // The terminal apps themselves are never installed.
3
3
  import fs from 'node:fs';
4
+ import os from 'node:os';
4
5
  import path from 'node:path';
5
6
  import { which, quiet } from './system.mjs';
6
7
  import { hasProxy } from './network.mjs';
7
- import { skillSource, skillsCli } from './pins.mjs';
8
+ import { skillSource, skillsCli, PINS } from './pins.mjs';
9
+ import { fileURLToPath } from 'node:url';
10
+
11
+ const VERIFY = fileURLToPath(new URL('./verify-sha256.mjs', import.meta.url));
8
12
 
9
13
  export const TERMINALS = ['warp', 'orca'];
10
14
  // Skills CLI agent ids; VS Code Copilot reads ~/.copilot/skills like Copilot CLI.
@@ -40,8 +44,101 @@ export function parseTerminal(v) {
40
44
  // Commands only: OpenCode plugin entries go into the OpenCode adapter's own json edit, because two
41
45
  // json actions on one file would each start from the unedited text.
42
46
  // `system` is false for --home runs: Windows user env changes are real-machine only.
43
- export function terminalCommands({ terminals, agents, network = {}, platform = process.platform, env = process.env, system = true, readEnv = readWindowsEnv }) {
47
+ export function terminalCommands({ home, terminals = [], installTerminals = [], agents = [], network = {}, platform = process.platform, env = process.env, system = true, readEnv = readWindowsEnv }) {
44
48
  const commands = [];
49
+
50
+ const arch = platform === 'darwin' ? process.arch : 'x64';
51
+ const warpPin = PINS['warp-app'];
52
+ const orcaPin = PINS['orca-app'];
53
+ const canInstall = system && (platform === 'darwin' || platform === 'win32');
54
+
55
+ if (canInstall && installTerminals.includes('warp')) {
56
+ if (platform === 'darwin') {
57
+ commands.push({
58
+ tool: 'warp',
59
+ desc: 'Install Warp app',
60
+ skipIfExists: [path.join(home, 'Applications', 'Warp.app'), '/Applications/Warp.app'],
61
+ run: [['bash', '-c', 'if command -v brew >/dev/null 2>&1; then brew install --cask warp; else echo "Error: Homebrew is required to install Warp on macOS. Please install Warp manually from https://warp.dev" >&2; exit 1; fi']],
62
+ undo: [['bash', '-c', 'if command -v brew >/dev/null 2>&1; then brew uninstall --cask warp; fi']],
63
+ });
64
+ } else if (platform === 'win32') {
65
+ const url = warpPin.url['windows-x64'];
66
+ const sha = warpPin.sha256['windows-x64'];
67
+ const exe = path.join(os.tmpdir(), 'warp-installer.exe');
68
+ const local = env.LOCALAPPDATA;
69
+ commands.push({
70
+ tool: 'warp',
71
+ desc: 'Install Warp app',
72
+ skipIfExists: [`${local}\\Programs\\Warp`],
73
+ run: [
74
+ ['curl', '-fsSL', '-o', exe, url],
75
+ ['node', VERIFY, exe, sha],
76
+ [exe, '/CURRENTUSER', '/VERYSILENT']
77
+ ],
78
+ always: [
79
+ ps(`if (Test-Path "${exe}") { Remove-Item "${exe}" }`)
80
+ ],
81
+ // Inno Setup cancels silently while Warp runs and relaunches from %TEMP%; refuse, then wait for it.
82
+ undo: [ps(`$u = "$env:LOCALAPPDATA\\Programs\\Warp\\unins000.exe"; if (-not (Test-Path $u)) { exit 0 }; if (Get-Process -Name warp -ErrorAction SilentlyContinue) { Write-Error 'Warp is running: close it, then run --uninstall again'; exit 1 }; $p = Start-Process -FilePath $u -ArgumentList '/VERYSILENT','/SUPPRESSMSGBOXES','/NORESTART' -Wait -PassThru; for ($i = 0; $i -lt 30 -and (Test-Path $u); $i++) { Start-Sleep 2 }; if (Test-Path $u) { Write-Error "Warp uninstaller exit code $($p.ExitCode)"; exit 1 }`)],
83
+ });
84
+ }
85
+ }
86
+
87
+ if (canInstall && installTerminals.includes('orca')) {
88
+ if (platform === 'darwin') {
89
+ const key = arch === 'arm64' ? 'darwin-arm64' : 'darwin-x64';
90
+ const url = orcaPin.url[key];
91
+ const sha = orcaPin.sha256[key];
92
+ const script = `set -e
93
+ DIR=$(mktemp -d)
94
+ MOUNT="$DIR/mount"
95
+ MOUNTED=0
96
+ cleanup() {
97
+ if [ "$MOUNTED" -eq 1 ]; then
98
+ hdiutil detach "$MOUNT" -force >/dev/null 2>&1 || true
99
+ fi
100
+ rm -rf "$DIR"
101
+ }
102
+ trap cleanup EXIT
103
+ curl -fsSL -o "$DIR/orca.dmg" "${url}"
104
+ node "${VERIFY}" "$DIR/orca.dmg" "${sha}"
105
+ hdiutil attach -nobrowse -readonly -mountpoint "$MOUNT" "$DIR/orca.dmg"
106
+ MOUNTED=1
107
+ mkdir -p "${home}/Applications"
108
+ ditto "$MOUNT/Orca.app" "${home}/Applications/Orca.app"
109
+ `;
110
+ commands.push({
111
+ tool: 'orca',
112
+ desc: 'Install Orca app',
113
+ skipIfExists: [path.join(home, 'Applications', 'Orca.app'), '/Applications/Orca.app'],
114
+ run: [
115
+ ['bash', '-c', script]
116
+ ],
117
+ undo: [['rm', '-rf', path.join(home, 'Applications', 'Orca.app')]],
118
+ });
119
+ } else if (platform === 'win32') {
120
+ const url = orcaPin.url['windows-x64'];
121
+ const sha = orcaPin.sha256['windows-x64'];
122
+ const exe = path.join(os.tmpdir(), 'orca-installer.exe');
123
+ const local = env.LOCALAPPDATA;
124
+ commands.push({
125
+ tool: 'orca',
126
+ desc: 'Install Orca app',
127
+ skipIfExists: [`${local}\\Programs\\Orca`],
128
+ run: [
129
+ ['curl', '-fsSL', '-o', exe, url],
130
+ ['node', VERIFY, exe, sha],
131
+ [exe, '/currentuser', '/S']
132
+ ],
133
+ always: [
134
+ ps(`if (Test-Path "${exe}") { Remove-Item "${exe}" }`)
135
+ ],
136
+ // The NSIS uninstaller relaunches itself from %TEMP% and returns at once: wait until it has removed itself.
137
+ undo: [ps(`$u = "$env:LOCALAPPDATA\\Programs\\Orca\\Uninstall Orca.exe"; if (-not (Test-Path $u)) { exit 0 }; Start-Process -FilePath $u -ArgumentList '/S' -Wait; for ($i = 0; $i -lt 60 -and (Test-Path $u); $i++) { Start-Sleep 2 }; if (Test-Path $u) { Write-Error 'Orca uninstaller did not finish in 120 s'; exit 1 }`)],
138
+ });
139
+ }
140
+ }
141
+
45
142
  if (terminals.includes('warp') && agents.includes('claude')) {
46
143
  commands.push({
47
144
  tool: 'warp',
@@ -111,7 +208,8 @@ function orcaWindowsCommands({ network, env, readEnv }) {
111
208
  // MSYSTEM alone (a shell started from Git Bash) carries no path, so it is not a source here.
112
209
  export function gitBashPath({ platform = process.platform, env = process.env } = {}) {
113
210
  if (platform !== 'win32') return null;
114
- const roots = [env.ProgramFiles, env['ProgramFiles(x86)'], env.LOCALAPPDATA && path.join(env.LOCALAPPDATA, 'Programs')];
211
+ // USERPROFILE too: winget's user-scope Git follows the profile folder, which differs from LOCALAPPDATA when USERPROFILE is overridden.
212
+ const roots = [env.ProgramFiles, env['ProgramFiles(x86)'], env.LOCALAPPDATA && path.join(env.LOCALAPPDATA, 'Programs'), env.USERPROFILE && path.join(env.USERPROFILE, 'AppData', 'Local', 'Programs')];
115
213
  for (const d of roots) {
116
214
  if (!d) continue;
117
215
  const p = path.join(d, 'Git', 'bin', 'bash.exe');
@@ -0,0 +1,60 @@
1
+ // The --update plan (#182): one row per tool `installed -> release pin`, what is held back, and the CHANGELOG notes
2
+ // since the installed lean-agents version. Pure: versions, state and the changelog text are passed in; no I/O, no network.
3
+ import { compare } from './node-runtime.mjs';
4
+ import { pinInUse } from './pins.mjs';
5
+
6
+ // Agent CLI binary -> [pin key, key in agents.json]. Cursor and Antigravity have no version pin, so they get no row.
7
+ const AGENTS = { claude: ['claude-code', 'claude'], opencode: ['opencode-v2', 'opencode-v2'], copilot: ['copilot-cli', 'copilot-cli'] };
8
+ const major = (v) => String(v).replace(/^v/, '').split('.')[0];
9
+ // `download` and `ciOnly` pins never reach state.pins (see pins.mjs), so they cannot be rows here either.
10
+ const tracked = (p) => !p.ciOnly && p.kind !== 'download';
11
+
12
+ // action: update (will move to the pin), held (never moved), major (pin is another major), own (not installed by lean-agents).
13
+ // `installed`: versions of the binaries on PATH ({ claude, opencode, copilot }, null when absent). `owned`: agents.json `agents` keys.
14
+ export function planUpdate({ saved, pins, installed = {}, owned = [] }) {
15
+ const rows = [];
16
+ for (const [tool, was] of Object.entries(saved.pins ?? {})) {
17
+ const p = pins[tool];
18
+ if (!p || !tracked(p) || p.version === was || !pinInUse(tool, saved.options)) continue;
19
+ rows.push({ tool, installed: was, pinned: p.version, action: p.hold ? 'held' : 'update', reason: p.hold ? 'held pin' : null });
20
+ }
21
+ for (const [bin, [key, agent]] of Object.entries(AGENTS)) {
22
+ const have = installed[bin];
23
+ if (!have || have === 'unknown') continue;
24
+ if (bin === 'opencode' && major(have) === '1') {
25
+ rows.push({ tool: 'opencode-v1', installed: have, pinned: pins['opencode-v1']?.version ?? null, action: 'held', reason: 'OpenCode 1.x is never updated by lean-agents' });
26
+ continue;
27
+ }
28
+ const pinned = pins[key]?.version;
29
+ if (!pinned || compare(have, pinned) >= 0) continue;
30
+ const base = { tool: key, installed: have, pinned };
31
+ if (!owned.includes(agent)) rows.push({ ...base, action: 'own', reason: 'installed by you, left alone' });
32
+ else if (major(have) !== major(pinned)) rows.push({ ...base, action: 'major', reason: `crosses major ${major(have)} -> ${major(pinned)}, update it yourself` });
33
+ else rows.push({ ...base, action: 'update', reason: null });
34
+ }
35
+ return rows;
36
+ }
37
+
38
+ // `## [x.y.z]` sections of the shipped CHANGELOG newer than `from`, up to and including `to`; [Unreleased] is never included.
39
+ export function changelogNotes(text, from, to) {
40
+ const out = [];
41
+ let cur = null;
42
+ for (const line of String(text ?? '').split('\n')) {
43
+ const h = /^## \[(\d+\.\d+\.\d+)\]/.exec(line);
44
+ if (h) {
45
+ cur = compare(h[1], from) > 0 && compare(h[1], to) <= 0 ? { version: h[1], body: [] } : null;
46
+ if (cur) out.push(cur);
47
+ } else if (cur) cur.body.push(line);
48
+ }
49
+ return out.map((s) => ({ version: s.version, body: s.body.join('\n').trim() }));
50
+ }
51
+
52
+ export function formatUpdatePlan(rows, notes) {
53
+ const out = [];
54
+ const moves = rows.filter((r) => r.action === 'update');
55
+ const rest = rows.filter((r) => r.action !== 'update');
56
+ if (moves.length) out.push('Pins that will change (old -> new):', ...moves.map((r) => `${r.tool}: ${r.installed} -> ${r.pinned}`));
57
+ if (rest.length) out.push('Not updated:', ...rest.map((r) => `${r.tool}: ${r.installed}${r.pinned && r.pinned !== r.installed ? ` -> ${r.pinned}` : ''} (${r.reason})`));
58
+ if (notes.length) out.push(`Release notes since your version (${notes.map((n) => n.version).join(', ')}):`, ...notes.flatMap((n) => [`## ${n.version}`, n.body]));
59
+ return out.join('\n');
60
+ }