aegiscode 7.0.24 → 7.0.26

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.
Files changed (113) hide show
  1. package/package.json +7 -3
  2. package/scripts/check.mjs +52 -1
  3. package/scripts/demo.mjs +94 -1
  4. package/scripts/predist.mjs +75 -1
  5. package/scripts/runtests.mjs +56 -1
  6. package/scripts/seal-gate.mjs +74 -1
  7. package/src/agents.js +139 -1
  8. package/src/app.js +2957 -1
  9. package/src/art.js +289 -1
  10. package/src/chatflow.js +3023 -1
  11. package/src/checkpoint.js +90 -1
  12. package/src/clipboard.js +424 -1
  13. package/src/cloudsync.js +528 -1
  14. package/src/commands.js +4089 -1
  15. package/src/config.js +581 -1
  16. package/src/connect.js +349 -1
  17. package/src/credentials.js +33 -1
  18. package/src/deps.js +232 -1
  19. package/src/devrun.js +187 -1
  20. package/src/diff.js +333 -1
  21. package/src/diffview.js +296 -1
  22. package/src/engine.js +297 -1
  23. package/src/entitlement.js +355 -1
  24. package/src/events.js +707 -1
  25. package/src/export.js +67 -1
  26. package/src/filepreview.js +153 -1
  27. package/src/fingerprint.js +592 -1
  28. package/src/format.js +259 -1
  29. package/src/fuzzy.js +119 -1
  30. package/src/history.js +423 -1
  31. package/src/init.js +175 -1
  32. package/src/input.js +139 -1
  33. package/src/keys.js +183 -1
  34. package/src/markdown.js +306 -1
  35. package/src/models.js +507 -1
  36. package/src/naming.js +57 -1
  37. package/src/overlays.js +462 -1
  38. package/src/panels.js +1418 -1
  39. package/src/ping.js +226 -1
  40. package/src/presence.js +238 -1
  41. package/src/render.js +516 -1
  42. package/src/screen.js +518 -1
  43. package/src/screens.js +896 -1
  44. package/src/secret.js +59 -1
  45. package/src/securefs.js +359 -1
  46. package/src/settings.js +155 -1
  47. package/src/shared.js +52 -1
  48. package/src/sharedpaths.js +53 -1
  49. package/src/signup.js +156 -1
  50. package/src/summarize.js +95 -1
  51. package/src/sysdiag.js +585 -1
  52. package/src/system.js +40 -1
  53. package/src/theme.js +570 -1
  54. package/src/title.js +220 -1
  55. package/src/todos.js +115 -1
  56. package/src/tokens.js +263 -1
  57. package/src/topup.js +210 -1
  58. package/src/update.js +191 -1
  59. package/vendor/client/aegis.js +2441 -1
  60. package/vendor/client/attest.js +518 -1
  61. package/vendor/client/authorship-key.js +410 -1
  62. package/vendor/client/auto-provision.js +134 -1
  63. package/vendor/client/brain-catalog.js +268 -1
  64. package/vendor/client/byok-catalog.js +199 -1
  65. package/vendor/client/catalog-client.js +487 -1
  66. package/vendor/client/conversation-export.js +177 -1
  67. package/vendor/client/credentials.js +494 -1
  68. package/vendor/client/device-fingerprint.js +141 -1
  69. package/vendor/client/drive-connect.js +110 -1
  70. package/vendor/client/drive-upload.js +234 -1
  71. package/vendor/client/env-file.js +1273 -1
  72. package/vendor/client/fingerprint.js +1064 -1
  73. package/vendor/client/foreign-memory.js +669 -1
  74. package/vendor/client/google-signin.js +133 -1
  75. package/vendor/client/hooks.js +430 -1
  76. package/vendor/client/model-discovery.js +373 -1
  77. package/vendor/client/naming.js +283 -1
  78. package/vendor/client/platform.js +937 -1
  79. package/vendor/client/prefs.js +351 -1
  80. package/vendor/client/presence-constants.js +107 -1
  81. package/vendor/client/presence.js +438 -1
  82. package/vendor/client/record-vault.js +1055 -3
  83. package/vendor/client/session-store.js +575 -1
  84. package/vendor/client/topup.js +297 -1
  85. package/vendor/client/touch.js +458 -1
  86. package/vendor/client/update.js +763 -1
  87. package/vendor/client/user-models.js +381 -1
  88. package/vendor/desktop/lib/local/agents.js +105 -1
  89. package/vendor/desktop/lib/local/attachments.js +276 -1
  90. package/vendor/desktop/lib/local/autonomous.js +1045 -1
  91. package/vendor/desktop/lib/local/claude-pro.js +1028 -1
  92. package/vendor/desktop/lib/local/context.js +125 -1
  93. package/vendor/desktop/lib/local/engine.js +3666 -1
  94. package/vendor/desktop/lib/local/entitlement.js +660 -1
  95. package/vendor/desktop/lib/local/git-scope.js +228 -1
  96. package/vendor/desktop/lib/local/local.js +2145 -1
  97. package/vendor/desktop/lib/local/prompt.js +280 -1
  98. package/vendor/desktop/lib/local/queue.js +560 -1
  99. package/vendor/desktop/lib/local/session-rounds.js +238 -1
  100. package/vendor/desktop/lib/local/spill.js +75 -1
  101. package/vendor/desktop/lib/local/turn-guard.js +300 -1
  102. package/vendor/desktop/lib/local/worktree-lock.js +235 -1
  103. package/vendor/desktop/lib/settings.js +890 -1
  104. package/vendor/desktop/renderer/usage.js +1239 -1
  105. package/vendor/hosts/install.js +638 -1
  106. package/vendor/hosts/openai-shim.js +515 -1
  107. package/vendor/hosts/spec.js +164 -1
  108. package/vendor/hosts/targets.js +346 -1
  109. package/vendor/mcp/server.js +221 -1
  110. package/vendor/mcp/tools.js +408 -1
  111. package/vendor/one/src/child.js +285 -1
  112. package/vendor/one/src/permissions.js +383 -1
  113. package/SOURCE-OFFER.txt +0 -9
package/src/events.js CHANGED
@@ -1,3 +1,709 @@
1
1
  // SPDX-License-Identifier: AGPL-3.0-or-later
