aegiscode 7.0.13 → 7.0.15

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 (109) hide show
  1. package/SOURCE-OFFER.txt +9 -0
  2. package/package.json +3 -2
  3. package/scripts/check.mjs +1 -52
  4. package/scripts/demo.mjs +1 -94
  5. package/scripts/predist.mjs +1 -75
  6. package/scripts/runtests.mjs +1 -56
  7. package/scripts/seal-gate.mjs +1 -74
  8. package/src/agents.js +1 -139
  9. package/src/app.js +1 -2932
  10. package/src/art.js +1 -289
  11. package/src/chatflow.js +1 -3008
  12. package/src/checkpoint.js +1 -90
  13. package/src/clipboard.js +1 -424
  14. package/src/cloudsync.js +1 -528
  15. package/src/commands.js +1 -3987
  16. package/src/config.js +1 -581
  17. package/src/connect.js +1 -349
  18. package/src/credentials.js +1 -33
  19. package/src/deps.js +1 -232
  20. package/src/devrun.js +1 -187
  21. package/src/diff.js +1 -333
  22. package/src/diffview.js +1 -296
  23. package/src/engine.js +1 -297
  24. package/src/entitlement.js +1 -355
  25. package/src/events.js +1 -707
  26. package/src/export.js +1 -67
  27. package/src/fingerprint.js +1 -592
  28. package/src/format.js +1 -259
  29. package/src/fuzzy.js +1 -119
  30. package/src/history.js +1 -401
  31. package/src/init.js +1 -175
  32. package/src/input.js +1 -139
  33. package/src/keys.js +1 -183
  34. package/src/markdown.js +1 -306
  35. package/src/models.js +1 -487
  36. package/src/naming.js +1 -229
  37. package/src/overlays.js +1 -461
  38. package/src/panels.js +1 -1418
  39. package/src/ping.js +1 -226
  40. package/src/presence.js +1 -238
  41. package/src/render.js +1 -515
  42. package/src/screen.js +1 -518
  43. package/src/screens.js +1 -896
  44. package/src/secret.js +1 -59
  45. package/src/securefs.js +1 -359
  46. package/src/settings.js +1 -155
  47. package/src/shared.js +1 -52
  48. package/src/sharedpaths.js +1 -53
  49. package/src/signup.js +1 -156
  50. package/src/summarize.js +1 -95
  51. package/src/sysdiag.js +1 -585
  52. package/src/system.js +1 -40
  53. package/src/theme.js +1 -570
  54. package/src/title.js +1 -220
  55. package/src/todos.js +1 -115
  56. package/src/tokens.js +1 -263
  57. package/src/topup.js +1 -210
  58. package/src/update.js +1 -181
  59. package/vendor/client/aegis.js +1 -2054
  60. package/vendor/client/attest.js +1 -442
  61. package/vendor/client/authorship-key.js +1 -410
  62. package/vendor/client/auto-provision.js +1 -134
  63. package/vendor/client/brain-catalog.js +1 -268
  64. package/vendor/client/byok-catalog.js +1 -230
  65. package/vendor/client/credentials.js +1 -494
  66. package/vendor/client/device-fingerprint.js +1 -141
  67. package/vendor/client/drive-connect.js +1 -85
  68. package/vendor/client/drive-upload.js +1 -174
  69. package/vendor/client/env-file.js +1 -1273
  70. package/vendor/client/fingerprint.js +1 -1064
  71. package/vendor/client/foreign-memory.js +1 -669
  72. package/vendor/client/google-signin.js +1 -125
  73. package/vendor/client/hooks.js +1 -430
  74. package/vendor/client/model-discovery.js +1 -330
  75. package/vendor/client/platform.js +1 -937
  76. package/vendor/client/prefs.js +1 -351
  77. package/vendor/client/presence-constants.js +1 -107
  78. package/vendor/client/presence.js +1 -438
  79. package/vendor/client/record-vault.js +3 -1055
  80. package/vendor/client/session-store.js +1 -548
  81. package/vendor/client/topup.js +1 -297
  82. package/vendor/client/touch.js +1 -458
  83. package/vendor/client/update.js +1 -704
  84. package/vendor/client/user-models.js +1 -381
  85. package/vendor/desktop/lib/local/agents.js +1 -105
  86. package/vendor/desktop/lib/local/autonomous.js +1 -1045
  87. package/vendor/desktop/lib/local/claude-pro.js +1 -993
  88. package/vendor/desktop/lib/local/context.js +1 -95
  89. package/vendor/desktop/lib/local/engine.js +1 -3228
  90. package/vendor/desktop/lib/local/entitlement.js +1 -654
  91. package/vendor/desktop/lib/local/git-scope.js +1 -228
  92. package/vendor/desktop/lib/local/local.js +1 -2135
  93. package/vendor/desktop/lib/local/prompt.js +1 -275
  94. package/vendor/desktop/lib/local/queue.js +1 -560
  95. package/vendor/desktop/lib/local/session-rounds.js +1 -208
  96. package/vendor/desktop/lib/local/shell.js +1 -680
  97. package/vendor/desktop/lib/local/tools.js +1 -1238
  98. package/vendor/desktop/lib/local/turn-guard.js +1 -300
  99. package/vendor/desktop/lib/local/worktree-lock.js +1 -235
  100. package/vendor/desktop/lib/settings.js +1 -890
  101. package/vendor/desktop/renderer/usage.js +1 -1239
  102. package/vendor/hosts/install.js +1 -638
  103. package/vendor/hosts/openai-shim.js +1 -515
  104. package/vendor/hosts/spec.js +1 -164
  105. package/vendor/hosts/targets.js +1 -346
  106. package/vendor/mcp/server.js +1 -221
  107. package/vendor/mcp/tools.js +1 -408
  108. package/vendor/one/src/child.js +1 -285
  109. package/vendor/one/src/permissions.js +1 -369
