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.
@@ -1,9 +1,8 @@
1
1
  'use strict';
2
2
 
3
3
  /**
4
- * The shared `~/.aegiscode/.env` loader.
5
- *
6
- * One file holding every key this product family can use, for every host:
4
+ * The shared `~/.aegiscode/.env` store — the one file holding every key this
5
+ * product family can use, for every host:
7
6
  *
8
7
  * AEGIS_API_KEY=aegis_…
9
8
  * OPENAI_API_KEY=sk-…
@@ -18,14 +17,39 @@
18
17
  * needs no other change in either, because `AEGIS_API_KEY` is already the FIRST
19
18
  * entry in `client/credentials.js`'s documented resolution order.
20
19
  *
21
- * Two rules this module deliberately obeys:
20
+ * READING still obeys two rules this module started with:
22
21
  *
23
22
  * 1. A variable already present in the environment is never overwritten. The
24
23
  * file is a convenience for the common case, not a way for a stale file to
25
24
  * shadow an explicit `AEGIS_API_KEY=… aegiscode` in CI.
26
- * 2. It reads only. Nothing here writes a secret, so the 0600 store remains
27
- * the one thing this repo creates; if the file the user made is readable
28
- * by other accounts we say so rather than fixing it silently.
25
+ * 2. A load never rewrites anything. If the file the user made is readable by
26
+ * other accounts we say so rather than fixing it silently.
27
+ *
28
+ * WRITING was added later, because the file being read-only was the reason the
29
+ * key a user typed at the model picker did not survive the session: the only
30
+ * place a host could put it was its own encrypted store, so the CLI and the
31
+ * desktop each held a private key for the same provider and the user had to
32
+ * enter it twice. The demand is one key, entered once at the model picker,
33
+ * stored where BOTH hosts already look. So `setEnvValue` is the single writer:
34
+ *
35
+ * - the variable name is validated (`/^[A-Za-z_][A-Za-z0-9_]*$/`) and the
36
+ * value may not contain a newline, so a key can never inject a second line
37
+ * (or an unrelated variable) into a file every host sources at start-up;
38
+ * - an existing line with the same name is REPLACED in place — including its
39
+ * `export ` prefix, which is preserved — so comments, ordering and every
40
+ * other key in the file survive untouched, and a hand-written file is not
41
+ * reformatted;
42
+ * - duplicate definitions of the same name are collapsed to the one that was
43
+ * just written. Two `OPENAI_API_KEY=` lines is the "which one won?" bug,
44
+ * and the answer would otherwise depend on the reader's merge order;
45
+ * - the file is created 0600 and written through a same-directory temp file
46
+ * + rename, so a crash mid-write cannot leave a half-written key file, and
47
+ * a write never widens permissions on a file that was already tighter. A
48
+ * file that WAS group/world-readable is tightened, and the caller is told
49
+ * (`tightened: true`) rather than the change going unmentioned;
50
+ * - the value is applied to `process.env` as well, so the selection that
51
+ * triggered the write runs on the key it just stored;
52
+ * - the value is never returned, logged or echoed by anything in here.
29
53
  */
30
54
 
31
55
  const fs = require('node:fs');
@@ -34,6 +58,12 @@ const credentials = require('./credentials.js');
34
58
 
35
59
  const ENV_FILE = '.env';
36
60
 
61
+ /** Permissions for a file holding secrets: owner read/write, nothing else. */
62
+ const SECRET_FILE_MODE = 0o600;
63
+
64
+ /** A directory we create for a secret file: owner only. */
65
+ const SECRET_DIR_MODE = 0o700;
66
+
37
67
  /**
38
68
  * provider id -> the env var a BYOK key is conventionally exported as, for the
39
69
  * ids where the generic rule below would spell the wrong name. The generic rule
@@ -56,6 +86,9 @@ const ALIASES = Object.freeze({
56
86
  'voyage-ai': 'VOYAGE_API_KEY',
57
87
  });
58
88
 
89
+ /** The variable that carries an AEGIS Cloud account key (see credentials.js). */
90
+ const ACCOUNT_ENV_VAR = 'AEGIS_API_KEY';
91
+
59
92
  /** The file this host would read, honouring `$AEGISCODE_HOME`. */
