from pathlib import Path from typing import Optional def discover_project(project_dir: str) -> str: base = Path(project_dir) structure = _build_tree(base, max_depth=3, max_files=200) context_items = _detect_context_files(base) parts = [structure] if context_items: parts.append("\n--- Key Context Files ---") parts.extend(context_items) return "\n".join(parts) def list_directory(path: str, project_dir: str) -> str: requested = Path(path) if requested.is_absolute() or ".." in requested.parts: return "Error: Directory paths must be relative and cannot traverse parent directories." base = Path(project_dir).resolve() target = (base / requested).resolve() if not target.is_relative_to(base): return "Error: Directory path resolves outside the target project." if not target.exists(): return f"Directory not found: {path}" if not target.is_dir(): return f"Not a directory: {path}" entries = sorted(target.iterdir(), key=lambda e: (not e.is_dir(), e.name.lower())) lines = [] for entry in entries[:200]: prefix = "dir /" if entry.is_dir() else " " suffix = f" ({_format_size(entry.stat().st_size)})" if entry.is_file() else "/" lines.append(f"{prefix} {entry.name}{suffix}") return "\n".join(lines) def grep_codebase(pattern: str, project_dir: str, include: str = "") -> str: import subprocess if not pattern: return "Error: Search pattern cannot be empty." if include: requested = Path(include) if requested.is_absolute() or ".." in requested.parts: return ( "Error: Grep include paths must be relative and cannot traverse parent directories." ) args = ["rg", "--no-heading", "-n", "--color", "never"] if include: args.extend(["--glob", include]) args.extend(["--", pattern]) try: result = subprocess.run( args, cwd=str(project_dir), capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=30, ) if result.returncode == 1: return f"No matches for: {pattern}" output = result.stdout.strip() lines = output.splitlines()[:100] return "\n".join(lines) if lines else f"No matches for: {pattern}" except FileNotFoundError: return _grep_codebase_fallback(pattern, project_dir, include) except subprocess.TimeoutExpired: return "Error: grep timed out" except Exception as e: return f"Error: {e}" _GREP_IGNORED_DIR_NAMES = { ".git", ".hg", ".svn", ".mypy_cache", ".pytest_cache", ".ruff_cache", ".venv", "venv", "env", "__pycache__", "node_modules", "dist", "build", } _GREP_BINARY_EXTENSIONS = { ".pyc", ".pyo", ".so", ".dll", ".exe", ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".ico", ".wav", ".mp3", ".zip", ".gz", ".pdf", } _GREP_MAX_FILE_BYTES = 2_000_000 _GREP_MAX_RESULT_LINES = 100 def _grep_codebase_fallback(pattern: str, project_dir: str, include: str) -> str: """Pure-Python regex search used when the 'rg' binary is not installed. ripgrep is a separate binary that many machines running AFK simply do not have on PATH, which previously made ``grep_codebase`` unconditionally fail with an install-ripgrep error message. This keeps the tool usable (if slower) everywhere by walking the tree directly with the standard library. """ import fnmatch import re base = Path(project_dir).resolve() try: regex = re.compile(pattern) except re.error as exc: return f"Error: invalid search pattern: {exc}" matches: list[str] = [] for path in sorted(base.rglob("*")): if not path.is_file(): continue if any( part in _GREP_IGNORED_DIR_NAMES or part.endswith(".egg-info") for part in path.parts ): continue if path.suffix.lower() in _GREP_BINARY_EXTENSIONS: continue rel = path.relative_to(base).as_posix() if include and not (fnmatch.fnmatch(path.name, include) or fnmatch.fnmatch(rel, include)): continue try: if path.stat().st_size > _GREP_MAX_FILE_BYTES: continue text = path.read_text(encoding="utf-8", errors="replace") except OSError: continue for line_number, line in enumerate(text.splitlines(), start=1): if regex.search(line): matches.append(f"{rel}:{line_number}:{line}") if len(matches) >= _GREP_MAX_RESULT_LINES: return "\n".join(matches) return "\n".join(matches) if matches else f"No matches for: {pattern}" def _build_tree( base: Path, current: Optional[Path] = None, depth: int = 0, max_depth: int = 3, max_files: int = 200, count: list = None, ) -> str: if count is None: count = [0] if current is None: current = base if depth > max_depth or count[0] >= max_files: return "" entries = sorted(current.iterdir(), key=lambda e: (not e.is_dir(), e.name.lower())) lines = [] indent = " " * depth for entry in entries: if entry.name.startswith(".") and entry.name not in (".env.example",): continue if entry.name in ("node_modules", "__pycache__", ".git", ".mypy_cache", ".ruff_cache"): continue count[0] += 1 if count[0] > max_files: lines.append(f"{indent}... ({max_files} files reached)") break if entry.is_dir(): lines.append(f"{indent}{entry.name}/") sub = _build_tree(base, entry, depth + 1, max_depth, max_files, count) if sub: lines.append(sub) else: lines.append(f"{indent}{entry.name}") return "\n".join(lines) def _detect_context_files(base: Path) -> list[str]: candidates = [ "pyproject.toml", "setup.py", "requirements.txt", "Cargo.toml", "package.json", "tsconfig.json", "go.mod", "CMakeLists.txt", "Makefile", "Makefile.in", "Dockerfile", "compose.yaml", "README.md", "README.rst", "AGENTS.md", "CONTRIBUTING.md", ] items = [] for c in candidates: if (base / c).exists(): try: content = (base / c).read_text(encoding="utf-8", errors="replace") preview = content[:1000] + ("..." if len(content) > 1000 else "") items.append(f"--- {c} ---\n{preview}") except OSError: pass return items def _format_size(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"