"""File system tools for the LangGraph agent.""" from pathlib import Path from langchain_core.tools import tool # Module-level WORKDIR variable, set by main.py during CLI parsing WORKDIR: Path | None = None def set_workdir(path: Path) -> None: """Set the workdir for all tools.""" global WORKDIR WORKDIR = path def get_workdir() -> Path | None: """Get the current workdir.""" return WORKDIR def validate_path(path: str) -> str: """Resolve path against WORKDIR and reject paths outside the boundary. Args: path: A relative or absolute file path. Returns: The resolved absolute path string. Raises: ValueError: If the resolved path is outside the workdir. """ if WORKDIR is None: raise RuntimeError("WORKDIR is not set") candidate = Path(path) if not candidate.is_absolute(): candidate = WORKDIR / candidate resolved = candidate.resolve() try: resolved.relative_to(WORKDIR.resolve()) except ValueError: raise ValueError( f"Error: Access denied — path is outside the workdir: {path}" ) return str(resolved) @tool def read_file( path: str, start_line: int | None = None, end_line: int | None = None ) -> str: """Read a file and return its contents. Args: path: Path to the file to read. start_line: Optional 1-indexed start line (inclusive). end_line: Optional 1-indexed end line (inclusive). Returns: The file contents, optionally filtered to the specified line range. Returns an error string if the file doesn't exist or path is outside workdir. """ try: resolved = validate_path(path) except ValueError as e: return str(e) resolved_path = Path(resolved) if not resolved_path.exists(): return f"Error: File not found: {path}" try: content = resolved_path.read_text() except PermissionError: return f"Error: Permission denied: {path}" if start_line is None and end_line is None: return content lines = content.splitlines(keepends=True) total_lines = len(lines) if total_lines == 0: return content if start_line is None: start_idx = 0 else: start_idx = max(0, start_line - 1) if end_line is None: end_idx = total_lines else: end_idx = min(total_lines, end_line) return "".join(lines[start_idx:end_idx]) @tool def grep(pattern: str, path: str = ".") -> str: """Search for a pattern in files under the given path. Args: pattern: The substring pattern to search for. path: Directory or file path to search in (default: current directory). Returns: Matching lines formatted as {file_path}:{line_number}: {line_content}. Returns a descriptive message if no matches found. Returns an error string if path is outside workdir or doesn't exist. """ try: resolved = validate_path(path) except ValueError as e: return str(e) resolved_path = Path(resolved) if not resolved_path.exists(): return f"Error: Path not found: {path}" results = [] if resolved_path.is_file(): files_to_search = [resolved_path] else: files_to_search = [f for f in resolved_path.rglob("*") if f.is_file()] for file_path in files_to_search: try: content = file_path.read_text() except (PermissionError, UnicodeDecodeError): continue for line_num, line in enumerate(content.splitlines(), start=1): if pattern in line: try: display_path = file_path.relative_to(WORKDIR) except ValueError: display_path = file_path results.append(f"{display_path}:{line_num}: {line}") if not results: return f"No matches found for pattern: {pattern}" return "\n".join(results) @tool def write_file(path: str, content: str) -> str: """Write content to a file. Args: path: Path to the file to write. content: Content to write to the file. Returns: A confirmation message with the file path on success. Returns an error string if path is outside workdir or permission denied. """ try: resolved = validate_path(path) except ValueError as e: return str(e) resolved_path = Path(resolved) resolved_path.parent.mkdir(parents=True, exist_ok=True) try: resolved_path.write_text(content) except PermissionError: return f"Error: Permission denied: {path}" return f"Successfully wrote to {path}" @tool def list_dir(path: str = ".") -> str: """List entries in a directory. Args: path: Path to the directory to list (default: current directory). Returns: A formatted list of entries with [FILE] or [DIR] prefix. Returns an error string if path doesn't exist, isn't a directory, or is outside workdir. """ try: resolved = validate_path(path) except ValueError as e: return str(e) resolved_path = Path(resolved) if not resolved_path.exists(): return f"Error: Path not found: {path}" if not resolved_path.is_dir(): return f"Error: Not a directory: {path}" entries = [] for entry in sorted(resolved_path.iterdir()): if entry.is_dir(): entries.append(f"[DIR] {entry.name}") else: entries.append(f"[FILE] {entry.name}") return "\n".join(entries) @tool def replace_in_file(path: str, search: str, replace: str) -> str: """Search for text in a file and replace first occurance with new text. Args: path: Path to the file to modify. search: The text to search for. replace: The text to replace it with. Returns: A confirmation message with the number of replacements made. Returns an error string if file doesn't exist, path is outside workdir, or the search text is not found. """ try: resolved = validate_path(path) except ValueError as e: return str(e) resolved_path = Path(resolved) if not resolved_path.exists(): return f"Error: File not found: {path}" if not resolved_path.is_file(): return f"Error: Not a file: {path}" try: content = resolved_path.read_text() except PermissionError: return f"Error: Permission denied: {path}" if search not in content: return f"Error: Search text not found in {path}" count = content.count(search) new_content = content.replace(search, replace) try: resolved_path.write_text(new_content) except PermissionError: return f"Error: Permission denied: {path}" return f"Successfully replaced {count} occurrence(s) in {path}"