aegiscode 6.7.2 → 6.7.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "6.7.2",
4
+ "version": "6.7.4",
5
5
  "description": "aegiscode — the command-line version of AEGIS Desktop. The shared tool surface in your shell, over the same thin transport and tool registry as the MCP plugin and the desktop app. Ships transport + UI only; no brain.",
6
6
  "author": {
7
7
  "name": "AEGIS Code",
package/src/app.js CHANGED
@@ -1154,7 +1154,14 @@ function createApp(options = {}) {
1154
1154
  try {
1155
1155
  let args = cmd.build(arg);
1156
1156
  if (cmd.secret) {
1157
- const key = await askSecret(`provider key for ${args.provider}: `);
1157
+ // A bare "provider key for openai:" tells the user nothing about which
1158
+ // key to paste or where to get it, which is exactly the step people get
1159
+ // wrong. When a command can describe its own secret it does, and the
1160
+ // description is best-effort: a catalog fetch that fails must still
1161
+ // leave a working prompt rather than aborting the command.
1162
+ const spec = await describeSecret(cmd, args);
1163
+ if (spec && spec.note) emit(render.renderNotice(ctx(), 'info', spec.note));
1164
+ const key = await askSecret((spec && spec.prompt) || `provider key for ${args.provider}: `);
1158
1165
  if (!key) {
1159
1166
  emit(render.renderNotice(ctx(), 'warn', 'empty key — nothing sent'));
1160
1167
  return true;
@@ -1204,6 +1211,25 @@ function createApp(options = {}) {
1204
1211
  emit(render.renderNotice(ctx(), 'info', `cloud memory: ${used} of ${limit} synced tokens — /cloud memory for the full state`));
1205
1212
  }
1206
1213
 
1214
+ /**
1215
+ * Ask the command how to describe the secret it is about to collect.
1216
+ *
1217
+ * Returns `{ note, prompt }` or null. The command opts in by defining
1218
+ * `secretDescribe(args, client)`, which is awaited and therefore free to
1219
+ * consult the server. A throw here is swallowed on purpose: guidance is an
1220
+ * improvement to a prompt, and a user who typed `/byok-set openai` on a
1221
+ * flaky connection should still get the prompt.
1222
+ */
1223
+ async function describeSecret(cmd, args) {
1224
+ if (typeof cmd.secretDescribe !== 'function') return null;
1225
+ try {
1226
+ const spec = await cmd.secretDescribe(args, client);
1227
+ return spec && typeof spec === 'object' ? spec : null;
1228
+ } catch {
1229
+ return null;
1230
+ }
1231
+ }
1232
+
1207
1233
  /**
1208
1234
  * Ask for a secret on this session's streams.
1209
1235
  *
package/src/art.js CHANGED
@@ -18,98 +18,75 @@ function capsOf(target) {
18
18
  }
19
19
 
20
20
  /**
21
- * Welcome art — the aegiscodex-dev mark, adopted wholesale.
21
+ * Welcome art — the ÆGIS wordmark, adopted verbatim from `aegiscodex-`.
22
22
  *
23
- * The composition is copied from `aegiscodex-dev/src/art.js`, which took the
24
- * glyph rows from the shipped Claude Code binary: a feather plume (░), a top hat
25
- * (█ ▓ ▒), the spark face (▐▛███▜▌ / ▝▜█████▛▘ / ▘▘ ▝▝), plus a crescent moon and
26
- * a diving whale for the second brain. Side-by-side when the terminal is wide
27
- * enough, stacked when it isn't.
23
+ * This is the mark the rest of the family already draws: the wordmark block in
24
+ * `aegiscodex-/src/ui/components/layout/WelcomeMessage.tsx`, which is kept in
25
+ * sync with `aegiscodex-/assets/demo.svg`, the canonical rendering. The CLI now
26
+ * shows the same welcome screen as the desktop host instead of its own art.
28
27
  *
29
- * Every row of a block is the same display width, so `center()` and
30
- * `joinSideBySide()` stay exact. `test/cli-conformance.test.mjs` asserts both
31
- * that property and that these rows still match aegiscodex-dev's source, so the
32
- * mark can't drift.
28
+ * It REPLACES the earlier Claude-binary composition (feather plume, top hat,
29
+ * ▐▛███▜▌ face, crescent moon, diving whale). That mark was three blocks joined
30
+ * side by side, which is why this file carried a stacking path, a `✦` star pass
31
+ * and a two-ink split; a single 13-cell block needs none of them, so the banner
32
+ * draws it in one ink — gold — exactly as `theme.colors.primary` inks it in the
33
+ * desktop, and the wide/narrow branch in both consumers now always takes the
34
+ * wide path.
33
35
  *
34
- * Which pass is applied is decided by the terminal's capabilities, not by
35
- * `process.platform` — see the portability section below and `caps.js`.
36
+ * Every row is the same display width with no trailing blank, so `center()` and
37
+ * `padCells()` stay exact. `test/cli-conformance.test.mjs` pins these rows to
38
+ * the literals they were lifted from, so the mark cannot drift from aegiscodex-.
39
+ *
40
+ * Which stencil pass is applied is decided by the terminal's capabilities, not
41
+ * by `process.platform` — see the portability section below and `caps.js`.
36
42
  */
37
43
 
38
- // The mascot face — exact glyphs from the binary (msS template).
39
- const FACE = [' ▐▛███▜▌', '▝▜█████▛▘', ' ▘▘ ▝▝'];
40
-
41
- // Top hat + feather plume, composed from the extracted row glyphs.
42
- const HAT = [
43
- ' ✦ ░░░░░░░░░░ ✦',
44
- ' ░░░░░░░░░░░░░░░░',
45
- ' █████▓▓░',
46
- ' ███▓░',
47
- ' ███▓░',
48
- ' ███▓░',
49
- ' ░▓▓███▓▓░',
50
- ' ▒▒░░▒▒ ▒ ▒▒',
51
- ];
52
-
53
- // Plume + hat + face: the left half of the welcome mark.
54
- const MASCOT_ART = [
55
- ' ✦ █████▓▓░',
56
- ' ✦ ███▓░ ░░',
57
- ' ░░░░ ███▓░',
58
- ' ░░░░░░░░ ███▓░',
59
- ' ░░░░░░░░░░░░ ███▓░',
60
- ' ██▓░░ ▓',
61
- ' ░▓▓███▓▓░',
62
- ...FACE,
63
- ];
64
-
65
- // Crescent moon in a starry night sky — lit rim (▓) with a faint earthshine
66
- // body (░). Rows are equal code-point length (13).
67
- const MOON = [
68
- ' ✦ ▓▓▓ ✦ ',
69
- ' ▓▓▓▓▓ ✦',
70
- ' ▓▓▓▓▓▓▓▓▓ ✦',
71
- ' ▓▓▓▓▓▓▓░░░ ',
72
- ' ▓▓▓▓░░░░░░ ',
73
- ' ░░░░░░ ',
74
- ' ✦ · · ',
75
- ];
76
-
77
- // The diving whale: spout (░), eye (██) on the rounded head, body (▒) sweeping
78
- // right to a small forked fluke (▓), water line (░) beneath. Rows are equal
79
- // code-point length (18).
80
- const WHALE = [
81
- ' ✦ ░ ░ ░ ',
82
- ' ✦ ░░░░░ ',
83
- ' ▒▒▒▒▒▒▒▒▒▒▒▒ ',
84
- ' ▒▒▒▒▒▒▒▒▒▒▒▒▒ ',
85
- ' ██▒▒▒▒▒▒▒▒▒▒▒▒▓▓',
86
- ' ██▒▒▒▒▒▒▒▒▒▒▒▒▓ ',
87
- ' ▒▒▒▒▒▒▒▒▒▒▒▒▒▒ ',
88
- ' ░░░░░░░░░░░░ ',
44
+ // The ÆGIS wordmark: 3 rows × 13 cells, uniform. Row 1 is the cap line, row 2
45
+ // carries the Æ crossbar (╦) and the G/S shoulders, row 3 the baseline.
46
+ //
47
+ // Deliberately not named after the old spaced `'A E G I S'` string: that
48
+ // export was removed and `cli-conformance.test.mjs` fails the build if its name
49
+ // reappears in this file's exports. The guard is about that string, not this
50
+ // block, so the block takes a name of its own rather than the guard being
51
+ // loosened to accommodate it.
52
+ const WELCOME_MARK = [
53
+ '╔═╗╔═╗╔═╗╦╔═╗',
54
+ '╠═╣║╣ ║ ╦║╚═╗',
55
+ '╩ ╩╚═╝╚═╝╩╚═╝',
89
56
  ];
90
57
 
91
- // Moon above the whale — the right half of the mark, 2-col gutter. The moon is
92
- // padded with a trailing blank row so joinSideBySide keeps both blocks aligned.
93
- const MOON_WHALE = joinSideBySide([...MOON, ''], WHALE, 2);
58
+ /** The welcome mark: the wordmark, with nothing drawn beside it. */
59
+ const WELCOME_ART = WELCOME_MARK;
94
60
 
95
- /** Full welcome mark: mascot + (moon + whale) side by side, bottom-aligned. */
96
- const WELCOME_ART = joinSideBySide(MASCOT_ART, MOON_WHALE, 2);
97
-
98
- /** Narrow-terminal fallback: mascot stacked above (moon + whale). */
99
- const WELCOME_ART_STACKED = stackVertical(MASCOT_ART, MOON_WHALE, 1);
61
+ /**
62
+ * There is no stacked variant any more: the mark is 13 cells, so it fits any
63
+ * terminal that can draw the banner's own frame. Kept as an alias rather than
64
+ * deleted because `welcomeArtFor()` and the capability matrix enumerate both
65
+ * names, and a second constant that happens to equal the first is cheaper than
66
+ * a branch in two consumers.
67
+ */
68
+ const WELCOME_ART_STACKED = WELCOME_MARK;
100
69
 
101
70
  /** Welcome copy, in aegiscode-dev's frame: coral title over the mark. */
102
71
  const WELCOME_TITLE = 'Welcome to AEGIS Code';
103
72
  const WELCOME_BACK = 'Welcome back!';
104
- const TAGLINE = 'Cloud brain in your shell.';
73
+ // One owner for the tagline: `render.js` joins it into the banner's version
74
+ // line and `screens.js` centres it on the welcome screen. It used to be written
75
+ // out twice — once here, once inline in `screens.js` — so a copy change landed
76
+ // in one place and left the other stale.
77
+ const TAGLINE = 'Your intent, AI automated.';
78
+ // For terminals too narrow for the full line. `centered()` clips rather than
79
+ // wraps, and a truncated tagline reads as a rendering fault, so this is a real
80
+ // fallback and not a stylistic variant.
81
+ const TAGLINE_SHORT = 'Your intent, automated.';
105
82
 
106
83
  // ── Terminal portability ─────────────────────────────────────────────────────
107
- // The block-glyph palette and ✦ stars are single-width on most terminals, but
108
- // not everywhere: a legacy Windows console font lacks the U+259B..U+259F face
109
- // edges and mangles █▓▒░ entirely; Terminal.app has no quartile edges and
110
- // renders ✦ through the two-cell emoji fallback. Each pass swaps offending code
111
- // points 1:1 (same character count per row) so the width maths stays exact and
112
- // the mark keeps its shape.
84
+ // The wordmark is drawn with U+2550 box-drawing runes. Those are single-width on
85
+ // most terminals, but not everywhere: a legacy Windows console font has no
86
+ // box-drawing block at all, Terminal.app's fallback font renders the quarters
87
+ // (▐▛▜▌▝▘) wrong and ✦ through the two-cell emoji fallback. Each pass swaps
88
+ // offending code points 1:1 (same character count per row) so the width maths
89
+ // stays exact and the mark keeps its shape.
113
90
  //
114
91
  // The pass is keyed on the terminal's CAPABILITIES (`caps.js`), never on
115
92
  // `process.platform`. That distinction is the whole point: PowerShell inside
@@ -127,11 +104,31 @@ const TAGLINE = 'Cloud brain in your shell.';
127
104
  // untinted on Windows. `test/cli-terminal-caps.test.mjs` pins all of it.
128
105
  const STAR = '✦';
129
106
 
130
- /** The quartile/quadrant face edges — the runes Apple and older Windows fonts lack. */
107
+ /** The quartile/quadrant face edges. The wordmark no longer draws them, but the
108
+ * `face` capability still resolves through this list, so the pass stays. */
131
109
  const EDGE_RUNES = ['▐', '▛', '▜', '▌', '▝', '▘'];
132
110
 
133
- /** Full ASCII pass: the block palette, the face edges, the star, the mid-dot. */
111
+ /**
112
+ * The box-drawing runes the wordmark is made of. A legacy console has none of
113
+ * them, and without a mapping the mark would be drawn in a font that has no
114
+ * glyphs for it — boxes of tofu where the product name should be.
115
+ *
116
+ * Every corner, tee and cross becomes `+` (the classic ASCII box) and the two
117
+ * straight strokes keep their meaning as `-` and `|`, so the stencilled mark is
118
+ * still legible as ÆGIS rather than as a row of plusses. Ten runes, ten 1:1
119
+ * swaps: the mark stays 13 cells wide and 3 rows tall on every terminal.
120
+ */
121
+ const BOX_RUNES = ['╔', '╗', '╚', '╝', '╠', '╣', '╦', '╩', '║', '═'];
122
+ const BOX_STENCIL = new Map([
123
+ ...['╔', '╗', '╚', '╝', '╠', '╣', '╦', '╩'].map((c) => [c, '+']),
124
+ ['═', '-'],
125
+ ['║', '|'],
126
+ ]);
127
+
128
+ /** Full ASCII pass: the wordmark's box runes, the block palette, the face
129
+ * edges, the star, the mid-dot. */
134
130
  const ASCII_STENCIL = new Map([
131
+ ...BOX_STENCIL,
135
132
  ['█', '#'],
136
133
  ['▓', '@'],
137
134
  ['▒', '='],
@@ -212,86 +209,35 @@ function portability(rows) {
212
209
  return portabilityFor(rows, null);
213
210
  }
214
211
 
215
- /** The mark that fits the current terminal: side-by-side when there's room. */
216
- function welcomeArtFor(cols) {
217
- const wide = portability(WELCOME_ART);
218
- const stacked = portability(WELCOME_ART_STACKED);
219
- const W = Math.max(...wide.map(cells));
220
- return cols >= W + 4 ? wide : stacked;
212
+ /** The welcome mark, as this terminal will render it. */
213
+ function welcomeArtFor() {
214
+ return portability(WELCOME_ART);
221
215
  }
222
216
 
223
217
  /**
224
- * Split the mark into its two halves so each can carry its own theme ink.
218
+ * The mark, ready for the banner: one row per output row, each as a
219
+ * `[left, right]` pair so the two consumers' ink split keeps working.
220
+ *
221
+ * The right half is always empty now. The pair shape is kept because
222
+ * `render.js`'s `artRow()` is built around it — `left` is painted gold, `right`
223
+ * per-shade — and collapsing it would mean a second, cosmetic signature for the
224
+ * same data. A future two-tone mark drops straight back into the right slot.
225
225
  *
226
- * Rows are padded to a whole-cell width with `padCells()`, not `padEnd()`: a
227
- * terminal that draws a rune two cells wide (`AEGIS_WIDE_RUNES=✦`, or a font
228
- * that falls back to an emoji glyph) would otherwise be padded by *code point*
229
- * and every row after it would drift one cell to the right of the one above.
226
+ * The width argument the consumers used to pass is gone with the wide/narrow
227
+ * split: 13 cells fits everywhere the banner itself fits, so there is nothing
228
+ * left for the terminal's column count to decide.
230
229
  *
231
230
  * @returns {{rows: Array<[string,string]>, width: number, gutter: number}}
232
231
  */
233
- function welcomeArtParts(cols) {
234
- const mascot = portability(MASCOT_ART);
235
- const moonWhale = portability(MOON_WHALE);
236
- const L = Math.max(...mascot.map(cells));
237
- const R = Math.max(...moonWhale.map(cells));
238
- const wide = cols >= L + R + 2 + 4;
239
- const gutter = wide ? 2 : 1;
240
- if (wide) {
241
- // The right half carries the moon *and* the whale. Using WHALE alone here —
242
- // which the reference does, because it only wants the per-mascot ink split —
243
- // would silently drop the crescent from the welcome screen this CLI renders.
244
- const n = Math.max(mascot.length, moonWhale.length);
245
- const rows = [];
246
- for (let i = 0; i < n; i++) {
247
- // Same bottom-align rule as joinSideBySide — subtract the offset.
248
- const li = i - (n - mascot.length);
249
- const ri = i - (n - moonWhale.length);
250
- rows.push([padCells(mascot[li] ?? '', L), padCells(moonWhale[ri] ?? '', R)]);
251
- }
252
- return { rows, width: L + gutter + R, gutter };
253
- }
254
- const w = Math.max(L, R);
255
- const centerBlock = (rows) => rows.map((r) => ' '.repeat(Math.max(0, Math.floor((w - cells(r)) / 2))) + r);
232
+ function welcomeArtParts() {
233
+ const rows = portability(WELCOME_MARK);
256
234
  return {
257
- rows: [
258
- ...centerBlock(mascot).map((c) => [c, '']),
259
- ['', ''],
260
- ...centerBlock(moonWhale).map((r) => ['', r]),
261
- ],
262
- width: w,
263
- gutter,
235
+ rows: rows.map((r) => [r, '']),
236
+ width: Math.max(...rows.map(cells)),
237
+ gutter: 0,
264
238
  };
265
239
  }
266
240
 
267
- /** Stack two art blocks vertically, each centred, separated by `gap` rows. */
268
- function stackVertical(top, bottom, gap = 1) {
269
- const w = Math.max(...[...top, ...bottom].map(cells));
270
- const centerBlock = (rows) =>
271
- rows.map((r) => ' '.repeat(Math.max(0, Math.floor((w - cells(r)) / 2))) + r);
272
- return [...centerBlock(top), ...Array(gap).fill(''), ...centerBlock(bottom)];
273
- }
274
-
275
- /** Join two art stacks row-aligned (bottom-aligned by default). */
276
- function joinSideBySide(left, right, gutter = 2, align = 'bottom') {
277
- const L = Math.max(...left.map(cells));
278
- const R = Math.max(...right.map(cells));
279
- const n = Math.max(left.length, right.length);
280
- return Array.from({ length: n }, (_, i) => {
281
- // Bottom-align puts each block's LAST row on the output's last row, so a
282
- // shorter block starts lower and its index runs *behind* the output index.
283
- // Adding the offset instead of subtracting it pushed the shorter block off
284
- // the bottom edge and silently dropped its top rows: the moon+whale half,
285
- // two rows shorter than the mascot, lost its spout and its top star and
286
- // hung two rows below the baseline.
287
- const li = align === 'bottom' ? i - (n - left.length) : i;
288
- const ri = align === 'bottom' ? i - (n - right.length) : i;
289
- const l = padCells(left[li] ?? '', L);
290
- const r = padCells(right[ri] ?? '', R);
291
- return l + ' '.repeat(gutter) + r;
292
- });
293
- }
294
-
295
241
  /** Centre every row of an art block inside `width` (left pad + right fill). */
296
242
  function center(rows, width) {
297
243
  return rows.map((r) => {
@@ -310,19 +256,16 @@ function padBoth(rows, width) {
310
256
  }
311
257
 
312
258
  module.exports = {
313
- FACE,
314
- HAT,
315
- MASCOT_ART,
316
- MOON,
317
- WHALE,
318
- MOON_WHALE,
259
+ WELCOME_MARK,
319
260
  WELCOME_ART,
320
261
  WELCOME_ART_STACKED,
321
262
  WELCOME_TITLE,
322
263
  WELCOME_BACK,
323
264
  TAGLINE,
265
+ TAGLINE_SHORT,
324
266
  STAR,
325
267
  EDGE_RUNES,
268
+ BOX_RUNES,
326
269
  PASSES,
327
270
  STENCILS,
328
271
  stencilFor,
@@ -331,8 +274,6 @@ module.exports = {
331
274
  portabilityFor,
332
275
  welcomeArtFor,
333
276
  welcomeArtParts,
334
- stackVertical,
335
- joinSideBySide,
336
277
  center,
337
278
  padBoth,
338
279
  };
package/src/commands.js CHANGED
@@ -142,6 +142,75 @@ async function loadModels(c) {
142
142
  */
143
143
  const cloudReady = () => credentials.hasApiKey();
144
144
 
145
+ // ── BYOK provider catalog ────────────────────────────────────────────────────
146
+
147
+ /**
148
+ * The server's BYOK provider catalog, or null when it cannot be reached.
149
+ *
150
+ * The catalog is the *server's* answer to "which keys do you accept, for which
151
+ * models, and where do I get one". It is deliberately not key-gated, so this
152
+ * works before an account key exists — which is the whole point, since it is
153
+ * the screen that tells a user which key to go buy. Returning null rather than
154
+ * throwing keeps every caller free to fall back to the prose description it
155
+ * used before the catalog existed.
156
+ */
157
+ async function byokCatalog(client) {
158
+ if (!client || typeof client.byokProviders !== 'function') return null;
159
+ try {
160
+ const data = await client.byokProviders();
161
+ const providers = (data && data.providers) || [];
162
+ return providers.length ? providers : null;
163
+ } catch {
164
+ return null;
165
+ }
166
+ }
167
+
168
+ /**
169
+ * Resolve a typed provider id against the catalog.
170
+ *
171
+ * Exact id first, then a unique case-insensitive match on id, label or alias, so
172
+ * `/byok-set OpenAI` and `/byok-set together-ai` both land. A non-unique match
173
+ * returns `{ ambiguous }` rather than silently picking one: storing a key
174
+ * against the wrong provider is the failure this whole path exists to prevent,
175
+ * and it is not visible until a call 401s upstream.
176
+ */
177
+ function findByokProvider(providers, typed) {
178
+ const want = String(typed || '').trim().toLowerCase();
179
+ if (!providers) return { provider: null, exact: false };
180
+ const exact = providers.find((p) => p.id === want);
181
+ if (exact) return { provider: exact, exact: true };
182
+ const loose = providers.filter((p) => {
183
+ const names = [p.id, p.label, ...(p.aliases || [])].filter(Boolean);
184
+ return names.some((n) => String(n).toLowerCase() === want);
185
+ });
186
+ if (loose.length === 1) return { provider: loose[0], exact: false };
187
+ if (loose.length > 1) return { ambiguous: loose.map((p) => p.id) };
188
+ return { provider: null, exact: false };
189
+ }
190
+
191
+ /** One catalog row: id, whether it is already set, its models, and key guidance. */
192
+ function byokProviderLines(providers) {
193
+ const lines = [];
194
+ for (const p of providers) {
195
+ const state = p.configured
196
+ ? span(C.green, `set${p.masked ? ` (${p.masked})` : ''}`)
197
+ : span(C.gray, 'not set');
198
+ const label = p.label ? span(C.gray, ` — ${p.label}`) : '';
199
+ lines.push(` ${span(C.gold + BOLD, p.id)}${label} ${state}`);
200
+ // `models` arrives as bare ids. The catalog used to be read here as if each
201
+ // one were an object with `.id`, which silently rendered nothing — a
202
+ // provider listed with an empty model line reads as "no models", not as a
203
+ // bug, so tolerate both shapes rather than repeat the mistake.
204
+ const models = (p.models || [])
205
+ .map((m) => (typeof m === 'string' ? m : m && m.id))
206
+ .filter(Boolean);
207
+ if (models.length) lines.push(` ${span(C.gray, `models: ${models.join(', ')}`)}`);
208
+ if (p.key_prefix) lines.push(` ${span(C.gray, `key starts with ${p.key_prefix}`)}`);
209
+ if (p.key_url) lines.push(` ${span(C.gray, p.key_url)}`);
210
+ }
211
+ return lines;
212
+ }
213
+
145
214
  // ── account key + cloud sync handlers ────────────────────────────────────────
146
215
 
147
216
  /** The account-key panel body, shared by /key, /login and /cloud. */
@@ -1824,10 +1893,36 @@ const COMMANDS = [
1824
1893
 
1825
1894
  // ── cloud-only additions (not in the reference vocabulary) ────────────────
1826
1895
  {
1896
+ // A bare `provider -> info` map is the wrong shape for a picker: it can only
1897
+ // describe providers you have ALREADY set, and the question this command
1898
+ // answers is "which key should I go buy". A command is either handler- or
1899
+ // tool-backed, never both (`cli-commands.test.mjs` enforces exactly one), so
1900
+ // this is handler-backed and reaches for the tool by name only as the
1901
+ // fallback for a server that predates the catalog — the command still works,
1902
+ // just with the older, sparser answer.
1827
1903
  name: 'byok', hint: '', category: 'auth',
1828
- desc: 'Show which providers have your own key configured',
1829
- tool: 'aegis_byok_status',
1830
- build: () => ({}),
1904
+ desc: 'List every provider you can bring your own key for, and which are set',
1905
+ handler: async (c) => {
1906
+ const providers = await byokCatalog(c.client);
1907
+ if (!providers) {
1908
+ await c.runTool('aegis_byok_status', {});
1909
+ return true;
1910
+ }
1911
+ const set = providers.filter((p) => p.configured).length;
1912
+ const lines = [
1913
+ [span(C.gold + BOLD, 'Bring your own key'), span(BOLD_OFF, '')],
1914
+ [span(C.gray, '─'.repeat(34))],
1915
+ [
1916
+ span(set ? C.green : C.gray, ` ${set} of ${providers.length} providers set`),
1917
+ span(C.gray, ' — /byok-set <provider>'),
1918
+ ],
1919
+ '',
1920
+ ...byokProviderLines(providers),
1921
+ ];
1922
+ panel(c, lines);
1923
+ c.render();
1924
+ return true;
1925
+ },
1831
1926
  },
1832
1927
  {
1833
1928
  name: 'byok-set', args: ['provider'], hint: '<provider>', category: 'auth',
@@ -1835,6 +1930,54 @@ const COMMANDS = [
1835
1930
  tool: 'aegis_byok_set',
1836
1931
  secret: 'key',
1837
1932
  build: (arg) => ({ provider: String(arg || '').trim() }),
1933
+ /**
1934
+ * Say which key this is and where to get it, before the prompt.
1935
+ *
1936
+ * The old prompt was `provider key for openai:` — which assumes the reader
1937
+ * already knows that a provider id is a company, and leaves them nothing to
1938
+ * check a pasted key against. Here the catalog names the provider, lists the
1939
+ * models the key unlocks, links the place to create it, and states the
1940
+ * prefix a valid key begins with, so a key for the wrong vendor is visible
1941
+ * before it is stored rather than as an upstream 401 later.
1942
+ *
1943
+ * Resolved against aliases too, so the prompt agrees with the id that will
1944
+ * actually be sent (`/byok-set OpenAI` → `openai`, not `OpenAI`).
1945
+ */
1946
+ async secretDescribe(args, client) {
1947
+ const typed = String(args.provider || '').trim();
1948
+ const providers = await byokCatalog(client);
1949
+ if (!providers) {
1950
+ // No catalog: still refuse to prompt for an empty provider, and keep the
1951
+ // words "provider key" so the request is intelligible on its own.
1952
+ return typed ? null : { note: 'Usage: /byok-set <provider> — /byok lists them.', prompt: 'provider key: ' };
1953
+ }
1954
+ const match = findByokProvider(providers, typed);
1955
+ if (match.ambiguous) {
1956
+ return {
1957
+ note: `"${typed}" matches ${match.ambiguous.join(', ')} — retype the exact id. Nothing was sent.`,
1958
+ prompt: null,
1959
+ };
1960
+ }
1961
+ const p = match.provider;
1962
+ if (!p) {
1963
+ const ids = providers.map((x) => x.id).join(', ');
1964
+ return { note: `unknown provider "${typed}". Known ids: ${ids}`, prompt: null };
1965
+ }
1966
+ if (p.configured) {
1967
+ return {
1968
+ note: `${p.id} already has a key${p.masked ? ` (${p.masked})` : ''} — pasting a new one replaces it.`,
1969
+ prompt: `new ${p.label || p.id} key: `,
1970
+ };
1971
+ }
1972
+ const bits = [`${p.label || p.id}`];
1973
+ const models = (p.models || [])
1974
+ .map((m) => (typeof m === 'string' ? m : m && m.id))
1975
+ .filter(Boolean);
1976
+ if (models.length) bits.push(`unlocks ${models.join(', ')}`);
1977
+ if (p.key_prefix) bits.push(`key starts with ${p.key_prefix}`);
1978
+ if (p.key_url) bits.push(`create one at ${p.key_url}`);
1979
+ return { note: bits.join(' · '), prompt: `${p.id} key: ` };
1980
+ },
1838
1981
  },
1839
1982
  {
1840
1983
  name: 'byok-rm', args: ['provider'], hint: '<provider>', category: 'auth',
package/src/panels.js CHANGED
@@ -42,6 +42,8 @@
42
42
  const { span, getSize, lineWidth } = require('./screen.js');
43
43
  const { themeOf, BOLD, BOLD_OFF, GLYPH } = require('./theme.js');
44
44
 
45
+ const VERSION = require('../package.json').version;
46
+
45
47
  // ── local helpers (this file stays self-contained apart from theme/screen) ────
46
48
 
47
49
  /** Finite number or 0 — never NaN (which would print as "NaN"). */
@@ -1139,26 +1141,57 @@ function buildYolo(state, ctx = {}) {
1139
1141
 
1140
1142
  // ── /release-notes ───────────────────────────────────────────────────────────
1141
1143
 
1144
+ /**
1145
+ * `/release-notes` — the long form of the welcome box's `What's new`.
1146
+ *
1147
+ * This panel was stale in a way the welcome box was not. It opened at v0.1.0
1148
+ * and closed with three bullets declaring /login /doctor /permissions /mcp
1149
+ * /skills /hooks /agents /resume /rewind /compact /init /export /vim /yolo
1150
+ * "unavailable here — each says why". Every one of those is implemented now
1151
+ * (no command reports `unavailable`, and `stubPanel` has zero callers), so the
1152
+ * panel was telling anyone who ran it that a third of the command surface did
1153
+ * not exist. The list below is the real one.
1154
+ *
1155
+ * The command count is read from the registry at call time rather than frozen
1156
+ * as a literal, because a frozen count is precisely what nobody re-derived.
1157
+ */
1142
1158
  function buildReleaseNotes(state, ctx = {}) {
1143
1159
  const t = themeOf(ctx);
1144
1160
  const out = [];
1145
- out.push([span(t.gold + BOLD, "What's new"), span(BOLD_OFF, '')]);
1161
+ out.push([span(t.gold + BOLD, `What's new in v${VERSION}`), span(BOLD_OFF, '')]);
1146
1162
  out.push([span(t.gray, '─'.repeat(30))]);
1163
+
1147
1164
  const bullets = [
1148
- '• v0.1.0 — aegiscode CLI: the aegiscode design system on the AEGIS pooled brain.',
1149
- '• /help /status /cost /tokens /context /models /model /theme /stream (local).',
1150
- '• /aegis-ask /aegis-status /aegis-recall /aegis-remember /memory /billing (tool-backed).',
1151
- '• /byok /byok-set /byok-rm — bring your own provider keys (never echoed).',
1152
- '• /tool <name> [json] — call any registry tool directly.',
1153
- '• Cost and tokens are metered in euro (€4dp below a cent).',
1154
- '• Config persists to ~/.aegiscode/config.json (theme/model/stream).',
1155
- '• Unavailable here: /login /doctor /permissions /mcp /skills /hooks /agents',
1156
- '• /resume /rewind /compact /init /export /vim /yolo /confirm — each says why.',
1157
- '• Repo: github.com/aegisinfo/aegiscode-plugin',
1165
+ 'v6.7.3 — the shared renderer is re-staged into cli/vendor.',
1166
+ 'v6.7.1 — terminal capabilities are read from the terminal, not the platform.',
1167
+ 'v6.7.0 — a file edit renders as a coloured diff block.',
1168
+ 'v6.6.0 — autonomous mode: a persistent work queue with a detached worker.',
1169
+ 'v6.5.x — the live tool row, /cost billed from the ledger the server settled at.',
1170
+ 'v6.4.0 — `aegiscode login`/`logout`/`key`, a 0600 credential store, /cloud and /sync.',
1158
1171
  ];
1159
- for (const text of bullets) out.push([span(t.green, '•'), span(t.white, ' ' + text.slice(1))]);
1160
- out.push([span('', '')]);
1161
- out.push([span(t.gray, '/release-notes for more')]);
1172
+ for (const text of bullets) {
1173
+ const i = text.indexOf(' — ');
1174
+ const head = i === -1 ? text : text.slice(0, i);
1175
+ const body = i === -1 ? '' : text.slice(i + 3);
1176
+ out.push([span(t.green, '•'), span(t.gold, ` ${head}`), span(t.white, body ? ` — ${body}` : '')]);
1177
+ }
1178
+
1179
+ let counts = null;
1180
+ try {
1181
+ // Call-time require: commands.js requires this module, so a top-level
1182
+ // require would close a cycle at load for no benefit.
1183
+ const commands = require('./commands.js');
1184
+ counts = { n: commands.visibleCommands().length, cats: commands.CATEGORIES.length };
1185
+ } catch {
1186
+ // A release-notes panel is never worth failing a render over — the bullets
1187
+ // above stand on their own without the count.
1188
+ }
1189
+ if (counts) {
1190
+ out.push([span('', '')]);
1191
+ out.push([span(t.gray, ` ${counts.n} commands across ${counts.cats} categories — /help lists them.`)]);
1192
+ }
1193
+ out.push([span(t.gray, ' The version above is read from the package; the prose is not.')]);
1194
+ out.push([span(t.gray, ' Repo: github.com/aegisinfo/aegiscode-plugin')]);
1162
1195
  return out;
1163
1196
  }
1164
1197
 
package/src/render.js CHANGED
@@ -4,8 +4,8 @@
4
4
  * The CLI's renderers — the start-up banner, transcript turns, the per-turn
5
5
  * accounting line, the status bar, the live working line and the transcript's
6
6
  * markdown body. The presentation layer is a fidelity port of
7
- * `aegiscodex-dev`: gold `━`/`─` rules, the two-tone welcome mark (gold mascot,
8
- * blue/lavender/dim whale), the coral-bold welcome title, the `❯` prompt, the
7
+ * `aegiscodex-dev`: gold `━`/`─` rules, the one-ink ÆGIS wordmark (box runes,
8
+ * in gold), the coral-bold welcome title, the `❯` prompt, the
9
9
  * `⎿` hook rows, the `●` answer/stream cursor and the `✻` done glyph.
10
10
  *
11
11
  * Every function returns lines (strings carrying SGR escapes) rather than
@@ -97,7 +97,8 @@ function tintWhale(str, t) {
97
97
  return spans;
98
98
  }
99
99
 
100
- /** One centred welcome-art row: gold mascot on the left, tinted whale right. */
100
+ /** One centred welcome-art row: the gold wordmark on the left, and (when a
101
+ * two-tone mark returns) the tinted right half. */
101
102
  function artRow(ctx, row, parts, leftPad) {
102
103
  const t = themeOf(ctx);
103
104
  const left = row[0] || '';
@@ -120,10 +121,10 @@ function artRow(ctx, row, parts, leftPad) {
120
121
  }
121
122
 
122
123
  /**
123
- * The start-up banner, matching aegiscodex-dev's welcome legs: a gold `━`+`─`
124
- * rule across the full terminal, the centred welcome mark (mascot half gold,
125
- * moon/whale half blue/lavender/dim), the coral-bold welcome title and a
126
- * version line, then the compact identity block.
124
+ * The start-up banner: a gold `━`+`─` rule across the full terminal, the
125
+ * centred welcome mark (the ÆGIS wordmark, in gold — the same mark and the same
126
+ * ink the desktop app draws), the coral-bold welcome title and a version line,
127
+ * then the compact identity block.
127
128
  */
128
129
  function renderBanner(ctx, info = {}) {
129
130
  const t = themeOf(ctx);
@@ -138,7 +139,7 @@ function renderBanner(ctx, info = {}) {
138
139
  );
139
140
  lines.push('');
140
141
 
141
- const parts = welcomeArtParts(width);
142
+ const parts = welcomeArtParts();
142
143
  if (width >= parts.width + 2) {
143
144
  const leftPad = Math.max(0, Math.floor((width - parts.width) / 2));
144
145
  for (const row of parts.rows) lines.push(artRow(ctx, row, parts, leftPad));
package/src/screens.js CHANGED
@@ -32,7 +32,7 @@ const { getSize, paint, span, lineWidth, clip, w } = require('./screen.js');
32
32
  const events = require('./events.js');
33
33
  const { nextKey, KEY } = events;
34
34
  const { C, BOLD, BOLD_OFF, GLYPH, THEME_TABLE, themeOf } = require('./theme.js');
35
- const { welcomeArtParts } = require('./art.js');
35
+ const { TAGLINE, TAGLINE_SHORT, welcomeArtParts } = require('./art.js');
36
36
  const { renderDiffPreview } = require('./markdown.js');
37
37
  const render = require('./render.js');
38
38
  const { updateConfig, configExists, loadConfig } = require('./config.js');
@@ -52,14 +52,30 @@ const TIPS = [
52
52
  ' Press ? for shortcuts',
53
53
  ];
54
54
 
55
+ /**
56
+ * The `What's new` box — newest release first, two rows per release, **eight
57
+ * rows in total**. The row count is load-bearing, not cosmetic: at 80×24 the
58
+ * welcome screen already fills exactly `rows - 1`, so a ninth row pushes the
59
+ * footer hint off the bottom of the commonest terminal there is. Retire the
60
+ * oldest entry rather than adding one.
61
+ *
62
+ * This block went four minor versions stale (it still topped out at v6.3.0
63
+ * while the package shipped 6.7.3) because nothing held it to anything. Two
64
+ * things do now: the box header names `VERSION`, so the screen always says
65
+ * which build is running, and every `/command` named below is asserted to
66
+ * exist in the registry by `test/cli-onboarding.test.mjs`. The prose stays
67
+ * hand-written — a changelog is prose — but it can no longer advertise a
68
+ * command that was renamed away, and it cannot claim to be news for a release
69
+ * the user is not running.
70
+ */
55
71
  const WHATS_NEW = [
56
- ' v6.3.0: onboarding — trust check,',
57
- ' theme picker and this welcome',
58
- ' v6.1.0: the / palette, the full',
59
- ' command registry, session',
60
- ' persistence and auto-checkpoints',
61
- ' v6.0.0: the aegiscodex-dev design',
62
- ' system — palette, mark, verbs',
72
+ ' v6.7.x: caps read from the tty,',
73
+ ' edits render as diff blocks',
74
+ ' v6.6.0: autonomous mode — a',
75
+ ' persistent work queue',
76
+ ' v6.5.0: live tool rows, /cost',
77
+ ' from the ledger the pool set',
78
+ ' v6.4.0: `aegiscode login`',
63
79
  ' /release-notes for more',
64
80
  ];
65
81
 
@@ -240,11 +256,11 @@ async function showThemePicker(ctx, title = `Welcome to ${PRODUCT}`) {
240
256
  // ── welcome ──────────────────────────────────────────────────────────────────
241
257
 
242
258
  /**
243
- * The welcome screen's lines: gold rule, the two-tone mark, the coral title,
259
+ * The welcome screen's lines: gold rule, the wordmark, the coral title,
244
260
  * the two boxes, the footer hint. Pure, so a test can assert all of it.
245
261
  *
246
262
  * The mark reuses `render.artRow`, the same renderer the scrollback banner
247
- * uses, so the mascot cannot render two different ways in two places.
263
+ * uses, so the mark cannot render two different ways in two places.
248
264
  */
249
265
  function welcomeLines(ctx, cols, rows, firstRun = true) {
250
266
  const t = themeOf(ctx);
@@ -268,7 +284,7 @@ function welcomeLines(ctx, cols, rows, firstRun = true) {
268
284
  // An update notice is never worth failing a launch over.
269
285
  }
270
286
 
271
- const parts = welcomeArtParts(cols);
287
+ const parts = welcomeArtParts();
272
288
  if (cols >= parts.width + 2) {
273
289
  const leftPad = Math.max(0, Math.floor((cols - parts.width) / 2));
274
290
  for (const row of parts.rows) {
@@ -286,11 +302,11 @@ function welcomeLines(ctx, cols, rows, firstRun = true) {
286
302
  const title = firstRun ? `Welcome to ${PRODUCT}` : 'Welcome back!';
287
303
  lines.push(centered(title, cols, t.coral + BOLD));
288
304
  // Shorten the subtitle rather than clipping it: a truncated tagline reads as
289
- // a rendering fault, a shorter one just reads as a shorter one.
290
- const tagline =
291
- cols >= 40
292
- ? 'Cloud brain in your shell — one account, three hosts.'
293
- : 'Cloud brain in your shell.';
305
+ // a rendering fault, a shorter one just reads as a shorter one. The threshold
306
+ // is derived from the string's own width, not a fixed column count — the copy
307
+ // lives in `art.js` now, so a hardcoded breakpoint here would silently start
308
+ // clipping the moment the tagline grew by a word.
309
+ const tagline = cols >= w(TAGLINE) + 4 ? TAGLINE : TAGLINE_SHORT;
294
310
  lines.push(centered(tagline, cols, t.gray));
295
311
  lines.push([span('', '')]);
296
312
 
@@ -334,9 +350,15 @@ function boxes(t, cols, avail) {
334
350
  const twoUp = Math.floor((cols - gap) / 2);
335
351
  const tipRows = TIPS.map((s) => `${GLYPH.pointer}${s}`);
336
352
  const newsRows = WHATS_NEW;
353
+ // Name the running build in the header. `WHATS_NEW` is hand-written prose and
354
+ // will always lag the release it describes by however long it takes someone
355
+ // to remember; the header cannot, so the box is never *silently* stale — a
356
+ // user on a newer build reads "What's new in vX" over notes that end earlier
357
+ // and can see the gap for what it is.
358
+ const newsHead = `What's new in v${VERSION}`;
337
359
  if (twoUp >= 30) {
338
360
  let a = boxLines(t, 'Tips for getting started', tipRows, twoUp);
339
- let b = boxLines(t, "What's new", newsRows, twoUp);
361
+ let b = boxLines(t, newsHead, newsRows, twoUp);
340
362
  // Equalise the heights so both bottom rules land on the same row — boxes of
341
363
  // different heights leave a ragged pair of corners otherwise.
342
364
  const h = Math.max(a.length, b.length);
@@ -358,7 +380,7 @@ function boxes(t, cols, avail) {
358
380
  }
359
381
  // Narrow: stack, so neither box is rendered at an unreadable width.
360
382
  const wd = Math.max(20, cols - 1);
361
- return [...boxLines(t, 'Tips for getting started', tipRows, wd), ...boxLines(t, "What's new", newsRows, wd)];
383
+ return [...boxLines(t, 'Tips for getting started', tipRows, wd), ...boxLines(t, newsHead, newsRows, wd)];
362
384
  }
363
385
 
364
386
  /**
@@ -7,10 +7,13 @@
7
7
  * orchestration, routing, or tier logic. All of that lives in the private
8
8
  * ae-guix product and behind aegiscloud.org.
9
9
  *
10
- * Runs unchanged under three hosts:
10
+ * Runs unchanged under four hosts:
11
11
  * - mcp/server.js (Claude Code MCP plugin) — CommonJS require
12
12
  * - desktop/ (thin Electron shell) — CommonJS require
13
13
  * (vendored byte-identical copy at desktop/vendor/aegis.js)
14
+ * - cli/ (aegiscode terminal host) — CommonJS require
15
+ * (vendored byte-identical copy at
16
+ * cli/vendor/client/aegis.js)
14
17
  * - aegis-online (browser SPA, vendored copy) — <script> tag →
15
18
  * window.AegisClient
16
19
  *
@@ -348,6 +351,12 @@ function createClient(opts = {}) {
348
351
  * provider key never touches AEGIS storage — it is forwarded straight to the
349
352
  * provider for this request only. Mirrors chatCompletion()'s streaming /
350
353
  * fallback semantics exactly.
354
+ *
355
+ * The caller's *AEGIS* key is sent alongside the provider key as X-AEGIS-Key.
356
+ * Two credentials, two headers, on purpose: the provider key authenticates the
357
+ * upstream call, the AEGIS key says whose bank pays the handling fee. With no
358
+ * AEGIS key configured the header is omitted and the call stays anonymous —
359
+ * allowed, just unbilled (see _byok_identify_user on the server).
351
360
  */
352
361
  async function byokChatCompletion({
353
362
  provider = 'openai',
@@ -373,6 +382,10 @@ function createClient(opts = {}) {
373
382
  'X-AEGIS-Version': clientVersion,
374
383
  'X-Provider-Key': key,
375
384
  };
385
+ // Identify the payer. Absent key => anonymous call, which the server
386
+ // accepts but cannot bill; sending it is what turns a BYOK turn into
387
+ // billable traffic instead of a free ride.
388
+ if (apiKey) headers['X-AEGIS-Key'] = apiKey;
376
389
  if (!stream || typeof onStream !== 'function') {
377
390
  return apiPost('/api/v1/byok/chat/completions', { ...body, stream: false }, headers);
378
391
  }
@@ -683,6 +696,15 @@ function createClient(opts = {}) {
683
696
  return apiGet('/api/user/api-keys');
684
697
  }
685
698
 
699
+ /** The server's BYOK provider catalog: which providers accept a key, which
700
+ * models each unlocks, where to get the key, and the prefix a valid key
701
+ * starts with. Deliberately NOT key-gated — "which key do I go get, and
702
+ * what will it unlock?" is the question asked *before* an AEGIS key exists.
703
+ * An AEGIS key, if present, only adds the `configured` column. */
704
+ async function byokProviders() {
705
+ return apiGet('/api/v1/byok/providers');
706
+ }
707
+
686
708
  async function byokSet(provider, providerApiKey) {
687
709
  return apiPost('/api/user/api-keys', {
688
710
  provider,
@@ -809,6 +831,7 @@ function createClient(opts = {}) {
809
831
  tokenBankTopup,
810
832
  billingCheckout,
811
833
  byokStatus,
834
+ byokProviders,
812
835
  byokSet,
813
836
  getMemoryToken,
814
837
  memorySearch,
@@ -4,13 +4,13 @@
4
4
  * credentials.js — the ONE AEGIS account credential store, shared by every
5
5
  * host in this repo (terminal `aegiscode`, the MCP plugin, the desktop app).
6
6
  *
7
- * Why it lives in `client/`: this directory is the only tree all three hosts
8
- * already bundle. The MCP plugin ships `mcp/` + `client/` and nothing else, so
7
+ * Why it lives in `client/`: this directory is the only tree every host
8
+ * already bundles. The MCP plugin ships `mcp/` + `client/` and nothing else, so
9
9
  * a reader placed here needs no cross-package dependency — which is what the
10
10
  * alternative (the MCP host requiring `cli/src/credentials.js`) would have
11
11
  * forced, and why that host used to read `AEGIS_API_KEY` from the environment
12
- * alone while the CLI could save a key to disk. One login, one file, three
13
- * hosts: that is the point of this module.
12
+ * alone while the CLI could save a key to disk. One login, one file, all
13
+ * four hosts: that is the point of this module.
14
14
  *
15
15
  * Zero dependencies, no host imports. The data dir is resolved here
16
16
  * (`aegisHome()`) rather than imported from the CLI's config.js, so this file
@@ -66,6 +66,68 @@ function usageTokens(usage) {
66
66
  return (input || 0) + (output || 0);
67
67
  }
68
68
 
69
+ /**
70
+ * Rough token count for text the wire never measured — a direct port of the
71
+ * CLI's own estimator (`aegiscodex-dev/src/tokens.js estimateTokens`), and the
72
+ * reason its session total is MONOTONIC.
73
+ *
74
+ * This is the whole difference being fixed. The CLI's `appendHistory`
75
+ * (aegiscodex-dev/src/history.js) writes a `tokens` object for EVERY finished
76
+ * exchange: `{input, output, cacheRead, cacheWrite, real: true}` when the wire
77
+ * reported usage, and `{input: estimateTokens(prompt), output:
78
+ * estimateTokens(reply), real: false}` when it did not. `real` is a FLAG, not a
79
+ * gate — `aggregateSessionUsage` adds `t.input || 0` for every row regardless,
80
+ * so a turn without usage still moves the total and only marks it as partly
81
+ * estimated.
82
+ *
83
+ * The desktop rolled only reported usage and dropped everything else, so its
84
+ * total was flat across any turn the pool did not report on — the meter looked
85
+ * dead while the conversation was being billed. ~4 characters per token, the
86
+ * CLI's heuristic, kept identical so the two surfaces estimate the same turn
87
+ * the same way. Empty text is 0, never the `Math.max(1, …)` floor.
88
+ */
89
+ function estimateTokens(text) {
90
+ if (!text) return 0;
91
+ return Math.max(1, Math.ceil([...String(text)].length / 4));
92
+ }
93
+
94
+ /**
95
+ * The bucket shape an exchange gets when the wire reported no usage: the CLI's
96
+ * `{input: estimateTokens(prompt), output: estimateTokens(reply)}`.
97
+ *
98
+ * `null` when there is no text at all to estimate from, so a dispatch that
99
+ * genuinely reported nothing (no usage, no prompt, no reply) still lands in
100
+ * `unknown` instead of being handed a fabricated zero.
101
+ *
102
+ * `reasoning` is the extended-thinking trace, and it is OUTPUT: a reasoning
103
+ * model bills its chain of thought as output tokens, which is why the wire's
104
+ * own `output_tokens` already includes it. The desktop renders that trace in
105
+ * its own element (app.js `reasoningText`) rather than in the reply body, so
106
+ * the two streams had to be added back together here — an estimate measured off
107
+ * the visible answer alone sat still for the entire think phase, which on a
108
+ * reasoning model is both the longest and the most expensive part of the turn.
109
+ *
110
+ * @param {string} [prompt]
111
+ * @param {string} [reply]
112
+ * @param {string} [reasoning]
113
+ * @returns {{input: number, output: number, cacheRead: number, cacheWrite: number}|null}
114
+ */
115
+ function estimatedBuckets(prompt, reply, reasoning) {
116
+ const hasPrompt = typeof prompt === 'string' && prompt.length > 0;
117
+ const out =
118
+ (typeof reply === 'string' ? reply : '') +
119
+ (typeof reasoning === 'string' ? reasoning : '');
120
+ const hasReply = out.length > 0;
121
+ if (!hasPrompt && !hasReply) return null;
122
+ return {
123
+ input: estimateTokens(prompt),
124
+ output: estimateTokens(out),
125
+ cacheRead: 0,
126
+ cacheWrite: 0,
127
+ real: false,
128
+ };
129
+ }
130
+
69
131
  // Per-million-token USD rates. Cache-read/write matter for long sessions.
70
132
  //
71
133
  // These are the PROVIDER's rates, for the fallback path where a turn has no
@@ -200,6 +262,8 @@ function turnAccounting(usage, model, opts = {}) {
200
262
  * back is that RUNNING TOTAL. The status bar prints `state.tokens`
201
263
  * (renderStatus), and `ctrl+t` prints the tallies in one line
202
264
  * (`tokenSummary`: `12,400 tok (10,100 in / 2,300 out) · 4 calls · €0.03`).
265
+ * The tallies are reproduced; that one abbreviation is not — `fmtRoll` explains
266
+ * why it drops the parenthetical rather than carrying the CLI's line verbatim.
203
267
  *
204
268
  * The desktop counted per turn only. Every meta row was a fresh count that
205
269
  * reset at the next call, so "what has this session spent" was answerable only
@@ -239,6 +303,12 @@ function emptyRoll() {
239
303
  cacheWrite: 0,
240
304
  /** Dispatches that reported no usage at all — the honest gap in `tokens`. */
241
305
  unknown: 0,
306
+ /**
307
+ * Exchanges folded from TEXT rather than reported usage, on the CLI's
308
+ * `real: false` rule. They are counted in `tokens` — that is the point —
309
+ * and named here so an estimated figure is never read as a measured one.
310
+ */
311
+ estimated: 0,
242
312
  /** Settled charges (server-settled `costUsd`), rolled. */
243
313
  cost: 0,
244
314
  /** Locally priced turns, rolled. Never mixed into `cost`. */
@@ -253,11 +323,14 @@ function emptyRoll() {
253
323
  *
254
324
  * @param {object} [roll] the roll so far (emptyRoll() when omitted)
255
325
  * @param {object} [usage] the response's `usage` object
256
- * @param {{model?: string, costUsd?: number, calls?: number, turns?: number}} [opts]
326
+ * @param {{model?: string, costUsd?: number, calls?: number, turns?: number,
327
+ * prompt?: string, reply?: string, estimated?: boolean}} [opts]
257
328
  * `calls` defaults to 1; a pooled turn may report how many provider
258
329
  * calls it actually made. `turns: 0` folds a dispatch that is not a
259
330
  * turn of its own — the discovery-lane card, which bills like any other
260
- * call but is not something the user asked for.
331
+ * call but is not something the user asked for. `prompt`/`reply` are the
332
+ * turn's text, used ONLY when the wire reported no usage, so the turn is
333
+ * estimated rather than dropped (the CLI's `appendHistory` rule).
261
334
  * @returns {object} the new roll
262
335
  */
263
336
  function rollTurn(roll, usage, opts = {}) {
@@ -265,8 +338,31 @@ function rollTurn(roll, usage, opts = {}) {
265
338
  next.turns += opts.turns === undefined ? 1 : Number(opts.turns) || 0;
266
339
  next.calls += opts.calls === undefined ? 1 : Number(opts.calls) || 0;
267
340
  const turn = turnAccounting(usage, opts.model, { costUsd: opts.costUsd });
341
+ // A row folded from text rather than from the wire: either this turn's own
342
+ // fallback below, or a stored ledger row carrying `real: false` — the shape
343
+ // the CLI's `appendHistory` writes for an exchange the provider did not
344
+ // report on.
345
+ const estimated = opts.estimated === true || (usage && usage.real === false);
268
346
  if (turn.tokens == null) {
269
- next.unknown += 1;
347
+ // No reported usage. The CLI does not let such a turn vanish from the
348
+ // total: `appendHistory` estimates it from the text and marks it
349
+ // `real: false` (aegiscodex-dev/src/history.js), and
350
+ // `aggregateSessionUsage` then adds it like any other row. Folding the same
351
+ // estimate here is what makes the live roll and the rebuilt roll the same
352
+ // number, and what stops the total standing still on exactly the turns the
353
+ // pool declined to report on — the symptom this fallback exists to remove.
354
+ const est = estimatedBuckets(opts.prompt, opts.reply, opts.reasoning);
355
+ if (!est) {
356
+ // Nothing reported AND no text to estimate from. The single case that
357
+ // stays uncounted: `unknown` names the gap, where a fabricated zero would
358
+ // read as a measurement.
359
+ next.unknown += 1;
360
+ return next;
361
+ }
362
+ next.tokens += est.input + est.output;
363
+ next.input += est.input;
364
+ next.output += est.output;
365
+ next.estimated += 1;
270
366
  return next;
271
367
  }
272
368
  const b = usageBuckets(usage);
@@ -275,6 +371,14 @@ function rollTurn(roll, usage, opts = {}) {
275
371
  next.output += b.output;
276
372
  next.cacheRead += b.cacheRead;
277
373
  next.cacheWrite += b.cacheWrite;
374
+ if (estimated) {
375
+ // Money stays out of an estimated exchange, deliberately and in both
376
+ // directions: the CLI writes no `costUsd` for one, so pricing it here would
377
+ // make the live roll drift from the rebuilt one — and pricing tokens that
378
+ // were themselves guessed would stack one guess on another.
379
+ next.estimated += 1;
380
+ return next;
381
+ }
278
382
  if (turn.real) next.cost += turn.cost;
279
383
  else if (turn.cost != null) next.estimate += turn.cost;
280
384
  return next;
@@ -307,6 +411,58 @@ function rollMessages(messages) {
307
411
  return roll;
308
412
  }
309
413
 
414
+ /**
415
+ * The ledger row one finished dispatch must carry into the shared session
416
+ * store, so the rolling total can be REBUILT when the thread is reopened —
417
+ * the desktop's counterpart of the CLI's `appendHistory`
418
+ * (aegiscodex-dev/src/history.js:36).
419
+ *
420
+ * One authority for the row, on purpose. The CLI writes a `tokens` object for
421
+ * EVERY exchange and skips none:
422
+ *
423
+ * tokens: usage
424
+ * ? { input, output, cacheRead, cacheWrite, real: true }
425
+ * : { input: estimateTokens(prompt), output: estimateTokens(reply), real: false }
426
+ *
427
+ * …and `aggregateSessionUsage` then sums `t.input || 0` over every entry with
428
+ * `real` as a FLAG, not a gate. Mirroring that shape here is what makes the
429
+ * live roll and the rebuilt roll the same number: `rollTurn` is handed this
430
+ * exact object on reopen, so an estimated exchange adds the same buckets it
431
+ * added live and is counted under `estimated` in both.
432
+ *
433
+ * Returns `null` when there is neither reported usage nor text to estimate
434
+ * from — the one case that must stay unrecorded, because a fabricated
435
+ * `{input: 0, output: 0}` row would read as a measured zero forever after.
436
+ *
437
+ * @param {object} [usage] the response's `usage` object
438
+ * @param {object} [turn] its accounting (turnAccounting), when already done
439
+ * @param {{model?: string, costUsd?: number, calls?: number, prompt?: string,
440
+ * reply?: string}} [opts]
441
+ * @returns {object|null} the row's ledger fields
442
+ */
443
+ function ledgerRow(usage, turn, opts = {}) {
444
+ const t = turn || turnAccounting(usage, opts.model, { costUsd: opts.costUsd });
445
+ const calls = Number.isFinite(opts.calls) && opts.calls > 0 ? opts.calls : undefined;
446
+ if (t.tokens != null) {
447
+ const row = { tokens: usageBuckets(usage) };
448
+ // Only a SETTLED charge is persisted. The CLI writes `costUsd` for a real
449
+ // charge only, and the rebuild prices an unpriced row from the same rate
450
+ // table this window used — persisting a local guess would let a stale
451
+ // table outlive the change that wrote it.
452
+ if (t.real && t.cost != null) row.costUsd = t.cost;
453
+ if (calls !== undefined) row.calls = calls;
454
+ return row;
455
+ }
456
+ // `reasoning` is part of the billed output, so it is estimated with the
457
+ // reply — a stored row for a thinking-heavy turn must not persist a count
458
+ // that excludes the longest thing the model wrote.
459
+ const est = estimatedBuckets(opts.prompt, opts.reply, opts.reasoning);
460
+ if (!est) return null;
461
+ const row = { tokens: est };
462
+ if (calls !== undefined) row.calls = calls;
463
+ return row;
464
+ }
465
+
310
466
  /**
311
467
  * The CLI's rendering of a session tally — `cli/src/format.js fmtTokens`, which
312
468
  * is the one `tokenSummary` actually imports (`cli/src/app.js:50`). NOT the
@@ -332,21 +488,32 @@ function fmtTokens(n) {
332
488
  * an untouched session adds no noise to a turn's meta line.
333
489
  *
334
490
  * @param {object} [roll]
335
- * @returns {string} e.g. `12,400 tok (10,100 in / 2,300 out) · 4 calls · $0.0310`
491
+ * @returns {string} e.g. `12,400 tok · 4 calls · $0.0310` — the CLI's fields in
492
+ * the CLI's order, minus the input/output parenthetical (see below).
336
493
  */
337
494
  function fmtRoll(roll) {
338
495
  const r = roll || emptyRoll();
339
496
  if (!r.turns && !r.calls) return '';
340
- // The first two fields are `tokenSummary` (cli/src/app.js:1413) verbatim,
341
- // separator and all: `12,400 tok (10,100 in / 2,300 out) · 4 calls`. There the
342
- // parenthetical is unconditional and the call count is singular at one; both
343
- // are kept, because a line that is only *sometimes* shaped like the CLI's is a
344
- // lookalike rather than the same quantity. The call count is also the number
345
- // that reveals a fan-out, which is why it is not hidden at 1.
346
- const bits = [
347
- `${fmtTokens(r.tokens)} tok (${fmtTokens(r.input)} in / ${fmtTokens(r.output)} out)`,
348
- `${r.calls} call${r.calls === 1 ? '' : 's'}`,
349
- ];
497
+ // The fields are `tokenSummary`'s (cli/src/app.js:1413) in its order — tokens,
498
+ // calls, money — with one dropped: the `(10,100 in / 2,300 out)` split. `in`
499
+ // and `out` are a terminal status-line shorthand, legible to someone already
500
+ // reading that status line and to nobody else, which is what an unlabelled
501
+ // abbreviation in a GUI topbar turns into. The total is the figure a reader
502
+ // wants; `r.input`/`r.output` are still folded onto the roll (see `rollTurn`)
503
+ // for any surface that wants to show the split with real labels. The call
504
+ // count stays unconditional, because it is the number that reveals a
505
+ // fan-out, and it is not hidden at 1.
506
+ const bits = [];
507
+ // The token half only when something was actually counted. `rollTurn` counts
508
+ // turns and calls BEFORE it looks at the token count, so a dispatch that
509
+ // reported nothing still reaches here — and printing its empty tally would
510
+ // put `0 tok` on the topbar, a figure the meter never took, which reads as a
511
+ // counter that does not move. The turn count is still stated, because that
512
+ // much is true.
513
+ if (r.tokens > 0) {
514
+ bits.push(`${fmtTokens(r.tokens)} tok`);
515
+ }
516
+ bits.push(`${r.calls} call${r.calls === 1 ? '' : 's'}`);
350
517
  // Money is where this line departs from `tokenSummary`, deliberately: that
351
518
  // one sums a single `session.cost` in EUR via fmtEur, while this surface keeps
352
519
  // a settled charge and a local estimate apart so a `~`-estimate can never be
@@ -363,6 +530,11 @@ function fmtRoll(roll) {
363
530
  // the count appears only when something went unreported, and it never changes
364
531
  // a number — it only says the number is not the whole story.
365
532
  if (r.unknown) bits.push(`${r.unknown} unrpt`);
533
+ // The other half of the same honesty: a total that includes estimated
534
+ // exchanges says so, because the CLI marks the same rows `real: false` and a
535
+ // reader is entitled to know which figure they are looking at. It changes no
536
+ // number — it says the number is partly inferred.
537
+ if (r.estimated) bits.push(`${r.estimated} est`);
366
538
  return bits.join(' · ');
367
539
  }
368
540
 
@@ -387,9 +559,12 @@ if (typeof module !== 'undefined' && module.exports) {
387
559
  usageBuckets,
388
560
  usageCost,
389
561
  turnAccounting,
562
+ estimateTokens,
563
+ estimatedBuckets,
390
564
  emptyRoll,
391
565
  rollTurn,
392
566
  rollMessages,
567
+ ledgerRow,
393
568
  fmtTokens,
394
569
  fmtRoll,
395
570
  fmtCost,
@@ -169,15 +169,56 @@ function createTools(client) {
169
169
  },
170
170
  },
171
171
 
172
+ aegis_byok_providers: {
173
+ description:
174
+ "List every provider that accepts a Bring-Your-Own-Key on AEGIS: the exact provider id to pass to aegis_byok_set, the models each one unlocks, where to create the key, and the prefix a valid key starts with. Call this before aegis_byok_set so the user knows which key to go get rather than guessing a provider id.",
175
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
176
+ async run() {
177
+ const data = await aegis.byokProviders();
178
+ const providers = data.providers || [];
179
+ if (!providers.length) return 'AEGIS is not advertising any BYOK providers right now.';
180
+ const lines = ["Set one with aegis_byok_set — pass the id exactly as shown:"];
181
+ for (const p of providers) {
182
+ // Bare ids, not objects — the same mismatch that made the CLI render
183
+ // an empty model line for every provider.
184
+ const models = (p.models || [])
185
+ .map((m) => (typeof m === 'string' ? m : m && m.id))
186
+ .filter(Boolean);
187
+ const state = p.configured ? ` ✓ set${p.masked ? ` (${p.masked})` : ''}` : '';
188
+ lines.push('');
189
+ lines.push(` ${p.id}${state}`);
190
+ if (p.label) lines.push(` ${p.label}`);
191
+ if (models.length) lines.push(` models: ${models.join(', ')}`);
192
+ if (p.key_prefix) lines.push(` key starts with: ${p.key_prefix}`);
193
+ if (p.key_url) lines.push(` get a key: ${p.key_url}`);
194
+ }
195
+ return lines.join('\n');
196
+ },
197
+ },
198
+
172
199
  aegis_byok_status: {
173
200
  description:
174
201
  "List which providers have a Bring-Your-Own-Key configured on this AEGIS account (known ids: openai, anthropic, groq, openrouter, together, deepseek, gemini, …). A configured BYOK key is used automatically by aegis_ask instead of the pooled balance for that provider, so calls no longer cost AEGIS token-bank funds.",
175
202
  inputSchema: { type: 'object', properties: {}, additionalProperties: false },
176
203
  async run() {
177
204
  const data = await aegis.byokStatus();
178
- const rows = Object.entries(data || {}).map(([provider, info]) => {
205
+ const entries = Object.entries(data || {});
206
+ if (!entries.length) return 'No BYOK providers are configured. Run aegis_byok_providers to see what you can set.';
207
+ // The status endpoint historically answered with a bare provider->info
208
+ // map. Once a catalog is available the same keys are rendered with the
209
+ // operator's own label, so a message never depends on the reader
210
+ // knowing that "together" is a company.
211
+ let labels = {};
212
+ try {
213
+ const cat = await aegis.byokProviders();
214
+ for (const p of cat.providers || []) labels[p.id] = p.label || '';
215
+ } catch {
216
+ // Catalog is a nicety here, never a reason to fail a status call.
217
+ }
218
+ const rows = entries.map(([provider, info]) => {
179
219
  const set = info && info.set;
180
- return ` ${provider}: ${set ? `set (${info.masked})` : 'not set'}`;
220
+ const label = labels[provider] ? ` ${labels[provider]}` : '';
221
+ return ` ${provider}${label}: ${set ? `set (${info.masked})` : 'not set'}`;
181
222
  });
182
223
  return `BYOK keys:\n${rows.join('\n')}`;
183
224
  },