micro-models-agent 0.7.10 → 0.8.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.
- package/dist/cli/commands.js +173 -0
- package/dist/cli/completer.js +168 -0
- package/dist/cli/index.js +2 -0
- package/dist/cli/main.js +95 -0
- package/dist/cli/repl.js +762 -0
- package/dist/cli/security-commands.js +166 -0
- package/dist/cli/setup.js +214 -0
- package/dist/config/config.js +123 -0
- package/dist/config/defaults.js +91 -0
- package/dist/config/experts.js +15 -0
- package/dist/config/index.js +3 -0
- package/dist/config/security.js +187 -0
- package/dist/config/types.js +1 -0
- package/dist/core/agent.js +626 -0
- package/dist/core/bootstrap.js +307 -0
- package/dist/core/index.js +2 -0
- package/dist/core/prompt-builder.js +55 -0
- package/dist/core/types.js +1 -0
- package/dist/i18n/en.json +405 -0
- package/dist/i18n/index.js +43 -0
- package/dist/i18n/ru.json +405 -0
- package/dist/index.js +22 -0
- package/dist/llm/index.js +4 -0
- package/dist/llm/model-loader.js +78 -0
- package/dist/llm/openai-compat.js +277 -0
- package/dist/llm/orchestrator.js +194 -0
- package/dist/llm/provider.js +2 -0
- package/dist/llm/response.js +39 -0
- package/dist/llm/token-counter.js +37 -0
- package/dist/llm/types.js +1 -0
- package/dist/logger/app-logger.js +76 -0
- package/dist/logger/index.js +1 -0
- package/dist/migration/backup.js +45 -0
- package/dist/migration/detect.js +50 -0
- package/dist/migration/index.js +2 -0
- package/dist/modules/browser/actions.js +46 -0
- package/dist/modules/browser/cookie-store.js +24 -0
- package/dist/modules/browser/index.js +5 -0
- package/dist/modules/browser/module.js +28 -0
- package/dist/modules/browser/session.js +287 -0
- package/dist/modules/browser/snapshot.js +114 -0
- package/dist/modules/browser/types.js +9 -0
- package/dist/modules/context/history.js +15 -0
- package/dist/modules/context/index.js +1 -0
- package/dist/modules/context/manager.js +179 -0
- package/dist/modules/execution/auditor.js +72 -0
- package/dist/modules/execution/index.js +6 -0
- package/dist/modules/execution/module.js +334 -0
- package/dist/modules/execution/moe-executor.js +196 -0
- package/dist/modules/execution/plan-validator.js +153 -0
- package/dist/modules/execution/planner.js +35 -0
- package/dist/modules/execution/stuck-detector.js +113 -0
- package/dist/modules/execution/tracker.js +53 -0
- package/dist/modules/execution/types.js +1 -0
- package/dist/modules/execution/verifier.js +149 -0
- package/dist/modules/hallucination/confidence.js +47 -0
- package/dist/modules/hallucination/consistency.js +32 -0
- package/dist/modules/hallucination/detector.js +41 -0
- package/dist/modules/hallucination/factual.js +128 -0
- package/dist/modules/hallucination/index.js +4 -0
- package/dist/modules/index.js +5 -0
- package/dist/modules/indexer/cache.js +38 -0
- package/dist/modules/indexer/index.js +3 -0
- package/dist/modules/indexer/module.js +192 -0
- package/dist/modules/indexer/walker.js +101 -0
- package/dist/modules/mcp/client.js +393 -0
- package/dist/modules/mcp/index.js +3 -0
- package/dist/modules/mcp/module.js +146 -0
- package/dist/modules/mcp/registry.js +15 -0
- package/dist/modules/memory/index.js +1 -0
- package/dist/modules/memory/search.js +26 -0
- package/dist/modules/memory/store.js +38 -0
- package/dist/modules/pipelines/engine.js +60 -0
- package/dist/modules/pipelines/index.js +3 -0
- package/dist/modules/pipelines/parser.js +53 -0
- package/dist/modules/pipelines/template.js +14 -0
- package/dist/modules/plugins/builtin/lint-on-write.js +121 -0
- package/dist/modules/plugins/builtin/notify.js +8 -0
- package/dist/modules/plugins/index.js +1 -0
- package/dist/modules/plugins/loader.js +28 -0
- package/dist/modules/plugins/manager.js +161 -0
- package/dist/modules/plugins/types.js +1 -0
- package/dist/modules/registry.js +45 -0
- package/dist/modules/security/audit-log.js +108 -0
- package/dist/modules/security/audit-notifier.js +292 -0
- package/dist/modules/security/command-validator.js +91 -0
- package/dist/modules/security/content-scanner.js +52 -0
- package/dist/modules/security/data-sanitizer.js +97 -0
- package/dist/modules/security/encryption.js +218 -0
- package/dist/modules/security/index.js +14 -0
- package/dist/modules/security/network-validator.js +79 -0
- package/dist/modules/security/path-validator.js +155 -0
- package/dist/modules/security/rate-limiter.js +119 -0
- package/dist/modules/security/security-policies.js +393 -0
- package/dist/modules/security/session-encryption.js +193 -0
- package/dist/modules/security/session-isolation.js +95 -0
- package/dist/modules/session/index.js +3 -0
- package/dist/modules/session/manager.js +167 -0
- package/dist/modules/session/module.js +28 -0
- package/dist/modules/session/store.js +174 -0
- package/dist/modules/session/types.js +1 -0
- package/dist/modules/skills/index.js +3 -0
- package/dist/modules/skills/loader.js +72 -0
- package/dist/modules/skills/matcher.js +27 -0
- package/dist/modules/skills/module.js +180 -0
- package/dist/modules/types.js +1 -0
- package/dist/modules/updater/checker.js +32 -0
- package/dist/modules/updater/index.js +1 -0
- package/dist/modules/user-profile/compressor.js +16 -0
- package/dist/modules/user-profile/index.js +1 -0
- package/dist/modules/user-profile/profile.js +68 -0
- package/dist/tools/approve.js +32 -0
- package/dist/tools/bash.js +77 -0
- package/dist/tools/browser.js +97 -0
- package/dist/tools/create-dir.js +57 -0
- package/dist/tools/delete-file.js +64 -0
- package/dist/tools/edit-file.js +78 -0
- package/dist/tools/executor.js +83 -0
- package/dist/tools/file-info.js +46 -0
- package/dist/tools/filter-tools.js +10 -0
- package/dist/tools/glob-tool.js +19 -0
- package/dist/tools/grep-tool.js +51 -0
- package/dist/tools/index.js +44 -0
- package/dist/tools/list-dir.js +40 -0
- package/dist/tools/load-skill.js +48 -0
- package/dist/tools/mcp-call.js +68 -0
- package/dist/tools/move-file.js +84 -0
- package/dist/tools/pipeline-run.js +39 -0
- package/dist/tools/question.js +142 -0
- package/dist/tools/read-file.js +65 -0
- package/dist/tools/registry.js +36 -0
- package/dist/tools/scope-check.js +30 -0
- package/dist/tools/search-history.js +64 -0
- package/dist/tools/subagent.js +130 -0
- package/dist/tools/types.js +1 -0
- package/dist/tools/user-input.js +123 -0
- package/dist/tools/web-browse.js +51 -0
- package/dist/tools/web-fetch.js +62 -0
- package/dist/tools/web-search.js +59 -0
- package/dist/tools/write-file.js +80 -0
- package/dist/ui/box.js +81 -0
- package/dist/ui/colors.js +4 -0
- package/dist/ui/diff.js +185 -0
- package/dist/ui/index.js +6 -0
- package/dist/ui/md-formatter.js +212 -0
- package/dist/ui/output.js +13 -0
- package/dist/ui/renderer.js +141 -0
- package/dist/ui/spinner.js +70 -0
- package/dist/ui/table.js +144 -0
- package/package.json +1 -1
|
@@ -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,130 @@
|
|
|
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
|
+
try {
|
|
87
|
+
const subContextManager = new ContextManager(ctx.config.contextWindow, ctx.config.contextBudget);
|
|
88
|
+
const subPluginManager = new PluginManager();
|
|
89
|
+
const hallucinationDetector = new HallucinationDetector();
|
|
90
|
+
const systemPrompt = {
|
|
91
|
+
content: `You are a sub-agent working on a specific task. ${context ? `Context: ${context}` : ""}`,
|
|
92
|
+
priority: "critical",
|
|
93
|
+
essential: true,
|
|
94
|
+
estimatedTokens: 100,
|
|
95
|
+
};
|
|
96
|
+
const subDeps = {
|
|
97
|
+
config: ctx.config,
|
|
98
|
+
llmProvider: ctx.llmProvider,
|
|
99
|
+
toolExecutor: ctx.toolExecutor,
|
|
100
|
+
pluginManager: subPluginManager,
|
|
101
|
+
contextManager: subContextManager,
|
|
102
|
+
hallucinationDetector,
|
|
103
|
+
logger: ctx.logger,
|
|
104
|
+
baseDir: ctx.baseDir,
|
|
105
|
+
scope,
|
|
106
|
+
toolTags,
|
|
107
|
+
promptBlocks: [systemPrompt],
|
|
108
|
+
recursionDepth: currentDepth + 1, // Increment recursion depth for sub-agent
|
|
109
|
+
};
|
|
110
|
+
const subAgent = new Agent(subDeps);
|
|
111
|
+
const fullTask = context ? `${task}\n\nContext: ${context}` : task;
|
|
112
|
+
const result = await subAgent.run(fullTask);
|
|
113
|
+
if (result.success) {
|
|
114
|
+
return {
|
|
115
|
+
success: true,
|
|
116
|
+
output: `Sub-agent completed:\n${result.text}\n\nIterations: ${result.iterationCount}`,
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
else {
|
|
120
|
+
return {
|
|
121
|
+
success: false,
|
|
122
|
+
output: `Sub-agent failed: ${result.error}\nPartial output: ${result.text}`,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
catch (e) {
|
|
127
|
+
return { success: false, output: `Sub-agent error: ${e.message}` };
|
|
128
|
+
}
|
|
129
|
+
},
|
|
130
|
+
};
|
|
@@ -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,51 @@
|
|
|
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 webBrowseTool = {
|
|
6
|
+
name: 'web_browse',
|
|
7
|
+
description: 'Fetch and read a web page. Returns the page content as plain text.',
|
|
8
|
+
tags: ['research'],
|
|
9
|
+
parameters: {
|
|
10
|
+
type: 'object',
|
|
11
|
+
properties: {
|
|
12
|
+
url: { type: 'string', description: 'URL to fetch' },
|
|
13
|
+
},
|
|
14
|
+
required: ['url'],
|
|
15
|
+
},
|
|
16
|
+
handler: async (ctx, args) => {
|
|
17
|
+
const url = String(args.url || '');
|
|
18
|
+
// Get session-specific security config
|
|
19
|
+
const securityConfig = ctx.sessionContext
|
|
20
|
+
? getSessionSecurityConfig(ctx.config, ctx.sessionContext).network
|
|
21
|
+
: ctx.config.security?.network;
|
|
22
|
+
const validation = isUrlAllowed(url, securityConfig);
|
|
23
|
+
if (!validation.allowed) {
|
|
24
|
+
logSecurityBlock(ctx.sessionId, "network_request", validation.reason || "URL blocked by security policy", sanitizeUrl(url));
|
|
25
|
+
return {
|
|
26
|
+
success: false,
|
|
27
|
+
output: `[SECURITY BLOCKED] URL is not allowed: ${validation.reason}`,
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
try {
|
|
31
|
+
const response = await fetch(url, { signal: AbortSignal.timeout(securityConfig?.requestTimeout || 15000) });
|
|
32
|
+
const text = await response.text();
|
|
33
|
+
const stripped = text
|
|
34
|
+
.replace(/<script[\s\S]*?<\/script>/gi, '')
|
|
35
|
+
.replace(/<style[\s\S]*?<\/style>/gi, '')
|
|
36
|
+
.replace(/<[^>]+>/g, '')
|
|
37
|
+
.replace(/&[^;]+;/g, ' ')
|
|
38
|
+
.replace(/\s+/g, ' ')
|
|
39
|
+
.trim();
|
|
40
|
+
// Log successful network request
|
|
41
|
+
logNetworkRequest(ctx.sessionId, sanitizeUrl(url), true, `Status: ${response.status}`);
|
|
42
|
+
const maxLen = securityConfig?.maxResponseSize || 8000;
|
|
43
|
+
const content = stripped.length > maxLen ? stripped.slice(0, maxLen) + t('file.truncated') : stripped;
|
|
44
|
+
return { success: true, output: content || t('file.empty_page') };
|
|
45
|
+
}
|
|
46
|
+
catch (err) {
|
|
47
|
+
logNetworkRequest(ctx.sessionId, sanitizeUrl(url), false, `Error: ${err.message}`);
|
|
48
|
+
return { success: false, output: t('error.fetch_url_failed', { url: sanitizeUrl(url), message: err.message }) };
|
|
49
|
+
}
|
|
50
|
+
},
|
|
51
|
+
};
|
|
@@ -0,0 +1,62 @@
|
|
|
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
|
+
const MAX_CHARS = 15000;
|
|
7
|
+
function stripHtml(html) {
|
|
8
|
+
return html
|
|
9
|
+
.replace(/<script[\s\S]*?<\/script>/gi, '')
|
|
10
|
+
.replace(/<style[\s\S]*?<\/style>/gi, '')
|
|
11
|
+
.replace(/<[^>]+>/g, '')
|
|
12
|
+
.replace(/&[^;]+;/g, ' ')
|
|
13
|
+
.replace(/\s+/g, ' ')
|
|
14
|
+
.trim();
|
|
15
|
+
}
|
|
16
|
+
export const webFetchTool = {
|
|
17
|
+
name: 'web_fetch',
|
|
18
|
+
description: 'Fetch a URL and convert its content to markdown. Use for reading documentation, APIs, web pages.',
|
|
19
|
+
tags: ['research'],
|
|
20
|
+
parameters: {
|
|
21
|
+
type: 'object',
|
|
22
|
+
properties: {
|
|
23
|
+
url: { type: 'string', description: 'URL to fetch' },
|
|
24
|
+
},
|
|
25
|
+
required: ['url'],
|
|
26
|
+
},
|
|
27
|
+
handler: async (ctx, args) => {
|
|
28
|
+
const url = String(args.url);
|
|
29
|
+
// Get session-specific security config
|
|
30
|
+
const config = ctx.config || {};
|
|
31
|
+
const securityConfig = ctx.sessionContext
|
|
32
|
+
? getSessionSecurityConfig(config, ctx.sessionContext).network
|
|
33
|
+
: config.security?.network || DEFAULT_SECURITY_CONFIG.network;
|
|
34
|
+
const validation = isUrlAllowed(url, securityConfig);
|
|
35
|
+
if (!validation.allowed) {
|
|
36
|
+
logSecurityBlock(ctx.sessionId, "network_request", validation.reason || "URL blocked by security policy", sanitizeUrl(url));
|
|
37
|
+
return {
|
|
38
|
+
success: false,
|
|
39
|
+
output: `[SECURITY BLOCKED] URL is not allowed: ${validation.reason}`,
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
try {
|
|
43
|
+
const response = await fetch(url, { signal: AbortSignal.timeout(securityConfig?.requestTimeout || 15000) });
|
|
44
|
+
if (!response.ok) {
|
|
45
|
+
return { success: false, output: t('error.http', { status: response.status, statusText: response.statusText }) };
|
|
46
|
+
}
|
|
47
|
+
const contentType = response.headers.get('content-type') || '';
|
|
48
|
+
const text = await response.text();
|
|
49
|
+
const cleaned = contentType.includes('html') ? stripHtml(text) : text;
|
|
50
|
+
// Log successful network request
|
|
51
|
+
logNetworkRequest(ctx.sessionId, sanitizeUrl(url), true, `Status: ${response.status}`);
|
|
52
|
+
if (cleaned.length > (securityConfig?.maxResponseSize || MAX_CHARS)) {
|
|
53
|
+
return { success: true, output: cleaned.slice(0, securityConfig?.maxResponseSize || MAX_CHARS) + t('file.truncated') };
|
|
54
|
+
}
|
|
55
|
+
return { success: true, output: cleaned || t('file.empty_page') };
|
|
56
|
+
}
|
|
57
|
+
catch (e) {
|
|
58
|
+
logNetworkRequest(ctx.sessionId, sanitizeUrl(url), false, `Error: ${e.message}`);
|
|
59
|
+
return { success: false, output: t('error.fetch_failed', { message: e.message }) };
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
};
|
|
@@ -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
|
+
};
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { writeFileSync, mkdirSync, existsSync, readFileSync } from "fs";
|
|
2
|
+
import { resolve, normalize, dirname } from "path";
|
|
3
|
+
import { t } from "../i18n/index";
|
|
4
|
+
import { isPathWritable } from "../modules/security/path-validator";
|
|
5
|
+
import { scanContent } from "../modules/security/content-scanner";
|
|
6
|
+
import { logFileWrite, logSecurityBlock } from "../modules/security/audit-log";
|
|
7
|
+
import { getSessionSecurityConfig } from "../modules/security/session-isolation";
|
|
8
|
+
import { generateDiff, generateNewFileDiff } from "../ui/diff";
|
|
9
|
+
export const writeFileTool = {
|
|
10
|
+
name: "write_file",
|
|
11
|
+
description: "Create or overwrite a file with given content. Creates intermediate directories if needed.",
|
|
12
|
+
tags: ["file", "code"],
|
|
13
|
+
parameters: {
|
|
14
|
+
type: "object",
|
|
15
|
+
properties: {
|
|
16
|
+
path: { type: "string", description: "File path" },
|
|
17
|
+
content: { type: "string", description: "File content" },
|
|
18
|
+
},
|
|
19
|
+
required: ["path", "content"],
|
|
20
|
+
},
|
|
21
|
+
handler: async (ctx, args) => {
|
|
22
|
+
const path = String(args.path);
|
|
23
|
+
const baseDir = resolve(ctx.baseDir);
|
|
24
|
+
const resolved = resolve(baseDir, normalize(path));
|
|
25
|
+
// Check path permissions
|
|
26
|
+
const scopeCheck = isPathWritable(ctx.baseDir, path, ctx.scope, ctx.config.security?.paths);
|
|
27
|
+
if (!scopeCheck.allowed) {
|
|
28
|
+
logSecurityBlock(ctx.sessionId, "file_write", scopeCheck.reason || "Path not allowed", path);
|
|
29
|
+
return {
|
|
30
|
+
success: false,
|
|
31
|
+
output: t("file.path_not_allowed", {
|
|
32
|
+
path: `${path} — ${scopeCheck.reason}`,
|
|
33
|
+
}),
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
// Get session-specific security config
|
|
37
|
+
const securityConfig = ctx.sessionContext
|
|
38
|
+
? getSessionSecurityConfig(ctx.config, ctx.sessionContext)
|
|
39
|
+
: ctx.config.security;
|
|
40
|
+
// Check file operations limit
|
|
41
|
+
const maxFileOps = securityConfig?.maxFileOperations ?? 100;
|
|
42
|
+
const currentCount = ctx.fileOperationsCount ?? 0;
|
|
43
|
+
if (currentCount >= maxFileOps) {
|
|
44
|
+
logSecurityBlock(ctx.sessionId, "file_write", `Maximum file operations (${maxFileOps}) exceeded`, path);
|
|
45
|
+
return {
|
|
46
|
+
success: false,
|
|
47
|
+
output: `[SECURITY BLOCKED] Maximum file operations (${maxFileOps}) exceeded`,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
// Check content for dangerous patterns
|
|
51
|
+
const content = String(args.content);
|
|
52
|
+
const scanResult = scanContent(content, path, ctx.config.security?.contentScan);
|
|
53
|
+
if (!scanResult.allowed) {
|
|
54
|
+
logSecurityBlock(ctx.sessionId, "file_write", scanResult.reason || "Content contains dangerous patterns", path);
|
|
55
|
+
return {
|
|
56
|
+
success: false,
|
|
57
|
+
output: `[SECURITY BLOCKED] ${scanResult.reason}`,
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
const dir = dirname(resolved);
|
|
61
|
+
if (!existsSync(dir)) {
|
|
62
|
+
mkdirSync(dir, { recursive: true });
|
|
63
|
+
}
|
|
64
|
+
const fileExists = existsSync(resolved);
|
|
65
|
+
let oldContent = "";
|
|
66
|
+
if (fileExists) {
|
|
67
|
+
oldContent = readFileSync(resolved, "utf-8");
|
|
68
|
+
}
|
|
69
|
+
writeFileSync(resolved, content, "utf-8");
|
|
70
|
+
const diff = fileExists
|
|
71
|
+
? generateDiff(oldContent, content)
|
|
72
|
+
: generateNewFileDiff(content);
|
|
73
|
+
// Increment file operations counter
|
|
74
|
+
ctx.fileOperationsCount = currentCount + 1;
|
|
75
|
+
// Log successful file write
|
|
76
|
+
logFileWrite(ctx.sessionId, path, true, `File ${fileExists ? 'updated' : 'created'}`);
|
|
77
|
+
ctx.trackCreatedPath?.(path);
|
|
78
|
+
return { success: true, output: t("file.written", { path }), diff };
|
|
79
|
+
},
|
|
80
|
+
};
|
package/dist/ui/box.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import stringWidth from "string-width";
|
|
2
|
+
import { pc } from "./colors";
|
|
3
|
+
import { getTerminalWidth } from "./table";
|
|
4
|
+
/** Wrap a string to `width` columns, keeping ANSI codes intact. */
|
|
5
|
+
export function wrapText(text, width) {
|
|
6
|
+
if (width < 1)
|
|
7
|
+
return text ? [text] : [];
|
|
8
|
+
const lines = [];
|
|
9
|
+
let current = "";
|
|
10
|
+
const push = (token) => {
|
|
11
|
+
const candidate = current ? `${current} ${token}` : token;
|
|
12
|
+
if (stringWidth(candidate) <= width) {
|
|
13
|
+
current = candidate;
|
|
14
|
+
return;
|
|
15
|
+
}
|
|
16
|
+
if (current) {
|
|
17
|
+
lines.push(current);
|
|
18
|
+
current = "";
|
|
19
|
+
}
|
|
20
|
+
if (stringWidth(token) <= width) {
|
|
21
|
+
current = token;
|
|
22
|
+
return;
|
|
23
|
+
}
|
|
24
|
+
let acc = "";
|
|
25
|
+
for (const ch of token) {
|
|
26
|
+
if (stringWidth(acc + ch) <= width) {
|
|
27
|
+
acc += ch;
|
|
28
|
+
}
|
|
29
|
+
else {
|
|
30
|
+
lines.push(acc);
|
|
31
|
+
acc = ch;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
current = acc;
|
|
35
|
+
};
|
|
36
|
+
for (const token of text.split(/\s+/)) {
|
|
37
|
+
if (token)
|
|
38
|
+
push(token);
|
|
39
|
+
}
|
|
40
|
+
if (current)
|
|
41
|
+
lines.push(current);
|
|
42
|
+
return lines.length ? lines : [""];
|
|
43
|
+
}
|
|
44
|
+
function padTo(text, width) {
|
|
45
|
+
const gap = Math.max(0, width - stringWidth(text));
|
|
46
|
+
return text + " ".repeat(gap);
|
|
47
|
+
}
|
|
48
|
+
/** Render a box with an optional title embedded in the top border. */
|
|
49
|
+
export function box(lines, opts = {}) {
|
|
50
|
+
const pad = opts.padding ?? 1;
|
|
51
|
+
const width = Math.max(20, Math.min(opts.width ?? getTerminalWidth(), 120));
|
|
52
|
+
const inner = Math.max(1, width - 2 - pad * 2);
|
|
53
|
+
const wrapped = [];
|
|
54
|
+
for (const line of lines) {
|
|
55
|
+
for (const part of wrapText(line, inner))
|
|
56
|
+
wrapped.push(part);
|
|
57
|
+
}
|
|
58
|
+
const out = [];
|
|
59
|
+
const title = opts.title ?? "";
|
|
60
|
+
if (title) {
|
|
61
|
+
const head = `─ ${title} `;
|
|
62
|
+
out.push(pc.dim(`┌${head}${"─".repeat(Math.max(0, width - 2 - stringWidth(head)))}┐`));
|
|
63
|
+
}
|
|
64
|
+
else {
|
|
65
|
+
out.push(pc.dim(`┌${"─".repeat(width - 2)}┐`));
|
|
66
|
+
}
|
|
67
|
+
for (const line of wrapped) {
|
|
68
|
+
out.push(pc.dim("│") +
|
|
69
|
+
" ".repeat(pad) +
|
|
70
|
+
padTo(line, inner) +
|
|
71
|
+
" ".repeat(pad) +
|
|
72
|
+
pc.dim("│"));
|
|
73
|
+
}
|
|
74
|
+
out.push(pc.dim(`└${"─".repeat(width - 2)}┘`));
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
/** A horizontal rule that respects the terminal width (max 60 cols). */
|
|
78
|
+
export function divider(width) {
|
|
79
|
+
const w = Math.min(width ?? getTerminalWidth(), 60);
|
|
80
|
+
return pc.dim("─".repeat(w));
|
|
81
|
+
}
|