60
93
  function envFileFor(dir) {
61
94
  return path.join(dir || credentials.aegisHome(), ENV_FILE);
@@ -85,7 +118,9 @@ function envVarFor(providerId) {
85
118
  * (and a stray `#` comment or a blank line is normal, not an error).
86
119
  *
87
120
  * Handles `export `, `KEY=value`, `KEY="value"`, `KEY='value'` and a trailing
88
- * ` # comment` on an unquoted value.
121
+ * ` # comment` on an unquoted value. A double-quoted value is unescaped (`\"`,
122
+ * `\\`) because that is what `quoteEnvValue` writes and what dotenv readers do;
123
+ * a single-quoted value is literal.
89
124
  */
90
125
  function parseEnvText(text) {
91
126
  const out = {};
@@ -98,9 +133,19 @@ function parseEnvText(text) {
98
133
  if (name.startsWith('export ')) name = name.slice('export '.length).trim();
99
134
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) continue;
100
135
  let value = line.slice(eq + 1).trim();
101
- const quoted = (value.startsWith('"') && value.endsWith('"') && value.length >= 2)
102
- || (value.startsWith("'") && value.endsWith("'") && value.length >= 2);
103
- if (quoted) {
136
+ const doubleQuoted = value.startsWith('"') && value.endsWith('"') && value.length >= 2;
137
+ const singleQuoted = value.startsWith("'") && value.endsWith("'") && value.length >= 2;
138
+ if (doubleQuoted) {
139
+ // Double quotes are the one form that carries escapes, so they are the
140
+ // one form that must be unescaped — `\"` and `\\`, exactly what
141
+ // `quoteEnvValue` writes and what every dotenv reader does. Without this
142
+ // the writer's escaping was one-way: a value containing a quote or a
143
+ // backslash was stored doubled and read back mangled, so a key survived
144
+ // the session it was typed in but not the next one. Single quotes stay
145
+ // literal (`'C:\keys'` is a backslash, not an escape), which is the
146
+ // convention that makes the two quote styles mean something different.
147
+ value = value.slice(1, -1).replace(/\\(["\\])/g, '$1');
148
+ } else if (singleQuoted) {
104
149
  value = value.slice(1, -1);
105
150
  } else {
106
151
  const hash = value.indexOf(' #');
@@ -171,12 +216,354 @@ function providerKeyFromEnv(providerId, env) {
171
216
  return { key, env: name };
172
217
  }
173
218
 
219
+ /** A variable name this module is willing to write. */
220
+ function isWritableName(name) {
221
+ return typeof name === 'string' && /^[A-Za-z_][A-Za-z0-9_]*$/.test(name);
222
+ }
223
+
224
+ /**
225
+ * Quote a value the way `parseEnvText` (and every dotenv reader) will read back
226
+ * byte-identically. Unquoted when it is safe; double-quoted with backslashes and
227
+ * quotes escaped when it is not. A newline is refused by the caller, never
228
+ * escaped here: escaping it would hide a malformed key behind a file that
229
+ * still looks right.
230
+ */
231
+ function quoteEnvValue(value) {
232
+ const s = String(value);
233
+ if (s === '') return '';
234
+ if (!/[\s"'#\\]/.test(s)) return s;
235
+ return `"${s.replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`;
236
+ }
237
+
238
+ /**
239
+ * Apply `name=value` to dotenv text: replace the first existing definition in
240
+ * place (keeping an `export ` prefix and any trailing comment-less formatting),
241
+ * drop later duplicates, and append when the name is new. Every other line —
242
+ * comments, blanks, unrelated keys, their order — is preserved verbatim.
243
+ *
244
+ * Pure, and exported for tests: this is the part worth pinning, because a bug
245
+ * here silently destroys a file the user also edits by hand.
246
+ *
247
+ * @returns {{text:string, replaced:boolean}}
248
+ */
249
+ function upsertEnvText(text, name, value) {
250
+ const src = String(text == null ? '' : text);
251
+ // Split without keeping the terminator, then re-join with '\n' and restore a
252
+ // final newline only if the file had one — so a write never adds a dangling
253
+ // blank line to a file that ended cleanly.
254
+ const hadFinalNewline = src === '' ? true : src.endsWith('\n');
255
+ const trailingBlank = src === '' ? false : src.split('\n').slice(-1)[0] === '';
256
+ const lines = src.split('\n');
257
+ if (trailingBlank) lines.pop();
258
+
259
+ const re = new RegExp(`^(\\s*(?:export\\s+)?)${name}\\s*=`);
260
+ const out = [];
261
+ let replaced = false;
262
+ for (const line of lines) {
263
+ const m = re.exec(line);
264
+ if (!m) {
265
+ out.push(line);
266
+ continue;
267
+ }
268
+ if (replaced) continue; // a second definition of the same name: collapse it
269
+ out.push(`${m[1]}${name}=${quoteEnvValue(value)}`);
270
+ replaced = true;
271
+ }
272
+ if (!replaced) out.push(`${name}=${quoteEnvValue(value)}`);
273
+
274
+ let joined = out.join('\n');
275
+ if (joined !== '' && (hadFinalNewline || trailingBlank)) joined += '\n';
276
+ return { text: joined, replaced };
277
+ }
278
+
279
+ /**
280
+ * Store one variable in `~/.aegiscode/.env`, creating the file (0600) and the
281
+ * directory (0700) when needed, and apply it to the live environment so the
282
+ * action that triggered the write runs on it.
283
+ *
284
+ * The one writer for every host: the CLI calls it when a model is selected and
285
+ * its key is missing, and the desktop calls the same function through the same
286
+ * staged file, which is what makes a key entered once usable in both.
287
+ *
288
+ * @param {string} name an env var name, e.g. 'OPENAI_API_KEY'
289
+ * @param {string} value the secret. Never returned, never logged.
290
+ * @param {object} [o]
291
+ * @param {string} [o.dir] defaults to aegisHome()
292
+ * @param {string} [o.file] an explicit path, for tests
293
+ * @param {object} [o.env] defaults to process.env
294
+ * @param {boolean} [o.apply=true] set it in `o.env`/process.env as well
295
+ * @returns {{ok:boolean, file:string, name:string, changed:boolean,
296
+ * created:boolean, replaced:boolean, mode:number, tightened:boolean,
297
+ * error:string}}
298
+ * `changed` is false when the file already held that exact value — a re-save
299
+ * of an unchanged key must not rewrite the file.
300
+ */
301
+ function setEnvValue(name, value, o = {}) {
302
+ const env = o.env || process.env;
303
+ const file = o.file || envFileFor(o.dir);
304
+ const out = {
305
+ ok: false, file, name: String(name || ''), changed: false, created: false,
306
+ replaced: false, mode: 0, tightened: false, error: '',
307
+ };
308
+
309
+ if (!isWritableName(name)) {
310
+ out.error = `refusing to write "${name}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`;
311
+ return out;
312
+ }
313
+ const secret = String(value == null ? '' : value).trim();
314
+ if (!secret) {
315
+ out.error = `refusing to write an empty ${name}`;
316
+ return out;
317
+ }
318
+ // The one injection this file must not accept: a value carrying a newline
319
+ // would append a line, and the file is sourced by every host at start-up.
320
+ if (/[\r\n]/.test(String(value))) {
321
+ out.error = `refusing to write ${name} — the value contains a line break`;
322
+ return out;
323
+ }
324
+
325
+ let before = '';
326
+ let previousMode = 0;
327
+ out.created = true;
328
+ try {
329
+ before = fs.readFileSync(file, 'utf8');
330
+ out.created = false;
331
+ try {
332
+ previousMode = fs.statSync(file).mode & 0o777;
333
+ } catch { /* advisory */ }
334
+ } catch (e) {
335
+ if (e && e.code !== 'ENOENT') {
336
+ out.error = `could not read ${file}: ${e.code || e.message}`;
337
+ return out;
338
+ }
339
+ }
340
+
341
+ const aligned = String(before).replace(/\r\n/g, '\n');
342
+ if (!out.created && parseEnvText(aligned)[name] === secret) {
343
+ // Same key already stored: leave the file (its mtime, its mode) alone.
344
+ out.ok = true;
345
+ out.changed = false;
346
+ out.replaced = true;
347
+ out.mode = previousMode || SECRET_FILE_MODE;
348
+ if (o.apply !== false) env[name] = secret;
349
+ return out;
350
+ }
351
+
352
+ const { text, replaced } = upsertEnvText(aligned, name, secret);
353
+ const tmp = `${file}.tmp-${process.pid}`;
354
+ try {
355
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: SECRET_DIR_MODE });
356
+ fs.writeFileSync(tmp, text, { encoding: 'utf8', mode: SECRET_FILE_MODE });
357
+ // The rename carries the temp file's 0600 onto the destination, so a file
358
+ // that was group-readable ends up owner-only. Say so rather than tightening
359
+ // a file behind the user's back.
360
+ fs.chmodSync(tmp, SECRET_FILE_MODE);
361
+ fs.renameSync(tmp, file);
362
+ } catch (e) {
363
+ try { fs.unlinkSync(tmp); } catch {}
364
+ out.error = `could not write ${file}: ${e.code || e.message}`;
365
+ return out;
366
+ }
367
+
368
+ out.ok = true;
369
+ out.changed = true;
370
+ out.replaced = replaced;
371
+ out.mode = SECRET_FILE_MODE;
372
+ out.tightened = !out.created && previousMode !== 0 && (previousMode & 0o077) !== 0;
373
+ if (o.apply !== false) env[name] = secret;
374
+ return out;
375
+ }
376
+
377
+ /**
378
+ * Delete every definition of `name` from an env file's text, leaving every
379
+ * other line — comments, blanks, unrelated keys, their order, `export `
380
+ * prefixes — byte-identical.
381
+ *
382
+ * Removing a key is NOT the same as storing an empty one: `parseEnvText` reads
383
+ * `NAME=""` back as a present-but-empty variable, so an empty write leaves the
384
+ * old value's line in the file and a stale key can still win later. A remover
385
+ * has to delete the line.
386
+ *
387
+ * Pure, and exported for tests: like `upsertEnvText`, a bug here silently
388
+ * damages a file the user also edits by hand.
389
+ *
390
+ * @returns {{text:string, removed:number, changed:boolean}}
391
+ */
392
+ function removeEnvText(text, name) {
393
+ const src = String(text == null ? '' : text);
394
+ const hadFinalNewline = src === '' ? true : src.endsWith('\n');
395
+ const trailingBlank = src === '' ? false : src.split('\n').slice(-1)[0] === '';
396
+ const lines = src.split('\n');
397
+ if (trailingBlank) lines.pop();
398
+
399
+ // Same definition matcher as upsertEnvText, so the two can never disagree
400
+ // about which lines count as this variable.
401
+ const re = new RegExp(`^(\\s*(?:export\\s+)?)${name}\\s*=`);
402
+ const out = [];
403
+ let removed = 0;
404
+ for (const line of lines) {
405
+ if (re.test(line)) {
406
+ removed += 1; // every definition goes, so duplicates cannot survive
407
+ continue;
408
+ }
409
+ out.push(line);
410
+ }
411
+
412
+ let joined = out.join('\n');
413
+ if (joined !== '' && (hadFinalNewline || trailingBlank)) joined += '\n';
414
+ return { text: joined, removed, changed: removed > 0 };
415
+ }
416
+
417
+ /**
418
+ * Remove one variable from `~/.aegiscode/.env` and from the live environment.
419
+ *
420
+ * The counterpart of `setEnvValue`, and the reason a provider key deleted in
421
+ * the desktop app stops being in force: without it, the key survives in the
422
+ * shared file and the desktop's own "removed" state disagrees with what the CLI
423
+ * reads next session.
424
+ *
425
+ * A file that never mentioned the name is left untouched — no stray empty
426
+ * variable, no rewritten mtime.
427
+ *
428
+ * @returns {{ok:boolean, file:string, name:string, changed:boolean,
429
+ * removed:number, mode:number, error:string}}
430
+ */
431
+ function clearEnvValue(name, o = {}) {
432
+ const env = o.env || process.env;
433
+ const file = o.file || envFileFor(o.dir);
434
+ const out = {
435
+ ok: false, file, name: String(name || ''), changed: false, removed: 0,
436
+ mode: 0, error: '',
437
+ };
438
+
439
+ if (!isWritableName(name)) {
440
+ out.error = `refusing to clear "${name}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`;
441
+ return out;
442
+ }
443
+
444
+ let before = '';
445
+ let missing = false;
446
+ let previousMode = 0;
447
+ try {
448
+ before = fs.readFileSync(file, 'utf8');
449
+ try {
450
+ previousMode = fs.statSync(file).mode & 0o777;
451
+ } catch { /* advisory */ }
452
+ } catch (e) {
453
+ if (e && e.code === 'ENOENT') missing = true;
454
+ else {
455
+ out.error = `could not read ${file}: ${e.code || e.message}`;
456
+ return out;
457
+ }
458
+ }
459
+
460
+ const { text, removed, changed } = missing
461
+ ? { text: '', removed: 0, changed: false }
462
+ : removeEnvText(before, name);
463
+
464
+ if (!changed) {
465
+ // Nothing in the file to remove. Still unset the live variable: the caller
466
+ // asked for the key to stop being used, and a shell export would otherwise
467
+ // keep serving it for the rest of this process.
468
+ out.ok = true;
469
+ out.mode = previousMode || SECRET_FILE_MODE;
470
+ if (o.apply !== false) delete env[String(name)];
471
+ return out;
472
+ }
473
+
474
+ const tmp = `${file}.tmp-${process.pid}`;
475
+ try {
476
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: SECRET_DIR_MODE });
477
+ fs.writeFileSync(tmp, text, { encoding: 'utf8', mode: SECRET_FILE_MODE });
478
+ fs.chmodSync(tmp, SECRET_FILE_MODE);
479
+ fs.renameSync(tmp, file);
480
+ } catch (e) {
481
+ try { fs.unlinkSync(tmp); } catch {}
482
+ out.error = `could not write ${file}: ${e.code || e.message}`;
483
+ return out;
484
+ }
485
+
486
+ out.ok = true;
487
+ out.changed = true;
488
+ out.removed = removed;
489
+ out.mode = SECRET_FILE_MODE;
490
+ if (o.apply !== false) delete env[String(name)];
491
+ return out;
492
+ }
493
+
494
+ /**
495
+ * Whether the key a route needs is already stored, and where that answer came
496
+ * from. Read-only; the caller uses it to decide whether to prompt.
497
+ *
498
+ * `inFile` is the distinction that matters for the model picker: a key in the
499
+ * process environment belongs to the shell that launched this host and is gone
500
+ * next session (and invisible to the desktop), where a key in the file is the
501
+ * durable, cross-host one.
502
+ *
503
+ * @returns {{name:string, present:boolean, inFile:boolean, source:string}}
504
+ * `source` — 'shell' | 'file' | 'both' | 'none'
505
+ */
506
+ function keyStatus(name, o = {}) {
507
+ const env = o.env || process.env;
508
+ const file = o.file || envFileFor(o.dir);
509
+ const varName = String(name || '');
510
+ const out = { name: varName, present: false, inFile: false, source: 'none' };
511
+ if (!isWritableName(varName)) return out;
512
+
513
+ const raw = env[varName];
514
+ const shell = typeof raw === 'string' && raw.trim() !== '';
515
+ let file_ = false;
516
+ try {
517
+ const parsed = parseEnvText(fs.readFileSync(file, 'utf8'));
518
+ file_ = typeof parsed[varName] === 'string' && parsed[varName].trim() !== '';
519
+ } catch { /* absent or unreadable is simply "not in the file" */ }
520
+
521
+ out.present = shell || file_;
522
+ out.inFile = file_;
523
+ out.source = shell && file_ ? 'both' : shell ? 'shell' : file_ ? 'file' : 'none';
524
+ return out;
525
+ }
526
+
527
+ /**
528
+ * The env var a model id's key belongs in — the question the model picker asks
529
+ * to know what to collect, and the reason one key is not collected twice.
530
+ *
531
+ * A byok id is `<provider>:<model>` and its key is that provider's variable. A
532
+ * pooled id (`deepseek`, `anthropic-haiku`, `nexus-brain`, …) is served by the
533
+ * pool, which holds the provider keys itself, so the credential such a route
534
+ * needs is the AEGIS ACCOUNT key — one variable, `AEGIS_API_KEY`, however many
535
+ * providers the picker lists.
536
+ *
537
+ * @param {string} modelId
538
+ * @param {string} [cls] 'byok' | 'aegis' | anything else
539
+ * @returns {{env:string, provider:string, pooled:boolean}}
540
+ */
541
+ function keyForModelId(modelId, cls) {
542
+ const id = String(modelId == null ? '' : modelId).trim();
543
+ const byok = String(cls || '').toLowerCase() === 'byok' || id.includes(':');
544
+ if (byok && id.includes(':')) {
545
+ const provider = id.slice(0, id.indexOf(':')).trim();
546
+ return { env: envVarFor(provider), provider, pooled: false };
547
+ }
548
+ return { env: ACCOUNT_ENV_VAR, provider: '', pooled: true };
549
+ }
550
+
174
551
  module.exports = {
175
552
  ENV_FILE,
176
553
  ALIASES,
554
+ ACCOUNT_ENV_VAR,
555
+ SECRET_FILE_MODE,
177
556
  envFileFor,
178
557
  envVarFor,
179
558
  parseEnvText,
180
559
  loadEnvFile,
181
560
  providerKeyFromEnv,
561
+ isWritableName,
562
+ quoteEnvValue,
563
+ upsertEnvText,
564
+ removeEnvText,
565
+ setEnvValue,
566
+ clearEnvValue,
567
+ keyStatus,
568
+ keyForModelId,
182
569
  };
@@ -84,7 +84,7 @@ function writtenPath(tool) {
84
84
  * The default AEGIS Cloud model for autonomous work: the pooled brain, which
85
85
  * is the tier the server can fan out to multiple reasoning workers and
86
86
  * synthesise. `nexus-brain` is the canonical id the catalog itself prefers
87
- * (the other tier spellings are aliases of it — see filterAegisCatalog in
87
+ * (the other tier spellings are aliases of it — see offerableCatalog in
88
88
  * engine.js).
89
89
  *
90
90
  * The model id is only the tier. It is NOT what makes an autonomous task
@@ -108,7 +108,7 @@ const DEFAULT_MODEL = 'nexus-brain';
108
108
  * the pool auto-route across whichever providers hold a live key.
109
109
  *
110
110
  * The accept-list is therefore the pooled-brain tier family — the one entry
111
- * engine.js's filterAegisCatalog offers for the Aegis Cloud class, plus the
111
+ * engine.js's offerableCatalog offers for the Aegis Cloud class, plus the
112
112
  * `-smart`/`-neo` tier spellings the server still serves as aliases of it. This
113
113
  * mirrors selectBrainEntry() there rather than re-deriving "anything starting
114
114
  * with nexus-": `nexus-fast` is not a tier the catalog has ever served, and
@@ -76,6 +76,63 @@ try {
76
76
  }
77
77
  }
78
78
 
79
+ /**
80
+ * The shared pooled-brain selection rule (`client/brain-catalog.js`), resolved
81
+ * the same two ways as every other shared module: repo-relative from a source
82
+ * checkout, and this app's own staged tree (`desktop/vendor/brain-catalog.js`,
83
+ * flattened by scripts/predist.mjs because a packaged app cannot reach outside
84
+ * its own directory). The CLI resolves the same file its own way, through
85
+ * `cli/src/sharedpaths.js`. Both hosts must agree on which entry stands for the
86
+ * pool, so there is deliberately no fallback implementation here — a silently
87
+ * divergent local copy is the exact bug this module removes. When neither
88
+ * layout has it, require() throws at load time naming the file, rather than the
89
+ * host quietly offering a different model list than its sibling.
90
+ */
91
+ function requireSharedBrain() {
92
+ const candidates = [
93
+ () => require('../../../client/brain-catalog.js'),
94
+ () => require('../../vendor/brain-catalog.js'),
95
+ ];
96
+ let last = null;
97
+ for (const load of candidates) {
98
+ try {
99
+ return load();
100
+ } catch (err) {
101
+ last = err;
102
+ }
103
+ }
104
+ throw last;
105
+ }
106
+
107
+ /**
108
+ * The shared BYOK model additions (`client/byok-catalog.js`), resolved exactly
109
+ * the two ways above and for the same reason: the CLI vendors THIS file
110
+ * (cli/scripts/predist.mjs) and requires the same module through
111
+ * `cli/src/sharedpaths.js`, so a copy-per-host here is how the terminal and the
112
+ * window would come to offer one account two different provider model lists —
113
+ * the defect class this repo keeps paying for.
114
+ *
115
+ * The module is pure and returns a NEW array, so a caller may apply it to a
116
+ * payload it did not build. It never invents a provider: a provider absent from
117
+ * the server's catalog stays absent, because a row that accepts a vendor key
118
+ * must correspond to a slug the relay actually takes.
119
+ */
120
+ function requireSharedByokCatalog() {
121
+ const candidates = [
122
+ () => require('../../../client/byok-catalog.js'),
123
+ () => require('../../vendor/byok-catalog.js'),
124
+ ];
125
+ let last = null;
126
+ for (const load of candidates) {
127
+ try {
128
+ return load();
129
+ } catch (err) {
130
+ last = err;
131
+ }
132
+ }
133
+ throw last;
134
+ }
135
+
79
136
  /**
80
137
  * How long a turn waits for the working-tree lock before running anyway.
81
138
  *
@@ -244,48 +301,36 @@ function normalizeCatalog(models) {
244
301
  }
245
302
 
246
303
  /**
247
- * The Aegis Cloud catalog (`/api/v1/models`) lists every backend the pool can
248
- * reach: per-provider ids (`openai`, `anthropic`, `groq`, `gemini`, ...) and
249
- * six pooled-brain tier ids (`{aegis,nexus}-brain[-smart|-neo]`) that all run
250
- * the same worker pool on the same backend model. None of that is a human's
251
- * model choice — which providers currently hold a valid key is an ops detail
252
- * (today: deepseek/anthropic/groq; openai and gemini drift in and out), and
253
- * surfacing it invites picking a provider that happens to be dead right now.
254
- * The pool already auto-routes across whichever providers are live, so the
255
- * desktop dropdown offers exactly one entry for the "aegis" class: the
256
- * collapsed "Nexus" brain — never the raw provider list.
304
+ * The Aegis Cloud (pooled) dropdown offers Nexus, and only Nexus.
305
+ *
306
+ * The catalog (`/api/v1/models`) lists per-provider ids (`deepseek`,
307
+ * `anthropic`, `groq`, `openai`, ...) alongside five pooled-brain tier
308
+ * spellings (`{aegis,nexus}-brain[-smart|-neo]`) that all route the same
309
+ * worker pool. This host briefly offered the full list — the per-provider ids
310
+ * included — on the theory that a funded account should be able to pin the
311
+ * exact model it pays for. Niklas's explicit instruction is narrower: AEGIS
312
+ * Cloud offers Nexus only, no per-provider pin, so this is back on
313
+ * `filterAegisCatalog` — the shared rule's single-row collapse.
314
+ *
315
+ * The rule itself lives in `client/brain-catalog.js`, shared with the CLI, so
316
+ * there is exactly one copy of it: two copies is how this host and the
317
+ * terminal previously came to offer the same account two different model
318
+ * lists. `filterAegisCatalog` collapses the five brain-tier spellings to the
319
+ * one row labelled Nexus; a payload with no brain tier (the BYOK listing) is
320
+ * unaffected — see the desktop's byok branch below, which still offers every
321
+ * provider id the account holds a key for. Resolved the two ways this repo
322
+ * resolves every shared module — repo-relative in a checkout, and this app's
323
+ * staged vendor/ tree.
257
324
  */
258
- const NEXUS_BRAIN_IDS = Object.freeze(['nexus-brain', 'aegis-brain']);
259
- const NEXUS_LABEL = 'Nexus';
325
+ const { filterAegisCatalog } = requireSharedBrain();
260
326
 
261
327
  /**
262
- * Pick the one entry standing in for the pooled brain. The server serves
263
- * `nexus-brain` as the canonical tier (`hidden: false`, no `alias_of`) and
264
- * marks every other spelling — `aegis-brain` and the `-smart`/`-neo` tiers —
265
- * as `hidden: true, alias_of: "nexus-brain"`. Prefer the canonical id so the
266
- * request travels on the name the server owns; fall back to the alias, then to
267
- * any tier whose `alias_of` names the brain, so a renamed or trimmed catalog
268
- * still resolves to something selectable instead of silently emptying the
269
- * dropdown (the previous fixed-id lookup returned [] if `aegis-brain` was ever
270
- * retired, leaving the class with no model to choose).
328
+ * The BYOK additions, applied to the server's provider catalog below. Same
329
+ * one-copy rule as the brain rule above: the terminal requires this same module
330
+ * (cli/src/commands.js, through sharedpaths.js), so neither host can offer a
331
+ * provider row the other does not.
271
332
  */
272
- function selectBrainEntry(models) {
273
- return (
274
- models.find((m) => NEXUS_BRAIN_IDS.includes(m.id) && !m.hidden && m.alias_of === undefined)
275
- || models.find((m) => NEXUS_BRAIN_IDS.includes(m.id))
276
- || models.find((m) => m.alias_of && NEXUS_BRAIN_IDS.includes(m.alias_of))
277
- || null
278
- );
279
- }
280
-
281
- function filterAegisCatalog(models) {
282
- const nexus = selectBrainEntry(models);
283
- if (!nexus) return [];
284
- // Drop the alias bookkeeping: this entry *is* the selection, so the renderer
285
- // must never treat it as a hidden alias and filter it back out.
286
- const { hidden, alias_of, ...rest } = nexus;
287
- return [{ ...rest, label: NEXUS_LABEL }];
288
- }
333
+ const { withByokAdditions } = requireSharedByokCatalog();
289
334
 
290
335
  // ── Agent-loop helpers ──────────────────────────────────────────────────────
291
336
 
@@ -790,7 +835,14 @@ function createLocalEngine({
790
835
  let fee = null;
791
836
  try {
792
837
  const data = await aegis.byokProviders();
793
- providers = (data && data.providers) || [];
838
+ // The server's catalog, plus the ids it does not name but the vendor
839
+ // serves and the relay will forward (`client/byok-catalog.js`, shared
840
+ // with the CLI so both hosts offer the same rows). Applied HERE, at the
841
+ // single point where the payload enters this engine, so every consumer
842
+ // of `providers` — the model list built just below, the renderer's
843
+ // per-provider Settings rows, and the CLI's own `/byok` listing when it
844
+ // runs on this engine — sees one list instead of three opinions.
845
+ providers = withByokAdditions((data && data.providers) || []);
794
846
  // The handling fee AEGIS adds on top of the caller's vendor bill. It is
795
847
  // the server's own published rate (services/pricing.price_byok_call) and
796
848
  // is passed through untouched — never re-derived here, because a client