@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.
package/bin/cli.js ADDED
@@ -0,0 +1,721 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ const path = require('node:path');
5
+ const { readFileSync } = require('node:fs');
6
+
7
+ const pkg = JSON.parse(
8
+ readFileSync(path.join(__dirname, '..', 'package.json'), 'utf8')
9
+ );
10
+
11
+ const { installBundle, defaultTargetBase, InstallError } = require('../lib/install');
12
+ const { uninstallBundle, UninstallError } = require('../lib/uninstall');
13
+ const { loadManifest, findBundle, ManifestError } = require('../lib/manifest');
14
+ const { loadLedger, bundleKeysInLedger, LedgerError } = require('../lib/ledger');
15
+ const { updateBundles, UpdateError } = require('../lib/update');
16
+ const { WiringError } = require('../lib/wiring');
17
+ const {
18
+ basicMenuBundles,
19
+ advancedMenuBundles,
20
+ describeBundleRow,
21
+ describeBundleItems,
22
+ planSelection,
23
+ } = require('../lib/menu');
24
+ const { pickBundles } = require('../lib/tty-menu');
25
+ const { collectBundleSecrets, collectComponentSecrets, isResolved, promptForMissingSecrets } = require('../lib/secretsPrompt');
26
+ const { runSelfProfilePostInstall } = require('../lib/selfProfile');
27
+
28
+ const PACKAGE_ROOT = path.join(__dirname, '..');
29
+
30
+ function printHelp() {
31
+ console.log(`${pkg.name} v${pkg.version}
32
+
33
+ Usage:
34
+ agents-cli --version Print the CLI version
35
+ agents-cli install Interactive bundle menu (TTY) or list bundles (non-TTY)
36
+ agents-cli install --advanced Interactive menu over ALL bundles, with per-item selection
37
+ agents-cli install --bundle <key> --yes Install one bundle non-interactively
38
+ agents-cli uninstall --bundle <key> --yes Remove a bundle's installed files and settings.json wiring
39
+ agents-cli update --yes Update every installed bundle to the current source
40
+ agents-cli update --bundle <key> --yes Update one installed bundle
41
+ agents-cli secrets Prompt for any missing secrets across all installed bundles
42
+ agents-cli secrets --bundle <key> Prompt for missing secrets for one bundle
43
+ agents-cli secrets --list Show which secrets are set/missing (names only — never values)
44
+ agents-cli --help Show this help
45
+
46
+ Flags for install:
47
+ --bundle <key> Bundle to install non-interactively — run "install" with no flags to list keys
48
+ --yes Required with --bundle: confirms the non-interactive install
49
+ --advanced Interactive menu: show every bundle (incl. advanced) and pick items within one
50
+ --profile <public|self> Which bundles the menu/listing offers (default: public). "self" adds this
51
+ repo's maintainer-only bundles (self-infra, self-skills, ...) on top of the
52
+ public set, and runs the self-profile post-install steps (repo-root marker,
53
+ stale-file cleanup, dispatch-tier lint, Windows scheduled-task registration)
54
+ once after every requested bundle installs. A bundle is always installable by
55
+ exact --bundle <key> regardless of --profile — this flag only affects what's
56
+ listed/offered and whether the post-install steps run.
57
+ --target-dir <path> Install target base, default ~/.claude (use for testing)
58
+ --target-config <path> MCP config file to wire into, default the sibling .claude.json
59
+ next to --target-dir (use for testing)
60
+ --no-secrets Skip secret prompting for this install (--yes alone does not skip it)
61
+
62
+ Flags for uninstall:
63
+ --bundle <key> Bundle to uninstall (required)
64
+ --yes Required: confirms the removal
65
+ --target-dir <path> Install target base, default ~/.claude (use for testing)
66
+ --target-config <path> MCP config file to unwire from, default the sibling .claude.json
67
+ next to --target-dir (use for testing)
68
+
69
+ Flags for secrets:
70
+ --bundle <key> Limit to one bundle's declared secrets (default: every installed bundle)
71
+ --list List secret names + set/missing status instead of prompting
72
+ --target-dir <path> Install target base, default ~/.claude (use for testing)
73
+
74
+ Flags for update:
75
+ --bundle <key> Limit to one bundle (default: every bundle recorded in the ledger)
76
+ --yes Required: confirms the update
77
+ --target-dir <path> Install target base, default ~/.claude (use for testing)
78
+ --target-config <path> MCP config file to update, default the sibling .claude.json
79
+ next to --target-dir (use for testing)
80
+ --json Print a machine-readable summary instead of prose
81
+ --theirs Non-interactive: resolve every file conflict by taking the new source
82
+ --keep-mine Non-interactive: resolve every file conflict by keeping your on-disk version
83
+
84
+ Update compares each installed file's source hash, ledger hash, and on-disk
85
+ hash: a file no one has touched since install is silently overwritten when
86
+ the source changed; a file you edited (and the source hasn't changed) is left
87
+ alone; a file edited on BOTH sides is a conflict — in a terminal you get a
88
+ diff and a keep/overwrite/backup prompt per file, otherwise pass --theirs or
89
+ --keep-mine (plain --yes does not resolve conflicts on its own; with neither
90
+ a strategy nor a TTY, conflicts are listed and the command exits 2, leaving
91
+ those files untouched). A file the manifest no longer ships is removed if
92
+ untouched, or kept-but-untracked with a warning if you'd edited it. Hook and
93
+ MCP wiring are refreshed to match the current manifest on every update.
94
+
95
+ Secrets are prompted per bundle at install time (masked input, every prompt
96
+ skippable with Enter), validated live where feasible (currently
97
+ GITLAB_TOKEN), and stored in <target>/agents.env with user-only file
98
+ permissions. They are never written to settings.json and never leave this
99
+ machine. Re-run "agents-cli secrets" any time to fill in values you skipped.
100
+
101
+ Bundles that declare a dependency (e.g. LiteLLM) are fully installable: selecting one
102
+ also runs its component's install flow (detect/install the binary via uv, falling back
103
+ to pipx, and copy its config + start-script templates to <target>/<component>/) — see
104
+ "LiteLLM-backed bundles" in the README for what a fresh install looks like end to end.
105
+
106
+ Hook items with wiring data are merged into <target>/settings.json's "hooks" section
107
+ after install (idempotent; a one-time settings.json.bak-<timestamp> backup is taken
108
+ before the CLI's first-ever write there). A Python-backed hook is skipped (not an
109
+ error) when no python3/python is on PATH — re-run "install --bundle <key> --yes" once
110
+ Python is installed to wire it.
111
+ `);
112
+ }
113
+
114
+ function parseInstallArgs(argv) {
115
+ const args = { bundle: null, yes: false, targetDir: null, targetConfig: null, advanced: false, noSecrets: false, profile: 'public' };
116
+ for (let i = 0; i < argv.length; i += 1) {
117
+ const arg = argv[i];
118
+ if (arg === '--bundle') {
119
+ args.bundle = argv[i + 1];
120
+ i += 1;
121
+ } else if (arg === '--yes') {
122
+ args.yes = true;
123
+ } else if (arg === '--target-dir') {
124
+ args.targetDir = argv[i + 1];
125
+ i += 1;
126
+ } else if (arg === '--target-config') {
127
+ args.targetConfig = argv[i + 1];
128
+ i += 1;
129
+ } else if (arg === '--advanced') {
130
+ args.advanced = true;
131
+ } else if (arg === '--no-secrets') {
132
+ args.noSecrets = true;
133
+ } else if (arg === '--profile') {
134
+ args.profile = argv[i + 1];
135
+ i += 1;
136
+ } else {
137
+ throw new InstallError(`Unknown install flag: ${arg}`);
138
+ }
139
+ }
140
+ if (args.profile !== 'public' && args.profile !== 'self') {
141
+ throw new InstallError(`Unknown --profile "${args.profile}" — must be "public" or "self".`);
142
+ }
143
+ return args;
144
+ }
145
+
146
+ function listBundles(profile = 'public') {
147
+ try {
148
+ const { manifest } = loadManifest(PACKAGE_ROOT);
149
+ const bundles = basicMenuBundlesForList(manifest, profile);
150
+ if (!bundles.length) {
151
+ console.log('No bundles are defined yet.');
152
+ return 0;
153
+ }
154
+ console.log('Not running in a terminal — printing the bundle list instead of the interactive menu.');
155
+ console.log('Available bundles:');
156
+ for (const bundle of bundles) {
157
+ console.log(` ${bundle.key} — ${bundle.summary}`);
158
+ }
159
+ console.log('\nRun: agents-cli install --bundle <key> --yes');
160
+ return 0;
161
+ } catch (err) {
162
+ console.error(err.message);
163
+ return 1;
164
+ }
165
+ }
166
+
167
+ /** advancedMenuBundles(manifest, profile) minus the advanced-only filter — the non-interactive
168
+ * listing shows every profile-visible bundle (basic + advanced), same breadth --advanced gives
169
+ * the interactive picker, since a plain listing has no follow-up per-item selection step to gate. */
170
+ function basicMenuBundlesForList(manifest, profile) {
171
+ return advancedMenuBundles(manifest, profile);
172
+ }
173
+
174
+ /**
175
+ * Run the --profile self post-install steps (repo-root marker, stale-file
176
+ * cleanup, dispatch-tier lint, scheduled-task registration) once, after
177
+ * every requested bundle has been installed. No-op for --profile public.
178
+ */
179
+ function runSelfProfileStepsIfNeeded({ profile, targetDir }) {
180
+ if (profile !== 'self') return;
181
+ const { manifestPath } = loadManifest(PACKAGE_ROOT);
182
+ const repoRoot = path.dirname(manifestPath);
183
+ const result = runSelfProfilePostInstall({
184
+ targetBase: targetDir || defaultTargetBase(),
185
+ repoRoot,
186
+ });
187
+ console.log('\n=== --profile self post-install steps ===');
188
+ console.log(
189
+ result.repoRootMarker.written
190
+ ? ` Wrote repo-root marker: ${result.repoRootMarker.path}`
191
+ : ' Repo-root marker skipped (no local repo root resolved).'
192
+ );
193
+ if (result.staleCleanup.removed.length > 0) {
194
+ console.log(` Removed ${result.staleCleanup.removed.length} stale agent file(s): ${result.staleCleanup.removed.join(', ')}`);
195
+ }
196
+ if (result.dispatchTierLint.ran) {
197
+ console.log(result.dispatchTierLint.ok ? ' Dispatch-tier lint: OK.' : ` Dispatch-tier lint FAILED:\n${result.dispatchTierLint.stderr}`);
198
+ } else {
199
+ console.log(` Dispatch-tier lint: ${result.dispatchTierLint.message}`);
200
+ }
201
+ if (result.scheduledTasks.ran) {
202
+ if (result.scheduledTasks.ok) {
203
+ console.log(' Scheduled tasks registered.');
204
+ } else if (result.scheduledTasks.blocked) {
205
+ console.log(' Scheduled-task registration skipped (blocked under NODE_ENV=test).');
206
+ } else {
207
+ console.log(` Scheduled-task registration FAILED (exit ${result.scheduledTasks.status}): ${result.scheduledTasks.stderr}`);
208
+ }
209
+ } else {
210
+ console.log(` Scheduled tasks: ${result.scheduledTasks.message}`);
211
+ }
212
+ return result;
213
+ }
214
+
215
+ function installOneBundle({ bundleKey, targetDir, targetConfig, itemPaths }) {
216
+ const result = installBundle({
217
+ packageRoot: PACKAGE_ROOT,
218
+ bundleKey,
219
+ targetBase: targetDir,
220
+ cliVersion: pkg.version,
221
+ itemPaths,
222
+ mcpConfigPath: targetConfig,
223
+ });
224
+ if (result.unchanged) {
225
+ console.log(`Bundle "${result.bundle}" already up to date at ${result.targetBase} (no changes).`);
226
+ } else {
227
+ console.log(
228
+ `Bundle "${result.bundle}" installed to ${result.targetBase}: ` +
229
+ `${result.filesWritten} file(s) written, ${result.filesUnchanged} unchanged.`
230
+ );
231
+ }
232
+ if (result.hooksWired.length > 0) {
233
+ console.log(` Wired ${result.hooksWired.length} hook(s) into ${result.targetBase}/settings.json.`);
234
+ }
235
+ if (result.settingsBackupFile) {
236
+ console.log(` Backed up existing settings.json to ${result.settingsBackupFile} before this CLI's first write.`);
237
+ }
238
+ if (result.hooksSkippedNoPython.length > 0) {
239
+ const names = result.hooksSkippedNoPython.map((h) => h.path).join(', ');
240
+ console.log(
241
+ ` Skipped wiring ${result.hooksSkippedNoPython.length} Python hook(s) (${names}): no python3/python found on PATH. ` +
242
+ `Install Python, then re-run: agents-cli install --bundle ${result.bundle} --yes`
243
+ );
244
+ }
245
+ if (result.mcpWired.length > 0) {
246
+ const names = result.mcpWired.map((m) => m.name).join(', ');
247
+ console.log(` Wired ${result.mcpWired.length} MCP server(s) (${names}) into ${result.mcpConfigPath}.`);
248
+ }
249
+ if (result.mcpBackupFile) {
250
+ console.log(` Backed up existing MCP config to ${result.mcpBackupFile} before this CLI's first write.`);
251
+ }
252
+ if (result.mcpSkippedNoSecret.length > 0) {
253
+ const names = result.mcpSkippedNoSecret.map((m) => m.name).join(', ');
254
+ console.log(` Skipped wiring ${result.mcpSkippedNoSecret.length} MCP server(s) (${names}): required secret not set.`);
255
+ }
256
+ for (const component of result.components || []) {
257
+ if (component.status === 'present') {
258
+ console.log(` Component "${component.key}": already on PATH.`);
259
+ } else if (component.status === 'installed') {
260
+ console.log(` Component "${component.key}": installed via ${component.tool}.`);
261
+ } else if (component.status === 'failed') {
262
+ console.log(` Component "${component.key}": ${component.message}`);
263
+ } else if (component.status === 'pending') {
264
+ console.log(` Component "${component.key}": ${component.message}`);
265
+ }
266
+ if (component.filesWritten && component.filesWritten.length > 0) {
267
+ console.log(` Component "${component.key}": wrote ${component.filesWritten.join(', ')} to ${result.targetBase}.`);
268
+ }
269
+ }
270
+ }
271
+
272
+ /**
273
+ * Runs the interactive picker, then hands the resulting selection to
274
+ * planSelection() (menu.js) and executes each disposition. This function is
275
+ * the only piece of the menu flow that isn't unit-testable without a TTY —
276
+ * everything it calls (planSelection, installBundle) is.
277
+ */
278
+ async function runInteractiveMenu({ advanced, targetDir, targetConfig, noSecrets, profile }) {
279
+ const { manifest } = loadManifest(PACKAGE_ROOT);
280
+ const candidateBundles = advanced ? advancedMenuBundles(manifest, profile) : basicMenuBundles(manifest, profile);
281
+ if (!candidateBundles.length) {
282
+ console.log('No bundles are defined yet.');
283
+ return 0;
284
+ }
285
+
286
+ const rows = candidateBundles.map(describeBundleRow);
287
+ const selectedKeys = await pickBundles(rows);
288
+ if (selectedKeys === null) {
289
+ console.log('Cancelled — nothing installed.');
290
+ return 0;
291
+ }
292
+ if (selectedKeys.length === 0) {
293
+ console.log('Nothing selected — nothing installed.');
294
+ return 0;
295
+ }
296
+
297
+ const plan = planSelection(manifest, selectedKeys);
298
+
299
+ for (const bundle of plan.passthroughs) {
300
+ console.log(`\n"${bundle.title}" is not shipped by this package — run:\n ${bundle.passthrough.command}`);
301
+ if (bundle.passthrough.note) {
302
+ console.log(bundle.passthrough.note);
303
+ }
304
+ }
305
+
306
+ const installedBundles = [];
307
+ for (const bundle of plan.toInstall) {
308
+ let itemPaths;
309
+ if (advanced) {
310
+ const itemRows = describeBundleItems(bundle).map((item) => ({
311
+ key: item.path,
312
+ title: item.path,
313
+ summary: item.kind + (item.advancedOnly ? ' (advanced)' : ''),
314
+ status: 'installable',
315
+ secretsHint: null,
316
+ }));
317
+ console.log(`\nSelect items to install for "${bundle.title}":`);
318
+ const selectedItemPaths = await pickBundles(itemRows);
319
+ if (selectedItemPaths === null || selectedItemPaths.length === 0) {
320
+ console.log(`Skipping "${bundle.title}" — no items selected.`);
321
+ continue;
322
+ }
323
+ itemPaths = selectedItemPaths;
324
+ }
325
+ try {
326
+ installOneBundle({ bundleKey: bundle.key, targetDir, targetConfig, itemPaths });
327
+ installedBundles.push(bundle);
328
+ } catch (err) {
329
+ if (err instanceof InstallError || err instanceof ManifestError || err instanceof LedgerError || err instanceof WiringError) {
330
+ console.error(err.message);
331
+ } else {
332
+ throw err;
333
+ }
334
+ }
335
+ }
336
+
337
+ await promptForMissingSecrets({
338
+ bundles: installedBundles,
339
+ targetBase: targetDir || defaultTargetBase(),
340
+ noSecrets,
341
+ manifest,
342
+ });
343
+
344
+ if (installedBundles.length > 0) {
345
+ runSelfProfileStepsIfNeeded({ profile, targetDir });
346
+ }
347
+
348
+ return 0;
349
+ }
350
+
351
+ async function runInstall(argv) {
352
+ let args;
353
+ try {
354
+ args = parseInstallArgs(argv);
355
+ } catch (err) {
356
+ console.error(err.message);
357
+ return 1;
358
+ }
359
+
360
+ if (!args.bundle) {
361
+ const isTTY = !!(process.stdin.isTTY && process.stdout.isTTY);
362
+ if (!isTTY) {
363
+ return listBundles(args.profile);
364
+ }
365
+ return runInteractiveMenu({
366
+ advanced: args.advanced,
367
+ targetDir: args.targetDir,
368
+ targetConfig: args.targetConfig,
369
+ noSecrets: args.noSecrets,
370
+ profile: args.profile,
371
+ });
372
+ }
373
+
374
+ if (!args.yes) {
375
+ console.error('Non-interactive installs require --yes to confirm.');
376
+ return 1;
377
+ }
378
+
379
+ try {
380
+ installOneBundle({ bundleKey: args.bundle, targetDir: args.targetDir, targetConfig: args.targetConfig });
381
+ const { manifest } = loadManifest(PACKAGE_ROOT);
382
+ const bundle = findBundle(manifest, args.bundle);
383
+ await promptForMissingSecrets({
384
+ bundles: bundle ? [bundle] : [],
385
+ targetBase: args.targetDir || defaultTargetBase(),
386
+ noSecrets: args.noSecrets,
387
+ manifest,
388
+ });
389
+ runSelfProfileStepsIfNeeded({ profile: args.profile, targetDir: args.targetDir });
390
+ return 0;
391
+ } catch (err) {
392
+ if (err instanceof InstallError || err instanceof ManifestError || err instanceof LedgerError || err instanceof WiringError) {
393
+ console.error(err.message);
394
+ return 1;
395
+ }
396
+ throw err;
397
+ }
398
+ }
399
+
400
+ function parseUninstallArgs(argv) {
401
+ const args = { bundle: null, yes: false, targetDir: null, targetConfig: null };
402
+ for (let i = 0; i < argv.length; i += 1) {
403
+ const arg = argv[i];
404
+ if (arg === '--bundle') {
405
+ args.bundle = argv[i + 1];
406
+ i += 1;
407
+ } else if (arg === '--yes') {
408
+ args.yes = true;
409
+ } else if (arg === '--target-dir') {
410
+ args.targetDir = argv[i + 1];
411
+ i += 1;
412
+ } else if (arg === '--target-config') {
413
+ args.targetConfig = argv[i + 1];
414
+ i += 1;
415
+ } else {
416
+ throw new UninstallError(`Unknown uninstall flag: ${arg}`);
417
+ }
418
+ }
419
+ return args;
420
+ }
421
+
422
+ async function runUninstall(argv) {
423
+ let args;
424
+ try {
425
+ args = parseUninstallArgs(argv);
426
+ } catch (err) {
427
+ console.error(err.message);
428
+ return 1;
429
+ }
430
+
431
+ if (!args.bundle) {
432
+ console.error('uninstall requires --bundle <key>.');
433
+ return 1;
434
+ }
435
+ if (!args.yes) {
436
+ console.error('uninstall requires --yes to confirm.');
437
+ return 1;
438
+ }
439
+
440
+ try {
441
+ const result = uninstallBundle({
442
+ packageRoot: PACKAGE_ROOT,
443
+ bundleKey: args.bundle,
444
+ targetBase: args.targetDir,
445
+ cliVersion: pkg.version,
446
+ mcpConfigPath: args.targetConfig,
447
+ });
448
+ if (result.noop) {
449
+ console.log(`Bundle "${result.bundle}" has no installed files or wiring recorded at ${result.targetBase} — nothing to do.`);
450
+ return 0;
451
+ }
452
+ console.log(
453
+ `Bundle "${result.bundle}" uninstalled from ${result.targetBase}: ` +
454
+ `${result.filesRemoved.length} file(s) removed, ${result.hooksRemoved.length} hook(s) unwired, ` +
455
+ `${result.mcpRemoved.length} MCP server(s) unwired.`
456
+ );
457
+ if (result.filesKeptUserEdited.length > 0) {
458
+ console.log(
459
+ ` Kept ${result.filesKeptUserEdited.length} file(s) that were edited since install (hash mismatch): ` +
460
+ `${result.filesKeptUserEdited.join(', ')}`
461
+ );
462
+ }
463
+ if (result.mcpKeptUserEdited.length > 0) {
464
+ console.log(
465
+ ` Kept ${result.mcpKeptUserEdited.length} MCP server entry(ies) edited since install: ` +
466
+ `${result.mcpKeptUserEdited.join(', ')}`
467
+ );
468
+ }
469
+ for (const component of result.components || []) {
470
+ if (component.kept) {
471
+ console.log(` Component "${component.key}": still depended on by another installed bundle — left as-is.`);
472
+ } else if (component.removed.length > 0 || component.keptUserEdited.length > 0) {
473
+ console.log(
474
+ ` Component "${component.key}": last dependent bundle removed — cleared its config/start files ` +
475
+ `(${component.removed.length} removed${component.keptUserEdited.length > 0 ? `, ${component.keptUserEdited.length} kept (edited since install)` : ''}). ` +
476
+ `The "${component.key}" binary itself was left installed — remove it yourself if you no longer want it (e.g. uv tool uninstall ${component.key}).`
477
+ );
478
+ }
479
+ }
480
+ return 0;
481
+ } catch (err) {
482
+ if (err instanceof UninstallError || err instanceof ManifestError || err instanceof LedgerError || err instanceof WiringError) {
483
+ console.error(err.message);
484
+ return 1;
485
+ }
486
+ throw err;
487
+ }
488
+ }
489
+
490
+ function parseSecretsArgs(argv) {
491
+ const args = { bundle: null, list: false, targetDir: null };
492
+ for (let i = 0; i < argv.length; i += 1) {
493
+ const arg = argv[i];
494
+ if (arg === '--bundle') {
495
+ args.bundle = argv[i + 1];
496
+ i += 1;
497
+ } else if (arg === '--list') {
498
+ args.list = true;
499
+ } else if (arg === '--target-dir') {
500
+ args.targetDir = argv[i + 1];
501
+ i += 1;
502
+ } else {
503
+ throw new InstallError(`Unknown secrets flag: ${arg}`);
504
+ }
505
+ }
506
+ return args;
507
+ }
508
+
509
+ /** Every bundle key with at least one file/wiring entry in the ledger at targetBase. */
510
+ function installedBundleKeys(targetBase, cliVersion) {
511
+ return bundleKeysInLedger(loadLedger(targetBase, cliVersion));
512
+ }
513
+
514
+ async function runSecrets(argv) {
515
+ let args;
516
+ try {
517
+ args = parseSecretsArgs(argv);
518
+ } catch (err) {
519
+ console.error(err.message);
520
+ return 1;
521
+ }
522
+
523
+ const targetBase = args.targetDir || defaultTargetBase();
524
+ const { manifest } = loadManifest(PACKAGE_ROOT);
525
+
526
+ let bundles;
527
+ if (args.bundle) {
528
+ const bundle = findBundle(manifest, args.bundle);
529
+ if (!bundle) {
530
+ const available = manifest.bundles.map((b) => b.key);
531
+ console.error(`Unknown bundle "${args.bundle}". Available bundles: ${available.length ? available.join(', ') : '(none defined yet)'}`);
532
+ return 1;
533
+ }
534
+ bundles = [bundle];
535
+ } else {
536
+ const keys = installedBundleKeys(targetBase, pkg.version);
537
+ bundles = keys.map((key) => findBundle(manifest, key)).filter(Boolean);
538
+ if (bundles.length === 0) {
539
+ console.log(`No installed bundles found at ${targetBase} — nothing to do. Pass --bundle <key> to target one directly.`);
540
+ return 0;
541
+ }
542
+ }
543
+
544
+ const declaredByName = new Map();
545
+ for (const secret of [...collectBundleSecrets(bundles), ...collectComponentSecrets(bundles, manifest)]) {
546
+ if (!declaredByName.has(secret.name)) declaredByName.set(secret.name, secret);
547
+ }
548
+ const declared = [...declaredByName.values()];
549
+ if (declared.length === 0) {
550
+ console.log(`${bundles.map((b) => b.key).join(', ')}: no secrets declared.`);
551
+ return 0;
552
+ }
553
+
554
+ if (args.list) {
555
+ console.log(`Secrets for ${bundles.map((b) => b.key).join(', ')} (status only — values are never shown):`);
556
+ for (const secret of declared) {
557
+ console.log(` ${secret.name}: ${isResolved(secret.name, targetBase) ? 'set' : 'missing'}`);
558
+ }
559
+ return 0;
560
+ }
561
+
562
+ const result = await promptForMissingSecrets({ bundles, targetBase, manifest });
563
+ if (result.written.length === 0 && result.skipped.length === 0) {
564
+ console.log('All secrets for these bundles are already set.');
565
+ }
566
+ return 0;
567
+ }
568
+
569
+ function parseUpdateArgs(argv) {
570
+ const args = { bundle: null, yes: false, targetDir: null, targetConfig: null, json: false, theirs: false, keepMine: false };
571
+ for (let i = 0; i < argv.length; i += 1) {
572
+ const arg = argv[i];
573
+ if (arg === '--bundle') {
574
+ args.bundle = argv[i + 1];
575
+ i += 1;
576
+ } else if (arg === '--yes') {
577
+ args.yes = true;
578
+ } else if (arg === '--target-dir') {
579
+ args.targetDir = argv[i + 1];
580
+ i += 1;
581
+ } else if (arg === '--target-config') {
582
+ args.targetConfig = argv[i + 1];
583
+ i += 1;
584
+ } else if (arg === '--json') {
585
+ args.json = true;
586
+ } else if (arg === '--theirs') {
587
+ args.theirs = true;
588
+ } else if (arg === '--keep-mine') {
589
+ args.keepMine = true;
590
+ } else {
591
+ throw new UpdateError(`Unknown update flag: ${arg}`);
592
+ }
593
+ }
594
+ if (args.theirs && args.keepMine) {
595
+ throw new UpdateError('--theirs and --keep-mine are mutually exclusive.');
596
+ }
597
+ return args;
598
+ }
599
+
600
+ function summarizeBundleUpdate(b) {
601
+ if (!b.changed && b.unresolvedConflicts.length === 0) {
602
+ return `Bundle "${b.bundle}": already up to date (${b.upToDate.length} file(s) unchanged).`;
603
+ }
604
+ const parts = [];
605
+ if (b.overwritten.length) parts.push(`${b.overwritten.length} overwritten`);
606
+ if (b.reinstalled.length) parts.push(`${b.reinstalled.length} reinstalled`);
607
+ if (b.kept.length) parts.push(`${b.kept.length} kept (locally edited, no upstream change)`);
608
+ if (b.removedUpstream.length) parts.push(`${b.removedUpstream.length} removed (no longer shipped)`);
609
+ if (b.keptUpstreamUserEdited.length) {
610
+ parts.push(`${b.keptUpstreamUserEdited.length} kept-but-untracked (removed upstream, locally edited)`);
611
+ }
612
+ if (b.conflictsResolved.length) parts.push(`${b.conflictsResolved.length} conflict(s) resolved`);
613
+ if (b.unresolvedConflicts.length) parts.push(`${b.unresolvedConflicts.length} conflict(s) unresolved`);
614
+ if (b.hooksWired.length) parts.push(`${b.hooksWired.length} hook(s) rewired`);
615
+ if (b.mcpWired.length) parts.push(`${b.mcpWired.length} MCP server(s) rewired`);
616
+ return `Bundle "${b.bundle}": ${parts.join(', ') || 'no changes'}.`;
617
+ }
618
+
619
+ async function runUpdate(argv) {
620
+ let args;
621
+ try {
622
+ args = parseUpdateArgs(argv);
623
+ } catch (err) {
624
+ console.error(err.message);
625
+ return 1;
626
+ }
627
+
628
+ if (!args.yes) {
629
+ console.error('update requires --yes to confirm.');
630
+ return 1;
631
+ }
632
+
633
+ const strategy = args.theirs ? 'theirs' : args.keepMine ? 'keep-mine' : undefined;
634
+
635
+ try {
636
+ const result = await updateBundles({
637
+ packageRoot: PACKAGE_ROOT,
638
+ bundleKey: args.bundle,
639
+ targetBase: args.targetDir,
640
+ cliVersion: pkg.version,
641
+ strategy,
642
+ mcpConfigPath: args.targetConfig,
643
+ });
644
+
645
+ if (args.json) {
646
+ console.log(JSON.stringify(result, null, 2));
647
+ return result.exitCode;
648
+ }
649
+
650
+ if (result.bundles.length === 0) {
651
+ console.log(`No installed bundles found at ${result.targetBase} — nothing to update.`);
652
+ return 0;
653
+ }
654
+
655
+ for (const b of result.bundles) {
656
+ console.log(summarizeBundleUpdate(b));
657
+ if (b.unresolvedConflicts.length > 0) {
658
+ console.log(` Unresolved: ${b.unresolvedConflicts.join(', ')}`);
659
+ }
660
+ }
661
+
662
+ if (result.exitCode !== 0) {
663
+ console.error(
664
+ `\n${result.unresolvedConflicts.length} file(s) have unresolved conflicts (edited locally AND changed ` +
665
+ 'upstream) — nothing was changed for them. Re-run with --theirs (take the new version) or --keep-mine ' +
666
+ '(keep your version) to resolve non-interactively, or run this in a terminal to be prompted per file.'
667
+ );
668
+ }
669
+
670
+ return result.exitCode;
671
+ } catch (err) {
672
+ if (err instanceof UpdateError || err instanceof ManifestError || err instanceof LedgerError || err instanceof WiringError) {
673
+ console.error(err.message);
674
+ return 1;
675
+ }
676
+ throw err;
677
+ }
678
+ }
679
+
680
+ async function main(argv) {
681
+ const [command, ...rest] = argv;
682
+
683
+ if (command === '--version' || command === '-v') {
684
+ console.log(pkg.version);
685
+ return 0;
686
+ }
687
+
688
+ if (command === '--help' || command === '-h' || command === undefined) {
689
+ printHelp();
690
+ return 0;
691
+ }
692
+
693
+ if (command === 'install') {
694
+ return runInstall(rest);
695
+ }
696
+
697
+ if (command === 'uninstall') {
698
+ return runUninstall(rest);
699
+ }
700
+
701
+ if (command === 'secrets') {
702
+ return runSecrets(rest);
703
+ }
704
+
705
+ if (command === 'update') {
706
+ return runUpdate(rest);
707
+ }
708
+
709
+ console.error(`Unknown command: ${command}`);
710
+ printHelp();
711
+ return 1;
712
+ }
713
+
714
+ main(process.argv.slice(2))
715
+ .then((code) => {
716
+ process.exitCode = code;
717
+ })
718
+ .catch((err) => {
719
+ console.error(err.stack || err.message);
720
+ process.exitCode = 1;
721
+ });