micro-models-agent 0.46.2 → 0.46.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/README.md +312 -312
  2. package/dist/main.js +711 -784
  3. package/dist/modules/browser/bridge-server.mjs +202 -202
  4. package/dist/skills/builtin/git.md +36 -36
  5. package/dist/skills/builtin/typescript.md +35 -35
  6. package/package.json +48 -48
  7. package/dist/cli/commands.js +0 -323
  8. package/dist/cli/completer.js +0 -167
  9. package/dist/cli/index.js +0 -2
  10. package/dist/cli/main.js +0 -165
  11. package/dist/cli/plugin-commands.js +0 -36
  12. package/dist/cli/repl-commands.js +0 -661
  13. package/dist/cli/repl.js +0 -616
  14. package/dist/cli/run-result.js +0 -22
  15. package/dist/cli/security-commands.js +0 -164
  16. package/dist/cli/setup.js +0 -231
  17. package/dist/config/config.js +0 -249
  18. package/dist/config/defaults.js +0 -124
  19. package/dist/config/experts.js +0 -15
  20. package/dist/config/index.js +0 -3
  21. package/dist/config/security.js +0 -193
  22. package/dist/config/types.js +0 -1
  23. package/dist/core/agent-moe.js +0 -102
  24. package/dist/core/agent.js +0 -886
  25. package/dist/core/bootstrap.js +0 -404
  26. package/dist/core/index.js +0 -2
  27. package/dist/core/prompt-builder.js +0 -76
  28. package/dist/core/session-logger.js +0 -197
  29. package/dist/core/types.js +0 -1
  30. package/dist/core/version.js +0 -24
  31. package/dist/core/workspace.js +0 -76
  32. package/dist/i18n/en.json +0 -598
  33. package/dist/i18n/index.js +0 -46
  34. package/dist/i18n/ru.json +0 -598
  35. package/dist/index.js +0 -22
  36. package/dist/llm/image-utils.js +0 -143
  37. package/dist/llm/index.js +0 -4
  38. package/dist/llm/model-loader.js +0 -78
  39. package/dist/llm/openai-compat.js +0 -359
  40. package/dist/llm/orchestrator.js +0 -198
  41. package/dist/llm/provider.js +0 -10
  42. package/dist/llm/response.js +0 -39
  43. package/dist/llm/token-counter.js +0 -39
  44. package/dist/llm/types.js +0 -1
  45. package/dist/logger/app-logger.js +0 -143
  46. package/dist/logger/file-log.js +0 -151
  47. package/dist/logger/index.js +0 -1
  48. package/dist/migration/backup.js +0 -45
  49. package/dist/migration/detect.js +0 -50
  50. package/dist/migration/index.js +0 -2
  51. package/dist/modules/artifacts/store.js +0 -61
  52. package/dist/modules/browser/actions.js +0 -76
  53. package/dist/modules/browser/bridge-client.js +0 -199
  54. package/dist/modules/browser/bridge-path.js +0 -10
  55. package/dist/modules/browser/cookie-store.js +0 -24
  56. package/dist/modules/browser/driver.js +0 -136
  57. package/dist/modules/browser/index.js +0 -7
  58. package/dist/modules/browser/module.js +0 -29
  59. package/dist/modules/browser/session.js +0 -338
  60. package/dist/modules/browser/snapshot.js +0 -148
  61. package/dist/modules/browser/types.js +0 -12
  62. package/dist/modules/certification/cli.js +0 -174
  63. package/dist/modules/certification/fact-checker.js +0 -82
  64. package/dist/modules/certification/loader.js +0 -105
  65. package/dist/modules/certification/manifest.js +0 -50
  66. package/dist/modules/certification/runner.js +0 -159
  67. package/dist/modules/certification/scenarios.js +0 -124
  68. package/dist/modules/certification/types.js +0 -1
  69. package/dist/modules/context/chunk-query.js +0 -100
  70. package/dist/modules/context/fact-extractor.js +0 -162
  71. package/dist/modules/context/history.js +0 -15
  72. package/dist/modules/context/index.js +0 -1
  73. package/dist/modules/context/manager.js +0 -423
  74. package/dist/modules/execution/audit-runners.js +0 -152
  75. package/dist/modules/execution/auditor.js +0 -218
  76. package/dist/modules/execution/execution-plugin.js +0 -272
  77. package/dist/modules/execution/index.js +0 -8
  78. package/dist/modules/execution/module.js +0 -436
  79. package/dist/modules/execution/moe-executor.js +0 -291
  80. package/dist/modules/execution/plan-coverage.js +0 -68
  81. package/dist/modules/execution/plan-persister.js +0 -46
  82. package/dist/modules/execution/plan-store.js +0 -157
  83. package/dist/modules/execution/plan-tool.js +0 -508
  84. package/dist/modules/execution/plan-validator.js +0 -153
  85. package/dist/modules/execution/planner.js +0 -90
  86. package/dist/modules/execution/stuck-detector.js +0 -510
  87. package/dist/modules/execution/tracker.js +0 -67
  88. package/dist/modules/execution/types.js +0 -1
  89. package/dist/modules/execution/verifier.js +0 -222
  90. package/dist/modules/execution/windows-commands.js +0 -41
  91. package/dist/modules/hallucination/confidence.js +0 -66
  92. package/dist/modules/hallucination/consistency.js +0 -26
  93. package/dist/modules/hallucination/detector.js +0 -43
  94. package/dist/modules/hallucination/factual.js +0 -129
  95. package/dist/modules/hallucination/index.js +0 -5
  96. package/dist/modules/hallucination/js-identifiers.js +0 -262
  97. package/dist/modules/hallucination/llm-judge.js +0 -101
  98. package/dist/modules/index.js +0 -5
  99. package/dist/modules/indexer/cache.js +0 -40
  100. package/dist/modules/indexer/index.js +0 -3
  101. package/dist/modules/indexer/module.js +0 -245
  102. package/dist/modules/indexer/project-profile.js +0 -183
  103. package/dist/modules/indexer/walker.js +0 -101
  104. package/dist/modules/lsp/check-tool.js +0 -58
  105. package/dist/modules/lsp/client.js +0 -278
  106. package/dist/modules/lsp/command.js +0 -60
  107. package/dist/modules/lsp/config.js +0 -135
  108. package/dist/modules/lsp/index.js +0 -3
  109. package/dist/modules/lsp/module.js +0 -232
  110. package/dist/modules/lsp/probe.js +0 -76
  111. package/dist/modules/lsp/project-root.js +0 -32
  112. package/dist/modules/lsp/startup-check.js +0 -141
  113. package/dist/modules/lsp/types.js +0 -1
  114. package/dist/modules/mcp/client.js +0 -399
  115. package/dist/modules/mcp/index.js +0 -3
  116. package/dist/modules/mcp/module.js +0 -142
  117. package/dist/modules/mcp/registry.js +0 -15
  118. package/dist/modules/memory/index.js +0 -1
  119. package/dist/modules/memory/module.js +0 -96
  120. package/dist/modules/memory/search.js +0 -42
  121. package/dist/modules/memory/store.js +0 -69
  122. package/dist/modules/pipelines/engine.js +0 -60
  123. package/dist/modules/pipelines/index.js +0 -3
  124. package/dist/modules/pipelines/parser.js +0 -56
  125. package/dist/modules/pipelines/template.js +0 -14
  126. package/dist/modules/plugins/builtin/lint-on-write.js +0 -231
  127. package/dist/modules/plugins/builtin/notify.js +0 -9
  128. package/dist/modules/plugins/index.js +0 -1
  129. package/dist/modules/plugins/loader.js +0 -70
  130. package/dist/modules/plugins/manager.js +0 -217
  131. package/dist/modules/plugins/types.js +0 -1
  132. package/dist/modules/processes/detect.js +0 -34
  133. package/dist/modules/processes/index.js +0 -2
  134. package/dist/modules/processes/registry.js +0 -327
  135. package/dist/modules/processes/runner.js +0 -23
  136. package/dist/modules/registry.js +0 -47
  137. package/dist/modules/security/audit-log.js +0 -136
  138. package/dist/modules/security/audit-notifier.js +0 -292
  139. package/dist/modules/security/command-validator.js +0 -205
  140. package/dist/modules/security/content-scanner.js +0 -53
  141. package/dist/modules/security/data-sanitizer.js +0 -89
  142. package/dist/modules/security/encryption.js +0 -242
  143. package/dist/modules/security/index.js +0 -14
  144. package/dist/modules/security/network-validator.js +0 -71
  145. package/dist/modules/security/path-validator.js +0 -207
  146. package/dist/modules/security/rate-limiter.js +0 -119
  147. package/dist/modules/security/security-policies.js +0 -531
  148. package/dist/modules/security/session-encryption.js +0 -210
  149. package/dist/modules/security/session-isolation.js +0 -95
  150. package/dist/modules/session/index.js +0 -3
  151. package/dist/modules/session/manager.js +0 -172
  152. package/dist/modules/session/module.js +0 -24
  153. package/dist/modules/session/store.js +0 -222
  154. package/dist/modules/session/types.js +0 -1
  155. package/dist/modules/skills/index.js +0 -2
  156. package/dist/modules/skills/loader.js +0 -72
  157. package/dist/modules/skills/matcher.js +0 -27
  158. package/dist/modules/skills/module.js +0 -129
  159. package/dist/modules/types.js +0 -1
  160. package/dist/modules/updater/checker.js +0 -96
  161. package/dist/modules/updater/index.js +0 -2
  162. package/dist/modules/updater/module.js +0 -116
  163. package/dist/modules/user-profile/compressor.js +0 -16
  164. package/dist/modules/user-profile/index.js +0 -1
  165. package/dist/modules/user-profile/profile.js +0 -68
  166. package/dist/tools/approve.js +0 -32
  167. package/dist/tools/attach-image.js +0 -89
  168. package/dist/tools/bash.js +0 -496
  169. package/dist/tools/browser.js +0 -114
  170. package/dist/tools/chunk-query.js +0 -99
  171. package/dist/tools/create-dir.js +0 -55
  172. package/dist/tools/delete-file.js +0 -62
  173. package/dist/tools/download-file.js +0 -116
  174. package/dist/tools/edit-file.js +0 -79
  175. package/dist/tools/enable-tools.js +0 -58
  176. package/dist/tools/executor.js +0 -144
  177. package/dist/tools/file-info.js +0 -46
  178. package/dist/tools/filter-tools.js +0 -17
  179. package/dist/tools/glob-tool.js +0 -26
  180. package/dist/tools/grep-tool.js +0 -84
  181. package/dist/tools/hidden-tools-block.js +0 -37
  182. package/dist/tools/index.js +0 -78
  183. package/dist/tools/list-dir.js +0 -48
  184. package/dist/tools/load-skill.js +0 -42
  185. package/dist/tools/mcp-call.js +0 -68
  186. package/dist/tools/move-file.js +0 -85
  187. package/dist/tools/path-utils.js +0 -51
  188. package/dist/tools/pipeline-run.js +0 -144
  189. package/dist/tools/preview.js +0 -2
  190. package/dist/tools/process-kill.js +0 -29
  191. package/dist/tools/process-list.js +0 -36
  192. package/dist/tools/process-log.js +0 -45
  193. package/dist/tools/question.js +0 -140
  194. package/dist/tools/read-file.js +0 -91
  195. package/dist/tools/recall.js +0 -117
  196. package/dist/tools/registry.js +0 -47
  197. package/dist/tools/remember.js +0 -67
  198. package/dist/tools/scope-check.js +0 -30
  199. package/dist/tools/search-history.js +0 -84
  200. package/dist/tools/subagent.js +0 -196
  201. package/dist/tools/types.js +0 -1
  202. package/dist/tools/user-input.js +0 -123
  203. package/dist/tools/web-browse.js +0 -86
  204. package/dist/tools/web-fetch.js +0 -98
  205. package/dist/tools/web-search.js +0 -78
  206. package/dist/tools/write-file.js +0 -81
  207. package/dist/ui/box.js +0 -77
  208. package/dist/ui/colors.js +0 -4
  209. package/dist/ui/diff.js +0 -178
  210. package/dist/ui/index.js +0 -6
  211. package/dist/ui/line-editor.js +0 -703
  212. package/dist/ui/line-math.js +0 -69
  213. package/dist/ui/md-formatter.js +0 -212
  214. package/dist/ui/output.js +0 -13
  215. package/dist/ui/plan-view.js +0 -103
  216. package/dist/ui/renderer.js +0 -209
  217. package/dist/ui/spinner.js +0 -70
  218. package/dist/ui/table.js +0 -144
