fix(tools): preserve authorized document link search

This commit is contained in:
Xubin Ren committed 2026-11-14 22:09:21 +08:00
1 parent d2e03d23a0
commit 66b8c447dc
5 files changed
+53 -19

No files matched your search

+2 -2
View File
@@ -634,7 +634,7 @@ class GrepTool(_SearchTool):
@staticmethod @staticmethod
def _open_source(source: ReadableFile, pages: str | None, max_bytes: int) -> DocumentLineSource | None: def _open_source(source: ReadableFile, pages: str | None, max_bytes: int) -> DocumentLineSource | None:
if source.path.suffix.lower() in _DOCUMENT_EXTENSIONS: if source.suffix in _DOCUMENT_EXTENSIONS:
return source.document_lines(pages=pages) return source.document_lines(pages=pages)
with source.open() as (file, size): with source.open() as (file, size):
if size > max_bytes: if size > max_bytes:
@@ -770,7 +770,7 @@ class GrepTool(_SearchTool):
skipped_large += 1 skipped_large += 1
continue continue
source_iterator: Iterator[LocatedDocumentLine] | None = None source_iterator: Iterator[LocatedDocumentLine] | None = None
is_document = file.path.suffix.lower() in _DOCUMENT_EXTENSIONS is_document = file.suffix in _DOCUMENT_EXTENSIONS
try: try:
source = self._open_source(file, pages, max_file_bytes) source = self._open_source(file, pages, max_file_bytes)
if source is None: if source is None:
+10 -12
View File
@@ -73,6 +73,7 @@ class ReadableFile:
path: Path path: Path
size: int size: int
modified: float modified: float
suffix: str
def open(self) -> AbstractContextManager[tuple[BinaryIO, int]]: def open(self) -> AbstractContextManager[tuple[BinaryIO, int]]:
return _open_regular_file(self.path) return _open_regular_file(self.path)
@@ -89,7 +90,7 @@ class ReadableFile:
def document_lines(self, *, pages: str | None = None) -> DocumentLineSource | None: def document_lines(self, *, pages: str | None = None) -> DocumentLineSource | None:
from nanobot.utils.document import open_document_line_source from nanobot.utils.document import open_document_line_source
return open_document_line_source(self.path, pages=pages) return open_document_line_source(self.path, pages=pages, suffix=self.suffix)
@dataclass(frozen=True, slots=True) @dataclass(frozen=True, slots=True)
@@ -218,15 +219,15 @@ class FileSearch:
return self._candidate(path).stat().st_mtime return self._candidate(path).stat().st_mtime
def read_file(self, path: Path) -> ReadableFile: def read_file(self, path: Path) -> ReadableFile:
return _regular_file(self._candidate(path)) return _regular_file(self._candidate(path), suffix=path.suffix.lower())
def _regular_file(target: Path) -> ReadableFile: def _regular_file(target: Path, *, suffix: str | None = None) -> ReadableFile:
_reject_device(target, resolved=True) _reject_device(target, resolved=True)
info = target.stat() info = target.stat()
if not stat.S_ISREG(info.st_mode): if not stat.S_ISREG(info.st_mode):
raise NotRegularFileError raise NotRegularFileError
return ReadableFile(target, info.st_size, info.st_mtime) return ReadableFile(target, info.st_size, info.st_mtime, target.suffix.lower() if suffix is None else suffix)
class WorkspaceFiles: class WorkspaceFiles:
@@ -305,7 +306,7 @@ class WorkspaceFiles:
) )
return access.project_path, self._allowed_root(access.allowed_root) return access.project_path, self._allowed_root(access.allowed_root)
def _read_path(self, path: str | Path, *, directory: bool = False) -> Path: def _read_path(self, path: str | Path) -> Path:
workspace, root = self._roots() workspace, root = self._roots()
extra_roots: list[Path] = [] extra_roots: list[Path] = []
if root is not None: if root is not None:
@@ -320,7 +321,7 @@ class WorkspaceFiles:
workspace=workspace, workspace=workspace,
allowed_root=root, allowed_root=root,
extra_allowed_roots=extra_roots, extra_allowed_roots=extra_roots,
extra_allowed_files=self._read_files if root is not None and not directory else (), extra_allowed_files=self._read_files if root is not None else (),
) )
def edit_target(self, path: str) -> WritableFile: def edit_target(self, path: str) -> WritableFile:
@@ -352,7 +353,7 @@ class WorkspaceFiles:
def list_directory( def list_directory(
self, path: str, *, recursive: bool, ignored: set[str], limit: int, self, path: str, *, recursive: bool, ignored: set[str], limit: int,
) -> DirectoryListing: ) -> DirectoryListing:
directory = self._read_path(path, directory=True) directory = self._read_path(path)
if not directory.exists(): if not directory.exists():
raise FileNotFoundError(path) raise FileNotFoundError(path)
if not directory.is_dir(): if not directory.is_dir():
@@ -379,7 +380,7 @@ class WorkspaceFiles:
def sibling_files(self, target: WritableFile) -> list[str]: def sibling_files(self, target: WritableFile) -> list[str]:
"""Suggest names only when the caller can read the directory itself.""" """Suggest names only when the caller can read the directory itself."""
try: try:
parent = self._read_path(target.path.parent, directory=True) parent = self._read_path(target.path.parent)
except PermissionError: except PermissionError:
return [] return []
return [item.name for item in parent.iterdir() if item.is_file()] if parent.is_dir() else [] return [item.name for item in parent.iterdir() if item.is_file()] if parent.is_dir() else []
@@ -389,7 +390,4 @@ class WorkspaceFiles:
mode = target.stat().st_mode mode = target.stat().st_mode
if not (stat.S_ISDIR(mode) or stat.S_ISREG(mode)): if not (stat.S_ISDIR(mode) or stat.S_ISREG(mode)):
raise NotRegularFileError raise NotRegularFileError
is_directory = stat.S_ISDIR(mode) return FileSearch(target, stat.S_ISDIR(mode), self._read_path)
if is_directory:
target = self._read_path(path, directory=True)
return FileSearch(target, is_directory, self._read_path)
+3 -1
View File
@@ -70,7 +70,9 @@ def _is_path_exactly_allowed(
except (OSError, RuntimeError, TypeError, ValueError): except (OSError, RuntimeError, TypeError, ValueError):
continue continue
if _path_key(allowed_file) == logical_key: if _path_key(allowed_file) == logical_key:
return True # A missing file can be created, but an exact file grant cannot
# become a directory grant if the path now refers to a directory.
return not resolved_path.is_dir()
return False return False
+7 -4
View File
@@ -136,6 +136,7 @@ def open_document_line_source(
path: str | Path, path: str | Path,
*, *,
pages: str | None = None, pages: str | None = None,
suffix: str | None = None,
) -> DocumentLineSource | None: ) -> DocumentLineSource | None:
"""Open a document as an incremental stream of extracted lines. """Open a document as an incremental stream of extracted lines.
@@ -145,8 +146,9 @@ def open_document_line_source(
blank separators) have ``searchable=False`` so range reads can retain them blank separators) have ``searchable=False`` so range reads can retain them
without making grep match synthetic text. without making grep match synthetic text.
""" """
# Format can come from a displayed name; all I/O uses the supplied path.
path = Path(path) path = Path(path)
ext = path.suffix.lower() ext = (path.suffix if suffix is None else suffix).lower()
if ext not in {".pdf", ".docx", ".xlsx", ".pptx"}: if ext not in {".pdf", ".docx", ".xlsx", ".pptx"}:
return None return None
if error := _extraction_path_error(path): if error := _extraction_path_error(path):
@@ -241,12 +243,13 @@ def _open_xlsx_line_source(path: Path) -> DocumentLineSource:
from openpyxl import load_workbook from openpyxl import load_workbook
except ImportError as e: except ImportError as e:
raise DocumentExtractionError("openpyxl not installed") from e raise DocumentExtractionError("openpyxl not installed") from e
def iter_lines() -> Iterator[LocatedDocumentLine]:
# Let openpyxl parse the authorized file even if its real name has no suffix.
with path.open("rb") as source:
try: try:
workbook = load_workbook(path, read_only=True, data_only=True) workbook = load_workbook(source, read_only=True, data_only=True)
except Exception as e: except Exception as e:
raise DocumentExtractionError(f"failed to open XLSX: {e!s}") from e raise DocumentExtractionError(f"failed to open XLSX: {e!s}") from e
def iter_lines() -> Iterator[LocatedDocumentLine]:
extracted_line = 0 extracted_line = 0
wrote_document_content = False wrote_document_content = False
try: try:
+31
View File
@@ -484,6 +484,37 @@ async def test_grep_searches_pdf_with_page_locator(tmp_path: Path) -> None:
assert "pdf needle" in result assert "pdf needle" in result
@pytest.mark.parametrize(("suffix", "locator"), [
(".pdf", "[page=1,line=1]"),
(".xlsx", "[sheet='Sheet',row=1,cell=A1]"),
])
async def test_grep_uses_document_link_name_for_format(tmp_path: Path, suffix: str, locator: str) -> None:
target = tmp_path / "stored-content"
link = tmp_path / f"manual{suffix}"
if suffix == ".pdf":
import fitz
with fitz.open() as document:
document.new_page().insert_text((72, 72), "document needle")
document.save(target)
else:
from openpyxl import Workbook
workbook = Workbook()
workbook["Sheet"]["A1"] = "document needle"
workbook.save(target)
workbook.close()
try:
link.symlink_to(target)
except (NotImplementedError, OSError):
pytest.skip("symlinks unavailable")
tool = GrepTool(workspace=tmp_path, allowed_dir=tmp_path)
result = await tool.execute(pattern="document needle", path=".", glob=f"*{suffix}", fixed_strings=True)
assert f"{link.name}:2 {locator}" in result
assert "document needle" in result
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_grep_searches_xlsx_beyond_attachment_preview_limit( async def test_grep_searches_xlsx_beyond_attachment_preview_limit(
tmp_path: Path, tmp_path: Path,