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
package/scripts/lean.mjs
ADDED
|
@@ -0,0 +1,1319 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// lean-agents engine: plan, apply, update, uninstall and doctor.
|
|
3
|
+
// `npx lean-agents` runs this file; install.sh / install.ps1 make sure Node and a verified release exist, then call it.
|
|
4
|
+
import fs from 'node:fs';
|
|
5
|
+
import os from 'node:os';
|
|
6
|
+
import path from 'node:path';
|
|
7
|
+
import readline from 'node:readline';
|
|
8
|
+
import tty from 'node:tty';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
import { plan, apply, undo, describe, writePrivate, privateDir, dropBackups, renameRetry } from './lib/fsops.mjs';
|
|
11
|
+
import { loadCore, renderRules, loadProfile, useToolNode } from './lib/render.mjs';
|
|
12
|
+
import { claudeAdapter } from './lib/adapters/claude.mjs';
|
|
13
|
+
import { opencodeV1Adapter } from './lib/adapters/opencode-v1.mjs';
|
|
14
|
+
import { opencodeV2Adapter } from './lib/adapters/opencode-v2.mjs';
|
|
15
|
+
import { copilotAdapter } from './lib/adapters/copilot-cli.mjs';
|
|
16
|
+
import { antigravityAdapter } from './lib/adapters/antigravity.mjs';
|
|
17
|
+
import { vscodeCopilotAdapter } from './lib/adapters/vscode-copilot.mjs';
|
|
18
|
+
import { cursorAdapter } from './lib/adapters/cursor.mjs';
|
|
19
|
+
import { projectPlan, projectStateDir } from './lib/project.mjs';
|
|
20
|
+
import { gsdPlan } from './lib/gsd.mjs';
|
|
21
|
+
import { MIGRATE_SOURCES, MIGRATE_TARGETS, readSource, detectSources, migratePlan, finishRows, formatTable } from './lib/migrate.mjs';
|
|
22
|
+
import { adhdCommand } from './lib/adhd.mjs';
|
|
23
|
+
import { version as binVersion, versionFull, gitHint, detectAgents, packageManager, prereqFor, antigravityPrereqs, bunInstall, bunPathCommand, bunPresent, which, run, quiet, exists, isolate, configHome, envDir } from './lib/system.mjs';
|
|
24
|
+
import { doctor } from './lib/doctor.mjs';
|
|
25
|
+
import { probePlugins } from './lib/plugin-health.mjs';
|
|
26
|
+
import { adopt, inventory, saveState } from './lib/adopt.mjs';
|
|
27
|
+
import { planPrereqs, pendingPrereqs, everythingAgents, undoArgv, nvmDirExistedBefore } from './lib/prereqs.mjs';
|
|
28
|
+
import { upgradeInventory, formatUpgrade } from './lib/upgrade.mjs';
|
|
29
|
+
import { backupOpencode, backupLayout, listProcesses, opencodeRunning } from './lib/opencode-backup.mjs';
|
|
30
|
+
import { readBackupStamp } from './lib/backup-stamp.mjs';
|
|
31
|
+
import { isActive, failAt, applyPreflight, verifyBackup, configDrift, createSteps, makeCtx, runApply, runUndo, restoreData } from './lib/opencode-upgrade.mjs';
|
|
32
|
+
import { planOpencode1, installOpencode1, removeOpencode1, layout as opencode1Layout } from './lib/opencode1.mjs';
|
|
33
|
+
import { posixPathBlock } from './lib/shell-path.mjs';
|
|
34
|
+
import { agentLifecycle, agentTable, upgradeCommands, undoPlan, undoUpgrades, agentOf, agentStamps, VSCODE_NOTE, AGENT_CLIS } from './lib/agent-lifecycle.mjs';
|
|
35
|
+
import { copilotUsage } from './lib/copilot-usage.mjs';
|
|
36
|
+
import { draftIssue, addFiledIssue } from './lib/feedback.mjs';
|
|
37
|
+
import { buildSummary } from './lib/summary-data.mjs';
|
|
38
|
+
import { loginRows } from './lib/logins.mjs';
|
|
39
|
+
import { renderSummary, canOffer, openArgv } from './lib/summary-html.mjs';
|
|
40
|
+
import { planUpdate, changelogNotes, formatUpdatePlan } from './lib/update-plan.mjs';
|
|
41
|
+
import { PINS, pinVersions, behindPins, pinTool, nodeRange, npmSpec } from './lib/pins.mjs';
|
|
42
|
+
import { findNvm, installedNodes, resolveToolNodes, nvmLatest, nvmInstallArgv, nvmEnv, toolEnv, satisfies } from './lib/node-runtime.mjs';
|
|
43
|
+
import { leanUpdateCommands, coordinateCommands, leanMigrateCommands } from './lib/lean-update.mjs';
|
|
44
|
+
import { canUseMenus, menuPrompter, menuProgress } from './lib/ui.mjs';
|
|
45
|
+
import { CATEGORIES, preset, onOff, fromPrivacy, privacyOf, childEnv, shareProxy, proxyReport } from './lib/network.mjs';
|
|
46
|
+
import { unverifiedItems, notesFile } from './lib/unverified.mjs';
|
|
47
|
+
import { detectTerminals, TERMINALS, parseTerminal, terminalCommands, terminalPrivacyNotes, orcaEnvSet, gitBashActions, stillNeeded, shellNotice } from './lib/terminals.mjs';
|
|
48
|
+
|
|
49
|
+
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
50
|
+
const ADAPTERS = { claude: claudeAdapter, 'opencode-v1': opencodeV1Adapter, 'opencode-v2': opencodeV2Adapter, 'copilot-cli': copilotAdapter, antigravity: antigravityAdapter };
|
|
51
|
+
// Agents whose models do not depend on --profile.
|
|
52
|
+
const FIXED_PROFILE = { claude: 'claude-subscription', 'copilot-cli': 'github-copilot', antigravity: 'antigravity' };
|
|
53
|
+
Object.assign(ADAPTERS, { 'vscode-copilot': vscodeCopilotAdapter, cursor: cursorAdapter });
|
|
54
|
+
FIXED_PROFILE['vscode-copilot'] = 'github-copilot';
|
|
55
|
+
// Extensions cannot be installed silently without admin policy, so the user installs it.
|
|
56
|
+
const CODE_MODE_NOTE = 'Claude Code Code Mode is experimental (Claude Code 2.1.323 or newer, interactive terminal only, a direct Anthropic subscription or Console login; not Vertex, Bedrock or a gateway). A session started with it resumes only with it on; --uninstall turns it off';
|
|
57
|
+
const EXTENSION_NOTE = 'install the Playwright Extension yourself from https://chromewebstore.google.com/detail/playwright-extension/mmlmfjhmonkocbjadbfplnigmagldckm . Each session asks you to approve the connection; optional auto-approve: docs/browser-extension.md';
|
|
58
|
+
const MINIMAL_TOOLS = ['rtk', 'context-mode'];
|
|
59
|
+
const OPTIONAL_TOOLS = ['serena', 'playwright', 'ponytail', 'caveman', 'i-have-adhd', 'dcp', 'codeburn', 'copilot-usage'];
|
|
60
|
+
// Asked for one by one and never part of --all-tools.
|
|
61
|
+
const OPT_IN_TOOLS = ['gsd', 'autoskills', 'playwright-extension', 'coordinate', 'lean-migrate', 'code-mode'];
|
|
62
|
+
const TOOL_INFO = {
|
|
63
|
+
serena: 'Serena MCP: symbol-level code navigation, so agents read less code',
|
|
64
|
+
playwright: 'Playwright MCP: lets agents drive a browser to check web UIs',
|
|
65
|
+
'playwright-extension': 'Playwright MCP extension mode: attaches to your own signed-in Chrome (pages behind single sign-on); not for Claude Code, which has Claude in Chrome',
|
|
66
|
+
ponytail: 'Ponytail: code-quality guidance injected each turn (lite mode recommended)',
|
|
67
|
+
caveman: 'Caveman skills: extra-compressed answers when you ask for them',
|
|
68
|
+
'i-have-adhd': 'i-have-adhd: skimmable, action-first formatting for every answer',
|
|
69
|
+
dcp: 'DCP: prunes old context on OpenCode 1.x (AGPL-3.0)',
|
|
70
|
+
codeburn: 'Codeburn: usage and cost report across agents, run with npx',
|
|
71
|
+
'copilot-usage': 'Copilot usage: credits left in the OpenCode sidebar and /copilot-usage, read with gh, no model request (needs gh login; off with --outbound off)',
|
|
72
|
+
gsd: 'GSD Core: spec-driven workflow skills and agents (large install)',
|
|
73
|
+
'lean-migrate': 'lean-migrate skill: guides the OpenCode 1.x to 2.x upgrade through --upgrade-agent opencode (dry run first)',
|
|
74
|
+
coordinate: 'Coordinate skill: playbook, session prompt and watcher to run several agents in separate git worktrees',
|
|
75
|
+
'code-mode': 'Claude Code Code Mode (experimental): Claude runs tool calls from small scripts; needs a direct Anthropic login, sessions started with it resume only with it on',
|
|
76
|
+
autoskills: 'AutoSkills: picks skills per project, run with npx (CC BY-NC 4.0: non-commercial use only)',
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
// Read before isolate() points HOME at --home.
|
|
80
|
+
const REAL_HOME = os.homedir();
|
|
81
|
+
|
|
82
|
+
function parseArgs(argv) {
|
|
83
|
+
const o = {
|
|
84
|
+
command: 'install', dryRun: false, yes: false, agents: null, tools: null, privacy: null, profile: null,
|
|
85
|
+
lang: null, home: os.homedir(), exec: true, adhdAlways: null, ponytailMode: null, shell: null,
|
|
86
|
+
networkPreset: null, networkFlags: {}, gh: null, bun: null, terminals: null, app: true, core: true,
|
|
87
|
+
};
|
|
88
|
+
const list = (v) => v.split(',').map((s) => s.trim()).filter(Boolean);
|
|
89
|
+
for (let i = 0; i < argv.length; i++) {
|
|
90
|
+
const a = argv[i];
|
|
91
|
+
const next = () => argv[++i];
|
|
92
|
+
switch (a) {
|
|
93
|
+
case '--dry-run': o.dryRun = true; break;
|
|
94
|
+
case '--yes': case '-y': o.yes = true; break;
|
|
95
|
+
case '--agents': o.agents = list(next()); break;
|
|
96
|
+
case '--tools': o.tools = [...new Set([...MINIMAL_TOOLS, ...list(next())])]; break;
|
|
97
|
+
case '--all-tools': o.tools = [...MINIMAL_TOOLS, ...OPTIONAL_TOOLS]; break;
|
|
98
|
+
case '--no-tools': o.tools = []; break;
|
|
99
|
+
case '--everything': o.everything = true; break;
|
|
100
|
+
case '--no-core': o.core = false; break;
|
|
101
|
+
case '--terminal': o.terminals = parseTerminal(next()); break;
|
|
102
|
+
case '--install-terminal': o.installTerminals = parseTerminal(next()); break;
|
|
103
|
+
case '--bun': o.bun = true; break;
|
|
104
|
+
case '--no-bun': o.bun = false; break;
|
|
105
|
+
case '--no-app': o.app = false; break;
|
|
106
|
+
case '--privacy': o.privacy = next(); fromPrivacy(o.privacy); break;
|
|
107
|
+
case '--gh': o.gh = true; break;
|
|
108
|
+
case '--no-gh': o.gh = false; break;
|
|
109
|
+
case '--json': o.json = true; break;
|
|
110
|
+
case '--probe-plugins': o.probePlugins = true; break;
|
|
111
|
+
case '--feedback-draft': o.command = 'feedback'; break;
|
|
112
|
+
case '--failed-command': o.failedCommand = next(); break;
|
|
113
|
+
case '--feedback-kind': o.feedbackKind = next(); break;
|
|
114
|
+
case '--network': o.networkPreset = onOff(a, next()); break;
|
|
115
|
+
case '--telemetry': o.networkFlags.telemetry = onOff(a, next()); break;
|
|
116
|
+
case '--auto-update': o.networkFlags.autoUpdate = onOff(a, next()); break;
|
|
117
|
+
case '--outbound': o.networkFlags.outbound = onOff(a, next()); break;
|
|
118
|
+
case '--profile': o.profile = next(); break;
|
|
119
|
+
case '--lang': o.lang = next(); break;
|
|
120
|
+
case '--home': o.home = path.resolve(next()); break;
|
|
121
|
+
// realpath: the state dir is keyed by this path, and /var and /private/var are one folder on macOS.
|
|
122
|
+
case '--project': o.project = fs.realpathSync(path.resolve(next())); break;
|
|
123
|
+
case '--migrate': o.migrate = next(); if (o.migrate !== 'auto' && !MIGRATE_SOURCES.includes(o.migrate)) throw new Error(`unknown --migrate source "${o.migrate}" (available: ${[...MIGRATE_SOURCES, 'auto'].join(', ')})`); break;
|
|
124
|
+
case '--no-exec': o.exec = false; break;
|
|
125
|
+
case '--shell': o.shell = next(); if (!['default', 'git-bash'].includes(o.shell)) throw new Error('--shell takes default or git-bash'); break;
|
|
126
|
+
case '--adhd-always': o.adhdAlways = true; break;
|
|
127
|
+
case '--ponytail-mode': o.ponytailMode = next(); break;
|
|
128
|
+
case '--update': o.command = 'update'; break;
|
|
129
|
+
case '--uninstall': o.command = 'uninstall'; break;
|
|
130
|
+
case '--doctor': o.command = 'doctor'; break;
|
|
131
|
+
case '--summary': o.command = 'summary'; break;
|
|
132
|
+
case '--no-open': o.noOpen = true; break;
|
|
133
|
+
case '--filed-issue': (o.filedIssues ??= []).push(next()); break;
|
|
134
|
+
case '--adopt': o.command = 'adopt'; break;
|
|
135
|
+
case '--upgrade-agent': o.command = 'upgrade-agent'; o.upgradeAgent = next(); if (!['opencode', 'vscode-copilot'].includes(o.upgradeAgent)) throw new Error('--upgrade-agent takes opencode or vscode-copilot'); break;
|
|
136
|
+
case '--undo': o.undo = true; break;
|
|
137
|
+
case '--keep-backup': o.keepBackup = true; break;
|
|
138
|
+
case '--backup': o.backup = true; break;
|
|
139
|
+
case '--opencode1': o.opencode1 = true; break;
|
|
140
|
+
case '--confirm-removals': o.confirmRemovals = true; break;
|
|
141
|
+
case '--install-agent': case '--uninstall-agent': o.command = 'agent'; o.agentMode = a.slice(2, -6); o.agentList = list(argv[i + 1]?.startsWith('--') ? '' : next() ?? ''); if (!o.agentList.length) throw new Error(`${a} needs an agent list (claude, opencode-v2, copilot-cli, cursor, antigravity, vscode-copilot)`); break;
|
|
142
|
+
case '--usage': o.command = 'usage'; break;
|
|
143
|
+
case '--skip-agents': case '--no-admin': console.error(`! ${a} does nothing (agents are never installed, nothing needs admin) and will be removed in the next release.`); break;
|
|
144
|
+
case '--help': case '-h': o.command = 'help'; break;
|
|
145
|
+
case '--version': o.command = 'version'; break;
|
|
146
|
+
default: throw new Error(`unknown option ${a} (see --help)`);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if (o.everything && !o.migrate) {
|
|
150
|
+
// Preset for a fresh machine: every default is taken, so the plan is the only question.
|
|
151
|
+
o.tools ??= [...MINIMAL_TOOLS, ...OPTIONAL_TOOLS];
|
|
152
|
+
o.gh ??= true;
|
|
153
|
+
o.bun ??= true;
|
|
154
|
+
o.lang ??= 'en';
|
|
155
|
+
o.profile ??= 'none';
|
|
156
|
+
o.ponytailMode ??= 'lite';
|
|
157
|
+
o.adhdAlways ??= true;
|
|
158
|
+
}
|
|
159
|
+
if (!o.core && o.tools) o.tools = o.tools.filter((t) => !MINIMAL_TOOLS.includes(t));
|
|
160
|
+
return o;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const HELP = `Usage: lean-agents [options]
|
|
164
|
+
|
|
165
|
+
--dry-run Show every file change and command; change nothing
|
|
166
|
+
--yes Accept defaults without asking
|
|
167
|
+
--everything Fresh-machine preset: plan the prerequisites (Homebrew, nvm, Node 24, uv, RTK, Bun) and Claude Code +
|
|
168
|
+
OpenCode 2 with every optional tool, show one plan, ask once (--yes accepts; --dry-run --json prints it)
|
|
169
|
+
--agents a,b ${Object.keys(ADAPTERS).join(', ')}
|
|
170
|
+
(default: the ones installed)
|
|
171
|
+
--tools a,b Optional tools on top of rtk and context-mode:
|
|
172
|
+
${[...OPTIONAL_TOOLS, ...OPT_IN_TOOLS].join(', ')}
|
|
173
|
+
--all-tools / --no-tools (--all-tools leaves out ${OPT_IN_TOOLS.join(', ')})
|
|
174
|
+
--no-core Leave out ${MINIMAL_TOOLS.join(' and ')}; install only the --tools you list
|
|
175
|
+
--privacy standard|strict Same as --network on / --network off
|
|
176
|
+
--network on|off Preset for telemetry, auto-updates and other outbound calls
|
|
177
|
+
--telemetry on|off, --auto-update on|off, --outbound on|off
|
|
178
|
+
One category; overrides the preset
|
|
179
|
+
--profile <name> Model profile for OpenCode (see profiles/)
|
|
180
|
+
--lang en|es Language for rules and replies
|
|
181
|
+
--terminal warp|orca|both|none
|
|
182
|
+
Agent integrations for a terminal you already have (default: the detected ones;
|
|
183
|
+
ignored with --project)
|
|
184
|
+
--install-terminal warp|orca|both
|
|
185
|
+
Install the terminal app and its agent integrations (macOS: Warp requires brew)
|
|
186
|
+
--gh / --no-gh Install GitHub CLI (gh) if it is missing (default: on; you run gh auth login yourself)
|
|
187
|
+
--feedback-draft After a failed install: read the error on stdin, print a redacted issue draft as JSON
|
|
188
|
+
(--feedback-kind update: the text is a finding from an update, not an error)
|
|
189
|
+
({"offer":false} when the network preset forbids it). Needs --failed-command <text>;
|
|
190
|
+
pass --network on|off when nothing is installed yet. Files nothing.
|
|
191
|
+
--no-exec Run no external command (no installs, no version probes); --uninstall refuses it when commands need undoing
|
|
192
|
+
--probe-plugins With --doctor or --adopt: start a short-lived opencode serve (throwaway state dir, loopback) and check a plugin's command registers
|
|
193
|
+
--json With --dry-run, --doctor or --yes: print one JSON object on stdout (messages go to stderr)
|
|
194
|
+
--no-app Do not install the Antigravity app (the CLI is still installed when missing)
|
|
195
|
+
--bun / --no-bun Install Bun for Context Mode (default: on; faster JS, TypeScript)
|
|
196
|
+
--project <dir> Write the shared team files into one repository
|
|
197
|
+
(AGENTS.md, .github/, .vscode/mcp.json, .cursor/)
|
|
198
|
+
--migrate <from|auto> Copy rules, agents, skills, prompts and MCP servers from another harness
|
|
199
|
+
(${MIGRATE_SOURCES.join(', ')}) to --agents. With --project, from and to the repository.
|
|
200
|
+
Never moves or overwrites; MCP env and header values are not copied; hooks are only listed
|
|
201
|
+
--adhd-always Turn on i-have-adhd for every answer
|
|
202
|
+
--ponytail-mode lite|full|ultra|off
|
|
203
|
+
--shell default|git-bash OpenCode on Windows: set its shell to Git Bash when found (default: git-bash;
|
|
204
|
+
never overwrites a shell you set yourself; "default" opts out)
|
|
205
|
+
--update Re-apply with your saved choices
|
|
206
|
+
--update --undo [--yes]
|
|
207
|
+
Put each agent CLI that --update upgraded back on the version it had before its first upgrade
|
|
208
|
+
(plan first, then a confirm; a failed step is reported and the rest run). --uninstall leaves
|
|
209
|
+
upgraded agent CLIs alone; use --uninstall-agent for ones lean-agents installed
|
|
210
|
+
--uninstall Undo everything lean-agents changed
|
|
211
|
+
--doctor Check the install
|
|
212
|
+
--summary Write the summary page (summary.html in the state dir; --uninstall removes it) and ask before opening it.
|
|
213
|
+
--filed-issue "item=issue url" records an issue you filed; --no-open only prints the path
|
|
214
|
+
--adopt List what a hand-built machine already has (MCPs, hooks, plugins, skills, npm copies),
|
|
215
|
+
classify each (managed, user, stale, duplicate, drift, wrong-node) and print the planned
|
|
216
|
+
actions; changes nothing (with --json: one JSON object). Always pass --home to try it
|
|
217
|
+
--adopt --yes Apply it: back up, re-register managed MCPs on one Node, verify, undo by itself on a failure
|
|
218
|
+
--confirm-removals With --adopt --yes and no terminal: also remove old npm copies, a duplicate skill folder and
|
|
219
|
+
hand-made stopgaps (all backed up; on a terminal a menu asks instead)
|
|
220
|
+
--keep-backup Keep the backup after a verified --adopt --yes (--adopt --undo needs it to restore bytes)
|
|
221
|
+
--upgrade-agent opencode Dry run: classify the OpenCode 1.x config as managed, translatable to 2.x or manual and print the
|
|
222
|
+
translation table; changes nothing (with --json: one JSON object)
|
|
223
|
+
--upgrade-agent opencode --yes
|
|
224
|
+
Apply, after --backup --yes made a verified backup: opencode1, install OpenCode 2, translate the
|
|
225
|
+
config, add DCP. Steps are journaled in state.json; a failed step undoes the finished ones
|
|
226
|
+
--upgrade-agent opencode --undo [--yes]
|
|
227
|
+
Back to 1.x: undo each step, move the 2.x db aside, copy the frozen copy back. Never deletes the
|
|
228
|
+
backup or the frozen copy. Plan first; --yes does it
|
|
229
|
+
--upgrade-agent opencode --backup [--dry-run|--yes]
|
|
230
|
+
Permanent sha256-checked backup of the OpenCode 1.x sessions and config, then a frozen copy for
|
|
231
|
+
opencode1; the live data is only read. Plan first (the default); --yes copies. Refuses while
|
|
232
|
+
OpenCode runs or free space is under 2 x size + 1 GB
|
|
233
|
+
--upgrade-agent opencode --opencode1 [--dry-run|--yes]
|
|
234
|
+
After --backup: copy the OpenCode 1.x binary next to the frozen copy and add opencode1, which runs
|
|
235
|
+
1.x on that copy only (XDG_DATA_HOME + XDG_STATE_HOME), to PATH. --uninstall removes it
|
|
236
|
+
--undo With --adopt: restore what the last --adopt --yes changed
|
|
237
|
+
--upgrade-agent vscode-copilot
|
|
238
|
+
Report only: VS Code owns the Copilot extension; --update refreshes the files lean-agents wrote
|
|
239
|
+
--install-agent a,b / --uninstall-agent a,b
|
|
240
|
+
Install (claude, opencode-v2, copilot-cli, cursor, antigravity) or remove the agent CLIs
|
|
241
|
+
lean-agents itself installed; plan first, --yes to run. Never OpenCode 1.x.
|
|
242
|
+
vscode-copilot: configure or remove only the files lean-agents wrote (VS Code owns the extension)
|
|
243
|
+
--version Print the lean-agents version
|
|
244
|
+
--usage Print the Copilot credits left (one gh call, no model request)
|
|
245
|
+
`;
|
|
246
|
+
|
|
247
|
+
async function prompter(yes) {
|
|
248
|
+
if (yes) return { ask: async (_q, def) => def, select: async ({ def }) => def, multi: async ({ defaults }) => defaults, close() {} };
|
|
249
|
+
let input = process.stdin;
|
|
250
|
+
if (!process.stdin.isTTY) {
|
|
251
|
+
// openSync reports a missing /dev/tty here, not later as a crash. A tty.ReadStream, unlike
|
|
252
|
+
// an fs stream, can close while a read is pending, so the process can exit.
|
|
253
|
+
try { input = new tty.ReadStream(fs.openSync(process.platform === 'win32' ? 'CONIN$' : '/dev/tty', 'r')); } catch { /* keep stdin */ }
|
|
254
|
+
}
|
|
255
|
+
if (canUseMenus(input)) return menuPrompter(input);
|
|
256
|
+
const rl = readline.createInterface({ input, output: process.stdout });
|
|
257
|
+
// Never fall back to the default answer here: nobody approved these changes.
|
|
258
|
+
const noInput = () => new Error('no terminal to ask on: pass --yes to accept the defaults, or --dry-run with --agents and --tools to preview');
|
|
259
|
+
let closed = false;
|
|
260
|
+
let fail = null;
|
|
261
|
+
rl.once('close', () => { closed = true; fail?.(noInput()); });
|
|
262
|
+
const ask = (q, def) => new Promise((res, rej) => {
|
|
263
|
+
if (closed) return rej(noInput());
|
|
264
|
+
fail = rej;
|
|
265
|
+
rl.question(`${q} [${def}] `, (a) => res(a.trim() || def));
|
|
266
|
+
});
|
|
267
|
+
return {
|
|
268
|
+
tty: Boolean(input.isTTY),
|
|
269
|
+
ask,
|
|
270
|
+
// Menus fall back to the same text questions as before.
|
|
271
|
+
select: ({ ask: q, def }) => ask(q, def),
|
|
272
|
+
multi: async ({ items, defaults }) => {
|
|
273
|
+
const picked = [];
|
|
274
|
+
for (const it of items) if (yesNo(await ask(it.ask, defaults.includes(it.value) ? 'y' : 'n'))) picked.push(it.value);
|
|
275
|
+
return picked;
|
|
276
|
+
},
|
|
277
|
+
close: () => { fail = null; rl.close(); if (input !== process.stdin) input.destroy(); },
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
const yesNo = (a) => /^(y|yes|s|si|sí)$/i.test(a);
|
|
281
|
+
|
|
282
|
+
// --project keeps its own state, so a repo install and a user install never mix.
|
|
283
|
+
let project = null;
|
|
284
|
+
function stateDir(home) {
|
|
285
|
+
if (project) return projectStateDir(home, project);
|
|
286
|
+
return path.join(home, '.config', 'lean-agents');
|
|
287
|
+
}
|
|
288
|
+
// Where the engine may write: home, the project, and the config dirs envDir() accepts.
|
|
289
|
+
const writeRoots = (o) => [o.home, o.project, configHome(o.home), envDir(o.home, 'COPILOT_HOME', null)].filter(Boolean);
|
|
290
|
+
function readState(home) {
|
|
291
|
+
const f = path.join(stateDir(home), 'state.json');
|
|
292
|
+
return fs.existsSync(f) ? JSON.parse(fs.readFileSync(f, 'utf8')) : null;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// LEAN_AGENTS_NODE fakes the Node version, so tests do not depend on the host.
|
|
296
|
+
const NODE_VERSION = process.env.LEAN_AGENTS_NODE ?? process.versions.node;
|
|
297
|
+
// [tool, pin] pairs whose pin declares an engines.node range lean-agents runs on a matching Node (wired in prereqCommands, gsd.mjs, claude.mjs and copilot-cli.mjs).
|
|
298
|
+
const NODE_TOOLS = [['context-mode', 'context-mode'], ['gsd', 'gsd-core']];
|
|
299
|
+
|
|
300
|
+
// Migration copies files only: no tools, terminals, network or model questions.
|
|
301
|
+
async function chooseMigration(o, p) {
|
|
302
|
+
if (!o.agents) {
|
|
303
|
+
// Antigravity has no project scope: never auto-pick it for --project.
|
|
304
|
+
const found = Object.keys(detectAgents()).filter((a) => MIGRATE_TARGETS.includes(a) && !(o.project && a === 'antigravity'));
|
|
305
|
+
if (!found.length) throw new Error('no target agent found on PATH: pass --agents');
|
|
306
|
+
o.agents = found;
|
|
307
|
+
}
|
|
308
|
+
for (const a of o.agents) if (!MIGRATE_TARGETS.includes(a)) throw new Error(`cannot migrate to "${a}" (available: ${MIGRATE_TARGETS.join(', ')})`);
|
|
309
|
+
if (o.agents.includes('opencode-v1') && o.agents.includes('opencode-v2')) throw new Error('opencode-v1 and opencode-v2 write the same config files: pick one');
|
|
310
|
+
Object.assign(o, { tools: [], terminals: [], network: preset('on'), privacy: 'standard', unverified: {}, notes: [], gh: false, bun: false, lang: 'en', profile: null });
|
|
311
|
+
return p;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
async function choose(o, saved) {
|
|
315
|
+
// --everything answers every question with its default; install() asks the one plan question.
|
|
316
|
+
const p = await prompter(o.yes || o.everything);
|
|
317
|
+
if (o.migrate) return chooseMigration(o, p);
|
|
318
|
+
if (!o.agents && o.everything) {
|
|
319
|
+
const team = everythingAgents({ platform: process.platform, project: !!o.project, detected: process.platform === 'win32' ? detectAgents() : {} }); // detection only matters for the Windows team preset
|
|
320
|
+
o.agents = team.agents;
|
|
321
|
+
if (team.skipped.length) o.agentNotes = [`not found, skipped: ${team.skipped.join(', ')} (install them, then rerun --everything)`];
|
|
322
|
+
}
|
|
323
|
+
if (!o.agents) {
|
|
324
|
+
o.agents = saved?.agents ?? [];
|
|
325
|
+
if (!saved) {
|
|
326
|
+
const detected = detectAgents();
|
|
327
|
+
const supported = Object.keys(detected).filter((a) => ADAPTERS[a]);
|
|
328
|
+
if (!supported.length) console.log('No supported agent found on PATH (claude, opencode, copilot, agy). Use --agents to configure anyway.');
|
|
329
|
+
const items = supported.map((a) => ({ value: a, label: `${a} ${detected[a]}`, ask: `Configure ${a} ${detected[a]}?` }));
|
|
330
|
+
if (items.length) o.agents.push(...await p.multi({ message: 'Agents to configure (space to toggle, enter to confirm)', items, defaults: supported }));
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
for (const a of o.agents) if (!ADAPTERS[a]) throw new Error(`agent "${a}" is not supported yet (available: ${Object.keys(ADAPTERS).join(', ')})`);
|
|
334
|
+
if (o.agents.includes('opencode-v1') && o.agents.includes('opencode-v2')) {
|
|
335
|
+
throw new Error('opencode-v1 and opencode-v2 write the same config files: pick one');
|
|
336
|
+
}
|
|
337
|
+
if (!o.tools) {
|
|
338
|
+
o.tools = saved?.tools ?? (o.core ? [...MINIMAL_TOOLS] : []);
|
|
339
|
+
if (!saved) {
|
|
340
|
+
const offered = [...OPTIONAL_TOOLS, ...OPT_IN_TOOLS].filter((t) => t !== 'dcp' || o.agents.includes('opencode-v1'));
|
|
341
|
+
const items = offered.map((t) => ({ value: t, label: t, hint: TOOL_INFO[t].replace(/^[^:]+: /, ''), ask: `Add ${TOOL_INFO[t]}?` }));
|
|
342
|
+
const message = o.core ? `Optional tools (${MINIMAL_TOOLS.join(' and ')} are always included)` : 'Tools (--no-core: nothing else is added)';
|
|
343
|
+
o.tools.push(...await p.multi({ message, items, defaults: [] }));
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
if (!o.core) o.tools = o.tools.filter((t) => !MINIMAL_TOOLS.includes(t));
|
|
347
|
+
const known = [...MINIMAL_TOOLS, ...OPTIONAL_TOOLS, ...OPT_IN_TOOLS];
|
|
348
|
+
const unknown = o.tools.filter((t) => !known.includes(t));
|
|
349
|
+
if (unknown.length) throw new Error(`unknown tools: ${unknown.join(', ')} (available: ${known.join(', ')})`);
|
|
350
|
+
if (!o.agents.includes('opencode-v1')) o.tools = o.tools.filter((t) => t !== 'dcp');
|
|
351
|
+
// The saved choice keeps Context Mode, so --update installs it once Node is new enough.
|
|
352
|
+
o.chosenTools = o.tools;
|
|
353
|
+
// Tools whose Node range the active Node fails run on an nvm Node of their own, or are skipped with one line.
|
|
354
|
+
const needs = Object.fromEntries(NODE_TOOLS.filter(([tool]) => o.tools.includes(tool)).map(([tool, pin]) => [tool, { node: nodeRange(pin) }]));
|
|
355
|
+
const nvm = findNvm({ env: process.env, home: o.home, platform: process.platform, realHome: REAL_HOME });
|
|
356
|
+
o.nvm = nvm;
|
|
357
|
+
const resolved = resolveToolNodes({ pins: needs, active: NODE_VERSION, nvm, latest: (major) => nvmLatest(nvm, major, { run: quiet }) });
|
|
358
|
+
for (const s of resolved.skipped) console.log(s.line);
|
|
359
|
+
o.tools = o.tools.filter((t) => !resolved.skipped.some((s) => s.tool === t));
|
|
360
|
+
o.deferred = resolved.skipped.map((s) => s.tool);
|
|
361
|
+
o.toolNode = resolved.toolNode && { ...resolved.toolNode, nvmDir: nvm.dir };
|
|
362
|
+
if (o.toolNode && o.agents.includes('claude') && o.tools.includes('context-mode')) console.log('Context Mode on Claude Code runs as an MCP server on its own Node: its hooks and skills (the plugin) are not installed.');
|
|
363
|
+
if (o.project) {
|
|
364
|
+
o.terminals = [];
|
|
365
|
+
o.installTerminals = [];
|
|
366
|
+
} else if (!o.terminals) {
|
|
367
|
+
const found = detectTerminals(o.home, { system: o.home === REAL_HOME });
|
|
368
|
+
o.terminals = saved ? saved.terminals ?? [] : found;
|
|
369
|
+
o.installTerminals = o.installTerminals ?? saved?.installTerminals ?? [];
|
|
370
|
+
if (!saved) {
|
|
371
|
+
const askIntegrate = found.map((t) => ({ value: t, label: `${t} integration (app already installed)`, ask: `Add the ${t} agent integration?` }));
|
|
372
|
+
const missing = TERMINALS.filter((t) => !found.includes(t));
|
|
373
|
+
const askInstall = (o.home === REAL_HOME && (process.platform === 'darwin' || process.platform === 'win32'))
|
|
374
|
+
? missing.map((t) => ({ value: t, label: `Install ${t} + integration`, ask: `Install the ${t} app and its agent integration?` }))
|
|
375
|
+
: [];
|
|
376
|
+
|
|
377
|
+
if (askIntegrate.length || askInstall.length) {
|
|
378
|
+
const picked = await p.multi({
|
|
379
|
+
message: 'Terminals (Warp, Orca)',
|
|
380
|
+
items: [...askIntegrate, ...askInstall],
|
|
381
|
+
defaults: found,
|
|
382
|
+
});
|
|
383
|
+
|
|
384
|
+
o.installTerminals = [...new Set([...o.installTerminals, ...picked.filter(t => missing.includes(t))])];
|
|
385
|
+
o.terminals = [...new Set([...picked, ...o.installTerminals])];
|
|
386
|
+
} else {
|
|
387
|
+
o.terminals = [...new Set([...o.terminals, ...o.installTerminals])];
|
|
388
|
+
}
|
|
389
|
+
} else {
|
|
390
|
+
o.terminals = [...new Set([...o.terminals, ...o.installTerminals])];
|
|
391
|
+
}
|
|
392
|
+
} else {
|
|
393
|
+
o.installTerminals = o.installTerminals ?? saved?.installTerminals ?? [];
|
|
394
|
+
o.terminals = [...new Set([...o.terminals, ...o.installTerminals])];
|
|
395
|
+
}
|
|
396
|
+
if (o.installTerminals?.length) {
|
|
397
|
+
const isReal = o.home === REAL_HOME;
|
|
398
|
+
const isSupported = process.platform === 'darwin' || process.platform === 'win32';
|
|
399
|
+
if (!isReal || !isSupported) {
|
|
400
|
+
for (const t of o.installTerminals) {
|
|
401
|
+
const reason = !isReal ? 'temp home' : `unsupported platform ${process.platform}`;
|
|
402
|
+
console.log(`! ${t} app: not installed (${reason})`);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
}
|
|
406
|
+
await chooseNetwork(o, saved, p);
|
|
407
|
+
if (o.network.outbound === 'off' && o.tools.includes('copilot-usage')) {
|
|
408
|
+
console.log('copilot-usage skipped: it calls api.github.com, which --outbound off blocks.');
|
|
409
|
+
o.tools = o.tools.filter((t) => t !== 'copilot-usage');
|
|
410
|
+
}
|
|
411
|
+
await chooseUnverified(o, saved, p);
|
|
412
|
+
o.gh ??= saved?.gh ?? (!which('gh') && yesNo(await p.ask('Install GitHub CLI (gh)? You log in yourself afterwards', 'y')));
|
|
413
|
+
if (o.tools.includes('copilot-usage') && !o.gh && !which('gh')) console.log('copilot-usage needs gh to read your credits: install it yourself (https://cli.github.com/) and run gh auth login.');
|
|
414
|
+
if (o.tools.includes('context-mode') && !o.project) o.bun ??= saved?.bun ?? (bunPresent(o.home) || yesNo(await p.ask('Install Bun so Context Mode runs faster?', 'y')));
|
|
415
|
+
o.lang ??= saved?.lang ?? (await p.select({ ask: 'Language for rules and replies (en/es)?', message: 'Language for rules and replies', options: [{ value: 'en', label: 'English' }, { value: 'es', label: 'Español' }], def: 'en' }));
|
|
416
|
+
if (o.agents.some((a) => a.startsWith('opencode')) && !o.profile) {
|
|
417
|
+
const profiles = ['github-copilot', 'vertex-gemini', 'anthropic-api', 'opencode-go', 'openai-api', 'none'];
|
|
418
|
+
o.profile = saved?.profile ?? (await p.select({ ask: `OpenCode model profile (${profiles.join(', ')})?`, message: 'OpenCode model profile', options: profiles.map((v) => ({ value: v })), def: 'none' }));
|
|
419
|
+
}
|
|
420
|
+
if (o.profile === 'none') o.profile = null;
|
|
421
|
+
if (o.tools.includes('i-have-adhd')) o.adhdAlways ??= saved?.adhdAlways ?? yesNo(await p.ask('Use i-have-adhd on every answer?', 'y'));
|
|
422
|
+
if (o.tools.includes('ponytail')) o.ponytailMode ??= saved?.ponytailMode ?? (await p.select({ ask: 'Ponytail default mode (lite/full/ultra/off)?', message: 'Ponytail default mode', options: ['lite', 'full', 'ultra', 'off'].map((v) => ({ value: v })), def: 'lite' }));
|
|
423
|
+
// On by default, never asked: --shell default opts out.
|
|
424
|
+
o.shell ??= saved?.shell ?? 'git-bash';
|
|
425
|
+
return p;
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
const NETWORK_INFO = { telemetry: 'telemetry and error reports', autoUpdate: 'auto-updates', outbound: 'other outbound calls (session sharing, feedback, built-in providers)' };
|
|
429
|
+
|
|
430
|
+
async function chooseNetwork(o, saved, p) {
|
|
431
|
+
let perCategory = null;
|
|
432
|
+
let base = o.networkPreset ? preset(o.networkPreset) : fromPrivacy(o.privacy) ?? saved?.network ?? fromPrivacy(saved?.privacy);
|
|
433
|
+
if (!base && !Object.keys(o.networkFlags).length) {
|
|
434
|
+
const a = await p.select({
|
|
435
|
+
ask: 'Network: off (enterprise PC: no telemetry, auto-updates or sharing), on (personal PC), or choose per category?',
|
|
436
|
+
message: 'Telemetry, auto-updates and other outbound calls',
|
|
437
|
+
options: [
|
|
438
|
+
{ value: 'off', label: 'All off', hint: 'enterprise PC' },
|
|
439
|
+
{ value: 'on', label: 'All on', hint: 'personal PC, nothing changes' },
|
|
440
|
+
{ value: 'choose', label: 'Choose per category' },
|
|
441
|
+
],
|
|
442
|
+
def: 'on',
|
|
443
|
+
});
|
|
444
|
+
if (a === 'off' || a === 'on') base = preset(a);
|
|
445
|
+
else if (a === 'choose') {
|
|
446
|
+
base = {};
|
|
447
|
+
for (const c of CATEGORIES) base[c] = yesNo(await p.ask(`Keep ${NETWORK_INFO[c]} on?`, 'y')) ? 'on' : 'off';
|
|
448
|
+
perCategory = base;
|
|
449
|
+
} else throw new Error(`network takes off, on or choose, not "${a}"`);
|
|
450
|
+
}
|
|
451
|
+
o.network = { ...(base ?? preset('on')), ...o.networkFlags };
|
|
452
|
+
// Updates the user asked for (flag, per-category menu, or the saved choice) keep the agent's own updater; a plain "on" preset does not.
|
|
453
|
+
o.keepUpdater = o.network.autoUpdate === 'on' && (o.networkFlags.autoUpdate === 'on' || perCategory?.autoUpdate === 'on' || (!o.networkPreset && !!saved?.keepUpdater));
|
|
454
|
+
o.privacy = privacyOf(o.network);
|
|
455
|
+
}
|
|
456
|
+
|
|
457
|
+
async function chooseUnverified(o, saved, p) {
|
|
458
|
+
o.unverified = { ...saved?.unverified };
|
|
459
|
+
o.notes = [];
|
|
460
|
+
for (const item of unverifiedItems(o, o.home, { stateFiles: readState(o.home)?.files ?? [] })) {
|
|
461
|
+
if (item.kept) { o.unverified[item.id] = 'kept'; continue; }
|
|
462
|
+
if (o.unverified[item.id] && o.unverified[item.id] !== 'kept') continue;
|
|
463
|
+
// --yes, pipes and no terminal keep the default: pasting is interactive only.
|
|
464
|
+
if (!p.menus && !p.tty) { o.unverified[item.id] = 'default'; continue; }
|
|
465
|
+
const a = await p.select({
|
|
466
|
+
ask: `${item.label} is not documented upstream. Paste your docs or IT notes (paste), or keep the tool's default (default)?`,
|
|
467
|
+
message: `${item.label}: not documented upstream`,
|
|
468
|
+
options: [
|
|
469
|
+
{ value: 'default', label: "Keep the tool's default" },
|
|
470
|
+
{ value: 'paste', label: 'Paste docs or IT notes', hint: 'saved for your agent to apply after review' },
|
|
471
|
+
],
|
|
472
|
+
def: 'default',
|
|
473
|
+
});
|
|
474
|
+
const pick = { p: 'paste', d: 'default' }[a.trim().toLowerCase()[0]];
|
|
475
|
+
if (!pick) throw new Error(`answer paste or default, not "${a}"`);
|
|
476
|
+
const answer = pick === 'paste' ? (await p.ask('One line of notes, or a path to a file with them (no passwords)', '')).trim() : '';
|
|
477
|
+
o.unverified[item.id] = answer ? 'notes' : 'default';
|
|
478
|
+
if (answer) o.notes.push(notesFile(o.home, item, answer));
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
function migrationPlan(o) {
|
|
483
|
+
const scope = o.project ? 'project' : 'user';
|
|
484
|
+
const base = o.project ?? o.home;
|
|
485
|
+
const names = o.migrate === 'auto' ? detectSources(base, scope, o.agents) : [o.migrate];
|
|
486
|
+
const r = migratePlan({ sources: names.map((n) => readSource(n, base, scope)), targets: o.agents, base, scope, stateDir: stateDir(o.home) });
|
|
487
|
+
const planned = plan(r.actions, writeRoots(o));
|
|
488
|
+
return { planned, commands: r.commands, migration: { ...r, rows: finishRows(r.rows, planned, o.exec), base, names } };
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
function buildPlan(o, every = null) {
|
|
492
|
+
if (o.migrate) return migrationPlan(o);
|
|
493
|
+
if (o.project) {
|
|
494
|
+
const r = projectPlan(ROOT, o.project, o);
|
|
495
|
+
return { planned: plan(r.actions, writeRoots(o), readState(o.home)?.files), commands: r.commands };
|
|
496
|
+
}
|
|
497
|
+
o.prior = readState(o.home)?.commands ?? [];
|
|
498
|
+
const core = useToolNode(loadCore(ROOT), o.toolNode, o.nvm);
|
|
499
|
+
const rulesPath = path.join(stateDir(o.home), 'AGENTS.md');
|
|
500
|
+
const rules = renderRules(ROOT, o);
|
|
501
|
+
const actions = [{ kind: 'file', path: rulesPath, content: rules }, ...o.notes];
|
|
502
|
+
const commands = [];
|
|
503
|
+
for (const agent of o.agents) {
|
|
504
|
+
const profile = loadProfile(ROOT, FIXED_PROFILE[agent] ?? o.profile);
|
|
505
|
+
const r = ADAPTERS[agent]({ home: o.home, core, profile, opts: o, rules, adhdCommand: adhdCommand(o.home), rulesPath: rulesPath.split(path.sep).join('/') });
|
|
506
|
+
actions.push(...r.actions);
|
|
507
|
+
commands.push(...r.commands.map((c) => ({ ...c, agent })));
|
|
508
|
+
}
|
|
509
|
+
commands.push(...leanUpdateCommands(o.agents));
|
|
510
|
+
if (o.tools.includes('coordinate')) commands.push(...coordinateCommands(o.agents));
|
|
511
|
+
if (o.tools.includes('lean-migrate')) commands.push(...leanMigrateCommands(o.agents));
|
|
512
|
+
commands.push(...terminalCommands({ home: o.home, terminals: o.terminals, installTerminals: o.installTerminals, agents: o.agents, network: o.network, system: o.home === REAL_HOME, platform: process.platform }));
|
|
513
|
+
actions.push(...gitBashActions({ home: o.home, terminals: o.terminals, agents: o.agents }));
|
|
514
|
+
if (o.tools.includes('gsd')) {
|
|
515
|
+
const r = gsdPlan(ROOT, o.home, o);
|
|
516
|
+
actions.push(...r.actions);
|
|
517
|
+
commands.push(...r.commands);
|
|
518
|
+
}
|
|
519
|
+
if (o.bun && o.network.telemetry === 'off') {
|
|
520
|
+
actions.push({ kind: 'block', toml: true, path: path.join(o.home, '.bunfig.toml'), body: 'telemetry = false' });
|
|
521
|
+
}
|
|
522
|
+
actions.push(...posixPathActions(o, every));
|
|
523
|
+
return { planned: plan(actions, writeRoots(o), readState(o.home)?.files), commands };
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
// `behind`: tools whose pinned version is newer than the installed one (--update); their installs run even when the binary is there.
|
|
527
|
+
function prereqCommands(o, behind = new Set()) {
|
|
528
|
+
const pm = packageManager();
|
|
529
|
+
const out = [];
|
|
530
|
+
const tn = o.toolNode;
|
|
531
|
+
if (tn?.install) out.push({ tool: 'node', desc: `install Node ${tn.install} with nvm (your default Node stays as it is)`, run: [nvmInstallArgv(tn.install)], undo: [], env: nvmEnv(tn.nvmDir) });
|
|
532
|
+
for (const t of [...o.tools, ...(o.gh ? ['gh'] : [])]) {
|
|
533
|
+
if (t === 'context-mode' && tn) {
|
|
534
|
+
const prefix = ['--prefix', tn.dir];
|
|
535
|
+
out.push({ tool: t, desc: `install context-mode on Node ${tn.version}`, run: [[tn.node, tn.npmCli, 'install', '-g', ...prefix, npmSpec('context-mode')]], undo: [[tn.node, tn.npmCli, 'uninstall', '-g', ...prefix, 'context-mode']], skipIfExists: path.join(tn.modules, 'context-mode', 'package.json'), env: toolEnv(tn) });
|
|
536
|
+
continue;
|
|
537
|
+
}
|
|
538
|
+
const p = prereqFor(t, pm);
|
|
539
|
+
if (!p || (which(p.bin) && !behind.has(t))) continue;
|
|
540
|
+
if (p.install) out.push({ tool: t, desc: `install ${p.bin}`, run: p.install, undo: [], optional: t === 'gh', bin: p.bin });
|
|
541
|
+
else out.push({ tool: t, desc: `${p.bin} is missing: install it from ${p.manual}`, run: [], undo: [], manual: true, optional: t === 'gh', bin: p.bin });
|
|
542
|
+
}
|
|
543
|
+
if (o.agents.includes('antigravity')) {
|
|
544
|
+
for (const c of antigravityPrereqs(pm, process.platform, o.home, o.app)) {
|
|
545
|
+
if (c.note) console.log(c.desc);
|
|
546
|
+
else out.push({ tool: 'antigravity', undo: [], ...c });
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
if (o.bun && o.tools.includes('context-mode') && process.platform !== 'linux' && !which('bun') && bunPresent(o.home)) {
|
|
550
|
+
if (process.platform === 'win32') out.push(bunPathCommand(o.home));
|
|
551
|
+
else console.log('! Bun is in ~/.bun/bin but not on PATH; Context Mode needs it on PATH here. Add that folder to PATH.');
|
|
552
|
+
}
|
|
553
|
+
if (o.bun && o.tools.includes('context-mode') && !bunPresent(o.home)) {
|
|
554
|
+
const b = bunInstall(o.home, stateDir(o.home), process.platform, pm);
|
|
555
|
+
if (b) out.push(b);
|
|
556
|
+
else if (!o.everything) console.log('! Bun needs Homebrew here: install it from https://bun.com/docs/installation. Context Mode will run on Node.'); // --everything: the planner installs Homebrew, then Bun
|
|
557
|
+
}
|
|
558
|
+
return out;
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
// The agents --everything configures whose CLI is missing and that --install-agent can install. Not recorded in state.json:
|
|
562
|
+
// agents.json records them, and --uninstall-agent removes them, like a separate --install-agent run.
|
|
563
|
+
function everythingCliInstalls(o, gitPending) {
|
|
564
|
+
const table = agentTable({ home: o.home, platform: process.platform, dir: stateDir(o.home), realHome: REAL_HOME, gitBash: gitPending ? 'bash.exe' : undefined });
|
|
565
|
+
return o.agents.filter((a) => AGENT_CLIS[a] && table[a] && !table[a].manual && !which(AGENT_CLIS[a])).map((a) => ({
|
|
566
|
+
desc: `install the ${AGENT_CLIS[a]} CLI (${table[a].method}${table[a].version ? ` ${table[a].version}` : ''})`, run: [], undo: [], lifecycle: a, bins: table[a].bins,
|
|
567
|
+
}));
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
// --everything: the planner's steps as engine commands. Probes the machine here; the planner itself stays pure.
|
|
571
|
+
function everythingPrereqs(o, saved) {
|
|
572
|
+
const mac = process.platform === 'darwin';
|
|
573
|
+
const has = {
|
|
574
|
+
brew: !!which('brew'), winget: !!which('winget'), uv: !!which('uv'), rtk: !!which('rtk'), jq: !!which('jq'), bun: bunPresent(o.home), git: !!which('git'),
|
|
575
|
+
clt: mac && quiet(['xcode-select', '-p']).ok, nvm: !!o.nvm, apt: !!which('apt-get'), sudo: !!which('sudo'), unzip: !!which('unzip'),
|
|
576
|
+
};
|
|
577
|
+
const steps = planPrereqs({
|
|
578
|
+
nvmDirExisted: nvmDirExistedBefore(saved?.commands, fs.existsSync(path.join(o.home, '.nvm'))),
|
|
579
|
+
platform: process.platform, arch: process.arch, home: o.home, tmp: stateDir(o.home), execPath: process.execPath, has, root: process.getuid?.() === 0,
|
|
580
|
+
nodeActive: NODE_VERSION, nvmNodes: o.nvm ? installedNodes(o.nvm).map((n) => n.version) : [],
|
|
581
|
+
proxyEnv: proxyReport().map((l) => l.split('=')[0]), done: (saved?.commands ?? []).filter((c) => c.ok && c.resumeKey).map((c) => c.resumeKey),
|
|
582
|
+
needsGit: true, terminals: o.terminals, agents: o.agents,
|
|
583
|
+
});
|
|
584
|
+
const commands = pendingPrereqs(steps).map((s) => s.commands.length
|
|
585
|
+
? { tool: s.id === 'node-24' ? 'node' : s.id, desc: `prerequisite: ${s.label}`, run: s.commands, undo: s.undo ?? [], optional: s.id === 'bun', resumeKey: s.resumeKey, ...(s.id === 'node-24' && o.nvm && { env: nvmEnv(o.nvm.dir) }) }
|
|
586
|
+
: { tool: s.id, desc: `${s.label} is missing: install it from ${s.manual}`, run: [], undo: [], manual: true, optional: true, resumeKey: s.resumeKey });
|
|
587
|
+
return { steps, commands };
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
function printPrereqs(steps, exec) {
|
|
591
|
+
console.log('\nPrerequisites (installed first, only what is missing; your own Node stays the default):');
|
|
592
|
+
for (const s of steps) console.log(` - ${s.label}: ${s.skipIf ? `skipped (${s.skipIf})` : s.commands.length ? 'will install' : `install it yourself: ${s.manual}`} | ${s.why}`);
|
|
593
|
+
if (!exec) console.log(' (--no-exec: not run)');
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
function printMigration(o, m, commands) {
|
|
597
|
+
const rel = (p) => (p.startsWith(o.home) ? `~${p.slice(o.home.length)}` : p.startsWith(m.base) ? `.${p.slice(m.base.length)}` : p);
|
|
598
|
+
console.log(`\nlean-agents migration: ${m.names.join(', ')} -> ${o.agents.join(', ')}${o.project ? ` (project ${o.project})` : ''}`);
|
|
599
|
+
console.log(formatTable(m.rows, rel));
|
|
600
|
+
if (m.env.length) console.log(`\nSet these env vars before you start your agents (values are never copied): ${m.env.join(', ')}`);
|
|
601
|
+
if (m.headers.length) console.log(`Add these MCP headers by hand: ${m.headers.join('; ')}`);
|
|
602
|
+
if (commands.some((c) => c.run.length)) console.log('\nCommands:');
|
|
603
|
+
for (const c of commands) for (const argv of c.run) console.log(` $ ${argv.join(' ')}`);
|
|
604
|
+
console.log('');
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
// Agents parse this instead of scraping the text plan. Paths use ~ so no home directory leaks.
|
|
608
|
+
function printJson(o, planned, commands, migration, behind, prereqs, update) {
|
|
609
|
+
const rel = (t) => (t.startsWith(o.home + path.sep) || t === o.home ? `~${t.slice(o.home.length)}` : t);
|
|
610
|
+
const inText = (t) => t.split(o.home).join('~');
|
|
611
|
+
const plan = {
|
|
612
|
+
agents: o.agents, tools: o.tools, privacy: o.privacy, lang: o.lang, profile: o.profile ?? null, terminals: o.terminals,
|
|
613
|
+
...(o.everything && { afterNvm: o.deferred ?? [], agentNotes: o.agentNotes ?? [] }), gh: !!o.gh, bun: !!o.bun, network: o.network, migrate: migration ? migration.names : null,
|
|
614
|
+
files: planned.map((f) => ({ status: f.status, path: rel(f.path), note: f.note ?? null })),
|
|
615
|
+
commands: commands.map((c) => ({ desc: inText(c.desc), agent: c.agent ?? null, run: [...c.run, ...(c.always ?? [])].map((a) => a.map(inText)) })),
|
|
616
|
+
...(behind && { behind }),
|
|
617
|
+
...(update && { update }),
|
|
618
|
+
...(prereqs && { prereqs: prereqs.map((s) => ({ id: s.id, label: s.label, why: s.why, status: s.skipIf ? 'skip' : s.commands.length ? 'install' : 'manual', skipIf: s.skipIf, manual: s.manual ?? null })) }),
|
|
619
|
+
};
|
|
620
|
+
process.stdout.write(`${JSON.stringify(plan, null, 2)}\n`);
|
|
621
|
+
}
|
|
622
|
+
|
|
623
|
+
// One JSON object on stdout after a real apply (--json --yes). Field names are a contract: see docs/install-json.md.
|
|
624
|
+
function printApplied(o, files, commands, errors) {
|
|
625
|
+
// The home becomes ~; any other absolute path (a --project dir, node's own) is masked like the files are.
|
|
626
|
+
const inText = (t) => t.split(o.home).join('~').replace(/(^|[\s'"=(])(?:\/|[A-Za-z]:[\\/])[^\s'")]*/g, '$1<outside-home>');
|
|
627
|
+
// Never an absolute path: --project files live outside the home.
|
|
628
|
+
const rel = (t) => { const r = path.relative(o.home, t); return r === '..' || r.startsWith(`..${path.sep}`) || path.isAbsolute(r) ? '<outside-home>' : r.split(path.sep).join('/') || '.'; };
|
|
629
|
+
process.stdout.write(`${JSON.stringify({
|
|
630
|
+
ok: errors.length === 0,
|
|
631
|
+
files: files.map((f) => rel(f.path)),
|
|
632
|
+
commands: commands.map((c) => ({ ...c, desc: inText(c.desc), ...(c.run && { run: c.run.map((a) => a.map(inText)) }) })),
|
|
633
|
+
errors: errors.map(inText),
|
|
634
|
+
version: JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version,
|
|
635
|
+
}, null, 2)}\n`);
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
function printPlan(o, planned, commands, behind = new Set()) {
|
|
639
|
+
console.log(`\nlean-agents plan for ${o.agents.join(', ') || 'no agents'}`);
|
|
640
|
+
if (o.project) console.log(` project: ${o.project}`);
|
|
641
|
+
for (const n of o.agentNotes ?? []) console.log(` agents ${n}`);
|
|
642
|
+
console.log(` tools: ${o.tools.join(', ') || 'none'} | privacy: ${o.privacy} | lang: ${o.lang} | profile: ${o.profile ?? 'none'}`);
|
|
643
|
+
if (o.terminals.length) console.log(` terminals: ${o.terminals.join(', ')}`);
|
|
644
|
+
if (o.network.telemetry === 'off') for (const n of terminalPrivacyNotes(o.terminals, { orcaEnvSet: orcaEnvSet({ system: o.home === REAL_HOME }) })) console.log(` ${n}`);
|
|
645
|
+
if (o.everything && o.deferred?.length) console.log(` after nvm: run lean-agents --update to add ${o.deferred.join(', ')} (they need Node 24, which the prerequisites install under nvm)`);
|
|
646
|
+
if (o.tools.includes('context-mode')) console.log(` bun: ${o.bun ? `on${bunPresent(o.home) ? ' (already installed)' : ''}` : 'off'}`);
|
|
647
|
+
console.log(` network: ${CATEGORIES.map((c) => `${c} ${o.network[c]}`).join(', ')}`);
|
|
648
|
+
const owned = o.agents.filter((a) => /^(claude|copilot-cli|opencode-v[12])$/.test(a));
|
|
649
|
+
if (o.network.autoUpdate === 'on' && !o.keepUpdater && owned.length) console.log(` auto-update: ${owned.join(', ')} keep their own updater off because --update owns updates (--auto-update on leaves it alone)`);
|
|
650
|
+
const net = proxyReport();
|
|
651
|
+
if (net.length) console.log(` proxy and CA (passed to every command): ${net.join(' ')}`);
|
|
652
|
+
if (o.tools.includes('playwright-extension')) console.log(` signed-in browser: ${EXTENSION_NOTE}`);
|
|
653
|
+
if (o.tools.includes('code-mode') && o.agents.includes('claude')) console.log(` code mode: ${CODE_MODE_NOTE}`);
|
|
654
|
+
if (o.notes.length) console.log(` your notes for undocumented settings (saved, never applied): ${o.notes.map((n) => path.basename(n.path, '.md')).join(', ')}`);
|
|
655
|
+
console.log('');
|
|
656
|
+
console.log('Files:');
|
|
657
|
+
console.log(describe(planned, o.home));
|
|
658
|
+
if (commands.length) {
|
|
659
|
+
console.log('\nCommands:');
|
|
660
|
+
for (const c of commands) {
|
|
661
|
+
// Same check as the run below: an install already there at its pin is skipped, so do not list its commands.
|
|
662
|
+
const there = !behind.has(c.tool) && ((c.skipIfExists && exists(c.skipIfExists)) || (o.exec && c.skipIfOutput && quiet(c.skipIfOutput.cmd).ok));
|
|
663
|
+
console.log(` - ${c.desc}${c.agent ? ` (${c.agent})` : ''}${there ? ': already there, skipped' : ''}`);
|
|
664
|
+
if (there) continue;
|
|
665
|
+
for (const argv of [...c.run, ...(c.always ?? [])]) console.log(` $ ${argv.join(' ')}`);
|
|
666
|
+
}
|
|
667
|
+
}
|
|
668
|
+
console.log('');
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
// --update: rows `tool: installed -> pin` plus the shipped CHANGELOG sections after the installed lean-agents version.
|
|
672
|
+
function updateInfo(o, saved) {
|
|
673
|
+
const agentsFile = path.join(stateDir(o.home), 'agents.json');
|
|
674
|
+
let owned = [];
|
|
675
|
+
try { owned = Object.keys(JSON.parse(fs.readFileSync(agentsFile, 'utf8')).agents ?? {}); } catch { /* absent or unreadable: no agent is ours */ }
|
|
676
|
+
// --no-exec runs no external command, not even a version probe: the agent rows then show nothing installed.
|
|
677
|
+
let installed = { claude: null, opencode: null, copilot: null };
|
|
678
|
+
if (o.exec) {
|
|
679
|
+
// A scratch HOME: `opencode --version` writes a log under HOME, and a dry run must leave --home untouched.
|
|
680
|
+
const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'lean-probe-'));
|
|
681
|
+
const env = { HOME: scratch, USERPROFILE: scratch };
|
|
682
|
+
const probe = (b) => versionFull(b, ['--version'], env);
|
|
683
|
+
installed = { claude: probe('claude'), opencode: probe('opencode'), copilot: probe('copilot') };
|
|
684
|
+
fs.rmSync(scratch, { recursive: true, force: true });
|
|
685
|
+
}
|
|
686
|
+
// planUpdate compares numeric versions; the raw string (pre-release tag kept) is what an undo reinstalls.
|
|
687
|
+
const numeric = Object.fromEntries(Object.entries(installed).map(([b, v]) => [b, v?.replace(/-.*/, '') ?? null]));
|
|
688
|
+
const raw = { 'claude-code': installed.claude, 'opencode-v2': installed.opencode, 'copilot-cli': installed.copilot };
|
|
689
|
+
const rows = planUpdate({ saved, pins: PINS, owned, installed: numeric }).map((r) => (r.action === 'update' && raw[r.tool] ? { ...r, raw: raw[r.tool] } : r));
|
|
690
|
+
const log = path.join(ROOT, 'CHANGELOG.md');
|
|
691
|
+
const current = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version;
|
|
692
|
+
return { rows, notes: changelogNotes(fs.existsSync(log) ? fs.readFileSync(log, 'utf8') : '', saved.version ?? '0.0.0', current) };
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
// The folders an --everything run installs into, as one marked rc block (#335). Folders already on PATH are left out.
|
|
696
|
+
function posixPathActions(o, every) {
|
|
697
|
+
if (!every || process.platform === 'win32') return [];
|
|
698
|
+
const pending = new Set(pendingPrereqs(every.steps).map((s) => s.id));
|
|
699
|
+
const dirs = [
|
|
700
|
+
...(o.agents.includes('claude') || pending.has('uv') || pending.has('rtk') ? ['.local/bin'] : []),
|
|
701
|
+
...(o.agents.includes('opencode-v2') ? ['.opencode/bin'] : []),
|
|
702
|
+
];
|
|
703
|
+
const brew = pending.has('homebrew') ? (process.arch === 'arm64' ? '/opt/homebrew' : '/usr/local') : null;
|
|
704
|
+
const privateNode = process.execPath.startsWith(path.join(o.home, '.config', 'lean-agents', 'node') + path.sep);
|
|
705
|
+
return posixPathBlock({ home: o.home, platform: process.platform, envPath: process.env.PATH, dirs, brew, privateNode, shell: process.env.SHELL });
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
async function install(o) {
|
|
709
|
+
if (o.json && !o.yes) throw new Error('--json needs --yes: the menus would write questions to stdout');
|
|
710
|
+
const saved = o.command === 'update' ? readState(o.home) : null;
|
|
711
|
+
if (o.command === 'update' && !saved) {
|
|
712
|
+
let found = false;
|
|
713
|
+
try { found = (await inventory({ home: o.home, env: process.env, realHome: REAL_HOME })).items.length > 0; } catch { /* the plain message below */ }
|
|
714
|
+
throw new Error(`nothing to update: lean-agents is not installed${found ? '; run --adopt --yes, then install (--everything --yes)' : ''}`);
|
|
715
|
+
}
|
|
716
|
+
if (o.command === 'update' && saved.options.migrateOnly) throw new Error(`nothing to update: only ${saved.adoptOnly ? '--adopt' : '--migrate'} ran here; install first (--everything --yes)`);
|
|
717
|
+
const p = await choose(o, saved?.options);
|
|
718
|
+
const every = o.everything && !o.migrate ? everythingPrereqs(o, readState(o.home)) : null;
|
|
719
|
+
const { planned, commands: agentCommands, migration } = buildPlan(o, every);
|
|
720
|
+
if (migration && !migration.rows.length) { p.close(); console.log('Nothing to migrate: no rules, agents, skills, prompts, MCP servers or hooks found.'); return o.json && printApplied(o, [], [], []); }
|
|
721
|
+
const behind = new Set((saved ? behindPins(saved) : []).map((b) => pinTool(b.tool)));
|
|
722
|
+
// The planner owns these installs; the per-tool ones below would repeat them.
|
|
723
|
+
const owned = new Set(pendingPrereqs(every?.steps ?? []).map((s) => (s.id === 'node-24' ? 'node' : s.id)));
|
|
724
|
+
const update = saved && (o.dryRun || o.exec) ? updateInfo(o, saved) : null;
|
|
725
|
+
const upgrades = update && o.exec ? upgradeCommands({ rows: update.rows, home: o.home, dir: stateDir(o.home), realHome: REAL_HOME, stamps: agentStamps(stateDir(o.home)) }) : [];
|
|
726
|
+
const commands = [...(o.exec ? [...every?.commands ?? [], ...prereqCommands(o, behind).filter((c) => !owned.has(c.tool))] : []), ...agentCommands, ...upgrades];
|
|
727
|
+
// --everything on a fresh machine: install the agent CLIs it configures (the --install-agent path), after the prerequisites.
|
|
728
|
+
const cliInstalls = every && o.exec ? everythingCliInstalls(o, pendingPrereqs(every.steps).some((s) => s.id === 'git')) : [];
|
|
729
|
+
commands.splice(commands.length - agentCommands.length - upgrades.length, 0, ...cliInstalls);
|
|
730
|
+
|
|
731
|
+
if (o.exec) {
|
|
732
|
+
const missing = new Map();
|
|
733
|
+
for (const c of commands) {
|
|
734
|
+
if (c.agent && AGENT_CLIS[c.agent] && !cliInstalls.some((x) => x.lifecycle === c.agent)) {
|
|
735
|
+
const cli = AGENT_CLIS[c.agent];
|
|
736
|
+
if ((c.run ?? []).some((argv) => argv[0] === cli) && !which(cli)) {
|
|
737
|
+
if (!missing.has(cli)) missing.set(cli, { agent: c.agent, steps: [] });
|
|
738
|
+
missing.get(cli).steps.push(c.desc);
|
|
739
|
+
}
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
if (missing.size > 0) {
|
|
743
|
+
for (const [cli, info] of missing) {
|
|
744
|
+
const others = o.agents.filter((a) => a !== info.agent).join(',') || 'none';
|
|
745
|
+
const warn = `! the ${cli} CLI is not on PATH: ${info.steps.length} steps need it (${info.steps.join(', ')}). Install it first (--install-agent ${info.agent}), or leave it out with --agents ${others}`;
|
|
746
|
+
if (o.json) console.error(warn);
|
|
747
|
+
else console.log(warn);
|
|
748
|
+
}
|
|
749
|
+
if (!o.dryRun) {
|
|
750
|
+
p.close();
|
|
751
|
+
console.log('nothing changed');
|
|
752
|
+
process.exitCode = 1;
|
|
753
|
+
return;
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
const noGit = migration ? null : gitHint(packageManager());
|
|
759
|
+
if (noGit) console.log(noGit);
|
|
760
|
+
if (o.json && o.dryRun) {
|
|
761
|
+
p.close();
|
|
762
|
+
return printJson(o, planned, commands, migration, saved ? behindPins(saved) : undefined, every?.steps, update ?? undefined);
|
|
763
|
+
}
|
|
764
|
+
if (migration) printMigration(o, migration, o.exec ? commands : []);
|
|
765
|
+
else {
|
|
766
|
+
if (every) printPrereqs(every.steps, o.exec);
|
|
767
|
+
printPlan(o, planned, commands, behind);
|
|
768
|
+
}
|
|
769
|
+
if (update) { const text = formatUpdatePlan(update.rows, update.notes); if (text) console.log(text); }
|
|
770
|
+
else if (saved) {
|
|
771
|
+
if (behindPins(saved).length) console.log('Pins that will change (old -> new):');
|
|
772
|
+
for (const b of behindPins(saved)) console.log(`${b.tool}: ${b.installed} -> ${b.pinned}`);
|
|
773
|
+
}
|
|
774
|
+
if (o.dryRun) { p.close(); console.log('Dry run: nothing was changed.'); return; }
|
|
775
|
+
// The one question of --everything: the choose() prompter answers by default, so ask on a real one.
|
|
776
|
+
const q = o.everything && !o.yes ? await prompter(false) : p;
|
|
777
|
+
if (q !== p) p.close();
|
|
778
|
+
try { if (!yesNo(await q.ask('Apply these changes?', 'y'))) { console.log('Cancelled.'); return; } } finally { q.close(); }
|
|
779
|
+
// A Homebrew that this run installs is not on this process's PATH yet.
|
|
780
|
+
if (every && process.platform === 'darwin' && pendingPrereqs(every.steps).some((s) => s.id === 'homebrew')) process.env.PATH = `/opt/homebrew/bin${path.delimiter}/usr/local/bin${path.delimiter}${process.env.PATH ?? ''}`;
|
|
781
|
+
// Linux: uv and rtk installers put binaries in ~/.local/bin, which only a new shell may have on PATH.
|
|
782
|
+
if (every && process.platform === 'linux' && pendingPrereqs(every.steps).some((s) => s.id === 'uv' || s.id === 'rtk')) process.env.PATH = `${path.join(o.home, '.local', 'bin')}${path.delimiter}${process.env.PATH ?? ''}`;
|
|
783
|
+
// winget --scope user puts command links (uv, rtk, jq) and Git.Git's git.exe here, and on the saved user PATH, which only new terminals see (nightly fresh-machine, 2026-11-20).
|
|
784
|
+
if (every && process.platform === 'win32' && pendingPrereqs(every.steps).some((s) => s.commands.some((argv) => argv[0] === 'winget'))) {
|
|
785
|
+
// Both: winget resolves the profile folder, which differs from LOCALAPPDATA when USERPROFILE is overridden (CI). An elevated shell gets Git under Program Files.
|
|
786
|
+
const locals = [...new Set([path.join(o.home, 'AppData', 'Local'), process.env.LOCALAPPDATA].filter(Boolean))];
|
|
787
|
+
const gitMachine = process.env.ProgramFiles ? [path.join(process.env.ProgramFiles, 'Git', 'cmd')] : [];
|
|
788
|
+
process.env.PATH = [...locals.flatMap((l) => [path.join(l, 'Microsoft', 'WinGet', 'Links'), path.join(l, 'Programs', 'Git', 'cmd')]), process.env.PATH ?? '', ...gitMachine].join(path.delimiter); // Program Files last: only a fallback
|
|
789
|
+
}
|
|
790
|
+
const ui = q.menus ? await menuProgress() : null;
|
|
791
|
+
Object.assign(process.env, childEnv(o.network));
|
|
792
|
+
|
|
793
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
794
|
+
const backupDir = path.join(stateDir(o.home), 'backups', stamp);
|
|
795
|
+
const previous = readState(o.home);
|
|
796
|
+
const files = [];
|
|
797
|
+
const ran = [];
|
|
798
|
+
let failed = 0;
|
|
799
|
+
// Saved as the run goes, so an error or a killed command still leaves a state --uninstall can undo.
|
|
800
|
+
// Resume stamps only matter for an interrupted run; once everything finished they would hide a later removal.
|
|
801
|
+
let finished = false;
|
|
802
|
+
const save = () => {
|
|
803
|
+
const state = {
|
|
804
|
+
version: JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version,
|
|
805
|
+
installedAt: previous?.installedAt ?? new Date().toISOString(),
|
|
806
|
+
updatedAt: new Date().toISOString(),
|
|
807
|
+
pins: pinVersions(),
|
|
808
|
+
options: o.migrate ? previous?.options ?? { migrateOnly: true, agents: o.agents, tools: [], privacy: o.privacy, network: o.network, gh: false, terminals: [], installTerminals: [], unverified: {}, lang: 'en', profile: null, adhdAlways: false, ponytailMode: null, bun: false, shell: 'git-bash' } : { agents: o.agents, tools: o.chosenTools ?? o.tools, privacy: o.privacy, network: o.network, keepUpdater: !!o.keepUpdater, gh: o.gh, terminals: o.terminals, installTerminals: o.installTerminals, unverified: o.unverified, lang: o.lang, profile: o.profile, adhdAlways: o.adhdAlways, ponytailMode: o.ponytailMode, bun: o.bun, shell: o.shell },
|
|
809
|
+
...(o.toolNode && { toolNode: { version: o.toolNode.version, installedByLean: !!o.toolNode.install || (previous?.toolNode?.version === o.toolNode.version && !!previous.toolNode.installedByLean) } }),
|
|
810
|
+
files: [...(previous?.files ?? []), ...files],
|
|
811
|
+
...(previous?.opencode1 && { opencode1: previous.opencode1 }),
|
|
812
|
+
// --adopt --undo reads this; `adoptOnly` is not carried, so --update works after the install.
|
|
813
|
+
...(previous?.adopt && { adopt: previous.adopt }),
|
|
814
|
+
...(previous?.upgrade && { upgrade: previous.upgrade }),
|
|
815
|
+
// A command that ran again replaces its earlier record, so --uninstall undoes it once.
|
|
816
|
+
commands: [...(previous?.commands ?? []).filter((c) => !ran.some((r) => r.desc === c.desc)), ...ran].map(({ resumeKey, ...c }) => (finished ? c : { ...c, ...(resumeKey && { resumeKey }) })),
|
|
817
|
+
};
|
|
818
|
+
privateDir(stateDir(o.home), stateDir(o.home));
|
|
819
|
+
writePrivate(path.join(stateDir(o.home), 'state.json'), `${JSON.stringify(state, null, 2)}\n`);
|
|
820
|
+
};
|
|
821
|
+
let applied = false;
|
|
822
|
+
try { apply(planned, backupDir, o.home, writeRoots(o), files); applied = true; } catch (e) {
|
|
823
|
+
if (o.json) printApplied(o, files, [], [e.message]);
|
|
824
|
+
throw e;
|
|
825
|
+
} finally { if (applied || files.length) save(); }
|
|
826
|
+
const report = [];
|
|
827
|
+
const errors = [];
|
|
828
|
+
if (o.exec) {
|
|
829
|
+
const noCli = new Set(); // agents whose CLI install failed above: their steps would only fail again
|
|
830
|
+
for (const [i, c] of commands.entries()) {
|
|
831
|
+
if (noCli.has(c.agent) && (c.run ?? []).some((argv) => argv[0] === AGENT_CLIS[c.agent])) { console.log(` skipped: ${c.desc} (no ${AGENT_CLIS[c.agent]} CLI)`); continue; }
|
|
832
|
+
// gh is on by default, so having no installer for it (no brew or winget) must not fail the run.
|
|
833
|
+
// Planned before the prerequisites ran: --everything may have installed it since (macOS: brew's uv brings uvx). Not for --update's behind tools.
|
|
834
|
+
if (c.bin && !behind.has(c.tool) && which(c.bin)) continue;
|
|
835
|
+
if (c.manual) { console.log(`! ${c.desc}`); if (!c.optional) { failed++; errors.push(c.desc); } continue; }
|
|
836
|
+
const there = (c.skipIfExists && exists(c.skipIfExists)) || (c.skipIfOutput && quiet(c.skipIfOutput.cmd).ok);
|
|
837
|
+
if (there) {
|
|
838
|
+
if (!behind.has(c.tool)) continue;
|
|
839
|
+
// Installed at an older pin: undo it, then add it again at the new pin.
|
|
840
|
+
if (!c.undo.every((argv) => run(undoArgv(argv), { dryRun: false, log: console.log, env: c.env, json: o.json }))) {
|
|
841
|
+
console.log(` ! could not remove the old ${c.desc}; left as it is. Fix it by hand, then --update.`);
|
|
842
|
+
failed++;
|
|
843
|
+
errors.push(`could not remove the old ${c.desc}`);
|
|
844
|
+
continue;
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
if (ui) ui.step(i + 1, commands.length, c.desc);
|
|
848
|
+
else console.log(`- ${c.desc}`);
|
|
849
|
+
if (c.lifecycle) {
|
|
850
|
+
await agentLifecycle({ mode: 'install', agents: [c.lifecycle], home: o.home, realHome: REAL_HOME, stateDir: stateDir(o.home), dryRun: false, exec: true, yes: true, ask: async (_q, def) => def, yesNo });
|
|
851
|
+
const bin = c.bins.find((b) => fs.existsSync(b));
|
|
852
|
+
// The installer's PATH change reaches new terminals only: put its folder first here so the agent's steps below find it.
|
|
853
|
+
if (bin) process.env.PATH = `${path.dirname(bin)}${path.delimiter}${process.env.PATH ?? ''}`;
|
|
854
|
+
else { failed++; errors.push(c.desc); noCli.add(c.lifecycle); }
|
|
855
|
+
report.push({ desc: c.desc, ok: !!bin, exit: null });
|
|
856
|
+
if (ui) ui.result(!!bin, c.desc);
|
|
857
|
+
continue;
|
|
858
|
+
}
|
|
859
|
+
// Recorded before it runs, so a command killed midway can still be undone.
|
|
860
|
+
const rec = { desc: c.desc, ok: false, undo: c.undo, ...(c.reinstall && { from: c.from, owner: c.owner, reinstall: c.reinstall, reinstallAlways: c.reinstallAlways }), ...(c.env && { env: c.env }), ...(c.resumeKey && { resumeKey: c.resumeKey }) };
|
|
861
|
+
ran.push(rec);
|
|
862
|
+
save();
|
|
863
|
+
const codes = [];
|
|
864
|
+
const ok = c.run.every((argv) => run(argv, { dryRun: false, log: console.log, env: c.env, json: o.json, codes }));
|
|
865
|
+
for (const argv of c.always ?? []) run(argv, { dryRun: false, log: console.log, env: c.env, json: o.json });
|
|
866
|
+
report.push({ desc: c.desc, ok, exit: codes.at(-1) ?? null });
|
|
867
|
+
if (!ok && !c.optional) errors.push(c.desc);
|
|
868
|
+
if (ui) ui.result(ok || c.optional, c.desc);
|
|
869
|
+
else if (!ok && !c.optional) console.log(` ! failed: ${c.desc}. Run the command above by hand, then --doctor.`);
|
|
870
|
+
// An optional step (Bun) that fails only means Context Mode runs on Node; nothing to undo.
|
|
871
|
+
if (!ok && c.optional) { console.log(c.tool === 'gh' ? '! gh install failed; install it yourself (--no-gh skips it).' : c.tool === 'lean-update' ? '! lean-update skill failed to install; run the command above by hand later.' : '! Bun install failed; Context Mode will run on Node.'); ran.pop(); save(); continue; }
|
|
872
|
+
if (!ok) failed++;
|
|
873
|
+
rec.ok = ok;
|
|
874
|
+
save();
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
if (failed) {
|
|
878
|
+
console.log(`\n${failed} step(s) failed; see the lines marked ! above. Backups: ${backupDir}`);
|
|
879
|
+
ui?.summary('Summary', [`${failed} of ${commands.length} commands failed`, `Backups: ${backupDir}`], false);
|
|
880
|
+
process.exitCode = 1;
|
|
881
|
+
return o.json && printApplied(o, files, report, errors);
|
|
882
|
+
}
|
|
883
|
+
finished = true;
|
|
884
|
+
save();
|
|
885
|
+
if (o.json) printApplied(o, files, report, errors);
|
|
886
|
+
console.log(`\nDone. Backups: ${backupDir}`);
|
|
887
|
+
if (!o.project) await summaryPage(o, { updated: o.command === 'update' ? report.filter((r) => r.ok).map((r) => r.desc) : [] });
|
|
888
|
+
if (o.project) return console.log('Next: review and commit these files. Each teammate runs the installer once for the tools (rtk, context-mode, ...).');
|
|
889
|
+
console.log('Next: restart your agents, log in to your providers, then run --doctor.');
|
|
890
|
+
const shell = shellNotice();
|
|
891
|
+
if (shell) console.log(shell.text);
|
|
892
|
+
const rc = files.find((f) => f.id === 'path');
|
|
893
|
+
if (rc) console.log(`Open a new terminal (or run: . ${rc.path}) so the new PATH takes effect.`);
|
|
894
|
+
const todo = stillNeeded({ home: o.home, terminals: o.terminals, agents: o.agents });
|
|
895
|
+
if (todo.length) console.log(`Still needed from you:\n${todo.map((t) => ` - ${t.text}`).join('\n')}`);
|
|
896
|
+
if (o.tools.includes('playwright-extension')) console.log(`Signed-in browser: ${EXTENSION_NOTE}`);
|
|
897
|
+
if (o.tools.includes('code-mode') && o.agents.includes('claude')) console.log(`Code Mode: ${CODE_MODE_NOTE}`);
|
|
898
|
+
if (o.gh) console.log('GitHub CLI: run `gh auth login` yourself; lean-agents never handles tokens.');
|
|
899
|
+
for (const n of o.notes) console.log(`Notes saved: ${n.path}. Ask your agent to apply them, showing you each change first.`);
|
|
900
|
+
if (o.network.telemetry === 'off' && o.agents.includes('claude')) {
|
|
901
|
+
console.log('Strict privacy: also turn off "Help improve Claude" in your claude.ai privacy settings.');
|
|
902
|
+
}
|
|
903
|
+
if (o.network.telemetry === 'off' && o.agents.includes('copilot-cli')) {
|
|
904
|
+
console.log('Strict privacy: Copilot CLI has no telemetry setting. Start it with --disable-client-telemetry.');
|
|
905
|
+
}
|
|
906
|
+
if (o.network.telemetry === 'off' && o.agents.includes('cursor')) {
|
|
907
|
+
console.log('Strict privacy: turn on Privacy Mode in Cursor settings. It is stored on your account.');
|
|
908
|
+
}
|
|
909
|
+
if (o.network.telemetry === 'off' && o.agents.includes('antigravity')) {
|
|
910
|
+
console.log('Strict privacy: turn off "Enable Telemetry" in Antigravity settings. It is stored on your account.');
|
|
911
|
+
}
|
|
912
|
+
if (o.network.autoUpdate === 'off' && o.agents.includes('antigravity')) {
|
|
913
|
+
console.log('Auto-updates off: Antigravity CLI updates itself and has no documented switch for it.');
|
|
914
|
+
}
|
|
915
|
+
ui?.summary('Summary', [`${files.length} files written, ${ran.length} commands run`, `Backups: ${backupDir}`], true);
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
// --update --undo (#278): each agent CLI goes back to the version it had before the first upgrade lean-agents ran.
|
|
919
|
+
// Plan first; the answer (or --yes) runs it. A failed step is reported and the rest still run; --uninstall never does this.
|
|
920
|
+
async function undoAgentUpgrades(o) {
|
|
921
|
+
const S = readState(o.home);
|
|
922
|
+
const stamps = agentStamps(stateDir(o.home));
|
|
923
|
+
const todo = undoPlan(S?.commands ?? [], stamps);
|
|
924
|
+
if (!todo.length) { console.log('nothing to undo: no agent CLI upgrade by lean-agents is recorded'); return true; }
|
|
925
|
+
console.log('lean-agents --update --undo plan (the oldest saved version per agent):');
|
|
926
|
+
for (const c of todo) {
|
|
927
|
+
console.log(` - ${agentOf(c)}: back to ${c.from}`);
|
|
928
|
+
for (const argv of [...c.reinstall, ...(c.reinstallAlways ?? [])]) console.log(` $ ${argv.join(' ')}`);
|
|
929
|
+
}
|
|
930
|
+
if (o.dryRun) { console.log('Dry run: nothing was changed.'); return true; }
|
|
931
|
+
if (!o.exec) { console.log('--no-exec: nothing was run. Not done.'); return false; }
|
|
932
|
+
if (!o.yes && !(process.stdin.isTTY && process.stdout.isTTY)) { console.log('No terminal to ask on: --yes runs it. Not done.'); return false; }
|
|
933
|
+
const p = await prompter(o.yes);
|
|
934
|
+
try { if (!yesNo(await p.ask('Reinstall these versions?', o.yes ? 'y' : 'n'))) { console.log('Cancelled.'); return true; } } finally { p.close(); }
|
|
935
|
+
Object.assign(process.env, childEnv(S.options.network));
|
|
936
|
+
const { ok, restored } = undoUpgrades(todo, {}, stamps);
|
|
937
|
+
// A restored agent's records are spent; a failed one keeps them so the next --update --undo retries it.
|
|
938
|
+
S.commands = S.commands.filter((c) => !(c.reinstall && restored.has(agentOf(c))));
|
|
939
|
+
S.updatedAt = new Date().toISOString();
|
|
940
|
+
writePrivate(path.join(stateDir(o.home), 'state.json'), `${JSON.stringify(S, null, 2)}\n`);
|
|
941
|
+
return ok;
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
// The state of a machine where only an upgrade step ran (nothing else installed yet).
|
|
945
|
+
const blankState = () => ({ version: JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version, installedAt: new Date().toISOString(), pins: {}, options: { agents: [], tools: [], terminals: [], unverified: {}, gh: false, lang: 'en', profile: null, network: {} }, files: [], commands: [] });
|
|
946
|
+
|
|
947
|
+
// The 1.x config the verified backup saved: opencode1 runs on a copy of it, not on the live (2.x) config.
|
|
948
|
+
const snapshot1x = (home) => { const st = readBackupStamp(home); return st ? path.join(st.dir, 'config') : null; };
|
|
949
|
+
|
|
950
|
+
// `opencode1` (P4). The state is saved after every step, so an error midway still leaves something --uninstall can undo.
|
|
951
|
+
function sideBySide(o) {
|
|
952
|
+
const p = planOpencode1({ home: o.home, exec: o.exec, configSnapshot: snapshot1x(o.home) });
|
|
953
|
+
if (!p.ok) { console.log(`refused, nothing changed:\n${p.problems.map((x) => ` - ${x}`).join('\n')}`); return false; }
|
|
954
|
+
const win = process.platform === 'win32';
|
|
955
|
+
console.log(`${o.dryRun || !o.yes ? 'dry run: would set up' : 'setting up'} opencode1 (OpenCode ${p.version}, from ${p.source})`);
|
|
956
|
+
console.log(` binary copy: ${p.binary}\n shim: ${p.actions[0].path}\n PATH: ${win ? `user PATH (HKCU) gets ${p.pathDir}` : `${p.actions.slice(1).map((a) => a.path).join(', ')} gets a marked block`}`);
|
|
957
|
+
console.log(` 1.x reads and writes only ${opencode1Layout(o.home).frozen} and its own config copy in ${opencode1Layout(o.home).config}; the live data and config are not touched`);
|
|
958
|
+
if (o.dryRun || !o.yes) { console.log('dry run: nothing was written'); return true; }
|
|
959
|
+
const previous = readState(o.home);
|
|
960
|
+
const files = [];
|
|
961
|
+
const save = (record) => {
|
|
962
|
+
const state = previous ?? blankState();
|
|
963
|
+
privateDir(stateDir(o.home), stateDir(o.home));
|
|
964
|
+
writePrivate(path.join(stateDir(o.home), 'state.json'), `${JSON.stringify({ ...state, updatedAt: new Date().toISOString(), files: [...state.files, ...files], opencode1: record }, null, 2)}\n`);
|
|
965
|
+
};
|
|
966
|
+
const ts = new Date().toISOString().replace(/\D/g, '');
|
|
967
|
+
installOpencode1(p, { home: o.home, roots: [...writeRoots(o), opencode1Layout(o.home).root], backupDir: path.join(stateDir(o.home), 'backups', ts), apply, files, onRecord: save });
|
|
968
|
+
console.log('done: run `opencode1 --version` in a new terminal. `--uninstall` removes it; the backup and the frozen copy stay.');
|
|
969
|
+
return true;
|
|
970
|
+
}
|
|
971
|
+
|
|
972
|
+
// `--upgrade-agent opencode --yes` / `--undo` (#80 part 2, P6). The journal is state.json `upgrade`; the steps are in lib/opencode-upgrade.mjs.
|
|
973
|
+
function upgradeDeps(o, S, save, extra) {
|
|
974
|
+
const ts = new Date().toISOString().replace(/\D/g, '');
|
|
975
|
+
const rulesPath = path.join(stateDir(o.home), 'AGENTS.md');
|
|
976
|
+
// The adapter's file and JSON actions only: its commands (npx skill installs, git clones) are not run by an upgrade.
|
|
977
|
+
const adapterFor = (tools) => {
|
|
978
|
+
const saved = S.options ?? {};
|
|
979
|
+
const opts = { tools, network: saved.network ?? {}, keepUpdater: !!saved.keepUpdater, terminals: [], platform: process.platform, env: process.env, shell: 'default', ponytailMode: saved.ponytailMode ?? 'lite', adhdAlways: false };
|
|
980
|
+
const r = opencodeV2Adapter({ home: o.home, core: loadCore(ROOT), profile: null, opts, rulesPath: rulesPath.split(path.sep).join('/') });
|
|
981
|
+
if (r.commands.length) console.log(` ${r.commands.length} adapter command(s) not run by the upgrade; --update runs them`);
|
|
982
|
+
// No rules file (lean-agents never installed the rules here): do not point `instructions` at a missing file.
|
|
983
|
+
return fs.existsSync(rulesPath) ? r : { ...r, actions: r.actions.map((a) => (a.kind === 'json' ? { ...a, edits: a.edits.filter((e) => e.path[0] !== 'instructions') } : a)) };
|
|
984
|
+
};
|
|
985
|
+
const lifecycle = (mode) => agentLifecycle({ mode, fromUpgrade: true, agents: ['opencode-v2'], home: o.home, realHome: REAL_HOME, stateDir: stateDir(o.home), dryRun: false, exec: o.exec, yes: true, ask: async (_q, def) => def, yesNo });
|
|
986
|
+
const d = {
|
|
987
|
+
home: o.home, platform: process.platform, log: console.log, state: S, save, roots: writeRoots(o), which,
|
|
988
|
+
tools: { config: (S.options?.tools ?? []).filter((t) => t !== 'dcp'), dcp: ['dcp'] },
|
|
989
|
+
adapterFor, backupDir: (name) => path.join(stateDir(o.home), 'backups', `${ts}-${name}`),
|
|
990
|
+
manual: agentTable({ home: o.home, platform: process.platform, dir: stateDir(o.home), realHome: REAL_HOME })['opencode-v2'].manual,
|
|
991
|
+
plan1: () => planOpencode1({ home: o.home, exec: o.exec, configSnapshot: snapshot1x(o.home) }),
|
|
992
|
+
install1: (p, files, onRecord) => installOpencode1(p, { home: o.home, roots: [...writeRoots(o), opencode1Layout(o.home).root], backupDir: path.join(stateDir(o.home), 'backups', `${ts}-opencode1`), apply, files, onRecord }),
|
|
993
|
+
installAgent: () => lifecycle('install'),
|
|
994
|
+
uninstallAgent: () => lifecycle('uninstall'),
|
|
995
|
+
...extra,
|
|
996
|
+
};
|
|
997
|
+
return d;
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
// Temp file then rename: a kill midway never leaves a truncated state.json (it holds the journal --undo needs).
|
|
1001
|
+
function saveJournalState(o, S) {
|
|
1002
|
+
S.updatedAt = new Date().toISOString();
|
|
1003
|
+
const dir = stateDir(o.home);
|
|
1004
|
+
privateDir(dir, dir);
|
|
1005
|
+
const file = path.join(dir, 'state.json');
|
|
1006
|
+
writePrivate(`${file}.tmp`, `${JSON.stringify(S, null, 2)}\n`);
|
|
1007
|
+
renameRetry(`${file}.tmp`, file);
|
|
1008
|
+
}
|
|
1009
|
+
|
|
1010
|
+
const refuse = (problems) => { console.log(`refused, nothing changed:\n${problems.map((x) => ` - ${x}`).join('\n')}`); return false; };
|
|
1011
|
+
|
|
1012
|
+
async function applyUpgrade(o) {
|
|
1013
|
+
const fail = failAt();
|
|
1014
|
+
const S = readState(o.home) ?? blankState();
|
|
1015
|
+
const stamp = readBackupStamp(o.home);
|
|
1016
|
+
const { problems, baseline } = applyPreflight({ home: o.home, stamp, upgrade: S.upgrade, exec: o.exec, list: listProcesses, opencodeRunning });
|
|
1017
|
+
if (problems.length) return refuse(problems);
|
|
1018
|
+
const save = () => saveJournalState(o, S);
|
|
1019
|
+
const inv = upgradeInventory(await inventory({ home: o.home, env: process.env, realHome: REAL_HOME }), { home: o.home });
|
|
1020
|
+
const steps = createSteps(upgradeDeps(o, S, save, { inv, stamp }));
|
|
1021
|
+
S.upgrade = { backup: stamp.dir, baseline };
|
|
1022
|
+
const ctx = makeCtx({ home: o.home, stamp, journal: S.upgrade });
|
|
1023
|
+
console.log(`applying the OpenCode upgrade: verified backup ${stamp.dir} (${stamp.sessions} sessions)`);
|
|
1024
|
+
const ok = await runApply({ steps, journal: S.upgrade, save, ctx, fail, restore: () => restoreData({ home: o.home, backupDir: stamp.dir }) });
|
|
1025
|
+
if (!ok) { process.exitCode = 1; return false; }
|
|
1026
|
+
console.log('done. Start OpenCode 2 once: it migrates the live session db (the backup and the frozen copy hold the 1.x state). `opencode1` runs 1.x on the frozen copy.\n`--upgrade-agent opencode --undo --yes` goes back to 1.x; the backup and the frozen copy are never deleted.');
|
|
1027
|
+
return true;
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
async function undoUpgrade(o) {
|
|
1031
|
+
const S = readState(o.home);
|
|
1032
|
+
const journal = S?.upgrade;
|
|
1033
|
+
if (!isActive(journal)) { console.log('nothing to undo: no OpenCode upgrade is active (the backup and the frozen copy are kept either way)'); return true; }
|
|
1034
|
+
const L = backupLayout(o.home, 'x');
|
|
1035
|
+
// The journal names the backup folder: only one inside lean-agents' own backups folder is used.
|
|
1036
|
+
if (typeof journal.backup !== 'string' || path.dirname(journal.backup) !== path.dirname(L.backup) || !/^opencode1-sessions-\d{8}T\d{6}Z$/.test(path.basename(journal.backup)) || !Array.isArray(journal.steps)) return refuse([`the journal names a backup outside ${path.dirname(L.backup)}: not used`]);
|
|
1037
|
+
const stamp = { dir: journal.backup, frozen: L.frozen };
|
|
1038
|
+
const todo = journal.steps.filter((s) => s.status !== 'undone').reverse().map((s) => s.id);
|
|
1039
|
+
console.log(`undo: ${todo.length ? todo.join(', ') : 'no step left to undo'}, then the 1.x data comes back from ${L.frozen} (the 2.x db is moved aside, never deleted)`);
|
|
1040
|
+
if (o.dryRun || !o.yes) { console.log('dry run: nothing was changed (--yes does it)'); return true; }
|
|
1041
|
+
const problems = [];
|
|
1042
|
+
try { if (opencodeRunning(listProcesses())) problems.push('an opencode process is running (the 1.x app or the 2.x background service): close it first; lean-agents did not start it'); } catch (e) { problems.push(`cannot list the running processes (${String(e.message).split('\n')[0]}): not safe to continue`); }
|
|
1043
|
+
const bad = verifyBackup(stamp.dir);
|
|
1044
|
+
if (bad.length) problems.push(`the backup does not match its manifest (${bad[0]}): not used; see ${path.join(stamp.dir, 'RESTORE.md')}`);
|
|
1045
|
+
if (!o.exec) problems.push('--no-exec: undo may run the OpenCode 2 uninstall and a `--version` probe');
|
|
1046
|
+
if (problems.length) return refuse(problems);
|
|
1047
|
+
const save = () => saveJournalState(o, S);
|
|
1048
|
+
const steps = createSteps(upgradeDeps(o, S, save, { stamp, inv: { items: [] } }));
|
|
1049
|
+
const ctx = makeCtx({ home: o.home, stamp, journal });
|
|
1050
|
+
const ok = await runUndo({ steps, journal, save, ctx, restore: () => restoreData({ home: o.home, backupDir: stamp.dir }) });
|
|
1051
|
+
if (!ok) { process.exitCode = 1; return false; }
|
|
1052
|
+
const drift = configDrift(L, stamp.dir);
|
|
1053
|
+
if (drift.length) console.log(`! these config files differ from the 1.x snapshot in the backup (left as they are): ${drift.join(', ')}`);
|
|
1054
|
+
const kept2x = journal.steps?.find((x) => x.id === 'install2x')?.kept2x;
|
|
1055
|
+
console.log(`undone: OpenCode 1.x data${kept2x ? ' is back; OpenCode 2 stays (see the ! line above)' : ' and binary are back'}. The backup (${stamp.dir}) and the frozen copy (${L.frozen}) are kept.`);
|
|
1056
|
+
return true;
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
// --uninstall after an applied upgrade: undo the files the opencode1, config and dcp steps wrote (same entry undo as --undo, roots
|
|
1060
|
+
// checked there). No 1.x restore, no 2.x uninstall, no data restore: the journal is archived right after.
|
|
1061
|
+
async function revertUpgradeFiles(o, S) {
|
|
1062
|
+
const steps = createSteps(upgradeDeps(o, S, () => {}, { stamp: {}, inv: { items: [] } }));
|
|
1063
|
+
const recs = Array.isArray(S.upgrade.steps) ? S.upgrade.steps : [];
|
|
1064
|
+
for (const rec of [...recs].reverse()) {
|
|
1065
|
+
const step = ['opencode1', 'config', 'dcp'].includes(rec?.id) && rec.status !== 'undone' ? steps.find((x) => x.id === rec.id) : null;
|
|
1066
|
+
if (step) await step.undo(rec, null);
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
|
|
1070
|
+
// The finish-step page (#181): an owned file in the state dir (--uninstall removes it). Returns its path, or null when nothing was written.
|
|
1071
|
+
async function summaryPage(o, { updated = [] } = {}) {
|
|
1072
|
+
const state = readState(o.home);
|
|
1073
|
+
if (!state) return null;
|
|
1074
|
+
const rows = [];
|
|
1075
|
+
doctor({ home: o.home, state, exec: o.exec, nodeVersion: NODE_VERSION, collect: rows });
|
|
1076
|
+
const network = state.options.network ?? o.network;
|
|
1077
|
+
const lang = o.lang ?? state.options.lang ?? 'en';
|
|
1078
|
+
const model = buildSummary({
|
|
1079
|
+
state, rows, updated, home: [o.home, os.homedir()], lang,
|
|
1080
|
+
applied: { ok: true, version: state.version, files: state.files.map((f) => f.path), commands: state.commands.map((c) => ({ desc: c.desc, ok: c.ok })), errors: [] },
|
|
1081
|
+
logins: loginRows({ agents: state.options.agents, gh: !!state.options.gh, exec: o.exec, outbound: network.outbound }),
|
|
1082
|
+
});
|
|
1083
|
+
const file = path.join(stateDir(o.home), 'summary.html');
|
|
1084
|
+
const content = renderSummary({ model, filed: state.filedIssues, network, home: [o.home, os.homedir()] });
|
|
1085
|
+
const [planned] = plan([{ kind: 'file', path: file, content }], writeRoots(o), state.files);
|
|
1086
|
+
if (planned.status === 'skip') { console.log(`Summary page not written: ${file} ${planned.note}.`); return null; }
|
|
1087
|
+
const [entry] = apply([planned], path.join(stateDir(o.home), 'backups', 'summary'), o.home, writeRoots(o));
|
|
1088
|
+
if (entry) {
|
|
1089
|
+
// A rewrite keeps the first record (created, backup), so --uninstall still removes the file.
|
|
1090
|
+
const first = state.files.find((f) => f.path === file);
|
|
1091
|
+
state.files = [...state.files.filter((f) => f !== first), { ...entry, ...(first && { created: first.created, backup: first.backup }) }];
|
|
1092
|
+
writePrivate(path.join(stateDir(o.home), 'state.json'), `${JSON.stringify(state, null, 2)}\n`);
|
|
1093
|
+
}
|
|
1094
|
+
console.log(`Summary page: ${file}`);
|
|
1095
|
+
if (canOffer({ noOpen: o.noOpen, yes: o.yes, json: o.json, tty: process.stdin.isTTY && process.stdout.isTTY })) {
|
|
1096
|
+
const p = await prompter(false);
|
|
1097
|
+
try { if (yesNo(await p.ask('Open it in your browser?', 'n'))) quiet(openArgv(process.platform, file), 15000); } finally { p.close(); }
|
|
1098
|
+
}
|
|
1099
|
+
return file;
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
// --summary: rebuild the page from state.json, after recording the issues the verify prompt filed (--filed-issue "item=url").
|
|
1103
|
+
async function summaryCommand(o) {
|
|
1104
|
+
const state = readState(o.home);
|
|
1105
|
+
if (!state) { console.log('lean-agents is not installed: nothing to summarize.'); process.exitCode = 1; return; }
|
|
1106
|
+
if (o.filedIssues?.length) {
|
|
1107
|
+
const home = [o.home, os.homedir()];
|
|
1108
|
+
for (const f of o.filedIssues) {
|
|
1109
|
+
const at = f.lastIndexOf('=');
|
|
1110
|
+
if (at < 1) throw new Error('--filed-issue takes "item=issue url"');
|
|
1111
|
+
state.filedIssues = addFiledIssue(state.filedIssues, { item: f.slice(0, at), title: f.slice(0, at), url: f.slice(at + 1) }, { home });
|
|
1112
|
+
}
|
|
1113
|
+
writePrivate(path.join(stateDir(o.home), 'state.json'), `${JSON.stringify(state, null, 2)}\n`);
|
|
1114
|
+
}
|
|
1115
|
+
if (!(await summaryPage(o))) process.exitCode = 1;
|
|
1116
|
+
}
|
|
1117
|
+
|
|
1118
|
+
async function uninstall(o) {
|
|
1119
|
+
const state = readState(o.home);
|
|
1120
|
+
if (!state) { console.log('lean-agents is not installed.'); return; }
|
|
1121
|
+
// A settled upgrade (`applied` never moves on by itself) must not block --uninstall for a user who stays on 2.x. Any other live
|
|
1122
|
+
// status is a half-done apply or undo: finish it with --undo first. --uninstall archives the journal, so --undo is gone after it.
|
|
1123
|
+
const up = state.upgrade;
|
|
1124
|
+
if (isActive(up) && up.status !== 'applied') throw new Error(`an OpenCode upgrade is ${up.status}: run --upgrade-agent opencode --undo first (it restores your 1.x data), then --uninstall`);
|
|
1125
|
+
if (isActive(up)) {
|
|
1126
|
+
const kept = typeof up.backup === 'string' ? `the 1.x backup (${up.backup}, see RESTORE.md in it)` : 'the 1.x backup';
|
|
1127
|
+
console.log(`! the OpenCode 2 upgrade stays: --uninstall does not go back to 1.x, and its journal is archived, so --undo is no longer available afterwards.\n Removed: what the upgrade added (the opencode1 shim and PATH block, the managed 2.x config and DCP edits).\n Kept: your data (the live 2.x sessions), ${kept}, the frozen copy and the OpenCode 2 install. To go back to 1.x, run --upgrade-agent opencode --undo --yes first.`);
|
|
1128
|
+
}
|
|
1129
|
+
const p = await prompter(o.yes);
|
|
1130
|
+
console.log(`This restores ${state.files.length} files and undoes ${state.commands.length} commands.`);
|
|
1131
|
+
if (o.dryRun) {
|
|
1132
|
+
for (const c of [...state.commands].reverse()) {
|
|
1133
|
+
if (c.undo?.length) console.log(` - undo: ${c.desc}${c.agent ? ` (${c.agent})` : ''}`);
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
if (o.dryRun || !yesNo(await p.ask('Uninstall?', o.yes ? 'y' : 'n'))) { p.close(); console.log('Nothing changed.'); return; }
|
|
1137
|
+
p.close();
|
|
1138
|
+
if (!o.exec && state.commands.length) throw new Error('--no-exec cannot undo the commands this install ran; run --uninstall without it');
|
|
1139
|
+
const failed = new Map();
|
|
1140
|
+
if (o.exec) {
|
|
1141
|
+
for (const c of [...state.commands].reverse()) {
|
|
1142
|
+
const bad = (c.undo ?? []).filter((argv) => !run(undoArgv(argv), { dryRun: false, log: console.log, env: c.env }));
|
|
1143
|
+
if (bad.length) {
|
|
1144
|
+
if (c.ok === false) {
|
|
1145
|
+
console.log(' (it did not finish, so there may be nothing to remove)');
|
|
1146
|
+
} else {
|
|
1147
|
+
console.log(' ! failed. Run the command above by hand.');
|
|
1148
|
+
process.exitCode = 1;
|
|
1149
|
+
failed.set(c, bad);
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
if (state.toolNode?.installedByLean) console.log(`Kept Node v${state.toolNode.version} (lean-agents never removes a Node); remove it with \`nvm uninstall ${state.toolNode.version}\`.`);
|
|
1155
|
+
if (isActive(up)) await revertUpgradeFiles(o, state);
|
|
1156
|
+
const report = undo(state.files, writeRoots(o));
|
|
1157
|
+
if (state.opencode1) report.push(...removeOpencode1(state.opencode1, { home: o.home }));
|
|
1158
|
+
for (const [what, file] of report) console.log(` ${what.padEnd(20)} ${file}`);
|
|
1159
|
+
if (report.some(([what]) => what === 'left (symlink)')) console.log(' ! Paths marked "left (symlink)" were not touched; remove our lines there by hand.');
|
|
1160
|
+
const stateFile = path.join(stateDir(o.home), 'state.json');
|
|
1161
|
+
if (failed.size) {
|
|
1162
|
+
// Files are already restored; keep only the failed undo argvs, so a second --uninstall retries them.
|
|
1163
|
+
const commands = state.commands.filter((c) => failed.has(c)).map((c) => ({ ...c, undo: failed.get(c) }));
|
|
1164
|
+
writePrivate(stateFile, `${JSON.stringify({ ...state, files: [], commands, opencode1: undefined, upgrade: undefined }, null, 2)}\n`);
|
|
1165
|
+
console.log(`Not finished: ${failed.size} undo command(s) failed and stay recorded. Fix the cause (or run them by hand), then run --uninstall again.`);
|
|
1166
|
+
return;
|
|
1167
|
+
}
|
|
1168
|
+
renameRetry(stateFile, path.join(stateDir(o.home), `state.uninstalled-${Date.now()}.json`));
|
|
1169
|
+
if (state.adopt) {
|
|
1170
|
+
saveState(stateDir(o.home), state.adopt);
|
|
1171
|
+
console.log(' kept: the --adopt record; undo it with --adopt --undo');
|
|
1172
|
+
}
|
|
1173
|
+
// Backups are the only undo for edits we cannot revert, so they stay unless the user says yes (--yes keeps them).
|
|
1174
|
+
const backups = path.join(stateDir(o.home), 'backups');
|
|
1175
|
+
const q = await prompter(o.yes);
|
|
1176
|
+
const drop = fs.existsSync(backups) && yesNo(await q.ask(`Delete backups in ${backups}?`, 'n'));
|
|
1177
|
+
q.close();
|
|
1178
|
+
if (drop) dropBackups(backups);
|
|
1179
|
+
console.log(drop ? 'Uninstalled. Backups deleted.' : `Uninstalled. Backups are kept in ${backups}.`);
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
// --install-agent / --uninstall-agent vscode-copilot: the engine's own install, and an undo scoped to this adapter's files.
|
|
1183
|
+
function vscodeHooks(o) {
|
|
1184
|
+
const configured = () => !!readState(o.home)?.options.agents.includes('vscode-copilot');
|
|
1185
|
+
const configure = () => {
|
|
1186
|
+
const saved = readState(o.home);
|
|
1187
|
+
// Tools and terminals stay as chosen before (none on a first run): this verb adds the agent only, so it asks nothing about them.
|
|
1188
|
+
return install({ ...o, command: 'install', yes: o.yes || o.dryRun, agents: [...new Set([...(saved?.options.agents ?? []), 'vscode-copilot'])], tools: o.tools ?? saved?.options.tools ?? [], terminals: o.terminals ?? saved?.options.terminals ?? [] });
|
|
1189
|
+
};
|
|
1190
|
+
const uninstallScoped = async () => {
|
|
1191
|
+
const state = readState(o.home);
|
|
1192
|
+
const core = loadCore(ROOT);
|
|
1193
|
+
const planned = vscodeCopilotAdapter({ home: o.home, core, profile: loadProfile(ROOT, FIXED_PROFILE['vscode-copilot']), opts: state.options, rules: '', adhdCommand: adhdCommand(o.home) });
|
|
1194
|
+
const mine = new Set(planned.actions.map((a) => a.path));
|
|
1195
|
+
const files = state.files.filter((f) => mine.has(f.path));
|
|
1196
|
+
const commands = state.commands.filter((c) => c.agent === 'vscode-copilot');
|
|
1197
|
+
console.log(`This restores ${files.length} files and undoes ${commands.length} commands, all written for vscode-copilot.`);
|
|
1198
|
+
if (o.dryRun) {
|
|
1199
|
+
for (const c of [...commands].reverse()) {
|
|
1200
|
+
if (c.undo?.length) console.log(` - undo: ${c.desc}${c.agent ? ` (${c.agent})` : ''}`);
|
|
1201
|
+
}
|
|
1202
|
+
}
|
|
1203
|
+
const p = await prompter(o.yes);
|
|
1204
|
+
const ok = !o.dryRun && yesNo(await p.ask('Remove the vscode-copilot config?', o.yes ? 'y' : 'n'));
|
|
1205
|
+
p.close();
|
|
1206
|
+
if (!ok) { console.log('Nothing changed.'); return; }
|
|
1207
|
+
if (!o.exec && commands.length) throw new Error('--no-exec cannot undo the commands this install ran; run it without --no-exec');
|
|
1208
|
+
for (const c of o.exec ? [...commands].reverse() : []) {
|
|
1209
|
+
for (const argv of c.undo ?? []) if (!run(undoArgv(argv), { dryRun: false, log: console.log, env: c.env })) { console.log(' ! failed. Run the command above by hand.'); process.exitCode = 1; }
|
|
1210
|
+
}
|
|
1211
|
+
for (const [what, file] of undo(files, writeRoots(o))) console.log(` ${what.padEnd(20)} ${file}`);
|
|
1212
|
+
const file = path.join(stateDir(o.home), 'state.json');
|
|
1213
|
+
writePrivate(file, `${JSON.stringify({ ...state, options: { ...state.options, agents: state.options.agents.filter((a) => a !== 'vscode-copilot') }, files: state.files.filter((f) => !mine.has(f.path)), commands: state.commands.filter((c) => c.agent !== 'vscode-copilot') }, null, 2)}\n`);
|
|
1214
|
+
console.log('vscode-copilot: removed. Your other config and the extension were not touched.');
|
|
1215
|
+
};
|
|
1216
|
+
return { configured, install: configure, uninstall: uninstallScoped };
|
|
1217
|
+
}
|
|
1218
|
+
|
|
1219
|
+
// The agent files the issue itself, and only after the user said yes; this only drafts.
|
|
1220
|
+
function feedback(o) {
|
|
1221
|
+
if (!o.failedCommand) throw new Error('--feedback-draft needs --failed-command <text>');
|
|
1222
|
+
const state = readState(o.home);
|
|
1223
|
+
const network = { ...(o.networkPreset ? preset(o.networkPreset) : fromPrivacy(o.privacy) ?? state?.options.network ?? {}), ...o.networkFlags };
|
|
1224
|
+
const versions = { 'lean-agents': JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version, node: NODE_VERSION };
|
|
1225
|
+
const draft = draftIssue({ network, home: [o.home, os.homedir()], versions, command: o.failedCommand, error: fs.readFileSync(0, 'utf8'), kind: o.feedbackKind });
|
|
1226
|
+
process.stdout.write(`${JSON.stringify(draft ?? { offer: false })}\n`);
|
|
1227
|
+
}
|
|
1228
|
+
|
|
1229
|
+
// Below the engines floor, read-only paths still report; anything that writes or runs commands stops.
|
|
1230
|
+
function checkNodeFloor(o) {
|
|
1231
|
+
const floor = JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).engines.node;
|
|
1232
|
+
// LEAN_AGENTS_NODE may fake a lower version for tests, never a higher one (#229).
|
|
1233
|
+
// A malformed or prerelease override (`abc`, `22.20.0-rc.1`) is cleaned or ignored (#235).
|
|
1234
|
+
const fake = (process.env.LEAN_AGENTS_NODE ?? '').replace(/-.*/, '');
|
|
1235
|
+
const override = /^v?\d+(\.\d+){0,2}$/.test(fake) ? fake.replace(/^v/, '').split('.').concat('0', '0').slice(0, 3).join('.') : null;
|
|
1236
|
+
const running = [process.versions.node, override].find((v) => v && !satisfies(v, floor));
|
|
1237
|
+
if (!running) return;
|
|
1238
|
+
const readOnly = ['help', 'version', 'doctor', 'usage', 'feedback'].includes(o.command) || (o.command === 'upgrade-agent' && !o.yes) || o.dryRun || (o.command === 'adopt' && !o.yes && !o.undo);
|
|
1239
|
+
const allow = process.env.LEAN_AGENTS_ALLOW_OLD_NODE === '1';
|
|
1240
|
+
console.error(`lean-agents: Node ${running} is older than ${floor.replace(/^>=/, '')}, which lean-agents needs. Fix: nvm install 22 && nvm use 22, or run install.sh.${readOnly || allow ? '' : ' Set LEAN_AGENTS_ALLOW_OLD_NODE=1 to run anyway.'}`);
|
|
1241
|
+
if (!readOnly && !allow) process.exit(1);
|
|
1242
|
+
}
|
|
1243
|
+
|
|
1244
|
+
async function main() {
|
|
1245
|
+
const o = parseArgs(process.argv.slice(2));
|
|
1246
|
+
checkNodeFloor(o);
|
|
1247
|
+
// A repository gets files only: tools and agents stay per user.
|
|
1248
|
+
if (o.project && o.agents?.length && !o.migrate) throw new Error('--project writes repository files only: run --agents in a separate install');
|
|
1249
|
+
if (o.project) { project = o.project; if (!o.migrate) { o.agents = []; o.exec = false; } }
|
|
1250
|
+
// --json keeps stdout for the one JSON object; every message goes to stderr.
|
|
1251
|
+
if (o.json) console.log = console.error;
|
|
1252
|
+
isolate(o.home);
|
|
1253
|
+
shareProxy();
|
|
1254
|
+
if (o.command === 'help') return console.log(HELP);
|
|
1255
|
+
if (o.command === 'version') return console.log(JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version);
|
|
1256
|
+
if (o.command === 'doctor') {
|
|
1257
|
+
const state = readState(o.home);
|
|
1258
|
+
const probe = o.probePlugins && state?.options.agents.some((a) => a.startsWith('opencode')) ? await probePlugins(o.home) : [];
|
|
1259
|
+
return process.exit(doctor({ home: o.home, state, exec: o.exec, nodeVersion: NODE_VERSION, json: o.json, probe }) ? 0 : 1);
|
|
1260
|
+
}
|
|
1261
|
+
if (o.command === 'upgrade-agent' && o.upgradeAgent === 'vscode-copilot') {
|
|
1262
|
+
if (o.backup || o.opencode1 || o.undo) throw new Error('--upgrade-agent vscode-copilot takes no other flags');
|
|
1263
|
+
console.log(`vscode-copilot: ${VSCODE_NOTE}\nNothing to upgrade here. To refresh the files lean-agents wrote (rules, agents, mcp.json), run --update.`);
|
|
1264
|
+
return;
|
|
1265
|
+
}
|
|
1266
|
+
if (o.command === 'upgrade-agent') {
|
|
1267
|
+
if (o.backup) {
|
|
1268
|
+
if (o.undo) throw new Error('--upgrade-agent opencode --backup has no --undo: the backup is permanent and lean-agents never deletes it');
|
|
1269
|
+
const r = backupOpencode({ home: o.home, dryRun: o.dryRun || !o.yes });
|
|
1270
|
+
return process.exit(r.ok ? 0 : 1);
|
|
1271
|
+
}
|
|
1272
|
+
if (o.opencode1) {
|
|
1273
|
+
if (o.undo) throw new Error('--upgrade-agent opencode --opencode1 has no --undo yet: run --uninstall');
|
|
1274
|
+
return process.exit(sideBySide(o) ? 0 : 1);
|
|
1275
|
+
}
|
|
1276
|
+
if (o.undo) return process.exit((await undoUpgrade(o)) ? 0 : 1);
|
|
1277
|
+
if (o.yes && !o.dryRun) return process.exit((await applyUpgrade(o)) ? 0 : 1);
|
|
1278
|
+
const env = process.env;
|
|
1279
|
+
const inv = await inventory({ home: o.home, env, realHome: REAL_HOME });
|
|
1280
|
+
const bin = which('opencode');
|
|
1281
|
+
// With --home elsewhere, `opencode --version` would still run the real agent (it writes logs): report it as not probed.
|
|
1282
|
+
const norm = (p) => (process.platform === 'win32' ? path.resolve(p).toLowerCase() : path.resolve(p));
|
|
1283
|
+
const own = norm(o.home) === norm(REAL_HOME);
|
|
1284
|
+
const binVer = bin && o.exec ? (own ? binVersion('opencode') : 'not probed (--home)') : null;
|
|
1285
|
+
const r = upgradeInventory(inv, { home: o.home, binary: { path: bin, version: binVer } });
|
|
1286
|
+
if (o.json) process.stdout.write(`${JSON.stringify(r, null, 2)}\n`); else console.log(formatUpgrade(r));
|
|
1287
|
+
return process.exit(0);
|
|
1288
|
+
}
|
|
1289
|
+
if (o.backup) throw new Error('--backup goes with --upgrade-agent opencode');
|
|
1290
|
+
if (o.command === 'update' && o.undo && o.json) throw new Error('--update --undo has no --json output: the plan and the results are text');
|
|
1291
|
+
if (o.command === 'update' && o.undo) return process.exit((await undoAgentUpgrades(o)) ? 0 : 1);
|
|
1292
|
+
if ((o.undo || o.keepBackup || o.confirmRemovals) && o.command !== 'adopt') throw new Error('--undo, --keep-backup and --confirm-removals go with --adopt');
|
|
1293
|
+
if (o.command === 'adopt') {
|
|
1294
|
+
// Removals outside the JSON edits need a yes: a menu on a terminal, --confirm-removals without one.
|
|
1295
|
+
const tty = process.stdin.isTTY && process.stdout.isTTY && !o.json;
|
|
1296
|
+
const p = o.yes && !o.confirmRemovals && tty ? await prompter(false) : null;
|
|
1297
|
+
const confirm = o.confirmRemovals ? async () => true : p ? async (q) => yesNo(await p.ask(q, 'n')) : async () => false;
|
|
1298
|
+
const ok = await adopt({ home: o.home, json: o.json, realHome: REAL_HOME, yes: o.yes, dryRun: o.dryRun, undo: o.undo, keepBackup: o.keepBackup, exec: o.exec, confirm, stateDir: stateDir(o.home) });
|
|
1299
|
+
p?.close();
|
|
1300
|
+
return process.exit(ok ? 0 : 1);
|
|
1301
|
+
}
|
|
1302
|
+
if (o.command === 'usage') {
|
|
1303
|
+
const network = { ...(o.networkPreset ? preset(o.networkPreset) : fromPrivacy(o.privacy) ?? readState(o.home)?.options.network ?? {}), ...o.networkFlags };
|
|
1304
|
+
return console.log(network.outbound === 'off' ? 'usage skipped: outbound calls are off (no request to api.github.com)' : copilotUsage());
|
|
1305
|
+
}
|
|
1306
|
+
if (o.command === 'agent') {
|
|
1307
|
+
const p = await prompter(o.yes);
|
|
1308
|
+
try { return await agentLifecycle({ mode: o.agentMode, agents: o.agentList, home: o.home, realHome: REAL_HOME, stateDir: stateDir(o.home), dryRun: o.dryRun, exec: o.exec, yes: o.yes, ask: p.ask, yesNo, vscode: vscodeHooks(o) }); } finally { p.close(); }
|
|
1309
|
+
}
|
|
1310
|
+
if (o.command === 'feedback') return feedback(o);
|
|
1311
|
+
if (o.command === 'summary') return summaryCommand(o);
|
|
1312
|
+
if (o.command === 'uninstall') return uninstall(o);
|
|
1313
|
+
return install(o);
|
|
1314
|
+
}
|
|
1315
|
+
|
|
1316
|
+
main().catch((e) => {
|
|
1317
|
+
console.error(`lean-agents: ${e.message}`);
|
|
1318
|
+
process.exit(1);
|
|
1319
|
+
});
|