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) | | 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) | | 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 | | 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/) | | 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. 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 ## 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. 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. 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 ## SSRF Protection
+15 -29
View File
@@ -1,10 +1,9 @@
from __future__ import annotations from __future__ import annotations
from pathlib import Path
from typing import Any, cast from typing import Any, cast
from nanobot.agent.tools.base import ToolResult, tool_parameters 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 ( from nanobot.agent.tools.schema import (
ArraySchema, ArraySchema,
BooleanSchema, BooleanSchema,
@@ -12,6 +11,7 @@ from nanobot.agent.tools.schema import (
StringSchema, StringSchema,
tool_parameters_schema, 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 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"], required=["edits"],
) )
) )
class ApplyPatchTool(_FsTool): class ApplyPatchTool(_WritableFsTool):
"""Apply file edits by providing structured edit instructions.""" """Apply file edits by providing structured edit instructions."""
_scopes = {"core", "subagent"} _scopes = {"core", "subagent"}
@@ -98,9 +98,9 @@ class ApplyPatchTool(_FsTool):
if not edits: if not edits:
raise _PatchError("must provide edits") raise _PatchError("must provide edits")
writes: dict[Path, str] = {} writes: dict[WritableFile, str] = {}
originals: dict[Path, str] = {} originals: dict[WritableFile, str] = {}
actions: dict[Path, str] = {} actions: dict[WritableFile, str] = {}
for edit_value in edits: for edit_value in edits:
if not isinstance(edit_value, dict): if not isinstance(edit_value, dict):
@@ -113,7 +113,7 @@ class ApplyPatchTool(_FsTool):
action = edit.get("action") action = edit.get("action")
if not isinstance(action, str): if not isinstance(action, str):
raise _PatchError(f"action required for edit: {path}") raise _PatchError(f"action required for edit: {path}")
source = self._resolve_write(path) source = self.file_edit_target(path)
if action == "add": if action == "add":
new_text = edit.get("new_text") new_text = edit.get("new_text")
@@ -211,7 +211,7 @@ class ApplyPatchTool(_FsTool):
summaries: list[str] = [] summaries: list[str] = []
for source, diff in diffs.items(): for source, diff in diffs.items():
action_name = actions[source] 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 added, deleted = diff.added, diff.deleted
stats = f" (+{added}/-{deleted})" if added or deleted else "" stats = f" (+{added}/-{deleted})" if added or deleted else ""
summaries.append(f"- {action_name} {path}{stats}") summaries.append(f"- {action_name} {path}{stats}")
@@ -219,27 +219,13 @@ class ApplyPatchTool(_FsTool):
if dry_run: if dry_run:
return "Patch dry-run succeeded:\n" + "\n".join(summaries) return "Patch dry-run succeeded:\n" + "\n".join(summaries)
backups: dict[Path, bytes | None] = {} commit_file_edits(writes)
for path in writes: for target in writes:
backups[path] = path.read_bytes() if path.exists() else None self._file_states.record_write(target.path)
return FileEditResult(
try: "Patch applied:\n" + "\n".join(summaries),
for path, content in writes.items(): {target.path: diff for target, diff in diffs.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)
except PermissionError as exc: except PermissionError as exc:
return ToolResult.error(f"Error: {exc}") return ToolResult.error(f"Error: {exc}")
except _PatchError as exc: except _PatchError as exc:
+93 -248
View File
@@ -4,31 +4,35 @@ import codecs
import difflib import difflib
import hashlib import hashlib
import mimetypes import mimetypes
import os
from copy import deepcopy from copy import deepcopy
from dataclasses import dataclass from dataclasses import dataclass
from pathlib import Path from pathlib import Path
from typing import Any, BinaryIO 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.base import Tool, ToolResult, tool_parameters
from nanobot.agent.tools.context import ToolContext from nanobot.agent.tools.context import ToolContext
from nanobot.agent.tools.file_state import FileStates, current_file_states from nanobot.agent.tools.file_state import FileStates, current_file_states
from nanobot.agent.tools.filesystem_config import FileToolsConfig from nanobot.agent.tools.filesystem_config import FileToolsConfig
from nanobot.agent.tools.path_utils import resolve_workspace_path
from nanobot.agent.tools.schema import ( from nanobot.agent.tools.schema import (
BooleanSchema, BooleanSchema,
IntegerSchema, IntegerSchema,
StringSchema, StringSchema,
tool_parameters_schema, tool_parameters_schema,
) )
from nanobot.execution.files import NotRegularFileError, open_regular_file from nanobot.execution.files import NotRegularFileError, ReadableFile, WorkspaceFiles, WritableFile
from nanobot.security.workspace_access import current_tool_workspace
from nanobot.utils.file_edit_events import FileDiff, FileEditResult, display_file_edit_path 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 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): 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" config_key = "file"
@@ -52,52 +56,37 @@ class _FsTool(Tool):
restrict_to_workspace: bool | None = None, restrict_to_workspace: bool | None = None,
sandbox_restricts_workspace: bool = False, sandbox_restricts_workspace: bool = False,
extra_read_allowed_files: list[Path] | None = None, extra_read_allowed_files: list[Path] | None = None,
*,
files: WorkspaceFiles | None = None,
): ):
self._workspace = workspace self._files = files if files is not None else WorkspaceFiles(
self._allowed_dir = allowed_dir workspace=workspace,
# Legacy alias: extra_allowed_dirs is read-only. Write-capable tools allowed_dir=allowed_dir,
# must opt in via extra_write_allowed_dirs. extra_allowed_dirs=extra_allowed_dirs,
self._extra_read_allowed_dirs = [ extra_read_allowed_dirs=extra_read_allowed_dirs,
*(extra_allowed_dirs or []), extra_write_allowed_dirs=extra_write_allowed_dirs,
*(extra_read_allowed_dirs or []), extra_write_allowed_files=extra_write_allowed_files,
] restrict_to_workspace=restrict_to_workspace,
self._extra_read_allowed_files = list(extra_read_allowed_files or []) sandbox_restricts_workspace=sandbox_restricts_workspace,
self._extra_write_allowed_dirs = list(extra_write_allowed_dirs or []) extra_read_allowed_files=extra_read_allowed_files,
self._extra_write_allowed_files = list(extra_write_allowed_files or []) builtin_skills=BUILTIN_SKILLS_DIR,
self._restrict_to_workspace = ( plugin_skill_roots=_plugin_skill_roots,
bool(restrict_to_workspace)
if restrict_to_workspace is not None
else allowed_dir is not None
) )
self._sandbox_restricts_workspace = sandbox_restricts_workspace # Dream and isolated runners can supply their own receipt store.
# 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.
self._explicit_file_states = file_states self._explicit_file_states = file_states
self._fallback_file_states = FileStates() self._fallback_file_states = FileStates()
@classmethod @classmethod
def create(cls, ctx: ToolContext) -> Tool: 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( return cls(
workspace=agent_workspace, files=WorkspaceFiles.for_agent(
allowed_dir=allowed_dir, Path(ctx.workspace),
extra_read_allowed_dirs=[BUILTIN_SKILLS_DIR, resolved_agent_workspace / "skills"], restrict_to_workspace=ctx.config.restrict_to_workspace,
extra_read_allowed_files=[resolved_agent_workspace / "memory" / "history.jsonl"], 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, file_states=ctx.file_state_store,
restrict_to_workspace=ctx.config.restrict_to_workspace,
sandbox_restricts_workspace=sandbox_restricts,
) )
@property @property
@@ -106,134 +95,16 @@ class _FsTool(Tool):
return self._explicit_file_states return self._explicit_file_states
return current_file_states(self._fallback_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( class _WritableFsTool(_FsTool):
self, """Expose the same write target to execution and edit activity tracking."""
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,
)
def _resolve_read(self, path: str) -> Path: def file_edit_target(self, path: str) -> WritableFile:
plugin_skill_dirs: list[Path] = [] return self._files.edit_target(path)
if self._workspace is not None:
from nanobot.agent.plugins import enabled_agent_plugin_skill_dirs
try: @property
access = current_tool_workspace( def file_edit_workspace(self) -> Path | None:
self._workspace, return self._files.display_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
_LINE_BREAKS = frozenset("\n\r\v\f\x1c\x1d\x1e\x85\u2028\u2029") _LINE_BREAKS = frozenset("\n\r\v\f\x1c\x1d\x1e\x85\u2028\u2029")
@@ -402,30 +273,21 @@ class ReadFileTool(_FsTool):
if not path: if not path:
return ToolResult.error("Error reading file: Unknown path") return ToolResult.error("Error reading file: Unknown path")
if _is_blocked_device(path): try:
return ToolResult.error(f"Error: Reading {path} is blocked (device path that could hang or produce infinite output).") source = self._files.read_file(path)
except FileNotFoundError:
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():
return ToolResult.error(f"Error: File not found: {path}") return ToolResult.error(f"Error: File not found: {path}")
if not fp.is_file(): fp = source.path
return ToolResult.error(f"Error: Not a file: {path}") if source.size > self._MAX_FILE_SIZE_BYTES:
return self._file_too_large(source.size)
file_size = fp.stat().st_size
if file_size > self._MAX_FILE_SIZE_BYTES:
return self._file_too_large(file_size)
if fp.suffix.lower() == ".pdf": 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"}: 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: if opened_size > self._MAX_FILE_SIZE_BYTES:
return self._file_too_large(opened_size) return self._file_too_large(opened_size)
@@ -443,7 +305,7 @@ class ReadFileTool(_FsTool):
bytes_read = len(first) bytes_read = len(first)
# Bound each read without preallocating from a size that # Bound each read without preallocating from a size that
# may have become stale during the receipt check. # 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)) chunk_size = min(self._IMAGE_READ_CHUNK_SIZE, max(self._READ_CHUNK_SIZE, remaining))
while chunk := stream.read(min( while chunk := stream.read(min(
chunk_size, self._MAX_FILE_SIZE_BYTES + 1 - bytes_read, chunk_size, self._MAX_FILE_SIZE_BYTES + 1 - bytes_read,
@@ -592,13 +454,12 @@ class ReadFileTool(_FsTool):
) )
return result return result
def _read_pdf(self, fp: Path, pages: str | None) -> str: def _read_pdf(self, source: ReadableFile, pages: str | None) -> str:
from nanobot.utils.document import PdfPageRangeError, PdfSafetyError, extract_pdf_pages from nanobot.utils.document import PdfPageRangeError, PdfSafetyError
try: try:
extraction = extract_pdf_pages( extraction = source.pdf_pages(
fp, pages,
pages=pages,
max_pages=self._MAX_PDF_PAGES, max_pages=self._MAX_PDF_PAGES,
max_chars=self._MAX_CHARS, max_chars=self._MAX_CHARS,
) )
@@ -610,7 +471,7 @@ class ReadFileTool(_FsTool):
return ToolResult.error(f"Error reading PDF: {e}") return ToolResult.error(f"Error reading PDF: {e}")
if not extraction.text: if not extraction.text:
return f"(PDF has no extractable text: {fp})" return f"(PDF has no extractable text: {source.path})"
result = extraction.text result = extraction.text
if extraction.truncated: if extraction.truncated:
@@ -629,17 +490,16 @@ class ReadFileTool(_FsTool):
def _read_office_doc( def _read_office_doc(
self, self,
fp: Path, file: ReadableFile,
offset: int, offset: int,
limit: int | None, limit: int | None,
) -> str: ) -> str:
from nanobot.utils.document import open_document_line_source fp = file.path
offset = max(1, offset) offset = max(1, offset)
requested_limit = limit or self._DEFAULT_LIMIT requested_limit = limit or self._DEFAULT_LIMIT
source_iterator = None source_iterator = None
try: try:
source = open_document_line_source(fp) source = file.document_lines()
if source is None: if source is None:
return ToolResult.error(f"Error: Unsupported file format: {fp.suffix}") return ToolResult.error(f"Error: Unsupported file format: {fp.suffix}")
source_iterator = source.lines source_iterator = source.lines
@@ -715,7 +575,7 @@ class ReadFileTool(_FsTool):
required=["path", "content"], required=["path", "content"],
) )
) )
class WriteFileTool(_FsTool): class WriteFileTool(_WritableFsTool):
"""Write content to a file.""" """Write content to a file."""
_scopes = {"core", "subagent", "memory"} _scopes = {"core", "subagent", "memory"}
@@ -737,11 +597,10 @@ class WriteFileTool(_FsTool):
raise ValueError("Unknown path") raise ValueError("Unknown path")
if content is None: if content is None:
raise ValueError("Unknown content") raise ValueError("Unknown content")
fp = self._resolve_write(path) target = self.file_edit_target(path)
fp.parent.mkdir(parents=True, exist_ok=True) target.write(content, create_parents=True)
fp.write_text(content, encoding="utf-8", newline="") self._file_states.record_write(target.path)
self._file_states.record_write(fp) return f"Successfully wrote {len(content)} characters to {target.path}"
return f"Successfully wrote {len(content)} characters to {fp}"
except PermissionError as e: except PermissionError as e:
return ToolResult.error(f"Error: {e}") return ToolResult.error(f"Error: {e}")
except Exception as 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"], required=["path", "old_text", "new_text"],
) )
) )
class EditFileTool(_FsTool): class EditFileTool(_WritableFsTool):
"""Edit a file by replacing text with fallback matching.""" """Edit a file by replacing text with fallback matching."""
_scopes = {"core", "subagent", "memory"} _scopes = {"core", "subagent", "memory"}
@@ -1066,7 +925,7 @@ class EditFileTool(_FsTool):
added, deleted = diff.added, diff.deleted added, deleted = diff.added, diff.deleted
action = "add" if created else "update" action = "add" if created else "update"
stats = f" (+{added}/-{deleted})" if added or deleted else "" 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}" text = f"Patch applied:\n- {action} {path}{stats}"
return FileEditResult(text, {resolved_path: diff}) return FileEditResult(text, {resolved_path: diff})
@@ -1090,36 +949,36 @@ class EditFileTool(_FsTool):
if expected_replacements is not None and expected_replacements < 1: if expected_replacements is not None and expected_replacements < 1:
return ToolResult.error("Error: expected_replacements must be >= 1.") return ToolResult.error("Error: expected_replacements must be >= 1.")
fp = self._resolve_write(path) target = self.file_edit_target(path)
file_exists = fp.exists() fp = target.path
file_exists = target.exists()
if file_exists and old_text == new_text: if file_exists and old_text == new_text:
return ToolResult.error("Error: new_text must be different from old_text.") return ToolResult.error("Error: new_text must be different from old_text.")
if not file_exists: if not file_exists:
if old_text == "": if old_text == "":
fp.parent.mkdir(parents=True, exist_ok=True) target.write(new_text, create_parents=True)
fp.write_text(new_text, encoding="utf-8", newline="")
self._file_states.record_write(fp) self._file_states.record_write(fp)
return self._format_summary(fp, "", fp.read_bytes().decode("utf-8"), created=True) return self._format_summary(fp, "", new_text, created=True)
return self._file_not_found_msg(path, fp) return self._file_not_found_msg(path, target)
try: try:
fsize = fp.stat().st_size fsize = target.size()
except OSError: except OSError:
fsize = 0 fsize = 0
if fsize > self._MAX_EDIT_FILE_SIZE: 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.") return ToolResult.error(f"Error: File too large to edit ({fsize / (1024**3):.1f} GiB). Maximum is 1 GiB.")
if old_text == "": if old_text == "":
raw = fp.read_bytes() raw = target.read_bytes()
content = raw.decode("utf-8") content = raw.decode("utf-8")
if content.strip(): if content.strip():
return ToolResult.error(f"Error: Cannot create file — {path} already exists and is not empty.") 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) 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 uses_crlf = b"\r\n" in raw
content = raw.decode("utf-8").replace("\r\n", "\n") content = raw.decode("utf-8").replace("\r\n", "\n")
norm_old = old_text.replace("\r\n", "\n") norm_old = old_text.replace("\r\n", "\n")
@@ -1212,7 +1071,7 @@ class EditFileTool(_FsTool):
if uses_crlf: if uses_crlf:
new_content = new_content.replace("\n", "\r\n") 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) self._file_states.record_write(fp)
return self._format_summary(fp, content, new_content) return self._format_summary(fp, content, new_content)
except PermissionError as e: except PermissionError as e:
@@ -1220,13 +1079,10 @@ class EditFileTool(_FsTool):
except Exception as e: except Exception as e:
return ToolResult.error(f"Error editing file: {e}") return ToolResult.error(f"Error editing file: {e}")
def _file_not_found_msg(self, path: str, fp: Path) -> str: def _file_not_found_msg(self, path: str, target: WritableFile) -> str:
parent = fp.parent siblings = self._files.sibling_files(target)
suggestions: list[str] = [] close = difflib.get_close_matches(target.path.name, siblings, n=3, cutoff=0.6)
if parent.is_dir(): suggestions = [str(target.path.parent / name) for name in close]
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]
parts = [f"Error: File not found: {path}"] parts = [f"Error: File not found: {path}"]
if suggestions: if suggestions:
parts.append("Did you mean: " + ", ".join(suggestions) + "?") parts.append("Did you mean: " + ", ".join(suggestions) + "?")
@@ -1304,32 +1160,21 @@ class ListDirTool(_FsTool):
try: try:
if path is None: if path is None:
raise ValueError("Unknown path") 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 cap = max_entries or self._DEFAULT_MAX
items: list[str] = [] try:
total = 0 listing = self._files.list_directory(
path, recursive=recursive, ignored=self._IGNORE_DIRS, limit=cap,
if recursive: )
for item in sorted(dp.rglob("*")): except FileNotFoundError:
rel = item.relative_to(dp) return ToolResult.error(f"Error: Directory not found: {path}")
if any(p in self._IGNORE_DIRS for p in rel.parts): except NotADirectoryError:
continue return ToolResult.error(f"Error: Not a directory: {path}")
total += 1 total = listing.total
if len(items) < cap: items = [
items.append(f"{rel}/" if item.is_dir() else str(rel)) (f"{item}/" if is_dir else str(item)) if recursive
else: else f"{'📁' if is_dir else '📄'} {item.name}"
for item in sorted(dp.iterdir()): for item, is_dir in listing.entries
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}")
if not items and total == 0: if not items and total == 0:
return f"Directory {path} is empty" return f"Directory {path} is empty"
+63 -58
View File
@@ -5,7 +5,6 @@ from __future__ import annotations
import asyncio import asyncio
import fnmatch import fnmatch
import heapq import heapq
import os
import re import re
import threading import threading
import time 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._search_content import ContentPage, MatchTooLargeError
from nanobot.agent.tools.base import ToolResult from nanobot.agent.tools.base import ToolResult
from nanobot.agent.tools.filesystem import ListDirTool, _FsTool from nanobot.agent.tools.filesystem import ListDirTool, _FsTool
from nanobot.execution.files import FileSearch, NotRegularFileError, ReadableFile
from nanobot.utils.document import ( from nanobot.utils.document import (
DocumentLineSource, DocumentLineSource,
LocatedDocumentLine, LocatedDocumentLine,
PdfPageRangeError, PdfPageRangeError,
open_document_line_source,
) )
_DEFAULT_HEAD_LIMIT = 250 _DEFAULT_HEAD_LIMIT = 250
@@ -211,24 +210,36 @@ class _SearchTool(_FsTool):
return name in cls._IGNORE_DIRS or name.startswith(".verify-") return name in cls._IGNORE_DIRS or name.startswith(".verify-")
def _display_path(self, target: Path, root: Path) -> str: def _display_path(self, target: Path, root: Path) -> str:
workspace = self._display_workspace() workspace = self._files.display_workspace
if workspace: if workspace:
with suppress(ValueError): with suppress(ValueError):
return target.relative_to(workspace).as_posix() return target.relative_to(workspace).as_posix()
return target.relative_to(root).as_posix() return target.relative_to(root).as_posix()
def _iter_files(self, root: Path, budget: _SearchBudget) -> Iterable[Path]: def _iter_files(self, tree: FileSearch, budget: _SearchBudget) -> Iterable[Path]:
if root.is_file(): if not tree.is_directory:
budget.visit_path() budget.visit_path()
yield root yield tree.root
return return
for dirpath, dirnames, filenames in os.walk(root): pending = [tree.root]
while pending:
budget.checkpoint() budget.checkpoint()
for _ in dirnames: current = pending.pop()
budget.visit_path() directories: list[str] = []
dirnames[:] = sorted(d for d in dirnames if not self._ignore_directory(d)) filenames: list[str] = []
current = Path(dirpath) 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): for filename in sorted(filenames):
budget.visit_path() budget.visit_path()
yield current / filename yield current / filename
@@ -310,6 +321,7 @@ class FindFilesTool(_SearchTool):
def _push_directory_entries( def _push_directory_entries(
self, self,
tree: FileSearch,
directory: Path, directory: Path,
root: Path, root: Path,
frontier: list[tuple[str, int, _FindFilesEntry]], frontier: list[tuple[str, int, _FindFilesEntry]],
@@ -318,24 +330,15 @@ class FindFilesTool(_SearchTool):
) -> int: ) -> int:
budget.checkpoint() budget.checkpoint()
try: try:
with os.scandir(directory) as entries: for raw_entry in tree.entries(directory):
for raw_entry in entries: budget.visit_path()
budget.visit_path() is_dir = raw_entry.is_directory
try: if raw_entry.is_directory_link or (is_dir and self._ignore_directory(raw_entry.name)):
is_dir = raw_entry.is_dir(follow_symlinks=False) continue
# os.walk yields special files and broken file symlinks, entry = self._entry(directory / raw_entry.name, root, is_dir=is_dir)
# but does not descend into directory symlinks by default. sort_path = entry.display_path + ("/" if is_dir else "")
if not is_dir and raw_entry.is_symlink() and raw_entry.is_dir(): heapq.heappush(frontier, (sort_path, sequence, entry))
continue sequence += 1
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
except OSError: except OSError:
# os.walk silently skips directories that cannot be listed. Preserve # os.walk silently skips directories that cannot be listed. Preserve
# that behavior while still allowing cancellation and budget errors # that behavior while still allowing cancellation and budget errors
@@ -345,13 +348,14 @@ class FindFilesTool(_SearchTool):
def _iter_paths( def _iter_paths(
self, self,
root: Path, tree: FileSearch,
*, *,
include_dirs: bool, include_dirs: bool,
budget: _SearchBudget, budget: _SearchBudget,
) -> Iterable[_FindFilesEntry]: ) -> Iterable[_FindFilesEntry]:
budget.checkpoint() budget.checkpoint()
if root.is_file(): root = tree.root
if not tree.is_directory:
budget.visit_path() budget.visit_path()
yield self._entry(root, root.parent, is_dir=False) yield self._entry(root, root.parent, is_dir=False)
return return
@@ -360,7 +364,7 @@ class FindFilesTool(_SearchTool):
yield self._entry(root, root, is_dir=True) yield self._entry(root, root, is_dir=True)
frontier: list[tuple[str, int, _FindFilesEntry]] = [] 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: while frontier:
budget.checkpoint() budget.checkpoint()
_, _, entry = heapq.heappop(frontier) _, _, entry = heapq.heappop(frontier)
@@ -368,6 +372,7 @@ class FindFilesTool(_SearchTool):
if include_dirs: if include_dirs:
yield entry yield entry
sequence = self._push_directory_entries( sequence = self._push_directory_entries(
tree,
entry.path, entry.path,
root, root,
frontier, frontier,
@@ -444,10 +449,11 @@ class FindFilesTool(_SearchTool):
started_at = time.monotonic() started_at = time.monotonic()
if cancelled.is_set(): if cancelled.is_set():
raise _SearchCancelledError raise _SearchCancelledError
target = self._resolve(path or ".") try:
if not target.exists(): tree = self._files.search_tree(path or ".")
except FileNotFoundError:
return ToolResult.error(f"Error: Path not found: {path}") 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}") return ToolResult.error(f"Error: Unsupported path: {path}")
if glob: if glob:
@@ -469,7 +475,7 @@ class FindFilesTool(_SearchTool):
def matching_entries() -> Iterator[tuple[str, float]]: def matching_entries() -> Iterator[tuple[str, float]]:
for entry in self._iter_paths( for entry in self._iter_paths(
target, tree,
include_dirs=include_dirs, include_dirs=include_dirs,
budget=budget, budget=budget,
): ):
@@ -483,7 +489,7 @@ class FindFilesTool(_SearchTool):
mtime = 0.0 mtime = 0.0
if sort == "modified": if sort == "modified":
try: try:
mtime = entry.path.stat().st_mtime mtime = tree.modified(entry.path)
except OSError: except OSError:
pass pass
suffix = "/" if entry.is_dir else "" suffix = "/" if entry.is_dir else ""
@@ -627,12 +633,14 @@ class GrepTool(_SearchTool):
} }
@staticmethod @staticmethod
def _open_source(path: Path, pages: str | None, max_bytes: int) -> DocumentLineSource | None: def _open_source(source: ReadableFile, pages: str | None, max_bytes: int) -> DocumentLineSource | None:
if path.suffix.lower() in _DOCUMENT_EXTENSIONS: if source.path.suffix.lower() in _DOCUMENT_EXTENSIONS:
return open_document_line_source(path, pages=pages) return source.document_lines(pages=pages)
with path.open("rb") as file: with source.open() as (file, size):
if size > max_bytes:
return None
raw = file.read(max_bytes + 1) raw = file.read(max_bytes + 1)
if _is_binary(raw): if len(raw) > max_bytes or _is_binary(raw):
return None return None
try: try:
content = raw.decode("utf-8") content = raw.decode("utf-8")
@@ -711,10 +719,11 @@ class GrepTool(_SearchTool):
budget.checkpoint() budget.checkpoint()
if glob: if glob:
_glob_patterns(glob) _glob_patterns(glob)
target = self._resolve(path or ".") try:
if not target.exists(): tree = self._files.search_tree(path or ".")
except FileNotFoundError:
return ToolResult.error(f"Error: Path not found: {path}") 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}") return ToolResult.error(f"Error: Unsupported path: {path}")
flags = re.IGNORECASE if case_insensitive else 0 flags = re.IGNORECASE if case_insensitive else 0
@@ -739,12 +748,12 @@ class GrepTool(_SearchTool):
document_continuations: list[str] = [] document_continuations: list[str] = []
counts: dict[str, int] = {} counts: dict[str, int] = {}
file_mtimes: dict[str, float] = {} 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 = ( 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() rel_path = file_path.relative_to(root).as_posix()
if glob and not _match_glob(rel_path, file_path.name, glob): if glob and not _match_glob(rel_path, file_path.name, glob):
continue continue
@@ -753,21 +762,17 @@ class GrepTool(_SearchTool):
display_path = self._display_path(file_path, root) display_path = self._display_path(file_path, root)
try: try:
file_size = file_path.stat().st_size file = tree.read_file(file_path)
except OSError: except OSError:
skipped_binary += 1 skipped_binary += 1
continue continue
if file_size > max_file_bytes: if file.size > max_file_bytes:
skipped_large += 1 skipped_large += 1
continue continue
try:
mtime = file_path.stat().st_mtime
except OSError:
mtime = 0.0
source_iterator: Iterator[LocatedDocumentLine] | None = None 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: try:
source = self._open_source(file_path, pages, max_file_bytes) source = self._open_source(file, pages, max_file_bytes)
if source is None: if source is None:
skipped_binary += 1 skipped_binary += 1
continue continue
@@ -795,7 +800,7 @@ class GrepTool(_SearchTool):
except Exception as e: except Exception as e:
if not is_document: if not is_document:
raise raise
if target.is_file(): if not tree.is_directory:
if isinstance(e, PdfPageRangeError): if isinstance(e, PdfPageRangeError):
return ToolResult.error( return ToolResult.error(
f"Error: Invalid PDF page range '{pages}': {e!s}." f"Error: Invalid PDF page range '{pages}': {e!s}."
@@ -811,7 +816,7 @@ class GrepTool(_SearchTool):
if close is not None: if close is not None:
close() close()
if file_had_match: if file_had_match:
file_mtimes[display_path] = mtime file_mtimes[display_path] = file.modified
if content_page.stopped: if content_page.stopped:
break 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 os
import re
import stat import stat
from collections.abc import Generator from collections.abc import Callable, Generator, Iterable
from contextlib import contextmanager from contextlib import AbstractContextManager, contextmanager
from dataclasses import dataclass
from pathlib import Path 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): class NotRegularFileError(OSError):
@@ -13,7 +24,7 @@ class NotRegularFileError(OSError):
@contextmanager @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. """Own one descriptor for the entire read and report its initial size.
Callers must resolve the path under the current access policy first. Callers must 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): if not stat.S_ISREG(opened.st_mode):
raise NotRegularFileError raise NotRegularFileError
yield stream, opened.st_size 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 dataclasses import dataclass
from itertools import groupby, islice from itertools import groupby, islice
from pathlib import Path 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 rapidfuzz.distance import Indel, Opcode, Opcodes
from nanobot.execution.files import FileSnapshot, WritableFile
TRACKED_FILE_EDIT_TOOLS = frozenset({"write_file", "edit_file", "apply_patch"}) TRACKED_FILE_EDIT_TOOLS = frozenset({"write_file", "edit_file", "apply_patch"})
_MAX_SNAPSHOT_BYTES = 2 * 1024 * 1024 _MAX_SNAPSHOT_BYTES = 2 * 1024 * 1024
_MAX_DIFF_LINES = 500 _MAX_DIFF_LINES = 500
@@ -16,33 +18,26 @@ _MAX_DIFF_LINE_CHARS = 1200
_DIFF_CONTEXT_LINES = 3 _DIFF_CONTEXT_LINES = 3
@dataclass(slots=True) @runtime_checkable
class FileSnapshot: class FileEditSource(Protocol):
path: Path def file_edit_target(self, path: str) -> WritableFile: ...
exists: bool
text: str | None
unreadable: bool = False
binary: bool = False
oversized: bool = False
@property @property
def countable(self) -> bool: def file_edit_workspace(self) -> Path | None: ...
return (
self.text is not None
and not self.binary
and not self.oversized
and not self.unreadable
)
@dataclass(slots=True) @dataclass(slots=True)
class FileEditTracker: class FileEditTracker:
call_id: str call_id: str
tool: str tool: str
path: Path target: WritableFile
display_path: str display_path: str
before: FileSnapshot before: FileSnapshot
@property
def path(self) -> Path:
return self.target.path
@dataclass(slots=True) @dataclass(slots=True)
class FileDiff: class FileDiff:
@@ -162,23 +157,6 @@ def display_file_edit_path(path: Path, workspace: Path | None) -> str:
return path.as_posix() 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( def build_unified_diff_payload(
@@ -330,105 +308,43 @@ def prepare_file_edit_trackers(
) -> list[FileEditTracker]: ) -> list[FileEditTracker]:
if not isinstance(params, dict) or not is_file_edit_tool(tool_name): if not isinstance(params, dict) or not is_file_edit_tool(tool_name):
return [] return []
paths = resolve_file_edit_paths(tool_name, tool, workspace, params) if not isinstance(tool, FileEditSource):
display_workspace = _display_workspace(tool, workspace) return []
display_workspace = tool.file_edit_workspace or workspace
trackers: list[FileEditTracker] = [] trackers: list[FileEditTracker] = []
seen: set[Path] = set() seen: set[Path] = set()
for path in paths: for raw_path in _file_edit_paths(tool_name, params):
try: try:
resolved = path.resolve() target = tool.file_edit_target(raw_path)
except Exception: except (OSError, RuntimeError, ValueError):
resolved = path
if resolved in seen:
continue continue
seen.add(resolved) if target.path in seen:
before = read_file_snapshot(path) continue
seen.add(target.path)
trackers.append(FileEditTracker( trackers.append(FileEditTracker(
call_id=str(call_id or ""), call_id=str(call_id or ""),
tool=tool_name, tool=tool_name,
path=path, target=target,
display_path=display_file_edit_path(path, display_workspace), display_path=display_file_edit_path(target.path, display_workspace),
before=before, before=target.snapshot(_MAX_SNAPSHOT_BYTES),
)) ))
return trackers return trackers
def resolve_file_edit_paths( def _file_edit_paths(tool_name: str, params: dict[str, Any]) -> Iterator[str]:
tool_name: str, if tool_name != "apply_patch":
tool: Any, path = params.get("path")
workspace: Path | None, if isinstance(path, str) and path.strip():
params: dict[str, Any] | None, yield path
) -> list[Path]: return
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 []
edits = params.get("edits") edits = params.get("edits")
if not isinstance(edits, list): if params.get("dry_run") is True or not isinstance(edits, list):
return [] return
patch_edits = cast(list[Any], edits) for edit in cast(list[object], edits):
paths: list[Path] = [] if isinstance(edit, dict):
seen: set[Path] = set() path = cast(dict[str, object], edit).get("path")
for edit in patch_edits: if isinstance(path, str) and (path := path.strip()) and "\0" not in path:
if not isinstance(edit, dict): yield path
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
def build_file_edit_start_event(tracker: FileEditTracker) -> dict[str, Any]: 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, diff: FileDiff | None = None,
) -> dict[str, Any]: ) -> dict[str, Any]:
after = read_file_snapshot(tracker.path) after = tracker.target.snapshot(_MAX_SNAPSHOT_BYTES)
diff_payload: dict[str, Any] | None = None diff_payload: dict[str, Any] | None = None
if ( if (
tracker.before.countable and after.countable tracker.before.countable and after.countable
+6
View File
@@ -119,6 +119,12 @@ IMPORT_RULES = (
("nanobot.execution",), ("nanobot.execution",),
(*_ADAPTERS, "nanobot.agent", "nanobot.session"), (*_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( ImportRule(
"websocket-transport", "websocket-transport",
("nanobot.channels.websocket.runtime",), ("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() media_dir.mkdir()
csv_path = media_dir / "report.csv" csv_path = media_dir / "report.csv"
csv_path.write_text("name,value\nnanobot,1", encoding="utf-8") 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( loop = _make_loop(
workspace, 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.llm_usage.context import llm_usage_source
from nanobot.providers.base import GenerationSettings, LLMProvider, LLMResponse, ToolCallRequest 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 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] spec = manager.runner.run.call_args.args[0]
assert spec.workspace == project assert spec.workspace == project
assert spec.tools.get("read_file")._workspace == agent_workspace.resolve() (project / "project.txt").write_text("project document", encoding="utf-8")
assert spec.tools.get("read_file")._restrict_to_workspace is True (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 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() media.mkdir()
target = media / "demo.md" target = media / "demo.md"
target.write_text("before\n", encoding="utf-8") 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) tool = ApplyPatchTool(workspace=workspace, allowed_dir=workspace)
result = asyncio.run( 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.asyncio
@pytest.mark.parametrize("newline", ["\n", "\r\n", "\r"]) @pytest.mark.parametrize("newline", ["\n", "\r\n", "\r"])
@pytest.mark.parametrize("operation", ["write", "edit_new", "edit_empty"]) @pytest.mark.parametrize("operation", ["write", "edit_new", "edit_empty"])
@@ -396,7 +417,7 @@ class TestWorkspaceRestriction:
media_file = media_dir / "photo.txt" media_file = media_dir / "photo.txt"
media_file.write_text("shared media", encoding="utf-8") 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) tool = ReadFileTool(workspace=workspace, allowed_dir=workspace)
result = await tool.execute(path=str(media_file)) result = await tool.execute(path=str(media_file))
@@ -410,7 +431,7 @@ class TestWorkspaceRestriction:
media_dir = tmp_path / "media" media_dir = tmp_path / "media"
media_dir.mkdir() 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) tool = WriteFileTool(workspace=workspace, allowed_dir=workspace)
result = await tool.execute(path=str(media_dir / "hack.txt"), content="pwned") 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) return self.stream.seek(*args)
monkeypatch.setattr( monkeypatch.setattr(
"nanobot.agent.tools.filesystem.os.fdopen", "nanobot.execution.files.os.fdopen",
lambda *args, **kwargs: CountingStream(real_fdopen(*args, **kwargs)), lambda *args, **kwargs: CountingStream(real_fdopen(*args, **kwargs)),
) )
visible = {} if case == "not_visible" else {"read-1": first} visible = {} if case == "not_visible" else {"read-1": first}
@@ -807,7 +807,7 @@ class TestBoundedTextReads:
return chunk return chunk
monkeypatch.setattr( monkeypatch.setattr(
"nanobot.agent.tools.filesystem.os.fdopen", "nanobot.execution.files.os.fdopen",
lambda *args, **kwargs: GrowingStream(real_fdopen(*args, **kwargs)), lambda *args, **kwargs: GrowingStream(real_fdopen(*args, **kwargs)),
) )
result = await tool.execute(path=str(f)) result = await tool.execute(path=str(f))
@@ -886,7 +886,7 @@ class TestBoundedTextReads:
return chunk return chunk
monkeypatch.setattr( monkeypatch.setattr(
"nanobot.agent.tools.filesystem.os.fdopen", "nanobot.execution.files.os.fdopen",
lambda *args, **kwargs: ChangeAfterPrecheck(real_fdopen(*args, **kwargs)), lambda *args, **kwargs: ChangeAfterPrecheck(real_fdopen(*args, **kwargs)),
) )
with file_state.file_read_context("read-2", lambda: {"read-1": first}): with file_state.file_read_context("read-2", lambda: {"read-1": first}):
@@ -932,7 +932,7 @@ class TestBoundedTextReads:
return chunk return chunk
monkeypatch.setattr( monkeypatch.setattr(
"nanobot.agent.tools.filesystem.os.fdopen", "nanobot.execution.files.os.fdopen",
lambda *args, **kwargs: ChangeAfterPrecheck(real_fdopen(*args, **kwargs)), lambda *args, **kwargs: ChangeAfterPrecheck(real_fdopen(*args, **kwargs)),
) )
tracemalloc.start() tracemalloc.start()
@@ -972,7 +972,7 @@ class TestBoundedTextReads:
return chunk return chunk
monkeypatch.setattr( monkeypatch.setattr(
"nanobot.agent.tools.filesystem.os.fdopen", "nanobot.execution.files.os.fdopen",
lambda *args, **kwargs: GrowingStream(real_fdopen(*args, **kwargs)), lambda *args, **kwargs: GrowingStream(real_fdopen(*args, **kwargs)),
) )
with file_state.file_read_context("read-2", lambda: {"read-1": first}): with file_state.file_read_context("read-2", lambda: {"read-1": first}):
@@ -1013,7 +1013,7 @@ class TestBoundedTextReads:
tool = ReadFileTool() tool = ReadFileTool()
try: try:
with monkeypatch.context() as scoped: 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)) result = await tool.execute(path=str(f))
finally: finally:
try: 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" 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 @pytest.mark.asyncio
async def test_find_files_cancellation_stops_worker_scan( async def test_find_files_cancellation_stops_worker_scan(
tmp_path: Path, 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) tool = FindFilesTool(workspace=tmp_path, allowed_dir=tmp_path)
visited: list[str] = [] 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 del include_dirs
for path in paths: for path in paths:
budget.checkpoint() budget.checkpoint()
visited.append(path.name) 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) monkeypatch.setattr(tool, "_iter_paths", ordered_iter_paths)
result = await tool.execute(path=".", head_limit=1) 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) tool = GrepTool(workspace=tmp_path)
started, stopped = threading.Event(), threading.Event() started, stopped = threading.Event(), threading.Event()
def blocking_iter_files(root, budget): def blocking_iter_files(tree, budget):
started.set() started.set()
try: try:
if not budget.cancelled.wait(timeout=2): if not budget.cancelled.wait(timeout=2):
raise TimeoutError("worker did not receive cancellation") raise TimeoutError("worker did not receive cancellation")
budget.checkpoint() budget.checkpoint()
yield root / "unreachable.txt" yield tree.root / "unreachable.txt"
finally: finally:
stopped.set() stopped.set()
@@ -1061,7 +1102,7 @@ async def test_grep_closes_document_stream_and_preserves_locators(tmp_path, monk
closed.append(True) closed.append(True)
monkeypatch.setattr( 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"), lambda *_args, **_kwargs: DocumentLineSource(document_lines(), "pages=2-3"),
) )
result = await GrepTool(workspace=tmp_path).execute( result = await GrepTool(workspace=tmp_path).execute(
+19 -28
View File
@@ -2,10 +2,11 @@ from __future__ import annotations
import shutil import shutil
from dataclasses import fields from dataclasses import fields
from pathlib import Path
from typing import Any from typing import Any
from unittest.mock import MagicMock from unittest.mock import MagicMock
import pytest
from nanobot.agent.tools.base import Tool from nanobot.agent.tools.base import Tool
from nanobot.agent.tools.context import ToolContext from nanobot.agent.tools.context import ToolContext
from nanobot.agent.tools.loader import _SKIP_MODULES, ToolLoader 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 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 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 = MagicMock()
mock_config.restrict_to_workspace = False mock_config.restrict_to_workspace = restrict
mock_config.exec.sandbox = "" mock_config.exec.sandbox = sandbox
ctx = ToolContext(config=mock_config, workspace="/tmp/test") tool = ReadFileTool.create(ToolContext(config=mock_config, workspace=str(workspace)))
tool = ReadFileTool.create(ctx) assert "inside" in await tool.execute(path="inside.txt")
assert isinstance(tool, ReadFileTool) outside = await tool.execute(path="../outside.txt")
assert tool._workspace == Path("/tmp/test") if restrict or sandbox:
assert outside.is_error
assert "outside contents" not in outside
def test_fs_tool_create_respects_restrict_to_workspace(): else:
from nanobot.agent.tools.filesystem import ReadFileTool assert "outside contents" in outside
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")
async def test_message_tool_create(): 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_file_edit_start_event,
build_unified_diff_payload, build_unified_diff_payload,
prepare_file_edit_trackers, 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"}, params={"path": "data.bin", "old_text": "before", "new_text": "after"},
) )
[tracker] = trackers [tracker] = trackers
assert not read_file_snapshot(target).countable assert not tracker.before.countable
target.write_bytes(b"\x00\x01after") target.write_bytes(b"\x00\x01after")
event = build_file_edit_end_event(tracker) event = build_file_edit_end_event(tracker)
assert event["binary"] is True 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, workspace=tmp_path,
params={"path": "created-by-shell.txt"}, 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"},
) == []