micro-models-agent 0.59.0 → 0.60.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (233) hide show
  1. package/CHANGELOG.md +578 -564
  2. package/README.md +358 -358
  3. package/dist/certification/certifications.json +493 -493
  4. package/dist/i18n/en.json +732 -718
  5. package/dist/i18n/ru.json +732 -718
  6. package/dist/main.js +504 -62
  7. package/dist/modules/browser/bridge-server.mjs +219 -219
  8. package/dist/skills/builtin/git.md +36 -36
  9. package/dist/skills/builtin/typescript.md +35 -35
  10. package/package.json +51 -51
  11. package/dist/cli/commands.js +0 -447
  12. package/dist/cli/completer.js +0 -167
  13. package/dist/cli/index.js +0 -2
  14. package/dist/cli/main.js +0 -153
  15. package/dist/cli/plugin-commands.js +0 -36
  16. package/dist/cli/repl-commands.js +0 -761
  17. package/dist/cli/repl.js +0 -702
  18. package/dist/cli/run-result.js +0 -33
  19. package/dist/cli/security-commands.js +0 -164
  20. package/dist/cli/setup.js +0 -237
  21. package/dist/config/config.js +0 -276
  22. package/dist/config/defaults.js +0 -141
  23. package/dist/config/domains.js +0 -179
  24. package/dist/config/experts.js +0 -15
  25. package/dist/config/index.js +0 -4
  26. package/dist/config/security.js +0 -213
  27. package/dist/config/types.js +0 -1
  28. package/dist/core/agent-moe.js +0 -102
  29. package/dist/core/agent.js +0 -1018
  30. package/dist/core/bootstrap.js +0 -481
  31. package/dist/core/crash-handler.js +0 -51
  32. package/dist/core/environment.js +0 -199
  33. package/dist/core/index.js +0 -2
  34. package/dist/core/prompt-builder.js +0 -76
  35. package/dist/core/session-logger.js +0 -251
  36. package/dist/core/types.js +0 -1
  37. package/dist/core/version.js +0 -26
  38. package/dist/core/workspace.js +0 -76
  39. package/dist/i18n/index.js +0 -46
  40. package/dist/index.js +0 -22
  41. package/dist/llm/image-utils.js +0 -143
  42. package/dist/llm/index.js +0 -4
  43. package/dist/llm/model-loader.js +0 -78
  44. package/dist/llm/openai-compat.js +0 -497
  45. package/dist/llm/orchestrator.js +0 -200
  46. package/dist/llm/provider.js +0 -10
  47. package/dist/llm/response.js +0 -39
  48. package/dist/llm/token-counter.js +0 -39
  49. package/dist/llm/types.js +0 -1
  50. package/dist/logger/app-logger.js +0 -189
  51. package/dist/logger/file-log.js +0 -151
  52. package/dist/logger/index.js +0 -1
  53. package/dist/migration/backup.js +0 -45
  54. package/dist/migration/detect.js +0 -50
  55. package/dist/migration/index.js +0 -2
  56. package/dist/modules/artifacts/store.js +0 -61
  57. package/dist/modules/browser/actions.js +0 -76
  58. package/dist/modules/browser/bridge-client.js +0 -199
  59. package/dist/modules/browser/bridge-path.js +0 -10
  60. package/dist/modules/browser/cookie-store.js +0 -24
  61. package/dist/modules/browser/driver.js +0 -136
  62. package/dist/modules/browser/index.js +0 -7
  63. package/dist/modules/browser/module.js +0 -29
  64. package/dist/modules/browser/session.js +0 -342
  65. package/dist/modules/browser/snapshot.js +0 -148
  66. package/dist/modules/browser/types.js +0 -12
  67. package/dist/modules/certification/cli.js +0 -213
  68. package/dist/modules/certification/fact-checker.js +0 -82
  69. package/dist/modules/certification/loader.js +0 -106
  70. package/dist/modules/certification/manifest.js +0 -58
  71. package/dist/modules/certification/runner.js +0 -245
  72. package/dist/modules/certification/scenarios.js +0 -407
  73. package/dist/modules/certification/types.js +0 -1
  74. package/dist/modules/context/chunk-query.js +0 -100
  75. package/dist/modules/context/fact-extractor.js +0 -168
  76. package/dist/modules/context/history.js +0 -15
  77. package/dist/modules/context/index.js +0 -1
  78. package/dist/modules/context/manager.js +0 -440
  79. package/dist/modules/execution/audit-runners.js +0 -206
  80. package/dist/modules/execution/auditor.js +0 -218
  81. package/dist/modules/execution/execution-plugin.js +0 -431
  82. package/dist/modules/execution/index.js +0 -8
  83. package/dist/modules/execution/module.js +0 -625
  84. package/dist/modules/execution/moe-executor.js +0 -304
  85. package/dist/modules/execution/plan-coverage.js +0 -68
  86. package/dist/modules/execution/plan-persister.js +0 -46
  87. package/dist/modules/execution/plan-store.js +0 -196
  88. package/dist/modules/execution/plan-tool.js +0 -677
  89. package/dist/modules/execution/plan-validator.js +0 -153
  90. package/dist/modules/execution/planner.js +0 -94
  91. package/dist/modules/execution/stuck-detector.js +0 -746
  92. package/dist/modules/execution/tracker.js +0 -69
  93. package/dist/modules/execution/types.js +0 -1
  94. package/dist/modules/execution/verifier.js +0 -235
  95. package/dist/modules/execution/windows-commands.js +0 -41
  96. package/dist/modules/hallucination/confidence.js +0 -66
  97. package/dist/modules/hallucination/consistency.js +0 -26
  98. package/dist/modules/hallucination/detector.js +0 -47
  99. package/dist/modules/hallucination/factual.js +0 -169
  100. package/dist/modules/hallucination/index.js +0 -5
  101. package/dist/modules/hallucination/js-identifiers.js +0 -262
  102. package/dist/modules/hallucination/llm-judge.js +0 -101
  103. package/dist/modules/index.js +0 -5
  104. package/dist/modules/indexer/cache.js +0 -40
  105. package/dist/modules/indexer/index.js +0 -3
  106. package/dist/modules/indexer/module.js +0 -246
  107. package/dist/modules/indexer/project-profile.js +0 -183
  108. package/dist/modules/indexer/walker.js +0 -101
  109. package/dist/modules/lsp/check-tool.js +0 -58
  110. package/dist/modules/lsp/client.js +0 -389
  111. package/dist/modules/lsp/command.js +0 -60
  112. package/dist/modules/lsp/config.js +0 -135
  113. package/dist/modules/lsp/index.js +0 -3
  114. package/dist/modules/lsp/module.js +0 -260
  115. package/dist/modules/lsp/probe.js +0 -86
  116. package/dist/modules/lsp/project-root.js +0 -32
  117. package/dist/modules/lsp/startup-check.js +0 -144
  118. package/dist/modules/lsp/types.js +0 -1
  119. package/dist/modules/mcp/client.js +0 -399
  120. package/dist/modules/mcp/index.js +0 -3
  121. package/dist/modules/mcp/module.js +0 -142
  122. package/dist/modules/mcp/registry.js +0 -15
  123. package/dist/modules/memory/index.js +0 -1
  124. package/dist/modules/memory/module.js +0 -96
  125. package/dist/modules/memory/search.js +0 -42
  126. package/dist/modules/memory/store.js +0 -69
  127. package/dist/modules/pipelines/engine.js +0 -60
  128. package/dist/modules/pipelines/index.js +0 -3
  129. package/dist/modules/pipelines/parser.js +0 -56
  130. package/dist/modules/pipelines/template.js +0 -14
  131. package/dist/modules/plugins/builtin/lint-on-write.js +0 -334
  132. package/dist/modules/plugins/builtin/notify.js +0 -9
  133. package/dist/modules/plugins/index.js +0 -1
  134. package/dist/modules/plugins/loader.js +0 -70
  135. package/dist/modules/plugins/manager.js +0 -261
  136. package/dist/modules/plugins/types.js +0 -1
  137. package/dist/modules/pricing/index.js +0 -61
  138. package/dist/modules/pricing/prices.js +0 -129
  139. package/dist/modules/processes/detect.js +0 -34
  140. package/dist/modules/processes/index.js +0 -2
  141. package/dist/modules/processes/registry.js +0 -327
  142. package/dist/modules/processes/runner.js +0 -23
  143. package/dist/modules/providers/create.js +0 -22
  144. package/dist/modules/providers/fallback.js +0 -79
  145. package/dist/modules/providers/health.js +0 -46
  146. package/dist/modules/providers/index.js +0 -5
  147. package/dist/modules/providers/manager.js +0 -161
  148. package/dist/modules/providers/presets.js +0 -128
  149. package/dist/modules/providers/registry.js +0 -22
  150. package/dist/modules/providers/types.js +0 -1
  151. package/dist/modules/registry.js +0 -48
  152. package/dist/modules/security/audit-log.js +0 -136
  153. package/dist/modules/security/audit-notifier.js +0 -292
  154. package/dist/modules/security/command-validator.js +0 -219
  155. package/dist/modules/security/content-scanner.js +0 -53
  156. package/dist/modules/security/data-sanitizer.js +0 -89
  157. package/dist/modules/security/encryption.js +0 -242
  158. package/dist/modules/security/index.js +0 -14
  159. package/dist/modules/security/network-validator.js +0 -88
  160. package/dist/modules/security/path-validator.js +0 -203
  161. package/dist/modules/security/rate-limiter.js +0 -119
  162. package/dist/modules/security/security-policies.js +0 -531
  163. package/dist/modules/security/session-encryption.js +0 -210
  164. package/dist/modules/security/session-isolation.js +0 -95
  165. package/dist/modules/session/index.js +0 -3
  166. package/dist/modules/session/manager.js +0 -172
  167. package/dist/modules/session/module.js +0 -24
  168. package/dist/modules/session/store.js +0 -222
  169. package/dist/modules/session/types.js +0 -1
  170. package/dist/modules/skills/index.js +0 -2
  171. package/dist/modules/skills/loader.js +0 -72
  172. package/dist/modules/skills/matcher.js +0 -27
  173. package/dist/modules/skills/module.js +0 -129
  174. package/dist/modules/types.js +0 -1
  175. package/dist/modules/updater/checker.js +0 -96
  176. package/dist/modules/updater/index.js +0 -2
  177. package/dist/modules/updater/module.js +0 -116
  178. package/dist/modules/user-profile/compressor.js +0 -16
  179. package/dist/modules/user-profile/index.js +0 -1
  180. package/dist/modules/user-profile/profile.js +0 -68
  181. package/dist/tools/approve.js +0 -33
  182. package/dist/tools/attach-image.js +0 -101
  183. package/dist/tools/bash.js +0 -519
  184. package/dist/tools/browser.js +0 -115
  185. package/dist/tools/chunk-query.js +0 -100
  186. package/dist/tools/create-dir.js +0 -56
  187. package/dist/tools/delete-file.js +0 -63
  188. package/dist/tools/download-file.js +0 -117
  189. package/dist/tools/edit-file.js +0 -80
  190. package/dist/tools/enable-tools.js +0 -59
  191. package/dist/tools/executor.js +0 -154
  192. package/dist/tools/file-info.js +0 -47
  193. package/dist/tools/filter-tools.js +0 -17
  194. package/dist/tools/glob-tool.js +0 -27
  195. package/dist/tools/grep-tool.js +0 -125
  196. package/dist/tools/hidden-tools-block.js +0 -37
  197. package/dist/tools/index.js +0 -78
  198. package/dist/tools/list-dir.js +0 -49
  199. package/dist/tools/load-skill.js +0 -43
  200. package/dist/tools/mcp-call.js +0 -69
  201. package/dist/tools/move-file.js +0 -86
  202. package/dist/tools/path-utils.js +0 -101
  203. package/dist/tools/pipeline-run.js +0 -145
  204. package/dist/tools/preview.js +0 -2
  205. package/dist/tools/process-kill.js +0 -40
  206. package/dist/tools/process-list.js +0 -37
  207. package/dist/tools/process-log.js +0 -54
  208. package/dist/tools/question.js +0 -141
  209. package/dist/tools/read-file.js +0 -179
  210. package/dist/tools/recall.js +0 -118
  211. package/dist/tools/registry.js +0 -47
  212. package/dist/tools/remember.js +0 -68
  213. package/dist/tools/scope-check.js +0 -32
  214. package/dist/tools/search-history.js +0 -85
  215. package/dist/tools/subagent.js +0 -196
  216. package/dist/tools/types.js +0 -1
  217. package/dist/tools/user-input.js +0 -123
  218. package/dist/tools/web-browse.js +0 -87
  219. package/dist/tools/web-fetch.js +0 -119
  220. package/dist/tools/web-search.js +0 -105
  221. package/dist/tools/write-file.js +0 -82
  222. package/dist/ui/box.js +0 -77
  223. package/dist/ui/colors.js +0 -4
  224. package/dist/ui/diff.js +0 -178
  225. package/dist/ui/index.js +0 -6
  226. package/dist/ui/line-editor.js +0 -822
  227. package/dist/ui/line-math.js +0 -73
  228. package/dist/ui/md-formatter.js +0 -212
  229. package/dist/ui/output.js +0 -13
  230. package/dist/ui/plan-view.js +0 -103
  231. package/dist/ui/renderer.js +0 -259
  232. package/dist/ui/spinner.js +0 -70
  233. package/dist/ui/table.js +0 -144
