aegiscode 6.8.14 → 6.8.16

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.
@@ -35,6 +35,32 @@
35
35
  /** Every id the server uses for the pooled brain, canonical spelling first. */
36
36
  const NEXUS_BRAIN_IDS = Object.freeze(['nexus-brain', 'aegis-brain']);
37
37
 
38
+ /**
39
+ * Every id the AEGIS Cloud (aegiscloud) lane serves that is NOT a per-provider
40
+ * id: the pooled brain and the `-smart`/`-neo` tier spellings the server sends
41
+ * as aliases of it. Verified against the live catalog 2026-09-30 —
42
+ * `GET /api/v1/models` answers exactly `deepseek`, `nexus-brain`, `aegis-brain`,
43
+ * `nexus-brain-smart`, `aegis-brain-smart`, `nexus-brain-neo`, `aegis-brain-neo`.
44
+ *
45
+ * A host that must not OFFER the aegiscloud lane needs this list rather than a
46
+ * bare `NEXUS_BRAIN_IDS` check: four of the six spellings are not in that array,
47
+ * and a filter written against it alone would leave `nexus-brain-neo` on screen
48
+ * — the "five spellings of one brain" defect again, one host at a time. The
49
+ * spelling is kept here, next to the ids, because this module is the one place
50
+ * both hosts already agree about what the pooled lane is called.
51
+ */
52
+ const AEGIS_CLOUD_MODEL_IDS = Object.freeze([
53
+ 'nexus-brain',
54
+ 'aegis-brain',
55
+ 'nexus-brain-smart',
56
+ 'aegis-brain-smart',
57
+ 'nexus-brain-neo',
58
+ 'aegis-brain-neo',
59
+ ]);
60
+
61
+ /** The tier-family shape, for a spelling the server adds after this release. */
62
+ const AEGIS_CLOUD_MODEL_RE = /^(?:nexus|aegis)-brain(?:-(?:smart|neo))?$/;
63
+
38
64
  /** The name users see for the collapsed entry. */
39
65
  const NEXUS_LABEL = 'Nexus';
40
66
 
@@ -105,6 +131,54 @@ function filterAegisCatalog(models) {
105
131
  return [{ ...rest, label: NEXUS_LABEL }];
106
132
  }
107
133
 
