micro-models-agent 0.63.0 → 1.1.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 (186) hide show
  1. package/CHANGELOG.md +174 -0
  2. package/dist/cli/cache-line.js +30 -0
  3. package/dist/cli/command-suggest.js +38 -0
  4. package/dist/cli/commands.js +285 -60
  5. package/dist/cli/completer.js +16 -16
  6. package/dist/cli/json-payload.js +32 -0
  7. package/dist/cli/main.js +165 -77
  8. package/dist/cli/plugin-commands.js +5 -4
  9. package/dist/cli/relaunch.js +37 -0
  10. package/dist/cli/repl-commands.js +441 -307
  11. package/dist/cli/repl.js +360 -83
  12. package/dist/cli/run-result.js +12 -6
  13. package/dist/cli/security-commands.js +64 -60
  14. package/dist/cli/setup-order.js +57 -0
  15. package/dist/cli/setup-prompt.js +49 -0
  16. package/dist/cli/setup.js +52 -48
  17. package/dist/config/budget.js +48 -0
  18. package/dist/config/config.js +132 -70
  19. package/dist/config/defaults.js +37 -11
  20. package/dist/config/domains.js +9 -50
  21. package/dist/config/utils.js +56 -0
  22. package/dist/core/agent/audit-gate.js +49 -0
  23. package/dist/core/agent/compaction.js +89 -0
  24. package/dist/core/agent/constants.js +61 -0
  25. package/dist/core/agent/context-renderer.js +40 -0
  26. package/dist/core/agent/hallucination-gate.js +87 -0
  27. package/dist/core/agent/loop-state.js +53 -0
  28. package/dist/core/agent/prefix-monitor.js +101 -0
  29. package/dist/core/agent/reasoning-resolver.js +56 -0
  30. package/dist/core/agent/token-tracker.js +96 -0
  31. package/dist/core/agent/tool-batch.js +237 -0
  32. package/dist/core/agent/tool-output.js +62 -0
  33. package/dist/core/agent-moe.js +214 -69
  34. package/dist/core/agent.js +506 -546
  35. package/dist/core/bootstrap.js +297 -98
  36. package/dist/core/crash-handler.js +2 -1
  37. package/dist/core/prompt-builder.js +3 -0
  38. package/dist/core/prompt-overflow.js +307 -0
  39. package/dist/core/session-logger.js +34 -2
  40. package/dist/i18n/en.json +8 -4
  41. package/dist/i18n/ru.json +8 -4
  42. package/dist/index.js +5 -1
  43. package/dist/llm/cache-usage.js +76 -0
  44. package/dist/llm/image-utils.js +20 -16
  45. package/dist/llm/llm-errors.js +41 -0
  46. package/dist/llm/model-loader.js +30 -0
  47. package/dist/llm/openai-compat.js +287 -101
  48. package/dist/llm/orchestrator.js +140 -68
  49. package/dist/llm/provider-budget.js +68 -0
  50. package/dist/llm/provider.js +0 -1
  51. package/dist/llm/stream-state.js +26 -0
  52. package/dist/llm/token-counter.js +28 -0
  53. package/dist/logger/app-logger.js +12 -15
  54. package/dist/main.js +1755 -841
  55. package/dist/migration/detect.js +3 -1
  56. package/dist/modules/browser/actions.js +0 -3
  57. package/dist/modules/browser/bridge-client.js +2 -0
  58. package/dist/modules/browser/bridge-server.mjs +37 -4
  59. package/dist/modules/browser/driver.js +46 -4
  60. package/dist/modules/certification/cli.js +85 -42
  61. package/dist/modules/certification/loader.js +15 -1
  62. package/dist/modules/certification/manifest.js +126 -15
  63. package/dist/modules/certification/runner.js +4 -26
  64. package/dist/modules/certification/scenarios.js +184 -5
  65. package/dist/modules/certification/syntax-scenarios.js +51 -0
  66. package/dist/modules/context/chunk-query.js +25 -5
  67. package/dist/modules/context/fact-extractor.js +6 -2
  68. package/dist/modules/context/manager.js +23 -7
  69. package/dist/modules/execution/audit-runners.js +7 -1
  70. package/dist/modules/execution/auditor.js +3 -3
  71. package/dist/modules/execution/execution-plugin.js +22 -15
  72. package/dist/modules/execution/input-from.js +46 -0
  73. package/dist/modules/execution/module.js +107 -18
  74. package/dist/modules/execution/moe-executor.js +166 -54
  75. package/dist/modules/execution/plan-actions.js +524 -0
  76. package/dist/modules/execution/plan-steps.js +23 -0
  77. package/dist/modules/execution/plan-store.js +15 -3
  78. package/dist/modules/execution/plan-tool.js +6 -488
  79. package/dist/modules/execution/plan-validator.js +24 -0
  80. package/dist/modules/execution/stuck-detector.js +3 -18
  81. package/dist/modules/execution/tracker.js +14 -5
  82. package/dist/modules/execution/transient-error.js +30 -0
  83. package/dist/modules/execution/verifier.js +94 -7
  84. package/dist/modules/execution/windows-commands.js +11 -0
  85. package/dist/modules/hallucination/confidence.js +36 -23
  86. package/dist/modules/hallucination/consistency.js +3 -0
  87. package/dist/modules/hallucination/detector.js +8 -3
  88. package/dist/modules/hallucination/factual.js +26 -7
  89. package/dist/modules/hallucination/llm-judge.js +12 -2
  90. package/dist/modules/indexer/map-command.js +35 -0
  91. package/dist/modules/indexer/map-select.js +87 -0
  92. package/dist/modules/indexer/module.js +34 -22
  93. package/dist/modules/indexer/symbols.js +189 -0
  94. package/dist/modules/indexer/walker.js +96 -42
  95. package/dist/modules/lsp/check-tool.js +2 -1
  96. package/dist/modules/lsp/client.js +49 -32
  97. package/dist/modules/lsp/config.js +55 -2
  98. package/dist/modules/lsp/module.js +38 -5
  99. package/dist/modules/lsp/probe.js +4 -3
  100. package/dist/modules/lsp/project-root.js +41 -1
  101. package/dist/modules/lsp/startup-check.js +12 -4
  102. package/dist/modules/mcp/client.js +153 -104
  103. package/dist/modules/mcp/module.js +165 -41
  104. package/dist/modules/memory/module.js +4 -3
  105. package/dist/modules/plugins/builtin/lint-on-write.js +36 -6
  106. package/dist/modules/plugins/manager.js +47 -84
  107. package/dist/modules/pricing/index.js +17 -7
  108. package/dist/modules/pricing/prices.js +30 -12
  109. package/dist/modules/processes/index.js +1 -0
  110. package/dist/modules/processes/kill-tree.js +56 -0
  111. package/dist/modules/processes/registry.js +2 -54
  112. package/dist/modules/providers/cache.js +23 -0
  113. package/dist/modules/providers/factory.js +28 -0
  114. package/dist/modules/providers/fallback.js +7 -5
  115. package/dist/modules/providers/health.js +2 -1
  116. package/dist/modules/providers/index.js +1 -0
  117. package/dist/modules/providers/manager.js +17 -2
  118. package/dist/modules/providers/presets.js +79 -6
  119. package/dist/modules/reasoning/policy.js +40 -0
  120. package/dist/modules/reasoning/probe.js +111 -0
  121. package/dist/modules/security/audit-notifier.js +42 -27
  122. package/dist/modules/security/command-validator.js +25 -20
  123. package/dist/modules/security/encryption.js +6 -12
  124. package/dist/modules/security/network-validator.js +76 -5
  125. package/dist/modules/security/path-validator.js +77 -34
  126. package/dist/modules/security/rate-limiter.js +11 -0
  127. package/dist/modules/security/security-policies.js +1 -1
  128. package/dist/modules/security/session-encryption.js +13 -2
  129. package/dist/modules/security/session-isolation.js +2 -9
  130. package/dist/modules/session/manager.js +11 -0
  131. package/dist/modules/session/module.js +11 -3
  132. package/dist/modules/session/store.js +41 -5
  133. package/dist/modules/skills/loader.js +7 -1
  134. package/dist/modules/skills/module.js +2 -1
  135. package/dist/modules/updater/changelog-reader.js +94 -0
  136. package/dist/modules/updater/dev-detect.js +17 -0
  137. package/dist/modules/updater/index.js +1 -0
  138. package/dist/modules/updater/module.js +14 -3
  139. package/dist/output/bus.js +32 -0
  140. package/dist/output/channel.js +233 -0
  141. package/dist/output/format.js +14 -0
  142. package/dist/output/index.js +7 -0
  143. package/dist/output/json-sink.js +22 -0
  144. package/dist/output/machine.js +8 -0
  145. package/dist/output/session-sink.js +27 -0
  146. package/dist/output/types.js +1 -0
  147. package/dist/tools/approve.js +6 -2
  148. package/dist/tools/attach-image.js +11 -11
  149. package/dist/tools/auto-fixer.js +198 -0
  150. package/dist/tools/bash.js +142 -89
  151. package/dist/tools/chunk-query.js +10 -6
  152. package/dist/tools/download-file.js +1 -1
  153. package/dist/tools/edit-file.js +20 -2
  154. package/dist/tools/executor.js +54 -9
  155. package/dist/tools/glob-tool.js +7 -0
  156. package/dist/tools/grep-tool.js +15 -1
  157. package/dist/tools/index.js +3 -1
  158. package/dist/tools/list-dir.js +3 -1
  159. package/dist/tools/load-skill.js +2 -1
  160. package/dist/tools/mcp-call.js +1 -1
  161. package/dist/tools/move-file.js +5 -4
  162. package/dist/tools/path-utils.js +7 -0
  163. package/dist/tools/pipeline-run.js +1 -1
  164. package/dist/tools/prompt-io.js +28 -0
  165. package/dist/tools/question.js +12 -12
  166. package/dist/tools/scope-request.js +91 -0
  167. package/dist/tools/session-info.js +44 -0
  168. package/dist/tools/set-thinking.js +71 -0
  169. package/dist/tools/subagent.js +50 -9
  170. package/dist/tools/syntax-validator.js +177 -0
  171. package/dist/tools/user-input.js +16 -9
  172. package/dist/tools/write-file.js +17 -1
  173. package/dist/ui/diff.js +10 -0
  174. package/dist/ui/line-editor.js +179 -26
  175. package/dist/ui/line-math.js +20 -3
  176. package/dist/ui/md-formatter.js +100 -10
  177. package/dist/ui/output.js +5 -4
  178. package/dist/ui/plan-view.js +2 -7
  179. package/dist/ui/renderer.js +89 -85
  180. package/dist/ui/spinner.js +14 -4
  181. package/dist/utils/error.js +4 -0
  182. package/dist/utils/index.js +4 -0
  183. package/dist/utils/retry.js +17 -0
  184. package/dist/utils/sleep.js +23 -0
  185. package/dist/utils/truncate.js +9 -0
  186. package/package.json +1 -1