@@ -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
- icon: "🤖",
25
- 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.",
26
- tags: ["code"],
27
- parameters: {
28
- type: "object",
29
- properties: {
30
- task: {
31
- type: "string",
32
- description: "Task description for the sub-agent",
33
- },
34
- context: {
35
- type: "string",
36
- description: "Optional context or constraints",
37
- },
38
- expert_tag: {
39
- type: "string",
40
- description: "Expert tag for tool filtering and model selection",
41
- },
42
- allowed_files: {
43
- type: "array",
44
- items: { type: "string" },
45
- description: "Files/directories the sub-agent can read and write",
46
- },
47
- read_only_files: {
48
- type: "array",
49
- items: { type: "string" },
50
- description: "Files/directories the sub-agent can read but not write",
51
- },
52
- shared_context: {
53
- type: "string",
54
- description: "Shared context/rules passed to the sub-agent",
55
- },
56
- max_tokens: {
57
- type: "number",
58
- description: "Maximum tokens for the sub-agent response",
59
- },
60
- tool_tags: {
61
- type: "array",
62
- items: { type: "string" },
63
- description: "Tool tags to expose to the sub-agent",
64
- },
65
- result_mode: {
66
- type: "string",
67
- enum: ["text", "file"],
68
- 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.',
69
- },
70
- artifact_name: {
71
- type: "string",
72
- description: "Artifact file name (sanitized). Default: subagent-<timestamp>.",
73
- },
74
- },
75
- required: ["task"],
76
- },
77
- handler: async (ctx, args) => {
78
- const task = String(args.task || "");
79
- const context = String(args.context || "");
80
- if (!task) {
81
- return { success: false, output: t("tool.name_or_task") };
82
- }
83
- // Get session-specific security config
84
- const securityConfig = ctx.sessionContext
85
- ? getSessionSecurityConfig(ctx.config, ctx.sessionContext)
86
- : ctx.config.security;
87
- // Security check: limit recursion depth
88
- const maxDepth = securityConfig?.maxRecursionDepth ?? 3;
89
- const currentDepth = ctx.recursionDepth ?? 0;
90
- if (currentDepth >= maxDepth) {
91
- logSecurityBlock(ctx.sessionId, "bash_command", `Maximum recursion depth (${maxDepth}) exceeded`, task);
92
- return {
93
- success: false,
94
- output: `[SECURITY BLOCKED] Maximum sub-agent recursion depth (${maxDepth}) exceeded`,
95
- };
96
- }
97
- const scope = args.allowed_files || args.read_only_files
98
- ? {
99
- allowed_files: args.allowed_files || [],
100
- read_only_files: args.read_only_files || [],
101
- }
102
- : ctx.scope;
103
- const toolTags = args.tool_tags ? args.tool_tags : undefined;
104
- if (!ctx.llmProvider || !ctx.toolExecutor) {
105
- return {
106
- success: false,
107
- output: "Sub-agent cannot run: missing llmProvider or toolExecutor in context",
108
- };
109
- }
110
- // Defensive guard: if the caller requested specific tool tags but none of the
111
- // registered tools match, the sub-agent would have zero tools and would
112
- // hallucinate instead of acting. Warn the caller so it can correct the tags.
113
- // Uses getByTags (not getAllForLLM) because alwaysOn tools always match the
114
- // latter — the guard must test real tag coverage, not schema presence.
115
- if (toolTags && toolTags.length > 0) {
116
- const matched = ctx.toolExecutor.getRegistry().getByTags(toolTags);
117
- if (matched.length === 0) {
118
- return {
119
- success: false,
120
- 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").`,
121
- };
122
- }
123
- }
124
- try {
125
- const subContextManager = new ContextManager(ctx.config.contextWindow, ctx.config.contextBudget);
126
- const subPluginManager = new PluginManager();
127
- const hallucinationDetector = new HallucinationDetector(ctx.baseDir, ctx.llmProvider);
128
- // Save/restore the shared executor scope so the sub-agent doesn't
129
- // permanently mutate the parent's scope.
130
- const parentScope = ctx.scope;
131
- ctx.toolExecutor.setScope(scope || { allowed_files: [], read_only_files: [] });
132
- const systemPrompt = {
133
- content: buildSubagentSystemPrompt(context, ctx.config.subagent?.stableSystemPrompt !== false),
134
- priority: "critical",
135
- essential: true,
136
- estimatedTokens: 150,
137
- };
138
- const subDeps = {
139
- config: ctx.config,
140
- llmProvider: ctx.llmProvider,
141
- toolExecutor: ctx.toolExecutor,
142
- pluginManager: subPluginManager,
143
- contextManager: subContextManager,
144
- hallucinationDetector,
145
- logger: ctx.logger,
146
- baseDir: ctx.baseDir,
147
- scope,
148
- toolTags,
149
- promptBlocks: [systemPrompt],
150
- recursionDepth: currentDepth + 1, // Increment recursion depth for sub-agent
151
- };
152
- const subAgent = new Agent(subDeps);
153
- const fullTask = context ? `${task}\n\nContext: ${context}` : task;
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
- // Restore the parent's exact scope: undefined means "no restrictions"
188
- // and must not become an empty scope (which denies everything).
189
- ctx.toolExecutor.setScope(parentScope);
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,87 +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
- icon: "🌐",
10
- 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.`,
11
- tags: ["research"],
12
- parameters: {
13
- type: "object",
14
- properties: {
15
- url: { type: "string", description: "URL to fetch" },
16
- },
17
- required: ["url"],
18
- },
19
- handler: async (ctx, args) => {
20
- const url = String(args.url || "");
21
- // Get session-specific security config
22
- const securityConfig = ctx.sessionContext
23
- ? getSessionSecurityConfig(ctx.config, ctx.sessionContext).network
24
- : ctx.config.security?.network;
25
- const validation = isUrlAllowed(url, securityConfig);
26
- if (!validation.allowed) {
27
- logSecurityBlock(ctx.sessionId, "network_request", validation.reason || "URL blocked by security policy", sanitizeUrl(url));
28
- return {
29
- success: false,
30
- output: `[SECURITY BLOCKED] URL is not allowed: ${validation.reason}`,
31
- };
32
- }
33
- try {
34
- const response = await fetch(url, {
35
- signal: AbortSignal.timeout(securityConfig?.requestTimeout || 15000),
36
- });
37
- const text = await response.text();
38
- const stripped = text
39
- .replace(/<script[\s\S]*?<\/script>/gi, "")
40
- .replace(/<style[\s\S]*?<\/style>/gi, "")
41
- .replace(/<[^>]+>/g, "")
42
- .replace(/&[^;]+;/g, " ")
43
- .replace(/\s+/g, " ")
44
- .trim();
45
- logNetworkRequest(ctx.sessionId, sanitizeUrl(url), true, `Status: ${response.status}`);
46
- const fullChars = stripped.length;
47
- const fullLines = stripped.split("\n").length;
48
- const maxChars = securityConfig?.maxResponseSize || MAX_CHARS;
49
- let content;
50
- if (stripped.length > maxChars) {
51
- content = stripped.slice(0, maxChars) + t("file.truncated");
52
- }
53
- else {
54
- content = stripped;
55
- }
56
- const contentLines = content.split("\n");
57
- if (contentLines.length > MAX_PREVIEW_LINES) {
58
- content =
59
- contentLines.slice(0, MAX_PREVIEW_LINES).join("\n") +
60
- `\n... (${contentLines.length - MAX_PREVIEW_LINES} more lines)`;
61
- }
62
- const truncated = stripped.length > maxChars || fullLines > MAX_PREVIEW_LINES
63
- ? t("file.truncated").trim()
64
- : "";
65
- return {
66
- success: true,
67
- output: content || t("file.empty_page"),
68
- display: t("tool.web_browse_result", {
69
- url: sanitizeUrl(url),
70
- chars: String(fullChars),
71
- lines: String(fullLines),
72
- truncated,
73
- }),
74
- };
75
- }
76
- catch (err) {
77
- logNetworkRequest(ctx.sessionId, sanitizeUrl(url), false, `Error: ${err.message}`);
78
- return {
79
- success: false,
80
- output: t("error.fetch_url_failed", {
81
- url: sanitizeUrl(url),
82
- message: err.message,
83
- }),
84
- };
85
- }
86
- },
87
- };
@@ -1,119 +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 { 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
- icon: "⬇️",
20
- description: 'Fetch a URL and convert its content to markdown. Use for reading documentation, APIs, web pages. This is a plain HTTP request without a browser engine — it does NOT run JavaScript, so JS-rendered single-page apps (weather sites, dashboards, modern SPAs) return empty or near-empty content; use the "browser" tool for those.',
21
- tags: ["research"],
22
- parameters: {
23
- type: "object",
24
- properties: {
25
- url: { type: "string", description: "URL to fetch" },
26
- },
27
- required: ["url"],
28
- },
29
- handler: async (ctx, args) => {
30
- const url = String(args.url);
31
- // Get session-specific security config
32
- const config = ctx.config || {};
33
- const securityConfig = ctx.sessionContext
34
- ? getSessionSecurityConfig(config, ctx.sessionContext).network
35
- : config.security?.network || DEFAULT_SECURITY_CONFIG.network;
36
- const validation = isUrlAllowed(url, securityConfig);
37
- if (!validation.allowed) {
38
- logSecurityBlock(ctx.sessionId, "network_request", validation.reason || "URL blocked by security policy", sanitizeUrl(url));
39
- return {
40
- success: false,
41
- output: `[SECURITY BLOCKED] URL is not allowed: ${validation.reason}`,
42
- };
43
- }
44
- try {
45
- const response = await fetch(url, {
46
- signal: AbortSignal.timeout(securityConfig?.requestTimeout || 15000),
47
- redirect: "manual",
48
- });
49
- let finalResponse = response;
50
- let finalUrl = url;
51
- // Follow one redirect level manually, re-validating the target (SSRF).
52
- if (response.status >= 300 && response.status < 400) {
53
- const loc = response.headers.get("location");
54
- if (!loc) {
55
- return { success: false, output: t("error.fetch_failed", { message: "Redirect without location" }) };
56
- }
57
- finalUrl = new URL(loc, url).toString();
58
- const recheck = isUrlAllowed(finalUrl, securityConfig);
59
- if (!recheck.allowed) {
60
- logSecurityBlock(ctx.sessionId, "network_request", recheck.reason || "redirect blocked", sanitizeUrl(finalUrl));
61
- return { success: false, output: `[SECURITY BLOCKED] redirect: ${recheck.reason}` };
62
- }
63
- finalResponse = await fetch(finalUrl, {
64
- signal: AbortSignal.timeout(securityConfig?.requestTimeout || 15000),
65
- redirect: "follow",
66
- });
67
- }
68
- if (!finalResponse.ok) {
69
- return {
70
- success: false,
71
- output: t("error.http", {
72
- status: finalResponse.status,
73
- statusText: finalResponse.statusText,
74
- }),
75
- };
76
- }
77
- const contentType = finalResponse.headers.get("content-type") || "";
78
- const text = await finalResponse.text();
79
- const cleaned = contentType.includes("html") ? stripHtml(text) : text;
80
- logNetworkRequest(ctx.sessionId, sanitizeUrl(finalUrl), true, `Status: ${finalResponse.status}`);
81
- const fullChars = cleaned.length;
82
- const fullLines = cleaned.split("\n").length;
83
- const maxChars = securityConfig?.maxResponseSize || MAX_CHARS;
84
- let content;
85
- if (cleaned.length > maxChars) {
86
- content = cleaned.slice(0, maxChars) + t("file.truncated");
87
- }
88
- else {
89
- content = cleaned;
90
- }
91
- const contentLines = content.split("\n");
92
- if (contentLines.length > MAX_PREVIEW_LINES) {
93
- content =
94
- contentLines.slice(0, MAX_PREVIEW_LINES).join("\n") +
95
- `\n... (${contentLines.length - MAX_PREVIEW_LINES} more lines)`;
96
- }
97
- const truncated = cleaned.length > maxChars || fullLines > MAX_PREVIEW_LINES
98
- ? t("file.truncated").trim()
99
- : "";
100
- return {
101
- success: true,
102
- output: content || t("file.empty_page"),
103
- display: t("tool.web_fetch_result", {
104
- url: sanitizeUrl(url),
105
- chars: String(fullChars),
106
- lines: String(fullLines),
107
- truncated,
108
- }),
109
- };
110
- }
111
- catch (e) {
112
- logNetworkRequest(ctx.sessionId, sanitizeUrl(url), false, `Error: ${e.message}`);
113
- return {
114
- success: false,
115
- output: t("error.fetch_failed", { message: e.message }),
116
- };
117
- }
118
- },
119
- };
@@ -1,105 +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
- /**
6
- * Shared web search (DuckDuckGo HTML) used by BOTH the web_search tool and
7
- * the automatic error search (execution module). `networkConfig` is the
8
- * resolved security network config (may be undefined when security is off);
9
- * `requestTimeoutMs` overrides the timeout when the caller has its own
10
- * setting (the error search uses errorWebSearch.requestTimeoutMs).
11
- */
12
- export async function performWebSearch(query, numResults, networkConfig, requestTimeoutMs) {
13
- const url = `https://html.duckduckgo.com/html/?q=${encodeURIComponent(query)}`;
14
- const validation = isUrlAllowed(url, networkConfig);
15
- if (!validation.allowed) {
16
- return {
17
- success: false,
18
- blocked: true,
19
- results: [],
20
- error: validation.reason || "URL blocked by security policy",
21
- };
22
- }
23
- try {
24
- const response = await fetch(url, {
25
- signal: AbortSignal.timeout(requestTimeoutMs ?? networkConfig?.requestTimeout ?? 10000),
26
- });
27
- const html = await response.text();
28
- const results = [];
29
- const snippetRegex = /<a[^>]+class="result__a"[^>]*href="([^"]*)"[^>]*>([\s\S]*?)<\/a>[\s\S]*?<a[^>]+class="result__snippet"[^>]*>([\s\S]*?)<\/a>/gi;
30
- let match;
31
- while ((match = snippetRegex.exec(html)) !== null && results.length < numResults) {
32
- results.push({
33
- url: match[1].trim(),
34
- title: match[2].replace(/<[^>]+>/g, "").trim(),
35
- snippet: match[3].replace(/<[^>]+>/g, "").trim(),
36
- });
37
- }
38
- return { success: true, results };
39
- }
40
- catch (err) {
41
- return { success: false, results: [], error: err.message };
42
- }
43
- }
44
- function formatResults(results) {
45
- return results
46
- .map((r, i) => `${i + 1}. ${r.title}\n URL: ${r.url}\n ${r.snippet}`)
47
- .join("\n");
48
- }
49
- export const webSearchTool = {
50
- name: "web_search",
51
- icon: "🌍",
52
- description: "Search the web for information. Returns search results with titles and snippets. Use this for search queries instead of opening search engines (Google/Yandex/Bing) in the browser — they block headless browsers.",
53
- tags: ["research"],
54
- parameters: {
55
- type: "object",
56
- properties: {
57
- query: { type: "string", description: "Search query" },
58
- numResults: {
59
- type: "number",
60
- description: "Number of results (default 5)",
61
- },
62
- },
63
- required: ["query"],
64
- },
65
- handler: async (ctx, args) => {
66
- if (ctx.config?.webSearch?.enabled === false) {
67
- return { success: false, output: t("tool.web_search_disabled") };
68
- }
69
- const query = String(args.query || "");
70
- const numResults = Number(args.numResults) || 5;
71
- const securityConfig = ctx.sessionContext
72
- ? getSessionSecurityConfig(ctx.config, ctx.sessionContext).network
73
- : ctx.config.security?.network;
74
- const outcome = await performWebSearch(query, numResults, securityConfig);
75
- const url = `https://html.duckduckgo.com/html/?q=${encodeURIComponent(query)}`;
76
- if (outcome.blocked) {
77
- logSecurityBlock(ctx.sessionId, "network_request", outcome.error || "URL blocked by security policy", sanitizeUrl(url));
78
- return {
79
- success: false,
80
- output: t("error.search_failed", { message: String(outcome.error) }),
81
- };
82
- }
83
- logNetworkRequest(ctx.sessionId, sanitizeUrl(url), outcome.success, `Results: ${outcome.results.length}`);
84
- if (!outcome.success) {
85
- return {
86
- success: false,
87
- output: t("error.search_failed", { message: String(outcome.error) }),
88
- };
89
- }
90
- if (outcome.results.length === 0) {
91
- return { success: true, output: t("tool.no_results", { query }) };
92
- }
93
- return {
94
- success: true,
95
- output: t("tool.search_results", {
96
- query,
97
- results: formatResults(outcome.results),
98
- }),
99
- display: t("tool.web_search_result", {
100
- query,
101
- count: String(outcome.results.length),
102
- }),
103
- };
104
- },
105
- };