Files
AgentScript/agent/backend/app/tools/file_tools.py
T

275 lines
9.6 KiB
Python
Raw Normal View History

"""
文件工具(读 / 写 / 编辑)
=========================
【功能说明】
自研工具链的文件操作能力:读取、写入、精确编辑(字符串替换)。
每次写盘前自动快照备份,支持一键还原(决策点 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)}