micro-models-agent 0.50.4 → 0.51.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (218) hide show
  1. package/README.md +358 -358
  2. package/dist/main.js +923 -590
  3. package/dist/modules/browser/bridge-server.mjs +202 -202
  4. package/dist/skills/builtin/git.md +36 -36
  5. package/dist/skills/builtin/typescript.md +35 -35
  6. package/package.json +48 -48
  7. package/dist/cli/commands.js +0 -323
  8. package/dist/cli/completer.js +0 -167
  9. package/dist/cli/index.js +0 -2
  10. package/dist/cli/main.js +0 -165
  11. package/dist/cli/plugin-commands.js +0 -36
  12. package/dist/cli/repl-commands.js +0 -661
  13. package/dist/cli/repl.js +0 -616
  14. package/dist/cli/run-result.js +0 -22
  15. package/dist/cli/security-commands.js +0 -164
  16. package/dist/cli/setup.js +0 -231
  17. package/dist/config/config.js +0 -249
  18. package/dist/config/defaults.js +0 -124
  19. package/dist/config/experts.js +0 -15
  20. package/dist/config/index.js +0 -3
  21. package/dist/config/security.js +0 -193
  22. package/dist/config/types.js +0 -1
  23. package/dist/core/agent-moe.js +0 -102
  24. package/dist/core/agent.js +0 -886
  25. package/dist/core/bootstrap.js +0 -404
  26. package/dist/core/index.js +0 -2
  27. package/dist/core/prompt-builder.js +0 -76
  28. package/dist/core/session-logger.js +0 -197
  29. package/dist/core/types.js +0 -1
  30. package/dist/core/version.js +0 -24
  31. package/dist/core/workspace.js +0 -76
  32. package/dist/i18n/en.json +0 -598
  33. package/dist/i18n/index.js +0 -46
  34. package/dist/i18n/ru.json +0 -598
  35. package/dist/index.js +0 -22
  36. package/dist/llm/image-utils.js +0 -143
  37. package/dist/llm/index.js +0 -4
  38. package/dist/llm/model-loader.js +0 -78
  39. package/dist/llm/openai-compat.js +0 -359
  40. package/dist/llm/orchestrator.js +0 -198
  41. package/dist/llm/provider.js +0 -10
  42. package/dist/llm/response.js +0 -39
  43. package/dist/llm/token-counter.js +0 -39
  44. package/dist/llm/types.js +0 -1
  45. package/dist/logger/app-logger.js +0 -143
  46. package/dist/logger/file-log.js +0 -151
  47. package/dist/logger/index.js +0 -1
  48. package/dist/migration/backup.js +0 -45
  49. package/dist/migration/detect.js +0 -50
  50. package/dist/migration/index.js +0 -2
  51. package/dist/modules/artifacts/store.js +0 -61
  52. package/dist/modules/browser/actions.js +0 -76
  53. package/dist/modules/browser/bridge-client.js +0 -199
  54. package/dist/modules/browser/bridge-path.js +0 -10
  55. package/dist/modules/browser/cookie-store.js +0 -24
  56. package/dist/modules/browser/driver.js +0 -136
  57. package/dist/modules/browser/index.js +0 -7
  58. package/dist/modules/browser/module.js +0 -29
  59. package/dist/modules/browser/session.js +0 -338
  60. package/dist/modules/browser/snapshot.js +0 -148
  61. package/dist/modules/browser/types.js +0 -12
  62. package/dist/modules/certification/cli.js +0 -174
  63. package/dist/modules/certification/fact-checker.js +0 -82
  64. package/dist/modules/certification/loader.js +0 -105
  65. package/dist/modules/certification/manifest.js +0 -50
  66. package/dist/modules/certification/runner.js +0 -159
  67. package/dist/modules/certification/scenarios.js +0 -124
  68. package/dist/modules/certification/types.js +0 -1
  69. package/dist/modules/context/chunk-query.js +0 -100
  70. package/dist/modules/context/fact-extractor.js +0 -162
  71. package/dist/modules/context/history.js +0 -15
  72. package/dist/modules/context/index.js +0 -1
  73. package/dist/modules/context/manager.js +0 -423
  74. package/dist/modules/execution/audit-runners.js +0 -152
  75. package/dist/modules/execution/auditor.js +0 -218
  76. package/dist/modules/execution/execution-plugin.js +0 -272
  77. package/dist/modules/execution/index.js +0 -8
  78. package/dist/modules/execution/module.js +0 -436
  79. package/dist/modules/execution/moe-executor.js +0 -291
  80. package/dist/modules/execution/plan-coverage.js +0 -68
  81. package/dist/modules/execution/plan-persister.js +0 -46
  82. package/dist/modules/execution/plan-store.js +0 -157
  83. package/dist/modules/execution/plan-tool.js +0 -508
  84. package/dist/modules/execution/plan-validator.js +0 -153
  85. package/dist/modules/execution/planner.js +0 -90
  86. package/dist/modules/execution/stuck-detector.js +0 -510
  87. package/dist/modules/execution/tracker.js +0 -67
  88. package/dist/modules/execution/types.js +0 -1
  89. package/dist/modules/execution/verifier.js +0 -222
  90. package/dist/modules/execution/windows-commands.js +0 -41
  91. package/dist/modules/hallucination/confidence.js +0 -66
  92. package/dist/modules/hallucination/consistency.js +0 -26
  93. package/dist/modules/hallucination/detector.js +0 -43
  94. package/dist/modules/hallucination/factual.js +0 -129
  95. package/dist/modules/hallucination/index.js +0 -5
  96. package/dist/modules/hallucination/js-identifiers.js +0 -262
  97. package/dist/modules/hallucination/llm-judge.js +0 -101
  98. package/dist/modules/index.js +0 -5
  99. package/dist/modules/indexer/cache.js +0 -40
  100. package/dist/modules/indexer/index.js +0 -3
  101. package/dist/modules/indexer/module.js +0 -245
  102. package/dist/modules/indexer/project-profile.js +0 -183
  103. package/dist/modules/indexer/walker.js +0 -101
  104. package/dist/modules/lsp/check-tool.js +0 -58
  105. package/dist/modules/lsp/client.js +0 -278
  106. package/dist/modules/lsp/command.js +0 -60
  107. package/dist/modules/lsp/config.js +0 -135
  108. package/dist/modules/lsp/index.js +0 -3
  109. package/dist/modules/lsp/module.js +0 -232
  110. package/dist/modules/lsp/probe.js +0 -76
  111. package/dist/modules/lsp/project-root.js +0 -32
  112. package/dist/modules/lsp/startup-check.js +0 -141
  113. package/dist/modules/lsp/types.js +0 -1
  114. package/dist/modules/mcp/client.js +0 -399
  115. package/dist/modules/mcp/index.js +0 -3
  116. package/dist/modules/mcp/module.js +0 -142
  117. package/dist/modules/mcp/registry.js +0 -15
  118. package/dist/modules/memory/index.js +0 -1
  119. package/dist/modules/memory/module.js +0 -96
  120. package/dist/modules/memory/search.js +0 -42
  121. package/dist/modules/memory/store.js +0 -69
  122. package/dist/modules/pipelines/engine.js +0 -60
  123. package/dist/modules/pipelines/index.js +0 -3
  124. package/dist/modules/pipelines/parser.js +0 -56
  125. package/dist/modules/pipelines/template.js +0 -14
  126. package/dist/modules/plugins/builtin/lint-on-write.js +0 -231
  127. package/dist/modules/plugins/builtin/notify.js +0 -9
  128. package/dist/modules/plugins/index.js +0 -1
  129. package/dist/modules/plugins/loader.js +0 -70
  130. package/dist/modules/plugins/manager.js +0 -217
  131. package/dist/modules/plugins/types.js +0 -1
  132. package/dist/modules/processes/detect.js +0 -34
  133. package/dist/modules/processes/index.js +0 -2
  134. package/dist/modules/processes/registry.js +0 -327
  135. package/dist/modules/processes/runner.js +0 -23
  136. package/dist/modules/registry.js +0 -47
  137. package/dist/modules/security/audit-log.js +0 -136
  138. package/dist/modules/security/audit-notifier.js +0 -292
  139. package/dist/modules/security/command-validator.js +0 -205
  140. package/dist/modules/security/content-scanner.js +0 -53
  141. package/dist/modules/security/data-sanitizer.js +0 -89
  142. package/dist/modules/security/encryption.js +0 -242
  143. package/dist/modules/security/index.js +0 -14
  144. package/dist/modules/security/network-validator.js +0 -71
  145. package/dist/modules/security/path-validator.js +0 -207
  146. package/dist/modules/security/rate-limiter.js +0 -119
  147. package/dist/modules/security/security-policies.js +0 -531
  148. package/dist/modules/security/session-encryption.js +0 -210
  149. package/dist/modules/security/session-isolation.js +0 -95
  150. package/dist/modules/session/index.js +0 -3
  151. package/dist/modules/session/manager.js +0 -172
  152. package/dist/modules/session/module.js +0 -24
  153. package/dist/modules/session/store.js +0 -222
  154. package/dist/modules/session/types.js +0 -1
  155. package/dist/modules/skills/index.js +0 -2
  156. package/dist/modules/skills/loader.js +0 -72
  157. package/dist/modules/skills/matcher.js +0 -27
  158. package/dist/modules/skills/module.js +0 -129
  159. package/dist/modules/types.js +0 -1
  160. package/dist/modules/updater/checker.js +0 -96
  161. package/dist/modules/updater/index.js +0 -2
  162. package/dist/modules/updater/module.js +0 -116
  163. package/dist/modules/user-profile/compressor.js +0 -16
  164. package/dist/modules/user-profile/index.js +0 -1
  165. package/dist/modules/user-profile/profile.js +0 -68
  166. package/dist/tools/approve.js +0 -32
  167. package/dist/tools/attach-image.js +0 -89
  168. package/dist/tools/bash.js +0 -496
  169. package/dist/tools/browser.js +0 -114
  170. package/dist/tools/chunk-query.js +0 -99
  171. package/dist/tools/create-dir.js +0 -55
  172. package/dist/tools/delete-file.js +0 -62
  173. package/dist/tools/download-file.js +0 -116
  174. package/dist/tools/edit-file.js +0 -79
  175. package/dist/tools/enable-tools.js +0 -58
  176. package/dist/tools/executor.js +0 -144
  177. package/dist/tools/file-info.js +0 -46
  178. package/dist/tools/filter-tools.js +0 -17
  179. package/dist/tools/glob-tool.js +0 -26
  180. package/dist/tools/grep-tool.js +0 -84
  181. package/dist/tools/hidden-tools-block.js +0 -37
  182. package/dist/tools/index.js +0 -78
  183. package/dist/tools/list-dir.js +0 -48
  184. package/dist/tools/load-skill.js +0 -42
  185. package/dist/tools/mcp-call.js +0 -68
  186. package/dist/tools/move-file.js +0 -85
  187. package/dist/tools/path-utils.js +0 -51
  188. package/dist/tools/pipeline-run.js +0 -144
  189. package/dist/tools/preview.js +0 -2
  190. package/dist/tools/process-kill.js +0 -29
  191. package/dist/tools/process-list.js +0 -36
  192. package/dist/tools/process-log.js +0 -45
  193. package/dist/tools/question.js +0 -140
  194. package/dist/tools/read-file.js +0 -91
  195. package/dist/tools/recall.js +0 -117
  196. package/dist/tools/registry.js +0 -47
  197. package/dist/tools/remember.js +0 -67
  198. package/dist/tools/scope-check.js +0 -30
  199. package/dist/tools/search-history.js +0 -84
  200. package/dist/tools/subagent.js +0 -196
  201. package/dist/tools/types.js +0 -1
  202. package/dist/tools/user-input.js +0 -123
  203. package/dist/tools/web-browse.js +0 -86
  204. package/dist/tools/web-fetch.js +0 -98
  205. package/dist/tools/web-search.js +0 -78
  206. package/dist/tools/write-file.js +0 -81
  207. package/dist/ui/box.js +0 -77
  208. package/dist/ui/colors.js +0 -4
  209. package/dist/ui/diff.js +0 -178
  210. package/dist/ui/index.js +0 -6
  211. package/dist/ui/line-editor.js +0 -703
  212. package/dist/ui/line-math.js +0 -69
  213. package/dist/ui/md-formatter.js +0 -212
  214. package/dist/ui/output.js +0 -13
  215. package/dist/ui/plan-view.js +0 -103
  216. package/dist/ui/renderer.js +0 -209
  217. package/dist/ui/spinner.js +0 -70
  218. package/dist/ui/table.js +0 -144
