diff --git a/nanobot/agent/tools/search.py b/nanobot/agent/tools/search.py index 65520314c..bf60cca24 100644 --- a/nanobot/agent/tools/search.py +++ b/nanobot/agent/tools/search.py @@ -18,7 +18,7 @@ from typing import Any, Iterable, Iterator, TypeVar from nanobot.agent.tools._search_content import ContentPage, MatchTooLargeError from nanobot.agent.tools.base import ToolResult from nanobot.agent.tools.filesystem import ListDirTool, _FsTool -from nanobot.execution.files import FileSearch, NotRegularFileError, ReadableFile +from nanobot.execution.files import FileSearch, NotRegularFileError from nanobot.utils.document import ( DocumentLineSource, LocatedDocumentLine, @@ -28,6 +28,7 @@ from nanobot.utils.document import ( _DEFAULT_HEAD_LIMIT = 250 _DEFAULT_FILE_HEAD_LIMIT = 200 _DOCUMENT_EXTENSIONS = frozenset({".pdf", ".docx", ".xlsx", ".pptx"}) +_NON_TEXT_BYTES = re.compile(rb"[\x01-\x08\x0e-\x1f]") T = TypeVar("T") _TYPE_GLOB_MAP = { "py": ("*.py", "*.pyi"), @@ -120,11 +121,19 @@ def _match_glob(rel_path: str, name: str, pattern: str) -> bool: return any(_match_path_glob(rel_path, name, item) for item in _glob_patterns(pattern)) +@lru_cache(maxsize=128) +def _glob_path_parts(pattern: str) -> tuple[str, ...]: + return PurePosixPath(pattern).parts + + def _match_path_glob(rel_path: str, name: str, normalized: str) -> bool: if not normalized: return False if "/" in normalized: - pattern_parts = PurePosixPath(normalized).parts + pattern_parts = _glob_path_parts(normalized) + if len(pattern_parts) == 2 and pattern_parts[0] == "**" and pattern_parts[1] != "**": + # Any directory prefix is allowed, so only the basename matters. + return rel_path != "." and fnmatch.fnmatchcase(name, pattern_parts[1]) path_parts = PurePosixPath(rel_path).parts matched = [True] + [False] * len(path_parts) for part in pattern_parts: @@ -146,8 +155,7 @@ def _is_binary(raw: bytes) -> bool: sample = raw[:4096] if not sample: return False - non_text = sum(byte < 9 or 13 < byte < 32 for byte in sample) - return (non_text / len(sample)) > 0.2 + return len(_NON_TEXT_BYTES.findall(sample)) / len(sample) > 0.2 def _paginate(items: list[T], limit: int | None, offset: int) -> tuple[list[T], bool]: @@ -674,13 +682,7 @@ class GrepTool(_SearchTool): } @staticmethod - def _open_source(source: ReadableFile, pages: str | None, max_bytes: int) -> DocumentLineSource | None: - if source.suffix in _DOCUMENT_EXTENSIONS: - return source.document_lines(pages=pages) - with source.open() as (file, size): - if size > max_bytes: - return None - raw = file.read(max_bytes + 1) + def _text_source(raw: bytes, max_bytes: int) -> DocumentLineSource | None: if len(raw) > max_bytes or _is_binary(raw): return None try: @@ -794,72 +796,89 @@ class GrepTool(_SearchTool): self._MAX_FILE_BYTES if tree.is_directory else self._MAX_EXPLICIT_FILE_BYTES ) - for file_path in self._iter_files(tree, budget): - rel_path = file_path.relative_to(root).as_posix() - if glob and not _match_glob(rel_path, file_path.name, glob): - continue - if not _matches_type(file_path.name, type): - continue - display_path = self._display_path(file_path, root) - - try: - file = tree.read_file(file_path) - except OSError: - skipped_binary += 1 - continue - if file.size > max_file_bytes: - skipped_large += 1 - continue - source_iterator: Iterator[LocatedDocumentLine] | None = None - is_document = file.suffix in _DOCUMENT_EXTENSIONS - try: - source = self._open_source(file, pages, max_file_bytes) - if source is None: - skipped_binary += 1 + workspace = self._files.display_workspace + with tree.search_bytes_reader() as read_bytes: + for file_path in self._iter_files(tree, budget): + rel_path = file_path.relative_to(root).as_posix() + if glob and not _match_glob(rel_path, file_path.name, glob): continue - source_iterator = source.lines - if source.continuation: - document_continuations.append( - f"({display_path}: continue PDF search with {source.continuation})" - ) - source_lines = checked_lines(source_iterator) + if not _matches_type(file_path.name, type): + continue + display_path = rel_path + if workspace is not None and workspace != root: + with suppress(ValueError): + display_path = file_path.relative_to(workspace).as_posix() - file_had_match = False - if output_mode == "content": - content_page.scan(display_path, source_lines, regex, context_before, context_after) - else: - for line in source_lines: - if not line.searchable or regex.search(line.text) is None: + source_iterator: Iterator[LocatedDocumentLine] | None = None + is_document = file_path.suffix.lower() in _DOCUMENT_EXTENSIONS + try: + if is_document: + try: + file = tree.read_file(file_path) + except OSError: + skipped_binary += 1 continue - file_had_match = True - if output_mode == "count": - counts[display_path] = counts.get(display_path, 0) + 1 + if file.size > max_file_bytes: + skipped_large += 1 continue - break - except (_SearchCancelledError, _SearchBudgetExceededError, MatchTooLargeError): - raise - except Exception as e: - if not is_document: - raise - if not tree.is_directory: - if isinstance(e, PdfPageRangeError): - return ToolResult.error( - f"Error: Invalid PDF page range '{pages}': {e!s}." + mtime = file.modified + source = file.document_lines(pages=pages) + else: + contents = read_bytes(file_path, max_file_bytes) + if contents is None: + skipped_binary += 1 + continue + if contents.data is None: + skipped_large += 1 + continue + mtime = contents.modified + source = self._text_source(contents.data, max_file_bytes) + if source is None: + skipped_binary += 1 + continue + source_iterator = source.lines + if source.continuation: + document_continuations.append( + f"({display_path}: continue PDF search with {source.continuation})" ) - return ToolResult.error( - f"Error searching document {display_path}: {e!s}" - ) - skipped_binary += 1 - document_errors.append(f"{display_path}: {e!s}") - continue - finally: - close = getattr(source_iterator, "close", None) - if close is not None: - close() - if file_had_match: - file_mtimes[display_path] = file.modified - if content_page.stopped: - break + source_lines = checked_lines(source_iterator) + + file_had_match = False + if output_mode == "content": + content_page.scan(display_path, source_lines, regex, context_before, context_after) + else: + for line in source_lines: + if not line.searchable or regex.search(line.text) is None: + continue + file_had_match = True + if output_mode == "count": + counts[display_path] = counts.get(display_path, 0) + 1 + continue + break + except (_SearchCancelledError, _SearchBudgetExceededError, MatchTooLargeError): + raise + except Exception as e: + if not is_document: + raise + if not tree.is_directory: + if isinstance(e, PdfPageRangeError): + return ToolResult.error( + f"Error: Invalid PDF page range '{pages}': {e!s}." + ) + return ToolResult.error( + f"Error searching document {display_path}: {e!s}" + ) + skipped_binary += 1 + document_errors.append(f"{display_path}: {e!s}") + continue + finally: + close = getattr(source_iterator, "close", None) + if close is not None: + close() + if file_had_match: + file_mtimes[display_path] = mtime + if content_page.stopped: + break no_matches = f"No matches found for pattern '{pattern}' in {path}" notes: list[str] = [] diff --git a/nanobot/execution/files.py b/nanobot/execution/files.py index c22deb191..6f21f48b1 100644 --- a/nanobot/execution/files.py +++ b/nanobot/execution/files.py @@ -6,7 +6,7 @@ import os import re import stat from collections.abc import Callable, Generator, Iterable -from contextlib import AbstractContextManager, contextmanager +from contextlib import AbstractContextManager, ExitStack, contextmanager from dataclasses import dataclass from pathlib import Path from typing import TYPE_CHECKING, BinaryIO @@ -24,16 +24,18 @@ class NotRegularFileError(OSError): @contextmanager -def _open_regular_file(resolved_path: Path) -> Generator[tuple[BinaryIO, int]]: +def _open_regular_file( + resolved_path: Path | str, *, dir_fd: int | None = None, +) -> Generator[tuple[BinaryIO, int]]: """Own one descriptor for the entire read and report its initial size. - Callers must resolve the path under the current access policy first. + Callers must supply an authorized path or a child of an authorized directory handle. Where supported, refuse a swapped-in final symlink and avoid waiting on a swapped-in FIFO. This does not protect ancestor path components. """ flags = os.O_RDONLY | getattr(os, "O_BINARY", 0) flags |= getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_NOFOLLOW", 0) - with os.fdopen(os.open(resolved_path, flags), "rb") as stream: + with os.fdopen(os.open(resolved_path, flags, dir_fd=dir_fd), "rb") as stream: opened = os.fstat(stream.fileno()) if not stat.S_ISREG(opened.st_mode): raise NotRegularFileError @@ -183,6 +185,24 @@ class SearchEntry: is_directory_link: bool +@dataclass(frozen=True, slots=True) +class SearchBytes: + """A bounded read; no data means the regular file exceeds the size limit.""" + + data: bytes | None + modified: float + + +def _supports_directory_handles() -> bool: + return ( + os.open in os.supports_dir_fd + and os.stat in os.supports_dir_fd + and os.stat in os.supports_follow_symlinks + and hasattr(os, "O_DIRECTORY") + and hasattr(os, "O_NOFOLLOW") + ) + + @dataclass(frozen=True, slots=True) class FileSearch: """An authorized search root; links are not recursive directories.""" @@ -223,13 +243,16 @@ class FileSearch: @contextmanager def _open_search_directory(self, directory: Path) -> Generator[int]: + relative = directory.relative_to(self.root) + if ".." in relative.parts: + raise ValueError("Expected a directory within the search root") flags = os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW root_info = self.root.stat(follow_symlinks=False) fd = os.open(self.root, flags) try: if not os.path.samestat(root_info, os.fstat(fd)): raise PermissionError("Search root changed") - for part in directory.relative_to(self.root).parts: + for part in relative.parts: child = os.open(part, flags, dir_fd=fd) os.close(fd) fd = child @@ -237,6 +260,13 @@ class FileSearch: finally: os.close(fd) + @staticmethod + def _directory_is_current(directory: Path, fd: int) -> bool: + return ( + Path(os.path.realpath(directory, strict=True)) == directory + and os.path.samestat(os.fstat(fd), directory.stat(follow_symlinks=False)) + ) + def modified_children( self, directory: Path, names: list[str], *, checkpoint: Callable[[], None], ) -> list[float]: @@ -247,14 +277,7 @@ class FileSearch: raise ValueError("Expected direct child names") # A small match set does not amortize opening and rechecking the directory. - if ( - len(names) >= 4 - and os.open in os.supports_dir_fd - and os.stat in os.supports_dir_fd - and os.stat in os.supports_follow_symlinks - and hasattr(os, "O_DIRECTORY") - and hasattr(os, "O_NOFOLLOW") - ): + if len(names) >= 4 and _supports_directory_handles(): try: with self._open_search_directory(directory) as fd: times: list[float] = [] @@ -271,10 +294,7 @@ class FileSearch: ) # An open directory survives a rename. Do not use its batch if # the authorized path no longer points to that directory. - if ( - Path(os.path.realpath(directory, strict=True)) == directory - and os.path.samestat(os.fstat(fd), directory.stat(follow_symlinks=False)) - ): + if self._directory_is_current(directory, fd): return times except OSError: pass # Reauthorize each child if the directory could not be pinned. @@ -288,6 +308,76 @@ class FileSearch: def read_file(self, path: Path) -> ReadableFile: return _regular_file(self._candidate(path), suffix=path.suffix.lower()) + def _read_search_bytes(self, path: Path, limit: int, fd: int | None = None) -> SearchBytes | None: + if fd is None: + try: + file = self.read_file(path) + except OSError: + return None + size, modified = file.size, file.modified + opened_path = file.path + else: + try: + info = os.stat(path.name, dir_fd=fd, follow_symlinks=False) + except OSError: + return None + if stat.S_ISLNK(info.st_mode): + return self._read_search_bytes(path, limit) + if not stat.S_ISREG(info.st_mode): + return None + size, modified = info.st_size, info.st_mtime + opened_path = path.name + if size > limit: + return SearchBytes(None, modified) + with _open_regular_file(opened_path, dir_fd=fd) as (stream, opened_size): + if opened_size > limit: + return None + return SearchBytes(stream.read(limit + 1), modified) + + @contextmanager + def search_bytes_reader(self) -> Generator[Callable[[Path, int], SearchBytes | None]]: + """Read consecutive files using one pinned parent; no handle leaves execution.""" + if not self.is_directory or not _supports_directory_handles(): + yield self._read_search_bytes + return + + parent: Path | None = None + fd: int | None = None + attempted = False + with ExitStack() as handle: + def check_parent() -> None: + if parent is not None and fd is not None: + try: + if self._directory_is_current(parent, fd): + return + except OSError: + pass + raise PermissionError("Search directory changed during the scan; retry the search.") + + def read(path: Path, limit: int) -> SearchBytes | None: + nonlocal parent, fd, attempted + if path.parent != parent: + check_parent() + handle.close() + parent, fd, attempted = path.parent, None, False + return self._read_search_bytes(path, limit) + if not attempted: + attempted = True + # Only open directories with multiple candidates. If the host + # cannot pin this path, keep using per-file authorization. + if parent is not None and parent.is_relative_to(self.root): + try: + _reject_device(parent, resolved=True) + fd = handle.enter_context(self._open_search_directory(parent)) + except (OSError, ValueError): + pass + if path.name in ("", ".", ".."): + return self._read_search_bytes(path, limit) + return self._read_search_bytes(path, limit, fd) + + yield read + check_parent() + def _regular_file(target: Path, *, suffix: str | None = None) -> ReadableFile: _reject_device(target, resolved=True) diff --git a/tests/tools/test_search_tools.py b/tests/tools/test_search_tools.py index 728161950..f57be0b9b 100644 --- a/tests/tools/test_search_tools.py +++ b/tests/tools/test_search_tools.py @@ -295,7 +295,7 @@ async def test_find_files_scan_keeps_event_loop_responsive( async def test_grep_authorizes_the_targets_of_links_found_during_traversal(tmp_path: Path): workspace = tmp_path / "workspace" workspace.mkdir() - inside = workspace / "inside.txt" + inside = workspace / "a.txt" inside.write_text("needle allowed", encoding="utf-8") outside = tmp_path / "outside.txt" outside.write_text("needle outside contents", encoding="utf-8") @@ -312,6 +312,36 @@ async def test_grep_authorizes_the_targets_of_links_found_during_traversal(tmp_p assert "needle outside contents" not in result +@pytest.mark.skipif(os.open not in os.supports_dir_fd, reason="requires native directory handles") +async def test_grep_discards_partial_results_when_a_pinned_directory_moves( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, +) -> None: + workspace = (tmp_path / "workspace").resolve() + directory = workspace / "src" + directory.mkdir(parents=True) + for name in ("a.txt", "b.txt", "c.txt"): + (directory / name).write_text("needle inside\n", encoding="utf-8") + outside = tmp_path / "outside" + outside.mkdir() + (outside / "b.txt").write_text("needle outside\n", encoding="utf-8") + original = FileSearch._open_search_directory + + @contextmanager + def replace_after_open(tree, path): + with original(tree, path) as fd: + if path == directory: + directory.rename(tmp_path / "moved") + directory.symlink_to(outside, target_is_directory=True) + yield fd + + monkeypatch.setattr(FileSearch, "_open_search_directory", replace_after_open) + tool = GrepTool(workspace=workspace, allowed_dir=workspace) + # The first result is already buffered when the second file pins the parent. + # Even a page that stops early must not return the old directory's results. + result = await tool.execute(pattern="needle", head_limit=1) + assert result == "Error: Search directory changed during the scan; retry the search." + + async def test_exact_read_grant_does_not_authorize_a_directory_tree(tmp_path: Path): workspace = tmp_path / "workspace" workspace.mkdir()