aegiscode 6.8.13 → 6.8.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "aegiscode",
3
3
  "productName": "AEGIS Code",
4
- "version": "6.8.13",
4
+ "version": "6.8.14",
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/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".
@@ -61,7 +84,26 @@ function isKeyStreamSuspended() {
61
84
 
62
85
  function attachKeyStream(stdin) {
63
86
  attachedStdin = stdin;
87
+ everAttached = true;
64
88
  onData = (chunk) => pushChars(String(chunk));
89
+ // Before the listener goes on, take anything the terminal already delivered
90
+ // while NOTHING owned the stream. That window is real: the startup background
91
+ // probe resumes stdin, then pauses it again when it finishes, so a command
92
+ // typed at launch can be sitting in the Readable's buffer — and `resume()`
93
+ // below emits from a state we do not control, which is why the pty sweep hung
94
+ // on 1 run in 10 with the frame fully drawn and no command ever seen. Pulling
95
+ // the buffer out first makes the handoff explicit instead of raced.
96
+ try {
97
+ if (typeof stdin.read === 'function') {
98
+ for (let i = 0; i < 64; i += 1) {
99
+ const buffered = stdin.read();
100
+ if (buffered === null) break;
101
+ feedKeys(String(buffered), { keystrokes: true });
102
+ }
103
+ }
104
+ } catch {
105
+ /* a stream without the Readable surface: resume() is all we ever had */
106
+ }
65
107
  // A non-TTY stdin has no setRawMode at all; guard it so callers degrade
66
108
  // instead of throwing "stdin.setRawMode is not a function".
67
109
  if (typeof stdin.setRawMode === 'function') stdin.setRawMode(true);
@@ -138,8 +180,42 @@ function flushPaste() {
138
180
  * receives. This runs through the queue instead, which `drainQueue`/`nextKey`
139
181
  * consult regardless of the stream's state.
140
182
  */
141
- function feedKeys(text) {
142
- if (text) pushChars(String(text));
183
+ function feedKeys(text, { keystrokes = false } = {}) {
184
+ if (!text) return;
185
+ const s = String(text);
186
+ // A handback from the startup probe is a burst of KEYSTROKES that raced the
187
+ // OSC-11 reply, not a paste — and the difference is not cosmetic. The probe
188
+ // reads whatever arrived before its 120ms deadline and hands it back as one
189
+ // string, so a command typed the instant the CLI started arrives as
190
+ // `"/exit\n\x04"` in a single call. `pushChars` sees the embedded newline,
191
+ // declares it a paste, and `flushPaste` collapses it into ONE `{name:'paste'}`
192
+ // key — so the session loop never receives the Enter and parks on `nextKey()`
193
+ // forever. Measured: 10/10 runs hung at 5029 bytes with the probe on, 10/10
194
+ // clean at 9113 bytes with it off. Replaying as keystrokes gives the loop the
195
+ // same sequence a `data` event would have: `/`, `e`, `x`, `i`, `t`, `enter`.
196
+ //
197
+ // The size guard keeps the other case honest: a real paste large enough to
198
+ // matter (or an explicit bracketed-paste frame) still takes the paste path,
199
+ // because feeding 10k characters through the decoder one at a time is the
200
+ // thing the heuristic exists to avoid.
201
+ if (keystrokes && s.length <= PASTE_LARGE && !s.includes('\x1b[200~')) {
202
+ feedChars(s);
203
+ return;
204
+ }
205
+ pushChars(s);
206
+ }
207
+
208
+ /** Decode a run of characters into keys, preserving multi-byte boundaries. */
209
+ function feedChars(s) {
210
+ buffer += s;
211
+ while (buffer.length) {
212
+ const cp = buffer.codePointAt(0);
213
+ const c = String.fromCodePoint(cp);
214
+ const units = c.length;
215
+ if (units > buffer.length) break; // incomplete multi-byte char
216
+ buffer = buffer.slice(units);
217
+ feed(c);
218
+ }
143
219
  }
144
220
 
145
221
  function pushChars(s) {
@@ -162,15 +238,7 @@ function pushChars(s) {
162
238
  pasteTimer = setTimeout(flushPaste, PASTE_DEBOUNCE_MS);
163
239
  return;
164
240
  }
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
- }
241
+ feedChars(s);
174
242
  }
175
243
 
176
244
  function feed(c) {
@@ -264,6 +332,10 @@ function dispatch(key) {
264
332
  if (waiting.length) {
265
333
  const w = waiting.shift();
266
334
  w(key);
335
+ } else if (!everAttached) {
336
+ // Nothing has ever consumed keys, so this is startup input: hold it where a
337
+ // session reset cannot reach it.
338
+ preSessionKeys.push(key);
267
339
  } else {
268
340
  queue.push(key);
269
341
  }
@@ -272,6 +344,7 @@ function dispatch(key) {
272
344
  /** The next key, waiting as long as it takes. */
273
345
  function nextKey() {
274
346
  if (queue.length) return Promise.resolve(queue.shift());
347
+ if (preSessionKeys.length) return Promise.resolve(preSessionKeys.shift());
275
348
  return new Promise((resolve) => waiting.push(resolve));
276
349
  }
277
350
 
@@ -284,6 +357,7 @@ function nextKey() {
284
357
  */
285
358
  function nextKeyTimeout(ms) {
286
359
  if (queue.length) return Promise.resolve(queue.shift());
360
+ if (preSessionKeys.length) return Promise.resolve(preSessionKeys.shift());
287
361
  return new Promise((resolve) => {
288
362
  const timer = setTimeout(() => {
289
363
  const i = waiting.indexOf(wrapper);
@@ -306,6 +380,9 @@ function requeueKeys(keys) {
306
380
  }
307
381
 
308
382
  function drainQueue() {
383
+ // Only this session's keys. `preSessionKeys` is deliberately left alone: it
384
+ // holds input captured before any session existed, and clearing it here is
385
+ // exactly the bug its comment describes.
309
386
  queue.length = 0;
310
387
  }
311
388
 
@@ -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
 
@@ -838,6 +898,15 @@ function createClient(opts = {}) {
838
898
  // resolve with text only and the caller could never see the calls.
839
899
  const toolCallsByIndex = new Map();
840
900
  let finishReason = null;
901
+ // `fullText` above stays RAW (it is also the `seen` cursor the snapshot
902
+ // reconciliation below compares against the provider's own un-stripped
903
+ // snapshots); `cleanText` is what the caller actually receives — the same
904
+ // stream, with DeepSeek's chat-template envelope removed — and is what the
905
+ // final `message.content` below is built from, so a non-streaming caller
906
+ // reading the resolved result sees the same clean text a streaming caller
907
+ // already saw via `onStream`.
908
+ let cleanText = '';
909
+ const stripEnvelope = makeDeepSeekEnvelopeStripper();
841
910
 
842
911
  // Idle watchdog: if the server holds the connection open without ever
843
912
  // sending another byte (a stuck upstream call, a proxy that swallows the
@@ -863,6 +932,7 @@ function createClient(opts = {}) {
863
932
  let keepAlives = 0;
864
933
  async function readWithIdleTimeout() {
865
934
  let timer;
935
+ let onAbort = null;
866
936
  const remaining = Math.max(0, idleMs - (Date.now() - lastPayloadAt));
867
937
  const timeout = new Promise((_, reject) => {
868
938
  timer = setTimeout(() => {
@@ -873,10 +943,37 @@ function createClient(opts = {}) {
873
943
  ));
874
944
  }, remaining);
875
945
  });
946
+ // The caller's abort, raced against the read directly rather than trusted
947
+ // to propagate through the body stream.
948
+ //
949
+ // Whether an abort of the caller's signal reaches a response body that is
950
+ // already being read is a property of `boundedFetch`, not of this loop —
951
+ // and it is not a property this loop can observe. Racing here makes "the
952
+ // caller stopped" a fact the read loop establishes for itself, so Stop
953
+ // and Escape end the turn at the next chunk boundary regardless of how
954
+ // the request's signal was assembled. Without it an aborted turn kept
955
+ // consuming a stream nobody wanted and `chat()` never settled at all.
956
+ const aborted = signal && typeof signal.addEventListener === 'function'
957
+ ? new Promise((_, reject) => {
958
+ onAbort = () => {
959
+ const e = new Error('The turn was stopped.');
960
+ e.name = 'AbortError';
961
+ e.code = 'ABORT_ERR';
962
+ reject(e);
963
+ };
964
+ if (signal.aborted) onAbort();
965
+ else signal.addEventListener('abort', onAbort, { once: true });
966
+ })
967
+ : null;
876
968
  try {
877
- return await Promise.race([reader.read(), timeout]);
969
+ return await (aborted
970
+ ? Promise.race([reader.read(), timeout, aborted])
971
+ : Promise.race([reader.read(), timeout]));
878
972
  } finally {
879
973
  clearTimeout(timer);
974
+ if (signal && onAbort && typeof signal.removeEventListener === 'function') {
975
+ signal.removeEventListener('abort', onAbort);
976
+ }
880
977
  }
881
978
  }
882
979
 
@@ -969,7 +1066,13 @@ function createClient(opts = {}) {
969
1066
  choice && choice.delta && choice.delta.content,
970
1067
  choice && choice.message && choice.message.content,
971
1068
  fullText,
972
- (chunk) => onStream({ delta: chunk })
1069
+ (chunk) => {
1070
+ const clean = stripEnvelope(chunk);
1071
+ if (clean) {
1072
+ cleanText += clean;
1073
+ onStream({ delta: clean });
1074
+ }
1075
+ }
973
1076
  );
974
1077
  const fragments =
975
1078
  (choice && choice.delta && choice.delta.tool_calls) ||
@@ -999,13 +1102,22 @@ function createClient(opts = {}) {
999
1102
  throw err;
1000
1103
  }
1001
1104
 
1105
+ // A trailing '|…' that never closed (stream ended right after it, or it
1106
+ // was real prose all along) is real content, not an unfinished envelope
1107
+ // token — release it rather than dropping it silently.
1108
+ const strayTail = stripEnvelope.flush();
1109
+ if (strayTail) {
1110
+ cleanText += strayTail;
1111
+ onStream({ delta: strayTail });
1112
+ }
1113
+
1002
1114
  // An id-less fragment stream still yields usable calls, but the caller
1003
1115
  // needs *an* id to pair results back, so synthesize one.
1004
1116
  const toolCalls = [...toolCallsByIndex.entries()]
1005
1117
  .sort((a, b) => a[0] - b[0])
1006
1118
  .map(([idx, c]) => ({ ...c, id: c.id || `call_${idx}` }));
1007
1119
 
1008
- const message = { content: fullText };
1120
+ const message = { content: cleanText };
1009
1121
  if (toolCalls.length) message.tool_calls = toolCalls;
1010
1122
  const result = {
1011
1123
  model: resultModel,
@@ -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