aegiscode 6.8.8 → 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/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "6.8.8",
4
+ "version": "6.8.9",
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",
@@ -62,6 +62,11 @@ const FILES = [
62
62
  // offer one account one list. Leaving it out stages a package whose every
63
63
  // model listing throws MODULE_NOT_FOUND before it can print a prompt.
64
64
  'client/brain-catalog.js',
65
+ // The BYOK model additions: the ids a provider relays but the server catalog
66
+ // does not name (the DeepSeek flash route). Required at load time by
67
+ // src/commands.js, so a package built without it throws MODULE_NOT_FOUND on
68
+ // the first picker or /byok listing instead of showing a short one.
69
+ 'client/byok-catalog.js',
65
70
  'mcp/tools.js',
66
71
  // The stdio MCP server itself — the process every editor config written by
67
72
  // `aegiscode mcp install` points at. Staging the registry without it ships a
package/src/app.js CHANGED
@@ -1232,6 +1232,19 @@ function createApp(options = {}) {
1232
1232
  // The one spelling of a provider's settings row, shared with the engine
1233
1233
  // that reads it (`byok:<provider>`) — see engine.js byokNamespace.
1234
1234
  byokNamespace: (p) => byokNamespace(p),
1235
+ // Whether a provider key is already on this machine — read through the
1236
+ // same `byok:<provider>` rows /byok-key writes, so the model picker's
1237
+ // "does this row need a key?" answer cannot disagree with the store that
1238
+ // would supply it. Never throws: an injected engine may carry no store.
1239
+ hasProviderKey: (p) => {
1240
+ const store = engine.settings || null;
1241
+ if (!store || !p || typeof store.rawKey !== 'function') return false;
1242
+ try { return !!store.rawKey(byokNamespace(p)); } catch { return false; }
1243
+ },
1244
+ // And whether the ACCOUNT key resolves anywhere (env → credentials.json).
1245
+ // A pooled row needs that key, not a provider one, and prompting for a
1246
+ // key the machine demonstrably holds is the bug this prevents.
1247
+ accountConfigured: () => !!credentials.keyStatus().configured,
1235
1248
  // The class surface: /class switches, /models lists for whichever class
1236
1249
  // is live (the frozen state carries the current one as c.ctx.modelClass).
1237
1250
  listModelsFor: (cls) => listModelsFor(cls),
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,25 +11,31 @@
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. What this host OFFERS for the pooled class is the
16
- * same single collapsed "Nexus" entry the desktop offers, and it is now the
17
- * same *code* that decides it: `client/brain-catalog.js`, required through
18
- * `src/sharedpaths.js` so a checkout and an installed package resolve it the
19
- * same way. Offering one entry is not accepting one entry — the server's ids
20
- * stay pinnable (`/model deepseek` still validates against the full catalog
21
- * through `findModel`/`catalogIds`), which is why the collapse lives here in
22
- * what we *show* rather than in what we *normalise*.
23
- *
24
- * This host used to keep every distinct id, on the argument that a CLI user
25
- * pinning `deepseek` explicitly is a legitimate request. It is — but that is
26
- * an argument about accepting ids, and it was implemented as an argument about
27
- * displaying them, so the same account saw seven models in the terminal and one
28
- * in the GUI. The two hosts disagreeing about one account was the actual bug.
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.
29
30
  *
30
31
  * A payload with no brain tier at all (the BYOK listing, which is per-provider
31
- * models) is not collapsed: `filterAegisCatalog` returns `[]` for it, and this
32
- * module then offers every distinct entry exactly as before.
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.
33
39
  */
34
40
 
35
41
  const path = require('node:path');
@@ -44,6 +50,15 @@ const { resolveShared } = require('./sharedpaths.js');
44
50
  */
45
51
  const { filterAegisCatalog } = require(resolveShared(path.join('client', 'brain-catalog.js')));
46
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')));
61
+
47
62
  /** A pinned id of `null` means "no pin — let the pool choose" (the server's own default). */
48
63
  const NO_PIN = null;
49
64
 
@@ -112,23 +127,27 @@ function normalizeModelCatalog(raw) {
112
127
  /**
113
128
  * The entries the picker and `/models` offer.
114
129
  *
115
- * Pooled class: exactly one entry, the collapsed brain, decided by the shared
116
- * rule (`client/brain-catalog.js`) so the terminal and the GUI cannot offer the
117
- * same account two different lists. The collapsed entry is re-normalised here
118
- * so renderers keep the `label`/`note` columns they already expect, and so the
119
- * brain's cost shape ("multi-call fan-out, sized by /effort") still reaches the
120
- * picker's right-hand column.
121
- *
122
- * BYOK class: no brain tier is present, `filterAegisCatalog` reports that with
123
- * `[]`, and every distinct advertised model is offered — minus the server's own
124
- * alias duplicates, unless the catalog is *only* aliases, in which case the
125
- * aliases are all the server advertises and are offered rather than leaving the
126
- * user with an empty list.
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.
127
146
  */
128
147
  function pickerEntries(catalog) {
129
148
  const all = Array.isArray(catalog) ? catalog.filter(Boolean) : [];
130
- const collapsed = filterAegisCatalog(all).map(normalizeModel).filter(Boolean);
131
- if (collapsed.length) return collapsed;
149
+ const offered = filterAegisCatalog(all).map(normalizeModel).filter(Boolean);
150
+ if (offered.length) return offered;
132
151
  const distinct = all.filter((m) => !m.aliasOf);
133
152
  return distinct.length ? distinct : all;
134
153
  }
@@ -150,6 +169,99 @@ function catalogIds(catalog) {
150
169
  return new Set((Array.isArray(catalog) ? catalog : []).map((m) => String((m && m.id) || '').toLowerCase()).filter(Boolean));
151
170
  }
152
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
+
153
265
  module.exports = {
154
266
  NO_PIN,
155
267
  ID_NOTES,
@@ -158,4 +270,7 @@ module.exports = {
158
270
  pickerEntries,
159
271
  findModel,
160
272
  catalogIds,
273
+ modelKeyPlan,
274
+ storeModelKey,
275
+ keyVarForModel,
161
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
  ]);