micro-models-agent 0.28.9 → 0.29.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 (167) hide show
  1. package/dist/cli/commands.js +220 -0
  2. package/dist/cli/completer.js +168 -0
  3. package/dist/cli/index.js +2 -0
  4. package/dist/cli/main.js +113 -0
  5. package/dist/cli/repl.js +987 -0
  6. package/dist/cli/security-commands.js +166 -0
  7. package/dist/cli/setup.js +229 -0
  8. package/dist/config/config.js +186 -0
  9. package/dist/config/defaults.js +91 -0
  10. package/dist/config/experts.js +15 -0
  11. package/dist/config/index.js +3 -0
  12. package/dist/config/security.js +193 -0
  13. package/dist/config/types.js +1 -0
  14. package/dist/core/agent-moe.js +98 -0
  15. package/dist/core/agent.js +461 -0
  16. package/dist/core/bootstrap.js +321 -0
  17. package/dist/core/index.js +2 -0
  18. package/dist/core/prompt-builder.js +55 -0
  19. package/dist/core/session-logger.js +122 -0
  20. package/dist/core/types.js +1 -0
  21. package/dist/i18n/en.json +461 -0
  22. package/dist/i18n/index.js +43 -0
  23. package/dist/i18n/ru.json +461 -0
  24. package/dist/index.js +22 -0
  25. package/dist/llm/image-utils.js +144 -0
  26. package/dist/llm/index.js +4 -0
  27. package/dist/llm/model-loader.js +78 -0
  28. package/dist/llm/openai-compat.js +324 -0
  29. package/dist/llm/orchestrator.js +194 -0
  30. package/dist/llm/provider.js +10 -0
  31. package/dist/llm/response.js +39 -0
  32. package/dist/llm/token-counter.js +39 -0
  33. package/dist/llm/types.js +1 -0
  34. package/dist/logger/app-logger.js +76 -0
  35. package/dist/logger/index.js +1 -0
  36. package/dist/main.js +2251 -724
  37. package/dist/migration/backup.js +45 -0
  38. package/dist/migration/detect.js +50 -0
  39. package/dist/migration/index.js +2 -0
  40. package/dist/modules/browser/actions.js +46 -0
  41. package/dist/modules/browser/cookie-store.js +24 -0
  42. package/dist/modules/browser/index.js +5 -0
  43. package/dist/modules/browser/module.js +28 -0
  44. package/dist/modules/browser/session.js +287 -0
  45. package/dist/modules/browser/snapshot.js +114 -0
  46. package/dist/modules/browser/types.js +9 -0
  47. package/dist/modules/context/history.js +15 -0
  48. package/dist/modules/context/index.js +1 -0
  49. package/dist/modules/context/manager.js +240 -0
  50. package/dist/modules/execution/auditor.js +72 -0
  51. package/dist/modules/execution/index.js +6 -0
  52. package/dist/modules/execution/module.js +337 -0
  53. package/dist/modules/execution/moe-executor.js +209 -0
  54. package/dist/modules/execution/plan-validator.js +153 -0
  55. package/dist/modules/execution/planner.js +35 -0
  56. package/dist/modules/execution/stuck-detector.js +134 -0
  57. package/dist/modules/execution/tracker.js +53 -0
  58. package/dist/modules/execution/types.js +1 -0
  59. package/dist/modules/execution/verifier.js +149 -0
  60. package/dist/modules/hallucination/confidence.js +54 -0
  61. package/dist/modules/hallucination/consistency.js +60 -0
  62. package/dist/modules/hallucination/detector.js +41 -0
  63. package/dist/modules/hallucination/factual.js +170 -0
  64. package/dist/modules/hallucination/index.js +4 -0
  65. package/dist/modules/index.js +5 -0
  66. package/dist/modules/indexer/cache.js +38 -0
  67. package/dist/modules/indexer/index.js +3 -0
  68. package/dist/modules/indexer/module.js +192 -0
  69. package/dist/modules/indexer/walker.js +101 -0
  70. package/dist/modules/mcp/client.js +393 -0
  71. package/dist/modules/mcp/index.js +3 -0
  72. package/dist/modules/mcp/module.js +146 -0
  73. package/dist/modules/mcp/registry.js +15 -0
  74. package/dist/modules/memory/index.js +1 -0
  75. package/dist/modules/memory/module.js +48 -0
  76. package/dist/modules/memory/search.js +40 -0
  77. package/dist/modules/memory/store.js +65 -0
  78. package/dist/modules/pipelines/engine.js +60 -0
  79. package/dist/modules/pipelines/index.js +3 -0
  80. package/dist/modules/pipelines/parser.js +53 -0
  81. package/dist/modules/pipelines/template.js +14 -0
  82. package/dist/modules/plugins/builtin/lint-on-write.js +121 -0
  83. package/dist/modules/plugins/builtin/notify.js +8 -0
  84. package/dist/modules/plugins/index.js +1 -0
  85. package/dist/modules/plugins/loader.js +28 -0
  86. package/dist/modules/plugins/manager.js +161 -0
  87. package/dist/modules/plugins/types.js +1 -0
  88. package/dist/modules/processes/detect.js +34 -0
  89. package/dist/modules/processes/index.js +3 -0
  90. package/dist/modules/processes/registry.js +148 -0
  91. package/dist/modules/processes/runner.js +124 -0
  92. package/dist/modules/registry.js +45 -0
  93. package/dist/modules/security/audit-log.js +116 -0
  94. package/dist/modules/security/audit-notifier.js +292 -0
  95. package/dist/modules/security/command-validator.js +185 -0
  96. package/dist/modules/security/content-scanner.js +52 -0
  97. package/dist/modules/security/data-sanitizer.js +97 -0
  98. package/dist/modules/security/encryption.js +240 -0
  99. package/dist/modules/security/index.js +14 -0
  100. package/dist/modules/security/network-validator.js +79 -0
  101. package/dist/modules/security/path-validator.js +155 -0
  102. package/dist/modules/security/rate-limiter.js +119 -0
  103. package/dist/modules/security/security-policies.js +393 -0
  104. package/dist/modules/security/session-encryption.js +193 -0
  105. package/dist/modules/security/session-isolation.js +95 -0
  106. package/dist/modules/session/index.js +3 -0
  107. package/dist/modules/session/manager.js +167 -0
  108. package/dist/modules/session/module.js +24 -0
  109. package/dist/modules/session/store.js +174 -0
  110. package/dist/modules/session/types.js +1 -0
  111. package/dist/modules/skills/index.js +3 -0
  112. package/dist/modules/skills/loader.js +72 -0
  113. package/dist/modules/skills/matcher.js +27 -0
  114. package/dist/modules/skills/module.js +143 -0
  115. package/dist/modules/types.js +1 -0
  116. package/dist/modules/updater/checker.js +32 -0
  117. package/dist/modules/updater/index.js +1 -0
  118. package/dist/modules/user-profile/compressor.js +16 -0
  119. package/dist/modules/user-profile/index.js +1 -0
  120. package/dist/modules/user-profile/profile.js +68 -0
  121. package/dist/tools/approve.js +32 -0
  122. package/dist/tools/attach-image.js +89 -0
  123. package/dist/tools/bash.js +140 -0
  124. package/dist/tools/browser.js +97 -0
  125. package/dist/tools/create-dir.js +56 -0
  126. package/dist/tools/delete-file.js +63 -0
  127. package/dist/tools/edit-file.js +77 -0
  128. package/dist/tools/executor.js +95 -0
  129. package/dist/tools/file-info.js +45 -0
  130. package/dist/tools/filter-tools.js +10 -0
  131. package/dist/tools/glob-tool.js +26 -0
  132. package/dist/tools/grep-tool.js +64 -0
  133. package/dist/tools/index.js +52 -0
  134. package/dist/tools/list-dir.js +47 -0
  135. package/dist/tools/load-skill.js +48 -0
  136. package/dist/tools/mcp-call.js +68 -0
  137. package/dist/tools/move-file.js +84 -0
  138. package/dist/tools/path-utils.js +51 -0
  139. package/dist/tools/pipeline-run.js +144 -0
  140. package/dist/tools/preview.js +2 -0
  141. package/dist/tools/process-kill.js +29 -0
  142. package/dist/tools/process-list.js +38 -0
  143. package/dist/tools/process-log.js +41 -0
  144. package/dist/tools/question.js +142 -0
  145. package/dist/tools/read-file.js +73 -0
  146. package/dist/tools/recall.js +110 -0
  147. package/dist/tools/registry.js +36 -0
  148. package/dist/tools/remember.js +67 -0
  149. package/dist/tools/scope-check.js +30 -0
  150. package/dist/tools/search-history.js +64 -0
  151. package/dist/tools/subagent.js +142 -0
  152. package/dist/tools/types.js +1 -0
  153. package/dist/tools/user-input.js +123 -0
  154. package/dist/tools/web-browse.js +57 -0
  155. package/dist/tools/web-fetch.js +72 -0
  156. package/dist/tools/web-search.js +59 -0
  157. package/dist/tools/write-file.js +80 -0
  158. package/dist/ui/box.js +81 -0
  159. package/dist/ui/colors.js +4 -0
  160. package/dist/ui/diff.js +185 -0
  161. package/dist/ui/index.js +6 -0
  162. package/dist/ui/md-formatter.js +212 -0
  163. package/dist/ui/output.js +13 -0
  164. package/dist/ui/renderer.js +141 -0
  165. package/dist/ui/spinner.js +70 -0
  166. package/dist/ui/table.js +144 -0
  167. package/package.json +4 -4
