micro-models-agent 0.46.1 → 0.46.3

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 (218) hide show
  1. package/README.md +312 -312
  2. package/dist/main.js +724 -530
  3. package/dist/modules/browser/bridge-server.mjs +202 -202
  4. package/dist/skills/builtin/git.md +36 -36
  5. package/dist/skills/builtin/typescript.md +35 -35
  6. package/package.json +48 -48
  7. package/dist/cli/commands.js +0 -323
  8. package/dist/cli/completer.js +0 -167
  9. package/dist/cli/index.js +0 -2
  10. package/dist/cli/main.js +0 -165
  11. package/dist/cli/plugin-commands.js +0 -36
  12. package/dist/cli/repl-commands.js +0 -661
  13. package/dist/cli/repl.js +0 -616
  14. package/dist/cli/run-result.js +0 -22
  15. package/dist/cli/security-commands.js +0 -164
  16. package/dist/cli/setup.js +0 -231
  17. package/dist/config/config.js +0 -249
  18. package/dist/config/defaults.js +0 -124
  19. package/dist/config/experts.js +0 -15
  20. package/dist/config/index.js +0 -3
  21. package/dist/config/security.js +0 -193
  22. package/dist/config/types.js +0 -1
  23. package/dist/core/agent-moe.js +0 -102
  24. package/dist/core/agent.js +0 -886
  25. package/dist/core/bootstrap.js +0 -404
  26. package/dist/core/index.js +0 -2
  27. package/dist/core/prompt-builder.js +0 -76
  28. package/dist/core/session-logger.js +0 -197
  29. package/dist/core/types.js +0 -1
  30. package/dist/core/version.js +0 -24
  31. package/dist/core/workspace.js +0 -76
  32. package/dist/i18n/en.json +0 -598
  33. package/dist/i18n/index.js +0 -46
  34. package/dist/i18n/ru.json +0 -598
  35. package/dist/index.js +0 -22
  36. package/dist/llm/image-utils.js +0 -143
  37. package/dist/llm/index.js +0 -4
  38. package/dist/llm/model-loader.js +0 -78
  39. package/dist/llm/openai-compat.js +0 -359
  40. package/dist/llm/orchestrator.js +0 -198
  41. package/dist/llm/provider.js +0 -10
  42. package/dist/llm/response.js +0 -39
  43. package/dist/llm/token-counter.js +0 -39
  44. package/dist/llm/types.js +0 -1
  45. package/dist/logger/app-logger.js +0 -143
  46. package/dist/logger/file-log.js +0 -151
  47. package/dist/logger/index.js +0 -1
  48. package/dist/migration/backup.js +0 -45
  49. package/dist/migration/detect.js +0 -50
  50. package/dist/migration/index.js +0 -2
  51. package/dist/modules/artifacts/store.js +0 -61
  52. package/dist/modules/browser/actions.js +0 -76
  53. package/dist/modules/browser/bridge-client.js +0 -199
  54. package/dist/modules/browser/bridge-path.js +0 -10
  55. package/dist/modules/browser/cookie-store.js +0 -24
  56. package/dist/modules/browser/driver.js +0 -136
  57. package/dist/modules/browser/index.js +0 -7
  58. package/dist/modules/browser/module.js +0 -29
  59. package/dist/modules/browser/session.js +0 -338
  60. package/dist/modules/browser/snapshot.js +0 -148
  61. package/dist/modules/browser/types.js +0 -12
  62. package/dist/modules/certification/cli.js +0 -174
  63. package/dist/modules/certification/fact-checker.js +0 -82
  64. package/dist/modules/certification/loader.js +0 -105
  65. package/dist/modules/certification/manifest.js +0 -50
  66. package/dist/modules/certification/runner.js +0 -159
  67. package/dist/modules/certification/scenarios.js +0 -124
  68. package/dist/modules/certification/types.js +0 -1
  69. package/dist/modules/context/chunk-query.js +0 -100
  70. package/dist/modules/context/fact-extractor.js +0 -162
  71. package/dist/modules/context/history.js +0 -15
  72. package/dist/modules/context/index.js +0 -1
  73. package/dist/modules/context/manager.js +0 -423
  74. package/dist/modules/execution/audit-runners.js +0 -152
  75. package/dist/modules/execution/auditor.js +0 -218
  76. package/dist/modules/execution/execution-plugin.js +0 -272
  77. package/dist/modules/execution/index.js +0 -8
  78. package/dist/modules/execution/module.js +0 -436
  79. package/dist/modules/execution/moe-executor.js +0 -291
  80. package/dist/modules/execution/plan-coverage.js +0 -68
  81. package/dist/modules/execution/plan-persister.js +0 -46
  82. package/dist/modules/execution/plan-store.js +0 -157
  83. package/dist/modules/execution/plan-tool.js +0 -508
  84. package/dist/modules/execution/plan-validator.js +0 -153
  85. package/dist/modules/execution/planner.js +0 -90
  86. package/dist/modules/execution/stuck-detector.js +0 -510
  87. package/dist/modules/execution/tracker.js +0 -67
  88. package/dist/modules/execution/types.js +0 -1
  89. package/dist/modules/execution/verifier.js +0 -222
  90. package/dist/modules/execution/windows-commands.js +0 -41
  91. package/dist/modules/hallucination/confidence.js +0 -66
  92. package/dist/modules/hallucination/consistency.js +0 -26
  93. package/dist/modules/hallucination/detector.js +0 -43
  94. package/dist/modules/hallucination/factual.js +0 -129
  95. package/dist/modules/hallucination/index.js +0 -5
  96. package/dist/modules/hallucination/js-identifiers.js +0 -262
  97. package/dist/modules/hallucination/llm-judge.js +0 -101
  98. package/dist/modules/index.js +0 -5
  99. package/dist/modules/indexer/cache.js +0 -40
  100. package/dist/modules/indexer/index.js +0 -3
  101. package/dist/modules/indexer/module.js +0 -245
  102. package/dist/modules/indexer/project-profile.js +0 -183
  103. package/dist/modules/indexer/walker.js +0 -101
  104. package/dist/modules/lsp/check-tool.js +0 -58
  105. package/dist/modules/lsp/client.js +0 -278
  106. package/dist/modules/lsp/command.js +0 -60
  107. package/dist/modules/lsp/config.js +0 -135
  108. package/dist/modules/lsp/index.js +0 -3
  109. package/dist/modules/lsp/module.js +0 -232
  110. package/dist/modules/lsp/probe.js +0 -76
  111. package/dist/modules/lsp/project-root.js +0 -32
  112. package/dist/modules/lsp/startup-check.js +0 -141
  113. package/dist/modules/lsp/types.js +0 -1
  114. package/dist/modules/mcp/client.js +0 -399
  115. package/dist/modules/mcp/index.js +0 -3
  116. package/dist/modules/mcp/module.js +0 -142
  117. package/dist/modules/mcp/registry.js +0 -15
  118. package/dist/modules/memory/index.js +0 -1
  119. package/dist/modules/memory/module.js +0 -96
  120. package/dist/modules/memory/search.js +0 -42
  121. package/dist/modules/memory/store.js +0 -69
  122. package/dist/modules/pipelines/engine.js +0 -60
  123. package/dist/modules/pipelines/index.js +0 -3
  124. package/dist/modules/pipelines/parser.js +0 -56
  125. package/dist/modules/pipelines/template.js +0 -14
  126. package/dist/modules/plugins/builtin/lint-on-write.js +0 -231
  127. package/dist/modules/plugins/builtin/notify.js +0 -9
  128. package/dist/modules/plugins/index.js +0 -1
  129. package/dist/modules/plugins/loader.js +0 -70
  130. package/dist/modules/plugins/manager.js +0 -217
  131. package/dist/modules/plugins/types.js +0 -1
  132. package/dist/modules/processes/detect.js +0 -34
  133. package/dist/modules/processes/index.js +0 -2
  134. package/dist/modules/processes/registry.js +0 -327
  135. package/dist/modules/processes/runner.js +0 -23
  136. package/dist/modules/registry.js +0 -47
  137. package/dist/modules/security/audit-log.js +0 -136
  138. package/dist/modules/security/audit-notifier.js +0 -292
  139. package/dist/modules/security/command-validator.js +0 -205
  140. package/dist/modules/security/content-scanner.js +0 -53
  141. package/dist/modules/security/data-sanitizer.js +0 -89
  142. package/dist/modules/security/encryption.js +0 -242
  143. package/dist/modules/security/index.js +0 -14
  144. package/dist/modules/security/network-validator.js +0 -71
  145. package/dist/modules/security/path-validator.js +0 -207
  146. package/dist/modules/security/rate-limiter.js +0 -119
  147. package/dist/modules/security/security-policies.js +0 -531
  148. package/dist/modules/security/session-encryption.js +0 -210
  149. package/dist/modules/security/session-isolation.js +0 -95
  150. package/dist/modules/session/index.js +0 -3
  151. package/dist/modules/session/manager.js +0 -172
  152. package/dist/modules/session/module.js +0 -24
  153. package/dist/modules/session/store.js +0 -222
  154. package/dist/modules/session/types.js +0 -1
  155. package/dist/modules/skills/index.js +0 -2
  156. package/dist/modules/skills/loader.js +0 -72
  157. package/dist/modules/skills/matcher.js +0 -27
  158. package/dist/modules/skills/module.js +0 -129
  159. package/dist/modules/types.js +0 -1
  160. package/dist/modules/updater/checker.js +0 -96
  161. package/dist/modules/updater/index.js +0 -2
  162. package/dist/modules/updater/module.js +0 -116
  163. package/dist/modules/user-profile/compressor.js +0 -16
  164. package/dist/modules/user-profile/index.js +0 -1
  165. package/dist/modules/user-profile/profile.js +0 -68
  166. package/dist/tools/approve.js +0 -32
  167. package/dist/tools/attach-image.js +0 -89
  168. package/dist/tools/bash.js +0 -496
  169. package/dist/tools/browser.js +0 -114
  170. package/dist/tools/chunk-query.js +0 -99
  171. package/dist/tools/create-dir.js +0 -55
  172. package/dist/tools/delete-file.js +0 -62
  173. package/dist/tools/download-file.js +0 -116
  174. package/dist/tools/edit-file.js +0 -79
  175. package/dist/tools/enable-tools.js +0 -58
  176. package/dist/tools/executor.js +0 -144
  177. package/dist/tools/file-info.js +0 -46
  178. package/dist/tools/filter-tools.js +0 -17
  179. package/dist/tools/glob-tool.js +0 -26
  180. package/dist/tools/grep-tool.js +0 -84
  181. package/dist/tools/hidden-tools-block.js +0 -37
  182. package/dist/tools/index.js +0 -78
  183. package/dist/tools/list-dir.js +0 -48
  184. package/dist/tools/load-skill.js +0 -42
  185. package/dist/tools/mcp-call.js +0 -68
  186. package/dist/tools/move-file.js +0 -85
  187. package/dist/tools/path-utils.js +0 -51
  188. package/dist/tools/pipeline-run.js +0 -144
  189. package/dist/tools/preview.js +0 -2
  190. package/dist/tools/process-kill.js +0 -29
  191. package/dist/tools/process-list.js +0 -36
  192. package/dist/tools/process-log.js +0 -45
  193. package/dist/tools/question.js +0 -140
  194. package/dist/tools/read-file.js +0 -91
  195. package/dist/tools/recall.js +0 -117
  196. package/dist/tools/registry.js +0 -47
  197. package/dist/tools/remember.js +0 -67
  198. package/dist/tools/scope-check.js +0 -30
  199. package/dist/tools/search-history.js +0 -84
  200. package/dist/tools/subagent.js +0 -196
  201. package/dist/tools/types.js +0 -1
  202. package/dist/tools/user-input.js +0 -123
  203. package/dist/tools/web-browse.js +0 -86
  204. package/dist/tools/web-fetch.js +0 -98
  205. package/dist/tools/web-search.js +0 -78
  206. package/dist/tools/write-file.js +0 -81
  207. package/dist/ui/box.js +0 -77
  208. package/dist/ui/colors.js +0 -4
  209. package/dist/ui/diff.js +0 -178
  210. package/dist/ui/index.js +0 -6
  211. package/dist/ui/line-editor.js +0 -703
  212. package/dist/ui/line-math.js +0 -69
  213. package/dist/ui/md-formatter.js +0 -212
  214. package/dist/ui/output.js +0 -13
  215. package/dist/ui/plan-view.js +0 -103
  216. package/dist/ui/renderer.js +0 -209
  217. package/dist/ui/spinner.js +0 -70
  218. package/dist/ui/table.js +0 -144