package/src/commands.js CHANGED
@@ -1,3989 +1,3 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
- // Conveying a modified copy, or running one as a network service, owes the
5
- // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
- 'use strict';
7
-
8
- /**
9
- * Slash commands — the CLI's full command vocabulary, ported from the sibling
10
- * the upstream engine client (`src/registry.js`), on top of the AEGIS tool registry
11
- * (`mcp/tools.js`).
12
- *
13
- * Three kinds of entry live in one table:
14
- *
15
- * (a) handler — a local `async (c, args) => bool` that runs against the
16
- * frozen command context `c` (see `cli/src/app.js`). It returns false to
17
- * end the session. This is the reference's own contract, so a handler
18
- * body reads the same here as it does in the upstream engine — only the panels
19
- * and support modules it calls are this client's.
20
- * (b) tool-backed — names a tool from `mcp/tools.js` and carries a
21
- * `build(arg) -> object` that turns the typed argument into the tool's
22
- * JSON. `test/cli-tools.test.mjs` asserts both directions: no command
23
- * points at a tool that does not exist, and no tool in the registry is
24
- * unreachable from the prompt (the `/tool` escape hatch keeps the latter
25
- * true for tools with no dedicated command).
26
- * (c) unavailable — a command whose whole premise is the Claude Code CLI's
27
- * own auth loop (`login`, `logout`). These carry an honest `unavailable`
28
- * reason and a working `alt`; `parseLine` returns `{ kind: 'unavailable' }`
29
- * and `app.js` prints the reason rather than a fake success.
30
- *
31
- * The names, aliases, categories and descriptions come from the upstream engine's
32
- * `COMMANDS`/`CATEGORIES`. Where this client's capability genuinely differs from
33
- * the reference's the handler says so honestly (a note, an honest panel, or a
34
- * real command run through the ported support modules) rather than copying a
35
- * sentence that would be untrue.
36
- *
37
- * Every command is defined against the FROZEN command context `c`:
38
- * c.ctx (mutable session context), c.sessionId, c.transcript,
39
- * c.push/note/panel, c.render, c.openOverlay, c.closeOverlay, c.askInput,
40
- * c.withWorking, c.runPrompt, c.ask, c.runTool, c.refreshSpend, c.state,
41
- * c.setInput, c.exit, c.client, c.TOOLS, c.saveConfig, c.showThemePicker.
42
- *
43
- * Plain text (no leading `/`) is a prompt: it goes to the pooled brain.
44
- */
45
-
46
- const fs = require('node:fs');
47
- const os = require('node:os');
48
- const path = require('node:path');
49
- const { execSync } = require('node:child_process');
50
-
51
- const { span } = require('./screen.js');
52
- const { C, BOLD, BOLD_OFF, THEME_TABLE, themeContradicts } = require('./theme.js');
53
- // `caps.js` is dependency-free (it requires nothing), so this cannot cycle the
54
- // way a `theme.js` → `art.js` → `theme.js` require would.
55
- const { caps, setCaps, resetCaps, describe, probeTerminalBackground } = require('./caps.js');
56
- const panels = require('./panels.js');
57
- const overlays = require('./overlays.js');
58
- const {
59
- updateConfig, loadConfig, loadPermissions, savePermissions, addPermissionRule,
60
- DEFAULT_PERMISSIONS, permissionsPath, configPath, aegisDir,
61
- // ON8 / D8 rule 1: the posture writers. Every "confirmations on/off" command
62
- // below goes through these rather than writing `defaultMode` itself, so the
63
- // window's switch and this face's gate cannot end up holding two answers.
64
- setConfirmPosture, setPermissionDefaultMode, confirmPosture,
65
- memoryPersistState, setMemoryPersist,
66
- } = require('./config.js');
67
- const { auditExposure, repairExposure } = require('./securefs.js');
68
- const { copyToClipboard } = require('./clipboard.js');
69
- const { snapshotCheckpoint, listCheckpoints, loadCheckpoint } = require('./checkpoint.js');
70
- const { signupUrl, goUrl } = require('./signup.js');
71
- const screens = require('./screens.js');
72
- const { summarizeTranscript, recapLine } = require('./summarize.js');
73
- const { sessionAccounting, accountingFromUsage, estimateTokens } = require('./tokens.js');
74
- // The one effort normaliser, so `/config effort <x>` writes the same rung the
75
- // turn will send (see effortRung in engine.js — it is what app.js puts on the
76
- // request).
77
- const { effortRung } = require('./engine.js');
78
- const { transcriptToMarkdown, transcriptToJSON, writeExportFile, lastAssistantText } = require('./export.js');
79
- const { detectDevCommand, runDevServer } = require('./devrun.js');
80
- // /ping — the terminal half of the desktop's "reply ready" alert. Pure and
81
- // dependency-free (no config, no TTY), so it is unit-testable on its own.
82
- const {
83
- PING_MODES, DEFAULT_PING_MODE, normalizePingMode, normalizePingSeconds,
84
- buildPing, writePing,
85
- } = require('./ping.js');
86
- // /todos — the session list. Owns its own file; shares only `aegisDir`.
87
- const { addTodo, completeTodo, clearTodos, formatTodos, todosFile } = require('./todos.js');
88
- // /config — the settings surface. Store-aware, so it cannot write a preference
89
- // to the host file (or the reverse) and re-open the drift ON8/D8 closed.
90
- const {
91
- configRows, formatConfigRows, setConfigValue, resetConfigValue,
92
- fullValue, summarizeValue, configStore,
93
- } = require('./settings.js');
94
- const credentials = require('./credentials.js');
95
- const cloudsync = require('./cloudsync.js');
96
- const { maskKey, fmtTokens, shortCwd } = require('./format.js');
97
- const { pickerEntries } = require('./models.js');
98
- const { resolveShared } = require('./sharedpaths.js');
99
- const { createCliEntitlement, paymentView, probeFee } = require('./entitlement.js');
100
- const { openUrl, URLS } = require('./system.js');
101
- // The machine checks behind `/doctor system` — see cli/src/sysdiag.js for why
102
- // they exist and why they never mutate anything.
103
- const sysdiag = require('./sysdiag.js');
104
- const { sniffProject, buildAegisMd } = require('./init.js');
105
- const {
106
- upgradeAdvice, latestPublishedVersion, applyUpgrade, installMethod,
107
- } = require('./update.js');
108
- const {
109
- AGENT_PRESETS, agentRoles, composeAgentPrompt, composeResearchPrompt, composeDebatePrompt,
110
- } = require('./agents.js');
111
- const {
112
- aggregateSessionUsage, pruneSessionHistory, readResumeList,
113
- } = require('./history.js');
114
- // Guarded: a concurrent workstream owns ./markdown.js.
115
- let markdownModule = null;
116
- try {
117
- // eslint-disable-next-line global-require
118
- markdownModule = require('./markdown.js');
119
- } catch {
120
- markdownModule = null;
121
- }
122
-
123
- const VERSION = require('../package.json').version;
124
-
125
- // ── Categories ────────────────────────────────────────────────────────────────
126
-
127
- const CATEGORIES = [
128
- { id: 'session', label: 'Session & context' },
129
- { id: 'workspace', label: 'Workspace' },
130
- { id: 'model', label: 'Model & behavior' },
131
- { id: 'data', label: 'Data' },
132
- { id: 'auth', label: 'Auth' },
133
- { id: 'support', label: 'Support' },
134
- { id: 'fun', label: 'Fun' },
135
- { id: 'aegis', label: 'Aegis plugin' },
136
- { id: 'custom', label: 'Custom' },
137
- ];
138
-
139
- const categoryLabel = (id) => (CATEGORIES.find((cat) => cat.id === id) || {}).label || id;
140
-
141
- // One table, shared with the picker that draws it. The two used to be separate
142
- // lists — this one a string array, chatflow.js's own copy of the same three
143
- // strings, and overlays.js's label/note rows — so adding a level meant editing
144
- // three places, and the index a picker row reported was mapped back to a value
145
- // through whichever list happened to be in scope. EFFORT_VALUES is the picker's
146
- // own order: the three rungs, with no `auto` entry any more.
147
- const EFFORT_LEVELS = overlays.EFFORT_VALUES;
148
-
149
- // ── Small handler helpers ─────────────────────────────────────────────────────
150
-
151
- const note = (c, text) => c.push({ role: 'note', text });const panel = (c, lines) => c.push({ role: 'panel', lines });
152
- const tip = (c, text) => c.push({ role: 'tip', text });
153
- const done = (c, text) => c.push({ role: 'done', text });
154
-
155
- // ── The multi-agent fan-out (/multi run, /multiyolo, /aegis-multi run) ────────
156
- //
157
- // These three commands used to only *compose* text: /multi <task> run and
158
- // /aegis-multi <task> run printed "Running the task through the pooled brain
159
- // (single-model — the reference fans it out)" and handed the raw task to
160
- // c.runPrompt — a single turn, not a fan-out — while /multiyolo printed the
161
- // paste-ready panel and never executed anything at all, so its `savePermissions
162
- // ({ defaultMode: 'allow' })` turned automode on and then did nothing with it.
163
- //
164
- // The upstream engine calls `multiData(task, { signal })`, which
165
- // shells out to aegis-cli (`aegis --print "/multi <task>"`) because the fan-out
166
- // lives in that binary. This host has no aegis-cli, and a shell-out that fails
167
- // on every machine without one is not a port — so the real multi-agent runtime
168
- // here is the engine's own `task` tool (desktop/lib/local/engine.js
169
- // `runSubagent`: a specialist subagent with its own tool loop, session id and
170
- // approval card, primed from agents.js). One turn drives it, and the delegation
171
- // is executed rather than described.
172
-
173
- /** The fan-out prompt handed to the engine — the specialists are named so the delegation actually happens. */
174
- function composeMultiFanoutPrompt(task) {
175
- return [
176
- 'Execute this task as a multi-agent fan-out.',
177
- '',
178
- `Task: ${task}`,
179
- '',
180
- `Workspace: ${process.cwd()}`,
181
- '',
182
- 'Use the task tool to delegate the independent parts to specialist subagents, in parallel where they do not depend on each other:',
183
- '- reconnaissance first (scanner for secrets/unsafe patterns, analyzer for refactor targets),',
184
- '- then design (architect, or planner when the work is a change to existing code),',
185
- '- then an implementer subagent to make the change.',
186
- 'Finally review the result (reviewer subagent), fix what it finds, and verify with the repository\'s real commands.',
187
- '',
188
- 'Return one consolidated report: what each subagent found, the files you changed, the exact commands you ran and their real output, and anything still blocked. No preamble.',
189
- ].join('\n');
190
- }
191
-
192
- /**
193
- * The this-host `multiData(task, { signal })`. Returns the reference's shape —
194
- * `{ result, model, provider }`, `{ cancelled }`, or `{ error }` — so callers
195
- * render it through `panels.buildAegisPrint` exactly as the reference does.
196
- * `{ error }` is the honest fallback: the caller says why and still hands the
197
- * user a paste-ready command instead of pretending the fan-out ran.
198
- */
199
- async function multiData(c, task) {
200
- const prompt = composeMultiFanoutPrompt(task);
201
- const run = c && c.withWorking ? (fn) => c.withWorking(fn) : (fn) => fn();
202
- // A context with no agent loop at all (no ask, no runPrompt) is the one case
203
- // this cannot execute — say so rather than returning an empty success.
204
- if (!c || (typeof c.ask !== 'function' && typeof c.runPrompt !== 'function')) {
205
- return { error: 'No agent loop in this context — the fan-out prompt was composed, not run.' };
206
- }
207
- try {
208
- if (typeof c.ask === 'function') {
209
- const res = await run((signal) => c.ask(prompt, { signal }));
210
- const text = (res && res.text) || '';
211
- if (res && res.interrupted && !text) return { cancelled: true };
212
- if (!text) return { error: 'The multi-agent fan-out returned nothing (the turn failed before it could delegate).' };
213
- return { result: text, model: (res && res.model) || (c.ctx && c.ctx.model) || null, provider: 'aegis' };
214
- }
215
- // No captured-answer path: still execute, streamed into the transcript.
216
- await run(() => c.runPrompt(prompt));
217
- return { streamed: true };
218
- } catch (e) {
219
- return { error: `ÆGIS multi failed — ${(e && e.message) || e}` };
220
- }
221
- }
222
-
223
- /**
224
- * Drive one of the three fan-out commands end to end. `automode` is /multiyolo's
225
- * edge: the permission mode is set to allow *and* the task then executes under
226
- * it (previously it was set and never used).
227
- */
228
- async function runMultiCommand(c, task, { yolo = false, title = 'ÆGIS Multi' } = {}) {
229
- if (yolo) {
230
- // ON8: through the posture writer, not a bare `defaultMode` write — /multiyolo
231
- // means "stop confirming", and that is now ONE fact in two stores rather than
232
- // a rule-file edit the window would never see.
233
- setConfirmPosture(false);
234
- panel(c, panels.buildAutomode(c.state(), c.ctx));
235
- }
236
- note(c, 'Running the multi-agent fan-out — the engine delegates to specialist subagents (headless: this skips aegis-cli\'s own confirmation step).');
237
- c.render();
238
- const res = await multiData(c, task);
239
- if (res.cancelled) { note(c, 'ÆGIS multi cancelled.'); c.render(); return true; }
240
- if (res.error) {
241
- note(c, res.error);
242
- // Unreachable is not the same as useless: hand over the command that runs
243
- // it in a real aegis-cli session.
244
- panel(c, panels.buildAegisMulti(task, c.ctx));
245
- c.render();
246
- return true;
247
- }
248
- if (res.streamed) return true;
249
- panel(c, panels.buildAegisPrint(title, res, c.ctx));
250
- c.render();
251
- return true;
252
- }
253
-
254
- /** /upgrade's advice as panel rows (the advice itself is plain strings). */
255
- const upgradePanelLines = (lines) => lines.map((l) => [span(C.white, l)]);
256
-
257
- /**
258
- * The paid prompt `/billing` prints, or `undefined` when it cannot be earned.
259
- *
260
- * WHY THIS EXISTS AS A FUNCTION. `/billing` is the one screen a user opens when
261
- * they are already thinking about money, and it was the only money surface in
262
- * this client that did not ask the account anything: it printed the ledger and
263
- * the line "AEGIS has no subscription of its own". Both are now answered from
264
- * the SAME decision the drain clamps on (`desktop/lib/local/entitlement.js`,
265
- * reached through `cli/src/entitlement.js` with `host: 'cli'`), so the terminal
266
- * cannot sell a plan the drain would refuse, or refuse a fan-out to a bank the
267
- * panel just called funded.
268
- *
269
- * `force` on the refresh, deliberately: the gate's snapshot is a 60 s cache
270
- * built for a drain that must not probe per task, but `/billing` is an explicit
271
- * ask — "what do I owe" answered from a minute-old read is the wrong answer at
272
- * exactly the moment it is being asked. One probe per `/billing`, not per task.
273
- *
274
- * Returns undefined rather than a guess when the gate cannot be built at all
275
- * (no client, no shared module). The panel then prints its neutral top-up row.
276
- * The failure direction matters: inventing a wall for an account we could not
277
- * read is the one error here that costs real money — either selling Pro to
278
- * someone who has it or telling a funded user their bank is empty.
279
- */
280
- async function billingPayment(c) {
281
- if (!c || !c.client) return undefined;
282
- let gate;
283
- try {
284
- gate = createCliEntitlement({ aegis: c.client });
285
- } catch {
286
- return undefined;
287
- }
288
- // Through the spinner when the host has one: this is a network read, and an
289
- // unannounced two-second pause after `/billing` reads as a hang.
290
- const run = c.withWorking ? (fn) => c.withWorking(fn) : (fn) => fn();
291
- try {
292
- await run(() => gate.refresh({ force: true }));
293
- } catch {
294
- // `refresh()` is contractually non-throwing, but a broken host could still
295
- // reject; the cached (or boot) snapshot is a real read and still usable.
296
- }
297
- // The relay's handling fee, published by the same server the probe just
298
- // talked to. Fetched here rather than in the panel because the panel is pure
299
- // (and tested as such), and fetched WITHOUT `force`: a minute-old price is
300
- // still the price, unlike a minute-old entitlement verdict, and this keeps
301
- // `/billing` at one probe plus one cheap GET rather than two round trips to
302
- // the same host.
303
- const fee = await probeFee();
304
- return paymentView(gate.current(), { host: 'cli', fee });
305
- }
306
-
307
- /**
308
- * The pinnable-model list for the class the session is on, fetched fresh.
309
- *
310
- * `c.loadModels()` on the command context is `() => listModelsFor(cls)` — it
311
- * already returns the class-scoped rows (the pooled catalog on aegis, the
312
- * `provider:model` ids this machine can relay on byok). This helper must
313
- * RETURN that value.
314
- *
315
- * It used to `await` it and discard the result, leaving every caller to read
316
- * `c.state().models` instead, which went stale the moment the live class
317
- * changed. Best-effort on failure: offline, the caller falls through to the
318
- * honest empty note rather than opening an empty picker.
319
- * @returns {Promise<Array<{id:string,label:string,note:string}>>}
320
- */
321
- async function loadModels(c) {
322
- try {
323
- return (await c.loadModels()) || [];
324
- } catch {
325
- return [];
326
- }
327
- }
328
-
329
- /**
330
- * The full model list across BOTH classes, for the /model picker: the pooled
331
- * Nexus entry plus every provider id this machine can relay directly (BYOK),
332
- * each tagged with the class ENTER should apply the pin under.
333
- *
334
- * Before this, the picker was class-scoped: opening it on the default 'aegis'
335
- * class showed the single collapsed Nexus row, and reaching any of the real
336
- * per-provider models meant already knowing to run `/class byok` first — the
337
- * BYOK half of the catalog was correct but undiscoverable. Building one merged
338
- * list here (rather than in two places) keeps the interactive picker and the
339
- * `/model list` panel from disagreeing about what "the full list" is.
340
- */
341
- async function mergedPickerModels(c) {
342
- const live = (c.ctx && c.ctx.modelClass) || 'aegis';
343
- const aegis = pickerEntries(await loadModelsFor(c, 'aegis', live)).map((m) => ({ ...m, cls: 'aegis' }));
344
- // `m.cls ||` and not `cls:`: the byok list carries rows that belong to
345
- // another class (the pooled lane's, prepended by classScopedModels), and
346
- // their own tag is the truth about where a pick of them runs.
347
- const byok = pickerEntries(await loadModelsFor(c, 'byok', live)).map((m) => ({ ...m, cls: m.cls || 'byok' }));
348
- // The Pro class' aliases are a third disjoint id space — `claude --model`
349
- // resolves them, the pooled catalog and the relay do not — so they are merged
350
- // into the same list for the same reason byok's are: a class the picker omits
351
- // is a class the user cannot switch to from the surface that exists to switch
352
- // models. Each row carries its own `cls`, exactly as the other two do, which
353
- // is what ENTER reads to move the session BEFORE the pin applies.
354
- const pro = pickerEntries(await loadModelsFor(c, 'pro', live)).map((m) => ({ ...m, cls: 'pro' }));
355
-
356
- // One row per id, and a row's OWN class tag wins over the group it arrived
357
- // in. Both halves are corrections, not tidying:
358
- //
359
- // - The byok group is not all byok. `classScopedModels` prepends the pooled
360
- // rows to it on purpose, so that a session sitting on byok can still see
361
- // the way back to the pooled lane — and this function's per-group
362
- // `.map(m => ({...m, cls}))` overwrote that tag, so the SAME Nexus row
363
- // arrived twice (the pooled group's, and a copy tagged `byok`). ENTER
364
- // reads `cls` to decide which class to switch to before the pin applies,
365
- // so the copy was not merely a duplicate line: picking it pinned a pooled
366
- // id while leaving the session on byok, where the relay parses a bare id
367
- // as a provider name and 400s.
368
- // - Deduping by id (first wins, so the class-scoped groups lead) is what
369
- // keeps that copy off the screen, and what stops any other id being
370
- // offered twice when two classes advertise it.
371
- const out = [];
372
- const seen = new Set();
373
- for (const row of [...aegis, ...byok, ...pro]) {
374
- const id = String((row && row.id) || '');
375
- if (!id || seen.has(id)) continue;
376
- seen.add(id);
377
- out.push(row);
378
- }
379
- return out;
380
- }
381
-
382
- /**
383
- * One class's catalog, read through whichever loader this host has.
384
- *
385
- * `c.listModelsFor(cls)` is the per-class loader app.js provides, and it is
386
- * preferred because /model is class-scoped: reading the live class's own list
387
- * is what stops a pin from being validated (and a row from being offered)
388
- * against a class the next turn will not use.
389
- *
390
- * The fallback is not decoration. `loadModels()` is the loader every host has
391
- * had since the context existed — including hosts and test doubles that predate
392
- * the per-class one — so when it is the only loader present, the picker is
393
- * populated from it for the class the session is actually on, and the other
394
- * class yields nothing rather than a duplicated list. Skipping the fallback is
395
- * how `/model` renders an empty picker against a healthy account: the list is
396
- * asked for through a method the host does not have, the miss is swallowed, and
397
- * "no models advertised" is what the user is told (§P in another guise).
398
- */
399
- async function loadModelsFor(c, cls, live) {
400
- if (typeof c.listModelsFor === 'function') {
401
- try {
402
- return (await c.listModelsFor(cls)) || [];
403
- } catch {
404
- return [];
405
- }
406
- }
407
- if (cls !== live || typeof c.loadModels !== 'function') return [];
408
- try {
409
- return (await c.loadModels()) || [];
410
- } catch {
411
- return [];
412
- }
413
- }
414
-
415
- /**
416
- * The ÆGIS LLM routes are gated on the pooled brain being reachable — exactly
417
- * as the reference hides its ÆGIS routes when the backend is absent. `hidden`
418
- * is a function so visibility follows the environment at call time.
419
- *
420
- * It reads the *resolved* credential, not the environment: a key saved by
421
- * `aegiscode login` lives in credentials.json, and checking only
422
- * `process.env.AEGIS_API_KEY` here hid every AEGIS route from a user who had
423
- * just successfully set one.
424
- */
425
- const cloudReady = () => credentials.hasApiKey();
426
-
427
- // ── BYOK provider catalog ────────────────────────────────────────────────────
428
-
429
- /**
430
- * The BYOK model additions (`client/byok-catalog.js`) — the ids the server's
431
- * catalog does not name but the vendor serves and the relay forwards, resolved
432
- * by EXISTENCE through `resolveShared`, never with a fallback copy here.
433
- *
434
- * `/byok` reads the server directly rather than through the engine, so without
435
- * this the CLI's own listing would show fewer models than the CLI's own model
436
- * picker for the same account — two screens in one program disagreeing, which
437
- * is the failure this file's sibling brain-catalog module exists to end. The
438
- * desktop requires the same file from `desktop/lib/local/engine.js`, so the
439
- * terminal and the window cannot drift either.
440
- */
441
- const { withByokAdditions } = require(resolveShared(path.join('client', 'byok-catalog.js')));
442
-
443
- /**
444
- * The models the USER declares (`client/user-models.js`) — the same file the
445
- * desktop's Settings row writes, resolved by existence through the same
446
- * `resolveShared` path and for the same reason: one store, three writers.
447
- *
448
- * `/byok` and `/models` read it here, and the CLI's own engine
449
- * (`desktop/lib/local/engine.js` `listModels('byok')`, vendored into this
450
- * package) applies it too, so the terminal's listing and the terminal's picker
451
- * cannot disagree about which ids this machine offers.
452
- */
453
- const {
454
- withUserModels,
455
- addUserModel,
456
- removeUserModel,
457
- userModelIdsFor,
458
- userModelsPath,
459
- } = require(resolveShared(path.join('client', 'user-models.js')));
460
-
461
- /**
462
- * Ask the VENDOR what it serves (`client/model-discovery.js`), so `/model-add`
463
- * can offer a list instead of asking the user to recall an id.
464
- *
465
- * Same `resolveShared` resolution as its two siblings above: one implementation
466
- * of "what does this provider's key actually reach", read by both faces. It is
467
- * loaded at module scope rather than lazily inside the handler because the
468
- * command needs it to decide what to PROMPT with — a discovery module that
469
- * loads only after discovery was decided to be possible would be circular.
470
- *
471
- * The module does no I/O at load (no key store, no network), so pulling it in
472
- * with `/help` costs a `require` and nothing else.
473
- */
474
- const {
475
- discoverModels: discoverVendorModels,
476
- endpointFor: vendorEndpointFor,
477
- discoverableProviders,
478
- } = require(resolveShared(path.join('client', 'model-discovery.js')));
479
-
480
- /**
481
- * The vendor key for a provider, resolved the way the engine resolves it:
482
- * the saved provider-key row first, then `~/.aegiscode/.env` (and the shell).
483
- *
484
- * Deliberately the same ORDER as `desktop/lib/local/engine.js`'s
485
- * `providerKeyFromEnv` + `byok:<provider>` lookup, because discovery must use
486
- * the key the NEXT TURN will use — a listing fetched with a different key than
487
- * the one the call runs on is a listing of somebody else's catalog. This is
488
- * read-only: it never writes a key, never logs one, and returns '' when the
489
- * machine has none, which the caller reports as "no key to ask with".
490
- */
491
- function byokKeyForProvider(c, provider) {
492
- const id = String(provider || '').trim().toLowerCase();
493
- if (!id) return '';
494
- try {
495
- const store = c && c.settings && c.settings();
496
- if (store && typeof store.rawKey === 'function' && typeof c.byokNamespace === 'function') {
497
- const saved = store.rawKey(c.byokNamespace(id));
498
- if (typeof saved === 'string' && saved.trim()) return saved.trim();
499
- }
500
- } catch {
501
- /* a store that throws is a store with no key, not a reason to stop */
502
- }
503
- try {
504
- const { providerKeyFromEnv } = require(resolveShared(path.join('client', 'env-file.js')));
505
- return (providerKeyFromEnv(id) || {}).key || '';
506
- } catch {
507
- return '';
508
- }
509
- }
510
-
511
- /**
512
- * Ask the provider's own list endpoint, if this machine can. Never throws.
513
- *
514
- * `fetchImpl` is injectable through the context so the CLI tests drive a stub
515
- * and never open a socket; `c.fetchImpl` is undefined in a real run, which is
516
- * the module's normal `fetch`.
517
- */
518
- async function discoverProviderModels(c, provider, key) {
519
- try {
520
- return await discoverVendorModels(provider, { key, fetchImpl: c && c.fetchImpl });
521
- } catch (err) {
522
- return { ok: false, provider, supported: true, error: (err && err.message) || String(err) };
523
- }
524
- }
525
-
526
- /**
527
- * The provider's own catalog, best-effort, as `[ids]`. Undefined when the
528
- * vendor could not be asked — the caller then falls back to a free-form id
529
- * prompt, because that path works and must keep working offline.
530
- */
531
- async function offeredModelIds(c, provider, key) {
532
- const res = await discoverProviderModels(c, provider, key);
533
- return res && res.ok && Array.isArray(res.ids) && res.ids.length ? res.ids : undefined;
534
- }
535
-
536
- /**
537
- * One argument string, tokenized with the SAME quote rule the app's own parser
538
- * uses (`app.js` tokenize): a quoted run is one token and the quotes are not
539
- * part of it.
540
- *
541
- * `_rest` is the raw remainder of the line (app.js parseArgs keeps it
542
- * verbatim), so the only unambiguous way to type a base URL — `/model-add
543
- * custom "https://my-vllm.example/v1" sk-… llama-3-70b` — arrives here still
544
- * wrapped in its quotes. Splitting on whitespace alone stores the quote
545
- * characters as part of the URL: the row then looks saved while every call on
546
- * it is refused upstream, which is the silent no-op this whole command exists
547
- * to avoid. The app's tokenizer is not reachable from here (it is a closure in
548
- * app.js), so the rule is restated once, beside the only command that needs it.
549
- */
550
- function splitCommandWords(rest) {
551
- const out = [];
552
- let cur = '';
553
- let quote = null;
554
- let has = false;
555
- for (const ch of String(rest == null ? '' : rest)) {
556
- if (quote) {
557
- if (ch === quote) quote = null;
558
- else cur += ch;
559
- continue;
560
- }
561
- if (ch === '"' || ch === "'") { quote = ch; has = true; continue; }
562
- if (/\s/.test(ch)) {
563
- if (cur || has) { out.push(cur); cur = ''; has = false; }
564
- continue;
565
- }
566
- cur += ch;
567
- has = true;
568
- }
569
- if (cur || has) out.push(cur);
570
- return out;
571
- }
572
-
573
- /**
574
- * The base URL this machine already holds for a provider, or ''.
575
- *
576
- * Only `custom` needs it, and only to answer one question: `/model-add custom
577
- * <word>` with a single leftover word is ambiguous on a machine with no
578
- * endpoint configured — the word could be the base URL (key and model still to
579
- * come) or a model id for an endpoint nobody has named — and unambiguous once
580
- * one IS configured, because then the word can be nothing but a model id.
581
- */
582
- function savedByokBaseURL(c, provider) {
583
- try {
584
- const store = c && c.settings && c.settings();
585
- if (!store || typeof store.get !== 'function' || typeof c.byokNamespace !== 'function') return '';
586
- const row = store.get(c.byokNamespace(provider)) || {};
587
- return String(row.baseURL || '').trim();
588
- } catch {
589
- return '';
590
- }
591
- }
592
-
593
- /**
594
- * Declare ids into the store, skipping the ones already there. Returns the
595
- * count added, plus what was skipped and WHY, so the caller can say
596
- * "3 added, 2 already declared" instead of claiming work it did not do.
597
- *
598
- * The cap matters here more than anywhere else: a vendor's list endpoint
599
- * answers with everything it serves — OpenAI currently returns 100 ids — and
600
- * the store holds at most 32 per provider by design. Without this the bulk
601
- * path would report sixty-eight "refused" models, which reads as sixty-eight
602
- * broken ids rather than one deliberate ceiling. So the cap ends the batch and
603
- * is reported as itself.
604
- */
605
- function addManyUserModels(provider, ids) {
606
- let added = 0;
607
- let capped = 0;
608
- const already = [];
609
- const failed = [];
610
- for (const id of ids) {
611
- try {
612
- if (addUserModel(provider, id).added) added += 1;
613
- else already.push(id);
614
- } catch (err) {
615
- const message = (err && err.message) || String(err);
616
- if (/the cap/.test(message)) {
617
- // Every remaining id would hit the same wall, so stop rather than
618
- // loop sixty more times to collect sixty copies of one message.
619
- capped = ids.length - added - already.length - failed.length;
620
- break;
621
- }
622
- failed.push({ id, reason: message });
623
- }
624
- }
625
- return { added, already, failed, capped };
626
- }
627
-
628
- /**
629
- * The server's BYOK provider catalog, or null when it cannot be reached.
630
- *
631
- * The catalog is the *server's* answer to "which keys do you accept, for which
632
- * models, and where do I get one". It is deliberately not key-gated, so this
633
- * works before an account key exists — which is the whole point, since it is
634
- * the screen that tells a user which key to go buy. Returning null rather than
635
- * throwing keeps every caller free to fall back to the prose description it
636
- * used before the catalog existed.
637
- */
638
- async function byokCatalog(client) {
639
- if (!client || typeof client.byokProviders !== 'function') return null;
640
- try {
641
- const data = await client.byokProviders();
642
- // Two layers, in this order and for the same reason both exist: the
643
- // shipped additions this repo maintains (`withByokAdditions`) and then the
644
- // USER's own declarations (`withUserModels`). The user's layer is applied
645
- // last because it is the most specific opinion — and because a user who
646
- // declares an id the shipped list also carries still gets ONE row (both
647
- // functions append only what is missing).
648
- const providers = withUserModels(withByokAdditions((data && data.providers) || []));
649
- return providers.length ? providers : null;
650
- } catch {
651
- return null;
652
- }
653
- }
654
-
655
- /**
656
- * Resolve a typed provider id against the catalog.
657
- *
658
- * Exact id first, then a unique case-insensitive match on id, label or alias, so
659
- * `/byok-set OpenAI` and `/byok-set together-ai` both land. A non-unique match
660
- * returns `{ ambiguous }` rather than silently picking one: storing a key
661
- * against the wrong provider is the failure this whole path exists to prevent,
662
- * and it is not visible until a call 401s upstream.
663
- */
664
- function findByokProvider(providers, typed) {
665
- const want = String(typed || '').trim().toLowerCase();
666
- if (!providers) return { provider: null, exact: false };
667
- const exact = providers.find((p) => p.id === want);
668
- if (exact) return { provider: exact, exact: true };
669
- const loose = providers.filter((p) => {
670
- const names = [p.id, p.label, ...(p.aliases || [])].filter(Boolean);
671
- return names.some((n) => String(n).toLowerCase() === want);
672
- });
673
- if (loose.length === 1) return { provider: loose[0], exact: false };
674
- if (loose.length > 1) return { ambiguous: loose.map((p) => p.id) };
675
- return { provider: null, exact: false };
676
- }
677
-
678
- /** One catalog row: id, whether it is already set, its models, and key guidance.
679
- *
680
- * Every line is an array of span objects, never a plain string — panel/paint
681
- * (`screen.js` `padLine`/`paint`) iterate a line as spans and read `.t`/`.w`
682
- * off each entry. A plain string here gets walked character-by-character
683
- * instead, each "span" comes out `{t: undefined, w: undefined}`, and paint's
684
- * `sp.s + sp.t` prints the literal text "NaN" once per character.
685
- */
686
- function byokProviderLines(providers) {
687
- const lines = [];
688
- for (const p of providers) {
689
- const state = p.configured
690
- ? span(C.green, `set${p.masked ? ` (${p.masked})` : ''}`)
691
- : span(C.gray, 'not set');
692
- const row = [span(C.gold + BOLD, ` ${p.id}`)];
693
- if (p.label) row.push(span(C.gray, ` — ${p.label}`));
694
- row.push(span('', ' '), state);
695
- lines.push(row);
696
- // `models` arrives as bare ids. The catalog used to be read here as if each
697
- // one were an object with `.id`, which silently rendered nothing — a
698
- // provider listed with an empty model line reads as "no models", not as a
699
- // bug, so tolerate both shapes rather than repeat the mistake.
700
- const models = (p.models || [])
701
- .map((m) => (typeof m === 'string' ? m : m && m.id))
702
- .filter(Boolean);
703
- if (models.length) lines.push([span(C.gray, ` models: ${models.join(', ')}`)]);
704
- if (p.key_prefix) lines.push([span(C.gray, ` key starts with ${p.key_prefix}`)]);
705
- if (p.key_url) lines.push([span(C.gray, ` ${p.key_url}`)]);
706
- }
707
- return lines;
708
- }
709
-
710
- // ── account key + cloud sync handlers ────────────────────────────────────────
711
-
712
- /** The account-key panel body, shared by /key, /login and /cloud. */
713
- function keyPanelLines(c, title = 'AEGIS account key') {
714
- const st = c.keyStatus();
715
- const lines = [
716
- [span(C.gold + BOLD, title), span(BOLD_OFF, '')],
717
- [span(C.gray, '─'.repeat(34))],
718
- [
719
- span(st.configured ? C.green : C.coral, ` ${st.configured ? '✔' : '⚠'}`),
720
- span(C.white, ' key: '),
721
- span(st.configured ? C.white : C.gray, st.configured ? maskKey(st.key) : 'not set'),
722
- span(C.gray, ` (${credentials.sourceLabel(st.source)})`),
723
- ],
724
- [span(C.gray, ` stored in: ${st.path}${st.fileMode ? ` ${st.fileMode}` : ''}`)],
725
- ];
726
- if (st.verifiedAt) lines.push([span(C.gray, ` verified: ${st.verifiedAt}`)]);
727
- if (st.account && (st.account.plan || st.account.email)) {
728
- lines.push([
729
- span(C.gray, ' account: '),
730
- span(C.white, [st.account.plan, st.account.email].filter(Boolean).join(' · ')),
731
- ]);
732
- }
733
- lines.push([
734
- span(C.gray, ' memory: '),
735
- span(st.memoryToken ? C.green : C.gray, st.memoryToken ? 'token held (cloud sync ready)' : 'no token yet'),
736
- ]);
737
- if (!st.configured) {
738
- lines.push([span(C.gray, '')]);
739
- lines.push([span(C.white, ' Set one with /key <api_key>, or press Enter on /key to paste it.')]);
740
- lines.push([span(C.gray, ` Free key: ${signupUrl('key_status')}`)]);
741
- }
742
- if (st.legacyPlaintext) {
743
- lines.push([span(C.gray, '')]);
744
- lines.push([
745
- span(C.coral, ' ⚠ a plaintext copy of the key is still in config.json (another AEGIS CLI wrote it).'),
746
- ]);
747
- lines.push([span(C.gray, ' Re-save with /key <api_key> and delete that block when convenient.')]);
748
- }
749
- return lines;
750
- }
751
-
752
- /**
753
- * Take a key from the argument or an echo-off prompt, save it, and report what
754
- * the account said. Shared by `/key`, `/login` and `/cloud key` so all three
755
- * behave identically — the whole point is that there is one way to set a key.
756
- */
757
- async function applyAccountKey(c, raw, { label = 'AEGIS API key' } = {}) {
758
- let key = String(raw || '').trim();
759
- if (!key) {
760
- key = await c.readSecret(`${label} (kept off screen, Enter to cancel): `);
761
- }
762
- if (!key) {
763
- note(c, 'no key given — /key <api_key> takes it inline, or press Enter on a bare /key to paste it');
764
- return { ok: false };
765
- }
766
- const res = await c.setApiKey(key);
767
- if (!res.ok) {
768
- note(c, res.message || 'that key could not be saved');
769
- return res;
770
- }
771
- if (res.error) {
772
- note(c, `saved, but the account check failed: ${res.error.message}`);
773
- note(c, 'the key is stored — /key status shows it; re-run /key <api_key> if it was mistyped');
774
- return res;
775
- }
776
- const acct = (res.account && (res.account.email || res.account.plan)) || null;
777
- done(c, `AEGIS key saved to ${res.path}${acct ? ` — signed in as ${acct}` : ' and verified'}`);
778
- // The catalog is key-gated, so a freshly authenticated session should offer
779
- // /model's picker without the user having to know to re-run it. Counted from
780
- // the loader's return value (through pickerEntries, the same filter the
781
- // picker applies) rather than `c.state().models`, so the number matches what
782
- // the picker will actually offer.
783
- try {
784
- const n = pickerEntries(await loadModels(c)).length;
785
- if (n) note(c, `${n} pinnable model${n === 1 ? '' : 's'} available — /model to pin one`);
786
- } catch {}
787
- return res;
788
- }
789
-
790
- /** Human token count for the sync quota: 1000000 -> "1M", 42800 -> "43k".
791
- * The ceiling is denominated in tokens (aegis1 FREE_SYNC_TOKENS = 1 MB,
792
- * PRO_SYNC_TOKENS = 10 MB), which for stored prose is about one per
793
- * character — "1000000" at a glance tells a user nothing about how close they
794
- * are to it. */
795
- function fmtQuotaTokens(n) {
796
- const v = Number(n);
797
- if (!Number.isFinite(v)) return '?';
798
- if (v >= 1e6) return `${(v / 1e6).toFixed(v % 1e6 === 0 ? 0 : 1)}M`;
799
- if (v >= 1e4) return `${Math.round(v / 1e3)}k`;
800
- return fmtTokens(v);
801
- }
802
-
803
- /**
804
- * The persisting-memory gate, read off the command context (the live app
805
- * exposes `cloudSyncState()`) with a fallback for callers that only pass the
806
- * older boolean probe — `/cloud` and `/sync` predate the rename, and a stub
807
- * context in a test must not have to grow a method to render a panel.
808
- */
809
- function memoryGate(c) {
810
- if (c && typeof c.cloudSyncState === 'function') {
811
- try {
812
- return c.cloudSyncState();
813
- } catch {
814
- /* fall through to the boolean */
815
- }
816
- }
817
- const enabled =
818
- c && typeof c.cloudSyncEnabled === 'function' ? c.cloudSyncEnabled() === true : true;
819
- return { enabled, source: 'default' };
820
- }
821
-
822
- /**
823
- * Flip the gate through the command context (app.js's `setCloudSync` is
824
- * `config.setMemoryPersist`), which is what keeps the setting and the running
825
- * session agreeing. Guarded because a context stub that never flips anything
826
- * still has to be able to *run* the handler — the command smoke test drives
827
- * every handler with no arguments.
828
- */
829
- function setMemoryGate(c, on) {
830
- if (c && typeof c.setCloudSync === 'function') return c.setCloudSync(on);
831
- try {
832
- return setMemoryPersist(on);
833
- } catch {
834
- return null;
835
- }
836
- }
837
-
838
- /**
839
- * The persisting-memory block every cloud surface shows: the switch, the
840
- * ceiling, and — the part that was missing — what a stopped write does and
841
- * does not cost.
842
- *
843
- * The honesty requirement is not cosmetic. aegis1 meters WRITES only
844
- * (`_memory_sync_access`), so a free account that passes ~1 MB of transcript
845
- * keeps every entry it stored and simply stops accumulating new ones. The old
846
- * rollout printed nothing at all, so "memory is free with any account" and
847
- * "nothing is being stored any more" were both true and indistinguishable.
848
- * These lines make the ceiling a state the user can see: the number, whose
849
- * limit it is, and the one sentence that separates the working half (reads)
850
- * from the stopped half (new writes).
851
- */
852
- function memoryStatusLines(c) {
853
- const gate = memoryGate(c);
854
- const st = cloudsync.status();
855
- const q = st.quota;
856
- const used = q && q.used != null ? fmtQuotaTokens(q.used) : null;
857
- const limit = q && q.limit != null ? fmtQuotaTokens(q.limit) : null;
858
- const how =
859
- gate.source === 'legacy'
860
- ? ' (kept from your old cloudSync setting)'
861
- : gate.source === 'default'
862
- ? ' (default)'
863
- : '';
864
- const rows = [
865
- // Both names, one gate. The commit that flipped the default renamed the
866
- // panel to say what is being stored, but `/sync`, `/cloud sync` and the
867
- // docs all still call it cloud sync — a panel that only answers to its new
868
- // name makes the setting unfindable to anyone who learned the old one.
869
- [span(C.white + BOLD, 'Persisting memory'), span(C.gray, ' · Cloud sync'), span(BOLD_OFF, '')],
870
- [span(C.gray, '─'.repeat(34))],
871
- [
872
- span(C.white, ` ${gate.enabled ? 'on' : 'off'}`),
873
- span(C.gray, `${how} · ${gate.enabled ? 'each session is stored so an interrupted turn can be resumed' : 'nothing new is stored'}`),
874
- ],
875
- ];
876
- if (limit) {
877
- rows.push([
878
- span(C.gray, ' quota: '),
879
- span(C.white, `${used} of ${limit} tokens synced`),
880
- span(C.gray, ' (aegis1 charges writes; reads are always served)'),
881
- ]);
882
- } else {
883
- rows.push([span(C.gray, ' quota: not reported yet — /sync now asks the server for the current numbers')]);
884
- }
885
- if (st.overQuota) {
886
- rows.push([span(C.coral, ' writes: paused — the plan’s ceiling is reached, so new memory is not being stored')]);
887
- rows.push([span(C.green, ' reads: still work — everything already stored stays readable (/aegis-recall <topic>)')]);
888
- // Two rows, not one. This was a single 92-cell line ending in
889
- // "or /cloud memory off to stop trying", and panel rows go through
890
- // `padLine()`, which TRUNCATES at `cols` instead of wrapping — so at 80
891
- // columns the escape hatch was cut off the end and never rendered. The URL
892
- // gets its own row for the same reason: it is the actionable half, and
893
- // truncation is survivable in prose and fatal in a URL. The rows are 76 and
894
- // 45 cells of 80, both asserted by test/cli-commands.test.mjs.
895
- rows.push([span(C.gray, ` free room at ${goUrl('upgrade', 'cloud_quota')}`)]);
896
- rows.push([span(C.gray, ' or /cloud memory off to stop trying')]);
897
- }
898
- if (gate.enabled && st.pending > 0) {
899
- rows.push([span(C.gray, ` pending: ${st.pending} session(s) waiting to sync`)]);
900
- }
901
- rows.push([span(C.gray, ` /cloud memory on | off · /sync now pushes once by hand`)]);
902
- return rows;
903
- }
904
-
905
- /** Push + pull once, and report the counts (or the quota refusal). */
906
- async function runCloudSync(c, o = {}) {
907
- if (!c.client.apiKey) {
908
- note(c, `no key — ${credentials.HOW_TO_SET}`);
909
- return null;
910
- }
911
- const res = await c.withWorking(() => cloudsync.syncNow(c.client, o));
912
- const pushed = (res.push && res.push.pushed) || [];
913
- const failed = [...((res.push && res.push.failed) || []), ...((res.pull && res.pull.failed) || [])];
914
- const pulled = (res.pull && res.pull.imported) || 0;
915
- if (pushed.length) {
916
- done(c, `pushed ${pushed.length} session${pushed.length === 1 ? '' : 's'} (${pushed[0].messages} messages in the first)`);
917
- } else if (res.push && res.push.skipped && res.push.skipped.length) {
918
- note(c, `${res.push.skipped.length} session(s) had nothing to send`);
919
- } else {
920
- note(c, 'nothing to push — every local session is already in the cloud');
921
- }
922
- if (pulled) done(c, `pulled ${pulled} record${pulled === 1 ? '' : 's'} into the local store — /resume lists them`);
923
- else if (res.pull && res.pull.ok) note(c, `cloud has ${res.pull.remote || 0} session(s); nothing newer locally`);
924
- for (const f of failed) {
925
- note(c, `${f.kind === 'quota' ? 'quota' : 'failed'}: ${f.message}`);
926
- if (f.hint) note(c, f.hint);
927
- }
928
- return res;
929
- }
930
-
931
- /**
932
- * Hook config and repo-hook install come from the SHARED module
933
- * (`client/hooks.js`, staged to vendor/client/hooks.js in a package), because
934
- * the desktop app reads the same files and installs the same `.githooks/`.
935
- *
936
- * This file used to carry a private `readHooks()`/`hookStats()`. Two copies of
937
- * "which settings files count" is how the terminal and the GUI end up
938
- * describing one machine differently, and the private copy was joined with the
939
- * HOST's separator — so a Windows path was handled correctly and could not be
940
- * tested anywhere but Windows.
941
- */
942
- const hooksLib = require(resolveShared(path.join('client', 'hooks.js')));
943
-
944
- function readHooks() {
945
- return hooksLib.readHookConfig();
946
- }
947
-
948
- function hookStats(hooks) {
949
- return hooksLib.hookStats(hooks);
950
- }
951
-
952
- /** Scan the standard skill dirs for SKILL.md files. */
953
- function scanSkills() {
954
- const dirs = [
955
- path.join(os.homedir(), '.aegis', 'skills'),
956
- path.join(process.cwd(), '.aegis', 'skills'),
957
- path.join(os.homedir(), '.aegiscode', 'skills'),
958
- path.join(process.cwd(), '.aegiscode', 'skills'),
959
- path.join(os.homedir(), '.claude', 'skills'),
960
- ];
961
- const found = [];
962
- for (const dir of dirs) {
963
- const source = dir.startsWith(process.cwd()) ? 'project' : 'user';
964
- let names = [];
965
- try {
966
- names = fs.readdirSync(dir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => d.name);
967
- } catch { continue; }
968
- for (const name of names) {
969
- const skillPath = path.join(dir, name, 'SKILL.md');
970
- try {
971
- const raw = fs.readFileSync(skillPath, 'utf8');
972
- const desc = (/^description:\s*(.+)$/m.exec(raw) || [])[1] || '';
973
- found.push({ source, name, namespace: null, description: desc.trim(), path: skillPath, content: raw });
974
- } catch {}
975
- }
976
- }
977
- return found;
978
- }
979
-
980
- // ── Command definitions ───────────────────────────────────────────────────────
981
- // Order here is the palette order.
982
-
983
- const COMMANDS = [
984
- // ── session & context ───────────────────────────────────────────────────────
985
- {
986
- name: 'run', hint: '', category: 'workspace',
987
- desc: "Launch and drive this project's app to see a change working",
988
- handler: async (c) => {
989
- const cmd = detectDevCommand(process.cwd());
990
- if (!cmd) {
991
- note(c, 'No dev command detected (no package.json scripts, go.mod, Cargo.toml or Makefile). Try /init first.');
992
- c.render();
993
- return true;
994
- }
995
- note(c, `Running ${cmd} in ${shortCwd()} — output streams below, Esc stops it.`);
996
- const job = runDevServer(cmd, {
997
- cwd: process.cwd(),
998
- onLine: (line) => c.push({ role: 'note', text: ` ${line}` }),
999
- });
1000
- // Bind the job to the session so the status line draws "esc to stop" and
1001
- // Esc actually stops it (the reference's openStream/closeStream contract).
1002
- if (!job.label) job.label = cmd;
1003
- c.openStream(job);
1004
- job.done.then(({ code, stopped }) => {
1005
- c.closeStream(job);
1006
- done(c, stopped ? `${cmd} stopped` : `${cmd} exited (code ${code})`);
1007
- c.render();
1008
- });
1009
- c.render();
1010
- return true;
1011
- },
1012
- },
1013
- {
1014
- name: 'schedule', hint: '', category: 'session',
1015
- desc: 'Create, update, list, or run scheduled cloud agents (routines)',
1016
- handler: async (c) => {
1017
- note(c, 'Scheduled routines run on the AEGIS cloud. Sign in with `aegis login`, then manage routines at aegiscloud.org.');
1018
- c.render();
1019
- return true;
1020
- },
1021
- },
1022
- {
1023
- name: 'build', aliases: ['forge'], args: ['task'], hint: '<description>', category: 'workspace',
1024
- desc: 'Build an app with the agent loop — /build <what to build>',
1025
- handler: async (c, args) => {
1026
- const task = (args._rest || args.task || '').trim();
1027
- if (!task) {
1028
- note(c, 'Usage: /build <what to build>');
1029
- note(c, 'Example: /build a REST API for a todo app');
1030
- c.render();
1031
- return true;
1032
- }
1033
- note(c, '⬡ AEGIS BUILD');
1034
- note(c, `Task: ${task}`);
1035
- c.render();
1036
- await c.runPrompt(`Build the following, creating every file it needs and running the build to verify it works: ${task}`);
1037
- return true;
1038
- },
1039
- },
1040
- {
1041
- name: 'cd', args: ['path'], hint: '<path>', category: 'workspace',
1042
- desc: 'Move this session to a new working directory',
1043
- handler: async (c, args) => {
1044
- const dir = args.path || (args._rest || '').trim();
1045
- if (!dir) { note(c, 'Usage: /cd <path>'); c.render(); return true; }
1046
- try {
1047
- process.chdir(dir);
1048
- c.ctx.cwd = process.cwd();
1049
- updateConfig({ lastCwd: process.cwd() });
1050
- note(c, `Changed directory to ${process.cwd()}`);
1051
- } catch (e) {
1052
- note(c, `/cd: ${e.message}`);
1053
- }
1054
- c.render();
1055
- return true;
1056
- },
1057
- },
1058
- {
1059
- name: 'copy', aliases: ['cp'], args: ['n'], hint: '[N]', category: 'data',
1060
- desc: "Copy the last response to the clipboard",
1061
- handler: async (c, args) => {
1062
- const n = parseInt(args.n || '1', 10) || 1;
1063
- const text = lastAssistantText(c.transcript, n);
1064
- if (!text) { note(c, 'Nothing to copy yet.'); c.render(); return true; }
1065
- const r = copyToClipboard(text);
1066
- if (r.ok) {
1067
- note(c, r.via.startsWith('tool:')
1068
- ? `Copied the last response to the clipboard (${r.via.split(':')[1]}).`
1069
- : `No clipboard tool found — response saved to ${r.path}`);
1070
- } else {
1071
- note(c, 'Clipboard unavailable; nothing copied.');
1072
- }
1073
- c.render();
1074
- return true;
1075
- },
1076
- },
1077
- {
1078
- name: 'clear', aliases: ['cls'], hint: '', category: 'session',
1079
- desc: 'Start a new session with empty context',
1080
- handler: async (c) => {
1081
- c.transcript.length = 0;
1082
- // Prune the session's history rows so /cost resets with /clear.
1083
- pruneSessionHistory(c.sessionId);
1084
- // Emptying the transcript is only half a clear: a transport that keeps
1085
- // its own memory of this conversation (the Pro class's `claude` child
1086
- // session) still holds the turns that were just erased, and would answer
1087
- // from them on the next turn. Clearing the transcript our loop reads is
1088
- // exactly the case where the other half must be dropped too.
1089
- if (typeof c.clearConversationMemory === 'function') c.clearConversationMemory();
1090
- note(c, 'Session cleared — transcript empty.');
1091
- c.render();
1092
- return true;
1093
- },
1094
- },
1095
- {
1096
- name: 'compact', hint: '', category: 'session',
1097
- desc: 'Compact the conversation history',
1098
- handler: async (c) => {
1099
- const has = c.transcript.some((m) => m.role === 'user' || m.role === 'assistant');
1100
- if (!has) { note(c, 'Nothing to compact yet.'); c.render(); return true; }
1101
- note(c, 'Compacting conversation history…');
1102
- c.render();
1103
- const summary = await c.withWorking((signal) =>
1104
- summarizeTranscript(c.transcript, {
1105
- callModel: (p, opts) => c.ask(p, opts).then((r) => r.text),
1106
- model: c.ctx.model,
1107
- signal,
1108
- }));
1109
- if (summary === null) { note(c, 'Compaction cancelled.'); c.render(); return true; }
1110
- c.transcript.length = 0;
1111
- note(c, 'Compacted. Earlier context summarized into the message below.');
1112
- c.transcript.push({ role: 'user', text: summary });
1113
- c.render();
1114
- return true;
1115
- },
1116
- },
1117
- {
1118
- name: 'cost', hint: '', category: 'data',
1119
- desc: 'Show the cost of the current session',
1120
- handler: async (c) => {
1121
- const agg = aggregateSessionUsage(c.sessionId);
1122
- const acct = agg.entries
1123
- ? accountingFromUsage(agg.usage, c.ctx.model, {
1124
- exchanges: agg.entries,
1125
- real: agg.real,
1126
- costUsd: agg.real && agg.costUsd ? agg.costUsd : undefined,
1127
- })
1128
- : sessionAccounting(c.transcript, c.ctx.model);
1129
- panel(c, panels.buildCost({ ...c.state(), contextWindow: acct.contextWindow, costEur: acct.cost }, c.ctx));
1130
- c.render();
1131
- return true;
1132
- },
1133
- },
1134
- {
1135
- name: 'context', hint: '', category: 'session',
1136
- desc: 'Show context usage for the current session',
1137
- handler: async (c) => {
1138
- const acct = sessionAccounting(c.transcript, c.ctx.model);
1139
- panel(c, panels.buildContext({ ...c.state(), contextWindow: acct.contextWindow }, c.ctx));
1140
- c.render();
1141
- return true;
1142
- },
1143
- },
1144
- {
1145
- name: 'ping', args: ['mode', 'seconds'], hint: '[off|bell|notify|both] [seconds] | test', category: 'model',
1146
- desc: 'Alert me when a long turn finishes, if I am looking elsewhere',
1147
- handler: async (c, args) => {
1148
- const cfg = loadConfig();
1149
- const raw = ((args._rest || '').trim()).split(/\s+/).filter(Boolean);
1150
- const first = (raw[0] || '').toLowerCase();
1151
- const mode = normalizePingMode(cfg.ping);
1152
- const seconds = normalizePingSeconds(cfg.pingMinSeconds);
1153
-
1154
- // No argument: report the state AND the vocabulary, so the command is its
1155
- // own help. Silence here would be indistinguishable from a broken config.
1156
- if (!first) {
1157
- note(c, `[ping] ${mode} — a turn longer than ${seconds}s raises a terminal notification.`);
1158
- note(c, ` /ping ${PING_MODES.filter((m) => m !== mode).join('|')} ${mode === 'off' ? 'turn it back on' : 'change the channel'}`);
1159
- note(c, ` /ping <mode> <seconds> move the threshold (0 pings every turn)`);
1160
- note(c, ' /ping test fire one now, to check this terminal supports it');
1161
- c.render();
1162
- return true;
1163
- }
1164
-
1165
- if (first === 'test') {
1166
- const text = buildPing({ mode: mode === 'off' ? DEFAULT_PING_MODE : mode });
1167
- // The test deliberately ignores the threshold and the abort rule — it is
1168
- // the user asking "does this terminal show anything?", and the only
1169
- // condition worth keeping is the one that makes the answer meaningful.
1170
- const wrote = process.stdout.isTTY ? writePing(process.stdout, text) : false;
1171
- note(c, wrote
1172
- ? '[ping] sent one just now. If nothing appeared or sounded, this terminal implements neither OSC 9 nor OSC 777 — /ping bell is the fallback.'
1173
- : '[ping] nothing sent: stdout is not a TTY (a piped or headless run has no one to notify).');
1174
- c.render();
1175
- return true;
1176
- }
1177
-
1178
- if (!PING_MODES.includes(first)) {
1179
- note(c, `Unknown ping mode "${raw[0]}". Use ${PING_MODES.join(', ')}.`);
1180
- c.render();
1181
- return true;
1182
- }
1183
-
1184
- const patch = { ping: first };
1185
- if (raw[1] != null) {
1186
- const n = Number(raw[1]);
1187
- if (!Number.isFinite(n) || n < 0) {
1188
- note(c, `"${raw[1]}" is not a number of seconds. Use /ping ${first} 30.`);
1189
- c.render();
1190
- return true;
1191
- }
1192
- patch.pingMinSeconds = normalizePingSeconds(n);
1193
- }
1194
- updateConfig(patch);
1195
-
1196
- if (first === 'off') {
1197
- note(c, '[ping] off — no notice will be raised, and nothing is reported as sent.');
1198
- } else {
1199
- note(c, `[ping] ${first} — turns longer than ${normalizePingSeconds(patch.pingMinSeconds ?? cfg.pingMinSeconds)}s will notify you.`);
1200
- note(c, ' Escape never pings (you were watching), and neither does a piped or headless run.');
1201
- }
1202
- c.render();
1203
- return true;
1204
- },
1205
- },
1206
- {
1207
- name: 'todos', aliases: ['todo'], args: ['sub', 'text'], hint: '[add <text> | done <n|text> | clear]', category: 'session',
1208
- desc: 'A session todo list that survives compaction',
1209
- handler: async (c, args) => {
1210
- const sub = (args.sub || '').toLowerCase();
1211
- const rest = (args._rest || '').trim();
1212
- // Everything after the subcommand. `_rest` is the whole line, so
1213
- // `/todos add buy milk` would otherwise store the literal string
1214
- // "add buy milk" — the subcommand has to come off first.
1215
- const tail = rest.replace(/^\S+\s*/, '');
1216
-
1217
- if (!sub) {
1218
- panel(c, formatTodos());
1219
- note(c, ` ${todosFile()}`);
1220
- note(c, ' /todos add <text> · /todos done <n|text> · /todos clear');
1221
- c.render();
1222
- return true;
1223
- }
1224
-
1225
- if (sub === 'add') {
1226
- const res = addTodo(tail);
1227
- if (res.error) { note(c, res.error); c.render(); return true; }
1228
- panel(c, formatTodos(res.list));
1229
- c.render();
1230
- return true;
1231
- }
1232
-
1233
- if (sub === 'done' || sub === 'do') {
1234
- const res = completeTodo(tail);
1235
- if (res.error) { note(c, res.error); c.render(); return true; }
1236
- note(c, `[todos] "${res.item.text}" is now ${res.item.done ? 'done' : 'open'}.`);
1237
- panel(c, formatTodos(res.list));
1238
- c.render();
1239
- return true;
1240
- }
1241
-
1242
- if (sub === 'clear') {
1243
- clearTodos();
1244
- note(c, '[todos] cleared.');
1245
- c.render();
1246
- return true;
1247
- }
1248
-
1249
- note(c, `Unknown /todos subcommand "${args.sub}". Use add, done or clear.`);
1250
- c.render();
1251
- return true;
1252
- },
1253
- },
1254
- {
1255
- name: 'config', args: ['key', 'value'], hint: '[<key> | <key> <value> | reset <key>]', category: 'session',
1256
- desc: 'Show or change any setting, and say which store holds it',
1257
- handler: async (c, args) => {
1258
- const rest = (args._rest || '').trim();
1259
- const key = (args.key || '').trim();
1260
- // The value is everything after the key, not the next token: a string
1261
- // setting may contain spaces, and `_rest` is the whole line.
1262
- const value = rest.replace(/^\S+\s*/, '');
1263
-
1264
- if (!key) {
1265
- // The list summarizes structured values rather than dumping them —
1266
- // `models` is a model table and `updateCheck` is an object, and printing
1267
- // them whole is how this command becomes unreadable.
1268
- panel(c, formatConfigRows(configRows()));
1269
- note(c, ' /config <key> show one value in full');
1270
- note(c, ' /config <key> <value> set it (true/false/null, numbers, JSON, or text)');
1271
- note(c, ' /config reset <key> back to the shipped value');
1272
- note(c, ' "shared" keys live in the store AEGIS Desktop writes too; "host" keys are this shell\'s own.');
1273
- c.render();
1274
- return true;
1275
- }
1276
-
1277
- if (key === 'reset') {
1278
- const res = resetConfigValue(value);
1279
- if (res.error) { note(c, res.error); c.render(); return true; }
1280
- note(c, `[config] ${res.key} reset to ${summarizeValue(res.value)} (${res.store}).`);
1281
- c.render();
1282
- return true;
1283
- }
1284
-
1285
- if (!value) {
1286
- const cfg = loadConfig();
1287
- if (!Object.prototype.hasOwnProperty.call(cfg, key)) {
1288
- note(c, `unknown config key "${key}" — run /config to list the keys`);
1289
- c.render();
1290
- return true;
1291
- }
1292
- note(c, `${key} (${configStore(key)}):`);
1293
- c.push({ role: 'panel', lines: fullValue(cfg[key]).split('\n').map((l) => ` ${l}`) });
1294
- c.render();
1295
- return true;
1296
- }
1297
-
1298
- const res = setConfigValue(key, value);
1299
- if (res.error) { note(c, res.error); c.render(); return true; }
1300
- note(c, `[config] ${res.key} = ${summarizeValue(res.value)} (${res.store}).`);
1301
- // A model/class/effort change is a live session decision, not just a file
1302
- // write; say so rather than leaving the user to wonder when it applies.
1303
- if (['model', 'currentModelId', 'modelClass', 'effort', 'themeIndex', 'vim'].includes(res.key)) {
1304
- // ...and for `effort` the session value is written here, not just
1305
- // promised. `setConfigValue` touches the file only, so the note used to
1306
- // announce a change that the very next turn did NOT make: the session
1307
- // kept its old rung until a relaunch, which is one more way `/effort`
1308
- // appeared to do nothing. Floored through effortRung, so a hand-written
1309
- // `/config effort ultra` cannot put a rung on the wire that the engine
1310
- // does not know.
1311
- if (res.key === 'effort') {
1312
- c.ctx.effort = effortRung(res.value);
1313
- // Persist the FLOORED rung, not the raw argument: `effort` is a
1314
- // shared key AEGIS Desktop reads too, and writing `bogus` would put a
1315
- // level in that file which every reader has to floor again. rungTaken
1316
- // reports the correction rather than letting the note claim a value
1317
- // the turn did not take.
1318
- if (c.ctx.effort !== String(res.value).toLowerCase()) {
1319
- c.saveConfig({ effort: c.ctx.effort });
1320
- note(c, ` "${res.value}" is not a level this build sends — recorded as ${c.ctx.effort}.`);
1321
- }
1322
- }
1323
- note(c, ` This takes effect on the next turn; /${res.key === 'currentModelId' ? 'model' : res.key} shows the live session value.`);
1324
- }
1325
- c.render();
1326
- return true;
1327
- },
1328
- },
1329
- {
1330
- name: 'effort', args: ['level'], hint: '[low|medium|high]', category: 'model',
1331
- desc: 'Set the token budget the pool sizes each turn from',
1332
- handler: async (c, args) => {
1333
- const level = (args.level || '').toLowerCase();
1334
- // Validated against EFFORT_LEVELS, which IS the picker's value list
1335
- // (overlays.EFFORT_VALUES, aliased above) — the same array the rows are
1336
- // drawn from, so a level the picker offers can never be rejected here.
1337
- if (level && level !== 'auto' && !EFFORT_LEVELS.includes(level)) {
1338
- note(c, `Unknown effort level "${args.level}". Use ${EFFORT_LEVELS.join(', ')}.`);
1339
- c.render();
1340
- return true;
1341
- }
1342
- if (!level) {
1343
- // The picker opens on the rung actually in force; a session whose
1344
- // config predates the default lands on high, which is what the engine
1345
- // applies to an unstored value.
1346
- c.openOverlay({ type: 'effort', sel: Math.max(0, EFFORT_LEVELS.indexOf(c.ctx.effort || 'high')) });
1347
- return true;
1348
- }
1349
- // `auto` is retired, not a fourth rung: it pinned nothing, and a fresh
1350
- // install therefore sent no effort and the knob did nothing. It is still
1351
- // ACCEPTED so an old habit (or a script) is not a hard error — it now
1352
- // resolves to the default rung, and says so.
1353
- const pinned = level === 'auto' ? 'high' : level;
1354
- c.ctx.effort = pinned;
1355
- c.saveConfig({ effort: pinned });
1356
- note(c, level === 'auto'
1357
- ? `effort: auto is retired — high is the default, and it is what this session now sends`
1358
- : `Effort level: ${pinned} — the pool sizes this turn's token budget from it`);
1359
- c.render();
1360
- return true;
1361
- },
1362
- },
1363
- {
1364
- name: 'exit', aliases: ['quit'], hint: '', category: 'session',
1365
- desc: 'Exit the CLI',
1366
- handler: async () => false,
1367
- },
1368
- {
1369
- name: 'export', args: ['format', 'target'], hint: '[markdown|json] [file|clipboard]', category: 'data',
1370
- desc: 'Export the current conversation to a file or clipboard',
1371
- handler: async (c, args) => {
1372
- const fmt = (args.format || 'markdown').toLowerCase();
1373
- const target = (args.target || 'file').toLowerCase();
1374
- if (!['markdown', 'md', 'json'].includes(fmt) || !['file', 'clipboard'].includes(target)) {
1375
- note(c, 'Usage: /export [markdown|json] [file|clipboard]');
1376
- c.render();
1377
- return true;
1378
- }
1379
- const isJson = fmt === 'json';
1380
- const body = isJson ? transcriptToJSON(c.transcript) : transcriptToMarkdown(c.transcript);
1381
- if (target === 'clipboard') {
1382
- const r = copyToClipboard(body);
1383
- note(c, r.ok
1384
- ? `Exported conversation (${isJson ? 'json' : 'markdown'}) to the clipboard.`
1385
- : 'Clipboard unavailable; nothing copied.');
1386
- } else {
1387
- try {
1388
- // Honour the command context's cwd. The handler used to fall through
1389
- // to writeExportFile's own `process.cwd()` default, so /export wrote
1390
- // into whatever directory the process happened to be in — which meant
1391
- // running the command smoke test (it invokes every handler) littered
1392
- // the repository root with aegiscodex-export-*.md files.
1393
- const p = writeExportFile(body, isJson ? 'json' : 'md', c.ctx.cwd || process.cwd());
1394
- note(c, `Exported conversation to ${p}`);
1395
- } catch (e) {
1396
- note(c, `/export: ${e.message}`);
1397
- }
1398
- }
1399
- c.render();
1400
- return true;
1401
- },
1402
- },
1403
- {
1404
- name: 'help', aliases: ['?', 'h'], hint: '', category: 'support',
1405
- desc: 'Show help',
1406
- handler: async (c) => {
1407
- panel(c, panels.buildHelp(visibleCommands(), c.ctx));
1408
- c.render();
1409
- return true;
1410
- },
1411
- },
1412
- {
1413
- name: 'init', args: ['file'], hint: '[file]', category: 'workspace',
1414
- desc: 'Create an AEGIS.md file in the project',
1415
- handler: async (c, args) => {
1416
- const file = (args.file || 'AEGIS.md').trim();
1417
- // The command context's cwd, not process.cwd(): /cd moves the session to
1418
- // another directory, and a handler that reads process.cwd() then writes
1419
- // the file into the directory the user just left. It also means the
1420
- // command smoke test (which invokes every handler) no longer drops an
1421
- // AEGIS.md into the repository root.
1422
- const cwd = c.ctx.cwd || process.cwd();
1423
- const p = path.resolve(cwd, file);
1424
- // Refuse a path that resolves outside the project — the reference's /init
1425
- // takes no argument, and `path.join(cwd, '../../x')` writes outside it.
1426
- const root = cwd.endsWith(path.sep) ? cwd : cwd + path.sep;
1427
- if (p !== cwd && !p.startsWith(root)) {
1428
- note(c, `/init: refusing to write outside the project directory (${p}).`);
1429
- c.render();
1430
- return true;
1431
- }
1432
- if (fs.existsSync(p)) { note(c, `${file} already exists — not overwriting.`); c.render(); return true; }
1433
- const sniff = sniffProject(cwd);
1434
- try {
1435
- fs.writeFileSync(p, buildAegisMd(sniff) + '\n');
1436
- } catch (e) {
1437
- note(c, `/init: ${e.message}`);
1438
- c.render();
1439
- return true;
1440
- }
1441
- note(c, `Created ${p} (${sniff.lang})`);
1442
- if (fs.existsSync(path.join(cwd, 'node_modules')) && !fs.existsSync(path.join(cwd, '.gitignore'))) {
1443
- tip(c, 'Add "node_modules/" to a .gitignore before committing.');
1444
- }
1445
- c.render();
1446
- return true;
1447
- },
1448
- },
1449
- {
1450
- name: 'login', aliases: ['signin'], args: ['value'], hint: '[<api_key>]', category: 'auth',
1451
- desc: 'Save your AEGIS API key',
1452
- handler: async (c, args) => {
1453
- // This used to be `unavailable` with `/byok-set` as its alternative —
1454
- // which was worse than useless: /byok-set stores a *provider* key
1455
- // server-side, so a user following that advice pasted their AEGIS key
1456
- // into a BYOK provider slot. Signing in to AEGIS Cloud *is* handing over
1457
- // an API key, and this is now where you give it one.
1458
- const arg = String(args.value || args._rest || '').trim();
1459
- await applyAccountKey(c, arg, { label: 'AEGIS API key' });
1460
- c.render();
1461
- return true;
1462
- },
1463
- },
1464
- {
1465
- name: 'logout', args: [], hint: '', category: 'auth',
1466
- desc: 'Remove the saved AEGIS API key',
1467
- handler: async (c) => {
1468
- const res = c.forgetApiKey();
1469
- done(c, res.cleared ? `key removed from ${res.path}` : 'there was no saved key to remove');
1470
- if (credentials.legacyKeyOnDisk()) {
1471
- note(c, `a copy is still in ${configPath()} (another AEGIS CLI wrote it) — delete its "aegiscloud" block too`);
1472
- }
1473
- c.render();
1474
- return true;
1475
- },
1476
- },
1477
- {
1478
- name: 'model', aliases: ['m'], args: ['sub'], hint: '[id|-]', category: 'model',
1479
- desc: 'Switch AI model — pin an id ("-" clears it)',
1480
- handler: async (c, args) => {
1481
- const id = (args.sub || '').trim();
1482
- // Which class the pin applies to — /model is class-scoped, because the
1483
- // id spaces are disjoint: the pooled catalog is server-advertised ids,
1484
- // byok is `provider:model`. Every branch below reads the live class, so
1485
- // the copy and the picker's contents describe the route the next turn
1486
- // will actually take (app.js's buildState().models is class-scoped too).
1487
- const cls = (c.ctx && c.ctx.modelClass) || 'aegis';
1488
- const byok = cls === 'byok';
1489
- if (!id) {
1490
- note(c, `model: ${c.ctx.model || 'server default'}`);
1491
- // The full list across BOTH classes — pooled Nexus plus every
1492
- // provider this machine can relay directly — not just the class the
1493
- // session happens to be on. Selecting one of the direct-provider rows
1494
- // (below) switches to byok and, if this machine holds no key for its
1495
- // provider yet, prompts for one right there — see the picker's ENTER
1496
- // handler in chatflow.js.
1497
- const models = await mergedPickerModels(c);
1498
- if (!models.length) {
1499
- // Say why, and what unblocks it: an unreachable catalog is almost
1500
- // always a missing key or no network, and "no models advertised"
1501
- // read as "the platform has none" rather than "this client could not
1502
- // ask". Reachable only when even Claude Code Pro's static alias rows
1503
- // are absent — PRO_MODELS is a non-empty constant, so in practice
1504
- // this is the full-outage fallback, not the common "no AEGIS key"
1505
- // case that used to land here (see the branch just below).
1506
- note(c, c.state().online
1507
- ? 'Could not read the model catalog (offline, or the server refused it) — /models retries.'
1508
- : // The key travels in the environment only (client/aegis.js reads
1509
- // AEGIS_API_KEY); /login is an unavailable command here, so
1510
- // pointing at it would send the user to a refusal.
1511
- `No API key set, so the model catalog cannot be read — export AEGIS_API_KEY (free key: ${signupUrl('model_blocked')}), then retry /model.`);
1512
- c.render();
1513
- return true;
1514
- }
1515
- // AEGIS Cloud and byok both need a key this machine does not have:
1516
- // almost always a missing AEGIS_API_KEY or no network. Claude Code Pro
1517
- // needs neither (it is the subscription's own OAuth token, collected
1518
- // when a pro row is picked), so its rows still show — the picker opens
1519
- // with what IS available rather than blocking on what is not.
1520
- if (!models.some((m) => m.cls === 'aegis' || m.cls === 'byok')) {
1521
- note(c, c.state().online
1522
- ? 'Could not read the AEGIS Cloud catalog (offline, or the server refused it) — showing Claude Code Pro only; /models retries.'
1523
- : `No AEGIS API key set, so the AEGIS Cloud catalog cannot be read (free key: ${signupUrl('model_blocked')}) — showing Claude Code Pro only.`);
1524
- }
1525
- // A pin that is not in the catalog is not honoured — the pool answers
1526
- // from its own default with no error. Say so where the pin is visible
1527
- // rather than letting the reply look like the pinned model. On byok the
1528
- // failure mode is different and louder (the relay 400s on a provider it
1529
- // has no key for).
1530
- if (c.ctx.model && !models.some((m) => m.id === c.ctx.model)) {
1531
- note(c, byok
1532
- ? `pinned model "${c.ctx.model}" is not one this machine can relay — pick from the list below.`
1533
- : `pinned model "${c.ctx.model}" is not in the catalog — the pool will answer with its own default; pick one below.`);
1534
- }
1535
- note(c, '/model <id> pins one for this session; picking a direct-provider row prompts for its key if this machine has none saved.');
1536
- // `cls` rides on the overlay so the picker's subtitle renders for the
1537
- // class the session is on right now; each row also carries its own
1538
- // `cls` so ENTER knows which class a pick switches to.
1539
- c.openOverlay({ type: 'model', items: models, sel: 0, current: c.ctx.model, cls });
1540
- return true;
1541
- }
1542
- if (id === 'list') {
1543
- // Same merged list as the picker above, so the static panel and the
1544
- // interactive one never disagree about what "the full list" is.
1545
- const models = await mergedPickerModels(c);
1546
- if (!models.length) note(c, 'No pinnable models advertised — /models lists the server\'s ids.');
1547
- else panel(c, panels.buildModelList(c.ctx.model, models, c.ctx));
1548
- c.render();
1549
- return true;
1550
- }
1551
- if (id === '-') {
1552
- c.ctx.model = null;
1553
- c.saveConfig({ model: null, currentModelId: null });
1554
- note(c, byok
1555
- // There is no such thing as a byok default: the relay addresses a
1556
- // provider by the id itself, so "nothing pinned" is not a fallback
1557
- // here, it is a turn that will 400 with "model must be
1558
- // <provider>:<model>". Said now rather than at the next send.
1559
- ? 'Model pin cleared. The byok class has no server default — the next turn needs <provider>:<model>, so pin one from /models before sending.'
1560
- : 'Model pin cleared — the server will choose.');
1561
- c.render();
1562
- return true;
1563
- }
1564
- c.ctx.model = id;
1565
- // Persist, so the next launch restores it. app.js's restorePrefs() reads
1566
- // this on startup; without the write it had nothing to restore and the
1567
- // pin silently evaporated at exit. Tests point AEGISCODE_HOME at a temp
1568
- // dir, so the write stays inside that dir.
1569
- c.saveConfig({ model: id, currentModelId: id });
1570
- note(c, `Pinned model: ${id}`);
1571
- // A pin the class cannot honour is the same problem on both classes and
1572
- // only the consequence differs, so both branches say the consequence.
1573
- // Pooled: the server accepts an id it does not advertise and answers from
1574
- // its own default — no error, a different model, and the spend attributed
1575
- // to the id that was pinned. Byok: the id is parsed as a provider name,
1576
- // so a pooled id becomes "no key saved for <that id>" at the relay.
1577
- // Warn, never refuse: the catalog is cached, and refusing would break a
1578
- // pin made against a server that is briefly unreachable.
1579
- const models = (await loadModels(c)) || [];
1580
- if (models.length && !models.some((m) => m.id === id)) {
1581
- note(c, byok
1582
- ? `"${id}" is not one this machine can relay — a byok id is "<provider>:<model>", and the relay will refuse anything else. /models lists the real ids.`
1583
- : `"${id}" is not in the AEGIS Cloud catalog — the pool will answer with its own default. /models lists the real ids.`);
1584
- }
1585
- c.render();
1586
- return true;
1587
- },
1588
- },
1589
- {
1590
- name: 'radio', hint: '', category: 'fun',
1591
- desc: 'Listen to AEGIS FM lo-fi radio',
1592
- handler: async (c) => {
1593
- note(c, 'Opening AEGIS FM lo-fi radio in your browser…');
1594
- if (!openUrl(URLS.radio)) note(c, `AEGIS FM: ${URLS.radio}`);
1595
- c.render();
1596
- return true;
1597
- },
1598
- },
1599
- {
1600
- name: 'recap', hint: '', category: 'session',
1601
- desc: 'Generate a one-line session recap now',
1602
- handler: async (c) => {
1603
- if (!c.transcript.some((m) => m.role === 'user' || m.role === 'assistant')) {
1604
- note(c, 'No exchanges yet — send a prompt first.');
1605
- c.render();
1606
- return true;
1607
- }
1608
- note(c, 'Recapping session…');
1609
- c.render();
1610
- const line = await c.withWorking((signal) =>
1611
- recapLine(c.transcript, {
1612
- callModel: (p, opts) => c.ask(p, opts).then((r) => r.text),
1613
- model: c.ctx.model,
1614
- signal,
1615
- }));
1616
- if (line === null) { note(c, 'Recap cancelled.'); c.render(); return true; }
1617
- c.ctx.lastRecap = { sessionId: c.sessionId, ts: new Date().toISOString(), text: line };
1618
- c.saveConfig({ lastRecap: c.ctx.lastRecap });
1619
- note(c, `Session recap: ${line}`);
1620
- c.render();
1621
- return true;
1622
- },
1623
- },
1624
- {
1625
- name: 'resume', hint: '', category: 'session',
1626
- desc: 'Switch to a previous session',
1627
- handler: async (c) => {
1628
- const items = readResumeList();
1629
- if (!items.length) { note(c, 'No previous sessions found — conversations from this host and from AEGIS Desktop both land in ~/.aegiscode/sessions.json'); c.render(); return true; }
1630
- c.openOverlay({ type: 'resume', items, sel: 0 });
1631
- return true;
1632
- },
1633
- },
1634
- {
1635
- name: 'rewind', args: ['n'], hint: '[N]', category: 'session',
1636
- desc: 'Revert the conversation to a checkpoint',
1637
- handler: async (c, args) => {
1638
- const items = listCheckpoints(c.sessionId);
1639
- if (!args.n) {
1640
- if (!items.length) { note(c, 'No checkpoints yet — snapshots are taken after each exchange.'); c.render(); return true; }
1641
- panel(c, panels.buildRewindList(items, c.ctx));
1642
- c.render();
1643
- return true;
1644
- }
1645
- const n = parseInt(args.n, 10);
1646
- if (Number.isNaN(n) || n < 0 || n >= items.length) {
1647
- note(c, `Unknown checkpoint ${args.n}. /rewind shows the list (indices 0..${Math.max(0, items.length - 1)}).`);
1648
- c.render();
1649
- return true;
1650
- }
1651
- snapshotCheckpoint(c.sessionId, c.transcript); // make the rewind undoable
1652
- const restored = loadCheckpoint(c.sessionId, n);
1653
- if (!restored) { note(c, 'Checkpoint unreadable — nothing restored.'); c.render(); return true; }
1654
- c.transcript.length = 0;
1655
- for (const m of restored) c.transcript.push(m);
1656
- note(c, `Rewound to checkpoint ${n} (${restored.length} messages). /rewind N again to undo.`);
1657
- c.render();
1658
- return true;
1659
- },
1660
- },
1661
- {
1662
- name: 'agents', aliases: ['sessions'], args: ['role', 'task'], hint: '[role] [task]', category: 'session',
1663
- desc: 'Show the agents panel, or run a sub-agent role preset — /agents <role> <task>',
1664
- handler: async (c, args) => {
1665
- const role = (args.role || '').trim().toLowerCase();
1666
- if (role) {
1667
- const task = (args._rest || '').trim().replace(/^\S+\s*/, '').trim();
1668
- if (!task) { note(c, `Usage: /agents <role> <task> — roles: ${agentRoles().join(', ')}`); c.render(); return true; }
1669
- if (!AGENT_PRESETS[role]) { note(c, `Unknown agent role "${role}". Roles: ${agentRoles().join(', ')}`); c.render(); return true; }
1670
- const prompt = composeAgentPrompt(role, task);
1671
- if (c.runPrompt) {
1672
- await c.runPrompt(prompt);
1673
- return true;
1674
- }
1675
- note(c, `Composed ${role} prompt (${prompt.length} chars) — run in the TUI to send it.`);
1676
- c.render();
1677
- return true;
1678
- }
1679
- panel(c, panels.buildAgents(c.state(), c.ctx));
1680
- c.render();
1681
- return true;
1682
- },
1683
- },
1684
- {
1685
- name: 'status', aliases: ['st'], hint: '', category: 'session',
1686
- desc: 'Show account and session status',
1687
- handler: async (c) => {
1688
- // This client's /status surface is the account-status tool (the same
1689
- // tool /aegis-status names) plus the local session panel below it.
1690
- await c.runTool('aegis_status', {});
1691
- panel(c, panels.buildStatus(c.state(), Object.assign({}, c.ctx, { caps: describe() })));
1692
- c.render();
1693
- return true;
1694
- },
1695
- },
1696
- {
1697
- name: 'teleport', hint: '', category: 'session',
1698
- desc: 'Resume a session from aegiscloud.org',
1699
- handler: async (c) => {
1700
- note(c, 'Teleport requires an AEGIS cloud account with sessions. Sign in with `aegis login`, then run aegiscloud.org/teleport.');
1701
- c.render();
1702
- return true;
1703
- },
1704
- },
1705
- {
1706
- name: 'theme', aliases: ['t'], args: ['mode'], hint: '[dark|light]', category: 'model',
1707
- desc: 'Change the color theme',
1708
- handler: async (c, args) => {
1709
- const m = (args.mode || '').toLowerCase();
1710
- if (m === 'dark' || m === 'light') {
1711
- // Resolve through the theme table rather than hardcoding an index, so
1712
- // "light" names the same row the picker would have named: index 2
1713
- // ("Light mode"), not index 0 ("Auto"). themeIndex is what the
1714
- // colorblind/ANSI palettes key off, so a wrong index silently selects
1715
- // the wrong palette rather than merely displaying a wrong label.
1716
- const want = m === 'light' ? 2 : 1;
1717
- screens.applyTheme(c.ctx, want);
1718
- } else {
1719
- await c.showThemePicker();
1720
- }
1721
- c.saveConfig({ themeIndex: c.ctx.themeIndex });
1722
- note(c, `Theme: ${c.ctx.light ? 'light' : 'dark'}`);
1723
- // An explicit row is a real preference — the whole point of `/theme dark`
1724
- // — so it is NOT overridden here, even on a terminal that will draw it
1725
- // badly. It is only reported, because "my text vanished" is otherwise
1726
- // indistinguishable from a crash and this is the one moment the user is
1727
- // looking at the setting that caused it.
1728
- const clash = themeContradicts(c.ctx.themeIndex);
1729
- if (clash) {
1730
- const background = caps().background;
1731
- note(c, `warning: this ${background} terminal is not what "${THEME_TABLE[c.ctx.themeIndex].name}" is drawn for — body text may be unreadable.`);
1732
- note(c, ` /terminal background ${background} pins the palette to this terminal, or /terminal background ${background === 'dark' ? 'light' : 'dark'} if it reads you wrong.`);
1733
- }
1734
- c.render();
1735
- return true;
1736
- },
1737
- },
1738
- {
1739
- name: 'terminal', aliases: ['tty'], args: ['mode', 'mode2'],
1740
- hint: '[ascii|unicode|color|no-color|background <dark|light>|probe|star <native|narrow>|width <cols>|auto|status]', category: 'model',
1741
- desc: 'Show or override how this terminal is drawn (mark, colour, width)',
1742
- handler: async (c, args) => {
1743
- // The same report `aegiscode --terminal` prints, and the same switch the
1744
- // `--ascii` flag sets — so a session can be re-styled without restarting
1745
- // when a paste from PowerShell turns out to render badly in this host.
1746
- // `args` is positional (app.js `parseArgs`), so the second token is
1747
- // `mode2` for both `star narrow` and `width 100`.
1748
- const sub = (args.mode || '').toLowerCase();
1749
- const second = args.mode2 != null ? String(args.mode2).trim() : '';
1750
-
1751
- if (sub === '' || sub === 'status') {
1752
- panel(c, panels.buildTerminalCaps(describe(), { pinned: !!caps().pinned }));
1753
- c.render();
1754
- return true;
1755
- }
1756
-
1757
- // The patch pins every *axis* but never the frame: `cols`/`rows` must stay
1758
- // absent so `setCaps` leaves `sizePinned` false and a live resize keeps
1759
- // re-reading the stream (see caps.js). Copying the whole caps object here
1760
- // would freeze the width at the moment the command ran.
1761
- const cur = caps();
1762
- const axes = {
1763
- glyphs: cur.glyphs, face: cur.face, star: cur.star,
1764
- depth: cur.depth, vt: cur.vt, wideRunes: cur.wideRunes,
1765
- background: cur.background,
1766
- backgroundKnown: cur.backgroundKnown,
1767
- reasons: Object.assign({}, cur.reasons),
1768
- };
1769
-
1770
- if (sub === 'auto') {
1771
- // Drop every override, including any the session inherited from the
1772
- // flags/env it was started with — "auto" means "probe again", not
1773
- // "restore what you were launched with".
1774
- resetCaps();
1775
- note(c, 'Terminal: auto — capabilities re-probed from the environment.');
1776
- c.render();
1777
- return true;
1778
- }
1779
- if (sub === 'probe') {
1780
- // Ask the terminal outright (OSC 11) and use its own answer. This is
1781
- // the same query the session runs once at startup, exposed because the
1782
- // one case it cannot handle is a terminal that started reporting
1783
- // differently afterwards — a terminal theme switched mid-session — and
1784
- // because "what does my terminal say it is?" is the first question a
1785
- // mis-rendered screen raises.
1786
- const probed = await probeTerminalBackground();
1787
- screens.applyTheme(c.ctx, c.ctx.themeIndex);
1788
- note(c, probed.known
1789
- ? `Terminal: background ${probed.background} (${probed.reason}) — /theme auto follows it.`
1790
- : `Terminal: no answer to the background query (${probed.reason}).`);
1791
- note(c, ' /terminal background dark|light pins it without asking.');
1792
- panel(c, panels.buildTerminalCaps(describe(), { pinned: !!caps().pinned }));
1793
- c.render();
1794
- return true;
1795
- }
1796
- // `why` in the report must describe what the session is actually doing,
1797
- // not the probe it started from: after `/terminal ascii` on a truecolor
1798
- // host, `why: TERM=xterm-256color` would contradict `mark: ascii`.
1799
- if (sub === 'ascii' || sub === 'unicode') {
1800
- axes.glyphs = sub === 'ascii' ? 'ascii' : 'unicode';
1801
- axes.face = sub === 'ascii' ? 'edges' : 'native';
1802
- axes.star = sub === 'ascii' ? 'narrow' : 'native';
1803
- if (axes.reasons) axes.reasons.glyphs = `/terminal ${sub}`;
1804
- } else if (sub === 'color' || sub === 'no-color' || sub === 'nocolor') {
1805
- axes.depth = sub === 'color' ? 24 : 0;
1806
- if (axes.reasons) axes.reasons.depth = `/terminal ${sub}`;
1807
- } else if (sub === 'star') {
1808
- const want = second.toLowerCase();
1809
- if (!['native', 'narrow'].includes(want)) { note(c, 'Usage: /terminal star <native|narrow>'); c.render(); return true; }
1810
- axes.star = want;
1811
- if (axes.reasons) axes.reasons.star = `/terminal star ${want}`;
1812
- } else if (sub === 'background' || sub === 'bg') {
1813
- // The one axis that is not about drawing: it says which of the two
1814
- // legible palettes "Auto (match terminal)" resolves to, for a terminal
1815
- // that reports nothing about itself (or reports it wrong). Pinning it
1816
- // here is the same decision `AEGIS_BACKGROUND` makes at launch, so a
1817
- // user on a light terminal can fix an invisible UI without restarting.
1818
- const want = second.toLowerCase();
1819
- if (!['dark', 'light'].includes(want)) { note(c, 'Usage: /terminal background <dark|light>'); c.render(); return true; }
1820
- axes.background = want;
1821
- axes.backgroundKnown = true;
1822
- if (axes.reasons) axes.reasons.background = `/terminal background ${want}`;
1823
- setCaps(Object.assign({}, axes));
1824
- screens.applyTheme(c.ctx, c.ctx.themeIndex);
1825
- note(c, `Terminal: background pinned to ${want} — /theme auto follows it.`);
1826
- panel(c, panels.buildTerminalCaps(describe(), { pinned: !!caps().pinned }));
1827
- c.render();
1828
- return true;
1829
- } else if (sub === 'width') {
1830
- // A pinned width is a frame override, so it goes in as cols — the one
1831
- // key that deliberately trips `sizePinned`.
1832
- const width = Number(second);
1833
- if (!Number.isFinite(width) || width < 20) { note(c, 'Usage: /terminal width <cols> (>= 20)'); c.render(); return true; }
1834
- setCaps(Object.assign({}, axes, { cols: Math.round(width) }));
1835
- note(c, `Terminal: width pinned to ${Math.round(width)} columns.`);
1836
- panel(c, panels.buildTerminalCaps(describe(), { pinned: !!caps().pinned }));
1837
- c.render();
1838
- return true;
1839
- } else {
1840
- note(c, 'Usage: /terminal [ascii|unicode|color|no-color|background <dark|light>|probe|star <native|narrow>|width <cols>|auto|status]');
1841
- c.render();
1842
- return true;
1843
- }
1844
-
1845
- setCaps(axes);
1846
- panel(c, panels.buildTerminalCaps(describe(), { pinned: !!caps().pinned }));
1847
- // Already-painted scrollback keeps the glyphs it was drawn with — a
1848
- // terminal has no way to rewrite what it has scrolled past. Everything
1849
- // from here on (and this viewport) uses the new mark.
1850
- note(c, 'Terminal updated — the current viewport is redrawn; text already scrolled past keeps its old glyphs.');
1851
- c.render();
1852
- return true;
1853
- },
1854
- },
1855
- {
1856
- name: 'version', aliases: ['v'], hint: '', category: 'session',
1857
- desc: 'Show version',
1858
- handler: async (c) => {
1859
- note(c, `aegiscode v${VERSION}`);
1860
- c.render();
1861
- return true;
1862
- },
1863
- },
1864
- {
1865
- name: 'doctor', args: ['action'], hint: '[fix|system]', category: 'support',
1866
- desc: 'Run diagnostic checks on this environment',
1867
- handler: async (c, args) => {
1868
- const action = ((args && args.action) || '').toLowerCase();
1869
- if (action && action !== 'fix' && action !== 'system') {
1870
- note(c, 'Usage: /doctor [fix|system] — "fix" re-tightens the data dir to 0700/0600, "system" checks the machine itself');
1871
- c.render();
1872
- return true;
1873
- }
1874
- const checks = [];
1875
- const ok = (label, good, detail) => checks.push([good, label, detail]);
1876
- ok('Node', true, process.version);
1877
- ok('CWD', fs.existsSync(process.cwd()), process.cwd());
1878
- let git = false;
1879
- try { execSync('git rev-parse --git-dir', { cwd: process.cwd(), stdio: ['ignore', 'ignore', 'ignore'], timeout: 4000 }); git = true; } catch {}
1880
- ok('git repo', git, git ? 'inside a work tree' : 'not a git repository');
1881
- const ks = credentials.keyStatus();
1882
- ok(
1883
- 'AEGIS key',
1884
- ks.configured,
1885
- ks.configured
1886
- ? `${maskKey(ks.key)} via ${credentials.sourceLabel(ks.source)}`
1887
- : `not set — ${credentials.HOW_TO_SET} (free key: ${signupUrl('doctor')})`
1888
- );
1889
- ok('credentials', true, `${ks.path}${ks.fileMode ? ` (${ks.fileMode})` : ''}`);
1890
- ok('cloud memory', ks.memoryToken, ks.memoryToken ? 'token held' : 'no memory token — /cloud activate');
1891
- if (ks.legacyPlaintext) {
1892
- ok('plaintext key', false, `a copy also sits in ${configPath()} (another AEGIS CLI) — /key re-saves it to ${ks.path}`);
1893
- }
1894
- ok('config path', true, configPath());
1895
- // The store sits at 0775/0664 on any install older than securefs.js —
1896
- // every file that has not happened to be rewritten since. Report that
1897
- // always, but repair only when asked: a diagnostic that silently rewrites
1898
- // the user's directory is a surprise, not a fix.
1899
- const dataDir = aegisDir();
1900
- let repaired = null;
1901
- if (action === 'fix') repaired = repairExposure(dataDir);
1902
- const audit = auditExposure(dataDir);
1903
- if (!audit.exists) {
1904
- ok('data dir', true, `${dataDir} (not created yet)`);
1905
- } else if (!audit.modesMeaningful) {
1906
- // Windows: fs.stat's mode is synthesised from the read-only attribute, so
1907
- // there are no group/other bits to audit (securefs.js hasPosixModes).
1908
- // Saying so beats the old output, which listed every file in the store as
1909
- // world-accessible and then could not fix a single one.
1910
- ok(
1911
- 'data dir',
1912
- true,
1913
- `${dataDir} (${audit.total} path(s)) — this filesystem has no POSIX permission bits; ` +
1914
- 'access is governed by the profile directory\'s own ACL',
1915
- );
1916
- } else {
1917
- const shown = audit.exposed.slice(0, 4).map((e) => `${e.rel} ${e.mode}`).join(', ');
1918
- ok(
1919
- 'data dir',
1920
- audit.exposed.length === 0,
1921
- audit.exposed.length === 0
1922
- ? `${dataDir} (${audit.rootMode}, all private)`
1923
- : `${dataDir} (${audit.rootMode}) — ${audit.exposed.length} path(s) group/world-accessible: ` +
1924
- `${shown}${audit.exposed.length > 4 ? ', …' : ''} — run /doctor fix`
1925
- );
1926
- }
1927
- if (repaired && !repaired.modesMeaningful) {
1928
- ok('repair', true, 'nothing to tighten — this filesystem has no POSIX permission bits');
1929
- } else if (repaired) {
1930
- const sample = repaired.fixed
1931
- .slice(0, 3)
1932
- .map((f) => `${f.rel} ${f.from}→${f.to}`)
1933
- .join(', ');
1934
- ok(
1935
- 'repair',
1936
- repaired.remaining.length === 0,
1937
- repaired.remaining.length === 0
1938
- ? repaired.fixed.length
1939
- ? `tightened ${repaired.fixed.length} path(s) — ${sample}${repaired.fixed.length > 3 ? ', …' : ''}`
1940
- : 'already private, nothing to tighten'
1941
- : `${repaired.remaining.length} path(s) still exposed — ` +
1942
- repaired.failed.map((f) => `${f.rel}: ${f.reason}`).join(', ')
1943
- );
1944
- }
1945
- // `/doctor system` — the machine, not the checkout. Read-only by design:
1946
- // cli/src/sysdiag.js holds the nine checks and each one's remedy, and
1947
- // nothing here executes a remedy, because all of them need elevation and
1948
- // the ordering matters (VSS has to survive DoSnapshotSet before a restore
1949
- // point can exist). An unread probe is its own state, never a ✔.
1950
- let systemReport = null;
1951
- if (action === 'system') {
1952
- const probe = sysdiag.collect();
1953
- if (!probe.ok) {
1954
- ok(
1955
- 'machine checks',
1956
- false,
1957
- probe.reason === 'not-windows'
1958
- ? 'not available on this platform — the machine audit is Windows-only (cli/src/sysdiag.js)'
1959
- : `could not run: ${probe.reason}`,
1960
- );
1961
- } else {
1962
- systemReport = sysdiag.assess(probe.data);
1963
- for (const f of systemReport.findings) ok(`${f.title} (${f.severity})`, false, `${f.detail} → ${f.remedyText}`);
1964
- for (const p of systemReport.clean) ok(p.title, true, p.detail);
1965
- for (const u of systemReport.unassessed) ok(`${u.title} (unassessed)`, false, u.reason);
1966
- }
1967
- }
1968
- const lines = [[span(C.gold + BOLD, 'Doctor'), span(BOLD_OFF, '')], [span(C.gray, '─'.repeat(30))]];
1969
- for (const [good, label, detail] of checks) {
1970
- lines.push([
1971
- span(good ? C.green : C.coral, ` ${good ? '✔' : '⚠'}`),
1972
- span(C.white, ` ${label}: `),
1973
- span(C.gray, String(detail)),
1974
- ]);
1975
- }
1976
- if (systemReport && systemReport.findings.length) {
1977
- const s = systemReport.summary;
1978
- lines.push([
1979
- span(C.gold, ' Remedy'),
1980
- span(C.gray, ` — ${s.findings} finding(s) across ${s.assessed}/${s.total} measured checks.`),
1981
- ]);
1982
- lines.push([span(C.gray, ' Run in an ELEVATED PowerShell. AEGIS diagnoses this; it does not change your machine.')]);
1983
- for (const line of sysdiag.remedyScript().split('\n')) lines.push([span(C.gray, ` ${line}`)]);
1984
- }
1985
- panel(c, lines);
1986
- c.render();
1987
- return true;
1988
- },
1989
- },
1990
- {
1991
- name: 'upgrade', args: ['action'], hint: '[check|apply]', category: 'support',
1992
- desc: 'Check for a newer published version (apply: install it now)',
1993
- handler: async (c, args) => {
1994
- const action = String((args && args.action) || 'check').toLowerCase();
1995
- if (!['check', 'apply'].includes(action)) {
1996
- note(c, 'Usage: /upgrade [check|apply]');
1997
- c.render();
1998
- return true;
1999
- }
2000
- // The channel is what THIS process was installed from — npm, pip, npx or
2001
- // a git checkout — so /upgrade never tells a pip install to run npm and
2002
- // then report success for a second copy that nothing is running from.
2003
- const method = installMethod();
2004
- note(c, 'Checking the npm registry…');
2005
- c.render();
2006
- // The registry lookup is a blocking `npm view`, so it runs inside the
2007
- // spinner when the context offers one (and is skipped entirely in demo
2008
- // mode, where a network answer would be a lie).
2009
- const run = c && c.withWorking ? (fn) => c.withWorking(fn) : (fn) => fn();
2010
- const latest = c.ctx && c.ctx.demo ? null : await run(() => Promise.resolve(latestPublishedVersion()));
2011
- const advice = upgradeAdvice({ latest, method });
2012
- panel(c, upgradePanelLines(advice.lines));
2013
- c.render();
2014
- if (action !== 'apply') return true;
2015
-
2016
- // Applying is opt-in and never inferred: it replaces the binaries under
2017
- // a running process, which is a different promise from "a release
2018
- // exists". A channel with nothing to install says so instead of running
2019
- // a command that would be a no-op.
2020
- if (!advice.plan || !advice.plan.apply) {
2021
- note(c, advice.plan ? `Nothing to install: ${advice.plan.instruction}` : 'Nothing to install.');
2022
- c.render();
2023
- return true;
2024
- }
2025
- note(c, `Running: ${advice.plan.instruction}`);
2026
- c.render();
2027
- const res = applyUpgrade({ method, latest, current: advice.plan.current });
2028
- if (res.ok && !res.skipped) {
2029
- // A global install does not touch the process already running, so the
2030
- // honest last line is "installed, restart to use it" — not "upgraded",
2031
- // which would claim this session is now on the new version.
2032
- note(c, `Installed ${advice.plan.latest}. Restart aegiscode to use it.`);
2033
- if (res.output) for (const line of res.output.split('\n').slice(-6)) note(c, ` ${line}`);
2034
- } else if (res.skipped) {
2035
- note(c, `Not applied: ${res.instruction}`);
2036
- } else {
2037
- note(c, `Upgrade failed: ${res.error}`);
2038
- note(c, `Run it yourself: ${res.command}`);
2039
- }
2040
- c.render();
2041
- return true;
2042
- },
2043
- },
2044
- {
2045
- name: 'vim', args: ['mode'], hint: '[on|off]', category: 'model',
2046
- desc: 'Toggle vim keymap',
2047
- handler: async (c, args) => {
2048
- const mode = (args.mode || '').toLowerCase();
2049
- if (mode && !['on', 'off'].includes(mode)) { note(c, 'Usage: /vim [on|off]'); c.render(); return true; }
2050
- const want = mode === 'on' ? true : mode === 'off' ? false : !c.ctx.vim;
2051
- c.ctx.vim = want;
2052
- c.saveConfig({ vim: want });
2053
- note(c, `Vim keymap: ${want ? 'on' : 'off'}`);
2054
- c.render();
2055
- return true;
2056
- },
2057
- },
2058
- {
2059
- name: 'permissions', args: ['mode', 'pattern'],
2060
- hint: '[allow|deny|ask "<pattern>" | default <ask|allow|deny> | clear]', category: 'model',
2061
- desc: 'Set permissions for tool use',
2062
- handler: async (c, args) => {
2063
- const rules = loadPermissions();
2064
- const mode = (args.mode || '').toLowerCase();
2065
- const pattern = args.pattern;
2066
- if (!mode) {
2067
- panel(c, panels.buildPermissions({ ...rules, _path: permissionsPath() }, null, c.ctx));
2068
- c.render();
2069
- return true;
2070
- }
2071
- if (mode === 'clear') {
2072
- // A reset is a posture change too: DEFAULT_PERMISSIONS' residual is
2073
- // `ask`, i.e. confirmations ON, and leaving the shared key where it was
2074
- // would keep the gate off in the window while this face asks.
2075
- setPermissionDefaultMode(DEFAULT_PERMISSIONS.defaultMode);
2076
- savePermissions({ ...DEFAULT_PERMISSIONS, allow: [], deny: [], ask: [] });
2077
- note(c, 'Permissions reset to defaults (no rules).');
2078
- c.render();
2079
- return true;
2080
- }
2081
- if (mode === 'default' && ['ask', 'allow', 'deny'].includes(pattern)) {
2082
- // ON8: `ask`/`allow` are the posture, so this moves the shared gate too
2083
- // (a `/permissions default ask` in the shell must close the window's
2084
- // switch, which is the whole point of rule 1). `deny` is not a posture:
2085
- // it writes the rule residual and leaves the gate UP.
2086
- setPermissionDefaultMode(pattern);
2087
- note(c, `Default permission mode: ${pattern}`);
2088
- c.render();
2089
- return true;
2090
- }
2091
- if (['allow', 'deny', 'ask'].includes(mode) && pattern) {
2092
- const { added, rules: next } = addPermissionRule(mode, pattern, rules);
2093
- savePermissions(next);
2094
- note(c, added ? `Added ${mode} rule: ${pattern}` : `Rule already present: ${pattern}`);
2095
- c.render();
2096
- return true;
2097
- }
2098
- note(c, 'Usage: /permissions [allow|deny|ask "<pattern>" | default <ask|allow|deny> | clear]');
2099
- c.render();
2100
- return true;
2101
- },
2102
- },
2103
- {
2104
- name: 'hooks', args: ['sub'], hint: '[status|list|install]', category: 'model',
2105
- desc: 'View hooks configuration status, list configured hooks, or install this repo\'s guard hooks',
2106
- handler: async (c, args) => {
2107
- const sub = (args.sub || '').toLowerCase();
2108
- if (sub === 'install') {
2109
- // The one mutating branch, and the one that makes the guards real: a
2110
- // fresh clone has .githooks/ present and core.hooksPath unset, so a
2111
- // commit runs NO guard at all (`.githooks/lib-gate.sh` says so itself).
2112
- const dryRun = /--dry-run|\bdry-?run\b/.test(String(args._rest || ''));
2113
- const res = hooksLib.installRepoHooks({ cwd: process.cwd(), dryRun });
2114
- if (!res.ok) {
2115
- note(c, res.error);
2116
- if (res.actions.length) for (const a of res.actions) note(c, ` ${a}`);
2117
- } else if (dryRun) {
2118
- note(c, `would install the guard hooks in ${res.status.repo}`);
2119
- for (const a of res.actions) note(c, ` ${a}`);
2120
- if (res.status.installed) note(c, 'core.hooksPath is already .githooks — nothing to change');
2121
- } else if (!res.changed) {
2122
- done(c, `guard hooks already installed (core.hooksPath = .githooks)`);
2123
- } else {
2124
- done(c, `installed the guard hooks — core.hooksPath = .githooks (verified)`);
2125
- for (const a of res.actions) note(c, ` ${a}`);
2126
- }
2127
- if (res.ok) note(c, res.status.execNote);
2128
- c.render();
2129
- return true;
2130
- }
2131
- const { hooks, from } = readHooks();
2132
- if (sub === 'list') {
2133
- panel(c, panels.buildHooksList({ hooks }, c.ctx));
2134
- c.render();
2135
- return true;
2136
- }
2137
- if (sub === '' || sub === 'status') {
2138
- panel(c, panels.buildHooksStatus({ ...hookStats(hooks), fromPaths: from }, c.ctx));
2139
- c.render();
2140
- return true;
2141
- }
2142
- note(c, `unknown subcommand: ${args.sub}`);
2143
- note(c, 'available: status, list, install [--dry-run]');
2144
- c.render();
2145
- return true;
2146
- },
2147
- },
2148
- {
2149
- name: 'credentials', hint: '', category: 'model',
2150
- desc: 'Show where credentials are stored',
2151
- handler: async (c) => {
2152
- const p = path.join(os.homedir(), '.claude', '.credentials.json');
2153
- const loc = p.replace(os.homedir(), '~');
2154
- if (!fs.existsSync(p)) {
2155
- note(c, 'No credential file found. The Claude Code CLI manages auth (OS keychain or ~/.claude/.credentials.json).');
2156
- } else {
2157
- note(c, `Credentials live in ${loc} (managed by the Claude Code CLI). aegiscode reads them but never writes them.`);
2158
- }
2159
- c.render();
2160
- return true;
2161
- },
2162
- },
2163
- {
2164
- name: 'install-github-app', hint: '', category: 'model',
2165
- desc: 'Install the GitHub App for PR workflows',
2166
- handler: async (c) => {
2167
- note(c, 'The GitHub App is installed through the Claude Code CLI: run `claude --install-github-app` once.');
2168
- c.render();
2169
- return true;
2170
- },
2171
- },
2172
- {
2173
- name: 'troubleshooting', hint: '', category: 'support',
2174
- desc: 'Troubleshoot common issues',
2175
- handler: async (c) => {
2176
- panel(c, panels.buildTroubleshooting(c.state(), c.ctx));
2177
- c.render();
2178
- return true;
2179
- },
2180
- },
2181
- {
2182
- name: 'feedback', hint: '', category: 'support',
2183
- desc: 'Send feedback to the AEGIS team',
2184
- handler: async (c) => {
2185
- note(c, 'Opening the feedback form…');
2186
- if (!openUrl(URLS.feedback)) note(c, `Feedback: ${URLS.feedback}`);
2187
- c.render();
2188
- return true;
2189
- },
2190
- },
2191
- {
2192
- name: 'bug', hint: '', category: 'support',
2193
- desc: 'Report a bug (opens a GitHub issue)',
2194
- handler: async (c) => {
2195
- note(c, `Opening a GitHub issue… (aegiscode v${VERSION}, ${process.version}, ${os.platform()})`);
2196
- if (!openUrl(URLS.issues)) note(c, `Issues: ${URLS.issues}`);
2197
- c.render();
2198
- return true;
2199
- },
2200
- },
2201
- {
2202
- name: 'issue', aliases: ['bugs'], hint: '', category: 'support',
2203
- desc: 'Report an issue',
2204
- handler: async (c) => {
2205
- note(c, 'Opening a GitHub issue…');
2206
- if (!openUrl(URLS.issues)) note(c, `Issues: ${URLS.issues}`);
2207
- c.render();
2208
- return true;
2209
- },
2210
- },
2211
- {
2212
- name: 'onboarding', hint: '', category: 'support',
2213
- desc: 'Show getting-started tips',
2214
- handler: async (c) => {
2215
- panel(c, panels.buildOnboarding(c.state(), c.ctx));
2216
- c.render();
2217
- return true;
2218
- },
2219
- },
2220
- {
2221
- name: 'shell-completion', hint: '', category: 'support',
2222
- desc: 'Set up shell completion',
2223
- handler: async (c) => {
2224
- panel(c, panels.buildShellCompletion(c.state(), c.ctx));
2225
- c.render();
2226
- return true;
2227
- },
2228
- },
2229
- {
2230
- name: 'terminal-setup', hint: '', category: 'support',
2231
- desc: 'Check and fix terminal setup',
2232
- handler: async (c) => {
2233
- panel(c, panels.buildTerminalSetup(c.state(), c.ctx));
2234
- c.render();
2235
- return true;
2236
- },
2237
- },
2238
- {
2239
- name: 'pr-comments', hint: '', category: 'support',
2240
- desc: 'Review and reply to pull request comments',
2241
- handler: async (c) => {
2242
- note(c, 'PR comments need GitHub auth. Run /prs to check connectivity, then use the `gh` CLI or the GitHub web UI.');
2243
- c.render();
2244
- return true;
2245
- },
2246
- },
2247
- {
2248
- name: 'prs', hint: '', category: 'support',
2249
- desc: 'List pull requests in this repo',
2250
- handler: async (c) => {
2251
- try {
2252
- const out = execSync('gh pr list --limit 8', { encoding: 'utf8', timeout: 15000, stdio: ['ignore', 'pipe', 'ignore'] });
2253
- panel(c, panels.buildPRs(out.toString(), c.ctx));
2254
- } catch {
2255
- note(c, 'gh not authenticated (or not installed) — run `gh auth login` first.');
2256
- }
2257
- c.render();
2258
- return true;
2259
- },
2260
- },
2261
- {
2262
- name: 'review', hint: '', category: 'support',
2263
- desc: 'Review a pull request',
2264
- handler: async (c) => {
2265
- note(c, '/review needs GitHub auth via gh. Run /prs to list open PRs, then open one in the browser.');
2266
- c.render();
2267
- return true;
2268
- },
2269
- },
2270
- {
2271
- name: 'benchmark', hint: '', category: 'support',
2272
- desc: 'Run in-app micro-benchmarks',
2273
- handler: async (c) => {
2274
- const t = (fn) => {
2275
- const s = process.hrtime.bigint();
2276
- fn();
2277
- return (Number(process.hrtime.bigint() - s) / 1e6).toFixed(2);
2278
- };
2279
- const sample = '# Heading\n\nSome **bold** and `code` with a [link](https://x.test).\n\n- a\n- b\n- c\n';
2280
- const results = [
2281
- ['2,000 span() calls', t(() => { for (let i = 0; i < 2000; i++) span(C.white, 'x'); })],
2282
- ['estimateTokens × 20 (500 chars)', t(() => { for (let i = 0; i < 20; i++) estimateTokens('x'.repeat(500)); })],
2283
- ];
2284
- if (markdownModule && typeof markdownModule.renderMarkdown === 'function') {
2285
- results.push(['renderMarkdown × 200', t(() => { for (let i = 0; i < 200; i++) markdownModule.renderMarkdown(sample, 80); })]);
2286
- }
2287
- panel(c, panels.buildBenchmark(results, c.ctx));
2288
- c.render();
2289
- return true;
2290
- },
2291
- },
2292
- {
2293
- name: 'waifu', hint: '', category: 'fun',
2294
- desc: 'Summon a waifu',
2295
- handler: async (c) => {
2296
- panel(c, panels.buildWaifu(c.ctx));
2297
- c.render();
2298
- return true;
2299
- },
2300
- },
2301
-
2302
- // ── additional command families ─────────────────────────────────────────────
2303
- {
2304
- name: 'new', aliases: ['start'], hint: '', category: 'session',
2305
- desc: 'Start a new session (clears the transcript, fresh session id)',
2306
- handler: async (c) => {
2307
- c.transcript.length = 0;
2308
- // Release the conversation being left behind BEFORE the id changes — a
2309
- // new session id is a new key, so the old entry would otherwise sit in
2310
- // the engine's map for the life of the process, holding a `claude` child
2311
- // session nobody can reach or clear again.
2312
- if (typeof c.clearConversationMemory === 'function') c.clearConversationMemory();
2313
- const id = 'aegis-' + Math.random().toString(36).slice(2, 10);
2314
- c.sessionId = id;
2315
- c.ctx.sessionId = id;
2316
- note(c, `New session started (${id}) — earlier context cleared.`);
2317
- c.render();
2318
- return true;
2319
- },
2320
- },
2321
- {
2322
- name: 'tokens', aliases: ['tok'], hint: '', category: 'data',
2323
- desc: 'Show token usage breakdown and estimated spend',
2324
- handler: async (c) => {
2325
- const acct = sessionAccounting(c.transcript, c.ctx.model);
2326
- panel(c, panels.buildTokens({ ...c.state(), contextWindow: acct.contextWindow, costEur: acct.cost }, c.ctx));
2327
- c.render();
2328
- return true;
2329
- },
2330
- },
2331
- {
2332
- name: 'skills', aliases: ['sk'], args: ['sub'], hint: '[name|refresh]', category: 'session',
2333
- desc: 'List skills (SKILL.md in the standard skill dirs)',
2334
- handler: async (c, args) => {
2335
- const sub = (args.sub || '').trim().toLowerCase();
2336
- const found = scanSkills();
2337
- const dirs = [
2338
- path.join(os.homedir(), '.aegis', 'skills'),
2339
- path.join(process.cwd(), '.aegis', 'skills'),
2340
- path.join(os.homedir(), '.aegiscode', 'skills'),
2341
- path.join(process.cwd(), '.aegiscode', 'skills'),
2342
- path.join(os.homedir(), '.claude', 'skills'),
2343
- ].map((d) => d.replace(os.homedir(), '~'));
2344
- if (sub === 'refresh' || sub === 'reload') {
2345
- note(c, `Skills refreshed — ${found.length} found (${dirs.length} dirs scanned).`);
2346
- c.render();
2347
- return true;
2348
- }
2349
- if (sub) {
2350
- const skill = found.find((s) => s.name === sub);
2351
- if (!skill) { note(c, `Unknown skill "${sub}". /skills lists what exists on disk.`); c.render(); return true; }
2352
- panel(c, panels.buildSkillDetail(skill, c.ctx));
2353
- c.render();
2354
- return true;
2355
- }
2356
- panel(c, panels.buildSkills(found, dirs, c.ctx));
2357
- c.render();
2358
- return true;
2359
- },
2360
- },
2361
- {
2362
- name: 'thinking', args: ['mode'], hint: '[on|off]', category: 'model',
2363
- desc: 'Toggle thinking blocks expanded/collapsed',
2364
- handler: async (c, args) => {
2365
- const mode = (args.mode || '').toLowerCase();
2366
- if (mode && !['on', 'off'].includes(mode)) { note(c, 'Usage: /thinking [on|off]'); c.render(); return true; }
2367
- const want = mode === 'on' ? true : mode === 'off' ? false : !(c.ctx.thinking === true);
2368
- c.ctx.thinking = want;
2369
- c.saveConfig({ thinking: want });
2370
- note(c, `Thinking blocks: ${want ? 'expanded' : 'collapsed'}`);
2371
- c.render();
2372
- return true;
2373
- },
2374
- },
2375
- {
2376
- name: 'mcp', args: ['sub', 'name', 'command'], hint: '[add <name> <command> [args…]|remove <name>|<name>]', category: 'model',
2377
- desc: 'Show MCP server configuration',
2378
- handler: async (c, args) => {
2379
- const cfg = loadConfig();
2380
- const servers = cfg.mcpServers || {};
2381
- const sub = (args.sub || '').toLowerCase();
2382
- if (sub === 'add') {
2383
- const name = (args.name || '').trim();
2384
- const command = (args.command || '').trim();
2385
- if (!name || !command) { note(c, 'Usage: /mcp add <name> "<command with args>"'); c.render(); return true; }
2386
- const parts = command.split(/\s+/).filter(Boolean);
2387
- updateConfig({ mcpServers: { ...servers, [name]: { command: parts[0], args: parts.slice(1) } } });
2388
- note(c, `Added MCP server "${name}" (${parts[0]}). Configuration only — this build has no MCP runtime.`);
2389
- c.render();
2390
- return true;
2391
- }
2392
- if (sub === 'remove' || sub === 'rm') {
2393
- const name = (args.name || '').trim();
2394
- if (!name) { note(c, 'Usage: /mcp remove <name>'); c.render(); return true; }
2395
- if (!servers[name]) { note(c, `No MCP server "${name}". /mcp lists the configured ones.`); c.render(); return true; }
2396
- const next = { ...servers };
2397
- delete next[name];
2398
- updateConfig({ mcpServers: next });
2399
- note(c, `Removed MCP server "${name}".`);
2400
- c.render();
2401
- return true;
2402
- }
2403
- if (sub && servers[sub]) {
2404
- const srv = servers[sub];
2405
- panel(c, [
2406
- [span(C.gold, `MCP server: ${sub}`)],
2407
- [span(C.gray, '─'.repeat(30))],
2408
- [span(C.white, ` command: ${`${srv.command || ''} ${(srv.args || []).join(' ')}`.trim()}`)],
2409
- [span('', '')],
2410
- [span(C.gray, 'Configuration only — this build has no MCP runtime.')],
2411
- ]);
2412
- c.render();
2413
- return true;
2414
- }
2415
- panel(c, panels.buildMcp(servers, [configPath(), permissionsPath()], c.ctx));
2416
- c.render();
2417
- return true;
2418
- },
2419
- },
2420
- {
2421
- name: 'memory', aliases: ['memories'], hint: '', category: 'model',
2422
- desc: 'List the most recent AEGIS cloud-memory entries',
2423
- tool: 'aegis_memory_list',
2424
- build: () => ({}),
2425
- },
2426
- {
2427
- name: 'memory-deep', aliases: ['recall-deep'], args: ['mode'], hint: '[on|off]', category: 'model',
2428
- desc: 'Toggle DEEP recall for this session — brain corrections + cached answers (metered: one embedding per turn)',
2429
- handler: async (c, args) => {
2430
- const mode = (args.mode || '').toLowerCase();
2431
- if (mode && !['on', 'off'].includes(mode)) { note(c, 'Usage: /memory-deep [on|off]'); c.render(); return true; }
2432
- const want = mode === 'on' ? true : mode === 'off' ? false : !(c.ctx.recallDeep === true);
2433
- c.ctx.recallDeep = want;
2434
- // Deliberately session-scoped: nothing is written to config.json, because
2435
- // this flag meters every turn (aegis1 services/brain_memory.py embeds the
2436
- // query once per turn) and a silent restore on a later launch would bill
2437
- // for a decision made in a session that has ended. Contrast /thinking,
2438
- // which persists — it costs nothing. The cheap read half (`aegis_recall`)
2439
- // is always on and has no toggle.
2440
- note(c, `Deep recall: ${want ? 'on — brain corrections + cached answers, one embedding per turn' : 'off (only the cheap recall read)'}${want ? ' · this session only' : ''}`);
2441
- c.render();
2442
- return true;
2443
- },
2444
- },
2445
- {
2446
- name: 'confirm', aliases: ['confirmations'], args: ['mode'], hint: '[on|off]', category: 'model',
2447
- desc: 'Toggle tool-call confirmation prompts',
2448
- handler: async (c, args) => {
2449
- const mode = (args.mode || '').toLowerCase();
2450
- if (mode && !['on', 'off'].includes(mode)) { note(c, 'Usage: /confirm [on|off]'); c.render(); return true; }
2451
- // ON8: the bare toggle reads the POSTURE (the shared `confirmMode` key
2452
- // both faces write), never the rule file's `defaultMode`.
2453
- //
2454
- // Two reasons, and the second one is the user-visible bug. (1) Since ON8
2455
- // the rule file holds the *residual* (`ask`/`allow`/`deny`) and the shared
2456
- // key holds the posture — reading the residual would answer a question the
2457
- // user did not ask, and `defaultMode: 'deny'` would read as "on". (2) The
2458
- // old spelling (`rules.defaultMode !== 'allow'`) could be turned ON and
2459
- // never OFF from the keyboard: `defaultMode` ships as 'ask', so a fresh
2460
- // install already read as "on" and a bare `/confirm` wrote `ask` — the
2461
- // same state it had just read — leaving prompts on with no way to toggle
2462
- // them off. `confirmPosture()` is the one read, exactly like the engine's.
2463
- const want = mode === 'on' ? true : mode === 'off' ? false : !confirmPosture().enabled;
2464
- // ON8: one writer for the posture — the shared key the window's switch
2465
- // reads, plus the rule residual this face's gate reads.
2466
- setConfirmPosture(want);
2467
- note(c, `Confirmation prompts: ${want ? 'on' : 'off'} (default permission mode: ${want ? 'ask' : 'allow'})`);
2468
- c.render();
2469
- return true;
2470
- },
2471
- },
2472
- {
2473
- name: 'automode', aliases: ['yolo'], args: ['mode'], hint: '[on|off]', category: 'model',
2474
- desc: 'Toggle automode — auto-approve all tool executions',
2475
- handler: async (c, args) => {
2476
- const mode = (args.mode || '').toLowerCase();
2477
- if (mode && !['on', 'off'].includes(mode)) { note(c, 'Usage: /automode [on|off]'); c.render(); return true; }
2478
- // Same one read as `/confirm` above, with the polarity this command's
2479
- // label implies: "automode" IS confirmations-off, so the bare toggle is
2480
- // `!automode` == the posture itself. Reading the rule file here wrongly
2481
- // reported automode as already-on for a fresh install (whose residual
2482
- // ships as 'ask'), so the first bare `/automode` turned it OFF — the
2483
- // opposite of what the word means to the person typing it — and the
2484
- // inverse mistake (`!confirmPosture().enabled`) made the first press a
2485
- // no-op with confirmations on. Both spellings are gone.
2486
- const want = mode === 'on' ? true : mode === 'off' ? false : confirmPosture().enabled;
2487
- // ON8: `/automode` (alias `/yolo`) is the posture's OFF state, written
2488
- // through the one writer, so the window's switch shows it and the two
2489
- // faces cannot disagree.
2490
- setConfirmPosture(!want);
2491
- // …and the SESSION's own half. The posture answers "does the window's
2492
- // switch say don't ask"; the session flag answers "did this sitting start
2493
- // in auto mode". They are two facts (the upstream engine keeps them apart:
2494
- // AEGIS_AUTO_ROUNDS=0 starts manual without touching any stored posture),
2495
- // and with an env opt-out standing, writing only the posture made this
2496
- // command — and the `→` chord that dispatches it — a no-op that reported
2497
- // success: the store said "off", the chip still read "manual mode on", and
2498
- // the tool gate in app.js's isYolo kept asking. Moving both here is what
2499
- // makes the opt-out escapable at the prompt instead of for the life of the
2500
- // process. Guarded because an injected/older context may not carry it.
2501
- if (typeof c.setAutoRounds === 'function') c.setAutoRounds(want);
2502
- if (want) panel(c, panels.buildAutomode(c.state(), c.ctx));
2503
- else note(c, 'automode off — confirmations restored.');
2504
- c.render();
2505
- return true;
2506
- },
2507
- },
2508
- {
2509
- name: 'multiyolo', aliases: ['multiauto'], args: ['task'], hint: '<task>', category: 'session',
2510
- desc: 'Multi-agent orchestration with automode — /multiyolo <task>',
2511
- handler: async (c, args) => {
2512
- const task = (args._rest || args.task || '').trim();
2513
- if (!task) { note(c, 'Usage: /multiyolo <task>'); c.render(); return true; }
2514
- // automode is the point of this alias: auto-approve, then actually run the
2515
- // fan-out. Composing the text and stopping (what this used to do) left the
2516
- // user with an enabled automode and an unexecuted task.
2517
- return runMultiCommand(c, task, { yolo: true });
2518
- },
2519
- },
2520
- {
2521
- name: 'router', args: ['sub', 'tier', 'modelId'], hint: '[on|off|set <tier> <modelId>|stats]', category: 'model',
2522
- desc: 'Show or manage the model router config',
2523
- handler: async (c, args) => {
2524
- const cfg = loadConfig();
2525
- const router = cfg.autoRouter || { enabled: false, tiers: {} };
2526
- const sub = (args.sub || '').toLowerCase();
2527
- const persist = (next) => updateConfig({ autoRouter: next });
2528
- if (sub === 'on') { persist({ ...router, enabled: true }); note(c, 'Auto-router: on.'); c.render(); return true; }
2529
- if (sub === 'off') { persist({ ...router, enabled: false }); note(c, 'Auto-router: off.'); c.render(); return true; }
2530
- if (sub === 'set') {
2531
- const tier = (args.tier || '').toLowerCase();
2532
- const modelId = (args.modelId || '').trim();
2533
- if (!['simple', 'medium', 'complex'].includes(tier) || !modelId) {
2534
- note(c, 'Usage: /router set <simple|medium|complex> <modelId>');
2535
- c.render();
2536
- return true;
2537
- }
2538
- persist({ ...router, tiers: { ...(router.tiers || {}), [tier]: modelId } });
2539
- note(c, `Auto-router: ${tier} -> ${modelId}`);
2540
- c.render();
2541
- return true;
2542
- }
2543
- if (sub === 'stats') {
2544
- panel(c, [
2545
- [span(C.gold + BOLD, 'Router stats'), span(BOLD_OFF, '')],
2546
- [span(C.gray, '─'.repeat(30))],
2547
- [span(C.gray, 'No learned outcomes yet — this build does not auto-route.')],
2548
- [span(C.gray, 'Tiers: simple/medium/complex via /router set.')],
2549
- ]);
2550
- c.render();
2551
- return true;
2552
- }
2553
- panel(c, panels.buildRouter(cfg, c.ctx));
2554
- c.render();
2555
- return true;
2556
- },
2557
- },
2558
- {
2559
- name: 'multi', args: ['task', 'mode'], hint: '<task> [run]', category: 'session',
2560
- desc: 'Compose a multi-agent task (add "run" to execute)',
2561
- handler: async (c, args) => {
2562
- let task = (args._rest || args.task || '').trim();
2563
- let mode = (args.mode || '').toLowerCase();
2564
- if (mode !== 'run' && /\s+run$/i.test(task)) { mode = 'run'; task = task.replace(/\s+run$/i, '').trim(); }
2565
- if (!task) { note(c, 'Usage: /multi <task> [run]'); c.render(); return true; }
2566
- if (mode !== 'run') { panel(c, panels.buildAegisMulti(task, c.ctx)); c.render(); return true; }
2567
- return runMultiCommand(c, task);
2568
- },
2569
- },
2570
- {
2571
- name: 'research', args: ['question'], hint: '<question>', category: 'session',
2572
- desc: 'Research a topic with a multi-perspective council prompt',
2573
- handler: async (c, args) => {
2574
- const q = (args._rest || args.question || '').trim();
2575
- if (!q) { note(c, 'Usage: /research <question>'); c.render(); return true; }
2576
- const prompt = composeResearchPrompt(q, process.cwd());
2577
- // Unguarded, `c.runPrompt` made this throw on any context without one
2578
- // (the command smoke test caught the class of bug; the reference guards
2579
- // it the same way). Composed-but-unrunnable is reported, not swallowed.
2580
- if (c.runPrompt) {
2581
- await c.runPrompt(prompt);
2582
- return true;
2583
- }
2584
- note(c, `Composed research prompt (${prompt.length} chars) — run in the TUI to send it.`);
2585
- c.render();
2586
- return true;
2587
- },
2588
- },
2589
- {
2590
- name: 'debate', aliases: ['db'], args: ['topic'], hint: '<topic>', category: 'session',
2591
- desc: 'Run a structured debate on the current model',
2592
- handler: async (c, args) => {
2593
- const topic = (args._rest || args.topic || '').trim();
2594
- if (!topic) { note(c, 'Usage: /debate <topic>'); c.render(); return true; }
2595
- const prompt = composeDebatePrompt(topic, c.ctx.model || '');
2596
- if (c.runPrompt) {
2597
- await c.runPrompt(prompt);
2598
- return true;
2599
- }
2600
- note(c, `Composed debate prompt (${prompt.length} chars) — run in the TUI to send it.`);
2601
- c.render();
2602
- return true;
2603
- },
2604
- },
2605
- {
2606
- name: 'billing', aliases: ['balance', 'spend'], hint: '', category: 'support',
2607
- desc: 'Show billing info — token-bank balance and recent spend',
2608
- handler: async (c) => {
2609
- // The account is the source of truth for the balance and ledger; the
2610
- // session panel below adds this session's spend.
2611
- await c.runTool('aegis_balance', {});
2612
- const spend = await c.refreshSpend();
2613
- const st = c.state();
2614
- panel(c, panels.buildBilling({
2615
- ...st,
2616
- balance: spend && spend.balance != null ? spend.balance : st.balance,
2617
- // The paid prompt, from the SAME gate that decides the fan-out. This is
2618
- // the whole reason `/billing` can be trusted to say what Pro costs: the
2619
- // verdict and the ceiling come from one decision (`is_pro` mirrored by
2620
- // the shared module) instead of a second, panel-local guess about the
2621
- // account — two readings is how a screen ends up selling Pro to someone
2622
- // who owns it, or telling a paying customer their bank is empty.
2623
- //
2624
- // A probe that cannot be built (no shared module, no client) leaves the
2625
- // field unset: the panel then prints its plain top-up row rather than an
2626
- // unverified pitch. Never the reverse — a failure here must not invent
2627
- // a wall.
2628
- payment: await billingPayment(c),
2629
- }, c.ctx));
2630
- c.render();
2631
- return true;
2632
- },
2633
- },
2634
- {
2635
- // The in-session top-up. `/billing` printed a link and that was the whole
2636
- // funding story in the terminal; the link is real but it lands on `/topup`,
2637
- // which is `@login_required` against a browser SESSION, and the account this
2638
- // product auto-provisions is a device key with no password anyone holds and
2639
- // an email at `@device.aegiscloud`. So the user who needs to fund a free
2640
- // account could not sign in to the page that funds it — they paid a visit to
2641
- // a login wall and read it as "my payment failed".
2642
- //
2643
- // This does what the desktop does, over the SAME shared core
2644
- // (`client/topup.js`): the credential that creates the checkout is the one
2645
- // that can read the bank, so the confirmation comes from the API rather than
2646
- // from a page the account cannot open. Bounds and payload reading are shared,
2647
- // never re-derived here.
2648
- name: 'topup', aliases: ['fund'], args: ['amount'], hint: '[EUR]', category: 'support',
2649
- desc: 'Top up the token bank — opens the payment page and confirms the credit here',
2650
- handler: async (c, args) => {
2651
- const raw = String(args.amount || args._rest || '').trim();
2652
- let shared;
2653
- try {
2654
- // Lazy: the TUI pays for this only when someone asks to pay.
2655
- shared = require(require('./sharedpaths.js').resolveShared('client/topup.js'));
2656
- } catch (e) {
2657
- note(c, `top-up is unavailable in this build — ${e.message}`);
2658
- c.render();
2659
- return true;
2660
- }
2661
- const parsed = shared.parseTopupAmount(raw);
2662
- if (!parsed.ok) {
2663
- note(c, parsed.message);
2664
- c.render();
2665
- return true;
2666
- }
2667
- if (!c.client.apiKey) {
2668
- // Same honest refusal the rest of the account surfaces give, and the
2669
- // same fix: the key is what pays. Auto-provisioning happens on session
2670
- // start (app.js ensureApiKey), so this is the offline/failed case.
2671
- note(c, `no AEGIS key on this machine — ${credentials.HOW_TO_SET}, then /topup ${parsed.amount}`);
2672
- c.render();
2673
- return true;
2674
- }
2675
- const started = c.withWorking
2676
- ? await c.withWorking(() => shared.startTopup(c.client, parsed.amount))
2677
- : await shared.startTopup(c.client, parsed.amount);
2678
- if (!started.ok) {
2679
- note(c, `the top-up could not be started — ${started.message}`);
2680
- if (started.hint) note(c, started.hint);
2681
- c.render();
2682
- return true;
2683
- }
2684
- // The URL rides its own row: `note` rows are a single unwrapped span
2685
- // (chatflow.js), so appending it to that sentence pushes the tail past
2686
- // `cols` where `padLine()` cuts it — and the tail is the URL.
2687
- note(c, `opening the payment page — ${parsed.amount} EUR`);
2688
- note(c, started.url);
2689
- const seconds = Math.round((shared.TOPUP_POLL_MS * shared.TOPUP_POLL_TRIES) / 1000);
2690
- note(c, `watching this account's bank for up to ${seconds}s; the credit is confirmed here, not in the browser`);
2691
- c.render();
2692
- const open = openUrl(started.url);
2693
- if (!open) note(c, 'could not open a browser — use the URL above');
2694
-
2695
- // A recursive timeout rather than an interval: the balance call can take
2696
- // longer than one period on a slow link, and an interval would start a
2697
- // second read on top of the first — two reads, two announcements of one
2698
- // credit. Unref'd so an unfinished payment never keeps the TUI alive.
2699
- const watch = shared.createCreditWatch(c.client);
2700
- let timer = null;
2701
- let done = false;
2702
- const settle = () => {
2703
- done = true;
2704
- if (timer) clearTimeout(timer);
2705
- };
2706
- const step = async () => {
2707
- if (done) return;
2708
- const res = await watch.tick();
2709
- if (res.state === 'credited') {
2710
- settle();
2711
- note(c, `credit confirmed — the bank is now ${res.amount.toFixed(2)} EUR`);
2712
- c.render();
2713
- return;
2714
- }
2715
- if (res.state === 'expired') {
2716
- settle();
2717
- note(c, 'no credit observed within the watch window — if you completed the payment it may still land; /billing shows the bank');
2718
- c.render();
2719
- return;
2720
- }
2721
- timer = setTimeout(step, shared.TOPUP_POLL_MS);
2722
- if (timer && typeof timer.unref === 'function') timer.unref();
2723
- };
2724
- timer = setTimeout(step, shared.TOPUP_POLL_MS);
2725
- if (timer && typeof timer.unref === 'function') timer.unref();
2726
- return true;
2727
- },
2728
- },
2729
- {
2730
- name: 'cloud', args: ['sub', 'value'], hint: '[status|key <api_key>|activate|deactivate|memory [on|off]|sync [on|off|now]]', category: 'support',
2731
- desc: 'Show and control ÆGIS cloud sync',
2732
- handler: async (c, args) => {
2733
- const sub = (args.sub || '').toLowerCase();
2734
- const rest = (args.value || args._rest || '').trim();
2735
-
2736
- if (sub === 'key') {
2737
- await applyAccountKey(c, rest);
2738
- c.render();
2739
- return true;
2740
- }
2741
-
2742
- if (sub === 'activate') {
2743
- if (!c.client.apiKey) {
2744
- note(c, `no key — ${credentials.HOW_TO_SET}`);
2745
- c.render();
2746
- return true;
2747
- }
2748
- try {
2749
- const res = await c.withWorking(() => c.client.memoryActivate());
2750
- const token = await c.client.getMemoryToken();
2751
- if (token) credentials.saveMemoryToken(token, { memorySubscribed: true });
2752
- done(c, res && res.ok === false ? 'the server refused activation' : 'cloud memory activated for this account');
2753
- if (res && res.token_limit) note(c, `quota: ${res.tokens_used || 0} / ${res.token_limit} synced tokens`);
2754
- } catch (e) {
2755
- note(c, `activation failed: ${e.message}`);
2756
- }
2757
- c.render();
2758
- return true;
2759
- }
2760
-
2761
- if (sub === 'deactivate') {
2762
- // There is no /api/memory/deactivate on the server, so this clears the
2763
- // credential this host holds rather than pretending to unenrol the
2764
- // account. Saying which one it did is the difference between a control
2765
- // and a lie.
2766
- credentials.clearMemoryToken();
2767
- c.client.setApiKey(c.client.apiKey);
2768
- note(c, 'cloud memory token cleared locally — sync stops until /cloud activate re-issues one');
2769
- // The URL rides its own note: `note` rows are a single unwrapped span
2770
- // (chatflow.js), so appending it to that sentence would push the tail
2771
- // past `cols` where `padLine()` cuts it — and the tail is the URL.
2772
- note(c, 'the account itself is still subscribed; manage the subscription here:');
2773
- note(c, goUrl('upgrade', 'cloud_deactivate'));
2774
- c.render();
2775
- return true;
2776
- }
2777
-
2778
- if (sub === 'memory' || sub === 'persist' || sub === 'memory-persist') {
2779
- // The write half's one switch. `/cloud sync on|off` and `/sync on|off`
2780
- // still work (they always meant "should this host store my sessions"),
2781
- // but this is the name that says what is actually being flipped.
2782
- const mode = (rest || 'status').toLowerCase();
2783
- if (mode === 'on' || mode === 'off') {
2784
- const on = mode === 'on';
2785
- setMemoryGate(c, on);
2786
- if (on) {
2787
- done(c, 'persisting memory on — sessions are stored to your account so an interrupted turn can be resumed');
2788
- note(c, '/cloud memory shows the quota; past the plan’s ceiling reads keep working and only new writes pause');
2789
- } else {
2790
- note(c, 'persisting memory off — nothing new is stored');
2791
- note(c, 'everything already in the cloud stays readable (/aegis-recall <topic>), and /sync now still pushes once by hand');
2792
- }
2793
- c.render();
2794
- return true;
2795
- }
2796
- panel(c, memoryStatusLines(c));
2797
- c.render();
2798
- return true;
2799
- }
2800
-
2801
- if (sub === 'sync' || sub === 'push' || sub === 'pull') {
2802
- const mode = sub === 'sync' ? (rest || 'status').toLowerCase() : sub;
2803
- if (mode === 'on' || mode === 'off') {
2804
- const on = mode === 'on';
2805
- setMemoryGate(c, on);
2806
- note(c, on ? 'persisting memory on — sessions are stored after each turn (this is the old "cloud sync")' : 'persisting memory off — nothing new is stored; /sync now still runs a manual pass');
2807
- c.render();
2808
- return true;
2809
- }
2810
- if (mode === 'now') {
2811
- await runCloudSync(c);
2812
- c.render();
2813
- return true;
2814
- }
2815
- const st = cloudsync.status();
2816
- panel(c, [
2817
- ...memoryStatusLines(c),
2818
- [span(C.gray, '')],
2819
- [span(C.white + BOLD, 'Sync ledger'), span(BOLD_OFF, '')],
2820
- [span(C.gray, ` local sessions: ${st.local} · pending push: ${st.pending} · in sync: ${st.synced}`)],
2821
- [span(C.gray, ` last push: ${st.lastPushAt ? new Date(st.lastPushAt).toLocaleString() : 'never'} · last pull: ${st.lastPullAt ? new Date(st.lastPullAt).toLocaleString() : 'never'}`)],
2822
- [span(C.gray, ` state: ${st.path}`)],
2823
- ]);
2824
- for (const e of st.errors.slice(0, 3)) {
2825
- panel(c, [[span(C.coral, ` ⚠ ${e.error}`)]]);
2826
- }
2827
- c.render();
2828
- return true;
2829
- }
2830
-
2831
- // Default: the whole picture — key plus sync state.
2832
- const st = cloudsync.status();
2833
- panel(c, [
2834
- ...keyPanelLines(c, 'AEGIS cloud'),
2835
- [span(C.gray, '')],
2836
- ...memoryStatusLines(c),
2837
- [span(C.gray, '')],
2838
- [span(C.white + BOLD, ' Sync'), span(BOLD_OFF, '')],
2839
- [span(C.gray, ` ${st.pending} pending · ${st.synced} in sync · ${st.importedRemote} pulled from cloud`)],
2840
- // Both names, because both work: `/cloud memory` is the new one that
2841
- // says what is being flipped, and `/cloud sync` is what every user who
2842
- // has ever turned this off typed (it dispatched here before the flip
2843
- // renamed the panel, and still does — see the `sub === 'sync'` branch).
2844
- // Advertising only the new name hides a working control behind a
2845
- // rename, which is how a setting becomes a rumour.
2846
- [span(C.gray, ' /cloud memory on | off · /cloud sync on | off · /sync now')],
2847
- ]);
2848
- c.render();
2849
- return true;
2850
- },
2851
- },
2852
- {
2853
- name: 'key', aliases: ['apikey', 'api-key'], args: ['value'], hint: '[<api_key>|status|clear|register]', category: 'auth',
2854
- desc: 'Save or show the AEGIS account key',
2855
- handler: async (c, args) => {
2856
- const arg = String(args.value || args._rest || '').trim();
2857
- const lower = arg.toLowerCase();
2858
- if (lower === 'status') {
2859
- panel(c, keyPanelLines(c));
2860
- c.render();
2861
- return true;
2862
- }
2863
- if (lower === 'register') {
2864
- const res = await c.registerAccount();
2865
- if (res.alreadyKeyed) {
2866
- // Registration is per machine fingerprint and the welcome trial is
2867
- // granted once per machine, ever, so this branch can never produce a
2868
- // new trial however many times it is run — and a user who wiped their
2869
- // credential store lands here precisely expecting one. Say so, and
2870
- // name the two paths that actually do something, rather than a
2871
- // no-op notice that reads like a refusal for no reason.
2872
- note(c, 'this machine already has an AEGIS key — /key status shows it. Re-registering cannot mint a new welcome trial: that is granted once per machine, ever. For a fresh trial, sign up at aegiscloud.org; to point this session at a different key, /key clear first.');
2873
- } else if (res.key && res.ok) {
2874
- done(c, 'AEGIS account key provisioned and saved');
2875
- } else if (res.key) {
2876
- note(c, 'the account was created but its key could not be saved — run /key <api_key> with the key from aegiscloud.org');
2877
- } else {
2878
- note(c, `could not register this machine: ${res.error ? res.error.message : 'the server returned no account key'}`);
2879
- }
2880
- c.render();
2881
- return true;
2882
- }
2883
- if (lower === 'clear' || lower === 'remove' || lower === 'rm') {
2884
- const res = c.forgetApiKey();
2885
- done(c, res.cleared ? `key removed from ${res.path}` : 'there was no saved key to remove');
2886
- if (credentials.legacyKeyOnDisk()) {
2887
- note(c, `a copy is still in ${configPath()} (written by another AEGIS CLI) — delete the "aegiscloud" block to finish the job`);
2888
- }
2889
- c.render();
2890
- return true;
2891
- }
2892
- await applyAccountKey(c, arg);
2893
- c.render();
2894
- return true;
2895
- },
2896
- },
2897
- {
2898
- name: 'sync', aliases: ['cloudsync', 'cloud-sync'], args: ['mode'], hint: '[now|on|off|status]', category: 'data',
2899
- desc: 'Store sessions in AEGIS Cloud (cross-session memory)',
2900
- hidden: (c) => !cloudReady(),
2901
- handler: async (c, args) => {
2902
- const mode = (args.mode || '').toLowerCase();
2903
- if (mode === 'on' || mode === 'off') {
2904
- setMemoryGate(c, mode === 'on');
2905
- note(c, mode === 'on' ? 'persisting memory on — sessions are stored so an interrupted turn can be resumed' : 'persisting memory off — nothing new is stored; /sync now still runs a manual pass');
2906
- c.render();
2907
- return true;
2908
- }
2909
- if (mode === 'status') {
2910
- const st = cloudsync.status();
2911
- const rows = memoryStatusLines(c);
2912
- rows.push([span(C.gray, '')]);
2913
- rows.push([span(C.gray, ` local ${st.local} · pending ${st.pending} · in sync ${st.synced}`)]);
2914
- panel(c, rows);
2915
- c.render();
2916
- return true;
2917
- }
2918
- // Bare /sync and /sync now both do the thing: this is the command a user
2919
- // reaches for when they want their sessions in the cloud right now.
2920
- await runCloudSync(c);
2921
- c.render();
2922
- return true;
2923
- },
2924
- },
2925
- {
2926
- name: 'gmail', hint: '', category: 'support',
2927
- desc: 'Link Gmail to conversations',
2928
- handler: async (c) => {
2929
- note(c, 'Gmail integration needs Google OAuth — not available in this build. Use /export to save conversations to files instead.');
2930
- c.render();
2931
- return true;
2932
- },
2933
- },
2934
- {
2935
- name: 'clone', aliases: ['fetch-site', 'websnap'], args: ['url'], hint: '<url>', category: 'workspace',
2936
- desc: 'Clone a website into a local project',
2937
- handler: async (c, args) => {
2938
- const url = (args._rest || args.url || '').trim();
2939
- if (!url) { note(c, 'Usage: /clone <url>'); c.render(); return true; }
2940
- note(c, `/clone needs a web-fetch tool and a chat service — not available in this build. Use /init to scaffold a fresh project instead of ${url}.`);
2941
- c.render();
2942
- return true;
2943
- },
2944
- },
2945
- {
2946
- name: 'release-notes', hint: '', category: 'support',
2947
- desc: "What's new",
2948
- handler: async (c) => {
2949
- panel(c, panels.buildReleaseNotes(c.state(), c.ctx));
2950
- c.render();
2951
- return true;
2952
- },
2953
- },
2954
-
2955
- // ── /aegis-* family ───────────────────────────────────────────────────────
2956
- {
2957
- name: 'aegis-status', hint: '', category: 'aegis',
2958
- desc: 'Show account status — API key, plan, account and cloud memory',
2959
- tool: 'aegis_status',
2960
- build: () => ({}),
2961
- },
2962
- {
2963
- name: 'aegis-ask', aliases: ['ask'], args: ['question'], hint: '<question>', category: 'aegis',
2964
- desc: 'Ask ÆGIS pooled inference a question (auto-routed)',
2965
- tool: 'aegis_ask',
2966
- build: (arg) => ({ prompt: arg }),
2967
- },
2968
- {
2969
- name: 'aegis-recall', aliases: ['recall'], args: ['topic'], hint: '<topic>', category: 'aegis',
2970
- desc: 'Recall cross-session memory about a topic (cloud)',
2971
- tool: 'aegis_memory_search',
2972
- build: (arg) => ({ query: arg }),
2973
- },
2974
- {
2975
- name: 'aegis-remember', aliases: ['remember'], args: ['note'], hint: '<note>', category: 'aegis',
2976
- desc: 'Save a note or decision to cross-session memory',
2977
- tool: 'aegis_memory_save',
2978
- build: (arg) => ({ content: arg }),
2979
- },
2980
- {
2981
- name: 'aegis-council', aliases: ['council'], args: ['question'], hint: '<question>', category: 'aegis',
2982
- desc: 'Put a question to the ÆGIS council (multi-perspective deliberation)',
2983
- hidden: () => !cloudReady(),
2984
- handler: async (c, args) => {
2985
- const q = (args._rest || args.question || '').trim();
2986
- if (!q) { note(c, 'Usage: /aegis-council <question>'); c.render(); return true; }
2987
- const prompt = composeResearchPrompt(`Deliberate as a council and vote on: ${q}`, process.cwd());
2988
- if (c.runPrompt) {
2989
- await c.runPrompt(prompt);
2990
- return true;
2991
- }
2992
- note(c, `Composed council prompt (${prompt.length} chars) — run in the TUI to send it.`);
2993
- c.render();
2994
- return true;
2995
- },
2996
- },
2997
- {
2998
- name: 'aegis-print', args: ['question'], hint: '<question>', category: 'aegis',
2999
- desc: 'Ask pooled inference and print the answer cleanly',
3000
- hidden: () => !cloudReady(),
3001
- handler: async (c, args) => {
3002
- const q = (args._rest || args.question || '').trim();
3003
- if (!q) { note(c, 'Usage: /aegis-print <question>'); c.render(); return true; }
3004
- const res = await c.ask(q);
3005
- panel(c, panels.buildAegisPrint('ÆGIS', { result: res.text, model: res.model, provider: 'aegis' }, c.ctx));
3006
- c.render();
3007
- return true;
3008
- },
3009
- },
3010
- {
3011
- name: 'aegis-multi', args: ['task', 'mode'], hint: '<task> [run]', category: 'aegis',
3012
- desc: 'Compose an ÆGIS /multi multi-agent task (add "run" to execute)',
3013
- hidden: () => !cloudReady(),
3014
- handler: async (c, args) => {
3015
- let task = (args._rest || args.task || '').trim();
3016
- let mode = (args.mode || '').toLowerCase();
3017
- if (mode !== 'run' && /\s+run$/i.test(task)) { mode = 'run'; task = task.replace(/\s+run$/i, '').trim(); }
3018
- if (!task) { note(c, 'Usage: /aegis-multi <task> [run]'); c.render(); return true; }
3019
- if (mode !== 'run') { panel(c, panels.buildAegisMulti(task, c.ctx)); c.render(); return true; }
3020
- return runMultiCommand(c, task);
3021
- },
3022
- },
3023
-
3024
- // ── cloud-only additions (not in the reference vocabulary) ────────────────
3025
- {
3026
- // A bare `provider -> info` map is the wrong shape for a picker: it can only
3027
- // describe providers you have ALREADY set, and the question this command
3028
- // answers is "which key should I go buy". A command is either handler- or
3029
- // tool-backed, never both (`cli-commands.test.mjs` enforces exactly one), so
3030
- // this is handler-backed and reaches for the tool by name only as the
3031
- // fallback for a server that predates the catalog — the command still works,
3032
- // just with the older, sparser answer.
3033
- name: 'byok', hint: '', category: 'auth',
3034
- desc: 'List every provider you can bring your own key for, and which are set',
3035
- handler: async (c) => {
3036
- const providers = await byokCatalog(c.client);
3037
- if (!providers) {
3038
- await c.runTool('aegis_byok_status', {});
3039
- return true;
3040
- }
3041
- const set = providers.filter((p) => p.configured).length;
3042
- const lines = [
3043
- [span(C.gold + BOLD, 'Bring your own key'), span(BOLD_OFF, '')],
3044
- [span(C.gray, '─'.repeat(34))],
3045
- [
3046
- span(set ? C.green : C.gray, ` ${set} of ${providers.length} providers set`),
3047
- // Name the PICKER first: the id is the one thing this screen was
3048
- // asking the reader to copy by eye, and `/byok-list` removes that
3049
- // step. The typed form stays beside it for scripts and for anyone who
3050
- // already knows the id.
3051
- span(C.gray, ' — /byok-list picks one, or /byok-key <provider>'),
3052
- ],
3053
- '',
3054
- ...byokProviderLines(providers),
3055
- ];
3056
- panel(c, lines);
3057
- c.render();
3058
- return true;
3059
- },
3060
- },
3061
- {
3062
- name: 'byok-set', args: ['provider'], hint: '<provider>', category: 'auth',
3063
- desc: 'Store your provider key on your AEGIS ACCOUNT (pooled route) — for the byok class use /byok-key',
3064
- tool: 'aegis_byok_set',
3065
- secret: 'key',
3066
- build: (arg) => ({ provider: String(arg || '').trim() }),
3067
- /**
3068
- * Say which key this is and where to get it, before the prompt.
3069
- *
3070
- * The old prompt was `provider key for openai:` — which assumes the reader
3071
- * already knows that a provider id is a company, and leaves them nothing to
3072
- * check a pasted key against. Here the catalog names the provider, lists the
3073
- * models the key unlocks, links the place to create it, and states the
3074
- * prefix a valid key begins with, so a key for the wrong vendor is visible
3075
- * before it is stored rather than as an upstream 401 later.
3076
- *
3077
- * Resolved against aliases too, so the prompt agrees with the id that will
3078
- * actually be sent (`/byok-set OpenAI` → `openai`, not `OpenAI`).
3079
- */
3080
- async secretDescribe(args, client) {
3081
- const typed = String(args.provider || '').trim();
3082
- const providers = await byokCatalog(client);
3083
- if (!providers) {
3084
- // No catalog: still refuse to prompt for an empty provider, and keep the
3085
- // words "provider key" so the request is intelligible on its own.
3086
- return typed ? null : { note: 'Usage: /byok-set <provider> — /byok lists them.', prompt: 'provider key: ' };
3087
- }
3088
- const match = findByokProvider(providers, typed);
3089
- if (match.ambiguous) {
3090
- return {
3091
- note: `"${typed}" matches ${match.ambiguous.join(', ')} — retype the exact id. Nothing was sent.`,
3092
- prompt: null,
3093
- };
3094
- }
3095
- const p = match.provider;
3096
- if (!p) {
3097
- const ids = providers.map((x) => x.id).join(', ');
3098
- return { note: `unknown provider "${typed}". Known ids: ${ids}`, prompt: null };
3099
- }
3100
- if (p.configured) {
3101
- return {
3102
- note: `${p.id} already has a key${p.masked ? ` (${p.masked})` : ''} — pasting a new one replaces it.`,
3103
- prompt: `new ${p.label || p.id} key: `,
3104
- provider: p.id,
3105
- };
3106
- }
3107
- const bits = [`${p.label || p.id}`];
3108
- const models = (p.models || [])
3109
- .map((m) => (typeof m === 'string' ? m : m && m.id))
3110
- .filter(Boolean);
3111
- if (models.length) bits.push(`unlocks ${models.join(', ')}`);
3112
- if (p.key_prefix) bits.push(`key starts with ${p.key_prefix}`);
3113
- if (p.key_url) bits.push(`create one at ${p.key_url}`);
3114
- return { note: bits.join(' · '), prompt: `${p.id} key: `, provider: p.id };
3115
- },
3116
- },
3117
- {
3118
- name: 'byok-rm', args: ['provider'], hint: '<provider>', category: 'auth',
3119
- desc: 'Remove a stored provider key',
3120
- tool: 'aegis_byok_set',
3121
- build: (arg) => ({ provider: String(arg || '').trim() }),
3122
- },
3123
- {
3124
- name: 'class', args: ['class', 'mode'], hint: '[aegis|byok|local|pro [on|off]]', category: 'model',
3125
- desc: 'Show or switch which class turns run on; pro (your Claude subscription) needs a one-time "on"',
3126
- handler: async (c, a) => {
3127
- const args = a || {};
3128
- const cur = (c.ctx && c.ctx.modelClass) || 'aegis';
3129
- const label = (id) => (c.classLabel ? c.classLabel(id) : id);
3130
- const want = String(args.class || '').trim().toLowerCase();
3131
- // `/class pro on|off` — the one-time opt-in for the subscription class.
3132
- //
3133
- // `pro` spends a real Claude Code Pro/Max subscription by spawning the
3134
- // `claude` CLI, and an account whose organization has disabled Claude
3135
- // Code answers every such turn with `oauth_org_not_allowed`, which this
3136
- // repo cannot fix. So `pro` ships DISABLED (config.js `proEnabled: false`)
3137
- // and this is the only way in: an explicit, deliberate word from the
3138
- // user. Written through saveConfig so it survives a restart — an opt-in
3139
- // that reverted on the next launch would put the class back out of reach
3140
- // with no way to tell why.
3141
- if (want === 'pro' && args.mode) {
3142
- const mode = String(args.mode).trim().toLowerCase();
3143
- if (mode !== 'on' && mode !== 'off') {
3144
- c.push({ role: 'error', text: `usage: /class pro [on|off] — got "${args.mode}"` });
3145
- return true;
3146
- }
3147
- const on = mode === 'on';
3148
- c.saveConfig({ proEnabled: on });
3149
- c.push({
3150
- role: on ? 'done' : 'note',
3151
- text: on
3152
- ? 'pro class enabled — /class pro switches to your Claude Code subscription. ' +
3153
- 'It runs only if that subscription has Claude Code access.'
3154
- : 'pro class disabled — it is no longer offered by /class or the model picker.',
3155
- });
3156
- // Turning it off while sitting on it would leave the session pointing
3157
- // at a class that can no longer run: fall back to the default class
3158
- // through the same path `/class aegis` takes, so the pin rules and the
3159
- // stored config are updated rather than only the panel.
3160
- if (!on && cur === 'pro') {
3161
- const back = c.switchClass('aegis');
3162
- if (back.ok) c.push({ role: 'note', text: `class: ${back.class} — ${label(back.class)}` });
3163
- }
3164
- return true;
3165
- }
3166
- if (!want) {
3167
- // Awaited: the engine's listClasses() is async (it probes for a local
3168
- // Ollama before answering), and a context that offers no class surface
3169
- // at all falls back to the two static rows below.
3170
- const classes = await Promise.resolve(c.classes ? c.classes() : []).catch(() => []);
3171
- const rows = classes.length ? classes : [{ class: 'aegis' }, { class: 'byok' }];
3172
- const sel = rows.findIndex((k) => k.class === cur);
3173
- // An interactive picker, not a static panel — the same tab/arrow/enter
3174
- // overlay machinery /model already uses (chatflow.js handleOverlayKey),
3175
- // so a class is switched by moving the highlight and hitting enter
3176
- // rather than retyping its name after reading it off this list.
3177
- c.openOverlay({ type: 'class', items: rows, sel: sel < 0 ? 0 : sel, current: cur });
3178
- return true;
3179
- }
3180
- const res = c.switchClass(want);
3181
- if (!res.ok) {
3182
- c.push({ role: 'error', text: res.error });
3183
- return true;
3184
- }
3185
- c.push({ role: 'done', text: `class: ${res.class} — ${label(res.class)}` });
3186
- if (res.cleared) {
3187
- c.push({
3188
- role: 'note',
3189
- text: `cleared the pin "${res.cleared}" — it does not belong to this class. /models lists what fits.`,
3190
- });
3191
- }
3192
- // Entering byok with nothing pinned fails the very next turn: the relay's
3193
- // model id must be "<provider>:<model>" and there is no server default to
3194
- // fall back to (engine.js chatCompletion throws a 400 on a bare id). So
3195
- // land on one this machine can actually run — a provider it holds a key
3196
- // for wins, since the alternative 400s on the key rather than the id.
3197
- if (res.class === 'byok' && !(c.ctx && c.ctx.model)) {
3198
- // The byok list carries the pooled Nexus row too (app.js
3199
- // classScopedModels) so the lane is discoverable — but this host cannot
3200
- // RUN it under byok: the relay reads a pinned id as a provider name, so
3201
- // auto-pinning Nexus here would fail the very next turn, which is the
3202
- // failure this whole branch exists to avoid. Pick from this class's own
3203
- // rows only.
3204
- const models = ((await c.listModelsFor('byok')) || [])
3205
- .filter((m) => !m.cls || m.cls === 'byok');
3206
- const pick = models.find((m) => m.configured) || models[0];
3207
- if (pick) {
3208
- c.ctx.model = pick.id;
3209
- c.saveConfig({ model: pick.id, currentModelId: pick.id });
3210
- c.push({
3211
- role: 'note',
3212
- text: pick.configured
3213
- ? `using ${pick.id} — /models lists the rest.`
3214
- : `using ${pick.id}, but no ${pick.provider} key is saved yet — /byok-key ${pick.provider}.`,
3215
- });
3216
- } else if (models.length === 0) {
3217
- c.push({
3218
- role: 'note',
3219
- text: 'nothing to relay yet — save a provider key with /byok-key <provider>, then /models.',
3220
- });
3221
- }
3222
- }
3223
- return true;
3224
- },
3225
- },
3226
- {
3227
- name: 'models', aliases: ['model-list'], hint: '', category: 'model',
3228
- desc: 'Pick a model to pin, for the class you are on — opens the same picker as /model',
3229
- handler: async (c) => {
3230
- const cls = (c.ctx && c.ctx.modelClass) || 'aegis';
3231
- const models = (await c.listModelsFor(cls)) || [];
3232
- if (!models.length) {
3233
- note(c, cls === 'byok'
3234
- ? 'nothing to relay yet — save a provider key with /byok-key <provider>'
3235
- : 'no models advertised — check the account with /status, then retry');
3236
- c.render();
3237
- return true;
3238
- }
3239
- const pinned = c.ctx && c.ctx.model;
3240
- // A row from the OTHER class rides on this list on purpose — the pooled
3241
- // Nexus row is what makes the byok list able to show a way back to the
3242
- // pooled lane (app.js classScopedModels). It is not a row of THIS
3243
- // class's own ids, so its note says which class it actually runs on
3244
- // instead of looking like a byok id that would 400 at the relay.
3245
- const items = models.map((m) => (m.cls && m.cls !== cls
3246
- ? { ...m, note: `${m.note || m.label || ''} · pooled lane — /class ${m.cls}` }
3247
- : m));
3248
- const sel = items.findIndex((m) => m.id === pinned);
3249
- // Same overlay /model opens (tab/arrow to move, enter to pin — see
3250
- // chatflow.js handleOverlayKey), just scoped to this class's own rows
3251
- // rather than /model's merged cross-class catalog. Picking the other
3252
- // class's row switches class first, the same cross-class pin
3253
- // applyModelRow already does for /model's own rows.
3254
- c.openOverlay({ type: 'model', items, sel: sel < 0 ? 0 : sel, current: pinned, cls });
3255
- return true;
3256
- },
3257
- },
3258
- {
3259
- // `/byok-list` — pick a provider from the catalog and store its key on THIS
3260
- // machine, the same route `/byok-key` takes once a provider is named. The
3261
- // picker is the point: the provider id was the one thing this flow asked
3262
- // the user to recall and retype, and a retyped or alias-matched id either
3263
- // matched nothing or matched another vendor. Arrow or Tab moves the
3264
- // highlight, Enter picks, and the id dispatched is the catalog's own — so
3265
- // the key lands under the id the relay will be asked for, and that
3266
- // provider's models then show up in `/model`.
3267
- name: 'byok-list', aliases: ['byok-pick'], hint: '', category: 'auth',
3268
- desc: 'Pick a provider to set a key for, then its models appear in /model',
3269
- handler: async (c) => {
3270
- const providers = await byokCatalog(c.client);
3271
- if (!providers || !providers.length) {
3272
- c.push({
3273
- role: 'error',
3274
- text: 'Could not read the provider catalog (offline, or no AEGIS key) — /byok lists what is known.',
3275
- });
3276
- return true;
3277
- }
3278
- if (typeof c.openOverlay !== 'function') {
3279
- // No interactive host: fall back to the printable list rather than a
3280
- // picker nothing can draw.
3281
- c.push({ role: 'note', text: '/byok-key <provider> — /byok lists the providers.' });
3282
- return true;
3283
- }
3284
- const cur = (providers.find((p) => p.configured) || {}).id || null;
3285
- const sel = Math.max(0, providers.findIndex((p) => p.configured));
3286
- c.openOverlay({
3287
- type: 'provider',
3288
- command: 'byok-key',
3289
- items: providers,
3290
- sel,
3291
- current: cur,
3292
- hint: '↑↓ or tab move · enter picks · the key is stored on this machine',
3293
- });
3294
- return true;
3295
- },
3296
- },
3297
- {
3298
- name: 'byok-key', args: ['provider'], hint: '<provider> [key]', category: 'auth',
3299
- desc: 'Save YOUR provider key on THIS MACHINE — the key the byok class sends',
3300
- handler: async (c, a) => {
3301
- const args = a || {};
3302
- const typed = String(args.provider || '').trim().toLowerCase();
3303
- if (!typed) {
3304
- // No provider typed: open the picker instead of printing a usage line.
3305
- // The id was the one thing this flow asked the user to RECALL, and a
3306
- // mistyped or alias-matched id either matched nothing or — worse —
3307
- // matched another vendor's row. Arrow or Tab moves, Enter picks, and
3308
- // the id Enter dispatches is the catalog's own, so the key lands under
3309
- // the id the relay will actually be asked for.
3310
- const providers = await byokCatalog(c.client);
3311
- if (!providers || !providers.length) {
3312
- c.push({ role: 'error', text: 'Usage: /byok-key <provider> — /byok lists the providers.' });
3313
- return true;
3314
- }
3315
- if (typeof c.openOverlay !== 'function') {
3316
- // No interactive host (a piped run): the old usage line, which at
3317
- // least names the command that lists the ids.
3318
- c.push({ role: 'error', text: 'Usage: /byok-key <provider> — /byok lists the providers.' });
3319
- return true;
3320
- }
3321
- const cur = (providers.find((p) => p.configured) || {}).id || null;
3322
- const sel = Math.max(0, providers.findIndex((p) => p.configured));
3323
- c.openOverlay({
3324
- type: 'provider',
3325
- command: 'byok-key',
3326
- items: providers,
3327
- sel,
3328
- current: cur,
3329
- hint: '↑↓ or tab move · enter picks · the key is stored on this machine',
3330
- });
3331
- return true;
3332
- }
3333
- const store = c.settings && c.settings();
3334
- if (!store || typeof store.set !== 'function') {
3335
- c.push({ role: 'error', text: 'this client has no provider-key store.' });
3336
- return true;
3337
- }
3338
- // Resolve the alias against the server's catalog so the row is written
3339
- // under the id the relay will actually be asked for (`/byok-key OpenAI`
3340
- // and `/byok-key openai` must be one key, not two).
3341
- const providers = await byokCatalog(c.client);
3342
- const match = providers ? findByokProvider(providers, typed) : null;
3343
- if (match && match.ambiguous) {
3344
- c.push({ role: 'error', text: `"${typed}" matches ${match.ambiguous.join(', ')} — retype the exact id.` });
3345
- return true;
3346
- }
3347
- // A key written under a provider the relay does not serve is unusable and
3348
- // invisible: the catalog never lists the row it created, so the user sees
3349
- // "saved" and then no models, with nothing naming the typo. `byok-set`
3350
- // already refuses this; the command it redirects users TO must refuse it
3351
- // too, or the redirect trades one silent failure for another.
3352
- //
3353
- // Only refused when the catalog actually answered. `byokCatalog` returns
3354
- // null on an unreachable server, and refusing on null would turn a
3355
- // network blip into "unknown provider" — a wrong reason for a right-looking
3356
- // stop. With no catalog the typed id is trusted, as before.
3357
- if (providers && !match?.provider) {
3358
- const ids = providers.map((x) => x.id).join(', ');
3359
- c.push({
3360
- role: 'error',
3361
- text: `unknown provider "${typed}". Known ids: ${ids} — nothing was saved.`,
3362
- });
3363
- return true;
3364
- }
3365
- const p = match && match.provider;
3366
- const id = (p && p.id) || typed;
3367
- // A second token is the scriptable path (`/byok-key openai sk-…`); with
3368
- // none we prompt — readSecret never echoes and never enters history.
3369
- const rest = String(args._rest || '').trim();
3370
- const sp = rest.indexOf(' ');
3371
- let key = sp === -1 ? '' : rest.slice(sp + 1).trim();
3372
- if (!key) {
3373
- if (p && p.key_url) c.push({ role: 'note', text: `create a ${p.label || id} key at ${p.key_url}` });
3374
- key = String((await c.readSecret(`${id} key: `)) || '').trim();
3375
- }
3376
- if (!key) {
3377
- c.push({ role: 'note', text: 'nothing saved.' });
3378
- return true;
3379
- }
3380
- if (p && p.key_prefix && !key.startsWith(p.key_prefix)) {
3381
- c.push({ role: 'note', text: `heads up: ${id} keys normally start with "${p.key_prefix}" — saved anyway.` });
3382
- }
3383
- store.set(c.byokNamespace(id), { key });
3384
-
3385
- // MIRROR IT INTO ~/.aegiscode/.env — the file every host (this CLI, the
3386
- // desktop, the MCP plugin) loads at start-up, and the one the shared
3387
- // engine's `providerKeyFromEnv` reads. The settings store alone made the
3388
- // key a private fact of this process's data dir: the next launch of the
3389
- // SAME host found it, but nothing else did, and the byok model list is
3390
- // built from a key the engine resolves through both. `/model-add` writes
3391
- // both stores for this exact reason (see its `setEnvValue` call), and a
3392
- // key entered here must not be the one row that behaves differently.
3393
- // Best-effort: the store row above is the row of record, so a failure to
3394
- // write the file is reported and never undoes the save.
3395
- let envWritten = '';
3396
- try {
3397
- const { envVarFor, setEnvValue } = require(resolveShared(path.join('client', 'env-file.js')));
3398
- const name = envVarFor(id);
3399
- if (name) {
3400
- const res = setEnvValue(name, key);
3401
- if (res.ok) envWritten = name;
3402
- else c.push({ role: 'note', text: `heads up: could not write ${name} to ~/.aegiscode/.env (${res.error}).` });
3403
- }
3404
- } catch {
3405
- /* the settings-store save is the row of record; this mirror is best-effort */
3406
- }
3407
-
3408
- // Then make the models it unlocks VISIBLE where the user asked for them:
3409
- // the byok model list is cached for five minutes (app.js MODEL_CACHE_MS),
3410
- // so without this the key is saved and `/model` keeps offering the list
3411
- // computed before it existed — the "I set a key and nothing new appeared"
3412
- // report. The refresh is forced, and its rows are what get pinned below.
3413
- let rows = [];
3414
- if (typeof c.refreshByokModels === 'function') {
3415
- try { rows = (await c.refreshByokModels()) || []; } catch { rows = []; }
3416
- }
3417
- if (!rows.length && typeof c.listModelsFor === 'function') {
3418
- // Hosts that expose the class surface but not the cache invalidation
3419
- // (an embedding) still get an answer: ask for the byok class directly.
3420
- try {
3421
- rows = ((await c.listModelsFor('byok')) || []).filter((m) => !m.cls || m.cls === 'byok');
3422
- } catch { rows = []; }
3423
- }
3424
- const mine = rows.filter((m) => m && (m.provider === id || String(m.id || '').startsWith(`${id}:`)));
3425
-
3426
- // Move onto the byok class — the key just saved can only be spent there,
3427
- // and a session sitting on `aegis` would show these rows in /model and
3428
- // then send the pinned `provider:model` id to the pool. Before the pin,
3429
- // so switchClass's own pin rules run on the id we are about to store.
3430
- let onByok = ((c.ctx && c.ctx.modelClass) || '') === 'byok';
3431
- if (!onByok && typeof c.switchClass === 'function') {
3432
- const sw = c.switchClass('byok');
3433
- if (sw && sw.ok) {
3434
- onByok = true;
3435
- c.push({ role: 'note', text: `class: byok — ${c.classLabel ? c.classLabel('byok') : 'your own key'}` });
3436
- }
3437
- }
3438
-
3439
- // Pin it and PERSIST it, which is what makes the pick survive a restart:
3440
- // app.js's restorePrefs() reads config.model/modelClass back. Only on
3441
- // success — this whole block is the success path, after the key landed.
3442
- const pickId = mine.length ? String(mine[0].id) : '';
3443
- if (pickId && c.ctx) {
3444
- c.ctx.model = pickId;
3445
- c.saveConfig({ model: pickId, currentModelId: pickId, ...(onByok ? { modelClass: 'byok' } : {}) });
3446
- }
3447
-
3448
- c.push({
3449
- role: 'done',
3450
- text: pickId
3451
- ? `saved a ${id} key on this machine${envWritten ? ` (${envWritten} in ~/.aegiscode/.env, so it is there next time)` : ''} — model ${pickId} pinned, /model lists the rest.`
3452
- : `saved a ${id} key on this machine${envWritten ? ` (${envWritten} in ~/.aegiscode/.env, so it is there next time)` : ''} — /models lists its models, /class byok runs on it.`,
3453
- });
3454
- return true;
3455
- },
3456
- },
3457
- {
3458
- name: 'byok-rm-key', args: ['provider'], hint: '<provider>', category: 'auth',
3459
- desc: 'Forget the provider key saved on this machine',
3460
- handler: async (c, a) => {
3461
- const args = a || {};
3462
- const id = String(args.provider || '').trim().toLowerCase();
3463
- if (!id) {
3464
- c.push({ role: 'error', text: 'Usage: /byok-rm-key <provider> — /byok lists the providers.' });
3465
- return true;
3466
- }
3467
- const store = c.settings && c.settings();
3468
- if (!store || typeof store.remove !== 'function') {
3469
- c.push({ role: 'error', text: 'this client has no provider-key store.' });
3470
- return true;
3471
- }
3472
- const row = c.byokNamespace(id);
3473
- const had = typeof store.rawKey === 'function' ? store.rawKey(row) : null;
3474
- store.remove(row);
3475
- c.push({
3476
- role: had ? 'done' : 'note',
3477
- text: had ? `removed the ${id} key from this machine.` : `no ${id} key was saved on this machine.`,
3478
- });
3479
- return true;
3480
- },
3481
- },
3482
- {
3483
- // ── the user's own model declarations ──────────────────────────────────
3484
- //
3485
- // The ONE thing this repo could not do before: a provider ships a model on
3486
- // Tuesday and the user can call it from a BYOK key that same day. The BYOK
3487
- // relay is a stateless pass-through — the caller's own vendor key
3488
- // authenticates upstream and AEGIS forwards whatever model string it was
3489
- // given — so any id the vendor serves is callable the moment this machine
3490
- // offers it as a row, and this command is how it becomes one without a
3491
- // release.
3492
- //
3493
- // Written through `client/user-models.js`, which is also what the desktop's
3494
- // Settings row writes and what the shared engine applies to
3495
- // `listModels('byok')`, so `/models` and the alt+p picker show the row on
3496
- // the next refresh and the window shows it on ITS next refresh. The file is
3497
- // printed on success, because a hand-edit is the bulk path and a store the
3498
- // user cannot find is a store they will not use.
3499
- name: 'model-add', aliases: ['add-model'], args: ['provider'],
3500
- hint: '<provider> [api-key] [model-id|*] (custom: <base-url> <api-key> [model-id|*])',
3501
- category: 'model',
3502
- desc: 'Save a provider key and offer a model id in one step (asks the vendor when it can)',
3503
- handler: async (c, a) => {
3504
- const args = a || {};
3505
- const typed = String(args.provider || '').trim();
3506
- if (!typed) {
3507
- c.push({
3508
- role: 'error',
3509
- text: 'Usage: /model-add <provider> [api-key] <model-id> — /byok lists the providers. '
3510
- + 'A vendor this catalog does not name yet: /model-add custom <https-base-url> <api-key> <model-id>. '
3511
- + 'Example: /model-add deepseek sk-xxxxxxxx deepseek-v4.3-preview',
3512
- });
3513
- return true;
3514
- }
3515
- const rest = String(args._rest || '').trim();
3516
- // Quote-aware, because the one word on this line that MAY need quoting is
3517
- // the base URL — see splitCommandWords.
3518
- const words = splitCommandWords(rest);
3519
- // `words[0]` is the provider token itself, echoed into `_rest` the same
3520
- // way `/byok-key` reads it — everything after it is ours to read. A
3521
- // `_rest` without it (a caller that passes only the trailing words) is
3522
- // tolerated rather than misread as the provider being the model id.
3523
- let extra = words.length && words[0].toLowerCase() === typed.toLowerCase()
3524
- ? words.slice(1)
3525
- : words;
3526
- // Resolve the provider against the relay's catalog first. A slug the
3527
- // server does not list can never be attached to a key, so storing it
3528
- // would produce a declaration that is invisible in every picker — the
3529
- // silent no-op this whole path is meant to avoid. When the catalog is
3530
- // unreachable the declaration is kept and SAID to be unverified, because
3531
- // refusing to work offline is worse than a row that appears later.
3532
- const providers = await byokCatalog(c.client);
3533
- const match = providers ? findByokProvider(providers, typed) : null;
3534
- if (match && match.ambiguous) {
3535
- c.push({ role: 'error', text: `"${typed}" matches ${match.ambiguous.join(', ')} — retype the exact id.` });
3536
- return true;
3537
- }
3538
- if (providers && !(match && match.provider)) {
3539
- c.push({
3540
- role: 'error',
3541
- text: `no provider "${typed}" in the relay's catalog — /byok lists the ones it takes a key for.`,
3542
- });
3543
- return true;
3544
- }
3545
- const id = (match && match.provider && match.provider.id) || typed.toLowerCase();
3546
- // ── fold the key-save step in, so one command does both ──────────────
3547
- //
3548
- // Before this, a never-configured provider needed /byok-key THEN
3549
- // /model-add — two commands for one outcome the user has in mind as
3550
- // one. Two extra words can only mean key-then-model (the one-word shape
3551
- // just below is already the model-id-alone case this command always
3552
- // had, and guessing "key or model id" from a single token is the
3553
- // ambiguity this rule avoids rather than resolves): `/model-add
3554
- // deepseek sk-… deepseek-v4.3-preview` saves the key and declares the
3555
- // model in the same breath, and shows up in the picker right after —
3556
- // no separate /byok-key round trip.
3557
- //
3558
- // "custom" (a vendor this catalog does not name, or a self-hosted
3559
- // OpenAI-compatible endpoint) reads one word EARLIER than every other
3560
- // provider: the base URL aegis1 has no constant for and must be told
3561
- // per call (`_byok_custom_base_url` there validates it — https, no
3562
- // loopback/private/link-local target). It gets its own branch rather
3563
- // than folding into the generic rule below, because with the base URL
3564
- // in play a lone leftover word is still ambiguous between "no model"
3565
- // and "no key" in a way the generic one-word-is-the-model-id rule
3566
- // cannot resolve.
3567
- let typedBaseURL = '';
3568
- let typedKey = '';
3569
- if (id === 'custom') {
3570
- // ONE leftover word for `custom` is genuinely ambiguous, so it is
3571
- // refused rather than guessed: with no endpoint on this machine the
3572
- // word could be the base URL (key and model still to come) or a model
3573
- // id for an endpoint nobody has named — and the guess that writes a
3574
- // model row against no endpoint is a row that cannot be called. Once an
3575
- // endpoint IS saved the ambiguity is gone, because a second endpoint
3576
- // needs its key with it (the two-word branch below), so a lone word can
3577
- // only be a model id. Named, not silently dropped.
3578
- if (extra.length === 1 && !savedByokBaseURL(c, id)) {
3579
- c.push({
3580
- role: 'error',
3581
- text: 'one word cannot say whether it is the URL or the model id — nothing was saved. '
3582
- + 'Type the endpoint first: /model-add custom <https-base-url> <api-key> [model-id]',
3583
- });
3584
- return true;
3585
- }
3586
- if (extra.length >= 2) {
3587
- typedBaseURL = extra.shift();
3588
- typedKey = extra.shift();
3589
- }
3590
- } else if (extra.length >= 2) {
3591
- typedKey = extra.shift();
3592
- }
3593
- let model = extra.join(' ').trim();
3594
- if (typedKey) {
3595
- const keyStore = c.settings && c.settings();
3596
- if (!keyStore || typeof keyStore.set !== 'function') {
3597
- c.push({ role: 'error', text: 'this client has no provider-key store.' });
3598
- return true;
3599
- }
3600
- const p = match && match.provider;
3601
- if (p && p.key_prefix && !typedKey.startsWith(p.key_prefix)) {
3602
- c.push({ role: 'note', text: `heads up: ${id} keys normally start with "${p.key_prefix}" — saved anyway.` });
3603
- }
3604
- if (typedBaseURL && !/^https:\/\//i.test(typedBaseURL)) {
3605
- c.push({ role: 'note', text: `heads up: aegis1 only dials an https:// base_url — saved anyway, but calls on it will be refused.` });
3606
- }
3607
- keyStore.set(c.byokNamespace(id), { key: typedKey, ...(typedBaseURL ? { baseURL: typedBaseURL } : {}) });
3608
- // Mirror it into ~/.aegiscode/.env too — the same file the model picker
3609
- // writes (models.js storeModelKey) and byokKeyForProvider() already
3610
- // falls back to reading. Without this a key saved here was invisible to
3611
- // anything that only reads process.env/.env (a shell, the other host
3612
- // before its settings store syncs), even though the two files name the
3613
- // same provider through the identical envVarFor() mapping. Best-effort:
3614
- // the settings-store save above is the row of record, so a failure here
3615
- // (e.g. an unwritable .env) is reported but never undoes it.
3616
- try {
3617
- const { envVarFor, setEnvValue } = require(resolveShared(path.join('client', 'env-file.js')));
3618
- const envName = envVarFor(id);
3619
- if (envName) {
3620
- const res = setEnvValue(envName, typedKey);
3621
- if (!res.ok) {
3622
- c.push({ role: 'note', text: `heads up: could not mirror the key into ~/.aegiscode/.env (${res.error}).` });
3623
- }
3624
- }
3625
- } catch {
3626
- /* the settings-store save is the row of record; this mirror is best-effort */
3627
- }
3628
- c.push({
3629
- role: 'done',
3630
- text: typedBaseURL
3631
- ? `saved a ${id} key and base URL (${typedBaseURL}) on this machine.`
3632
- : `saved a ${id} key on this machine.`,
3633
- });
3634
- }
3635
- // ── what the vendor says, before we ask the user to remember it ──────
3636
- //
3637
- // The whole cost of this feature used to be "know the vendor's model id",
3638
- // which is the release-lag problem handed to the user instead of solved.
3639
- // When this machine holds a key for the provider, its own list endpoint
3640
- // answers that in one request. Best-effort by construction: no key, no
3641
- // endpoint, no network or an unparseable reply all fall through to the
3642
- // free-form prompt below, which is the path that already worked offline.
3643
- const key = byokKeyForProvider(c, id);
3644
- const offered = await offeredModelIds(c, id, key);
3645
-
3646
- // `*` is the bulk path: declare everything the vendor currently serves.
3647
- // Only the CHAT rows are declared (an embeddings or TTS id in a model
3648
- // picker is a row nobody can run), and only after the vendor answered —
3649
- // with no list there is nothing to take all of, and saying so is the
3650
- // honest outcome rather than an empty success.
3651
- if (model === '*') {
3652
- if (!offered) {
3653
- const why = await discoverProviderModels(c, id, key);
3654
- c.push({
3655
- role: 'error',
3656
- text: `cannot list ${id}: ${(why && why.error) || 'no list available'} — type the ids instead: /model-add ${id} <model-id>`,
3657
- });
3658
- return true;
3659
- }
3660
- const bulk = addManyUserModels(id, offered);
3661
- if (typeof c.refreshByokModels === 'function') {
3662
- try { await c.refreshByokModels(); } catch { /* the next refresh reads the file anyway */ }
3663
- }
3664
- c.push({
3665
- role: 'done',
3666
- text: `added ${bulk.added} of the ${offered.length} model ids ${id} serves${bulk.already.length ? ` (${bulk.already.length} were already declared)` : ''}.`,
3667
- });
3668
- if (bulk.capped) {
3669
- // The store's per-provider ceiling, named as a ceiling. A vendor list
3670
- // is a hundred rows; this is one deliberate limit, not sixty broken
3671
- // ids, and the two must not read the same in the transcript.
3672
- c.push({
3673
- role: 'note',
3674
- text: `stopped at the store's per-provider cap (32) — ${bulk.capped} more id(s) were left out; /model-add ${id} <model-id> stores a specific one, /model-rm frees a slot.`,
3675
- });
3676
- }
3677
- if (bulk.failed.length) {
3678
- c.push({ role: 'note', text: `${bulk.failed.length} id(s) were refused: ${bulk.failed.map((f) => f.id).join(', ')}` });
3679
- }
3680
- c.push({ role: 'note', text: `stored in ${userModelsPath()} — the desktop reads the same file. /model-discover ${id} lists what the vendor serves.` });
3681
- return true;
3682
- }
3683
-
3684
- if (!model) {
3685
- // Plain inline input, NOT readSecret: a model id is not a secret, and
3686
- // hiding it would make a typo unreviewable before it is stored.
3687
- if (offered) {
3688
- c.push({ role: 'note', text: `${id} serves ${offered.length} model ids — ${offered.slice(0, 12).join(', ')}${offered.length > 12 ? ', …' : ''}` });
3689
- }
3690
- const typedId = String((await c.askInput(
3691
- offered
3692
- ? `model id for ${id} (1-${offered.length}, or type one): `
3693
- : `model id for ${id}: `
3694
- )) || '').trim();
3695
- // A bare number picks the row it is listed under. Only an in-range
3696
- // integer is read that way, so an id that happens to start with a digit
3697
- // is still stored verbatim unless it is exactly a listed position.
3698
- // `offered` is undefined whenever the vendor could not be asked (no
3699
- // key, no endpoint, no network) — reading `.length` off it here threw a
3700
- // TypeError out of the handler, which reads to the user as the command
3701
- // crashing rather than as the id being stored, so the position rule is
3702
- // applied only when there is a list to be a position IN.
3703
- const n = offered && /^\d+$/.test(typedId) ? Number(typedId) : 0;
3704
- model = offered && n >= 1 && n <= offered.length ? offered[n - 1] : typedId;
3705
- }
3706
- if (!model) {
3707
- c.push({ role: 'note', text: 'nothing saved.' });
3708
- return true;
3709
- }
3710
- let res;
3711
- try {
3712
- res = addUserModel(id, model);
3713
- } catch (err) {
3714
- c.push({ role: 'error', text: (err && err.message) || String(err) });
3715
- return true;
3716
- }
3717
- // The picker's cache (app.js `byokCache`, 5 minutes) is older than the
3718
- // file the instant it is written, so refresh it here: a user who adds a
3719
- // model and types `/models` must see it, not "already listed" five
3720
- // minutes later.
3721
- if (typeof c.refreshByokModels === 'function') {
3722
- try {
3723
- await c.refreshByokModels();
3724
- } catch {
3725
- /* the next refresh reads the file anyway */
3726
- }
3727
- }
3728
- const rows = (typeof c.listModelsFor === 'function' ? (await c.listModelsFor('byok')) : []) || [];
3729
- const row = rows.find((m) => m && m.id === `${id}:${model}`);
3730
- c.push({
3731
- role: res.added ? 'done' : 'note',
3732
- text: res.added
3733
- ? `added ${id}:${model} — offered on this machine now, in the CLI and the desktop.`
3734
- : `${id}:${model} was already declared.`,
3735
- });
3736
- if (!providers) {
3737
- c.push({
3738
- role: 'note',
3739
- text: `the relay's catalog could not be read, so "${id}" is unverified — if it does not appear in /models, /byok lists the provider ids it takes.`,
3740
- });
3741
- }
3742
- if (res.added && !row) {
3743
- c.push({
3744
- role: 'note',
3745
- text: `saved, but no row will be offered for "${id}" yet — the relay lists no provider of that id (or that provider lists no models).`,
3746
- });
3747
- }
3748
- if (res.added && offered) {
3749
- // The vendor was asked and it lists more than the one id just stored.
3750
- // Naming the size of that list is the difference between "the picker has
3751
- // four models" and "this vendor ships forty and you have one of them".
3752
- c.push({
3753
- role: 'note',
3754
- text: `${id} currently serves ${offered.length} model ids — /model-discover ${id} lists them, /model-add ${id} '*' takes them all.`,
3755
- });
3756
- }
3757
- c.push({ role: 'note', text: `stored in ${res.file} — the desktop reads the same file.` });
3758
- return true;
3759
- },
3760
- },
3761
- {
3762
- // ── what the vendor serves, right now ─────────────────────────────────
3763
- //
3764
- // `/model-add` answers "store THIS id"; this answers "which ids are there",
3765
- // which is the question a user actually has when a vendor ships something
3766
- // on a Tuesday. It reads the same key `client/env-file.js` and the provider
3767
- // CRUD share (saved row first, `~/.aegiscode/.env` second) and hits the
3768
- // vendor's own list endpoint, so the answer cannot be stale by
3769
- // construction — that is the whole point of asking instead of shipping
3770
- // another hand-copied list.
3771
- //
3772
- // Offline, keyless and shape-changed are all REPORTED, never thrown: this
3773
- // command sits beside a manual path that works, so its worst case has to be
3774
- // a sentence, not a stack trace.
3775
- name: 'model-discover', aliases: ['discover-models', 'vendor-models'], args: ['provider'], hint: '<provider>',
3776
- category: 'model',
3777
- desc: "List the model ids your provider's own API serves",
3778
- handler: async (c, a) => {
3779
- const args = a || {};
3780
- const typed = String(args.provider || '').trim();
3781
- if (!typed) {
3782
- c.push({
3783
- role: 'error',
3784
- text: `Usage: /model-discover <provider> — this client can ask: ${discoverableProviders().join(', ')}`,
3785
- });
3786
- return true;
3787
- }
3788
- // Resolve the alias against the relay's catalog when it is reachable, so
3789
- // `/model-discover xai` and `/model-discover grok` are one request.
3790
- const providers = await byokCatalog(c.client);
3791
- const match = providers ? findByokProvider(providers, typed) : null;
3792
- const id = ((match && match.provider && match.provider.id) || typed).toLowerCase();
3793
- const entry = vendorEndpointFor(id);
3794
- if (!entry) {
3795
- c.push({
3796
- role: 'error',
3797
- text: `no list endpoint for "${id}" in this client — /model-add ${id} <model-id> stores an id you already know. Providers it can ask: ${discoverableProviders().join(', ')}`,
3798
- });
3799
- return true;
3800
- }
3801
- const key = byokKeyForProvider(c, id);
3802
- if (!key) {
3803
- c.push({
3804
- role: 'error',
3805
- text: `no ${id} key on this machine — /byok-key ${id} saves one (or put it in ~/.aegiscode/.env), then this lists what the key reaches.`,
3806
- });
3807
- return true;
3808
- }
3809
- const res = await discoverProviderModels(c, id, key);
3810
- if (!res || !res.ok) {
3811
- c.push({ role: 'error', text: `could not list ${id}: ${(res && res.error) || 'no answer'}` });
3812
- return true;
3813
- }
3814
- // Where the user stands: which of these are already offered here.
3815
- const declared = new Set(userModelIdsFor(id));
3816
- const known = new Set(
3817
- ((match && match.provider && match.provider.models) || []).map((m) => String(m))
3818
- );
3819
- c.push({ role: 'note', text: `${id} at ${entry.url}${entry.note ? ` (${entry.note})` : ''}` });
3820
- c.push({
3821
- role: 'note',
3822
- text: `${res.count} chat model id(s) the vendor serves — mark: [seen] the relay already lists it, [your] you declared it, [new] this machine does not offer it yet.`,
3823
- });
3824
- const lines = res.ids.map((m, i) => {
3825
- const mark = declared.has(m) ? '[your]' : known.has(m) ? '[seen]' : '[new]';
3826
- return `${String(i + 1).padStart(3)}. ${mark} ${m}`;
3827
- });
3828
- if (lines.length) c.push({ role: 'panel', lines });
3829
- if (!lines.length) {
3830
- c.push({ role: 'note', text: `the vendor answered with no chat models — /model-add ${id} <model-id> stores one by hand.` });
3831
- }
3832
- if (res.others.length) {
3833
- // Named, not hidden. "the vendor lists 60 and you were shown 12" is a
3834
- // fact the user is owed; a silent filter is how a picker looks empty
3835
- // for a reason nobody can see.
3836
- c.push({
3837
- role: 'note',
3838
- text: `${res.others.length} id(s) are not chat models (embeddings, audio, moderation or an unsupported method) and are left out: ${res.others.slice(0, 8).join(', ')}${res.others.length > 8 ? ', …' : ''}`,
3839
- });
3840
- }
3841
- const fresh = res.ids.filter((m) => !declared.has(m) && !known.has(m));
3842
- if (fresh.length) {
3843
- c.push({
3844
- role: 'note',
3845
- text: `${fresh.length} of them are not offered on this machine yet — /model-add ${id} '<model-id>' stores one, /model-add ${id} '*' stores every chat model the vendor serves.`,
3846
- });
3847
- }
3848
- return true;
3849
- },
3850
- },
3851
- {
3852
- name: 'model-rm', aliases: ['rm-model'], args: ['provider'], hint: '<provider> <model-id>',
3853
- category: 'model',
3854
- desc: 'Forget a model id you added with /model-add',
3855
- handler: async (c, a) => {
3856
- const args = a || {};
3857
- const typed = String(args.provider || '').trim();
3858
- const rest = String(args._rest || '').trim();
3859
- const sp = rest.indexOf(' ');
3860
- const model = sp === -1 ? '' : rest.slice(sp + 1).trim();
3861
- if (!typed || !model) {
3862
- c.push({ role: 'error', text: 'Usage: /model-rm <provider> <model-id> — /model-add lists what you added.' });
3863
- return true;
3864
- }
3865
- let res;
3866
- try {
3867
- res = removeUserModel(typed, model);
3868
- } catch (err) {
3869
- c.push({ role: 'error', text: (err && err.message) || String(err) });
3870
- return true;
3871
- }
3872
- if (typeof c.refreshByokModels === 'function') {
3873
- try {
3874
- await c.refreshByokModels();
3875
- } catch {
3876
- /* the next refresh reads the file anyway */
3877
- }
3878
- }
3879
- c.push({
3880
- role: res.removed ? 'done' : 'note',
3881
- text: res.removed
3882
- ? `removed ${res.provider}:${res.model} — the picker stops offering it on the next refresh.`
3883
- : `${res.provider}:${res.model} was not declared on this machine.`,
3884
- });
3885
- return true;
3886
- },
3887
- },
3888
- {
3889
- name: 'tool', args: ['name', 'json'], hint: '<name> [json]', category: 'aegis',
3890
- desc: 'Call any registry tool directly (escape hatch for new tools)',
3891
- generic: true,
3892
- build: (arg) => {
3893
- const s = String(arg || '');
3894
- const sp = s.indexOf(' ');
3895
- const name = (sp === -1 ? s : s.slice(0, sp)).trim();
3896
- const rest = sp === -1 ? '' : s.slice(sp + 1).trim();
3897
- let args = {};
3898
- if (rest) {
3899
- try {
3900
- args = JSON.parse(rest);
3901
- } catch (err) {
3902
- throw new Error(`/tool: arguments must be JSON — ${err.message}`);
3903
- }
3904
- }
3905
- return { tool: name, args };
3906
- },
3907
- },
3908
- {
3909
- name: 'aegis-import', aliases: ['import'], hint: '[--confirm]', category: 'aegis',
3910
- desc: 'Import memory from other AI tools on this machine (dry run unless --confirm)',
3911
- tool: 'aegis_memory_import',
3912
- build: (arg) => ({ confirm: /--confirm\b/.test(String(arg || '')) }),
3913
- },
3914
- ];
3915
-
3916
- // ── Index + the one invariant a table like this must hold ─────────────────────
3917
- // A name or alias registered twice would silently shadow the earlier entry, so
3918
- // the collision is a module-load error rather than a runtime surprise.
3919
-
3920
- const BY_NAME = new Map();
3921
- for (const c of COMMANDS) {
3922
- for (const n of [c.name, ...(c.aliases || [])]) {
3923
- if (BY_NAME.has(n)) {
3924
- throw new Error(`aegiscode: command name or alias /${n} is registered twice`);
3925
- }
3926
- BY_NAME.set(n, c);
3927
- }
3928
- }
3929
-
3930
- /** Every builtin entry, in palette order, with its category label attached. */
3931
- function allCommands() {
3932
- return COMMANDS.map((entry) => ({ ...entry, categoryLabel: categoryLabel(entry.category) }));
3933
- }
3934
-
3935
- /** Commands shown in the palette, /help and Tab completion. */
3936
- function visibleCommands() {
3937
- return allCommands().filter((c) => !(typeof c.hidden === 'function' ? c.hidden() : c.hidden));
3938
- }
3939
-
3940
- /** Find by name or alias, case-insensitive. Returns the entry or null. */
3941
- function findCommand(name) {
3942
- return BY_NAME.get(String(name || '').toLowerCase()) || null;
3943
- }
3944
-
3945
- /** The canonical name of a command, resolving aliases. */
3946
- function canonicalName(name) {
3947
- const e = findCommand(name);
3948
- return e ? e.name : name;
3949
- }
3950
-
3951
- /**
3952
- * Classify one input line.
3953
- * @returns {{kind:'empty'}
3954
- * |{kind:'command',command:object,arg:string}
3955
- * |{kind:'unavailable',command:object,arg:string}
3956
- * |{kind:'unknown',name:string,text:string}
3957
- * |{kind:'prompt',text:string}}
3958
- */
3959
- function parseLine(line) {
3960
- const raw = String(line == null ? '' : line);
3961
- const trimmed = raw.trim();
3962
- if (!trimmed) return { kind: 'empty' };
3963
- if (trimmed[0] !== '/') return { kind: 'prompt', text: trimmed };
3964
- const sp = trimmed.indexOf(' ');
3965
- const name = (sp === -1 ? trimmed.slice(1) : trimmed.slice(1, sp)).trim();
3966
- const arg = sp === -1 ? '' : trimmed.slice(sp + 1).trim();
3967
- const command = findCommand(name);
3968
- if (!command) return { kind: 'unknown', name, text: trimmed };
3969
- if (command.unavailable) return { kind: 'unavailable', command, arg };
3970
- return { kind: 'command', command, arg };
3971
- }
3972
-
3973
- /** Commands that map to a registry tool, for the coverage test. */
3974
- function toolBackedCommands() {
3975
- return COMMANDS.filter((c) => c.tool);
3976
- }
3977
-
3978
- module.exports = {
3979
- CATEGORIES,
3980
- categoryLabel,
3981
- EFFORT_LEVELS,
3982
- COMMANDS,
3983
- allCommands,
3984
- visibleCommands,
3985
- findCommand,
3986
- canonicalName,
3987
- parseLine,
3988
- toolBackedCommands,
3989
- };
3
+ const e=require("node:fs"),t=require("node:os"),r=require("node:path"),{execSync:n}=require("node:child_process"),{span:o}=require("./screen.js"),{C:s,BOLD:i,BOLD_OFF:a,THEME_TABLE:d,themeContradicts:l}=require("./theme.js"),{caps:c,setCaps:u,resetCaps:h,describe:p,probeTerminalBackground:m}=require("./caps.js"),g=require("./panels.js"),y=require("./overlays.js"),{updateConfig:f,loadConfig:k,loadPermissions:w,savePermissions:b,addPermissionRule:v,DEFAULT_PERMISSIONS:$,permissionsPath:x,configPath:S,aegisDir:C,setConfirmPosture:I,setPermissionDefaultMode:j,confirmPosture:A,memoryPersistState:L,setMemoryPersist:M}=require("./config.js"),{auditExposure:_,repairExposure:T}=require("./securefs.js"),{copyToClipboard:P}=require("./clipboard.js"),{snapshotCheckpoint:E,listCheckpoints:U,loadCheckpoint:q}=require("./checkpoint.js"),{signupUrl:R,goUrl:O}=require("./signup.js"),G=require("./screens.js"),{summarizeTranscript:N,recapLine:F}=require("./summarize.js"),{sessionAccounting:W,accountingFromUsage:D,estimateTokens:B}=require("./tokens.js"),{effortRung:K}=require("./engine.js"),{transcriptToMarkdown:H,transcriptToJSON:V,writeExportFile:z,lastAssistantText:J}=require("./export.js"),{detectDevCommand:Y,runDevServer:X}=require("./devrun.js"),{PING_MODES:Q,DEFAULT_PING_MODE:Z,normalizePingMode:ee,normalizePingSeconds:te,buildPing:re,writePing:ne}=require("./ping.js"),{addTodo:oe,completeTodo:se,clearTodos:ie,formatTodos:ae,todosFile:de}=require("./todos.js"),{configRows:le,formatConfigRows:ce,setConfigValue:ue,resetConfigValue:he,fullValue:pe,summarizeValue:me,configStore:ge}=require("./settings.js"),ye=require("./credentials.js"),fe=require("./cloudsync.js"),{maskKey:ke,fmtTokens:we,shortCwd:be}=require("./format.js"),{pickerEntries:ve}=require("./models.js"),{resolveShared:$e}=require("./sharedpaths.js"),{createCliEntitlement:xe,paymentView:Se,probeFee:Ce}=require("./entitlement.js"),{openUrl:Ie,URLS:je}=require("./system.js"),Ae=require("./sysdiag.js"),{sniffProject:Le,buildAegisMd:Me}=require("./init.js"),{upgradeAdvice:_e,latestPublishedVersion:Te,applyUpgrade:Pe,installMethod:Ee}=require("./update.js"),{AGENT_PRESETS:Ue,agentRoles:qe,composeAgentPrompt:Re,composeResearchPrompt:Oe,composeDebatePrompt:Ge}=require("./agents.js"),{aggregateSessionUsage:Ne,pruneSessionHistory:Fe,readResumeList:We}=require("./history.js");let De=null;try{De=require("./markdown.js")}catch{De=null}const Be=require("../package.json").version,Ke=[{id:"session",label:"Session & context"},{id:"workspace",label:"Workspace"},{id:"model",label:"Model & behavior"},{id:"data",label:"Data"},{id:"auth",label:"Auth"},{id:"support",label:"Support"},{id:"fun",label:"Fun"},{id:"aegis",label:"Aegis plugin"},{id:"custom",label:"Custom"}],He=e=>(Ke.find((t=>t.id===e))||{}).label||e,Ve=y.EFFORT_VALUES,ze=(e,t)=>e.push({role:"note",text:t}),Je=(e,t)=>e.push({role:"panel",lines:t}),Ye=(e,t)=>e.push({role:"done",text:t});async function Xe(e,t,{yolo:r=!1,title:n="ÆGIS Multi"}={}){r&&(I(!1),Je(e,g.buildAutomode(e.state(),e.ctx))),ze(e,"Running the multi-agent fan-out — the engine delegates to specialist subagents (headless: this skips aegis-cli's own confirmation step)."),e.render();const o=await async function(e,t){const r=function(e){return["Execute this task as a multi-agent fan-out.","",`Task: ${e}`,"",`Workspace: ${process.cwd()}`,"","Use the task tool to delegate the independent parts to specialist subagents, in parallel where they do not depend on each other:","- reconnaissance first (scanner for secrets/unsafe patterns, analyzer for refactor targets),","- then design (architect, or planner when the work is a change to existing code),","- then an implementer subagent to make the change.","Finally review the result (reviewer subagent), fix what it finds, and verify with the repository's real commands.","","Return one consolidated report: what each subagent found, the files you changed, the exact commands you ran and their real output, and anything still blocked. No preamble."].join("\n")}(t),n=e&&e.withWorking?t=>e.withWorking(t):e=>e();if(!e||"function"!=typeof e.ask&&"function"!=typeof e.runPrompt)return{error:"No agent loop in this context — the fan-out prompt was composed, not run."};try{if("function"==typeof e.ask){const t=await n((t=>e.ask(r,{signal:t}))),o=t&&t.text||"";return t&&t.interrupted&&!o?{cancelled:!0}:o?{result:o,model:t&&t.model||e.ctx&&e.ctx.model||null,provider:"aegis"}:{error:"The multi-agent fan-out returned nothing (the turn failed before it could delegate)."}}return await n((()=>e.runPrompt(r))),{streamed:!0}}catch(e){return{error:`ÆGIS multi failed — ${e&&e.message||e}`}}}(e,t);return o.cancelled?(ze(e,"ÆGIS multi cancelled."),e.render(),!0):o.error?(ze(e,o.error),Je(e,g.buildAegisMulti(t,e.ctx)),e.render(),!0):(o.streamed||(Je(e,g.buildAegisPrint(n,o,e.ctx)),e.render()),!0)}async function Qe(e){if(!e||!e.client)return;let t;try{t=xe({aegis:e.client})}catch{return}const r=e.withWorking?t=>e.withWorking(t):e=>e();try{await r((()=>t.refresh({force:!0})))}catch{}const n=await Ce();return Se(t.current(),{host:"cli",fee:n})}async function Ze(e){try{return await e.loadModels()||[]}catch{return[]}}async function et(e){const t=e.ctx&&e.ctx.modelClass||"aegis",r=ve(await tt(e,"aegis",t)).map((e=>({...e,cls:"aegis"}))),n=ve(await tt(e,"byok",t)).map((e=>({...e,cls:e.cls||"byok"}))),o=ve(await tt(e,"pro",t)).map((e=>({...e,cls:"pro"}))),s=[],i=new Set;for(const e of[...r,...n,...o]){const t=String(e&&e.id||"");t&&!i.has(t)&&(i.add(t),s.push(e))}return s}async function tt(e,t,r){if("function"==typeof e.listModelsFor)try{return await e.listModelsFor(t)||[]}catch{return[]}if(t!==r||"function"!=typeof e.loadModels)return[];try{return await e.loadModels()||[]}catch{return[]}}const rt=()=>ye.hasApiKey(),{withByokAdditions:nt}=require($e(r.join("client","byok-catalog.js"))),{withUserModels:ot,addUserModel:st,removeUserModel:it,userModelIdsFor:at,userModelsPath:dt}=require($e(r.join("client","user-models.js"))),{discoverModels:lt,endpointFor:ct,discoverableProviders:ut}=require($e(r.join("client","model-discovery.js")));function ht(e,t){const n=String(t||"").trim().toLowerCase();if(!n)return"";try{const t=e&&e.settings&&e.settings();if(t&&"function"==typeof t.rawKey&&"function"==typeof e.byokNamespace){const r=t.rawKey(e.byokNamespace(n));if("string"==typeof r&&r.trim())return r.trim()}}catch{}try{const{providerKeyFromEnv:e}=require($e(r.join("client","env-file.js")));return(e(n)||{}).key||""}catch{return""}}async function pt(e,t,r){try{return await lt(t,{key:r,fetchImpl:e&&e.fetchImpl})}catch(e){return{ok:!1,provider:t,supported:!0,error:e&&e.message||String(e)}}}function mt(e,t){try{const r=e&&e.settings&&e.settings();if(!r||"function"!=typeof r.get||"function"!=typeof e.byokNamespace)return"";const n=r.get(e.byokNamespace(t))||{};return String(n.baseURL||"").trim()}catch{return""}}async function gt(e){if(!e||"function"!=typeof e.byokProviders)return null;try{const t=await e.byokProviders(),r=ot(nt(t&&t.providers||[]));return r.length?r:null}catch{return null}}function yt(e,t){const r=String(t||"").trim().toLowerCase();if(!e)return{provider:null,exact:!1};const n=e.find((e=>e.id===r));if(n)return{provider:n,exact:!0};const o=e.filter((e=>[e.id,e.label,...e.aliases||[]].filter(Boolean).some((e=>String(e).toLowerCase()===r))));return 1===o.length?{provider:o[0],exact:!1}:o.length>1?{ambiguous:o.map((e=>e.id))}:{provider:null,exact:!1}}function ft(e){const t=[];for(const r of e){const e=r.configured?o(s.green,"set"+(r.masked?` (${r.masked})`:"")):o(s.gray,"not set"),n=[o(s.gold+i,` ${r.id}`)];r.label&&n.push(o(s.gray,` — ${r.label}`)),n.push(o(""," "),e),t.push(n);const a=(r.models||[]).map((e=>"string"==typeof e?e:e&&e.id)).filter(Boolean);a.length&&t.push([o(s.gray,` models: ${a.join(", ")}`)]),r.key_prefix&&t.push([o(s.gray,` key starts with ${r.key_prefix}`)]),r.key_url&&t.push([o(s.gray,` ${r.key_url}`)])}return t}function kt(e,t="AEGIS account key"){const r=e.keyStatus(),n=[[o(s.gold+i,t),o(a,"")],[o(s.gray,"─".repeat(34))],[o(r.configured?s.green:s.coral," "+(r.configured?"✔":"⚠")),o(s.white," key: "),o(r.configured?s.white:s.gray,r.configured?ke(r.key):"not set"),o(s.gray,` (${ye.sourceLabel(r.source)})`)],[o(s.gray,` stored in: ${r.path}${r.fileMode?` ${r.fileMode}`:""}`)]];return r.verifiedAt&&n.push([o(s.gray,` verified: ${r.verifiedAt}`)]),r.account&&(r.account.plan||r.account.email)&&n.push([o(s.gray," account: "),o(s.white,[r.account.plan,r.account.email].filter(Boolean).join(" · "))]),n.push([o(s.gray," memory: "),o(r.memoryToken?s.green:s.gray,r.memoryToken?"token held (cloud sync ready)":"no token yet")]),r.configured||(n.push([o(s.gray,"")]),n.push([o(s.white," Set one with /key <api_key>, or press Enter on /key to paste it.")]),n.push([o(s.gray,` Free key: ${R("key_status")}`)])),r.legacyPlaintext&&(n.push([o(s.gray,"")]),n.push([o(s.coral," ⚠ a plaintext copy of the key is still in config.json (another AEGIS CLI wrote it).")]),n.push([o(s.gray," Re-save with /key <api_key> and delete that block when convenient.")])),n}async function wt(e,t,{label:r="AEGIS API key"}={}){let n=String(t||"").trim();if(n||(n=await e.readSecret(`${r} (kept off screen, Enter to cancel): `)),!n)return ze(e,"no key given — /key <api_key> takes it inline, or press Enter on a bare /key to paste it"),{ok:!1};const o=await e.setApiKey(n);if(!o.ok)return ze(e,o.message||"that key could not be saved"),o;if(o.error)return ze(e,`saved, but the account check failed: ${o.error.message}`),ze(e,"the key is stored — /key status shows it; re-run /key <api_key> if it was mistyped"),o;const s=o.account&&(o.account.email||o.account.plan)||null;Ye(e,`AEGIS key saved to ${o.path}${s?` — signed in as ${s}`:" and verified"}`);try{const t=ve(await Ze(e)).length;t&&ze(e,`${t} pinnable model${1===t?"":"s"} available — /model to pin one`)}catch{}return o}function bt(e){const t=Number(e);return Number.isFinite(t)?t>=1e6?`${(t/1e6).toFixed(t%1e6==0?0:1)}M`:t>=1e4?`${Math.round(t/1e3)}k`:we(t):"?"}function vt(e,t){if(e&&"function"==typeof e.setCloudSync)return e.setCloudSync(t);try{return M(t)}catch{return null}}function $t(e){const t=function(e){if(e&&"function"==typeof e.cloudSyncState)try{return e.cloudSyncState()}catch{}return{enabled:!e||"function"!=typeof e.cloudSyncEnabled||!0===e.cloudSyncEnabled(),source:"default"}}(e),r=fe.status(),n=r.quota,d=n&&null!=n.used?bt(n.used):null,l=n&&null!=n.limit?bt(n.limit):null,c="legacy"===t.source?" (kept from your old cloudSync setting)":"default"===t.source?" (default)":"",u=[[o(s.white+i,"Persisting memory"),o(s.gray," · Cloud sync"),o(a,"")],[o(s.gray,"─".repeat(34))],[o(s.white," "+(t.enabled?"on":"off")),o(s.gray,`${c} · ${t.enabled?"each session is stored so an interrupted turn can be resumed":"nothing new is stored"}`)]];return l?u.push([o(s.gray," quota: "),o(s.white,`${d} of ${l} tokens synced`),o(s.gray," (aegis1 charges writes; reads are always served)")]):u.push([o(s.gray," quota: not reported yet — /sync now asks the server for the current numbers")]),r.overQuota&&(u.push([o(s.coral," writes: paused — the plan’s ceiling is reached, so new memory is not being stored")]),u.push([o(s.green," reads: still work — everything already stored stays readable (/aegis-recall <topic>)")]),u.push([o(s.gray,` free room at ${O("upgrade","cloud_quota")}`)]),u.push([o(s.gray," or /cloud memory off to stop trying")])),t.enabled&&r.pending>0&&u.push([o(s.gray,` pending: ${r.pending} session(s) waiting to sync`)]),u.push([o(s.gray," /cloud memory on | off · /sync now pushes once by hand")]),u}async function xt(e,t={}){if(!e.client.apiKey)return ze(e,`no key — ${ye.HOW_TO_SET}`),null;const r=await e.withWorking((()=>fe.syncNow(e.client,t))),n=r.push&&r.push.pushed||[],o=[...r.push&&r.push.failed||[],...r.pull&&r.pull.failed||[]],s=r.pull&&r.pull.imported||0;n.length?Ye(e,`pushed ${n.length} session${1===n.length?"":"s"} (${n[0].messages} messages in the first)`):r.push&&r.push.skipped&&r.push.skipped.length?ze(e,`${r.push.skipped.length} session(s) had nothing to send`):ze(e,"nothing to push — every local session is already in the cloud"),s?Ye(e,`pulled ${s} record${1===s?"":"s"} into the local store — /resume lists them`):r.pull&&r.pull.ok&&ze(e,`cloud has ${r.pull.remote||0} session(s); nothing newer locally`);for(const t of o)ze(e,`${"quota"===t.kind?"quota":"failed"}: ${t.message}`),t.hint&&ze(e,t.hint);return r}const St=require($e(r.join("client","hooks.js")));function Ct(e){return St.hookStats(e)}const It=[{name:"run",hint:"",category:"workspace",desc:"Launch and drive this project's app to see a change working",handler:async e=>{const t=Y(process.cwd());if(!t)return ze(e,"No dev command detected (no package.json scripts, go.mod, Cargo.toml or Makefile). Try /init first."),e.render(),!0;ze(e,`Running ${t} in ${be()} — output streams below, Esc stops it.`);const r=X(t,{cwd:process.cwd(),onLine:t=>e.push({role:"note",text:` ${t}`})});return r.label||(r.label=t),e.openStream(r),r.done.then((({code:n,stopped:o})=>{e.closeStream(r),Ye(e,o?`${t} stopped`:`${t} exited (code ${n})`),e.render()})),e.render(),!0}},{name:"schedule",hint:"",category:"session",desc:"Create, update, list, or run scheduled cloud agents (routines)",handler:async e=>(ze(e,"Scheduled routines run on the AEGIS cloud. Sign in with `aegis login`, then manage routines at aegiscloud.org."),e.render(),!0)},{name:"build",aliases:["forge"],args:["task"],hint:"<description>",category:"workspace",desc:"Build an app with the agent loop — /build <what to build>",handler:async(e,t)=>{const r=(t._rest||t.task||"").trim();return r?(ze(e,"⬡ AEGIS BUILD"),ze(e,`Task: ${r}`),e.render(),await e.runPrompt(`Build the following, creating every file it needs and running the build to verify it works: ${r}`),!0):(ze(e,"Usage: /build <what to build>"),ze(e,"Example: /build a REST API for a todo app"),e.render(),!0)}},{name:"cd",args:["path"],hint:"<path>",category:"workspace",desc:"Move this session to a new working directory",handler:async(e,t)=>{const r=t.path||(t._rest||"").trim();if(!r)return ze(e,"Usage: /cd <path>"),e.render(),!0;try{process.chdir(r),e.ctx.cwd=process.cwd(),f({lastCwd:process.cwd()}),ze(e,`Changed directory to ${process.cwd()}`)}catch(t){ze(e,`/cd: ${t.message}`)}return e.render(),!0}},{name:"copy",aliases:["cp"],args:["n"],hint:"[N]",category:"data",desc:"Copy the last response to the clipboard",handler:async(e,t)=>{const r=parseInt(t.n||"1",10)||1,n=J(e.transcript,r);if(!n)return ze(e,"Nothing to copy yet."),e.render(),!0;const o=P(n);return o.ok?ze(e,o.via.startsWith("tool:")?`Copied the last response to the clipboard (${o.via.split(":")[1]}).`:`No clipboard tool found — response saved to ${o.path}`):ze(e,"Clipboard unavailable; nothing copied."),e.render(),!0}},{name:"clear",aliases:["cls"],hint:"",category:"session",desc:"Start a new session with empty context",handler:async e=>(e.transcript.length=0,Fe(e.sessionId),"function"==typeof e.clearConversationMemory&&e.clearConversationMemory(),ze(e,"Session cleared — transcript empty."),e.render(),!0)},{name:"compact",hint:"",category:"session",desc:"Compact the conversation history",handler:async e=>{if(!e.transcript.some((e=>"user"===e.role||"assistant"===e.role)))return ze(e,"Nothing to compact yet."),e.render(),!0;ze(e,"Compacting conversation history…"),e.render();const t=await e.withWorking((t=>N(e.transcript,{callModel:(t,r)=>e.ask(t,r).then((e=>e.text)),model:e.ctx.model,signal:t})));return null===t?(ze(e,"Compaction cancelled."),e.render(),!0):(e.transcript.length=0,ze(e,"Compacted. Earlier context summarized into the message below."),e.transcript.push({role:"user",text:t}),e.render(),!0)}},{name:"cost",hint:"",category:"data",desc:"Show the cost of the current session",handler:async e=>{const t=Ne(e.sessionId),r=t.entries?D(t.usage,e.ctx.model,{exchanges:t.entries,real:t.real,costUsd:t.real&&t.costUsd?t.costUsd:void 0}):W(e.transcript,e.ctx.model);return Je(e,g.buildCost({...e.state(),contextWindow:r.contextWindow,costEur:r.cost},e.ctx)),e.render(),!0}},{name:"context",hint:"",category:"session",desc:"Show context usage for the current session",handler:async e=>{const t=W(e.transcript,e.ctx.model);return Je(e,g.buildContext({...e.state(),contextWindow:t.contextWindow},e.ctx)),e.render(),!0}},{name:"ping",args:["mode","seconds"],hint:"[off|bell|notify|both] [seconds] | test",category:"model",desc:"Alert me when a long turn finishes, if I am looking elsewhere",handler:async(e,t)=>{const r=k(),n=(t._rest||"").trim().split(/\s+/).filter(Boolean),o=(n[0]||"").toLowerCase(),s=ee(r.ping),i=te(r.pingMinSeconds);if(!o)return ze(e,`[ping] ${s} — a turn longer than ${i}s raises a terminal notification.`),ze(e,` /ping ${Q.filter((e=>e!==s)).join("|")} ${"off"===s?"turn it back on":"change the channel"}`),ze(e," /ping <mode> <seconds> move the threshold (0 pings every turn)"),ze(e," /ping test fire one now, to check this terminal supports it"),e.render(),!0;if("test"===o){const t=re({mode:"off"===s?Z:s}),r=!!process.stdout.isTTY&&ne(process.stdout,t);return ze(e,r?"[ping] sent one just now. If nothing appeared or sounded, this terminal implements neither OSC 9 nor OSC 777 — /ping bell is the fallback.":"[ping] nothing sent: stdout is not a TTY (a piped or headless run has no one to notify)."),e.render(),!0}if(!Q.includes(o))return ze(e,`Unknown ping mode "${n[0]}". Use ${Q.join(", ")}.`),e.render(),!0;const a={ping:o};if(null!=n[1]){const t=Number(n[1]);if(!Number.isFinite(t)||t<0)return ze(e,`"${n[1]}" is not a number of seconds. Use /ping ${o} 30.`),e.render(),!0;a.pingMinSeconds=te(t)}return f(a),"off"===o?ze(e,"[ping] off — no notice will be raised, and nothing is reported as sent."):(ze(e,`[ping] ${o} — turns longer than ${te(a.pingMinSeconds??r.pingMinSeconds)}s will notify you.`),ze(e," Escape never pings (you were watching), and neither does a piped or headless run.")),e.render(),!0}},{name:"todos",aliases:["todo"],args:["sub","text"],hint:"[add <text> | done <n|text> | clear]",category:"session",desc:"A session todo list that survives compaction",handler:async(e,t)=>{const r=(t.sub||"").toLowerCase(),n=(t._rest||"").trim().replace(/^\S+\s*/,"");if(!r)return Je(e,ae()),ze(e,` ${de()}`),ze(e," /todos add <text> · /todos done <n|text> · /todos clear"),e.render(),!0;if("add"===r){const t=oe(n);return t.error?(ze(e,t.error),e.render(),!0):(Je(e,ae(t.list)),e.render(),!0)}if("done"===r||"do"===r){const t=se(n);return t.error?(ze(e,t.error),e.render(),!0):(ze(e,`[todos] "${t.item.text}" is now ${t.item.done?"done":"open"}.`),Je(e,ae(t.list)),e.render(),!0)}return"clear"===r?(ie(),ze(e,"[todos] cleared."),e.render(),!0):(ze(e,`Unknown /todos subcommand "${t.sub}". Use add, done or clear.`),e.render(),!0)}},{name:"config",args:["key","value"],hint:"[<key> | <key> <value> | reset <key>]",category:"session",desc:"Show or change any setting, and say which store holds it",handler:async(e,t)=>{const r=(t._rest||"").trim(),n=(t.key||"").trim(),o=r.replace(/^\S+\s*/,"");if(!n)return Je(e,ce(le())),ze(e," /config <key> show one value in full"),ze(e," /config <key> <value> set it (true/false/null, numbers, JSON, or text)"),ze(e," /config reset <key> back to the shipped value"),ze(e,' "shared" keys live in the store AEGIS Desktop writes too; "host" keys are this shell\'s own.'),e.render(),!0;if("reset"===n){const t=he(o);return t.error?(ze(e,t.error),e.render(),!0):(ze(e,`[config] ${t.key} reset to ${me(t.value)} (${t.store}).`),e.render(),!0)}if(!o){const t=k();return Object.prototype.hasOwnProperty.call(t,n)?(ze(e,`${n} (${ge(n)}):`),e.push({role:"panel",lines:pe(t[n]).split("\n").map((e=>` ${e}`))}),e.render(),!0):(ze(e,`unknown config key "${n}" — run /config to list the keys`),e.render(),!0)}const s=ue(n,o);return s.error?(ze(e,s.error),e.render(),!0):(ze(e,`[config] ${s.key} = ${me(s.value)} (${s.store}).`),["model","currentModelId","modelClass","effort","themeIndex","vim"].includes(s.key)&&("effort"===s.key&&(e.ctx.effort=K(s.value),e.ctx.effort!==String(s.value).toLowerCase()&&(e.saveConfig({effort:e.ctx.effort}),ze(e,` "${s.value}" is not a level this build sends — recorded as ${e.ctx.effort}.`))),ze(e,` This takes effect on the next turn; /${"currentModelId"===s.key?"model":s.key} shows the live session value.`)),e.render(),!0)}},{name:"effort",args:["level"],hint:"[low|medium|high]",category:"model",desc:"Set the token budget the pool sizes each turn from",handler:async(e,t)=>{const r=(t.level||"").toLowerCase();if(r&&"auto"!==r&&!Ve.includes(r))return ze(e,`Unknown effort level "${t.level}". Use ${Ve.join(", ")}.`),e.render(),!0;if(!r)return e.openOverlay({type:"effort",sel:Math.max(0,Ve.indexOf(e.ctx.effort||"high"))}),!0;const n="auto"===r?"high":r;return e.ctx.effort=n,e.saveConfig({effort:n}),ze(e,"auto"===r?"effort: auto is retired — high is the default, and it is what this session now sends":`Effort level: ${n} — the pool sizes this turn's token budget from it`),e.render(),!0}},{name:"exit",aliases:["quit"],hint:"",category:"session",desc:"Exit the CLI",handler:async()=>!1},{name:"export",args:["format","target"],hint:"[markdown|json] [file|clipboard]",category:"data",desc:"Export the current conversation to a file or clipboard",handler:async(e,t)=>{const r=(t.format||"markdown").toLowerCase(),n=(t.target||"file").toLowerCase();if(!["markdown","md","json"].includes(r)||!["file","clipboard"].includes(n))return ze(e,"Usage: /export [markdown|json] [file|clipboard]"),e.render(),!0;const o="json"===r,s=o?V(e.transcript):H(e.transcript);if("clipboard"===n){const t=P(s);ze(e,t.ok?`Exported conversation (${o?"json":"markdown"}) to the clipboard.`:"Clipboard unavailable; nothing copied.")}else try{const t=z(s,o?"json":"md",e.ctx.cwd||process.cwd());ze(e,`Exported conversation to ${t}`)}catch(t){ze(e,`/export: ${t.message}`)}return e.render(),!0}},{name:"help",aliases:["?","h"],hint:"",category:"support",desc:"Show help",handler:async e=>(Je(e,g.buildHelp(Lt(),e.ctx)),e.render(),!0)},{name:"init",args:["file"],hint:"[file]",category:"workspace",desc:"Create an AEGIS.md file in the project",handler:async(t,n)=>{const o=(n.file||"AEGIS.md").trim(),s=t.ctx.cwd||process.cwd(),i=r.resolve(s,o),a=s.endsWith(r.sep)?s:s+r.sep;if(i!==s&&!i.startsWith(a))return ze(t,`/init: refusing to write outside the project directory (${i}).`),t.render(),!0;if(e.existsSync(i))return ze(t,`${o} already exists — not overwriting.`),t.render(),!0;const d=Le(s);try{e.writeFileSync(i,Me(d)+"\n")}catch(e){return ze(t,`/init: ${e.message}`),t.render(),!0}return ze(t,`Created ${i} (${d.lang})`),e.existsSync(r.join(s,"node_modules"))&&!e.existsSync(r.join(s,".gitignore"))&&((e,t)=>{e.push({role:"tip",text:'Add "node_modules/" to a .gitignore before committing.'})})(t),t.render(),!0}},{name:"login",aliases:["signin"],args:["value"],hint:"[<api_key>]",category:"auth",desc:"Save your AEGIS API key",handler:async(e,t)=>{const r=String(t.value||t._rest||"").trim();return await wt(e,r,{label:"AEGIS API key"}),e.render(),!0}},{name:"logout",args:[],hint:"",category:"auth",desc:"Remove the saved AEGIS API key",handler:async e=>{const t=e.forgetApiKey();return Ye(e,t.cleared?`key removed from ${t.path}`:"there was no saved key to remove"),ye.legacyKeyOnDisk()&&ze(e,`a copy is still in ${S()} (another AEGIS CLI wrote it) — delete its "aegiscloud" block too`),e.render(),!0}},{name:"model",aliases:["m"],args:["sub"],hint:"[id|-]",category:"model",desc:'Switch AI model — pin an id ("-" clears it)',handler:async(e,t)=>{const r=(t.sub||"").trim(),n=e.ctx&&e.ctx.modelClass||"aegis",o="byok"===n;if(!r){ze(e,`model: ${e.ctx.model||"server default"}`);const t=await et(e);return t.length?(t.some((e=>"aegis"===e.cls||"byok"===e.cls))||ze(e,e.state().online?"Could not read the AEGIS Cloud catalog (offline, or the server refused it) — showing Claude Code Pro only; /models retries.":`No AEGIS API key set, so the AEGIS Cloud catalog cannot be read (free key: ${R("model_blocked")}) — showing Claude Code Pro only.`),e.ctx.model&&!t.some((t=>t.id===e.ctx.model))&&ze(e,o?`pinned model "${e.ctx.model}" is not one this machine can relay — pick from the list below.`:`pinned model "${e.ctx.model}" is not in the catalog — the pool will answer with its own default; pick one below.`),ze(e,"/model <id> pins one for this session; picking a direct-provider row prompts for its key if this machine has none saved."),e.openOverlay({type:"model",items:t,sel:0,current:e.ctx.model,cls:n}),!0):(ze(e,e.state().online?"Could not read the model catalog (offline, or the server refused it) — /models retries.":`No API key set, so the model catalog cannot be read — export AEGIS_API_KEY (free key: ${R("model_blocked")}), then retry /model.`),e.render(),!0)}if("list"===r){const t=await et(e);return t.length?Je(e,g.buildModelList(e.ctx.model,t,e.ctx)):ze(e,"No pinnable models advertised — /models lists the server's ids."),e.render(),!0}if("-"===r)return e.ctx.model=null,e.saveConfig({model:null,currentModelId:null}),ze(e,o?"Model pin cleared. The byok class has no server default — the next turn needs <provider>:<model>, so pin one from /models before sending.":"Model pin cleared — the server will choose."),e.render(),!0;e.ctx.model=r,e.saveConfig({model:r,currentModelId:r}),ze(e,`Pinned model: ${r}`);const s=await Ze(e)||[];return s.length&&!s.some((e=>e.id===r))&&ze(e,o?`"${r}" is not one this machine can relay — a byok id is "<provider>:<model>", and the relay will refuse anything else. /models lists the real ids.`:`"${r}" is not in the AEGIS Cloud catalog — the pool will answer with its own default. /models lists the real ids.`),e.render(),!0}},{name:"radio",hint:"",category:"fun",desc:"Listen to AEGIS FM lo-fi radio",handler:async e=>(ze(e,"Opening AEGIS FM lo-fi radio in your browser…"),Ie(je.radio)||ze(e,`AEGIS FM: ${je.radio}`),e.render(),!0)},{name:"recap",hint:"",category:"session",desc:"Generate a one-line session recap now",handler:async e=>{if(!e.transcript.some((e=>"user"===e.role||"assistant"===e.role)))return ze(e,"No exchanges yet — send a prompt first."),e.render(),!0;ze(e,"Recapping session…"),e.render();const t=await e.withWorking((t=>F(e.transcript,{callModel:(t,r)=>e.ask(t,r).then((e=>e.text)),model:e.ctx.model,signal:t})));return null===t?(ze(e,"Recap cancelled."),e.render(),!0):(e.ctx.lastRecap={sessionId:e.sessionId,ts:(new Date).toISOString(),text:t},e.saveConfig({lastRecap:e.ctx.lastRecap}),ze(e,`Session recap: ${t}`),e.render(),!0)}},{name:"resume",hint:"",category:"session",desc:"Switch to a previous session",handler:async e=>{const t=We();return t.length?(e.openOverlay({type:"resume",items:t,sel:0}),!0):(ze(e,"No previous sessions found — conversations from this host and from AEGIS Desktop both land in ~/.aegiscode/sessions.json"),e.render(),!0)}},{name:"rewind",args:["n"],hint:"[N]",category:"session",desc:"Revert the conversation to a checkpoint",handler:async(e,t)=>{const r=U(e.sessionId);if(!t.n)return r.length?(Je(e,g.buildRewindList(r,e.ctx)),e.render(),!0):(ze(e,"No checkpoints yet — snapshots are taken after each exchange."),e.render(),!0);const n=parseInt(t.n,10);if(Number.isNaN(n)||n<0||n>=r.length)return ze(e,`Unknown checkpoint ${t.n}. /rewind shows the list (indices 0..${Math.max(0,r.length-1)}).`),e.render(),!0;E(e.sessionId,e.transcript);const o=q(e.sessionId,n);if(!o)return ze(e,"Checkpoint unreadable — nothing restored."),e.render(),!0;e.transcript.length=0;for(const t of o)e.transcript.push(t);return ze(e,`Rewound to checkpoint ${n} (${o.length} messages). /rewind N again to undo.`),e.render(),!0}},{name:"agents",aliases:["sessions"],args:["role","task"],hint:"[role] [task]",category:"session",desc:"Show the agents panel, or run a sub-agent role preset — /agents <role> <task>",handler:async(e,t)=>{const r=(t.role||"").trim().toLowerCase();if(r){const n=(t._rest||"").trim().replace(/^\S+\s*/,"").trim();if(!n)return ze(e,`Usage: /agents <role> <task> — roles: ${qe().join(", ")}`),e.render(),!0;if(!Ue[r])return ze(e,`Unknown agent role "${r}". Roles: ${qe().join(", ")}`),e.render(),!0;const o=Re(r,n);return e.runPrompt?(await e.runPrompt(o),!0):(ze(e,`Composed ${r} prompt (${o.length} chars) — run in the TUI to send it.`),e.render(),!0)}return Je(e,g.buildAgents(e.state(),e.ctx)),e.render(),!0}},{name:"status",aliases:["st"],hint:"",category:"session",desc:"Show account and session status",handler:async e=>(await e.runTool("aegis_status",{}),Je(e,g.buildStatus(e.state(),Object.assign({},e.ctx,{caps:p()}))),e.render(),!0)},{name:"teleport",hint:"",category:"session",desc:"Resume a session from aegiscloud.org",handler:async e=>(ze(e,"Teleport requires an AEGIS cloud account with sessions. Sign in with `aegis login`, then run aegiscloud.org/teleport."),e.render(),!0)},{name:"theme",aliases:["t"],args:["mode"],hint:"[dark|light]",category:"model",desc:"Change the color theme",handler:async(e,t)=>{const r=(t.mode||"").toLowerCase();if("dark"===r||"light"===r){const t="light"===r?2:1;G.applyTheme(e.ctx,t)}else await e.showThemePicker();if(e.saveConfig({themeIndex:e.ctx.themeIndex}),ze(e,"Theme: "+(e.ctx.light?"light":"dark")),l(e.ctx.themeIndex)){const t=c().background;ze(e,`warning: this ${t} terminal is not what "${d[e.ctx.themeIndex].name}" is drawn for — body text may be unreadable.`),ze(e,` /terminal background ${t} pins the palette to this terminal, or /terminal background ${"dark"===t?"light":"dark"} if it reads you wrong.`)}return e.render(),!0}},{name:"terminal",aliases:["tty"],args:["mode","mode2"],hint:"[ascii|unicode|color|no-color|background <dark|light>|probe|star <native|narrow>|width <cols>|auto|status]",category:"model",desc:"Show or override how this terminal is drawn (mark, colour, width)",handler:async(e,t)=>{const r=(t.mode||"").toLowerCase(),n=null!=t.mode2?String(t.mode2).trim():"";if(""===r||"status"===r)return Je(e,g.buildTerminalCaps(p(),{pinned:!!c().pinned})),e.render(),!0;const o=c(),s={glyphs:o.glyphs,face:o.face,star:o.star,depth:o.depth,vt:o.vt,wideRunes:o.wideRunes,background:o.background,backgroundKnown:o.backgroundKnown,reasons:Object.assign({},o.reasons)};if("auto"===r)return h(),ze(e,"Terminal: auto — capabilities re-probed from the environment."),e.render(),!0;if("probe"===r){const t=await m();return G.applyTheme(e.ctx,e.ctx.themeIndex),ze(e,t.known?`Terminal: background ${t.background} (${t.reason}) — /theme auto follows it.`:`Terminal: no answer to the background query (${t.reason}).`),ze(e," /terminal background dark|light pins it without asking."),Je(e,g.buildTerminalCaps(p(),{pinned:!!c().pinned})),e.render(),!0}if("ascii"===r||"unicode"===r)s.glyphs="ascii"===r?"ascii":"unicode",s.face="ascii"===r?"edges":"native",s.star="ascii"===r?"narrow":"native",s.reasons&&(s.reasons.glyphs=`/terminal ${r}`);else if("color"===r||"no-color"===r||"nocolor"===r)s.depth="color"===r?24:0,s.reasons&&(s.reasons.depth=`/terminal ${r}`);else{if("star"!==r){if("background"===r||"bg"===r){const t=n.toLowerCase();return["dark","light"].includes(t)?(s.background=t,s.backgroundKnown=!0,s.reasons&&(s.reasons.background=`/terminal background ${t}`),u(Object.assign({},s)),G.applyTheme(e.ctx,e.ctx.themeIndex),ze(e,`Terminal: background pinned to ${t} — /theme auto follows it.`),Je(e,g.buildTerminalCaps(p(),{pinned:!!c().pinned})),e.render(),!0):(ze(e,"Usage: /terminal background <dark|light>"),e.render(),!0)}if("width"===r){const t=Number(n);return!Number.isFinite(t)||t<20?(ze(e,"Usage: /terminal width <cols> (>= 20)"),e.render(),!0):(u(Object.assign({},s,{cols:Math.round(t)})),ze(e,`Terminal: width pinned to ${Math.round(t)} columns.`),Je(e,g.buildTerminalCaps(p(),{pinned:!!c().pinned})),e.render(),!0)}return ze(e,"Usage: /terminal [ascii|unicode|color|no-color|background <dark|light>|probe|star <native|narrow>|width <cols>|auto|status]"),e.render(),!0}{const t=n.toLowerCase();if(!["native","narrow"].includes(t))return ze(e,"Usage: /terminal star <native|narrow>"),e.render(),!0;s.star=t,s.reasons&&(s.reasons.star=`/terminal star ${t}`)}}return u(s),Je(e,g.buildTerminalCaps(p(),{pinned:!!c().pinned})),ze(e,"Terminal updated — the current viewport is redrawn; text already scrolled past keeps its old glyphs."),e.render(),!0}},{name:"version",aliases:["v"],hint:"",category:"session",desc:"Show version",handler:async e=>(ze(e,`aegiscode v${Be}`),e.render(),!0)},{name:"doctor",args:["action"],hint:"[fix|system]",category:"support",desc:"Run diagnostic checks on this environment",handler:async(t,r)=>{const d=(r&&r.action||"").toLowerCase();if(d&&"fix"!==d&&"system"!==d)return ze(t,'Usage: /doctor [fix|system] — "fix" re-tightens the data dir to 0700/0600, "system" checks the machine itself'),t.render(),!0;const l=[],c=(e,t,r)=>l.push([t,e,r]);c("Node",!0,process.version),c("CWD",e.existsSync(process.cwd()),process.cwd());let u=!1;try{n("git rev-parse --git-dir",{cwd:process.cwd(),stdio:["ignore","ignore","ignore"],timeout:4e3}),u=!0}catch{}c("git repo",u,u?"inside a work tree":"not a git repository");const h=ye.keyStatus();c("AEGIS key",h.configured,h.configured?`${ke(h.key)} via ${ye.sourceLabel(h.source)}`:`not set — ${ye.HOW_TO_SET} (free key: ${R("doctor")})`),c("credentials",!0,`${h.path}${h.fileMode?` (${h.fileMode})`:""}`),c("cloud memory",h.memoryToken,h.memoryToken?"token held":"no memory token — /cloud activate"),h.legacyPlaintext&&c("plaintext key",!1,`a copy also sits in ${S()} (another AEGIS CLI) — /key re-saves it to ${h.path}`),c("config path",!0,S());const p=C();let m=null;"fix"===d&&(m=T(p));const g=_(p);if(g.exists)if(g.modesMeaningful){const e=g.exposed.slice(0,4).map((e=>`${e.rel} ${e.mode}`)).join(", ");c("data dir",0===g.exposed.length,0===g.exposed.length?`${p} (${g.rootMode}, all private)`:`${p} (${g.rootMode}) — ${g.exposed.length} path(s) group/world-accessible: ${e}${g.exposed.length>4?", …":""} — run /doctor fix`)}else c("data dir",!0,`${p} (${g.total} path(s)) — this filesystem has no POSIX permission bits; access is governed by the profile directory's own ACL`);else c("data dir",!0,`${p} (not created yet)`);if(m&&!m.modesMeaningful)c("repair",!0,"nothing to tighten — this filesystem has no POSIX permission bits");else if(m){const e=m.fixed.slice(0,3).map((e=>`${e.rel} ${e.from}→${e.to}`)).join(", ");c("repair",0===m.remaining.length,0===m.remaining.length?m.fixed.length?`tightened ${m.fixed.length} path(s) — ${e}${m.fixed.length>3?", …":""}`:"already private, nothing to tighten":`${m.remaining.length} path(s) still exposed — `+m.failed.map((e=>`${e.rel}: ${e.reason}`)).join(", "))}let y=null;if("system"===d){const e=Ae.collect();if(e.ok){y=Ae.assess(e.data);for(const e of y.findings)c(`${e.title} (${e.severity})`,!1,`${e.detail} → ${e.remedyText}`);for(const e of y.clean)c(e.title,!0,e.detail);for(const e of y.unassessed)c(`${e.title} (unassessed)`,!1,e.reason)}else c("machine checks",!1,"not-windows"===e.reason?"not available on this platform — the machine audit is Windows-only (cli/src/sysdiag.js)":`could not run: ${e.reason}`)}const f=[[o(s.gold+i,"Doctor"),o(a,"")],[o(s.gray,"─".repeat(30))]];for(const[e,t,r]of l)f.push([o(e?s.green:s.coral," "+(e?"✔":"⚠")),o(s.white,` ${t}: `),o(s.gray,String(r))]);if(y&&y.findings.length){const e=y.summary;f.push([o(s.gold," Remedy"),o(s.gray,` — ${e.findings} finding(s) across ${e.assessed}/${e.total} measured checks.`)]),f.push([o(s.gray," Run in an ELEVATED PowerShell. AEGIS diagnoses this; it does not change your machine.")]);for(const e of Ae.remedyScript().split("\n"))f.push([o(s.gray,` ${e}`)])}return Je(t,f),t.render(),!0}},{name:"upgrade",args:["action"],hint:"[check|apply]",category:"support",desc:"Check for a newer published version (apply: install it now)",handler:async(e,t)=>{const r=String(t&&t.action||"check").toLowerCase();if(!["check","apply"].includes(r))return ze(e,"Usage: /upgrade [check|apply]"),e.render(),!0;const n=Ee();ze(e,"Checking the npm registry…"),e.render();const i=e&&e.withWorking?t=>e.withWorking(t):e=>e(),a=e.ctx&&e.ctx.demo?null:await i((()=>Promise.resolve(Te()))),d=_e({latest:a,method:n});if(Je(e,d.lines.map((e=>[o(s.white,e)]))),e.render(),"apply"!==r)return!0;if(!d.plan||!d.plan.apply)return ze(e,d.plan?`Nothing to install: ${d.plan.instruction}`:"Nothing to install."),e.render(),!0;ze(e,`Running: ${d.plan.instruction}`),e.render();const l=Pe({method:n,latest:a,current:d.plan.current});if(l.ok&&!l.skipped){if(ze(e,`Installed ${d.plan.latest}. Restart aegiscode to use it.`),l.output)for(const t of l.output.split("\n").slice(-6))ze(e,` ${t}`)}else l.skipped?ze(e,`Not applied: ${l.instruction}`):(ze(e,`Upgrade failed: ${l.error}`),ze(e,`Run it yourself: ${l.command}`));return e.render(),!0}},{name:"vim",args:["mode"],hint:"[on|off]",category:"model",desc:"Toggle vim keymap",handler:async(e,t)=>{const r=(t.mode||"").toLowerCase();if(r&&!["on","off"].includes(r))return ze(e,"Usage: /vim [on|off]"),e.render(),!0;const n="on"===r||"off"!==r&&!e.ctx.vim;return e.ctx.vim=n,e.saveConfig({vim:n}),ze(e,"Vim keymap: "+(n?"on":"off")),e.render(),!0}},{name:"permissions",args:["mode","pattern"],hint:'[allow|deny|ask "<pattern>" | default <ask|allow|deny> | clear]',category:"model",desc:"Set permissions for tool use",handler:async(e,t)=>{const r=w(),n=(t.mode||"").toLowerCase(),o=t.pattern;if(!n)return Je(e,g.buildPermissions({...r,_path:x()},null,e.ctx)),e.render(),!0;if("clear"===n)return j($.defaultMode),b({...$,allow:[],deny:[],ask:[]}),ze(e,"Permissions reset to defaults (no rules)."),e.render(),!0;if("default"===n&&["ask","allow","deny"].includes(o))return j(o),ze(e,`Default permission mode: ${o}`),e.render(),!0;if(["allow","deny","ask"].includes(n)&&o){const{added:t,rules:s}=v(n,o,r);return b(s),ze(e,t?`Added ${n} rule: ${o}`:`Rule already present: ${o}`),e.render(),!0}return ze(e,'Usage: /permissions [allow|deny|ask "<pattern>" | default <ask|allow|deny> | clear]'),e.render(),!0}},{name:"hooks",args:["sub"],hint:"[status|list|install]",category:"model",desc:"View hooks configuration status, list configured hooks, or install this repo's guard hooks",handler:async(e,t)=>{const r=(t.sub||"").toLowerCase();if("install"===r){const r=/--dry-run|\bdry-?run\b/.test(String(t._rest||"")),n=St.installRepoHooks({cwd:process.cwd(),dryRun:r});if(n.ok)if(r){ze(e,`would install the guard hooks in ${n.status.repo}`);for(const t of n.actions)ze(e,` ${t}`);n.status.installed&&ze(e,"core.hooksPath is already .githooks — nothing to change")}else if(n.changed){Ye(e,"installed the guard hooks — core.hooksPath = .githooks (verified)");for(const t of n.actions)ze(e,` ${t}`)}else Ye(e,"guard hooks already installed (core.hooksPath = .githooks)");else if(ze(e,n.error),n.actions.length)for(const t of n.actions)ze(e,` ${t}`);return n.ok&&ze(e,n.status.execNote),e.render(),!0}const{hooks:n,from:o}=St.readHookConfig();return"list"===r?(Je(e,g.buildHooksList({hooks:n},e.ctx)),e.render(),!0):""===r||"status"===r?(Je(e,g.buildHooksStatus({...Ct(n),fromPaths:o},e.ctx)),e.render(),!0):(ze(e,`unknown subcommand: ${t.sub}`),ze(e,"available: status, list, install [--dry-run]"),e.render(),!0)}},{name:"credentials",hint:"",category:"model",desc:"Show where credentials are stored",handler:async n=>{const o=r.join(t.homedir(),".claude",".credentials.json"),s=o.replace(t.homedir(),"~");return e.existsSync(o)?ze(n,`Credentials live in ${s} (managed by the Claude Code CLI). aegiscode reads them but never writes them.`):ze(n,"No credential file found. The Claude Code CLI manages auth (OS keychain or ~/.claude/.credentials.json)."),n.render(),!0}},{name:"install-github-app",hint:"",category:"model",desc:"Install the GitHub App for PR workflows",handler:async e=>(ze(e,"The GitHub App is installed through the Claude Code CLI: run `claude --install-github-app` once."),e.render(),!0)},{name:"troubleshooting",hint:"",category:"support",desc:"Troubleshoot common issues",handler:async e=>(Je(e,g.buildTroubleshooting(e.state(),e.ctx)),e.render(),!0)},{name:"feedback",hint:"",category:"support",desc:"Send feedback to the AEGIS team",handler:async e=>(ze(e,"Opening the feedback form…"),Ie(je.feedback)||ze(e,`Feedback: ${je.feedback}`),e.render(),!0)},{name:"bug",hint:"",category:"support",desc:"Report a bug (opens a GitHub issue)",handler:async e=>(ze(e,`Opening a GitHub issue… (aegiscode v${Be}, ${process.version}, ${t.platform()})`),Ie(je.issues)||ze(e,`Issues: ${je.issues}`),e.render(),!0)},{name:"issue",aliases:["bugs"],hint:"",category:"support",desc:"Report an issue",handler:async e=>(ze(e,"Opening a GitHub issue…"),Ie(je.issues)||ze(e,`Issues: ${je.issues}`),e.render(),!0)},{name:"onboarding",hint:"",category:"support",desc:"Show getting-started tips",handler:async e=>(Je(e,g.buildOnboarding(e.state(),e.ctx)),e.render(),!0)},{name:"shell-completion",hint:"",category:"support",desc:"Set up shell completion",handler:async e=>(Je(e,g.buildShellCompletion(e.state(),e.ctx)),e.render(),!0)},{name:"terminal-setup",hint:"",category:"support",desc:"Check and fix terminal setup",handler:async e=>(Je(e,g.buildTerminalSetup(e.state(),e.ctx)),e.render(),!0)},{name:"pr-comments",hint:"",category:"support",desc:"Review and reply to pull request comments",handler:async e=>(ze(e,"PR comments need GitHub auth. Run /prs to check connectivity, then use the `gh` CLI or the GitHub web UI."),e.render(),!0)},{name:"prs",hint:"",category:"support",desc:"List pull requests in this repo",handler:async e=>{try{const t=n("gh pr list --limit 8",{encoding:"utf8",timeout:15e3,stdio:["ignore","pipe","ignore"]});Je(e,g.buildPRs(t.toString(),e.ctx))}catch{ze(e,"gh not authenticated (or not installed) — run `gh auth login` first.")}return e.render(),!0}},{name:"review",hint:"",category:"support",desc:"Review a pull request",handler:async e=>(ze(e,"/review needs GitHub auth via gh. Run /prs to list open PRs, then open one in the browser."),e.render(),!0)},{name:"benchmark",hint:"",category:"support",desc:"Run in-app micro-benchmarks",handler:async e=>{const t=e=>{const t=process.hrtime.bigint();return e(),(Number(process.hrtime.bigint()-t)/1e6).toFixed(2)},r=[["2,000 span() calls",t((()=>{for(let e=0;e<2e3;e++)o(s.white,"x")}))],["estimateTokens × 20 (500 chars)",t((()=>{for(let e=0;e<20;e++)B("x".repeat(500))}))]];return De&&"function"==typeof De.renderMarkdown&&r.push(["renderMarkdown × 200",t((()=>{for(let e=0;e<200;e++)De.renderMarkdown("# Heading\n\nSome **bold** and `code` with a [link](https://x.test).\n\n- a\n- b\n- c\n",80)}))]),Je(e,g.buildBenchmark(r,e.ctx)),e.render(),!0}},{name:"waifu",hint:"",category:"fun",desc:"Summon a waifu",handler:async e=>(Je(e,g.buildWaifu(e.ctx)),e.render(),!0)},{name:"new",aliases:["start"],hint:"",category:"session",desc:"Start a new session (clears the transcript, fresh session id)",handler:async e=>{e.transcript.length=0,"function"==typeof e.clearConversationMemory&&e.clearConversationMemory();const t="aegis-"+Math.random().toString(36).slice(2,10);return e.sessionId=t,e.ctx.sessionId=t,ze(e,`New session started (${t}) — earlier context cleared.`),e.render(),!0}},{name:"tokens",aliases:["tok"],hint:"",category:"data",desc:"Show token usage breakdown and estimated spend",handler:async e=>{const t=W(e.transcript,e.ctx.model);return Je(e,g.buildTokens({...e.state(),contextWindow:t.contextWindow,costEur:t.cost},e.ctx)),e.render(),!0}},{name:"skills",aliases:["sk"],args:["sub"],hint:"[name|refresh]",category:"session",desc:"List skills (SKILL.md in the standard skill dirs)",handler:async(n,o)=>{const s=(o.sub||"").trim().toLowerCase(),i=function(){const n=[r.join(t.homedir(),".aegis","skills"),r.join(process.cwd(),".aegis","skills"),r.join(t.homedir(),".aegiscode","skills"),r.join(process.cwd(),".aegiscode","skills"),r.join(t.homedir(),".claude","skills")],o=[];for(const t of n){const n=t.startsWith(process.cwd())?"project":"user";let s=[];try{s=e.readdirSync(t,{withFileTypes:!0}).filter((e=>e.isDirectory())).map((e=>e.name))}catch{continue}for(const i of s){const s=r.join(t,i,"SKILL.md");try{const t=e.readFileSync(s,"utf8"),r=(/^description:\s*(.+)$/m.exec(t)||[])[1]||"";o.push({source:n,name:i,namespace:null,description:r.trim(),path:s,content:t})}catch{}}}return o}(),a=[r.join(t.homedir(),".aegis","skills"),r.join(process.cwd(),".aegis","skills"),r.join(t.homedir(),".aegiscode","skills"),r.join(process.cwd(),".aegiscode","skills"),r.join(t.homedir(),".claude","skills")].map((e=>e.replace(t.homedir(),"~")));if("refresh"===s||"reload"===s)return ze(n,`Skills refreshed — ${i.length} found (${a.length} dirs scanned).`),n.render(),!0;if(s){const e=i.find((e=>e.name===s));return e?(Je(n,g.buildSkillDetail(e,n.ctx)),n.render(),!0):(ze(n,`Unknown skill "${s}". /skills lists what exists on disk.`),n.render(),!0)}return Je(n,g.buildSkills(i,a,n.ctx)),n.render(),!0}},{name:"thinking",args:["mode"],hint:"[on|off]",category:"model",desc:"Toggle thinking blocks expanded/collapsed",handler:async(e,t)=>{const r=(t.mode||"").toLowerCase();if(r&&!["on","off"].includes(r))return ze(e,"Usage: /thinking [on|off]"),e.render(),!0;const n="on"===r||"off"!==r&&!(!0===e.ctx.thinking);return e.ctx.thinking=n,e.saveConfig({thinking:n}),ze(e,"Thinking blocks: "+(n?"expanded":"collapsed")),e.render(),!0}},{name:"mcp",args:["sub","name","command"],hint:"[add <name> <command> [args…]|remove <name>|<name>]",category:"model",desc:"Show MCP server configuration",handler:async(e,t)=>{const r=k().mcpServers||{},n=(t.sub||"").toLowerCase();if("add"===n){const n=(t.name||"").trim(),o=(t.command||"").trim();if(!n||!o)return ze(e,'Usage: /mcp add <name> "<command with args>"'),e.render(),!0;const s=o.split(/\s+/).filter(Boolean);return f({mcpServers:{...r,[n]:{command:s[0],args:s.slice(1)}}}),ze(e,`Added MCP server "${n}" (${s[0]}). Configuration only — this build has no MCP runtime.`),e.render(),!0}if("remove"===n||"rm"===n){const n=(t.name||"").trim();if(!n)return ze(e,"Usage: /mcp remove <name>"),e.render(),!0;if(!r[n])return ze(e,`No MCP server "${n}". /mcp lists the configured ones.`),e.render(),!0;const o={...r};return delete o[n],f({mcpServers:o}),ze(e,`Removed MCP server "${n}".`),e.render(),!0}if(n&&r[n]){const t=r[n];return Je(e,[[o(s.gold,`MCP server: ${n}`)],[o(s.gray,"─".repeat(30))],[o(s.white,` command: ${`${t.command||""} ${(t.args||[]).join(" ")}`.trim()}`)],[o("","")],[o(s.gray,"Configuration only — this build has no MCP runtime.")]]),e.render(),!0}return Je(e,g.buildMcp(r,[S(),x()],e.ctx)),e.render(),!0}},{name:"memory",aliases:["memories"],hint:"",category:"model",desc:"List the most recent AEGIS cloud-memory entries",tool:"aegis_memory_list",build:()=>({})},{name:"memory-deep",aliases:["recall-deep"],args:["mode"],hint:"[on|off]",category:"model",desc:"Toggle DEEP recall for this session — brain corrections + cached answers (metered: one embedding per turn)",handler:async(e,t)=>{const r=(t.mode||"").toLowerCase();if(r&&!["on","off"].includes(r))return ze(e,"Usage: /memory-deep [on|off]"),e.render(),!0;const n="on"===r||"off"!==r&&!(!0===e.ctx.recallDeep);return e.ctx.recallDeep=n,ze(e,`Deep recall: ${n?"on — brain corrections + cached answers, one embedding per turn":"off (only the cheap recall read)"}${n?" · this session only":""}`),e.render(),!0}},{name:"confirm",aliases:["confirmations"],args:["mode"],hint:"[on|off]",category:"model",desc:"Toggle tool-call confirmation prompts",handler:async(e,t)=>{const r=(t.mode||"").toLowerCase();if(r&&!["on","off"].includes(r))return ze(e,"Usage: /confirm [on|off]"),e.render(),!0;const n="on"===r||"off"!==r&&!A().enabled;return I(n),ze(e,`Confirmation prompts: ${n?"on":"off"} (default permission mode: ${n?"ask":"allow"})`),e.render(),!0}},{name:"automode",aliases:["yolo"],args:["mode"],hint:"[on|off]",category:"model",desc:"Toggle automode — auto-approve all tool executions",handler:async(e,t)=>{const r=(t.mode||"").toLowerCase();if(r&&!["on","off"].includes(r))return ze(e,"Usage: /automode [on|off]"),e.render(),!0;const n="on"===r||"off"!==r&&A().enabled;return I(!n),"function"==typeof e.setAutoRounds&&e.setAutoRounds(n),n?Je(e,g.buildAutomode(e.state(),e.ctx)):ze(e,"automode off — confirmations restored."),e.render(),!0}},{name:"multiyolo",aliases:["multiauto"],args:["task"],hint:"<task>",category:"session",desc:"Multi-agent orchestration with automode — /multiyolo <task>",handler:async(e,t)=>{const r=(t._rest||t.task||"").trim();return r?Xe(e,r,{yolo:!0}):(ze(e,"Usage: /multiyolo <task>"),e.render(),!0)}},{name:"router",args:["sub","tier","modelId"],hint:"[on|off|set <tier> <modelId>|stats]",category:"model",desc:"Show or manage the model router config",handler:async(e,t)=>{const r=k(),n=r.autoRouter||{enabled:!1,tiers:{}},d=(t.sub||"").toLowerCase(),l=e=>f({autoRouter:e});if("on"===d)return l({...n,enabled:!0}),ze(e,"Auto-router: on."),e.render(),!0;if("off"===d)return l({...n,enabled:!1}),ze(e,"Auto-router: off."),e.render(),!0;if("set"===d){const r=(t.tier||"").toLowerCase(),o=(t.modelId||"").trim();return["simple","medium","complex"].includes(r)&&o?(l({...n,tiers:{...n.tiers||{},[r]:o}}),ze(e,`Auto-router: ${r} -> ${o}`),e.render(),!0):(ze(e,"Usage: /router set <simple|medium|complex> <modelId>"),e.render(),!0)}return"stats"===d?(Je(e,[[o(s.gold+i,"Router stats"),o(a,"")],[o(s.gray,"─".repeat(30))],[o(s.gray,"No learned outcomes yet — this build does not auto-route.")],[o(s.gray,"Tiers: simple/medium/complex via /router set.")]]),e.render(),!0):(Je(e,g.buildRouter(r,e.ctx)),e.render(),!0)}},{name:"multi",args:["task","mode"],hint:"<task> [run]",category:"session",desc:'Compose a multi-agent task (add "run" to execute)',handler:async(e,t)=>{let r=(t._rest||t.task||"").trim(),n=(t.mode||"").toLowerCase();return"run"!==n&&/\s+run$/i.test(r)&&(n="run",r=r.replace(/\s+run$/i,"").trim()),r?"run"!==n?(Je(e,g.buildAegisMulti(r,e.ctx)),e.render(),!0):Xe(e,r):(ze(e,"Usage: /multi <task> [run]"),e.render(),!0)}},{name:"research",args:["question"],hint:"<question>",category:"session",desc:"Research a topic with a multi-perspective council prompt",handler:async(e,t)=>{const r=(t._rest||t.question||"").trim();if(!r)return ze(e,"Usage: /research <question>"),e.render(),!0;const n=Oe(r,process.cwd());return e.runPrompt?(await e.runPrompt(n),!0):(ze(e,`Composed research prompt (${n.length} chars) — run in the TUI to send it.`),e.render(),!0)}},{name:"debate",aliases:["db"],args:["topic"],hint:"<topic>",category:"session",desc:"Run a structured debate on the current model",handler:async(e,t)=>{const r=(t._rest||t.topic||"").trim();if(!r)return ze(e,"Usage: /debate <topic>"),e.render(),!0;const n=Ge(r,e.ctx.model||"");return e.runPrompt?(await e.runPrompt(n),!0):(ze(e,`Composed debate prompt (${n.length} chars) — run in the TUI to send it.`),e.render(),!0)}},{name:"billing",aliases:["balance","spend"],hint:"",category:"support",desc:"Show billing info — token-bank balance and recent spend",handler:async e=>{await e.runTool("aegis_balance",{});const t=await e.refreshSpend(),r=e.state();return Je(e,g.buildBilling({...r,balance:t&&null!=t.balance?t.balance:r.balance,payment:await Qe(e)},e.ctx)),e.render(),!0}},{name:"topup",aliases:["fund"],args:["amount"],hint:"[EUR]",category:"support",desc:"Top up the token bank — opens the payment page and confirms the credit here",handler:async(e,t)=>{const r=String(t.amount||t._rest||"").trim();let n;try{n=require(require("./sharedpaths.js").resolveShared("client/topup.js"))}catch(t){return ze(e,`top-up is unavailable in this build — ${t.message}`),e.render(),!0}const o=n.parseTopupAmount(r);if(!o.ok)return ze(e,o.message),e.render(),!0;if(!e.client.apiKey)return ze(e,`no AEGIS key on this machine — ${ye.HOW_TO_SET}, then /topup ${o.amount}`),e.render(),!0;const s=e.withWorking?await e.withWorking((()=>n.startTopup(e.client,o.amount))):await n.startTopup(e.client,o.amount);if(!s.ok)return ze(e,`the top-up could not be started — ${s.message}`),s.hint&&ze(e,s.hint),e.render(),!0;ze(e,`opening the payment page — ${o.amount} EUR`),ze(e,s.url);const i=Math.round(n.TOPUP_POLL_MS*n.TOPUP_POLL_TRIES/1e3);ze(e,`watching this account's bank for up to ${i}s; the credit is confirmed here, not in the browser`),e.render(),Ie(s.url)||ze(e,"could not open a browser — use the URL above");const a=n.createCreditWatch(e.client);let d=null,l=!1;const c=()=>{l=!0,d&&clearTimeout(d)},u=async()=>{if(l)return;const t=await a.tick();return"credited"===t.state?(c(),ze(e,`credit confirmed — the bank is now ${t.amount.toFixed(2)} EUR`),void e.render()):"expired"===t.state?(c(),ze(e,"no credit observed within the watch window — if you completed the payment it may still land; /billing shows the bank"),void e.render()):(d=setTimeout(u,n.TOPUP_POLL_MS),void(d&&"function"==typeof d.unref&&d.unref()))};return d=setTimeout(u,n.TOPUP_POLL_MS),d&&"function"==typeof d.unref&&d.unref(),!0}},{name:"cloud",args:["sub","value"],hint:"[status|key <api_key>|activate|deactivate|memory [on|off]|sync [on|off|now]]",category:"support",desc:"Show and control ÆGIS cloud sync",handler:async(e,t)=>{const r=(t.sub||"").toLowerCase(),n=(t.value||t._rest||"").trim();if("key"===r)return await wt(e,n),e.render(),!0;if("activate"===r){if(!e.client.apiKey)return ze(e,`no key — ${ye.HOW_TO_SET}`),e.render(),!0;try{const t=await e.withWorking((()=>e.client.memoryActivate())),r=await e.client.getMemoryToken();r&&ye.saveMemoryToken(r,{memorySubscribed:!0}),Ye(e,t&&!1===t.ok?"the server refused activation":"cloud memory activated for this account"),t&&t.token_limit&&ze(e,`quota: ${t.tokens_used||0} / ${t.token_limit} synced tokens`)}catch(t){ze(e,`activation failed: ${t.message}`)}return e.render(),!0}if("deactivate"===r)return ye.clearMemoryToken(),e.client.setApiKey(e.client.apiKey),ze(e,"cloud memory token cleared locally — sync stops until /cloud activate re-issues one"),ze(e,"the account itself is still subscribed; manage the subscription here:"),ze(e,O("upgrade","cloud_deactivate")),e.render(),!0;if("memory"===r||"persist"===r||"memory-persist"===r){const t=(n||"status").toLowerCase();if("on"===t||"off"===t){const r="on"===t;return vt(e,r),r?(Ye(e,"persisting memory on — sessions are stored to your account so an interrupted turn can be resumed"),ze(e,"/cloud memory shows the quota; past the plan’s ceiling reads keep working and only new writes pause")):(ze(e,"persisting memory off — nothing new is stored"),ze(e,"everything already in the cloud stays readable (/aegis-recall <topic>), and /sync now still pushes once by hand")),e.render(),!0}return Je(e,$t(e)),e.render(),!0}if("sync"===r||"push"===r||"pull"===r){const t="sync"===r?(n||"status").toLowerCase():r;if("on"===t||"off"===t){const r="on"===t;return vt(e,r),ze(e,r?'persisting memory on — sessions are stored after each turn (this is the old "cloud sync")':"persisting memory off — nothing new is stored; /sync now still runs a manual pass"),e.render(),!0}if("now"===t)return await xt(e),e.render(),!0;const d=fe.status();Je(e,[...$t(e),[o(s.gray,"")],[o(s.white+i,"Sync ledger"),o(a,"")],[o(s.gray,` local sessions: ${d.local} · pending push: ${d.pending} · in sync: ${d.synced}`)],[o(s.gray,` last push: ${d.lastPushAt?new Date(d.lastPushAt).toLocaleString():"never"} · last pull: ${d.lastPullAt?new Date(d.lastPullAt).toLocaleString():"never"}`)],[o(s.gray,` state: ${d.path}`)]]);for(const t of d.errors.slice(0,3))Je(e,[[o(s.coral,` ⚠ ${t.error}`)]]);return e.render(),!0}const d=fe.status();return Je(e,[...kt(e,"AEGIS cloud"),[o(s.gray,"")],...$t(e),[o(s.gray,"")],[o(s.white+i," Sync"),o(a,"")],[o(s.gray,` ${d.pending} pending · ${d.synced} in sync · ${d.importedRemote} pulled from cloud`)],[o(s.gray," /cloud memory on | off · /cloud sync on | off · /sync now")]]),e.render(),!0}},{name:"key",aliases:["apikey","api-key"],args:["value"],hint:"[<api_key>|status|clear|register]",category:"auth",desc:"Save or show the AEGIS account key",handler:async(e,t)=>{const r=String(t.value||t._rest||"").trim(),n=r.toLowerCase();if("status"===n)return Je(e,kt(e)),e.render(),!0;if("register"===n){const t=await e.registerAccount();return t.alreadyKeyed?ze(e,"this machine already has an AEGIS key — /key status shows it. Re-registering cannot mint a new welcome trial: that is granted once per machine, ever. For a fresh trial, sign up at aegiscloud.org; to point this session at a different key, /key clear first."):t.key&&t.ok?Ye(e,"AEGIS account key provisioned and saved"):t.key?ze(e,"the account was created but its key could not be saved — run /key <api_key> with the key from aegiscloud.org"):ze(e,`could not register this machine: ${t.error?t.error.message:"the server returned no account key"}`),e.render(),!0}if("clear"===n||"remove"===n||"rm"===n){const t=e.forgetApiKey();return Ye(e,t.cleared?`key removed from ${t.path}`:"there was no saved key to remove"),ye.legacyKeyOnDisk()&&ze(e,`a copy is still in ${S()} (written by another AEGIS CLI) — delete the "aegiscloud" block to finish the job`),e.render(),!0}return await wt(e,r),e.render(),!0}},{name:"sync",aliases:["cloudsync","cloud-sync"],args:["mode"],hint:"[now|on|off|status]",category:"data",desc:"Store sessions in AEGIS Cloud (cross-session memory)",hidden:e=>!rt(),handler:async(e,t)=>{const r=(t.mode||"").toLowerCase();if("on"===r||"off"===r)return vt(e,"on"===r),ze(e,"on"===r?"persisting memory on — sessions are stored so an interrupted turn can be resumed":"persisting memory off — nothing new is stored; /sync now still runs a manual pass"),e.render(),!0;if("status"===r){const t=fe.status(),r=$t(e);return r.push([o(s.gray,"")]),r.push([o(s.gray,` local ${t.local} · pending ${t.pending} · in sync ${t.synced}`)]),Je(e,r),e.render(),!0}return await xt(e),e.render(),!0}},{name:"gmail",hint:"",category:"support",desc:"Link Gmail to conversations",handler:async e=>(ze(e,"Gmail integration needs Google OAuth — not available in this build. Use /export to save conversations to files instead."),e.render(),!0)},{name:"clone",aliases:["fetch-site","websnap"],args:["url"],hint:"<url>",category:"workspace",desc:"Clone a website into a local project",handler:async(e,t)=>{const r=(t._rest||t.url||"").trim();return r?(ze(e,`/clone needs a web-fetch tool and a chat service — not available in this build. Use /init to scaffold a fresh project instead of ${r}.`),e.render(),!0):(ze(e,"Usage: /clone <url>"),e.render(),!0)}},{name:"release-notes",hint:"",category:"support",desc:"What's new",handler:async e=>(Je(e,g.buildReleaseNotes(e.state(),e.ctx)),e.render(),!0)},{name:"aegis-status",hint:"",category:"aegis",desc:"Show account status — API key, plan, account and cloud memory",tool:"aegis_status",build:()=>({})},{name:"aegis-ask",aliases:["ask"],args:["question"],hint:"<question>",category:"aegis",desc:"Ask ÆGIS pooled inference a question (auto-routed)",tool:"aegis_ask",build:e=>({prompt:e})},{name:"aegis-recall",aliases:["recall"],args:["topic"],hint:"<topic>",category:"aegis",desc:"Recall cross-session memory about a topic (cloud)",tool:"aegis_memory_search",build:e=>({query:e})},{name:"aegis-remember",aliases:["remember"],args:["note"],hint:"<note>",category:"aegis",desc:"Save a note or decision to cross-session memory",tool:"aegis_memory_save",build:e=>({content:e})},{name:"aegis-council",aliases:["council"],args:["question"],hint:"<question>",category:"aegis",desc:"Put a question to the ÆGIS council (multi-perspective deliberation)",hidden:()=>!rt(),handler:async(e,t)=>{const r=(t._rest||t.question||"").trim();if(!r)return ze(e,"Usage: /aegis-council <question>"),e.render(),!0;const n=Oe(`Deliberate as a council and vote on: ${r}`,process.cwd());return e.runPrompt?(await e.runPrompt(n),!0):(ze(e,`Composed council prompt (${n.length} chars) — run in the TUI to send it.`),e.render(),!0)}},{name:"aegis-print",args:["question"],hint:"<question>",category:"aegis",desc:"Ask pooled inference and print the answer cleanly",hidden:()=>!rt(),handler:async(e,t)=>{const r=(t._rest||t.question||"").trim();if(!r)return ze(e,"Usage: /aegis-print <question>"),e.render(),!0;const n=await e.ask(r);return Je(e,g.buildAegisPrint("ÆGIS",{result:n.text,model:n.model,provider:"aegis"},e.ctx)),e.render(),!0}},{name:"aegis-multi",args:["task","mode"],hint:"<task> [run]",category:"aegis",desc:'Compose an ÆGIS /multi multi-agent task (add "run" to execute)',hidden:()=>!rt(),handler:async(e,t)=>{let r=(t._rest||t.task||"").trim(),n=(t.mode||"").toLowerCase();return"run"!==n&&/\s+run$/i.test(r)&&(n="run",r=r.replace(/\s+run$/i,"").trim()),r?"run"!==n?(Je(e,g.buildAegisMulti(r,e.ctx)),e.render(),!0):Xe(e,r):(ze(e,"Usage: /aegis-multi <task> [run]"),e.render(),!0)}},{name:"byok",hint:"",category:"auth",desc:"List every provider you can bring your own key for, and which are set",handler:async e=>{const t=await gt(e.client);if(!t)return await e.runTool("aegis_byok_status",{}),!0;const r=t.filter((e=>e.configured)).length,n=[[o(s.gold+i,"Bring your own key"),o(a,"")],[o(s.gray,"─".repeat(34))],[o(r?s.green:s.gray,` ${r} of ${t.length} providers set`),o(s.gray," — /byok-list picks one, or /byok-key <provider>")],"",...ft(t)];return Je(e,n),e.render(),!0}},{name:"byok-set",args:["provider"],hint:"<provider>",category:"auth",desc:"Store your provider key on your AEGIS ACCOUNT (pooled route) — for the byok class use /byok-key",tool:"aegis_byok_set",secret:"key",build:e=>({provider:String(e||"").trim()}),async secretDescribe(e,t){const r=String(e.provider||"").trim(),n=await gt(t);if(!n)return r?null:{note:"Usage: /byok-set <provider> — /byok lists them.",prompt:"provider key: "};const o=yt(n,r);if(o.ambiguous)return{note:`"${r}" matches ${o.ambiguous.join(", ")} — retype the exact id. Nothing was sent.`,prompt:null};const s=o.provider;if(!s)return{note:`unknown provider "${r}". Known ids: ${n.map((e=>e.id)).join(", ")}`,prompt:null};if(s.configured)return{note:`${s.id} already has a key${s.masked?` (${s.masked})`:""} — pasting a new one replaces it.`,prompt:`new ${s.label||s.id} key: `,provider:s.id};const i=[`${s.label||s.id}`],a=(s.models||[]).map((e=>"string"==typeof e?e:e&&e.id)).filter(Boolean);return a.length&&i.push(`unlocks ${a.join(", ")}`),s.key_prefix&&i.push(`key starts with ${s.key_prefix}`),s.key_url&&i.push(`create one at ${s.key_url}`),{note:i.join(" · "),prompt:`${s.id} key: `,provider:s.id}}},{name:"byok-rm",args:["provider"],hint:"<provider>",category:"auth",desc:"Remove a stored provider key",tool:"aegis_byok_set",build:e=>({provider:String(e||"").trim()})},{name:"class",args:["class","mode"],hint:"[aegis|byok|local|pro [on|off]]",category:"model",desc:'Show or switch which class turns run on; pro (your Claude subscription) needs a one-time "on"',handler:async(e,t)=>{const r=t||{},n=e.ctx&&e.ctx.modelClass||"aegis",o=t=>e.classLabel?e.classLabel(t):t,s=String(r.class||"").trim().toLowerCase();if("pro"===s&&r.mode){const t=String(r.mode).trim().toLowerCase();if("on"!==t&&"off"!==t)return e.push({role:"error",text:`usage: /class pro [on|off] — got "${r.mode}"`}),!0;const s="on"===t;if(e.saveConfig({proEnabled:s}),e.push({role:s?"done":"note",text:s?"pro class enabled — /class pro switches to your Claude Code subscription. It runs only if that subscription has Claude Code access.":"pro class disabled — it is no longer offered by /class or the model picker."}),!s&&"pro"===n){const t=e.switchClass("aegis");t.ok&&e.push({role:"note",text:`class: ${t.class} — ${o(t.class)}`})}return!0}if(!s){const t=await Promise.resolve(e.classes?e.classes():[]).catch((()=>[])),r=t.length?t:[{class:"aegis"},{class:"byok"}],o=r.findIndex((e=>e.class===n));return e.openOverlay({type:"class",items:r,sel:o<0?0:o,current:n}),!0}const i=e.switchClass(s);if(!i.ok)return e.push({role:"error",text:i.error}),!0;if(e.push({role:"done",text:`class: ${i.class} — ${o(i.class)}`}),i.cleared&&e.push({role:"note",text:`cleared the pin "${i.cleared}" — it does not belong to this class. /models lists what fits.`}),!("byok"!==i.class||e.ctx&&e.ctx.model)){const t=(await e.listModelsFor("byok")||[]).filter((e=>!e.cls||"byok"===e.cls)),r=t.find((e=>e.configured))||t[0];r?(e.ctx.model=r.id,e.saveConfig({model:r.id,currentModelId:r.id}),e.push({role:"note",text:r.configured?`using ${r.id} — /models lists the rest.`:`using ${r.id}, but no ${r.provider} key is saved yet — /byok-key ${r.provider}.`})):0===t.length&&e.push({role:"note",text:"nothing to relay yet — save a provider key with /byok-key <provider>, then /models."})}return!0}},{name:"models",aliases:["model-list"],hint:"",category:"model",desc:"Pick a model to pin, for the class you are on — opens the same picker as /model",handler:async e=>{const t=e.ctx&&e.ctx.modelClass||"aegis",r=await e.listModelsFor(t)||[];if(!r.length)return ze(e,"byok"===t?"nothing to relay yet — save a provider key with /byok-key <provider>":"no models advertised — check the account with /status, then retry"),e.render(),!0;const n=e.ctx&&e.ctx.model,o=r.map((e=>e.cls&&e.cls!==t?{...e,note:`${e.note||e.label||""} · pooled lane — /class ${e.cls}`}:e)),s=o.findIndex((e=>e.id===n));return e.openOverlay({type:"model",items:o,sel:s<0?0:s,current:n,cls:t}),!0}},{name:"byok-list",aliases:["byok-pick"],hint:"",category:"auth",desc:"Pick a provider to set a key for, then its models appear in /model",handler:async e=>{const t=await gt(e.client);if(!t||!t.length)return e.push({role:"error",text:"Could not read the provider catalog (offline, or no AEGIS key) — /byok lists what is known."}),!0;if("function"!=typeof e.openOverlay)return e.push({role:"note",text:"/byok-key <provider> — /byok lists the providers."}),!0;const r=(t.find((e=>e.configured))||{}).id||null,n=Math.max(0,t.findIndex((e=>e.configured)));return e.openOverlay({type:"provider",command:"byok-key",items:t,sel:n,current:r,hint:"↑↓ or tab move · enter picks · the key is stored on this machine"}),!0}},{name:"byok-key",args:["provider"],hint:"<provider> [key]",category:"auth",desc:"Save YOUR provider key on THIS MACHINE — the key the byok class sends",handler:async(e,t)=>{const n=t||{},o=String(n.provider||"").trim().toLowerCase();if(!o){const t=await gt(e.client);if(!t||!t.length)return e.push({role:"error",text:"Usage: /byok-key <provider> — /byok lists the providers."}),!0;if("function"!=typeof e.openOverlay)return e.push({role:"error",text:"Usage: /byok-key <provider> — /byok lists the providers."}),!0;const r=(t.find((e=>e.configured))||{}).id||null,n=Math.max(0,t.findIndex((e=>e.configured)));return e.openOverlay({type:"provider",command:"byok-key",items:t,sel:n,current:r,hint:"↑↓ or tab move · enter picks · the key is stored on this machine"}),!0}const s=e.settings&&e.settings();if(!s||"function"!=typeof s.set)return e.push({role:"error",text:"this client has no provider-key store."}),!0;const i=await gt(e.client),a=i?yt(i,o):null;if(a&&a.ambiguous)return e.push({role:"error",text:`"${o}" matches ${a.ambiguous.join(", ")} — retype the exact id.`}),!0;if(i&&!a?.provider){const t=i.map((e=>e.id)).join(", ");return e.push({role:"error",text:`unknown provider "${o}". Known ids: ${t} — nothing was saved.`}),!0}const d=a&&a.provider,l=d&&d.id||o,c=String(n._rest||"").trim(),u=c.indexOf(" ");let h=-1===u?"":c.slice(u+1).trim();if(h||(d&&d.key_url&&e.push({role:"note",text:`create a ${d.label||l} key at ${d.key_url}`}),h=String(await e.readSecret(`${l} key: `)||"").trim()),!h)return e.push({role:"note",text:"nothing saved."}),!0;if(d&&d.key_prefix&&!h.startsWith(d.key_prefix)&&e.push({role:"note",text:`heads up: ${l} keys normally start with "${d.key_prefix}" — saved anyway.`}),"custom"===l&&!mt(e,l))return e.push({role:"error",text:`the "custom" provider needs an endpoint as well as a key — a key alone dials nothing. Use: /model-add custom <https-base-url> ${h} <model-id> (saves endpoint, key and model together) — nothing was saved.`}),!0;s.set(e.byokNamespace(l),{key:h});let p="";try{const{envVarFor:t,setEnvValue:n}=require($e(r.join("client","env-file.js"))),o=t(l);if(o){const t=n(o,h);t.ok?p=o:e.push({role:"note",text:`heads up: could not write ${o} to ~/.aegiscode/.env (${t.error}).`})}}catch{}let m=[];if("function"==typeof e.refreshByokModels)try{m=await e.refreshByokModels()||[]}catch{m=[]}if(!m.length&&"function"==typeof e.listModelsFor)try{m=(await e.listModelsFor("byok")||[]).filter((e=>!e.cls||"byok"===e.cls))}catch{m=[]}const g=m.filter((e=>e&&(e.provider===l||String(e.id||"").startsWith(`${l}:`))));let y="byok"===(e.ctx&&e.ctx.modelClass||"");if(!y&&"function"==typeof e.switchClass){const t=e.switchClass("byok");t&&t.ok&&(y=!0,e.push({role:"note",text:`class: byok — ${e.classLabel?e.classLabel("byok"):"your own key"}`}))}const f=g.length?String(g[0].id):"";return f&&e.ctx&&(e.ctx.model=f,e.saveConfig({model:f,currentModelId:f,...y?{modelClass:"byok"}:{}})),e.push({role:"done",text:f?`saved a ${l} key on this machine${p?` (${p} in ~/.aegiscode/.env, so it is there next time)`:""} — model ${f} pinned, /model lists the rest.`:`saved a ${l} key on this machine${p?` (${p} in ~/.aegiscode/.env, so it is there next time)`:""} — /models lists its models, /class byok runs on it.`}),!0}},{name:"byok-rm-key",args:["provider"],hint:"<provider>",category:"auth",desc:"Forget the provider key saved on this machine",handler:async(e,t)=>{const r=String((t||{}).provider||"").trim().toLowerCase();if(!r)return e.push({role:"error",text:"Usage: /byok-rm-key <provider> — /byok lists the providers."}),!0;const n=e.settings&&e.settings();if(!n||"function"!=typeof n.remove)return e.push({role:"error",text:"this client has no provider-key store."}),!0;const o=e.byokNamespace(r),s="function"==typeof n.rawKey?n.rawKey(o):null;return n.remove(o),e.push({role:s?"done":"note",text:s?`removed the ${r} key from this machine.`:`no ${r} key was saved on this machine.`}),!0}},{name:"model-add",aliases:["add-model"],args:["provider"],hint:"<provider> [api-key] [model-id|*] (custom: <base-url> <api-key> [model-id|*])",category:"model",desc:"Save a provider key and offer a model id in one step (asks the vendor when it can)",handler:async(e,t)=>{const n=t||{},o=String(n.provider||"").trim();if(!o)return e.push({role:"error",text:"Usage: /model-add <provider> [api-key] <model-id> — /byok lists the providers. A vendor this catalog does not name yet: /model-add custom <https-base-url> <api-key> <model-id>. Example: /model-add deepseek sk-xxxxxxxx deepseek-v4.3-preview"}),!0;const s=function(e){const t=[];let r="",n=null,o=!1;for(const s of String(null==e?"":e))n?s===n?n=null:r+=s:'"'!==s&&"'"!==s?/\s/.test(s)?(r||o)&&(t.push(r),r="",o=!1):(r+=s,o=!0):(n=s,o=!0);return(r||o)&&t.push(r),t}(String(n._rest||"").trim());let i=s.length&&s[0].toLowerCase()===o.toLowerCase()?s.slice(1):s;const a=await gt(e.client),d=a?yt(a,o):null;if(d&&d.ambiguous)return e.push({role:"error",text:`"${o}" matches ${d.ambiguous.join(", ")} — retype the exact id.`}),!0;if(a&&(!d||!d.provider))return e.push({role:"error",text:`no provider "${o}" in the relay's catalog — /byok lists the ones it takes a key for.`}),!0;const l=d&&d.provider&&d.provider.id||o.toLowerCase();let c="",u="";if("custom"===l){if(1===i.length&&!mt(e,l))return e.push({role:"error",text:"one word cannot say whether it is the URL or the model id — nothing was saved. Type the endpoint first: /model-add custom <https-base-url> <api-key> [model-id]"}),!0;i.length>=2&&(c=i.shift(),u=i.shift())}else i.length>=2&&(u=i.shift());let h=i.join(" ").trim();if(u){const t=e.settings&&e.settings();if(!t||"function"!=typeof t.set)return e.push({role:"error",text:"this client has no provider-key store."}),!0;const n=d&&d.provider;n&&n.key_prefix&&!u.startsWith(n.key_prefix)&&e.push({role:"note",text:`heads up: ${l} keys normally start with "${n.key_prefix}" — saved anyway.`}),c&&!/^https:\/\//i.test(c)&&e.push({role:"note",text:"heads up: aegis1 only dials an https:// base_url — saved anyway, but calls on it will be refused."}),t.set(e.byokNamespace(l),{key:u,...c?{baseURL:c}:{}});try{const{envVarFor:t,setEnvValue:n}=require($e(r.join("client","env-file.js"))),o=t(l);if(o){const t=n(o,u);t.ok||e.push({role:"note",text:`heads up: could not mirror the key into ~/.aegiscode/.env (${t.error}).`})}}catch{}e.push({role:"done",text:c?`saved a ${l} key and base URL (${c}) on this machine.`:`saved a ${l} key on this machine.`})}const p=ht(e,l),m=await async function(e,t,r){const n=await pt(e,t,r);return n&&n.ok&&Array.isArray(n.ids)&&n.ids.length?n.ids:void 0}(e,l,p);if("*"===h){if(!m){const t=await pt(e,l,p);return e.push({role:"error",text:`cannot list ${l}: ${t&&t.error||"no list available"} — type the ids instead: /model-add ${l} <model-id>`}),!0}const t=function(e,t){let r=0,n=0;const o=[],s=[];for(const i of t)try{st(e,i).added?r+=1:o.push(i)}catch(e){const a=e&&e.message||String(e);if(/the cap/.test(a)){n=t.length-r-o.length-s.length;break}s.push({id:i,reason:a})}return{added:r,already:o,failed:s,capped:n}}(l,m);if("function"==typeof e.refreshByokModels)try{await e.refreshByokModels()}catch{}return e.push({role:"done",text:`added ${t.added} of the ${m.length} model ids ${l} serves${t.already.length?` (${t.already.length} were already declared)`:""}.`}),t.capped&&e.push({role:"note",text:`stopped at the store's per-provider cap (32) — ${t.capped} more id(s) were left out; /model-add ${l} <model-id> stores a specific one, /model-rm frees a slot.`}),t.failed.length&&e.push({role:"note",text:`${t.failed.length} id(s) were refused: ${t.failed.map((e=>e.id)).join(", ")}`}),e.push({role:"note",text:`stored in ${dt()} — the desktop reads the same file. /model-discover ${l} lists what the vendor serves.`}),!0}if(!h){m&&e.push({role:"note",text:`${l} serves ${m.length} model ids — ${m.slice(0,12).join(", ")}${m.length>12?", …":""}`});const t=String(await e.askInput(m?`model id for ${l} (1-${m.length}, or type one): `:`model id for ${l}: `)||"").trim(),r=m&&/^\d+$/.test(t)?Number(t):0;h=m&&r>=1&&r<=m.length?m[r-1]:t}if(!h)return e.push({role:"note",text:"nothing saved."}),!0;let g;try{g=st(l,h)}catch(t){return e.push({role:"error",text:t&&t.message||String(t)}),!0}if("function"==typeof e.refreshByokModels)try{await e.refreshByokModels()}catch{}const y=(("function"==typeof e.listModelsFor?await e.listModelsFor("byok"):[])||[]).find((e=>e&&e.id===`${l}:${h}`));return e.push({role:g.added?"done":"note",text:g.added?`added ${l}:${h} — offered on this machine now, in the CLI and the desktop.`:`${l}:${h} was already declared.`}),a||e.push({role:"note",text:`the relay's catalog could not be read, so "${l}" is unverified — if it does not appear in /models, /byok lists the provider ids it takes.`}),g.added&&!y&&e.push({role:"note",text:`saved, but no row will be offered for "${l}" yet — the relay lists no provider of that id (or that provider lists no models).`}),g.added&&m&&e.push({role:"note",text:`${l} currently serves ${m.length} model ids — /model-discover ${l} lists them, /model-add ${l} '*' takes them all.`}),e.push({role:"note",text:`stored in ${g.file} — the desktop reads the same file.`}),!0}},{name:"model-discover",aliases:["discover-models","vendor-models"],args:["provider"],hint:"<provider>",category:"model",desc:"List the model ids your provider's own API serves",handler:async(e,t)=>{const r=String((t||{}).provider||"").trim();if(!r)return e.push({role:"error",text:`Usage: /model-discover <provider> — this client can ask: ${ut().join(", ")}`}),!0;const n=await gt(e.client),o=n?yt(n,r):null,s=(o&&o.provider&&o.provider.id||r).toLowerCase(),i=ct(s);if(!i)return e.push({role:"error",text:`no list endpoint for "${s}" in this client — /model-add ${s} <model-id> stores an id you already know. Providers it can ask: ${ut().join(", ")}`}),!0;const a=ht(e,s);if(!a)return e.push({role:"error",text:`no ${s} key on this machine — /byok-key ${s} saves one (or put it in ~/.aegiscode/.env), then this lists what the key reaches.`}),!0;const d=await pt(e,s,a);if(!d||!d.ok)return e.push({role:"error",text:`could not list ${s}: ${d&&d.error||"no answer"}`}),!0;const l=new Set(at(s)),c=new Set((o&&o.provider&&o.provider.models||[]).map((e=>String(e))));e.push({role:"note",text:`${s} at ${i.url}${i.note?` (${i.note})`:""}`}),e.push({role:"note",text:`${d.count} chat model id(s) the vendor serves — mark: [seen] the relay already lists it, [your] you declared it, [new] this machine does not offer it yet.`});const u=d.ids.map(((e,t)=>{const r=l.has(e)?"[your]":c.has(e)?"[seen]":"[new]";return`${String(t+1).padStart(3)}. ${r} ${e}`}));u.length&&e.push({role:"panel",lines:u}),u.length||e.push({role:"note",text:`the vendor answered with no chat models — /model-add ${s} <model-id> stores one by hand.`}),d.others.length&&e.push({role:"note",text:`${d.others.length} id(s) are not chat models (embeddings, audio, moderation or an unsupported method) and are left out: ${d.others.slice(0,8).join(", ")}${d.others.length>8?", …":""}`});const h=d.ids.filter((e=>!l.has(e)&&!c.has(e)));return h.length&&e.push({role:"note",text:`${h.length} of them are not offered on this machine yet — /model-add ${s} '<model-id>' stores one, /model-add ${s} '*' stores every chat model the vendor serves.`}),!0}},{name:"model-rm",aliases:["rm-model"],args:["provider"],hint:"<provider> <model-id>",category:"model",desc:"Forget a model id you added with /model-add",handler:async(e,t)=>{const r=t||{},n=String(r.provider||"").trim(),o=String(r._rest||"").trim(),s=o.indexOf(" "),i=-1===s?"":o.slice(s+1).trim();if(!n||!i)return e.push({role:"error",text:"Usage: /model-rm <provider> <model-id> — /model-add lists what you added."}),!0;let a;try{a=it(n,i)}catch(t){return e.push({role:"error",text:t&&t.message||String(t)}),!0}if("function"==typeof e.refreshByokModels)try{await e.refreshByokModels()}catch{}return e.push({role:a.removed?"done":"note",text:a.removed?`removed ${a.provider}:${a.model} — the picker stops offering it on the next refresh.`:`${a.provider}:${a.model} was not declared on this machine.`}),!0}},{name:"tool",args:["name","json"],hint:"<name> [json]",category:"aegis",desc:"Call any registry tool directly (escape hatch for new tools)",generic:!0,build:e=>{const t=String(e||""),r=t.indexOf(" "),n=(-1===r?t:t.slice(0,r)).trim(),o=-1===r?"":t.slice(r+1).trim();let s={};if(o)try{s=JSON.parse(o)}catch(e){throw new Error(`/tool: arguments must be JSON — ${e.message}`)}return{tool:n,args:s}}},{name:"aegis-import",aliases:["import"],hint:"[--confirm]",category:"aegis",desc:"Import memory from other AI tools on this machine (dry run unless --confirm)",tool:"aegis_memory_import",build:e=>({confirm:/--confirm\b/.test(String(e||""))})}],jt=new Map;for(const e of It)for(const t of[e.name,...e.aliases||[]]){if(jt.has(t))throw new Error(`aegiscode: command name or alias /${t} is registered twice`);jt.set(t,e)}function At(){return It.map((e=>({...e,categoryLabel:He(e.category)})))}function Lt(){return At().filter((e=>!("function"==typeof e.hidden?e.hidden():e.hidden)))}function Mt(e){return jt.get(String(e||"").toLowerCase())||null}module.exports={CATEGORIES:Ke,categoryLabel:He,EFFORT_LEVELS:Ve,COMMANDS:It,allCommands:At,visibleCommands:Lt,findCommand:Mt,canonicalName:function(e){const t=Mt(e);return t?t.name:e},parseLine:function(e){const t=String(null==e?"":e).trim();if(!t)return{kind:"empty"};if("/"!==t[0])return{kind:"prompt",text:t};const r=t.indexOf(" "),n=(-1===r?t.slice(1):t.slice(1,r)).trim(),o=-1===r?"":t.slice(r+1).trim(),s=Mt(n);return s?s.unavailable?{kind:"unavailable",command:s,arg:o}:{kind:"command",command:s,arg:o}:{kind:"unknown",name:n,text:t}},toolBackedCommands:function(){return It.filter((e=>e.tool))}};