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

+1 -1
View File
@@ -17,7 +17,7 @@ Choose the affected behavior below, then read its owner and existing tests. Foll
| Prompt assembly, skills, or context limits | [`agent/context.py`](../nanobot/agent/context.py), [`agent/context_governance.py`](../nanobot/agent/context_governance.py); [prompt cautions](gotchas.md#prompt-templates) | [`test_context_builder.py`](../tests/agent/test_context_builder.py), [`test_skills_loader.py`](../tests/agent/test_skills_loader.py), [`test_context_governance.py`](../tests/agent/test_context_governance.py) |
| Session persistence or recovery | [`session/state.py`](../nanobot/session/state.py), [`session/sqlite_store.py`](../nanobot/session/sqlite_store.py), [`session/recovery.py`](../nanobot/session/recovery.py) | [`tests/session/`](../tests/session/), [`test_loop_recovery.py`](../tests/agent/test_loop_recovery.py) |
| WebUI/TUI wire events or displayed history | [`webui/outbound_delivery.py`](../nanobot/webui/outbound_delivery.py), [`webui/transcript.py`](../nanobot/webui/transcript.py); [client compatibility](review-guide.md) | [`tests/webui/`](../tests/webui/), [`WebSocket tests`](../nanobot/channels/websocket/tests/), and affected client tests |
| Workspace access or sandbox enforcement | [`security/workspace_access.py`](../nanobot/security/workspace_access.py), [`execution/sandbox.py`](../nanobot/execution/sandbox.py); [security rules](security.md) | [`tests/security/`](../tests/security/), [`test_workspace_scope.py`](../tests/agent/test_workspace_scope.py), [`test_sandbox.py`](../tests/tools/test_sandbox.py) |
| Workspace access or sandbox enforcement | [`security/workspace_access.py`](../nanobot/security/workspace_access.py), [`execution/files.py`](../nanobot/execution/files.py), [`execution/sandbox.py`](../nanobot/execution/sandbox.py); [security rules](security.md) | [`tests/security/`](../tests/security/), [`test_workspace_scope.py`](../tests/agent/test_workspace_scope.py), [`test_sandbox.py`](../tests/tools/test_sandbox.py) |
| Gateway startup, shutdown, or launchers | [`gateway/`](../nanobot/gateway/), [`cli/gateway_runtime.py`](../nanobot/cli/gateway_runtime.py) | [`tests/gateway/`](../tests/gateway/), the matching launcher tests in [`tests/cli/`](../tests/cli/) |
For the end-to-end runtime flow, expand to [Architecture](../docs/architecture.md). For ownership changes, read [Design Constraints](design.md); directory proximity does not permit crossing those boundaries.
+2 -2
View File
@@ -4,13 +4,13 @@ Consult this document when changing path access, outbound HTTP/MCP, or shell exe
## Workspace Restriction
Filesystem tools (`read_file`, `write_file`, `edit_file`, `list_dir`, `apply_patch`) resolve paths through the workspace path resolver (`agent/tools/filesystem.py` / `agent/tools/path_utils.py`), which enforces that the resolved path must lie under the active workspace when workspace restriction is enabled. The media upload directory is always an internal extra read root while restricted.
Filesystem tools and native file search use scoped operations in `nanobot/execution/files.py`. Those operations apply `nanobot/security/workspace_policy.py` to the effective request workspace before opening a file, listing a directory, or writing a patch. Edit activity snapshots use the same authorized write target, not a path from tool arguments. The media upload directory is an internal extra read root while restricted. These are application-level checks, not OS confinement against a process that can concurrently replace ancestor directories.
Additional filesystem roots must be capability-specific. `extra_allowed_dirs` is a legacy read-only alias. Use `extra_read_allowed_dirs` for read-only roots, `extra_write_allowed_dirs` only when a write-capable tool is intentionally allowed to modify an extra directory, and exact file allowlists when a tool may modify only specific files.
Shell execution (`ExecTool`, `agent/tools/shell.py`) also respects `restrict_to_workspace` as an application-level guard: if enabled and `working_dir` is outside the workspace, the command is rejected before execution, and command text is checked for obvious workspace escapes. This is not process-level isolation; use an exec sandbox backend for that.
**Rule**: Any new path-handling logic must go through the workspace path resolver or perform an equivalent containment check with explicit read/write capability semantics.
**Rule**: File tool adapters should request a scoped file operation; do not add direct path authorization or filesystem effects in those adapters. When traversing a directory, authorize discovered file targets before reading them. Subprocess-backed search follows the shell rules below.
## SSRF Protection
+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
+371 -5
View File
@@ -1,11 +1,22 @@
"""Descriptor-based reads for paths already resolved under workspace policy."""
"""Filesystem operations and their workspace authorization."""
from __future__ import annotations
import os
import re
import stat
from collections.abc import Generator
from contextlib import contextmanager
from collections.abc import Callable, Generator, Iterable
from contextlib import AbstractContextManager, contextmanager
from dataclasses import dataclass
from pathlib import Path
from typing import BinaryIO
from typing import TYPE_CHECKING, BinaryIO
from nanobot.config.paths import get_media_dir
from nanobot.security.workspace_access import current_tool_workspace
from nanobot.security.workspace_policy import resolve_allowed_path, resolve_path
if TYPE_CHECKING:
from nanobot.utils.document import DocumentLineSource, PdfExtraction
class NotRegularFileError(OSError):
@@ -13,7 +24,7 @@ class NotRegularFileError(OSError):
@contextmanager
def open_regular_file(resolved_path: Path) -> Generator[tuple[BinaryIO, int]]:
def _open_regular_file(resolved_path: Path) -> 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.
@@ -27,3 +38,358 @@ def open_regular_file(resolved_path: Path) -> Generator[tuple[BinaryIO, int]]:
if not stat.S_ISREG(opened.st_mode):
raise NotRegularFileError
yield stream, opened.st_size
_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",
})
_PROCESS_STDIO = re.compile(r"/proc/(?:[0-9]+|self)/fd/[012]$")
def _reject_device(path: str | Path, *, resolved: bool = False) -> None:
raw = str(path)
canonical = raw
if not resolved:
try:
canonical = str(Path(raw).resolve())
except (OSError, ValueError):
pass
if (
raw in _BLOCKED_DEVICE_PATHS or canonical in _BLOCKED_DEVICE_PATHS
or _PROCESS_STDIO.match(raw) or _PROCESS_STDIO.match(canonical)
or canonical.startswith("/dev/")
):
raise PermissionError(
f"Reading {path} is blocked (device path that could hang or produce infinite output)."
)
@dataclass(frozen=True, slots=True)
class ReadableFile:
"""A file selected by the workspace read policy."""
path: Path
size: int
modified: float
def open(self) -> AbstractContextManager[tuple[BinaryIO, int]]:
return _open_regular_file(self.path)
@staticmethod
def open_size(stream: BinaryIO) -> int:
return os.fstat(stream.fileno()).st_size
def pdf_pages(self, pages: str | None, *, max_pages: int, max_chars: int) -> PdfExtraction:
from nanobot.utils.document import extract_pdf_pages
return extract_pdf_pages(self.path, pages=pages, max_pages=max_pages, max_chars=max_chars)
def document_lines(self, *, pages: str | None = None) -> DocumentLineSource | None:
from nanobot.utils.document import open_document_line_source
return open_document_line_source(self.path, pages=pages)
@dataclass(frozen=True, slots=True)
class FileSnapshot:
exists: bool
text: str | None
unreadable: bool = False
binary: bool = False
oversized: bool = False
@property
def countable(self) -> bool:
return self.text is not None and not (self.binary or self.oversized or self.unreadable)
@dataclass(frozen=True, slots=True)
class WritableFile:
"""A selected write target; editing may inspect that file, not its parent."""
path: Path
def exists(self) -> bool:
return self.path.exists()
def is_file(self) -> bool:
return self.path.is_file()
def size(self) -> int:
return self.path.stat().st_size
def read_bytes(self) -> bytes:
return self.path.read_bytes()
def write(self, content: str, *, create_parents: bool = False) -> None:
if create_parents:
self.path.parent.mkdir(parents=True, exist_ok=True)
self.path.write_text(content, encoding="utf-8", newline="")
def snapshot(self, max_bytes: int) -> FileSnapshot:
"""Read a bounded edit preview, not an independent path grant."""
try:
if not self.is_file():
return FileSnapshot(exists=False, text="")
with _open_regular_file(self.path) as (stream, size):
if size > max_bytes:
return FileSnapshot(exists=True, text=None, oversized=True)
raw = stream.read(max_bytes + 1)
except OSError:
return FileSnapshot(exists=self.exists(), text=None, unreadable=True)
if len(raw) > max_bytes:
return FileSnapshot(exists=True, text=None, oversized=True)
if b"\x00" in raw:
return FileSnapshot(exists=True, text=None, binary=True)
try:
text = raw.decode("utf-8")
except UnicodeDecodeError:
return FileSnapshot(exists=True, text=None, binary=True)
return FileSnapshot(exists=True, text=text.replace("\r\n", "\n"))
def commit_file_edits(writes: dict[WritableFile, str]) -> None:
"""Write validated patch targets; restore their previous bytes on failure."""
backups = {target: target.read_bytes() if target.exists() else None for target in writes}
attempted: list[WritableFile] = []
try:
for target, content in writes.items():
attempted.append(target)
target.write(content, create_parents=True)
except Exception:
for target in attempted:
data = backups[target]
if data is None:
target.path.unlink(missing_ok=True)
else:
target.path.parent.mkdir(parents=True, exist_ok=True)
target.path.write_bytes(data)
raise
@dataclass(frozen=True, slots=True)
class DirectoryListing:
entries: list[tuple[Path, bool]]
total: int
@dataclass(frozen=True, slots=True)
class SearchEntry:
name: str
is_directory: bool
is_directory_link: bool
@dataclass(frozen=True, slots=True)
class FileSearch:
"""An authorized search root; links are not recursive directories."""
root: Path
is_directory: bool
_authorize_read: Callable[[str | Path], Path]
def entries(self, directory: Path) -> Generator[SearchEntry]:
target = resolve_path(directory)
if not self.is_directory or not target.is_relative_to(self.root) or target != directory:
return
with os.scandir(target) as entries:
for entry in entries:
try:
is_directory = entry.is_dir(follow_symlinks=False)
directory_link = not is_directory and entry.is_symlink() and entry.is_dir()
if os.name == "nt" and is_directory:
directory_link = bool(
entry.stat(follow_symlinks=False).st_file_attributes
& stat.FILE_ATTRIBUTE_REPARSE_POINT
)
except OSError:
continue
yield SearchEntry(entry.name, is_directory or directory_link, directory_link)
def _candidate(self, path: Path) -> Path:
target = Path(os.path.realpath(path, strict=True))
if target == self.root or (self.is_directory and target.is_relative_to(self.root)):
return target
return self._authorize_read(path)
def modified(self, path: Path) -> float:
return self._candidate(path).stat().st_mtime
def read_file(self, path: Path) -> ReadableFile:
return _regular_file(self._candidate(path))
def _regular_file(target: Path) -> ReadableFile:
_reject_device(target, resolved=True)
info = target.stat()
if not stat.S_ISREG(info.st_mode):
raise NotRegularFileError
return ReadableFile(target, info.st_size, info.st_mtime)
class WorkspaceFiles:
"""File operations authorized against the effective request's workspace."""
def __init__(
self,
workspace: Path | None = None,
allowed_dir: Path | None = None,
extra_allowed_dirs: Iterable[Path] | None = None,
extra_read_allowed_dirs: Iterable[Path] | None = None,
extra_write_allowed_dirs: Iterable[Path] | None = None,
extra_write_allowed_files: Iterable[Path] | None = None,
restrict_to_workspace: bool | None = None,
sandbox_restricts_workspace: bool = False,
extra_read_allowed_files: Iterable[Path] | None = None,
*,
builtin_skills: Path,
plugin_skill_roots: Callable[[Path, Path], Iterable[Path]],
) -> None:
self._workspace = workspace
self._allowed_dir = allowed_dir
# The legacy extra_allowed_dirs option only grants reads.
self._read_dirs = (*tuple(extra_allowed_dirs or ()), *tuple(extra_read_allowed_dirs or ()))
self._read_files = tuple(extra_read_allowed_files or ())
self._write_dirs = tuple(extra_write_allowed_dirs or ())
self._write_files = tuple(extra_write_allowed_files or ())
self._restricted = (
restrict_to_workspace if restrict_to_workspace is not None else allowed_dir is not None
)
self._sandbox_restricted = sandbox_restricts_workspace
self._builtin_skills = builtin_skills
self._plugin_skill_roots = plugin_skill_roots
@classmethod
def for_agent(
cls,
workspace: Path,
*,
restrict_to_workspace: bool,
sandbox_restricts_workspace: bool,
builtin_skills: Path,
plugin_skill_roots: Callable[[Path, Path], Iterable[Path]],
) -> WorkspaceFiles:
root = workspace.expanduser().resolve(strict=False)
return cls(
workspace,
allowed_dir=workspace if restrict_to_workspace or sandbox_restricts_workspace else None,
extra_read_allowed_dirs=[builtin_skills, root / "skills"],
extra_read_allowed_files=[root / "memory" / "history.jsonl"],
restrict_to_workspace=restrict_to_workspace,
sandbox_restricts_workspace=sandbox_restricts_workspace,
builtin_skills=builtin_skills,
plugin_skill_roots=plugin_skill_roots,
)
@property
def display_workspace(self) -> Path | None:
return current_tool_workspace(self._workspace).project_path
def _allowed_root(self, request_root: Path | None) -> Path | None:
if self._allowed_dir is None or self._workspace is None:
return request_root
try:
if Path(self._allowed_dir).expanduser().resolve() == Path(self._workspace).expanduser().resolve():
return request_root
except (OSError, RuntimeError, TypeError, ValueError):
return request_root if request_root is not None else self._allowed_dir
return self._allowed_dir
def _roots(self) -> tuple[Path | None, Path | None]:
access = current_tool_workspace(
self._workspace,
restrict_to_workspace=self._restricted,
sandbox_restricts_workspace=self._sandbox_restricted,
)
return access.project_path, self._allowed_root(access.allowed_root)
def _read_path(self, path: str | Path, *, directory: bool = False) -> Path:
workspace, root = self._roots()
extra_roots: list[Path] = []
if root is not None:
extra_roots = [get_media_dir(), *self._read_dirs]
if self._workspace is not None:
try:
extra_roots.extend(self._plugin_skill_roots(self._workspace, resolve_path(path, workspace)))
except (OSError, RuntimeError):
pass
return resolve_allowed_path(
path,
workspace=workspace,
allowed_root=root,
extra_allowed_roots=extra_roots,
extra_allowed_files=self._read_files if root is not None and not directory else (),
)
def edit_target(self, path: str) -> WritableFile:
workspace, root = self._roots()
return WritableFile(resolve_allowed_path(
path,
workspace=workspace,
allowed_root=root,
extra_allowed_roots=self._write_dirs if root is not None else (),
extra_allowed_files=self._write_files,
))
def read_file(self, path: str) -> ReadableFile:
_reject_device(path)
target = self._read_path(path)
if not target.exists():
requested = Path(path)
parts = requested.parts
if not requested.is_absolute() and len(parts) >= 2 and parts[0] == "skills":
builtin = self._builtin_skills.resolve()
candidate = (builtin / Path(*parts[1:])).resolve()
if candidate.is_relative_to(builtin) and candidate.is_file():
target = candidate
if not target.exists():
_reject_device(target, resolved=True)
raise FileNotFoundError(path)
return _regular_file(target)
def list_directory(
self, path: str, *, recursive: bool, ignored: set[str], limit: int,
) -> DirectoryListing:
directory = self._read_path(path, directory=True)
if not directory.exists():
raise FileNotFoundError(path)
if not directory.is_dir():
raise NotADirectoryError(path)
tree = FileSearch(directory, True, self._read_path)
pending = [directory]
entries: list[tuple[Path, bool]] = []
while pending:
parent = pending.pop()
try:
for entry in tree.entries(parent):
if entry.name in ignored:
continue
child = parent / entry.name
entries.append((child.relative_to(directory), entry.is_directory))
if recursive and entry.is_directory and not entry.is_directory_link:
pending.append(child)
except PermissionError:
if not recursive:
raise
entries.sort(key=lambda entry: entry[0])
return DirectoryListing(entries[:max(0, limit)], len(entries))
def sibling_files(self, target: WritableFile) -> list[str]:
"""Suggest names only when the caller can read the directory itself."""
try:
parent = self._read_path(target.path.parent, directory=True)
except PermissionError:
return []
return [item.name for item in parent.iterdir() if item.is_file()] if parent.is_dir() else []
def search_tree(self, path: str) -> FileSearch:
target = self._read_path(path)
mode = target.stat().st_mode
if not (stat.S_ISDIR(mode) or stat.S_ISREG(mode)):
raise NotRegularFileError
is_directory = stat.S_ISDIR(mode)
if is_directory:
target = self._read_path(path, directory=True)
return FileSearch(target, is_directory, self._read_path)
+38 -122
View File
@@ -5,10 +5,12 @@ from collections.abc import Iterable, Iterator
from dataclasses import dataclass
from itertools import groupby, islice
from pathlib import Path
from typing import Any, cast
from typing import Any, Protocol, cast, runtime_checkable
from rapidfuzz.distance import Indel, Opcode, Opcodes
from nanobot.execution.files import FileSnapshot, WritableFile
TRACKED_FILE_EDIT_TOOLS = frozenset({"write_file", "edit_file", "apply_patch"})
_MAX_SNAPSHOT_BYTES = 2 * 1024 * 1024
_MAX_DIFF_LINES = 500
@@ -16,33 +18,26 @@ _MAX_DIFF_LINE_CHARS = 1200
_DIFF_CONTEXT_LINES = 3
@dataclass(slots=True)
class FileSnapshot:
path: Path
exists: bool
text: str | None
unreadable: bool = False
binary: bool = False
oversized: bool = False
@runtime_checkable
class FileEditSource(Protocol):
def file_edit_target(self, path: str) -> WritableFile: ...
@property
def countable(self) -> bool:
return (
self.text is not None
and not self.binary
and not self.oversized
and not self.unreadable
)
def file_edit_workspace(self) -> Path | None: ...
@dataclass(slots=True)
class FileEditTracker:
call_id: str
tool: str
path: Path
target: WritableFile
display_path: str
before: FileSnapshot
@property
def path(self) -> Path:
return self.target.path
@dataclass(slots=True)
class FileDiff:
@@ -162,23 +157,6 @@ def display_file_edit_path(path: Path, workspace: Path | None) -> str:
return path.as_posix()
def read_file_snapshot(path: Path, *, max_bytes: int = _MAX_SNAPSHOT_BYTES) -> FileSnapshot:
try:
if not path.exists() or not path.is_file():
return FileSnapshot(path=path, exists=False, text="")
size = path.stat().st_size
if size > max_bytes:
return FileSnapshot(path=path, exists=True, text=None, oversized=True)
raw = path.read_bytes()
except OSError:
return FileSnapshot(path=path, exists=path.exists(), text=None, unreadable=True)
if b"\x00" in raw:
return FileSnapshot(path=path, exists=True, text=None, binary=True)
try:
text = raw.decode("utf-8")
except UnicodeDecodeError:
return FileSnapshot(path=path, exists=True, text=None, binary=True)
return FileSnapshot(path=path, exists=True, text=text.replace("\r\n", "\n"))
def build_unified_diff_payload(
@@ -330,105 +308,43 @@ def prepare_file_edit_trackers(
) -> list[FileEditTracker]:
if not isinstance(params, dict) or not is_file_edit_tool(tool_name):
return []
paths = resolve_file_edit_paths(tool_name, tool, workspace, params)
display_workspace = _display_workspace(tool, workspace)
if not isinstance(tool, FileEditSource):
return []
display_workspace = tool.file_edit_workspace or workspace
trackers: list[FileEditTracker] = []
seen: set[Path] = set()
for path in paths:
for raw_path in _file_edit_paths(tool_name, params):
try:
resolved = path.resolve()
except Exception:
resolved = path
if resolved in seen:
target = tool.file_edit_target(raw_path)
except (OSError, RuntimeError, ValueError):
continue
seen.add(resolved)
before = read_file_snapshot(path)
if target.path in seen:
continue
seen.add(target.path)
trackers.append(FileEditTracker(
call_id=str(call_id or ""),
tool=tool_name,
path=path,
display_path=display_file_edit_path(path, display_workspace),
before=before,
target=target,
display_path=display_file_edit_path(target.path, display_workspace),
before=target.snapshot(_MAX_SNAPSHOT_BYTES),
))
return trackers
def resolve_file_edit_paths(
tool_name: str,
tool: Any,
workspace: Path | None,
params: dict[str, Any] | None,
) -> list[Path]:
if not isinstance(params, dict):
return []
if tool_name == "apply_patch":
return _resolve_apply_patch_paths(tool, workspace, params)
if tool_name not in {"write_file", "edit_file"}:
return []
path = _resolve_single_path(tool, workspace, params.get("path"))
return [path] if path is not None else []
def _resolve_apply_patch_paths(
tool: Any,
workspace: Path | None,
params: dict[str, Any],
) -> list[Path]:
if params.get("dry_run") is True:
return []
def _file_edit_paths(tool_name: str, params: dict[str, Any]) -> Iterator[str]:
if tool_name != "apply_patch":
path = params.get("path")
if isinstance(path, str) and path.strip():
yield path
return
edits = params.get("edits")
if not isinstance(edits, list):
return []
patch_edits = cast(list[Any], edits)
paths: list[Path] = []
seen: set[Path] = set()
for edit in patch_edits:
if not isinstance(edit, dict):
continue
raw_path = cast(dict[str, Any], edit).get("path")
if not isinstance(raw_path, str):
continue
raw_path = raw_path.strip()
if not raw_path or "\0" in raw_path:
continue
path = _resolve_single_path(tool, workspace, raw_path)
if path is not None and path not in seen:
seen.add(path)
paths.append(path)
return paths
def _resolve_single_path(tool: Any, workspace: Path | None, raw_path: Any) -> Path | None:
if not isinstance(raw_path, str) or not raw_path.strip():
return None
for resolver_name in ("_resolve_write", "_resolve"):
resolver = getattr(tool, resolver_name, None)
if callable(resolver):
try:
resolved = resolver(raw_path)
if isinstance(resolved, Path):
return resolved
if resolved:
return Path(cast(str, resolved))
except Exception:
return None
if workspace is None:
return Path(raw_path).expanduser().resolve()
return (workspace / raw_path).expanduser().resolve()
def _display_workspace(tool: Any, fallback: Path | None) -> Path | None:
resolver = getattr(tool, "_display_workspace", None)
if callable(resolver):
try:
value = resolver()
except Exception:
return fallback
if isinstance(value, Path):
return value
if value:
return Path(cast(str, value))
return fallback
if params.get("dry_run") is True or not isinstance(edits, list):
return
for edit in cast(list[object], edits):
if isinstance(edit, dict):
path = cast(dict[str, object], edit).get("path")
if isinstance(path, str) and (path := path.strip()) and "\0" not in path:
yield path
def build_file_edit_start_event(tracker: FileEditTracker) -> dict[str, Any]:
@@ -447,7 +363,7 @@ def build_file_edit_end_event(
*,
diff: FileDiff | None = None,
) -> dict[str, Any]:
after = read_file_snapshot(tracker.path)
after = tracker.target.snapshot(_MAX_SNAPSHOT_BYTES)
diff_payload: dict[str, Any] | None = None
if (
tracker.before.countable and after.countable
+6
View File
@@ -119,6 +119,12 @@ IMPORT_RULES = (
("nanobot.execution",),
(*_ADAPTERS, "nanobot.agent", "nanobot.session"),
),
ImportRule(
"file-tool-execution",
("nanobot.agent.tools.filesystem", "nanobot.agent.tools.apply_patch",
"nanobot.agent.tools.search", "nanobot.utils.file_edit_events"),
("nanobot.security", "nanobot.agent.tools.path_utils", "os", "shutil", "glob"),
),
ImportRule(
"websocket-transport",
("nanobot.channels.websocket.runtime",),
+1 -1
View File
@@ -57,7 +57,7 @@ async def test_document_attachment_is_referenced_and_read_on_demand(
media_dir.mkdir()
csv_path = media_dir / "report.csv"
csv_path.write_text("name,value\nnanobot,1", encoding="utf-8")
monkeypatch.setattr("nanobot.agent.tools.path_utils.get_media_dir", lambda: media_dir)
monkeypatch.setattr("nanobot.config.loader._current_config_path", tmp_path / "config.json")
loop = _make_loop(
workspace,
+21 -3
View File
@@ -20,7 +20,11 @@ from nanobot.context_sources import (
)
from nanobot.llm_usage.context import llm_usage_source
from nanobot.providers.base import GenerationSettings, LLMProvider, LLMResponse, ToolCallRequest
from nanobot.security.workspace_access import build_workspace_scope
from nanobot.security.workspace_access import (
bind_workspace_scope,
build_workspace_scope,
reset_workspace_scope,
)
from nanobot.utils.llm_runtime import LLMRuntime
@@ -217,8 +221,22 @@ async def test_subagent_keeps_project_runtime_scope_with_agent_owned_tools(tmp_p
spec = manager.runner.run.call_args.args[0]
assert spec.workspace == project
assert spec.tools.get("read_file")._workspace == agent_workspace.resolve()
assert spec.tools.get("read_file")._restrict_to_workspace is True
(project / "project.txt").write_text("project document", encoding="utf-8")
(agent_workspace / "skills").mkdir()
(agent_workspace / "skills" / "reference.txt").write_text("agent skill", encoding="utf-8")
private = agent_workspace / "private.txt"
private.write_text("agent private data", encoding="utf-8")
token = bind_workspace_scope(build_workspace_scope(project, "restricted"))
try:
assert "project document" in await spec.tools.execute("read_file", {"path": "project.txt"})
assert "agent skill" in await spec.tools.execute(
"read_file", {"path": str(agent_workspace / "skills" / "reference.txt")},
)
denied = await spec.tools.execute("read_file", {"path": str(private)})
assert denied.is_error
assert "agent private data" not in denied
finally:
reset_workspace_scope(token)
assert manager.tools_config.restrict_to_workspace is False
+1 -1
View File
@@ -356,7 +356,7 @@ def test_apply_patch_media_dir_is_read_only_by_default(tmp_path, monkeypatch):
media.mkdir()
target = media / "demo.md"
target.write_text("before\n", encoding="utf-8")
monkeypatch.setattr("nanobot.agent.tools.path_utils.get_media_dir", lambda: media)
monkeypatch.setattr("nanobot.config.loader._current_config_path", tmp_path / "config.json")
tool = ApplyPatchTool(workspace=workspace, allowed_dir=workspace)
result = asyncio.run(
+23 -2
View File
@@ -9,6 +9,27 @@ from nanobot.agent.tools.filesystem import (
)
async def test_exact_edit_grant_does_not_list_sibling_files(tmp_path):
workspace = tmp_path / "workspace"
workspace.mkdir()
outside = tmp_path / "outside"
outside.mkdir()
target = outside / "approved.txt"
(outside / "approved-secret.txt").write_text("private", encoding="utf-8")
tool = EditFileTool(
workspace=workspace, allowed_dir=workspace, extra_write_allowed_files=[target],
)
missing = await tool.execute(path=str(target), old_text="old", new_text="new")
assert "File not found" in missing
assert "approved-secret.txt" not in missing
assert not target.exists()
created = await tool.execute(path=str(target), old_text="", new_text="approved contents")
assert not getattr(created, "is_error", False)
assert target.read_text(encoding="utf-8") == "approved contents"
@pytest.mark.asyncio
@pytest.mark.parametrize("newline", ["\n", "\r\n", "\r"])
@pytest.mark.parametrize("operation", ["write", "edit_new", "edit_empty"])
@@ -396,7 +417,7 @@ class TestWorkspaceRestriction:
media_file = media_dir / "photo.txt"
media_file.write_text("shared media", encoding="utf-8")
monkeypatch.setattr("nanobot.agent.tools.path_utils.get_media_dir", lambda: media_dir)
monkeypatch.setattr("nanobot.config.loader._current_config_path", tmp_path / "config.json")
tool = ReadFileTool(workspace=workspace, allowed_dir=workspace)
result = await tool.execute(path=str(media_file))
@@ -410,7 +431,7 @@ class TestWorkspaceRestriction:
media_dir = tmp_path / "media"
media_dir.mkdir()
monkeypatch.setattr("nanobot.agent.tools.path_utils.get_media_dir", lambda: media_dir)
monkeypatch.setattr("nanobot.config.loader._current_config_path", tmp_path / "config.json")
tool = WriteFileTool(workspace=workspace, allowed_dir=workspace)
result = await tool.execute(path=str(media_dir / "hack.txt"), content="pwned")
+6 -6
View File
@@ -110,7 +110,7 @@ class TestReadDedup:
return self.stream.seek(*args)
monkeypatch.setattr(
"nanobot.agent.tools.filesystem.os.fdopen",
"nanobot.execution.files.os.fdopen",
lambda *args, **kwargs: CountingStream(real_fdopen(*args, **kwargs)),
)
visible = {} if case == "not_visible" else {"read-1": first}
@@ -807,7 +807,7 @@ class TestBoundedTextReads:
return chunk
monkeypatch.setattr(
"nanobot.agent.tools.filesystem.os.fdopen",
"nanobot.execution.files.os.fdopen",
lambda *args, **kwargs: GrowingStream(real_fdopen(*args, **kwargs)),
)
result = await tool.execute(path=str(f))
@@ -886,7 +886,7 @@ class TestBoundedTextReads:
return chunk
monkeypatch.setattr(
"nanobot.agent.tools.filesystem.os.fdopen",
"nanobot.execution.files.os.fdopen",
lambda *args, **kwargs: ChangeAfterPrecheck(real_fdopen(*args, **kwargs)),
)
with file_state.file_read_context("read-2", lambda: {"read-1": first}):
@@ -932,7 +932,7 @@ class TestBoundedTextReads:
return chunk
monkeypatch.setattr(
"nanobot.agent.tools.filesystem.os.fdopen",
"nanobot.execution.files.os.fdopen",
lambda *args, **kwargs: ChangeAfterPrecheck(real_fdopen(*args, **kwargs)),
)
tracemalloc.start()
@@ -972,7 +972,7 @@ class TestBoundedTextReads:
return chunk
monkeypatch.setattr(
"nanobot.agent.tools.filesystem.os.fdopen",
"nanobot.execution.files.os.fdopen",
lambda *args, **kwargs: GrowingStream(real_fdopen(*args, **kwargs)),
)
with file_state.file_read_context("read-2", lambda: {"read-1": first}):
@@ -1013,7 +1013,7 @@ class TestBoundedTextReads:
tool = ReadFileTool()
try:
with monkeypatch.context() as scoped:
scoped.setattr("nanobot.agent.tools.filesystem.os.open", open_replacement)
scoped.setattr("nanobot.execution.files.os.open", open_replacement)
result = await tool.execute(path=str(f))
finally:
try:
+46 -5
View File
@@ -186,6 +186,47 @@ async def test_find_files_scan_keeps_event_loop_responsive(
assert await asyncio.wait_for(task, timeout=0.5) == "match.txt"
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.write_text("needle allowed", encoding="utf-8")
outside = tmp_path / "outside.txt"
outside.write_text("needle outside contents", encoding="utf-8")
try:
(workspace / "inside-link.txt").symlink_to(inside)
(workspace / "outside-link.txt").symlink_to(outside)
except (NotImplementedError, OSError):
pytest.skip("symlinks unavailable")
tool = GrepTool(workspace=workspace, allowed_dir=workspace)
result = await tool.execute(pattern="needle", fixed_strings=True)
assert "inside-link.txt" in result
assert "needle allowed" in result
assert "needle outside contents" not in result
async def test_exact_read_grant_does_not_authorize_a_directory_tree(tmp_path: Path):
workspace = tmp_path / "workspace"
workspace.mkdir()
grant = tmp_path / "history.jsonl"
options = {
"workspace": workspace,
"allowed_dir": workspace,
"extra_read_allowed_files": [grant],
}
grant.write_text("needle history", encoding="utf-8")
grep = GrepTool(**options)
assert "needle history" in await grep.execute(pattern="needle", path=str(grant))
grant.unlink()
grant.mkdir()
(grant / "private.txt").write_text("needle private", encoding="utf-8")
result = await grep.execute(pattern="needle", path=str(grant))
assert "outside allowed directory" in result
assert "needle private" not in result
@pytest.mark.asyncio
async def test_find_files_cancellation_stops_worker_scan(
tmp_path: Path,
@@ -226,12 +267,12 @@ async def test_find_files_path_limit_stops_after_pagination_lookahead(
tool = FindFilesTool(workspace=tmp_path, allowed_dir=tmp_path)
visited: list[str] = []
def ordered_iter_paths(root: Path, *, include_dirs: bool, budget):
def ordered_iter_paths(tree, *, include_dirs: bool, budget):
del include_dirs
for path in paths:
budget.checkpoint()
visited.append(path.name)
yield tool._entry(path, root, is_dir=False)
yield tool._entry(path, tree.root, is_dir=False)
monkeypatch.setattr(tool, "_iter_paths", ordered_iter_paths)
result = await tool.execute(path=".", head_limit=1)
@@ -982,13 +1023,13 @@ async def test_grep_scan_yields_and_cancellation_stops_worker(tmp_path, monkeypa
tool = GrepTool(workspace=tmp_path)
started, stopped = threading.Event(), threading.Event()
def blocking_iter_files(root, budget):
def blocking_iter_files(tree, budget):
started.set()
try:
if not budget.cancelled.wait(timeout=2):
raise TimeoutError("worker did not receive cancellation")
budget.checkpoint()
yield root / "unreachable.txt"
yield tree.root / "unreachable.txt"
finally:
stopped.set()
@@ -1061,7 +1102,7 @@ async def test_grep_closes_document_stream_and_preserves_locators(tmp_path, monk
closed.append(True)
monkeypatch.setattr(
"nanobot.agent.tools.search.open_document_line_source",
"nanobot.utils.document.open_document_line_source",
lambda *_args, **_kwargs: DocumentLineSource(document_lines(), "pages=2-3"),
)
result = await GrepTool(workspace=tmp_path).execute(
+19 -28
View File
@@ -2,10 +2,11 @@ from __future__ import annotations
import shutil
from dataclasses import fields
from pathlib import Path
from typing import Any
from unittest.mock import MagicMock
import pytest
from nanobot.agent.tools.base import Tool
from nanobot.agent.tools.context import ToolContext
from nanobot.agent.tools.loader import _SKIP_MODULES, ToolLoader
@@ -184,35 +185,25 @@ def test_loader_preserves_caller_supplied_tool(tmp_path):
assert "read_file" not in registered
def test_fs_tool_create_builds_from_context():
@pytest.mark.parametrize(("restrict", "sandbox"), [(False, ""), (True, ""), (False, "bwrap")])
async def test_fs_tool_create_uses_context_workspace_and_restrictions(tmp_path, restrict, sandbox):
from nanobot.agent.tools.filesystem import ReadFileTool
workspace = tmp_path / "workspace"
workspace.mkdir()
(workspace / "inside.txt").write_text("inside", encoding="utf-8")
(tmp_path / "outside.txt").write_text("outside contents", encoding="utf-8")
mock_config = MagicMock()
mock_config.restrict_to_workspace = False
mock_config.exec.sandbox = ""
ctx = ToolContext(config=mock_config, workspace="/tmp/test")
tool = ReadFileTool.create(ctx)
assert isinstance(tool, ReadFileTool)
assert tool._workspace == Path("/tmp/test")
def test_fs_tool_create_respects_restrict_to_workspace():
from nanobot.agent.tools.filesystem import ReadFileTool
mock_config = MagicMock()
mock_config.restrict_to_workspace = True
mock_config.exec.sandbox = ""
ctx = ToolContext(config=mock_config, workspace="/tmp/test")
tool = ReadFileTool.create(ctx)
assert tool._allowed_dir == Path("/tmp/test")
def test_fs_tool_create_respects_sandbox():
from nanobot.agent.tools.filesystem import ReadFileTool
mock_config = MagicMock()
mock_config.restrict_to_workspace = False
mock_config.exec.sandbox = "bwrap"
ctx = ToolContext(config=mock_config, workspace="/tmp/test")
tool = ReadFileTool.create(ctx)
assert tool._allowed_dir == Path("/tmp/test")
mock_config.restrict_to_workspace = restrict
mock_config.exec.sandbox = sandbox
tool = ReadFileTool.create(ToolContext(config=mock_config, workspace=str(workspace)))
assert "inside" in await tool.execute(path="inside.txt")
outside = await tool.execute(path="../outside.txt")
if restrict or sandbox:
assert outside.is_error
assert "outside contents" not in outside
else:
assert "outside contents" in outside
async def test_message_tool_create():
+15 -2
View File
@@ -15,7 +15,6 @@ from nanobot.utils.file_edit_events import (
build_file_edit_start_event,
build_unified_diff_payload,
prepare_file_edit_trackers,
read_file_snapshot,
)
@@ -245,7 +244,7 @@ def test_binary_file_is_reported_but_not_counted(tmp_path: Path) -> None:
params={"path": "data.bin", "old_text": "before", "new_text": "after"},
)
[tracker] = trackers
assert not read_file_snapshot(target).countable
assert not tracker.before.countable
target.write_bytes(b"\x00\x01after")
event = build_file_edit_end_event(tracker)
assert event["binary"] is True
@@ -371,3 +370,17 @@ def test_untracked_tools_do_not_prepare_file_edit_trackers(tmp_path: Path) -> No
workspace=tmp_path,
params={"path": "created-by-shell.txt"},
) == []
def test_edit_progress_does_not_snapshot_a_denied_target(tmp_path: Path) -> None:
workspace = tmp_path / "workspace"
workspace.mkdir()
(tmp_path / "outside.txt").write_text("private", encoding="utf-8")
tool = WriteFileTool(workspace=workspace, allowed_dir=workspace)
assert prepare_file_edit_trackers(
call_id="denied",
tool_name="write_file",
tool=tool,
workspace=workspace,
params={"path": "../outside.txt", "content": "new"},
) == []