134
+ /**
135
+ * Whether an entry is a model of the AEGIS CLOUD (aegiscloud) lane — the pooled
136
+ * brain under any of its spellings, whether it is the canonical id, a
137
+ * `-smart`/`-neo` tier, or a row that aliases the brain (`alias_of` in the
138
+ * relay's shape, `aliasOf` in the CLI's).
139
+ *
140
+ * Accepts an id string or an entry object, like the rest of this module.
141
+ *
142
+ * @param {string|object} entry
143
+ * @returns {boolean}
144
+ */
145
+ function isAegisCloudModel(entry) {
146
+ const id = typeof entry === 'string'
147
+ ? entry.trim()
148
+ : entry && typeof entry === 'object' && typeof entry.id === 'string'
149
+ ? entry.id.trim()
150
+ : '';
151
+ if (AEGIS_CLOUD_MODEL_IDS.includes(id)) return true;
152
+ if (AEGIS_CLOUD_MODEL_RE.test(id)) return true;
153
+ return NEXUS_BRAIN_IDS.includes(aliasOfEntry(entry));
154
+ }
155
+
156
+ /**
157
+ * The same list with the AEGIS Cloud (aegiscloud) models omitted.
158
+ *
159
+ * A host that keeps the cloud lane's *credential* (the account key BYOK billing
160
+ * rides on) without offering its *models* needs a filter that is one rule and
161
+ * survives a renamed tier — which is why this is here and not a regex spelled
162
+ * again inside a host: a second copy is how this repo's two clients came to show
163
+ * one account two different model lists in the first place.
164
+ *
165
+ * Pure and non-mutating; a non-array yields `[]`, and an entry with no usable id
166
+ * is dropped rather than passed through, because "a row we cannot name" is not a
167
+ * row a picker may paint.
168
+ *
169
+ * @param {Array<object|string>} models
170
+ * @returns {Array} a new array, order preserved
171
+ */
172
+ function omitAegisCloudModels(models) {
173
+ const list = Array.isArray(models) ? models : [];
174
+ return list.filter((m) => {
175
+ if (!m) return false;
176
+ if (typeof m === 'string') return !isAegisCloudModel(m);
177
+ const id = typeof m.id === 'string' ? m.id.trim() : '';
178
+ return Boolean(id) && !isAegisCloudModel(m);
179
+ });
180
+ }
181
+
108
182
  /**
109
183
  * The Aegis-class catalog as a host must OFFER it: the FULL list the server
110
184
  * advertises — the pooled brain first, under its one name, then every other
@@ -182,6 +256,9 @@ function offerableCatalog(models) {
182
256
  module.exports = {
183
257
  NEXUS_BRAIN_IDS,
184
258
  NEXUS_LABEL,
259
+ AEGIS_CLOUD_MODEL_IDS,
260
+ isAegisCloudModel,
261
+ omitAegisCloudModels,
185
262
  selectBrainEntry,
186
263
  filterAegisCatalog,
187
264
  offerableCatalog,
@@ -50,6 +50,38 @@
50
50
  * - the value is applied to `process.env` as well, so the selection that
51
51
  * triggered the write runs on the key it just stored;
52
52
  * - the value is never returned, logged or echoed by anything in here.
53
+ *
54
+ * THE SECOND FILE — `~/.aegiscode/secrets.env`, and why the split exists.
55
+ *
56
+ * One file for every key the family can use was right while the keys were all
57
+ * HOST credentials: a provider key or the account key is read by the CLI, the
58
+ * desktop and the MCP plugin, so one file is what makes "enter the key once"
59
+ * true. It was never right for the variables that are not host credentials at
60
+ * all — `STRIPE_SECRET_KEY` (the billing rail of the aegis1/server product),
61
+ * `PYPI_API_TOKEN`, `CLAUDE_CODE_OAUTH_TOKEN` — which had been poured into the
62
+ * same file by hand. Those are loaded into `process.env` by every host at
63
+ * start-up, so they were inherited by every child process and visible to any
64
+ * account that can read `/proc/<pid>/environ`, for a key no host ever reads.
65
+ * That is exposure with no function behind it.
66
+ *
67
+ * The split keeps the sharing that matters and removes the sharing that does
68
+ * not:
69
+ *
70
+ * - `.env` still holds every host credential, still loaded by every host,
71
+ * still written by `setEnvValue`, still the answer to "where do I put my
72
+ * API key". Nothing about that changed.
73
+ * - `secrets.env` holds the foreign production secrets. It is NOT read at
74
+ * host start-up. `loadForeignSecrets()` reads it explicitly, for the one
75
+ * process that genuinely needs a billing token, so the value is available
76
+ * without being ambient. `setEnvValue` refuses to write a foreign name at
77
+ * all (see FOREIGN_SECRET_NAMES below), so the file cannot silently
78
+ * re-acquire one.
79
+ * - `splitForeignSecrets()` performs the migration: it moves the foreign
80
+ * names out of `.env` into `secrets.env` (0600), preserving comments,
81
+ * ordering and every other line, and is idempotent — a second run moves
82
+ * nothing. `tools/split-env-secrets.mjs` is its command line.
83
+ *
84
+ * Reading is what changed, and only for the names on that list.
53
85
  */
54
86
 
55
87
  const fs = require('node:fs');
@@ -58,6 +90,59 @@ const credentials = require('./credentials.js');
58
90
 
59
91
  const ENV_FILE = '.env';
60
92
 
