refactor(tools): route file operations through scoped execution

This commit is contained in:
Xubin Ren committed 2026-11-14 22:09:21 +08:00
1 parent c539da9269
commit d2e03d23a0
16 files changed
+721 -513

No files matched your search

+15 -29
View File
@@ -1,10 +1,9 @@
from __future__ import annotations
from pathlib import Path
from typing import Any, cast
from nanobot.agent.tools.base import ToolResult, tool_parameters
from nanobot.agent.tools.filesystem import _FsTool # pyright: ignore[reportPrivateUsage]
from nanobot.agent.tools.filesystem import _WritableFsTool # pyright: ignore[reportPrivateUsage]
from nanobot.agent.tools.schema import (
ArraySchema,
BooleanSchema,
@@ -12,6 +11,7 @@ from nanobot.agent.tools.schema import (
StringSchema,
tool_parameters_schema,
)
from nanobot.execution.files import WritableFile, commit_file_edits
from nanobot.utils.file_edit_events import FileDiff, FileEditResult, display_file_edit_path
@@ -72,7 +72,7 @@ def _append_text(content: str, addition: str) -> str:
required=["edits"],
)
)
class ApplyPatchTool(_FsTool):
class ApplyPatchTool(_WritableFsTool):
"""Apply file edits by providing structured edit instructions."""
_scopes = {"core", "subagent"}
@@ -98,9 +98,9 @@ class ApplyPatchTool(_FsTool):
if not edits:
raise _PatchError("must provide edits")
writes: dict[Path, str] = {}
originals: dict[Path, str] = {}
actions: dict[Path, str] = {}
writes: dict[WritableFile, str] = {}
originals: dict[WritableFile, str] = {}
actions: dict[WritableFile, str] = {}
for edit_value in edits:
if not isinstance(edit_value, dict):
@@ -113,7 +113,7 @@ class ApplyPatchTool(_FsTool):
action = edit.get("action")
if not isinstance(action, str):
raise _PatchError(f"action required for edit: {path}")
source = self._resolve_write(path)
source = self.file_edit_target(path)
if action == "add":
new_text = edit.get("new_text")
@@ -211,7 +211,7 @@ class ApplyPatchTool(_FsTool):
summaries: list[str] = []
for source, diff in diffs.items():
action_name = actions[source]
path = display_file_edit_path(source, self._display_workspace())
path = display_file_edit_path(source.path, self._files.display_workspace)
added, deleted = diff.added, diff.deleted
stats = f" (+{added}/-{deleted})" if added or deleted else ""
summaries.append(f"- {action_name} {path}{stats}")
@@ -219,27 +219,13 @@ class ApplyPatchTool(_FsTool):
if dry_run:
return "Patch dry-run succeeded:\n" + "\n".join(summaries)
backups: dict[Path, bytes | None] = {}
for path in writes:
backups[path] = path.read_bytes() if path.exists() else None
try:
for path, content in writes.items():
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content, encoding="utf-8", newline="")
except Exception:
for path, data in backups.items():
if data is None:
if path.exists():
path.unlink()
else:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
raise
for path in writes:
self._file_states.record_write(path)
return FileEditResult("Patch applied:\n" + "\n".join(summaries), diffs)
commit_file_edits(writes)
for target in writes:
self._file_states.record_write(target.path)
return FileEditResult(
"Patch applied:\n" + "\n".join(summaries),
{target.path: diff for target, diff in diffs.items()},
)
except PermissionError as exc:
return ToolResult.error(f"Error: {exc}")
except _PatchError as exc:
+93 -248
View File
@@ -4,31 +4,35 @@ import codecs
import difflib
import hashlib
import mimetypes
import os
from copy import deepcopy
from dataclasses import dataclass
from pathlib import Path
from typing import Any, BinaryIO
from nanobot.agent.skill_metadata import BUILTIN_SKILLS_DIR
from nanobot.agent.tools.base import Tool, ToolResult, tool_parameters
from nanobot.agent.tools.context import ToolContext
from nanobot.agent.tools.file_state import FileStates, current_file_states
from nanobot.agent.tools.filesystem_config import FileToolsConfig
from nanobot.agent.tools.path_utils import resolve_workspace_path
from nanobot.agent.tools.schema import (
BooleanSchema,
IntegerSchema,
StringSchema,
tool_parameters_schema,
)
from nanobot.execution.files import NotRegularFileError, open_regular_file
from nanobot.security.workspace_access import current_tool_workspace
from nanobot.execution.files import NotRegularFileError, ReadableFile, WorkspaceFiles, WritableFile
from nanobot.utils.file_edit_events import FileDiff, FileEditResult, display_file_edit_path
from nanobot.utils.helpers import build_image_content_blocks, detect_image_mime
def _plugin_skill_roots(workspace: Path, target: Path) -> tuple[Path, ...]:
from nanobot.agent.plugins import enabled_agent_plugin_skill_dirs
return enabled_agent_plugin_skill_dirs(workspace, requested_path=target)
class _FsTool(Tool):
"""Shared base for filesystem tools — common init and path resolution."""
"""Wire file tools to workspace execution and call-local read receipts."""
config_key = "file"
@@ -52,52 +56,37 @@ class _FsTool(Tool):
restrict_to_workspace: bool | None = None,
sandbox_restricts_workspace: bool = False,
extra_read_allowed_files: list[Path] | None = None,
*,
files: WorkspaceFiles | None = None,
):
self._workspace = workspace
self._allowed_dir = allowed_dir
# Legacy alias: extra_allowed_dirs is read-only. Write-capable tools
# must opt in via extra_write_allowed_dirs.
self._extra_read_allowed_dirs = [
*(extra_allowed_dirs or []),
*(extra_read_allowed_dirs or []),
]
self._extra_read_allowed_files = list(extra_read_allowed_files or [])
self._extra_write_allowed_dirs = list(extra_write_allowed_dirs or [])
self._extra_write_allowed_files = list(extra_write_allowed_files or [])
self._restrict_to_workspace = (
bool(restrict_to_workspace)
if restrict_to_workspace is not None
else allowed_dir is not None
self._files = files if files is not None else WorkspaceFiles(
workspace=workspace,
allowed_dir=allowed_dir,
extra_allowed_dirs=extra_allowed_dirs,
extra_read_allowed_dirs=extra_read_allowed_dirs,
extra_write_allowed_dirs=extra_write_allowed_dirs,
extra_write_allowed_files=extra_write_allowed_files,
restrict_to_workspace=restrict_to_workspace,
sandbox_restricts_workspace=sandbox_restricts_workspace,
extra_read_allowed_files=extra_read_allowed_files,
builtin_skills=BUILTIN_SKILLS_DIR,
plugin_skill_roots=_plugin_skill_roots,
)
self._sandbox_restricts_workspace = sandbox_restricts_workspace
# Explicit state is used by isolated runners like Dream/subagents.
# Main AgentLoop tools leave this unset and resolve state from the
# current async task, which keeps shared tool instances session-safe.
# Dream and isolated runners can supply their own receipt store.
self._explicit_file_states = file_states
self._fallback_file_states = FileStates()
@classmethod
def create(cls, ctx: ToolContext) -> Tool:
from nanobot.agent.skill_metadata import BUILTIN_SKILLS_DIR
agent_workspace = Path(ctx.workspace)
resolved_agent_workspace = agent_workspace.expanduser().resolve(strict=False)
restrict = (
ctx.config.restrict_to_workspace
or ctx.config.exec.sandbox
)
sandbox_restricts = bool(ctx.config.exec.sandbox)
allowed_dir = agent_workspace if restrict else None
# Agent-owned skills stay available from project scopes. History is a narrower
# capability: expose only the append-only log, not the surrounding memory directory.
return cls(
workspace=agent_workspace,
allowed_dir=allowed_dir,
extra_read_allowed_dirs=[BUILTIN_SKILLS_DIR, resolved_agent_workspace / "skills"],
extra_read_allowed_files=[resolved_agent_workspace / "memory" / "history.jsonl"],
files=WorkspaceFiles.for_agent(
Path(ctx.workspace),
restrict_to_workspace=ctx.config.restrict_to_workspace,
sandbox_restricts_workspace=bool(ctx.config.exec.sandbox),
builtin_skills=BUILTIN_SKILLS_DIR,
plugin_skill_roots=_plugin_skill_roots,
),
file_states=ctx.file_state_store,
restrict_to_workspace=ctx.config.restrict_to_workspace,
sandbox_restricts_workspace=sandbox_restricts,
)
@property
@@ -106,134 +95,16 @@ class _FsTool(Tool):
return self._explicit_file_states
return current_file_states(self._fallback_file_states)
def _effective_allowed_root(self, access_allowed_root: Path | None) -> Path | None:
if self._allowed_dir is None or self._workspace is None:
return access_allowed_root
try:
allowed_dir = Path(self._allowed_dir).expanduser().resolve(strict=False)
workspace = Path(self._workspace).expanduser().resolve(strict=False)
except (OSError, RuntimeError, TypeError, ValueError):
return access_allowed_root if access_allowed_root is not None else self._allowed_dir
if allowed_dir == workspace:
return access_allowed_root
return allowed_dir
def _resolve_with_extra(
self,
path: str,
extra_allowed_dirs: list[Path] | None,
extra_allowed_files: list[Path] | None,
*,
include_media_dir: bool,
extra_files_require_allowed_root: bool = False,
) -> Path:
access = current_tool_workspace(
self._workspace,
restrict_to_workspace=self._restrict_to_workspace,
sandbox_restricts_workspace=self._sandbox_restricts_workspace,
)
allowed_root = self._effective_allowed_root(access.allowed_root)
if extra_files_require_allowed_root and allowed_root is None:
extra_allowed_files = None
return resolve_workspace_path(
path,
access.project_path,
allowed_root,
extra_allowed_dirs,
extra_allowed_files,
include_media_dir=include_media_dir,
)
class _WritableFsTool(_FsTool):
"""Expose the same write target to execution and edit activity tracking."""
def _resolve_read(self, path: str) -> Path:
plugin_skill_dirs: list[Path] = []
if self._workspace is not None:
from nanobot.agent.plugins import enabled_agent_plugin_skill_dirs
def file_edit_target(self, path: str) -> WritableFile:
return self._files.edit_target(path)
try:
access = current_tool_workspace(
self._workspace,
restrict_to_workspace=self._restrict_to_workspace,
sandbox_restricts_workspace=self._sandbox_restricts_workspace,
)
if self._effective_allowed_root(access.allowed_root) is not None:
candidate = Path(path).expanduser()
if not candidate.is_absolute() and access.project_path is not None:
candidate = access.project_path / candidate
plugin_skill_dirs = list(
enabled_agent_plugin_skill_dirs(
Path(self._workspace),
requested_path=candidate.resolve(strict=False),
)
)
except (OSError, RuntimeError):
pass
return self._resolve_with_extra(
path,
[*self._extra_read_allowed_dirs, *plugin_skill_dirs],
self._extra_read_allowed_files,
include_media_dir=True,
extra_files_require_allowed_root=True,
)
def _resolve_write(self, path: str) -> Path:
return self._resolve_with_extra(
path,
self._extra_write_allowed_dirs,
self._extra_write_allowed_files,
include_media_dir=False,
)
def _resolve(self, path: str) -> Path:
return self._resolve_read(path)
def _display_workspace(self) -> Path | None:
return current_tool_workspace(self._workspace).project_path
_BLOCKED_DEVICE_PATHS = frozenset({
"/dev/zero", "/dev/random", "/dev/urandom", "/dev/full",
"/dev/stdin", "/dev/stdout", "/dev/stderr",
"/dev/tty", "/dev/console",
"/dev/fd/0", "/dev/fd/1", "/dev/fd/2",
})
def _is_blocked_device(path: str | Path) -> bool:
"""Check if path is a blocked device that could hang or produce infinite output."""
import re
raw = str(path)
try:
resolved = str(Path(raw).resolve())
except (OSError, ValueError):
resolved = raw
if raw in _BLOCKED_DEVICE_PATHS or resolved in _BLOCKED_DEVICE_PATHS:
return True
if re.match(r"/proc/\d+/fd/[012]$", raw) or re.match(r"/proc/self/fd/[012]$", raw):
return True
if re.match(r"/proc/\d+/fd/[012]$", resolved) or re.match(r"/proc/self/fd/[012]$", resolved):
return True
if resolved.startswith("/dev/"):
return True
return False
def _builtin_skill_read_path(path: str) -> Path | None:
from nanobot.agent.skill_metadata import BUILTIN_SKILLS_DIR
requested = Path(path)
if requested.is_absolute():
return None
parts = requested.parts
if len(parts) < 2 or parts[0] != "skills":
return None
root = BUILTIN_SKILLS_DIR.resolve()
candidate = (root / Path(*parts[1:])).resolve()
if candidate != root and root not in candidate.parents:
return None
return candidate if candidate.is_file() else None
@property
def file_edit_workspace(self) -> Path | None:
return self._files.display_workspace
_LINE_BREAKS = frozenset("\n\r\v\f\x1c\x1d\x1e\x85\u2028\u2029")
@@ -402,30 +273,21 @@ class ReadFileTool(_FsTool):
if not path:
return ToolResult.error("Error reading file: Unknown path")
if _is_blocked_device(path):
return ToolResult.error(f"Error: Reading {path} is blocked (device path that could hang or produce infinite output).")
fp = self._resolve_read(path)
if not fp.exists():
fp = _builtin_skill_read_path(path) or fp
if _is_blocked_device(fp):
return ToolResult.error(f"Error: Reading {fp} is blocked (device path that could hang or produce infinite output).")
if not fp.exists():
try:
source = self._files.read_file(path)
except FileNotFoundError:
return ToolResult.error(f"Error: File not found: {path}")
if not fp.is_file():
return ToolResult.error(f"Error: Not a file: {path}")
file_size = fp.stat().st_size
if file_size > self._MAX_FILE_SIZE_BYTES:
return self._file_too_large(file_size)
fp = source.path
if source.size > self._MAX_FILE_SIZE_BYTES:
return self._file_too_large(source.size)
if fp.suffix.lower() == ".pdf":
return self._read_pdf(fp, pages)
return self._read_pdf(source, pages)
if fp.suffix.lower() in {".docx", ".xlsx", ".pptx"}:
return self._read_office_doc(fp, offset, limit)
return self._read_office_doc(source, offset, limit)
with open_regular_file(fp) as (stream, opened_size):
with source.open() as (stream, opened_size):
if opened_size > self._MAX_FILE_SIZE_BYTES:
return self._file_too_large(opened_size)
@@ -443,7 +305,7 @@ class ReadFileTool(_FsTool):
bytes_read = len(first)
# Bound each read without preallocating from a size that
# may have become stale during the receipt check.
remaining = os.fstat(stream.fileno()).st_size - bytes_read
remaining = source.open_size(stream) - bytes_read
chunk_size = min(self._IMAGE_READ_CHUNK_SIZE, max(self._READ_CHUNK_SIZE, remaining))
while chunk := stream.read(min(
chunk_size, self._MAX_FILE_SIZE_BYTES + 1 - bytes_read,
@@ -592,13 +454,12 @@ class ReadFileTool(_FsTool):
)
return result
def _read_pdf(self, fp: Path, pages: str | None) -> str:
from nanobot.utils.document import PdfPageRangeError, PdfSafetyError, extract_pdf_pages
def _read_pdf(self, source: ReadableFile, pages: str | None) -> str:
from nanobot.utils.document import PdfPageRangeError, PdfSafetyError
try:
extraction = extract_pdf_pages(
fp,
pages=pages,
extraction = source.pdf_pages(
pages,
max_pages=self._MAX_PDF_PAGES,
max_chars=self._MAX_CHARS,
)
@@ -610,7 +471,7 @@ class ReadFileTool(_FsTool):
return ToolResult.error(f"Error reading PDF: {e}")
if not extraction.text:
return f"(PDF has no extractable text: {fp})"
return f"(PDF has no extractable text: {source.path})"
result = extraction.text
if extraction.truncated:
@@ -629,17 +490,16 @@ class ReadFileTool(_FsTool):
def _read_office_doc(
self,
fp: Path,
file: ReadableFile,
offset: int,
limit: int | None,
) -> str:
from nanobot.utils.document import open_document_line_source
fp = file.path
offset = max(1, offset)
requested_limit = limit or self._DEFAULT_LIMIT
source_iterator = None
try:
source = open_document_line_source(fp)
source = file.document_lines()
if source is None:
return ToolResult.error(f"Error: Unsupported file format: {fp.suffix}")
source_iterator = source.lines
@@ -715,7 +575,7 @@ class ReadFileTool(_FsTool):
required=["path", "content"],
)
)
class WriteFileTool(_FsTool):
class WriteFileTool(_WritableFsTool):
"""Write content to a file."""
_scopes = {"core", "subagent", "memory"}
@@ -737,11 +597,10 @@ class WriteFileTool(_FsTool):
raise ValueError("Unknown path")
if content is None:
raise ValueError("Unknown content")
fp = self._resolve_write(path)
fp.parent.mkdir(parents=True, exist_ok=True)
fp.write_text(content, encoding="utf-8", newline="")
self._file_states.record_write(fp)
return f"Successfully wrote {len(content)} characters to {fp}"
target = self.file_edit_target(path)
target.write(content, create_parents=True)
self._file_states.record_write(target.path)
return f"Successfully wrote {len(content)} characters to {target.path}"
except PermissionError as e:
return ToolResult.error(f"Error: {e}")
except Exception as e:
@@ -1030,7 +889,7 @@ def _best_window(old_text: str, content: str) -> tuple[float, int, list[str], li
required=["path", "old_text", "new_text"],
)
)
class EditFileTool(_FsTool):
class EditFileTool(_WritableFsTool):
"""Edit a file by replacing text with fallback matching."""
_scopes = {"core", "subagent", "memory"}
@@ -1066,7 +925,7 @@ class EditFileTool(_FsTool):
added, deleted = diff.added, diff.deleted
action = "add" if created else "update"
stats = f" (+{added}/-{deleted})" if added or deleted else ""
path = display_file_edit_path(resolved_path, self._display_workspace())
path = display_file_edit_path(resolved_path, self._files.display_workspace)
text = f"Patch applied:\n- {action} {path}{stats}"
return FileEditResult(text, {resolved_path: diff})
@@ -1090,36 +949,36 @@ class EditFileTool(_FsTool):
if expected_replacements is not None and expected_replacements < 1:
return ToolResult.error("Error: expected_replacements must be >= 1.")
fp = self._resolve_write(path)
file_exists = fp.exists()
target = self.file_edit_target(path)
fp = target.path
file_exists = target.exists()
if file_exists and old_text == new_text:
return ToolResult.error("Error: new_text must be different from old_text.")
if not file_exists:
if old_text == "":
fp.parent.mkdir(parents=True, exist_ok=True)
fp.write_text(new_text, encoding="utf-8", newline="")
target.write(new_text, create_parents=True)
self._file_states.record_write(fp)
return self._format_summary(fp, "", fp.read_bytes().decode("utf-8"), created=True)
return self._file_not_found_msg(path, fp)
return self._format_summary(fp, "", new_text, created=True)
return self._file_not_found_msg(path, target)
try:
fsize = fp.stat().st_size
fsize = target.size()
except OSError:
fsize = 0
if fsize > self._MAX_EDIT_FILE_SIZE:
return ToolResult.error(f"Error: File too large to edit ({fsize / (1024**3):.1f} GiB). Maximum is 1 GiB.")
if old_text == "":
raw = fp.read_bytes()
raw = target.read_bytes()
content = raw.decode("utf-8")
if content.strip():
return ToolResult.error(f"Error: Cannot create file — {path} already exists and is not empty.")
fp.write_text(new_text, encoding="utf-8", newline="")
target.write(new_text)
self._file_states.record_write(fp)
return self._format_summary(fp, content, fp.read_bytes().decode("utf-8"))
return self._format_summary(fp, content, new_text)
raw = fp.read_bytes()
raw = target.read_bytes()
uses_crlf = b"\r\n" in raw
content = raw.decode("utf-8").replace("\r\n", "\n")
norm_old = old_text.replace("\r\n", "\n")
@@ -1212,7 +1071,7 @@ class EditFileTool(_FsTool):
if uses_crlf:
new_content = new_content.replace("\n", "\r\n")
fp.write_bytes(new_content.encode("utf-8"))
target.write(new_content)
self._file_states.record_write(fp)
return self._format_summary(fp, content, new_content)
except PermissionError as e:
@@ -1220,13 +1079,10 @@ class EditFileTool(_FsTool):
except Exception as e:
return ToolResult.error(f"Error editing file: {e}")
def _file_not_found_msg(self, path: str, fp: Path) -> str:
parent = fp.parent
suggestions: list[str] = []
if parent.is_dir():
siblings = [f.name for f in parent.iterdir() if f.is_file()]
close = difflib.get_close_matches(fp.name, siblings, n=3, cutoff=0.6)
suggestions = [str(parent / c) for c in close]
def _file_not_found_msg(self, path: str, target: WritableFile) -> str:
siblings = self._files.sibling_files(target)
close = difflib.get_close_matches(target.path.name, siblings, n=3, cutoff=0.6)
suggestions = [str(target.path.parent / name) for name in close]
parts = [f"Error: File not found: {path}"]
if suggestions:
parts.append("Did you mean: " + ", ".join(suggestions) + "?")
@@ -1304,32 +1160,21 @@ class ListDirTool(_FsTool):
try:
if path is None:
raise ValueError("Unknown path")
dp = self._resolve(path)
if not dp.exists():
return ToolResult.error(f"Error: Directory not found: {path}")
if not dp.is_dir():
return ToolResult.error(f"Error: Not a directory: {path}")
cap = max_entries or self._DEFAULT_MAX
items: list[str] = []
total = 0
if recursive:
for item in sorted(dp.rglob("*")):
rel = item.relative_to(dp)
if any(p in self._IGNORE_DIRS for p in rel.parts):
continue
total += 1
if len(items) < cap:
items.append(f"{rel}/" if item.is_dir() else str(rel))
else:
for item in sorted(dp.iterdir()):
if item.name in self._IGNORE_DIRS:
continue
total += 1
if len(items) < cap:
pfx = "📁 " if item.is_dir() else "📄 "
items.append(f"{pfx}{item.name}")
try:
listing = self._files.list_directory(
path, recursive=recursive, ignored=self._IGNORE_DIRS, limit=cap,
)
except FileNotFoundError:
return ToolResult.error(f"Error: Directory not found: {path}")
except NotADirectoryError:
return ToolResult.error(f"Error: Not a directory: {path}")
total = listing.total
items = [
(f"{item}/" if is_dir else str(item)) if recursive
else f"{'📁' if is_dir else '📄'} {item.name}"
for item, is_dir in listing.entries
]
if not items and total == 0:
return f"Directory {path} is empty"
+63 -58
View File
@@ -5,7 +5,6 @@ from __future__ import annotations
import asyncio
import fnmatch
import heapq
import os
import re
import threading
import time
@@ -18,11 +17,11 @@ 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.utils.document import (
DocumentLineSource,
LocatedDocumentLine,
PdfPageRangeError,
open_document_line_source,
)
_DEFAULT_HEAD_LIMIT = 250
@@ -211,24 +210,36 @@ class _SearchTool(_FsTool):
return name in cls._IGNORE_DIRS or name.startswith(".verify-")
def _display_path(self, target: Path, root: Path) -> str:
workspace = self._display_workspace()
workspace = self._files.display_workspace
if workspace:
with suppress(ValueError):
return target.relative_to(workspace).as_posix()
return target.relative_to(root).as_posix()
def _iter_files(self, root: Path, budget: _SearchBudget) -> Iterable[Path]:
if root.is_file():
def _iter_files(self, tree: FileSearch, budget: _SearchBudget) -> Iterable[Path]:
if not tree.is_directory:
budget.visit_path()
yield root
yield tree.root
return
for dirpath, dirnames, filenames in os.walk(root):
pending = [tree.root]
while pending:
budget.checkpoint()
for _ in dirnames:
budget.visit_path()
dirnames[:] = sorted(d for d in dirnames if not self._ignore_directory(d))
current = Path(dirpath)
current = pending.pop()
directories: list[str] = []
filenames: list[str] = []
try:
for entry in tree.entries(current):
budget.checkpoint()
if not entry.is_directory:
filenames.append(entry.name)
else:
budget.visit_path()
if not entry.is_directory_link and not self._ignore_directory(entry.name):
directories.append(entry.name)
except OSError:
continue
pending.extend(current / name for name in sorted(directories, reverse=True))
for filename in sorted(filenames):
budget.visit_path()
yield current / filename
@@ -310,6 +321,7 @@ class FindFilesTool(_SearchTool):
def _push_directory_entries(
self,
tree: FileSearch,
directory: Path,
root: Path,
frontier: list[tuple[str, int, _FindFilesEntry]],
@@ -318,24 +330,15 @@ class FindFilesTool(_SearchTool):
) -> int:
budget.checkpoint()
try:
with os.scandir(directory) as entries:
for raw_entry in entries:
budget.visit_path()
try:
is_dir = raw_entry.is_dir(follow_symlinks=False)
# os.walk yields special files and broken file symlinks,
# but does not descend into directory symlinks by default.
if not is_dir and raw_entry.is_symlink() and raw_entry.is_dir():
continue
except OSError:
continue
if is_dir and self._ignore_directory(raw_entry.name):
continue
entry = self._entry(Path(raw_entry.path), root, is_dir=is_dir)
sort_path = entry.display_path + ("/" if is_dir else "")
heapq.heappush(frontier, (sort_path, sequence, entry))
sequence += 1
for raw_entry in tree.entries(directory):
budget.visit_path()
is_dir = raw_entry.is_directory
if raw_entry.is_directory_link or (is_dir and self._ignore_directory(raw_entry.name)):
continue
entry = self._entry(directory / raw_entry.name, root, is_dir=is_dir)
sort_path = entry.display_path + ("/" if is_dir else "")
heapq.heappush(frontier, (sort_path, sequence, entry))
sequence += 1
except OSError:
# os.walk silently skips directories that cannot be listed. Preserve
# that behavior while still allowing cancellation and budget errors
@@ -345,13 +348,14 @@ class FindFilesTool(_SearchTool):
def _iter_paths(
self,
root: Path,
tree: FileSearch,
*,
include_dirs: bool,
budget: _SearchBudget,
) -> Iterable[_FindFilesEntry]:
budget.checkpoint()
if root.is_file():
root = tree.root
if not tree.is_directory:
budget.visit_path()
yield self._entry(root, root.parent, is_dir=False)
return
@@ -360,7 +364,7 @@ class FindFilesTool(_SearchTool):
yield self._entry(root, root, is_dir=True)
frontier: list[tuple[str, int, _FindFilesEntry]] = []
sequence = self._push_directory_entries(root, root, frontier, 0, budget)
sequence = self._push_directory_entries(tree, root, root, frontier, 0, budget)
while frontier:
budget.checkpoint()
_, _, entry = heapq.heappop(frontier)
@@ -368,6 +372,7 @@ class FindFilesTool(_SearchTool):
if include_dirs:
yield entry
sequence = self._push_directory_entries(
tree,
entry.path,
root,
frontier,
@@ -444,10 +449,11 @@ class FindFilesTool(_SearchTool):
started_at = time.monotonic()
if cancelled.is_set():
raise _SearchCancelledError
target = self._resolve(path or ".")
if not target.exists():
try:
tree = self._files.search_tree(path or ".")
except FileNotFoundError:
return ToolResult.error(f"Error: Path not found: {path}")
if not (target.is_dir() or target.is_file()):
except NotRegularFileError:
return ToolResult.error(f"Error: Unsupported path: {path}")
if glob:
@@ -469,7 +475,7 @@ class FindFilesTool(_SearchTool):
def matching_entries() -> Iterator[tuple[str, float]]:
for entry in self._iter_paths(
target,
tree,
include_dirs=include_dirs,
budget=budget,
):
@@ -483,7 +489,7 @@ class FindFilesTool(_SearchTool):
mtime = 0.0
if sort == "modified":
try:
mtime = entry.path.stat().st_mtime
mtime = tree.modified(entry.path)
except OSError:
pass
suffix = "/" if entry.is_dir else ""
@@ -627,12 +633,14 @@ class GrepTool(_SearchTool):
}
@staticmethod
def _open_source(path: Path, pages: str | None, max_bytes: int) -> DocumentLineSource | None:
if path.suffix.lower() in _DOCUMENT_EXTENSIONS:
return open_document_line_source(path, pages=pages)
with path.open("rb") as file:
def _open_source(source: ReadableFile, pages: str | None, max_bytes: int) -> DocumentLineSource | None:
if source.path.suffix.lower() 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)
if _is_binary(raw):
if len(raw) > max_bytes or _is_binary(raw):
return None
try:
content = raw.decode("utf-8")
@@ -711,10 +719,11 @@ class GrepTool(_SearchTool):
budget.checkpoint()
if glob:
_glob_patterns(glob)
target = self._resolve(path or ".")
if not target.exists():
try:
tree = self._files.search_tree(path or ".")
except FileNotFoundError:
return ToolResult.error(f"Error: Path not found: {path}")
if not (target.is_dir() or target.is_file()):
except NotRegularFileError:
return ToolResult.error(f"Error: Unsupported path: {path}")
flags = re.IGNORECASE if case_insensitive else 0
@@ -739,12 +748,12 @@ class GrepTool(_SearchTool):
document_continuations: list[str] = []
counts: dict[str, int] = {}
file_mtimes: dict[str, float] = {}
root = target if target.is_dir() else target.parent
root = tree.root if tree.is_directory else tree.root.parent
max_file_bytes = (
self._MAX_EXPLICIT_FILE_BYTES if target.is_file() else self._MAX_FILE_BYTES
self._MAX_FILE_BYTES if tree.is_directory else self._MAX_EXPLICIT_FILE_BYTES
)
for file_path in self._iter_files(target, budget):
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
@@ -753,21 +762,17 @@ class GrepTool(_SearchTool):
display_path = self._display_path(file_path, root)
try:
file_size = file_path.stat().st_size
file = tree.read_file(file_path)
except OSError:
skipped_binary += 1
continue
if file_size > max_file_bytes:
if file.size > max_file_bytes:
skipped_large += 1
continue
try:
mtime = file_path.stat().st_mtime
except OSError:
mtime = 0.0
source_iterator: Iterator[LocatedDocumentLine] | None = None
is_document = file_path.suffix.lower() in _DOCUMENT_EXTENSIONS
is_document = file.path.suffix.lower() in _DOCUMENT_EXTENSIONS
try:
source = self._open_source(file_path, pages, max_file_bytes)
source = self._open_source(file, pages, max_file_bytes)
if source is None:
skipped_binary += 1
continue
@@ -795,7 +800,7 @@ class GrepTool(_SearchTool):
except Exception as e:
if not is_document:
raise
if target.is_file():
if not tree.is_directory:
if isinstance(e, PdfPageRangeError):
return ToolResult.error(
f"Error: Invalid PDF page range '{pages}': {e!s}."
@@ -811,7 +816,7 @@ class GrepTool(_SearchTool):
if close is not None:
close()
if file_had_match:
file_mtimes[display_path] = mtime
file_mtimes[display_path] = file.modified
if content_page.stopped:
break