aegiscode 6.8.18 → 6.8.19

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.18",
4
+ "version": "6.8.19",
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
@@ -1762,6 +1762,22 @@ function createApp(options = {}) {
1762
1762
  TOOLS,
1763
1763
  ask: (prompt, o) => ask(prompt, o),
1764
1764
  makeCommandContext: () => makeCommandContext(),
1765
+ // The two stores that are NOT `~/.aegiscode/.env`, which the picker's key
1766
+ // queue has to consult before it may ask for a key that is already saved
1767
+ // somewhere both hosts read:
1768
+ // - `accountConfigured` — the AEGIS account key in credentials.json,
1769
+ // written by /key and by `aegiscode login`.
1770
+ // - `hasProviderKey(p)` — a `byok:<provider>` row, the store /byok-key
1771
+ // and the desktop's Provider settings share (engine.js byokNamespace).
1772
+ // Without these two the picker would re-prompt for a key the machine
1773
+ // demonstrably holds, which is how the same key got saved twice.
1774
+ accountConfigured: () => !!(credentials.keyStatus() || {}).configured,
1775
+ hasProviderKey: (provider) => {
1776
+ const store = engine.settings;
1777
+ if (!store || typeof store.get !== 'function' || !provider) return false;
1778
+ const row = (store.get(byokNamespace(provider)) || {});
1779
+ return !!String(row.key || '').trim();
1780
+ },
1765
1781
  loadModels: (o) => loadModels(o),
1766
1782
  buildState: () => buildState(),
1767
1783
  dispatchLine: (line, c) => handleLine(line, c),
@@ -2052,6 +2068,13 @@ function createApp(options = {}) {
2052
2068
  setCloudSync,
2053
2069
  cloudsync,
2054
2070
  keyStatus: () => credentials.keyStatus(),
2071
+ accountConfigured: () => !!(credentials.keyStatus() || {}).configured,
2072
+ hasProviderKey: (provider) => {
2073
+ const store = engine.settings;
2074
+ if (!store || typeof store.get !== 'function' || !provider) return false;
2075
+ const row = (store.get(byokNamespace(provider)) || {});
2076
+ return !!String(row.key || '').trim();
2077
+ },
2055
2078
  sessionId: () => commandCtx.sessionId,
2056
2079
  tokenSummary,
2057
2080
  resumeSession,
package/src/chatflow.js CHANGED
@@ -1548,39 +1548,66 @@ async function runSession(host) {
1548
1548
  * with the provider's own error until a key arrives — never a silent no-op).
1549
1549
  */
1550
1550
  const collectKeyFor = async (chosen) => {
1551
- const plan = models.modelKeyPlan(chosen, {
1551
+ // EVERY key this row needs, in ask order: the AEGIS account key first (the
1552
+ // pooled route's identity, and what reads the catalog at all), then the
1553
+ // VENDOR key the row is named after when this machine lacks one
1554
+ // (`deepseek` → DEEPSEEK_API_KEY). One prompt was not enough: a pooled row
1555
+ // named after a vendor is billed to the account, but the pool calls that
1556
+ // vendor, so an account key alone left the turn failing upstream with
1557
+ // nothing the user could act on — see models.js modelKeyQueue.
1558
+ //
1559
+ // Both facts about the stores that are NOT the env file are supplied here,
1560
+ // because only the host knows them: `accountConfigured` (credentials.json,
1561
+ // written by /key or `aegiscode login`) and `hasStoredFor` (the
1562
+ // `byok:<provider>` rows the provider store and the desktop's provider
1563
+ // settings share).
1564
+ const queue = models.modelKeyQueue(chosen, {
1552
1565
  // Never throws: an injected engine may carry no provider store, and a
1553
1566
  // missing store must read as "no key" rather than break the picker.
1554
1567
  accountConfigured: host.accountConfigured ? !!host.accountConfigured() : false,
1555
- hasStored: chosen.provider && host.hasProviderKey ? !!host.hasProviderKey(chosen.provider) : false,
1568
+ hasStoredFor: (vendor) => (host.hasProviderKey ? !!host.hasProviderKey(vendor) : false),
1556
1569
  });
1557
- if (!plan.needed) {
1558
- // Quiet on purpose: the key is already somewhere both hosts look, and a
1559
- // note per pick would be noise on the common path.
1570
+ if (!queue.length) {
1571
+ // Quiet on purpose: every key this row needs is already somewhere both
1572
+ // hosts look, and a note per pick would be noise on the common path.
1560
1573
  return;
1561
1574
  }
1562
1575
  let c = null;
1563
1576
  try { c = host.makeCommandContext(); } catch { c = null; }
1564
1577
  if (!c || typeof c.readSecret !== 'function') {
1565
- note(`${chosen.id} has no key: ${plan.why}. Set ${plan.env} and pick it again.`);
1578
+ // No way to ask where the user can answer: name every variable still
1579
+ // missing rather than only the last one, so one round of setup finishes
1580
+ // the job instead of leaving the second key to be discovered by failure.
1581
+ const missing = queue.map((s) => `${s.env}: ${s.why}`).join(' · ');
1582
+ note(`${chosen.id} has no key: ${missing}. Set the ones above and pick it again.`);
1566
1583
  return;
1567
1584
  }
1568
- const label = plan.pooled ? 'AEGIS account key' : `${plan.provider} key`;
1569
- const key = String(
1570
- (await c.readSecret(`${label} → ${plan.env} (kept off screen, Enter to skip): `)) || ''
1571
- ).trim();
1572
- if (!key) {
1573
- note(`no key given — ${plan.env} is still unset, so ${chosen.id} will fail until it is.`);
1574
- return;
1575
- }
1576
- const res = models.storeModelKey(chosen, key);
1577
- if (!res.ok) {
1578
- note(`could not save the key: ${res.error || 'unknown error'}`);
1579
- return;
1585
+ for (const step of queue) {
1586
+ // Pooled rows bill the account; a vendor step names its provider. The
1587
+ // label says WHICH key is wanted, because two prompts in a row for the
1588
+ // same row must not read as the same question asked twice.
1589
+ const label = step.role === 'account' ? 'AEGIS account key' : `${step.provider} key`;
1590
+ const key = String(
1591
+ (await c.readSecret(`${label} → ${step.env} (kept off screen, Enter to skip): `)) || ''
1592
+ ).trim();
1593
+ if (!key) {
1594
+ // Skipping one key must not abandon the rest: the vendor key is still
1595
+ // worth collecting for a row whose account key the user just pasted
1596
+ // elsewhere, and vice versa.
1597
+ note(`no key given — ${step.env} is still unset, so ${chosen.id} will fail until it is.`);
1598
+ continue;
1599
+ }
1600
+ // `env: step.env` is what makes a per-step store possible at all: the row
1601
+ // alone cannot say which of its two keys this value is for.
1602
+ const res = models.storeModelKey(chosen, key, { env: step.env });
1603
+ if (!res.ok) {
1604
+ note(`could not save the key: ${res.error || 'unknown error'}`);
1605
+ continue;
1606
+ }
1607
+ note(res.changed
1608
+ ? `${step.env} saved to ${res.file} (0600) — both hosts read that file; nothing to export.`
1609
+ : `${step.env} was already set in ${res.file}.`);
1580
1610
  }
1581
- note(res.changed
1582
- ? `${plan.env} saved to ${res.file} (0600) — both hosts read that file; nothing to export.`
1583
- : `${plan.env} was already set in ${res.file}.`);
1584
1611
  };
1585
1612
 
1586
1613
  const handleOverlayKey = async (key) => {
package/src/models.js CHANGED
@@ -11,27 +11,26 @@
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
- * WHAT IS OFFERED on the AEGIS (pooled) class is Nexus, and only Nexus.
14
+ * WHAT IS OFFERED on the AEGIS (pooled) class is the server's FULL catalog: the
15
+ * brain first, under its one name (Nexus), then every other model the account
16
+ * can pin.
15
17
  *
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.
18
+ * The single-Nexus-row collapse was shipped here and is now reverted, because
19
+ * the report it produced is exactly the defect that shape creates: "there are
20
+ * only 2 models left in models" — one version back the picker listed them all.
21
+ * Removing the choice was never the fix for the two hosts disagreeing about the
22
+ * brain's five spellings; `offerableCatalog` ends that disagreement by folding
23
+ * only the *aliases*, which is what this module now calls. A funded account can
24
+ * pin the deepseek or anthropic model it actually pays for instead of having
25
+ * one chosen for it, while `nexus-brain` still paints as one row and not five.
26
26
  *
27
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.
28
+ * the same `resolveShared` path, so the two hosts cannot drift — that one-copy
29
+ * guarantee is the part of the earlier change that stays.
30
30
  *
31
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.
32
+ * models) never had a brain row to collapse, and stays offered in full: BYOK is
33
+ * unaffected by this — see `offerableCatalog`'s own doc for the alias-only case.
35
34
  *
36
35
  * Offering is still not the same as accepting: `/model deepseek` still
37
36
  * validates against the full catalog through `findModel`/`catalogIds`, so a
@@ -48,7 +47,7 @@ const { resolveShared } = require('./sharedpaths.js');
48
47
  * precise defect this file was changed to remove. A missing module is a loud
49
48
  * error naming the file, which is what `resolveShared` throws.
50
49
  */
51
- const { filterAegisCatalog } = require(resolveShared(path.join('client', 'brain-catalog.js')));
50
+ const { offerableCatalog } = require(resolveShared(path.join('client', 'brain-catalog.js')));
52
51
 
53
52
  /**
54
53
  * The shared env-file module, required through the same `resolveShared` path the
@@ -97,10 +96,18 @@ function normalizeModel(entry) {
97
96
  id;
98
97
  // The picker's right-hand column: what this entry *is*. An alias says so —
99
98
  // otherwise a user reads five brain tiers and assumes five different models.
100
- const note = aliasOf
101
- ? `alias of ${aliasOf}`
102
- : ID_NOTES[id] || capabilities.join(', ');
103
- return {
99
+ //
100
+ // A CALLER's own note wins over the derived one, and that precedence is the
101
+ // fix for a real defect: `app.js` builds the BYOK rows with the note the
102
+ // renderers paint ('key on this machine' / 'no key — /byok-key openai') and
103
+ // then passes them through `pickerEntries` → here, which used to re-derive the
104
+ // note from `capabilities` — empty for a byok row — so every row's note became
105
+ // blank and the picker could not say which providers this machine is ready to
106
+ // call. A note someone deliberately set is information; the derived string is
107
+ // a default, and a default must never overwrite it.
108
+ const given = typeof m.note === 'string' && m.note.trim() ? m.note.trim() : '';
109
+ const note = given || (aliasOf ? `alias of ${aliasOf}` : ID_NOTES[id] || capabilities.join(', '));
110
+ const out = {
104
111
  id,
105
112
  label,
106
113
  note,
@@ -108,6 +115,20 @@ function normalizeModel(entry) {
108
115
  aliasOf,
109
116
  capabilities,
110
117
  };
118
+ // Pass-through fields this module does not own but must not eat. They are the
119
+ // byok half of the list's whole content:
120
+ // - `provider` — which provider's key the relay will ask for (`collectKeyFor`
121
+ // read it, and `/byok-key` addresses the row by it);
122
+ // - `configured` — whether that key is on this machine, which is what paints
123
+ // the `[key needed]` flag and what tells a user whether a pick will work;
124
+ // - `cls` — the class the row belongs to, which ENTER switches on.
125
+ // Dropping them (as this did) meant `m.configured` was `undefined` for every
126
+ // row, so the flag fired on rows that were fully configured and the list could
127
+ // not distinguish "ready" from "needs a key".
128
+ if (typeof m.provider === 'string' && m.provider.trim()) out.provider = m.provider.trim();
129
+ if (m.configured === true) out.configured = true;
130
+ if (typeof m.cls === 'string' && m.cls.trim()) out.cls = m.cls.trim();
131
+ return out;
111
132
  }
112
133
 
113
134
  /** Normalise a raw `/api/v1/models` payload (`{models: [...]}` or the array). */
@@ -127,26 +148,27 @@ function normalizeModelCatalog(raw) {
127
148
  /**
128
149
  * The entries the picker and `/models` offer.
129
150
  *
130
- * The selection itself is not decided here — it is `filterAegisCatalog` in
151
+ * The selection itself is not decided here — it is `offerableCatalog` in
131
152
  * `client/brain-catalog.js`, which the desktop requires through the same
132
153
  * `resolveShared` path (and its own staged `vendor/` copy). Two hosts, one
133
154
  * function: that is the part that must not be re-implemented, and the reason
134
155
  * this is a thin call rather than a second copy of the rule.
135
156
  *
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.
157
+ * `offerableCatalog` offers every id the payload advertises, with the brain's
158
+ * spellings folded into the one row labelled Nexus and listed first — so a
159
+ * catalog naming a brain tier no longer collapses to that row alone. The
160
+ * fallback below still covers a payload whose entries survive as bare strings
161
+ * or as aliases the shared rule dropped: an empty picker would tell the user
162
+ * there are no models when the server just named them, so a list of aliases is
163
+ * a better answer than nothing.
141
164
  *
142
165
  * Re-normalised afterwards so renderers keep the `label`/`note`/`id` columns
143
166
  * 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.
167
+ * right-hand column.
146
168
  */
147
169
  function pickerEntries(catalog) {
148
170
  const all = Array.isArray(catalog) ? catalog.filter(Boolean) : [];
149
- const offered = filterAegisCatalog(all).map(normalizeModel).filter(Boolean);
171
+ const offered = offerableCatalog(all).map(normalizeModel).filter(Boolean);
150
172
  if (offered.length) return offered;
151
173
  const distinct = all.filter((m) => !m.aliasOf);
152
174
  return distinct.length ? distinct : all;
@@ -236,6 +258,100 @@ function modelKeyPlan(entry, o = {}) {
236
258
  };
237
259
  }
238
260
 
261
+ /**
262
+ * EVERY key a just-picked model needs, in the order to ask for them.
263
+ *
264
+ * `modelKeyPlan` answers with the one credential the ROUTE needs and stops
265
+ * there. That is the wrong answer at the picker, and it is the defect the report
266
+ * "I picked deepseek and it still failed" names: a pooled row named after a
267
+ * vendor is billed to the AEGIS account, so the route's credential is
268
+ * `AEGIS_API_KEY` — but the pool calls `deepseek` with a provider key, and when
269
+ * this machine holds none, the turn fails at the pool with nothing the user can
270
+ * act on. One prompt was not enough, and the missing one was never offered.
271
+ *
272
+ * So the order is fixed and it is the order the two keys are actually needed in:
273
+ *
274
+ * 1. `AEGIS_API_KEY` — the account key. Nothing works without it: it is what
275
+ * authenticates the catalog read that listed the row at all, and it is the
276
+ * pooled route's identity. Asked first, and asked on every class, because
277
+ * a byok listing cannot be read without it either.
278
+ * 2. the VENDOR key for the row (`DEEPSEEK_API_KEY` for `deepseek` or
279
+ * `deepseek:…`) — what actually calls the model. Asked second, and only
280
+ * when the row names a vendor `client/env-file.js` knows a variable for:
281
+ * `nexus-brain` names none, so it produces no second step rather than an
282
+ * invented `NEXUS_API_KEY`.
283
+ *
284
+ * A step is emitted only when its key is genuinely MISSING on this machine —
285
+ * `keyStatus().inFile` for a durable copy, plus the caller's `accountConfigured`
286
+ * / `hasStoredFor` for the two stores that are not the env file
287
+ * (`credentials.json` for the account, `byok:<provider>` rows for a vendor, both
288
+ * written by the other host). An empty array means "nothing to ask for", which
289
+ * is the common case and must stay silent.
290
+ *
291
+ * @param {object} entry a picker row ({id, cls, provider?})
292
+ * @param {object} [o]
293
+ * @param {boolean} [o.accountConfigured] the account key resolves somewhere
294
+ * @param {(vendor:string)=>boolean} [o.hasStoredFor] that vendor's key is in
295
+ * the provider store
296
+ * @returns {Array<{env:string, provider:string, vendor:string, role:string,
297
+ * needed:boolean, status:object|null, why:string}>} in ask order
298
+ */
299
+ function modelKeyQueue(entry, o = {}) {
300
+ const id = (entry && entry.id) || '';
301
+ // No id at all: there is no row to make callable, so there is nothing to ask
302
+ // for. Checked on the ID and not on `plan.env`, because an empty id still
303
+ // derives a perfectly nameable variable (the account key) — the pooled branch
304
+ // of `keyForModelId` ignores the id — and prompting for the account key off a
305
+ // row that names no model is exactly the unanswerable prompt this refuses.
306
+ if (!String(id).trim()) return [];
307
+ const plan = envFile.keyForModelId(id, entry && entry.cls);
308
+ // A non-empty id that yields no variable cannot be asked about either: an
309
+ // unanswerable prompt is worse than a turn that 400s with the id in it.
310
+ if (!plan.env) return [];
311
+
312
+ const steps = [];
313
+ const account = envFile.keyStatus(envFile.ACCOUNT_ENV_VAR);
314
+ if (!account.present && !o.accountConfigured) {
315
+ steps.push({
316
+ env: envFile.ACCOUNT_ENV_VAR,
317
+ provider: '',
318
+ vendor: '',
319
+ role: 'account',
320
+ needed: true,
321
+ status: account,
322
+ why: `no ${envFile.ACCOUNT_ENV_VAR} is set on this machine`,
323
+ });
324
+ }
325
+
326
+ // The vendor the row names. For byok that is the id's own `<provider>` half;
327
+ // for a pooled id it is the vendor spelled into the id (`deepseek`), and it is
328
+ // the same variable either way — one key, one file, whichever class reads it.
329
+ const vendor = plan.vendor || '';
330
+ const vendorEnv = vendor ? envFile.envVarFor(vendor) : '';
331
+ const stored = vendor && typeof o.hasStoredFor === 'function' ? !!o.hasStoredFor(vendor) : false;
332
+ if (vendorEnv) {
333
+ const status = envFile.keyStatus(vendorEnv);
334
+ // `inFile` rather than `present` for the same reason as modelKeyPlan: a
335
+ // shell export belongs to this process, and the desktop — the other host
336
+ // that has to make this call — cannot see it. The provider store counts as
337
+ // stored (`hasStoredFor`), because that is the row the desktop writes.
338
+ if (!status.inFile && !stored) {
339
+ steps.push({
340
+ env: vendorEnv,
341
+ provider: vendor,
342
+ vendor,
343
+ role: 'provider',
344
+ needed: true,
345
+ status,
346
+ why: status.present
347
+ ? `${vendorEnv} is exported in this shell only — the desktop cannot see it`
348
+ : `no ${vendorEnv} is stored for provider "${vendor}"`,
349
+ });
350
+ }
351
+ }
352
+ return steps;
353
+ }
354
+
239
355
  /**
240
356
  * Store a key collected at the picker, in the one file every host reads.
241
357
  *
@@ -243,18 +359,34 @@ function modelKeyPlan(entry, o = {}) {
243
359
  * can report WHERE the key went without re-deriving it (and re-deriving it is
244
360
  * how the two hosts would end up disagreeing about the name).
245
361
  *
362
+ * `o.env` overrides the derived variable, and it is how a QUEUE step is stored:
363
+ * a pooled row has two keys (the account's and the vendor's), so the row alone
364
+ * cannot say which one this value is for — the step can. Without it the
365
+ * derivation is `keyForModelId`, which is the right answer for a single-key
366
+ * caller and unchanged.
367
+ *
246
368
  * @param {object} entry the row the key was collected for
247
369
  * @param {string} key the secret
370
+ * @param {object} [o] `setEnvValue` options; `env` names the variable to write
248
371
  * @returns {{ok:boolean, file:string, changed:boolean, error:string,
249
372
  * env:string, provider:string, pooled:boolean}}
250
373
  */
251
374
  function storeModelKey(entry, key, o = {}) {
252
375
  const plan = envFile.keyForModelId(entry && entry.id, entry && entry.cls);
253
- if (!plan.env) {
376
+ const env = String(o.env || '').trim() || plan.env;
377
+ if (!env) {
254
378
  return { ok: false, file: '', changed: false, error: `cannot name a key variable for "${(entry && entry.id) || ''}"`, env: '', provider: '', pooled: plan.pooled };
255
379
  }
256
- const res = envFile.setEnvValue(plan.env, key, o);
257
- return { ...res, env: plan.env, provider: plan.provider, pooled: plan.pooled };
380
+ const opts = { ...o };
381
+ delete opts.env;
382
+ const res = envFile.setEnvValue(env, key, opts);
383
+ // `pooled` describes the VARIABLE that was written, not the class of the row:
384
+ // the account key is the pooled route's credential wherever it is stored,
385
+ // while a vendor key written for a pooled row is still the user's own vendor
386
+ // key. Reading it off the row (as this once did) reported DEEPSEEK_API_KEY as
387
+ // pooled, which told the caller the pool held a key the user had just supplied.
388
+ const pooled = env === envFile.ACCOUNT_ENV_VAR;
389
+ return { ...res, env, provider: env === plan.env ? plan.provider : '', pooled };
258
390
  }
259
391
 
260
392
  /** The env var name a key for `entry` belongs in ('' when there is none). */
@@ -271,6 +403,7 @@ module.exports = {
271
403
  findModel,
272
404
  catalogIds,
273
405
  modelKeyPlan,
406
+ modelKeyQueue,
274
407
  storeModelKey,
275
408
  keyVarForModel,
276
409
  };
@@ -18,10 +18,18 @@
18
18
  *
19
19
  * Resolution order, first hit wins:
20
20
  *
21
- * 1. `AEGIS_API_KEY` — the environment, so CI and an explicit export keep
22
- * working and nothing written here can shadow them.
23
- * 2. `credentials.json` in the data dir, mode 0600. The writable store.
24
- * 3. `config.json`'s `aegiscloud.api_key` / `memory.token` — the shape an
21
+ * 1. `AEGIS_API_KEY` **exported by the launching shell** — so CI and an
22
+ * explicit export keep working.
23
+ * 2. `credentials.json` in the data dir, mode 0600. The writable store, and
24
+ * the record of a key the user deliberately saved (`aegiscode login`, the
25
+ * CLI's `/key`, the desktop's Settings pane).
26
+ * 3. `AEGIS_API_KEY` from `~/.aegiscode/.env` — the documented place to put a
27
+ * key, but a FALLBACK rather than a decision: no save stamp, shared by
28
+ * every host, hand-edited. Both rungs read the same variable, which is why
29
+ * `isFromEnvFile()` exists — without it a leftover line in that file
30
+ * outranked rung 2 forever and a freshly saved key was silently ignored
31
+ * while every host reported it as saved. See `resolveApiKey`.
32
+ * 4. `config.json`'s `aegiscloud.api_key` / `memory.token` — the shape an
25
33
  * earlier AEGIS CLI left in the same data dir. Read, never written, and
26
34
  * never deleted: it is another product's file and the user's key is in
27
35
  * it. When one is found it is *also* copied into credentials.json so the
@@ -189,21 +197,79 @@ function adoptLegacy(dir) {
189
197
  return { adopted: Object.keys(patch) };
190
198
  }
191
199
 
200
+ /**
201
+ * Was this environment value put there by `~/.aegiscode/.env`, rather than
202
+ * exported by the launching shell?
203
+ *
204
+ * The env object is passed through: provenance is a property of the object the
205
+ * value was loaded INTO, so a caller resolving from an injected `{ env }` (every
206
+ * test, and any host that scopes its environment) must be answered about that
207
+ * object rather than about `process.env`.
208
+ *
209
+ * Loaded lazily and defensively: this module is deliberately dependency-free
210
+ * (it is copied into hosts that bundle no other file), so an absent env-file
211
+ * module simply means "nothing is file-sourced" — which is the pre-existing
212
+ * behaviour, not a failure.
213
+ */
214
+ function fromEnvFile(name, value, env) {
215
+ try {
216
+ const envFile = require('./env-file.js');
217
+ return (
218
+ typeof envFile.isFromEnvFile === 'function' &&
219
+ envFile.isFromEnvFile(name, value, env ? { env } : undefined)
220
+ );
221
+ } catch {
222
+ return false;
223
+ }
224
+ }
225
+
192
226
  /**
193
227
  * The key to use, and where it came from.
194
228
  *
195
- * @returns {{key:string, source:'env'|'credentials'|'config'|'none', from:string}}
229
+ * Order, and the one asymmetry that matters:
230
+ *
231
+ * 1. `AEGIS_API_KEY` **exported by the launching shell** — unchanged, and
232
+ * still first, so CI and an explicit `AEGIS_API_KEY=… aegiscode` keep
233
+ * working.
234
+ * 2. `credentials.json` — a key the user explicitly saved with
235
+ * `aegiscode login`, the CLI's `/key`, or the desktop's Settings pane.
236
+ * 3. `AEGIS_API_KEY` **from `~/.aegiscode/.env`** — the documented place to
237
+ * put a key, but a fallback rather than a decision: it carries no save
238
+ * stamp and the file is shared by every host and hand-edited by users.
239
+ * 4. `config.json`'s legacy `aegiscloud.api_key`.
240
+ *
241
+ * Rungs 1 and 3 are the same variable, which is exactly the bug this ordering
242
+ * fixes. `env-file.js` copies the file into `process.env` at host start-up, so a
243
+ * leftover line — a rotated key that was never cleaned up, a value from an
244
+ * older install, a provider row mirrored into the wrong name — became
245
+ * indistinguishable from a deliberate export and permanently outranked the file
246
+ * the user had just written. The symptom is the one that gets reported as
247
+ * "it says the key is saved but it is not using it": `aegiscode login` prints
248
+ * `key saved`, the desktop prints `saved (aegis_••••1234)`, `key status` reads
249
+ * back the new key — and every request authenticates with the stale one, so the
250
+ * account check 401s and nothing names the cause. `env-file.js`'s own contract
251
+ * is that the file is "a convenience for the common case, not a way for a stale
252
+ * file to shadow an explicit" setting; `isFromEnvFile()` is what makes that
253
+ * true for a save as well as for an export.
254
+ *
255
+ * @returns {{key:string, source:'env'|'credentials'|'envfile'|'config'|'none', from:string}}
196
256
  */
197
257
  function resolveApiKey(o = {}) {
198
258
  const env = o.env || process.env;
199
259
  const dir = o.dir;
200
260
  const fromEnv = normalizeApiKey(env && env[KEY_ENV]);
201
- if (fromEnv) return { key: fromEnv, source: 'env', from: KEY_ENV };
261
+ // An explicit export wins outright. A value the env FILE supplied does not:
262
+ // it is held back to rung 3 so an explicit save outranks it.
263
+ if (fromEnv && !fromEnvFile(KEY_ENV, env && env[KEY_ENV], env)) {
264
+ return { key: fromEnv, source: 'env', from: KEY_ENV };
265
+ }
202
266
 
203
267
  const creds = readCredentials(dir);
204
268
  const stored = normalizeApiKey(creds.aegisApiKey);
205
269
  if (stored) return { key: stored, source: 'credentials', from: credentialsPath(dir) };
206
270
 
271
+ if (fromEnv) return { key: fromEnv, source: 'envfile', from: envFileLabel(env, dir) };
272
+
207
273
  const legacy = readLegacyConfig(dir).apiKey;
208
274
  if (legacy) return { key: legacy, source: 'config', from: configPath(dir) };
209
275
 
@@ -318,10 +384,30 @@ function clientOptions(o = {}) {
318
384
  const SOURCE_LABEL = {
319
385
  env: `${KEY_ENV}`,
320
386
  credentials: 'saved key file',
387
+ envfile: `~/.aegiscode/.env (${KEY_ENV})`,
321
388
  config: 'config.json (aegis CLI)',
322
389
  none: 'not set',
323
390
  };
324
391
 
392
+ /**
393
+ * The env file a value came from, for the `envfile` status line. Resolved
394
+ * through env-file.js when it is present so the answer is the real path
395
+ * (`$AEGISCODE_HOME/.env` included) rather than a guess.
396
+ */
397
+ function envFileLabel(env, dir) {
398
+ try {
399
+ const envFile = require('./env-file.js');
400
+ if (typeof envFile.envFileFor === 'function') return envFile.envFileFor(dir);
401
+ } catch {}
402
+ return envFileForFallback(dir);
403
+ }
404
+
405
+ /** `~/.aegiscode/.env`, built here so the label survives a host that ships no
406
+ * env-file module (same rule aegisHome() exists for). */
407
+ function envFileForFallback(dir) {
408
+ return path.join(dir || aegisHome(), '.env');
409
+ }
410
+
325
411
  function sourceLabel(source) {
326
412
  return SOURCE_LABEL[source] || SOURCE_LABEL.none;
327
413
  }
@@ -377,6 +463,8 @@ module.exports = {
377
463
  adoptLegacy,
378
464
  resolveApiKey,
379
465
  hasApiKey,
466
+ fromEnvFile,
467
+ envFileForFallback,
380
468
  saveApiKey,
381
469
  clearApiKey,
382
470
  resolveMemoryToken,
@@ -262,9 +262,67 @@ function parseEnvText(text) {
262
262
  * `loaded` — names taken from the file. `kept` — names the environment
263
263
  * already had, left alone (a real export always wins).
264
264
  */
265
+ /**
266
+ * Provenance of every value this process took from `~/.aegiscode/.env`.
267
+ *
268
+ * Keyed off the env object itself (a WeakMap, so an injected `{ env }` in a
269
+ * test is tracked without leaking and `process.env` needs no extra property).
270
+ * See `isFromEnvFile`.
271
+ */
272
+ const ENV_SOURCED = new WeakMap();
273
+
274
+ function sourcedFrom(env) {
275
+ let map = ENV_SOURCED.get(env);
276
+ if (!map) {
277
+ map = new Map();
278
+ ENV_SOURCED.set(env, map);
279
+ }
280
+ return map;
281
+ }
282
+
283
+ /**
284
+ * Was `name`'s CURRENT value in `env` one this process took from the shared env
285
+ * file, rather than something the launching shell exported?
286
+ *
287
+ * This is the distinction the file's own rule 1 depends on and could not
288
+ * previously express. The file is documented as a *convenience for the common
289
+ * case, not a way for a stale file to shadow an explicit export* — but once a
290
+ * value is copied into `process.env` the two are the same thing, so every
291
+ * env-first reader (`client/credentials.js`) treated a line in the file exactly
292
+ * like a deliberate export and let it win forever. Concretely: a user runs
293
+ * `aegiscode login`, the key is written to `credentials.json` (0600) and
294
+ * reported as saved, and every request since then authenticates with whatever
295
+ * `AEGIS_API_KEY=` line the file still carries — the "it says saved but the key
296
+ * is wrong" report. A real export still wins; a file value is a fallback.
297
+ *
298
+ * `value` is checked as well as the name: a shell export that replaced the
299
+ * loaded value is no longer file-sourced, and neither is a later `setEnvValue`
300
+ * (which applies the value it just wrote and marks it accordingly).
301
+ *
302
+ * @param {string} name
303
+ * @param {string} [value] the current value, to confirm it is still the one the
304
+ * file provided. Omit to ask about the name alone.
305
+ * @param {object} [o] `env`, for tests and injected environments
306
+ */
307
+ function isFromEnvFile(name, value, o = {}) {
308
+ const env = o.env || process.env;
309
+ const map = ENV_SOURCED.get(env);
310
+ if (!map || !map.has(name)) return false;
311
+ if (value === undefined) return true;
312
+ return map.get(name) === String(value);
313
+ }
314
+
265
315
  function loadEnvFile(o = {}) {
266
316
  const env = o.env || process.env;
267
317
  const file = o.file || envFileFor(o.dir);
318
+ // Names this process took from the FILE, with the value it took. Kept so a
319
+ // consumer can tell the two sources apart: rule 1 above makes the file a
320
+ // fallback, but the moment its value lands in `process.env` it is otherwise
321
+ // indistinguishable from an explicit `AEGIS_API_KEY=… aegiscode` export, and
322
+ // `client/credentials.js`'s resolution order is env-first. Without this
323
+ // marker a leftover line in a file every host sources at start-up outranks
324
+ // the key the user explicitly saved — see `isFromEnvFile()` below.
325
+ const sourced = sourcedFrom(env);
268
326
  const result = {
269
327
  ok: false, file, loaded: [], kept: [], refused: [], reason: '', loose: false, mode: 0,
270
328
  };
@@ -296,8 +354,14 @@ function loadEnvFile(o = {}) {
296
354
  }
297
355
  if (env[name] === undefined || env[name] === '') {
298
356
  env[name] = value;
357
+ // Provenance: this value is the FILE's, not the launching shell's. An
358
+ // env-first reader must treat it as the fallback the file is documented
359
+ // to be, not as an explicit export that outranks a saved key.
360
+ sourced.set(name, value);
299
361
  result.loaded.push(name);
300
362
  } else {
363
+ // A real export wins (rule 1) and is deliberately NOT marked: it is the
364
+ // one source allowed to outrank `credentials.json`.
301
365
  result.kept.push(name);
302
366
  }
303
367
  }
@@ -615,7 +679,12 @@ function setEnvValue(name, value, o = {}) {
615
679
  out.changed = false;
616
680
  out.replaced = true;
617
681
  out.mode = previousMode || SECRET_FILE_MODE;
618
- if (o.apply !== false) env[name] = secret;
682
+ if (o.apply !== false) {
683
+ env[name] = secret;
684
+ // Applied, and the file carries it: file-sourced, so an env-first reader
685
+ // treats it as the fallback it is (see isFromEnvFile).
686
+ sourcedFrom(env).set(name, secret);
687
+ }
619
688
  return out;
620
689
  }
621
690
 
@@ -640,7 +709,11 @@ function setEnvValue(name, value, o = {}) {
640
709
  out.replaced = replaced;
641
710
  out.mode = SECRET_FILE_MODE;
642
711
  out.tightened = !out.created && previousMode !== 0 && (previousMode & 0o077) !== 0;
643
- if (o.apply !== false) env[name] = secret;
712
+ if (o.apply !== false) {
713
+ env[name] = secret;
714
+ // Just written to the file and applied here: file-sourced (see above).
715
+ sourcedFrom(env).set(name, secret);
716
+ }
644
717
  return out;
645
718
  }
646
719
 
@@ -810,16 +883,91 @@ function keyStatus(name, o = {}) {
810
883
  *
811
884
  * @param {string} modelId
812
885
  * @param {string} [cls] 'byok' | 'aegis' | anything else
813
- * @returns {{env:string, provider:string, pooled:boolean}}
886
+ * @returns {{env:string, provider:string, vendor:string, pooled:boolean}}
814
887
  */
815
888
  function keyForModelId(modelId, cls) {
816
889
  const id = String(modelId == null ? '' : modelId).trim();
817
890
  const byok = String(cls || '').toLowerCase() === 'byok' || id.includes(':');
818
891
  if (byok && id.includes(':')) {
819
892
  const provider = id.slice(0, id.indexOf(':')).trim();
820
- return { env: envVarFor(provider), provider, pooled: false };
893
+ return { env: envVarFor(provider), provider, vendor: provider, pooled: false };
894
+ }
895
+ // A pooled id is served by the pool, so the credential the ROUTE needs is the
896
+ // account key — but the id may still NAME the vendor underneath it
897
+ // (`deepseek`, `anthropic-haiku`, `openai-gpt4o-mini`). That vendor is what
898
+ // `vendor` reports, and it is not the same question as `env`: it is the
899
+ // provider key a user may also want on this machine, which the picker asks
900
+ // for after the account key. `provider` stays '' for pooled on purpose — the
901
+ // byok call path reads it as "which provider's settings row to address", and
902
+ // a pooled row has none.
903
+ return { env: ACCOUNT_ENV_VAR, provider: '', vendor: providerForModelId(id, cls), pooled: true };
904
+ }
905
+
906
+ /**
907
+ * Vendors whose slug is a namespace a model id may be spelled under.
908
+ *
909
+ * Deliberately a *table* and not a pattern: the derivation below is a claim that
910
+ * a key for this vendor exists, so an id whose first segment is not on this list
911
+ * derives NO vendor (and the picker asks only for the account key) rather than
912
+ * inventing a variable name like `NEXUS_API_KEY` for the pool's own namespace.
913
+ * The list is the platform's providers as its own BYOK catalog spells them
914
+ * (aegis1 services/nexus_provider/catalog.py MODEL_CATALOG) plus the ids this
915
+ * module already re-spells in ALIASES above — keep it in step with that catalog,
916
+ * not with whatever vendor a user might mention.
917
+ */
918
+ const VENDOR_SLUGS = Object.freeze([
919
+ 'openai',
920
+ 'anthropic',
921
+ 'deepseek',
922
+ 'google',
923
+ 'gemini',
924
+ 'groq',
925
+ 'mistral',
926
+ 'openrouter',
927
+ 'together',
928
+ 'together-ai',
929
+ 'xai',
930
+ 'x-ai',
931
+ 'grok',
932
+ 'huggingface',
933
+ 'fireworks',
934
+ 'voyage-ai',
935
+ 'azure-openai',
936
+ ]);
937
+
938
+ /** The multi-segment slugs, longest first, so `azure-openai-x` matches the full slug. */
939
+ const VENDOR_COMPOUNDS = Object.freeze(
940
+ VENDOR_SLUGS.filter((s) => s.includes('-')).sort((a, b) => b.length - a.length)
941
+ );
942
+
943
+ /**
944
+ * The vendor a model id names, or '' — `deepseek-flash` → `deepseek`,
945
+ * `nexus-brain` → '', `deepseek:deepseek-v4-flash` → `deepseek`.
946
+ *
947
+ * The one question the picker needs to answer "is there a SECOND key worth
948
+ * asking for on this row?" A pooled row is billed to the AEGIS account, so its
949
+ * route needs the account key and nothing else — but when the row is named
950
+ * after a vendor whose key this machine could hold (`deepseek`), asking for that
951
+ * key too is what lets the account actually call the model instead of the pool
952
+ * failing a turn with "no provider key". That is the gap this closes:
953
+ * aegis-key present, models listed, and every turn still failing because the
954
+ * vendor key the models route through was never collected.
955
+ *
956
+ * @param {string} modelId
957
+ * @param {string} [cls] unused by the derivation; accepted so a caller can pass
958
+ * the same (id, cls) pair it passes `keyForModelId` without branching.
959
+ * @returns {string} the vendor slug, or '' when the id names none this module
960
+ * knows a variable for.
961
+ */
962
+ function providerForModelId(modelId, cls) { // eslint-disable-line no-unused-vars
963
+ const id = String(modelId == null ? '' : modelId).trim().toLowerCase();
964
+ if (!id) return '';
965
+ if (id.includes(':')) return id.slice(0, id.indexOf(':')).trim();
966
+ for (const slug of VENDOR_COMPOUNDS) {
967
+ if (id === slug || id.startsWith(slug + '-')) return slug;
821
968
  }
822
- return { env: ACCOUNT_ENV_VAR, provider: '', pooled: true };
969
+ const first = id.split('-')[0];
970
+ return VENDOR_SLUGS.includes(first) ? first : '';
823
971
  }
824
972
 
825
973
  module.exports = {
@@ -831,7 +979,15 @@ module.exports = {
831
979
  envVarFor,
832
980
  parseEnvText,
833
981
  loadEnvFile,
982
+ // Provenance of what loadEnvFile put in the environment: a value taken from
983
+ // the FILE is a fallback, not an explicit export, and the env-first readers
984
+ // (client/credentials.js) must be able to tell the two apart.
985
+ isFromEnvFile,
834
986
  providerKeyFromEnv,
987
+ // The vendor half of "what key does this model id need": the account key is
988
+ // the route's credential, this is the provider key underneath it.
989
+ providerForModelId,
990
+ VENDOR_SLUGS,
835
991
  isWritableName,
836
992
  quoteEnvValue,
837
993
  upsertEnvText,
@@ -307,35 +307,32 @@ function normalizeCatalog(models) {
307
307
  /**
308
308
  * The Aegis Cloud (pooled) dropdown.
309
309
  *
310
- * It offers NO aegiscloud model. The catalog (`/api/v1/models`) lists
311
- * per-provider ids (`deepseek`, `anthropic`, `groq`, `openai`, ...) alongside
312
- * five pooled-brain tier spellings (`{aegis,nexus}-brain[-smart|-neo]`) that all
313
- * route the same worker pool, and this host must offer neither: "omit the
314
- * aegiscloud models" is the instruction, and a host that omitted the brain row
315
- * while leaving `deepseek` on screen would have kept exactly the per-provider
316
- * pin the Aegis Cloud policy is about. The class stays selectable and its
317
- * dropdown keeps the "server default (auto)" row, so the pooled lane still runs
318
- * — it just advertises nothing to pin.
310
+ * It offers the server's whole catalog (`/api/v1/models`): the pooled brain
311
+ * first, under its one name (Nexus), then every per-provider id the account can
312
+ * pin (`deepseek`, `anthropic`, `groq`, `openai`, ...).
313
+ *
314
+ * Two narrower shapes were shipped here and both are reverted, because both
315
+ * produced the same report — a user asking where the models went. First the
316
+ * class collapsed to a single "Nexus" row (`filterAegisCatalog`), which ended
317
+ * the two-host disagreement about the brain's five tier spellings by removing
318
+ * the choice: a funded account had `deepseek` advertised to it and no way to
319
+ * pin it. Then it offered nothing at all — `omitAegisCloudModels` composed with
320
+ * that collapse returns `[]`, because the omission removes the only entry the
321
+ * collapse looks for. The rule both hosts call now is `offerableCatalog`:
322
+ * everything the server advertises, the tier spellings folded into the one row
323
+ * they point at.
319
324
  *
320
325
  * What is NOT changed: the account key, and everything the key is *for* — the
321
326
  * pooled turn itself, cloud memory sync, and the BYOK handling fee that is
322
- * billed to this account (see the byok branch below, which still offers every
323
- * provider id the server's catalog names). Omitting a model list is not
324
- * disconnecting the lane.
325
- *
326
- * The omission itself is one shared rule (`omitAegisCloudModels`, and the
327
- * collapse it is composed with) in `client/brain-catalog.js`, shared with the
328
- * CLI: two copies is how this host and the terminal previously came to offer
329
- * the same account two different model lists. Resolved the two ways this repo
330
- * resolves every shared module — repo-relative in a checkout, and this app's
331
- * staged vendor/ tree.
327
+ * billed to this account (see the byok branch below).
332
328
  *
333
- * `filterAegisCatalog` is kept in the composition rather than dropped for the
334
- * shorter `models: []`: a payload with no brain tier at all (a self-hosted or
335
- * trimmed deployment) must still yield nothing here rather than leaking its
336
- * per-provider ids, and that is precisely the case the collapse already answers.
329
+ * The list itself is one shared rule in `client/brain-catalog.js`, shared with
330
+ * the CLI: two copies is how this host and the terminal previously came to
331
+ * offer the same account two different model lists. Resolved the two ways this
332
+ * repo resolves every shared module — repo-relative in a checkout, and this
333
+ * app's staged vendor/ tree.
337
334
  */
338
- const { filterAegisCatalog, omitAegisCloudModels } = requireSharedBrain();
335
+ const { offerableCatalog } = requireSharedBrain();
339
336
 
340
337
  /**
341
338
  * The BYOK additions, applied to the server's provider catalog below. Same
@@ -855,20 +852,16 @@ function createLocalEngine({
855
852
  // entry so the class is usable the moment a key lands.
856
853
  if (!aegis.apiKey) return { class: cls, models: [], needsKey: true };
857
854
  const data = await aegis.listModels();
858
- // No aegiscloud model is offered — see the rule above. The class, the
859
- // auto row and the pooled turn are untouched; only the pinnable list is
860
- // emptied, which is why `needsKey` keeps its meaning and the renderer's
861
- // hint for this class is unchanged.
855
+ // The whole catalog, aliases folded — see the rule above. What the list
856
+ // contains does not touch `needsKey` or the renderer's per-class hint.
862
857
  return {
863
858
  class: cls,
864
- // Omit FIRST, then collapse: the omission has to see the payload's own
865
- // `alias_of` bookkeeping, which the collapse deliberately strips (a
866
- // collapsed row IS the selection, so a renderer must not filter it back
867
- // out as a hidden alias). Filtering a collapsed row instead would leave
868
- // a renamed tier — `nexus-brain-v2`, an alias OF the brain under a
869
- // spelling this release has never seen — on screen, which is the one
870
- // case the rule exists to catch.
871
- models: filterAegisCatalog(omitAegisCloudModels(normalizeCatalog(data && data.models))),
859
+ // One call, because the folding has to see the payload's own `alias_of`
860
+ // bookkeeping: a pre-collapsed row IS the selection, so a renderer must
861
+ // not filter it back out as a hidden alias, and folding what has already
862
+ // been folded would leave a renamed tier (`nexus-brain-v2`, an alias OF
863
+ // the brain under a spelling this release has never seen) on screen.
864
+ models: offerableCatalog(normalizeCatalog(data && data.models)),
872
865
  };
873
866
  }
874
867
  if (cls === 'byok') {