feat: Agent 工作区初始提交(源码+文档+Skills)
包含 CodeAgent 前后端源码、SKILLS、MCP、demo 代码与工作区文档。 排除依赖缓存、运行数据、备份与二进制附件,规则见 .gitignore。 Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
@@ -0,0 +1,234 @@
|
||||
"""
|
||||
白名单命令执行器
|
||||
================
|
||||
|
||||
【功能说明】
|
||||
受限执行系统命令(编译、测试、git 等),带白名单校验、超时保护、
|
||||
输出截断与审计日志。对应决策点 11「白名单受限执行」。
|
||||
|
||||
【技术选型理由】
|
||||
1. 选白名单而非完整 Shell(决策点 11 已论证):
|
||||
Agent 能跑编译验证假设,但不能 rm -rf /、不能改系统配置。
|
||||
2. list 参数传参(shell=False):杜绝命令注入,`&&`、`|`、`;` 全部失效。
|
||||
3. 超时 + 输出截断:防止编译卡死或日志刷爆上下文(硬约束 5 兜底)。
|
||||
|
||||
【实现思路】
|
||||
- ALLOWED_COMMANDS 白名单:mvn/npm/npx/git/java/javac 等;
|
||||
- 命令首段必须命中白名单,否则直接拒绝并审计;
|
||||
- cwd 强制限定在允许根目录内;
|
||||
- 执行结果统一返回 {stdout, stderr, returncode, truncated}。
|
||||
|
||||
【潜在风险与应对】
|
||||
风险1:白名单命令带危险子参数(如 `git push --force`、`mvn clean` 误删)。
|
||||
应对:一级黑名单子参数(push/force/reset --hard 等)直接拒绝。
|
||||
风险2:命令执行卡死占用资源。
|
||||
应对:强制 timeout(默认 60s,可配),超时 kill 进程组。
|
||||
风险3:输出超大撑爆 Agent 上下文。
|
||||
应对:stdout/stderr 各截断到 EXEC_OUTPUT_MAX_CHARS(默认 20000)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import shutil
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from app.config.settings import load_settings
|
||||
from app.tools.audit import log_action
|
||||
from app.tools.path_guard import ensure_under_root
|
||||
from app.tools.proc_flags import hidden_popen_kwargs
|
||||
|
||||
logger = logging.getLogger("agent.tools.executor")
|
||||
|
||||
# 允许执行的命令白名单(决策点 11)
|
||||
ALLOWED_COMMANDS = {
|
||||
"mvn", "npm", "npx", "git", "java", "javac", "python", "python3",
|
||||
}
|
||||
|
||||
# 禁止的子命令/参数(二级黑名单,防滥用)
|
||||
FORBIDDEN_PATTERNS = [
|
||||
"push", "--force", "-f ", "reset --hard", "clean --force",
|
||||
"rm ", "del ", "format", "shutdown", "mkfs",
|
||||
]
|
||||
|
||||
|
||||
class ExecutorError(RuntimeError):
|
||||
"""执行器异常(中文可读)"""
|
||||
|
||||
def __init__(self, message: str, *, error_type: str = "ExecutorError") -> None:
|
||||
super().__init__(message)
|
||||
self.error_type = error_type
|
||||
|
||||
|
||||
def _validate_command(args: list[str]) -> None:
|
||||
"""
|
||||
校验命令是否在白名单内。
|
||||
|
||||
【规则】
|
||||
1. args 非空且首段命中 ALLOWED_COMMANDS;
|
||||
2. 整条命令不得命中 FORBIDDEN_PATTERNS。
|
||||
"""
|
||||
if not args:
|
||||
raise ExecutorError("命令为空", error_type="EmptyCommand")
|
||||
|
||||
cmd_name = Path(args[0]).name.lower()
|
||||
if cmd_name not in ALLOWED_COMMANDS:
|
||||
raise ExecutorError(
|
||||
f"命令 {cmd_name} 不在白名单内(允许:{sorted(ALLOWED_COMMANDS)})",
|
||||
error_type="CommandNotAllowed",
|
||||
)
|
||||
|
||||
full = " ".join(args).lower()
|
||||
for pattern in FORBIDDEN_PATTERNS:
|
||||
if pattern in full:
|
||||
raise ExecutorError(
|
||||
f"命令包含被禁止的子参数:{pattern}(安全策略拒绝)",
|
||||
error_type="ForbiddenArgument",
|
||||
)
|
||||
|
||||
|
||||
def _resolve_command(cmd_name: str) -> str:
|
||||
"""
|
||||
解析命令为完整可执行路径。
|
||||
|
||||
【Windows 坑】mvn 实际是 mvn.cmd,subprocess 无 shell 时找不到;
|
||||
shutil.which 会自动解析 .cmd/.exe/.bat 后缀,必须先解析再执行。
|
||||
"""
|
||||
resolved = shutil.which(cmd_name)
|
||||
if resolved:
|
||||
return resolved
|
||||
# 兜底:逐个尝试常见 Windows 后缀
|
||||
for suffix in (".cmd", ".bat", ".exe"):
|
||||
candidate = shutil.which(cmd_name + suffix)
|
||||
if candidate:
|
||||
return candidate
|
||||
return cmd_name # 交给 FileNotFoundError 报错
|
||||
|
||||
|
||||
def run_command(
|
||||
args: list[str],
|
||||
cwd: str | Path,
|
||||
timeout: int | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
执行白名单命令。
|
||||
|
||||
【参数】
|
||||
args:命令参数列表(如 ["mvn", "-q", "compile"])
|
||||
cwd:工作目录(必须在允许范围内)
|
||||
timeout:超时秒数(默认取配置 EXEC_TIMEOUT_SECONDS)
|
||||
【返回】{stdout, stderr, returncode, truncated, command, cwd}
|
||||
"""
|
||||
settings = load_settings()
|
||||
timeout = timeout or settings.exec_timeout_seconds
|
||||
max_chars = settings.exec_output_max_chars
|
||||
|
||||
_validate_command(args)
|
||||
work_dir = ensure_under_root(Path(cwd), action="执行命令")
|
||||
|
||||
if not work_dir.exists():
|
||||
raise ExecutorError(f"工作目录不存在:{work_dir}", error_type="PathNotFound")
|
||||
|
||||
# Windows 下解析命令为完整路径(mvn → mvn.cmd)
|
||||
resolved_args = [_resolve_command(args[0])] + list(args[1:])
|
||||
command_str = " ".join(args)
|
||||
logger.info("执行命令:%s(cwd=%s)", command_str, work_dir)
|
||||
|
||||
try:
|
||||
completed = subprocess.run(
|
||||
resolved_args,
|
||||
cwd=str(work_dir),
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=timeout,
|
||||
shell=False,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
**hidden_popen_kwargs(),
|
||||
)
|
||||
except FileNotFoundError as exc:
|
||||
raise ExecutorError(
|
||||
f"命令不存在:{args[0]},请确认已安装并加入 PATH",
|
||||
error_type="CommandNotFound",
|
||||
) from exc
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
log_action(
|
||||
action="exec_command",
|
||||
target=command_str,
|
||||
result="failure",
|
||||
details={"error": "timeout", "timeout": timeout},
|
||||
)
|
||||
raise ExecutorError(
|
||||
f"命令执行超时(>{timeout}秒):{command_str}",
|
||||
error_type="Timeout",
|
||||
) from exc
|
||||
|
||||
stdout = completed.stdout or ""
|
||||
stderr = completed.stderr or ""
|
||||
truncated = False
|
||||
if len(stdout) > max_chars:
|
||||
stdout = stdout[:max_chars] + f"\n…(输出截断,共 {len(completed.stdout)} 字符)"
|
||||
truncated = True
|
||||
if len(stderr) > max_chars:
|
||||
stderr = stderr[:max_chars] + f"\n…(输出截断,共 {len(completed.stderr)} 字符)"
|
||||
truncated = True
|
||||
|
||||
log_action(
|
||||
action="exec_command",
|
||||
target=command_str,
|
||||
result="success" if completed.returncode == 0 else "failure",
|
||||
details={
|
||||
"returncode": completed.returncode,
|
||||
"cwd": str(work_dir),
|
||||
"stdout_len": len(completed.stdout or ""),
|
||||
"stderr_len": len(completed.stderr or ""),
|
||||
"truncated": truncated,
|
||||
},
|
||||
)
|
||||
|
||||
return {
|
||||
"command": command_str,
|
||||
"cwd": str(work_dir),
|
||||
"stdout": stdout,
|
||||
"stderr": stderr,
|
||||
"returncode": completed.returncode,
|
||||
"truncated": truncated,
|
||||
}
|
||||
|
||||
|
||||
# ---------- 便捷封装:编译验证 ----------
|
||||
|
||||
|
||||
def run_compile_check(project_path: str | Path) -> dict[str, Any]:
|
||||
"""
|
||||
对目标项目执行编译级验证(决策点 8)。
|
||||
|
||||
【自动识别】
|
||||
- 有 pom.xml → Maven:mvn -q -DskipTests compile
|
||||
- 有 package.json → npm:npm run build(或 tsc --noEmit)
|
||||
【返回】{passed, command, stdout, stderr}
|
||||
"""
|
||||
root = ensure_under_root(Path(project_path), action="编译验证")
|
||||
|
||||
if (root / "pom.xml").exists():
|
||||
result = run_command(["mvn", "-q", "-DskipTests", "compile"], cwd=root)
|
||||
elif (root / "package.json").exists():
|
||||
result = run_command(["npm", "run", "build"], cwd=root)
|
||||
else:
|
||||
return {
|
||||
"passed": False,
|
||||
"command": "",
|
||||
"stdout": "",
|
||||
"stderr": f"无法识别项目类型(未找到 pom.xml 或 package.json):{root}",
|
||||
"returncode": -1,
|
||||
}
|
||||
|
||||
return {
|
||||
"passed": result["returncode"] == 0,
|
||||
"command": result["command"],
|
||||
"stdout": result["stdout"],
|
||||
"stderr": result["stderr"],
|
||||
"returncode": result["returncode"],
|
||||
}
|
||||
Reference in New Issue
Block a user