467 lines
18 KiB
Python
467 lines
18 KiB
Python
"""Workspace filesystem and shell tools for workers, plus read-only tools for the lead."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import asyncio
|
||
import fnmatch
|
||
import os
|
||
import re
|
||
import shutil
|
||
import signal
|
||
import time
|
||
from pathlib import Path
|
||
from typing import Any
|
||
|
||
from .config import LimitsConfig
|
||
from .utils import truncate
|
||
|
||
IGNORED_DIRS = {
|
||
".git",
|
||
".hg",
|
||
".svn",
|
||
".airouter",
|
||
".venv",
|
||
"venv",
|
||
"node_modules",
|
||
"__pycache__",
|
||
".pytest_cache",
|
||
".mypy_cache",
|
||
".ruff_cache",
|
||
"dist",
|
||
"build",
|
||
".next",
|
||
"target",
|
||
}
|
||
|
||
|
||
class ToolError(RuntimeError):
|
||
pass
|
||
|
||
|
||
def _is_binary(data: bytes) -> bool:
|
||
return b"\x00" in data[:4096]
|
||
|
||
|
||
def _read_text(path: Path, limits: LimitsConfig) -> str:
|
||
try:
|
||
size = path.stat().st_size
|
||
except OSError as exc:
|
||
raise ToolError(f"Не удалось прочитать {path}: {exc}") from exc
|
||
if size > limits.max_file_bytes:
|
||
raise ToolError(
|
||
f"Файл слишком большой ({size} байт > {limits.max_file_bytes}). "
|
||
"Прочитайте фрагмент через bash, например `head -n 200 файл`."
|
||
)
|
||
data = path.read_bytes()
|
||
if _is_binary(data):
|
||
raise ToolError(f"{path} — бинарный файл, чтение текстом невозможно")
|
||
with open(path, "r", encoding="utf-8", errors="replace", newline="") as fh:
|
||
return fh.read()
|
||
|
||
|
||
def _numbered(text: str, offset: int, limit: int) -> tuple[str, int]:
|
||
lines = text.splitlines()
|
||
total = len(lines)
|
||
start = max(0, offset - 1)
|
||
end = min(total, start + limit)
|
||
numbered = "\n".join(f"{i + 1}: {line}" for i, line in enumerate(lines[start:end], start))
|
||
return numbered, total
|
||
|
||
|
||
def _format_bytes(size: int) -> str:
|
||
if size < 1024:
|
||
return f"{size} B"
|
||
if size < 1024 * 1024:
|
||
return f"{size / 1024:.1f} KB"
|
||
return f"{size / (1024 * 1024):.1f} MB"
|
||
|
||
|
||
class Workspace:
|
||
"""A worker workspace. File operations are confined to its root by default."""
|
||
|
||
def __init__(
|
||
self,
|
||
root: Path,
|
||
limits: LimitsConfig,
|
||
*,
|
||
read_only: bool = False,
|
||
allow_outside: bool = False,
|
||
) -> None:
|
||
self.root = root.expanduser().resolve()
|
||
self.root.mkdir(parents=True, exist_ok=True)
|
||
self.limits = limits
|
||
self.read_only = read_only
|
||
self.allow_outside = allow_outside
|
||
self.touched_files: set[str] = set()
|
||
self.commands: list[dict[str, Any]] = []
|
||
|
||
def _resolve(self, path: str) -> Path:
|
||
raw = Path(path).expanduser()
|
||
candidate = raw if raw.is_absolute() else self.root / raw
|
||
resolved = candidate.resolve()
|
||
if not self.allow_outside and resolved != self.root and self.root not in resolved.parents:
|
||
raise ToolError(
|
||
f"Путь {path!r} выходит за пределы рабочей папки {self.root}. "
|
||
"Работать можно только внутри неё."
|
||
)
|
||
return resolved
|
||
|
||
def rel(self, path: Path) -> str:
|
||
try:
|
||
return str(path.relative_to(self.root))
|
||
except ValueError:
|
||
return str(path)
|
||
|
||
async def read_file(self, path: str, offset: int = 1, limit: int = 400) -> str:
|
||
target = self._resolve(path)
|
||
if not target.exists():
|
||
raise ToolError(f"Файл не найден: {self.rel(target)}")
|
||
if target.is_dir():
|
||
raise ToolError(f"{self.rel(target)} — директория. Используйте list_files.")
|
||
text = _read_text(target, self.limits)
|
||
offset = max(1, int(offset))
|
||
limit = max(1, min(int(limit), 2000))
|
||
numbered, total = _numbered(text, offset, limit)
|
||
header = f"{self.rel(target)} (строки {offset}–{min(total, offset + limit - 1)} из {total})"
|
||
return f"# {header}\n{numbered}" if numbered else f"# {header}\n(пусто)"
|
||
|
||
async def write_file(self, path: str, content: str) -> str:
|
||
if self.read_only:
|
||
raise ToolError("Эта рабочая папка открыта только для чтения")
|
||
target = self._resolve(path)
|
||
if target.exists() and target.is_dir():
|
||
raise ToolError(f"{self.rel(target)} — директория, нельзя записать файл")
|
||
target.parent.mkdir(parents=True, exist_ok=True)
|
||
with open(target, "w", encoding="utf-8", newline="") as fh:
|
||
fh.write(content)
|
||
self.touched_files.add(self.rel(target))
|
||
return f"Записан {self.rel(target)} ({len(content)} символов)"
|
||
|
||
async def edit_file(
|
||
self,
|
||
path: str,
|
||
old_string: str,
|
||
new_string: str,
|
||
replace_all: bool = False,
|
||
) -> str:
|
||
if self.read_only:
|
||
raise ToolError("Эта рабочая папка открыта только для чтения")
|
||
target = self._resolve(path)
|
||
if not target.exists():
|
||
raise ToolError(f"Файл не найден: {self.rel(target)}")
|
||
if not old_string:
|
||
raise ToolError("old_string не может быть пустым")
|
||
with open(target, "r", encoding="utf-8", errors="replace", newline="") as fh:
|
||
text = fh.read()
|
||
count = text.count(old_string)
|
||
if count == 0:
|
||
raise ToolError(
|
||
f"Строка не найдена в {self.rel(target)}. Прочитайте файл и повторите "
|
||
"с точным фрагментом (включая отступы)."
|
||
)
|
||
if count > 1 and not replace_all:
|
||
raise ToolError(
|
||
f"Фрагмент встречается {count} раз(а) в {self.rel(target)}. "
|
||
"Добавьте контекст или используйте replace_all=true."
|
||
)
|
||
updated = text.replace(old_string, new_string) if replace_all else text.replace(
|
||
old_string, new_string, 1
|
||
)
|
||
with open(target, "w", encoding="utf-8", newline="") as fh:
|
||
fh.write(updated)
|
||
self.touched_files.add(self.rel(target))
|
||
replacements = count if replace_all else 1
|
||
return f"Изменён {self.rel(target)} — заменено вхождений: {replacements}"
|
||
|
||
async def list_files(self, path: str = ".", depth: int = 2, limit: int = 300) -> str:
|
||
target = self._resolve(path)
|
||
if not target.exists():
|
||
raise ToolError(f"Путь не найден: {self.rel(target)}")
|
||
if target.is_file():
|
||
return f"{self.rel(target)} ({_format_bytes(target.stat().st_size)})"
|
||
depth = max(1, min(int(depth), 6))
|
||
limit = max(1, min(int(limit), 1000))
|
||
lines: list[str] = []
|
||
truncated = False
|
||
|
||
def walk(directory: Path, level: int) -> None:
|
||
nonlocal truncated
|
||
if len(lines) >= limit:
|
||
truncated = True
|
||
return
|
||
try:
|
||
entries = sorted(
|
||
directory.iterdir(), key=lambda p: (not p.is_dir(), p.name.lower())
|
||
)
|
||
except OSError:
|
||
return
|
||
for entry in entries:
|
||
if len(lines) >= limit:
|
||
truncated = True
|
||
return
|
||
if entry.name in IGNORED_DIRS:
|
||
continue
|
||
indent = " " * (level - 1)
|
||
if entry.is_symlink():
|
||
lines.append(f"{indent}{entry.name} -> symlink")
|
||
continue
|
||
if entry.is_dir():
|
||
lines.append(f"{indent}{entry.name}/")
|
||
if level < depth:
|
||
walk(entry, level + 1)
|
||
else:
|
||
try:
|
||
size = entry.stat().st_size
|
||
lines.append(f"{indent}{entry.name} ({_format_bytes(size)})")
|
||
except OSError:
|
||
lines.append(f"{indent}{entry.name}")
|
||
|
||
walk(target, 1)
|
||
body = "\n".join(lines) if lines else "(пусто)"
|
||
root_label = self.rel(target) or "."
|
||
note = "\n… (список обрезан)" if truncated else ""
|
||
return f"# {root_label}\n{body}{note}"
|
||
|
||
async def search_files(
|
||
self,
|
||
pattern: str,
|
||
path: str = ".",
|
||
glob: str | None = None,
|
||
max_results: int = 80,
|
||
) -> str:
|
||
target = self._resolve(path)
|
||
max_results = max(1, min(int(max_results), 500))
|
||
rg = shutil.which("rg")
|
||
if rg:
|
||
cmd = [
|
||
rg,
|
||
"-n",
|
||
"--no-heading",
|
||
"--color",
|
||
"never",
|
||
"--hidden",
|
||
"--glob",
|
||
"!.git/**",
|
||
"--glob",
|
||
"!.airouter/**",
|
||
"--glob",
|
||
"!node_modules/**",
|
||
"--glob",
|
||
"!.venv/**",
|
||
]
|
||
if glob:
|
||
cmd += ["--glob", glob]
|
||
cmd += ["-e", pattern, "--", str(target)]
|
||
try:
|
||
proc = await self._run_proc(cmd, cwd=self.root, timeout=25)
|
||
if proc["exit_code"] in (0, 1):
|
||
lines = proc["stdout"].splitlines()
|
||
if not lines:
|
||
return "Совпадений не найдено"
|
||
if len(lines) > max_results:
|
||
lines = lines[:max_results]
|
||
lines.append(f"… (показано {max_results} совпадений)")
|
||
return "\n".join(
|
||
line.replace(str(self.root) + "/", "") for line in lines
|
||
)
|
||
except ToolError:
|
||
raise
|
||
except Exception:
|
||
pass
|
||
return self._python_search(target, pattern, glob, max_results)
|
||
|
||
def _python_search(
|
||
self, target: Path, pattern: str, glob: str | None, max_results: int
|
||
) -> str:
|
||
try:
|
||
regex = re.compile(pattern)
|
||
except re.error as exc:
|
||
raise ToolError(f"Некорректное регулярное выражение: {exc}") from exc
|
||
results: list[str] = []
|
||
candidates: list[Path] = []
|
||
if target.is_file():
|
||
candidates = [target]
|
||
else:
|
||
for root, dirs, files in os.walk(target):
|
||
dirs[:] = [d for d in dirs if d not in IGNORED_DIRS]
|
||
for name in files:
|
||
candidates.append(Path(root) / name)
|
||
if len(candidates) > 3000:
|
||
break
|
||
for file in candidates:
|
||
if glob and not fnmatch.fnmatch(file.name, glob):
|
||
continue
|
||
try:
|
||
if file.stat().st_size > 1_000_000:
|
||
continue
|
||
with open(file, "r", encoding="utf-8", errors="replace") as fh:
|
||
for number, line in enumerate(fh, 1):
|
||
if regex.search(line):
|
||
results.append(f"{self.rel(file)}:{number}: {line.rstrip()}")
|
||
if len(results) >= max_results:
|
||
break
|
||
except (OSError, UnicodeError):
|
||
continue
|
||
if len(results) >= max_results:
|
||
break
|
||
return "\n".join(results) if results else "Совпадений не найдено"
|
||
|
||
async def _run_proc(self, cmd: list[str], *, cwd: Path, timeout: float) -> dict[str, Any]:
|
||
started = time.monotonic()
|
||
proc = await asyncio.create_subprocess_exec(
|
||
*cmd,
|
||
cwd=str(cwd),
|
||
stdin=asyncio.subprocess.DEVNULL,
|
||
stdout=asyncio.subprocess.PIPE,
|
||
stderr=asyncio.subprocess.PIPE,
|
||
start_new_session=True,
|
||
)
|
||
try:
|
||
stdout_b, stderr_b = await asyncio.wait_for(proc.communicate(), timeout=timeout)
|
||
except TimeoutError:
|
||
try:
|
||
os.killpg(proc.pid, signal.SIGKILL)
|
||
except OSError:
|
||
proc.kill()
|
||
await proc.wait()
|
||
raise ToolError(f"Команда превысила лимит {timeout:.0f}с и была остановлена")
|
||
return {
|
||
"exit_code": proc.returncode or 0,
|
||
"stdout": stdout_b.decode("utf-8", errors="replace"),
|
||
"stderr": stderr_b.decode("utf-8", errors="replace"),
|
||
"duration": time.monotonic() - started,
|
||
}
|
||
|
||
async def bash(self, command: str, timeout: int | None = None) -> str:
|
||
if self.read_only:
|
||
raise ToolError("Bash недоступен для этой рабочей папки")
|
||
timeout = max(1, min(int(timeout or self.limits.bash_timeout), 3600))
|
||
shell = shutil.which("bash") or "/bin/sh"
|
||
started = time.monotonic()
|
||
proc = await asyncio.create_subprocess_shell(
|
||
command,
|
||
cwd=str(self.root),
|
||
executable=shell,
|
||
stdin=asyncio.subprocess.DEVNULL,
|
||
stdout=asyncio.subprocess.PIPE,
|
||
stderr=asyncio.subprocess.PIPE,
|
||
start_new_session=True,
|
||
env={**os.environ, "AIROUTER_WORKSPACE": str(self.root)},
|
||
)
|
||
timed_out = False
|
||
try:
|
||
stdout_b, stderr_b = await asyncio.wait_for(proc.communicate(), timeout=timeout)
|
||
except TimeoutError:
|
||
timed_out = True
|
||
try:
|
||
os.killpg(proc.pid, signal.SIGKILL)
|
||
except OSError:
|
||
proc.kill()
|
||
try:
|
||
stdout_b, stderr_b = await asyncio.wait_for(proc.communicate(), timeout=5)
|
||
except TimeoutError:
|
||
stdout_b, stderr_b = b"", b""
|
||
duration = time.monotonic() - started
|
||
exit_code = proc.returncode if proc.returncode is not None else -1
|
||
stdout = stdout_b.decode("utf-8", errors="replace")
|
||
stderr = stderr_b.decode("utf-8", errors="replace")
|
||
self.commands.append(
|
||
{
|
||
"command": command,
|
||
"exit_code": exit_code,
|
||
"duration": round(duration, 2),
|
||
"timed_out": timed_out,
|
||
}
|
||
)
|
||
|
||
limit = self.limits.tool_output_max_chars
|
||
stdout = truncate(stdout, limit)
|
||
stderr = truncate(stderr, limit)
|
||
parts = [f"$ {command}", f"exit_code: {exit_code}", f"duration: {duration:.2f}s"]
|
||
if timed_out:
|
||
parts.append(f"TIMEOUT: команда остановлена через {timeout}s")
|
||
if stdout.strip():
|
||
parts.append("stdout:\n" + stdout.rstrip())
|
||
if stderr.strip():
|
||
parts.append("stderr:\n" + stderr.rstrip())
|
||
if not stdout.strip() and not stderr.strip():
|
||
parts.append("(нет вывода)")
|
||
return "\n".join(parts)
|
||
|
||
async def git_changed_files(self) -> list[str]:
|
||
changed = set(self.touched_files)
|
||
git = shutil.which("git")
|
||
if not git:
|
||
return sorted(changed)
|
||
try:
|
||
check = await self._run_proc(
|
||
[git, "rev-parse", "--is-inside-work-tree"], cwd=self.root, timeout=10
|
||
)
|
||
if check["exit_code"] != 0 or check["stdout"].strip() != "true":
|
||
return sorted(changed)
|
||
proc = await self._run_proc(
|
||
[git, "status", "--porcelain", "--", "."], cwd=self.root, timeout=10
|
||
)
|
||
for line in proc["stdout"].splitlines():
|
||
if not line.strip():
|
||
continue
|
||
name = line[3:].strip()
|
||
if " -> " in name:
|
||
name = name.split(" -> ", 1)[1]
|
||
name = name.strip('"')
|
||
if any(part in IGNORED_DIRS for part in Path(name).parts):
|
||
continue
|
||
changed.add(name)
|
||
except Exception:
|
||
pass
|
||
return sorted(changed)[:100]
|
||
|
||
def snapshot(self, limit: int = 5000) -> dict[str, tuple[int, int]]:
|
||
"""Cheap fingerprint of the workspace to catch changes made via bash."""
|
||
files: dict[str, tuple[int, int]] = {}
|
||
for root, dirs, names in os.walk(self.root):
|
||
dirs[:] = [d for d in dirs if d not in IGNORED_DIRS]
|
||
for name in names:
|
||
path = Path(root) / name
|
||
try:
|
||
if path.is_symlink():
|
||
continue
|
||
stat = path.stat()
|
||
files[str(path.relative_to(self.root))] = (stat.st_mtime_ns, stat.st_size)
|
||
except OSError:
|
||
continue
|
||
if len(files) >= limit:
|
||
return files
|
||
return files
|
||
|
||
def snapshot_diff(self, before: dict[str, tuple[int, int]]) -> list[str]:
|
||
after = self.snapshot()
|
||
changed: set[str] = set()
|
||
for path, meta in after.items():
|
||
if before.get(path) != meta:
|
||
changed.add(path)
|
||
for path in before:
|
||
if path not in after:
|
||
changed.add(path)
|
||
return sorted(changed)
|
||
|
||
|
||
class ReadOnlyFS:
|
||
"""Read-only file access for the lead agent, including paths outside cwd."""
|
||
|
||
def __init__(self, root: Path, limits: LimitsConfig) -> None:
|
||
self.workspace = Workspace(
|
||
root, limits, read_only=True, allow_outside=True
|
||
)
|
||
|
||
async def read_file(self, path: str, offset: int = 1, limit: int = 400) -> str:
|
||
return await self.workspace.read_file(path, offset, limit)
|
||
|
||
async def list_files(self, path: str = ".", depth: int = 2, limit: int = 300) -> str:
|
||
return await self.workspace.list_files(path, depth, limit)
|
||
|
||
async def search_files(
|
||
self, pattern: str, path: str = ".", glob: str | None = None, max_results: int = 80
|
||
) -> str:
|
||
return await self.workspace.search_files(pattern, path, glob, max_results)
|