aegiscode 6.8.14 → 6.8.15

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/bin/aegiscode.js CHANGED
@@ -644,11 +644,40 @@ async function main(argv = process.argv.slice(2)) {
644
644
  );
645
645
  return 2;
646
646
  }
647
- const code = await app.runInteractive();
648
647
  // The reference leaves a resume hint on exit; without one there is no way to
649
648
  // discover that a session was persisted at all (`/resume` lists them, but a
650
649
  // user who just quit is not looking at a command list).
651
- process.stdout.write(`\nResume this session with:\n aegiscode --continue (or /resume for the list)\n`);
650
+ //
651
+ // It is written from two places on purpose, and latched so it can only ever
652
+ // be written once. It used to be a single write after the await below, which
653
+ // made the hint depend on the session promise settling: when the key pump
654
+ // ended and the loop drained instead — the same failure that ate the alt
655
+ // screen teardown — the process exited before this line ran, and the frames
656
+ // differed by exactly these 81 bytes. That is what the parity suite was
657
+ // reporting, and it was load-dependent: measured 3 of 4 runs losing the hint
658
+ // while four pty runs competed for the cpu, 0 of 12 when they did not. The
659
+ // teardown is guaranteed the same way (see chatflow.js); the hint now is too,
660
+ // so the bytes no longer depend on which of the two paths ended the process.
661
+ let hinted = false;
662
+ const leaveResumeHint = () => {
663
+ if (hinted) return;
664
+ hinted = true;
665
+ try {
666
+ process.stdout.write('\nResume this session with:\n aegiscode --continue (or /resume for the list)\n');
667
+ } catch { /* the terminal is already gone; nothing to say it to */ }
668
+ };
669
+ // Registration order *is* byte order: `process.once('exit')` handlers run in
670
+ // the order they were added, and the session registers its own teardown
671
+ // (leave the alternate screen, drop mouse reporting) inside
672
+ // `runInteractive`. Adding this handler *after* that call is what puts the
673
+ // hint last, i.e. outside the alternate screen. Written before the teardown
674
+ // it is erased by the restore that follows it — the user sees a clean shell
675
+ // and concludes the session was never saved, which is the same bug as losing
676
+ // the hint outright, one layer down.
677
+ const running = app.runInteractive();
678
+ process.once('exit', leaveResumeHint);
679
+ const code = await running;
680
+ leaveResumeHint();
652
681
  return code;
653
682
  }
654
683
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "6.8.14",
4
+ "version": "6.8.15",
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/chatflow.js CHANGED
@@ -555,7 +555,12 @@ function rowLines(msg, cols, ctx, now = Date.now()) {
555
555
  if (i === 0) line.unshift(span(t.white, GLYPH.block), span('', ' '));
556
556
  out.push(line);
557
557
  }
