feat: Agent 工作区初始提交(源码+文档+Skills)
包含 CodeAgent 前后端源码、SKILLS、MCP、demo 代码与工作区文档。 排除依赖缓存、运行数据、备份与二进制附件,规则见 .gitignore。 Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""自研工具层包:路径守卫 / 文件读写 / 搜索定位 / 白名单执行 / Git 操作 / 审计"""
|
||||
@@ -0,0 +1,91 @@
|
||||
"""
|
||||
审计日志
|
||||
========
|
||||
|
||||
【功能说明】
|
||||
记录工具层的每一次敏感操作(文件写入、命令执行、git 提交),
|
||||
落盘到 D:\\Agent\\agent\\data\\audit,支持事后追溯与合规审查。
|
||||
|
||||
【技术选型理由】
|
||||
1. 硬约束 5 要求「任何异常不能直接崩溃、要可排查」:
|
||||
审计日志是排查 Agent 误操作的第一手证据。
|
||||
2. 追加写 JSONL(每行一个 JSON):无需数据库、可 grep、可程序化分析。
|
||||
3. 与工具层同步写入:不异步、不缓冲,保证操作与日志强一致。
|
||||
|
||||
【实现思路】
|
||||
- log_action() 记录 {时间, 操作, 目标, 结果, 详情};
|
||||
- 按日期分文件:audit-YYYYMMDD.jsonl,便于按天归档;
|
||||
- 敏感字段(如完整文件内容)只记摘要,不记全文(防止日志膨胀+泄密)。
|
||||
|
||||
【潜在风险与应对】
|
||||
风险1:日志写入失败影响主流程。
|
||||
应对:日志写入全程 try/except,失败只 warning 不抛出。
|
||||
风险2:日志文件无限膨胀。
|
||||
应对:按日期分文件;后续可加自动清理(保留 N 天)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
logger = logging.getLogger("agent.tools.audit")
|
||||
|
||||
# 审计日志默认目录
|
||||
DEFAULT_AUDIT_DIR = Path(r"D:\Agent\agent\data\audit")
|
||||
|
||||
|
||||
def log_action(
|
||||
action: str,
|
||||
target: str,
|
||||
result: str = "success",
|
||||
details: dict[str, Any] | None = None,
|
||||
audit_dir: Path | None = None,
|
||||
) -> None:
|
||||
"""
|
||||
记录一次工具操作。
|
||||
|
||||
【参数】
|
||||
action:操作类型(file_write / file_edit / exec_command / git_commit 等)
|
||||
target:操作对象(文件路径/命令/git 仓库)
|
||||
result:success / failure / denied
|
||||
details:补充详情(会做摘要,不记全文)
|
||||
"""
|
||||
try:
|
||||
audit_dir = audit_dir or DEFAULT_AUDIT_DIR
|
||||
audit_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
today = datetime.now().strftime("%Y%m%d")
|
||||
log_file = audit_dir / f"audit-{today}.jsonl"
|
||||
|
||||
entry = {
|
||||
"timestamp": datetime.now().astimezone().isoformat(timespec="seconds"),
|
||||
"action": action,
|
||||
"target": target,
|
||||
"result": result,
|
||||
"details": _summarize_details(details or {}),
|
||||
}
|
||||
|
||||
with open(log_file, "a", encoding="utf-8") as f:
|
||||
f.write(json.dumps(entry, ensure_ascii=False) + "\n")
|
||||
|
||||
except Exception as exc: # noqa: BLE001 - 审计失败不阻塞主流程
|
||||
logger.warning("审计日志写入失败:%s", exc)
|
||||
|
||||
|
||||
def _summarize_details(details: dict[str, Any]) -> dict[str, Any]:
|
||||
"""摘要化详情:长文本截断,避免日志膨胀。"""
|
||||
summary: dict[str, Any] = {}
|
||||
for key, value in details.items():
|
||||
if isinstance(value, str) and len(value) > 500:
|
||||
summary[key] = value[:500] + f"…(共{len(value)}字符)"
|
||||
elif isinstance(value, (int, float, bool)):
|
||||
summary[key] = value
|
||||
elif value is None:
|
||||
summary[key] = None
|
||||
else:
|
||||
summary[key] = str(value)[:200]
|
||||
return summary
|
||||
@@ -0,0 +1,605 @@
|
||||
"""
|
||||
Claude Code 改码引擎
|
||||
====================
|
||||
|
||||
【功能说明】
|
||||
把 Claude Code CLI 作为「改码执行器」接入 Agent 系统。
|
||||
当 CODING_ENGINE=claude_code 时,Worker 的 modify 节点调用
|
||||
Claude Code 完成代码阅读、理解、修改,替代自研工具链。
|
||||
|
||||
【技术选型理由】
|
||||
1. 选 subprocess 调用 claude CLI 而非 Agent SDK:
|
||||
CLI 成熟稳定、已配置好 ccswitch 模型路由、无需额外依赖。
|
||||
2. 非交互模式(-p / --print):一次调用完成任务并输出结果,
|
||||
适合编排集成。
|
||||
3. 工作目录指向项目代码根目录:Claude Code 在该目录下读写文件。
|
||||
|
||||
【实现思路】
|
||||
- build_prompt():把任务描述、目标文件线索、上次失败原因组装成 Prompt;
|
||||
- execute():subprocess 调用 claude CLI,捕获输出;
|
||||
- 结果解析:提取 Claude Code 的改动摘要与执行结论。
|
||||
|
||||
【潜在风险与应对】
|
||||
风险1:claude CLI 不可用(未安装/PATH 缺失)。
|
||||
应对:启动时探测,失败则降级到 builtin 引擎并告警。
|
||||
风险2:Claude Code 改码范围过大(改无关文件)。
|
||||
应对:Prompt 中明确约束「只改指定文件的指定问题」,
|
||||
执行前对目标目录做快照(复用 file_tools 的备份机制)。
|
||||
风险3:执行时间长(Claude Code 自主循环改码)。
|
||||
应对:超时默认 300 秒,超时后终止并降级。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import shutil
|
||||
import subprocess
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from app.tools.audit import log_action
|
||||
from app.tools.file_tools import _backup_file
|
||||
|
||||
logger = logging.getLogger("agent.claude_engine")
|
||||
|
||||
# 运行中的子进程注册表:task_id → Popen(供「停止」按钮 kill 用)
|
||||
_running_processes: dict[str, subprocess.Popen] = {}
|
||||
|
||||
|
||||
def kill_process(task_id: str) -> bool:
|
||||
"""
|
||||
强制终止指定任务的 Claude CLI 子进程。
|
||||
|
||||
【用途】用户点「停止」时调用,防止进程失控。
|
||||
【返回】是否成功 kill
|
||||
"""
|
||||
proc = _running_processes.pop(task_id, None)
|
||||
if proc is None:
|
||||
return False
|
||||
try:
|
||||
proc.kill()
|
||||
proc.wait()
|
||||
logger.info("已终止任务 %s 的 Claude 进程", task_id)
|
||||
return True
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("终止进程失败:%s", exc)
|
||||
return False
|
||||
|
||||
|
||||
class ClaudeCodeError(RuntimeError):
|
||||
"""Claude Code 引擎异常"""
|
||||
|
||||
def __init__(self, message: str, *, error_type: str = "ClaudeCodeError") -> None:
|
||||
super().__init__(message)
|
||||
self.error_type = error_type
|
||||
|
||||
|
||||
def is_available() -> bool:
|
||||
"""检测 claude CLI 是否可用。"""
|
||||
return shutil.which("claude") is not None
|
||||
|
||||
|
||||
def get_claude_path() -> str:
|
||||
"""
|
||||
获取 claude CLI 的完整可执行路径。
|
||||
|
||||
【Windows 坑】subprocess.run(["claude"], shell=False) 找不到 claude.CMD,
|
||||
因为不走 PATHEXT 扩展名解析。必须用 shutil.which 拿到完整路径再调用。
|
||||
"""
|
||||
path = shutil.which("claude")
|
||||
if not path:
|
||||
raise ClaudeCodeError(
|
||||
"claude CLI 不可用,请确认已安装 Claude Code 并加入 PATH",
|
||||
error_type="ClaudeNotFound",
|
||||
)
|
||||
return path
|
||||
|
||||
|
||||
def _extract_session_id_from_line(line: str) -> str:
|
||||
"""从单行 stream-json 中取 session_id(取不到返回空串)。"""
|
||||
import json as _json
|
||||
|
||||
line = line.strip()
|
||||
if not line:
|
||||
return ""
|
||||
try:
|
||||
obj = _json.loads(line)
|
||||
except Exception: # noqa: BLE001
|
||||
return ""
|
||||
if isinstance(obj, dict) and obj.get("session_id"):
|
||||
return str(obj["session_id"])
|
||||
return ""
|
||||
|
||||
|
||||
class _StreamTextExtractor:
|
||||
"""
|
||||
从 Claude Code stream-json 逐行提取可展示文本(有状态)。
|
||||
|
||||
【为什么要状态】
|
||||
`--include-partial-messages` 打开后,同一条回复会出现两遍:
|
||||
① 增量:{"type":"stream_event","event":{"type":"content_block_delta",
|
||||
"delta":{"type":"text_delta","text":"..."}}}
|
||||
② 成块:{"type":"assistant","message":{"content":[{"type":"text","text":"..."}]}}
|
||||
两者都推给前端,文本会翻倍。故:已推过增量就跳过成块文本。
|
||||
|
||||
【兼容的三种形状】
|
||||
A. Claude Code CLI 增量(嵌在 event 里)
|
||||
B. Messages API 增量(顶层 delta)—— 历史实现按此解析,保留兼容
|
||||
C. 成块文本(assistant / message.content)—— 未开 partial 时的兜底
|
||||
|
||||
【刻意不推】
|
||||
`result` 是最终汇总,前端已通过增量/成块累积过,再推必重复(沿用 BUG-2 原则)。
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._saw_delta = False
|
||||
|
||||
def feed(self, line: str) -> str:
|
||||
line = line.strip()
|
||||
if not line:
|
||||
return ""
|
||||
import json as _json
|
||||
|
||||
try:
|
||||
obj = _json.loads(line)
|
||||
except Exception: # noqa: BLE001 - 非 JSON 行,原样透出
|
||||
return line + "\n"
|
||||
if not isinstance(obj, dict):
|
||||
return ""
|
||||
|
||||
# ① 错误事件必须透出,用户要看到失败原因
|
||||
if obj.get("type") == "error" and isinstance(obj.get("message"), str):
|
||||
return f"\n[错误] {obj['message']}"
|
||||
|
||||
# ② 增量形状 A:CLI 的 stream_event 嵌套
|
||||
event = obj.get("event")
|
||||
if isinstance(event, dict):
|
||||
delta = event.get("delta")
|
||||
if isinstance(delta, dict) and isinstance(delta.get("text"), str):
|
||||
self._saw_delta = True
|
||||
return delta["text"]
|
||||
|
||||
# ③ 增量形状 B:Messages API 顶层 delta
|
||||
delta = obj.get("delta")
|
||||
if isinstance(delta, dict) and isinstance(delta.get("text"), str):
|
||||
self._saw_delta = True
|
||||
return delta["text"]
|
||||
|
||||
# ④ 成块文本(形状 C):已有增量就跳过,防重复
|
||||
if self._saw_delta:
|
||||
return ""
|
||||
return self._block_text(obj)
|
||||
|
||||
@staticmethod
|
||||
def _block_text(obj: dict) -> str:
|
||||
"""取成块文本:只认 type=text 的 content block,跳过 tool_use / tool_result。"""
|
||||
if isinstance(obj.get("result"), str):
|
||||
return "" # 最终汇总不推流式,防重复
|
||||
msg = obj.get("message")
|
||||
source = msg if isinstance(msg, dict) else obj
|
||||
content = source.get("content")
|
||||
if isinstance(content, str):
|
||||
return content
|
||||
if isinstance(content, list):
|
||||
parts = [
|
||||
block.get("text", "")
|
||||
for block in content
|
||||
if isinstance(block, dict)
|
||||
and block.get("type") == "text"
|
||||
and isinstance(block.get("text"), str)
|
||||
]
|
||||
return "".join(parts)
|
||||
return ""
|
||||
|
||||
|
||||
def _extract_stream_text(line: str) -> str:
|
||||
"""
|
||||
无状态便捷入口:单行提取文本(不跨行去重)。
|
||||
|
||||
【注意】execute() 内部用有状态的 _StreamTextExtractor;
|
||||
此函数仅供单行调试/兼容旧调用,跨行场景会失去 delta/成块去重能力。
|
||||
"""
|
||||
return _StreamTextExtractor().feed(line)
|
||||
|
||||
|
||||
def _extract_final_text(stdout: str) -> str:
|
||||
"""
|
||||
从 stream-json 全量输出中提取最终完整文本。
|
||||
|
||||
优先取顶层 `result` 字段(Claude 的最终汇总,最权威);
|
||||
没有 result 行时用 _StreamTextExtractor 累积(自动去重 delta 与成块文本)。
|
||||
"""
|
||||
import json as _json
|
||||
|
||||
for line in stdout.splitlines():
|
||||
line = line.strip()
|
||||
if not line:
|
||||
continue
|
||||
try:
|
||||
obj = _json.loads(line)
|
||||
except Exception: # noqa: BLE001
|
||||
continue
|
||||
if isinstance(obj, dict) and isinstance(obj.get("result"), str):
|
||||
return obj["result"]
|
||||
|
||||
extractor = _StreamTextExtractor()
|
||||
parts = [text for text in (extractor.feed(line) for line in stdout.splitlines()) if text]
|
||||
return "".join(parts)
|
||||
|
||||
|
||||
def _extract_session_id(stdout: str) -> str:
|
||||
"""
|
||||
从 stream-json 输出中提取 Claude 会话 ID。
|
||||
|
||||
stream-json 开头会有:{"type":"system","subtype":"init","session_id":"xxx",...}
|
||||
"""
|
||||
for line in stdout.splitlines():
|
||||
sid = _extract_session_id_from_line(line)
|
||||
if sid:
|
||||
return sid
|
||||
return ""
|
||||
|
||||
|
||||
def _normalize_model_id(model: str) -> str:
|
||||
"""
|
||||
从模型注册表 key 中提取真实 model_id。
|
||||
|
||||
【背景】模型管理的注册表 key 格式是 "provider_key/model_id"(如 "小米6360/mimo-v2.6-pro"),
|
||||
但 Claude CLI 只认 model_id(如 "mimo-v2.6-pro"),不认带前缀的 key。
|
||||
【规则】含 "/" 时取最后一段作为 model_id;不含则原样返回。
|
||||
"""
|
||||
if not model:
|
||||
return model
|
||||
return model.rsplit("/", 1)[-1] if "/" in model else model
|
||||
|
||||
|
||||
def prepare_claude_config(model_id: str, session_id: str = "") -> Path:
|
||||
"""
|
||||
生成 Claude Code 独立配置目录(不动用户的 ~/.claude/settings.json)。
|
||||
|
||||
【方案】在 ~/.claude/agent-{session_id}/ 下写一份 settings.json,
|
||||
连接信息(base_url + api_key)从 Provider 管理读,
|
||||
模型名从用户提交时选的 model_id 取。
|
||||
【关键】目录名用 session_id 做持久化——续聊时复用同一目录,
|
||||
否则 --resume 找不到上一轮的会话!
|
||||
【调用时】通过 CLAUDE_CONFIG_DIR 环境变量让 claude CLI 用这份配置。
|
||||
"""
|
||||
import json as _json
|
||||
|
||||
# 用 session_id 做目录名,确保续聊时复用同一目录(会话文件在里面)
|
||||
dir_name = f"agent-{session_id[:12]}" if session_id else f"agent-{uuid.uuid4().hex[:12]}"
|
||||
cfg_dir = Path.home() / ".claude" / dir_name
|
||||
cfg_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# 1. 从模型配置找 provider_key → 从 Provider 管理拿 base_url + api_key
|
||||
# 注意:model_id 可能是注册表 key("provider_key/model_id"),需要提取真实 model_id
|
||||
real_model_id = _normalize_model_id(model_id)
|
||||
base_url, api_key = "", ""
|
||||
try:
|
||||
from app.store.model_config_store import get_model_config_store
|
||||
from app.store.provider_store import get_provider_store
|
||||
|
||||
# 按 model_id 找模型配置(取第一个匹配的)
|
||||
mc_store = get_model_config_store()
|
||||
all_models = mc_store.list_all()
|
||||
target_model = next((m for m in all_models if m.model_id == real_model_id), None)
|
||||
if target_model:
|
||||
provider_key = target_model.provider_key
|
||||
provider = get_provider_store().get_with_key(provider_key)
|
||||
if provider:
|
||||
base_url = provider.get("base_url", "")
|
||||
api_key = provider.get("api_key", "")
|
||||
except Exception: # noqa: BLE001 - 读不到就降级为空(走 CLI 默认)
|
||||
pass
|
||||
|
||||
# 2. 继承用户 settings.json 的非模型字段(如 AUTH_TOKEN),只替换核心的
|
||||
user_cfg_path = Path.home() / ".claude" / "settings.json"
|
||||
user_env: dict = {}
|
||||
if user_cfg_path.exists():
|
||||
try:
|
||||
user_cfg = _json.loads(user_cfg_path.read_text(encoding="utf-8"))
|
||||
user_env = dict(user_cfg.get("env", {}))
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
|
||||
# 3. 组装独立配置:连接信息覆盖为 Provider 管理的值,模型覆盖为用户选的
|
||||
env = {
|
||||
**user_env,
|
||||
"ANTHROPIC_MODEL": real_model_id,
|
||||
"CLAUDE_CODE_SUBAGENT_MODEL": real_model_id,
|
||||
}
|
||||
if base_url:
|
||||
env["ANTHROPIC_BASE_URL"] = base_url
|
||||
if api_key:
|
||||
env["ANTHROPIC_AUTH_TOKEN"] = api_key
|
||||
|
||||
clean_cfg = {"env": env, "model": real_model_id}
|
||||
settings_file = cfg_dir / "settings.json"
|
||||
settings_file.write_text(
|
||||
_json.dumps(clean_cfg, ensure_ascii=False, indent=2), encoding="utf-8"
|
||||
)
|
||||
logger.info(
|
||||
"已生成 Claude Code 独立配置:%s(模型=%s,provider_base_url=%s)",
|
||||
settings_file, real_model_id, base_url or "继承",
|
||||
)
|
||||
return cfg_dir
|
||||
|
||||
|
||||
def build_prompt(
|
||||
step_description: str,
|
||||
expected_output: str,
|
||||
target_files: list[str],
|
||||
prev_error: str = "",
|
||||
retry: int = 0,
|
||||
) -> str:
|
||||
"""
|
||||
构建 Claude Code 的改码 Prompt。
|
||||
|
||||
【要点】
|
||||
- 明确任务范围(只改指定文件);
|
||||
- 附带上次失败原因(修复循环);
|
||||
- 要求代码注释(符合项目规范)。
|
||||
"""
|
||||
files_desc = "\n".join(f" - {f}" for f in target_files[:5]) if target_files else " - 请自行定位相关文件"
|
||||
|
||||
retry_hint = f"\n【上次修改失败原因,请修正】{prev_error}" if prev_error else ""
|
||||
|
||||
return f"""你是一个 Java 项目代码修复工程师。请完成以下修改任务。
|
||||
|
||||
【修改任务】{step_description}
|
||||
【预期产出】{expected_output}
|
||||
【重试次数】{retry}{retry_hint}
|
||||
|
||||
【候选文件】
|
||||
{files_desc}
|
||||
|
||||
【硬性要求】
|
||||
1. 只修改与本任务直接相关的代码,禁止改动无关文件;
|
||||
2. 修改处必须加中文注释(说明功能、修改原因);
|
||||
3. 修改完成后自行检查代码语法正确性;
|
||||
4. 完成后在最后一行输出固定格式摘要:DONE: <一句话修改说明>。"""
|
||||
|
||||
|
||||
def execute(
|
||||
project_root: Path,
|
||||
prompt: str,
|
||||
task_id: str = "",
|
||||
timeout: int = 0,
|
||||
model: str = "",
|
||||
on_output=None,
|
||||
session_id: str = "",
|
||||
resume: bool = False,
|
||||
skip_snapshot: bool = False,
|
||||
on_session=None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
调用 Claude Code CLI 执行任务(零限制,流式输出,会话续聊)。
|
||||
|
||||
【参数】
|
||||
project_root:项目代码根目录
|
||||
prompt:用户原话,不做任何包装
|
||||
task_id:任务 ID(用于审计与快照)
|
||||
timeout:0=不超时,跑完为止
|
||||
model:模型名
|
||||
on_output:流式回调 fn(text),每提取到一段可展示文本调用一次
|
||||
session_id:Claude 会话 ID(首次传入 = 指定会话;resume 时 = 续接该会话)
|
||||
resume:True = 用 --resume 续接已有会话(Claude 自己管上下文)
|
||||
skip_snapshot:True = 跳过文件快照(对话续聊不需要快照代码)
|
||||
on_session:会话就绪回调 fn(session_id),CLI 一吐出 init 事件立刻触发
|
||||
—— 供调用方提前落库,避免执行完才补写时进程已死
|
||||
"""
|
||||
project_root = Path(project_root)
|
||||
if not project_root.exists():
|
||||
raise ClaudeCodeError(f"项目根目录不存在:{project_root}", error_type="PathNotFound")
|
||||
claude_path = get_claude_path() # 拿完整路径,绕过 Windows PATHEXT 问题
|
||||
|
||||
# 执行前对项目做快照(对话续聊跳过,代码改码才需要)
|
||||
if not skip_snapshot:
|
||||
try:
|
||||
snapshot_count = 0
|
||||
for java_file in project_root.rglob("*.java"):
|
||||
if _backup_file(java_file, task_id):
|
||||
snapshot_count += 1
|
||||
if snapshot_count >= 20:
|
||||
break
|
||||
logger.info("改码前快照完成:%d 个文件", snapshot_count)
|
||||
except Exception as exc: # noqa: BLE001
|
||||
logger.warning("改码前快照失败(继续执行):%s", exc)
|
||||
|
||||
import time
|
||||
|
||||
start = time.time()
|
||||
logger.info("调用 Claude Code 执行改码任务(cwd=%s)", project_root)
|
||||
|
||||
cfg_dir: Path | None = None # 临时配置目录,finally 中清理
|
||||
try:
|
||||
real_model = _normalize_model_id(model) if model else ""
|
||||
cmd = [
|
||||
claude_path,
|
||||
"-p", # --print 模式,prompt 从 STDIN 读取
|
||||
"--permission-mode", "acceptEdits",
|
||||
"--output-format", "stream-json",
|
||||
# 【13.7 修复】不加这个参数,stream-json 只吐成块消息,没有逐字增量,
|
||||
# 前端只能在 done 时一把出。加了才会输出 stream_event/content_block_delta。
|
||||
"--include-partial-messages",
|
||||
"--verbose",
|
||||
]
|
||||
# 会话机制(终端同款):续聊用 --resume,首轮/无 session_id 时必须用 --session-id
|
||||
# 【关键】session_id 为空也必须传 --session-id(随机 UUID),
|
||||
# 否则 Claude CLI 默认续接 cwd 下的上一个会话 → 串台!
|
||||
use_resume = bool(resume and session_id)
|
||||
if use_resume:
|
||||
cmd += ["--resume", session_id]
|
||||
else:
|
||||
if not session_id:
|
||||
session_id = str(uuid.uuid4())
|
||||
cmd += ["--session-id", session_id]
|
||||
if real_model and real_model != "auto" and real_model.startswith("claude-"):
|
||||
cmd += ["--model", real_model]
|
||||
|
||||
import os
|
||||
env = os.environ.copy()
|
||||
if real_model and real_model != "auto":
|
||||
env["ANTHROPIC_MODEL"] = real_model
|
||||
# 【关键】用 session_id 做目录名持久化,续聊时复用同一目录
|
||||
cfg_dir = prepare_claude_config(real_model, session_id)
|
||||
env["CLAUDE_CONFIG_DIR"] = str(cfg_dir)
|
||||
else:
|
||||
env.pop("ANTHROPIC_MODEL", None)
|
||||
|
||||
# 流式执行:prompt 从 STDIN 传入(避免命令行截断/乱码)
|
||||
import subprocess as sp
|
||||
|
||||
from app.tools.proc_flags import hidden_popen_kwargs
|
||||
|
||||
process = sp.Popen(
|
||||
cmd,
|
||||
cwd=str(project_root),
|
||||
stdin=sp.PIPE,
|
||||
stdout=sp.PIPE,
|
||||
stderr=sp.STDOUT,
|
||||
text=True,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
env=env,
|
||||
shell=False,
|
||||
bufsize=1, # 行缓冲,逐行输出
|
||||
# 【弹窗修复】claude 的入口是 claude.CMD(控制台程序),
|
||||
# 直接拉起会分配可见控制台窗口。CREATE_NO_WINDOW 让它照常跑但不弹窗。
|
||||
# 注意:不要用 DETACHED_PROCESS,它才是弹窗元凶(见 proc_flags 实测表)。
|
||||
**hidden_popen_kwargs(),
|
||||
)
|
||||
# 写入 prompt 到 STDIN 并关闭
|
||||
process.stdin.write(prompt)
|
||||
process.stdin.close()
|
||||
# 注册进程,供外部「停止」按钮 kill
|
||||
if task_id:
|
||||
_running_processes[task_id] = process
|
||||
try:
|
||||
output_lines: list[str] = []
|
||||
extractor = _StreamTextExtractor()
|
||||
session_reported = False
|
||||
# 逐行读取 stream-json,提取文本内容后回调
|
||||
while True:
|
||||
line = process.stdout.readline()
|
||||
if not line and process.poll() is not None:
|
||||
break
|
||||
if line:
|
||||
output_lines.append(line)
|
||||
# 【13.8 修复】会话 ID 一拿到就立刻回调落库,
|
||||
# 不等 execute() 返回——进程随时可能被 reload 杀掉。
|
||||
if on_session and not session_reported:
|
||||
sid = _extract_session_id_from_line(line)
|
||||
if sid:
|
||||
session_reported = True
|
||||
try:
|
||||
on_session(sid)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
if on_output:
|
||||
try:
|
||||
text = extractor.feed(line)
|
||||
if text:
|
||||
on_output(text)
|
||||
except Exception: # noqa: BLE001
|
||||
pass
|
||||
process.wait(timeout=timeout if timeout and timeout > 0 else None)
|
||||
finally:
|
||||
# 【BUG-3 修复】异常/退出时确保子进程被清理,防止僵尸进程
|
||||
if process.poll() is None:
|
||||
process.kill()
|
||||
process.wait()
|
||||
|
||||
class _FakeCompleted:
|
||||
"""模拟 subprocess.run 返回结构,统一后续处理"""
|
||||
def __init__(self, rc: int) -> None:
|
||||
self.returncode = rc
|
||||
self.stdout = "".join(output_lines)
|
||||
self.stderr = ""
|
||||
|
||||
completed = _FakeCompleted(process.returncode)
|
||||
|
||||
duration = round(time.time() - start, 1)
|
||||
stdout = completed.stdout or ""
|
||||
|
||||
# 从 stream-json 提取完整文本输出(result 字段)
|
||||
output = _extract_final_text(stdout)
|
||||
if not output:
|
||||
# 【BUG-3 修复】降级兜底时过滤 JSON 行,只保留纯文本
|
||||
text_lines = []
|
||||
for line in stdout.splitlines():
|
||||
stripped = line.strip()
|
||||
if stripped.startswith("{") and stripped.endswith("}"):
|
||||
continue # 跳过 stream-json 行
|
||||
if stripped:
|
||||
text_lines.append(stripped)
|
||||
output = "\n".join(text_lines) if text_lines else stdout
|
||||
|
||||
# 提取 Claude 会话 ID(供 --resume 续聊用)
|
||||
detected_session_id = _extract_session_id(stdout)
|
||||
|
||||
# 成功判定:returncode==0 即算成功
|
||||
success = completed.returncode == 0
|
||||
|
||||
# 【13.8 兜底】--resume 找不到会话(配置目录丢失 / 会话被清理)时,
|
||||
# 回退成 --session-id 重跑一次,避免整轮对话直接失败且上下文全丢。
|
||||
if use_resume and not success and "No conversation found" in stdout:
|
||||
logger.warning("会话 %s 已丢失,回退 --session-id 重跑一次", session_id)
|
||||
return execute(
|
||||
project_root=project_root,
|
||||
prompt=prompt,
|
||||
task_id=task_id,
|
||||
timeout=timeout,
|
||||
model=model,
|
||||
on_output=on_output,
|
||||
session_id=session_id,
|
||||
resume=False,
|
||||
skip_snapshot=True, # 首跑已快照过,重跑不再重复
|
||||
on_session=on_session,
|
||||
)
|
||||
|
||||
result = {
|
||||
"success": success,
|
||||
"output": output,
|
||||
"summary": output.strip().splitlines()[-1][:200] if output.strip() else "(无输出)",
|
||||
"duration": duration,
|
||||
"returncode": completed.returncode,
|
||||
"session_id": detected_session_id,
|
||||
}
|
||||
|
||||
log_action(
|
||||
action="claude_code_execute",
|
||||
target=str(project_root),
|
||||
result="success" if success else "failure",
|
||||
details={
|
||||
"summary": result["summary"][:200],
|
||||
"duration": duration,
|
||||
"returncode": completed.returncode,
|
||||
"task_id": task_id,
|
||||
},
|
||||
)
|
||||
logger.info("Claude Code 执行完成:success=%s, duration=%ss", success, duration)
|
||||
return result
|
||||
|
||||
except FileNotFoundError as exc:
|
||||
raise ClaudeCodeError(
|
||||
f"claude CLI 未找到(路径:{claude_path}),请确认已安装 Claude Code",
|
||||
error_type="ClaudeNotFound",
|
||||
) from exc
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
log_action(
|
||||
action="claude_code_execute",
|
||||
target=str(project_root),
|
||||
result="failure",
|
||||
details={"error": "timeout", "timeout": timeout, "task_id": task_id},
|
||||
)
|
||||
raise ClaudeCodeError(
|
||||
f"Claude Code 执行超时(>{timeout}秒)", error_type="Timeout"
|
||||
) from exc
|
||||
finally:
|
||||
# 注销进程
|
||||
if task_id:
|
||||
_running_processes.pop(task_id, None)
|
||||
# 【注意】配置目录不能删!Claude 会话文件在里面,删了 --resume 就找不到了。
|
||||
# 目录在任务删除时由 delete_task 统一清理。
|
||||
@@ -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"],
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
"""
|
||||
文件工具(读 / 写 / 编辑)
|
||||
=========================
|
||||
|
||||
【功能说明】
|
||||
自研工具链的文件操作能力:读取、写入、精确编辑(字符串替换)。
|
||||
每次写盘前自动快照备份,支持一键还原(决策点 12「Git + 快照」双安全网)。
|
||||
|
||||
【技术选型理由】
|
||||
1. 决策点 2 选「纯自研工具链」:不引入 Aider 等外部编码引擎,
|
||||
文件读写编辑自己实现,彻底掌握编码 Agent 的底层机制(教学价值)。
|
||||
2. 编辑用「精确字符串替换」而非整文件覆盖:
|
||||
最小化改动面、可预测、diff 可读,符合你 CLAUDE.md「最小必要改动」。
|
||||
3. 写盘前快照到 D:\\Agent\\agent\\data\\backups:
|
||||
即使没有 Git,也能还原到修改前(硬约束 5 兜底)。
|
||||
|
||||
【实现思路】
|
||||
- read_file:支持按行号范围读取(大文件只读所需片段,省 token);
|
||||
- write_file:写盘前备份原文件,新文件无需备份;
|
||||
- edit_file:精确匹配 old_str → new_str,要求唯一匹配,避免误替换;
|
||||
- 所有路径经 PathGuard 校验,越权直接拒绝。
|
||||
|
||||
【潜在风险与应对】
|
||||
风险1:edit_file 的 old_str 在文件中多次出现 → 误替换。
|
||||
应对:强制唯一匹配,多次出现时报错并提示用户给更多上下文。
|
||||
风险2:写入半途断电/异常 → 文件损坏。
|
||||
应对:先写临时文件再原子替换(Windows 下 os.replace)。
|
||||
风险3:编码不一致(GBK/UTF-8)导致写坏文件。
|
||||
应对:读取时探测编码,写入统一 UTF-8;无法确定时拒写并报错。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import shutil
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from app.tools.audit import log_action
|
||||
from app.tools.path_guard import ensure_under_root
|
||||
|
||||
logger = logging.getLogger("agent.tools.file")
|
||||
|
||||
# 快照备份目录(决策点 12:Git 之外的二道保险)
|
||||
BACKUP_DIR = Path(r"D:\Agent\agent\data\backups")
|
||||
|
||||
|
||||
class FileToolError(RuntimeError):
|
||||
"""文件工具异常(中文可读)"""
|
||||
|
||||
def __init__(self, message: str, *, error_type: str = "FileToolError") -> None:
|
||||
super().__init__(message)
|
||||
self.error_type = error_type
|
||||
|
||||
|
||||
def _detect_encoding(path: Path) -> str:
|
||||
"""探测文件编码:UTF-8 优先,回退 GBK。"""
|
||||
raw = path.read_bytes()
|
||||
for enc in ("utf-8", "gbk"):
|
||||
try:
|
||||
raw.decode(enc)
|
||||
return enc
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
return "utf-8" # 兜底(读取时 errors=replace)
|
||||
|
||||
|
||||
def _backup_file(path: Path, task_id: str = "") -> Path | None:
|
||||
"""
|
||||
写盘前快照备份原文件。
|
||||
|
||||
【返回】备份文件路径;原文件不存在返回 None。
|
||||
【联动】同时写入回滚索引,供 RollbackService 按任务还原。
|
||||
"""
|
||||
if not path.exists():
|
||||
return None
|
||||
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
rel_name = str(path).replace("\\", "_").replace(":", "").replace("/", "_")
|
||||
backup_name = f"{timestamp}_{task_id}_{rel_name}" if task_id else f"{timestamp}_{rel_name}"
|
||||
backup_path = BACKUP_DIR / backup_name
|
||||
backup_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
shutil.copy2(path, backup_path)
|
||||
|
||||
# 写入回滚索引(M5:一键回滚依赖此映射)
|
||||
try:
|
||||
from app.tasks.rollback_service import record_backup
|
||||
|
||||
record_backup(str(backup_path), str(path), task_id)
|
||||
except Exception as exc: # noqa: BLE001 - 索引失败不影响备份本身
|
||||
logger.warning("写入回滚索引失败:%s", exc)
|
||||
|
||||
logger.info("已快照备份:%s → %s", path, backup_path)
|
||||
return backup_path
|
||||
|
||||
|
||||
# ---------- 读取 ----------
|
||||
|
||||
|
||||
def read_file(
|
||||
path: str | Path,
|
||||
start_line: int = 0,
|
||||
end_line: int | None = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
读取文件内容(支持按行号范围)。
|
||||
|
||||
【返回】{path, content, total_lines, start_line, end_line}
|
||||
【用途】Agent 读取源码以理解上下文(决策点 2 自研工具链)。
|
||||
"""
|
||||
file_path = ensure_under_root(Path(path), action="读取", readonly=True)
|
||||
if not file_path.exists():
|
||||
raise FileToolError(f"文件不存在:{file_path}", error_type="FileNotFound")
|
||||
if not file_path.is_file():
|
||||
raise FileToolError(f"路径不是文件:{file_path}", error_type="NotAFile")
|
||||
|
||||
encoding = _detect_encoding(file_path)
|
||||
try:
|
||||
text = file_path.read_text(encoding=encoding, errors="replace")
|
||||
except Exception as exc:
|
||||
raise FileToolError(f"读取失败:{file_path},原因:{exc}", error_type="ReadFailed")
|
||||
|
||||
lines = text.splitlines(keepends=True)
|
||||
total = len(lines)
|
||||
start = max(0, start_line)
|
||||
end = total if end_line is None else min(end_line, total)
|
||||
selected = "".join(lines[start:end])
|
||||
|
||||
log_action(
|
||||
action="file_read",
|
||||
target=str(file_path),
|
||||
result="success",
|
||||
details={"start_line": start, "end_line": end, "total_lines": total},
|
||||
)
|
||||
return {
|
||||
"path": str(file_path),
|
||||
"content": selected,
|
||||
"total_lines": total,
|
||||
"start_line": start,
|
||||
"end_line": end,
|
||||
"encoding": encoding,
|
||||
}
|
||||
|
||||
|
||||
# ---------- 写入 ----------
|
||||
|
||||
|
||||
def write_file(
|
||||
path: str | Path,
|
||||
content: str,
|
||||
task_id: str = "",
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
写入文件(写盘前自动快照备份)。
|
||||
|
||||
【返回】{path, backup_path, bytes_written}
|
||||
【安全】路径经守卫校验;原文件先备份;原子替换防写坏。
|
||||
"""
|
||||
file_path = ensure_under_root(Path(path), action="写入")
|
||||
file_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
backup_path = _backup_file(file_path, task_id)
|
||||
|
||||
try:
|
||||
# 先写临时文件再原子替换,防止半途失败写坏原文件
|
||||
tmp_path = file_path.with_suffix(file_path.suffix + ".tmp_write")
|
||||
tmp_path.write_text(content, encoding="utf-8")
|
||||
os.replace(tmp_path, file_path)
|
||||
except Exception as exc:
|
||||
raise FileToolError(
|
||||
f"写入失败:{file_path},原因:{exc}", error_type="WriteFailed"
|
||||
)
|
||||
|
||||
log_action(
|
||||
action="file_write",
|
||||
target=str(file_path),
|
||||
result="success",
|
||||
details={
|
||||
"backup_path": str(backup_path) if backup_path else "新文件无备份",
|
||||
"bytes": len(content.encode("utf-8")),
|
||||
"task_id": task_id,
|
||||
},
|
||||
)
|
||||
return {
|
||||
"path": str(file_path),
|
||||
"backup_path": str(backup_path) if backup_path else None,
|
||||
"bytes_written": len(content.encode("utf-8")),
|
||||
}
|
||||
|
||||
|
||||
# ---------- 精确编辑 ----------
|
||||
|
||||
|
||||
def edit_file(
|
||||
path: str | Path,
|
||||
old_str: str,
|
||||
new_str: str,
|
||||
task_id: str = "",
|
||||
replace_all: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
精确编辑:把 old_str 替换为 new_str(最小改动面)。
|
||||
|
||||
【约束】
|
||||
- old_str 必须在文件中唯一出现(除非 replace_all=True);
|
||||
- 匹配失败或多次匹配时抛错,不猜测、不误替换。
|
||||
【返回】{path, replacements, backup_path}
|
||||
"""
|
||||
file_path = ensure_under_root(Path(path), action="编辑")
|
||||
if not file_path.exists():
|
||||
raise FileToolError(f"文件不存在:{file_path}", error_type="FileNotFound")
|
||||
|
||||
encoding = _detect_encoding(file_path)
|
||||
text = file_path.read_text(encoding=encoding, errors="replace")
|
||||
|
||||
occurrences = text.count(old_str)
|
||||
if occurrences == 0:
|
||||
raise FileToolError(
|
||||
f"编辑失败:在 {file_path} 中未找到匹配文本。"
|
||||
f"请确认 old_str 与文件内容完全一致(含缩进与换行)",
|
||||
error_type="StringNotFound",
|
||||
)
|
||||
if occurrences > 1 and not replace_all:
|
||||
raise FileToolError(
|
||||
f"编辑失败:匹配文本在文件中出现 {occurrences} 次,无法确定替换位置。"
|
||||
f"请提供更多上下文使匹配唯一,或设置 replace_all=True",
|
||||
error_type="AmbiguousMatch",
|
||||
)
|
||||
|
||||
backup_path = _backup_file(file_path, task_id)
|
||||
new_text = text.replace(old_str, new_str) if replace_all else text.replace(old_str, new_str, 1)
|
||||
|
||||
try:
|
||||
tmp_path = file_path.with_suffix(file_path.suffix + ".tmp_edit")
|
||||
tmp_path.write_text(new_text, encoding="utf-8")
|
||||
os.replace(tmp_path, file_path)
|
||||
except Exception as exc:
|
||||
raise FileToolError(f"编辑写入失败:{exc}", error_type="WriteFailed")
|
||||
|
||||
replacements = occurrences if replace_all else 1
|
||||
log_action(
|
||||
action="file_edit",
|
||||
target=str(file_path),
|
||||
result="success",
|
||||
details={
|
||||
"old_str_preview": old_str[:100],
|
||||
"new_str_preview": new_str[:100],
|
||||
"replacements": replacements,
|
||||
"backup_path": str(backup_path) if backup_path else None,
|
||||
"task_id": task_id,
|
||||
},
|
||||
)
|
||||
return {
|
||||
"path": str(file_path),
|
||||
"replacements": replacements,
|
||||
"backup_path": str(backup_path) if backup_path else None,
|
||||
}
|
||||
|
||||
|
||||
def restore_backup(backup_path: str | Path, target_path: str | Path) -> dict[str, Any]:
|
||||
"""
|
||||
从快照还原文件(回滚能力)。
|
||||
|
||||
【用途】改错时一键还原到修改前状态(硬约束 5 兜底)。
|
||||
"""
|
||||
backup = Path(backup_path)
|
||||
target = ensure_under_root(Path(target_path), action="还原")
|
||||
if not backup.exists():
|
||||
raise FileToolError(f"备份文件不存在:{backup}", error_type="BackupNotFound")
|
||||
shutil.copy2(backup, target)
|
||||
log_action(action="file_restore", target=str(target), result="success",
|
||||
details={"backup": str(backup)})
|
||||
return {"restored": str(target), "from_backup": str(backup)}
|
||||
@@ -0,0 +1,163 @@
|
||||
"""
|
||||
Git 操作工具
|
||||
============
|
||||
|
||||
【功能说明】
|
||||
封装本地 Git 的常用写操作:状态查看、diff、建任务分支、提交。
|
||||
对应决策点 12/13「本地 Git 管理 + 真实分支语义」。
|
||||
|
||||
【技术选型理由】
|
||||
1. 决策点 12 已锁定「本地 Git(无远程)」:改动可回滚、可审计、可并发隔离;
|
||||
2. 任务分支策略:每个任务自动建 `agent/task_<id>` 分支,
|
||||
改动隔离在任务分支上,master 不受污染(企业级标准做法);
|
||||
3. 仍走 subprocess list 传参,防注入(与 GitReadService 同款)。
|
||||
|
||||
【实现思路】
|
||||
- ensure_task_branch:存在则切、不存在则建并切;
|
||||
- commit_changes:add + commit(不 push,无远程);
|
||||
- get_diff:工作区相对 HEAD 的 diff,供 Agent/人查看改动。
|
||||
|
||||
【潜在风险与应对】
|
||||
风险1:工作区有未提交改动时切分支被拒。
|
||||
应对:先自动 stash 或 commit 当前改动(决策:选 commit 留痕)。
|
||||
风险2:git user.name/email 未配置导致 commit 失败。
|
||||
应对:首次提交前自动设置仓库级 user(agent-bot)。
|
||||
风险3:误提交大文件/敏感文件。
|
||||
应对:.gitignore 已排除 .env 等;审计日志记录每次 commit 内容摘要。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
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.git")
|
||||
|
||||
|
||||
class GitToolError(RuntimeError):
|
||||
"""Git 工具异常(中文可读)"""
|
||||
|
||||
def __init__(self, message: str, *, error_type: str = "GitToolError") -> None:
|
||||
super().__init__(message)
|
||||
self.error_type = error_type
|
||||
|
||||
|
||||
def _git(repo: Path, args: list[str], timeout: int = 30) -> str:
|
||||
"""在指定仓库执行 git 命令,返回 stdout。"""
|
||||
try:
|
||||
completed = subprocess.run(
|
||||
["git", *args],
|
||||
cwd=str(repo),
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=timeout,
|
||||
shell=False,
|
||||
encoding="utf-8",
|
||||
errors="replace",
|
||||
**hidden_popen_kwargs(),
|
||||
)
|
||||
except FileNotFoundError as exc:
|
||||
raise GitToolError("未检测到 git 命令", error_type="GitNotFound") from exc
|
||||
except subprocess.TimeoutExpired as exc:
|
||||
raise GitToolError(f"git 命令超时:git {' '.join(args)}", error_type="Timeout") from exc
|
||||
|
||||
if completed.returncode != 0:
|
||||
raise GitToolError(
|
||||
f"git {' '.join(args)} 失败(退出码 {completed.returncode}):{(completed.stderr or '')[:500]}",
|
||||
error_type="GitCommandFailed",
|
||||
)
|
||||
return completed.stdout or ""
|
||||
|
||||
|
||||
def ensure_task_branch(repo_path: str | Path, task_id: str) -> dict[str, Any]:
|
||||
"""
|
||||
确保当前仓库位于任务分支上(存在则切、不存在则建并切)。
|
||||
|
||||
【分支命名】agent/task_<task_id>,隔离任务改动。
|
||||
"""
|
||||
repo = ensure_under_root(Path(repo_path), action="Git 操作")
|
||||
branch = f"agent/task_{task_id}"
|
||||
|
||||
# 确保 user 配置存在(否则 commit 会失败)
|
||||
try:
|
||||
_git(repo, ["config", "user.email"], timeout=10)
|
||||
except GitToolError:
|
||||
_git(repo, ["config", "user.email", "agent-bot@local"], timeout=10)
|
||||
_git(repo, ["config", "user.name", "agent-bot"], timeout=10)
|
||||
|
||||
try:
|
||||
_git(repo, ["rev-parse", "--verify", "--quiet", f"refs/heads/{branch}"], timeout=10)
|
||||
# 分支已存在 → 切换
|
||||
_git(repo, ["checkout", branch], timeout=15)
|
||||
action = "switched"
|
||||
except GitToolError:
|
||||
# 分支不存在 → 创建并切换(若工作区脏,先建分支自带改动)
|
||||
try:
|
||||
_git(repo, ["checkout", "-b", branch], timeout=15)
|
||||
action = "created"
|
||||
except GitToolError as exc:
|
||||
raise GitToolError(
|
||||
f"创建任务分支失败:{exc}", error_type="BranchCreateFailed"
|
||||
) from exc
|
||||
|
||||
log_action(
|
||||
action="git_branch",
|
||||
target=str(repo),
|
||||
result="success",
|
||||
details={"branch": branch, "action": action, "task_id": task_id},
|
||||
)
|
||||
return {"repo": str(repo), "branch": branch, "action": action}
|
||||
|
||||
|
||||
def commit_changes(repo_path: str | Path, message: str, task_id: str = "") -> dict[str, Any]:
|
||||
"""
|
||||
提交当前工作区改动(add + commit,不 push——决策点 12 无远程)。
|
||||
|
||||
【返回】{commit_hash, branch, files_changed}
|
||||
"""
|
||||
repo = ensure_under_root(Path(repo_path), action="Git 提交")
|
||||
|
||||
# add 全部改动(.gitignore 自动排除敏感文件)
|
||||
_git(repo, ["add", "-A"], timeout=30)
|
||||
|
||||
# 若无可提交内容,返回空
|
||||
status = _git(repo, ["status", "--porcelain"], timeout=15)
|
||||
if not status.strip():
|
||||
logger.info("无可提交内容:%s", repo)
|
||||
return {"commit_hash": None, "branch": "", "files_changed": 0}
|
||||
|
||||
_git(repo, ["commit", "-m", message], timeout=30)
|
||||
commit_hash = _git(repo, ["rev-parse", "--short", "HEAD"], timeout=10).strip()
|
||||
branch = _git(repo, ["rev-parse", "--abbrev-ref", "HEAD"], timeout=10).strip()
|
||||
files_changed = len([l for l in status.splitlines() if l.strip()])
|
||||
|
||||
log_action(
|
||||
action="git_commit",
|
||||
target=str(repo),
|
||||
result="success",
|
||||
details={
|
||||
"commit": commit_hash,
|
||||
"branch": branch,
|
||||
"files_changed": files_changed,
|
||||
"message": message[:200],
|
||||
"task_id": task_id,
|
||||
},
|
||||
)
|
||||
return {
|
||||
"commit_hash": commit_hash,
|
||||
"branch": branch,
|
||||
"files_changed": files_changed,
|
||||
}
|
||||
|
||||
|
||||
def get_diff(repo_path: str | Path) -> dict[str, Any]:
|
||||
"""获取工作区相对 HEAD 的 diff(供 Agent/人查看改动)。"""
|
||||
repo = ensure_under_root(Path(repo_path), action="Git diff")
|
||||
diff = _git(repo, ["diff", "HEAD"], timeout=20)
|
||||
return {"repo": str(repo), "diff": diff[:5000], "truncated": len(diff) > 5000}
|
||||
@@ -0,0 +1,127 @@
|
||||
"""
|
||||
路径安全守卫
|
||||
============
|
||||
|
||||
【功能说明】
|
||||
统一校验文件路径是否在允许的操作范围内,杜绝 Agent 越权读写系统文件。
|
||||
是整个工具层的「安全第一道闸门」。
|
||||
|
||||
【技术选型理由】
|
||||
1. 白名单根目录(默认 D:\\Agent\\code):决策点 3 已定代码集中在该目录,
|
||||
工具只允许在此范围内操作,硬约束 6「全落 D 盘」在路径层强制。
|
||||
2. resolve() 后再比对:防 `..\\..\\Windows` 路径穿越攻击,
|
||||
以及符号链接逃逸(Windows 下 junction/symlink 同理)。
|
||||
3. 校验函数独立成模块:所有工具(file/executor/git)共用同一套规则,
|
||||
避免各写一套校验导致漏网之鱼。
|
||||
|
||||
【实现思路】
|
||||
- PathGuard 持有 allowed_roots 列表;
|
||||
- 校验时先 resolve() 为绝对路径,再判断是否位于任一根目录之下;
|
||||
- 提供 ensure_under_root() 便捷函数,工具层一行调用。
|
||||
|
||||
【潜在风险与应对】
|
||||
风险1:allowed_roots 配置过宽(如允许整个 D 盘)。
|
||||
应对:默认只允许 D:\\Agent\\code 与 D:\\Agent\\agent\\data,
|
||||
其他路径需在配置里显式追加。
|
||||
风险2:符号链接指向根目录之外。
|
||||
应对:resolve() 会解析符号链接到真实路径,再做前缀比对。
|
||||
风险3:大小写差异导致比对失败(Windows 不区分大小写)。
|
||||
应对:统一转小写后再比对。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger("agent.tools.path_guard")
|
||||
|
||||
|
||||
class PathSecurityError(PermissionError):
|
||||
"""路径越权访问异常(中文可读)"""
|
||||
|
||||
def __init__(self, message: str) -> None:
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class PathGuard:
|
||||
"""路径安全守卫:限定工具可操作的根目录范围"""
|
||||
|
||||
def __init__(self, allowed_roots: list[Path]) -> None:
|
||||
# 统一 resolve 为真实绝对路径,比对时用小写规避大小写差异
|
||||
self._roots = [Path(r).expanduser().resolve() for r in allowed_roots]
|
||||
logger.info("路径守卫初始化,允许根目录:%s", self._roots)
|
||||
|
||||
def is_allowed(self, path: Path, *, readonly: bool = False) -> bool:
|
||||
"""
|
||||
判断路径是否在允许范围内。
|
||||
|
||||
【策略】
|
||||
- readonly=True(读取/搜索):允许任意本地目录(用户要求);
|
||||
- readonly=False(写入/删除/执行):仍限定白名单根目录。
|
||||
"""
|
||||
try:
|
||||
resolved = Path(path).expanduser().resolve()
|
||||
except OSError:
|
||||
return False
|
||||
# 拒绝 UNC 网络路径(防止误操作远程共享)
|
||||
if str(resolved).startswith("\\\\"):
|
||||
return False
|
||||
if readonly:
|
||||
return True
|
||||
# 写入/删除:仍走白名单
|
||||
resolved_lower = str(resolved).lower()
|
||||
return any(
|
||||
resolved_lower == str(root).lower()
|
||||
or resolved_lower.startswith(str(root).lower() + "\\")
|
||||
or resolved_lower.startswith(str(root).lower() + "/")
|
||||
for root in self._roots
|
||||
)
|
||||
|
||||
def ensure_allowed(self, path: Path, action: str = "访问", *, readonly: bool = False) -> Path:
|
||||
"""
|
||||
校验路径合法性,不合法抛 PathSecurityError。
|
||||
|
||||
【返回】解析后的绝对路径(后续工具可直接使用)。
|
||||
"""
|
||||
resolved = Path(path).expanduser().resolve()
|
||||
if not self.is_allowed(resolved, readonly=readonly):
|
||||
raise PathSecurityError(
|
||||
f"拒绝{action}:路径 {resolved} 不在允许的操作范围内 "
|
||||
f"(允许根目录:{[str(r) for r in self._roots]})"
|
||||
)
|
||||
return resolved
|
||||
|
||||
|
||||
# ---------- 默认守卫(工具层统一使用)----------
|
||||
|
||||
_default_guard: PathGuard | None = None
|
||||
|
||||
|
||||
def get_default_guard() -> PathGuard:
|
||||
"""
|
||||
获取默认路径守卫。
|
||||
|
||||
【允许范围】全部 D 盘 + 常见项目目录(用户要求 Agent 可读取任意目录)。
|
||||
"""
|
||||
global _default_guard
|
||||
if _default_guard is None:
|
||||
_default_guard = PathGuard(
|
||||
allowed_roots=[
|
||||
Path(r"D:\Agent\code"),
|
||||
Path(r"D:\Agent\agent\data"),
|
||||
Path(r"D:\Agent\pytest_tmp"),
|
||||
Path(r"D:\Project"),
|
||||
Path(r"D:\Code"),
|
||||
Path(r"D:\Workspace"),
|
||||
Path(r"D:\Work"),
|
||||
Path(r"D:\Git"),
|
||||
Path("D:\\"),
|
||||
]
|
||||
)
|
||||
return _default_guard
|
||||
|
||||
|
||||
def ensure_under_root(path: Path, action: str = "访问", *, readonly: bool = False) -> Path:
|
||||
"""便捷函数:校验路径并返回解析后的绝对路径。"""
|
||||
return get_default_guard().ensure_allowed(path, action, readonly=readonly)
|
||||
@@ -0,0 +1,63 @@
|
||||
"""
|
||||
Windows 子进程窗口抑制
|
||||
====================
|
||||
|
||||
【功能说明】
|
||||
统一提供「子进程不弹出控制台窗口」的 Popen/run 参数。
|
||||
|
||||
【为什么需要】
|
||||
claude CLI 的入口是 **claude.CMD 批处理脚本**(控制台程序),
|
||||
直接拉起会分配一个可见控制台窗口 → 用户每次提问都弹出命令行。
|
||||
|
||||
【关键实测结论】(2026-10-23 探针验证,勿再改错)
|
||||
|
||||
标志组合 控制台窗口 父进程退出后存活
|
||||
───────────────────────────────────────────── ───────── ────────────────
|
||||
无标志 无 ?
|
||||
CREATE_NO_WINDOW **无** **存活**
|
||||
CREATE_NO_WINDOW | CREATE_NEW_PROCESS_GROUP **无** **存活**
|
||||
DETACHED_PROCESS | CREATE_NO_WINDOW | GROUP **有!** 存活
|
||||
|
||||
→ **DETACHED_PROCESS 才是弹窗元凶**:它让控制台程序「无台可继承」时
|
||||
**自己 AllocConsole 一个可见控制台**,并压过 CREATE_NO_WINDOW。
|
||||
→ 只用 CREATE_NO_WINDOW 就同时拿到「不弹窗」和「独立存活」,
|
||||
不要再加 DETACHED_PROCESS。
|
||||
|
||||
【教训】第一次修复往 DETACHED_PROCESS 上叠 CREATE_NO_WINDOW,等于没治病根。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
|
||||
def hidden_popen_kwargs() -> dict:
|
||||
"""
|
||||
返回隐藏窗口所需的额外 Popen/run 参数。
|
||||
|
||||
【用法】
|
||||
subprocess.Popen(cmd, **hidden_popen_kwargs())
|
||||
subprocess.run(cmd, capture_output=True, **hidden_popen_kwargs())
|
||||
|
||||
【返回】Windows 下为 {"creationflags": CREATE_NO_WINDOW},其它平台为空 dict。
|
||||
"""
|
||||
if os.name != "nt":
|
||||
return {}
|
||||
return {"creationflags": subprocess.CREATE_NO_WINDOW}
|
||||
|
||||
|
||||
def worker_creation_flags() -> int:
|
||||
"""
|
||||
独立 worker 进程的创建标志。
|
||||
|
||||
【Windows】CREATE_NO_WINDOW 不弹出控制台窗口
|
||||
CREATE_NEW_PROCESS_GROUP 不接收父进程 Ctrl+C
|
||||
【绝不使用】DETACHED_PROCESS —— 会让控制台程序自建**可见**控制台,是弹窗元凶。
|
||||
【独立性】Windows 上父进程退出不会连带杀死子进程(无 Job Object 时),
|
||||
实测 CREATE_NO_WINDOW 下父退子活,足够支撑「API 重启不杀任务」。
|
||||
【其它平台】返回 0(由调用方改用 start_new_session)
|
||||
"""
|
||||
if os.name != "nt":
|
||||
return 0
|
||||
return subprocess.CREATE_NO_WINDOW | subprocess.CREATE_NEW_PROCESS_GROUP
|
||||
@@ -0,0 +1,182 @@
|
||||
"""
|
||||
搜索定位工具(grep / 文件查找)
|
||||
=============================
|
||||
|
||||
【功能说明】
|
||||
自研工具链的代码定位能力:正则内容搜索(grep)与文件名模糊查找。
|
||||
对应《核心诉求》「代码定位」环节,决策点 6 定为「代码走符号检索不进向量库」。
|
||||
|
||||
【技术选型理由】
|
||||
1. 选 ripgrep 风格的纯 Python 实现(re + pathlib):
|
||||
不依赖外部 rg 二进制,跨平台一致、可单测、可控。
|
||||
2. grep 而非向量检索:代码定位要的是**精确符号匹配**,
|
||||
向量检索在代码上召回不准(决策点 6 已论证)。
|
||||
3. 输出结构化(文件+行号+内容片段):Agent 能直接定位到行级修改点。
|
||||
|
||||
【实现思路】
|
||||
- grep_files:按正则搜索,支持 glob 过滤、大小写开关、结果上限;
|
||||
- find_files:按文件名模式查找(支持 * 通配);
|
||||
- 两者都经路径守卫校验,结果上限防止刷爆上下文。
|
||||
|
||||
【潜在风险与应对】
|
||||
风险1:正则写错导致全库扫描耗时。
|
||||
应对:结果上限 100 条 + 扫描文件数上限 5000,超时保护。
|
||||
风险2:搜索到二进制文件产生乱码。
|
||||
应对:跳过常见二进制扩展名(.png/.zip/.class/.jar 等)。
|
||||
风险3:结果过多撑爆 Agent 上下文。
|
||||
应对:每条结果截断到 200 字符,总数硬上限。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
from app.tools.audit import log_action
|
||||
from app.tools.path_guard import ensure_under_root
|
||||
|
||||
logger = logging.getLogger("agent.tools.search")
|
||||
|
||||
# 结果上限(防止刷爆 Agent 上下文)
|
||||
MAX_RESULTS = 100
|
||||
MAX_SCAN_FILES = 5000
|
||||
MAX_LINE_LENGTH = 200
|
||||
|
||||
# 跳过的二进制/无意义扩展名
|
||||
SKIP_EXTENSIONS = {
|
||||
".png", ".jpg", ".jpeg", ".gif", ".bmp", ".ico",
|
||||
".zip", ".jar", ".war", ".class", ".pyc", ".pyd",
|
||||
".pdf", ".docx", ".xlsx", ".pptx",
|
||||
".exe", ".dll", ".so", ".dylib",
|
||||
".db", ".sqlite", ".sqlite3",
|
||||
}
|
||||
|
||||
|
||||
class SearchToolError(RuntimeError):
|
||||
"""搜索工具异常(中文可读)"""
|
||||
|
||||
def __init__(self, message: str, *, error_type: str = "SearchToolError") -> None:
|
||||
super().__init__(message)
|
||||
self.error_type = error_type
|
||||
|
||||
|
||||
def grep_files(
|
||||
pattern: str,
|
||||
search_path: str | Path,
|
||||
glob_filter: str = "*",
|
||||
case_sensitive: bool = False,
|
||||
max_results: int = MAX_RESULTS,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
正则内容搜索(grep)。
|
||||
|
||||
【参数】
|
||||
pattern:正则表达式
|
||||
search_path:搜索根目录
|
||||
glob_filter:文件名过滤(如 *.java)
|
||||
case_sensitive:是否区分大小写
|
||||
max_results:结果上限
|
||||
【返回】{pattern, total_matches, results: [{file, line_no, line}]}
|
||||
"""
|
||||
root = ensure_under_root(Path(search_path), action="搜索", readonly=True)
|
||||
if not root.exists():
|
||||
raise SearchToolError(f"搜索路径不存在:{root}", error_type="PathNotFound")
|
||||
|
||||
try:
|
||||
regex = re.compile(pattern, 0 if case_sensitive else re.IGNORECASE)
|
||||
except re.error as exc:
|
||||
raise SearchToolError(f"正则表达式无效:{pattern},原因:{exc}", error_type="InvalidRegex")
|
||||
|
||||
results: list[dict[str, Any]] = []
|
||||
scanned = 0
|
||||
|
||||
for file_path in root.rglob(glob_filter):
|
||||
if scanned >= MAX_SCAN_FILES:
|
||||
logger.warning("扫描文件数超限 %d,提前终止", MAX_SCAN_FILES)
|
||||
break
|
||||
if not file_path.is_file():
|
||||
continue
|
||||
if file_path.suffix.lower() in SKIP_EXTENSIONS:
|
||||
continue
|
||||
scanned += 1
|
||||
|
||||
try:
|
||||
text = file_path.read_text(encoding="utf-8", errors="replace")
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
for line_no, line in enumerate(text.splitlines(), start=1):
|
||||
if regex.search(line):
|
||||
results.append(
|
||||
{
|
||||
"file": str(file_path),
|
||||
"line_no": line_no,
|
||||
"line": line[:MAX_LINE_LENGTH],
|
||||
}
|
||||
)
|
||||
if len(results) >= max_results:
|
||||
break
|
||||
if len(results) >= max_results:
|
||||
break
|
||||
|
||||
log_action(
|
||||
action="grep_files",
|
||||
target=str(root),
|
||||
result="success",
|
||||
details={"pattern": pattern, "matches": len(results), "scanned": scanned},
|
||||
)
|
||||
return {
|
||||
"pattern": pattern,
|
||||
"search_path": str(root),
|
||||
"total_matches": len(results),
|
||||
"scanned_files": scanned,
|
||||
"results": results,
|
||||
}
|
||||
|
||||
|
||||
def find_files(
|
||||
name_pattern: str,
|
||||
search_path: str | Path,
|
||||
max_results: int = MAX_RESULTS,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
按文件名模式查找文件。
|
||||
|
||||
【参数】name_pattern:支持 * 通配(如 *Controller.java)或纯名片段
|
||||
【返回】{pattern, total, files: [...]}
|
||||
"""
|
||||
root = ensure_under_root(Path(search_path), action="查找", readonly=True)
|
||||
if not root.exists():
|
||||
raise SearchToolError(f"查找路径不存在:{root}", error_type="PathNotFound")
|
||||
|
||||
# 纯名片段转通配模式
|
||||
pattern = name_pattern if "*" in name_pattern else f"*{name_pattern}*"
|
||||
|
||||
files: list[str] = []
|
||||
scanned = 0
|
||||
for file_path in root.rglob(pattern):
|
||||
if scanned >= MAX_SCAN_FILES:
|
||||
break
|
||||
if not file_path.is_file():
|
||||
continue
|
||||
if file_path.suffix.lower() in SKIP_EXTENSIONS:
|
||||
continue
|
||||
scanned += 1
|
||||
files.append(str(file_path))
|
||||
if len(files) >= max_results:
|
||||
break
|
||||
|
||||
log_action(
|
||||
action="find_files",
|
||||
target=str(root),
|
||||
result="success",
|
||||
details={"pattern": pattern, "found": len(files)},
|
||||
)
|
||||
return {
|
||||
"pattern": pattern,
|
||||
"search_path": str(root),
|
||||
"total": len(files),
|
||||
"files": files,
|
||||
}
|
||||
Reference in New Issue
Block a user