93
+ /**
94
+ * The file for production secrets that are NOT host credentials. Read only by
95
+ * an explicit `loadForeignSecrets()` call — never at host start-up — so a
96
+ * billing or publishing token stops being ambient in every process.
97
+ */
98
+ const SECRETS_FILE = 'secrets.env';
99
+
100
+ /**
101
+ * Names that belong to another product and are never loaded into a host's
102
+ * environment, however they got into the file.
103
+ *
104
+ * The list is deliberately a *deny* list and not an allow list. An allow list
105
+ * would have to be updated every time a provider is added, and a key missing
106
+ * from it would stop working — the failure mode of the one feature this module
107
+ * exists to provide. A deny list can only ever make a host *less* exposed, so
108
+ * it fails in the safe direction: the worst case is a foreign secret that stays
109
+ * in `.env` and keeps being loaded, which is exactly today's behaviour.
110
+ *
111
+ * `STRIPE_` is a prefix rather than four names because the rail has grown a
112
+ * price id per plan; a new one must not be able to re-enter the shared file by
113
+ * being new.
114
+ */
115
+ const FOREIGN_SECRET_PREFIXES = Object.freeze(['STRIPE_']);
116
+
117
+ const FOREIGN_SECRET_NAMES = Object.freeze([
118
+ // Billing — the aegis1/server product's rail, not a host credential.
119
+ 'STRIPE_SECRET_KEY',
120
+ 'STRIPE_WEBHOOK_SECRET',
121
+ 'STRIPE_PRODUCT',
122
+ 'STRIPE_PRO_PRICE_ID',
123
+ 'STRIPE_S_PRICE_ID',
124
+ 'STRIPE_MEMORY_PRICE_ID',
125
+ // Publishing.
126
+ 'PYPI_API_TOKEN',
127
+ 'TWINE_PASSWORD',
128
+ // Claude Code's own OAuth token: a credential for a different CLI, which
129
+ // reads it from its own environment. No host in this repo does.
130
+ 'CLAUDE_CODE_OAUTH_TOKEN',
131
+ ]);
132
+
133
+ /**
134
+ * Is this variable one that must never be loaded into a host process?
135
+ *
136
+ * @param {string} name
137
+ * @returns {boolean}
138
+ */
139
+ function isForeignSecret(name) {
140
+ const n = String(name == null ? '' : name).trim();
141
+ if (!n) return false;
142
+ if (FOREIGN_SECRET_NAMES.includes(n)) return true;
143
+ return FOREIGN_SECRET_PREFIXES.some((p) => n.startsWith(p));
144
+ }
145
+
61
146
  /** Permissions for a file holding secrets: owner read/write, nothing else. */
62
147
  const SECRET_FILE_MODE = 0o600;
63
148
 
@@ -94,6 +179,14 @@ function envFileFor(dir) {
94
179
  return path.join(dir || credentials.aegisHome(), ENV_FILE);
95
180
  }
96
181
 