package/dist/cli/repl.js DELETED
@@ -1,616 +0,0 @@
1
- import * as readline from "readline";
2
- import { pc } from "../ui/colors";
3
- import { LineEditor } from "../ui/line-editor";
4
- import { existsSync, readFileSync, writeFileSync } from "fs";
5
- import { join, dirname } from "path";
6
- import { homedir } from "os";
7
- import { fileURLToPath } from "url";
8
- import { Completer, SlashCommandProvider, SessionNameProvider, SubcommandProvider, SkillNameProvider, } from "./completer";
9
- import { Renderer } from "../ui/renderer";
10
- import { box, divider } from "../ui/box";
11
- import stringWidth from "string-width";
12
- import { t } from "../i18n/index";
13
- import { registerAllCommands } from "./repl-commands";
14
- import { probeLspServers } from "../modules/lsp/probe";
15
- import { DEFAULT_LSP_CONFIG } from "../modules/lsp/config";
16
- import { readActivePlan, formatPlanChecklist, stepContextForTool } from "../ui/plan-view";
17
- function readVersion() {
18
- const here = dirname(fileURLToPath(import.meta.url));
19
- const candidates = [join(here, "..", "..", "package.json"), join(here, "..", "package.json")];
20
- for (const p of candidates) {
21
- if (existsSync(p)) {
22
- try {
23
- const raw = JSON.parse(readFileSync(p, "utf8"));
24
- if (raw.version)
25
- return raw.version;
26
- }
27
- catch {
28
- // Broken package.json — fall through to the next candidate
29
- }
30
- }
31
- }
32
- return "0.0.0";
33
- }
34
- const version = readVersion();
35
- function formatContextBar(used, limit, compactions, quality) {
36
- const pct = Math.min(100, Math.round((used / limit) * 100));
37
- const barLen = 20;
38
- const filled = Math.round((pct / 100) * barLen);
39
- const bar = pc.green("█".repeat(filled)) + pc.dim("░".repeat(barLen - filled));
40
- const pctStr = pct >= 75 ? pc.yellow(`${pct}%`) : pc.dim(`${pct}%`);
41
- let line = ` ${bar} ${pctStr} ${pc.dim(`(${used} / ${limit} tokens)`)}`;
42
- if (compactions !== undefined) {
43
- line += pc.dim(` compactions: ${compactions}`);
44
- }
45
- if (quality !== undefined) {
46
- const qColor = quality >= 70 ? pc.green : quality >= 40 ? pc.yellow : pc.red;
47
- line += ` ${qColor(`quality: ${quality}%`)}`;
48
- }
49
- return line;
50
- }
51
- export class Repl {
52
- completer = new Completer();
53
- running = false;
54
- agentRunning = false;
55
- inputLocked = false;
56
- historyPath;
57
- history = [];
58
- maxHistory = 1000;
59
- lastEscTime = 0;
60
- doubleEscDelay = 500;
61
- configDir;
62
- baseDir;
63
- noAgentsMd;
64
- pendingClipboardImage = null;
65
- exitOnClose = false;
66
- activePlan = null;
67
- lastPlanSig = "";
68
- rl;
69
- agent;
70
- config;
71
- sessionManager;
72
- skillsModule;
73
- pluginManager;
74
- logger;
75
- constructor(agent, config, sessionManager, skillsModule, pluginManager, configDir, baseDir, noAgentsMd, logger, exitOnClose) {
76
- this.agent = agent;
77
- this.config = config;
78
- this.exitOnClose = exitOnClose === true;
79
- this.sessionManager = sessionManager;
80
- this.skillsModule = skillsModule;
81
- this.pluginManager = pluginManager;
82
- this.logger = logger;
83
- this.configDir = configDir || join(homedir(), ".mma");
84
- this.baseDir = baseDir || process.cwd();
85
- this.noAgentsMd = noAgentsMd === true;
86
- this.historyPath = join(homedir(), ".mma", "repl-history");
87
- this.loadHistory();
88
- this.rl = process.stdin.isTTY
89
- ? new LineEditor({
90
- input: process.stdin,
91
- output: process.stdout,
92
- prompt: pc.cyan(t("repl.you")),
93
- history: this.history,
94
- historySize: this.maxHistory,
95
- completer: (line) => {
96
- const [matches, partial] = this.completer.complete(line);
97
- if (matches.length > 0)
98
- return [matches, partial];
99
- return [[], line];
100
- },
101
- })
102
- : readline.createInterface({
103
- input: process.stdin,
104
- output: process.stdout,
105
- prompt: pc.cyan(t("repl.you")),
106
- history: this.history,
107
- historySize: this.maxHistory,
108
- tabSize: 2,
109
- completer: (line) => {
110
- const [matches, partial] = this.completer.complete(line);
111
- if (matches.length > 0)
112
- return [matches, partial];
113
- return [[], line];
114
- },
115
- });
116
- registerAllCommands(this);
117
- this.setupCompleter();
118
- this.setupListeners();
119
- }
120
- loadHistory() {
121
- if (existsSync(this.historyPath)) {
122
- try {
123
- const raw = readFileSync(this.historyPath, "utf-8");
124
- this.history = raw.split("\n").filter(Boolean).slice(-this.maxHistory);
125
- }
126
- catch {
127
- this.history = [];
128
- }
129
- }
130
- }
131
- saveHistory() {
132
- const allHistory = this.history.slice(-this.maxHistory);
133
- writeFileSync(this.historyPath, allHistory.join("\n"), "utf-8");
134
- }
135
- setupCompleter() {
136
- const slashCommands = Array.from(this.commands.keys());
137
- this.completer.registerProvider(new SlashCommandProvider(slashCommands));
138
- if (this.sessionManager) {
139
- this.completer.registerProvider(new SessionNameProvider(() => this.sessionManager.list().map((s) => s.name)));
140
- }
141
- if (this.skillsModule) {
142
- this.completer.registerProvider(new SubcommandProvider("skill", ["list", "loaded", "load", "unload", "search"]));
143
- this.completer.registerProvider(new SkillNameProvider(this.skillsModule));
144
- }
145
- }
146
- setupListeners() {
147
- let multiLineBuffer = "";
148
- let inMultiLine = false;
149
- this.rl.on("line", async (line) => {
150
- const trimmed = line.trim();
151
- if (this.agentRunning || this.inputLocked) {
152
- if (trimmed) {
153
- this.history.push(trimmed);
154
- if (this.history.length > this.maxHistory) {
155
- this.history = this.history.slice(-this.maxHistory);
156
- }
157
- }
158
- return;
159
- }
160
- if (trimmed) {
161
- this.history.push(trimmed);
162
- if (this.history.length > this.maxHistory) {
163
- this.history = this.history.slice(-this.maxHistory);
164
- }
165
- }
166
- if (inMultiLine) {
167
- multiLineBuffer += "\n" + line;
168
- if (!this.isMultiLineInput(multiLineBuffer)) {
169
- inMultiLine = false;
170
- const fullInput = multiLineBuffer.trim();
171
- multiLineBuffer = "";
172
- if (fullInput) {
173
- if (fullInput.startsWith("/")) {
174
- await this.executeCommand(fullInput);
175
- }
176
- else {
177
- await this.runAgent(fullInput);
178
- }
179
- }
180
- if (this.running) {
181
- this.rl.setPrompt(pc.cyan(t("repl.you")));
182
- this.rl.prompt();
183
- }
184
- }
185
- else {
186
- this.rl.setPrompt(pc.cyan(t("repl.you") + "… "));
187
- this.rl.prompt();
188
- }
189
- return;
190
- }
191
- if (this.isMultiLineInput(trimmed)) {
192
- inMultiLine = true;
193
- multiLineBuffer = trimmed;
194
- this.rl.setPrompt(pc.cyan(t("repl.you") + "… "));
195
- this.rl.prompt();
196
- return;
197
- }
198
- if (!trimmed) {
199
- this.rl.prompt();
200
- return;
201
- }
202
- if (trimmed.startsWith("/")) {
203
- await this.executeCommand(trimmed);
204
- }
205
- else {
206
- await this.runAgent(trimmed);
207
- }
208
- if (this.running) {
209
- this.rl.prompt();
210
- }
211
- });
212
- this.rl.on("close", () => {
213
- this.running = false;
214
- this.saveHistory();
215
- this.agent.shutdown();
216
- if (this.exitOnClose)
217
- process.exit(0);
218
- });
219
- if (this.exitOnClose && !process.stdin.isTTY) {
220
- process.stdin.on("end", () => {
221
- this.running = false;
222
- this.saveHistory();
223
- this.agent.shutdown();
224
- process.exit(0);
225
- });
226
- }
227
- if (this.rl instanceof LineEditor) {
228
- this.rl.onKeyInput = (str, key) => this.handleSpecialKey(str, key);
229
- }
230
- let forceExitTimer = null;
231
- process.on("SIGINT", () => {
232
- if (this.agentRunning) {
233
- console.log(pc.yellow("\n[Ctrl+C] Остановка агента... (ещё раз — принудительно)"));
234
- this.agent.shutdown();
235
- this.agentRunning = false;
236
- if (forceExitTimer)
237
- clearTimeout(forceExitTimer);
238
- forceExitTimer = setTimeout(() => process.exit(1), 2000).unref();
239
- }
240
- else {
241
- process.exit(0);
242
- }
243
- });
244
- }
245
- handleSpecialKey(str, key) {
246
- if (key.name === "escape") {
247
- // Bun's keypress decoder collapses a fast double-Esc into a single
248
- // keypress whose `sequence` contains two ESC bytes ("\x1b\x1b").
249
- // Counting bytes (not events) catches both the collapsed case and
250
- // the case where two separate escape keypresses land in the window.
251
- const escBytes = key.sequence ? (key.sequence.match(/\x1b/g) || []).length : 1;
252
- const now = Date.now();
253
- const withinWindow = now - this.lastEscTime < this.doubleEscDelay;
254
- this.lastEscTime = now;
255
- if (escBytes >= 2 || withinWindow) {
256
- this.lastEscTime = 0;
257
- if (this.agentRunning) {
258
- process.stdout.write(pc.yellow(`\n${t("repl.interrupt")}\n`));
259
- this.agent.shutdown();
260
- }
261
- }
262
- return true;
263
- }
264
- if (key.ctrl && key.name === "v" && !this.agentRunning) {
265
- this.pasteClipboardImage();
266
- return true;
267
- }
268
- return false;
269
- }
270
- async pasteClipboardImage() {
271
- try {
272
- const { readClipboardImage, bufferToDataUrl } = await import("../llm/image-utils");
273
- const clipBuf = await readClipboardImage();
274
- if (clipBuf) {
275
- const { dataUrl } = await bufferToDataUrl(clipBuf);
276
- this.pendingClipboardImage = dataUrl;
277
- const sizeKb = Math.round((dataUrl.length * 3) / 4 / 1024);
278
- console.log(pc.green(`\n${t("image.attached", { source: "clipboard", size: `${sizeKb} KB` })}`));
279
- if (this.rl instanceof LineEditor)
280
- this.rl.reset();
281
- this.rl.prompt();
282
- }
283
- else {
284
- console.log(pc.yellow(`\n${t("image.clipboard_empty")}`));
285
- if (this.rl instanceof LineEditor)
286
- this.rl.reset();
287
- this.rl.prompt();
288
- }
289
- }
290
- catch {
291
- // clipboard read failed — ignore, let terminal paste text normally
292
- }
293
- }
294
- isMultiLineInput(line) {
295
- if (line.endsWith("\\"))
296
- return true;
297
- const openBraces = (line.match(/\{/g) || []).length;
298
- const closeBraces = (line.match(/\}/g) || []).length;
299
- if (openBraces > closeBraces)
300
- return true;
301
- return false;
302
- }
303
- async runAgent(input) {
304
- if (this.agentRunning)
305
- return;
306
- this.agentRunning = true;
307
- try {
308
- if (this.pendingClipboardImage) {
309
- const contextManager = this.agent.contextManager;
310
- if (contextManager) {
311
- contextManager.addPendingImage({
312
- type: "image_url",
313
- image_url: { url: this.pendingClipboardImage },
314
- });
315
- }
316
- this.pendingClipboardImage = null;
317
- }
318
- this.logger?.logREPL("user", input);
319
- if (this.rl instanceof LineEditor)
320
- this.rl.reset();
321
- // Overwrite the empty prompt that reset() just drew with a divider,
322
- // then label the agent's reply — separates the user's message from
323
- // the agent's answer.
324
- process.stdout.write("\r" + divider() + "\n" + pc.green(t("repl.agent")));
325
- const renderer = new Renderer({
326
- spinner: this.config.ui?.spinner ?? true,
327
- toolStyle: this.config.ui?.toolStyle ?? "inline",
328
- });
329
- this.refreshActivePlan(renderer);
330
- const result = await this.agent.run(input, (c) => renderer.text(c), (m) => renderer.meta(m), (ev) => {
331
- if (ev.type === "start") {
332
- renderer.toolStart(ev.tool, ev.args, stepContextForTool(this.activePlan, ev.tool, ev.args));
333
- }
334
- else {
335
- renderer.toolEnd(ev.tool, ev.duration ?? 0, ev.error, ev.ctxDelta);
336
- if (ev.tool === "plan" || ev.tool === "todo") {
337
- this.refreshActivePlan(renderer);
338
- }
339
- }
340
- }, (phase) => {
341
- if (phase === "thinking") {
342
- renderer.thinkingStart();
343
- }
344
- else {
345
- renderer.thinkingEnd();
346
- }
347
- });
348
- renderer.flush();
349
- process.stdout.write("\n");
350
- this.logger?.logREPL(result.success ? "assistant" : "system", result.text?.slice(0, 400) || result.error || "");
351
- if (!result.success) {
352
- console.error(pc.red(`${t("error.prefix")}${result.error}`));
353
- }
354
- this.showContextBar(result);
355
- // Close the agent's turn: a divider before the next prompt keeps
356
- // consecutive user/agent messages visually separated.
357
- process.stdout.write("\n" + divider() + "\n");
358
- }
359
- finally {
360
- this.agentRunning = false;
361
- }
362
- }
363
- /** Re-read the active plan from disk; print a live checklist when it changed. */
364
- refreshActivePlan(renderer) {
365
- const plan = readActivePlan(this.baseDir);
366
- const sig = plan ? JSON.stringify(plan.steps.map((s) => `${s.id}:${s.status}`)) : "";
367
- if (!plan) {
368
- this.activePlan = null;
369
- this.lastPlanSig = "";
370
- return;
371
- }
372
- this.activePlan = plan;
373
- if (sig !== this.lastPlanSig) {
374
- this.lastPlanSig = sig;
375
- renderer.planBlock(formatPlanChecklist(plan));
376
- }
377
- }
378
- commands = new Map();
379
- registerCommand(cmd) {
380
- this.commands.set(cmd.name, cmd);
381
- if (cmd.aliases) {
382
- for (const alias of cmd.aliases) {
383
- this.commands.set(alias, cmd);
384
- }
385
- }
386
- }
387
- async withExclusiveInput(fn) {
388
- this.inputLocked = true;
389
- try {
390
- await fn();
391
- }
392
- finally {
393
- this.inputLocked = false;
394
- }
395
- }
396
- async executeCommand(input) {
397
- const parts = input.split(/\s+/);
398
- const name = parts[0].slice(1);
399
- const args = parts.slice(1);
400
- const cmd = this.commands.get(name);
401
- if (!cmd) {
402
- console.log(pc.red(t("cli.unknown_cmd", { name })), t("cli.help_hint"));
403
- return;
404
- }
405
- try {
406
- await cmd.action(args);
407
- }
408
- catch (err) {
409
- console.error(pc.red(t("error.command_error", {
410
- message: err instanceof Error ? err.message : String(err),
411
- })));
412
- }
413
- }
414
- showHelp() {
415
- const { COMMAND_GROUPS } = require("./repl-commands");
416
- const order = ["general", "agent", "session", "skill"];
417
- const seen = new Set();
418
- for (const groupKey of order) {
419
- const cmds = [];
420
- for (const [name, cmd] of this.commands) {
421
- if (cmd.aliases?.includes(name))
422
- continue;
423
- if (seen.has(cmd.name))
424
- continue;
425
- const group = COMMAND_GROUPS[cmd.name] ?? "general";
426
- if (group !== groupKey)
427
- continue;
428
- seen.add(cmd.name);
429
- cmds.push(cmd);
430
- }
431
- if (cmds.length === 0)
432
- continue;
433
- console.log(pc.bold(t(`repl.group.${groupKey}`)));
434
- for (const cmd of cmds) {
435
- const aliases = cmd.aliases?.length ? ` (${pc.dim(cmd.aliases.join(", "))})` : "";
436
- console.log(` ${pc.cyan("/" + cmd.name)}${aliases} ${pc.dim(cmd.description)}`);
437
- if (cmd.usage) {
438
- console.log(` ${pc.dim(cmd.usage)}`);
439
- }
440
- }
441
- console.log();
442
- }
443
- }
444
- lastCompactionShown = 0;
445
- showContextBar(result) {
446
- if (result.contextUsed === undefined ||
447
- result.contextLimit === undefined ||
448
- result.contextLimit <= 0) {
449
- return;
450
- }
451
- const ui = this.config.ui;
452
- if (ui?.showContextStats) {
453
- console.log();
454
- const ctxLine = formatContextBar(result.contextUsed, result.contextLimit, result.compactionCount, result.contextQuality);
455
- console.log(ctxLine);
456
- if (result.totalTokens !== undefined && result.totalTokens > 0) {
457
- const apiLine = pc.dim(` API: ${result.promptTokens} prompt + ${result.completionTokens} completion = ${result.totalTokens} total`);
458
- console.log(apiLine);
459
- }
460
- }
461
- else if (ui?.showCompaction && result.compactionCount !== undefined) {
462
- if (result.compactionCount > this.lastCompactionShown) {
463
- this.lastCompactionShown = result.compactionCount;
464
- console.log(pc.dim(`\n ⟳ Context compacted (${result.compactionCount})`));
465
- }
466
- }
467
- }
468
- async start() {
469
- this.running = true;
470
- const info = [];
471
- const row = (label, value) => {
472
- info.push(` ${pc.yellow(label)} ${value}`);
473
- };
474
- const ctx = this.config.contextWindow;
475
- const sysBudget = Math.floor(ctx * this.config.contextBudget.systemPrompt);
476
- const resBudget = Math.floor(ctx * this.config.contextBudget.responseReserve);
477
- const histBudget = ctx - sysBudget - resBudget;
478
- row(t("repl.model"), pc.white(this.config.model));
479
- row(t("repl.provider"), `${this.config.provider.type} → ${pc.dim(this.config.provider.baseUrl)}`);
480
- row(t("repl.context"), `${pc.white(String(ctx))} ${pc.dim(`(sys:${sysBudget} res:${resBudget} hist:${histBudget})`)}`);
481
- const si = this.agent.getSystemPromptInfo();
482
- row(t("repl.sysprompt_label"), pc.dim(t("repl.sysprompt_size", { used: si.tokenCount, budget: sysBudget })));
483
- if (this.skillsModule) {
484
- const budget = this.skillsModule.getBudget();
485
- row(t("repl.skills_label"), `${pc.white(String(this.skillsModule.getAvailable().length))} available, ${pc.dim(`budget: ${budget.total} tokens`)}`);
486
- }
487
- if (this.pluginManager) {
488
- const infos = this.pluginManager.getPluginInfos().filter(({ plugin }) => !plugin.isBuiltin);
489
- if (infos.length > 0) {
490
- const pluginNames = infos
491
- .map(({ plugin, source }) => {
492
- const version = plugin.version ? `${pc.dim(plugin.version)}` : "";
493
- const origin = source ? pc.dim(` [${source}]`) : "";
494
- return `${plugin.name}${version}${origin}`;
495
- })
496
- .join(", ");
497
- row(t("repl.plugins_label"), `${pc.white(String(infos.length))} active ${pc.dim(`(${pluginNames})`)}`);
498
- }
499
- }
500
- const mcpServers = this.config.mcpServers || {};
501
- const enabledServers = Object.entries(mcpServers).filter(([, s]) => s.enabled !== false);
502
- if (enabledServers.length > 0) {
503
- const names = enabledServers.map(([name]) => name).join(", ");
504
- row(t("repl.mcp_label"), `${pc.white(String(enabledServers.length))} ${pc.dim(`(${names})`)}`);
505
- }
506
- const cwd = process.cwd();
507
- row(t("repl.work_dir"), pc.dim(cwd));
508
- if (this.noAgentsMd) {
509
- row(t("repl.agents_label"), pc.red(t("repl.disabled")));
510
- }
511
- else {
512
- const agentsMdCandidates = [
513
- join(this.baseDir, "AGENTS.md"),
514
- join(this.baseDir, ".mma", "AGENTS.md"),
515
- join(this.configDir, "AGENTS.md"),
516
- ];
517
- const foundAgents = agentsMdCandidates.filter((p) => existsSync(p));
518
- if (foundAgents.length > 0) {
519
- for (const p of foundAgents) {
520
- row(t("repl.agents_label"), pc.dim(p));
521
- }
522
- }
523
- else {
524
- row(t("repl.agents_label"), pc.dim(t("repl.not_found")));
525
- }
526
- }
527
- const meta = this.sessionManager?.getActiveMeta();
528
- if (meta) {
529
- const sessionPath = join(this.configDir, "sessions", meta.id);
530
- row(t("repl.session_label"), `${pc.cyan(meta.name)} ${pc.dim(`(${meta.id.slice(0, 12)})`)} — ${meta.messageCount} msgs ${pc.dim(sessionPath)}`);
531
- }
532
- const headerWidth = Math.max(50, Math.min(96, process.stdout.columns || 96));
533
- // LSP status is probed in the background — it must never block the banner.
534
- const isTty = process.stdout.isTTY === true;
535
- const lspEnabled = isTty && (this.config.lsp ?? DEFAULT_LSP_CONFIG).enabled !== false;
536
- if (lspEnabled) {
537
- row(t("repl.lsp_label"), pc.dim("…"));
538
- }
539
- const boxLines = box(info, {
540
- title: t("repl.title", { version }),
541
- width: headerWidth,
542
- });
543
- for (const line of boxLines) {
544
- console.log(line);
545
- }
546
- console.log();
547
- this.rl.prompt();
548
- if (lspEnabled) {
549
- this.probeLspBanner()
550
- .then((lspSummary) => {
551
- if (lspSummary)
552
- this.updateLspRow(boxLines.length, headerWidth, lspSummary);
553
- })
554
- .catch(() => { });
555
- }
556
- }
557
- /**
558
- * Replace the LSP banner row (rendered as "…") in place once the probe
559
- * finishes. The LSP row is the last data row of the box, so it sits exactly
560
- * two terminal rows above the prompt line — that offset is stable no matter
561
- * how earlier rows wrap. Skipped (placeholder stays) when a rewrite would
562
- * corrupt the screen: the agent is already running, the terminal is not a
563
- * TTY, a box line wrapped, or the summary is too wide for a single row.
564
- */
565
- updateLspRow(boxLineCount, headerWidth, summary) {
566
- if (this.agentRunning || !process.stdout.isTTY)
567
- return;
568
- if ((process.stdout.columns ?? 96) < headerWidth)
569
- return;
570
- const inner = headerWidth - 4;
571
- // Match box()'s wrapText normalization (leading space stripped, runs of
572
- // whitespace collapsed) so the rewritten row is byte-identical to what
573
- // box() would render for the same text.
574
- const rowText = `${pc.yellow(t("repl.lsp_label"))} ${summary.replace(/\s+/g, " ").trim()}`;
575
- if (stringWidth(rowText) > inner)
576
- return;
577
- const padded = rowText + " ".repeat(Math.max(0, inner - stringWidth(rowText)));
578
- const line = pc.dim("│") + " " + padded + " " + pc.dim("│");
579
- // From the prompt row (boxLineCount) up 2 to the LSP row (last data row,
580
- // directly above the bottom border), clear it, write the new row, and
581
- // return the cursor to the prompt row. The editor re-positions itself on
582
- // the next keystroke, so any typed input is preserved.
583
- process.stdout.write(`\x1b[2A\r\x1b[2K${line}\x1b[2B\r`);
584
- }
585
- /**
586
- * Probe the LSP servers applicable to the current project and format a
587
- * one-line banner summary, e.g. "✓ typescript (1.2s)" or "✗ css — timeout".
588
- * Returns null when LSP is disabled or no server applies.
589
- */
590
- async probeLspBanner() {
591
- const config = this.config.lsp ?? DEFAULT_LSP_CONFIG;
592
- try {
593
- const summary = await probeLspServers(config, this.baseDir);
594
- if (summary.noneApplicable)
595
- return null;
596
- const parts = [];
597
- for (const r of summary.ok) {
598
- parts.push(pc.green(`✓ ${r.language}${pc.dim(` (${(r.durationMs / 1000).toFixed(1)}s)`)}`));
599
- }
600
- for (const r of summary.failed) {
601
- const reason = r.error?.includes("timeout") ? t("repl.lsp_timeout") : t("repl.lsp_failed");
602
- parts.push(pc.red(`✗ ${r.language}${pc.dim(` — ${reason}`)}`));
603
- }
604
- return parts.join(" ");
605
- }
606
- catch {
607
- return pc.yellow(t("repl.lsp_unknown"));
608
- }
609
- }
610
- stop() {
611
- this.running = false;
612
- this.saveHistory();
613
- this.agent.shutdown();
614
- this.rl.close();
615
- }
616
- }
@@ -1,22 +0,0 @@
1
- import { t } from "../i18n/index";
2
- import { pc } from "../ui/colors";
3
- /**
4
- * Render a single-run AgentResult to the terminal (non-JSON mode) and return
5
- * the process exit code.
6
- *
7
- * On failure only the error is printed. The model's `text` (which is the last
8
- * *accepted* message, i.e. possibly stale after an audit/hallucination error)
9
- * was already streamed live during the run — re-printing it here misleadingly
10
- * suggests the task succeeded.
11
- */
12
- export function printRunResult(result, flush) {
13
- flush();
14
- if (result.success) {
15
- if (!result.text) {
16
- console.log(pc.yellow(t("cli.no_output")));
17
- }
18
- return 0;
19
- }
20
- console.error(`${t("error.prefix")}${result.error}`);
21
- return 1;
22
- }