558
- if (msg.streaming) {
558
+ // The live cursor trails the LAST line of a still-growing answer — but only
559
+ // when that line is not the one already carrying the `●` answer marker.
560
+ // A one-line answer put both on the same row (`● Working●`), which reads as a
561
+ // stray glyph rather than a cursor: two dots where the user expects one. The
562
+ // marker is the indicator then, exactly as it is after the turn finishes.
563
+ if (msg.streaming && out.length > 1) {
559
564
  const last = out[out.length - 1];
560
565
  if (last) last.push(span(t.white, GLYPH.block));
561
566
  }
@@ -1715,6 +1720,12 @@ async function runSession(host) {
1715
1720
  };
1716
1721
 
1717
1722
  const handleKey = async (key) => {
1723
+ // No key is not a key. The pump can legitimately deliver nothing — a reset
1724
+ // during teardown, a stdin that closed before the keystroke landed — and
1725
+ // that used to reach `key.name` and throw, which the loop's catch turned
1726
+ // into a stray note and another park. See the STREAM_END branch in the
1727
+ // session loop for what that cost.
1728
+ if (!key) return;
1718
1729
  if (overlay) {
1719
1730
  await handleOverlayKey(key);
1720
1731
  return;
@@ -2038,6 +2049,25 @@ async function runSession(host) {
2038
2049
  leaveAltScreen();
2039
2050
  };
2040
2051
 
2052
+ // …and it must not depend on the session resolving to run. Anything that ends
2053
+ // the process — a turn parked on a stream that will never produce a key, a
2054
+ // future early `return`, another `process.exit` added above this line —
2055
+ // otherwise hands the user back a terminal still sitting in the alternate
2056
+ // screen with mouse reporting enabled. That is precisely the exit frame the
2057
+ // parity test caught. Once-only, and unregistered in the `finally` so a host
2058
+ // that runs several sessions in one process does not stack handlers.
2059
+ let cleanedUp = false;
2060
+ const cleanupOnce = () => {
2061
+ if (cleanedUp) return;
2062
+ cleanedUp = true;
2063
+ try {
2064
+ cleanup();
2065
+ } catch {
2066
+ /* the terminal is already gone; nothing left to restore */
2067
+ }
2068
+ };
2069
+ process.once('exit', cleanupOnce);
2070
+
2041
2071
  // Enter the alternate screen and take over the terminal. `host.stdin` exists
2042
2072
  // so the loop can be driven from a test with a synthetic key stream.
2043
2073
  const stdin = host.stdin || process.stdin;
@@ -2092,7 +2122,28 @@ async function runSession(host) {
2092
2122
  // stream that no longer exists. Without this a session parked on
2093
2123
  // nextKey() at reset time never wakes, and the loop outlives its
2094
2124
  // terminal — repainting into whatever stdout it captured.
2095
- if (key === STREAM_END) break;
2125
+ //
2126
+ // `nextKey()` maps STREAM_END to null (`events.js`: "this call's
2127
+ // contract is a key or null, and STREAM_END is not a key"), so a
2128
+ // reset arrives here as `null`, not as STREAM_END. Testing for
2129
+ // STREAM_END alone therefore missed every real reset: the loop fed
2130
+ // `null` to handleKey, which threw, and re-parked on a pump that had
2131
+ // been cleared — leaving the promise unsettled. The event loop then
2132
+ // drained on its own and Node exited WITHOUT this function's
2133
+ // `finally`, so `cleanup()` never ran: the alternate screen was never
2134
+ // left, bracketed paste and mouse tracking stayed enabled in the
2135
+ // user's shell, and the "aegiscode --continue" hint never printed.
2136
+ // Measured as two different exit frames from the SAME host — 9561
2137
+ // bytes with teardown, 9120 without — which is what surfaced as
2138
+ // `cli-platform-parity.test.mjs` reporting "linux and darwin wrote
2139
+ // different bytes": a coin flip, not a platform difference.
2140
+ //
2141
+ // Ending the session here is the fix: it resolves the promise so the
2142
+ // teardown below runs on every exit, not only on a clean /exit.
2143
+ if (key === STREAM_END || !key) {
2144
+ endSession();
2145
+ break;
2146
+ }
2096
2147
  try {
2097
2148
  await handleKey(key);
2098
2149
  } catch (err) {
@@ -2110,7 +2161,8 @@ async function runSession(host) {
2110
2161
  else process.stdout.off('resize', onResize);
2111
2162
  process.off('uncaughtException', crash);
2112
2163
  process.off('unhandledRejection', crash);
2113
- cleanup();
2164
+ process.off('exit', cleanupOnce);
2165
+ cleanupOnce();
2114
2166
  resetKeyStream();
2115
2167
  }
2116
2168
  }
package/src/events.js CHANGED
@@ -76,7 +76,12 @@ const looksLikePaste = (s) => {
76
76
 
77
77
  let attachedStdin = null;
78
78
  let onData = null;
79
+ let onEnd = null;
79
80
  let suspended = false;
81
+ // Latched: stdin reached EOF and will never produce another key. Lives outside
82
+ // `resetKeyStream()`'s transient state because the loop can ask for a key long
83
+ // after the EOF arrived. Cleared only by attaching a fresh stream.
84
+ let streamEnded = false;
80
85
 
81
86
  function isKeyStreamSuspended() {
82
87
  return suspended;
@@ -85,6 +90,9 @@ function isKeyStreamSuspended() {
85
90
  function attachKeyStream(stdin) {
86
91
  attachedStdin = stdin;
87
92
  everAttached = true;
93
+ // A fresh stream is a fresh session: the previous one's EOF must not be
94
+ // inherited, or the new loop would exit on its first `nextKey()`.
95
+ streamEnded = false;
88
96
  onData = (chunk) => pushChars(String(chunk));
89
97
  // Before the listener goes on, take anything the terminal already delivered
90
98
  // while NOTHING owned the stream. That window is real: the startup background
@@ -110,6 +118,56 @@ function attachKeyStream(stdin) {
110
118
  stdin.resume();
111
119
  stdin.setEncoding('utf8');
112
120
  stdin.on('data', onData);
121
+ attachEndHandler(stdin);
122
+ }
123
+
124
+ /**
125
+ * EOF is the end of the session's input, and it must RESOLVE the loop parked on
126
+ * `nextKey()` rather than leave it waiting on a stream that will never speak
127
+ * again. `attachKeyStream` used to register `data` alone, so a closed stdin
128
+ * (ctrl-d, a pty master that went away, a piped caller that finished writing)
129
+ * silently stranded every waiter: the session promise never settled, so
130
+ * `bin/aegiscode.js` never printed the "aegiscode --continue" hint and never
131
+ * reached `process.exit` — the process only left when the event loop happened
132
+ * to drain on its own, which skips the session's `finally` entirely. That is
133
+ * the difference between a 9561-byte exit frame and a 9120-byte one on the
134
+ * SAME host, which `test/cli-platform-parity.test.mjs` reported as "linux and
135
+ * darwin wrote different bytes". A race, not a platform difference.
136
+ *
137
+ * `resetKeyStream()` is the resolution primitive: it drains the queue and hands
138
+ * every parked waiter STREAM_END, which `nextKey()` reports as `null` and the
139
+ * session loop now treats as "the session is over". It is idempotent, so a
140
+ * second EOF (or a teardown that already reset) costs nothing.
141
+ */
142
+ function attachEndHandler(stdin) {
143
+ onEnd = () => {
144
+ // Latch BEFORE resolving: the loop may not be parked yet, and the latch is
145
+ // what makes the *next* `nextKey()` answer STREAM_END rather than wait on a
146
+ // finished stream.
147
+ streamEnded = true;
148
+ try {
149
+ resetKeyStream();
150
+ } catch {
151
+ /* already reset by a teardown that got there first */
152
+ }
153
+ };
154
+ try {
155
+ stdin.on('end', onEnd);
156
+ stdin.on('close', onEnd);
157
+ } catch {
158
+ /* a stream without an event surface: the timeout paths still apply */
159
+ }
160
+ }
161
+
162
+ /** Undo `attachEndHandler`. Split out so the detach paths stay symmetric. */
163
+ function detachEndHandler(stdin) {
164
+ if (!stdin || !onEnd) return;
165
+ try {
166
+ stdin.removeListener('end', onEnd);
167
+ stdin.removeListener('close', onEnd);
168
+ } catch {
169
+ /* stream already gone */
170
+ }
113
171
  }
114
172
 
115
173
  /** Hand the terminal to a child process: detach the pump and drop half-parsed
@@ -118,6 +176,9 @@ function suspendKeyStream() {
118
176
  if (!attachedStdin || suspended) return;
119
177
  suspended = true;
120
178
  attachedStdin.removeListener('data', onData);
179
+ // A handover is not an end: the child owns the terminal now, and an EOF on
180
+ // the paused stream must not be read as "the session is over".
181
+ detachEndHandler(attachedStdin);
121
182
  clearTimeout(escTimer);
122
183
  seq = '';
123
184
  buffer = '';
@@ -144,6 +205,7 @@ function resumeKeyStream() {
144
205
  attachedStdin.resume();
145
206
  attachedStdin.setEncoding('utf8');
146
207
  attachedStdin.on('data', onData);
208
+ attachEndHandler(attachedStdin);
147
209
  }
148
210
 
149
211
  function flushPaste() {
@@ -345,6 +407,14 @@ function dispatch(key) {
345
407
  function nextKey() {
346
408
  if (queue.length) return Promise.resolve(queue.shift());
347
409
  if (preSessionKeys.length) return Promise.resolve(preSessionKeys.shift());
410
+ // The stream is over and nothing is queued: answer STREAM_END instead of
411
+ // parking. Without this latch the EOF resolution is a one-instant event —
412
+ // `resetKeyStream()` wakes the waiters that happen to be parked when it runs,
413
+ // and a loop that was mid-turn at that moment simply parks again on a stream
414
+ // that is finished and will never emit another byte. That is the hang: the
415
+ // session never settles, so the teardown and the resume hint are skipped and
416
+ // the process only ends when the event loop drains by itself.
417
+ if (streamEnded) return Promise.resolve(STREAM_END);
348
418
  return new Promise((resolve) => waiting.push(resolve));
349
419
  }
350
420
 
@@ -408,6 +478,7 @@ function detachKeyStream() {
408
478
  } catch {
409
479
  /* stream already gone */
410
480
  }
481
+ detachEndHandler(attachedStdin);
411
482
  try {
412
483
  if (typeof attachedStdin.setRawMode === 'function') attachedStdin.setRawMode(false);
413
484
  } catch {
@@ -444,6 +515,7 @@ function resetKeyStream() {
444
515
  }
445
516
  attachedStdin = null;
446
517
  onData = null;
518
+ onEnd = null;
447
519
  suspended = false;
448
520
  }
449
521
 
package/src/render.js CHANGED
@@ -242,8 +242,9 @@ function assistantLines(ctx, text, width) {
242
242
 
243
243
  /**
244
244
  * One transcript turn: a `❯`-prefixed user line, an assistant answer whose
245
- * first line carries the `●` marker (and a `●` cursor while streaming), a tool
246
- * line with its `⎿ $ …` hook row, and each turn's accounting line beneath.
245
+ * first line carries the `●` marker (and, on a multi-line streaming answer, a
246
+ * `●` cursor on its last line), a tool line with its `⎿ $ …` hook row, and
247
+ * each turn's accounting line beneath.
247
248
  */
248
249
  function renderTurn(ctx, turn, width = 80) {
249
250
  const t = themeOf(ctx);
@@ -261,7 +262,9 @@ function renderTurn(ctx, turn, width = 80) {
261
262
  const body = assistantLines(ctx, text, Math.max(8, width - 2));
262
263
  if (!body.length) body.push('');
263
264
  body[0] = `${t.white}${GLYPH.block}${RESET} ` + body[0];
264
- if (turn.streaming) body[body.length - 1] += `${t.white}${GLYPH.block}${RESET}`;
265
+ // Two lines minimum, or the cursor lands on the marker's own line and a
266
+ // one-line answer prints `● Working●` — two dots where there should be one.
267
+ if (turn.streaming && body.length > 1) body[body.length - 1] += `${t.white}${GLYPH.block}${RESET}`;
265
268
  lines.push(...body);
266
269
  } else if (role === 'tool') {
267
270
  // turn.ok is only known once the call has actually run (the agent loop's
@@ -650,6 +650,12 @@ function createClient(opts = {}) {
650
650
  includeUsage,
651
651
  signal,
652
652
  extra,
653
+ // Opt-in only: the caller (the agent loop, which already knows whether
654
+ // the tools it just attached to `extra` are code-capable) decides
655
+ // whether this turn needs one — this file has no policy of its own for
656
+ // when to attach it, only how. See aegis1 services/agent_gate.py
657
+ // CODE_TOOLS for the server-side verb list a caller should mirror.
658
+ agentKey,
653
659
  } = {}) {
654
660
  // Model-first: an explicit `model` pins that provider id verbatim; with no
655
661
  // model the server picks its default (no client-invented tier id). `mode`
@@ -670,8 +676,9 @@ function createClient(opts = {}) {
670
676
  };
671
677
  if (model) body.model = model;
672
678
  else if (mode) body.mode = mode;
679
+ const headers = authHeaders(agentKey ? { 'X-AEGIS-Agent-Key': agentKey } : undefined);
673
680
  if (!stream || typeof onStream !== 'function') {
674
- return apiPost('/api/v1/chat/completions', { ...body, stream: false });
681
+ return apiPost('/api/v1/chat/completions', { ...body, stream: false }, headers);
675
682
  }
676
683
  // An OpenAI-compatible SSE response carries no `usage` unless the caller
677
684
  // asks for it (`stream_options.include_usage`). Without this the streamed
@@ -682,7 +689,7 @@ function createClient(opts = {}) {
682
689
  // is invalid alongside `stream:false`, so the non-stream branch above and
683
690
  // every non-stream fallback must stay clean.
684
691
  if (includeUsage) body.stream_options = { include_usage: true };
685
- return postStream('/api/v1/chat/completions', body, authHeaders(), onStream, signal, {
692
+ return postStream('/api/v1/chat/completions', body, headers, onStream, signal, {
686
693
  onReasoning,
687
694
  idleTimeoutMs,
688
695
  // A server that predates `stream_options` 400s the whole request; the
@@ -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
@@ -310,6 +564,15 @@ function setEnvValue(name, value, o = {}) {
310
564
  out.error = `refusing to write "${name}" — an env var name is [A-Za-z_][A-Za-z0-9_]*`;
311
565
  return out;
312
566
  }
567
+ // The lock on the split: this file holds host keys, so a name that is not a
568
+ // host key is refused rather than written. Saying so is the point — the
569
+ // alternative (writing it and declining to load it) would recreate the exact
570
+ // state the split removed, with the value still on disk in the shared file.
571
+ if (isForeignSecret(name)) {
572
+ out.error = `refusing to write ${name} to ${ENV_FILE} — it is a production secret, not a host key;`
573
+ + ` put it in ${SECRETS_FILE} (or use loadForeignSecrets)`;
574
+ return out;
575
+ }
313
576
  const secret = String(value == null ? '' : value).trim();
314
577
  if (!secret) {
315
578
  out.error = `refusing to write an empty ${name}`;
@@ -566,4 +829,14 @@ module.exports = {
566
829
  clearEnvValue,
567
830
  keyStatus,
568
831
  keyForModelId,
832
+ // The split: the second file, the list that decides what may not be loaded,
833
+ // and the reader a process that genuinely needs a billing token calls.
834
+ SECRETS_FILE,
835
+ FOREIGN_SECRET_NAMES,
836
+ FOREIGN_SECRET_PREFIXES,
837
+ isForeignSecret,
838
+ secretEnvFileFor,
839
+ loadForeignSecrets,
840
+ foreignSecretValue,
841
+ splitForeignSecrets,
569
842
  };
@@ -1107,6 +1107,17 @@ function createLocalEngine({
1107
1107
  ...(opts.tools.length ? { tools: opts.tools } : {}),
1108
1108
  ...(opts.toolChoice ? { tool_choice: opts.toolChoice } : {}),
1109
1109
  },
1110
+ // aegis1's agent-key gate (services/agent_gate.py) 403s a pooled turn
1111
+ // whose `tools` names a code-capable verb (writeFile/editFile/exec —
1112
+ // this engine's builtin set — normalise to the server's CODE_TOOLS
1113
+ // entries) unless X-AEGIS-Agent-Key is attached. `AEGIS_API_KEY` says
1114
+ // who pays; this says who may change code, and is deliberately a
1115
+ // separate credential (see agent_gate.py's module docstring). Read
1116
+ // from `~/.aegiscode/.env` via the same loadEnvFile() both hosts
1117
+ // already run at startup — no new key store. Absent by default: an
1118
+ // account with no agent key simply gets the same 403 as before,
1119
+ // scoped to turns that actually carry tools.
1120
+ agentKey: opts.tools.length ? (process.env.AEGIS_AGENT_KEY || '').trim() || undefined : undefined,
1110
1121
  });
1111
1122
  }
1112
1123