@@ -1,67 +0,0 @@
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
- };
@@ -1,30 +0,0 @@
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
- }
@@ -1,84 +0,0 @@
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 {
16
- /* skip */
17
- }
18
- }
19
- if (results.length >= maxResults)
20
- break;
21
- }
22
- }
23
- export const searchHistoryTool = {
24
- name: "search_history",
25
- description: "Search through session history for past interactions across all sessions.",
26
- tags: ["research"],
27
- parameters: {
28
- type: "object",
29
- properties: {
30
- query: { type: "string", description: "Search query" },
31
- maxResults: {
32
- type: "number",
33
- description: "Maximum results (default 5)",
34
- },
35
- sessionId: {
36
- type: "string",
37
- description: "Optional: limit search to a specific session",
38
- },
39
- },
40
- required: ["query"],
41
- },
42
- handler: async (_ctx, args) => {
43
- const query = String(args.query || "").toLowerCase();
44
- const maxResults = Number(args.maxResults) || 5;
45
- const sessionId = args.sessionId ? String(args.sessionId) : null;
46
- const sessionDir = join(homedir(), ".mma", "sessions");
47
- const results = [];
48
- try {
49
- if (!fs.existsSync(sessionDir)) {
50
- return {
51
- success: true,
52
- output: t("tool.no_sessions_dir", { dir: sessionDir }),
53
- };
54
- }
55
- const entries = fs.readdirSync(sessionDir, { withFileTypes: true });
56
- for (const entry of entries) {
57
- if (!entry.isDirectory())
58
- continue;
59
- if (sessionId && entry.name !== sessionId)
60
- continue;
61
- const historyFile = join(sessionDir, entry.name, "history.jsonl");
62
- searchFile(historyFile, query, maxResults, results);
63
- if (results.length >= maxResults)
64
- break;
65
- }
66
- if (results.length === 0) {
67
- return { success: true, output: t("tool.no_history", { query }) };
68
- }
69
- return {
70
- success: true,
71
- output: t("tool.history_results", {
72
- query,
73
- results: results.join("\n"),
74
- }),
75
- };
76
- }
77
- catch (err) {
78
- return {
79
- success: false,
80
- output: t("tool.history_error", { error: String(err) }),
81
- };
82
- }
83
- },
84
- };
@@ -1,196 +0,0 @@
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
- import { ArtifactStore } from "../modules/artifacts/store";
9
- /** Fixed system prompt (KV-cache friendly when stableSystemPrompt is on). */
10
- export const SUBAGENT_SYSTEM_PROMPT_TEMPLATE = `You are a sub-agent working on a specific task. You have your own context window and tool set.
11
-
12
- Workflow rules:
13
- - Prefer small, focused steps. Verify your own work (typecheck/tests) before finishing.
14
- - For large outputs, write the result to a file with write_file instead of reproducing it in your answer.
15
- - If the task is big and decomposable, delegate parts to the subagent tool instead of doing everything in one context.
16
- - When you finish, return a concise final answer; do not repeat file contents verbatim if you already wrote them to disk.`;
17
- function buildSubagentSystemPrompt(context, stable) {
18
- if (stable)
19
- return SUBAGENT_SYSTEM_PROMPT_TEMPLATE;
20
- return `You are a sub-agent working on a specific task. ${context ? `Context: ${context}` : ""}`;
21
- }
22
- export const subagentTool = {
23
- name: "subagent",
24
- 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.",
25
- tags: ["code"],
26
- parameters: {
27
- type: "object",
28
- properties: {
29
- task: {
30
- type: "string",
31
- description: "Task description for the sub-agent",
32
- },
33
- context: {
34
- type: "string",
35
- description: "Optional context or constraints",
36
- },
37
- expert_tag: {
38
- type: "string",
39
- description: "Expert tag for tool filtering and model selection",
40
- },
41
- allowed_files: {
42
- type: "array",
43
- items: { type: "string" },
44
- description: "Files/directories the sub-agent can read and write",
45
- },
46
- read_only_files: {
47
- type: "array",
48
- items: { type: "string" },
49
- description: "Files/directories the sub-agent can read but not write",
50
- },
51
- shared_context: {
52
- type: "string",
53
- description: "Shared context/rules passed to the sub-agent",
54
- },
55
- max_tokens: {
56
- type: "number",
57
- description: "Maximum tokens for the sub-agent response",
58
- },
59
- tool_tags: {
60
- type: "array",
61
- items: { type: "string" },
62
- description: "Tool tags to expose to the sub-agent",
63
- },
64
- result_mode: {
65
- type: "string",
66
- enum: ["text", "file"],
67
- description: '"file": persist the full result to an artifact and return a path + summary (pass-by-reference). "text" (default): return the full text into context.',
68
- },
69
- artifact_name: {
70
- type: "string",
71
- description: "Artifact file name (sanitized). Default: subagent-<timestamp>.",
72
- },
73
- },
74
- required: ["task"],
75
- },
76
- handler: async (ctx, args) => {
77
- const task = String(args.task || "");
78
- const context = String(args.context || "");
79
- if (!task) {
80
- return { success: false, output: t("tool.name_or_task") };
81
- }
82
- // Get session-specific security config
83
- const securityConfig = ctx.sessionContext
84
- ? getSessionSecurityConfig(ctx.config, ctx.sessionContext)
85
- : ctx.config.security;
86
- // Security check: limit recursion depth
87
- const maxDepth = securityConfig?.maxRecursionDepth ?? 3;
88
- const currentDepth = ctx.recursionDepth ?? 0;
89
- if (currentDepth >= maxDepth) {
90
- logSecurityBlock(ctx.sessionId, "bash_command", `Maximum recursion depth (${maxDepth}) exceeded`, task);
91
- return {
92
- success: false,
93
- output: `[SECURITY BLOCKED] Maximum sub-agent recursion depth (${maxDepth}) exceeded`,
94
- };
95
- }
96
- const scope = args.allowed_files || args.read_only_files
97
- ? {
98
- allowed_files: args.allowed_files || [],
99
- read_only_files: args.read_only_files || [],
100
- }
101
- : ctx.scope;
102
- const toolTags = args.tool_tags ? args.tool_tags : undefined;
103
- if (!ctx.llmProvider || !ctx.toolExecutor) {
104
- return {
105
- success: false,
106
- output: "Sub-agent cannot run: missing llmProvider or toolExecutor in context",
107
- };
108
- }
109
- // Defensive guard: if the caller requested specific tool tags but none of the
110
- // registered tools match, the sub-agent would have zero tools and would
111
- // hallucinate instead of acting. Warn the caller so it can correct the tags.
112
- // Uses getByTags (not getAllForLLM) because alwaysOn tools always match the
113
- // latter — the guard must test real tag coverage, not schema presence.
114
- if (toolTags && toolTags.length > 0) {
115
- const matched = ctx.toolExecutor.getRegistry().getByTags(toolTags);
116
- if (matched.length === 0) {
117
- return {
118
- success: false,
119
- 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").`,
120
- };
121
- }
122
- }
123
- try {
124
- const subContextManager = new ContextManager(ctx.config.contextWindow, ctx.config.contextBudget);
125
- const subPluginManager = new PluginManager();
126
- const hallucinationDetector = new HallucinationDetector(ctx.baseDir, ctx.llmProvider);
127
- // Save/restore the shared executor scope so the sub-agent doesn't
128
- // permanently mutate the parent's scope.
129
- const parentScope = ctx.scope;
130
- ctx.toolExecutor.setScope(scope || { allowed_files: [], read_only_files: [] });
131
- const systemPrompt = {
132
- content: buildSubagentSystemPrompt(context, ctx.config.subagent?.stableSystemPrompt !== false),
133
- priority: "critical",
134
- essential: true,
135
- estimatedTokens: 150,
136
- };
137
- const subDeps = {
138
- config: ctx.config,
139
- llmProvider: ctx.llmProvider,
140
- toolExecutor: ctx.toolExecutor,
141
- pluginManager: subPluginManager,
142
- contextManager: subContextManager,
143
- hallucinationDetector,
144
- logger: ctx.logger,
145
- baseDir: ctx.baseDir,
146
- scope,
147
- toolTags,
148
- promptBlocks: [systemPrompt],
149
- recursionDepth: currentDepth + 1, // Increment recursion depth for sub-agent
150
- };
151
- const subAgent = new Agent(subDeps);
152
- const fullTask = context ? `${task}\n\nContext: ${context}` : task;
153
- let scopeRestored = false;
154
- try {
155
- const result = await subAgent.run(fullTask);
156
- if (!result.success) {
157
- return {
158
- success: false,
159
- output: `Sub-agent failed: ${result.error}\nPartial output: ${result.text}`,
160
- };
161
- }
162
- const resultMode = args.result_mode || ctx.config.subagent?.resultMode || "text";
163
- if (resultMode === "file") {
164
- const store = new ArtifactStore({
165
- baseDir: ctx.baseDir,
166
- sessionId: ctx.sessionId || "default",
167
- artifactsDir: ctx.config.subagent?.artifactsDir,
168
- });
169
- const abs = store.save(args.artifact_name || `subagent-${Date.now()}`, result.text, "md");
170
- const summary = store.summary(result.text, ctx.config.subagent?.maxSummaryChars ?? 2000);
171
- ctx.logger.debug(`subagent result persisted to artifact ${abs} (${result.text.length} chars, ${result.iterationCount} iterations)`);
172
- return {
173
- success: true,
174
- output: t("tool.subagent_artifact", {
175
- path: abs,
176
- iterations: String(result.iterationCount),
177
- summary,
178
- }),
179
- };
180
- }
181
- return {
182
- success: true,
183
- output: `Sub-agent completed:\n${result.text}\n\nIterations: ${result.iterationCount}`,
184
- };
185
- }
186
- finally {
187
- if (!scopeRestored) {
188
- ctx.toolExecutor.setScope(parentScope || { allowed_files: [], read_only_files: [] });
189
- }
190
- }
191
- }
192
- catch (e) {
193
- return { success: false, output: `Sub-agent error: ${e.message}` };
194
- }
195
- },
196
- };
@@ -1 +0,0 @@
1
- export {};
@@ -1,123 +0,0 @@
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
- }
@@ -1,86 +0,0 @@
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). This is a plain HTTP request — it does NOT execute JavaScript, so JS-rendered single-page apps (weather sites, dashboards, modern SPAs) return empty or near-empty content. For such pages use the "browser" tool instead.`,
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, {
34
- signal: AbortSignal.timeout(securityConfig?.requestTimeout || 15000),
35
- });
36
- const text = await response.text();
37
- const stripped = text
38
- .replace(/<script[\s\S]*?<\/script>/gi, "")
39
- .replace(/<style[\s\S]*?<\/style>/gi, "")
40
- .replace(/<[^>]+>/g, "")
41
- .replace(/&[^;]+;/g, " ")
42
- .replace(/\s+/g, " ")
43
- .trim();
44
- logNetworkRequest(ctx.sessionId, sanitizeUrl(url), true, `Status: ${response.status}`);
45
- const fullChars = stripped.length;
46
- const fullLines = stripped.split("\n").length;
47
- const maxChars = securityConfig?.maxResponseSize || MAX_CHARS;
48
- let content;
49
- if (stripped.length > maxChars) {
50
- content = stripped.slice(0, maxChars) + t("file.truncated");
51
- }
52
- else {
53
- content = stripped;
54
- }
55
- const contentLines = content.split("\n");
56
- if (contentLines.length > MAX_PREVIEW_LINES) {
57
- content =
58
- contentLines.slice(0, MAX_PREVIEW_LINES).join("\n") +
59
- `\n... (${contentLines.length - MAX_PREVIEW_LINES} more lines)`;
60
- }
61
- const truncated = stripped.length > maxChars || fullLines > MAX_PREVIEW_LINES
62
- ? t("file.truncated").trim()
63
- : "";
64
- return {
65
- success: true,
66
- output: content || t("file.empty_page"),
67
- display: t("tool.web_browse_result", {
68
- url: sanitizeUrl(url),
69
- chars: String(fullChars),
70
- lines: String(fullLines),
71
- truncated,
72
- }),
73
- };
74
- }
75
- catch (err) {
76
- logNetworkRequest(ctx.sessionId, sanitizeUrl(url), false, `Error: ${err.message}`);
77
- return {
78
- success: false,
79
- output: t("error.fetch_url_failed", {
80
- url: sanitizeUrl(url),
81
- message: err.message,
82
- }),
83
- };
84
- }
85
- },
86
- };