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,67 @@
1
+ import { homedir } from 'os';
2
+ import { join } from 'path';
3
+ import { t } from '../i18n/index';
4
+ import { MemoryStore } from '../modules/memory/store';
5
+ const CATEGORIES = ['preferences', 'conventions', 'decisions', 'errors', 'facts'];
6
+ export const rememberTool = {
7
+ name: 'remember',
8
+ description: 'Remember information across sessions. Use for user preferences, facts, conventions, decisions, or errors.',
9
+ tags: ['memory'],
10
+ parameters: {
11
+ type: 'object',
12
+ properties: {
13
+ category: {
14
+ type: 'string',
15
+ description: 'Memory category: preferences, conventions, decisions, errors, facts',
16
+ enum: CATEGORIES,
17
+ },
18
+ key: {
19
+ type: 'string',
20
+ description: 'Key name (required for preferences, e.g. "color", "language")',
21
+ },
22
+ value: {
23
+ type: 'string',
24
+ description: 'Value to store (required for preferences)',
25
+ },
26
+ entry: {
27
+ type: 'string',
28
+ description: 'Text entry to append (for conventions, decisions, errors, facts)',
29
+ },
30
+ },
31
+ required: ['category'],
32
+ },
33
+ handler: async (_ctx, args) => {
34
+ const category = String(args.category || '');
35
+ if (!CATEGORIES.includes(category)) {
36
+ return { success: false, output: t('tool.invalid_params') };
37
+ }
38
+ const memoryDir = join(homedir(), '.mma', 'memory');
39
+ const store = new MemoryStore(memoryDir);
40
+ try {
41
+ if (category === 'preferences') {
42
+ const key = String(args.key || '');
43
+ const value = String(args.value || '');
44
+ if (!key) {
45
+ return { success: false, output: t('tool.remember.key_required') };
46
+ }
47
+ store.setPreference(key, value);
48
+ return {
49
+ success: true,
50
+ output: t('tool.remember.preference', { key, value }),
51
+ };
52
+ }
53
+ const entry = String(args.entry || '');
54
+ if (!entry) {
55
+ return { success: false, output: t('tool.remember.entry_required') };
56
+ }
57
+ store.append(category, entry);
58
+ return {
59
+ success: true,
60
+ output: t('tool.remember.entry', { category, entry }),
61
+ };
62
+ }
63
+ catch (err) {
64
+ return { success: true, output: t('tool.memory_error', { error: String(err) }) };
65
+ }
66
+ },
67
+ };
@@ -0,0 +1,30 @@
1
+ import { resolve, normalize } from 'path';
2
+ export function isPathInScope(baseDir, targetPath, scope) {
3
+ const baseResolved = resolve(baseDir);
4
+ const targetResolved = resolve(baseDir, normalize(targetPath));
5
+ if (!targetResolved.startsWith(baseResolved)) {
6
+ return { allowed: false, reason: 'Path is outside the base working directory' };
7
+ }
8
+ if (!scope)
9
+ return { allowed: true };
10
+ const isRead = scope.read_only_files.some(f => targetResolved.startsWith(resolve(baseDir, f)));
11
+ const isWrite = scope.allowed_files.some(f => targetResolved.startsWith(resolve(baseDir, f)));
12
+ if (isWrite)
13
+ return { allowed: true };
14
+ if (isRead)
15
+ return { allowed: true, reason: 'Read-only file' };
16
+ return { allowed: false, reason: 'Path is not within the allowed scope for this sub-agent' };
17
+ }
18
+ export function isPathWritable(baseDir, targetPath, scope) {
19
+ const baseResolved = resolve(baseDir);
20
+ const targetResolved = resolve(baseDir, normalize(targetPath));
21
+ if (!targetResolved.startsWith(baseResolved)) {
22
+ return { allowed: false, reason: 'Path is outside the base working directory' };
23
+ }
24
+ if (!scope)
25
+ return { allowed: true };
26
+ const isWrite = scope.allowed_files.some(f => targetResolved.startsWith(resolve(baseDir, f)));
27
+ if (isWrite)
28
+ return { allowed: true };
29
+ return { allowed: false, reason: 'Path is not within the writable scope for this sub-agent' };
30
+ }
@@ -0,0 +1,64 @@
1
+ import * as fs from 'fs';
2
+ import { join } from 'path';
3
+ import { homedir } from 'os';
4
+ import { t } from '../i18n/index';
5
+ function searchFile(filePath, query, maxResults, results) {
6
+ if (!fs.existsSync(filePath))
7
+ return;
8
+ const content = fs.readFileSync(filePath, 'utf-8');
9
+ for (const line of content.split('\n').filter(Boolean)) {
10
+ if (line.toLowerCase().includes(query)) {
11
+ try {
12
+ const entry = JSON.parse(line);
13
+ results.push(`[${filePath}] ${JSON.stringify(entry).slice(0, 200)}`);
14
+ }
15
+ catch { /* skip */ }
16
+ }
17
+ if (results.length >= maxResults)
18
+ break;
19
+ }
20
+ }
21
+ export const searchHistoryTool = {
22
+ name: 'search_history',
23
+ description: 'Search through session history for past interactions across all sessions.',
24
+ tags: ['research'],
25
+ parameters: {
26
+ type: 'object',
27
+ properties: {
28
+ query: { type: 'string', description: 'Search query' },
29
+ maxResults: { type: 'number', description: 'Maximum results (default 5)' },
30
+ sessionId: { type: 'string', description: 'Optional: limit search to a specific session' },
31
+ },
32
+ required: ['query'],
33
+ },
34
+ handler: async (_ctx, args) => {
35
+ const query = String(args.query || '').toLowerCase();
36
+ const maxResults = Number(args.maxResults) || 5;
37
+ const sessionId = args.sessionId ? String(args.sessionId) : null;
38
+ const sessionDir = join(homedir(), '.mma', 'sessions');
39
+ const results = [];
40
+ try {
41
+ if (!fs.existsSync(sessionDir)) {
42
+ return { success: true, output: t('tool.no_sessions_dir', { dir: sessionDir }) };
43
+ }
44
+ const entries = fs.readdirSync(sessionDir, { withFileTypes: true });
45
+ for (const entry of entries) {
46
+ if (!entry.isDirectory())
47
+ continue;
48
+ if (sessionId && entry.name !== sessionId)
49
+ continue;
50
+ const historyFile = join(sessionDir, entry.name, 'history.jsonl');
51
+ searchFile(historyFile, query, maxResults, results);
52
+ if (results.length >= maxResults)
53
+ break;
54
+ }
55
+ if (results.length === 0) {
56
+ return { success: true, output: t('tool.no_history', { query }) };
57
+ }
58
+ return { success: true, output: t('tool.history_results', { query, results: results.join('\n') }) };
59
+ }
60
+ catch (err) {
61
+ return { success: true, output: t('tool.history_error', { error: String(err) }) };
62
+ }
63
+ },
64
+ };
@@ -0,0 +1,142 @@
1
+ import { t } from "../i18n/index";
2
+ import { Agent } from "../core/agent";
3
+ import { ContextManager } from "../modules/context/manager";
4
+ import { HallucinationDetector } from "../modules/hallucination/detector";
5
+ import { PluginManager } from "../modules/plugins/manager";
6
+ import { logSecurityBlock } from "../modules/security/audit-log";
7
+ import { getSessionSecurityConfig } from "../modules/security/session-isolation";
8
+ export const subagentTool = {
9
+ name: "subagent",
10
+ description: "Spawn an isolated sub-agent to work on a task independently. The sub-agent has its own context and executes autonomously. Use for parallel work or complex sub-tasks.",
11
+ tags: ["code"],
12
+ parameters: {
13
+ type: "object",
14
+ properties: {
15
+ task: {
16
+ type: "string",
17
+ description: "Task description for the sub-agent",
18
+ },
19
+ context: {
20
+ type: "string",
21
+ description: "Optional context or constraints",
22
+ },
23
+ expert_tag: {
24
+ type: "string",
25
+ description: "Expert tag for tool filtering and model selection",
26
+ },
27
+ allowed_files: {
28
+ type: "array",
29
+ items: { type: "string" },
30
+ description: "Files/directories the sub-agent can read and write",
31
+ },
32
+ read_only_files: {
33
+ type: "array",
34
+ items: { type: "string" },
35
+ description: "Files/directories the sub-agent can read but not write",
36
+ },
37
+ shared_context: {
38
+ type: "string",
39
+ description: "Shared context/rules passed to the sub-agent",
40
+ },
41
+ max_tokens: {
42
+ type: "number",
43
+ description: "Maximum tokens for the sub-agent response",
44
+ },
45
+ tool_tags: {
46
+ type: "array",
47
+ items: { type: "string" },
48
+ description: "Tool tags to expose to the sub-agent",
49
+ },
50
+ },
51
+ required: ["task"],
52
+ },
53
+ handler: async (ctx, args) => {
54
+ const task = String(args.task || "");
55
+ const context = String(args.context || "");
56
+ if (!task) {
57
+ return { success: false, output: t("tool.name_or_task") };
58
+ }
59
+ // Get session-specific security config
60
+ const securityConfig = ctx.sessionContext
61
+ ? getSessionSecurityConfig(ctx.config, ctx.sessionContext)
62
+ : ctx.config.security;
63
+ // Security check: limit recursion depth
64
+ const maxDepth = securityConfig?.maxRecursionDepth ?? 3;
65
+ const currentDepth = ctx.recursionDepth ?? 0;
66
+ if (currentDepth >= maxDepth) {
67
+ logSecurityBlock(ctx.sessionId, "bash_command", `Maximum recursion depth (${maxDepth}) exceeded`, task);
68
+ return {
69
+ success: false,
70
+ output: `[SECURITY BLOCKED] Maximum sub-agent recursion depth (${maxDepth}) exceeded`,
71
+ };
72
+ }
73
+ const scope = args.allowed_files || args.read_only_files
74
+ ? {
75
+ allowed_files: args.allowed_files || [],
76
+ read_only_files: args.read_only_files || [],
77
+ }
78
+ : ctx.scope;
79
+ const toolTags = args.tool_tags ? args.tool_tags : undefined;
80
+ if (!ctx.llmProvider || !ctx.toolExecutor) {
81
+ return {
82
+ success: false,
83
+ output: "Sub-agent cannot run: missing llmProvider or toolExecutor in context",
84
+ };
85
+ }
86
+ // Defensive guard: if the caller requested specific tool tags but none of the
87
+ // registered tools match, the sub-agent would have zero tools and would
88
+ // hallucinate instead of acting. Warn the caller so it can correct the tags.
89
+ if (toolTags && toolTags.length > 0) {
90
+ const matched = ctx.toolExecutor.getToolDefinitions(toolTags);
91
+ if (matched.length === 0) {
92
+ return {
93
+ success: false,
94
+ output: `[SECURITY BLOCKED] No tools match the requested tool_tags: [${toolTags.join(", ")}]. Check the subagent tool_tags parameter and retry with valid tags (e.g. "file", "code", "shell", "research").`,
95
+ };
96
+ }
97
+ }
98
+ try {
99
+ const subContextManager = new ContextManager(ctx.config.contextWindow, ctx.config.contextBudget);
100
+ const subPluginManager = new PluginManager();
101
+ const hallucinationDetector = new HallucinationDetector();
102
+ const systemPrompt = {
103
+ content: `You are a sub-agent working on a specific task. ${context ? `Context: ${context}` : ""}`,
104
+ priority: "critical",
105
+ essential: true,
106
+ estimatedTokens: 100,
107
+ };
108
+ const subDeps = {
109
+ config: ctx.config,
110
+ llmProvider: ctx.llmProvider,
111
+ toolExecutor: ctx.toolExecutor,
112
+ pluginManager: subPluginManager,
113
+ contextManager: subContextManager,
114
+ hallucinationDetector,
115
+ logger: ctx.logger,
116
+ baseDir: ctx.baseDir,
117
+ scope,
118
+ toolTags,
119
+ promptBlocks: [systemPrompt],
120
+ recursionDepth: currentDepth + 1, // Increment recursion depth for sub-agent
121
+ };
122
+ const subAgent = new Agent(subDeps);
123
+ const fullTask = context ? `${task}\n\nContext: ${context}` : task;
124
+ const result = await subAgent.run(fullTask);
125
+ if (result.success) {
126
+ return {
127
+ success: true,
128
+ output: `Sub-agent completed:\n${result.text}\n\nIterations: ${result.iterationCount}`,
129
+ };
130
+ }
131
+ else {
132
+ return {
133
+ success: false,
134
+ output: `Sub-agent failed: ${result.error}\nPartial output: ${result.text}`,
135
+ };
136
+ }
137
+ }
138
+ catch (e) {
139
+ return { success: false, output: `Sub-agent error: ${e.message}` };
140
+ }
141
+ },
142
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,123 @@
1
+ import * as readline from "readline";
2
+ import { t } from "../i18n/index";
3
+ /** Index returned by askChoice when the user picks the "custom answer" entry. */
4
+ export const CUSTOM_INDEX = -1;
5
+ /**
6
+ * Parse user input like "1" or "1,3" into 0-based option indexes.
7
+ * Returns null on invalid input (empty, non-numeric, out of range,
8
+ * duplicates, or multiple values when multiple is false).
9
+ */
10
+ export function parseSelection(input, optionCount, multiple) {
11
+ const trimmed = input.trim();
12
+ if (!trimmed)
13
+ return null;
14
+ const parts = trimmed.split(",").map((p) => p.trim());
15
+ if (!multiple && parts.length > 1)
16
+ return null;
17
+ const indexes = [];
18
+ for (const part of parts) {
19
+ if (!/^\d+$/.test(part))
20
+ return null;
21
+ const idx = Number(part) - 1;
22
+ if (idx < 0 || idx >= optionCount)
23
+ return null;
24
+ if (indexes.includes(idx))
25
+ return null;
26
+ indexes.push(idx);
27
+ }
28
+ return indexes.length ? indexes : null;
29
+ }
30
+ /** Render question + numbered option list as a single string. */
31
+ export function formatMenu(question, options, opts = {}) {
32
+ const lines = [question];
33
+ options.forEach((opt, i) => {
34
+ lines.push(` [${i + 1}] ${opt.label} — ${opt.description}`);
35
+ });
36
+ if (opts.allowCustom) {
37
+ lines.push(` [${options.length + 1}] ${t("tool.user_input.custom_option")}`);
38
+ }
39
+ return lines.join("\n");
40
+ }
41
+ /** Prompt text for the choice input. */
42
+ export function choicePrompt(optionCount, multiple) {
43
+ return multiple
44
+ ? t("tool.user_input.choice_multiple")
45
+ : t("tool.user_input.choice_single", { max: optionCount });
46
+ }
47
+ function createRl() {
48
+ return readline.createInterface({
49
+ input: process.stdin,
50
+ output: process.stdout,
51
+ });
52
+ }
53
+ function promptLine(rl, prompt) {
54
+ return new Promise((resolve) => {
55
+ rl.question(prompt, (answer) => resolve(answer));
56
+ });
57
+ }
58
+ /** Free-text question. Returns trimmed answer (may be empty). */
59
+ export async function askText(question) {
60
+ const rl = createRl();
61
+ try {
62
+ const answer = await promptLine(rl, `${question} `);
63
+ return answer.trim();
64
+ }
65
+ finally {
66
+ rl.close();
67
+ }
68
+ }
69
+ /**
70
+ * Choice question: shows a numbered menu and waits for a valid selection.
71
+ * Returns selected 0-based indexes; CUSTOM_INDEX marks the custom entry.
72
+ * Re-asks until the input is valid.
73
+ */
74
+ export async function askChoice(question, options, opts = {}) {
75
+ const multiple = opts.multiple ?? false;
76
+ const entryCount = options.length + (opts.allowCustom ? 1 : 0);
77
+ const customEntry = options.length; // index of the custom entry, if enabled
78
+ const rl = createRl();
79
+ try {
80
+ console.log(formatMenu(question, options, opts));
81
+ for (;;) {
82
+ const answer = await promptLine(rl, choicePrompt(entryCount, multiple));
83
+ const parsed = parseSelection(answer, entryCount, multiple);
84
+ if (parsed) {
85
+ return parsed.map((i) => opts.allowCustom && i === customEntry ? CUSTOM_INDEX : i);
86
+ }
87
+ console.log(t("tool.user_input.invalid"));
88
+ }
89
+ }
90
+ finally {
91
+ rl.close();
92
+ }
93
+ }
94
+ /**
95
+ * High-level helper used by the question tool.
96
+ * - No options: free-text input, returns [text] or [] when empty.
97
+ * - With options: returns selected labels; custom entry resolves to typed text.
98
+ */
99
+ export async function askUser(question, opts = {}) {
100
+ const header = [opts.progress, opts.header].filter(Boolean).join(" — ");
101
+ const text = header ? `${header}\n${question}` : question;
102
+ if (!opts.options || opts.options.length === 0) {
103
+ const answer = await askText(text);
104
+ return answer ? [answer] : [];
105
+ }
106
+ const allowCustom = opts.custom ?? true;
107
+ const indexes = await askChoice(text, opts.options, {
108
+ multiple: opts.multiple,
109
+ allowCustom,
110
+ });
111
+ const labels = [];
112
+ for (const idx of indexes) {
113
+ if (idx === CUSTOM_INDEX) {
114
+ const custom = await askText(t("tool.user_input.custom_prompt"));
115
+ if (custom)
116
+ labels.push(custom);
117
+ }
118
+ else {
119
+ labels.push(opts.options[idx].label);
120
+ }
121
+ }
122
+ return labels;
123
+ }
@@ -0,0 +1,57 @@
1
+ import { t } from '../i18n/index';
2
+ import { isUrlAllowed, sanitizeUrl } from '../modules/security/network-validator';
3
+ import { logNetworkRequest, logSecurityBlock } from '../modules/security/audit-log';
4
+ import { getSessionSecurityConfig } from '../modules/security/session-isolation';
5
+ import { MAX_PREVIEW_LINES } from './preview';
6
+ const MAX_CHARS = 3000;
7
+ export const webBrowseTool = {
8
+ name: 'web_browse',
9
+ description: `Fetch and read a web page. Returns the page content as plain text (max ${MAX_PREVIEW_LINES} lines / ${MAX_CHARS} chars).`,
10
+ tags: ['research'],
11
+ parameters: {
12
+ type: 'object',
13
+ properties: {
14
+ url: { type: 'string', description: 'URL to fetch' },
15
+ },
16
+ required: ['url'],
17
+ },
18
+ handler: async (ctx, args) => {
19
+ const url = String(args.url || '');
20
+ // Get session-specific security config
21
+ const securityConfig = ctx.sessionContext
22
+ ? getSessionSecurityConfig(ctx.config, ctx.sessionContext).network
23
+ : ctx.config.security?.network;
24
+ const validation = isUrlAllowed(url, securityConfig);
25
+ if (!validation.allowed) {
26
+ logSecurityBlock(ctx.sessionId, "network_request", validation.reason || "URL blocked by security policy", sanitizeUrl(url));
27
+ return {
28
+ success: false,
29
+ output: `[SECURITY BLOCKED] URL is not allowed: ${validation.reason}`,
30
+ };
31
+ }
32
+ try {
33
+ const response = await fetch(url, { signal: AbortSignal.timeout(securityConfig?.requestTimeout || 15000) });
34
+ const text = await response.text();
35
+ const stripped = text
36
+ .replace(/<script[\s\S]*?<\/script>/gi, '')
37
+ .replace(/<style[\s\S]*?<\/style>/gi, '')
38
+ .replace(/<[^>]+>/g, '')
39
+ .replace(/&[^;]+;/g, ' ')
40
+ .replace(/\s+/g, ' ')
41
+ .trim();
42
+ // Log successful network request
43
+ logNetworkRequest(ctx.sessionId, sanitizeUrl(url), true, `Status: ${response.status}`);
44
+ const maxLen = securityConfig?.maxResponseSize || MAX_CHARS;
45
+ let content = stripped.length > maxLen ? stripped.slice(0, maxLen) + t('file.truncated') : stripped;
46
+ const lines = content.split('\n');
47
+ if (lines.length > MAX_PREVIEW_LINES) {
48
+ content = lines.slice(0, MAX_PREVIEW_LINES).join('\n') + `\n... (${lines.length - MAX_PREVIEW_LINES} more lines)`;
49
+ }
50
+ return { success: true, output: content || t('file.empty_page') };
51
+ }
52
+ catch (err) {
53
+ logNetworkRequest(ctx.sessionId, sanitizeUrl(url), false, `Error: ${err.message}`);
54
+ return { success: false, output: t('error.fetch_url_failed', { url: sanitizeUrl(url), message: err.message }) };
55
+ }
56
+ },
57
+ };
@@ -0,0 +1,72 @@
1
+ import { t } from '../i18n/index';
2
+ import { isUrlAllowed, sanitizeUrl } from '../modules/security/network-validator';
3
+ import { logNetworkRequest, logSecurityBlock } from '../modules/security/audit-log';
4
+ import { getSessionSecurityConfig } from '../modules/security/session-isolation';
5
+ import { DEFAULT_SECURITY_CONFIG } from '../config/security';
6
+ import { MAX_PREVIEW_LINES } from './preview';
7
+ const MAX_CHARS = 5000;
8
+ function stripHtml(html) {
9
+ return html
10
+ .replace(/<script[\s\S]*?<\/script>/gi, '')
11
+ .replace(/<style[\s\S]*?<\/style>/gi, '')
12
+ .replace(/<[^>]+>/g, '')
13
+ .replace(/&[^;]+;/g, ' ')
14
+ .replace(/\s+/g, ' ')
15
+ .trim();
16
+ }
17
+ export const webFetchTool = {
18
+ name: 'web_fetch',
19
+ description: 'Fetch a URL and convert its content to markdown. Use for reading documentation, APIs, web pages.',
20
+ tags: ['research'],
21
+ parameters: {
22
+ type: 'object',
23
+ properties: {
24
+ url: { type: 'string', description: 'URL to fetch' },
25
+ },
26
+ required: ['url'],
27
+ },
28
+ handler: async (ctx, args) => {
29
+ const url = String(args.url);
30
+ // Get session-specific security config
31
+ const config = ctx.config || {};
32
+ const securityConfig = ctx.sessionContext
33
+ ? getSessionSecurityConfig(config, ctx.sessionContext).network
34
+ : config.security?.network || DEFAULT_SECURITY_CONFIG.network;
35
+ const validation = isUrlAllowed(url, securityConfig);
36
+ if (!validation.allowed) {
37
+ logSecurityBlock(ctx.sessionId, "network_request", validation.reason || "URL blocked by security policy", sanitizeUrl(url));
38
+ return {
39
+ success: false,
40
+ output: `[SECURITY BLOCKED] URL is not allowed: ${validation.reason}`,
41
+ };
42
+ }
43
+ try {
44
+ const response = await fetch(url, { signal: AbortSignal.timeout(securityConfig?.requestTimeout || 15000) });
45
+ if (!response.ok) {
46
+ return { success: false, output: t('error.http', { status: response.status, statusText: response.statusText }) };
47
+ }
48
+ const contentType = response.headers.get('content-type') || '';
49
+ const text = await response.text();
50
+ const cleaned = contentType.includes('html') ? stripHtml(text) : text;
51
+ // Log successful network request
52
+ logNetworkRequest(ctx.sessionId, sanitizeUrl(url), true, `Status: ${response.status}`);
53
+ if (cleaned.length > (securityConfig?.maxResponseSize || MAX_CHARS)) {
54
+ let content = cleaned.slice(0, securityConfig?.maxResponseSize || MAX_CHARS) + t('file.truncated');
55
+ const lines = content.split('\n');
56
+ if (lines.length > MAX_PREVIEW_LINES) {
57
+ content = lines.slice(0, MAX_PREVIEW_LINES).join('\n') + `\n... (${lines.length - MAX_PREVIEW_LINES} more lines)`;
58
+ }
59
+ return { success: true, output: content };
60
+ }
61
+ const lines = cleaned.split('\n');
62
+ if (lines.length > MAX_PREVIEW_LINES) {
63
+ return { success: true, output: lines.slice(0, MAX_PREVIEW_LINES).join('\n') + `\n... (${lines.length - MAX_PREVIEW_LINES} more lines)` };
64
+ }
65
+ return { success: true, output: cleaned || t('file.empty_page') };
66
+ }
67
+ catch (e) {
68
+ logNetworkRequest(ctx.sessionId, sanitizeUrl(url), false, `Error: ${e.message}`);
69
+ return { success: false, output: t('error.fetch_failed', { message: e.message }) };
70
+ }
71
+ },
72
+ };
@@ -0,0 +1,59 @@
1
+ import { t } from '../i18n/index';
2
+ import { isUrlAllowed, sanitizeUrl } from '../modules/security/network-validator';
3
+ import { logNetworkRequest, logSecurityBlock } from '../modules/security/audit-log';
4
+ import { getSessionSecurityConfig } from '../modules/security/session-isolation';
5
+ export const webSearchTool = {
6
+ name: 'web_search',
7
+ description: 'Search the web for information. Returns search results with titles and snippets.',
8
+ tags: ['research'],
9
+ parameters: {
10
+ type: 'object',
11
+ properties: {
12
+ query: { type: 'string', description: 'Search query' },
13
+ numResults: { type: 'number', description: 'Number of results (default 5)' },
14
+ },
15
+ required: ['query'],
16
+ },
17
+ handler: async (ctx, args) => {
18
+ const query = String(args.query || '');
19
+ const numResults = Number(args.numResults) || 5;
20
+ // Build search URL
21
+ const url = `https://html.duckduckgo.com/html/?q=${encodeURIComponent(query)}`;
22
+ // Get session-specific security config
23
+ const securityConfig = ctx.sessionContext
24
+ ? getSessionSecurityConfig(ctx.config, ctx.sessionContext).network
25
+ : ctx.config.security?.network;
26
+ const validation = isUrlAllowed(url, securityConfig);
27
+ if (!validation.allowed) {
28
+ logSecurityBlock(ctx.sessionId, "network_request", validation.reason || "URL blocked by security policy", sanitizeUrl(url));
29
+ return {
30
+ success: false,
31
+ output: `[SECURITY BLOCKED] Search URL is not allowed: ${validation.reason}`,
32
+ };
33
+ }
34
+ try {
35
+ const response = await fetch(url, { signal: AbortSignal.timeout(securityConfig?.requestTimeout || 10000) });
36
+ const html = await response.text();
37
+ const results = [];
38
+ const snippetRegex = /<a[^>]+class="result__a"[^>]*>([\s\S]*?)<\/a>[\s\S]*?<a[^>]+class="result__snippet"[^>]*>([\s\S]*?)<\/a>/gi;
39
+ let match;
40
+ let count = 0;
41
+ while ((match = snippetRegex.exec(html)) !== null && count < numResults) {
42
+ const title = match[1].replace(/<[^>]+>/g, '').trim();
43
+ const snippet = match[2].replace(/<[^>]+>/g, '').trim();
44
+ results.push(`${title}: ${snippet}`);
45
+ count++;
46
+ }
47
+ // Log successful network request
48
+ logNetworkRequest(ctx.sessionId, sanitizeUrl(url), true, `Results: ${results.length}`);
49
+ if (results.length === 0) {
50
+ return { success: true, output: t('tool.no_results', { query }) };
51
+ }
52
+ return { success: true, output: t('tool.search_results', { query, results: results.join('\n') }) };
53
+ }
54
+ catch (err) {
55
+ logNetworkRequest(ctx.sessionId, sanitizeUrl(url), false, `Error: ${err.message}`);
56
+ return { success: false, output: t('error.search_failed', { message: err.message }) };
57
+ }
58
+ },
59
+ };