2
2
  // Copyright (C) 2026 Niklas Borneklint — AEGIS Code (aegiscode) / Aegiscloud.
3
- "use strict";const{decodeEscSequence:decodeEscSequence,decodePlain:decodePlain,KEY:KEY}=require("./keys.js"),queue=[];let waiting=[],preSessionKeys=[],everAttached=!1;const STREAM_END=Symbol("aegis.streamEnd");let buffer="",seq="",escTimer=null;const PASTE_LARGE=100,PASTE_DEBOUNCE_MS=30;let pasteChunks=[],pasteTimer=null;const ESC_SEQUENCE_RE=/\x1b\[[0-9;?<]*[A-Za-z~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[\s\S]/g,SGR_MOUSE_RE=/\x1b\[<\d+;\d+;\d+[Mm]/g,isControlOnly=e=>{const t=String(e);return!!t.includes("")&&""===t.replace(ESC_SEQUENCE_RE,"").replace(/[\u0000-\u001f\u007f]/g,"").trim()},looksLikePaste=e=>!isControlOnly(e)&&(e.length>PASTE_LARGE||/[\n\r]/.test(e.replace(/\r\n$|[\r\n]$/,"")));let attachedStdin=null,onData=null,onEnd=null,suspended=!1,streamEnded=!1,sessionStarted=!1;function isKeyStreamSuspended(){return suspended}function attachKeyStream(e){attachedStdin=e,everAttached=!0;const t=!(!e||!0!==e.readableEnded&&!0!==e.destroyed);streamEnded=t,onData=e=>pushChars(String(e));try{if("function"==typeof e.read)for(let t=0;t<64;t+=1){const t=e.read();if(null===t)break;feedKeys(String(t),{keystrokes:!0})}}catch{}"function"==typeof e.setRawMode&&e.setRawMode(!0),e.resume(),e.setEncoding("utf8"),e.on("data",onData),attachEndHandler(e)}function attachEndHandler(e){onEnd=()=>{streamEnded=!0;try{resetKeyStream()}catch{}};try{e.on("end",onEnd),e.on("close",onEnd)}catch{}}function detachEndHandler(e){if(e&&onEnd)try{e.removeListener("end",onEnd),e.removeListener("close",onEnd)}catch{}}function suspendKeyStream(){if(attachedStdin&&!suspended){suspended=!0,attachedStdin.removeListener("data",onData),detachEndHandler(attachedStdin),clearTimeout(escTimer),seq="",buffer="",clearTimeout(pasteTimer),pasteTimer=null,pasteChunks=[],drainQueue();try{attachedStdin.setRawMode(!1)}catch{}attachedStdin.pause()}}function resumeKeyStream(){if(attachedStdin&&suspended){suspended=!1;try{attachedStdin.setRawMode(!0)}catch{}attachedStdin.resume(),attachedStdin.setEncoding("utf8"),attachedStdin.on("data",onData),attachEndHandler(attachedStdin)}}function flushPaste(){const e=pasteChunks.join("");pasteChunks=[],pasteTimer=null;const t=e.replace(/\x1b\[200~/g,"").replace(/\x1b\[201~/g,"").replace(SGR_MOUSE_RE,"").replace(/\r\n/g,"\n").replace(/\r/g,"\n").trimEnd();t&&dispatch({name:"paste",text:t})}function feedKeys(e,{keystrokes:t=!1}={}){if(!e)return;const n=String(e);t&&n.length<=PASTE_LARGE&&!n.includes("[200~")?feedChars(n):pushChars(n)}function feedChars(e){for(buffer+=e;buffer.length;){const e=buffer.codePointAt(0),t=String.fromCodePoint(e),n=t.length;if(n>buffer.length)break;buffer=buffer.slice(n),feed(t)}}function pushChars(e){const t=e.match(/^\x1b\[200~(.*)\x1b\[201~$/s);return t?(pasteChunks.push(t[1]),clearTimeout(pasteTimer),void(pasteTimer=setTimeout(flushPaste,PASTE_DEBOUNCE_MS))):e.startsWith("[200~")?(pasteChunks.push(e.slice(6)),clearTimeout(pasteTimer),void(pasteTimer=setTimeout(flushPaste,PASTE_DEBOUNCE_MS))):isControlOnly(e)?void feedChars(e):pasteChunks.length||looksLikePaste(e)?(pasteChunks.push(e),clearTimeout(pasteTimer),void(pasteTimer=setTimeout(flushPaste,PASTE_DEBOUNCE_MS))):void feedChars(e)}function feed(e){if(""===e)return clearTimeout(escTimer),escTimer=setTimeout((()=>{""===seq&&dispatch({name:KEY.ESC}),seq=""}),60),void(seq="");if(""===seq)return"["===e||"O"===e?void(seq+=e):(clearTimeout(escTimer),seq="","\r"===e||"\n"===e?void dispatch({name:"shift-enter"}):void dispatch({name:"alt",ch:e}));if(seq.startsWith("[")||seq.startsWith("O")){if(seq+=e,/[A-Za-z~]/.test(e)){clearTimeout(escTimer);const e=parseSgrMouse(seq);if(e)return seq="",void dispatch("string"==typeof e?{name:"wheel",dir:e}:e);const t=decodeEscSequence(seq);seq="",t&&dispatch(t)}return}const t=decodePlain(e);t&&dispatch(t)}function parseSgrMouse(e){const t=/^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(e);if(!t)return null;const n=parseInt(t[1],10),s=parseInt(t[2],10),a=parseInt(t[3],10);if(!Number.isFinite(n)||!Number.isFinite(s)||!Number.isFinite(a))return null;const r=-61&n;return 64===r?"up":65===r?"down":3==(3&n)&&"M"===t[4]?{name:"release",col:s,row:a}:0!=(3&n)?null:"m"===t[4]?{name:"release",col:s,row:a}:0!=(32&n)?{name:"drag",col:s,row:a}:{name:"click",col:s,row:a}}function dispatch(e){waiting.length?waiting.shift()(e):everAttached?queue.push(e):preSessionKeys.push(e)}function streamFinished(){return!!attachedStdin&&(!0===attachedStdin.readableEnded||!0===attachedStdin.destroyed)}function nextKey(){return queue.length?Promise.resolve(queue.shift()):preSessionKeys.length?Promise.resolve(preSessionKeys.shift()):streamEnded||streamFinished()?Promise.resolve(STREAM_END):new Promise((e=>waiting.push(e)))}function nextKeyTimeout(e){return queue.length?Promise.resolve(queue.shift()):preSessionKeys.length?Promise.resolve(preSessionKeys.shift()):new Promise((t=>{const n=setTimeout((()=>{const e=waiting.indexOf(s);-1!==e&&waiting.splice(e,1),t(null)}),e),s=e=>{clearTimeout(n),t(e===STREAM_END?null:e)};waiting.push(s)}))}function requeueKeys(e){e&&e.length&&queue.unshift(...e)}function drainQueue(){if(sessionStarted)queue.length=0;else for(;queue.length;)preSessionKeys.push(queue.shift())}function markSessionStart(){sessionStarted=!0}function isKeyStreamAttached(){return!!attachedStdin}function detachKeyStream(){if(attachedStdin&&onData){try{attachedStdin.removeListener("data",onData)}catch{}detachEndHandler(attachedStdin);try{"function"==typeof attachedStdin.setRawMode&&attachedStdin.setRawMode(!1)}catch{}}resetKeyStream()}function resetKeyStream(){clearTimeout(escTimer),clearTimeout(pasteTimer),escTimer=null,pasteTimer=null,seq="",buffer="",pasteChunks=[],drainQueue();const e=waiting;waiting=[];for(const t of e)try{t(STREAM_END)}catch{}attachedStdin=null,onData=null,onEnd=null,suspended=!1}module.exports={KEY:KEY,STREAM_END:STREAM_END,parseSgrMouse:parseSgrMouse,attachKeyStream:attachKeyStream,feedKeys:feedKeys,suspendKeyStream:suspendKeyStream,resumeKeyStream:resumeKeyStream,isKeyStreamSuspended:isKeyStreamSuspended,isKeyStreamAttached:isKeyStreamAttached,detachKeyStream:detachKeyStream,nextKey:nextKey,nextKeyTimeout:nextKeyTimeout,requeueKeys:requeueKeys,drainQueue:drainQueue,markSessionStart:markSessionStart,resetKeyStream:resetKeyStream};
3
+ // AEGIS Code (aegiscode) — source: https://github.com/aegisinfo/aegiscode-plugin
4
+ // Conveying a modified copy, or running one as a network service, owes the
5
+ // corresponding source under this licence (§5/§13) — see LICENSING.md.
6
+ 'use strict';
7
+
8
+ /**
9
+ * The global key-event pump.
10
+ *
11
+ * A single stdin 'data' event may carry many keystrokes (pipes batch writes),
12
+ * so each chunk is split into characters and fed through a small state machine
13
+ * that also handles:
14
+ *
15
+ * · a lone Escape, resolved by a short timeout so it is distinguishable from
16
+ * the start of an escape sequence;
17
+ * · bracketed paste (DECSET 2004) and, for terminals that ignore it, a
18
+ * length/newline heuristic so a multi-line paste does not submit the prompt
19
+ * line-by-line as it arrives;
20
+ * · SGR mouse wheel events (DECSET 1000+1006), decoded to `{name:'wheel'}`
21
+ * instead of being mistaken for Escape (which would abort a working turn).
22
+ *
23
+ * Ported from the upstream engine reference. It is a module-level singleton —
24
+ * one stdin, one queue — which is what lets the session loop, a command
25
+ * handler's `askInput()`, and the mid-turn Esc drain all read keys through the
26
+ * same nextKey() without fighting over the `data` listener.
27
+ */
28
+
29
+ const { decodeEscSequence, decodePlain, KEY } = require('./keys.js');
30
+
31
+ const queue = [];
32
+ let waiting = [];
33
+
34
+ /**
35
+ * Keys handed in from OUTSIDE the pump before any pump existed — the startup
36
+ * background probe is the only caller (see `feedKeys`).
37
+ *
38
+ * Why this is not just `queue`. A `resetKeyStream()` clears the queue on
39
+ * purpose: typed-ahead from a dead session must not land in the next one. But
40
+ * the probe runs BEFORE onboarding and BEFORE the session loop, and onboarding
41
+ * attaches a pump of its own and detaches it in a `finally` — so an early
42
+ * command was being queued, then wiped by that detach, and the session loop
43
+ * that followed waited forever for input that had already been read and
44
+ * thrown away.
45
+ *
46
+ * That is a real user-visible bug, not just a test artefact: anything typed
47
+ * while the CLI is still starting up was silently dropped. It also made
48
+ * `test/cli-platform-parity.test.mjs` fail roughly 4 runs in 10 on a SINGLE
49
+ * platform — same code, same machine — which is why "parity" kept being
50
+ * reported as broken and re-fixed for a day. Bytes captured before any session
51
+ * existed belong to the session that has not started yet, so they survive a
52
+ * session teardown and are delivered to the first consumer that asks.
53
+ */
54
+ let preSessionKeys = [];
55
+ let everAttached = false;
56
+
57
+ /**
58
+ * Handed to every parked `nextKey()` waiter when the pump is reset, so a
59
+ * consumer can tell "the stream went away" from "the user pressed nothing".
60
+ * Without it the only way to unblock a waiter is a real keypress, which means a
61
+ * session whose loop is parked on a bare `nextKey()` cannot be stopped at all.
62
+ */
63
+ const STREAM_END = Symbol('aegis.streamEnd');
64
+ let buffer = '';
65
+ let seq = '';
66
+ let escTimer = null;
67
+
68
+ // A paste-like chunk accumulates instead of being fed char-by-char; a short
69
+ // idle window merges chunks that a pty fragmented across 'data' events.
70
+ const PASTE_LARGE = 100;
71
+ const PASTE_DEBOUNCE_MS = 30;
72
+ let pasteChunks = [];
73
+ let pasteTimer = null;
74
+
75
+ // Any single escape sequence: a CSI (ESC [ … final), an OSC (ESC ] … BEL/ST) or
76
+ // a two-byte escape. Applied globally to strip control traffic out of a chunk
77
+ // so what remains can be judged as text.
78
+ const ESC_SEQUENCE_RE = /\x1b\[[0-9;?<]*[A-Za-z~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b[\s\S]/g;
79
+ // SGR mouse reports specifically (DECSET 1006): the bytes a drag is made of.
80
+ const SGR_MOUSE_RE = /\x1b\[<\d+;\d+;\d+[Mm]/g;
81
+
82
+ /**
83
+ * Is this chunk *only* control traffic — escape sequences and control bytes,
84
+ * with no text in it at all?
85
+ *
86
+ * This is the guard that made drag-to-copy work. DECSET 1002 reports one mouse
87
+ * cell per sweep, so a quick drag arrives as a single `data` event of ~15 bytes
88
+ * per report: eleven reports is 268 bytes, which crossed `PASTE_LARGE` and was
89
+ * classified as a PASTE. `flushPaste()` then dispatched ONE `{name:'paste'}`
90
+ * key — so `chatflow.js` never saw a single `drag`, nothing was ever marked,
91
+ * nothing was painted in reverse video, and the release arrived with no anchor
92
+ * (it became a click and copied nothing). Measured through the real pump on
93
+ * this host: a 268-byte swept read produced `SGR-7 present: false`, `input row:
94
+ * "❯ MARKER_ALPHA …"`, `release hint: undefined`. The same bug hits a burst of
95
+ * repeated arrow / function keys (20 × `\x1b[1;5A` = 120 bytes), which used to
96
+ * be typed into the editor as the literal text `[1;5A`.
97
+ *
98
+ * A chunk that mixes escapes with real text (`ESC[31mred` pasted from a
99
+ * colored log, or a mouse report that raced a genuine paste) is NOT control
100
+ * only, so it still takes the paste path.
101
+ */
102
+ const isControlOnly = (s) => {
103
+ const str = String(s);
104
+ if (!str.includes('\x1b')) return false;
105
+ const rest = str.replace(ESC_SEQUENCE_RE, '').replace(/[\u0000-\u001f\u007f]/g, '');
106
+ return rest.trim() === '';
107
+ };
108
+
109
+ const looksLikePaste = (s) => {
110
+ // Mouse reports and key-repeat bursts are keystrokes, not pasted text — see
111
+ // isControlOnly. Checked first: size is not evidence when the chunk is all
112
+ // escape traffic.
113
+ if (isControlOnly(s)) return false;
114
+ if (s.length > PASTE_LARGE) return true;
115
+ // A trailing \n or \r\n is the ordinary end of a piped batch, not evidence
116
+ // of a paste; strip one terminator before looking for an embedded newline.
117
+ return /[\n\r]/.test(s.replace(/\r\n$|[\r\n]$/, ''));
118
+ };
119
+
120
+ let attachedStdin = null;
121
+ let onData = null;
122
+ let onEnd = null;
123
+ let suspended = false;
124
+ // Latched: stdin reached EOF and will never produce another key. Lives outside
125
+ // `resetKeyStream()`'s transient state because the loop can ask for a key long
126
+ // after the EOF arrived. Cleared only by attaching a fresh stream.
127
+ let streamEnded = false;
128
+ // Has the interactive SESSION taken the terminal yet? Onboarding attaches a
129
+ // pump of its own before the session loop does (`screens.js` owns that attach
130
+ // and detaches it in a `finally`), so "a pump is attached" is not the same
131
+ // question as "a session owns these keys" — and the difference decides whether
132
+ // the teardown is allowed to destroy what is in the queue. See `drainQueue`.
133
+ let sessionStarted = false;
134
+
135
+ function isKeyStreamSuspended() {
136
+ return suspended;
137
+ }
138
+
139
+ function attachKeyStream(stdin) {
140
+ attachedStdin = stdin;
141
+ everAttached = true;
142
+ // A fresh stream is a fresh session: the previous one's EOF must not be
143
+ // inherited, or the new loop would exit on its first `nextKey()`.
144
+ //
145
+ // …unless this stream is ALREADY finished, which is not the exception but a
146
+ // routine startup state. `end`/`close` are emitted once, to whoever is
147
+ // listening at that instant: the startup background probe resumes and then
148
+ // *pauses* stdin without an end listener (`caps.probeBackground`), and
149
+ // onboarding attaches a pump and detaches it in a `finally`. If the pty's
150
+ // write end closed during either gap, the EOF was announced into an empty
151
+ // room — so clearing the latch here, in the one place that could re-learn the
152
+ // fact, strands the loop in a way the latch exists to prevent: `nextKey()`
153
+ // parks on a stream that will never emit again, the session promise never
154
+ // settles, and the teardown and the resume hint are skipped entirely.
155
+ //
156
+ // Measured on the real binary through a pty: 2 of 12 runs ended at a fully
157
+ // drawn 9120-byte welcome frame with NO teardown at all — no `\x1b[?1049l`,
158
+ // no hint — the command sent at launch (`/exit`) never seen and never
159
+ // resolved. `test/cli-platform-parity.test.mjs` reports that as "linux and
160
+ // darwin wrote different bytes", because whichever platform drew the short
161
+ // frame is compared against one that drew the long one. It is a race, not a
162
+ // platform difference, and the short frame is always the losing side.
163
+ //
164
+ // So: BELIEVE the stream's own state rather than the absence of an event. If
165
+ // it has already ended, keep the latch (a first-time attach that finds a
166
+ // finished stream must set it, not clear it). Launch keystrokes are not lost
167
+ // by doing so — `nextKey()` consults the queues before the latch, so input
168
+ // captured ahead of the session is still delivered and the loop resolves on
169
+ // the first call instead of after it.
170
+ const alreadyEnded = !!(stdin && (stdin.readableEnded === true || stdin.destroyed === true));
171
+ streamEnded = alreadyEnded;
172
+ onData = (chunk) => pushChars(String(chunk));
173
+ // Before the listener goes on, take anything the terminal already delivered
174
+ // while NOTHING owned the stream. That window is real: the startup background
175
+ // probe resumes stdin, then pauses it again when it finishes, so a command
176
+ // typed at launch can be sitting in the Readable's buffer — and `resume()`
177
+ // below emits from a state we do not control, which is why the pty sweep hung
178
+ // on 1 run in 10 with the frame fully drawn and no command ever seen. Pulling
179
+ // the buffer out first makes the handoff explicit instead of raced.
180
+ try {
181
+ if (typeof stdin.read === 'function') {
182
+ for (let i = 0; i < 64; i += 1) {
183
+ const buffered = stdin.read();
184
+ if (buffered === null) break;
185
+ feedKeys(String(buffered), { keystrokes: true });
186
+ }
187
+ }
188
+ } catch {
189
+ /* a stream without the Readable surface: resume() is all we ever had */
190
+ }
191
+ // A non-TTY stdin has no setRawMode at all; guard it so callers degrade
192
+ // instead of throwing "stdin.setRawMode is not a function".
193
+ if (typeof stdin.setRawMode === 'function') stdin.setRawMode(true);
194
+ stdin.resume();
195
+ stdin.setEncoding('utf8');
196
+ stdin.on('data', onData);
197
+ attachEndHandler(stdin);
198
+ }
199
+
200
+ /**
201
+ * EOF is the end of the session's input, and it must RESOLVE the loop parked on
202
+ * `nextKey()` rather than leave it waiting on a stream that will never speak
203
+ * again. `attachKeyStream` used to register `data` alone, so a closed stdin
204
+ * (ctrl-d, a pty master that went away, a piped caller that finished writing)
205
+ * silently stranded every waiter: the session promise never settled, so
206
+ * `bin/aegiscode.js` never printed the "aegiscode --continue" hint and never
207
+ * reached `process.exit` — the process only left when the event loop happened
208
+ * to drain on its own, which skips the session's `finally` entirely. That is
209
+ * the difference between a 9561-byte exit frame and a 9120-byte one on the
210
+ * SAME host, which `test/cli-platform-parity.test.mjs` reported as "linux and
211
+ * darwin wrote different bytes". A race, not a platform difference.
212
+ *
213
+ * `resetKeyStream()` is the resolution primitive: it drains the queue and hands
214
+ * every parked waiter STREAM_END, which `nextKey()` reports as `null` and the
215
+ * session loop now treats as "the session is over". It is idempotent, so a
216
+ * second EOF (or a teardown that already reset) costs nothing.
217
+ */
218
+ function attachEndHandler(stdin) {
219
+ onEnd = () => {
220
+ // Latch BEFORE resolving: the loop may not be parked yet, and the latch is
221
+ // what makes the *next* `nextKey()` answer STREAM_END rather than wait on a
222
+ // finished stream.
223
+ streamEnded = true;
224
+ try {
225
+ resetKeyStream();
226
+ } catch {
227
+ /* already reset by a teardown that got there first */
228
+ }
229
+ };
230
+ try {
231
+ stdin.on('end', onEnd);
232
+ stdin.on('close', onEnd);
233
+ } catch {
234
+ /* a stream without an event surface: the timeout paths still apply */
235
+ }
236
+ }
237
+
238
+ /** Undo `attachEndHandler`. Split out so the detach paths stay symmetric. */
239
+ function detachEndHandler(stdin) {
240
+ if (!stdin || !onEnd) return;
241
+ try {
242
+ stdin.removeListener('end', onEnd);
243
+ stdin.removeListener('close', onEnd);
244
+ } catch {
245
+ /* stream already gone */
246
+ }
247
+ }
248
+
249
+ /** Hand the terminal to a child process: detach the pump and drop half-parsed
250
+ * state so nothing leaks across the suspension. Pair with resumeKeyStream(). */
251
+ function suspendKeyStream() {
252
+ if (!attachedStdin || suspended) return;
253
+ suspended = true;
254
+ attachedStdin.removeListener('data', onData);
255
+ // A handover is not an end: the child owns the terminal now, and an EOF on
256
+ // the paused stream must not be read as "the session is over".
257
+ detachEndHandler(attachedStdin);
258
+ clearTimeout(escTimer);
259
+ seq = '';
260
+ buffer = '';
261
+ clearTimeout(pasteTimer);
262
+ pasteTimer = null;
263
+ pasteChunks = [];
264
+ drainQueue();
265
+ try {
266
+ attachedStdin.setRawMode(false);
267
+ } catch {
268
+ /* not a TTY */
269
+ }
270
+ attachedStdin.pause();
271
+ }
272
+
273
+ function resumeKeyStream() {
274
+ if (!attachedStdin || !suspended) return;
275
+ suspended = false;
276
+ try {
277
+ attachedStdin.setRawMode(true);
278
+ } catch {
279
+ /* not a TTY */
280
+ }
281
+ attachedStdin.resume();
282
+ attachedStdin.setEncoding('utf8');
283
+ attachedStdin.on('data', onData);
284
+ attachEndHandler(attachedStdin);
285
+ }
286
+
287
+ function flushPaste() {
288
+ const raw = pasteChunks.join('');
289
+ pasteChunks = [];
290
+ pasteTimer = null;
291
+ // Strip any bracketed-paste framing that reached the buffer via a chunk
292
+ // split mid-frame, so literal [200~…[201~ can never leak into the editor.
293
+ // Mouse reports are stripped too: a report that raced a real paste into the
294
+ // same accumulate window (or a drag that started inside a paste's debounce)
295
+ // is not text, and typing `[<32;12;4M` into the prompt is the visible half of
296
+ // the bug the isControlOnly guard fixes.
297
+ const text = raw
298
+ .replace(/\x1b\[200~/g, '')
299
+ .replace(/\x1b\[201~/g, '')
300
+ .replace(SGR_MOUSE_RE, '')
301
+ .replace(/\r\n/g, '\n')
302
+ .replace(/\r/g, '\n')
303
+ .trimEnd();
304
+ if (text) dispatch({ name: 'paste', text });
305
+ }
306
+
307
+ /**
308
+ * Feed bytes that were read off the terminal by something *other* than this
309
+ * pump, as if they had arrived here.
310
+ *
311
+ * The startup background query (`caps.probeBackground`) is the caller: it must
312
+ * read stdin to see the terminal's answer (OSC 11), and a keypress can race the
313
+ * reply into the same read. Bytes it consumed are not lost — it hands them back
314
+ * here, and they take the identical path (`pushChars`) a `data` event would
315
+ * have taken, so the pump's parsing, paste handling and key queue all see them
316
+ * in order.
317
+ *
318
+ * This exists because the alternative — putting the bytes back on the stream
319
+ * (`stdin.unshift`) — is not lossless: `script`/`spawnSync` closes the write end
320
+ * immediately after sending a command, so by the time the probe's deadline
321
+ * expires stdin has already emitted `end` and the unshifted bytes are never
322
+ * delivered. The parked `nextKey()` then waits forever for a command it never
323
+ * receives. This runs through the queue instead, which `drainQueue`/`nextKey`
324
+ * consult regardless of the stream's state.
325
+ */
326
+ function feedKeys(text, { keystrokes = false } = {}) {
327
+ if (!text) return;
328
+ const s = String(text);
329
+ // A handback from the startup probe is a burst of KEYSTROKES that raced the
330
+ // OSC-11 reply, not a paste — and the difference is not cosmetic. The probe
331
+ // reads whatever arrived before its 120ms deadline and hands it back as one
332
+ // string, so a command typed the instant the CLI started arrives as
333
+ // `"/exit\n\x04"` in a single call. `pushChars` sees the embedded newline,
334
+ // declares it a paste, and `flushPaste` collapses it into ONE `{name:'paste'}`
335
+ // key — so the session loop never receives the Enter and parks on `nextKey()`
336
+ // forever. Measured: 10/10 runs hung at 5029 bytes with the probe on, 10/10
337
+ // clean at 9113 bytes with it off. Replaying as keystrokes gives the loop the
338
+ // same sequence a `data` event would have: `/`, `e`, `x`, `i`, `t`, `enter`.
339
+ //
340
+ // The size guard keeps the other case honest: a real paste large enough to
341
+ // matter (or an explicit bracketed-paste frame) still takes the paste path,
342
+ // because feeding 10k characters through the decoder one at a time is the
343
+ // thing the heuristic exists to avoid.
344
+ if (keystrokes && s.length <= PASTE_LARGE && !s.includes('\x1b[200~')) {
345
+ feedChars(s);
346
+ return;
347
+ }
348
+ pushChars(s);
349
+ }
350
+
351
+ /** Decode a run of characters into keys, preserving multi-byte boundaries. */
352
+ function feedChars(s) {
353
+ buffer += s;
354
+ while (buffer.length) {
355
+ const cp = buffer.codePointAt(0);
356
+ const c = String.fromCodePoint(cp);
357
+ const units = c.length;
358
+ if (units > buffer.length) break; // incomplete multi-byte char
359
+ buffer = buffer.slice(units);
360
+ feed(c);
361
+ }
362
+ }
363
+
364
+ function pushChars(s) {
365
+ const framed = s.match(/^\x1b\[200~(.*)\x1b\[201~$/s);
366
+ if (framed) {
367
+ pasteChunks.push(framed[1]);
368
+ clearTimeout(pasteTimer);
369
+ pasteTimer = setTimeout(flushPaste, PASTE_DEBOUNCE_MS);
370
+ return;
371
+ }
372
+ if (s.startsWith('\x1b[200~')) {
373
+ pasteChunks.push(s.slice('\x1b[200~'.length));
374
+ clearTimeout(pasteTimer);
375
+ pasteTimer = setTimeout(flushPaste, PASTE_DEBOUNCE_MS);
376
+ return;
377
+ }
378
+ // Control traffic is never paste text, not even inside an accumulate window:
379
+ // a drag that lands within a paste's 30ms debounce still has to arrive as
380
+ // drag reports, or the marking silently does nothing again.
381
+ if (isControlOnly(s)) {
382
+ feedChars(s);
383
+ return;
384
+ }
385
+ if (pasteChunks.length || looksLikePaste(s)) {
386
+ pasteChunks.push(s);
387
+ clearTimeout(pasteTimer);
388
+ pasteTimer = setTimeout(flushPaste, PASTE_DEBOUNCE_MS);
389
+ return;
390
+ }
391
+ feedChars(s);
392
+ }
393
+
394
+ function feed(c) {
395
+ if (c === '\x1b') {
396
+ clearTimeout(escTimer);
397
+ escTimer = setTimeout(() => {
398
+ // Nothing followed the ESC within the window → it was a bare Escape.
399
+ if (seq === '\x1b') dispatch({ name: KEY.ESC });
400
+ seq = '';
401
+ }, 60);
402
+ seq = '\x1b';
403
+ return;
404
+ }
405
+ if (seq === '\x1b') {
406
+ // First char after ESC: a CSI (ESC[), an SS3 (ESCO), or an Alt chord.
407
+ if (c === '[' || c === 'O') {
408
+ seq += c;
409
+ return;
410
+ }
411
+ clearTimeout(escTimer);
412
+ seq = '';
413
+ // ESC followed by CR is the legacy spelling of shift+Enter, and it is the
414
+ // only spelling some terminals have. Without this it fell through to the
415
+ // generic Alt chord ({name:'alt', ch:'\r'}), which nothing handled — so the
416
+ // chord the palette advertises was dead on exactly the terminals that need
417
+ // it. The kitty/modifyOtherKeys spelling (`CSI 13;2 u`) is decoded in
418
+ // keys.js; both have to land on the same key name.
419
+ if (c === '\r' || c === '\n') {
420
+ dispatch({ name: 'shift-enter' });
421
+ return;
422
+ }
423
+ dispatch({ name: 'alt', ch: c });
424
+ return;
425
+ }
426
+ if (seq.startsWith('\x1b[') || seq.startsWith('\x1bO')) {
427
+ seq += c;
428
+ if (/[A-Za-z~]/.test(c)) {
429
+ clearTimeout(escTimer);
430
+ const mouse = parseSgrMouse(seq);
431
+ if (mouse) {
432
+ seq = '';
433
+ // Wheel decodes to a direction string; a left press to a {name,col,row}
434
+ // event. Both are returned by parseSgrMouse so the caller stays a
435
+ // one-line dispatch.
436
+ dispatch(typeof mouse === 'string' ? { name: 'wheel', dir: mouse } : mouse);
437
+ return;
438
+ }
439
+ const k = decodeEscSequence(seq);
440
+ seq = '';
441
+ if (k) dispatch(k);
442
+ }
443
+ return;
444
+ }
445
+ const key = decodePlain(c);
446
+ if (key) dispatch(key);
447
+ }
448
+
449
+ /**
450
+ * SGR mouse sequence → a wheel direction ('up'/'down') or a left-button
451
+ * gesture, with the wire's own 1-based coordinates.
452
+ *
453
+ * Button codes: 0/1/2 are left/middle/right, 64/65 are wheel up/down, and bit
454
+ * 32 (0b100000) marks a motion event — with DECSET 1002 the terminal reports
455
+ * one per cell of a sweep while the left button is held. Modifier bits (shift
456
+ * 4, meta 8, ctrl 16) are masked off so Shift+wheel and Shift-click still work.
457
+ *
458
+ * A gesture therefore arrives as a triplet and is named stage by stage, so the
459
+ * caller can tell a click from a marking:
460
+ *
461
+ * press {name:'click'} 'M', left button, no motion bit
462
+ * sweep {name:'drag'} 'M', left button, motion bit set
463
+ * release {name:'release'} 'm' terminator (or the X10-style code 3)
464
+ *
465
+ * chatflow.js defers the click to the release, because with 1002 tracking
466
+ * enabled the SAME press can turn into a drag: acting on 'click' straight away
467
+ * would toggle an edit block at the start of every text selection swept across
468
+ * one. Right/middle clicks and anything unrecognized return null, and the
469
+ * caller then falls through to the ordinary CSI decoder, which ignores it — so
470
+ * stray mouse bytes can't type into the editor or abort a turn.
471
+ * Ported from the upstream engine reference so both hosts mark identically.
472
+ */
473
+ function parseSgrMouse(seq) {
474
+ const m = /^\x1b\[<(\d+);(\d+);(\d+)([Mm])$/.exec(seq);
475
+ if (!m) return null;
476
+ const code = parseInt(m[1], 10);
477
+ const col = parseInt(m[2], 10);
478
+ const row = parseInt(m[3], 10);
479
+ if (!Number.isFinite(code) || !Number.isFinite(col) || !Number.isFinite(row)) return null;
480
+ const base = code & ~0b111100;
481
+ if (base === 64) return 'up';
482
+ if (base === 65) return 'down';
483
+ // Code 3 is "no button" — the X10 encoding of a release, which some
484
+ // terminals and multiplexers still send instead of SGR's `m`.
485
+ if ((code & 3) === 3 && m[4] === 'M') return { name: 'release', col, row };
486
+ if ((code & 3) !== 0) return null; // middle/right button — not ours
487
+ if (m[4] === 'm') return { name: 'release', col, row };
488
+ return (code & 32) !== 0 ? { name: 'drag', col, row } : { name: 'click', col, row };
489
+ }
490
+
491
+ function dispatch(key) {
492
+ if (waiting.length) {
493
+ const w = waiting.shift();
494
+ w(key);
495
+ } else if (!everAttached) {
496
+ // Nothing has ever consumed keys, so this is startup input: hold it where a
497
+ // session reset cannot reach it.
498
+ preSessionKeys.push(key);
499
+ } else {
500
+ queue.push(key);
501
+ }
502
+ }
503
+
504
+ /**
505
+ * Has the attached stream already finished?
506
+ *
507
+ * Ground truth, asked of the stream rather than remembered as an event. `end`
508
+ * and `close` are announced once, to whoever happens to be listening: the
509
+ * startup background probe resumes and pauses stdin with no end listener
510
+ * (`caps.probeBackground`), onboarding attaches a pump and detaches it in a
511
+ * `finally`, and `resume()` itself can flush a pending `end` in the window
512
+ * between the check in `attachKeyStream` and `attachEndHandler` going on. In any
513
+ * of those the EOF is announced into an empty room and the `streamEnded` latch
514
+ * stays false forever, so a parked `nextKey()` waits on a stream that will never
515
+ * speak again.
516
+ *
517
+ * That is the whole of the 9120-byte exit frame: the loop parks, the session
518
+ * promise never settles, and the teardown and resume hint are skipped — 2 of 12
519
+ * runs of the real binary through a pty, reported by the parity suite as a
520
+ * cross-platform byte difference because the short frame was measured against a
521
+ * long one. Asking the stream makes the answer independent of who was listening.
522
+ */
523
+ function streamFinished() {
524
+ if (!attachedStdin) return false;
525
+ return attachedStdin.readableEnded === true || attachedStdin.destroyed === true;
526
+ }
527
+
528
+ /** The next key, waiting as long as it takes. */
529
+ function nextKey() {
530
+ if (queue.length) return Promise.resolve(queue.shift());
531
+ if (preSessionKeys.length) return Promise.resolve(preSessionKeys.shift());
532
+ // The stream is over and nothing is queued: answer STREAM_END instead of
533
+ // parking. Without this latch the EOF resolution is a one-instant event —
534
+ // `resetKeyStream()` wakes the waiters that happen to be parked when it runs,
535
+ // and a loop that was mid-turn at that moment simply parks again on a stream
536
+ // that is finished and will never emit another byte. That is the hang: the
537
+ // session never settles, so the teardown and the resume hint are skipped and
538
+ // the process only ends when the event loop drains by itself.
539
+ //
540
+ // The latch is checked *together with* the stream's own state, because the
541
+ // latch can only record an event that was heard (see `streamFinished`). Order
542
+ // matters and is deliberate: both queues are consulted first, so a command
543
+ // captured at launch is still delivered and this returns it rather than the
544
+ // end of input.
545
+ if (streamEnded || streamFinished()) return Promise.resolve(STREAM_END);
546
+ return new Promise((resolve) => waiting.push(resolve));
547
+ }
548
+
549
+ /**
550
+ * nextKey with an upper bound: resolves null when no key arrives within `ms`.
551
+ * The session loop polls with this while a turn runs — it must never wedge on a
552
+ * key that never comes once the turn settles. The timeout path removes the
553
+ * resolver from the waiting stack, so a late keystroke routes to the queue and
554
+ * the loop's next nextKey() sees it.
555
+ */
556
+ function nextKeyTimeout(ms) {
557
+ if (queue.length) return Promise.resolve(queue.shift());
558
+ if (preSessionKeys.length) return Promise.resolve(preSessionKeys.shift());
559
+ return new Promise((resolve) => {
560
+ const timer = setTimeout(() => {
561
+ const i = waiting.indexOf(wrapper);
562
+ if (i !== -1) waiting.splice(i, 1);
563
+ resolve(null);
564
+ }, ms);
565
+ const wrapper = (key) => {
566
+ clearTimeout(timer);
567
+ // A pump reset resolves null, exactly like the timeout path: this call's
568
+ // contract is "a key or null", and STREAM_END is not a key.
569
+ resolve(key === STREAM_END ? null : key);
570
+ };
571
+ waiting.push(wrapper);
572
+ });
573
+ }
574
+
575
+ /** Put keys back at the FRONT of the queue (typed-ahead replay after a turn). */
576
+ function requeueKeys(keys) {
577
+ if (keys && keys.length) queue.unshift(...keys);
578
+ }
579
+
580
+ function drainQueue() {
581
+ // Only this session's keys. `preSessionKeys` is deliberately left alone: it
582
+ // holds input captured before any session existed, and clearing it here is
583
+ // exactly the bug its comment describes.
584
+ //
585
+ // …and while no session has started, nothing in the queue is "this session's"
586
+ // either — it is input aimed at the session that has not begun yet, so it is
587
+ // moved rather than dropped. Onboarding is why: it attaches the pump *before*
588
+ // the session loop does, so the launch command lands in `queue` (a pump is
589
+ // attached, `everAttached` is true, so `dispatch` puts it there and NOT in
590
+ // `preSessionKeys`), and its `finally` then detaches — draining the queue and
591
+ // destroying the command as it goes. The session that follows has nothing to
592
+ // read and no EOF pending (`script` keeps the pty open until the command
593
+ // exits), so it parks on `nextKey()` forever: the teardown never runs, the
594
+ // resume hint is never printed, and the process only ends when an outer
595
+ // deadline kills it. Measured through a pty on the real binary, a hung run
596
+ // observed from inside the process showed `dataListeners=1 endListeners=3
597
+ // ended=false isRaw=true` — attached, raw, alive, waiting on input that had
598
+ // already been thrown away. That is 4 of 16 runs, and it is the entire
599
+ // cli-platform-parity flake: the losing run writes a 9120-byte frame with no
600
+ // `\x1b[?1049l` and no hint, and the suite compares it against a 9561-byte
601
+ // one from another platform and calls the difference a platform divergence.
602
+ //
603
+ // Order is preserved (a FIFO move, not a stack) so `/exit\r` still arrives as
604
+ // `/`, `e`, `x`, `i`, `t`, enter. Once the session has started, the old
605
+ // contract holds unchanged: typed-ahead from a dead session must not land in
606
+ // the next one.
607
+ if (!sessionStarted) {
608
+ while (queue.length) preSessionKeys.push(queue.shift());
609
+ return;
610
+ }
611
+ queue.length = 0;
612
+ }
613
+
614
+ /**
615
+ * The interactive session has taken the terminal: from here on the queue
616
+ * belongs to it, and `drainQueue()` may destroy what it holds. Called by the
617
+ * session loop immediately before it attaches (`chatflow.js`), never by a
618
+ * transient screen pump.
619
+ */
620
+ function markSessionStart() {
621
+ sessionStarted = true;
622
+ }
623
+
624
+ /** Test seam: forget attached stdin, timers and queued keys. */
625
+ /** True once a key stream is attached — i.e. whether nextKey() has a source. */
626
+ function isKeyStreamAttached() {
627
+ return !!attachedStdin;
628
+ }
629
+
630
+ /**
631
+ * Tear the pump down, removing the data listener.
632
+ *
633
+ * `resetKeyStream()` deliberately only *drops the reference* (it is used
634
+ * between tests and after a child-process handover), which leaves the listener
635
+ * registered on stdin. Attaching again would then run two pumps over the same
636
+ * bytes and dispatch every keystroke twice. Onboarding attaches before the
637
+ * session loop does, so it needs a real detach rather than a reset.
638
+ */
639
+ function detachKeyStream() {
640
+ if (attachedStdin && onData) {
641
+ try {
642
+ attachedStdin.removeListener('data', onData);
643
+ } catch {
644
+ /* stream already gone */
645
+ }
646
+ detachEndHandler(attachedStdin);
647
+ try {
648
+ if (typeof attachedStdin.setRawMode === 'function') attachedStdin.setRawMode(false);
649
+ } catch {
650
+ /* not a TTY */
651
+ }
652
+ }
653
+ resetKeyStream();
654
+ }
655
+
656
+ function resetKeyStream() {
657
+ clearTimeout(escTimer);
658
+ clearTimeout(pasteTimer);
659
+ escTimer = null;
660
+ pasteTimer = null;
661
+ seq = '';
662
+ buffer = '';
663
+ pasteChunks = [];
664
+ drainQueue();
665
+ // Resolve — do NOT merely drop — the parked waiters. `waiting = []` on its own
666
+ // leaves every loop sitting on a bare nextKey() parked forever: nothing can
667
+ // ever wake it, so any consumer that leaks the pump becomes unkillable and
668
+ // keeps painting into the stdout it captured. Handing each waiter STREAM_END
669
+ // lets its loop observe the teardown and break. A leaked session's keystrokes
670
+ // also stop landing in the next session's queue, because the queue is cleared
671
+ // here and the stale waiter is gone rather than still attached to it.
672
+ const parked = waiting;
673
+ waiting = [];
674
+ for (const w of parked) {
675
+ try {
676
+ w(STREAM_END);
677
+ } catch {
678
+ /* waiter already settled */
679
+ }
680
+ }
681
+ attachedStdin = null;
682
+ onData = null;
683
+ onEnd = null;
684
+ suspended = false;
685
+ }
686
+
687
+ module.exports = {
688
+ KEY,
689
+ STREAM_END,
690
+ // Exported for `test/cli-marking.test.mjs`: the click/drag/release split is
691
+ // the half of the marking gesture that is pure decoding, and it is the half
692
+ // that regressed silently once already (only left presses were named, so a
693
+ // sweep arrived as a single cell and nothing copied). A test that can't reach
694
+ // it can't pin it.
695
+ parseSgrMouse,
696
+ attachKeyStream,
697
+ feedKeys,
698
+ suspendKeyStream,
699
+ resumeKeyStream,
700
+ isKeyStreamSuspended,
701
+ isKeyStreamAttached,
702
+ detachKeyStream,
703
+ nextKey,
704
+ nextKeyTimeout,
705
+ requeueKeys,
706
+ drainQueue,
707
+ markSessionStart,
708
+ resetKeyStream,
709
+ };