@@ -1,7 +1,7 @@
1
1
  import { loadConfig } from "../config/config";
2
2
  import { Logger } from "../logger/app-logger";
3
- import { ProviderManager } from "../modules/providers/index";
4
- import { FallbackProvider } from "../modules/providers/fallback";
3
+ import { buildActiveProvider } from "../modules/providers/factory";
4
+ import { BUILTIN_PROVIDERS } from "../modules/providers/presets";
5
5
  import { ModelLoader } from "../llm/model-loader";
6
6
  import { ToolRegistry, registerAllTools } from "../tools/index";
7
7
  import { buildHiddenToolsBlock } from "../tools/hidden-tools-block";
@@ -12,7 +12,7 @@ import { PluginLoader } from "../modules/plugins/loader";
12
12
  import { plugin as lintOnWritePlugin } from "../modules/plugins/builtin/lint-on-write";
13
13
  import { plugin as notifyPlugin } from "../modules/plugins/builtin/notify";
14
14
  import { ContextManager } from "../modules/context/manager";
15
- import { TokenCounter } from "../llm/token-counter";
15
+ import { TokenCounter, estimateTokens } from "../llm/token-counter";
16
16
  import { HallucinationDetector } from "../modules/hallucination/detector";
17
17
  import { ExecutionModule } from "../modules/execution/module";
