aegiscode 6.8.13 → 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.13",
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/app.js CHANGED
@@ -1879,7 +1879,14 @@ function createApp(options = {}) {
1879
1879
  // byte that was not the answer is handed back to the key pump's own queue
1880
1880
  // rather than to the stream: `events.feedKeys` delivers it exactly as a
1881
1881
  // `data` event would have, including after stdin has ended.
1882
- await probeTerminalBackground({ onLeftover: (text) => events.feedKeys(text) });
1882
+ // `keystrokes: true` matters. The probe hands back a whole burst, and a
1883
+ // command issued at launch (`/exit\r`) arrives as one string containing a
1884
+ // newline — which the paste heuristic would otherwise collapse into a
1885
+ // single paste key, losing the Enter and parking the session loop forever
1886
+ // at the welcome screen. See `events.feedKeys`.
1887
+ await probeTerminalBackground({
1888
+ onLeftover: (text) => events.feedKeys(text, { keystrokes: true }),
1889
+ });
1883
1890
  restorePrefs();
1884
1891
  themeNoticeFirstRun();
1885
1892
  adoptLegacyKeyOnce();
package/src/caps.js CHANGED
@@ -380,13 +380,20 @@ function probeBackground({ stdin = process.stdin, stdout = process.stdout, timeo
380
380
  if (settled) return;
381
381
  settled = true;
382
382
  if (timer) clearTimeout(timer);
383
+ // Pause BEFORE dropping the listener. In flowing mode a chunk emitted
384
+ // between `removeListener` and `pause` has no subscriber and is silently
385
+ // discarded — and that gap is a real window, not a theoretical one: with
386
+ // the probe on, 1 run in 10 lost the command typed at launch and hung at
387
+ // the fully-drawn welcome screen (9120 bytes, no exit). Pausing first
388
+ // stops the flow and leaves any in-flight bytes in the readable buffer,
389
+ // where the session pump's `resume()` collects them.
390
+ stdin.pause();
383
391
  stdin.removeListener('data', onData);
384
392
  try {
385
393
  if (!wasRaw) stdin.setRawMode(false);
386
394
  } catch {
387
395
  /* the terminal closed under us; the read end is already gone */
388
396
  }
389
- stdin.pause();
390
397
  if (leftover) {
391
398
  // Bytes that were not the answer belong to the session, not to us.
392
399
  // `onLeftover` routes them back through the caller's key queue, which
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
@@ -26,6 +26,29 @@ const { decodeEscSequence, decodePlain, KEY } = require('./keys.js');
26
26
  const queue = [];
27
27
  let waiting = [];
28
28
 
29
+ /**
30
+ * Keys handed in from OUTSIDE the pump before any pump existed — the startup
31
+ * background probe is the only caller (see `feedKeys`).
32
+ *
33
+ * Why this is not just `queue`. A `resetKeyStream()` clears the queue on
34
+ * purpose: typed-ahead from a dead session must not land in the next one. But
35
+ * the probe runs BEFORE onboarding and BEFORE the session loop, and onboarding
36
+ * attaches a pump of its own and detaches it in a `finally` — so an early
37
+ * command was being queued, then wiped by that detach, and the session loop
38
+ * that followed waited forever for input that had already been read and
39
+ * thrown away.
40
+ *
41
+ * That is a real user-visible bug, not just a test artefact: anything typed
42
+ * while the CLI is still starting up was silently dropped. It also made
43
+ * `test/cli-platform-parity.test.mjs` fail roughly 4 runs in 10 on a SINGLE
44
+ * platform — same code, same machine — which is why "parity" kept being
45
+ * reported as broken and re-fixed for a day. Bytes captured before any session
46
+ * existed belong to the session that has not started yet, so they survive a
47
+ * session teardown and are delivered to the first consumer that asks.
48
+ */
49
+ let preSessionKeys = [];
50
+ let everAttached = false;
51
+
29
52
  /**
30
53
  * Handed to every parked `nextKey()` waiter when the pump is reset, so a
31
54
  * consumer can tell "the stream went away" from "the user pressed nothing".
@@ -53,7 +76,12 @@ const looksLikePaste = (s) => {
53
76
 
54
77
  let attachedStdin = null;
55
78
  let onData = null;
79
+ let onEnd = null;
56
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;
57
85
 
58
86
  function isKeyStreamSuspended() {
59
87
  return suspended;
@@ -61,13 +89,85 @@ function isKeyStreamSuspended() {
61
89
 
62
90
  function attachKeyStream(stdin) {
63
91
  attachedStdin = stdin;
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;
64
96
  onData = (chunk) => pushChars(String(chunk));
97
+ // Before the listener goes on, take anything the terminal already delivered
98
+ // while NOTHING owned the stream. That window is real: the startup background
99
+ // probe resumes stdin, then pauses it again when it finishes, so a command
100
+ // typed at launch can be sitting in the Readable's buffer — and `resume()`
101
+ // below emits from a state we do not control, which is why the pty sweep hung
102
+ // on 1 run in 10 with the frame fully drawn and no command ever seen. Pulling
103
+ // the buffer out first makes the handoff explicit instead of raced.
104
+ try {
105
+ if (typeof stdin.read === 'function') {
106
+ for (let i = 0; i < 64; i += 1) {
107
+ const buffered = stdin.read();
108
+ if (buffered === null) break;
109
+ feedKeys(String(buffered), { keystrokes: true });
110
+ }
111
+ }
112
+ } catch {
113
+ /* a stream without the Readable surface: resume() is all we ever had */
114
+ }
65
115
  // A non-TTY stdin has no setRawMode at all; guard it so callers degrade
66
116
  // instead of throwing "stdin.setRawMode is not a function".
67
117
  if (typeof stdin.setRawMode === 'function') stdin.setRawMode(true);
68
118
  stdin.resume();
69
119
  stdin.setEncoding('utf8');
70
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
+ }
71
171
  }
72
172
 
73
173
  /** Hand the terminal to a child process: detach the pump and drop half-parsed
@@ -76,6 +176,9 @@ function suspendKeyStream() {
76
176
  if (!attachedStdin || suspended) return;
77
177
  suspended = true;
78
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);
79
182
  clearTimeout(escTimer);
80
183
  seq = '';
81
184
  buffer = '';
@@ -102,6 +205,7 @@ function resumeKeyStream() {
102
205
  attachedStdin.resume();
103
206
  attachedStdin.setEncoding('utf8');
104
207
  attachedStdin.on('data', onData);
208
+ attachEndHandler(attachedStdin);
105
209
  }
106
210
 
107
211
  function flushPaste() {
@@ -138,8 +242,42 @@ function flushPaste() {
138
242
  * receives. This runs through the queue instead, which `drainQueue`/`nextKey`
139
243
  * consult regardless of the stream's state.
140
244
  */
141
- function feedKeys(text) {
142
- if (text) pushChars(String(text));
245
+ function feedKeys(text, { keystrokes = false } = {}) {
246
+ if (!text) return;
247
+ const s = String(text);
248
+ // A handback from the startup probe is a burst of KEYSTROKES that raced the
249
+ // OSC-11 reply, not a paste — and the difference is not cosmetic. The probe
250
+ // reads whatever arrived before its 120ms deadline and hands it back as one
251
+ // string, so a command typed the instant the CLI started arrives as
252
+ // `"/exit\n\x04"` in a single call. `pushChars` sees the embedded newline,
253
+ // declares it a paste, and `flushPaste` collapses it into ONE `{name:'paste'}`
254
+ // key — so the session loop never receives the Enter and parks on `nextKey()`
255
+ // forever. Measured: 10/10 runs hung at 5029 bytes with the probe on, 10/10
256
+ // clean at 9113 bytes with it off. Replaying as keystrokes gives the loop the
257
+ // same sequence a `data` event would have: `/`, `e`, `x`, `i`, `t`, `enter`.
258
+ //
259
+ // The size guard keeps the other case honest: a real paste large enough to
260
+ // matter (or an explicit bracketed-paste frame) still takes the paste path,
261
+ // because feeding 10k characters through the decoder one at a time is the
262
+ // thing the heuristic exists to avoid.
263
+ if (keystrokes && s.length <= PASTE_LARGE && !s.includes('\x1b[200~')) {
264
+ feedChars(s);
265
+ return;
266
+ }
267
+ pushChars(s);
268
+ }
269
+
270
+ /** Decode a run of characters into keys, preserving multi-byte boundaries. */
271
+ function feedChars(s) {
272
+ buffer += s;
273
+ while (buffer.length) {
274
+ const cp = buffer.codePointAt(0);
275
+ const c = String.fromCodePoint(cp);
276
+ const units = c.length;
277
+ if (units > buffer.length) break; // incomplete multi-byte char
278
+ buffer = buffer.slice(units);
279
+ feed(c);
280
+ }
143
281
  }
144
282
 
145
283
  function pushChars(s) {
@@ -162,15 +300,7 @@ function pushChars(s) {
162
300
  pasteTimer = setTimeout(flushPaste, PASTE_DEBOUNCE_MS);
163
301
  return;
164
302
  }
165
- buffer += s;
166
- while (buffer.length) {
167
- const cp = buffer.codePointAt(0);
168
- const c = String.fromCodePoint(cp);
169
- const units = c.length;
170
- if (units > buffer.length) break; // incomplete multi-byte char
171
- buffer = buffer.slice(units);
172
- feed(c);
173
- }
303
+ feedChars(s);
174
304
  }
175
305
 
176
306
  function feed(c) {
@@ -264,6 +394,10 @@ function dispatch(key) {
264
394
  if (waiting.length) {
265
395
  const w = waiting.shift();
266
396
  w(key);
397
+ } else if (!everAttached) {
398
+ // Nothing has ever consumed keys, so this is startup input: hold it where a
399
+ // session reset cannot reach it.
400
+ preSessionKeys.push(key);
267
401
  } else {
268
402
  queue.push(key);
269
403
  }
@@ -272,6 +406,15 @@ function dispatch(key) {
272
406
  /** The next key, waiting as long as it takes. */
273
407
  function nextKey() {
274
408
  if (queue.length) return Promise.resolve(queue.shift());
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);
275
418
  return new Promise((resolve) => waiting.push(resolve));
276
419
  }
277
420
 
@@ -284,6 +427,7 @@ function nextKey() {
284
427
  */
285
428
  function nextKeyTimeout(ms) {
286
429
  if (queue.length) return Promise.resolve(queue.shift());
430
+ if (preSessionKeys.length) return Promise.resolve(preSessionKeys.shift());
287
431
  return new Promise((resolve) => {
288
432
  const timer = setTimeout(() => {
289
433
  const i = waiting.indexOf(wrapper);
@@ -306,6 +450,9 @@ function requeueKeys(keys) {
306
450
  }
307
451
 
308
452
  function drainQueue() {
453
+ // Only this session's keys. `preSessionKeys` is deliberately left alone: it
454
+ // holds input captured before any session existed, and clearing it here is
455
+ // exactly the bug its comment describes.
309
456
  queue.length = 0;
310
457
  }
311
458
 
@@ -331,6 +478,7 @@ function detachKeyStream() {
331
478
  } catch {
332
479
  /* stream already gone */
333
480
  }
481
+ detachEndHandler(attachedStdin);
334
482
  try {
335
483
  if (typeof attachedStdin.setRawMode === 'function') attachedStdin.setRawMode(false);
336
484
  } catch {
@@ -367,6 +515,7 @@ function resetKeyStream() {
367
515
  }
368
516
  attachedStdin = null;
369
517
  onData = null;
518
+ onEnd = null;
370
519
  suspended = false;
371
520
  }
372
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
@@ -65,6 +65,50 @@ function envIdleMs(name) {
65
65
  return Number.isFinite(n) && n > 0 ? n : 0;
66
66
  }
67
67
 
68
+ /**
69
+ * DeepSeek's chat template wraps tool calls and turn boundaries in special
70
+ * tokens — fullwidth pipe (U+FF5C) delimiting an identifier that uses ▁
71
+ * (U+2581) as its word separator, e.g. |tool▁calls▁begin|, |tool▁call▁end|,
72
+ * |Assistant|, |begin▁of▁sentence|. These are chat-template internals, never
73
+ * user-facing text; when the provider's streaming tool-call path leaks them
74
+ * into `delta.content` they used to reach the screen verbatim — reported as
75
+ * the pasted "||DSML||" envelope on Windows/macOS. Returns a per-stream
76
+ * stripper closure with a short lookback buffer so a token split across two
77
+ * SSE chunks isn't half-rendered before its closing pipe arrives.
78
+ */
79
+ const DEEPSEEK_ENVELOPE_RE = /|[A-Za-z][A-Za-z0-9]*(?:▁[A-Za-z0-9]+)*|/g;
80
+ function makeDeepSeekEnvelopeStripper() {
81
+ let buf = '';
82
+ const strip = (chunk) => {
83
+ buf += chunk;
84
+ buf = buf.replace(DEEPSEEK_ENVELOPE_RE, '');
85
+ const openIdx = buf.lastIndexOf('|');
86
+ if (openIdx !== -1) {
87
+ const tail = buf.slice(openIdx);
88
+ // Held back only while the tail still looks like an in-progress token
89
+ // (no closing pipe yet); a bare '|' or genuine prose flushes normally.
90
+ if (tail.length <= 60 && /^|[A-Za-z0-9▁]*$/.test(tail)) {
91
+ const out = buf.slice(0, openIdx);
92
+ buf = tail;
93
+ return out;
94
+ }
95
+ }
96
+ const out = buf;
97
+ buf = '';
98
+ return out;
99
+ };
100
+ // Unconditional release of whatever is left buffered — called once the
101
+ // stream is fully drained, when a held-back '|…' is known to never close
102
+ // (dropped connection, or it was real prose all along) rather than an
103
+ // in-progress token.
104
+ strip.flush = () => {
105
+ const out = buf;
106
+ buf = '';
107
+ return out;
108
+ };
109
+ return strip;
110
+ }
111
+
68
112
  /**
69
113
  * UUID v4 that works everywhere: Web Crypto first (browsers, Node ≥ 19),
70
114
  * then Node's CJS crypto module (Node < 19), then a Math.random fallback for
@@ -221,10 +265,26 @@ function createClient(opts = {}) {
221
265
  }
222
266
  throw err;
223
267
  } finally {
268
+ // The timeout is time-to-*headers* only, so it is cleared the moment the
269
+ // response resolves: a long generation must never be cut off by it.
224
270
  if (timer) clearTimeout(timer);
225
- if (controller && callerSignal && typeof callerSignal.removeEventListener === 'function') {
226
- callerSignal.removeEventListener('abort', onAbort);
227
- }
271
+ // …but the caller's abort bridge is deliberately NOT removed here.
272
+ //
273
+ // `fetch` resolves at the status line, while the RESPONSE BODY is still
274
+ // bound to `controller.signal` and keeps being read long after this
275
+ // function has returned. Unhooking the caller's signal at that point
276
+ // detached Stop/Escape from the stream it was supposed to stop: the
277
+ // engine's own controller really did abort — `engine.cancel()` answered
278
+ // `{ ok: true }`, so the right controller was found and `abort()` was
279
+ // really called — and nothing happened, because the only thing wired to
280
+ // the live body had already been told to stop listening. The turn then
281
+ // streamed to completion while the UI sat on "stopping…", never settled,
282
+ // and never produced the salvaged bubble, because no error ever reached
283
+ // the caller's catch.
284
+ //
285
+ // `once: true` plus one signal per turn bounds the cost of leaving it
286
+ // attached to a single listener per turn — a far smaller price than a
287
+ // cancel button that does nothing.
228
288
  }
229
289
  }
230
290
 
@@ -590,6 +650,12 @@ function createClient(opts = {}) {
590
650
  includeUsage,
591
651
  signal,
592
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,
593
659
  } = {}) {
594
660
  // Model-first: an explicit `model` pins that provider id verbatim; with no
595
661
  // model the server picks its default (no client-invented tier id). `mode`
@@ -610,8 +676,9 @@ function createClient(opts = {}) {
610
676
  };
611
677
  if (model) body.model = model;
612
678
  else if (mode) body.mode = mode;
679
+ const headers = authHeaders(agentKey ? { 'X-AEGIS-Agent-Key': agentKey } : undefined);
613
680
  if (!stream || typeof onStream !== 'function') {
614
- return apiPost('/api/v1/chat/completions', { ...body, stream: false });
681
+ return apiPost('/api/v1/chat/completions', { ...body, stream: false }, headers);
615
682
  }
616
683
  // An OpenAI-compatible SSE response carries no `usage` unless the caller
617
684
  // asks for it (`stream_options.include_usage`). Without this the streamed
@@ -622,7 +689,7 @@ function createClient(opts = {}) {
622
689
  // is invalid alongside `stream:false`, so the non-stream branch above and
623
690
  // every non-stream fallback must stay clean.
624
691
  if (includeUsage) body.stream_options = { include_usage: true };
625
- return postStream('/api/v1/chat/completions', body, authHeaders(), onStream, signal, {
692
+ return postStream('/api/v1/chat/completions', body, headers, onStream, signal, {
626
693
  onReasoning,
627
694
  idleTimeoutMs,
628
695
  // A server that predates `stream_options` 400s the whole request; the
@@ -838,6 +905,15 @@ function createClient(opts = {}) {
838
905
  // resolve with text only and the caller could never see the calls.
839
906
  const toolCallsByIndex = new Map();
840
907
  let finishReason = null;
908
+ // `fullText` above stays RAW (it is also the `seen` cursor the snapshot
909
+ // reconciliation below compares against the provider's own un-stripped
910
+ // snapshots); `cleanText` is what the caller actually receives — the same
911
+ // stream, with DeepSeek's chat-template envelope removed — and is what the
912
+ // final `message.content` below is built from, so a non-streaming caller
913
+ // reading the resolved result sees the same clean text a streaming caller
914
+ // already saw via `onStream`.
915
+ let cleanText = '';
916
+ const stripEnvelope = makeDeepSeekEnvelopeStripper();
841
917
 
842
918
  // Idle watchdog: if the server holds the connection open without ever
843
919
  // sending another byte (a stuck upstream call, a proxy that swallows the
@@ -863,6 +939,7 @@ function createClient(opts = {}) {
863
939
  let keepAlives = 0;
864
940
  async function readWithIdleTimeout() {
865
941
  let timer;
942
+ let onAbort = null;
866
943
  const remaining = Math.max(0, idleMs - (Date.now() - lastPayloadAt));
867
944
  const timeout = new Promise((_, reject) => {
868
945
  timer = setTimeout(() => {
@@ -873,10 +950,37 @@ function createClient(opts = {}) {
873
950
  ));
874
951
  }, remaining);
875
952
  });
953
+ // The caller's abort, raced against the read directly rather than trusted
954
+ // to propagate through the body stream.
955
+ //
956
+ // Whether an abort of the caller's signal reaches a response body that is
957
+ // already being read is a property of `boundedFetch`, not of this loop —
958
+ // and it is not a property this loop can observe. Racing here makes "the
959
+ // caller stopped" a fact the read loop establishes for itself, so Stop
960
+ // and Escape end the turn at the next chunk boundary regardless of how
961
+ // the request's signal was assembled. Without it an aborted turn kept
962
+ // consuming a stream nobody wanted and `chat()` never settled at all.
963
+ const aborted = signal && typeof signal.addEventListener === 'function'
964
+ ? new Promise((_, reject) => {
965
+ onAbort = () => {
966
+ const e = new Error('The turn was stopped.');
967
+ e.name = 'AbortError';
968
+ e.code = 'ABORT_ERR';
969
+ reject(e);
970
+ };
971
+ if (signal.aborted) onAbort();
972
+ else signal.addEventListener('abort', onAbort, { once: true });
973
+ })
974
+ : null;
876
975
  try {
877
- return await Promise.race([reader.read(), timeout]);
976
+ return await (aborted
977
+ ? Promise.race([reader.read(), timeout, aborted])
978
+ : Promise.race([reader.read(), timeout]));
878
979
  } finally {
879
980
  clearTimeout(timer);
981
+ if (signal && onAbort && typeof signal.removeEventListener === 'function') {
982
+ signal.removeEventListener('abort', onAbort);
983
+ }
880
984
  }
881
985
  }
882
986
 
@@ -969,7 +1073,13 @@ function createClient(opts = {}) {
969
1073
  choice && choice.delta && choice.delta.content,
970
1074
  choice && choice.message && choice.message.content,
971
1075
  fullText,
972
- (chunk) => onStream({ delta: chunk })
1076
+ (chunk) => {
1077
+ const clean = stripEnvelope(chunk);
1078
+ if (clean) {
1079
+ cleanText += clean;
1080
+ onStream({ delta: clean });
1081
+ }
1082
+ }
973
1083
  );
974
1084
  const fragments =
975
1085
  (choice && choice.delta && choice.delta.tool_calls) ||
@@ -999,13 +1109,22 @@ function createClient(opts = {}) {
999
1109
  throw err;
1000
1110
  }
1001
1111
 
1112
+ // A trailing '|…' that never closed (stream ended right after it, or it
1113
+ // was real prose all along) is real content, not an unfinished envelope
1114
+ // token — release it rather than dropping it silently.
1115
+ const strayTail = stripEnvelope.flush();
1116
+ if (strayTail) {
1117
+ cleanText += strayTail;
1118
+ onStream({ delta: strayTail });
1119
+ }
1120
+
1002
1121
  // An id-less fragment stream still yields usable calls, but the caller
1003
1122
  // needs *an* id to pair results back, so synthesize one.
1004
1123
  const toolCalls = [...toolCallsByIndex.entries()]
1005
1124
  .sort((a, b) => a[0] - b[0])
1006
1125
  .map(([idx, c]) => ({ ...c, id: c.id || `call_${idx}` }));
1007
1126
 
1008
- const message = { content: fullText };
1127
+ const message = { content: cleanText };
1009
1128
  if (toolCalls.length) message.tool_calls = toolCalls;
1010
1129
  const result = {
1011
1130
  model: resultModel,
@@ -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
 
@@ -58,6 +58,45 @@ function baseOf(baseURL) {
58
58
  return String(baseURL || DEFAULT_BASE).replace(/\/+$/, '');
59
59
  }
60
60
 
61
+ /**
62
+ * DeepSeek's chat template (also the one a locally-pulled `deepseek-*` Ollama
63
+ * model uses) wraps tool calls and turn boundaries in special tokens —
64
+ * fullwidth pipe (U+FF5C) delimiting an identifier that uses ▁ (U+2581) as its
65
+ * word separator, e.g. |tool▁calls▁begin|, |tool▁call▁end|, |Assistant|,
66
+ * |begin▁of▁sentence|. These are chat-template internals, never user-facing
67
+ * text; when the local daemon's tool-call path leaks them into `delta.content`
68
+ * they used to reach the screen verbatim — reported as the pasted
69
+ * "||DSML||" envelope. Returns a per-turn stripper closure with a short
70
+ * lookback buffer so a token split across two SSE chunks isn't half-rendered
71
+ * before its closing pipe arrives.
72
+ */
73
+ const DEEPSEEK_ENVELOPE_RE = /|[A-Za-z][A-Za-z0-9]*(?:▁[A-Za-z0-9]+)*|/g;
74
+ function makeDeepSeekEnvelopeStripper() {
75
+ let buf = '';
76
+ const strip = (chunk) => {
77
+ buf += chunk;
78
+ buf = buf.replace(DEEPSEEK_ENVELOPE_RE, '');
79
+ const openIdx = buf.lastIndexOf('|');
80
+ if (openIdx !== -1) {
81
+ const tail = buf.slice(openIdx);
82
+ if (tail.length <= 60 && /^|[A-Za-z0-9▁]*$/.test(tail)) {
83
+ const out = buf.slice(0, openIdx);
84
+ buf = tail;
85
+ return out;
86
+ }
87
+ }
88
+ const out = buf;
89
+ buf = '';
90
+ return out;
91
+ };
92
+ strip.flush = () => {
93
+ const out = buf;
94
+ buf = '';
95
+ return out;
96
+ };
97
+ return strip;
98
+ }
99
+
61
100
  /**
62
101
  * Whether a base URL addresses hardware on this machine (or on this private
63
102
  * network) — the gate that decides whether the free lane exists at all.
@@ -369,6 +408,7 @@ async function chat({
369
408
  let usage = null;
370
409
  const toolCalls = [];
371
410
  const byIndex = new Map();
411
+ const stripEnvelope = makeDeepSeekEnvelopeStripper();
372
412
 
373
413
  await readSSE(
374
414
  res,
@@ -378,8 +418,11 @@ async function chat({
378
418
  if (!choice) return;
379
419
  const delta = choice.delta || {};
380
420
  if (typeof delta.content === 'string' && delta.content) {
381
- content += delta.content;
382
- if (typeof onDelta === 'function') onDelta({ text: delta.content });
421
+ const clean = stripEnvelope(delta.content);
422
+ if (clean) {
423
+ content += clean;
424
+ if (typeof onDelta === 'function') onDelta({ text: clean });
425
+ }
383
426
  }
384
427
  const frags = delta.tool_calls || [];
385
428
  for (const f of frags) {
@@ -399,6 +442,15 @@ async function chat({
399
442
  { idleTimeoutMs: SSE_IDLE_TIMEOUT_MS }
400
443
  );
401
444
 
445
+ // A trailing '|…' that never closed (stream ended right after it, or it
446
+ // was real prose all along) is real content, not an unfinished envelope
447
+ // token — release it rather than dropping it silently.
448
+ const strayTail = stripEnvelope.flush();
449
+ if (strayTail) {
450
+ content += strayTail;
451
+ if (typeof onDelta === 'function') onDelta({ text: strayTail });
452
+ }
453
+
402
454
  for (const [i, acc] of [...byIndex.entries()].sort((a, b) => a[0] - b[0])) {
403
455
  if (!acc.function.name && !acc.function.arguments) continue;
404
456
  // Ollama does not always mint an id; the engine's tool loop keys results