micro-models-agent 0.61.0 → 0.62.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 (233) hide show
  1. package/CHANGELOG.md +619 -595
  2. package/README.md +358 -358
  3. package/dist/certification/certifications.json +493 -493
  4. package/dist/cli/commands.js +447 -0
  5. package/dist/cli/completer.js +167 -0
  6. package/dist/cli/index.js +2 -0
  7. package/dist/cli/main.js +153 -0
  8. package/dist/cli/plugin-commands.js +36 -0
  9. package/dist/cli/repl-commands.js +761 -0
  10. package/dist/cli/repl.js +702 -0
  11. package/dist/cli/run-result.js +33 -0
  12. package/dist/cli/security-commands.js +164 -0
  13. package/dist/cli/setup.js +237 -0
  14. package/dist/config/config.js +276 -0
  15. package/dist/config/defaults.js +141 -0
  16. package/dist/config/domains.js +179 -0
  17. package/dist/config/experts.js +15 -0
  18. package/dist/config/index.js +4 -0
  19. package/dist/config/security.js +213 -0
  20. package/dist/config/types.js +1 -0
  21. package/dist/core/agent-moe.js +102 -0
  22. package/dist/core/agent.js +1018 -0
  23. package/dist/core/bootstrap.js +481 -0
  24. package/dist/core/crash-handler.js +51 -0
  25. package/dist/core/environment.js +199 -0
  26. package/dist/core/index.js +2 -0
  27. package/dist/core/prompt-builder.js +76 -0
  28. package/dist/core/session-logger.js +251 -0
  29. package/dist/core/types.js +1 -0
  30. package/dist/core/version.js +26 -0
  31. package/dist/core/workspace.js +76 -0
  32. package/dist/i18n/en.json +776 -757
  33. package/dist/i18n/index.js +46 -0
  34. package/dist/i18n/ru.json +776 -757
  35. package/dist/index.js +22 -0
  36. package/dist/llm/image-utils.js +143 -0
  37. package/dist/llm/index.js +4 -0
  38. package/dist/llm/model-loader.js +78 -0
  39. package/dist/llm/openai-compat.js +497 -0
  40. package/dist/llm/orchestrator.js +200 -0
  41. package/dist/llm/provider.js +10 -0
  42. package/dist/llm/response.js +39 -0
  43. package/dist/llm/token-counter.js +39 -0
  44. package/dist/llm/types.js +1 -0
  45. package/dist/logger/app-logger.js +189 -0
  46. package/dist/logger/file-log.js +151 -0
  47. package/dist/logger/index.js +1 -0
  48. package/dist/main.js +1026 -417
  49. package/dist/migration/backup.js +45 -0
  50. package/dist/migration/detect.js +50 -0
  51. package/dist/migration/index.js +2 -0
  52. package/dist/modules/artifacts/store.js +61 -0
  53. package/dist/modules/browser/actions.js +76 -0
  54. package/dist/modules/browser/bridge-client.js +199 -0
  55. package/dist/modules/browser/bridge-path.js +10 -0
  56. package/dist/modules/browser/bridge-server.mjs +219 -219
  57. package/dist/modules/browser/cookie-store.js +24 -0
  58. package/dist/modules/browser/driver.js +136 -0
  59. package/dist/modules/browser/index.js +7 -0
  60. package/dist/modules/browser/module.js +29 -0
  61. package/dist/modules/browser/session.js +342 -0
  62. package/dist/modules/browser/snapshot.js +148 -0
  63. package/dist/modules/browser/types.js +12 -0
  64. package/dist/modules/certification/cli.js +213 -0
  65. package/dist/modules/certification/fact-checker.js +82 -0
  66. package/dist/modules/certification/loader.js +106 -0
  67. package/dist/modules/certification/manifest.js +58 -0
  68. package/dist/modules/certification/runner.js +245 -0
  69. package/dist/modules/certification/scenarios.js +407 -0
  70. package/dist/modules/certification/types.js +1 -0
  71. package/dist/modules/context/chunk-query.js +100 -0
  72. package/dist/modules/context/fact-extractor.js +168 -0
  73. package/dist/modules/context/history.js +15 -0
  74. package/dist/modules/context/index.js +1 -0
  75. package/dist/modules/context/manager.js +440 -0
  76. package/dist/modules/execution/audit-runners.js +206 -0
  77. package/dist/modules/execution/auditor.js +218 -0
  78. package/dist/modules/execution/execution-plugin.js +431 -0
  79. package/dist/modules/execution/index.js +8 -0
  80. package/dist/modules/execution/module.js +625 -0
  81. package/dist/modules/execution/moe-executor.js +304 -0
  82. package/dist/modules/execution/plan-coverage.js +68 -0
  83. package/dist/modules/execution/plan-persister.js +46 -0
  84. package/dist/modules/execution/plan-store.js +196 -0
  85. package/dist/modules/execution/plan-tool.js +677 -0
  86. package/dist/modules/execution/plan-validator.js +153 -0
  87. package/dist/modules/execution/planner.js +94 -0
  88. package/dist/modules/execution/stuck-detector.js +746 -0
  89. package/dist/modules/execution/tracker.js +69 -0
  90. package/dist/modules/execution/types.js +1 -0
  91. package/dist/modules/execution/verifier.js +235 -0
  92. package/dist/modules/execution/windows-commands.js +41 -0
  93. package/dist/modules/hallucination/confidence.js +66 -0
  94. package/dist/modules/hallucination/consistency.js +26 -0
  95. package/dist/modules/hallucination/detector.js +47 -0
  96. package/dist/modules/hallucination/factual.js +169 -0
  97. package/dist/modules/hallucination/index.js +5 -0
  98. package/dist/modules/hallucination/js-identifiers.js +262 -0
  99. package/dist/modules/hallucination/llm-judge.js +101 -0
  100. package/dist/modules/index.js +5 -0
  101. package/dist/modules/indexer/cache.js +40 -0
  102. package/dist/modules/indexer/index.js +3 -0
  103. package/dist/modules/indexer/module.js +246 -0
  104. package/dist/modules/indexer/project-profile.js +183 -0
  105. package/dist/modules/indexer/walker.js +101 -0
  106. package/dist/modules/lsp/check-tool.js +58 -0
  107. package/dist/modules/lsp/client.js +389 -0
  108. package/dist/modules/lsp/command.js +60 -0
  109. package/dist/modules/lsp/config.js +135 -0
  110. package/dist/modules/lsp/index.js +3 -0
  111. package/dist/modules/lsp/module.js +260 -0
  112. package/dist/modules/lsp/probe.js +86 -0
  113. package/dist/modules/lsp/project-root.js +32 -0
  114. package/dist/modules/lsp/startup-check.js +144 -0
  115. package/dist/modules/lsp/types.js +1 -0
  116. package/dist/modules/mcp/client.js +399 -0
  117. package/dist/modules/mcp/index.js +3 -0
  118. package/dist/modules/mcp/module.js +142 -0
  119. package/dist/modules/mcp/registry.js +15 -0
  120. package/dist/modules/memory/index.js +1 -0
  121. package/dist/modules/memory/module.js +96 -0
  122. package/dist/modules/memory/search.js +42 -0
  123. package/dist/modules/memory/store.js +69 -0
  124. package/dist/modules/pipelines/engine.js +60 -0
  125. package/dist/modules/pipelines/index.js +3 -0
  126. package/dist/modules/pipelines/parser.js +56 -0
  127. package/dist/modules/pipelines/template.js +14 -0
  128. package/dist/modules/plugins/builtin/lint-on-write.js +334 -0
  129. package/dist/modules/plugins/builtin/notify.js +9 -0
  130. package/dist/modules/plugins/index.js +1 -0
  131. package/dist/modules/plugins/loader.js +70 -0
  132. package/dist/modules/plugins/manager.js +261 -0
  133. package/dist/modules/plugins/types.js +1 -0
  134. package/dist/modules/pricing/index.js +61 -0
  135. package/dist/modules/pricing/prices.js +129 -0
  136. package/dist/modules/processes/detect.js +34 -0
  137. package/dist/modules/processes/index.js +2 -0
  138. package/dist/modules/processes/registry.js +327 -0
  139. package/dist/modules/processes/runner.js +23 -0
  140. package/dist/modules/providers/create.js +22 -0
  141. package/dist/modules/providers/fallback.js +79 -0
  142. package/dist/modules/providers/health.js +46 -0
  143. package/dist/modules/providers/index.js +5 -0
  144. package/dist/modules/providers/manager.js +161 -0
  145. package/dist/modules/providers/presets.js +128 -0
  146. package/dist/modules/providers/registry.js +22 -0
  147. package/dist/modules/providers/types.js +1 -0
  148. package/dist/modules/registry.js +48 -0
  149. package/dist/modules/security/audit-log.js +136 -0
  150. package/dist/modules/security/audit-notifier.js +292 -0
  151. package/dist/modules/security/command-validator.js +219 -0
  152. package/dist/modules/security/content-scanner.js +53 -0
  153. package/dist/modules/security/data-sanitizer.js +89 -0
  154. package/dist/modules/security/encryption.js +242 -0
  155. package/dist/modules/security/index.js +14 -0
  156. package/dist/modules/security/network-validator.js +88 -0
  157. package/dist/modules/security/path-validator.js +203 -0
  158. package/dist/modules/security/rate-limiter.js +119 -0
  159. package/dist/modules/security/security-policies.js +531 -0
  160. package/dist/modules/security/session-encryption.js +210 -0
  161. package/dist/modules/security/session-isolation.js +95 -0
  162. package/dist/modules/session/index.js +3 -0
  163. package/dist/modules/session/manager.js +172 -0
  164. package/dist/modules/session/module.js +24 -0
  165. package/dist/modules/session/store.js +222 -0
  166. package/dist/modules/session/types.js +1 -0
  167. package/dist/modules/skills/index.js +2 -0
  168. package/dist/modules/skills/loader.js +72 -0
  169. package/dist/modules/skills/matcher.js +27 -0
  170. package/dist/modules/skills/module.js +129 -0
  171. package/dist/modules/types.js +1 -0
  172. package/dist/modules/updater/checker.js +96 -0
  173. package/dist/modules/updater/index.js +2 -0
  174. package/dist/modules/updater/module.js +116 -0
  175. package/dist/modules/user-profile/compressor.js +16 -0
  176. package/dist/modules/user-profile/index.js +1 -0
  177. package/dist/modules/user-profile/profile.js +68 -0
  178. package/dist/skills/builtin/git.md +36 -36
  179. package/dist/skills/builtin/typescript.md +35 -35
  180. package/dist/tools/approve.js +33 -0
  181. package/dist/tools/attach-image.js +101 -0
  182. package/dist/tools/bash.js +519 -0
  183. package/dist/tools/browser.js +115 -0
  184. package/dist/tools/chunk-query.js +100 -0
  185. package/dist/tools/create-dir.js +56 -0
  186. package/dist/tools/delete-file.js +63 -0
  187. package/dist/tools/download-file.js +117 -0
  188. package/dist/tools/edit-file.js +80 -0
  189. package/dist/tools/enable-tools.js +59 -0
  190. package/dist/tools/executor.js +154 -0
  191. package/dist/tools/file-info.js +47 -0
  192. package/dist/tools/filter-tools.js +17 -0
  193. package/dist/tools/glob-tool.js +27 -0
  194. package/dist/tools/grep-tool.js +125 -0
  195. package/dist/tools/hidden-tools-block.js +37 -0
  196. package/dist/tools/index.js +78 -0
  197. package/dist/tools/list-dir.js +49 -0
  198. package/dist/tools/load-skill.js +43 -0
  199. package/dist/tools/mcp-call.js +69 -0
  200. package/dist/tools/move-file.js +86 -0
  201. package/dist/tools/path-utils.js +101 -0
  202. package/dist/tools/pipeline-run.js +145 -0
  203. package/dist/tools/preview.js +2 -0
  204. package/dist/tools/process-kill.js +40 -0
  205. package/dist/tools/process-list.js +37 -0
  206. package/dist/tools/process-log.js +54 -0
  207. package/dist/tools/question.js +141 -0
  208. package/dist/tools/read-file.js +179 -0
  209. package/dist/tools/recall.js +118 -0
  210. package/dist/tools/registry.js +47 -0
  211. package/dist/tools/remember.js +68 -0
  212. package/dist/tools/scope-check.js +32 -0
  213. package/dist/tools/search-history.js +85 -0
  214. package/dist/tools/subagent.js +196 -0
  215. package/dist/tools/types.js +1 -0
  216. package/dist/tools/user-input.js +123 -0
  217. package/dist/tools/web-browse.js +87 -0
  218. package/dist/tools/web-fetch.js +119 -0
  219. package/dist/tools/web-search.js +105 -0
  220. package/dist/tools/write-file.js +82 -0
  221. package/dist/ui/box.js +77 -0
  222. package/dist/ui/colors.js +4 -0
  223. package/dist/ui/diff.js +178 -0
  224. package/dist/ui/index.js +6 -0
  225. package/dist/ui/line-editor.js +822 -0
  226. package/dist/ui/line-math.js +73 -0
  227. package/dist/ui/md-formatter.js +212 -0
  228. package/dist/ui/output.js +13 -0
  229. package/dist/ui/plan-view.js +103 -0
  230. package/dist/ui/renderer.js +259 -0
  231. package/dist/ui/spinner.js +70 -0
  232. package/dist/ui/table.js +144 -0
  233. package/package.json +51 -51