182
+ /**
183
+ * The foreign-secrets file beside `envFileFor()`, honouring the same
184
+ * `$AEGISCODE_HOME`. Never read implicitly.
185
+ */
186
+ function secretEnvFileFor(dir) {
187
+ return path.join(dir || credentials.aegisHome(), SECRETS_FILE);
188
+ }
189
+
97
190
  /**
98
191
  * The env var one BYOK provider's key is read from.
99
192
  *
@@ -172,7 +265,9 @@ function parseEnvText(text) {
172
265
  function loadEnvFile(o = {}) {
173
266
  const env = o.env || process.env;
174
267
  const file = o.file || envFileFor(o.dir);
175
- const result = { ok: false, file, loaded: [], kept: [], reason: '', loose: false, mode: 0 };
268
+ const result = {
269
+ ok: false, file, loaded: [], kept: [], refused: [], reason: '', loose: false, mode: 0,
270
+ };
176
271
 
177
272
  let text;
178
273
  try {
@@ -192,6 +287,13 @@ function loadEnvFile(o = {}) {
192
287
 
193
288
  const parsed = parseEnvText(text);
194
289
  for (const [name, value] of Object.entries(parsed)) {
290
+ // A foreign secret is neither loaded nor "kept": it is refused, and named
291
+ // in `refused` so a caller can tell the user it is in the wrong file
292
+ // instead of silently ignoring it.
293
+ if (isForeignSecret(name)) {
294
+ result.refused.push(name);
295
+ continue;
296
+ }
195
297
  if (env[name] === undefined || env[name] === '') {
196
298
  env[name] = value;
197
299
  result.loaded.push(name);
@@ -203,6 +305,158 @@ function loadEnvFile(o = {}) {
203
305
  return result;
204
306
  }
205
307
 
308
+ /**
309
+ * Read the foreign-secrets file into an environment, on purpose.
310
+ *
311
+ * The counterpart of the refusal inside `loadEnvFile`: a process that actually
312
+ * needs a billing or publishing token asks for it by name, and it is documented
313
+ * at the call site. Nothing calls this at host start-up — that is the point of
314
+ * the split — and unlike `loadEnvFile` it does NOT treat an already-set variable
315
+ * as a reason to skip: a caller who asks for the secrets file gets the file's
316
+ * values, in a fresh object unless one is passed.
317
+ *
318
+ * @param {object} [o]
319
+ * @param {object} [o.env]
320
+ * @param {string} [o.dir]
321
+ * @param {string} [o.file]
322
+ * @param {string[]} [o.only] restrict to these names
323
+ * @returns {{ok:boolean, file:string, loaded:string[], reason:string,
324
+ * mode:number, loose:boolean}}
325
+ */
326
+ function loadForeignSecrets(o = {}) {
327
+ const env = o.env || process.env;
328
+ const file = o.file || secretEnvFileFor(o.dir);
329
+ const result = { ok: false, file, loaded: [], reason: '', mode: 0, loose: false };
330
+ const only = Array.isArray(o.only) && o.only.length
331
+ ? o.only.filter(isForeignSecret)
332
+ : null;
333
+
334
+ let text;
335
+ try {
336
+ text = fs.readFileSync(file, 'utf8');
337
+ } catch (e) {
338
+ result.reason = e && e.code === 'ENOENT' ? 'absent' : 'unreadable';
339
+ return result;
340
+ }
341
+
342
+ try {
343
+ const st = fs.statSync(file);
344
+ result.mode = st.mode & 0o777;
345
+ result.loose = (st.mode & 0o077) !== 0;
346
+ } catch { /* advisory */ }
347
+
348
+ const parsed = parseEnvText(text);
349
+ for (const [name, value] of Object.entries(parsed)) {
350
+ if (only && !only.includes(name)) continue;
351
+ env[name] = value;
352
+ result.loaded.push(name);
353
+ }
354
+ result.ok = true;
355
+ return result;
356
+ }
357
+
358
+ /**
359
+ * One foreign secret, read without exporting it into an environment.
360
+ *
361
+ * @returns {string} '' when the file does not exist or does not hold the name
362
+ */
363
+ function foreignSecretValue(name, o = {}) {
364
+ if (!isForeignSecret(name)) return '';
365
+ const file = o.file || secretEnvFileFor(o.dir);
366
+ try {
367
+ const parsed = parseEnvText(fs.readFileSync(file, 'utf8'));
368
+ const v = parsed[String(name)];
369
+ return typeof v === 'string' ? v : '';
370
+ } catch {
371
+ return '';
372
+ }
373
+ }
374
+
375
+ /** Write a secrets file with the right permissions and no half-written state. */
376
+ function writeSecretFile(file, text) {
377
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: SECRET_DIR_MODE });
378
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
379
+ fs.writeFileSync(tmp, text, { mode: SECRET_FILE_MODE });
380
+ fs.renameSync(tmp, file);
381
+ // rename preserves the temp file's mode, which the umask may have loosened on
382
+ // a machine with a permissive one — so the mode is asserted after the move.
383
+ fs.chmodSync(file, SECRET_FILE_MODE);
384
+ }
385
+
386
+ /**
387
+ * Move every foreign secret out of `~/.aegiscode/.env` into `secrets.env`.
388
+ *
389
+ * Idempotent by construction: the names moved are the ones the parse finds in
390
+ * `.env`, and a second run finds none. A name already present in `secrets.env`
391
+ * is not overwritten — the destination is the authority once it exists, so a
392
+ * migration can never silently revert a value someone rotated there.
393
+ *
394
+ * Every other line of `.env` — comments, order, unrelated keys, `export`
395
+ * prefixes — survives verbatim, because both edits go through the same
396
+ * `upsertEnvText`/`removeEnvText` pair the writers use.
397
+ *
398
+ * @param {object} [o]
399
+ * @param {boolean} [o.apply=false] without it, nothing is written (dry run)
400
+ * @returns {{ok:boolean, moved:string[], kept:string[], envFile:string,
401
+ * secretsFile:string, apply:boolean, reason?:string}}
402
+ */
403
+ function splitForeignSecrets(o = {}) {
404
+ const env = o.env || process.env;
405
+ const envFile = o.file || envFileFor(o.dir);
406
+ const secretsFile = o.secretsFile || secretEnvFileFor(o.dir);
407
+ const apply = o.apply === true;
408
+ const out = { ok: false, moved: [], kept: [], envFile, secretsFile, apply };
409
+
410
+ let envText;
411
+ try {
412
+ envText = fs.readFileSync(envFile, 'utf8');
413
+ } catch (e) {
414
+ out.reason = e && e.code === 'ENOENT' ? 'absent' : 'unreadable';
415
+ return out;
416
+ }
417
+
418
+ const parsed = parseEnvText(envText);
419
+ const names = Object.keys(parsed).filter(isForeignSecret).sort();
420
+ if (!names.length) {
421
+ out.ok = true;
422
+ return out;
423
+ }
424
+
425
+ let secretsText = '';
426
+ try {
427
+ secretsText = fs.readFileSync(secretsFile, 'utf8');
428
+ } catch { /* the file is created below */ }
429
+ const already = parseEnvText(secretsText);
430
+
431
+ for (const name of names) {
432
+ if (Object.prototype.hasOwnProperty.call(already, name)) {
433
+ out.kept.push(name);
434
+ continue;
435
+ }
436
+ secretsText = upsertEnvText(secretsText, name, parsed[name]).text;
437
+ out.moved.push(name);
438
+ }
439
+
440
+ if (apply) {
441
+ for (const name of names) {
442
+ envText = removeEnvText(envText, name).text;
443
+ }
444
+ if (out.moved.length) writeSecretFile(secretsFile, secretsText);
445
+ writeSecretFile(envFile, envText);
446
+ // And out of the live environment of THIS process, or a running host would
447
+ // keep the value it had already loaded until it restarted.
448
+ for (const name of names) {
449
+ if (env[name] === parsed[name]) delete env[name];
450
+ }
451
+ } else if (out.moved.length) {
452
+ // A dry run still shows the destination, without creating it.
453
+ out.secretsFile = secretsFile;
454
+ }
455
+
456
+ out.ok = true;
457
+ return out;
458
+ }
459
+
206
460
  /**
207
461
  * The BYOK key for a provider out of the environment, if the env file (or the
208
462
  * shell) supplies one. Returns '' when it does not — the encrypted store then
@@ -253,7 +507,14 @@ function upsertEnvText(text, name, value) {
253
507
  // blank line to a file that ended cleanly.
254
508
  const hadFinalNewline = src === '' ? true : src.endsWith('\n');
255
509
  const trailingBlank = src === '' ? false : src.split('\n').slice(-1)[0] === '';
256
- const lines = src.split('\n');
510
+ // An EMPTY file is zero lines, not one empty line: `''.split('\n')` is `['']`,
511
+ // and that stray element survives to `out` because the pop above only fires
512
+ // when `trailingBlank` is true (forced false for an empty source). The result
513
+ // was a first-ever write that opened the file with a leading blank line —
514
+ // `'\nNAME=secret\n'` — breaking the contract the comment two lines up
515
+ // states and the round-trip guarantee below. The common case is exactly this
516
+ // one: a fresh ~/.aegiscode/.env on a new machine.
517
+ const lines = src === '' ? [] : src.split('\n');
257
518
  if (trailingBlank) lines.pop();
258
519
 
259
520
  const re = new RegExp(`^(\\s*(?:export\\s+)?)${name}\\s*=`);
@@ -310,6 +571,15 @@ function setEnvValue(name, value, o = {}) {
310
571
  out.error = `refusing to write "${name}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`;
311
572
  return out;
312
573
  }
574
+ // The lock on the split: this file holds host keys, so a name that is not a
575
+ // host key is refused rather than written. Saying so is the point — the
576
+ // alternative (writing it and declining to load it) would recreate the exact
577
+ // state the split removed, with the value still on disk in the shared file.
578
+ if (isForeignSecret(name)) {
579
+ out.error = `refusing to write ${name} to ${ENV_FILE} — it is a production secret, not a host key;`
580
+ + ` put it in ${SECRETS_FILE} (or use loadForeignSecrets)`;
581
+ return out;
582
+ }
313
583
  const secret = String(value == null ? '' : value).trim();
314
584
  if (!secret) {
315
585
  out.error = `refusing to write an empty ${name}`;
@@ -393,7 +663,11 @@ function removeEnvText(text, name) {
393
663
  const src = String(text == null ? '' : text);
394
664
  const hadFinalNewline = src === '' ? true : src.endsWith('\n');
395
665
  const trailingBlank = src === '' ? false : src.split('\n').slice(-1)[0] === '';
396
- const lines = src.split('\n');
666
+ // Zero lines for an empty source — see upsertEnvText. Here it is defensive
667
+ // rather than observable (a remover on an empty file writes nothing either
668
+ // way), but the two functions must split identically or a later change to one
669
+ // starts disagreeing with the other about what a line is.
670
+ const lines = src === '' ? [] : src.split('\n');
397
671
  if (trailingBlank) lines.pop();
398
672
 
399
673
  // Same definition matcher as upsertEnvText, so the two can never disagree
@@ -566,4 +840,14 @@ module.exports = {
566
840
  clearEnvValue,
567
841
  keyStatus,
568
842
  keyForModelId,
843
+ // The split: the second file, the list that decides what may not be loaded,
844
+ // and the reader a process that genuinely needs a billing token calls.
845
+ SECRETS_FILE,
846
+ FOREIGN_SECRET_NAMES,
847
+ FOREIGN_SECRET_PREFIXES,
848
+ isForeignSecret,
849
+ secretEnvFileFor,
850
+ loadForeignSecrets,
851
+ foreignSecretValue,
852
+ splitForeignSecrets,
569
853
  };
@@ -305,28 +305,37 @@ function normalizeCatalog(models) {
305
305
  }
306
306
 
307
307
  /**
308
- * The Aegis Cloud (pooled) dropdown offers Nexus, and only Nexus.
308
+ * The Aegis Cloud (pooled) dropdown.
309
309
  *
310
- * The catalog (`/api/v1/models`) lists per-provider ids (`deepseek`,
311
- * `anthropic`, `groq`, `openai`, ...) alongside five pooled-brain tier
312
- * spellings (`{aegis,nexus}-brain[-smart|-neo]`) that all route the same
313
- * worker pool. This host briefly offered the full list — the per-provider ids
314
- * included — on the theory that a funded account should be able to pin the
315
- * exact model it pays for. Niklas's explicit instruction is narrower: AEGIS
316
- * Cloud offers Nexus only, no per-provider pin, so this is back on
317
- * `filterAegisCatalog` — the shared rule's single-row collapse.
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.
318
319
  *
319
- * The rule itself lives in `client/brain-catalog.js`, shared with the CLI, so
320
- * there is exactly one copy of it: two copies is how this host and the
321
- * terminal previously came to offer the same account two different model
322
- * lists. `filterAegisCatalog` collapses the five brain-tier spellings to the
323
- * one row labelled Nexus; a payload with no brain tier (the BYOK listing) is
324
- * unaffected — see the desktop's byok branch below, which still offers every
325
- * provider id the account holds a key for. Resolved the two ways this repo
320
+ * What is NOT changed: the account key, and everything the key is *for* — the
321
+ * 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
326
330
  * resolves every shared module — repo-relative in a checkout, and this app's
327
331
  * staged vendor/ tree.
332
+ *
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.
328
337
  */
