micro-models-agent 2.11.0 → 2.12.0

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 (347) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/assets/js/tabs.js +22 -3
  3. package/dist/cli/cache-line.js +1 -0
  4. package/dist/cli/command-suggest.js +5 -4
  5. package/dist/cli/commands.js +231 -122
  6. package/dist/cli/completer.js +132 -31
  7. package/dist/cli/index.js +1 -0
  8. package/dist/cli/json-payload.js +4 -4
  9. package/dist/cli/main.js +166 -61
  10. package/dist/cli/onboarding-commands.js +126 -0
  11. package/dist/cli/plugin-commands.js +2 -1
  12. package/dist/cli/relaunch.js +16 -13
  13. package/dist/cli/repl-commands-lsp.js +75 -0
  14. package/dist/cli/repl-commands-skills.js +105 -0
  15. package/dist/cli/repl-commands.js +589 -266
  16. package/dist/cli/repl.js +436 -177
  17. package/dist/cli/run-result.js +5 -6
  18. package/dist/cli/security-commands.js +37 -28
  19. package/dist/cli/setup-order.js +4 -55
  20. package/dist/cli/setup-prompt.js +3 -2
  21. package/dist/cli/setup.js +27 -107
  22. package/dist/cli/web-command.js +98 -0
  23. package/dist/config/budget.js +5 -5
  24. package/dist/config/config.js +103 -96
  25. package/dist/config/defaults.js +38 -8
  26. package/dist/config/domains.js +24 -27
  27. package/dist/config/env.js +46 -0
  28. package/dist/config/experts.js +2 -0
  29. package/dist/config/index.js +1 -0
  30. package/dist/config/paths.js +56 -0
  31. package/dist/config/redact.js +44 -0
  32. package/dist/config/registry-extra.js +334 -0
  33. package/dist/config/registry.js +584 -0
  34. package/dist/config/security.js +35 -36
  35. package/dist/config/timeouts.js +74 -0
  36. package/dist/config/utils.js +16 -15
  37. package/dist/core/agent/artifact-progress.js +59 -0
  38. package/dist/core/agent/artifact-resolve.js +79 -0
  39. package/dist/core/agent/audit-gate.js +7 -3
  40. package/dist/core/agent/compaction.js +2 -2
  41. package/dist/core/agent/constants.js +33 -4
  42. package/dist/core/agent/context-log.js +454 -0
  43. package/dist/core/agent/context-renderer.js +5 -0
  44. package/dist/core/agent/critic-gate.js +132 -0
  45. package/dist/core/agent/hallucination-gate.js +148 -38
  46. package/dist/core/agent/loop-state.js +15 -0
  47. package/dist/core/agent/prefix-monitor.js +1 -1
  48. package/dist/core/agent/reasoning-resolver.js +10 -1
  49. package/dist/core/agent/token-tracker.js +7 -4
  50. package/dist/core/agent/tool-batch.js +93 -18
  51. package/dist/core/agent/tool-images.js +18 -0
  52. package/dist/core/agent/tool-output.js +65 -11
  53. package/dist/core/agent/tool-pairing.js +60 -0
  54. package/dist/core/agent-moe.js +25 -24
  55. package/dist/core/agent.js +429 -108
  56. package/dist/core/bootstrap/agent-phase.js +66 -0
  57. package/dist/core/bootstrap/config-phase.js +86 -0
  58. package/dist/core/bootstrap/modules-phase.js +269 -0
  59. package/dist/core/bootstrap/provider-phase.js +183 -0
  60. package/dist/core/bootstrap/session-phase.js +204 -0
  61. package/dist/core/bootstrap/state.js +94 -0
  62. package/dist/core/bootstrap/workspace-phase.js +115 -0
  63. package/dist/core/bootstrap.js +92 -660
  64. package/dist/core/crash-handler.js +17 -7
  65. package/dist/core/environment.js +37 -12
  66. package/dist/core/host-plan.js +43 -0
  67. package/dist/core/host.js +23 -0
  68. package/dist/core/index.js +1 -0
  69. package/dist/core/prompt-builder.js +17 -1
  70. package/dist/core/prompt-overflow.js +42 -43
  71. package/dist/core/session-logger.js +122 -30
  72. package/dist/core/system-prompt.js +117 -0
  73. package/dist/core/version.js +6 -4
  74. package/dist/core/web-host.js +34 -0
  75. package/dist/core/workspace.js +19 -15
  76. package/dist/i18n/index.js +37 -3
  77. package/dist/index.js +7 -3
  78. package/dist/llm/image-utils.js +55 -64
  79. package/dist/llm/llm-errors.js +9 -0
  80. package/dist/llm/model-loader.js +10 -32
  81. package/dist/llm/models-dev.js +121 -0
  82. package/dist/llm/openai-compat.js +146 -73
  83. package/dist/llm/orchestrator.js +33 -11
  84. package/dist/llm/provider-budget.js +2 -2
  85. package/dist/llm/provider-context.js +233 -0
  86. package/dist/llm/provider.js +1 -1
  87. package/dist/llm/response.js +5 -0
  88. package/dist/llm/token-counter.js +27 -11
  89. package/dist/logger/app-logger.js +48 -22
  90. package/dist/logger/file-log.js +28 -19
  91. package/dist/logger/index.js +1 -0
  92. package/dist/main.js +273 -47
  93. package/dist/migration/backup.js +14 -3
  94. package/dist/migration/detect.js +12 -3
  95. package/dist/migration/index.js +1 -0
  96. package/dist/modules/artifacts/store.js +9 -8
  97. package/dist/modules/browser/actions.js +6 -0
  98. package/dist/modules/browser/bridge-client.js +14 -12
  99. package/dist/modules/browser/bridge-path.js +4 -4
  100. package/dist/modules/browser/console-buffer.js +37 -0
  101. package/dist/modules/browser/cookie-store.js +5 -0
  102. package/dist/modules/browser/driver-types.js +1 -0
  103. package/dist/modules/browser/driver.js +19 -11
  104. package/dist/modules/browser/index.js +3 -1
  105. package/dist/modules/browser/module.js +2 -1
  106. package/dist/modules/browser/session.js +10 -30
  107. package/dist/modules/browser/snapshot.js +19 -13
  108. package/dist/modules/browser/types.js +1 -0
  109. package/dist/modules/certification/cli.js +28 -20
  110. package/dist/modules/certification/fact-checker.js +9 -1
  111. package/dist/modules/certification/loader.js +9 -2
  112. package/dist/modules/certification/manifest.js +83 -21
  113. package/dist/modules/certification/runner.js +23 -13
  114. package/dist/modules/certification/scenarios.js +20 -20
  115. package/dist/modules/certification/syntax-scenarios.js +1 -2
  116. package/dist/modules/context/chunk-query.js +11 -9
  117. package/dist/modules/context/fact-extractor.js +37 -39
  118. package/dist/modules/context/index.js +1 -0
  119. package/dist/modules/context/manager.js +106 -80
  120. package/dist/modules/critic/client.js +176 -0
  121. package/dist/modules/critic/evidence.js +81 -0
  122. package/dist/modules/critic/provider.js +45 -0
  123. package/dist/modules/critic/tools.js +78 -0
  124. package/dist/modules/critic/types.js +1 -0
  125. package/dist/modules/execution/audit-runners.js +28 -34
  126. package/dist/modules/execution/auditor.js +53 -49
  127. package/dist/modules/execution/execution-plugin.js +142 -102
  128. package/dist/modules/execution/index.js +1 -1
  129. package/dist/modules/execution/input-from.js +37 -13
  130. package/dist/modules/execution/module.js +368 -191
  131. package/dist/modules/execution/moe-executor.js +53 -26
  132. package/dist/modules/execution/plan-actions.js +320 -202
  133. package/dist/modules/execution/plan-checks.js +35 -0
  134. package/dist/modules/execution/plan-coverage.js +36 -33
  135. package/dist/modules/execution/plan-steps.js +11 -3
  136. package/dist/modules/execution/plan-store.js +83 -17
  137. package/dist/modules/execution/plan-tool.js +89 -35
  138. package/dist/modules/execution/plan-validator.js +30 -10
  139. package/dist/modules/execution/planner.js +22 -13
  140. package/dist/modules/execution/stuck-detector.js +196 -93
  141. package/dist/modules/execution/tracker.js +22 -8
  142. package/dist/modules/execution/verifier.js +69 -48
  143. package/dist/modules/execution/windows-commands.js +12 -12
  144. package/dist/modules/hallucination/artifact-claim.js +93 -0
  145. package/dist/modules/hallucination/confidence.js +13 -11
  146. package/dist/modules/hallucination/consistency.js +10 -2
  147. package/dist/modules/hallucination/detector.js +10 -5
  148. package/dist/modules/hallucination/factual.js +43 -26
  149. package/dist/modules/hallucination/index.js +1 -0
  150. package/dist/modules/hallucination/js-identifiers.js +44 -45
  151. package/dist/modules/hallucination/llm-judge.js +17 -12
  152. package/dist/modules/hallucination/success-claim.js +59 -0
  153. package/dist/modules/indexer/cache.js +52 -4
  154. package/dist/modules/indexer/index.js +1 -0
  155. package/dist/modules/indexer/map-command.js +2 -4
  156. package/dist/modules/indexer/map-select.js +16 -16
  157. package/dist/modules/indexer/module.js +47 -12
  158. package/dist/modules/indexer/project-profile.js +8 -7
  159. package/dist/modules/indexer/symbols.js +15 -15
  160. package/dist/modules/indexer/walker.js +159 -29
  161. package/dist/modules/lsp/check-tool.js +7 -5
  162. package/dist/modules/lsp/client.js +39 -39
  163. package/dist/modules/lsp/command.js +17 -24
  164. package/dist/modules/lsp/config.js +12 -11
  165. package/dist/modules/lsp/index.js +1 -0
  166. package/dist/modules/lsp/module.js +48 -46
  167. package/dist/modules/lsp/probe.js +13 -14
  168. package/dist/modules/lsp/project-root.js +14 -17
  169. package/dist/modules/lsp/startup-check.js +18 -16
  170. package/dist/modules/mcp/client.js +59 -62
  171. package/dist/modules/mcp/index.js +1 -0
  172. package/dist/modules/mcp/module.js +66 -37
  173. package/dist/modules/mcp/registry.js +5 -0
  174. package/dist/modules/memory/index.js +1 -0
  175. package/dist/modules/memory/module.js +12 -8
  176. package/dist/modules/memory/search.js +4 -1
  177. package/dist/modules/memory/store.js +40 -2
  178. package/dist/modules/onboarding/init.js +47 -0
  179. package/dist/modules/onboarding/meet.js +30 -0
  180. package/dist/modules/onboarding/mode.js +30 -0
  181. package/dist/modules/onboarding/prompts.js +43 -0
  182. package/dist/modules/pipelines/engine.js +10 -0
  183. package/dist/modules/pipelines/index.js +1 -0
  184. package/dist/modules/pipelines/parser.js +4 -1
  185. package/dist/modules/pipelines/template.js +4 -0
  186. package/dist/modules/plugins/builtin/lint-on-write.js +80 -67
  187. package/dist/modules/plugins/builtin/notify.js +2 -0
  188. package/dist/modules/plugins/index.js +1 -0
  189. package/dist/modules/plugins/loader.js +18 -3
  190. package/dist/modules/plugins/manager.js +37 -17
  191. package/dist/modules/pricing/index.js +10 -11
  192. package/dist/modules/pricing/prices.js +12 -12
  193. package/dist/modules/processes/index.js +1 -0
  194. package/dist/modules/processes/kill-tree.js +27 -31
  195. package/dist/modules/processes/registry.js +44 -25
  196. package/dist/modules/processes/runner.js +4 -4
  197. package/dist/modules/providers/capabilities.js +28 -0
  198. package/dist/modules/providers/create.js +3 -4
  199. package/dist/modules/providers/factory.js +7 -7
  200. package/dist/modules/providers/fallback.js +12 -12
  201. package/dist/modules/providers/health.js +4 -4
  202. package/dist/modules/providers/manager.js +50 -19
  203. package/dist/modules/providers/naming.js +15 -0
  204. package/dist/modules/providers/preflight.js +71 -0
  205. package/dist/modules/providers/presets.js +39 -8
  206. package/dist/modules/providers/registry.js +7 -2
  207. package/dist/modules/reasoning/policy.js +8 -6
  208. package/dist/modules/reasoning/probe.js +30 -25
  209. package/dist/modules/security/audit-log.js +19 -36
  210. package/dist/modules/security/audit-notifier.js +35 -75
  211. package/dist/modules/security/command-validator.js +99 -51
  212. package/dist/modules/security/content-scanner.js +8 -8
  213. package/dist/modules/security/data-sanitizer.js +9 -16
  214. package/dist/modules/security/encryption.js +32 -52
  215. package/dist/modules/security/index.js +2 -1
  216. package/dist/modules/security/network-validator.js +120 -43
  217. package/dist/modules/security/path-validator.js +61 -46
  218. package/dist/modules/security/protected-paths.js +73 -0
  219. package/dist/modules/security/rate-limiter.js +17 -49
  220. package/dist/modules/security/security-policies.js +25 -57
  221. package/dist/modules/security/session-encryption.js +32 -71
  222. package/dist/modules/security/session-isolation.js +15 -28
  223. package/dist/modules/session/auto-name.js +63 -0
  224. package/dist/modules/session/export.js +98 -0
  225. package/dist/modules/session/index.js +1 -0
  226. package/dist/modules/session/manager.js +79 -28
  227. package/dist/modules/session/module.js +4 -3
  228. package/dist/modules/session/store.js +57 -20
  229. package/dist/modules/setup/answers.js +35 -0
  230. package/dist/modules/setup/apply.js +79 -0
  231. package/dist/modules/setup/discovery.js +72 -0
  232. package/dist/modules/skills/index.js +1 -0
  233. package/dist/modules/skills/loader.js +9 -1
  234. package/dist/modules/skills/module.js +11 -0
  235. package/dist/modules/updater/changelog-reader.js +15 -16
  236. package/dist/modules/updater/checker.js +9 -4
  237. package/dist/modules/updater/dev-detect.js +7 -6
  238. package/dist/modules/updater/index.js +1 -0
  239. package/dist/modules/updater/module.js +17 -15
  240. package/dist/modules/user-profile/compressor.js +2 -0
  241. package/dist/modules/user-profile/index.js +1 -0
  242. package/dist/modules/user-profile/profile.js +10 -1
  243. package/dist/modules/webui/answer-api.js +29 -0
  244. package/dist/modules/webui/assets.js +50 -0
  245. package/dist/modules/webui/body.js +21 -0
  246. package/dist/modules/webui/commands-settings.js +209 -0
  247. package/dist/modules/webui/commands-shared.js +60 -0
  248. package/dist/modules/webui/commands.js +174 -0
  249. package/dist/modules/webui/config-api.js +134 -0
  250. package/dist/modules/webui/file-api.js +202 -0
  251. package/dist/modules/webui/forward.js +159 -0
  252. package/dist/modules/webui/history-api.js +112 -0
  253. package/dist/modules/webui/host-state.js +60 -0
  254. package/dist/modules/webui/i18n-api.js +9 -0
  255. package/dist/modules/webui/limits.js +6 -0
  256. package/dist/modules/webui/log-forward.js +20 -0
  257. package/dist/modules/webui/memory-commands.js +64 -0
  258. package/dist/modules/webui/model-cache.js +18 -0
  259. package/dist/modules/webui/module.js +148 -0
  260. package/dist/modules/webui/persist.js +24 -0
  261. package/dist/modules/webui/prompt-io.js +97 -0
  262. package/dist/modules/webui/providers-api.js +337 -0
  263. package/dist/modules/webui/providers-view.js +56 -0
  264. package/dist/modules/webui/reasoning-view.js +15 -0
  265. package/dist/modules/webui/run-agent.js +81 -0
  266. package/dist/modules/webui/server.js +284 -0
  267. package/dist/modules/webui/sessions-api.js +178 -0
  268. package/dist/modules/webui/settings-api.js +561 -0
  269. package/dist/modules/webui/setup-api.js +201 -0
  270. package/dist/modules/webui/state.js +74 -0
  271. package/dist/modules/webui/util.js +261 -0
  272. package/dist/output/bus.js +7 -2
  273. package/dist/output/channel.js +80 -28
  274. package/dist/output/format.js +2 -1
  275. package/dist/output/index.js +1 -0
  276. package/dist/output/json-sink.js +5 -3
  277. package/dist/output/machine.js +4 -3
  278. package/dist/output/session-sink.js +4 -4
  279. package/dist/tools/approve.js +4 -0
  280. package/dist/tools/attach-image.js +5 -4
  281. package/dist/tools/auto-fixer.js +26 -44
  282. package/dist/tools/auto-tags.js +83 -0
  283. package/dist/tools/bash.js +193 -116
  284. package/dist/tools/browser.js +76 -31
  285. package/dist/tools/chunk-query.js +14 -6
  286. package/dist/tools/create-dir.js +9 -5
  287. package/dist/tools/delete-file.js +9 -5
  288. package/dist/tools/download-file.js +32 -7
  289. package/dist/tools/edit-file.js +52 -14
  290. package/dist/tools/enable-tools.js +6 -6
  291. package/dist/tools/executor.js +132 -27
  292. package/dist/tools/file-info.js +3 -1
  293. package/dist/tools/filter-tools.js +3 -3
  294. package/dist/tools/glob-tool.js +4 -1
  295. package/dist/tools/grep-tool.js +13 -10
  296. package/dist/tools/hidden-tools-block.js +6 -6
  297. package/dist/tools/index.js +16 -8
  298. package/dist/tools/list-dir.js +4 -2
  299. package/dist/tools/load-skill.js +7 -0
  300. package/dist/tools/mcp-call.js +15 -4
  301. package/dist/tools/meet-done.js +14 -0
  302. package/dist/tools/move-file.js +14 -7
  303. package/dist/tools/path-utils.js +29 -29
  304. package/dist/tools/pipeline-run.js +29 -7
  305. package/dist/tools/preview.js +1 -1
  306. package/dist/tools/process-ids.js +31 -0
  307. package/dist/tools/process-kill.js +9 -16
  308. package/dist/tools/process-list.js +1 -0
  309. package/dist/tools/process-log.js +11 -16
  310. package/dist/tools/process-wait.js +63 -0
  311. package/dist/tools/prompt-io.js +4 -3
  312. package/dist/tools/question.js +172 -25
  313. package/dist/tools/read-file.js +55 -34
  314. package/dist/tools/recall.js +14 -8
  315. package/dist/tools/registry.js +6 -5
  316. package/dist/tools/remember.js +8 -4
  317. package/dist/tools/scope-request.js +11 -6
  318. package/dist/tools/search-history.js +5 -2
  319. package/dist/tools/session-info.js +2 -0
  320. package/dist/tools/set-thinking.js +8 -4
  321. package/dist/tools/subagent.js +59 -39
  322. package/dist/tools/syntax-validator.js +292 -90
  323. package/dist/tools/user-input.js +22 -18
  324. package/dist/tools/web-browse.js +9 -3
  325. package/dist/tools/web-fetch.js +12 -23
  326. package/dist/tools/web-search.js +7 -5
  327. package/dist/tools/write-file.js +45 -15
  328. package/dist/ui/action-log.js +13 -0
  329. package/dist/ui/box.js +4 -3
  330. package/dist/ui/colors.js +2 -0
  331. package/dist/ui/diff.js +6 -5
  332. package/dist/ui/index.js +1 -0
  333. package/dist/ui/line-editor.js +230 -122
  334. package/dist/ui/line-math.js +10 -2
  335. package/dist/ui/md-formatter.js +57 -37
  336. package/dist/ui/output.js +8 -3
  337. package/dist/ui/plan-view.js +21 -10
  338. package/dist/ui/renderer.js +393 -67
  339. package/dist/ui/spinner.js +16 -5
  340. package/dist/ui/table.js +15 -17
  341. package/dist/ui/theme.js +143 -0
  342. package/dist/utils/child-run.js +20 -0
  343. package/dist/utils/error.js +1 -1
  344. package/dist/utils/index.js +2 -0
  345. package/dist/utils/retry.js +2 -2
  346. package/dist/utils/truncate.js +1 -1
  347. package/package.json +1 -1
