lean-agents 0.0.0-stage → 0.8.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/LICENSE +21 -0
- package/README.es.md +454 -0
- package/README.md +453 -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 +186 -0
- package/core/mcp.json +38 -0
- package/core/pins.json +30 -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 +29 -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/bump-pins.mjs +104 -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/copilot-context-mode.mjs +33 -0
- package/scripts/labels.sh +55 -0
- package/scripts/lean.mjs +700 -0
- package/scripts/lib/adapters/antigravity.mjs +72 -0
- package/scripts/lib/adapters/claude.mjs +122 -0
- package/scripts/lib/adapters/copilot-cli.mjs +81 -0
- package/scripts/lib/adapters/cursor.mjs +60 -0
- package/scripts/lib/adapters/opencode-v1.mjs +86 -0
- package/scripts/lib/adapters/opencode-v2.mjs +168 -0
- package/scripts/lib/adapters/vscode-copilot.mjs +56 -0
- package/scripts/lib/adhd.mjs +28 -0
- package/scripts/lib/adopt.mjs +474 -0
- package/scripts/lib/agent-lifecycle.mjs +163 -0
- package/scripts/lib/copilot-usage.mjs +49 -0
- package/scripts/lib/doctor.mjs +207 -0
- package/scripts/lib/feedback.mjs +30 -0
- package/scripts/lib/fsops.mjs +291 -0
- package/scripts/lib/gsd.mjs +42 -0
- package/scripts/lib/inventory.mjs +195 -0
- package/scripts/lib/lean-update.mjs +30 -0
- package/scripts/lib/migrate.mjs +407 -0
- package/scripts/lib/network.mjs +79 -0
- package/scripts/lib/node-runtime.mjs +85 -0
- package/scripts/lib/parallel.mjs +265 -0
- package/scripts/lib/pins.mjs +47 -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/system.mjs +178 -0
- package/scripts/lib/terminals.mjs +218 -0
- package/scripts/lib/ui.mjs +34 -0
- package/scripts/lib/unverified.mjs +49 -0
- package/scripts/lib/upgrade.mjs +130 -0
- package/scripts/lib/verify-commit.mjs +16 -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 +43 -0
- package/scripts/release.mjs +46 -0
- package/scripts/verify-pins.mjs +36 -0
- package/scripts/version-watch.mjs +118 -0
package/scripts/lean.mjs
ADDED
|
@@ -0,0 +1,700 @@
|
|
|
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 } 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, gitHint, detectAgents, packageManager, prereqFor, antigravityPrereqs, bunInstall, bunPresent, which, run, quiet, exists, isolate, configHome, envDir } from './lib/system.mjs';
|
|
24
|
+
import { doctor } from './lib/doctor.mjs';
|
|
25
|
+
import { adopt, inventory } from './lib/adopt.mjs';
|
|
26
|
+
import { upgradeInventory, formatUpgrade } from './lib/upgrade.mjs';
|
|
27
|
+
import { agentLifecycle } from './lib/agent-lifecycle.mjs';
|
|
28
|
+
import { copilotUsage } from './lib/copilot-usage.mjs';
|
|
29
|
+
import { draftIssue } from './lib/feedback.mjs';
|
|
30
|
+
import { pinVersions, behindPins, pinTool, nodeRange, npmSpec } from './lib/pins.mjs';
|
|
31
|
+
import { findNvm, resolveToolNodes, nvmLatest, nvmInstallArgv, nvmEnv, toolEnv } from './lib/node-runtime.mjs';
|
|
32
|
+
import { leanUpdateCommands, coordinateCommands, leanMigrateCommands } from './lib/lean-update.mjs';
|
|
33
|
+
import { canUseMenus, menuPrompter, menuProgress } from './lib/ui.mjs';
|
|
34
|
+
import { CATEGORIES, preset, onOff, fromPrivacy, privacyOf, childEnv, shareProxy, proxyReport } from './lib/network.mjs';
|
|
35
|
+
import { unverifiedItems, notesFile } from './lib/unverified.mjs';
|
|
36
|
+
import { detectTerminals, parseTerminal, terminalCommands, terminalPrivacyNotes, orcaEnvSet, gitBashActions, stillNeeded, shellNotice } from './lib/terminals.mjs';
|
|
37
|
+
|
|
38
|
+
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
|
|
39
|
+
const ADAPTERS = { claude: claudeAdapter, 'opencode-v1': opencodeV1Adapter, 'opencode-v2': opencodeV2Adapter, 'copilot-cli': copilotAdapter, antigravity: antigravityAdapter };
|
|
40
|
+
// Agents whose models do not depend on --profile.
|
|
41
|
+
const FIXED_PROFILE = { claude: 'claude-subscription', 'copilot-cli': 'github-copilot', antigravity: 'antigravity' };
|
|
42
|
+
Object.assign(ADAPTERS, { 'vscode-copilot': vscodeCopilotAdapter, cursor: cursorAdapter });
|
|
43
|
+
FIXED_PROFILE['vscode-copilot'] = 'github-copilot';
|
|
44
|
+
// Extensions cannot be installed silently without admin policy, so the user installs it.
|
|
45
|
+
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';
|
|
46
|
+
const MINIMAL_TOOLS = ['rtk', 'context-mode'];
|
|
47
|
+
const OPTIONAL_TOOLS = ['serena', 'playwright', 'ponytail', 'caveman', 'i-have-adhd', 'dcp', 'codeburn', 'copilot-usage'];
|
|
48
|
+
// Asked for one by one and never part of --all-tools.
|
|
49
|
+
const OPT_IN_TOOLS = ['gsd', 'autoskills', 'playwright-extension', 'coordinate', 'lean-migrate'];
|
|
50
|
+
const TOOL_INFO = {
|
|
51
|
+
serena: 'Serena MCP: symbol-level code navigation, so agents read less code',
|
|
52
|
+
playwright: 'Playwright MCP: lets agents drive a browser to check web UIs',
|
|
53
|
+
'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',
|
|
54
|
+
ponytail: 'Ponytail: code-quality guidance injected each turn (lite mode recommended)',
|
|
55
|
+
caveman: 'Caveman skills: extra-compressed answers when you ask for them',
|
|
56
|
+
'i-have-adhd': 'i-have-adhd: skimmable, action-first formatting for every answer',
|
|
57
|
+
dcp: 'DCP: prunes old context on OpenCode 1.x (AGPL-3.0)',
|
|
58
|
+
codeburn: 'Codeburn: usage and cost report across agents, run with npx',
|
|
59
|
+
'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)',
|
|
60
|
+
gsd: 'GSD Core: spec-driven workflow skills and agents (large install)',
|
|
61
|
+
'lean-migrate': 'lean-migrate skill: guides the OpenCode 1.x to 2.x upgrade through --upgrade-agent opencode (dry run first)',
|
|
62
|
+
coordinate: 'Coordinate skill: playbook, session prompt and watcher to run several agents in separate git worktrees',
|
|
63
|
+
autoskills: 'AutoSkills: picks skills per project, run with npx (CC BY-NC 4.0: non-commercial use only)',
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
// Read before isolate() points HOME at --home.
|
|
67
|
+
const REAL_HOME = os.homedir();
|
|
68
|
+
|
|
69
|
+
function parseArgs(argv) {
|
|
70
|
+
const o = {
|
|
71
|
+
command: 'install', dryRun: false, yes: false, agents: null, tools: null, privacy: null, profile: null,
|
|
72
|
+
lang: null, home: os.homedir(), exec: true, adhdAlways: null, ponytailMode: null, shell: null,
|
|
73
|
+
networkPreset: null, networkFlags: {}, gh: null, bun: null, terminals: null, app: true, core: true,
|
|
74
|
+
};
|
|
75
|
+
const list = (v) => v.split(',').map((s) => s.trim()).filter(Boolean);
|
|
76
|
+
for (let i = 0; i < argv.length; i++) {
|
|
77
|
+
const a = argv[i];
|
|
78
|
+
const next = () => argv[++i];
|
|
79
|
+
switch (a) {
|
|
80
|
+
case '--dry-run': o.dryRun = true; break;
|
|
81
|
+
case '--yes': case '-y': o.yes = true; break;
|
|
82
|
+
case '--agents': o.agents = list(next()); break;
|
|
83
|
+
case '--tools': o.tools = [...new Set([...MINIMAL_TOOLS, ...list(next())])]; break;
|
|
84
|
+
case '--all-tools': o.tools = [...MINIMAL_TOOLS, ...OPTIONAL_TOOLS]; break;
|
|
85
|
+
case '--no-tools': o.tools = []; break;
|
|
86
|
+
case '--no-core': o.core = false; break;
|
|
87
|
+
case '--terminal': o.terminals = parseTerminal(next()); break;
|
|
88
|
+
case '--bun': o.bun = true; break;
|
|
89
|
+
case '--no-bun': o.bun = false; break;
|
|
90
|
+
case '--no-app': o.app = false; break;
|
|
91
|
+
case '--privacy': o.privacy = next(); fromPrivacy(o.privacy); break;
|
|
92
|
+
case '--gh': o.gh = true; break;
|
|
93
|
+
case '--no-gh': o.gh = false; break;
|
|
94
|
+
case '--json': o.json = true; break;
|
|
95
|
+
case '--feedback-draft': o.command = 'feedback'; break;
|
|
96
|
+
case '--failed-command': o.failedCommand = next(); break;
|
|
97
|
+
case '--feedback-kind': o.feedbackKind = next(); break;
|
|
98
|
+
case '--network': o.networkPreset = onOff(a, next()); break;
|
|
99
|
+
case '--telemetry': o.networkFlags.telemetry = onOff(a, next()); break;
|
|
100
|
+
case '--auto-update': o.networkFlags.autoUpdate = onOff(a, next()); break;
|
|
101
|
+
case '--outbound': o.networkFlags.outbound = onOff(a, next()); break;
|
|
102
|
+
case '--profile': o.profile = next(); break;
|
|
103
|
+
case '--lang': o.lang = next(); break;
|
|
104
|
+
case '--home': o.home = path.resolve(next()); break;
|
|
105
|
+
// realpath: the state dir is keyed by this path, and /var and /private/var are one folder on macOS.
|
|
106
|
+
case '--project': o.project = fs.realpathSync(path.resolve(next())); break;
|
|
107
|
+
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;
|
|
108
|
+
case '--no-exec': o.exec = false; break;
|
|
109
|
+
case '--shell': o.shell = next(); if (!['default', 'git-bash'].includes(o.shell)) throw new Error('--shell takes default or git-bash'); break;
|
|
110
|
+
case '--adhd-always': o.adhdAlways = true; break;
|
|
111
|
+
case '--ponytail-mode': o.ponytailMode = next(); break;
|
|
112
|
+
case '--update': o.command = 'update'; break;
|
|
113
|
+
case '--uninstall': o.command = 'uninstall'; break;
|
|
114
|
+
case '--doctor': o.command = 'doctor'; break;
|
|
115
|
+
case '--adopt': o.command = 'adopt'; break;
|
|
116
|
+
case '--upgrade-agent': o.command = 'upgrade-agent'; o.upgradeAgent = next(); if (o.upgradeAgent !== 'opencode') throw new Error('--upgrade-agent takes opencode'); break;
|
|
117
|
+
case '--undo': o.undo = true; break;
|
|
118
|
+
case '--keep-backup': o.keepBackup = true; break;
|
|
119
|
+
case '--confirm-removals': o.confirmRemovals = true; break;
|
|
120
|
+
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)`); break;
|
|
121
|
+
case '--usage': o.command = 'usage'; break;
|
|
122
|
+
case '--skip-agents': case '--no-admin': break; // defaults in v1: agents are never installed, nothing needs admin
|
|
123
|
+
case '--help': case '-h': o.command = 'help'; break;
|
|
124
|
+
case '--version': o.command = 'version'; break;
|
|
125
|
+
default: throw new Error(`unknown option ${a} (see --help)`);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (!o.core && o.tools) o.tools = o.tools.filter((t) => !MINIMAL_TOOLS.includes(t));
|
|
129
|
+
return o;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const HELP = `Usage: lean-agents [options]
|
|
133
|
+
|
|
134
|
+
--dry-run Show every file change and command; change nothing
|
|
135
|
+
--yes Accept defaults without asking
|
|
136
|
+
--agents a,b ${Object.keys(ADAPTERS).join(', ')}
|
|
137
|
+
(default: the ones installed)
|
|
138
|
+
--tools a,b Optional tools on top of rtk and context-mode:
|
|
139
|
+
${[...OPTIONAL_TOOLS, ...OPT_IN_TOOLS].join(', ')}
|
|
140
|
+
--all-tools / --no-tools (--all-tools leaves out ${OPT_IN_TOOLS.join(', ')})
|
|
141
|
+
--no-core Leave out ${MINIMAL_TOOLS.join(' and ')}; install only the --tools you list
|
|
142
|
+
--privacy standard|strict Same as --network on / --network off
|
|
143
|
+
--network on|off Preset for telemetry, auto-updates and other outbound calls
|
|
144
|
+
--telemetry on|off, --auto-update on|off, --outbound on|off
|
|
145
|
+
One category; overrides the preset
|
|
146
|
+
--profile <name> Model profile for OpenCode (see profiles/)
|
|
147
|
+
--lang en|es Language for rules and replies
|
|
148
|
+
--terminal warp|orca|both|none
|
|
149
|
+
Agent integrations for a terminal you already have (default: the detected ones;
|
|
150
|
+
ignored with --project)
|
|
151
|
+
--gh / --no-gh Install GitHub CLI (gh) if it is missing (default: on; you run gh auth login yourself)
|
|
152
|
+
--feedback-draft After a failed install: read the error on stdin, print a redacted issue draft as JSON
|
|
153
|
+
(--feedback-kind update: the text is a finding from an update, not an error)
|
|
154
|
+
({"offer":false} when the network preset forbids it). Needs --failed-command <text>;
|
|
155
|
+
pass --network on|off when nothing is installed yet. Files nothing.
|
|
156
|
+
--json With --dry-run or --doctor: print one JSON object on stdout (messages go to stderr)
|
|
157
|
+
--no-app Do not install the Antigravity app (the CLI is still installed when missing)
|
|
158
|
+
--bun / --no-bun Install Bun for Context Mode (default: on; faster JS, TypeScript)
|
|
159
|
+
--project <dir> Write the shared team files into one repository
|
|
160
|
+
(AGENTS.md, .github/, .vscode/mcp.json, .cursor/)
|
|
161
|
+
--migrate <from|auto> Copy rules, agents, skills, prompts and MCP servers from another harness
|
|
162
|
+
(${MIGRATE_SOURCES.join(', ')}) to --agents. With --project, from and to the repository.
|
|
163
|
+
Never moves or overwrites; MCP env and header values are not copied; hooks are only listed
|
|
164
|
+
--adhd-always Turn on i-have-adhd for every answer
|
|
165
|
+
--ponytail-mode lite|full|ultra|off
|
|
166
|
+
--shell default|git-bash OpenCode on Windows: set its shell to Git Bash when found (default: git-bash;
|
|
167
|
+
never overwrites a shell you set yourself; "default" opts out)
|
|
168
|
+
--update Re-apply with your saved choices
|
|
169
|
+
--uninstall Undo everything lean-agents changed
|
|
170
|
+
--doctor Check the install
|
|
171
|
+
--adopt List what a hand-built machine already has (MCPs, hooks, plugins, skills, npm copies),
|
|
172
|
+
classify each (managed, user, stale, duplicate, drift, wrong-node) and print the planned
|
|
173
|
+
actions; changes nothing (with --json: one JSON object). Always pass --home to try it
|
|
174
|
+
--adopt --yes Apply it: back up, re-register managed MCPs on one Node, verify, undo by itself on a failure
|
|
175
|
+
--confirm-removals With --adopt --yes and no terminal: also remove old npm copies, a duplicate skill folder and
|
|
176
|
+
hand-made stopgaps (all backed up; on a terminal a menu asks instead)
|
|
177
|
+
--keep-backup Keep the backup after a verified --adopt --yes (--adopt --undo needs it to restore bytes)
|
|
178
|
+
--upgrade-agent opencode Dry run: classify the OpenCode 1.x config as managed, translatable to 2.x or manual and print the
|
|
179
|
+
translation table; changes nothing (with --json: one JSON object). Apply and --undo come later
|
|
180
|
+
--undo With --adopt: restore what the last --adopt --yes changed
|
|
181
|
+
--install-agent a,b / --uninstall-agent a,b
|
|
182
|
+
Install (claude, opencode-v2, copilot-cli, cursor, antigravity) or remove the agent CLIs
|
|
183
|
+
lean-agents itself installed; plan first, --yes to run. Never OpenCode 1.x
|
|
184
|
+
--version Print the lean-agents version
|
|
185
|
+
--usage Print the Copilot credits left (one gh call, no model request)
|
|
186
|
+
`;
|
|
187
|
+
|
|
188
|
+
async function prompter(yes) {
|
|
189
|
+
if (yes) return { ask: async (_q, def) => def, select: async ({ def }) => def, multi: async ({ defaults }) => defaults, close() {} };
|
|
190
|
+
let input = process.stdin;
|
|
191
|
+
if (!process.stdin.isTTY) {
|
|
192
|
+
// openSync reports a missing /dev/tty here, not later as a crash. A tty.ReadStream, unlike
|
|
193
|
+
// an fs stream, can close while a read is pending, so the process can exit.
|
|
194
|
+
try { input = new tty.ReadStream(fs.openSync(process.platform === 'win32' ? 'CONIN$' : '/dev/tty', 'r')); } catch { /* keep stdin */ }
|
|
195
|
+
}
|
|
196
|
+
if (canUseMenus(input)) return menuPrompter(input);
|
|
197
|
+
const rl = readline.createInterface({ input, output: process.stdout });
|
|
198
|
+
// Never fall back to the default answer here: nobody approved these changes.
|
|
199
|
+
const noInput = () => new Error('no terminal to ask on: pass --yes to accept the defaults, or --dry-run with --agents and --tools to preview');
|
|
200
|
+
let closed = false;
|
|
201
|
+
let fail = null;
|
|
202
|
+
rl.once('close', () => { closed = true; fail?.(noInput()); });
|
|
203
|
+
const ask = (q, def) => new Promise((res, rej) => {
|
|
204
|
+
if (closed) return rej(noInput());
|
|
205
|
+
fail = rej;
|
|
206
|
+
rl.question(`${q} [${def}] `, (a) => res(a.trim() || def));
|
|
207
|
+
});
|
|
208
|
+
return {
|
|
209
|
+
tty: Boolean(input.isTTY),
|
|
210
|
+
ask,
|
|
211
|
+
// Menus fall back to the same text questions as before.
|
|
212
|
+
select: ({ ask: q, def }) => ask(q, def),
|
|
213
|
+
multi: async ({ items, defaults }) => {
|
|
214
|
+
const picked = [];
|
|
215
|
+
for (const it of items) if (yesNo(await ask(it.ask, defaults.includes(it.value) ? 'y' : 'n'))) picked.push(it.value);
|
|
216
|
+
return picked;
|
|
217
|
+
},
|
|
218
|
+
close: () => { fail = null; rl.close(); if (input !== process.stdin) input.destroy(); },
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
const yesNo = (a) => /^(y|yes|s|si|sí)$/i.test(a);
|
|
222
|
+
|
|
223
|
+
// --project keeps its own state, so a repo install and a user install never mix.
|
|
224
|
+
let project = null;
|
|
225
|
+
function stateDir(home) {
|
|
226
|
+
if (project) return projectStateDir(home, project);
|
|
227
|
+
return path.join(home, '.config', 'lean-agents');
|
|
228
|
+
}
|
|
229
|
+
// Where the engine may write: home, the project, and the config dirs envDir() accepts.
|
|
230
|
+
const writeRoots = (o) => [o.home, o.project, configHome(o.home), envDir(o.home, 'COPILOT_HOME', null)].filter(Boolean);
|
|
231
|
+
function readState(home) {
|
|
232
|
+
const f = path.join(stateDir(home), 'state.json');
|
|
233
|
+
return fs.existsSync(f) ? JSON.parse(fs.readFileSync(f, 'utf8')) : null;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// LEAN_AGENTS_NODE fakes the Node version, so tests do not depend on the host.
|
|
237
|
+
const NODE_VERSION = process.env.LEAN_AGENTS_NODE ?? process.versions.node;
|
|
238
|
+
// [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).
|
|
239
|
+
const NODE_TOOLS = [['context-mode', 'context-mode'], ['gsd', 'gsd-core']];
|
|
240
|
+
|
|
241
|
+
// Migration copies files only: no tools, terminals, network or model questions.
|
|
242
|
+
async function chooseMigration(o, p) {
|
|
243
|
+
if (!o.agents) {
|
|
244
|
+
// Antigravity has no project scope: never auto-pick it for --project.
|
|
245
|
+
const found = Object.keys(detectAgents()).filter((a) => MIGRATE_TARGETS.includes(a) && !(o.project && a === 'antigravity'));
|
|
246
|
+
if (!found.length) throw new Error('no target agent found on PATH: pass --agents');
|
|
247
|
+
o.agents = found;
|
|
248
|
+
}
|
|
249
|
+
for (const a of o.agents) if (!MIGRATE_TARGETS.includes(a)) throw new Error(`cannot migrate to "${a}" (available: ${MIGRATE_TARGETS.join(', ')})`);
|
|
250
|
+
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');
|
|
251
|
+
Object.assign(o, { tools: [], terminals: [], network: preset('on'), privacy: 'standard', unverified: {}, notes: [], gh: false, bun: false, lang: 'en', profile: null });
|
|
252
|
+
return p;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
async function choose(o, saved) {
|
|
256
|
+
const p = await prompter(o.yes);
|
|
257
|
+
if (o.migrate) return chooseMigration(o, p);
|
|
258
|
+
if (!o.agents) {
|
|
259
|
+
o.agents = saved?.agents ?? [];
|
|
260
|
+
if (!saved) {
|
|
261
|
+
const detected = detectAgents();
|
|
262
|
+
const supported = Object.keys(detected).filter((a) => ADAPTERS[a]);
|
|
263
|
+
if (!supported.length) console.log('No supported agent found on PATH (claude, opencode, copilot, agy). Use --agents to configure anyway.');
|
|
264
|
+
const items = supported.map((a) => ({ value: a, label: `${a} ${detected[a]}`, ask: `Configure ${a} ${detected[a]}?` }));
|
|
265
|
+
if (items.length) o.agents.push(...await p.multi({ message: 'Agents to configure (space to toggle, enter to confirm)', items, defaults: supported }));
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
for (const a of o.agents) if (!ADAPTERS[a]) throw new Error(`agent "${a}" is not supported yet (available: ${Object.keys(ADAPTERS).join(', ')})`);
|
|
269
|
+
if (o.agents.includes('opencode-v1') && o.agents.includes('opencode-v2')) {
|
|
270
|
+
throw new Error('opencode-v1 and opencode-v2 write the same config files: pick one');
|
|
271
|
+
}
|
|
272
|
+
if (!o.tools) {
|
|
273
|
+
o.tools = saved?.tools ?? (o.core ? [...MINIMAL_TOOLS] : []);
|
|
274
|
+
if (!saved) {
|
|
275
|
+
const offered = [...OPTIONAL_TOOLS, ...OPT_IN_TOOLS].filter((t) => t !== 'dcp' || o.agents.includes('opencode-v1'));
|
|
276
|
+
const items = offered.map((t) => ({ value: t, label: t, hint: TOOL_INFO[t].replace(/^[^:]+: /, ''), ask: `Add ${TOOL_INFO[t]}?` }));
|
|
277
|
+
const message = o.core ? `Optional tools (${MINIMAL_TOOLS.join(' and ')} are always included)` : 'Tools (--no-core: nothing else is added)';
|
|
278
|
+
o.tools.push(...await p.multi({ message, items, defaults: [] }));
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
if (!o.core) o.tools = o.tools.filter((t) => !MINIMAL_TOOLS.includes(t));
|
|
282
|
+
const known = [...MINIMAL_TOOLS, ...OPTIONAL_TOOLS, ...OPT_IN_TOOLS];
|
|
283
|
+
const unknown = o.tools.filter((t) => !known.includes(t));
|
|
284
|
+
if (unknown.length) throw new Error(`unknown tools: ${unknown.join(', ')} (available: ${known.join(', ')})`);
|
|
285
|
+
if (!o.agents.includes('opencode-v1')) o.tools = o.tools.filter((t) => t !== 'dcp');
|
|
286
|
+
// The saved choice keeps Context Mode, so --update installs it once Node is new enough.
|
|
287
|
+
o.chosenTools = o.tools;
|
|
288
|
+
// Tools whose Node range the active Node fails run on an nvm Node of their own, or are skipped with one line.
|
|
289
|
+
const needs = Object.fromEntries(NODE_TOOLS.filter(([tool]) => o.tools.includes(tool)).map(([tool, pin]) => [tool, { node: nodeRange(pin) }]));
|
|
290
|
+
const nvm = findNvm({ env: process.env, home: o.home, platform: process.platform, realHome: REAL_HOME });
|
|
291
|
+
o.nvm = nvm;
|
|
292
|
+
const resolved = resolveToolNodes({ pins: needs, active: NODE_VERSION, nvm, latest: (major) => nvmLatest(nvm, major, { run: quiet }) });
|
|
293
|
+
for (const s of resolved.skipped) console.log(s.line);
|
|
294
|
+
o.tools = o.tools.filter((t) => !resolved.skipped.some((s) => s.tool === t));
|
|
295
|
+
o.toolNode = resolved.toolNode && { ...resolved.toolNode, nvmDir: nvm.dir };
|
|
296
|
+
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.');
|
|
297
|
+
if (o.project) o.terminals = [];
|
|
298
|
+
else if (!o.terminals) {
|
|
299
|
+
// Terminals are never installed, only detected; nothing found means no question.
|
|
300
|
+
const found = detectTerminals(o.home, { system: o.home === REAL_HOME });
|
|
301
|
+
o.terminals = saved ? saved.terminals ?? [] : found;
|
|
302
|
+
if (!saved && found.length) {
|
|
303
|
+
const items = found.map((t) => ({ value: t, label: t, ask: `Add the ${t} agent integration?` }));
|
|
304
|
+
o.terminals = await p.multi({ message: 'Terminals found: add their agent integrations', items, defaults: found });
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
await chooseNetwork(o, saved, p);
|
|
308
|
+
if (o.network.outbound === 'off' && o.tools.includes('copilot-usage')) {
|
|
309
|
+
console.log('copilot-usage skipped: it calls api.github.com, which --outbound off blocks.');
|
|
310
|
+
o.tools = o.tools.filter((t) => t !== 'copilot-usage');
|
|
311
|
+
}
|
|
312
|
+
await chooseUnverified(o, saved, p);
|
|
313
|
+
o.gh ??= saved?.gh ?? (!which('gh') && yesNo(await p.ask('Install GitHub CLI (gh)? You log in yourself afterwards', 'y')));
|
|
314
|
+
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.');
|
|
315
|
+
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')));
|
|
316
|
+
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' }));
|
|
317
|
+
if (o.agents.some((a) => a.startsWith('opencode')) && !o.profile) {
|
|
318
|
+
const profiles = ['github-copilot', 'vertex-gemini', 'anthropic-api', 'opencode-go', 'openai-api', 'none'];
|
|
319
|
+
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' }));
|
|
320
|
+
}
|
|
321
|
+
if (o.profile === 'none') o.profile = null;
|
|
322
|
+
if (o.tools.includes('i-have-adhd')) o.adhdAlways ??= saved?.adhdAlways ?? yesNo(await p.ask('Use i-have-adhd on every answer?', 'y'));
|
|
323
|
+
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' }));
|
|
324
|
+
// On by default, never asked: --shell default opts out.
|
|
325
|
+
o.shell ??= saved?.shell ?? 'git-bash';
|
|
326
|
+
return p;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
const NETWORK_INFO = { telemetry: 'telemetry and error reports', autoUpdate: 'auto-updates', outbound: 'other outbound calls (session sharing, feedback, built-in providers)' };
|
|
330
|
+
|
|
331
|
+
async function chooseNetwork(o, saved, p) {
|
|
332
|
+
let base = o.networkPreset ? preset(o.networkPreset) : fromPrivacy(o.privacy) ?? saved?.network ?? fromPrivacy(saved?.privacy);
|
|
333
|
+
if (!base && !Object.keys(o.networkFlags).length) {
|
|
334
|
+
const a = await p.select({
|
|
335
|
+
ask: 'Network: off (enterprise PC: no telemetry, auto-updates or sharing), on (personal PC), or choose per category?',
|
|
336
|
+
message: 'Telemetry, auto-updates and other outbound calls',
|
|
337
|
+
options: [
|
|
338
|
+
{ value: 'off', label: 'All off', hint: 'enterprise PC' },
|
|
339
|
+
{ value: 'on', label: 'All on', hint: 'personal PC, nothing changes' },
|
|
340
|
+
{ value: 'choose', label: 'Choose per category' },
|
|
341
|
+
],
|
|
342
|
+
def: 'on',
|
|
343
|
+
});
|
|
344
|
+
if (a === 'off' || a === 'on') base = preset(a);
|
|
345
|
+
else if (a === 'choose') {
|
|
346
|
+
base = {};
|
|
347
|
+
for (const c of CATEGORIES) base[c] = yesNo(await p.ask(`Keep ${NETWORK_INFO[c]} on?`, 'y')) ? 'on' : 'off';
|
|
348
|
+
} else throw new Error(`network takes off, on or choose, not "${a}"`);
|
|
349
|
+
}
|
|
350
|
+
o.network = { ...(base ?? preset('on')), ...o.networkFlags };
|
|
351
|
+
o.privacy = privacyOf(o.network);
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
async function chooseUnverified(o, saved, p) {
|
|
355
|
+
o.unverified = { ...saved?.unverified };
|
|
356
|
+
o.notes = [];
|
|
357
|
+
for (const item of unverifiedItems(o, o.home, { stateFiles: readState(o.home)?.files ?? [] })) {
|
|
358
|
+
if (item.kept) { o.unverified[item.id] = 'kept'; continue; }
|
|
359
|
+
if (o.unverified[item.id] && o.unverified[item.id] !== 'kept') continue;
|
|
360
|
+
// --yes, pipes and no terminal keep the default: pasting is interactive only.
|
|
361
|
+
if (!p.menus && !p.tty) { o.unverified[item.id] = 'default'; continue; }
|
|
362
|
+
const a = await p.select({
|
|
363
|
+
ask: `${item.label} is not documented upstream. Paste your docs or IT notes (paste), or keep the tool's default (default)?`,
|
|
364
|
+
message: `${item.label}: not documented upstream`,
|
|
365
|
+
options: [
|
|
366
|
+
{ value: 'default', label: "Keep the tool's default" },
|
|
367
|
+
{ value: 'paste', label: 'Paste docs or IT notes', hint: 'saved for your agent to apply after review' },
|
|
368
|
+
],
|
|
369
|
+
def: 'default',
|
|
370
|
+
});
|
|
371
|
+
const pick = { p: 'paste', d: 'default' }[a.trim().toLowerCase()[0]];
|
|
372
|
+
if (!pick) throw new Error(`answer paste or default, not "${a}"`);
|
|
373
|
+
const answer = pick === 'paste' ? (await p.ask('One line of notes, or a path to a file with them (no passwords)', '')).trim() : '';
|
|
374
|
+
o.unverified[item.id] = answer ? 'notes' : 'default';
|
|
375
|
+
if (answer) o.notes.push(notesFile(o.home, item, answer));
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
function migrationPlan(o) {
|
|
380
|
+
const scope = o.project ? 'project' : 'user';
|
|
381
|
+
const base = o.project ?? o.home;
|
|
382
|
+
const names = o.migrate === 'auto' ? detectSources(base, scope, o.agents) : [o.migrate];
|
|
383
|
+
const r = migratePlan({ sources: names.map((n) => readSource(n, base, scope)), targets: o.agents, base, scope, stateDir: stateDir(o.home) });
|
|
384
|
+
const planned = plan(r.actions, writeRoots(o));
|
|
385
|
+
return { planned, commands: r.commands, migration: { ...r, rows: finishRows(r.rows, planned, o.exec), base, names } };
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
function buildPlan(o) {
|
|
389
|
+
if (o.migrate) return migrationPlan(o);
|
|
390
|
+
if (o.project) {
|
|
391
|
+
const r = projectPlan(ROOT, o.project, o);
|
|
392
|
+
return { planned: plan(r.actions, writeRoots(o), readState(o.home)?.files), commands: r.commands };
|
|
393
|
+
}
|
|
394
|
+
o.prior = readState(o.home)?.commands ?? [];
|
|
395
|
+
const core = useToolNode(loadCore(ROOT), o.toolNode, o.nvm);
|
|
396
|
+
const rulesPath = path.join(stateDir(o.home), 'AGENTS.md');
|
|
397
|
+
const rules = renderRules(ROOT, o);
|
|
398
|
+
const actions = [{ kind: 'file', path: rulesPath, content: rules }, ...o.notes];
|
|
399
|
+
const commands = [];
|
|
400
|
+
for (const agent of o.agents) {
|
|
401
|
+
const profile = loadProfile(ROOT, FIXED_PROFILE[agent] ?? o.profile);
|
|
402
|
+
const r = ADAPTERS[agent]({ home: o.home, core, profile, opts: o, rules, adhdCommand: adhdCommand(o.home), rulesPath: rulesPath.split(path.sep).join('/') });
|
|
403
|
+
actions.push(...r.actions);
|
|
404
|
+
commands.push(...r.commands.map((c) => ({ ...c, agent })));
|
|
405
|
+
}
|
|
406
|
+
commands.push(...leanUpdateCommands(o.agents));
|
|
407
|
+
if (o.tools.includes('coordinate')) commands.push(...coordinateCommands(o.agents));
|
|
408
|
+
if (o.tools.includes('lean-migrate')) commands.push(...leanMigrateCommands(o.agents));
|
|
409
|
+
commands.push(...terminalCommands({ terminals: o.terminals, agents: o.agents, network: o.network, system: o.home === REAL_HOME }));
|
|
410
|
+
actions.push(...gitBashActions({ home: o.home, terminals: o.terminals, agents: o.agents }));
|
|
411
|
+
if (o.tools.includes('gsd')) {
|
|
412
|
+
const r = gsdPlan(ROOT, o.home, o);
|
|
413
|
+
actions.push(...r.actions);
|
|
414
|
+
commands.push(...r.commands);
|
|
415
|
+
}
|
|
416
|
+
if (o.bun && o.network.telemetry === 'off') {
|
|
417
|
+
actions.push({ kind: 'block', toml: true, path: path.join(o.home, '.bunfig.toml'), body: 'telemetry = false' });
|
|
418
|
+
}
|
|
419
|
+
return { planned: plan(actions, writeRoots(o), readState(o.home)?.files), commands };
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
// `behind`: tools whose pinned version is newer than the installed one (--update); their installs run even when the binary is there.
|
|
423
|
+
function prereqCommands(o, behind = new Set()) {
|
|
424
|
+
const pm = packageManager();
|
|
425
|
+
const out = [];
|
|
426
|
+
const tn = o.toolNode;
|
|
427
|
+
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) });
|
|
428
|
+
for (const t of [...o.tools, ...(o.gh ? ['gh'] : [])]) {
|
|
429
|
+
if (t === 'context-mode' && tn) {
|
|
430
|
+
const prefix = ['--prefix', tn.dir];
|
|
431
|
+
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) });
|
|
432
|
+
continue;
|
|
433
|
+
}
|
|
434
|
+
const p = prereqFor(t, pm);
|
|
435
|
+
if (!p || (which(p.bin) && !behind.has(t))) continue;
|
|
436
|
+
if (p.install) out.push({ tool: t, desc: `install ${p.bin}`, run: p.install, undo: [], optional: t === 'gh' });
|
|
437
|
+
else out.push({ tool: t, desc: `${p.bin} is missing: install it from ${p.manual}`, run: [], undo: [], manual: true, optional: t === 'gh' });
|
|
438
|
+
}
|
|
439
|
+
if (o.agents.includes('antigravity')) {
|
|
440
|
+
for (const c of antigravityPrereqs(pm, process.platform, o.home, o.app)) {
|
|
441
|
+
if (c.note) console.log(c.desc);
|
|
442
|
+
else out.push({ tool: 'antigravity', undo: [], ...c });
|
|
443
|
+
}
|
|
444
|
+
}
|
|
445
|
+
if (o.bun && o.tools.includes('context-mode') && process.platform !== 'linux' && !which('bun') && bunPresent(o.home)) {
|
|
446
|
+
console.log('! Bun is in ~/.bun/bin but not on PATH; Context Mode needs it on PATH here. Add that folder to PATH.');
|
|
447
|
+
}
|
|
448
|
+
if (o.bun && o.tools.includes('context-mode') && !bunPresent(o.home)) {
|
|
449
|
+
const b = bunInstall(o.home, stateDir(o.home), process.platform, pm);
|
|
450
|
+
if (b) out.push(b);
|
|
451
|
+
else console.log('! Bun needs Homebrew here: install it from https://bun.com/docs/installation. Context Mode will run on Node.');
|
|
452
|
+
}
|
|
453
|
+
return out;
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
function printMigration(o, m, commands) {
|
|
457
|
+
const rel = (p) => (p.startsWith(o.home) ? `~${p.slice(o.home.length)}` : p.startsWith(m.base) ? `.${p.slice(m.base.length)}` : p);
|
|
458
|
+
console.log(`\nlean-agents migration: ${m.names.join(', ')} -> ${o.agents.join(', ')}${o.project ? ` (project ${o.project})` : ''}`);
|
|
459
|
+
console.log(formatTable(m.rows, rel));
|
|
460
|
+
if (m.env.length) console.log(`\nSet these env vars before you start your agents (values are never copied): ${m.env.join(', ')}`);
|
|
461
|
+
if (m.headers.length) console.log(`Add these MCP headers by hand: ${m.headers.join('; ')}`);
|
|
462
|
+
if (commands.some((c) => c.run.length)) console.log('\nCommands:');
|
|
463
|
+
for (const c of commands) for (const argv of c.run) console.log(` $ ${argv.join(' ')}`);
|
|
464
|
+
console.log('');
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
// Agents parse this instead of scraping the text plan. Paths use ~ so no home directory leaks.
|
|
468
|
+
function printJson(o, planned, commands, migration, behind) {
|
|
469
|
+
const rel = (t) => (t.startsWith(o.home + path.sep) || t === o.home ? `~${t.slice(o.home.length)}` : t);
|
|
470
|
+
const inText = (t) => t.split(o.home).join('~');
|
|
471
|
+
const plan = {
|
|
472
|
+
agents: o.agents, tools: o.tools, privacy: o.privacy, lang: o.lang, profile: o.profile ?? null, terminals: o.terminals,
|
|
473
|
+
gh: !!o.gh, bun: !!o.bun, network: o.network, migrate: migration ? migration.names : null,
|
|
474
|
+
files: planned.map((f) => ({ status: f.status, path: rel(f.path), note: f.note ?? null })),
|
|
475
|
+
commands: commands.map((c) => ({ desc: inText(c.desc), agent: c.agent ?? null, run: c.run.map((a) => a.map(inText)) })),
|
|
476
|
+
...(behind && { behind }),
|
|
477
|
+
};
|
|
478
|
+
process.stdout.write(`${JSON.stringify(plan, null, 2)}\n`);
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
function printPlan(o, planned, commands) {
|
|
482
|
+
console.log(`\nlean-agents plan for ${o.agents.join(', ') || 'no agents'}`);
|
|
483
|
+
if (o.project) console.log(` project: ${o.project}`);
|
|
484
|
+
console.log(` tools: ${o.tools.join(', ') || 'none'} | privacy: ${o.privacy} | lang: ${o.lang} | profile: ${o.profile ?? 'none'}`);
|
|
485
|
+
if (o.terminals.length) console.log(` terminals: ${o.terminals.join(', ')}`);
|
|
486
|
+
if (o.network.telemetry === 'off') for (const n of terminalPrivacyNotes(o.terminals, { orcaEnvSet: orcaEnvSet({ system: o.home === REAL_HOME }) })) console.log(` ${n}`);
|
|
487
|
+
if (o.tools.includes('context-mode')) console.log(` bun: ${o.bun ? `on${bunPresent(o.home) ? ' (already installed)' : ''}` : 'off'}`);
|
|
488
|
+
console.log(` network: ${CATEGORIES.map((c) => `${c} ${o.network[c]}`).join(', ')}`);
|
|
489
|
+
const net = proxyReport();
|
|
490
|
+
if (net.length) console.log(` proxy and CA (passed to every command): ${net.join(' ')}`);
|
|
491
|
+
if (o.tools.includes('playwright-extension')) console.log(` signed-in browser: ${EXTENSION_NOTE}`);
|
|
492
|
+
if (o.notes.length) console.log(` your notes for undocumented settings (saved, never applied): ${o.notes.map((n) => path.basename(n.path, '.md')).join(', ')}`);
|
|
493
|
+
console.log('');
|
|
494
|
+
console.log('Files:');
|
|
495
|
+
console.log(describe(planned, o.home));
|
|
496
|
+
if (commands.length) {
|
|
497
|
+
console.log('\nCommands:');
|
|
498
|
+
for (const c of commands) {
|
|
499
|
+
console.log(` - ${c.desc}${c.agent ? ` (${c.agent})` : ''}`);
|
|
500
|
+
for (const argv of c.run) console.log(` $ ${argv.join(' ')}`);
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
console.log('');
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
async function install(o) {
|
|
507
|
+
if (o.json && !o.yes) throw new Error('--json needs --yes: the menus would write questions to stdout');
|
|
508
|
+
const saved = o.command === 'update' ? readState(o.home) : null;
|
|
509
|
+
if (o.command === 'update' && !saved) throw new Error('nothing to update: lean-agents is not installed');
|
|
510
|
+
if (o.command === 'update' && saved.options.migrateOnly) throw new Error('nothing to update: only --migrate ran here');
|
|
511
|
+
const p = await choose(o, saved?.options);
|
|
512
|
+
const { planned, commands: agentCommands, migration } = buildPlan(o);
|
|
513
|
+
if (migration && !migration.rows.length) { p.close(); console.log('Nothing to migrate: no rules, agents, skills, prompts, MCP servers or hooks found.'); return; }
|
|
514
|
+
const behind = new Set((saved ? behindPins(saved) : []).map((b) => pinTool(b.tool)));
|
|
515
|
+
const commands = [...(o.exec ? prereqCommands(o, behind) : []), ...agentCommands];
|
|
516
|
+
const noGit = migration ? null : gitHint(packageManager());
|
|
517
|
+
if (noGit) console.log(noGit);
|
|
518
|
+
if (o.json) {
|
|
519
|
+
if (!o.dryRun) throw new Error('--json needs --dry-run (or --doctor)');
|
|
520
|
+
p.close();
|
|
521
|
+
return printJson(o, planned, commands, migration, saved ? behindPins(saved) : undefined);
|
|
522
|
+
}
|
|
523
|
+
if (migration) printMigration(o, migration, o.exec ? commands : []);
|
|
524
|
+
else printPlan(o, planned, commands);
|
|
525
|
+
if (saved && behindPins(saved).length) console.log('Pins that will change (old -> new):');
|
|
526
|
+
if (saved) for (const b of behindPins(saved)) console.log(`${b.tool}: ${b.installed} -> ${b.pinned}`);
|
|
527
|
+
if (o.dryRun) { p.close(); console.log('Dry run: nothing was changed.'); return; }
|
|
528
|
+
if (!yesNo(await p.ask('Apply these changes?', 'y'))) { p.close(); console.log('Cancelled.'); return; }
|
|
529
|
+
p.close();
|
|
530
|
+
const ui = p.menus ? await menuProgress() : null;
|
|
531
|
+
Object.assign(process.env, childEnv(o.network));
|
|
532
|
+
|
|
533
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
|
|
534
|
+
const backupDir = path.join(stateDir(o.home), 'backups', stamp);
|
|
535
|
+
const files = apply(planned, backupDir, o.home, writeRoots(o));
|
|
536
|
+
const ran = [];
|
|
537
|
+
let failed = 0;
|
|
538
|
+
if (o.exec) {
|
|
539
|
+
for (const [i, c] of commands.entries()) {
|
|
540
|
+
// gh is on by default, so having no installer for it (no brew or winget) must not fail the run.
|
|
541
|
+
if (c.manual) { console.log(`! ${c.desc}`); if (!c.optional) failed++; continue; }
|
|
542
|
+
const there = (c.skipIfExists && exists(c.skipIfExists)) || (c.skipIfOutput && quiet(c.skipIfOutput.cmd).ok);
|
|
543
|
+
if (there) {
|
|
544
|
+
if (!behind.has(c.tool)) continue;
|
|
545
|
+
// Installed at an older pin: undo it, then add it again at the new pin.
|
|
546
|
+
if (!c.undo.every((argv) => run(argv, { dryRun: false, log: console.log, env: c.env }))) {
|
|
547
|
+
console.log(` ! could not remove the old ${c.desc}; left as it is. Fix it by hand, then --update.`);
|
|
548
|
+
failed++;
|
|
549
|
+
continue;
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
if (ui) ui.step(i + 1, commands.length, c.desc);
|
|
553
|
+
else console.log(`- ${c.desc}`);
|
|
554
|
+
const ok = c.run.every((argv) => run(argv, { dryRun: false, log: console.log, env: c.env }));
|
|
555
|
+
if (ui) ui.result(ok || c.optional, c.desc);
|
|
556
|
+
else if (!ok && !c.optional) console.log(` ! failed: ${c.desc}. Run the command above by hand, then --doctor.`);
|
|
557
|
+
// An optional step (Bun) that fails only means Context Mode runs on Node; nothing to undo.
|
|
558
|
+
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.'); continue; }
|
|
559
|
+
if (!ok) failed++;
|
|
560
|
+
ran.push({ desc: c.desc, ok, undo: c.undo, ...(c.env && { env: c.env }) });
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
const previous = readState(o.home);
|
|
564
|
+
const state = {
|
|
565
|
+
version: JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version,
|
|
566
|
+
installedAt: previous?.installedAt ?? new Date().toISOString(),
|
|
567
|
+
updatedAt: new Date().toISOString(),
|
|
568
|
+
pins: pinVersions(),
|
|
569
|
+
options: o.migrate ? previous?.options ?? { migrateOnly: true, agents: o.agents, tools: [], privacy: o.privacy, network: o.network, gh: false, terminals: [], 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, gh: o.gh, terminals: o.terminals, unverified: o.unverified, lang: o.lang, profile: o.profile, adhdAlways: o.adhdAlways, ponytailMode: o.ponytailMode, bun: o.bun, shell: o.shell },
|
|
570
|
+
...(o.toolNode && { toolNode: { version: o.toolNode.version, installedByLean: !!o.toolNode.install || (previous?.toolNode?.version === o.toolNode.version && !!previous.toolNode.installedByLean) } }),
|
|
571
|
+
files: [...(previous?.files ?? []), ...files],
|
|
572
|
+
// A command that ran again replaces its earlier record, so --uninstall undoes it once.
|
|
573
|
+
commands: [...(previous?.commands ?? []).filter((c) => !ran.some((r) => r.desc === c.desc)), ...ran],
|
|
574
|
+
};
|
|
575
|
+
privateDir(stateDir(o.home), stateDir(o.home));
|
|
576
|
+
writePrivate(path.join(stateDir(o.home), 'state.json'), `${JSON.stringify(state, null, 2)}\n`);
|
|
577
|
+
if (failed) {
|
|
578
|
+
console.log(`\n${failed} step(s) failed; see the lines marked ! above. Backups: ${backupDir}`);
|
|
579
|
+
ui?.summary('Summary', [`${failed} of ${commands.length} commands failed`, `Backups: ${backupDir}`], false);
|
|
580
|
+
process.exitCode = 1;
|
|
581
|
+
return;
|
|
582
|
+
}
|
|
583
|
+
console.log(`\nDone. Backups: ${backupDir}`);
|
|
584
|
+
if (o.project) return console.log('Next: review and commit these files. Each teammate runs the installer once for the tools (rtk, context-mode, ...).');
|
|
585
|
+
console.log('Next: restart your agents, log in to your providers, then run --doctor.');
|
|
586
|
+
const shell = shellNotice();
|
|
587
|
+
if (shell) console.log(shell.text);
|
|
588
|
+
const todo = stillNeeded({ home: o.home, terminals: o.terminals, agents: o.agents });
|
|
589
|
+
if (todo.length) console.log(`Still needed from you:\n${todo.map((t) => ` - ${t.text}`).join('\n')}`);
|
|
590
|
+
if (o.tools.includes('playwright-extension')) console.log(`Signed-in browser: ${EXTENSION_NOTE}`);
|
|
591
|
+
if (o.gh) console.log('GitHub CLI: run `gh auth login` yourself; lean-agents never handles tokens.');
|
|
592
|
+
for (const n of o.notes) console.log(`Notes saved: ${n.path}. Ask your agent to apply them, showing you each change first.`);
|
|
593
|
+
if (o.network.telemetry === 'off' && o.agents.includes('claude')) {
|
|
594
|
+
console.log('Strict privacy: also turn off "Help improve Claude" in your claude.ai privacy settings.');
|
|
595
|
+
}
|
|
596
|
+
if (o.network.telemetry === 'off' && o.agents.includes('copilot-cli')) {
|
|
597
|
+
console.log('Strict privacy: Copilot CLI has no telemetry setting. Start it with --disable-client-telemetry.');
|
|
598
|
+
}
|
|
599
|
+
if (o.network.telemetry === 'off' && o.agents.includes('cursor')) {
|
|
600
|
+
console.log('Strict privacy: turn on Privacy Mode in Cursor settings. It is stored on your account.');
|
|
601
|
+
}
|
|
602
|
+
if (o.network.telemetry === 'off' && o.agents.includes('antigravity')) {
|
|
603
|
+
console.log('Strict privacy: turn off "Enable Telemetry" in Antigravity settings. It is stored on your account.');
|
|
604
|
+
}
|
|
605
|
+
if (o.network.autoUpdate === 'off' && o.agents.includes('antigravity')) {
|
|
606
|
+
console.log('Auto-updates off: Antigravity CLI updates itself and has no documented switch for it.');
|
|
607
|
+
}
|
|
608
|
+
ui?.summary('Summary', [`${files.length} files written, ${ran.length} commands run`, `Backups: ${backupDir}`], true);
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
async function uninstall(o) {
|
|
612
|
+
const state = readState(o.home);
|
|
613
|
+
if (!state) { console.log('lean-agents is not installed.'); return; }
|
|
614
|
+
const p = await prompter(o.yes);
|
|
615
|
+
console.log(`This restores ${state.files.length} files and undoes ${state.commands.length} commands.`);
|
|
616
|
+
if (o.dryRun || !yesNo(await p.ask('Uninstall?', o.yes ? 'y' : 'n'))) { p.close(); console.log('Nothing changed.'); return; }
|
|
617
|
+
p.close();
|
|
618
|
+
if (!o.exec && state.commands.length) throw new Error('--no-exec cannot undo the commands this install ran; run --uninstall without it');
|
|
619
|
+
if (o.exec) {
|
|
620
|
+
for (const c of [...state.commands].reverse()) {
|
|
621
|
+
for (const argv of c.undo ?? []) {
|
|
622
|
+
if (!run(argv, { dryRun: false, log: console.log, env: c.env })) {
|
|
623
|
+
console.log(' ! failed. Run the command above by hand.');
|
|
624
|
+
process.exitCode = 1;
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
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}\`.`);
|
|
630
|
+
const report = undo(state.files, writeRoots(o));
|
|
631
|
+
for (const [what, file] of report) console.log(` ${what.padEnd(20)} ${file}`);
|
|
632
|
+
if (report.some(([what]) => what === 'left (symlink)')) console.log(' ! Paths marked "left (symlink)" were not touched; remove our lines there by hand.');
|
|
633
|
+
fs.renameSync(path.join(stateDir(o.home), 'state.json'), path.join(stateDir(o.home), `state.uninstalled-${Date.now()}.json`));
|
|
634
|
+
// Backups are the only undo for edits we cannot revert, so they stay unless the user says yes (--yes keeps them).
|
|
635
|
+
const backups = path.join(stateDir(o.home), 'backups');
|
|
636
|
+
const q = await prompter(o.yes);
|
|
637
|
+
const drop = fs.existsSync(backups) && yesNo(await q.ask(`Delete backups in ${backups}?`, 'n'));
|
|
638
|
+
q.close();
|
|
639
|
+
if (drop) dropBackups(backups);
|
|
640
|
+
console.log(drop ? 'Uninstalled. Backups deleted.' : `Uninstalled. Backups are kept in ${backups}.`);
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
// The agent files the issue itself, and only after the user said yes; this only drafts.
|
|
644
|
+
function feedback(o) {
|
|
645
|
+
if (!o.failedCommand) throw new Error('--feedback-draft needs --failed-command <text>');
|
|
646
|
+
const state = readState(o.home);
|
|
647
|
+
const network = { ...(o.networkPreset ? preset(o.networkPreset) : fromPrivacy(o.privacy) ?? state?.options.network ?? {}), ...o.networkFlags };
|
|
648
|
+
const versions = { 'lean-agents': JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version, node: NODE_VERSION };
|
|
649
|
+
const draft = draftIssue({ network, home: [o.home, os.homedir()], versions, command: o.failedCommand, error: fs.readFileSync(0, 'utf8'), kind: o.feedbackKind });
|
|
650
|
+
process.stdout.write(`${JSON.stringify(draft ?? { offer: false })}\n`);
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
async function main() {
|
|
654
|
+
const o = parseArgs(process.argv.slice(2));
|
|
655
|
+
// A repository gets files only: tools and agents stay per user.
|
|
656
|
+
if (o.project && o.agents?.length && !o.migrate) throw new Error('--project writes repository files only: run --agents in a separate install');
|
|
657
|
+
if (o.project) { project = o.project; if (!o.migrate) { o.agents = []; o.exec = false; } }
|
|
658
|
+
// --json keeps stdout for the one JSON object; every message goes to stderr.
|
|
659
|
+
if (o.json) console.log = console.error;
|
|
660
|
+
isolate(o.home);
|
|
661
|
+
shareProxy();
|
|
662
|
+
if (o.command === 'help') return console.log(HELP);
|
|
663
|
+
if (o.command === 'version') return console.log(JSON.parse(fs.readFileSync(path.join(ROOT, 'package.json'), 'utf8')).version);
|
|
664
|
+
if (o.command === 'doctor') return process.exit(doctor({ home: o.home, state: readState(o.home), exec: o.exec, nodeVersion: NODE_VERSION, json: o.json }) ? 0 : 1);
|
|
665
|
+
if (o.command === 'upgrade-agent') {
|
|
666
|
+
if (o.undo || (o.yes && !o.dryRun)) throw new Error('--upgrade-agent opencode apply and --undo are not in this release yet; it only lists (dry run)');
|
|
667
|
+
const env = process.env;
|
|
668
|
+
const inv = await inventory({ home: o.home, env, realHome: REAL_HOME });
|
|
669
|
+
const bin = which('opencode');
|
|
670
|
+
const r = upgradeInventory(inv, { home: o.home, binary: { path: bin, version: bin && o.exec ? binVersion('opencode') : null } });
|
|
671
|
+
if (o.json) process.stdout.write(`${JSON.stringify(r, null, 2)}\n`); else console.log(formatUpgrade(r));
|
|
672
|
+
return process.exit(0);
|
|
673
|
+
}
|
|
674
|
+
if ((o.undo || o.keepBackup || o.confirmRemovals) && o.command !== 'adopt') throw new Error('--undo, --keep-backup and --confirm-removals go with --adopt');
|
|
675
|
+
if (o.command === 'adopt') {
|
|
676
|
+
// Removals outside the JSON edits need a yes: a menu on a terminal, --confirm-removals without one.
|
|
677
|
+
const tty = process.stdin.isTTY && process.stdout.isTTY && !o.json;
|
|
678
|
+
const p = o.yes && !o.confirmRemovals && tty ? await prompter(false) : null;
|
|
679
|
+
const confirm = o.confirmRemovals ? async () => true : p ? async (q) => yesNo(await p.ask(q, 'n')) : async () => false;
|
|
680
|
+
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) });
|
|
681
|
+
p?.close();
|
|
682
|
+
return process.exit(ok ? 0 : 1);
|
|
683
|
+
}
|
|
684
|
+
if (o.command === 'usage') {
|
|
685
|
+
const network = { ...(o.networkPreset ? preset(o.networkPreset) : fromPrivacy(o.privacy) ?? readState(o.home)?.options.network ?? {}), ...o.networkFlags };
|
|
686
|
+
return console.log(network.outbound === 'off' ? 'usage skipped: outbound calls are off (no request to api.github.com)' : copilotUsage());
|
|
687
|
+
}
|
|
688
|
+
if (o.command === 'agent') {
|
|
689
|
+
const p = await prompter(o.yes);
|
|
690
|
+
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 }); } finally { p.close(); }
|
|
691
|
+
}
|
|
692
|
+
if (o.command === 'feedback') return feedback(o);
|
|
693
|
+
if (o.command === 'uninstall') return uninstall(o);
|
|
694
|
+
return install(o);
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
main().catch((e) => {
|
|
698
|
+
console.error(`lean-agents: ${e.message}`);
|
|
699
|
+
process.exit(1);
|
|
700
|
+
});
|