329
- const { filterAegisCatalog } = requireSharedBrain();
338
+ const { filterAegisCatalog, omitAegisCloudModels } = requireSharedBrain();
330
339
 
331
340
  /**
332
341
  * The BYOK additions, applied to the server's provider catalog below. Same
@@ -846,7 +855,21 @@ function createLocalEngine({
846
855
  // entry so the class is usable the moment a key lands.
847
856
  if (!aegis.apiKey) return { class: cls, models: [], needsKey: true };
848
857
  const data = await aegis.listModels();
849
- return { class: cls, models: filterAegisCatalog(normalizeCatalog(data && data.models)) };
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.
862
+ return {
863
+ 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))),
872
+ };
850
873
  }
851
874
  if (cls === 'byok') {
852
875
  // The server's catalog names every provider it accepts a key for, the
@@ -1107,6 +1130,17 @@ function createLocalEngine({
1107
1130
  ...(opts.tools.length ? { tools: opts.tools } : {}),
1108
1131
  ...(opts.toolChoice ? { tool_choice: opts.toolChoice } : {}),
1109
1132
  },
1133
+ // aegis1's agent-key gate (services/agent_gate.py) 403s a pooled turn
1134
+ // whose `tools` names a code-capable verb (writeFile/editFile/exec —
1135
+ // this engine's builtin set — normalise to the server's CODE_TOOLS
1136
+ // entries) unless X-AEGIS-Agent-Key is attached. `AEGIS_API_KEY` says
1137
+ // who pays; this says who may change code, and is deliberately a
1138
+ // separate credential (see agent_gate.py's module docstring). Read
1139
+ // from `~/.aegiscode/.env` via the same loadEnvFile() both hosts
1140
+ // already run at startup — no new key store. Absent by default: an
1141
+ // account with no agent key simply gets the same 403 as before,
1142
+ // scoped to turns that actually carry tools.
1143
+ agentKey: opts.tools.length ? (process.env.AEGIS_AGENT_KEY || '').trim() || undefined : undefined,
1110
1144
  });
1111
1145
  }
1112
1146
 
@@ -31,6 +31,40 @@ function cap(s) {
31
31
  return s.length > OUTPUT_CAP ? `${s.slice(0, OUTPUT_CAP)}\n… (truncated)` : s;
32
32
  }
33
33
 
34
+ // The buffer is BOUNDED WHILE IT FILLS, not just when it is reported.
35
+ //
36
+ // `cap()` above runs on close, which is fine for the text the user sees but
37
+ // useless as a memory bound: between the spawn and the exit the raw stream is
38
+ // accumulated in this process with no ceiling at all, so a command that never
39
+ // stops printing (`yes`, `cat /dev/zero`, a runaway build log) grows the MAIN
40
+ // process's heap for as long as the timeout allows — up to 10 minutes — before
41
+ // the truncation it was always going to get. A tool call must not be able to
42
+ // OOM the app it runs in.
43
+ //
44
+ // The window kept is head + tail, because neither end may be dropped:
45
+ // - the HEAD is what the user and the model are shown (OUTPUT_CAP already
46
+ // says only that much is reported);
47
+ // - the TAIL is where the exit sentinel lives for a session (`printf
48
+ // '__AEGIS_SH_…EXIT:%d'`) — dropping it would not merely lose output, it
49
+ // would hang the session until the timeout, because the resolver scans the
50
+ // buffer for a marker that can never arrive.
51
+ // 64 KiB of tail is ~1500× the sentinel line, and surviving a chunk boundary
52
+ // needs only the sentinel's own length.
53
+ const TAIL_KEEP = 64 * 1024;
54
+ const BUFFER_CEILING = OUTPUT_CAP + TAIL_KEEP;
55
+ const ELISION = '\n… (earlier output elided — command produced more than the buffer ceiling)\n';
56
+
57
+ /** Append one stream chunk to `prev`, keeping the bounded head+tail window.
58
+ * Pure, so the streaming paths and their tests agree on the policy. */
59
+ function appendBounded(prev, chunk) {
60
+ const next = prev + chunk;
61
+ if (next.length <= BUFFER_CEILING) return next;
62
+ // Elide the MIDDLE: head stays visible, tail keeps the sentinel reachable.
63
+ // The marker makes the missing bytes explicit rather than letting the two
64
+ // halves read as contiguous output.
65
+ return next.slice(0, OUTPUT_CAP) + ELISION + next.slice(-TAIL_KEEP);
66
+ }
67
+
34
68
  /** One-shot fallback — the pre-session behavior, used when no live session. */
