micro-models-agent 0.60.1 → 0.61.1

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 (233) hide show
  1. package/CHANGELOG.md +601 -584
  2. package/README.md +358 -358
  3. package/dist/certification/certifications.json +493 -493
  4. package/dist/cli/commands.js +447 -0
  5. package/dist/cli/completer.js +167 -0
  6. package/dist/cli/index.js +2 -0
  7. package/dist/cli/main.js +153 -0
  8. package/dist/cli/plugin-commands.js +36 -0
  9. package/dist/cli/repl-commands.js +761 -0
  10. package/dist/cli/repl.js +702 -0
  11. package/dist/cli/run-result.js +33 -0
  12. package/dist/cli/security-commands.js +164 -0
  13. package/dist/cli/setup.js +237 -0
  14. package/dist/config/config.js +276 -0
  15. package/dist/config/defaults.js +141 -0
  16. package/dist/config/domains.js +179 -0
  17. package/dist/config/experts.js +15 -0
  18. package/dist/config/index.js +4 -0
  19. package/dist/config/security.js +213 -0
  20. package/dist/config/types.js +1 -0
  21. package/dist/core/agent-moe.js +102 -0
  22. package/dist/core/agent.js +1018 -0
  23. package/dist/core/bootstrap.js +481 -0
  24. package/dist/core/crash-handler.js +51 -0
  25. package/dist/core/environment.js +199 -0
  26. package/dist/core/index.js +2 -0
  27. package/dist/core/prompt-builder.js +76 -0
  28. package/dist/core/session-logger.js +251 -0
  29. package/dist/core/types.js +1 -0
  30. package/dist/core/version.js +26 -0
  31. package/dist/core/workspace.js +76 -0
  32. package/dist/i18n/en.json +757 -746
  33. package/dist/i18n/index.js +46 -0
  34. package/dist/i18n/ru.json +757 -746
  35. package/dist/index.js +22 -0
  36. package/dist/llm/image-utils.js +143 -0
  37. package/dist/llm/index.js +4 -0
  38. package/dist/llm/model-loader.js +78 -0
  39. package/dist/llm/openai-compat.js +497 -0
  40. package/dist/llm/orchestrator.js +200 -0
  41. package/dist/llm/provider.js +10 -0
  42. package/dist/llm/response.js +39 -0
  43. package/dist/llm/token-counter.js +39 -0
  44. package/dist/llm/types.js +1 -0
  45. package/dist/logger/app-logger.js +189 -0
  46. package/dist/logger/file-log.js +151 -0
  47. package/dist/logger/index.js +1 -0
  48. package/dist/main.js +503 -340
  49. package/dist/migration/backup.js +45 -0
  50. package/dist/migration/detect.js +50 -0
  51. package/dist/migration/index.js +2 -0
  52. package/dist/modules/artifacts/store.js +61 -0
  53. package/dist/modules/browser/actions.js +76 -0
  54. package/dist/modules/browser/bridge-client.js +199 -0
  55. package/dist/modules/browser/bridge-path.js +10 -0
  56. package/dist/modules/browser/bridge-server.mjs +219 -219
  57. package/dist/modules/browser/cookie-store.js +24 -0
  58. package/dist/modules/browser/driver.js +136 -0
  59. package/dist/modules/browser/index.js +7 -0
  60. package/dist/modules/browser/module.js +29 -0
  61. package/dist/modules/browser/session.js +342 -0
  62. package/dist/modules/browser/snapshot.js +148 -0
  63. package/dist/modules/browser/types.js +12 -0
  64. package/dist/modules/certification/cli.js +213 -0
  65. package/dist/modules/certification/fact-checker.js +82 -0
  66. package/dist/modules/certification/loader.js +106 -0
  67. package/dist/modules/certification/manifest.js +58 -0
  68. package/dist/modules/certification/runner.js +245 -0
  69. package/dist/modules/certification/scenarios.js +407 -0
  70. package/dist/modules/certification/types.js +1 -0
  71. package/dist/modules/context/chunk-query.js +100 -0
  72. package/dist/modules/context/fact-extractor.js +168 -0
  73. package/dist/modules/context/history.js +15 -0
  74. package/dist/modules/context/index.js +1 -0
  75. package/dist/modules/context/manager.js +440 -0
  76. package/dist/modules/execution/audit-runners.js +206 -0
  77. package/dist/modules/execution/auditor.js +218 -0
  78. package/dist/modules/execution/execution-plugin.js +431 -0
  79. package/dist/modules/execution/index.js +8 -0
  80. package/dist/modules/execution/module.js +625 -0
  81. package/dist/modules/execution/moe-executor.js +304 -0
  82. package/dist/modules/execution/plan-coverage.js +68 -0
  83. package/dist/modules/execution/plan-persister.js +46 -0
  84. package/dist/modules/execution/plan-store.js +196 -0
  85. package/dist/modules/execution/plan-tool.js +677 -0
  86. package/dist/modules/execution/plan-validator.js +153 -0
  87. package/dist/modules/execution/planner.js +94 -0
  88. package/dist/modules/execution/stuck-detector.js +746 -0
  89. package/dist/modules/execution/tracker.js +69 -0
  90. package/dist/modules/execution/types.js +1 -0
  91. package/dist/modules/execution/verifier.js +235 -0
  92. package/dist/modules/execution/windows-commands.js +41 -0
  93. package/dist/modules/hallucination/confidence.js +66 -0
  94. package/dist/modules/hallucination/consistency.js +26 -0
  95. package/dist/modules/hallucination/detector.js +47 -0
  96. package/dist/modules/hallucination/factual.js +169 -0
  97. package/dist/modules/hallucination/index.js +5 -0
  98. package/dist/modules/hallucination/js-identifiers.js +262 -0
  99. package/dist/modules/hallucination/llm-judge.js +101 -0
  100. package/dist/modules/index.js +5 -0
  101. package/dist/modules/indexer/cache.js +40 -0
  102. package/dist/modules/indexer/index.js +3 -0
  103. package/dist/modules/indexer/module.js +246 -0
  104. package/dist/modules/indexer/project-profile.js +183 -0
  105. package/dist/modules/indexer/walker.js +101 -0
  106. package/dist/modules/lsp/check-tool.js +58 -0
  107. package/dist/modules/lsp/client.js +389 -0
  108. package/dist/modules/lsp/command.js +60 -0
  109. package/dist/modules/lsp/config.js +135 -0
  110. package/dist/modules/lsp/index.js +3 -0
  111. package/dist/modules/lsp/module.js +260 -0
  112. package/dist/modules/lsp/probe.js +86 -0
  113. package/dist/modules/lsp/project-root.js +32 -0
  114. package/dist/modules/lsp/startup-check.js +144 -0
  115. package/dist/modules/lsp/types.js +1 -0
  116. package/dist/modules/mcp/client.js +399 -0
  117. package/dist/modules/mcp/index.js +3 -0
  118. package/dist/modules/mcp/module.js +142 -0
  119. package/dist/modules/mcp/registry.js +15 -0
  120. package/dist/modules/memory/index.js +1 -0
  121. package/dist/modules/memory/module.js +96 -0
  122. package/dist/modules/memory/search.js +42 -0
  123. package/dist/modules/memory/store.js +69 -0
  124. package/dist/modules/pipelines/engine.js +60 -0
  125. package/dist/modules/pipelines/index.js +3 -0
  126. package/dist/modules/pipelines/parser.js +56 -0
  127. package/dist/modules/pipelines/template.js +14 -0
  128. package/dist/modules/plugins/builtin/lint-on-write.js +334 -0
  129. package/dist/modules/plugins/builtin/notify.js +9 -0
  130. package/dist/modules/plugins/index.js +1 -0
  131. package/dist/modules/plugins/loader.js +70 -0
  132. package/dist/modules/plugins/manager.js +261 -0
  133. package/dist/modules/plugins/types.js +1 -0
  134. package/dist/modules/pricing/index.js +61 -0
  135. package/dist/modules/pricing/prices.js +129 -0
  136. package/dist/modules/processes/detect.js +34 -0
  137. package/dist/modules/processes/index.js +2 -0
  138. package/dist/modules/processes/registry.js +327 -0
  139. package/dist/modules/processes/runner.js +23 -0
  140. package/dist/modules/providers/create.js +22 -0
  141. package/dist/modules/providers/fallback.js +79 -0
  142. package/dist/modules/providers/health.js +46 -0
  143. package/dist/modules/providers/index.js +5 -0
  144. package/dist/modules/providers/manager.js +161 -0
  145. package/dist/modules/providers/presets.js +128 -0
  146. package/dist/modules/providers/registry.js +22 -0
  147. package/dist/modules/providers/types.js +1 -0
  148. package/dist/modules/registry.js +48 -0
  149. package/dist/modules/security/audit-log.js +136 -0
  150. package/dist/modules/security/audit-notifier.js +292 -0
  151. package/dist/modules/security/command-validator.js +219 -0
  152. package/dist/modules/security/content-scanner.js +53 -0
  153. package/dist/modules/security/data-sanitizer.js +89 -0
  154. package/dist/modules/security/encryption.js +242 -0
  155. package/dist/modules/security/index.js +14 -0
  156. package/dist/modules/security/network-validator.js +88 -0
  157. package/dist/modules/security/path-validator.js +203 -0
  158. package/dist/modules/security/rate-limiter.js +119 -0
  159. package/dist/modules/security/security-policies.js +531 -0
  160. package/dist/modules/security/session-encryption.js +210 -0
  161. package/dist/modules/security/session-isolation.js +95 -0
  162. package/dist/modules/session/index.js +3 -0
  163. package/dist/modules/session/manager.js +172 -0
  164. package/dist/modules/session/module.js +24 -0
  165. package/dist/modules/session/store.js +222 -0
  166. package/dist/modules/session/types.js +1 -0
  167. package/dist/modules/skills/index.js +2 -0
  168. package/dist/modules/skills/loader.js +72 -0
  169. package/dist/modules/skills/matcher.js +27 -0
  170. package/dist/modules/skills/module.js +129 -0
  171. package/dist/modules/types.js +1 -0
  172. package/dist/modules/updater/checker.js +96 -0
  173. package/dist/modules/updater/index.js +2 -0
  174. package/dist/modules/updater/module.js +116 -0
  175. package/dist/modules/user-profile/compressor.js +16 -0
  176. package/dist/modules/user-profile/index.js +1 -0
  177. package/dist/modules/user-profile/profile.js +68 -0
  178. package/dist/skills/builtin/git.md +36 -36
  179. package/dist/skills/builtin/typescript.md +35 -35
  180. package/dist/tools/approve.js +33 -0
  181. package/dist/tools/attach-image.js +101 -0
  182. package/dist/tools/bash.js +519 -0
  183. package/dist/tools/browser.js +115 -0
  184. package/dist/tools/chunk-query.js +100 -0
  185. package/dist/tools/create-dir.js +56 -0
  186. package/dist/tools/delete-file.js +63 -0
  187. package/dist/tools/download-file.js +117 -0
  188. package/dist/tools/edit-file.js +80 -0
  189. package/dist/tools/enable-tools.js +59 -0
  190. package/dist/tools/executor.js +154 -0
  191. package/dist/tools/file-info.js +47 -0
  192. package/dist/tools/filter-tools.js +17 -0
  193. package/dist/tools/glob-tool.js +27 -0
  194. package/dist/tools/grep-tool.js +125 -0
  195. package/dist/tools/hidden-tools-block.js +37 -0
  196. package/dist/tools/index.js +78 -0
  197. package/dist/tools/list-dir.js +49 -0
  198. package/dist/tools/load-skill.js +43 -0
  199. package/dist/tools/mcp-call.js +69 -0
  200. package/dist/tools/move-file.js +86 -0
  201. package/dist/tools/path-utils.js +101 -0
  202. package/dist/tools/pipeline-run.js +145 -0
  203. package/dist/tools/preview.js +2 -0
  204. package/dist/tools/process-kill.js +40 -0
  205. package/dist/tools/process-list.js +37 -0
  206. package/dist/tools/process-log.js +54 -0
  207. package/dist/tools/question.js +141 -0
  208. package/dist/tools/read-file.js +179 -0
  209. package/dist/tools/recall.js +118 -0
  210. package/dist/tools/registry.js +47 -0
  211. package/dist/tools/remember.js +68 -0
  212. package/dist/tools/scope-check.js +32 -0
  213. package/dist/tools/search-history.js +85 -0
  214. package/dist/tools/subagent.js +196 -0
  215. package/dist/tools/types.js +1 -0
  216. package/dist/tools/user-input.js +123 -0
  217. package/dist/tools/web-browse.js +87 -0
  218. package/dist/tools/web-fetch.js +119 -0
  219. package/dist/tools/web-search.js +105 -0
  220. package/dist/tools/write-file.js +82 -0
  221. package/dist/ui/box.js +77 -0
  222. package/dist/ui/colors.js +4 -0
  223. package/dist/ui/diff.js +178 -0
  224. package/dist/ui/index.js +6 -0
  225. package/dist/ui/line-editor.js +822 -0
  226. package/dist/ui/line-math.js +73 -0
  227. package/dist/ui/md-formatter.js +212 -0
  228. package/dist/ui/output.js +13 -0
  229. package/dist/ui/plan-view.js +103 -0
  230. package/dist/ui/renderer.js +259 -0
  231. package/dist/ui/spinner.js +70 -0
  232. package/dist/ui/table.js +144 -0
  233. package/package.json +51 -51