@@ -0,0 +1,128 @@
1
+ // src/modules/providers/presets.ts
2
+ import { OpenAICompatProvider } from "../../llm/openai-compat";
3
+ /** Build an OpenAI-compatible provider (default for most backends). */
4
+ function openaiCompat(opts) {
5
+ const retry = (opts.retry ?? {
6
+ maxRetries: 3,
7
+ baseDelay: 1000,
8
+ maxDelay: 30000,
9
+ });
10
+ const rateLimits = opts.rateLimits;
11
+ return new OpenAICompatProvider({
12
+ model: opts.model,
13
+ baseUrl: opts.baseUrl,
14
+ apiKey: opts.apiKey,
15
+ contextWindow: opts.contextWindow,
16
+ retry,
17
+ rateLimits,
18
+ maxCompletionTokens: opts.maxCompletionTokens,
19
+ });
20
+ }
21
+ const OPENAI_COMPAT = {
22
+ type: "openai-compat",
23
+ label: "OpenAI-compatible (LM Studio, Ollama, vLLM, etc.)",
24
+ baseUrl: "",
25
+ capabilities: {
26
+ streaming: true,
27
+ tools: true,
28
+ vision: false,
29
+ reasoningEffort: false,
30
+ listModels: true,
31
+ requiresKey: false,
32
+ auth: "bearer",
33
+ },
34
+ create: openaiCompat,
35
+ };
36
+ const OPENROUTER = {
37
+ type: "openrouter",
38
+ label: "OpenRouter (openrouter.ai)",
39
+ baseUrl: "https://openrouter.ai/api/v1",
40
+ capabilities: {
41
+ streaming: true,
42
+ tools: true,
43
+ vision: true,
44
+ reasoningEffort: false,
45
+ listModels: true,
46
+ requiresKey: true,
47
+ auth: "bearer",
48
+ },
49
+ create: openaiCompat,
50
+ };
51
+ const OPENAI = {
52
+ type: "openai",
53
+ label: "OpenAI API",
54
+ baseUrl: "https://api.openai.com/v1",
55
+ capabilities: {
56
+ streaming: true,
57
+ tools: true,
58
+ vision: true,
59
+ reasoningEffort: true,
60
+ listModels: true,
61
+ requiresKey: true,
62
+ auth: "bearer",
63
+ },
64
+ create: openaiCompat,
65
+ };
66
+ const ANTHROPIC = {
67
+ type: "anthropic",
68
+ label: "Anthropic Claude",
69
+ baseUrl: "https://api.anthropic.com",
70
+ capabilities: {
71
+ streaming: false,
72
+ tools: false,
73
+ vision: true,
74
+ reasoningEffort: false,
75
+ listModels: false,
76
+ requiresKey: true,
77
+ auth: "header",
78
+ },
79
+ // The Anthropic messages API is NOT OpenAI-compatible. This preset is a
80
+ // placeholder until a real AnthropicProvider lands; the factory still uses
81
+ // the OpenAI-compatible code path today (broken), flagged via capabilities.
82
+ create: openaiCompat,
83
+ };
84
+ const OPENCODE_ZEN = {
85
+ type: "opencode-zen",
86
+ label: "OpenCode Zen (opencode.ai/zen)",
87
+ baseUrl: "https://opencode.ai/zen/v1",
88
+ capabilities: {
89
+ streaming: true,
90
+ tools: true,
91
+ vision: false,
92
+ reasoningEffort: false,
93
+ listModels: true,
94
+ requiresKey: false,
95
+ auth: "bearer",
96
+ },
97
+ create: openaiCompat,
98
+ };
99
+ const OPENCODE_GO = {
100
+ type: "opencode-go",
101
+ label: "OpenCode Go (opencode.ai/go)",
102
+ baseUrl: "https://opencode.ai/zen/go/v1",
103
+ capabilities: {
104
+ streaming: true,
105
+ tools: true,
106
+ vision: false,
107
+ reasoningEffort: false,
108
+ listModels: true,
109
+ requiresKey: false,
110
+ auth: "bearer",
111
+ },
112
+ create: openaiCompat,
113
+ };
114
+ /** All builtin provider presets. */
115
+ export const BUILTIN_PROVIDERS = [
116
+ OPENAI_COMPAT,
117
+ OPENROUTER,
118
+ OPENAI,
119
+ ANTHROPIC,
120
+ OPENCODE_ZEN,
121
+ OPENCODE_GO,
122
+ ];
123
+ /** Fixed base URLs for hosted providers (no port scan / model autodetect). */
124
+ export const HOSTED_BASE_URLS = {};
125
+ for (const spec of BUILTIN_PROVIDERS) {
126
+ if (spec.baseUrl)
127
+ HOSTED_BASE_URLS[spec.type] = spec.baseUrl;
128
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Single source of truth mapping provider `type` → factory + capabilities.
3
+ * Adding a provider = one `register()` call; no changes to the agent loop.
4
+ */
5
+ export class ProviderRegistry {
6
+ specs = new Map();
7
+ register(spec) {
8
+ this.specs.set(spec.type, spec);
9
+ }
10
+ get(type) {
11
+ return this.specs.get(type);
12
+ }
13
+ has(type) {
14
+ return this.specs.has(type);
15
+ }
16
+ list() {
17
+ return [...this.specs.values()];
18
+ }
19
+ types() {
20
+ return [...this.specs.keys()];
21
+ }
22
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,48 @@
1
+ export class ModuleRegistry {
2
+ modules = new Map();
3
+ register(mod) {
4
+ this.modules.set(mod.name, mod);
5
+ return this;
6
+ }
7
+ get(name) {
8
+ return this.modules.get(name);
9
+ }
10
+ listModules() {
11
+ return Array.from(this.modules.keys()).sort();
12
+ }
13
+ collectPromptBlocks(exclude = []) {
14
+ const blocks = [];
15
+ for (const [name, mod] of this.modules) {
16
+ if (exclude.includes(name))
17
+ continue;
18
+ if (mod.getSystemPromptBlock) {
19
+ const block = mod.getSystemPromptBlock();
20
+ if (block)
21
+ blocks.push(block);
22
+ }
23
+ }
24
+ return blocks;
25
+ }
26
+ collectToolDefinitions() {
27
+ const tools = [];
28
+ for (const mod of this.modules.values()) {
29
+ if (mod.getToolDefinitions) {
30
+ const defs = mod.getToolDefinitions();
31
+ if (defs)
32
+ tools.push(...defs);
33
+ }
34
+ }
35
+ return tools;
36
+ }
37
+ collectPlugins() {
38
+ const plugins = [];
39
+ for (const mod of this.modules.values()) {
40
+ if (mod.getPlugin) {
41
+ const plugin = mod.getPlugin();
42
+ if (plugin)
43
+ plugins.push(plugin);
44
+ }
45
+ }
46
+ return plugins;
47
+ }
48
+ }
@@ -0,0 +1,136 @@
1
+ import { existsSync, mkdirSync, appendFileSync } from "fs";
2
+ import { resolve, join } from "path";
3
+ import { homedir } from "os";
4
+ import { globalAuditNotifier } from "./audit-notifier";
5
+ let _globalAuditDir = resolve(homedir(), ".mma", "logs");
6
+ let _sessionAuditDir = null;
7
+ function getAuditDir() {
8
+ return _sessionAuditDir ?? _globalAuditDir;
9
+ }
10
+ /**
11
+ * Set the session directory for audit logs. When set, all audit entries
12
+ * are written to the session-specific directory instead of the global one.
13
+ */
14
+ export function setAuditSessionDir(dir) {
15
+ _sessionAuditDir = dir;
16
+ if (!existsSync(dir)) {
17
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
18
+ }
19
+ }
20
+ /**
21
+ * Clear the session directory — fall back to global audit dir.
22
+ */
23
+ export function clearAuditSessionDir() {
24
+ _sessionAuditDir = null;
25
+ }
26
+ /**
27
+ * Set the global audit log directory (used when no session dir is active).
28
+ */
29
+ export function setGlobalAuditDir(dir) {
30
+ _globalAuditDir = dir;
31
+ if (!existsSync(dir)) {
32
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
33
+ }
34
+ }
35
+ /**
36
+ * Write an audit log entry
37
+ */
38
+ export function logAudit(entry) {
39
+ const dir = getAuditDir();
40
+ if (!existsSync(dir)) {
41
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
42
+ }
43
+ try {
44
+ const logEntry = JSON.stringify(entry);
45
+ appendFileSync(join(dir, "audit.jsonl"), logEntry + "\n", "utf8");
46
+ }
47
+ catch {
48
+ // Silently fail if we can't write to audit log
49
+ // This shouldn't break the agent
50
+ }
51
+ // Notify audit notifier if enabled
52
+ try {
53
+ globalAuditNotifier.notify(entry);
54
+ }
55
+ catch {
56
+ // Silently fail if notification fails
57
+ }
58
+ }
59
+ /**
60
+ * Log a tool call
61
+ */
62
+ export function logToolCall(sessionId, tool, success, details) {
63
+ logAudit({
64
+ timestamp: new Date().toISOString(),
65
+ sessionId,
66
+ action: "tool_call",
67
+ tool,
68
+ success,
69
+ details,
70
+ });
71
+ }
72
+ /**
73
+ * Log a file write operation
74
+ */
75
+ export function logFileWrite(sessionId, path, success, details) {
76
+ logAudit({
77
+ timestamp: new Date().toISOString(),
78
+ sessionId,
79
+ action: "file_write",
80
+ path,
81
+ success,
82
+ details,
83
+ });
84
+ }
85
+ /**
86
+ * Log a file delete operation
87
+ */
88
+ export function logFileDelete(sessionId, path, success, details) {
89
+ logAudit({
90
+ timestamp: new Date().toISOString(),
91
+ sessionId,
92
+ action: "file_delete",
93
+ path,
94
+ success,
95
+ details,
96
+ });
97
+ }
98
+ /**
99
+ * Log a bash command execution
100
+ */
101
+ export function logBashCommand(sessionId, command, success, details) {
102
+ logAudit({
103
+ timestamp: new Date().toISOString(),
104
+ sessionId,
105
+ action: "bash_command",
106
+ command,
107
+ success,
108
+ details,
109
+ });
110
+ }
111
+ /**
112
+ * Log a network request
113
+ */
114
+ export function logNetworkRequest(sessionId, url, success, details) {
115
+ logAudit({
116
+ timestamp: new Date().toISOString(),
117
+ sessionId,
118
+ action: "network_request",
119
+ url,
120
+ success,
121
+ details,
122
+ });
123
+ }
124
+ /**
125
+ * Log a security block event
126
+ */
127
+ export function logSecurityBlock(sessionId, action, reason, details) {
128
+ logAudit({
129
+ timestamp: new Date().toISOString(),
130
+ sessionId,
131
+ action: "security_block",
132
+ success: false,
133
+ reason,
134
+ details,
135
+ });
136
+ }
@@ -0,0 +1,292 @@
1
+ import { writeFileSync, appendFileSync, existsSync, mkdirSync } from "fs";
2
+ import { join, dirname } from "path";
3
+ import { homedir } from "os";
4
+ /**
5
+ * Severity weights for comparison
6
+ */
7
+ const SEVERITY_WEIGHTS = {
8
+ low: 1,
9
+ medium: 2,
10
+ high: 3,
11
+ critical: 4,
12
+ };
13
+ /**
14
+ * Default audit notifier configuration
15
+ */
16
+ export const DEFAULT_AUDIT_NOTIFIER_CONFIG = {
17
+ enabled: false,
18
+ filePath: join(homedir(), ".mma", "logs", "audit-notifications.jsonl"),
19
+ webhookTimeout: 5000,
20
+ minSeverity: "medium",
21
+ eventTypes: [
22
+ "security_block",
23
+ "bash_command",
24
+ "file_operation",
25
+ "network_request",
26
+ "authentication",
27
+ "configuration_change",
28
+ ],
29
+ maxRetries: 3,
30
+ };
31
+ /**
32
+ * Audit notifier for sending notifications about security events
33
+ */
34
+ export class AuditNotifier {
35
+ config;
36
+ retryQueue = [];
37
+ isProcessing = false;
38
+ constructor(config) {
39
+ this.config = { ...DEFAULT_AUDIT_NOTIFIER_CONFIG, ...config };
40
+ this.ensureLogDirectory();
41
+ }
42
+ /**
43
+ * Check if notifier is enabled
44
+ */
45
+ isEnabled() {
46
+ return this.config.enabled;
47
+ }
48
+ /**
49
+ * Enable the notifier
50
+ */
51
+ enable() {
52
+ this.config.enabled = true;
53
+ }
54
+ /**
55
+ * Disable the notifier
56
+ */
57
+ disable() {
58
+ this.config.enabled = false;
59
+ }
60
+ /**
61
+ * Update configuration
62
+ */
63
+ updateConfig(config) {
64
+ this.config = { ...this.config, ...config };
65
+ this.ensureLogDirectory();
66
+ }
67
+ /**
68
+ * Ensure the log directory exists
69
+ */
70
+ ensureLogDirectory() {
71
+ if (this.config.filePath) {
72
+ const dir = dirname(this.config.filePath);
73
+ mkdirSync(dir, { recursive: true });
74
+ }
75
+ }
76
+ /**
77
+ * Check if an event type should be notified
78
+ */
79
+ shouldNotify(eventType) {
80
+ if (!this.config.enabled)
81
+ return false;
82
+ return this.config.eventTypes?.includes(eventType) ?? false;
83
+ }
84
+ /**
85
+ * Check if a severity level should be notified
86
+ */
87
+ shouldNotifySeverity(severity) {
88
+ const minSeverity = this.config.minSeverity ?? "medium";
89
+ const minWeight = SEVERITY_WEIGHTS[minSeverity];
90
+ const eventWeight = SEVERITY_WEIGHTS[severity];
91
+ return eventWeight >= minWeight;
92
+ }
93
+ /**
94
+ * Send a notification for an audit event
95
+ */
96
+ async notify(entry) {
97
+ if (!this.config.enabled)
98
+ return null;
99
+ const eventType = this.mapEventType(entry.action);
100
+ if (!eventType || !this.shouldNotify(eventType))
101
+ return null;
102
+ const severity = this.determineSeverity(entry);
103
+ if (!this.shouldNotifySeverity(severity))
104
+ return null;
105
+ const notification = {
106
+ timestamp: new Date().toISOString(),
107
+ eventType,
108
+ severity,
109
+ message: entry.details || entry.reason || entry.action,
110
+ details: entry.details ? { details: entry.details } : undefined,
111
+ sessionId: entry.sessionId,
112
+ };
113
+ // Write to file
114
+ this.writeToFile(notification);
115
+ // Send to webhook if configured
116
+ if (this.config.webhookUrl) {
117
+ await this.sendToWebhook(notification);
118
+ }
119
+ return notification;
120
+ }
121
+ /**
122
+ * Map audit log entry action to notification event type
123
+ */
124
+ mapEventType(action) {
125
+ const typeMap = {
126
+ tool_call: "tool_call",
127
+ bash_command: "bash_command",
128
+ file_write: "file_operation",
129
+ file_delete: "file_operation",
130
+ network_request: "network_request",
131
+ security_block: "security_block",
132
+ };
133
+ return typeMap[action] || null;
134
+ }
135
+ /**
136
+ * Determine severity from audit log entry
137
+ */
138
+ determineSeverity(entry) {
139
+ // Default severity based on action type
140
+ const typeSeverity = {
141
+ security_block: "high",
142
+ bash_command: "high",
143
+ file_delete: "medium",
144
+ file_write: "medium",
145
+ network_request: "medium",
146
+ tool_call: "low",
147
+ session_start: "low",
148
+ session_end: "low",
149
+ };
150
+ return typeSeverity[entry.action] || "low";
151
+ }
152
+ /**
153
+ * Write notification to file
154
+ */
155
+ writeToFile(notification) {
156
+ if (!this.config.filePath)
157
+ return;
158
+ try {
159
+ const line = JSON.stringify(notification);
160
+ appendFileSync(this.config.filePath, line + "\n", "utf8");
161
+ }
162
+ catch (error) {
163
+ console.error("[AuditNotifier] Failed to write to file:", error);
164
+ }
165
+ }
166
+ /**
167
+ * Send notification to webhook
168
+ */
169
+ async sendToWebhook(notification) {
170
+ if (!this.config.webhookUrl)
171
+ return;
172
+ try {
173
+ const controller = new AbortController();
174
+ const timeoutId = setTimeout(() => controller.abort(), this.config.webhookTimeout);
175
+ const response = await fetch(this.config.webhookUrl, {
176
+ method: "POST",
177
+ headers: { "Content-Type": "application/json" },
178
+ body: JSON.stringify(notification),
179
+ signal: controller.signal,
180
+ });
181
+ clearTimeout(timeoutId);
182
+ if (!response.ok) {
183
+ throw new Error(`Webhook returned ${response.status}`);
184
+ }
185
+ }
186
+ catch (error) {
187
+ console.error("[AuditNotifier] Webhook failed, adding to retry queue:", error);
188
+ this.addToRetryQueue(notification);
189
+ }
190
+ }
191
+ /**
192
+ * Add notification to retry queue
193
+ */
194
+ addToRetryQueue(notification) {
195
+ this.retryQueue.push({ entry: notification, retries: 0 });
196
+ if (!this.isProcessing) {
197
+ this.processRetryQueue();
198
+ }
199
+ }
200
+ /**
201
+ * Process the retry queue
202
+ */
203
+ async processRetryQueue() {
204
+ if (this.retryQueue.length === 0 || this.isProcessing)
205
+ return;
206
+ this.isProcessing = true;
207
+ while (this.retryQueue.length > 0) {
208
+ const item = this.retryQueue[0];
209
+ if (item.retries >= (this.config.maxRetries ?? 3)) {
210
+ console.error("[AuditNotifier] Max retries exceeded for notification:", item.entry);
211
+ this.retryQueue.shift();
212
+ continue;
213
+ }
214
+ try {
215
+ await this.sendToWebhook(item.entry);
216
+ this.retryQueue.shift();
217
+ }
218
+ catch (error) {
219
+ item.retries++;
220
+ // Exponential backoff
221
+ const delay = Math.pow(2, item.retries) * 1000;
222
+ await new Promise((resolve) => setTimeout(resolve, delay));
223
+ }
224
+ }
225
+ this.isProcessing = false;
226
+ }
227
+ /**
228
+ * Read notifications from file
229
+ */
230
+ readNotifications(limit = 100) {
231
+ if (!this.config.filePath || !existsSync(this.config.filePath)) {
232
+ return [];
233
+ }
234
+ try {
235
+ const content = readFileSync(this.config.filePath, "utf8");
236
+ const lines = content.split("\n").filter(Boolean);
237
+ return lines.slice(-limit).map((line) => JSON.parse(line));
238
+ }
239
+ catch {
240
+ return [];
241
+ }
242
+ }
243
+ /**
244
+ * Clear all notifications
245
+ */
246
+ clearNotifications() {
247
+ if (this.config.filePath) {
248
+ writeFileSync(this.config.filePath, "", "utf8");
249
+ }
250
+ this.retryQueue = [];
251
+ }
252
+ /**
253
+ * Get notification statistics
254
+ */
255
+ getStats() {
256
+ const notifications = this.readNotifications();
257
+ const bySeverity = { low: 0, medium: 0, high: 0, critical: 0 };
258
+ const byType = {
259
+ tool_call: 0,
260
+ tool_result: 0,
261
+ bash_command: 0,
262
+ file_operation: 0,
263
+ network_request: 0,
264
+ security_block: 0,
265
+ authentication: 0,
266
+ configuration_change: 0,
267
+ session_start: 0,
268
+ session_end: 0,
269
+ };
270
+ for (const n of notifications) {
271
+ bySeverity[n.severity] = (bySeverity[n.severity] || 0) + 1;
272
+ byType[n.eventType] = (byType[n.eventType] || 0) + 1;
273
+ }
274
+ return {
275
+ total: notifications.length,
276
+ bySeverity,
277
+ byType,
278
+ };
279
+ }
280
+ }
281
+ /**
282
+ * Global audit notifier instance
283
+ */
284
+ export const globalAuditNotifier = new AuditNotifier();
285
+ /**
286
+ * Create an audit notifier with custom configuration
287
+ */
288
+ export function createAuditNotifier(config) {
289
+ return new AuditNotifier(config);
290
+ }
291
+ // Import readFileSync for readNotifications
292
+ import { readFileSync } from "fs";