aegiscode 6.8.7 → 6.8.9

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/src/chatflow.js CHANGED
@@ -48,6 +48,7 @@ const { GLYPH, VERBS, DONE_VERBS, BOLD, BOLD_OFF, themeOf } = require('./theme.j
48
48
  const { LineEditor } = require('./input.js');
49
49
  const { renderMarkdown } = require('./markdown.js');
50
50
  const overlays = require('./overlays.js');
51
+ const models = require('./models.js');
51
52
  const fuzzy = require('./fuzzy.js');
52
53
  const { fmtTokens, fmtEur, fmtElapsed } = require('./format.js');
53
54
  const { editPreview } = require('./diff.js');
@@ -1524,6 +1525,59 @@ async function runSession(host) {
1524
1525
  return 0;
1525
1526
  };
1526
1527
 
1528
+ /**
1529
+ * Collect the key a just-picked model needs, when it needs one, and store it
1530
+ * where EVERY host reads it.
1531
+ *
1532
+ * Requirement this exists for: picking a model that has no credential on this
1533
+ * machine must ask for the key there and then, and the answer must be durable
1534
+ * — not a shell export that dies with the terminal, and not a file only this
1535
+ * host knows about. `models.modelKeyPlan` answers "does this row need one?"
1536
+ * through the shared `client/env-file.js` the desktop engine also loads, so
1537
+ * the variable name here and the variable name there cannot drift; that drift
1538
+ * is how the same account ended up holding two private copies of one provider
1539
+ * key and looking unconfigured in whichever host it did not hold.
1540
+ *
1541
+ * Three outcomes, all reported in the transcript rather than swallowed:
1542
+ * stored, already present, or skipped (the row keeps its pin and will fail
1543
+ * with the provider's own error until a key arrives — never a silent no-op).
1544
+ */
1545
+ const collectKeyFor = async (chosen) => {
1546
+ const plan = models.modelKeyPlan(chosen, {
1547
+ // Never throws: an injected engine may carry no provider store, and a
1548
+ // missing store must read as "no key" rather than break the picker.
1549
+ accountConfigured: host.accountConfigured ? !!host.accountConfigured() : false,
1550
+ hasStored: chosen.provider && host.hasProviderKey ? !!host.hasProviderKey(chosen.provider) : false,
1551
+ });
1552
+ if (!plan.needed) {
1553
+ // Quiet on purpose: the key is already somewhere both hosts look, and a
1554
+ // note per pick would be noise on the common path.
1555
+ return;
1556
+ }
1557
+ let c = null;
1558
+ try { c = host.makeCommandContext(); } catch { c = null; }
1559
+ if (!c || typeof c.readSecret !== 'function') {
1560
+ note(`${chosen.id} has no key: ${plan.why}. Set ${plan.env} and pick it again.`);
1561
+ return;
1562
+ }
1563
+ const label = plan.pooled ? 'AEGIS account key' : `${plan.provider} key`;
1564
+ const key = String(
1565
+ (await c.readSecret(`${label} → ${plan.env} (kept off screen, Enter to skip): `)) || ''
1566
+ ).trim();
1567
+ if (!key) {
1568
+ note(`no key given — ${plan.env} is still unset, so ${chosen.id} will fail until it is.`);
1569
+ return;
1570
+ }
1571
+ const res = models.storeModelKey(chosen, key);
1572
+ if (!res.ok) {
1573
+ note(`could not save the key: ${res.error || 'unknown error'}`);
1574
+ return;
1575
+ }
1576
+ note(res.changed
1577
+ ? `${plan.env} saved to ${res.file} (0600) — both hosts read that file; nothing to export.`
1578
+ : `${plan.env} was already set in ${res.file}.`);
1579
+ };
1580
+
1527
1581
  const handleOverlayKey = async (key) => {
1528
1582
  const type = overlay.type;
1529
1583
  if (key.name === KEY.ESC || key.name === KEY.CTRL_C) {
@@ -1576,10 +1630,20 @@ async function runSession(host) {
1576
1630
  if (type === 'model') {
1577
1631
  const chosen = (overlay.items || [])[overlay.sel || 0];
1578
1632
  overlay = null;
1633
+ render();
1579
1634
  if (chosen) {
1635
+ // A direct-provider (byok) row needs the class the id actually
1636
+ // belongs to before the pin can route anywhere.
1637
+ if (chosen.cls === 'byok' && ctx.modelClass !== 'byok') await dispatch('/class byok');
1580
1638
  ctx.model = chosen.id;
1581
- host.updateConfig({ model: chosen.id });
1582
- note(`model: ${chosen.id}`);
1639
+ host.updateConfig({ model: chosen.id, currentModelId: chosen.id, modelClass: ctx.modelClass });
1640
+ note(`model: ${chosen.id}${chosen.cls === 'byok' ? ' (byok)' : ''}`);
1641
+ // Then the key, if this row needs one this machine does not have —
1642
+ // collected here rather than as a warning to run some command
1643
+ // afterward. See collectKeyFor: the decision comes from the shared
1644
+ // env-file module, so the variable a key is written to is the same
1645
+ // one the desktop reads, instead of each host keeping a private copy.
1646
+ await collectKeyFor(chosen);
1583
1647
  }
1584
1648
  render();
1585
1649
  return;
package/src/commands.js CHANGED
@@ -68,6 +68,7 @@ const credentials = require('./credentials.js');
68
68
  const cloudsync = require('./cloudsync.js');
69
69
  const { maskKey, fmtTokens } = require('./format.js');
70
70
  const { pickerEntries } = require('./models.js');
71
+ const { resolveShared } = require('./sharedpaths.js');
71
72
  const { openUrl, URLS } = require('./system.js');
72
73
  const { sniffProject, buildAegisMd } = require('./init.js');
73
74
  const { upgradeAdvice, latestPublishedVersion } = require('./update.js');
@@ -241,6 +242,58 @@ async function loadModels(c) {
241
242
  }
242
243
  }
243
244
 
245
+ /**
246
+ * The full model list across BOTH classes, for the /model picker: the pooled
247
+ * Nexus entry plus every provider id this machine can relay directly (BYOK),
248
+ * each tagged with the class ENTER should apply the pin under.
249
+ *
250
+ * Before this, the picker was class-scoped: opening it on the default 'aegis'
251
+ * class showed the single collapsed Nexus row, and reaching any of the real
252
+ * per-provider models meant already knowing to run `/class byok` first — the
253
+ * BYOK half of the catalog was correct but undiscoverable. Building one merged
254
+ * list here (rather than in two places) keeps the interactive picker and the
255
+ * `/model list` panel from disagreeing about what "the full list" is.
256
+ */
257
+ async function mergedPickerModels(c) {
258
+ const live = (c.ctx && c.ctx.modelClass) || 'aegis';
259
+ const aegis = pickerEntries(await loadModelsFor(c, 'aegis', live)).map((m) => ({ ...m, cls: 'aegis' }));
260
+ const byok = pickerEntries(await loadModelsFor(c, 'byok', live)).map((m) => ({ ...m, cls: 'byok' }));
261
+ return [...aegis, ...byok];
262
+ }
263
+
264
+ /**
265
+ * One class's catalog, read through whichever loader this host has.
266
+ *
267
+ * `c.listModelsFor(cls)` is the per-class loader app.js provides, and it is
268
+ * preferred because /model is class-scoped: reading the live class's own list
269
+ * is what stops a pin from being validated (and a row from being offered)
270
+ * against a class the next turn will not use.
271
+ *
272
+ * The fallback is not decoration. `loadModels()` is the loader every host has
273
+ * had since the context existed — including hosts and test doubles that predate
274
+ * the per-class one — so when it is the only loader present, the picker is
275
+ * populated from it for the class the session is actually on, and the other
276
+ * class yields nothing rather than a duplicated list. Skipping the fallback is
277
+ * how `/model` renders an empty picker against a healthy account: the list is
278
+ * asked for through a method the host does not have, the miss is swallowed, and
279
+ * "no models advertised" is what the user is told (§P in another guise).
280
+ */
281
+ async function loadModelsFor(c, cls, live) {
282
+ if (typeof c.listModelsFor === 'function') {
283
+ try {
284
+ return (await c.listModelsFor(cls)) || [];
285
+ } catch {
286
+ return [];
287
+ }
288
+ }
289
+ if (cls !== live || typeof c.loadModels !== 'function') return [];
290
+ try {
291
+ return (await c.loadModels()) || [];
292
+ } catch {
293
+ return [];
294
+ }
295
+ }
296
+
244
297
  /**
245
298
  * The ÆGIS LLM routes are gated on the pooled brain being reachable — exactly
246
299
  * as the reference hides its ÆGIS routes when the backend is absent. `hidden`
@@ -255,6 +308,20 @@ const cloudReady = () => credentials.hasApiKey();
255
308
 
256
309
  // ── BYOK provider catalog ────────────────────────────────────────────────────
257
310
 
311
+ /**
312
+ * The BYOK model additions (`client/byok-catalog.js`) — the ids the server's
313
+ * catalog does not name but the vendor serves and the relay forwards, resolved
314
+ * by EXISTENCE through `resolveShared`, never with a fallback copy here.
315
+ *
316
+ * `/byok` reads the server directly rather than through the engine, so without
317
+ * this the CLI's own listing would show fewer models than the CLI's own model
318
+ * picker for the same account — two screens in one program disagreeing, which
319
+ * is the failure this file's sibling brain-catalog module exists to end. The
320
+ * desktop requires the same file from `desktop/lib/local/engine.js`, so the
321
+ * terminal and the window cannot drift either.
322
+ */
323
+ const { withByokAdditions } = require(resolveShared(path.join('client', 'byok-catalog.js')));
324
+
258
325
  /**
259
326
  * The server's BYOK provider catalog, or null when it cannot be reached.
260
327
  *
@@ -269,7 +336,7 @@ async function byokCatalog(client) {
269
336
  if (!client || typeof client.byokProviders !== 'function') return null;
270
337
  try {
271
338
  const data = await client.byokProviders();
272
- const providers = (data && data.providers) || [];
339
+ const providers = withByokAdditions((data && data.providers) || []);
273
340
  return providers.length ? providers : null;
274
341
  } catch {
275
342
  return null;
@@ -930,31 +997,24 @@ const COMMANDS = [
930
997
  const byok = cls === 'byok';
931
998
  if (!id) {
932
999
  note(c, `model: ${c.ctx.model || 'server default'}`);
933
- // Populate the picker for the LIVE class first. The list is the return
934
- // value, not `c.state().models`: that field is rebuilt from a cache the
935
- // current class may not populate, so reading it rendered an empty
936
- // picker on a class whose models are local and always readable.
937
- //
938
- // `pickerEntries` is the same filter app.js's buildState() applies to
939
- // that field, and it has to be applied here for the same reason it is
940
- // applied there: the loader returns the catalog — aliases included —
941
- // and an alias row is not a pinnable entry, so listing it puts a
942
- // duplicate in the picker that pins the id it points at.
943
- const models = pickerEntries(await loadModels(c));
1000
+ // The full list across BOTH classes — pooled Nexus plus every
1001
+ // provider this machine can relay directly — not just the class the
1002
+ // session happens to be on. Selecting one of the direct-provider rows
1003
+ // (below) switches to byok and, if this machine holds no key for its
1004
+ // provider yet, prompts for one right there — see the picker's ENTER
1005
+ // handler in chatflow.js.
1006
+ const models = await mergedPickerModels(c);
944
1007
  if (!models.length) {
945
1008
  // Say why, and what unblocks it: an unreachable catalog is almost
946
1009
  // always a missing key or no network, and "no models advertised"
947
1010
  // read as "the platform has none" rather than "this client could not
948
- // ask". On byok "no models" means this machine simply holds no
949
- // provider key yet, which is exactly what /byok-key fixes.
950
- note(c, byok
951
- ? 'No relayable models — this machine holds no provider key yet. Save one with /byok-key <provider>, then retry /model.'
952
- : c.state().online
953
- ? 'Could not read the model catalog (offline, or the server refused it) — /models retries.'
954
- : // The key travels in the environment only (client/aegis.js reads
955
- // AEGIS_API_KEY); /login is an unavailable command here, so
956
- // pointing at it would send the user to a refusal.
957
- `No API key set, so the model catalog cannot be read — export AEGIS_API_KEY (free key: ${signupUrl('model_blocked')}), then retry /model.`);
1011
+ // ask".
1012
+ note(c, c.state().online
1013
+ ? 'Could not read the model catalog (offline, or the server refused it) — /models retries.'
1014
+ : // The key travels in the environment only (client/aegis.js reads
1015
+ // AEGIS_API_KEY); /login is an unavailable command here, so
1016
+ // pointing at it would send the user to a refusal.
1017
+ `No API key set, so the model catalog cannot be read — export AEGIS_API_KEY (free key: ${signupUrl('model_blocked')}), then retry /model.`);
958
1018
  c.render();
959
1019
  return true;
960
1020
  }
@@ -968,18 +1028,17 @@ const COMMANDS = [
968
1028
  ? `pinned model "${c.ctx.model}" is not one this machine can relay — pick from the list below.`
969
1029
  : `pinned model "${c.ctx.model}" is not in the catalog — the pool will answer with its own default; pick one below.`);
970
1030
  }
971
- note(c, byok
972
- ? '/model <id> pins one for this session; /models lists what this machine can relay.'
973
- : '/model <id> pins one for this session; /models lists what the server advertises.');
974
- // `cls` rides on the overlay so the picker's title and subtitle render
975
- // for the class that opened it, even if /class moves while it is open.
1031
+ note(c, '/model <id> pins one for this session; picking a direct-provider row prompts for its key if this machine has none saved.');
1032
+ // `cls` rides on the overlay so the picker's subtitle renders for the
1033
+ // class the session is on right now; each row also carries its own
1034
+ // `cls` so ENTER knows which class a pick switches to.
976
1035
  c.openOverlay({ type: 'model', items: models, sel: 0, current: c.ctx.model, cls });
977
1036
  return true;
978
1037
  }
979
1038
  if (id === 'list') {
980
- // Filtered like the picker above: the panel lists what can be pinned,
981
- // so it cannot carry the alias rows the loader returns alongside them.
982
- const models = pickerEntries(await loadModels(c));
1039
+ // Same merged list as the picker above, so the static panel and the
1040
+ // interactive one never disagree about what "the full list" is.
1041
+ const models = await mergedPickerModels(c);
983
1042
  if (!models.length) note(c, 'No pinnable models advertised — /models lists the server\'s ids.');
984
1043
  else panel(c, panels.buildModelList(c.ctx.model, models, c.ctx));
985
1044
  c.render();
package/src/models.js CHANGED
@@ -11,16 +11,53 @@
11
11
  * fallback list: an offline client offers nothing rather than a model name that
12
12
  * would silently route somewhere else.
13
13
  *
14
- * The platform lists per-provider ids (`deepseek`, `anthropic`, `groq`, …) plus
15
- * the pooled-brain tiers. The desktop host collapsed all of that to a single
16
- * "Nexus" entry because its dropdown *is* the model choice and surfacing
17
- * per-provider routing invites pinning a provider that happens to be dead right
18
- * now (see desktop/lib/local/engine.js selectBrainEntry). This host keeps every
19
- * distinct id — a CLI user pinning `deepseek` explicitly is a legitimate
20
- * request — but drops the pure-alias duplicates the server itself marks
21
- * `hidden: true, alias_of: "<id>"` (`aegis-brain`, `nexus-brain-smart`, …),
22
- * which are the same model advertised under another spelling.
14
+ * WHAT IS OFFERED on the AEGIS (pooled) class is Nexus, and only Nexus.
15
+ *
16
+ * This module briefly offered the full catalog — every per-provider id
17
+ * (`deepseek`, `anthropic`, `groq`, …) the pooled payload lists alongside the
18
+ * brain tiers — on the theory that a funded account should be able to pin the
19
+ * exact model it pays for instead of one collapsed "Nexus" row. That widened
20
+ * the picker correctly for BYOK (a payload with no brain tier, where a
21
+ * per-provider id genuinely is what gets called, with the caller's own key)
22
+ * but was the wrong call for the pooled class specifically: Niklas's explicit
23
+ * instruction is that AEGIS Cloud offers Nexus only — no per-provider pin —
24
+ * so `pickerEntries` is back on `filterAegisCatalog`, the shared rule's
25
+ * single-row collapse, for this class.
26
+ *
27
+ * The rule lives in `client/brain-catalog.js`, shared with the desktop through
28
+ * the same `resolveShared` path, so the collapse cannot drift between hosts —
29
+ * that one-copy guarantee is the part of the earlier change that stays.
30
+ *
31
+ * A payload with no brain tier at all (the BYOK listing, which is per-provider
32
+ * models) never had a brain row to collapse, and stays offered in full: BYOK
33
+ * is unaffected by this — see `filterAegisCatalog`'s own doc for why an empty
34
+ * collapse result there falls through to the full distinct list.
35
+ *
36
+ * Offering is still not the same as accepting: `/model deepseek` still
37
+ * validates against the full catalog through `findModel`/`catalogIds`, so a
38
+ * scripted pin is not refused — only the interactive picker is narrowed.
39
+ */
40
+
41
+ const path = require('node:path');
42
+
43
+ const { resolveShared } = require('./sharedpaths.js');
44
+
45
+ /**
46
+ * The shared selection rule — required at load time and by EXISTENCE, never
47
+ * with a fallback copy here: a silently divergent local implementation is the
48
+ * precise defect this file was changed to remove. A missing module is a loud
49
+ * error naming the file, which is what `resolveShared` throws.
23
50
  */
51
+ const { filterAegisCatalog } = require(resolveShared(path.join('client', 'brain-catalog.js')));
52
+
53
+ /**
54
+ * The shared env-file module, required through the same `resolveShared` path the
55
+ * desktop uses, for the same reason: the file the key is WRITTEN to must be the
56
+ * file both hosts READ from, and a second implementation of "where does a key
57
+ * go" is exactly how the CLI and the desktop ended up each holding a private
58
+ * copy of the same provider key.
59
+ */
60
+ const envFile = require(resolveShared(path.join('client', 'env-file.js')));
24
61
 
25
62
  /** A pinned id of `null` means "no pin — let the pool choose" (the server's own default). */
26
63
  const NO_PIN = null;
@@ -88,13 +125,29 @@ function normalizeModelCatalog(raw) {
88
125
  }
89
126
 
90
127
  /**
91
- * The entries the picker and `/models` offer: every distinct advertised model,
92
- * minus the alias duplicates — unless the catalog is *only* aliases, in which
93
- * case the aliases are all the server advertises and are offered rather than
94
- * leaving the user with an empty list.
128
+ * The entries the picker and `/models` offer.
129
+ *
130
+ * The selection itself is not decided here — it is `filterAegisCatalog` in
131
+ * `client/brain-catalog.js`, which the desktop requires through the same
132
+ * `resolveShared` path (and its own staged `vendor/` copy). Two hosts, one
133
+ * function: that is the part that must not be re-implemented, and the reason
134
+ * this is a thin call rather than a second copy of the rule.
135
+ *
136
+ * A payload naming a brain tier (the AEGIS/pooled catalog) collapses to that
137
+ * one row, labelled Nexus — never returns empty — so the branch below never
138
+ * reaches the fallback for it. A payload with no brain tier (BYOK, per-provider
139
+ * models with no pooled fan-out to collapse) is what the fallback is for: every
140
+ * distinct, non-alias entry, offered in full.
141
+ *
142
+ * Re-normalised afterwards so renderers keep the `label`/`note`/`id` columns
143
+ * they already expect, and so the brain's cost shape still reaches the picker's
144
+ * right-hand column. The alias fallbacks stay for a payload whose entries are
145
+ * bare strings or survive as pure aliases.
95
146
  */
96
147
  function pickerEntries(catalog) {
97
148
  const all = Array.isArray(catalog) ? catalog.filter(Boolean) : [];
149
+ const offered = filterAegisCatalog(all).map(normalizeModel).filter(Boolean);
150
+ if (offered.length) return offered;
98
151
  const distinct = all.filter((m) => !m.aliasOf);
99
152
  return distinct.length ? distinct : all;
100
153
  }
@@ -116,6 +169,99 @@ function catalogIds(catalog) {
116
169
  return new Set((Array.isArray(catalog) ? catalog : []).map((m) => String((m && m.id) || '').toLowerCase()).filter(Boolean));
117
170
  }
118
171
 
172
+ /**
173
+ * What key a catalog entry needs, and whether a DURABLE copy already exists —
174
+ * the question the model picker asks before it may send a turn on that id.
175
+ *
176
+ * Picking a model is the moment the answer matters: the turn goes out
177
+ * immediately, so a missing key has to be collected HERE, and stored where both
178
+ * hosts look (`~/.aegiscode/.env`), or the user types the same key twice — once
179
+ * in the terminal and once in the desktop — which is the defect this exists to
180
+ * end.
181
+ *
182
+ * `keyStatus().inFile` is the half that decides it, not `.present`. A key
183
+ * exported in the shell belongs to the process that launched this host: it is
184
+ * gone next session and invisible to the desktop, so "present" is not "stored".
185
+ *
186
+ * Two classes are exempt, and neither exemption is a heuristic:
187
+ *
188
+ * - the POOLED class, when the account is already signed in. Its credential is
189
+ * the AEGIS account key, which `aegiscode login` also keeps in
190
+ * credentials.json (client/credentials.js resolves that FIRST), a file both
191
+ * hosts share. Prompting for it on every pooled pick would be asking for a
192
+ * key the machine demonstrably has, so `accountConfigured` short-circuits.
193
+ * - a BYOK provider whose key is already in the provider store
194
+ * (`byok:<provider>`, engine.js byokNamespace — the rows the desktop's
195
+ * Provider settings write), passed in as `hasStored`.
196
+ *
197
+ * @param {object} entry a picker row ({id, cls})
198
+ * @param {object} [o]
199
+ * @param {boolean} [o.accountConfigured] the account key resolves somewhere
200
+ * @param {boolean} [o.hasStored] the provider key is already in the store
201
+ * @returns {{needed:boolean, env:string, provider:string, pooled:boolean,
202
+ * status:object|null, why:string}}
203
+ */
204
+ function modelKeyPlan(entry, o = {}) {
205
+ const id = (entry && entry.id) || '';
206
+ const plan = envFile.keyForModelId(id, entry && entry.cls);
207
+ if (!plan.env) {
208
+ // No id, no key to ask for. Never prompt on a row we cannot name a variable
209
+ // for — an unanswerable prompt is worse than a turn that 400s with the id.
210
+ return { needed: false, env: '', provider: '', pooled: plan.pooled, status: null, why: 'this id has no key variable' };
211
+ }
212
+ const status = envFile.keyStatus(plan.env);
213
+ if (plan.pooled) {
214
+ const needed = !status.present && !o.accountConfigured;
215
+ return {
216
+ needed,
217
+ env: plan.env,
218
+ provider: '',
219
+ pooled: true,
220
+ status,
221
+ why: needed
222
+ ? `no ${plan.env} is set on this machine`
223
+ : `account key present (${o.accountConfigured && !status.present ? 'credentials.json' : status.source})`,
224
+ };
225
+ }
226
+ const needed = !status.inFile && !o.hasStored;
227
+ return {
228
+ needed,
229
+ env: plan.env,
230
+ provider: plan.provider,
231
+ pooled: false,
232
+ status,
233
+ why: needed
234
+ ? `no ${plan.env} is stored for provider "${plan.provider}"`
235
+ : `${plan.env} is already stored (${!status.inFile ? 'provider store' : status.source})`,
236
+ };
237
+ }
238
+
239
+ /**
240
+ * Store a key collected at the picker, in the one file every host reads.
241
+ *
242
+ * Returns `setEnvValue`'s result plus the resolved variable name, so a caller
243
+ * can report WHERE the key went without re-deriving it (and re-deriving it is
244
+ * how the two hosts would end up disagreeing about the name).
245
+ *
246
+ * @param {object} entry the row the key was collected for
247
+ * @param {string} key the secret
248
+ * @returns {{ok:boolean, file:string, changed:boolean, error:string,
249
+ * env:string, provider:string, pooled:boolean}}
250
+ */
251
+ function storeModelKey(entry, key, o = {}) {
252
+ const plan = envFile.keyForModelId(entry && entry.id, entry && entry.cls);
253
+ if (!plan.env) {
254
+ return { ok: false, file: '', changed: false, error: `cannot name a key variable for "${(entry && entry.id) || ''}"`, env: '', provider: '', pooled: plan.pooled };
255
+ }
256
+ const res = envFile.setEnvValue(plan.env, key, o);
257
+ return { ...res, env: plan.env, provider: plan.provider, pooled: plan.pooled };
258
+ }
259
+
260
+ /** The env var name a key for `entry` belongs in ('' when there is none). */
261
+ function keyVarForModel(entry) {
262
+ return envFile.keyForModelId(entry && entry.id, entry && entry.cls).env;
263
+ }
264
+
119
265
  module.exports = {
120
266
  NO_PIN,
121
267
  ID_NOTES,
@@ -124,4 +270,7 @@ module.exports = {
124
270
  pickerEntries,
125
271
  findModel,
126
272
  catalogIds,
273
+ modelKeyPlan,
274
+ storeModelKey,
275
+ keyVarForModel,
127
276
  };
package/src/overlays.js CHANGED
@@ -152,22 +152,38 @@ function renderPalette(commands, state = {}, width = 80, height = 24) {
152
152
  */
153
153
  function renderModelPicker(models, sel = 0, width = 80, height = 24, current = null, cls = null, classLabel = null) {
154
154
  const lines = [];
155
- const byok = cls === 'byok';
156
155
  const label = typeof classLabel === 'function' && cls ? classLabel(cls) : null;
157
156
  lines.push(blank(width));
158
157
  lines.push([
159
158
  span('', ' '), span(C.white + BOLD, 'Select model'), span(BOLD_OFF, ''),
160
- ...(label ? [span(C.gray, ` — ${label}`)] : []),
159
+ ...(label ? [span(C.gray, ` — running on ${label}`)] : []),
161
160
  ]);
162
161
  lines.push([span('', ' '), span(C.gray, 'Switch between models. Your pick becomes the default for new sessions.')]);
163
162
  lines.push([
164
163
  span('', ' '),
165
- span(C.gray, byok
166
- ? 'Add one with /byok-key <provider> — /models lists what this machine can relay.'
167
- : 'Manage the list with /model add|remove — /model <id> switches directly.'),
164
+ // The list mixes both classes: Nexus runs pooled (your AEGIS account
165
+ // pays); every other row relays through your own provider key, and
166
+ // picking one prompts for that key right here if this machine has none
167
+ // saved yet — no need to run /byok-key first.
168
+ span(C.gray, 'Nexus is pooled; any other row prompts for its provider key on pick.'),
168
169
  ]);
169
170
  lines.push(blank(width));
170
- for (let i = 0; i < models.length; i++) {
171
+ // The list is the FULL catalog now (models.js pickerEntries), which is more
172
+ // rows than any terminal has: ~40 ids against the 16 a 24-row window has left
173
+ // once the title, subtitle and hint are paid for. Without a window the
174
+ // selected row walked off the bottom of the frame while `sel` kept moving, so
175
+ // arrow-DOWN looked broken — the row WAS selected, just never painted.
176
+ //
177
+ // The window keeps the selection as close to the middle as it can, clamped so
178
+ // it never runs past either end, and states the number of hidden rows on the
179
+ // side they are hidden. Row format and widths are unchanged: this is the same
180
+ // line the un-windowed loop drew, over a slice of the list.
181
+ const rows = Math.max(1, (height || 24) - 8);
182
+ const count = models.length;
183
+ const start = count > rows ? Math.min(Math.max(0, sel - Math.floor(rows / 2)), count - rows) : 0;
184
+ const end = Math.min(count, start + rows);
185
+ if (start > 0) lines.push([span('', ' '), span(C.gray, `↑ ${start} more above`)]);
186
+ for (let i = start; i < end; i++) {
171
187
  const m = models[i] || {};
172
188
  const label = m.label || m.name || m.id || '';
173
189
  const active = i === sel;
@@ -177,6 +193,9 @@ function renderModelPicker(models, sel = 0, width = 80, height = 24, current = n
177
193
  const nameSpan = active ? span(C.lavender, label) : span(C.white, label);
178
194
  const mark = cur ? span(C.green, ' ' + GLYPH.check) : span('', '');
179
195
  const pad = ' '.repeat(Math.max(1, 22 - [...label].length));
196
+ // A byok row not yet configured on this machine gets a visible flag ahead
197
+ // of its note, so "needs a key" is legible without reading the whole line.
198
+ const flag = m.cls === 'byok' && !m.configured ? '[key needed] ' : '';
180
199
  lines.push([
181
200
  span('', ' '),
182
201
  left,
@@ -185,9 +204,10 @@ function renderModelPicker(models, sel = 0, width = 80, height = 24, current = n
185
204
  span('', ' '),
186
205
  nameSpan,
187
206
  mark,
188
- span(C.gray, pad + (m.note || m.model || '')),
207
+ span(C.gray, pad + flag + (m.note || m.model || '')),
189
208
  ]);
190
209
  }
210
+ if (end < count) lines.push([span('', ' '), span(C.gray, `↓ ${count - end} more below`)]);
191
211
  lines.push(blank(width));
192
212
  lines.push([span('', ' '), span(C.gray, `arrow keys to navigate ${GLYPH.bullet} enter to select ${GLYPH.bullet} esc to cancel`)]);
193
213
  return fit(lines, width);
package/src/panels.js CHANGED
@@ -460,14 +460,16 @@ function buildModelList(currentId, models, ctx = {}) {
460
460
  const t = themeOf(ctx);
461
461
  const list = Array.isArray(models) ? models : [];
462
462
  const cur0 = str(currentId);
463
- // Which class these rows belong to. On byok a row is `provider:model` (the
463
+ // Which class each row belongs to. On byok a row is `provider:model` (the
464
464
  // engine's listModels('byok') shape) and `model` is unset, so the third
465
465
  // column would otherwise print "(default)" down the whole panel; the row's
466
466
  // `note` is what actually tells the user whether this machine holds the key.
467
- // The usage line follows the class too: /model add|remove is refused by this
468
- // build, and on byok the list is not a stored list at all — it is a function
469
- // of which provider keys exist, so the command that changes it is /byok-key.
470
- const byok = ctx.modelClass === 'byok';
467
+ // A merged list (both classes at once, e.g. the /model picker's full list)
468
+ // tags each row with its own `cls`, checked first so an aegis row and a byok
469
+ // row in the same panel each render with the format that fits its shape;
470
+ // `ctx.modelClass` is the fallback for a single-class list with no per-row tag.
471
+ const byokRow = (m) => (m.cls ? m.cls === 'byok' : ctx.modelClass === 'byok');
472
+ const anyByok = list.some(byokRow);
471
473
  const lines = [];
472
474
  lines.push([span(t.gold + BOLD, 'Models'), span(BOLD_OFF, '')]);
473
475
  lines.push([span(t.gray, '─'.repeat(30))]);
@@ -477,7 +479,7 @@ function buildModelList(currentId, models, ctx = {}) {
477
479
  const cur = idv !== '' && idv === cur0;
478
480
  const id = (cur ? '▶ ' : ' ') + idv;
479
481
  const name = str(m.name || m.label || m.model);
480
- const model = byok ? str(m.note) || str(m.model) : str(m.model) || '(default)';
482
+ const model = byokRow(m) ? str(m.note) || str(m.model) : str(m.model) || '(default)';
481
483
  lines.push([
482
484
  span(t.white, id), span('', ' '.repeat(Math.max(1, 26 - [...id].length))),
483
485
  span(t.gray, name), span('', ' '.repeat(Math.max(1, 22 - [...name].length))),
@@ -487,7 +489,7 @@ function buildModelList(currentId, models, ctx = {}) {
487
489
  if (!list.length) lines.push([span('', ' '), span(t.gray, '(no models configured)')]);
488
490
  lines.push([span('', '')]);
489
491
  lines.push([
490
- span(t.gray, byok
492
+ span(t.gray, anyByok
491
493
  ? 'Switch: /model <id> · Add a provider key: /byok-key <provider> · Run on it: /class byok'
492
494
  : 'Switch: /model <id> · Add: /model add <id> <name> <model> <baseURL> [apiKey] · Remove: /model remove <id>'),
493
495
  ]);
package/src/theme.js CHANGED
@@ -15,14 +15,15 @@
15
15
  * What DOES change per terminal is how those triples reach the screen:
16
16
  *
17
17
  * · `RGB()`/`BG()` go through `caps.rgb()/caps.bg()`, which emit 24-bit SGR,
18
- * the 256-colour cube, the 16 ANSI slots, or nothing at all — decided by the
19
- * terminal, not by us. On a legacy Windows console or `TERM=linux` the UI
20
- * now paints in colours that console can actually show, instead of emitting
21
- * truecolor escapes it renders as literal text or dithers unpredictably.
22
- * · `glyphsFor()` is a function of the resolved capabilities, so PowerShell in
23
- * Windows Terminal gets the same ❯ ⎿ ✻ ✦ set as zsh, and only a terminal
24
- * that genuinely cannot draw them (legacy console, `TERM=dumb`, a non-UTF-8
25
- * locale, `AEGIS_ART=ascii`) gets the ASCII stand-ins.
18
+ * the 256-colour cube, the 16 ANSI slots, or nothing at all. Truecolor is
19
+ * the default on every platform, because the terminals we ship to all pass
20
+ * 24-bit SGR through and a terminal that cannot downsamples it itself —
21
+ * which is the correct authority for the decision. Narrowing the palette is
22
+ * an explicit request (`AEGIS_COLOR=1|2`, `FORCE_COLOR`, `NO_COLOR`,
23
+ * `AEGIS_FORCE_TRUECOLOR=0`), never an inference from `TERM` or the OS.
24
+ * · `glyphsFor()` is a function of the resolved capabilities, so every host
25
+ * gets the same ❯ ⎿ ✻ ✦ set; the ASCII stand-ins appear only when the user
26
+ * asks for them (`AEGIS_ART=ascii`, `--ascii`).
26
27
  *
27
28
  * Both are re-materialised when the capabilities change (`onCapsChange`), so
28
29
  * `aegiscode --ascii`, `--no-color` and the `/terminal` command take effect on
@@ -284,25 +285,26 @@ function diffOf(ctx) {
284
285
  * A few of the reference's glyphs are missing from some terminal fonts
285
286
  * (⎿ U+23BF, ⏸ U+23F8, ✔ U+2714, ▸ U+25B8) or render as double-width emoji
286
287
  * (✦ U+2726, ✻/✢/✽/✶), which breaks row alignment exactly like the welcome art.
287
- * The three capability classes in `caps.js` decide the set:
288
+ * The capability classes in `caps.js` decide the set, and the host is not one of
289
+ * them — see the policy at the top of that file:
288
290
  *
289
- * · `glyphs: 'ascii'` — no Unicode claim at all: legacy Windows console,
290
- * `TERM=dumb`, a non-UTF-8 locale, `AEGIS_ART=ascii`. Every mark becomes a
291
- * single-column ASCII stand-in, so the layout is identical but nothing is
292
- * mis-rendered by a font that lacks the glyph.
293
- * · `face: 'edges'` — the block palette survives but the quartile edges
294
- * and the typographic marks (⎿, ⏸, ✔) do not (Apple fonts, older Windows
295
- * fonts). Only those are swapped.
296
- * · native — the reference's own set, on any terminal that can
297
- * draw it: Windows Terminal, VS Code, iTerm2, WezTerm, kitty, Ghostty,
298
- * Alacritty, GNOME Terminal, xterm, zsh on Linux/macOS.
291
+ * · `glyphs: 'ascii'` — no Unicode claim at all, requested with
292
+ * `AEGIS_ART=ascii` / `--ascii`. Every mark becomes a single-column ASCII
293
+ * stand-in, so the layout is identical but nothing is mis-rendered by a font
294
+ * that lacks the glyph.
295
+ * · `face: 'edges'` — the quartile edges and the typographic marks (⎿, ⏸,
296
+ * ✔) are swapped; reachable today only through the ASCII pass, and kept
297
+ * because `AEGIS_ART=unicode` on a font without the edges must be
298
+ * expressible.
299
+ * · native — the default everywhere: the reference's own set.
299
300
  *
300
301
  * `star` is NOT restated here: it is resolved through `art.js`'s stencil, the
301
302
  * single source of truth for the mark's runes, so the glyph table and the art
302
303
  * can never disagree about the same character.
303
304
  *
304
- * @param {string|object} [target] a `process.platform` name, or a caps object,
305
- * or nothing at all for the live process's resolved capabilities.
305
+ * @param {string|object} [target] a `process.platform` name (accepted for
306
+ * tests, ignored by the policy), or a caps object, or nothing at all for the
307
+ * live process's resolved capabilities.
306
308
  */
307
309
  function glyphsFor(target = null) {
308
310
  const c = !target