@@ -1,680 +1,112 @@
1
- import { loadConfig } from "../config/config";
2
- import { Logger } from "../logger/app-logger";
3
- import { buildActiveProvider } from "../modules/providers/factory";
4
- import { BUILTIN_PROVIDERS } from "../modules/providers/presets";
5
- import { ModelLoader } from "../llm/model-loader";
6
- import { ToolRegistry, registerAllTools } from "../tools/index";
7
- import { buildHiddenToolsBlock } from "../tools/hidden-tools-block";
8
- import { ToolExecutor } from "../tools/executor";
9
- import { ModuleRegistry } from "../modules/registry";
10
- import { PluginManager } from "../modules/plugins/manager";
11
- import { PluginLoader } from "../modules/plugins/loader";
12
- import { plugin as lintOnWritePlugin } from "../modules/plugins/builtin/lint-on-write";
13
- import { plugin as notifyPlugin } from "../modules/plugins/builtin/notify";
14
- import { ContextManager } from "../modules/context/manager";
15
- import { TokenCounter, estimateTokens } from "../llm/token-counter";
16
- import { HallucinationDetector } from "../modules/hallucination/detector";
17
- import { ExecutionModule } from "../modules/execution/module";
18
- import { SessionStore, SessionManager, SessionModule } from "../modules/session/index";
19
- import { UserProfile } from "../modules/user-profile/profile";
20
- import { SkillsLoader, SkillsModule } from "../modules/skills/index";
21
- import { BrowserModule } from "../modules/browser/index";
22
- import { LspModule, FileOnlyLogger, DEFAULT_LSP_CONFIG } from "../modules/lsp/index";
23
- import { runStartupHealthCheck } from "../modules/lsp/startup-check";
24
- import { IndexerModule } from "../modules/indexer/index";
25
- import { MCPModule } from "../modules/mcp/index";
26
- import { MemoryModule } from "../modules/memory/module";
27
- import { MemoryStore } from "../modules/memory/store";
28
- import { t, setLocale } from "../i18n/index";
29
- import { Agent } from "./agent";
30
- import { homedir } from "os";
31
- import { join, resolve } from "path";
32
- import { existsSync, readFileSync } from "fs";
33
- import { readMmaVersion } from "./version";
34
- import { collectEnvironment, logEnvironment } from "./environment";
35
- import { dryRunOverflow, overflowHint } from "./prompt-overflow";
36
- import { getLoadedContextLength } from "../llm/model-loader";
1
+ import { initConfigPhase } from "./bootstrap/config-phase";
2
+ import { setupProviderPhase } from "./bootstrap/provider-phase";
3
+ import { setupWorkspacePhase } from "./bootstrap/workspace-phase";
4
+ import { setupSessionPhase } from "./bootstrap/session-phase";
5
+ import { setupModulesPhase } from "./bootstrap/modules-phase";
6
+ import { assembleAgent } from "./bootstrap/agent-phase";
7
+ // Публичные экспорты 1:1 (сигнатуры и поведение не меняются) — потребители
8
+ // (cli/main, web-command, тесты) продолжают импортить из "../core/bootstrap".
9
+ export { applyReasoningCliOverride } from "./bootstrap/config-phase";
10
+ export { applyProbedContext } from "./bootstrap/provider-phase";
11
+ export { resolveBaseDir } from "./bootstrap/workspace-phase";
12
+ export { agentsMdPaths, setOneShotMode } from "./bootstrap/state";
13
+ export { buildSystemInfo } from "./system-prompt";
37
14
  /**
38
- * CLI --reasoning переопределяет конфигурационный режим
39
- * (приоритет: CLI > config > default). "auto" пропускается — полагаемся
40
- * на конфиг. Строка CLI приводится к типизированному ReasoningLevel.
15
+ * Собирает всё для работы агента: конфиг, окружение, провайдер, пробы,
16
+ * тулы, модули, Agent. Тяжёлые старты (health-check, пробы) — фоном.
17
+ * Тонкий оркестратор: каждая фаза — в `src/core/bootstrap/*.ts`.
18
+ * @param configDir каталог конфига; @param projectDir workspace;
19
+ * @param noAgentsMd пропустить AGENTS.md; @param exitOnComplete стоп на первом ответе;
20
+ * @param reasoningLevel CLI-override reasoning; @param contextLog git-лог контекста.
21
+ * @returns агент и окружение.
41
22
  */