@@ -1,404 +0,0 @@
1
- import { loadConfig } from "../config/config";
2
- import { Logger } from "../logger/app-logger";
3
- import { OpenAICompatProvider } from "../llm/openai-compat";
4
- import { ModelLoader } from "../llm/model-loader";
5
- import { ToolRegistry, registerAllTools } from "../tools/index";
6
- import { buildHiddenToolsBlock } from "../tools/hidden-tools-block";
7
- import { ToolExecutor } from "../tools/executor";
8
- import { ModuleRegistry } from "../modules/registry";
9
- import { PluginManager } from "../modules/plugins/manager";
10
- import { PluginLoader } from "../modules/plugins/loader";
11
- import { plugin as lintOnWritePlugin } from "../modules/plugins/builtin/lint-on-write";
12
- import { plugin as notifyPlugin } from "../modules/plugins/builtin/notify";
13
- import { ContextManager } from "../modules/context/manager";
14
- import { TokenCounter } from "../llm/token-counter";
15
- import { HallucinationDetector } from "../modules/hallucination/detector";
16
- import { ExecutionModule } from "../modules/execution/module";
17
- import { SessionStore, SessionManager, SessionModule } from "../modules/session/index";
18
- import { UserProfile } from "../modules/user-profile/profile";
19
- import { SkillsLoader, SkillsModule } from "../modules/skills/index";
20
- import { BrowserModule } from "../modules/browser/index";
21
- import { LspModule, DEFAULT_LSP_CONFIG } from "../modules/lsp/index";
22
- import { runStartupHealthCheck } from "../modules/lsp/startup-check";
23
- import { IndexerModule } from "../modules/indexer/index";
24
- import { MCPModule } from "../modules/mcp/index";
25
- import { MemoryModule } from "../modules/memory/module";
26
- import { MemoryStore } from "../modules/memory/store";
27
- import { setLocale } from "../i18n/index";
28
- import { Agent } from "./agent";
29
- import { homedir } from "os";
30
- import { join, resolve } from "path";
31
- import { existsSync, readFileSync, writeFileSync } from "fs";
32
- import { readMmaVersion } from "./version";
33
- export function buildSystemInfo(config, baseDir, profileCompressed) {
34
- const now = new Date().toISOString().replace("T", " ").slice(0, 19);
35
- const isWin = profileCompressed.toLowerCase().includes("win32");
36
- const lines = [
37
- `You are MMA v2, an AI coding agent for small models (${config.model}). Date: ${now}. Workspace: ${baseDir}. ${profileCompressed}.`,
38
- `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.`,
39
- `Design: YAGNI (no unneeded code), KISS (simple over clever), DRY (reuse existing utilities).`,
40
- ];
41
- if (isWin) {
42
- 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}`);
43
- }
44
- // MMA is a Bun-only project (package.json scripts, Bun API in code) — the
45
- // model should prefer bun over node/tsx/ts-node for running TypeScript
46
- // files and tests (observed: model wasted 10+ iterations installing tsx
47
- // instead of running `bun file.ts`).
48
- 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).`);
49
- 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.`);
50
- if (config.autoPlan) {
51
- 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.`);
52
- }
53
- // When a bug is described in terms of runtime behavior (what happens when
54
- // the app runs), the fix is only provable by REPRODUCING it — running the
55
- // app/build/browser and comparing against actual output. The model decides
56
- // when this applies (no keyword classification). Stale dev servers started
57
- // before a config/deps change keep the OLD pipeline in memory and still
58
- // throw the original error (observed: old vite on 5173-5176 kept failing
59
- // postcss after the fix was on disk, while a fresh server on 5177 was
60
- // clean) — the fix is only real when the USER's running server is clean.
61
- 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.`);
62
- const hasMCP = config.mcpServers && Object.values(config.mcpServers).some((s) => s.enabled !== false);
63
- if (hasMCP) {
64
- lines.push(`MCP servers are available — use the named MCP tools (prefixed mcp__) to query external services.`);
65
- }
66
- return lines.join("\n");
67
- }
68
- export async function bootstrap(configDir, projectDir, noAgentsMd, exitOnComplete) {
69
- const dir = configDir || join(homedir(), ".mma");
70
- const projectConfigPath = projectDir ? join(projectDir, ".mmrc") : join(process.cwd(), ".mmrc");
71
- const config = loadConfig({ configDir: dir, projectConfigPath });
72
- setLocale(config.locale);
73
- // Update global audit notifier with config
74
- try {
75
- const { globalAuditNotifier } = await import("../modules/security/audit-notifier");
76
- if (config.security?.auditNotifier) {
77
- globalAuditNotifier.updateConfig(config.security.auditNotifier);
78
- }
79
- }
80
- catch {
81
- // Ignore if audit notifier is not available
82
- }
83
- const logger = new Logger(config.logLevel);
84
- logger.setLogDir(join(dir, "logs"));
85
- logger.debug("MMA bootstrap", {
86
- version: config.version,
87
- model: config.model,
88
- });
89
- if (config.modelLoad.autoLoad) {
90
- const modelLoader = new ModelLoader(config.provider.baseUrl, logger);
91
- const loadResult = await modelLoader.ensureModelLoaded({
92
- model: config.model,
93
- contextLength: config.contextWindow,
94
- flashAttention: config.modelLoad.flashAttention,
95
- offloadKvCacheToGpu: config.modelLoad.offloadKvCacheToGpu,
96
- autoLoad: config.modelLoad.autoLoad,
97
- });
98
- if (!loadResult.success) {
99
- logger.warn(`Model auto-load failed: ${loadResult.error}. Continuing with manual load.`);
100
- }
101
- else if (loadResult.alreadyLoaded) {
102
- logger.debug(`Model ${config.model} already loaded`);
103
- }
104
- else {
105
- logger.info(`Model ${config.model} loaded in ${loadResult.loadTime}s`);
106
- }
107
- }
108
- const profile = new UserProfile(join(dir));
109
- profile.load() || profile.collect();
110
- profile.save();
111
- const llmProvider = new OpenAICompatProvider({
112
- model: config.model,
113
- baseUrl: config.provider.baseUrl,
114
- apiKey: config.provider.apiKey,
115
- contextWindow: config.contextWindow,
116
- retry: config.retry,
117
- rateLimits: config.security?.rateLimits,
118
- });
119
- const baseDir = projectDir ? resolve(projectDir) : process.cwd();
120
- const projectMapCacheDir = join(baseDir, ".mma");
121
- const indexerModule = new IndexerModule({
122
- baseDir,
123
- cacheDir: projectMapCacheDir,
124
- });
125
- try {
126
- await indexerModule.buildIndex();
127
- }
128
- catch (err) {
129
- logger.warn(`Project indexing failed: ${err.message}`);
130
- }
131
- const skillsLoader = new SkillsLoader();
132
- const builtinDir = join(import.meta.dirname, "skills", "builtin");
133
- const globalDir = join(homedir(), ".agents", "skills");
134
- const projectSkillsDir = join(baseDir, ".mma", "skills");
135
- const availableSkills = skillsLoader.loadFromAllSources(builtinDir, globalDir, projectSkillsDir);
136
- const skillsBudget = Math.floor(config.contextWindow * config.skills.budget);
137
- const skillsModule = new SkillsModule(availableSkills, skillsBudget);
138
- const toolRegistry = new ToolRegistry();
139
- registerAllTools(toolRegistry, skillsModule, {
140
- enableOnDemand: config.tools?.enableOnDemand,
141
- });
142
- const pluginManager = new PluginManager();
143
- const systemInfoContent = buildSystemInfo(config, baseDir, profile.compress());
144
- const systemInfoPrompt = {
145
- content: systemInfoContent,
146
- priority: "critical",
147
- essential: true,
148
- estimatedTokens: Math.ceil(systemInfoContent.length / 4),
149
- };
150
- const agentsMdGlobal = join(dir, "AGENTS.md");
151
- if (!existsSync(agentsMdGlobal)) {
152
- writeFileSync(agentsMdGlobal, "", "utf-8");
153
- }
154
- const sessionDir = join(dir, "sessions");
155
- const sessionStore = new SessionStore(sessionDir);
156
- sessionStore.init();
157
- const sessionManager = new SessionManager(sessionStore, {
158
- model: config.model,
159
- contextWindow: config.contextWindow,
160
- projectDir: baseDir,
161
- maxSessions: config.session.maxSessions,
162
- isolation: config.sessionIsolation,
163
- });
164
- if (config.session.autoSave && !sessionManager.getActive()) {
165
- sessionManager.create();
166
- }
167
- const tokenCounter = new TokenCounter(config.model);
168
- // Mutable set of active tool tags, shared between the agent loop and the
169
- // `enable_tools` tool. The loop re-reads it every iteration to recompute the
170
- // LLM-visible tool set; enable_tools pushes tags into it. When on-demand
171
- // enabling is disabled the tag set stays empty, which restores the legacy
172
- // all-tools behavior (getAllForLLM returns everything for empty tags).
173
- const enableOnDemand = config.tools?.enableOnDemand !== false;
174
- const activeToolTags = enableOnDemand
175
- ? config.tools?.defaultTags
176
- ? [...config.tools.defaultTags]
177
- : []
178
- : [];
179
- const contextManager = new ContextManager(config.contextWindow, config.contextBudget, tokenCounter);
180
- const toolCtx = {
181
- config,
182
- baseDir,
183
- logger,
184
- exitOnComplete,
185
- contextManager,
186
- activeToolTags,
187
- sessionId: sessionManager.getActiveMeta()?.id,
188
- sessionContext: sessionManager.getSessionContext() ?? undefined,
189
- recursionDepth: 0,
190
- fileOperationsCount: 0,
191
- sessionHistory: {
192
- append: async (type, content) => {
193
- const meta = sessionManager.getActiveMeta();
194
- if (!meta)
195
- return;
196
- sessionManager.appendMessage({
197
- role: "tool",
198
- content: typeof content === "string" ? content : JSON.stringify(content),
199
- name: type,
200
- timestamp: new Date().toISOString(),
201
- });
202
- },
203
- },
204
- sessionLog: {
205
- plan: (event, detail, iteration) => {
206
- sessionManager.appendLog({
207
- ts: new Date().toISOString(),
208
- type: "plan",
209
- tool: event,
210
- content: detail,
211
- ...(iteration !== undefined ? { iteration } : {}),
212
- });
213
- },
214
- },
215
- };
216
- const toolExecutor = new ToolExecutor(toolRegistry, toolCtx, pluginManager);
217
- toolCtx.llmProvider = llmProvider;
218
- toolCtx.toolExecutor = toolExecutor;
219
- const hallucinationDetector = new HallucinationDetector(baseDir, llmProvider);
220
- const moduleRegistry = new ModuleRegistry();
221
- const execModule = new ExecutionModule(baseDir, config.stuckThreshold);
222
- const activeMeta = sessionManager.getActiveMeta();
223
- if (activeMeta && activeMeta.messageCount > 0) {
224
- execModule.restorePlan();
225
- }
226
- moduleRegistry.register(execModule);
227
- const sessionModule = new SessionModule(sessionManager);
228
- moduleRegistry.register(sessionModule);
229
- moduleRegistry.register(indexerModule);
230
- const mcpModule = new MCPModule(config);
231
- await mcpModule.initialize();
232
- moduleRegistry.register(mcpModule);
233
- const memoryStore = new MemoryStore(join(dir, "memory"));
234
- const memoryModule = new MemoryModule(memoryStore);
235
- moduleRegistry.register(memoryModule);
236
- if (config.browser.enabled) {
237
- const browserModule = new BrowserModule();
238
- moduleRegistry.register(browserModule);
239
- const browserPlugin = browserModule.getPlugin();
240
- if (browserPlugin) {
241
- browserPlugin.isBuiltin = true;
242
- pluginManager.register(browserPlugin);
243
- }
244
- }
245
- const lspModule = new LspModule(config.lsp);
246
- moduleRegistry.register(lspModule);
247
- const lspPlugin = lspModule.getPlugin();
248
- if (lspPlugin) {
249
- lspPlugin.isBuiltin = true;
250
- pluginManager.register(lspPlugin);
251
- }
252
- // Startup health check: scan project for existing errors so the model
253
- // knows the baseline before it starts working. Skip for one-shot runs and
254
- // test environments. Started in the background (never awaited) so the REPL
255
- // banner is not blocked by `npx tsc` on the whole project; the Agent awaits
256
- // it before the first LLM call via `lazyPromptBlocks` (already resolved by
257
- // the time the user types in the interactive REPL).
258
- let startupCheckBlock = null;
259
- const startupCheckPromise = !exitOnComplete && process.env.NODE_ENV !== "test"
260
- ? runStartupHealthCheck(config.lsp ?? DEFAULT_LSP_CONFIG, baseDir)
261
- : Promise.resolve(null);
262
- const moduleTools = moduleRegistry.collectToolDefinitions();
263
- for (const tool of moduleTools) {
264
- toolRegistry.register(tool);
265
- }
266
- const plugin = execModule.getPlugin();
267
- if (plugin) {
268
- plugin.isBuiltin = true;
269
- pluginManager.register(plugin);
270
- }
271
- const sessionPlugin = sessionModule.getPlugin();
272
- if (sessionPlugin) {
273
- sessionPlugin.isBuiltin = true;
274
- pluginManager.register(sessionPlugin);
275
- }
276
- const skillsPlugin = skillsModule.getPlugin();
277
- if (skillsPlugin) {
278
- skillsPlugin.isBuiltin = true;
279
- pluginManager.register(skillsPlugin);
280
- }
281
- const indexerPlugin = indexerModule.getPlugin();
282
- if (indexerPlugin) {
283
- indexerPlugin.isBuiltin = true;
284
- pluginManager.register(indexerPlugin);
285
- }
286
- const mcpPlugin = mcpModule.getPlugin();
287
- if (mcpPlugin) {
288
- mcpPlugin.isBuiltin = true;
289
- pluginManager.register(mcpPlugin);
290
- }
291
- pluginManager.register(lintOnWritePlugin);
292
- pluginManager.register(notifyPlugin);
293
- const pluginLoader = new PluginLoader();
294
- const globalPluginsDir = join(homedir(), ".mma", "plugins");
295
- const projectPluginsDir = join(baseDir, ".mma", "plugins");
296
- const mmaVersion = readMmaVersion();
297
- pluginLoader.loadFromDir(globalPluginsDir, pluginManager, logger, {
298
- source: "global",
299
- mmaVersion,
300
- });
301
- pluginLoader.loadFromDir(projectPluginsDir, pluginManager, logger, {
302
- source: "project",
303
- mmaVersion,
304
- });
305
- contextManager.onCompact = (summary) => {
306
- const meta = sessionManager.getActiveMeta();
307
- if (!meta || !config.session.autoSave)
308
- return;
309
- sessionManager.appendMessage({
310
- role: summary.role,
311
- content: summary.content,
312
- name: summary.name,
313
- timestamp: new Date().toISOString(),
314
- });
315
- };
316
- // Carry the active plan (id, progress, current step) into the compaction
317
- // summary so a 9B model doesn't re-create the plan from scratch right after
318
- // compaction (observed: ses_msvuao0h — plan_e07pb2 (1/6) discarded for a
319
- // fresh plan_xzq9xe the same iteration the old plan was still visible).
320
- contextManager.setPlanSummaryProvider(() => execModule.getPlanSummary());
321
- const agentsMdBlocks = [];
322
- const skipAgentsMd = noAgentsMd === true;
323
- if (!skipAgentsMd) {
324
- const agentsMdCandidates = [
325
- join(baseDir, "AGENTS.md"),
326
- join(baseDir, ".mma", "AGENTS.md"),
327
- join(dir, "AGENTS.md"),
328
- ];
329
- for (const p of agentsMdCandidates) {
330
- if (existsSync(p)) {
331
- const content = readFileSync(p, "utf-8").trim();
332
- if (content) {
333
- agentsMdBlocks.push({
334
- content,
335
- priority: "high",
336
- essential: false,
337
- estimatedTokens: Math.ceil(content.length / 4),
338
- });
339
- }
340
- }
341
- }
342
- }
343
- const promptBlocks = [
344
- systemInfoPrompt,
345
- ...moduleRegistry.collectPromptBlocks(["indexer"]),
346
- ...agentsMdBlocks,
347
- ];
348
- const agentDeps = {
349
- config,
350
- llmProvider,
351
- toolExecutor,
352
- pluginManager,
353
- contextManager,
354
- hallucinationDetector,
355
- logger,
356
- baseDir,
357
- toolTags: activeToolTags,
358
- promptBlocks,
359
- getDynamicPromptBlocks: () => {
360
- const blocks = [];
361
- const planBlock = execModule.getSystemPromptBlock();
362
- if (planBlock)
363
- blocks.push(planBlock);
364
- const skillsBlock = skillsModule.getSystemPromptBlock();
365
- if (skillsBlock)
366
- blocks.push(skillsBlock);
367
- const mapBlock = indexerModule.getSystemPromptBlock();
368
- if (mapBlock)
369
- blocks.push(mapBlock);
370
- const hiddenToolsBlock = buildHiddenToolsBlock(toolRegistry.getAll(), activeToolTags);
371
- if (hiddenToolsBlock) {
372
- blocks.push({
373
- content: hiddenToolsBlock,
374
- priority: "low",
375
- essential: false,
376
- estimatedTokens: Math.ceil(hiddenToolsBlock.length / 4),
377
- });
378
- }
379
- return blocks;
380
- },
381
- finalAudit: () => execModule.runFinalAudit(),
382
- lazyPromptBlocks: async () => {
383
- if (startupCheckBlock)
384
- return [startupCheckBlock];
385
- startupCheckBlock = (await startupCheckPromise) ?? null;
386
- return startupCheckBlock ? [startupCheckBlock] : [];
387
- },
388
- sessionManager,
389
- memoryStore,
390
- exitOnComplete,
391
- };
392
- const agent = new Agent(agentDeps);
393
- return {
394
- agent,
395
- config,
396
- logger,
397
- sessionManager,
398
- skillsModule,
399
- pluginManager,
400
- configDir: dir,
401
- baseDir,
402
- noAgentsMd: skipAgentsMd,
403
- };
404
- }
@@ -1,2 +0,0 @@
1
- export { PromptBuilder } from "./prompt-builder";
2
- export { Agent } from "./agent";
@@ -1,76 +0,0 @@
1
- const PRIORITY_ORDER = {
2
- critical: 0,
3
- high: 1,
4
- normal: 2,
5
- low: 3,
6
- };
7
- function blockLabel(content) {
8
- const firstLine = content.split("\n")[0].trim();
9
- return firstLine.length > 70 ? firstLine.slice(0, 67) + "..." : firstLine;
10
- }
11
- export class PromptBuilder {
12
- blocks = [];
13
- budget;
14
- constructor(budget) {
15
- this.budget = budget;
16
- }
17
- addBlock(block) {
18
- this.blocks.push(block);
19
- }
20
- addBlocks(blocks) {
21
- for (const b of blocks) {
22
- this.blocks.push(b);
23
- }
24
- }
25
- build() {
26
- const essential = [];
27
- const nonEssential = [];
28
- for (const block of this.blocks) {
29
- if (block.essential) {
30
- essential.push(block);
31
- }
32
- else {
33
- nonEssential.push(block);
34
- }
35
- }
36
- nonEssential.sort((a, b) => PRIORITY_ORDER[a.priority] - PRIORITY_ORDER[b.priority]);
37
- let usedTokens = 0;
38
- const included = [];
39
- const excluded = [];
40
- const blocks = [];
41
- for (const block of essential) {
42
- included.push(block.content);
43
- usedTokens += block.estimatedTokens;
44
- blocks.push({
45
- label: blockLabel(block.content),
46
- priority: block.priority,
47
- essential: true,
48
- tokens: block.estimatedTokens,
49
- included: true,
50
- });
51
- }
52
- for (const block of nonEssential) {
53
- const tokens = block.estimatedTokens;
54
- const fits = usedTokens + tokens <= this.budget;
55
- if (fits) {
56
- included.push(block.content);
57
- usedTokens += tokens;
58
- }
59
- else {
60
- excluded.push(block.content);
61
- }
62
- blocks.push({
63
- label: blockLabel(block.content),
64
- priority: block.priority,
65
- essential: false,
66
- tokens,
67
- included: fits,
68
- });
69
- }
70
- return {
71
- prompt: included.join("\n\n"),
72
- excluded,
73
- blocks,
74
- };
75
- }
76
- }
@@ -1,197 +0,0 @@
1
- import { setAuditSessionDir } from "../modules/security/audit-log";
2
- /**
3
- * Thin wrapper around SessionManager that eliminates repetitive
4
- * `if (sessionManager)` + `new Date().toISOString()` boilerplate
5
- * from the agent loop.
6
- *
7
- * When constructed, it configures the app logger and audit log to write into
8
- * the session directory (instead of global ~/.mma/logs/).
9
- */
10
- export class SessionLogger {
11
- session;
12
- logger;
13
- constructor(session, logger) {
14
- this.session = session;
15
- this.logger = logger;
16
- this.bindSessionDir();
17
- }
18
- bindSessionDir() {
19
- const meta = this.session?.getActiveMeta();
20
- if (!meta)
21
- return;
22
- const dir = this.session.getSessionDirectory(meta.id);
23
- if (this.logger) {
24
- this.logger.setSessionDir(dir);
25
- this.logger.initSessionLog(meta.id);
26
- }
27
- setAuditSessionDir(dir);
28
- }
29
- get active() {
30
- return !!this.session?.getActive();
31
- }
32
- logSystem(content) {
33
- this.session?.appendLog({
34
- ts: new Date().toISOString(),
35
- type: "system",
36
- content,
37
- });
38
- }
39
- logUser(content) {
40
- this.session?.appendMessage({
41
- role: "user",
42
- content,
43
- timestamp: new Date().toISOString(),
44
- });
45
- this.session?.appendLog({
46
- ts: new Date().toISOString(),
47
- type: "user",
48
- content,
49
- });
50
- }
51
- logAssistant(content, reasoning, toolCalls, iteration) {
52
- if (reasoning) {
53
- this.session?.appendLog({
54
- ts: new Date().toISOString(),
55
- type: "reasoning",
56
- content: reasoning,
57
- iteration,
58
- });
59
- }
60
- this.session?.appendLog({
61
- ts: new Date().toISOString(),
62
- type: "assistant",
63
- content,
64
- ...(toolCalls
65
- ? {
66
- tool_calls: toolCalls.map((tc) => ({
67
- id: tc.id,
68
- name: tc.name,
69
- arguments: tc.arguments,
70
- })),
71
- }
72
- : {}),
73
- iteration,
74
- });
75
- }
76
- saveAssistantMessage(content) {
77
- this.session?.appendMessage({
78
- role: "assistant",
79
- content: content.slice(0, 500),
80
- timestamp: new Date().toISOString(),
81
- });
82
- }
83
- logToolDefs(toolCount, toolNames, iteration) {
84
- this.session?.appendLog({
85
- ts: new Date().toISOString(),
86
- type: "tool_defs",
87
- toolCount,
88
- toolNames,
89
- iteration,
90
- });
91
- }
92
- logToolCall(call, iteration) {
93
- this.session?.appendLog({
94
- ts: new Date().toISOString(),
95
- type: "tool_call",
96
- tool: call.name,
97
- tool_call_id: call.id,
98
- args: call.arguments,
99
- iteration,
100
- });
101
- }
102
- logToolResult(call, result, duration, iteration) {
103
- this.session?.appendMessage({
104
- role: "tool",
105
- content: result.output.slice(0, 500),
106
- name: call.name,
107
- timestamp: new Date().toISOString(),
108
- });
109
- this.session?.appendLog({
110
- ts: new Date().toISOString(),
111
- type: "tool_result",
112
- tool: call.name,
113
- tool_call_id: call.id,
114
- success: result.success,
115
- content: result.output.slice(0, 1000),
116
- diff: result.diff,
117
- duration,
118
- iteration,
119
- });
120
- }
121
- logCompaction(info) {
122
- this.session?.appendLog({
123
- ts: new Date().toISOString(),
124
- type: "compaction",
125
- content: `${info.reason}, iteration ${info.iteration}`,
126
- iteration: info.iteration,
127
- reason: info.reason,
128
- tokensBefore: info.tokensBefore,
129
- tokensAfter: info.tokensAfter,
130
- qualityBefore: info.qualityBefore,
131
- qualityAfter: info.qualityAfter,
132
- messagesBefore: info.messagesBefore,
133
- messagesAfter: info.messagesAfter,
134
- removedTurns: info.removedTurns,
135
- keptTurns: info.keptTurns,
136
- summary: info.summary,
137
- });
138
- }
139
- logContext(info) {
140
- this.session?.appendLog({
141
- ts: new Date().toISOString(),
142
- type: "context",
143
- content: info.kind === "start"
144
- ? "context snapshot at session start"
145
- : `context at iteration ${info.iteration}`,
146
- iteration: info.iteration,
147
- window: info.window,
148
- systemBudget: info.systemBudget,
149
- reserveBudget: info.reserveBudget,
150
- historyBudget: info.historyBudget,
151
- systemTokens: info.systemTokens,
152
- toolTokens: info.toolTokens,
153
- contextTokens: info.tokens,
154
- quality: info.quality,
155
- messageCount: info.messageCount,
156
- compactionCount: info.compactionCount,
157
- iterationsSinceCompaction: info.iterationsSinceCompaction,
158
- blocks: info.blocks,
159
- });
160
- }
161
- logLlmUsage(iteration, usage) {
162
- this.session?.appendLog({
163
- ts: new Date().toISOString(),
164
- type: "llm_usage",
165
- iteration,
166
- promptTokens: usage.promptTokens,
167
- completionTokens: usage.completionTokens,
168
- totalTokens: usage.totalTokens,
169
- source: usage.source,
170
- durationMs: usage.durationMs,
171
- });
172
- }
173
- logError(message) {
174
- this.session?.appendLog({
175
- ts: new Date().toISOString(),
176
- type: "error",
177
- content: message,
178
- });
179
- }
180
- logAudit(summary, iteration) {
181
- this.session?.appendLog({
182
- ts: new Date().toISOString(),
183
- type: "audit",
184
- content: summary,
185
- iteration,
186
- });
187
- }
188
- logPlan(event, detail, iteration) {
189
- this.session?.appendLog({
190
- ts: new Date().toISOString(),
191
- type: "plan",
192
- content: detail,
193
- tool: event,
194
- ...(iteration !== undefined ? { iteration } : {}),
195
- });
196
- }
197
- }
@@ -1 +0,0 @@
1
- export {};