18
18
  import { SessionStore, SessionManager, SessionModule } from "../modules/session/index";
@@ -25,13 +25,85 @@ import { IndexerModule } from "../modules/indexer/index";
25
25
  import { MCPModule } from "../modules/mcp/index";
26
26
  import { MemoryModule } from "../modules/memory/module";
27
27
  import { MemoryStore } from "../modules/memory/store";
28
- import { setLocale } from "../i18n/index";
28
+ import { t, setLocale } from "../i18n/index";
29
29
  import { Agent } from "./agent";
30
30
  import { homedir } from "os";
31
31
  import { join, resolve } from "path";
32
- import { existsSync, readFileSync, writeFileSync } from "fs";
32
+ import { existsSync, readFileSync } from "fs";
33
33
  import { readMmaVersion } from "./version";
34
34
  import { collectEnvironment, logEnvironment } from "./environment";
35
+ import { dryRunOverflow, overflowHint } from "./prompt-overflow";
36
+ import { getLoadedContextLength } from "../llm/model-loader";
37
+ /**
38
+ * CLI --reasoning переопределяет конфигурационный режим
39
+ * (приоритет: CLI > config > default). "auto" пропускается — полагаемся
40
+ * на конфиг. Строка CLI приводится к типизированному ReasoningLevel.
41
+ */
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
+ }
35
107
  export function buildSystemInfo(config, baseDir, profileCompressed) {
36
108
  const now = new Date().toISOString().replace("T", " ").slice(0, 19);
37
109
  const isWin = profileCompressed.toLowerCase().includes("win32");
@@ -40,6 +112,7 @@ export function buildSystemInfo(config, baseDir, profileCompressed) {
40
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.`,
41
113
  `Design: YAGNI (no unneeded code), KISS (simple over clever), DRY (reuse existing utilities).`,
42
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.`,
43
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.`,
44
117
  ];
45
118
  if (isWin) {
@@ -98,11 +171,24 @@ export function buildSystemInfo(config, baseDir, profileCompressed) {
98
171
  }
99
172
  return lines.join("\n");
100
173
  }
101
- export async function bootstrap(configDir, projectDir, noAgentsMd, exitOnComplete) {
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) {
102
186
  const dir = configDir || process.env.MMA_CONFIG_DIR || join(homedir(), ".mma");
103
187
  const projectConfigPath = projectDir ? join(projectDir, ".mmrc") : join(process.cwd(), ".mmrc");
104
188
  const { config, legacyDetected } = loadConfig({ configDir: dir, projectConfigPath });
105
189
  setLocale(config.locale);
190
+ // CLI --reasoning overrides config mode (priority: CLI > config > default)
191
+ applyReasoningCliOverride(config, reasoningLevel);
106
192
  // Update global audit notifier with config
107
193
  try {
108
194
  const { globalAuditNotifier } = await import("../modules/security/audit-notifier");
@@ -119,6 +205,19 @@ export async function bootstrap(configDir, projectDir, noAgentsMd, exitOnComplet
119
205
  version: config.version,
120
206
  model: config.model,
121
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
+ }
122
221
  if (config.modelLoad.autoLoad) {
123
222
  const modelLoader = new ModelLoader(config.provider.baseUrl, logger);
124
223
  const loadResult = await modelLoader.ensureModelLoaded({
@@ -129,34 +228,84 @@ export async function bootstrap(configDir, projectDir, noAgentsMd, exitOnComplet
129
228
  autoLoad: config.modelLoad.autoLoad,
130
229
  });
131
230
  if (!loadResult.success) {
132
- logger.warn(`Model auto-load failed: ${loadResult.error}. Continuing with manual load.`);
231
+ logger.warn(t("env.model_autoload_failed", { error: String(loadResult.error ?? "") }));
133
232
  }
134
233
  else if (loadResult.alreadyLoaded) {
135
234
  logger.debug(`Model ${config.model} already loaded`);
136
235
  }
137
236
  else {
138
- logger.info(`Model ${config.model} loaded in ${loadResult.loadTime}s`);
237
+ logger.info(t("env.model_loaded", { model: config.model, seconds: String(loadResult.loadTime) }));
139
238
  }
140
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
+ })();
141
264
  const profile = new UserProfile(join(dir));
142
265
  profile.load() || profile.collect();
143
266
  profile.save();
144
- // Multi-provider manager (Phase 2). Built from the (possibly legacy flat)
145
- // config; the active provider is resolved through it. The initial provider
146
- // comes from the manager so the active entry is honored on startup.
147
- const providerManager = new ProviderManager(config.provider, {
148
- contextWindow: config.contextWindow,
149
- retry: config.retry,
150
- rateLimits: config.security?.rateLimits,
151
- });
152
- providerManager.setModel(config.model);
153
- let llmProvider = providerManager.active;
154
- // Phase 4.2: transparent failover to the next configured provider on
155
- // 429/5xx/network errors (only with multiple entries + fallback: true).
156
- if (config.provider.fallback && providerManager.listNames().length > 1) {
157
- llmProvider = new FallbackProvider(providerManager, (from, to, error) => {
158
- logger.warn(`provider failover: ${from} -> ${to} (${error.message.slice(0, 120)})`);
159
- });
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
+ })();
160
309
  }
161
310
  const baseDir = projectDir ? resolve(projectDir) : process.cwd();
162
311
  // Cross-device diagnosis: log a full environment report (OS, runtime,
@@ -177,10 +326,20 @@ export async function bootstrap(configDir, projectDir, noAgentsMd, exitOnComplet
177
326
  cacheDir: projectMapCacheDir,
178
327
  });
179
328
  try {
180
- await indexerModule.buildIndex();
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
+ }
181
340
  }
182
341
  catch (err) {
183
- logger.warn(`Project indexing failed: ${err.message}`);
342
+ logger.warn(t("env.indexing_failed", { error: String(err?.message ?? err) }));
184
343
  }
185
344
  const skillsLoader = new SkillsLoader();
186
345
  const builtinDir = join(import.meta.dirname, "skills", "builtin");
@@ -199,12 +358,8 @@ export async function bootstrap(configDir, projectDir, noAgentsMd, exitOnComplet
199
358
  content: systemInfoContent,
200
359
  priority: "critical",
201
360
  essential: true,
202
- estimatedTokens: Math.ceil(systemInfoContent.length / 4),
361
+ estimatedTokens: estimateTokens(systemInfoContent),
203
362
  };
204
- const agentsMdGlobal = join(dir, "AGENTS.md");
205
- if (!existsSync(agentsMdGlobal)) {
206
- writeFileSync(agentsMdGlobal, "", "utf-8");
207
- }
208
363
  const sessionDir = join(dir, "sessions");
209
364
  const sessionStore = new SessionStore(sessionDir);
210
365
  sessionStore.init();
@@ -215,6 +370,7 @@ export async function bootstrap(configDir, projectDir, noAgentsMd, exitOnComplet
215
370
  maxSessions: config.session.maxSessions,
216
371
  isolation: config.sessionIsolation,
217
372
  });
373
+ activeSessionManager = sessionManager;
218
374
  if (config.session.autoSave && !sessionManager.getActive()) {
219
375
  sessionManager.create();
220
376
  }
@@ -231,8 +387,13 @@ export async function bootstrap(configDir, projectDir, noAgentsMd, exitOnComplet
231
387
  : []
232
388
  : [];
233
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 };
234
396
  const toolCtx = {
235
- config,
236
397
  baseDir,
237
398
  logger,
238
399
  exitOnComplete,
@@ -265,6 +426,12 @@ export async function bootstrap(configDir, projectDir, noAgentsMd, exitOnComplet
265
426
  },
266
427
  },
267
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
+ });
268
435
  // `sessionId`/`sessionContext` are exposed as LIVE getters over the session
269
436
  // manager instead of being captured once at bootstrap. Capturing the values
270
437
  // pinned them to the session active at startup, so after a REPL /new or
@@ -281,10 +448,16 @@ export async function bootstrap(configDir, projectDir, noAgentsMd, exitOnComplet
281
448
  get: () => sessionManager.getSessionContext() ?? undefined,
282
449
  configurable: true,
283
450
  });
451
+ Object.defineProperty(toolCtx, "sessionManager", {
452
+ get: () => sessionManager,
453
+ configurable: true,
454
+ });
284
455
  const toolExecutor = new ToolExecutor(toolRegistry, toolCtx, pluginManager);
285
456
  toolCtx.llmProvider = llmProvider;
286
457
  toolCtx.toolExecutor = toolExecutor;
287
- const hallucinationDetector = new HallucinationDetector(baseDir, llmProvider);
458
+ const hallucinationDetector = new HallucinationDetector(baseDir, llmProvider, {
459
+ judgeEnabled: config.hallucination?.judge?.enabled ?? false,
460
+ });
288
461
  const moduleRegistry = new ModuleRegistry();
289
462
  const execModule = new ExecutionModule(baseDir, config.stuckThreshold, config.errorWebSearch?.threshold ?? 5);
290
463
  // A plan in .mma/plans/active.json is PROJECT state, not session state —
@@ -298,7 +471,15 @@ export async function bootstrap(configDir, projectDir, noAgentsMd, exitOnComplet
298
471
  moduleRegistry.register(sessionModule);
299
472
  moduleRegistry.register(indexerModule);
300
473
  const mcpModule = new MCPModule(config);
301
- await mcpModule.initialize();
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
+ }
302
483
  moduleRegistry.register(mcpModule);
303
484
  const memoryStore = new MemoryStore(join(dir, "memory"));
304
485
  const memoryModule = new MemoryModule(memoryStore);
@@ -306,20 +487,12 @@ export async function bootstrap(configDir, projectDir, noAgentsMd, exitOnComplet
306
487
  if (config.browser.enabled) {
307
488
  const browserModule = new BrowserModule();
308
489
  moduleRegistry.register(browserModule);
309
- const browserPlugin = browserModule.getPlugin();
310
- if (browserPlugin) {
311
- browserPlugin.isBuiltin = true;
312
- pluginManager.register(browserPlugin);
313
- }
490
+ registerBuiltinPlugin(pluginManager, browserModule.getPlugin());
314
491
  }
315
492
  const lspLogger = new FileOnlyLogger(logger);
316
493
  const lspModule = new LspModule(config.lsp, undefined, lspLogger);
317
494
  moduleRegistry.register(lspModule);
318
- const lspPlugin = lspModule.getPlugin();
319
- if (lspPlugin) {
320
- lspPlugin.isBuiltin = true;
321
- pluginManager.register(lspPlugin);
322
- }
495
+ registerBuiltinPlugin(pluginManager, lspModule.getPlugin());
323
496
  // Startup health check: scan project for existing errors so the model
324
497
  // knows the baseline before it starts working. Skip for one-shot runs and
325
498
  // test environments. Started in the background (never awaited) so the REPL
@@ -327,7 +500,7 @@ export async function bootstrap(configDir, projectDir, noAgentsMd, exitOnComplet
327
500
  // it before the first LLM call via `lazyPromptBlocks` (already resolved by
328
501
  // the time the user types in the interactive REPL).
329
502
  let startupCheckBlock = null;
330
- const startupCheckPromise = !exitOnComplete && process.env.NODE_ENV !== "test"
503
+ const startupCheckPromise = !oneShotMode && !exitOnComplete && process.env.NODE_ENV !== "test"
331
504
  ? runStartupHealthCheck(config.lsp ?? DEFAULT_LSP_CONFIG, baseDir, { logger: lspLogger })
332
505
  : Promise.resolve(null);
333
506
  const moduleTools = moduleRegistry.collectToolDefinitions();
@@ -335,30 +508,11 @@ export async function bootstrap(configDir, projectDir, noAgentsMd, exitOnComplet
335
508
  toolRegistry.register(tool);
336
509
  }
337
510
  const plugin = execModule.getPlugin();
338
- if (plugin) {
339
- plugin.isBuiltin = true;
340
- pluginManager.register(plugin);
341
- }
342
- const sessionPlugin = sessionModule.getPlugin();
343
- if (sessionPlugin) {
344
- sessionPlugin.isBuiltin = true;
345
- pluginManager.register(sessionPlugin);
346
- }
347
- const skillsPlugin = skillsModule.getPlugin();
348
- if (skillsPlugin) {
349
- skillsPlugin.isBuiltin = true;
350
- pluginManager.register(skillsPlugin);
351
- }
352
- const indexerPlugin = indexerModule.getPlugin();
353
- if (indexerPlugin) {
354
- indexerPlugin.isBuiltin = true;
355
- pluginManager.register(indexerPlugin);
356
- }
357
- const mcpPlugin = mcpModule.getPlugin();
358
- if (mcpPlugin) {
359
- mcpPlugin.isBuiltin = true;
360
- pluginManager.register(mcpPlugin);
361
- }
511
+ registerBuiltinPlugin(pluginManager, plugin);
512
+ registerBuiltinPlugin(pluginManager, sessionModule.getPlugin());
513
+ registerBuiltinPlugin(pluginManager, skillsModule.getPlugin());
514
+ registerBuiltinPlugin(pluginManager, indexerModule.getPlugin());
515
+ registerBuiltinPlugin(pluginManager, mcpModule.getPlugin());
362
516
  pluginManager.register(lintOnWritePlugin);
363
517
  pluginManager.register(notifyPlugin);
364
518
  const pluginLoader = new PluginLoader();
@@ -389,35 +543,62 @@ export async function bootstrap(configDir, projectDir, noAgentsMd, exitOnComplet
389
543
  // compaction (observed: ses_msvuao0h — plan_e07pb2 (1/6) discarded for a
390
544
  // fresh plan_xzq9xe the same iteration the old plan was still visible).
391
545
  contextManager.setPlanSummaryProvider(() => execModule.getPlanSummary());
392
- const agentsMdBlocks = [];
393
- const skipAgentsMd = noAgentsMd === true;
394
- if (!skipAgentsMd) {
395
- const agentsMdCandidates = [
396
- join(baseDir, "AGENTS.md"),
397
- join(baseDir, ".mma", "AGENTS.md"),
398
- join(dir, "AGENTS.md"),
399
- ];
400
- for (const p of agentsMdCandidates) {
401
- if (existsSync(p)) {
402
- const content = readFileSync(p, "utf-8").trim();
403
- if (content) {
404
- agentsMdBlocks.push({
405
- content,
406
- priority: "high",
407
- essential: false,
408
- estimatedTokens: Math.ceil(content.length / 4),
409
- });
410
- }
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
+ }));
411
596
  }
412
597
  }
413
598
  }
414
- const promptBlocks = [
415
- systemInfoPrompt,
416
- ...moduleRegistry.collectPromptBlocks(["indexer"]),
417
- ...agentsMdBlocks,
418
- ];
419
599
  const agentDeps = {
420
600
  config,
601
+ configRef,
421
602
  llmProvider,
422
603
  toolExecutor,
423
604
  pluginManager,
@@ -425,17 +606,25 @@ export async function bootstrap(configDir, projectDir, noAgentsMd, exitOnComplet
425
606
  hallucinationDetector,
426
607
  logger,
427
608
  baseDir,
609
+ configDir: dir,
428
610
  toolTags: activeToolTags,
429
611
  promptBlocks,
430
612
  envReport,
431
613
  getDynamicPromptBlocks: () => {
432
614
  const blocks = [];
433
- const planBlock = execModule.getSystemPromptBlock();
434
- if (planBlock)
435
- blocks.push(planBlock);
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.
436
618
  const skillsBlock = skillsModule.getSystemPromptBlock();
437
619
  if (skillsBlock)
438
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);
439
628
  const mapBlock = indexerModule.getSystemPromptBlock();
440
629
  if (mapBlock)
441
630
  blocks.push(mapBlock);
@@ -445,7 +634,7 @@ export async function bootstrap(configDir, projectDir, noAgentsMd, exitOnComplet
445
634
  content: hiddenToolsBlock,
446
635
  priority: "low",
447
636
  essential: false,
448
- estimatedTokens: Math.ceil(hiddenToolsBlock.length / 4),
637
+ estimatedTokens: estimateTokens(hiddenToolsBlock),
449
638
  });
450
639
  }
451
640
  return blocks;
@@ -461,8 +650,17 @@ export async function bootstrap(configDir, projectDir, noAgentsMd, exitOnComplet
461
650
  memoryStore,
462
651
  moduleRegistry,
463
652
  exitOnComplete,
653
+ reasoningProbe: () => reasoningProbePromise,
654
+ reasoningStrategy,
655
+ planSummary: () => execModule.getPlanSummary(),
464
656
  };
465
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
+ }
466
664
  return {
467
665
  agent,
468
666
  config,
@@ -474,8 +672,9 @@ export async function bootstrap(configDir, projectDir, noAgentsMd, exitOnComplet
474
672
  toolCtx,
475
673
  configDir: dir,
476
674
  baseDir,
477
- noAgentsMd: skipAgentsMd,
675
+ noAgentsMd: noAgentsMd === true,
478
676
  envReport,
479
677
  legacyDetected,
678
+ contextProbe: contextProbePromise,
480
679
  };
481
680
  }
@@ -4,11 +4,12 @@ import { homedir } from "os";
4
4
  import { collectEnvironment } from "./environment";
5
5
  import { sanitizeLogMessage } from "../modules/security/data-sanitizer";
6
6
  import { t } from "../i18n/index";
7
+ import { errMsg } from "../utils";
7
8
  export const CRASH_LOG_DIR = join(homedir(), ".mma", "logs");
8
9
  export const CRASH_LOG_FILE = "crash.jsonl";
9
10
  /** Build a sanitized crash entry. Environment is captured at crash time (no tool scan). */
10
11
  export function formatCrashEntry(type, err) {
11
- const message = err instanceof Error ? err.message : String(err);
12
+ const message = errMsg(err);
12
13
  const stack = err instanceof Error && err.stack ? err.stack : message;
13
14
  return {
14
15
  ts: new Date().toISOString(),
@@ -37,6 +37,7 @@ export class PromptBuilder {
37
37
  let usedTokens = 0;
38
38
  const included = [];
39
39
  const excluded = [];
40
+ const excludedBlocks = [];
40
41
  const blocks = [];
41
42
  for (const block of essential) {
42
43
  included.push(block.content);
@@ -58,6 +59,7 @@ export class PromptBuilder {
58
59
  }
59
60
  else {
60
61
  excluded.push(block.content);
62
+ excludedBlocks.push(block);
61
63
  }
62
64
  blocks.push({
63
65
  label: blockLabel(block.content),
@@ -70,6 +72,7 @@ export class PromptBuilder {
70
72
  return {
71
73
  prompt: included.join("\n\n"),
72
74
  excluded,
75
+ excludedBlocks,
73
76
  blocks,
74
77
  };
75
78
  }