Репозитории / AiRouter / airouter/workspace.py

workspace.py

К файлам Скачать / raw
1"""Workspace filesystem and shell tools for workers, plus read-only tools for the lead."""
2
3from __future__ import annotations
4
5import asyncio
6import fnmatch
7import os
8import re
9import shutil
10import signal
11import time
12from pathlib import Path
13from typing import Any
14
15from .config import LimitsConfig
16from .utils import truncate
17
18IGNORED_DIRS = {
19 ".git",
20 ".hg",
21 ".svn",
22 ".airouter",
23 ".venv",
24 "venv",
25 "node_modules",
26 "__pycache__",
27 ".pytest_cache",
28 ".mypy_cache",
29 ".ruff_cache",
30 "dist",
31 "build",
32 ".next",
33 "target",
34}
35
36
37class ToolError(RuntimeError):
38 pass
39
40
41def _is_binary(data: bytes) -> bool:
42 return b"\x00" in data[:4096]
43
44
45def _read_text(path: Path, limits: LimitsConfig) -> str:
46 try:
47 size = path.stat().st_size
48 except OSError as exc:
49 raise ToolError(f"Не удалось прочитать {path}: {exc}") from exc
50 if size > limits.max_file_bytes:
51 raise ToolError(
52 f"Файл слишком большой ({size} байт > {limits.max_file_bytes}). "
53 "Прочитайте фрагмент через bash, например `head -n 200 файл`."
54 )
55 data = path.read_bytes()
56 if _is_binary(data):
57 raise ToolError(f"{path} — бинарный файл, чтение текстом невозможно")
58 with open(path, "r", encoding="utf-8", errors="replace", newline="") as fh:
59 return fh.read()
60
61
62def _numbered(text: str, offset: int, limit: int) -> tuple[str, int]:
63 lines = text.splitlines()
64 total = len(lines)
65 start = max(0, offset - 1)
66 end = min(total, start + limit)
67 numbered = "\n".join(f"{i + 1}: {line}" for i, line in enumerate(lines[start:end], start))
68 return numbered, total
69
70
71def _format_bytes(size: int) -> str:
72 if size < 1024:
73 return f"{size} B"
74 if size < 1024 * 1024:
75 return f"{size / 1024:.1f} KB"
76 return f"{size / (1024 * 1024):.1f} MB"
77
78
79class Workspace:
80 """A worker workspace. File operations are confined to its root by default."""
81
82 def __init__(
83 self,
84 root: Path,
85 limits: LimitsConfig,
86 *,
87 read_only: bool = False,
88 allow_outside: bool = False,
89 ) -> None:
90 self.root = root.expanduser().resolve()
91 self.root.mkdir(parents=True, exist_ok=True)
92 self.limits = limits
93 self.read_only = read_only
94 self.allow_outside = allow_outside
95 self.touched_files: set[str] = set()
96 self.commands: list[dict[str, Any]] = []
97
98 def _resolve(self, path: str) -> Path:
99 raw = Path(path).expanduser()
100 candidate = raw if raw.is_absolute() else self.root / raw
101 resolved = candidate.resolve()
102 if not self.allow_outside and resolved != self.root and self.root not in resolved.parents:
103 raise ToolError(
104 f"Путь {path!r} выходит за пределы рабочей папки {self.root}. "
105 "Работать можно только внутри неё."
106 )
107 return resolved
108
109 def rel(self, path: Path) -> str:
110 try:
111 return str(path.relative_to(self.root))
112 except ValueError:
113 return str(path)
114
115 async def read_file(self, path: str, offset: int = 1, limit: int = 400) -> str:
116 target = self._resolve(path)
117 if not target.exists():
118 raise ToolError(f"Файл не найден: {self.rel(target)}")
119 if target.is_dir():
120 raise ToolError(f"{self.rel(target)} — директория. Используйте list_files.")
121 text = _read_text(target, self.limits)
122 offset = max(1, int(offset))
123 limit = max(1, min(int(limit), 2000))
124 numbered, total = _numbered(text, offset, limit)
125 header = f"{self.rel(target)} (строки {offset}–{min(total, offset + limit - 1)} из {total})"
126 return f"# {header}\n{numbered}" if numbered else f"# {header}\n(пусто)"
127
128 async def write_file(self, path: str, content: str) -> str:
129 if self.read_only:
130 raise ToolError("Эта рабочая папка открыта только для чтения")
131 target = self._resolve(path)
132 if target.exists() and target.is_dir():
133 raise ToolError(f"{self.rel(target)} — директория, нельзя записать файл")
134 target.parent.mkdir(parents=True, exist_ok=True)
135 with open(target, "w", encoding="utf-8", newline="") as fh:
136 fh.write(content)
137 self.touched_files.add(self.rel(target))
138 return f"Записан {self.rel(target)} ({len(content)} символов)"
139
140 async def edit_file(
141 self,
142 path: str,
143 old_string: str,
144 new_string: str,
145 replace_all: bool = False,
146 ) -> str:
147 if self.read_only:
148 raise ToolError("Эта рабочая папка открыта только для чтения")
149 target = self._resolve(path)
150 if not target.exists():
151 raise ToolError(f"Файл не найден: {self.rel(target)}")
152 if not old_string:
153 raise ToolError("old_string не может быть пустым")
154 with open(target, "r", encoding="utf-8", errors="replace", newline="") as fh:
155 text = fh.read()
156 count = text.count(old_string)
157 if count == 0:
158 raise ToolError(
159 f"Строка не найдена в {self.rel(target)}. Прочитайте файл и повторите "
160 "с точным фрагментом (включая отступы)."
161 )
162 if count > 1 and not replace_all:
163 raise ToolError(
164 f"Фрагмент встречается {count} раз(а) в {self.rel(target)}. "
165 "Добавьте контекст или используйте replace_all=true."
166 )
167 updated = text.replace(old_string, new_string) if replace_all else text.replace(
168 old_string, new_string, 1
169 )
170 with open(target, "w", encoding="utf-8", newline="") as fh:
171 fh.write(updated)
172 self.touched_files.add(self.rel(target))
173 replacements = count if replace_all else 1
174 return f"Изменён {self.rel(target)} — заменено вхождений: {replacements}"
175
176 async def list_files(self, path: str = ".", depth: int = 2, limit: int = 300) -> str:
177 target = self._resolve(path)
178 if not target.exists():
179 raise ToolError(f"Путь не найден: {self.rel(target)}")
180 if target.is_file():
181 return f"{self.rel(target)} ({_format_bytes(target.stat().st_size)})"
182 depth = max(1, min(int(depth), 6))
183 limit = max(1, min(int(limit), 1000))
184 lines: list[str] = []
185 truncated = False
186
187 def walk(directory: Path, level: int) -> None:
188 nonlocal truncated
189 if len(lines) >= limit:
190 truncated = True
191 return
192 try:
193 entries = sorted(
194 directory.iterdir(), key=lambda p: (not p.is_dir(), p.name.lower())
195 )
196 except OSError:
197 return
198 for entry in entries:
199 if len(lines) >= limit:
200 truncated = True
201 return
202 if entry.name in IGNORED_DIRS:
203 continue
204 indent = " " * (level - 1)
205 if entry.is_symlink():
206 lines.append(f"{indent}{entry.name} -> symlink")
207 continue
208 if entry.is_dir():
209 lines.append(f"{indent}{entry.name}/")
210 if level < depth:
211 walk(entry, level + 1)
212 else:
213 try:
214 size = entry.stat().st_size
215 lines.append(f"{indent}{entry.name} ({_format_bytes(size)})")
216 except OSError:
217 lines.append(f"{indent}{entry.name}")
218
219 walk(target, 1)
220 body = "\n".join(lines) if lines else "(пусто)"
221 root_label = self.rel(target) or "."
222 note = "\n… (список обрезан)" if truncated else ""
223 return f"# {root_label}\n{body}{note}"
224
225 async def search_files(
226 self,
227 pattern: str,
228 path: str = ".",
229 glob: str | None = None,
230 max_results: int = 80,
231 ) -> str:
232 target = self._resolve(path)
233 max_results = max(1, min(int(max_results), 500))
234 rg = shutil.which("rg")
235 if rg:
236 cmd = [
237 rg,
238 "-n",
239 "--no-heading",
240 "--color",
241 "never",
242 "--hidden",
243 "--glob",
244 "!.git/**",
245 "--glob",
246 "!.airouter/**",
247 "--glob",
248 "!node_modules/**",
249 "--glob",
250 "!.venv/**",
251 ]
252 if glob:
253 cmd += ["--glob", glob]
254 cmd += ["-e", pattern, "--", str(target)]
255 try:
256 proc = await self._run_proc(cmd, cwd=self.root, timeout=25)
257 if proc["exit_code"] in (0, 1):
258 lines = proc["stdout"].splitlines()
259 if not lines:
260 return "Совпадений не найдено"
261 if len(lines) > max_results:
262 lines = lines[:max_results]
263 lines.append(f"… (показано {max_results} совпадений)")
264 return "\n".join(
265 line.replace(str(self.root) + "/", "") for line in lines
266 )
267 except ToolError:
268 raise
269 except Exception:
270 pass
271 return self._python_search(target, pattern, glob, max_results)
272
273 def _python_search(
274 self, target: Path, pattern: str, glob: str | None, max_results: int
275 ) -> str:
276 try:
277 regex = re.compile(pattern)
278 except re.error as exc:
279 raise ToolError(f"Некорректное регулярное выражение: {exc}") from exc
280 results: list[str] = []
281 candidates: list[Path] = []
282 if target.is_file():
283 candidates = [target]
284 else:
285 for root, dirs, files in os.walk(target):
286 dirs[:] = [d for d in dirs if d not in IGNORED_DIRS]
287 for name in files:
288 candidates.append(Path(root) / name)
289 if len(candidates) > 3000:
290 break
291 for file in candidates:
292 if glob and not fnmatch.fnmatch(file.name, glob):
293 continue
294 try:
295 if file.stat().st_size > 1_000_000:
296 continue
297 with open(file, "r", encoding="utf-8", errors="replace") as fh:
298 for number, line in enumerate(fh, 1):
299 if regex.search(line):
300 results.append(f"{self.rel(file)}:{number}: {line.rstrip()}")
301 if len(results) >= max_results:
302 break
303 except (OSError, UnicodeError):
304 continue
305 if len(results) >= max_results:
306 break
307 return "\n".join(results) if results else "Совпадений не найдено"
308
309 async def _run_proc(self, cmd: list[str], *, cwd: Path, timeout: float) -> dict[str, Any]:
310 started = time.monotonic()
311 proc = await asyncio.create_subprocess_exec(
312 *cmd,
313 cwd=str(cwd),
314 stdin=asyncio.subprocess.DEVNULL,
315 stdout=asyncio.subprocess.PIPE,
316 stderr=asyncio.subprocess.PIPE,
317 start_new_session=True,
318 )
319 try:
320 stdout_b, stderr_b = await asyncio.wait_for(proc.communicate(), timeout=timeout)
321 except TimeoutError:
322 try:
323 os.killpg(proc.pid, signal.SIGKILL)
324 except OSError:
325 proc.kill()
326 await proc.wait()
327 raise ToolError(f"Команда превысила лимит {timeout:.0f}с и была остановлена")
328 return {
329 "exit_code": proc.returncode or 0,
330 "stdout": stdout_b.decode("utf-8", errors="replace"),
331 "stderr": stderr_b.decode("utf-8", errors="replace"),
332 "duration": time.monotonic() - started,
333 }
334
335 async def bash(self, command: str, timeout: int | None = None) -> str:
336 if self.read_only:
337 raise ToolError("Bash недоступен для этой рабочей папки")
338 timeout = max(1, min(int(timeout or self.limits.bash_timeout), 3600))
339 shell = shutil.which("bash") or "/bin/sh"
340 started = time.monotonic()
341 proc = await asyncio.create_subprocess_shell(
342 command,
343 cwd=str(self.root),
344 executable=shell,
345 stdin=asyncio.subprocess.DEVNULL,
346 stdout=asyncio.subprocess.PIPE,
347 stderr=asyncio.subprocess.PIPE,
348 start_new_session=True,
349 env={**os.environ, "AIROUTER_WORKSPACE": str(self.root)},
350 )
351 timed_out = False
352 try:
353 stdout_b, stderr_b = await asyncio.wait_for(proc.communicate(), timeout=timeout)
354 except TimeoutError:
355 timed_out = True
356 try:
357 os.killpg(proc.pid, signal.SIGKILL)
358 except OSError:
359 proc.kill()
360 try:
361 stdout_b, stderr_b = await asyncio.wait_for(proc.communicate(), timeout=5)
362 except TimeoutError:
363 stdout_b, stderr_b = b"", b""
364 duration = time.monotonic() - started
365 exit_code = proc.returncode if proc.returncode is not None else -1
366 stdout = stdout_b.decode("utf-8", errors="replace")
367 stderr = stderr_b.decode("utf-8", errors="replace")
368 self.commands.append(
369 {
370 "command": command,
371 "exit_code": exit_code,
372 "duration": round(duration, 2),
373 "timed_out": timed_out,
374 }
375 )
376
377 limit = self.limits.tool_output_max_chars
378 stdout = truncate(stdout, limit)
379 stderr = truncate(stderr, limit)
380 parts = [f"$ {command}", f"exit_code: {exit_code}", f"duration: {duration:.2f}s"]
381 if timed_out:
382 parts.append(f"TIMEOUT: команда остановлена через {timeout}s")
383 if stdout.strip():
384 parts.append("stdout:\n" + stdout.rstrip())
385 if stderr.strip():
386 parts.append("stderr:\n" + stderr.rstrip())
387 if not stdout.strip() and not stderr.strip():
388 parts.append("(нет вывода)")
389 return "\n".join(parts)
390
391 async def git_changed_files(self) -> list[str]:
392 changed = set(self.touched_files)
393 git = shutil.which("git")
394 if not git:
395 return sorted(changed)
396 try:
397 check = await self._run_proc(
398 [git, "rev-parse", "--is-inside-work-tree"], cwd=self.root, timeout=10
399 )
400 if check["exit_code"] != 0 or check["stdout"].strip() != "true":
401 return sorted(changed)
402 proc = await self._run_proc(
403 [git, "status", "--porcelain", "--", "."], cwd=self.root, timeout=10
404 )
405 for line in proc["stdout"].splitlines():
406 if not line.strip():
407 continue
408 name = line[3:].strip()
409 if " -> " in name:
410 name = name.split(" -> ", 1)[1]
411 name = name.strip('"')
412 if any(part in IGNORED_DIRS for part in Path(name).parts):
413 continue
414 changed.add(name)
415 except Exception:
416 pass
417 return sorted(changed)[:100]
418
419 def snapshot(self, limit: int = 5000) -> dict[str, tuple[int, int]]:
420 """Cheap fingerprint of the workspace to catch changes made via bash."""
421 files: dict[str, tuple[int, int]] = {}
422 for root, dirs, names in os.walk(self.root):
423 dirs[:] = [d for d in dirs if d not in IGNORED_DIRS]
424 for name in names:
425 path = Path(root) / name
426 try:
427 if path.is_symlink():
428 continue
429 stat = path.stat()
430 files[str(path.relative_to(self.root))] = (stat.st_mtime_ns, stat.st_size)
431 except OSError:
432 continue
433 if len(files) >= limit:
434 return files
435 return files
436
437 def snapshot_diff(self, before: dict[str, tuple[int, int]]) -> list[str]:
438 after = self.snapshot()
439 changed: set[str] = set()
440 for path, meta in after.items():
441 if before.get(path) != meta:
442 changed.add(path)
443 for path in before:
444 if path not in after:
445 changed.add(path)
446 return sorted(changed)
447
448
449class ReadOnlyFS:
450 """Read-only file access for the lead agent, including paths outside cwd."""
451
452 def __init__(self, root: Path, limits: LimitsConfig) -> None:
453 self.workspace = Workspace(
454 root, limits, read_only=True, allow_outside=True
455 )
456
457 async def read_file(self, path: str, offset: int = 1, limit: int = 400) -> str:
458 return await self.workspace.read_file(path, offset, limit)
459
460 async def list_files(self, path: str = ".", depth: int = 2, limit: int = 300) -> str:
461 return await self.workspace.list_files(path, depth, limit)
462
463 async def search_files(
464 self, pattern: str, path: str = ".", glob: str | None = None, max_results: int = 80
465 ) -> str:
466 return await self.workspace.search_files(pattern, path, glob, max_results)