import hashlib import mmap from pathlib import Path from codecs import getincrementaldecoder def read_file(path: str, project_dir: str, offset: int = 0, limit: int = 2000) -> str: full_path, error = _resolve_project_path(path, project_dir) if error: return error if not full_path.exists(): return f"Error: File not found: {path}" if not full_path.is_file(): return f"Error: Not a file: {path}" return _read_numbered_file(full_path, offset, limit) def _read_numbered_file(full_path: Path, offset: int, limit: int) -> str: content = full_path.read_text(encoding="utf-8", errors="replace") lines = content.splitlines() if offset > 0 or limit < len(lines): lines = lines[offset : offset + limit] numbered = [f"{i + offset + 1}: {line}" for i, line in enumerate(lines)] return "\n".join(numbered) def read_evidence_file( path: str, evidence_roots: list[str], offset: int = 0, limit: int = 2000 ) -> str: """Read a relative file from one of a task's explicitly approved evidence roots.""" candidate, error = _resolve_evidence_file(path, evidence_roots) if error: return error return _read_numbered_file(candidate, offset, limit) def read_evidence_metadata( path: str, evidence_roots: list[str], max_file_bytes: int = 1_000_000_000, ) -> str: """Return bounded byte-level metadata for one approved evidence file. The result deliberately omits file content. It allows a read-only task to confirm a source's hash, UTF-8/BOM state, and newline characteristics before proposing an exact raw-output contract. """ candidate, error = _resolve_evidence_file(path, evidence_roots) if error: return error if max_file_bytes < 1: return "Error: max_file_bytes must be positive." try: if candidate.stat().st_size > max_file_bytes: return f"Error: Evidence file exceeds the {max_file_bytes} byte metadata safety limit." metadata = _stream_evidence_metadata(candidate) except OSError as exc: return f"Error: Could not read evidence metadata: {exc}" return "\n".join( ( f"Evidence metadata: {path}", f"Byte length: {metadata['byte_length']}", f"SHA-256: {metadata['sha256']}", f"UTF-8 decode: {metadata['utf8_state']}; BOM: {metadata['bom']}", f"ASCII-only: {metadata['ascii_only']}", f"Line endings: LF={metadata['lf_count']}, CRLF={metadata['crlf_count']}, CR={metadata['cr_count']}", f"Terminal newline: {metadata['terminal_newline']}", ) ) def _stream_evidence_metadata(candidate: Path) -> dict[str, int | str]: """Collect exact byte facts with bounded memory for an approved corpus file.""" digest = hashlib.sha256() decoder = getincrementaldecoder("utf-8-sig")() byte_length = lf_count = crlf_count = cr_count = 0 ascii_only = True utf8_state = "valid" previous_cr = False first_bytes = b"" tail = b"" with candidate.open("rb") as handle: for chunk in iter(lambda: handle.read(1024 * 1024), b""): if not first_bytes: first_bytes = chunk[:3] byte_length += len(chunk) digest.update(chunk) ascii_only = ascii_only and chunk.isascii() try: decoder.decode(chunk) except UnicodeDecodeError: utf8_state = "invalid" for value in chunk: if previous_cr: if value == 10: crlf_count += 1 previous_cr = False continue cr_count += 1 previous_cr = False if value == 13: previous_cr = True elif value == 10: lf_count += 1 tail = (tail + chunk)[-2:] if previous_cr: cr_count += 1 if utf8_state == "valid": try: decoder.decode(b"", final=True) except UnicodeDecodeError: utf8_state = "invalid" return { "byte_length": byte_length, "sha256": digest.hexdigest(), "utf8_state": utf8_state, "bom": "utf-8" if first_bytes.startswith(b"\xef\xbb\xbf") else "none", "ascii_only": "yes" if ascii_only else "no", "lf_count": lf_count, "crlf_count": crlf_count, "cr_count": cr_count, "terminal_newline": ( "crlf" if tail.endswith(b"\r\n") else "lf" if tail.endswith(b"\n") else "cr" if tail.endswith(b"\r") else "none" ), } def read_evidence_section( path: str, start_text: str, evidence_roots: list[str], end_text: str = "", occurrence: int = 0, max_chars: int = 60000, ) -> str: """Return one bounded, marker-delimited section from approved evidence. This makes a large one-line corpus file inspectable without granting the worker arbitrary shell access outside the project. Markers are literal text rather than regular expressions so callers cannot execute code. """ candidate, error = _resolve_evidence_file(path, evidence_roots) if error: return error if occurrence < 0 or max_chars < 1: return "Error: occurrence must be non-negative and max_chars must be positive." start_bytes = start_text.encode("utf-8") end_bytes = end_text.encode("utf-8") try: with ( candidate.open("rb") as handle, mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_READ) as content, ): start = _find_occurrence(content, start_bytes, occurrence) if start < 0: return f"Error: Start marker not found in evidence file: {start_text}" cursor = start + len(start_bytes) end = len(content) if end_text: end = content.find(end_bytes, cursor) if end < 0: return f"Error: End marker not found after start marker: {end_text}" end += len(end_bytes) excerpt = content[start:end].decode("utf-8", errors="replace") except OSError as exc: return f"Error: Could not read evidence section: {exc}" if len(excerpt) > max_chars: return ( f"Error: Evidence section is {len(excerpt)} characters, exceeding the {max_chars} " "character safety limit. Use a narrower end marker." ) return excerpt def search_evidence_text( text: str, evidence_roots: list[str], suffix: str = ".xml", max_results: int = 100, max_file_bytes: int = 1_000_000_000, ) -> str: """Find literal text in approved evidence and return bounded per-file counts.""" if not text: return "Error: Evidence search text cannot be empty." if max_results < 1 or max_file_bytes < 1: return "Error: max_results and max_file_bytes must be positive." normalized_suffix = suffix.lower() matches: list[str] = [] skipped_large = 0 needle = text.encode("utf-8") for raw_root in evidence_roots: root = Path(raw_root).resolve() if not root.is_dir(): continue for candidate in sorted(root.rglob("*")): if not candidate.is_file() or candidate.suffix.lower() != normalized_suffix: continue if candidate.stat().st_size > max_file_bytes: skipped_large += 1 continue try: with ( candidate.open("rb") as handle, mmap.mmap(handle.fileno(), 0, access=mmap.ACCESS_READ) as content, ): count = _count_occurrences(content, needle) except OSError: continue if count: matches.append(f"{candidate.relative_to(root)} ({count} matches; root={root})") if len(matches) >= max_results: return "Matches (truncated):\n" + "\n".join(matches) if not matches: detail = ( f"; skipped {skipped_large} files over {max_file_bytes} bytes" if skipped_large else "" ) return f"No evidence matches for literal text: {text}{detail}" return "Matches:\n" + "\n".join(matches) def _find_occurrence(content: mmap.mmap, needle: bytes, occurrence: int) -> int: cursor = 0 for _ in range(occurrence + 1): cursor = content.find(needle, cursor) if cursor < 0: return -1 if _ < occurrence: cursor += len(needle) return cursor def _count_occurrences(content: mmap.mmap, needle: bytes) -> int: count = 0 cursor = 0 while True: cursor = content.find(needle, cursor) if cursor < 0: return count count += 1 cursor += len(needle) def _resolve_evidence_file(path: str, evidence_roots: list[str]) -> tuple[Path, str]: """Resolve a relative evidence path under an explicitly approved root.""" requested = Path(path) if requested.is_absolute() or ".." in requested.parts: return ( Path(), "Error: Evidence paths must be relative and cannot traverse parent directories.", ) for raw_root in evidence_roots: root = Path(raw_root).resolve() candidate = (root / requested).resolve() if candidate.is_relative_to(root) and candidate.is_file(): return candidate, "" return Path(), f"Error: Evidence file not found in approved roots: {path}" def _resolve_project_path(path: str, project_dir: str) -> tuple[Path, str]: """Resolve a relative project path without allowing an agent to escape its root.""" requested = Path(path) if requested.is_absolute() or ".." in requested.parts: return ( Path(), "Error: Project paths must be relative and cannot traverse parent directories.", ) root = Path(project_dir).resolve() candidate = (root / requested).resolve() if not candidate.is_relative_to(root): return Path(), "Error: Project path resolves outside the target project." return candidate, "" def write_file(path: str, content: str, project_dir: str) -> str: full_path, error = _resolve_project_path(path, project_dir) if error: return error full_path.parent.mkdir(parents=True, exist_ok=True) encoded = content.encode("utf-8") full_path.write_bytes(encoded) return f"File written: {path} ({len(encoded)} bytes)" def normalize_line_endings(path: str, style: str, project_dir: str) -> str: """Normalize an existing UTF-8 project file to LF or CRLF without changing text.""" full_path, error = _resolve_project_path(path, project_dir) if error: return error if not full_path.exists() or not full_path.is_file(): return f"Error: File not found: {path}" if style not in {"lf", "crlf"}: return "Error: style must be 'lf' or 'crlf'." try: content = full_path.read_bytes().decode("utf-8") except UnicodeDecodeError: return f"Error: File is not valid UTF-8: {path}" normalized = content.replace("\r\n", "\n").replace("\r", "\n") newline = "\n" if style == "lf" else "\r\n" encoded = normalized.replace("\n", newline).encode("utf-8") full_path.write_bytes(encoded) return f"Line endings normalized: {path} ({style}, {len(encoded)} bytes)" def edit_file(path: str, old_string: str, new_string: str, project_dir: str) -> str: full_path, error = _resolve_project_path(path, project_dir) if error: return error if not full_path.exists(): return f"Error: File not found: {path}" content = full_path.read_text(encoding="utf-8") # 1. Exact match (fast path) exact_count = content.count(old_string) if exact_count == 1: new_content = content.replace(old_string, new_string, 1) full_path.write_bytes(new_content.encode("utf-8")) return f"File edited: {path} (replaced {len(old_string)} -> {len(new_string)} bytes)" elif exact_count > 1: return ( f"Error: old_string found {exact_count} times in {path}. " "Provide more context to make the match unique." ) # 2. Normalized whitespace match (strip trailing whitespace, normalize tabs) normalized_content = _normalize_whitespace(content) normalized_old = _normalize_whitespace(old_string) norm_count = normalized_content.count(normalized_old) if norm_count == 1: idx = normalized_content.index(normalized_old) new_content = content[:idx] + new_string + content[idx + len(old_string) :] full_path.write_bytes(new_content.encode("utf-8")) return f"File edited (whitespace-normalized): {path}" elif norm_count > 1: return ( f"Error: old_string found {norm_count} times after normalizing whitespace in {path}. " "Provide more surrounding context." ) # 3. Strip leading whitespace from every line and try matching stripped_content = _strip_all_leading_whitespace(content) stripped_old = _strip_all_leading_whitespace(old_string) strip_count = stripped_content.count(stripped_old) if strip_count == 1: idx = stripped_content.index(stripped_old) new_content = content[:idx] + new_string + content[idx + len(old_string) :] full_path.write_bytes(new_content.encode("utf-8")) return f"File edited (indentation-stripped match): {path}" elif strip_count > 1: return ( f"Error: old_string found {strip_count} times after stripping indentation in {path}. " "Provide more surrounding context." ) # 4. Try matching individual lines old_lines = old_string.strip().splitlines() if len(old_lines) >= 2: for i, line in enumerate(old_lines): stripped = line.strip() if stripped and stripped in content: return ( f"Error: old_string not found as a block in {path}, " f"but line {i + 1} ('{stripped[:60]}...') was found individually. " "Check indentation levels — the exact whitespace must match." ) return f"Error: old_string not found in {path}. Check exact whitespace and indentation." def _normalize_whitespace(text: str) -> str: """Replace tabs with 4 spaces and strip trailing whitespace from each line.""" lines = text.splitlines() normalized = "\n".join(line.replace("\t", " ").rstrip() for line in lines) return normalized def _strip_all_leading_whitespace(text: str) -> str: """Remove all leading whitespace from every line.""" lines = text.splitlines() return "\n".join(line.lstrip() for line in lines) def glob_files(pattern: str, project_dir: str) -> str: requested = Path(pattern) if requested.is_absolute() or ".." in requested.parts: return "Error: Glob patterns must be relative and cannot traverse parent directories." base = Path(project_dir).resolve() try: matches = list(base.rglob(pattern)) except ValueError as exc: return f"Error: Invalid glob pattern: {exc}" matches = [ str(m.relative_to(base)) for m in matches if m.resolve().is_relative_to(base) and ".git" not in m.parts and "node_modules" not in m.parts ] if not matches: return f"No files match pattern: {pattern}" return "Files matching:\n" + "\n".join(matches[:100])