@yasaswy.nagavolu/agents 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.
@@ -0,0 +1,328 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const { writeFileAtomic } = require('./fsutil');
6
+ const { getSecret } = require('./agentsEnv');
7
+ const { WiringError, asWiringList } = require('./wiring');
8
+
9
+ const MCP_CONFIG_FILE_NAME = '.claude.json';
10
+ const MCP_SERVERS_KEY = 'mcpServers';
11
+ // Whole-string placeholder only (e.g. "${CONTEXT7_API_KEY}") — matches the
12
+ // shared secrets contract's resolution order (agentsEnv.getSecret), never a
13
+ // partial/interpolated substring.
14
+ const PLACEHOLDER = /^\$\{([A-Z0-9_]+)\}$/;
15
+
16
+ /**
17
+ * Default MCP config path: a sibling `.claude.json` next to targetBase,
18
+ * matching the real machine convention (this CLI's default targetBase is
19
+ * `~/.claude`, and Claude Code's real MCP config is the sibling
20
+ * `~/.claude.json`) — so a scratch `--target-dir` used in tests gets an
21
+ * isolated sibling file for free, with no risk of ever touching the real one.
22
+ */
23
+ function defaultMcpConfigPath(targetBase) {
24
+ return path.join(path.dirname(targetBase), MCP_CONFIG_FILE_NAME);
25
+ }
26
+
27
+ function loadMcpConfig(configPath) {
28
+ if (!fs.existsSync(configPath)) {
29
+ return {};
30
+ }
31
+ let raw;
32
+ try {
33
+ raw = JSON.parse(fs.readFileSync(configPath, 'utf8'));
34
+ } catch (err) {
35
+ throw new WiringError(`MCP config at ${configPath} is not valid JSON: ${err.message}`);
36
+ }
37
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
38
+ throw new WiringError(`MCP config at ${configPath} must be a JSON object at its root`);
39
+ }
40
+ return raw;
41
+ }
42
+
43
+ function saveMcpConfig(configPath, config) {
44
+ writeFileAtomic(configPath, `${JSON.stringify(config, null, 2)}\n`);
45
+ }
46
+
47
+ /**
48
+ * One-time backup of the pre-existing MCP config, taken immediately before
49
+ * the FIRST write this CLI ever makes to it at this configPath — same
50
+ * contract as wiring.js's `ensureSettingsBackup`, tracked on its own ledger
51
+ * marker (`ledger.mcpBackup`) so it never collides with the settings.json
52
+ * backup marker and never re-backs-up on a later install/uninstall.
53
+ */
54
+ function ensureMcpBackup(configPath, ledger, timestamp) {
55
+ if (ledger.mcpBackup && ledger.mcpBackup.taken) {
56
+ return null;
57
+ }
58
+ let backupFile = null;
59
+ if (fs.existsSync(configPath)) {
60
+ const safeStamp = timestamp.replace(/[:.]/g, '-');
61
+ backupFile = `${configPath}.bak-${safeStamp}`;
62
+ fs.copyFileSync(configPath, backupFile);
63
+ }
64
+ ledger.mcpBackup = { taken: true, at: timestamp, file: backupFile };
65
+ return backupFile;
66
+ }
67
+
68
+ /**
69
+ * Resolve "${VAR_NAME}" placeholder strings against the shared secrets
70
+ * contract (agentsEnv.getSecret: real env var, else <base>/agents.env).
71
+ * Recurses into objects/arrays. A string that isn't a whole-string
72
+ * placeholder passes through unchanged.
73
+ *
74
+ * An unresolved placeholder is dropped from its parent (not written as a
75
+ * literal "${...}" template into the real config) — this is how an optional
76
+ * secret (e.g. CONTEXT7_API_KEY) degrades to an unauthenticated/rate-limited
77
+ * entry instead of blocking install. If dropping placeholders empties out an
78
+ * object/array that originally had entries, that now-empty container is
79
+ * itself dropped from ITS parent in turn (e.g. a `headers` object whose only
80
+ * key was an unresolved secret placeholder never appears in the written
81
+ * config at all, rather than being written as `"headers": {}`).
82
+ */
83
+ function resolvePlaceholders(value, { base }) {
84
+ if (typeof value === 'string') {
85
+ const m = value.match(PLACEHOLDER);
86
+ if (!m) return { value, resolved: true };
87
+ const secret = getSecret(m[1], undefined, { base });
88
+ return secret ? { value: secret, resolved: true } : { value: undefined, resolved: false };
89
+ }
90
+ if (Array.isArray(value)) {
91
+ const out = [];
92
+ for (const item of value) {
93
+ const r = resolvePlaceholders(item, { base });
94
+ if (r.resolved) out.push(r.value);
95
+ }
96
+ const droppedAll = value.length > 0 && out.length === 0;
97
+ return { value: out, resolved: !droppedAll };
98
+ }
99
+ if (value !== null && typeof value === 'object') {
100
+ const out = {};
101
+ for (const [k, v] of Object.entries(value)) {
102
+ const r = resolvePlaceholders(v, { base });
103
+ if (r.resolved) out[k] = r.value;
104
+ }
105
+ const droppedAll = Object.keys(value).length > 0 && Object.keys(out).length === 0;
106
+ return { value: out, resolved: !droppedAll };
107
+ }
108
+ return { value, resolved: true };
109
+ }
110
+
111
+ /**
112
+ * Merge every mcp item's wiring (kind === "mcp", non-null wiring shaped like
113
+ * {name, type, url|command, ...} — the mcpServers server-entry object itself
114
+ * plus a `name` key naming its mcpServers key) into the real user-scope MCP
115
+ * config file's `mcpServers` object, and record the exact JSON we wrote
116
+ * under `ledger.mcp[bundleKey][name]` so `unwireMcpBundle` can later remove
117
+ * exactly (and only) what this bundle wired, and skip removal (report
118
+ * `keptUserEdited`) if the entry was hand-edited since.
119
+ *
120
+ * Idempotent: re-running with the same items produces the same entry (a
121
+ * byte-identical re-write is treated as `alreadyWired`, not `wired`). Every
122
+ * other key in the config file — and every other mcpServers entry — is
123
+ * preserved verbatim; the whole file is round-tripped through
124
+ * JSON.parse/stringify and only the entries we own are read or mutated.
125
+ *
126
+ * `scope` is metadata (mirrors mcps.json's own-registry convention for
127
+ * documenting the intended `claude mcp add --scope` value) — it's dropped
128
+ * before writing, since the real mcpServers entry shape never includes it.
129
+ * Only "user" scope is supported by this executor; a non-"user" scope on an
130
+ * mcp item is a WiringError (fail loud rather than silently mis-target a
131
+ * project/local config this executor doesn't manage).
132
+ */
133
+ function wireMcpItems(items, { targetBase, bundleKey, ledger, timestamp, configPath }) {
134
+ const mcpItems = items.filter((item) => item.kind === 'mcp' && item.wiring);
135
+ const wired = [];
136
+ const alreadyWired = [];
137
+ const skippedNoSecret = [];
138
+
139
+ if (mcpItems.length === 0) {
140
+ return { wired, alreadyWired, skippedNoSecret, configChanged: false, backupFile: null, configPath: null };
141
+ }
142
+
143
+ const resolvedConfigPath = configPath || defaultMcpConfigPath(targetBase);
144
+ const config = loadMcpConfig(resolvedConfigPath);
145
+ config[MCP_SERVERS_KEY] =
146
+ config[MCP_SERVERS_KEY] && typeof config[MCP_SERVERS_KEY] === 'object' && !Array.isArray(config[MCP_SERVERS_KEY])
147
+ ? config[MCP_SERVERS_KEY]
148
+ : {};
149
+
150
+ let mutated = false;
151
+
152
+ for (const item of mcpItems) {
153
+ for (const wiring of asWiringList(item.wiring)) {
154
+ if (!wiring.name) {
155
+ throw new WiringError(`MCP wiring for item "${item.path}" is missing "name" (the mcpServers key to write)`);
156
+ }
157
+ if (wiring.scope && wiring.scope !== 'user') {
158
+ throw new WiringError(
159
+ `MCP wiring for item "${item.path}" (name "${wiring.name}") declares scope "${wiring.scope}" — ` +
160
+ `this executor only writes user-scope MCP config`
161
+ );
162
+ }
163
+
164
+ const { name, scope, ...serverDef } = wiring;
165
+ const { value: resolvedDef, resolved } = resolvePlaceholders(serverDef, { base: targetBase });
166
+
167
+ if (!resolved) {
168
+ skippedNoSecret.push({ path: item.path, name });
169
+ continue;
170
+ }
171
+
172
+ if (ledger) {
173
+ ledger.mcp = ledger.mcp || {};
174
+ ledger.mcp[bundleKey] = ledger.mcp[bundleKey] || {};
175
+ }
176
+
177
+ const writtenJson = JSON.stringify(resolvedDef);
178
+ const existing = config[MCP_SERVERS_KEY][name];
179
+ const same = existing !== undefined && JSON.stringify(existing) === writtenJson;
180
+
181
+ if (ledger) {
182
+ ledger.mcp[bundleKey][name] = writtenJson;
183
+ }
184
+
185
+ if (same) {
186
+ alreadyWired.push({ path: item.path, name });
187
+ continue;
188
+ }
189
+
190
+ config[MCP_SERVERS_KEY][name] = resolvedDef;
191
+ wired.push({ path: item.path, name });
192
+ mutated = true;
193
+ }
194
+ }
195
+
196
+ if (!mutated) {
197
+ return { wired, alreadyWired, skippedNoSecret, configChanged: false, backupFile: null, configPath: resolvedConfigPath };
198
+ }
199
+
200
+ const backupFile = ensureMcpBackup(resolvedConfigPath, ledger || {}, timestamp);
201
+ saveMcpConfig(resolvedConfigPath, config);
202
+
203
+ return { wired, alreadyWired, skippedNoSecret, configChanged: true, backupFile, configPath: resolvedConfigPath };
204
+ }
205
+
206
+ /**
207
+ * Remove exactly the mcpServers entries recorded under
208
+ * `ledger.mcp[bundleKey]` — nothing else. An entry whose current on-disk
209
+ * value no longer matches what this CLI last wrote (hand-edited since) is
210
+ * left in place and reported in `keptUserEdited`, mirroring uninstallBundle's
211
+ * file-hash-mismatch protection. No-op (not an error) if the bundle has no
212
+ * recorded MCP wiring.
213
+ */
214
+ function unwireMcpBundle(bundleKey, { targetBase, configPath, ledger }) {
215
+ const records = (ledger.mcp && ledger.mcp[bundleKey]) || {};
216
+ const names = Object.keys(records);
217
+ if (names.length === 0) {
218
+ return { removed: [], keptUserEdited: [], configChanged: false };
219
+ }
220
+
221
+ const resolvedConfigPath = configPath || defaultMcpConfigPath(targetBase);
222
+ const config = loadMcpConfig(resolvedConfigPath);
223
+ const removed = [];
224
+ const keptUserEdited = [];
225
+ let mutated = false;
226
+
227
+ const servers = config[MCP_SERVERS_KEY];
228
+ if (servers && typeof servers === 'object' && !Array.isArray(servers)) {
229
+ for (const name of names) {
230
+ const current = servers[name];
231
+ if (current === undefined) {
232
+ removed.push(name);
233
+ continue;
234
+ }
235
+ if (JSON.stringify(current) === records[name]) {
236
+ delete servers[name];
237
+ removed.push(name);
238
+ mutated = true;
239
+ } else {
240
+ keptUserEdited.push(name);
241
+ }
242
+ }
243
+ } else {
244
+ removed.push(...names);
245
+ }
246
+
247
+ if (mutated) {
248
+ saveMcpConfig(resolvedConfigPath, config);
249
+ }
250
+
251
+ if (ledger.mcp) {
252
+ delete ledger.mcp[bundleKey];
253
+ }
254
+
255
+ return { removed, keptUserEdited, configChanged: mutated };
256
+ }
257
+
258
+ /**
259
+ * Every mcpServers name the current manifest `items` declare for this bundle
260
+ * — independent of secret availability, so an entry temporarily skipped for
261
+ * a missing secret is still "expected" (not pruned as stale). Used by the
262
+ * update command to detect when the manifest's MCP wiring declarations
263
+ * changed since install.
264
+ */
265
+ function expectedMcpNames(items) {
266
+ const mcpItems = items.filter((item) => item.kind === 'mcp' && item.wiring);
267
+ const names = new Set();
268
+ for (const item of mcpItems) {
269
+ for (const wiring of asWiringList(item.wiring)) {
270
+ if (wiring.name) names.add(wiring.name);
271
+ }
272
+ }
273
+ return names;
274
+ }
275
+
276
+ /**
277
+ * Remove ledger.mcp[bundleKey] entries whose name is no longer in
278
+ * `expectedNames` (the manifest dropped or renamed that MCP wiring
279
+ * declaration). Same hash-compare protection as unwireMcpBundle: an entry
280
+ * whose on-disk value no longer matches what this CLI last wrote is left in
281
+ * place and reported in `keptUserEdited` rather than removed.
282
+ */
283
+ function pruneStaleMcp(bundleKey, { targetBase, configPath, ledger, expectedNames }) {
284
+ const existing = (ledger.mcp && ledger.mcp[bundleKey]) || {};
285
+ const staleNames = Object.keys(existing).filter((name) => !expectedNames.has(name));
286
+ if (staleNames.length === 0) {
287
+ return { removed: [], keptUserEdited: [], configChanged: false };
288
+ }
289
+
290
+ const resolvedConfigPath = configPath || defaultMcpConfigPath(targetBase);
291
+ const config = loadMcpConfig(resolvedConfigPath);
292
+ const removed = [];
293
+ const keptUserEdited = [];
294
+ let mutated = false;
295
+ const servers = config[MCP_SERVERS_KEY];
296
+
297
+ for (const name of staleNames) {
298
+ const current = servers && typeof servers === 'object' ? servers[name] : undefined;
299
+ if (current === undefined) {
300
+ removed.push(name);
301
+ } else if (JSON.stringify(current) === existing[name]) {
302
+ delete servers[name];
303
+ removed.push(name);
304
+ mutated = true;
305
+ } else {
306
+ keptUserEdited.push(name);
307
+ }
308
+ delete ledger.mcp[bundleKey][name];
309
+ }
310
+
311
+ if (mutated) {
312
+ saveMcpConfig(resolvedConfigPath, config);
313
+ }
314
+
315
+ return { removed, keptUserEdited, configChanged: mutated };
316
+ }
317
+
318
+ module.exports = {
319
+ wireMcpItems,
320
+ unwireMcpBundle,
321
+ pruneStaleMcp,
322
+ expectedMcpNames,
323
+ defaultMcpConfigPath,
324
+ loadMcpConfig,
325
+ saveMcpConfig,
326
+ MCP_CONFIG_FILE_NAME,
327
+ MCP_SERVERS_KEY,
328
+ };
package/lib/menu.js ADDED
@@ -0,0 +1,138 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Pure classification/selection logic for the bundle picker. Deliberately
5
+ * decoupled from any TTY/readline code so it's testable without a real
6
+ * terminal — the interactive renderer in tty-menu.js is the only piece that
7
+ * touches process.stdin/stdout directly.
8
+ */
9
+
10
+ /**
11
+ * Classify a bundle for menu display/install purposes.
12
+ * 'passthrough' — selecting it prints bundle.passthrough.command, installs nothing.
13
+ * 'installable' — installs via installBundle() as-is. This includes bundles
14
+ * that declare `deps` (e.g. litellm): installing one now
15
+ * also runs the dependency's component flow (detect/install
16
+ * the binary, copy its config/start-script templates) —
17
+ * see components.js. Landed in slice #27; before that, a
18
+ * deps-bearing bundle was classified 'needs-deps' and the
19
+ * interactive menu refused to select it.
20
+ */
21
+ function classifyBundle(bundle) {
22
+ if (bundle.passthrough) {
23
+ return 'passthrough';
24
+ }
25
+ return 'installable';
26
+ }
27
+
28
+ function secretsHint(bundle) {
29
+ if (!bundle.secrets || bundle.secrets.length === 0) {
30
+ return null;
31
+ }
32
+ return bundle.secrets.map((s) => s.name).join(', ');
33
+ }
34
+
35
+ /** Comma-joined component keys this bundle depends on (e.g. "litellm"), or null if none. */
36
+ function depsHint(bundle) {
37
+ if (!bundle.deps || bundle.deps.length === 0) {
38
+ return null;
39
+ }
40
+ return bundle.deps.join(', ');
41
+ }
42
+
43
+ /**
44
+ * Is `bundle` visible under the given --profile selection? "public" (the
45
+ * default, and the only thing offered before npx distribution slice #28)
46
+ * shows only bundle.profile === "public". "self" is additive — the
47
+ * maintainer machine wants the full public offering PLUS the self-only
48
+ * extras (self-infra, self-skills, ...), matching what install.ps1 already
49
+ * deploys as one undifferentiated whole. Self bundles stay unreachable from
50
+ * the default/public profile's menu (they're still installable directly via
51
+ * `--bundle <key> --yes` regardless of --profile, same as any bundle key).
52
+ */
53
+ function profileVisible(bundle, profile) {
54
+ if (profile === 'self') {
55
+ return bundle.profile === 'public' || bundle.profile === 'self';
56
+ }
57
+ return bundle.profile === 'public';
58
+ }
59
+
60
+ /**
61
+ * Bundles offered in the basic menu: profile-visible, non-advanced.
62
+ * (Advanced-only bundles — none exist yet, but the schema supports
63
+ * bundle.advanced: true — only show up under --advanced.)
64
+ */
65
+ function basicMenuBundles(manifest, profile = 'public') {
66
+ return manifest.bundles.filter((b) => profileVisible(b, profile) && !b.advanced);
67
+ }
68
+
69
+ /** Every profile-visible bundle, advanced or not — for `--advanced`. */
70
+ function advancedMenuBundles(manifest, profile = 'public') {
71
+ return manifest.bundles.filter((b) => profileVisible(b, profile));
72
+ }
73
+
74
+ /**
75
+ * Build the row data a renderer (TTY or fallback numbered list) needs for
76
+ * one bundle, without any presentation/formatting decisions baked in.
77
+ */
78
+ function describeBundleRow(bundle) {
79
+ const status = classifyBundle(bundle);
80
+ return {
81
+ key: bundle.key,
82
+ title: bundle.title,
83
+ summary: bundle.summary,
84
+ status,
85
+ secretsHint: secretsHint(bundle),
86
+ depsHint: depsHint(bundle),
87
+ itemCount: bundle.items.length,
88
+ passthroughCommand: bundle.passthrough ? bundle.passthrough.command : null,
89
+ };
90
+ }
91
+
92
+ /**
93
+ * Given a manifest and a list of selected bundle keys (from either menu
94
+ * mode), split them into dispositions. This is the seam the CLI calls after
95
+ * the interactive picker returns (or after a non-interactive/testing caller
96
+ * supplies a selection directly) — no TTY involved past this point.
97
+ */
98
+ function planSelection(manifest, selectedKeys) {
99
+ const plan = { toInstall: [], passthroughs: [], unknown: [] };
100
+ for (const key of selectedKeys) {
101
+ const bundle = manifest.bundles.find((b) => b.key === key);
102
+ if (!bundle) {
103
+ plan.unknown.push(key);
104
+ continue;
105
+ }
106
+ if (classifyBundle(bundle) === 'passthrough') {
107
+ plan.passthroughs.push(bundle);
108
+ } else {
109
+ plan.toInstall.push(bundle);
110
+ }
111
+ }
112
+ return plan;
113
+ }
114
+
115
+ /**
116
+ * Items offered for per-item selection within one bundle under --advanced.
117
+ * advancedOnly items are included (that's the point of advanced mode) but
118
+ * reported separately so a renderer can flag them.
119
+ */
120
+ function describeBundleItems(bundle) {
121
+ return bundle.items.map((item) => ({
122
+ path: item.path,
123
+ kind: item.kind,
124
+ advancedOnly: !!item.advancedOnly,
125
+ }));
126
+ }
127
+
128
+ module.exports = {
129
+ classifyBundle,
130
+ secretsHint,
131
+ depsHint,
132
+ profileVisible,
133
+ basicMenuBundles,
134
+ advancedMenuBundles,
135
+ describeBundleRow,
136
+ planSelection,
137
+ describeBundleItems,
138
+ };