@@ -0,0 +1,822 @@
1
+ import * as readline from "readline";
2
+ import stringWidth from "string-width";
3
+ import { buildLayout, layoutIndexFor, visualColAt, charOffsetFor, charLen, stripAnsi, } from "./line-math";
4
+ export class LineEditor {
5
+ input;
6
+ output;
7
+ /** Host hook: return true to swallow the key before the editor handles it. */
8
+ onKeyInput;
9
+ onInterrupt;
10
+ promptStr;
11
+ completer;
12
+ history;
13
+ historySize;
14
+ lines = [""];
15
+ row = 0;
16
+ col = 0;
17
+ historyIndex = -1;
18
+ stash = null;
19
+ isDone = false;
20
+ isPaste = false;
21
+ /** Pasted characters accumulated between `paste-start` and `paste-end`.
22
+ * Inserted as a single batch on `paste-end` — one render instead of one
23
+ * per keypress, so a paste appears as a paste, not as fast typing. */
24
+ pasteBuffer = "";
25
+ /** Whether the last paste keypress was a bare CR — used to collapse a
26
+ * CRLF pair into a single newline (Windows clipboard text). */
27
+ pasteLastWasCR = false;
28
+ lastWasCR = false;
29
+ questionCb = null;
30
+ rawMode = false;
31
+ listeners = {};
32
+ /** Visual row (within the drawn frame) where the cursor was placed by the
33
+ * last render — fallback for moving back to the frame's first row before
34
+ * redrawing when no absolute anchor is known yet. Relative moves break
35
+ * once the terminal scrolls (the frame shifts up on screen while the
36
+ * relative count does not), which duplicated multi-line input. */
37
+ prevCursorRow = 0;
38
+ /** Absolute 1-based screen row of the frame's first visual row, learned
39
+ * from a single DSR cursor-position report (`ESC[6n`) sent once per
40
+ * prompt presentation. After the initial query the anchor is updated
41
+ * deterministically via scroll math — no further queries are sent,
42
+ * avoiding ConPTY desync. Falls back to relative moves when the reply
43
+ * never arrives (timeout / broken terminal). */
44
+ frameTopAbs = null;
45
+ /** True while waiting for a DSR reply (exactly one outstanding query). */
46
+ dsrPending = false;
47
+ /** Buffer for partial DSR escape sequences split across data chunks. */
48
+ dsrTail = "";
49
+ constructor(opts) {
50
+ this.input = opts.input;
51
+ this.output = opts.output;
52
+ this.promptStr = opts.prompt ?? "";
53
+ this.completer = opts.completer;
54
+ this.onInterrupt = opts.onInterrupt;
55
+ this.history = opts.history ?? [];
56
+ this.historySize = opts.historySize ?? 50;
57
+ if (this.history.length > this.historySize) {
58
+ this.history = this.history.slice(-this.historySize);
59
+ }
60
+ if (this.input.isTTY) {
61
+ this.rawMode = typeof this.input.setRawMode === "function";
62
+ if (this.rawMode)
63
+ this.input.setRawMode(true);
64
+ this.enableTerminalProtocols();
65
+ // Raw data listener for DSR cursor-position replies. Runs alongside
66
+ // readline's keypress emitter (both receive every chunk); replies may
67
+ // arrive merged with regular keystrokes, hence the global regex.
68
+ this.input.on("data", (buf) => this.consumeDsrReplies(buf.toString("utf-8")));
69
+ readline.emitKeypressEvents(this.input);
70
+ this.input.on("keypress", (str, key) => this.onKey(str, key));
71
+ }
72
+ else {
73
+ this.input.on("data", (buf) => this.onData(buf));
74
+ this.input.on("end", () => {
75
+ const last = this.lines.join("\n");
76
+ this.lines = [""];
77
+ this.row = 0;
78
+ this.col = 0;
79
+ if (last)
80
+ this.emitLine(last);
81
+ this.emitClose();
82
+ });
83
+ }
84
+ }
85
+ on(event, listener) {
86
+ if (event === "line") {
87
+ this.listeners.line = listener;
88
+ }
89
+ else {
90
+ this.listeners.close = listener;
91
+ }
92
+ return this;
93
+ }
94
+ setPrompt(prompt) {
95
+ this.promptStr = prompt;
96
+ if (this.input.isTTY)
97
+ this.render();
98
+ }
99
+ prompt(_preserveCursor) {
100
+ if (this.input.isTTY)
101
+ this.render();
102
+ }
103
+ write(s) {
104
+ this.insertText(s);
105
+ }
106
+ reset() {
107
+ this.lines = [""];
108
+ this.row = 0;
109
+ this.col = 0;
110
+ this.historyIndex = -1;
111
+ this.stash = null;
112
+ this.invalidateAnchor();
113
+ if (this.input.isTTY)
114
+ this.render();
115
+ }
116
+ question(query, cb) {
117
+ this.questionCb = cb;
118
+ this.promptStr = query;
119
+ this.lines = [""];
120
+ this.row = 0;
121
+ this.col = 0;
122
+ this.invalidateAnchor();
123
+ if (this.input.isTTY)
124
+ this.render();
125
+ }
126
+ close() {
127
+ if (this.isDone)
128
+ return;
129
+ this.isDone = true;
130
+ this.disableTerminalProtocols();
131
+ if (this.rawMode && this.input.setRawMode) {
132
+ this.input.setRawMode(false);
133
+ }
134
+ this.emitClose();
135
+ }
136
+ // ---- input handling ----
137
+ onData(buf) {
138
+ if (this.isDone)
139
+ return;
140
+ let text = buf.toString("utf-8");
141
+ text = text.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
142
+ const parts = text.split("\n");
143
+ for (let i = 0; i < parts.length; i++) {
144
+ if (i < parts.length - 1) {
145
+ this.emitLine(parts[i]);
146
+ this.lines = [""];
147
+ this.row = 0;
148
+ this.col = 0;
149
+ }
150
+ else if (parts[i]) {
151
+ this.emitLine(parts[i]);
152
+ this.lines = [""];
153
+ this.row = 0;
154
+ this.col = 0;
155
+ }
156
+ }
157
+ }
158
+ onKey(str, key) {
159
+ if (this.isDone)
160
+ return;
161
+ if (this.onKeyInput && this.onKeyInput(str, key))
162
+ return;
163
+ const k = key;
164
+ const name = k?.name ?? "undefined";
165
+ const seq = k?.sequence ?? str ?? "";
166
+ if (name === "undefined" && /^\x1b\[\d+(?:;\d+)?u$/.test(seq)) {
167
+ const m = seq.match(/^\x1b\[(\d+)(?:;(\d+))?u$/);
168
+ if (m && Number(m[1]) === 13 && Number(m[2] ?? 0) !== 0) {
169
+ this.insertNewline();
170
+ }
171
+ return;
172
+ }
173
+ if (name === "paste-start" || seq === "\x1b[200~") {
174
+ this.isPaste = true;
175
+ this.pasteBuffer = "";
176
+ this.pasteLastWasCR = false;
177
+ return;
178
+ }
179
+ if (name === "paste-end" || seq === "\x1b[201~") {
180
+ this.isPaste = false;
181
+ if (this.pasteBuffer) {
182
+ this.insertPaste(this.pasteBuffer);
183
+ }
184
+ else {
185
+ this.render();
186
+ }
187
+ this.pasteBuffer = "";
188
+ this.pasteLastWasCR = false;
189
+ return;
190
+ }
191
+ if (this.isPaste) {
192
+ if (name === "return" || seq === "\r") {
193
+ this.pasteBuffer += "\n";
194
+ this.pasteLastWasCR = true;
195
+ }
196
+ else if (name === "enter" || seq === "\n") {
197
+ if (this.pasteLastWasCR) {
198
+ this.pasteLastWasCR = false;
199
+ }
200
+ else {
201
+ this.pasteBuffer += "\n";
202
+ }
203
+ }
204
+ else if (str) {
205
+ this.pasteLastWasCR = false;
206
+ this.pasteBuffer += str;
207
+ }
208
+ return;
209
+ }
210
+ if (name === "return" && (seq === "\x1b\r" || k.meta)) {
211
+ this.insertNewline();
212
+ return;
213
+ }
214
+ if (name === "undefined" && seq === "\x1b\r") {
215
+ this.insertNewline();
216
+ return;
217
+ }
218
+ if (k?.ctrl && name === "j") {
219
+ this.insertNewline();
220
+ return;
221
+ }
222
+ if (name === "escape")
223
+ return;
224
+ switch (name) {
225
+ case "return":
226
+ this.lastWasCR = true;
227
+ this.submit();
228
+ return;
229
+ case "enter":
230
+ if (this.lastWasCR) {
231
+ this.lastWasCR = false;
232
+ return;
233
+ }
234
+ // In question mode, LF should also submit (script/pipes send
235
+ // \n without preceding \r, unlike real terminals).
236
+ if (this.questionCb) {
237
+ this.submit();
238
+ return;
239
+ }
240
+ this.insertNewline();
241
+ return;
242
+ case "backspace":
243
+ this.lastWasCR = false;
244
+ this.backspace();
245
+ return;
246
+ case "delete":
247
+ this.lastWasCR = false;
248
+ this.deleteForward();
249
+ return;
250
+ case "left":
251
+ this.lastWasCR = false;
252
+ this.moveLeft();
253
+ return;
254
+ case "right":
255
+ this.lastWasCR = false;
256
+ this.moveRight();
257
+ return;
258
+ case "up":
259
+ this.lastWasCR = false;
260
+ this.moveUp();
261
+ return;
262
+ case "down":
263
+ this.lastWasCR = false;
264
+ this.moveDown();
265
+ return;
266
+ case "home":
267
+ this.lastWasCR = false;
268
+ this.moveHome();
269
+ return;
270
+ case "end":
271
+ this.lastWasCR = false;
272
+ this.moveEnd();
273
+ return;
274
+ case "pageup":
275
+ this.lastWasCR = false;
276
+ this.moveToStart();
277
+ return;
278
+ case "pagedown":
279
+ this.lastWasCR = false;
280
+ this.moveToEnd();
281
+ return;
282
+ case "tab":
283
+ this.lastWasCR = false;
284
+ this.tabComplete();
285
+ return;
286
+ }
287
+ if (k?.ctrl) {
288
+ this.lastWasCR = false;
289
+ switch (name) {
290
+ case "c":
291
+ this.ctrlC();
292
+ return;
293
+ case "d":
294
+ this.ctrlD();
295
+ return;
296
+ case "a":
297
+ this.moveHome();
298
+ return;
299
+ case "e":
300
+ this.moveEnd();
301
+ return;
302
+ case "u":
303
+ this.killToStart();
304
+ return;
305
+ case "k":
306
+ this.killToEnd();
307
+ return;
308
+ case "w":
309
+ this.killWordBefore();
310
+ return;
311
+ case "l":
312
+ this.clearScreen();
313
+ return;
314
+ default:
315
+ return;
316
+ }
317
+ }
318
+ if (k?.meta) {
319
+ this.lastWasCR = false;
320
+ switch (name) {
321
+ case "b":
322
+ this.moveWordLeft();
323
+ return;
324
+ case "f":
325
+ this.moveWordRight();
326
+ return;
327
+ case "d":
328
+ this.killWordAfter();
329
+ return;
330
+ default:
331
+ return;
332
+ }
333
+ }
334
+ if (str && !/^[\u0000-\u001f\u007f]/.test(str)) {
335
+ this.lastWasCR = false;
336
+ this.insertText(str);
337
+ }
338
+ }
339
+ submit() {
340
+ if (this.questionCb) {
341
+ const cb = this.questionCb;
342
+ this.questionCb = null;
343
+ const answer = this.lines.join("\n").trim();
344
+ this.commitFrame();
345
+ this.output.write("\r\n");
346
+ this.invalidateAnchor();
347
+ this.lines = [""];
348
+ this.row = 0;
349
+ this.col = 0;
350
+ cb(answer);
351
+ return;
352
+ }
353
+ const text = this.lines.join("\n");
354
+ if (text.trim()) {
355
+ this.history.push(text);
356
+ if (this.history.length > this.historySize) {
357
+ this.history = this.history.slice(-this.historySize);
358
+ }
359
+ }
360
+ this.historyIndex = -1;
361
+ this.stash = null;
362
+ this.commitFrame();
363
+ this.output.write("\r\n");
364
+ this.invalidateAnchor();
365
+ this.lines = [""];
366
+ this.row = 0;
367
+ this.col = 0;
368
+ this.emitLine(text);
369
+ }
370
+ /** Move the cursor to the end of the buffer's last visual row so the
371
+ * submitted text stays on screen (commit), without erasing the frame.
372
+ * Uses the absolute anchor when known — relative moves land short once
373
+ * a tall frame has scrolled the terminal. */
374
+ commitFrame() {
375
+ const layout = this.visibleLayout();
376
+ const lastLen = charLen(stripAnsi(layout[layout.length - 1].text));
377
+ if (this.frameTopAbs !== null) {
378
+ this.output.write(`\x1b[${this.frameTopAbs + layout.length - 1};${lastLen + 1}H`);
379
+ return;
380
+ }
381
+ const idx = layoutIndexFor(layout, this.row, this.col);
382
+ const rowsDown = layout.length - 1 - idx;
383
+ const out = [];
384
+ if (rowsDown > 0)
385
+ out.push(`\x1b[${rowsDown}B`);
386
+ out.push("\r");
387
+ if (lastLen > 0)
388
+ out.push(`\x1b[${lastLen}C`);
389
+ this.output.write(out.join(""));
390
+ }
391
+ ctrlC() {
392
+ this.lines = [""];
393
+ this.row = 0;
394
+ this.col = 0;
395
+ this.invalidateAnchor();
396
+ this.render();
397
+ if (this.onInterrupt) {
398
+ this.onInterrupt();
399
+ return;
400
+ }
401
+ // Default: emit only when someone listens. With zero handlers
402
+ // process.emit("SIGINT") takes the DEFAULT action (process termination);
403
+ // the REPL always installs a listener, so production is unaffected.
404
+ if (process.listenerCount("SIGINT") > 0) {
405
+ process.emit("SIGINT");
406
+ }
407
+ }
408
+ ctrlD() {
409
+ if (this.lines.length === 1 && this.lines[0] === "") {
410
+ this.emitClose();
411
+ }
412
+ else {
413
+ this.deleteForward();
414
+ }
415
+ }
416
+ // ---- editing primitives ----
417
+ currentChars() {
418
+ return Array.from(this.lines[this.row]);
419
+ }
420
+ setCurrentChars(chars) {
421
+ this.lines[this.row] = chars.join("");
422
+ }
423
+ insertText(text) {
424
+ const sanitized = text.replace(/\r\n/g, "\n").replace(/\r/g, "");
425
+ const chars = this.currentChars();
426
+ const t = Array.from(sanitized);
427
+ chars.splice(this.col, 0, ...t);
428
+ this.setCurrentChars(chars);
429
+ this.col += t.length;
430
+ this.render();
431
+ }
432
+ /** Bulk-insert pasted text at the cursor. Splits on newlines so the buffer
433
+ * keeps one string per line (instead of embedding literal `\n` chars),
434
+ * and renders once — a paste must look like a paste, not like typing. */
435
+ insertPaste(text) {
436
+ const segments = text.split("\n");
437
+ if (segments.length === 1) {
438
+ this.insertText(segments[0]);
439
+ return;
440
+ }
441
+ const chars = this.currentChars();
442
+ const head = chars.slice(0, this.col).join("");
443
+ const tail = chars.slice(this.col).join("");
444
+ const lines = [head + segments[0]];
445
+ for (let i = 1; i < segments.length - 1; i++)
446
+ lines.push(segments[i]);
447
+ lines.push(segments[segments.length - 1] + tail);
448
+ this.lines.splice(this.row, 1, ...lines);
449
+ this.row += segments.length - 1;
450
+ this.col = charLen(segments[segments.length - 1]);
451
+ this.render();
452
+ }
453
+ insertNewline() {
454
+ const chars = this.currentChars();
455
+ const rest = chars.slice(this.col).join("");
456
+ this.setCurrentChars(chars.slice(0, this.col));
457
+ this.lines.splice(this.row + 1, 0, rest);
458
+ this.row++;
459
+ this.col = 0;
460
+ this.render();
461
+ }
462
+ backspace() {
463
+ const chars = this.currentChars();
464
+ if (this.col > 0) {
465
+ chars.splice(this.col - 1, 1);
466
+ this.setCurrentChars(chars);
467
+ this.col--;
468
+ }
469
+ else if (this.row > 0) {
470
+ const prevLen = charLen(this.lines[this.row - 1]);
471
+ this.lines[this.row - 1] = this.lines[this.row - 1] + this.lines[this.row];
472
+ this.lines.splice(this.row, 1);
473
+ this.row--;
474
+ this.col = prevLen;
475
+ }
476
+ this.render();
477
+ }
478
+ deleteForward() {
479
+ const chars = this.currentChars();
480
+ if (this.col < chars.length) {
481
+ chars.splice(this.col, 1);
482
+ this.setCurrentChars(chars);
483
+ }
484
+ else if (this.row < this.lines.length - 1) {
485
+ this.lines[this.row] = this.lines[this.row] + this.lines[this.row + 1];
486
+ this.lines.splice(this.row + 1, 1);
487
+ }
488
+ this.render();
489
+ }
490
+ killToStart() {
491
+ const chars = this.currentChars();
492
+ this.setCurrentChars(chars.slice(this.col));
493
+ this.col = 0;
494
+ this.render();
495
+ }
496
+ killToEnd() {
497
+ const chars = this.currentChars();
498
+ this.setCurrentChars(chars.slice(0, this.col));
499
+ this.render();
500
+ }
501
+ killWordBefore() {
502
+ const chars = this.currentChars();
503
+ let i = this.col;
504
+ while (i > 0 && /\s/.test(chars[i - 1]))
505
+ i--;
506
+ while (i > 0 && !/\s/.test(chars[i - 1]))
507
+ i--;
508
+ chars.splice(i, this.col - i);
509
+ this.setCurrentChars(chars);
510
+ this.col = i;
511
+ this.render();
512
+ }
513
+ killWordAfter() {
514
+ const chars = this.currentChars();
515
+ const n = chars.length;
516
+ let i = this.col;
517
+ while (i < n && /\s/.test(chars[i]))
518
+ i++;
519
+ while (i < n && !/\s/.test(chars[i]))
520
+ i++;
521
+ chars.splice(this.col, i - this.col);
522
+ this.setCurrentChars(chars);
523
+ this.render();
524
+ }
525
+ // ---- navigation ----
526
+ moveLeft() {
527
+ if (this.col > 0) {
528
+ this.col--;
529
+ }
530
+ else if (this.row > 0) {
531
+ this.row--;
532
+ this.col = charLen(this.lines[this.row]);
533
+ }
534
+ this.render();
535
+ }
536
+ moveRight() {
537
+ if (this.col < charLen(this.lines[this.row])) {
538
+ this.col++;
539
+ }
540
+ else if (this.row < this.lines.length - 1) {
541
+ this.row++;
542
+ this.col = 0;
543
+ }
544
+ this.render();
545
+ }
546
+ moveUp() {
547
+ const layout = this.layout();
548
+ const idx = layoutIndexFor(layout, this.row, this.col);
549
+ const vcol = visualColAt(layout, idx, this.col);
550
+ if (idx > 0) {
551
+ const target = layout[idx - 1];
552
+ this.row = target.bufRow;
553
+ this.col = charOffsetFor(layout, idx - 1, vcol);
554
+ this.render();
555
+ }
556
+ else {
557
+ this.historyPrev();
558
+ }
559
+ }
560
+ moveDown() {
561
+ const layout = this.layout();
562
+ const idx = layoutIndexFor(layout, this.row, this.col);
563
+ const vcol = visualColAt(layout, idx, this.col);
564
+ if (idx < layout.length - 1) {
565
+ const target = layout[idx + 1];
566
+ this.row = target.bufRow;
567
+ this.col = charOffsetFor(layout, idx + 1, vcol);
568
+ this.render();
569
+ }
570
+ else {
571
+ this.historyNext();
572
+ }
573
+ }
574
+ moveHome() {
575
+ this.col = 0;
576
+ this.render();
577
+ }
578
+ moveEnd() {
579
+ this.col = charLen(this.lines[this.row]);
580
+ this.render();
581
+ }
582
+ moveToStart() {
583
+ this.row = 0;
584
+ this.col = 0;
585
+ this.render();
586
+ }
587
+ moveToEnd() {
588
+ this.row = this.lines.length - 1;
589
+ this.col = charLen(this.lines[this.row]);
590
+ this.render();
591
+ }
592
+ moveWordLeft() {
593
+ const chars = this.currentChars();
594
+ let i = this.col;
595
+ while (i > 0 && /\s/.test(chars[i - 1]))
596
+ i--;
597
+ while (i > 0 && !/\s/.test(chars[i - 1]))
598
+ i--;
599
+ this.col = i;
600
+ this.render();
601
+ }
602
+ moveWordRight() {
603
+ const chars = this.currentChars();
604
+ const n = chars.length;
605
+ let i = this.col;
606
+ while (i < n && !/\s/.test(chars[i]))
607
+ i++;
608
+ while (i < n && /\s/.test(chars[i]))
609
+ i++;
610
+ this.col = i;
611
+ this.render();
612
+ }
613
+ historyPrev() {
614
+ if (this.history.length === 0)
615
+ return;
616
+ if (this.historyIndex === -1) {
617
+ this.stash = {
618
+ lines: this.lines.slice(),
619
+ row: this.row,
620
+ col: this.col,
621
+ };
622
+ this.historyIndex = 0;
623
+ }
624
+ else if (this.historyIndex < this.history.length - 1) {
625
+ this.historyIndex++;
626
+ }
627
+ else {
628
+ return;
629
+ }
630
+ this.applyHistoryEntry();
631
+ }
632
+ historyNext() {
633
+ if (this.historyIndex === -1)
634
+ return;
635
+ if (this.historyIndex > 0) {
636
+ this.historyIndex--;
637
+ this.applyHistoryEntry();
638
+ }
639
+ else if (this.stash) {
640
+ this.lines = this.stash.lines.slice();
641
+ this.row = this.stash.row;
642
+ this.col = this.stash.col;
643
+ this.historyIndex = -1;
644
+ this.stash = null;
645
+ this.render();
646
+ }
647
+ }
648
+ applyHistoryEntry() {
649
+ const entry = this.history[this.history.length - 1 - this.historyIndex];
650
+ this.lines = entry.split("\n");
651
+ if (this.lines.length === 0)
652
+ this.lines = [""];
653
+ this.row = this.lines.length - 1;
654
+ this.col = charLen(this.lines[this.row]);
655
+ this.render();
656
+ }
657
+ // ---- completion / misc ----
658
+ tabComplete() {
659
+ if (!this.completer)
660
+ return;
661
+ const line = this.lines[this.row];
662
+ const [matches, partial] = this.completer(line);
663
+ if (matches.length === 0) {
664
+ this.output.write("\x07");
665
+ return;
666
+ }
667
+ if (matches.length === 1) {
668
+ const from = line.lastIndexOf(partial);
669
+ const head = line.slice(0, from);
670
+ const tail = line.slice(from + partial.length);
671
+ this.lines[this.row] = head + matches[0] + tail;
672
+ this.col = charLen(head) + charLen(matches[0]);
673
+ this.render();
674
+ return;
675
+ }
676
+ const lines = matches.map((m) => " " + m);
677
+ this.output.write("\r\n" + lines.join("\r\n") + "\r\n");
678
+ this.output.write(`\x1b[${lines.length + 1}A`);
679
+ this.render();
680
+ }
681
+ clearScreen() {
682
+ this.output.write("\x1b[2J\x1b[H");
683
+ this.invalidateAnchor();
684
+ this.render();
685
+ }
686
+ // ---- rendering ----
687
+ columns() {
688
+ return this.output.columns || 80;
689
+ }
690
+ layout() {
691
+ const promptWidth = stringWidth(stripAnsi(this.promptStr));
692
+ return buildLayout(this.lines, this.columns(), Math.max(1, this.columns() - promptWidth));
693
+ }
694
+ /** 1-based terminal height, or null when unknown (tests / non-TTY). */
695
+ screenRows() {
696
+ const r = this.output.rows;
697
+ return typeof r === "number" && r > 3 ? r : null;
698
+ }
699
+ /** Cap the rendered frame to the visible screen. A frame taller than the
700
+ * terminal cannot be redrawn in place at all (its top scrolls off), so
701
+ * only the tail is drawn; the absolute anchor keeps the next render
702
+ * consistent regardless. */
703
+ visibleLayout() {
704
+ const layout = this.layout();
705
+ const H = this.screenRows();
706
+ const maxRows = H ? H - 2 : 0;
707
+ if (maxRows > 0 && layout.length > maxRows) {
708
+ return layout.slice(layout.length - maxRows);
709
+ }
710
+ return layout;
711
+ }
712
+ /** Forget the learned absolute frame position — the cursor has jumped to
713
+ * an unknown location (external output, clear screen, fresh prompt).
714
+ * The next render will re-query via DSR. */
715
+ invalidateAnchor() {
716
+ this.frameTopAbs = null;
717
+ this.dsrPending = false;
718
+ this.dsrTail = "";
719
+ this.prevCursorRow = 0;
720
+ }
721
+ /** Parse `ESC[row;colR` cursor-position replies. Buffers partial escape
722
+ * sequences across chunks. Accepts at most one reply (the outstanding
723
+ * query); extras are silently dropped. Validates the reported row against
724
+ * `screenRows()` to reject implausible ConPTY values. */
725
+ consumeDsrReplies(chunk) {
726
+ this.dsrTail = (this.dsrTail + chunk).slice(-80);
727
+ const m = /\x1b\[(\d+);(\d+)R/.exec(this.dsrTail);
728
+ if (!m)
729
+ return;
730
+ this.dsrTail = "";
731
+ if (!this.dsrPending)
732
+ return;
733
+ this.dsrPending = false;
734
+ const row = Number(m[1]);
735
+ const idx = Number(m[2]);
736
+ // idx is not the layout index — it's the column from the reply; ignore it.
737
+ // We compute frameTop from the reply row minus the cursor's visual row
738
+ // at query time. The visual row was stored in `prevCursorRow` when the
739
+ // query was sent (right after render).
740
+ const top = row - this.prevCursorRow;
741
+ if (top >= 1)
742
+ this.frameTopAbs = top;
743
+ }
744
+ render() {
745
+ if (!this.input.isTTY || this.isDone)
746
+ return;
747
+ const layout = this.visibleLayout();
748
+ const promptWidth = stringWidth(stripAnsi(this.promptStr));
749
+ const idx = layoutIndexFor(layout, this.row, this.col);
750
+ const vcol = visualColAt(layout, idx, this.col);
751
+ const rowsAfter = layout.length - idx - 1;
752
+ const ccol = (idx === 0 ? promptWidth : 0) + vcol;
753
+ const out = [];
754
+ // Return to the frame's first row before redrawing. Absolute
755
+ // positioning (learned via a single DSR query per prompt) is
756
+ // scroll-proof; relative up-moves are the fallback until the
757
+ // initial reply arrives.
758
+ if (this.frameTopAbs !== null) {
759
+ out.push(`\x1b[${this.frameTopAbs};1H`);
760
+ }
761
+ else if (this.prevCursorRow > 0) {
762
+ out.push(`\x1b[${this.prevCursorRow}A`);
763
+ out.push("\r");
764
+ }
765
+ else {
766
+ out.push("\r");
767
+ }
768
+ for (let i = 0; i < layout.length; i++) {
769
+ out.push("\x1b[2K");
770
+ if (i === 0)
771
+ out.push(this.promptStr);
772
+ out.push(layout[i].text);
773
+ if (i < layout.length - 1)
774
+ out.push("\r\n");
775
+ }
776
+ out.push("\x1b[J");
777
+ if (rowsAfter > 0)
778
+ out.push(`\x1b[${rowsAfter}A`);
779
+ out.push("\r");
780
+ if (ccol > 0)
781
+ out.push(`\x1b[${ccol}C`);
782
+ this.output.write(out.join(""));
783
+ // Deterministic scroll math: update the anchor for the NEXT render.
784
+ // After writing L rows starting from frameTopAbs, if the frame extends
785
+ // past the screen bottom the terminal scrolls; the new frame top is
786
+ // computed locally — no further DSR queries needed.
787
+ if (this.frameTopAbs !== null) {
788
+ const H = this.screenRows();
789
+ if (H) {
790
+ const T = this.frameTopAbs;
791
+ const L = layout.length;
792
+ if (T + L - 1 > H)
793
+ this.frameTopAbs = H - L + 1;
794
+ // else: no scroll, anchor unchanged
795
+ }
796
+ }
797
+ else if (!this.dsrPending) {
798
+ // First render after prompt — send exactly ONE DSR query.
799
+ // Disabled for now: ConPTY may buffer stdout while processing
800
+ // the DSR reply, hiding agent responses. Will revisit once
801
+ // scroll-proof rendering is solved via deterministic tracking.
802
+ //
803
+ // this.dsrPending = true;
804
+ // this.output.write("\x1b[6n");
805
+ }
806
+ this.prevCursorRow = idx;
807
+ }
808
+ enableTerminalProtocols() {
809
+ this.output.write("\x1b[?2004h");
810
+ this.output.write("\x1b[>1u");
811
+ }
812
+ disableTerminalProtocols() {
813
+ this.output.write("\x1b[?2004l");
814
+ this.output.write("\x1b[<u");
815
+ }
816
+ emitLine(line) {
817
+ this.listeners.line?.(line);
818
+ }
819
+ emitClose() {
820
+ this.listeners.close?.();
821
+ }
822
+ }