42
- export function applyReasoningCliOverride(config, reasoningLevel) {
43
- if (!reasoningLevel || reasoningLevel === "auto")
44
- return;
45
- if (!config.reasoning) {
46
- config.reasoning = {
47
- mode: reasoningLevel,
48
- min: "low",
49
- max: "high",
50
- overrideCooldown: 3,
51
- };
52
- }
53
- else {
54
- config.reasoning.mode = reasoningLevel;
55
- }
56
- }
57
- /** Регистрация встроенного плагина модуля: пометка + регистрация. */
58
- function registerBuiltinPlugin(pm, plugin) {
59
- if (!plugin)
60
- return;
61
- plugin.isBuiltin = true;
62
- pm.register(plugin);
63
- }
64
- /**
65
- * Загрузка AGENTS.md из базового каталога проекта и конфиг-каталога
66
- * (в порядке приоритета). Каждый найденный непустой файл — prompt-блок
67
- * высокого приоритета.
68
- */
69
- function loadAgentsMdBlocks(baseDir, dir, skip) {
70
- if (skip)
71
- return [];
72
- const blocks = [];
73
- const candidates = [
74
- join(baseDir, "AGENTS.md"),
75
- join(baseDir, ".mma", "AGENTS.md"),
76
- join(dir, "AGENTS.md"),
77
- ];
78
- for (const p of candidates) {
79
- if (existsSync(p)) {
80
- const content = readFileSync(p, "utf-8").trim();
81
- if (content) {
82
- blocks.push({
83
- content,
84
- priority: "high",
85
- essential: false,
86
- estimatedTokens: estimateTokens(content),
87
- kind: "instructions",
88
- });
89
- }
90
- }
91
- }
92
- return blocks;
93
- }
94
- /** Reject `promise` after `ms`; the winner's timer is cleared. */
95
- function withTimeout(promise, ms) {
96
- return new Promise((resolve, reject) => {
97
- const timer = setTimeout(() => reject(new Error(`timeout after ${ms}ms`)), ms);
98
- promise.then((v) => {
99
- clearTimeout(timer);
100
- resolve(v);
101
- }, (e) => {
102
- clearTimeout(timer);
103
- reject(e);
104
- });
105
- });
106
- }
107
- export function buildSystemInfo(config, baseDir, profileCompressed) {
108
- const now = new Date().toISOString().replace("T", " ").slice(0, 19);
109
- const isWin = profileCompressed.toLowerCase().includes("win32");
110
- const lines = [
111
- `You are MMA v2, an AI coding agent for small models (${config.model}). Date: ${now}. Workspace: ${baseDir}. ${profileCompressed}.`,
112
- `Reply in the user's language. Use tools for file ops (read/write/edit/delete), search (glob/grep), shell (bash), web, subagents, browser, MCP. Explain briefly if not obvious. On tool failure: analyze, fix the call, retry up to 2x with different approaches, then ask the user.`,
113
- `Design: YAGNI (no unneeded code), KISS (simple over clever), DRY (reuse existing utilities).`,
114
- `SCOPE DISCIPLINE: do ONLY what the user explicitly asked — no extra features, files, refactors, "improvements", or fixes beyond the request. Read-only requests ("расскажи", "покажи", "объясни", "check") mean READ-ONLY: inspect and answer, never create/modify/delete anything. If the task is ambiguous (what to create, where, which variant) or the request implies action on something you could not find — STOP and ask the user a short clarifying question in plain text instead of guessing.`,
115
- `INPUT PRIORITY: the current user message outranks stored memory/preferences/facts. Never override, reinterpret, or "correct" an explicit value the user states now (city, path, name, language, choice) because a stored preference disagrees — follow the user's current message. If they truly conflict or look like a typo, ask the user instead of assuming.`,
116
- `NOT FOUND ≠ MISSING PROJECT: a "not found" tool result means the PATH was wrong (typo, different location), not that the project does not exist. Before creating or scaffolding ANY project/files: first run list_dir on the working directory to see what is already there; if a user-named path is not found, list its parent directory to locate the real path. NEVER create a new project when the user asked about an existing one — inspect first, create only after confirming the workspace is empty AND the user asked for creation.`,
117
- ];
118
- if (isWin) {
119
- lines.push(`Windows (PowerShell): use list_dir/read_file/delete_file/create_dir tools instead of dir/type/del/mkdir. No PowerShell cmdlets (Get-Content, Select-Object, Write-Output), no head/tail/grep/cat. Use forward slashes in paths. CWD: ${baseDir}`);
120
- }
121
- // MMA is a Bun-only project (package.json scripts, Bun API in code) — the
122
- // model should prefer bun over node/tsx/ts-node for running TypeScript
123
- // files and tests (observed: model wasted 10+ iterations installing tsx
124
- // instead of running `bun file.ts`).
125
- lines.push(`Runtime: Bun is available — run TypeScript directly with "bun <file.ts>" and tests with "bun test" (no tsx/ts-node/npm install needed for that).`);
126
- lines.push(`Bash: use "workdir" param instead of "cd dir && cmd". One command per call. Long-running processes: pass "background: true" (id immediately), otherwise auto-backgrounded after a few seconds — check with process_log.`, `DEVELOPMENT RULES (strict): 1) install deps BEFORE writing source (npm/pip/cargo, verify lockfile exists; never import uninstalled packages); 2) framework/toolkit init BEFORE app code; 3) follow plan sequentially, after each step verify deliverables exist with real content, then "plan update step=N status=done"; 4) verify work on disk + command output — don't assume success; 5) no premature work (no files/imports for future steps); 6) stuck after 2+ failures: STOP, try a different approach, write files directly, ask the user.`, `VERIFY EVERY WRITE: after write_file or edit_file, if the tool result contains NO [LSP errors], [LSP warnings], [Syntax check failed], or [Project typecheck failed] feedback, call the "lsp_check" tool on the file you just wrote BEFORE marking the step done. Never assume a written file is valid — prove it.`, `PLAN QUALITY: each step = CONCRETE deliverables (exact file paths with extensions, exact packages, exact commands). Vague steps ("Setup the project") forbidden. Cover init → deps → framework → code → verification. 5-8 steps.`, `For "check/fix errors" tasks, each verification step must name the exact command that proves the errors are gone — "bun run build", "bun test", or the "lsp_check" tool — and the step is done only after that check reports clean.`);
127
- if (config.autoPlan) {
128
- lines.push(`Plan rule (MANDATORY): any task creating files, installing packages, or requiring multiple actions MUST create a plan with the "plan" tool BEFORE starting. Each step = a concrete deliverable.`);
129
- }
130
- // When a bug is described in terms of runtime behavior (what happens when
131
- // the app runs), the fix is only provable by REPRODUCING it — running the
132
- // app/build/browser and comparing against actual output. The model decides
133
- // when this applies (no keyword classification). Stale dev servers started
134
- // before a config/deps change keep the OLD pipeline in memory and still
135
- // throw the original error (observed: old vite on 5173-5176 kept failing
136
- // postcss after the fix was on disk, while a fresh server on 5177 was
137
- // clean) — the fix is only real when the USER's running server is clean.
138
- lines.push(`Runtime verification: when a bug is described in terms of runtime behavior (what happens when the app runs), reproduce it — run the app / build / browser tool — and confirm the fix against actual runtime output before calling "plan update step=N status=done". Check existing servers first with process_list/process_log: a stale dev server started BEFORE your change still runs the old pipeline and keeps failing even after the files on disk are fixed. Restart or kill it (process_kill) and verify the exact endpoint/port the user reported — a fresh server on a new port does NOT prove the user's error is gone.`);
139
- // Security rules: when security is enabled the model should know the
140
- // restrictions up front — a blocked call costs an iteration, while this
141
- // block costs ~100 tokens once. Kept compact and capped so a long user
142
- // blacklist cannot blow the system budget.
143
- const sec = config.security;
144
- if (sec?.enabled) {
145
- const secLines = [`SECURITY RESTRICTIONS (enforced — blocked calls return "[SECURITY BLOCKED]", do not retry them):`];
146
- if (sec.bash?.enabled && sec.bash.blacklist.length > 0) {
147
- const cmds = sec.bash.blacklist.slice(0, 15).join(", ");
148
- secLines.push(`Forbidden bash commands: ${cmds}${sec.bash.blacklist.length > 15 ? ", …" : ""}.`);
149
- if (sec.bash.whitelist.length > 0) {
150
- secLines.push(`Only whitelisted bash commands are allowed: ${sec.bash.whitelist.slice(0, 15).join(", ")}.`);
151
- }
152
- if (sec.bash.blockDangerousFlags) {
153
- secLines.push(`Pipes/redirects/chaining (| > >> ; &&) in bash are blocked — one plain command per call.`);
154
- }
155
- }
156
- if (sec.paths?.enabled && sec.paths.denied.length > 0) {
157
- const paths = sec.paths.denied.slice(0, 10).join(", ");
158
- secLines.push(`Denied paths (read/write): ${paths}${sec.paths.denied.length > 10 ? ", …" : ""}.`);
159
- }
160
- if (sec.network?.enabled && sec.network.deniedDomains.length > 0) {
161
- const domains = sec.network.deniedDomains.slice(0, 10).join(", ");
162
- secLines.push(`Denied network domains: ${domains}${sec.network.deniedDomains.length > 10 ? ", …" : ""}.`);
163
- }
164
- if (secLines.length > 1) {
165
- lines.push(...secLines);
166
- }
167
- }
168
- const hasMCP = config.mcpServers && Object.values(config.mcpServers).some((s) => s.enabled !== false);
169
- if (hasMCP) {
170
- lines.push(`MCP servers are available — use the named MCP tools (prefixed mcp__) to query external services.`);
171
- }
172
- return lines.join("\n");
173
- }
174
- /**
175
- * One-shot CLI subcommands (`session show`, `usage`, `config` …) paint a result
176
- * and exit. The background startup health check spawns a child (LSP server /
177
- * tsc) that `process.exit` does not reap — on Windows the orphan keeps the
178
- * stdout pipe open, so piping the command (`mma session show <id> | cat`)
179
- * hangs. Subcommands never run an agent, so the check is skipped there.
180
- */
181
- let oneShotMode = false;
182
- export function setOneShotMode(value) {
183
- oneShotMode = value;
184
- }
185
- export async function bootstrap(configDir, projectDir, noAgentsMd, exitOnComplete, reasoningLevel) {
186
- const dir = configDir || process.env.MMA_CONFIG_DIR || join(homedir(), ".mma");
187
- const projectConfigPath = projectDir ? join(projectDir, ".mmrc") : join(process.cwd(), ".mmrc");
188
- const { config, legacyDetected } = loadConfig({ configDir: dir, projectConfigPath });
189
- setLocale(config.locale);
190
- // CLI --reasoning overrides config mode (priority: CLI > config > default)
191
- applyReasoningCliOverride(config, reasoningLevel);
192
- // Update global audit notifier with config
193
- try {
194
- const { globalAuditNotifier } = await import("../modules/security/audit-notifier");
195
- if (config.security?.auditNotifier) {
196
- globalAuditNotifier.updateConfig(config.security.auditNotifier);
197
- }
198
- }
199
- catch {
200
- // Ignore if audit notifier is not available
201
- }
202
- const logger = new Logger(config.logLevel);
203
- logger.setLogDir(join(dir, "logs"));
204
- logger.debug("MMA bootstrap", {
205
- version: config.version,
206
- model: config.model,
207
- });
208
- // Sync the manifest bundled with this package version into
209
- // ~/.mma/certifications.json (bundled entries overwrite their keys on
210
- // update; user-local certifications are preserved). Best-effort, silent.
211
- try {
212
- const { syncGlobalManifest } = await import("../modules/certification/manifest");
213
- const syncResult = syncGlobalManifest();
214
- if (syncResult.synced) {
215
- logger.debug("Certification manifest synced from package");
216
- }
217
- }
218
- catch {
219
- // Certification marks are cosmetic — never block startup.
220
- }
221
- if (config.modelLoad.autoLoad) {
222
- const modelLoader = new ModelLoader(config.provider.baseUrl, logger);
223
- const loadResult = await modelLoader.ensureModelLoaded({
224
- model: config.model,
225
- contextLength: config.contextWindow,
226
- flashAttention: config.modelLoad.flashAttention,
227
- offloadKvCacheToGpu: config.modelLoad.offloadKvCacheToGpu,
228
- autoLoad: config.modelLoad.autoLoad,
229
- });
230
- if (!loadResult.success) {
231
- logger.warn(t("env.model_autoload_failed", { error: String(loadResult.error ?? "") }));
232
- }
233
- else if (loadResult.alreadyLoaded) {
234
- logger.debug(`Model ${config.model} already loaded`);
235
- }
236
- else {
237
- logger.info(t("env.model_loaded", { model: config.model, seconds: String(loadResult.loadTime) }));
238
- }
239
- }
240
- // Context probe (background): ask the provider (LM Studio native API) for
241
- // the context length the model is ACTUALLY loaded with and compare it with
242
- // the configured contextWindow. Never blocks the banner; null = probe not
243
- // applicable (not LM Studio / model not loaded / transient error).
244
- const contextProbePromise = (async () => {
245
- try {
246
- const probe = await getLoadedContextLength(config.provider.baseUrl, config.model);
247
- if (!probe)
248
- return null;
249
- if (probe.actual < config.contextWindow) {
250
- logger.logSilent("warn", `Context probe: model "${probe.model}" is loaded with ${probe.actual} tokens, but contextWindow is configured as ${config.contextWindow} — overflow/429 risk. Lower contextWindow or reload the model with a larger context.`);
251
- }
252
- else if (probe.actual > config.contextWindow) {
253
- logger.logSilent("info", `Context probe: model "${probe.model}" supports ${probe.actual} tokens — consider "mma context ${probe.actual}" to use the full window.`);
254
- }
255
- else {
256
- logger.logSilent("debug", `Context probe: configured contextWindow matches loaded context (${probe.actual})`);
257
- }
258
- return probe;
259
- }
260
- catch {
261
- return null;
262
- }
263
- })();
264
- const profile = new UserProfile(join(dir));
265
- profile.load() || profile.collect();
266
- profile.save();
267
- // Multi-provider manager (Phase 2) + optional transparent failover wrapper
268
- // (Phase 4.2). Built through the shared factory so a hot-swap via
269
- // Agent.setProvider gets the SAME fallback behavior as startup instead of
270
- // rebuilding a bare manager that silently drops failover (B4).
271
- //
272
- // Session id is resolved lazily: the session manager is created further down,
273
- // and providers must read the CURRENT session at request time (hot-swap,
274
- // session switch). OpenCode Go rejects requests without `x-opencode-session`.
275
- let activeSessionManager;
276
- const getSessionId = () => activeSessionManager?.getActiveMeta()?.id;
277
- const llmProvider = buildActiveProvider(config, logger, { getSessionId }).provider;
278
- // Resolve reasoning strategy from provider preset + probe
279
- const providerSpec = BUILTIN_PROVIDERS.find((p) => p.type === config.provider.type);
280
- const reasoningStrategy = providerSpec?.capabilities.reasoningStrategy ?? "none";
281
- // Reasoning probe runs in the BACKGROUND (B2). It used to block bootstrap
282
- // with an extra LLM round-trip on every launch; the agent now consumes it
283
- // lazily before the first LLM call (same pattern as the startup health
284
- // check) and treats the mechanism as NOT passed until it resolves. The 24h
285
- // TTL disk cache in probe.ts already avoids re-probing a stable backend.
286
- let reasoningProbePromise = Promise.resolve(false);
287
- if (config.reasoning && config.reasoning.mode !== "none" && reasoningStrategy !== "none") {
288
- reasoningProbePromise = (async () => {
289
- try {
290
- const { probeReasoningSupport, getCachedProbeResult, setCachedProbeResult } = await import("../modules/reasoning/probe");
291
- const cacheK = `${config.provider.baseUrl ?? ""}|${config.model}`;
292
- const cached = getCachedProbeResult(cacheK);
293
- const passed = cached !== undefined ? cached : await probeReasoningSupport(llmProvider, reasoningStrategy);
294
- // Only cache a definitive result — a transient probe error (null) must
295
- // NOT pin "reasoning not supported" for the 24h TTL.
296
- if (cached === undefined && passed !== null)
297
- setCachedProbeResult(cacheK, passed);
298
- logger.logSilent("info", t("env.reasoning_probe", {
299
- strategy: reasoningStrategy,
300
- result: passed === true ? t("env.reasoning_respected") : t("env.reasoning_ignored"),
301
- }));
302
- // null (transient error) falls back to "not passed" for this session.
303
- return passed === true;
304
- }
305
- catch {
306
- return false;
307
- }
308
- })();
309
- }
310
- const baseDir = projectDir ? resolve(projectDir) : process.cwd();
311
- // Cross-device diagnosis: log a full environment report (OS, runtime,
312
- // engines, PATH tools, provider/retry, playwright) at every startup.
313
- const envReport = collectEnvironment({
314
- configDir: dir,
315
- baseDir,
23
+ export async function bootstrap(configDir, projectDir, noAgentsMd, exitOnComplete, reasoningLevel, contextLog) {
24
+ // Фаза 1: пути, конфиг, локаль, логгер.
25
+ const { dir, config, legacyDetected, logger } = await initConfigPhase(configDir, projectDir, reasoningLevel);
26
+ // Фаза 2: провайдер, автозагрузка модели, фоновые пробы, профиль.
27
+ const provider = await setupProviderPhase(config, logger, dir);
28
+ // Фаза 3: workspace, окружение, индекс, скиллы, реестр тулов, system-блок.
29
+ const workspace = await setupWorkspacePhase(config, logger, dir, projectDir, provider.profile);
30
+ // Фаза 4: сессии, context-лог, менеджер контекста, живой toolCtx.
31
+ const session = await setupSessionPhase({
316
32
  config,
317
- scanTools: process.env.NODE_ENV !== "test",
318
- });
319
- logEnvironment(envReport, logger);
320
- for (const warning of envReport.warnings) {
321
- logger.warn(warning);
322
- }
323
- const projectMapCacheDir = join(baseDir, ".mma");
324
- const indexerModule = new IndexerModule({
325
- baseDir,
326
- cacheDir: projectMapCacheDir,
327
- });
328
- try {
329
- // Build (or load from cache) the project index. On a large workspace the
330
- // first walk can pause startup with no other output — announce both ends
331
- // so the silence is explained.
332
- logger.info(t("env.indexing"));
333
- const index = await indexerModule.buildIndex();
334
- if (index) {
335
- logger.info(t("env.indexed", { files: String(index.files.length) }));
336
- }
337
- else {
338
- logger.warn(t("env.indexing_failed", { error: "no index produced" }));
339
- }
340
- }
341
- catch (err) {
342
- logger.warn(t("env.indexing_failed", { error: String(err?.message ?? err) }));
343
- }
344
- const skillsLoader = new SkillsLoader();
345
- const builtinDir = join(import.meta.dirname, "skills", "builtin");
346
- const globalDir = join(homedir(), ".agents", "skills");
347
- const projectSkillsDir = join(baseDir, ".mma", "skills");
348
- const availableSkills = skillsLoader.loadFromAllSources(builtinDir, globalDir, projectSkillsDir);
349
- const skillsBudget = Math.floor(config.contextWindow * config.skills.budget);
350
- const skillsModule = new SkillsModule(availableSkills, skillsBudget);
351
- const toolRegistry = new ToolRegistry();
352
- registerAllTools(toolRegistry, skillsModule, {
353
- enableOnDemand: config.tools?.enableOnDemand,
354
- });
355
- const pluginManager = new PluginManager();
356
- const systemInfoContent = buildSystemInfo(config, baseDir, profile.compress());
357
- const systemInfoPrompt = {
358
- content: systemInfoContent,
359
- priority: "critical",
360
- essential: true,
361
- estimatedTokens: estimateTokens(systemInfoContent),
362
- };
363
- const sessionDir = join(dir, "sessions");
364
- const sessionStore = new SessionStore(sessionDir);
365
- sessionStore.init();
366
- const sessionManager = new SessionManager(sessionStore, {
367
- model: config.model,
368
- contextWindow: config.contextWindow,
369
- projectDir: baseDir,
370
- maxSessions: config.session.maxSessions,
371
- isolation: config.sessionIsolation,
372
- });
373
- activeSessionManager = sessionManager;
374
- if (config.session.autoSave && !sessionManager.getActive()) {
375
- sessionManager.create();
376
- }
377
- const tokenCounter = new TokenCounter(config.model);
378
- // Mutable set of active tool tags, shared between the agent loop and the
379
- // `enable_tools` tool. The loop re-reads it every iteration to recompute the
380
- // LLM-visible tool set; enable_tools pushes tags into it. When on-demand
381
- // enabling is disabled the tag set stays empty, which restores the legacy
382
- // all-tools behavior (getAllForLLM returns everything for empty tags).
383
- const enableOnDemand = config.tools?.enableOnDemand !== false;
384
- const activeToolTags = enableOnDemand
385
- ? config.tools?.defaultTags
386
- ? [...config.tools.defaultTags]
387
- : []
388
- : [];
389
- const contextManager = new ContextManager(config.contextWindow, config.contextBudget, tokenCounter);
390
- // Shared box for the LIVE config. `Agent.reconfigure` replaces deps.config
391
- // AND this box, so anything that captured the reference at bootstrap —
392
- // toolCtx.config, security validators, tool rules — keeps seeing the CURRENT
393
- // settings after /model use or the wizard. Pinning the value once meant
394
- // tools enforced the pre-reconfigure security/maxTool settings all session.
395
- const configRef = { current: config };
396
- const toolCtx = {
397
- baseDir,
398
33
  logger,
34
+ dir,
35
+ baseDir: workspace.baseDir,
399
36
  exitOnComplete,
400
- contextManager,
401
- activeToolTags,
402
- recursionDepth: 0,
403
- fileOperationsCount: 0,
404
- sessionHistory: {
405
- append: async (type, content) => {
406
- const meta = sessionManager.getActiveMeta();
407
- if (!meta)
408
- return;
409
- sessionManager.appendMessage({
410
- role: "tool",
411
- content: typeof content === "string" ? content : JSON.stringify(content),
412
- name: type,
413
- timestamp: new Date().toISOString(),
414
- });
415
- },
416
- },
417
- sessionLog: {
418
- plan: (event, detail, iteration) => {
419
- sessionManager.appendLog({
420
- ts: new Date().toISOString(),
421
- type: "plan",
422
- tool: event,
423
- content: detail,
424
- ...(iteration !== undefined ? { iteration } : {}),
425
- });
426
- },
427
- },
428
- };
429
- // `config` is exposed as a LIVE getter over the shared configRef so tools
430
- // and security validators see the CURRENT settings after a reconfigure.
431
- Object.defineProperty(toolCtx, "config", {
432
- get: () => configRef.current,
433
- configurable: true,
434
- });
435
- // `sessionId`/`sessionContext` are exposed as LIVE getters over the session
436
- // manager instead of being captured once at bootstrap. Capturing the values
437
- // pinned them to the session active at startup, so after a REPL /new or
438
- // /resume the new session's audit.jsonl entries were tagged with the
439
- // PREVIOUS session's id (observed: ses_msyghz8w audit entries carrying
440
- // ses_msyg892p_78kqhc) while sessionHistory kept reading the live meta.
441
- // Everything that consumes ctx.sessionId — audit log, process registry,
442
- // file-ops counters — now always sees the session that is actually active.
443
- Object.defineProperty(toolCtx, "sessionId", {
444
- get: () => sessionManager.getActiveMeta()?.id,
445
- configurable: true,
446
- });
447
- Object.defineProperty(toolCtx, "sessionContext", {
448
- get: () => sessionManager.getSessionContext() ?? undefined,
449
- configurable: true,
450
- });
451
- Object.defineProperty(toolCtx, "sessionManager", {
452
- get: () => sessionManager,
453
- configurable: true,
37
+ contextLogFlag: contextLog,
38
+ contextProbePromise: provider.contextProbePromise,
39
+ capabilitiesRef: provider.capabilitiesRef,
40
+ llmProvider: provider.llmProvider,
41
+ bindSessionManager: provider.bindSessionManager,
42
+ toolRegistry: workspace.toolRegistry,
43
+ pluginManager: workspace.pluginManager,
454
44
  });
455
- const toolExecutor = new ToolExecutor(toolRegistry, toolCtx, pluginManager);
456
- toolCtx.llmProvider = llmProvider;
457
- toolCtx.toolExecutor = toolExecutor;
458
- const hallucinationDetector = new HallucinationDetector(baseDir, llmProvider, {
459
- judgeEnabled: config.hallucination?.judge?.enabled ?? false,
460
- });
461
- const moduleRegistry = new ModuleRegistry();
462
- const execModule = new ExecutionModule(baseDir, config.stuckThreshold, config.errorWebSearch?.threshold ?? 5);
463
- // A plan in .mma/plans/active.json is PROJECT state, not session state —
464
- // restore it in every session so `plan show` works and the checklist is
465
- // visible. Nothing is printed unprompted: the REPL renders the checklist
466
- // only on plan/todo tool events.
467
- execModule.restorePlan();
468
- moduleRegistry.register(execModule);
469
- execModule.setHallucinationDetector(hallucinationDetector);
470
- const sessionModule = new SessionModule(sessionManager);
471
- moduleRegistry.register(sessionModule);
472
- moduleRegistry.register(indexerModule);
473
- const mcpModule = new MCPModule(config);
474
- try {
475
- // Bound the MCP init so one slow/hung MCP server can't block boot forever
476
- // (B5): on timeout, log-and-continue — MCP tools appear late or not at all
477
- // instead of stalling startup.
478
- await withTimeout(mcpModule.initialize(), 10_000);
479
- }
480
- catch (err) {
481
- logger.warn(`MCP init failed or timed out (${err instanceof Error ? err.message.slice(0, 120) : String(err)}) — continuing without MCP tools.`);
482
- }
483
- moduleRegistry.register(mcpModule);
484
- const memoryStore = new MemoryStore(join(dir, "memory"));
485
- const memoryModule = new MemoryModule(memoryStore);
486
- moduleRegistry.register(memoryModule);
487
- if (config.browser.enabled) {
488
- const browserModule = new BrowserModule();
489
- moduleRegistry.register(browserModule);
490
- registerBuiltinPlugin(pluginManager, browserModule.getPlugin());
491
- }
492
- const lspLogger = new FileOnlyLogger(logger);
493
- const lspModule = new LspModule(config.lsp, undefined, lspLogger);
494
- moduleRegistry.register(lspModule);
495
- registerBuiltinPlugin(pluginManager, lspModule.getPlugin());
496
- // Startup health check: scan project for existing errors so the model
497
- // knows the baseline before it starts working. Skip for one-shot runs and
498
- // test environments. Started in the background (never awaited) so the REPL
499
- // banner is not blocked by `npx tsc` on the whole project; the Agent awaits
500
- // it before the first LLM call via `lazyPromptBlocks` (already resolved by
501
- // the time the user types in the interactive REPL).
502
- let startupCheckBlock = null;
503
- const startupCheckPromise = !oneShotMode && !exitOnComplete && process.env.NODE_ENV !== "test"
504
- ? runStartupHealthCheck(config.lsp ?? DEFAULT_LSP_CONFIG, baseDir, { logger: lspLogger })
505
- : Promise.resolve(null);
506
- const moduleTools = moduleRegistry.collectToolDefinitions();
507
- for (const tool of moduleTools) {
508
- toolRegistry.register(tool);
509
- }
510
- const plugin = execModule.getPlugin();
511
- registerBuiltinPlugin(pluginManager, plugin);
512
- registerBuiltinPlugin(pluginManager, sessionModule.getPlugin());
513
- registerBuiltinPlugin(pluginManager, skillsModule.getPlugin());
514
- registerBuiltinPlugin(pluginManager, indexerModule.getPlugin());
515
- registerBuiltinPlugin(pluginManager, mcpModule.getPlugin());
516
- pluginManager.register(lintOnWritePlugin);
517
- pluginManager.register(notifyPlugin);
518
- const pluginLoader = new PluginLoader();
519
- const globalPluginsDir = join(homedir(), ".mma", "plugins");
520
- const projectPluginsDir = join(baseDir, ".mma", "plugins");
521
- const mmaVersion = readMmaVersion();
522
- pluginLoader.loadFromDir(globalPluginsDir, pluginManager, logger, {
523
- source: "global",
524
- mmaVersion,
525
- });
526
- pluginLoader.loadFromDir(projectPluginsDir, pluginManager, logger, {
527
- source: "project",
528
- mmaVersion,
45
+ // Фаза 5: модули, плагины, промпт-блоки, dry-run переполнения.
46
+ const modules = await setupModulesPhase({
47
+ config,
48
+ logger,
49
+ dir,
50
+ baseDir: workspace.baseDir,
51
+ noAgentsMd,
52
+ exitOnComplete,
53
+ toolRegistry: workspace.toolRegistry,
54
+ pluginManager: workspace.pluginManager,
55
+ skillsModule: workspace.skillsModule,
56
+ indexerModule: workspace.indexerModule,
57
+ sessionManager: session.sessionManager,
58
+ contextManager: session.contextManager,
59
+ toolCtx: session.toolCtx,
60
+ activeToolTags: session.activeToolTags,
61
+ hallucinationDetector: session.hallucinationDetector,
62
+ systemInfoPrompt: workspace.systemInfoPrompt,
529
63
  });
530
- contextManager.onCompact = (summary) => {
531
- const meta = sessionManager.getActiveMeta();
532
- if (!meta || !config.session.autoSave)
533
- return;
534
- sessionManager.appendMessage({
535
- role: summary.role,
536
- content: summary.content,
537
- name: summary.name,
538
- timestamp: new Date().toISOString(),
539
- });
540
- };
541
- // Carry the active plan (id, progress, current step) into the compaction
542
- // summary so a 9B model doesn't re-create the plan from scratch right after
543
- // compaction (observed: ses_msvuao0h — plan_e07pb2 (1/6) discarded for a
544
- // fresh plan_xzq9xe the same iteration the old plan was still visible).
545
- contextManager.setPlanSummaryProvider(() => execModule.getPlanSummary());
546
- const agentsMdBlocks = loadAgentsMdBlocks(baseDir, dir, noAgentsMd === true);
547
- const promptBlocks = [systemInfoPrompt,
548
- ...moduleRegistry.collectPromptBlocks(["indexer", "session"]),
549
- ...agentsMdBlocks,
550
- // Static plan reminder: always present so the model knows to check for an
551
- // active plan before creating a new one (even on the first iteration before
552
- // the <system-summary> envelope appears).
553
- {
554
- content: "[Plan Reminder] An active plan may exist for this session. Before creating a new plan, check with `plan show`. If a plan is active, continue it — do NOT create a new plan.",
555
- priority: "high",
556
- essential: false,
557
- estimatedTokens: 50,
558
- },
559
- ];
560
- // Startup overflow warning (banner, A3): dry-run the system-prompt budget
561
- // with the same block set the Agent's first build will use (static + skills
562
- // + project map + hidden tools) and surface instructions/project-map blocks
563
- // that will not fit. The Agent compresses them before the first LLM call;
564
- // this warning tells the USER why and how to get the full text included.
565
- {
566
- const dynamicBlocks = [];
567
- const skillsBlock = skillsModule.getSystemPromptBlock();
568
- if (skillsBlock)
569
- dynamicBlocks.push(skillsBlock);
570
- const mapBlock = indexerModule.getSystemPromptBlock();
571
- if (mapBlock)
572
- dynamicBlocks.push(mapBlock);
573
- const hiddenToolsBlock = buildHiddenToolsBlock(toolRegistry.getAll(), activeToolTags);
574
- if (hiddenToolsBlock) {
575
- dynamicBlocks.push({
576
- content: hiddenToolsBlock,
577
- priority: "low",
578
- essential: false,
579
- estimatedTokens: estimateTokens(hiddenToolsBlock),
580
- });
581
- }
582
- const systemBudget = Math.floor(config.contextWindow * config.contextBudget.systemPrompt);
583
- const dry = dryRunOverflow([...promptBlocks, ...dynamicBlocks], systemBudget);
584
- if (dry.overflow.length > 0) {
585
- const overflowTokens = dry.overflow.reduce((s, b) => s + b.estimatedTokens, 0);
586
- const needed = dry.includedTokens + overflowTokens;
587
- const hint = overflowHint(config, dir, needed);
588
- for (const b of dry.overflow) {
589
- logger.warn(t("prompt.overflow.startup", {
590
- block: b.kind === "instructions" ? "AGENTS.md" : "project map",
591
- original: String(b.estimatedTokens),
592
- needed: String(needed),
593
- budget: String(systemBudget),
594
- hint,
595
- }));
596
- }
597
- }
598
- }
599
- const agentDeps = {
64
+ // Фаза 6: AgentDeps, late-apply пробы, set_thinking.
65
+ const agent = await assembleAgent({
600
66
  config,
601
- configRef,
602
- llmProvider,
603
- toolExecutor,
604
- pluginManager,
605
- contextManager,
606
- hallucinationDetector,
67
+ configRef: session.configRef,
68
+ llmProvider: provider.llmProvider,
69
+ providerManager: provider.providerManager,
70
+ toolExecutor: session.toolExecutor,
71
+ pluginManager: workspace.pluginManager,
72
+ contextManager: session.contextManager,
73
+ hallucinationDetector: session.hallucinationDetector,
607
74
  logger,
608
- baseDir,
75
+ baseDir: workspace.baseDir,
609
76
  configDir: dir,
610
- toolTags: activeToolTags,
611
- promptBlocks,
612
- envReport,
613
- getDynamicPromptBlocks: () => {
614
- const blocks = [];
615
- // Plan block removed: it mutates every iteration (step status changes),
616
- // invalidating the local KV-cache. The plan status is now injected into
617
- // the <system-summary> envelope after each tool batch instead.
618
- const skillsBlock = skillsModule.getSystemPromptBlock();
619
- if (skillsBlock)
620
- blocks.push(skillsBlock);
621
- // Session metadata (id/name/model/context) is collected here, not at
622
- // bootstrap: the session is created during bootstrap with messageCount 0,
623
- // so a static collect would always yield null. Content is stable per
624
- // session (no per-turn fields) to preserve prefix KV-cache.
625
- const sessionBlock = sessionModule.getSystemPromptBlock();
626
- if (sessionBlock)
627
- blocks.push(sessionBlock);
628
- const mapBlock = indexerModule.getSystemPromptBlock();
629
- if (mapBlock)
630
- blocks.push(mapBlock);
631
- const hiddenToolsBlock = buildHiddenToolsBlock(toolRegistry.getAll(), activeToolTags);
632
- if (hiddenToolsBlock) {
633
- blocks.push({
634
- content: hiddenToolsBlock,
635
- priority: "low",
636
- essential: false,
637
- estimatedTokens: estimateTokens(hiddenToolsBlock),
638
- });
639
- }
640
- return blocks;
641
- },
642
- finalAudit: () => execModule.runFinalAudit(),
643
- lazyPromptBlocks: async () => {
644
- if (startupCheckBlock)
645
- return [startupCheckBlock];
646
- startupCheckBlock = (await startupCheckPromise) ?? null;
647
- return startupCheckBlock ? [startupCheckBlock] : [];
648
- },
649
- sessionManager,
650
- memoryStore,
651
- moduleRegistry,
77
+ activeToolTags: session.activeToolTags,
78
+ promptBlocks: modules.promptBlocks,
79
+ envReport: workspace.envReport,
80
+ getDynamicPromptBlocks: modules.getDynamicPromptBlocks,
81
+ lazyPromptBlocks: modules.lazyPromptBlocks,
82
+ sessionManager: session.sessionManager,
83
+ memoryStore: modules.memoryStore,
84
+ moduleRegistry: modules.moduleRegistry,
652
85
  exitOnComplete,
653
- reasoningProbe: () => reasoningProbePromise,
654
- reasoningStrategy,
655
- planSummary: () => execModule.getPlanSummary(),
656
- };
657
- const agent = new Agent(agentDeps);
658
- // Register set_thinking tool (needs agent's shared reasoning state)
659
- if (config.reasoning) {
660
- const { createSetThinkingTool } = await import("../tools/set-thinking");
661
- const setThinkingTool = createSetThinkingTool(agent.reasoningState, config.reasoning, () => agent.currentIteration);
662
- toolRegistry.register(setThinkingTool);
663
- }
86
+ contextLogger: session.contextLogger,
87
+ reasoningProbePromise: provider.reasoningProbePromise,
88
+ reasoningStrategy: provider.reasoningStrategy,
89
+ execModule: modules.execModule,
90
+ toolCtx: session.toolCtx,
91
+ contextProbePromise: provider.contextProbePromise,
92
+ }, workspace.toolRegistry);
664
93
  return {
665
94
  agent,
666
95
  config,
667
96
  logger,
668
- sessionManager,
669
- skillsModule,
670
- pluginManager,
671
- execModule,
672
- toolCtx,
97
+ sessionManager: session.sessionManager,
98
+ skillsModule: workspace.skillsModule,
99
+ pluginManager: workspace.pluginManager,
100
+ execModule: modules.execModule,
101
+ toolCtx: session.toolCtx,
102
+ toolRegistry: workspace.toolRegistry,
673
103
  configDir: dir,
674
- baseDir,
104
+ baseDir: workspace.baseDir,
675
105
  noAgentsMd: noAgentsMd === true,
676
- envReport,
106
+ envReport: workspace.envReport,
677
107
  legacyDetected,
678
- contextProbe: contextProbePromise,
108
+ contextProbe: provider.contextProbePromise,
109
+ memoryStore: modules.memoryStore,
110
+ indexerModule: workspace.indexerModule,
679
111
  };
680
112
  }