35
69
  function oneShotShell({ command, timeout = DEFAULT_TIMEOUT, working_directory } = {}) {
36
70
  return new Promise((resolve) => {
@@ -42,8 +76,10 @@ function oneShotShell({ command, timeout = DEFAULT_TIMEOUT, working_directory }
42
76
  });
43
77
  let out = '';
44
78
  let err = '';
45
- child.stdout.on('data', (d) => { out += d; });
46
- child.stderr.on('data', (d) => { err += d; });
79
+ // Bounded both ways: a one-shot command with no live session is just as
80
+ // capable of printing forever as a session command (appendBounded's header).
81
+ child.stdout.on('data', (d) => { out = appendBounded(out, d.toString()); });
82
+ child.stderr.on('data', (d) => { err = appendBounded(err, d.toString()); });
47
83
  child.on('error', (e) => resolve({ content: `error: ${e.message}`, isError: true }));
48
84
  child.on('close', (code) => {
49
85
  const body = `${out}${err ? `\n${err}` : ''}`.trim() || `(exit ${code})`;
@@ -84,7 +120,12 @@ class ShellSession {
84
120
  return;
85
121
  }
86
122
  this.alive = true;
87
- const onData = (d) => { this.buf += d.toString(); if (this._pending) this._pending(); };
123
+ const onData = (d) => {
124
+ // Bounded — see appendBounded. The tail is kept precisely so the sentinel
125
+ // this session's resolver scans for survives a command that floods stdout.
126
+ this.buf = appendBounded(this.buf, d.toString());
127
+ if (this._pending) this._pending();
128
+ };
88
129
  this.child.stdout.on('data', onData);
89
130
  this.child.stderr.on('data', onData);
90
131
  this.child.on('exit', () => { this.alive = false; if (this._pending) this._pending(true); });
@@ -205,4 +246,4 @@ function pshq(s) {
205
246
  return `'${String(s).replace(/'/g, "''")}'`;
206
247
  }
207
248
 
208
- module.exports = { ShellSession, oneShotShell, IS_WIN32 };
249
+ module.exports = { ShellSession, oneShotShell, IS_WIN32, appendBounded, OUTPUT_CAP, BUFFER_CEILING, TAIL_KEEP };