aegiscode 6.8.3 → 6.8.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +2 -2
  2. package/bin/aegiscode.js +35 -5
  3. package/package.json +1 -6
  4. package/scripts/predist.mjs +99 -0
  5. package/src/agents.js +1 -1
  6. package/src/app.js +41 -9
  7. package/src/caps.js +1 -1
  8. package/src/chatflow.js +182 -34
  9. package/src/checkpoint.js +1 -1
  10. package/src/clipboard.js +1 -1
  11. package/src/commands.js +158 -21
  12. package/src/config.js +2 -2
  13. package/src/deps.js +2 -1
  14. package/src/devrun.js +1 -1
  15. package/src/diff.js +1 -1
  16. package/src/events.js +38 -15
  17. package/src/export.js +1 -1
  18. package/src/fuzzy.js +1 -1
  19. package/src/history.js +3 -3
  20. package/src/init.js +1 -1
  21. package/src/input.js +1 -1
  22. package/src/keys.js +1 -1
  23. package/src/markdown.js +2 -2
  24. package/src/mcp.js +683 -0
  25. package/src/overlays.js +2 -2
  26. package/src/panels.js +52 -19
  27. package/src/permissions.js +2 -2
  28. package/src/render.js +2 -2
  29. package/src/screen.js +133 -8
  30. package/src/screens.js +1 -1
  31. package/src/summarize.js +1 -1
  32. package/src/system.js +2 -2
  33. package/src/theme.js +6 -6
  34. package/src/title.js +217 -0
  35. package/src/tokens.js +75 -96
  36. package/src/update.js +75 -1
  37. package/vendor/desktop/lib/local/agents.js +1 -1
  38. package/vendor/desktop/lib/local/autonomous.js +1 -1
  39. package/vendor/desktop/lib/local/engine.js +32 -8
  40. package/vendor/desktop/lib/local/git-scope.js +1 -1
  41. package/vendor/desktop/lib/local/prompt.js +3 -3
  42. package/vendor/desktop/lib/local/queue.js +2 -2
  43. package/vendor/desktop/lib/local/shell.js +1 -1
  44. package/vendor/desktop/lib/local/tools.js +2 -2
  45. package/vendor/desktop/lib/local/turn-guard.js +1 -1
  46. package/vendor/desktop/lib/local/worktree-lock.js +1 -1
  47. package/vendor/desktop/lib/settings.js +67 -0
  48. package/vendor/desktop/renderer/usage.js +377 -46
  49. package/vendor/hosts/install.js +638 -0
  50. package/vendor/hosts/openai-shim.js +419 -0
  51. package/vendor/hosts/spec.js +164 -0
  52. package/vendor/hosts/targets.js +346 -0
  53. package/vendor/mcp/server.js +186 -0
