按 README 设计方案实现 Agent 系统 app/:多模型 FIFO 调度、Agent 主循环、13 个沙箱工具(web_search 走内网 MCP)、H5 前端(SSE 流式)、Docker 部署与端到端冒烟测试(25/25 通过)
This commit is contained in:
@@ -0,0 +1,360 @@
|
||||
[
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "copy_path",
|
||||
"description": "Copies a file or directory in the project, and returns confirmation that the copy succeeded.\nDirectory contents will be copied recursively.\n\nThis tool should be used when it's desirable to create a copy of a file or directory without modifying the original.\nIt's much more efficient than doing this by separately reading and then writing the file or directory's contents, so this tool should be preferred over that approach whenever copying is the goal.\nThe only supported paths outside the project are descendants of `~/.agents/skills`, for global agent skills.",
|
||||
"parameters": {
|
||||
"required": [
|
||||
"source_path",
|
||||
"destination_path"
|
||||
],
|
||||
"properties": {
|
||||
"source_path": {
|
||||
"description": "The source path of the file or directory to copy.\nIf a directory is specified, its contents will be copied recursively.\n\n<example>\nIf the project has the following files:\n\n- directory1/a/something.txt\n- directory2/a/things.txt\n- directory3/a/other.txt\n\nYou can copy the first file by providing a source_path of \"directory1/a/something.txt\"\n</example>",
|
||||
"type": "string"
|
||||
},
|
||||
"destination_path": {
|
||||
"description": "The destination path where the file or directory should be copied to.\n\n<example>\nTo copy \"directory1/a/something.txt\" to \"directory2/b/copy.txt\", provide a destination_path of \"directory2/b/copy.txt\"\n</example>",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "create_directory",
|
||||
"description": "Creates a new directory at the specified path within the project. Returns confirmation that the directory was created.\n\nThis tool creates a directory and all necessary parent directories. It should be used whenever you need to create new directories within the project.\nThe only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.",
|
||||
"parameters": {
|
||||
"required": [
|
||||
"path"
|
||||
],
|
||||
"properties": {
|
||||
"path": {
|
||||
"description": "The path of the new directory.\n\n<example>\nIf the project has the following structure:\n\n- directory1/\n- directory2/\n\nYou can create a new directory by providing a path of \"directory1/new_directory\"\n</example>\n\n<example>\nTo create a global agent skill directory, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill`.\n</example>",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "delete_path",
|
||||
"description": "Deletes the file or directory (and the directory's contents, recursively) at the specified path in the project, and returns confirmation of the deletion.\n\nThe only supported paths outside the project are descendants of `~/.agents/skills`, for global agent skills.",
|
||||
"parameters": {
|
||||
"required": [
|
||||
"path"
|
||||
],
|
||||
"properties": {
|
||||
"path": {
|
||||
"description": "The path of the file or directory to delete.\n\n<example>\nIf the project has the following files:\n\n- directory1/a/something.txt\n- directory2/a/things.txt\n- directory3/a/other.txt\n\nYou can delete the first file by providing a path of \"directory1/a/something.txt\"\n</example>",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "edit_file",
|
||||
"description": "This is a tool for applying edits to an existing file.\n\nBefore using this tool, use the `read_file` tool to understand the file's contents and context.\nTo create a new file or overwrite an existing one with completely new contents, use the `write_file` tool instead.\n\nThe only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.\n\n`read_file` prefixes each line of its output with a line number right-aligned in a\n6-character field followed by a single tab, then the line's actual content. When you\nderive `old_text` or `new_text` from that output, strip this prefix and keep only what\ncomes after the tab, preserving the original indentation (tabs and spaces) exactly.\nNever include any part of the line number prefix in `old_text` or `new_text`.",
|
||||
"parameters": {
|
||||
"required": [
|
||||
"path",
|
||||
"edits"
|
||||
],
|
||||
"properties": {
|
||||
"path": {
|
||||
"description": "The full path of the file to edit in the project.\n\nWARNING: When specifying which file path need changing, you MUST start each path with one of the project's root directories, unless it's a global agent skill under `~/.agents/skills`.\n\nThe following examples assume we have two root directories in the project:\n- /a/b/backend\n- /c/d/frontend\n\n<example>\n`backend/src/main.rs`\n\nNotice how the file path starts with `backend`. Without that, the path would be ambiguous and the call would fail!\n</example>\n\n<example>\n`frontend/db.js`\n</example>\n\n<example>\nTo edit a global agent skill file, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill/SKILL.md`.\n</example>",
|
||||
"type": "string"
|
||||
},
|
||||
"edits": {
|
||||
"description": "List of edit operations to apply sequentially.\nEach edit finds `old_text` in the file and replaces it with `new_text`.",
|
||||
"type": "array",
|
||||
"items": {
|
||||
"description": "A single edit operation that replaces old text with new text\nProperly escape all text fields as valid JSON strings.\nRemember to escape special characters like newlines (`\\n`) and quotes (`\"`) in JSON strings.",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"old_text": {
|
||||
"description": "The exact text to find in the file. This will be matched using fuzzy matching\nto handle minor differences in whitespace or formatting.\n\nBe minimal with replacements:\n- For unique lines, include only those lines\n- For non-unique lines, include enough context to identify them",
|
||||
"type": "string"
|
||||
},
|
||||
"new_text": {
|
||||
"description": "The text to replace it with",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"old_text",
|
||||
"new_text"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "fetch",
|
||||
"description": "Fetches a URL and returns the content as Markdown.\n\nThis tool is not run inside the terminal OS sandbox, but it still refuses to\nreach any host that hasn't been granted network access. It shares the same\nper-host grants as the `terminal` tool: approving a host for one authorizes\nit for the other, whether the grant is for this thread or saved permanently.\nWhen unsandboxed access has been granted, these restrictions are lifted\nentirely, matching the terminal, which is also how loopback and IP-literal\nhosts (which can't be granted individually) become reachable.",
|
||||
"parameters": {
|
||||
"required": [
|
||||
"url"
|
||||
],
|
||||
"properties": {
|
||||
"url": {
|
||||
"description": "The URL to fetch.",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "find_path",
|
||||
"description": "Find file paths that match a given pattern.\n\n- Supports glob patterns like \"**/*.js\" or \"src/**/*.ts\"\n- Returns matching file paths sorted alphabetically\n- Prefer the `grep` tool to this tool when searching for symbols unless you have specific information about paths.\n- Use this tool when you need to find files by name patterns\n- Results are paginated with 50 matches per page. Use the optional 'offset' parameter to request subsequent pages.",
|
||||
"parameters": {
|
||||
"required": [
|
||||
"glob"
|
||||
],
|
||||
"properties": {
|
||||
"glob": {
|
||||
"description": "The glob to match against every path in the project.\n\n<example>\nIf the project has the following root directories:\n\n- directory1/a/something.txt\n- directory2/a/things.txt\n- directory3/a/other.txt\n\nYou can get back the first two paths by providing a glob of \"*thing*.txt\"\n</example>",
|
||||
"type": "string"
|
||||
},
|
||||
"offset": {
|
||||
"description": "Optional starting position for paginated results (0-based).\nWhen not provided, starts from the beginning.",
|
||||
"type": "integer",
|
||||
"default": 0,
|
||||
"minimum": 0
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "grep",
|
||||
"description": "Searches the contents of files in the project with a regular expression\n\n- Prefer this tool to path search when searching for symbols in the project, because you won't need to guess what path it's in.\n- Supports full regex syntax (eg. \"log.*Error\", \"function\\\\s+\\\\w+\", etc.)\n- Pass an `include_pattern` if you know how to narrow your search on the files system\n- Never use this tool to search for paths. Only search file contents with this tool.\n- Use this tool when you need to find files containing specific patterns\n- Results are paginated with 20 matches per page. Use the optional 'offset' parameter to request subsequent pages.\n- DO NOT use HTML entities solely to escape characters in the tool parameters.",
|
||||
"parameters": {
|
||||
"required": [
|
||||
"regex"
|
||||
],
|
||||
"properties": {
|
||||
"regex": {
|
||||
"description": "A regex pattern to search for in the entire project. Note that the regex will be parsed by the Rust `regex` crate.\n\nDo NOT specify a path here! This will only be matched against the code **content**.",
|
||||
"type": "string"
|
||||
},
|
||||
"include_pattern": {
|
||||
"description": "A glob pattern for the paths of files to include in the search.\nSupports standard glob patterns like \"**/*.rs\" or \"frontend/src/**/*.ts\".\nIf omitted, all files in the project will be searched.\n\nThe glob pattern is matched against the full path including the project root directory.\n\n<example>\nIf the project has the following root directories:\n\n- /a/b/backend\n- /c/d/frontend\n\nUse \"backend/**/*.rs\" to search only Rust files in the backend root directory.\nUse \"frontend/src/**/*.ts\" to search TypeScript files only in the frontend root directory (sub-directory \"src\").\nUse \"**/*.rs\" to search Rust files across all root directories.\n</example>",
|
||||
"type": "string",
|
||||
"nullable": true
|
||||
},
|
||||
"offset": {
|
||||
"description": "Optional starting position for paginated results (0-based).\nWhen not provided, starts from the beginning.",
|
||||
"type": "integer",
|
||||
"default": 0,
|
||||
"minimum": 0
|
||||
},
|
||||
"case_sensitive": {
|
||||
"description": "Whether the regex is case-sensitive. Defaults to false (case-insensitive).",
|
||||
"type": "boolean",
|
||||
"default": false
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "list_directory",
|
||||
"description": "Lists files and directories in a given path. Prefer the `grep` or `find_path` tools when searching the codebase.\n\nThe only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.",
|
||||
"parameters": {
|
||||
"required": [
|
||||
"path"
|
||||
],
|
||||
"properties": {
|
||||
"path": {
|
||||
"description": "The fully-qualified path of the directory to list in the project.\n\nThis path should never be absolute, and the first component of the path should always be a root directory in a project, unless it's a global agent skill directory under `~/.agents/skills`.\n\n<example>\nIf the project has the following root directories:\n\n- directory1\n- directory2\n\nYou can list the contents of `directory1` by using the path `directory1`.\n</example>\n\n<example>\nIf the project has the following root directories:\n\n- foo\n- bar\n\nIf you wanna list contents in the directory `foo/baz`, you should use the path `foo/baz`.\n</example>\n\n<example>\nTo list a global agent skill directory, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill`.\n</example>",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "move_path",
|
||||
"description": "Moves or rename a file or directory in the project, and returns confirmation that the move succeeded.\n\nIf the source and destination directories are the same, but the filename is different, this performs a rename. Otherwise, it performs a move.\n\nThis tool should be used when it's desirable to move or rename a file or directory without changing its contents at all.\nThe only supported paths outside the project are descendants of `~/.agents/skills`, for global agent skills.",
|
||||
"parameters": {
|
||||
"required": [
|
||||
"source_path",
|
||||
"destination_path"
|
||||
],
|
||||
"properties": {
|
||||
"source_path": {
|
||||
"description": "The source path of the file or directory to move/rename.\n\n<example>\nIf the project has the following files:\n\n- directory1/a/something.txt\n- directory2/a/things.txt\n- directory3/a/other.txt\n\nYou can move the first file by providing a source_path of \"directory1/a/something.txt\"\n</example>",
|
||||
"type": "string"
|
||||
},
|
||||
"destination_path": {
|
||||
"description": "The destination path where the file or directory should be moved/renamed to.\nIf the paths are the same except for the filename, then this will be a rename.\n\n<example>\nTo move \"directory1/a/something.txt\" to \"directory2/b/renamed.txt\",\nprovide a destination_path of \"directory2/b/renamed.txt\"\n</example>",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "read_file",
|
||||
"description": "Reads the content of the given file in the project.\n\n- Never attempt to read a path that hasn't been previously mentioned.\n- For large files, this tool returns a file outline with symbol names and line numbers instead of the full content.\n This outline IS a successful response - use the line numbers to read specific sections with start_line/end_line.\n Do NOT retry reading the same file without line numbers if you receive an outline.\n- This tool supports reading image files. Supported formats: PNG, JPEG, WebP, GIF, BMP, TIFF.\n Image files are returned as visual content that you can analyze directly.\n\nThe only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.",
|
||||
"parameters": {
|
||||
"required": [
|
||||
"path"
|
||||
],
|
||||
"properties": {
|
||||
"path": {
|
||||
"description": "The relative path of the file to read.\n\nThis path should never be absolute, and the first component of the path should always be a root directory in a project, unless it's a global agent skill under `~/.agents/skills`.\n\n<example>\nIf the project has the following root directories:\n\n- /a/b/directory1\n- /c/d/directory2\n\nIf you want to access `file.txt` in `directory1`, you should use the path `directory1/file.txt`.\nIf you want to access `file.txt` in `directory2`, you should use the path `directory2/file.txt`.\n</example>\n\n<example>\nTo read a global agent skill file, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill/SKILL.md`.\n</example>",
|
||||
"type": "string"
|
||||
},
|
||||
"start_line": {
|
||||
"description": "Optional line number to start reading on (1-based index)",
|
||||
"type": "integer",
|
||||
"nullable": true,
|
||||
"minimum": 0,
|
||||
"default": null
|
||||
},
|
||||
"end_line": {
|
||||
"description": "Optional line number to end reading on (1-based index, inclusive)",
|
||||
"type": "integer",
|
||||
"nullable": true,
|
||||
"minimum": 0,
|
||||
"default": null
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "terminal",
|
||||
"description": "Executes a shell one-liner and returns the combined output.\n\nThis tool spawns a process using the user's shell, reads from stdout and stderr (preserving the order of writes), and returns a string with the combined output result.\n\nThe output results will be shown to the user already, only list it again if necessary, avoid being redundant.\n\nMake sure you use the `cd` parameter to navigate to one of the root directories of the project. NEVER do it as part of the `command` itself, otherwise it will error.\n\nDo not generate terminal commands that use shell substitutions or interpolations such as `$VAR`, `${VAR}`, `$(...)`, backticks, `$((...))`, `<(...)`, or `>(...)`. Resolve those values yourself before calling this tool, or ask the user for the literal value to use.\n\nDo not pipe output to `head`, `tail`, or similar output-filtering commands just to reduce what you receive. Instead, use `head_lines` and/or `tail_lines`; this keeps the terminal output visible to the user in real time while limiting only the final output sent back to you. When both are specified, the first `head_lines` lines are returned, then a blank line, then the last `tail_lines` lines. Avoid requesting too many lines, or the response may waste tokens or exceed the context window.\n\nDo not use this tool for commands that run indefinitely, such as servers (like `npm run start`, `npm run dev`, `python -m http.server`, etc) or file watchers that don't terminate on their own.\n\nFor potentially long-running commands, prefer specifying `timeout_ms` to bound runtime and prevent indefinite hangs.\n\nRemember that each invocation of this tool will spawn a new shell process, so you can't rely on any state from previous invocations.\n\nThe terminal is an interactive pty, so any command that blocks waiting for input will hang the tool until it times out. To avoid this:\n\n- Always insert `--no-pager` immediately after `git` for any read-only git command, including `git log`, `git diff`, `git show`, `git blame`, and `git stash show`. Example: `git --no-pager log -n 5` (NOT `git log -n 5`).\n- Prefer Git flags that avoid optional metadata writes when possible, such as `git --no-optional-locks status` instead of `git status`.\n- Always prepend `GIT_EDITOR=true ` to any git command that may invoke an editor, including `git rebase`, `git commit`, `git merge`, and `git tag`. Example: `GIT_EDITOR=true git rebase origin/main` (NOT `git rebase origin/main`).\n- For other commands that may open a pager or editor, set `PAGER=cat` and/or `EDITOR=true` similarly.",
|
||||
"parameters": {
|
||||
"required": [
|
||||
"command",
|
||||
"cd"
|
||||
],
|
||||
"properties": {
|
||||
"command": {
|
||||
"description": "The one-liner command to execute. Do not include shell substitutions or interpolations such as `$VAR`, `${VAR}`, `$(...)`, backticks, `$((...))`, `<(...)`, or `>(...)`; resolve those values first or ask the user for the literal value to use.\n\nREMINDER: read-only git commands (`git log`, `git diff`, `git show`, `git blame`) MUST include `--no-pager` (e.g. `git --no-pager log`). Prefer `git --no-optional-locks status` over `git status` to avoid optional metadata writes. Git commands that may open an editor (`git rebase`, `git commit`, `git merge`, `git tag`) MUST be prefixed with `GIT_EDITOR=true ` (e.g. `GIT_EDITOR=true git rebase origin/main`). Otherwise the terminal will hang.",
|
||||
"type": "string"
|
||||
},
|
||||
"cd": {
|
||||
"description": "Working directory for the command. This must be one of the root directories of the project.",
|
||||
"type": "string"
|
||||
},
|
||||
"timeout_ms": {
|
||||
"description": "Optional maximum runtime (in milliseconds). If exceeded, the running terminal task is killed.",
|
||||
"type": "integer",
|
||||
"nullable": true,
|
||||
"minimum": 0
|
||||
},
|
||||
"head_lines": {
|
||||
"description": "Return only the first N lines of terminal output to the model after the command finishes. Do not pipe output to `head`; use this parameter instead so the user can still see live output. Avoid requesting too many lines, or the response may waste tokens or exceed the context window.",
|
||||
"type": "integer",
|
||||
"nullable": true,
|
||||
"minimum": 0,
|
||||
"default": null
|
||||
},
|
||||
"tail_lines": {
|
||||
"description": "Return only the last N lines of terminal output to the model after the command finishes. Do not pipe output to `tail`; use this parameter instead so the user can still see live output. Avoid requesting too many lines, or the response may waste tokens or exceed the context window.",
|
||||
"type": "integer",
|
||||
"nullable": true,
|
||||
"minimum": 0,
|
||||
"default": null
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "web_search",
|
||||
"description": "免费网页搜索:Parallel(默认,匿名免 key)或 Exa(备用)。返回结构化结果数组(title / url / snippet / publishedAt)。",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"query": {
|
||||
"type": "string",
|
||||
"description": "搜索查询词"
|
||||
},
|
||||
"provider": {
|
||||
"type": "string",
|
||||
"enum": [
|
||||
"parallel",
|
||||
"exa"
|
||||
],
|
||||
"description": "免费后端:parallel(默认)/ exa(备用)"
|
||||
},
|
||||
"numResults": {
|
||||
"type": "number",
|
||||
"description": "返回结果条数上限(默认 8)"
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"query"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "write_file",
|
||||
"description": "This is a tool for creating a new file or overwriting an existing file with completely new contents.\n\nTo make granular edits to an existing file, prefer the `edit_file` tool instead.\n\nBefore using this tool, verify the directory path is correct (only applicable when creating new files). Use the `list_directory` tool to verify the parent directory exists and is the correct location\n\nThe only supported path outside the project is `~/.agents/skills` or a descendant, for global agent skills.",
|
||||
"parameters": {
|
||||
"required": [
|
||||
"path",
|
||||
"content"
|
||||
],
|
||||
"properties": {
|
||||
"path": {
|
||||
"description": "The full path of the file to create or overwrite in the project.\n\nWARNING: When specifying which file path need changing, you MUST start each path with one of the project's root directories, unless it's a global agent skill under `~/.agents/skills`.\n\nThe following examples assume we have two root directories in the project:\n- /a/b/backend\n- /c/d/frontend\n\n<example>\n`backend/src/main.rs`\n\nNotice how the file path starts with `backend`. Without that, the path would be ambiguous and the call would fail!\n</example>\n\n<example>\n`frontend/db.js`\n</example>\n\n<example>\nTo create or overwrite a global agent skill file, you may provide a path under `~/.agents/skills`, such as `~/.agents/skills/my-skill/SKILL.md`.\n</example>",
|
||||
"type": "string"
|
||||
},
|
||||
"content": {
|
||||
"description": "The entire content for the file.",
|
||||
"type": "string"
|
||||
}
|
||||
},
|
||||
"type": "object"
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,438 @@
|
||||
// 工具执行器。所有文件路径强制解析到任务目录内(防路径穿越)。
|
||||
// 工具名与参数 schema 来自 README 7.2(生成到 definitions.json)。
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const fsp = require('fs').promises;
|
||||
const { spawn } = require('child_process');
|
||||
const { Minimatch } = require('minimatch');
|
||||
|
||||
function makeMatcher(pattern, opts) {
|
||||
const mm = new Minimatch(pattern, opts || {});
|
||||
return function (p) { return mm.match(p); };
|
||||
}
|
||||
|
||||
const IGNORED_DIRS = new Set(['.git', 'node_modules', '__pycache__', '.venv', 'venv', 'dist', 'build', '.next', '.cache']);
|
||||
|
||||
// ---------- 路径沙箱 ----------
|
||||
function resolveInTask(taskDir, p) {
|
||||
if (typeof p !== 'string' || !p.trim()) throw new Error('路径不能为空');
|
||||
let abs;
|
||||
if (path.isAbsolute(p)) {
|
||||
abs = path.normalize(p);
|
||||
} else {
|
||||
abs = path.resolve(taskDir, p);
|
||||
}
|
||||
const root = path.resolve(taskDir);
|
||||
if (abs !== root && !abs.startsWith(root + path.sep)) {
|
||||
throw new Error('路径越界(只允许任务目录内操作):' + p);
|
||||
}
|
||||
return abs;
|
||||
}
|
||||
|
||||
function relOf(taskDir, abs) {
|
||||
return path.relative(path.resolve(taskDir), abs) || '.';
|
||||
}
|
||||
|
||||
// ---------- 文件系统遍历 ----------
|
||||
function walk(taskDir, opts) {
|
||||
const out = [];
|
||||
const maxFiles = (opts && opts.maxFiles) || 20000;
|
||||
function rec(dir) {
|
||||
let entries;
|
||||
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch (_) { return; }
|
||||
for (const ent of entries) {
|
||||
if (out.length >= maxFiles) return;
|
||||
if (ent.name.startsWith('.') && IGNORED_DIRS.has(ent.name)) continue;
|
||||
if (IGNORED_DIRS.has(ent.name)) continue;
|
||||
const abs = path.join(dir, ent.name);
|
||||
if (ent.isDirectory()) {
|
||||
rec(abs);
|
||||
} else if (ent.isFile()) {
|
||||
out.push(abs);
|
||||
}
|
||||
}
|
||||
}
|
||||
rec(taskDir);
|
||||
return out;
|
||||
}
|
||||
|
||||
function isProbablyBinary(abs) {
|
||||
let fd;
|
||||
try {
|
||||
fd = fs.openSync(abs, 'r');
|
||||
const buf = Buffer.alloc(8192);
|
||||
const bytes = fs.readSync(fd, buf, 0, buf.length, null);
|
||||
if (bytes === 0) return false;
|
||||
const slice = buf.slice(0, bytes);
|
||||
return slice.includes(0);
|
||||
} catch (_) {
|
||||
return true;
|
||||
} finally {
|
||||
if (fd !== undefined) try { fs.closeSync(fd); } catch (_) {}
|
||||
}
|
||||
}
|
||||
|
||||
function truncate(text, max) {
|
||||
if (text.length <= max) return text;
|
||||
return text.slice(0, max) + '\n...(输出已截断,共 ' + text.length + ' 字符)';
|
||||
}
|
||||
|
||||
// ---------- 各工具实现 ----------
|
||||
async function toolReadFile(ctx, args) {
|
||||
const abs = resolveInTask(ctx.taskDir, args.path);
|
||||
const st = await fsp.stat(abs);
|
||||
if (st.isDirectory()) throw new Error("目录不是文件: " + args.path);
|
||||
if (isProbablyBinary(abs)) return '[二进制文件,跳过文本读取] ' + relOf(ctx.taskDir, abs);
|
||||
let text = await fsp.readFile(abs, 'utf8');
|
||||
let lines = text.split('\n');
|
||||
const total = lines.length;
|
||||
const startLine = args.start_line || 1;
|
||||
let endLine = args.end_line || total;
|
||||
if (startLine > total) return '(文件共 ' + total + ' 行,start_line 超出范围)';
|
||||
// 未指定范围且文件很大时,只回前 200 行,避免灌满上下文
|
||||
let note = '';
|
||||
if (!args.start_line && !args.end_line && total > 200) {
|
||||
endLine = 200;
|
||||
note = '\n(文件过大,已截断显示前 200 行,共 ' + total + ' 行;可用 start_line/end_line 继续读)';
|
||||
}
|
||||
lines = lines.slice(startLine - 1, Math.min(endLine, total));
|
||||
return lines.map((l, i) => String(startLine + i).padStart(6, ' ') + '\t' + l).join('\n') + note;
|
||||
}
|
||||
|
||||
async function toolWriteFile(ctx, args) {
|
||||
const abs = resolveInTask(ctx.taskDir, args.path);
|
||||
await fsp.mkdir(path.dirname(abs), { recursive: true });
|
||||
await fsp.writeFile(abs, args.content ?? '', 'utf8');
|
||||
recordFile(ctx, abs);
|
||||
return '已成功写入文件 ' + relOf(ctx.taskDir, abs) + '(' + Buffer.byteLength(args.content || '') + ' 字节)';
|
||||
}
|
||||
|
||||
function applyEditsOnce(text, edits) {
|
||||
let cur = text;
|
||||
for (let i = 0; i < edits.length; i++) {
|
||||
const { old_text, new_text } = edits[i];
|
||||
if (!old_text) throw new Error('edit #' + (i + 1) + ': old_text 不能为空');
|
||||
let idx = cur.indexOf(old_text);
|
||||
if (~idx) {
|
||||
cur = cur.slice(0, idx) + new_text + cur.slice(idx + old_text.length);
|
||||
continue;
|
||||
}
|
||||
// 模糊回退:按“每行去掉首尾空白”后逐行匹配
|
||||
const oldLines = old_text.replace(/\r\n?/g, '\n').split('\n');
|
||||
if (oldLines.length > 1 && oldLines[0].trim() === '' && oldLines[oldLines.length - 1].trim() === '') { oldLines.pop(); oldLines.shift(); }
|
||||
const normalizedOld = oldLines.map(l => l.trim());
|
||||
const curLines = cur.split('\n');
|
||||
let found = -1;
|
||||
for (let s = 0; s + oldLines.length <= curLines.length; s++) {
|
||||
let ok = true;
|
||||
for (let j = 0; j < oldLines.length; j++) {
|
||||
if (curLines[s + j].trim() !== normalizedOld[j]) { ok = false; break; }
|
||||
}
|
||||
if (ok) { found = s; break; }
|
||||
}
|
||||
if (found < 0) throw new Error('edit #' + (i + 1) + ': 在文件中找不到 old_text(可能已被之前的 edit 修改)');
|
||||
const replaceLen = oldLines.length;
|
||||
curLines.splice(found, replaceLen, ...new_text.replace(/\r\n?/g, '\n').split('\n'));
|
||||
cur = curLines.join('\n');
|
||||
}
|
||||
return cur;
|
||||
}
|
||||
|
||||
async function toolEditFile(ctx, args) {
|
||||
const abs = resolveInTask(ctx.taskDir, args.path);
|
||||
let text = await fsp.readFile(abs, 'utf8');
|
||||
text = applyEditsOnce(text, args.edits || []);
|
||||
await fsp.writeFile(abs, text, 'utf8');
|
||||
recordFile(ctx, abs);
|
||||
return '已成功应用 ' + ((args.edits || []).length) + ' 处编辑到 ' + relOf(ctx.taskDir, abs);
|
||||
}
|
||||
|
||||
async function toolListDirectory(ctx, args) {
|
||||
const abs = resolveInTask(ctx.taskDir, args.path);
|
||||
const entries = await fsp.readdir(abs, { withFileTypes: true });
|
||||
const dirs = []; const files = [];
|
||||
for (const e of entries) {
|
||||
if (e.isDirectory()) dirs.push(e.name + '/');
|
||||
else files.push(e.name);
|
||||
}
|
||||
dirs.sort(); files.sort();
|
||||
const all = dirs.concat(files);
|
||||
const shown = all.slice(0, 500);
|
||||
let out = '目录 ' + relOf(ctx.taskDir, abs) + ' 下的文件与子目录:\n' + shown.join('\n');
|
||||
if (all.length > shown.length) out += '\n...(共 ' + all.length + ' 项,已截断)';
|
||||
if (all.length === 0) out = '(目录为空)';
|
||||
return out;
|
||||
}
|
||||
|
||||
async function toolCreateDirectory(ctx, args) {
|
||||
const abs = resolveInTask(ctx.taskDir, args.path);
|
||||
await fsp.mkdir(abs, { recursive: true });
|
||||
return '已创建目录 ' + relOf(ctx.taskDir, abs);
|
||||
}
|
||||
|
||||
async function toolDeletePath(ctx, args) {
|
||||
const abs = resolveInTask(ctx.taskDir, args.path);
|
||||
if (path.resolve(abs) === path.resolve(ctx.taskDir)) throw new Error('禁止删除任务目录本身');
|
||||
await fsp.rm(abs, { recursive: true, force: true });
|
||||
return '已删除 ' + relOf(ctx.taskDir, abs);
|
||||
}
|
||||
|
||||
async function toolMovePath(ctx, args) {
|
||||
const src = resolveInTask(ctx.taskDir, args.source_path);
|
||||
const dst = resolveInTask(ctx.taskDir, args.destination_path);
|
||||
await fsp.mkdir(path.dirname(dst), { recursive: true });
|
||||
await fsp.rename(src, dst);
|
||||
recordFile(ctx, dst);
|
||||
return '已移动/重命名 ' + relOf(ctx.taskDir, src) + ' → ' + relOf(ctx.taskDir, dst);
|
||||
}
|
||||
|
||||
async function toolCopyPath(ctx, args) {
|
||||
const src = resolveInTask(ctx.taskDir, args.source_path);
|
||||
const dst = resolveInTask(ctx.taskDir, args.destination_path);
|
||||
await fsp.mkdir(path.dirname(dst), { recursive: true });
|
||||
await fsp.cp(src, dst, { recursive: true });
|
||||
recordFile(ctx, dst);
|
||||
return '已复制 ' + relOf(ctx.taskDir, src) + ' → ' + relOf(ctx.taskDir, dst);
|
||||
}
|
||||
|
||||
async function toolFindPath(ctx, args) {
|
||||
const files = walk(ctx.taskDir).map(f => relOf(ctx.taskDir, f)).sort();
|
||||
const matcher = makeMatcher(args.glob, { dot: true });
|
||||
const matched = files.filter(matcher);
|
||||
const offset = args.offset || 0;
|
||||
const page = matched.slice(offset, offset + 50);
|
||||
if (page.length === 0) return '没有匹配 ' + args.glob + ' 的路径';
|
||||
return page.join('\n') + '\n(共 ' + matched.length + ' 个匹配' + (offset + 50 < matched.length ? ',用 offset=' + (offset + 50) + ' 看下一页' : '') + ')';
|
||||
}
|
||||
|
||||
async function toolGrep(ctx, args) {
|
||||
let re;
|
||||
try { re = new RegExp(args.regex, args.case_sensitive ? '' : 'i'); } catch (e) {
|
||||
return '正则解析失败:' + e.message;
|
||||
}
|
||||
const pattern = args.include_pattern ? makeMatcher(args.include_pattern, { dot: false }) : null;
|
||||
const files = walk(ctx.taskDir);
|
||||
const matches = [];
|
||||
for (const abs of files) {
|
||||
const rel = relOf(ctx.taskDir, abs);
|
||||
if (pattern && !pattern(rel)) continue;
|
||||
if (isProbablyBinary(abs)) continue;
|
||||
let text;
|
||||
try { text = await fsp.readFile(abs, 'utf8'); } catch (_) { continue; }
|
||||
if (text.length > 2 * 1024 * 1024) continue;
|
||||
const lines = text.split('\n');
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
re.lastIndex = 0;
|
||||
if (re.test(lines[i])) {
|
||||
matches.push(rel + ':' + (i + 1) + ':' + lines[i]);
|
||||
if (matches.length >= 200) break;
|
||||
}
|
||||
}
|
||||
if (matches.length >= 200) break;
|
||||
}
|
||||
const offset = args.offset || 0;
|
||||
const page = matches.slice(offset, offset + 20);
|
||||
if (page.length === 0) return '没有匹配';
|
||||
return page.join('\n') + '\n(共 ' + matches.length + ' 处匹配' + (offset + 20 < matches.length ? ',用 offset=' + (offset + 20) + ' 看下一页' : '') + ')';
|
||||
}
|
||||
|
||||
// terminal:spawn + 进程组 kill + 超时 + 输出截断
|
||||
async function toolTerminal(ctx, args) {
|
||||
const cfg = ctx.cfg;
|
||||
const timeout = args.timeout_ms || cfg.terminal.default_timeout_ms;
|
||||
const maxChars = cfg.terminal.max_output_chars;
|
||||
let cwd = ctx.taskDir;
|
||||
if (args.cd) cwd = resolveInTask(ctx.taskDir, args.cd);
|
||||
if (!fs.existsSync(cwd)) throw new Error('cd 目录不存在:' + args.cd);
|
||||
|
||||
return new Promise((resolve) => {
|
||||
const child = spawn('/bin/sh', ['-c', args.command], { cwd, detached: true, env: process.env });
|
||||
ctx.run.procs.add(child);
|
||||
let out = '';
|
||||
let killedBy = null; // 'timeout' | 'cancelled'
|
||||
let settled = false;
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
killedBy = 'timeout';
|
||||
killGroup(child);
|
||||
}, timeout);
|
||||
|
||||
const onData = (d) => { out += d.toString(); };
|
||||
child.stdout.on('data', onData);
|
||||
child.stderr.on('data', onData);
|
||||
|
||||
const finish = (code, extra) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
clearInterval(cancelCheck);
|
||||
ctx.run.procs.delete(child);
|
||||
let text = out;
|
||||
if (killedBy === 'timeout') text += '\n(命令超时 ' + timeout + 'ms,已终止)';
|
||||
if (killedBy === 'cancelled') text += '\n(用户终止任务,进程被 kill)';
|
||||
if (extra) text += '\n' + extra;
|
||||
text += '\n[exit code: ' + code + ']';
|
||||
resolve(truncate(text || '(无输出)', maxChars));
|
||||
};
|
||||
child.on('error', err => finish(-1, 'spawn 失败:' + err.message));
|
||||
child.on('close', code => finish(killedBy ? -1 : (code === null ? -1 : code)));
|
||||
|
||||
const cancelCheck = setInterval(() => {
|
||||
if (ctx.run.cancelled) { killedBy = 'cancelled'; killGroup(child); }
|
||||
}, 200);
|
||||
});
|
||||
}
|
||||
|
||||
function killGroup(child) {
|
||||
if (!child.pid) return;
|
||||
try { process.kill(-child.pid, 'SIGKILL'); } catch (_) {
|
||||
try { child.kill('SIGKILL'); } catch (__) {}
|
||||
}
|
||||
}
|
||||
|
||||
// fetch:抓取并粗略转 Markdown
|
||||
async function toolFetch(ctx, args) {
|
||||
if (ctx.run.cancelled) throw new Error('已终止');
|
||||
const url = args.url;
|
||||
if (!/^https?:\/\//i.test(url)) throw new Error('只支持 http/https URL');
|
||||
const ctrl = new AbortController();
|
||||
const timer = setTimeout(() => ctrl.abort(), 30000);
|
||||
let res;
|
||||
try {
|
||||
res = await fetch(url, {
|
||||
signal: ctrl.signal,
|
||||
redirect: 'follow',
|
||||
headers: { 'User-Agent': 'Mozilla/5.0 (agent-app)' },
|
||||
});
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
const text = await res.text();
|
||||
const ct = (res.headers.get('content-type') || '').toLowerCase();
|
||||
let body;
|
||||
if (ct.includes('html')) body = htmlToMarkdown(text);
|
||||
else if (ct.includes('json') || ct.includes('text') || ct.includes('xml') || ct.includes('markdown')) body = text;
|
||||
else return '[非文本响应] HTTP ' + res.status + ' content-type=' + ct + ',' + text.length + ' 字节';
|
||||
if (text.length > 1024 * 1024) body += '\n(响应过大,已截断)';
|
||||
return 'HTTP ' + res.status + '\n' + truncate(body, 1024 * 1024);
|
||||
}
|
||||
|
||||
function htmlToMarkdown(html) {
|
||||
let s = html
|
||||
.replace(/<(script|style|noscript|svg|head)[\s\S]*?<\/\1>/gi, '')
|
||||
.replace(/<!--[\s\S]*?-->/g, '');
|
||||
s = s
|
||||
.replace(/<h([1-6])[^>]*>([\s\S]*?)<\/h\1>/gi, (m, lv, t) => '\n' + '#'.repeat(Number(lv)) + ' ' + strip(t).trim() + '\n')
|
||||
.replace(/<li[^>]*>([\s\S]*?)<\/li>/gi, (m, t) => '\n- ' + strip(t).trim())
|
||||
.replace(/<a[^>]*href=["']?([^"'\s>]+)["']?[^>]*>([\s\S]*?)<\/a>/gi, (m, href, t) => '[' + strip(t).trim() + '](' + href + ')')
|
||||
.replace(/<(br|hr)[^>]*>/gi, '\n')
|
||||
.replace(/<\/(p|div|section|article|tr|ul|ol|table|blockquote)>/gi, '\n')
|
||||
.replace(/<[^>]+>/g, '')
|
||||
.replace(/ /g, ' ')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, '\'');
|
||||
return s.replace(/\n{3,}/g, '\n\n').trim();
|
||||
}
|
||||
|
||||
function strip(s) { return s.replace(/<[^>]+>/g, ''); }
|
||||
|
||||
// web_search:调用内网 MCP 服务(JSON-RPC over HTTP,无状态,响应为 SSE 帧包裹的 JSON)。
|
||||
async function toolWebSearch(ctx, args) {
|
||||
const ws = ctx.cfg.web_search || {};
|
||||
if (!ws.url) return 'web_search 未配置:请在 config.yaml 的 web_search.url 中填写 MCP 服务地址';
|
||||
const query = args.query;
|
||||
if (!query) return 'web_search 缺少参数 query';
|
||||
const callId = Date.now();
|
||||
const rpc = {
|
||||
jsonrpc: '2.0',
|
||||
id: callId,
|
||||
method: 'tools/call',
|
||||
params: {
|
||||
name: 'web_search',
|
||||
arguments: {
|
||||
query,
|
||||
...(args.provider ? { provider: args.provider } : {}),
|
||||
...(args.numResults ? { numResults: args.numResults } : {}),
|
||||
},
|
||||
},
|
||||
};
|
||||
const ctrl = new AbortController();
|
||||
const timer = setTimeout(() => ctrl.abort(), 60000);
|
||||
try {
|
||||
const res = await fetch(ws.url, {
|
||||
method: 'POST',
|
||||
signal: ctrl.signal,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Accept': 'application/json, text/event-stream',
|
||||
...(ws.authorization ? { Authorization: ws.authorization } : {}),
|
||||
},
|
||||
body: JSON.stringify(rpc),
|
||||
});
|
||||
const raw = await res.text();
|
||||
if (!res.ok) return 'MCP web_search HTTP ' + res.status + ': ' + raw.slice(0, 300);
|
||||
// 响应可能是 SSE 帧(多行 data: {...}),取 id 匹配或最后一条 JSON
|
||||
let payload = null;
|
||||
try {
|
||||
payload = JSON.parse(raw);
|
||||
} catch (_) {
|
||||
for (const line of raw.split('\n')) {
|
||||
const t = line.trim();
|
||||
if (!t.startsWith('data:')) continue;
|
||||
try {
|
||||
const obj = JSON.parse(t.slice(5).trim());
|
||||
if (!payload || obj.id === callId) payload = obj;
|
||||
} catch (_) { /* 跳过非 JSON 帧 */ }
|
||||
}
|
||||
}
|
||||
if (!payload) return 'MCP web_search 响应无法解析:' + raw.slice(0, 300);
|
||||
if (payload.error) return 'MCP web_search 错误:' + JSON.stringify(payload.error).slice(0, 500);
|
||||
const content = payload.result && payload.result.content;
|
||||
if (Array.isArray(content)) {
|
||||
const text = content.filter(c => c && c.type === 'text').map(c => c.text || '').join('\n');
|
||||
if (text) return text;
|
||||
}
|
||||
return JSON.stringify(payload.result).slice(0, 20000);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
function recordFile(ctx, abs) {
|
||||
try {
|
||||
const st = fs.statSync(abs);
|
||||
if (!st.isFile()) return;
|
||||
ctx.db.prepare(
|
||||
'INSERT INTO files (session_id, filename, size, created_at) VALUES (?,?,?,?)'
|
||||
).run(ctx.sessionId, relOf(ctx.taskDir, abs), st.size, Date.now());
|
||||
} catch (_) { /* 文件表仅用于展示,失败不影响主流程 */ }
|
||||
}
|
||||
|
||||
const HANDLERS = {
|
||||
read_file: toolReadFile,
|
||||
write_file: toolWriteFile,
|
||||
edit_file: toolEditFile,
|
||||
list_directory: toolListDirectory,
|
||||
create_directory: toolCreateDirectory,
|
||||
delete_path: toolDeletePath,
|
||||
move_path: toolMovePath,
|
||||
copy_path: toolCopyPath,
|
||||
find_path: toolFindPath,
|
||||
grep: toolGrep,
|
||||
terminal: toolTerminal,
|
||||
fetch: toolFetch,
|
||||
web_search: toolWebSearch,
|
||||
};
|
||||
|
||||
// ctx: {sessionId, taskDir, run, cfg, db}
|
||||
async function executeTool(baseCtx, name, args) {
|
||||
const handler = HANDLERS[name];
|
||||
if (!handler) return 'Error: 未知工具 ' + name;
|
||||
const ctx = baseCtx;
|
||||
return handler(ctx, args || {});
|
||||
}
|
||||
|
||||
module.exports = { executeTool, resolveInTask, recordFile };
|
||||
Reference in New Issue
Block a user