@@ -0,0 +1,166 @@
1
+ import { bootstrap } from "../core/bootstrap";
2
+ import { saveConfig } from "../config/config";
3
+ import { join } from "path";
4
+ import { homedir } from "os";
5
+ import { SECURITY_POLICIES, applySecurityPolicy, getSecurityPolicy, } from "../modules/security/security-policies";
6
+ import { globalAuditNotifier } from "../modules/security/audit-notifier";
7
+ import { t } from "../i18n/index";
8
+ /**
9
+ * Create security subcommand
10
+ */
11
+ export function createSecurityCommand(program) {
12
+ const securityCmd = program
13
+ .command("security")
14
+ .description(t("cli.security.description"));
15
+ // security status - show current security configuration
16
+ securityCmd
17
+ .command("status")
18
+ .description(t("cli.security.status"))
19
+ .action(async () => {
20
+ const { config } = await bootstrap();
21
+ const security = config.security || {};
22
+ const bash = security.bash || {};
23
+ const paths = security.paths || {};
24
+ const network = security.network || {};
25
+ const contentScan = security.contentScan || {};
26
+ const rateLimits = security.rateLimits || {};
27
+ const sessionEncryption = security.sessionEncryption || {};
28
+ const auditNotifier = security.auditNotifier || {};
29
+ console.log(t("cli.security.current_policy"));
30
+ console.log(` ${t("cli.security.bash_enabled")}: ${bash.blacklist?.length > 0 ? t("cli.yes") : t("cli.no")}`);
31
+ console.log(` ${t("cli.security.path_validation")}: ${paths.denied?.length > 0 ? t("cli.yes") : t("cli.no")}`);
32
+ console.log(` ${t("cli.security.network_validation")}: ${network.deniedDomains?.length > 0 || network.allowedDomains?.length > 0 ? t("cli.yes") : t("cli.no")}`);
33
+ console.log(` ${t("cli.security.content_scanning")}: ${contentScan.enabled ? t("cli.yes") : t("cli.no")}`);
34
+ console.log(` ${t("cli.security.max_recursion")}: ${security.maxRecursionDepth ?? 3}`);
35
+ console.log(` ${t("cli.security.max_file_ops")}: ${security.maxFileOperations ?? 100}`);
36
+ console.log(` ${t("cli.security.rate_limit")}: ${rateLimits.maxRequestsPerMinute ?? 60}/min`);
37
+ console.log(` ${t("cli.security.session_encryption")}: ${sessionEncryption.enabled ? t("cli.yes") : t("cli.no")}`);
38
+ console.log(` ${t("cli.security.audit_notifier")}: ${auditNotifier.enabled ? t("cli.yes") : t("cli.no")}`);
39
+ });
40
+ // security policies - manage security policies
41
+ securityCmd
42
+ .command("policies")
43
+ .description(t("cli.security.policies"))
44
+ .action(async () => {
45
+ console.log(t("cli.security.available_policies"));
46
+ console.log("");
47
+ for (const [preset, policy] of Object.entries(SECURITY_POLICIES)) {
48
+ if (preset === 'custom')
49
+ continue;
50
+ const marker = " ";
51
+ console.log(` ${marker}${preset.padEnd(12)} ${policy.name}`);
52
+ console.log(` ${policy.description}`);
53
+ console.log(` ${t("cli.security.recommended_for")}: ${policy.recommendedFor.join(", ")}`);
54
+ console.log("");
55
+ }
56
+ });
57
+ // security set-policy - apply a security policy
58
+ securityCmd
59
+ .command("set-policy")
60
+ .argument("<preset>", t("cli.security.preset"))
61
+ .description(t("cli.security.set_policy"))
62
+ .action(async (preset) => {
63
+ const configPath = join(homedir(), ".mma", "config.json");
64
+ const { config: appConfig } = await bootstrap();
65
+ const validPresets = ['strict', 'balanced', 'permissive'];
66
+ if (!validPresets.includes(preset)) {
67
+ console.log(t("cli.security.invalid_preset", { presets: validPresets.join(", ") }));
68
+ return;
69
+ }
70
+ const policy = getSecurityPolicy(preset);
71
+ const newSecurityConfig = applySecurityPolicy(preset);
72
+ // Merge with existing config
73
+ appConfig.security = newSecurityConfig;
74
+ saveConfig(appConfig, configPath);
75
+ console.log(t("cli.security.policy_applied", { name: policy.name }));
76
+ console.log(t("cli.security.policy_description", { description: policy.description }));
77
+ });
78
+ // security enable-encryption - enable session file encryption
79
+ securityCmd
80
+ .command("enable-encryption")
81
+ .description(t("cli.security.enable_encryption"))
82
+ .action(async () => {
83
+ const configPath = join(homedir(), ".mma", "config.json");
84
+ const { config: appConfig } = await bootstrap();
85
+ appConfig.security = appConfig.security || {};
86
+ appConfig.security.sessionEncryption = {
87
+ enabled: true,
88
+ encryptHistory: true,
89
+ encryptSessionLog: true,
90
+ };
91
+ saveConfig(appConfig, configPath);
92
+ console.log(t("cli.security.encryption_enabled"));
93
+ });
94
+ // security disable-encryption - disable session file encryption
95
+ securityCmd
96
+ .command("disable-encryption")
97
+ .description(t("cli.security.disable_encryption"))
98
+ .action(async () => {
99
+ const configPath = join(homedir(), ".mma", "config.json");
100
+ const { config: appConfig } = await bootstrap();
101
+ appConfig.security = appConfig.security || {};
102
+ appConfig.security.sessionEncryption = {
103
+ enabled: false,
104
+ encryptHistory: false,
105
+ encryptSessionLog: false,
106
+ };
107
+ saveConfig(appConfig, configPath);
108
+ console.log(t("cli.security.encryption_disabled"));
109
+ });
110
+ // security enable-audit - enable audit notifications
111
+ securityCmd
112
+ .command("enable-audit")
113
+ .description(t("cli.security.enable_audit"))
114
+ .action(async () => {
115
+ const configPath = join(homedir(), ".mma", "config.json");
116
+ const { config: appConfig } = await bootstrap();
117
+ appConfig.security = appConfig.security || {};
118
+ appConfig.security.auditNotifier = {
119
+ enabled: true,
120
+ minSeverity: 'medium',
121
+ eventTypes: ['security_block', 'bash_command', 'file_operation', 'network_request'],
122
+ maxRetries: 3,
123
+ webhookTimeout: 5000,
124
+ };
125
+ saveConfig(appConfig, configPath);
126
+ console.log(t("cli.security.audit_enabled"));
127
+ });
128
+ // security disable-audit - disable audit notifications
129
+ securityCmd
130
+ .command("disable-audit")
131
+ .description(t("cli.security.disable_audit"))
132
+ .action(async () => {
133
+ const configPath = join(homedir(), ".mma", "config.json");
134
+ const { config: appConfig } = await bootstrap();
135
+ appConfig.security = appConfig.security || {};
136
+ appConfig.security.auditNotifier = {
137
+ enabled: false,
138
+ maxRetries: 3,
139
+ webhookTimeout: 5000,
140
+ };
141
+ saveConfig(appConfig, configPath);
142
+ console.log(t("cli.security.audit_disabled"));
143
+ });
144
+ // security audit-stats - show audit notification statistics
145
+ securityCmd
146
+ .command("audit-stats")
147
+ .description(t("cli.security.audit_stats"))
148
+ .action(async () => {
149
+ const stats = globalAuditNotifier.getStats();
150
+ console.log(t("cli.security.audit_stats_title"));
151
+ console.log(` ${t("cli.security.total_notifications")}: ${stats.total}`);
152
+ console.log("");
153
+ console.log(t("cli.security.by_severity"));
154
+ console.log(` ${t("cli.security.low")}: ${stats.bySeverity.low}`);
155
+ console.log(` ${t("cli.security.medium")}: ${stats.bySeverity.medium}`);
156
+ console.log(` ${t("cli.security.high")}: ${stats.bySeverity.high}`);
157
+ console.log(` ${t("cli.security.critical")}: ${stats.bySeverity.critical}`);
158
+ console.log("");
159
+ console.log(t("cli.security.by_type"));
160
+ for (const [type, count] of Object.entries(stats.byType)) {
161
+ if (count > 0) {
162
+ console.log(` ${type}: ${count}`);
163
+ }
164
+ }
165
+ });
166
+ }
@@ -0,0 +1,229 @@
1
+ import * as readline from "readline";
2
+ import { pc } from "../ui/colors";
3
+ import { t, setLocale } from "../i18n/index";
4
+ import { Spinner } from "../ui/spinner";
5
+ import { box } from "../ui/box";
6
+ import { renderTable } from "../ui/table";
7
+ async function withSpinner(message, fn) {
8
+ const spinner = new Spinner();
9
+ spinner.start(message);
10
+ try {
11
+ return await fn();
12
+ }
13
+ finally {
14
+ spinner.stop();
15
+ }
16
+ }
17
+ /** Render a numbered list inside a box. */
18
+ function menuList(items) {
19
+ const lines = items.map((it, i) => ` ${pc.cyan(`[${i + 1}]`)} ${it.label}${it.url ? ` ${pc.dim(it.url)}` : ""}`);
20
+ for (const l of box(lines, { width: 72 }))
21
+ console.log(l);
22
+ }
23
+ function ask(rl, question, defaultValue) {
24
+ return new Promise((resolve) => {
25
+ const prompt = defaultValue
26
+ ? `${question} [${defaultValue}]: `
27
+ : `${question}: `;
28
+ rl.question(prompt, (answer) => {
29
+ resolve(answer.trim() || defaultValue || "");
30
+ });
31
+ });
32
+ }
33
+ const PROVIDER_TYPES = [
34
+ {
35
+ value: "openai-compat",
36
+ label: "OpenAI-compatible (LM Studio, Ollama, vLLM, etc.)",
37
+ },
38
+ { value: "openai", label: "OpenAI API" },
39
+ { value: "anthropic", label: "Anthropic Claude" },
40
+ ];
41
+ const KNOWN_PORTS = [
42
+ { port: 1234, label: "LM Studio" },
43
+ { port: 11434, label: "Ollama" },
44
+ { port: 8080, label: "vLLM / custom" },
45
+ { port: 4891, label: "GPT4All" },
46
+ ];
47
+ async function scanPorts() {
48
+ const found = [];
49
+ for (const { port, label } of KNOWN_PORTS) {
50
+ try {
51
+ const controller = new AbortController();
52
+ const timeout = setTimeout(() => controller.abort(), 2000);
53
+ const resp = await fetch(`http://localhost:${port}/v1/models`, {
54
+ signal: controller.signal,
55
+ });
56
+ clearTimeout(timeout);
57
+ if (resp.ok) {
58
+ found.push({ label, url: `http://localhost:${port}/v1` });
59
+ }
60
+ }
61
+ catch {
62
+ /* port not available */
63
+ }
64
+ }
65
+ return found;
66
+ }
67
+ async function fetchModels(apiBase, apiKey) {
68
+ try {
69
+ const url = `${apiBase.replace(/\/+$/, "")}/models`;
70
+ const controller = new AbortController();
71
+ const timeout = setTimeout(() => controller.abort(), 5000);
72
+ const resp = await fetch(url, {
73
+ headers: {
74
+ Authorization: `Bearer ${apiKey}`,
75
+ "Content-Type": "application/json",
76
+ },
77
+ signal: controller.signal,
78
+ });
79
+ clearTimeout(timeout);
80
+ if (!resp.ok)
81
+ return [];
82
+ const data = (await resp.json());
83
+ const models = (data.data || data || [])
84
+ .map((m) => m.id || m.name || m.model || "")
85
+ .filter(Boolean);
86
+ return models;
87
+ }
88
+ catch {
89
+ return [];
90
+ }
91
+ }
92
+ async function testChat(apiBase, apiKey, model) {
93
+ try {
94
+ const url = `${apiBase.replace(/\/+$/, "")}/chat/completions`;
95
+ const controller = new AbortController();
96
+ const timeout = setTimeout(() => controller.abort(), 10000);
97
+ const resp = await fetch(url, {
98
+ method: "POST",
99
+ headers: {
100
+ Authorization: `Bearer ${apiKey}`,
101
+ "Content-Type": "application/json",
102
+ },
103
+ body: JSON.stringify({
104
+ model,
105
+ messages: [{ role: "user", content: 'Say "ok"' }],
106
+ max_tokens: 20,
107
+ }),
108
+ signal: controller.signal,
109
+ });
110
+ clearTimeout(timeout);
111
+ if (!resp.ok)
112
+ return false;
113
+ const data = (await resp.json());
114
+ const msg = data.choices?.[0]?.message;
115
+ const text = msg?.content || msg?.reasoning_content || "";
116
+ return text.length > 0;
117
+ }
118
+ catch {
119
+ return false;
120
+ }
121
+ }
122
+ export async function runSetup() {
123
+ console.log(t("setup.title"));
124
+ const rl = readline.createInterface({
125
+ input: process.stdin,
126
+ output: process.stdout,
127
+ });
128
+ console.log(t("setup.language"));
129
+ const locale = await ask(rl, t("setup.ui_lang"), "en");
130
+ setLocale(locale);
131
+ console.log(t("setup.select_provider"));
132
+ menuList(PROVIDER_TYPES);
133
+ const providerChoice = await ask(rl, t("setup.select_provider_num", { max: PROVIDER_TYPES.length }), "1");
134
+ const providerIdx = Math.max(0, Math.min(PROVIDER_TYPES.length - 1, (parseInt(providerChoice) || 1) - 1));
135
+ const provider = PROVIDER_TYPES[providerIdx].value;
136
+ let apiBase = "";
137
+ if (provider === "openai-compat") {
138
+ const found = await withSpinner(t("setup.scanning_spinner"), async () => scanPorts());
139
+ if (found.length > 0) {
140
+ console.log(t("setup.found_servers", { count: found.length }));
141
+ menuList([
142
+ ...found.map((f) => ({ label: f.label, url: f.url })),
143
+ { label: t("setup.custom_url") },
144
+ ]);
145
+ const choice = await ask(rl, t("setup.select_server", { max: found.length + 1 }), "1");
146
+ const idx = (parseInt(choice) || 1) - 1;
147
+ if (idx >= found.length) {
148
+ apiBase = await ask(rl, t("setup.api_base"), "http://localhost:1234/v1");
149
+ }
150
+ else {
151
+ apiBase = found[Math.max(0, Math.min(found.length - 1, idx))].url;
152
+ }
153
+ }
154
+ else {
155
+ console.log(t("setup.no_servers"));
156
+ apiBase = await ask(rl, t("setup.api_base"), "http://localhost:1234/v1");
157
+ }
158
+ }
159
+ else if (provider === "openai") {
160
+ apiBase = "https://api.openai.com/v1";
161
+ }
162
+ else if (provider === "anthropic") {
163
+ apiBase = "https://api.anthropic.com";
164
+ }
165
+ const defaultKey = provider === "openai-compat" ? "not-needed" : "";
166
+ const apiKey = await ask(rl, t("setup.api_key"), defaultKey);
167
+ const models = await withSpinner(t("setup.fetching_spinner"), () => fetchModels(apiBase, apiKey));
168
+ let model = "";
169
+ if (models.length > 0) {
170
+ console.log(t("setup.available_models"));
171
+ menuList(models.slice(0, 10).map((m) => ({ label: m })));
172
+ const choice = await ask(rl, t("setup.select_model", { max: Math.min(models.length, 10) }), "1");
173
+ const idx = Math.max(0, Math.min(models.length - 1, (parseInt(choice) || 1) - 1));
174
+ model = models[idx];
175
+ }
176
+ else {
177
+ model = await ask(rl, t("setup.model_name"), "qwen3.5-9b");
178
+ }
179
+ const connected = await withSpinner(t("setup.testing_spinner", { model }), () => testChat(apiBase, apiKey, model));
180
+ if (connected) {
181
+ console.log(pc.green(t("setup.ok")));
182
+ }
183
+ else {
184
+ console.log(pc.yellow(t("setup.warning")));
185
+ }
186
+ console.log(t("setup.agent_settings"));
187
+ const contextWindow = parseInt(await ask(rl, t("setup.context_window"), "32768"));
188
+ const maxIterations = parseInt(await ask(rl, t("setup.max_iters"), "1000"));
189
+ // Security settings
190
+ console.log(t("setup.security_header"));
191
+ console.log(pc.dim(t("setup.security_status_off")));
192
+ const configureSecurity = await ask(rl, t("setup.security_configure"), "n");
193
+ let securityBashBlock = false;
194
+ let securityFlagsBlock = false;
195
+ let securityPathsDeny = true;
196
+ if (configureSecurity.toLowerCase() === "y" || configureSecurity.toLowerCase() === "yes") {
197
+ securityBashBlock = (await ask(rl, t("setup.security_bash_block"), "n")).toLowerCase() === "y";
198
+ securityFlagsBlock = (await ask(rl, t("setup.security_flags_block"), "n")).toLowerCase() === "y";
199
+ securityPathsDeny = (await ask(rl, t("setup.security_paths_deny"), "Y")).toLowerCase() !== "n";
200
+ }
201
+ rl.close();
202
+ const answers = {
203
+ provider,
204
+ apiBase,
205
+ apiKey: apiKey || "not-needed",
206
+ model,
207
+ contextWindow,
208
+ maxToolIterations: maxIterations,
209
+ locale,
210
+ securityBashBlock,
211
+ securityFlagsBlock,
212
+ securityPathsDeny,
213
+ };
214
+ console.log(pc.green(pc.bold(t("setup.complete"))));
215
+ const summary = renderTable([
216
+ t("setup.summary_setting"),
217
+ t("setup.summary_value"),
218
+ t("setup.summary_setting"),
219
+ t("setup.summary_value"),
220
+ ], [
221
+ [t("setup.provider_type"), provider, t("setup.model_name"), model],
222
+ ["API Base URL", apiBase, t("setup.context_window"), String(contextWindow)],
223
+ [t("setup.api_key"), apiKey || "not-needed", t("setup.max_iters"), String(maxIterations)],
224
+ [t("setup.ui_lang"), locale, "", ""],
225
+ ], { maxColumns: 4 });
226
+ for (const l of summary)
227
+ console.log(l);
228
+ return answers;
229
+ }
@@ -0,0 +1,186 @@
1
+ import { existsSync, readFileSync, unlinkSync, writeFileSync, mkdirSync } from 'fs';
2
+ import { join, dirname } from 'path';
3
+ import { DEFAULTS } from './defaults';
4
+ import { DEFAULT_SECURITY_CONFIG } from './security';
5
+ import { t } from '../i18n/index';
6
+ import { MigrationDetector } from '../migration/detect';
7
+ import { BackupManager } from '../migration/backup';
8
+ import { validateExpertConfig } from './experts';
9
+ import { ConfigEncryptor } from '../modules/security/encryption';
10
+ /**
11
+ * Restore RegExp instances in dangerousPatterns that were serialized as {}
12
+ * (pre-0.8.0 configs) or as {__regex, source, flags} (new format).
13
+ * Falls back to default patterns for any entry that is not a real RegExp.
14
+ */
15
+ function restoreDangerousPatterns(patterns, defaults) {
16
+ const fallback = (Array.isArray(defaults) ? defaults : []);
17
+ if (!Array.isArray(patterns) || patterns.length === 0) {
18
+ return fallback;
19
+ }
20
+ return patterns.map((p, i) => {
21
+ if (p instanceof RegExp)
22
+ return p;
23
+ // If the pattern was serialized as {__regex, source, flags}, revive it
24
+ if (p && typeof p === "object") {
25
+ const { source, flags } = p;
26
+ if (source && typeof source === "string") {
27
+ try {
28
+ return new RegExp(source, flags || "");
29
+ }
30
+ catch {
31
+ // fall through
32
+ }
33
+ }
34
+ }
35
+ // Corrupted entry (e.g. serialized as {} pre-0.8.0): use default by index
36
+ return fallback[i] || fallback[0] || p;
37
+ });
38
+ }
39
+ function deepMerge(target, source) {
40
+ const result = { ...target };
41
+ for (const key of Object.keys(source)) {
42
+ const srcVal = source[key];
43
+ const tgtVal = target[key];
44
+ if (srcVal !== null && srcVal !== undefined &&
45
+ typeof srcVal === 'object' && !Array.isArray(srcVal) &&
46
+ typeof tgtVal === 'object' && !Array.isArray(tgtVal)) {
47
+ result[key] = deepMerge(tgtVal, srcVal);
48
+ }
49
+ else if (srcVal !== undefined) {
50
+ result[key] = srcVal;
51
+ }
52
+ }
53
+ return result;
54
+ }
55
+ /**
56
+ * JSON replacer that serializes RegExp objects as {__regex, source, flags}
57
+ * so they survive JSON.stringify/parse round-trips.
58
+ */
59
+ function regexReplacer(_key, value) {
60
+ if (value instanceof RegExp) {
61
+ return { __regex: true, source: value.source, flags: value.flags };
62
+ }
63
+ return value;
64
+ }
65
+ /**
66
+ * JSON reviver that restores RegExp objects serialized by regexReplacer.
67
+ */
68
+ function regexReviver(_key, value) {
69
+ if (value &&
70
+ typeof value === "object" &&
71
+ value.__regex === true) {
72
+ const { source, flags } = value;
73
+ try {
74
+ return new RegExp(source, flags);
75
+ }
76
+ catch {
77
+ return value;
78
+ }
79
+ }
80
+ return value;
81
+ }
82
+ function loadJSON(path) {
83
+ try {
84
+ if (existsSync(path)) {
85
+ return JSON.parse(readFileSync(path, 'utf-8'), regexReviver);
86
+ }
87
+ }
88
+ catch { /* ignore malformed files */ }
89
+ return null;
90
+ }
91
+ function applyEnvVars(config) {
92
+ const env = process.env;
93
+ const result = { ...config };
94
+ if (env.MMA_MODEL)
95
+ result.model = env.MMA_MODEL;
96
+ if (env.MMA_PROVIDER_TYPE)
97
+ result.provider = { ...result.provider, type: env.MMA_PROVIDER_TYPE };
98
+ if (env.MMA_PROVIDER_BASEURL)
99
+ result.provider = { ...result.provider, baseUrl: env.MMA_PROVIDER_BASEURL };
100
+ if (env.MMA_PROVIDER_APIKEY)
101
+ result.provider = { ...result.provider, apiKey: env.MMA_PROVIDER_APIKEY };
102
+ if (env.MMA_LOG_LEVEL)
103
+ result.logLevel = env.MMA_LOG_LEVEL;
104
+ if (env.MMA_LOCALE)
105
+ result.locale = env.MMA_LOCALE;
106
+ if (env.MMA_CONTEXT_WINDOW)
107
+ result.contextWindow = parseInt(env.MMA_CONTEXT_WINDOW, 10);
108
+ if (env.MMA_MAX_TOOL_ITERATIONS)
109
+ result.maxToolIterations = parseInt(env.MMA_MAX_TOOL_ITERATIONS, 10);
110
+ if (env.MMA_STUCK_THRESHOLD)
111
+ result.stuckThreshold = parseInt(env.MMA_STUCK_THRESHOLD, 10);
112
+ if (env.MMA_AUTO_PLAN)
113
+ result.autoPlan = env.MMA_AUTO_PLAN === 'true';
114
+ if (env.MMA_MOE_ENABLED)
115
+ result.moe = { ...result.moe, enabled: env.MMA_MOE_ENABLED === 'true' };
116
+ return result;
117
+ }
118
+ export function loadConfig(options) {
119
+ const globalPath = join(options.configDir, 'config.json');
120
+ mkdirSync(options.configDir, { recursive: true });
121
+ const detector = new MigrationDetector(options.configDir);
122
+ if (detector.needsMigration()) {
123
+ const backup = new BackupManager(options.configDir);
124
+ backup.backupConfig();
125
+ const summary = backup.getBackupSummary();
126
+ console.log(t('migration.detected', { summary }));
127
+ try {
128
+ unlinkSync(globalPath);
129
+ }
130
+ catch { }
131
+ }
132
+ let config = { ...DEFAULTS };
133
+ const globalData = loadJSON(globalPath);
134
+ if (globalData) {
135
+ config = deepMerge(config, globalData);
136
+ }
137
+ if (!existsSync(globalPath)) {
138
+ saveConfig(config, globalPath);
139
+ }
140
+ const projectData = loadJSON(options.projectConfigPath);
141
+ if (projectData) {
142
+ config = deepMerge(config, projectData);
143
+ }
144
+ // Restore RegExp patterns in contentScan that may have been serialized
145
+ // as {} in pre-0.8.0 config files, or merged from user config.
146
+ if (config.security?.contentScan?.dangerousPatterns) {
147
+ config.security.contentScan.dangerousPatterns = restoreDangerousPatterns(config.security.contentScan.dangerousPatterns, DEFAULT_SECURITY_CONFIG.contentScan.dangerousPatterns);
148
+ }
149
+ config = applyEnvVars(config);
150
+ // Decrypt sensitive fields in the loaded config
151
+ try {
152
+ const encryptor = new ConfigEncryptor();
153
+ const decrypted = encryptor.decrypt(config);
154
+ // Merge decrypted sensitive fields back into config
155
+ for (const key of Object.keys(decrypted)) {
156
+ config[key] = decrypted[key];
157
+ }
158
+ }
159
+ catch (e) {
160
+ // If decryption fails, log a warning but continue with the config
161
+ console.warn(t('config.decryption_warning', { error: e.message }));
162
+ }
163
+ // Update global audit notifier with config (done in bootstrap.ts)
164
+ return config;
165
+ }
166
+ export function validateConfig(config, allToolTags) {
167
+ const errors = validateExpertConfig(config, allToolTags);
168
+ if (errors.length > 0) {
169
+ throw new Error(`Config validation failed:\n${errors.join('\n')}`);
170
+ }
171
+ }
172
+ export function saveConfig(config, configPath) {
173
+ const dir = dirname(configPath);
174
+ mkdirSync(dir, { recursive: true });
175
+ // Encrypt sensitive fields before saving
176
+ try {
177
+ const encryptor = new ConfigEncryptor();
178
+ const encryptedConfig = encryptor.encrypt({ ...config });
179
+ writeFileSync(configPath, JSON.stringify(encryptedConfig, regexReplacer, 2), 'utf-8');
180
+ }
181
+ catch (e) {
182
+ // If encryption fails, save without encryption
183
+ console.warn(t('config.encryption_warning', { error: e.message }));
184
+ writeFileSync(configPath, JSON.stringify(config, regexReplacer, 2), 'utf-8');
185
+ }
186
+ }
@@ -0,0 +1,91 @@
1
+ import { DEFAULT_SECURITY_CONFIG } from "./security";
2
+ export const DEFAULTS = {
3
+ version: "2.0.0",
4
+ model: "qwen3.5-9b",
5
+ provider: {
6
+ type: "openai-compat",
7
+ baseUrl: "http://localhost:1234/v1",
8
+ apiKey: "not-needed",
9
+ },
10
+ orchestrator: {
11
+ model: undefined,
12
+ provider: undefined,
13
+ },
14
+ moe: {
15
+ enabled: false,
16
+ },
17
+ experts: {
18
+ code: {
19
+ model: "qwen3.5-9b",
20
+ tool_tags: ["file", "code", "shell"],
21
+ max_attempts: 3,
22
+ },
23
+ research: { model: "qwen3.5-9b", tool_tags: ["research"], max_attempts: 3 },
24
+ browser: {
25
+ model: "qwen3.5-9b",
26
+ tool_tags: ["browser", "vision"],
27
+ max_attempts: 3,
28
+ },
29
+ vision: {
30
+ model: "qwen3.5-9b",
31
+ tool_tags: ["browser", "vision", "file"],
32
+ max_attempts: 2,
33
+ },
34
+ },
35
+ contextWindow: 32768,
36
+ contextBudget: {
37
+ systemPrompt: 0.1,
38
+ responseReserve: 0.15,
39
+ compactionThreshold: 0.75,
40
+ },
41
+ modelLoad: {
42
+ autoLoad: false,
43
+ flashAttention: true,
44
+ offloadKvCacheToGpu: true,
45
+ },
46
+ retry: {
47
+ maxRetries: 3,
48
+ baseDelay: 1000,
49
+ maxDelay: 30000,
50
+ },
51
+ maxToolIterations: 1000,
52
+ stuckThreshold: 8,
53
+ autoPlan: true,
54
+ showReasoning: false,
55
+ logLevel: "info",
56
+ locale: "en",
57
+ session: {
58
+ autoSave: true,
59
+ maxSessions: 50,
60
+ isolateMemory: false,
61
+ },
62
+ browser: {
63
+ enabled: true,
64
+ headless: true,
65
+ maxElements: 30,
66
+ viewportWidth: 1280,
67
+ viewportHeight: 720,
68
+ navigationTimeout: 15000,
69
+ },
70
+ ui: {
71
+ spinner: true,
72
+ },
73
+ mcpServers: {
74
+ context7: {
75
+ name: "context7",
76
+ transport: "http",
77
+ url: "https://mcp.context7.com/mcp",
78
+ headers: {
79
+ CONTEXT7_API_KEY: process.env.CONTEXT7_API_KEY || "",
80
+ },
81
+ enabled: true,
82
+ timeout: 30000,
83
+ },
84
+ },
85
+ security: DEFAULT_SECURITY_CONFIG,
86
+ sessionIsolation: {
87
+ enabled: false,
88
+ isolatePlugins: true,
89
+ isolateTempFiles: true,
90
+ },
91
+ };
@@ -0,0 +1,15 @@
1
+ export function getExpertConfig(config, tag) {
2
+ return config.experts?.[tag];
3
+ }
4
+ export function validateExpertConfig(config, allToolTags) {
5
+ const errors = [];
6
+ const knownTags = new Set(allToolTags);
7
+ for (const [name, expert] of Object.entries(config.experts || {})) {
8
+ for (const tag of expert.tool_tags) {
9
+ if (!knownTags.has(tag)) {
10
+ errors.push(`Expert "${name}" references unknown tool_tag "${tag}". Known tags: ${Array.from(knownTags).join(', ')}`);
11
+ }
12
+ }
13
+ }
14
+ return errors;
15
+ }
@@ -0,0 +1,3 @@
1
+ export { DEFAULTS } from './defaults';
2
+ export { loadConfig, saveConfig, validateConfig } from './config';
3
+ export { getExpertConfig, validateExpertConfig } from './experts';