package/src/mcp.js ADDED
@@ -0,0 +1,683 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * `aegiscode mcp …` — the host that puts AEGIS inside every coding program.
5
+ *
6
+ * The other three hosts answer "talk to AEGIS from here". This one answers
7
+ * "make AEGIS appear in the editor I already use", and it does that in the two
8
+ * ways an editor can accept it:
9
+ *
10
+ * - MCP. `install` writes the editor's own config so its agent mode gains the
11
+ * tools in `mcp/tools.js`. The server is `mcp/server.js`, spawned over
12
+ * stdio by the editor itself — never by us.
13
+ * - An OpenAI-compatible endpoint. `shim` runs `hosts/openai-shim.js`, for
14
+ * clients that let you type a base URL but speak no MCP.
15
+ *
16
+ * Everything mechanical lives in `hosts/`: the host registry (paths, dialects),
17
+ * the canonical server spec, and the merge-only installer. Those are shared
18
+ * with any other host that wants them and are staged into `cli/vendor/hosts/`
19
+ * at publish time, exactly like `client/` and `mcp/` — so this file is argv →
20
+ * those calls, and the honest report of what came back.
21
+ *
22
+ * Two properties this surface must not lose, because losing either one damages
23
+ * a file the user did not ask us to touch:
24
+ *
25
+ * 1. NO SECRET IS WRITTEN BY DEFAULT. These config files are plain, often
26
+ * world-readable, and frequently inside a committed project directory. The
27
+ * server already resolves a key from the environment, then the 0600 store,
28
+ * then `~/.aegiscode/.env`. `--with-key` is the escape hatch and
29
+ * `--prompt-key` is the one host (VS Code) that can hold no value at all.
30
+ * 2. AN UNPARSEABLE CONFIG IS REFUSED, NOT OVERWRITTEN. The installer returns
31
+ * an error and the file is left exactly as it was; a JSON syntax error we
32
+ * "fixed" would silently discard whatever the user had in there.
33
+ *
34
+ * Exit codes, same contract as the autonomous surface:
35
+ * 0 everything asked for happened
36
+ * 1 a config could not be read/parsed, or a write failed
37
+ * 2 usage error
38
+ */
39
+
40
+ const path = require('node:path');
41
+ const { spawn } = require('node:child_process');
42
+
43
+ // Paths only, no eager requires: `sharedpaths.js` is what the rest of the CLI
44
+ // uses to find the shared modules in both layouts (a source checkout and an
45
+ // installed package), and `hosts/` is staged into the same vendor tree.
46
+ const { resolveShared } = require('./sharedpaths.js');
47
+
48
+ const install = require(resolveShared(path.join('hosts', 'install.js')));
49
+ const targets = require(resolveShared(path.join('hosts', 'targets.js')));
50
+ const spec = require(resolveShared(path.join('hosts', 'spec.js')));
51
+
52
+ const SUBCOMMANDS = new Set([
53
+ 'install', 'remove', 'status', 'list', 'print', 'serve', 'shim', 'help',
54
+ ]);
55
+
56
+ const USAGE = `aegiscode mcp — put AEGIS inside your editor.
57
+
58
+ Usage:
59
+ aegiscode mcp install [options] write the editor config (merges, never replaces)
60
+ aegiscode mcp status [options] which hosts are configured, and do they still work
61
+ aegiscode mcp list every supported host, its config file and its docs
62
+ aegiscode mcp print <host> show the entry that would be written, touch nothing
63
+ aegiscode mcp remove [options] take our entry out again
64
+ aegiscode mcp serve run the stdio MCP server (editors spawn this themselves)
65
+ aegiscode mcp shim [options] run the OpenAI-compatible endpoint on loopback
66
+
67
+ Targets:
68
+ --target <id> one host, repeatable and comma-separated (see \`aegiscode mcp list\`)
69
+ --all every supported host, not just the ones detected
70
+ --scope <s> user (default) or workspace — workspace writes into the
71
+ current directory, which is committed in many projects
72
+
73
+ Install options:
74
+ --dry-run print what would change, write nothing
75
+ --with-key embed the resolved API key in the config file. Off by
76
+ default: these files are plain and often world-readable, and
77
+ the server already finds a key from the environment, the
78
+ 0600 store, or ~/.aegiscode/.env
79
+ --prompt-key VS Code only: reference its own secret prompt instead of
80
+ storing a value anywhere
81
+ --base <url> API base to record (default $AEGIS_API_BASE or aegiscloud.org)
82
+
83
+ Shim options:
84
+ --port <n> default 8787
85
+ --host <addr> default 127.0.0.1; any non-loopback address also requires
86
+ --allow-remote ... this flag, because the endpoint spends your tokens
87
+
88
+ Options:
89
+ --json machine-readable output
90
+ -h, --help this text
91
+ `;
92
+
93
+ // ---------------------------------------------------------------------------
94
+ // argv
95
+ // ---------------------------------------------------------------------------
96
+
97
+ const BOOL_FLAGS = new Set([
98
+ 'json', 'all', 'dry-run', 'with-key', 'prompt-key', 'yes', 'allow-remote', 'help',
99
+ ]);
100
+ const VALUE_FLAGS = new Set(['target', 'scope', 'base', 'port', 'host']);
101
+
102
+ /**
103
+ * Parse the subcommand's own argv.
104
+ *
105
+ * Its own parser rather than bin/aegiscode.js's, for the reason the autonomous
106
+ * surface has one: the top-level parser owns the session flags, and everything
107
+ * after `mcp <sub>` belongs to the subcommand.
108
+ */
109
+ function parseFlags(argv) {
110
+ const opts = { terms: [], json: false, flags: {}, targetList: [] };
111
+ for (let i = 0; i < argv.length; i++) {
112
+ const a = argv[i];
113
+ if (a === '--json') {
114
+ opts.json = true;
115
+ continue;
116
+ }
117
+ if (a === '-h') {
118
+ opts.flags.help = true;
119
+ continue;
120
+ }
121
+ if (!a.startsWith('--')) {
122
+ opts.terms.push(a);
123
+ continue;
124
+ }
125
+ const [rawName, inline] = a.slice(2).split('=');
126
+ const name = rawName.trim();
127
+ if (BOOL_FLAGS.has(name)) {
128
+ opts.flags[name] = true;
129
+ continue;
130
+ }
131
+ if (!VALUE_FLAGS.has(name)) throw new Error(`unknown option: --${name}`);
132
+ const value = inline !== undefined ? inline : argv[++i];
133
+ if (value === undefined) throw new Error(`--${name} needs a value`);
134
+ if (name === 'target') {
135
+ // `--target cursor --target zed` and `--target cursor,zed` are the same
136
+ // request; both spellings are common enough to be worth accepting.
137
+ for (const id of String(value).split(',')) {
138
+ const trimmed = id.trim();
139
+ if (trimmed) opts.targetList.push(trimmed);
140
+ }
141
+ continue;
142
+ }
143
+ opts.flags[name] = value;
144
+ }
145
+ return opts;
146
+ }
147
+
148
+ /**
149
+ * Resolve `--target` / `--all` / detection into a concrete list of targets.
150
+ *
151
+ * The default matters: with no flag, only hosts that are actually INSTALLED on
152
+ * this machine are touched. Writing a Cursor config for somebody who has never
153
+ * installed Cursor is not helpful, it is a file appearing out of nowhere.
154
+ *
155
+ * @returns {{targets: object[], ids: string[], source: string, unknown: string[]}}
156
+ */
157
+ function selectTargets(opts, ctx, io) {
158
+ const unknown = [];
159
+ let ids = [];
160
+ let source;
161
+
162
+ if (opts.targetList.length) {
163
+ source = 'named';
164
+ for (const id of opts.targetList) {
165
+ const target = targets.getTarget(id);
166
+ if (target) ids.push(target.id);
167
+ else unknown.push(id);
168
+ }
169
+ ids = [...new Set(ids)];
170
+ } else if (opts.flags.all) {
171
+ source = 'all';
172
+ ids = targets.targetIds();
173
+ } else {
174
+ source = 'detected';
175
+ ids = [...install.detected({ ctx })];
176
+ // Detection works by finding a config file or an app-support directory, so
177
+ // an editor that is installed but has never written a config is invisible
178
+ // here. That is the honest reading of "detected", and the report says so.
179
+ }
180
+
181
+ return { targets: ids.map((id) => targets.getTarget(id)).filter(Boolean), ids, source, unknown };
182
+ }
183
+
184
+ /** The spec opts the flags imply. Nothing secret is included unless asked. */
185
+ function specOptsFor(opts, io) {
186
+ const specOpts = {};
187
+ if (opts.flags.base) specOpts.apiBase = String(opts.flags.base);
188
+ if (opts.flags['prompt-key']) specOpts.promptKey = true;
189
+ if (opts.flags['with-key']) {
190
+ const credentials = require('./credentials.js');
191
+ const st = credentials.keyStatus();
192
+ if (!st.configured) {
193
+ io.stderr.write(
194
+ 'aegiscode mcp: --with-key was given but no key is configured. ' +
195
+ 'Run `aegiscode login` first, or export AEGIS_API_KEY.\n'
196
+ );
197
+ return null;
198
+ }
199
+ specOpts.apiKey = st.key;
200
+ }
201
+ return specOpts;
202
+ }
203
+
204
+ /**
205
+ * `--scope`, validated against what the target actually supports.
206
+ *
207
+ * `quiet` swallows the "has no X config" message: `--all` and detected sweeps
208
+ * hit hosts like Claude Code (workspace-only) as a matter of course, and that
209
+ * is not a failure worth a stderr line — a target named explicitly with
210
+ * `--target` gets the loud version, because there the mismatch is the whole
211
+ * ask.
212
+ */
213
+ function scopeFor(target, opts, io, { quiet = false } = {}) {
214
+ const scope = String(opts.flags.scope || 'user').toLowerCase();
215
+ if (scope !== 'user' && scope !== 'workspace' && scope !== 'project') return null;
216
+ const normalized = scope === 'project' ? 'workspace' : scope;
217
+ if (!(target.scopes || ['user']).includes(normalized)) {
218
+ if (!quiet) {
219
+ io.stderr.write(
220
+ `aegiscode mcp: ${target.label} has no ${normalized} config — ` +
221
+ `it supports: ${(target.scopes || ['user']).join(', ')}\n`
222
+ );
223
+ }
224
+ return null;
225
+ }
226
+ return normalized;
227
+ }
228
+
229
+ // ---------------------------------------------------------------------------
230
+ // Reporting
231
+ // ---------------------------------------------------------------------------
232
+
233
+ function homeShort(p, ctx) {
234
+ const home = ctx.home || ctx.env.HOME || ctx.env.USERPROFILE;
235
+ if (home && p.startsWith(home)) return `~${p.slice(home.length)}`;
236
+ return p;
237
+ }
238
+
239
+ function statusWord(row) {
240
+ if (row.error) return 'unreadable';
241
+ if (!row.installed) return row.exists ? 'not installed' : 'no config';
242
+ if (row.serverExists === false) return 'BROKEN';
243
+ if (row.serverUnverifiable) return 'host-resolved';
244
+ return 'installed';
245
+ }
246
+
247
+ function statusText(rows, ctx, io) {
248
+ const w = Math.max(9, ...rows.map((r) => statusWord(r).length));
249
+ const lines = [];
250
+ for (const row of rows) {
251
+ lines.push(
252
+ ` ${statusWord(row).padEnd(w)} ${row.id.padEnd(14)} ` +
253
+ `${homeShort(row.file, ctx)}${row.scope === 'workspace' ? ' (workspace)' : ''}`
254
+ );
255
+ if (row.error) lines.push(` ${' '.repeat(w)} ${row.error}`);
256
+ if (row.serverExists === false) {
257
+ lines.push(
258
+ ` ${' '.repeat(w)} the server this names is gone: ${row.serverPath}` +
259
+ '\n' + ` ${' '.repeat(w)} re-run \`aegiscode mcp install --target ${row.id}\``
260
+ );
261
+ }
262
+ if (row.serverUnverifiable) {
263
+ lines.push(
264
+ ` ${' '.repeat(w)} path is host-resolved (${row.serverPath}) — the editor\n` +
265
+ ` ${' '.repeat(w)} expands it at load time, so it cannot be checked from here.`
266
+ );
267
+ }
268
+ }
269
+ return lines.join('\n') + '\n';
270
+ }
271
+
272
+ // ---------------------------------------------------------------------------
273
+ // Subcommands
274
+ // ---------------------------------------------------------------------------
275
+
276
+ function runList(opts, ctx, io) {
277
+ const detected = install.detected({ ctx });
278
+ const rows = targets.TARGETS.map((target) => ({
279
+ id: target.id,
280
+ label: target.label,
281
+ kind: target.kind,
282
+ scopes: target.scopes || ['user'],
283
+ docs: target.docs,
284
+ verified: Boolean(target.verified),
285
+ detected: detected.has(target.id),
286
+ files: (target.scopes || ['user']).map((scope) => target.path(scope, ctx)),
287
+ note: target.note || null,
288
+ }));
289
+
290
+ if (opts.json) {
291
+ io.stdout.write(`${JSON.stringify(rows, null, 2)}\n`);
292
+ return 0;
293
+ }
294
+
295
+ io.stdout.write(`${rows.length} hosts AEGIS can appear in:\n\n`);
296
+ for (const row of rows) {
297
+ io.stdout.write(
298
+ ` ${row.id.padEnd(16)} ${row.label}${row.detected ? ' [present on this machine]' : ''}\n`
299
+ );
300
+ io.stdout.write(` ${' '.repeat(16)} ${homeShort(row.files[0], ctx)} (${row.scopes.join(', ')})\n`);
301
+ if (row.note) io.stdout.write(` ${' '.repeat(16)} ${row.note}\n`);
302
+ if (!row.verified) {
303
+ io.stdout.write(
304
+ ` ${' '.repeat(16)} ✗ NOT VERIFIED against this host's own docs — check ${row.docs} ` +
305
+ 'before relying on it\n'
306
+ );
307
+ }
308
+ }
309
+ io.stdout.write(
310
+ '\n `aegiscode mcp install` with no --target configures every host detected above.\n' +
311
+ ' API keys are NOT written unless you pass --with-key.\n'
312
+ );
313
+ return 0;
314
+ }
315
+
316
+ function runStatus(opts, ctx, io) {
317
+ const sel = selectTargets(opts, ctx, io);
318
+ if (sel.unknown.length) {
319
+ io.stderr.write(
320
+ `aegiscode mcp: unknown host${sel.unknown.length > 1 ? 's' : ''}: ${sel.unknown.join(', ')}` +
321
+ ' — run `aegiscode mcp list`\n'
322
+ );
323
+ return 2;
324
+ }
325
+ // Bare `status` reports on the whole registry: "is AEGIS in my editors" is a
326
+ // question you ask before choosing a target, so restricting it to detected
327
+ // hosts would hide the answer. `--target` narrows it.
328
+ const scope = opts.flags.scope ? scopeFor(sel.targets[0], opts, io) : null;
329
+ if (opts.flags.scope && !scope) return 2;
330
+
331
+ const ids = opts.targetList.length ? sel.ids : [];
332
+ let rows = install.status(ids, { ctx });
333
+
334
+ if (!opts.flags.all && !opts.targetList.length) {
335
+ // Default view: rows that exist, plus anything of ours we can see. An entry
336
+ // in a config for an editor that is no longer installed still matters —
337
+ // that is exactly the stale config worth being told about.
338
+ rows = rows.filter((r) => r.exists || r.installed || r.error);
339
+ }
340
+
341
+ if (opts.json) {
342
+ io.stdout.write(
343
+ `${JSON.stringify(
344
+ rows.map((r) => ({
345
+ id: r.id,
346
+ label: r.label,
347
+ scope: r.scope,
348
+ file: r.file,
349
+ exists: r.exists,
350
+ installed: r.installed,
351
+ state: statusWord(r),
352
+ server_path: r.serverPath || null,
353
+ server_exists: r.serverExists === undefined ? null : r.serverExists,
354
+ server_unverifiable: Boolean(r.serverUnverifiable),
355
+ entry: r.entry,
356
+ error: r.error,
357
+ docs: r.docs,
358
+ verified: r.verified,
359
+ })),
360
+ null,
361
+ 2
362
+ )}\n`
363
+ );
364
+ return 0;
365
+ }
366
+
367
+ if (!rows.length) {
368
+ io.stdout.write(
369
+ 'aegiscode mcp: no editor configs found on this machine.\n' +
370
+ ' `aegiscode mcp list` shows every host AEGIS supports,\n' +
371
+ ' `aegiscode mcp install --target <id>` configures one.\n'
372
+ );
373
+ return 0;
374
+ }
375
+
376
+ io.stdout.write(statusText(rows, ctx, io));
377
+ const bad = rows.filter((r) => r.serverExists === false).length;
378
+ const held = rows.filter((r) => r.installed).length;
379
+ const unver = rows.filter((r) => r.serverUnverifiable).length;
380
+ io.stdout.write(
381
+ `\n ${held} configured` +
382
+ `${unver ? `, ${unver} host-resolved` : ''}` +
383
+ `${bad ? `, ${bad} pointing at a missing server — re-run install` : ''}.\n`
384
+ );
385
+ return 0;
386
+ }
387
+
388
+ function runInstall(opts, ctx, io) {
389
+ const sel = selectTargets(opts, ctx, io);
390
+ if (sel.unknown.length) {
391
+ io.stderr.write(
392
+ `aegiscode mcp: unknown host${sel.unknown.length > 1 ? 's' : ''}: ${sel.unknown.join(', ')}` +
393
+ ' — run `aegiscode mcp list`\n'
394
+ );
395
+ return 2;
396
+ }
397
+ if (!sel.targets.length) {
398
+ io.stderr.write(
399
+ 'aegiscode mcp: no editor detected, so there is nothing to configure automatically.\n' +
400
+ ' `aegiscode mcp list` shows the hosts AEGIS supports;\n' +
401
+ ' `aegiscode mcp install --target <id>` names one explicitly.\n'
402
+ );
403
+ return 2;
404
+ }
405
+
406
+ const specOpts = specOptsFor(opts, io);
407
+ if (!specOpts) return 2;
408
+ if (opts.flags['prompt-key'] && sel.targets.some((t) => !t.supportsKeyPrompt)) {
409
+ io.stderr.write(
410
+ 'aegiscode mcp: --prompt-key only works for VS Code, which is the only host ' +
411
+ 'with a secret-prompt mechanism. Drop it for the rest.\n'
412
+ );
413
+ return 2;
414
+ }
415
+
416
+ const resolved = spec.resolveServer();
417
+ const results = [];
418
+ let failed = 0;
419
+
420
+ for (const target of sel.targets) {
421
+ const named = sel.source === 'named';
422
+ const scope = scopeFor(target, opts, io, { quiet: !named });
423
+ if (!scope) {
424
+ if (named) {
425
+ failed++;
426
+ } else {
427
+ results.push({ id: target.id, file: null, applied: false, skipped: true });
428
+ io.stdout.write(`aegiscode mcp: ${target.label} — skipped (no ${String(opts.flags.scope || 'user')} config)\n`);
429
+ }
430
+ continue;
431
+ }
432
+ const plan = install.planTarget(target, scope, { ctx, specOpts });
433
+ if (plan.error) {
434
+ io.stderr.write(`aegiscode mcp: ${target.label} — ${plan.error.message}\n`);
435
+ results.push({ id: target.id, file: plan.file, error: plan.error.message, applied: false });
436
+ failed++;
437
+ continue;
438
+ }
439
+ if (!plan.changed) {
440
+ io.stdout.write(
441
+ `aegiscode mcp: ${target.label} — already configured (${homeShort(plan.file, ctx)})\n`
442
+ );
443
+ results.push({ id: target.id, file: plan.file, applied: false, changed: false });
444
+ continue;
445
+ }
446
+ if (opts.flags['dry-run']) {
447
+ results.push({ id: target.id, file: plan.file, applied: false, changed: true, dryRun: true });
448
+ io.stdout.write(
449
+ `aegiscode mcp: ${target.label} — would write ${homeShort(plan.file, ctx)}\n` +
450
+ `${indent(plan.after)}\n`
451
+ );
452
+ continue;
453
+ }
454
+ const done = install.apply(plan, { withKey: Boolean(opts.flags['with-key']) });
455
+ results.push({
456
+ id: target.id,
457
+ file: plan.file,
458
+ applied: done.applied,
459
+ changed: plan.changed,
460
+ backup: done.backupOf || null,
461
+ });
462
+ io.stdout.write(
463
+ `aegiscode mcp: ${target.label} — wrote ${homeShort(plan.file, ctx)}` +
464
+ `${done.backupOf ? ` (backup: ${homeShort(done.backupOf, ctx)})` : ''}\n`
465
+ );
466
+ }
467
+
468
+ if (!opts.flags['dry-run'] && !failed && results.some((r) => r.applied)) {
469
+ if (!resolved.exists) {
470
+ // Should be impossible: a plan that names a missing server is refused
471
+ // above. Reported anyway, because the failure mode (an editor that shows
472
+ // nothing and explains nothing) is expensive enough to guard twice.
473
+ io.stderr.write(
474
+ 'aegiscode mcp: WARNING — the server file does not exist at ' +
475
+ `${resolved.path}, so the editors just configured will not start it.\n`
476
+ );
477
+ failed++;
478
+ } else {
479
+ io.stdout.write(
480
+ '\n Restart the editor (or its MCP host) to pick this up. Configured hosts\n' +
481
+ ' spawn the AEGIS server themselves — nothing needs to keep running in a terminal.\n'
482
+ );
483
+ }
484
+ }
485
+ if (opts.flags['dry-run']) {
486
+ io.stdout.write('\naegiscode mcp: dry run — nothing was written.\n');
487
+ }
488
+
489
+ if (opts.json) {
490
+ io.stdout.write(`${JSON.stringify({ changed: results, server: resolved.path, exists: resolved.exists }, null, 2)}\n`);
491
+ }
492
+ return failed ? 1 : 0;
493
+ }
494
+
495
+ function indent(text) {
496
+ return String(text || '')
497
+ .split('\n')
498
+ .filter((l, i, a) => !(i === a.length - 1 && l === ''))
499
+ .map((l) => ` ${l}`)
500
+ .join('\n');
501
+ }
502
+
503
+ function runRemove(opts, ctx, io) {
504
+ const sel = selectTargets(opts, ctx, io);
505
+ if (sel.unknown.length) {
506
+ io.stderr.write(
507
+ `aegiscode mcp: unknown host${sel.unknown.length > 1 ? 's' : ''}: ${sel.unknown.join(', ')}\n`
508
+ );
509
+ return 2;
510
+ }
511
+ // Removal defaults to "anywhere we can see ourselves", not "detected hosts":
512
+ // an editor that has since been uninstalled still has a config on disk, and
513
+ // that is the one most worth cleaning up.
514
+ const ids = opts.targetList.length || opts.flags.all ? sel.ids : [];
515
+ const specOpts = {};
516
+ if (opts.flags.base) specOpts.apiBase = String(opts.flags.base);
517
+ const rows = install.status(ids, { ctx, specOpts }).filter((r) => r.installed);
518
+ let failed = 0;
519
+
520
+ if (!rows.length) {
521
+ io.stdout.write('aegiscode mcp: nothing to remove — no config names an AEGIS server.\n');
522
+ if (opts.json) io.stdout.write(`${JSON.stringify({ removed: [], changed: [] }, null, 2)}\n`);
523
+ return 0;
524
+ }
525
+
526
+ const changed = [];
527
+ for (const row of rows) {
528
+ const target = targets.getTarget(row.id);
529
+ const plan = install.planRemove(target, row.scope, { ctx, specOpts });
530
+ if (plan.error) {
531
+ io.stderr.write(`aegiscode mcp: ${row.label} — ${plan.error.message}\n`);
532
+ failed++;
533
+ continue;
534
+ }
535
+ if (!plan.changed) {
536
+ io.stdout.write(`aegiscode mcp: ${row.label} — nothing of ours in ${homeShort(plan.file, ctx)}\n`);
537
+ continue;
538
+ }
539
+ if (opts.flags['dry-run']) {
540
+ changed.push({ id: row.id, file: plan.file, dryRun: true });
541
+ io.stdout.write(`aegiscode mcp: ${row.label} — would update ${homeShort(plan.file, ctx)}\n`);
542
+ continue;
543
+ }
544
+ const done = install.apply(plan);
545
+ changed.push({ id: row.id, file: plan.file, backup: done.backupOf || null });
546
+ io.stdout.write(
547
+ `aegiscode mcp: ${row.label} — removed from ${homeShort(plan.file, ctx)}` +
548
+ `${done.backupOf ? ` (backup: ${homeShort(done.backupOf, ctx)})` : ''}\n`
549
+ );
550
+ }
551
+
552
+ if (opts.flags['dry-run']) io.stdout.write('\naegiscode mcp: dry run — nothing was written.\n');
553
+ if (opts.json) io.stdout.write(`${JSON.stringify({ changed }, null, 2)}\n`);
554
+ return failed ? 1 : 0;
555
+ }
556
+
557
+ function runPrint(opts, ctx, io) {
558
+ const id = opts.terms[0] || opts.targetList[0];
559
+ if (!id) {
560
+ io.stderr.write('aegiscode mcp print: name a host — `aegiscode mcp print vscode`\n');
561
+ return 2;
562
+ }
563
+ const target = targets.getTarget(id);
564
+ if (!target) {
565
+ io.stderr.write(`aegiscode mcp print: unknown host "${id}" — run \`aegiscode mcp list\`\n`);
566
+ return 2;
567
+ }
568
+ const specOpts = {};
569
+ if (opts.flags.base) specOpts.apiBase = String(opts.flags.base);
570
+ if (opts.flags['prompt-key']) specOpts.promptKey = true;
571
+ const built = spec.buildSpec(specOpts);
572
+ const entry = install.renderEntry(target, built);
573
+ const file = target.path(target.scopes ? target.scopes[0] : 'user', ctx);
574
+
575
+ if (target.kind === 'mcp-toml') {
576
+ io.stdout.write(`# ${file}\n[${target.container}.${entry.name || 'aegis'}]\n${entry.join('\n')}\n`);
577
+ return 0;
578
+ }
579
+ if (opts.json) {
580
+ io.stdout.write(`${JSON.stringify({ file, container: target.container, entry }, null, 2)}\n`);
581
+ return 0;
582
+ }
583
+ io.stdout.write(`# ${file}\n${JSON.stringify({ [target.container]: { aegis: entry } }, null, 2)}\n`);
584
+ if (opts.flags['prompt-key']) {
585
+ io.stdout.write(
586
+ `\n# VS Code also needs this in the same file so the prompt can resolve:\n` +
587
+ `${JSON.stringify({ inputs: [spec.vscodeKeyInput()] }, null, 2)}\n`
588
+ );
589
+ }
590
+ return 0;
591
+ }
592
+
593
+ /**
594
+ * Run a staged script as a child with our own stdio attached.
595
+ *
596
+ * Both long-running surfaces are launched as CHILDREN rather than required into
597
+ * this process, and that is not a stylistic choice: `mcp/server.js` registers
598
+ * its stdin handlers at load time and exports nothing, and the shim owns its own
599
+ * listener and shutdown path. Spawning them means the two behave identically to
600
+ * the way an editor starts them, and this host keeps its "main() returns an exit
601
+ * code" lifecycle instead of having to hold the process open by hand.
602
+ */
603
+ function runChild(script, args, io) {
604
+ return new Promise((resolve) => {
605
+ const child = spawn(process.execPath, [script, ...args], { stdio: 'inherit' });
606
+ child.on('error', (err) => {
607
+ io.stderr.write(`aegiscode mcp: could not start ${script}: ${err.message}\n`);
608
+ resolve(1);
609
+ });
610
+ child.on('exit', (code, signal) => {
611
+ if (signal) resolve(0); // ctrl+c: the user asked for it, not a failure
612
+ else resolve(code === null ? 1 : code);
613
+ });
614
+ });
615
+ }
616
+
617
+ function runServe(opts, ctx, io) {
618
+ const resolved = spec.resolveServer();
619
+ if (!resolved.exists) {
620
+ io.stderr.write(
621
+ `aegiscode mcp serve: no server found at ${resolved.path}.\n` +
622
+ ` Looked in:\n ${resolved.candidates.join('\n ')}\n`
623
+ );
624
+ return 2;
625
+ }
626
+ io.stderr.write(
627
+ `aegiscode mcp: serving ${resolved.path} on stdio.\n` +
628
+ ' Editors start this themselves — you only need it to test one by hand.\n'
629
+ );
630
+ return runChild(resolved.path, [], io);
631
+ }
632
+
633
+ function runShim(opts, ctx, io) {
634
+ const shim = resolveShared(path.join('hosts', 'openai-shim.js'));
635
+ const args = [];
636
+ if (opts.flags.port) args.push('--port', String(opts.flags.port));
637
+ if (opts.flags.host) args.push('--host', String(opts.flags.host));
638
+ if (opts.flags['allow-remote']) args.push('--allow-remote');
639
+ return runChild(shim, args, io);
640
+ }
641
+
642
+ // ---------------------------------------------------------------------------
643
+ // Entry point
644
+ // ---------------------------------------------------------------------------
645
+
646
+ async function runMcpCommand(command, argv, io = {}) {
647
+ const stdout = io.stdout || process.stdout;
648
+ const stderr = io.stderr || process.stderr;
649
+ const out = { stdout, stderr };
650
+
651
+ let opts;
652
+ try {
653
+ opts = parseFlags(argv || []);
654
+ } catch (e) {
655
+ stderr.write(`aegiscode mcp: ${e.message}\n`);
656
+ return 2;
657
+ }
658
+ opts.json = Boolean(io.json || opts.json);
659
+ out.json = opts.json;
660
+
661
+ if (command === 'help' || !SUBCOMMANDS.has(command) || opts.flags.help) {
662
+ stdout.write(USAGE);
663
+ return command === 'help' || opts.flags.help ? 0 : 2;
664
+ }
665
+ if (command === 'serve' || command === 'shim') {
666
+ const ctx = install.hostCtx({ cwd: io.cwd || process.cwd(), home: io.home || null });
667
+ return command === 'serve' ? runServe(opts, ctx, out) : runShim(opts, ctx, out);
668
+ }
669
+ if (command === 'list') {
670
+ return runList(opts, install.hostCtx({ cwd: io.cwd || process.cwd(), home: io.home || null }), out);
671
+ }
672
+ if (command === 'print') {
673
+ return runPrint(opts, install.hostCtx({ cwd: io.cwd || process.cwd(), home: io.home || null }), out);
674
+ }
675
+
676
+ const ctx = install.hostCtx({ cwd: io.cwd || process.cwd(), home: io.home || null });
677
+ if (command === 'install') return runInstall(opts, ctx, out);
678
+ if (command === 'remove') return runRemove(opts, ctx, out);
679
+ if (command === 'status') return runStatus(opts, ctx, out);
680
+ return 2;
681
+ }
682
+
683
+ module.exports = { runMcpCommand, parseFlags, selectTargets, USAGE, SUBCOMMANDS };
package/src/overlays.js CHANGED
@@ -3,7 +3,7 @@
3
3
  /**
4
4
  * Overlay renderers — the "/" command palette, the alt+p model picker, the
5
5
  * /effort picker and the /resume session list. Ported from
6
- * `aegiscodex-dev/src/commands.js` (which mirrors live captures of Claude Code
6
+ * the upstream engine reference (which mirrors live captures of Claude Code
7
7
  * 2.1.228: a gray `─` rule, a lavender `❯` cursor, a blue selected row, a
8
8
  * `⎿ Usage: /x hint` hook under the focused command and a `·`-separated footer).
9
9
  *
@@ -58,7 +58,7 @@ function fit(lines, width) {
58
58
  /** A full-width blank row. */
59
59
  const blank = (width) => [span('', ' '.repeat(Math.max(0, width)))];
60
60
 
61
- // Phase 10b (2.1.228 port): split a command name into spans that bold the
61
+ // Split a command name into spans that bold the
62
62
  // characters which matched the query; the selected row reads blue.
63
63
  function boldMatched(query, name, colour) {
64
64
  const pos = fuzzy && typeof fuzzy.fuzzyMatchPositions === 'function'