refactor(files): observe authorized edit targets by capability

This commit is contained in:
Xubin Ren committed 2026-11-14 22:09:21 +08:00
1 parent 436ba1617c
commit f24383771d
5 files changed
+54 -55

No files matched your search

+3 -4
View File
@@ -1,7 +1,7 @@
from __future__ import annotations from __future__ import annotations
from pathlib import Path from pathlib import Path
from typing import Any, cast from typing import Any
from nanobot.agent.hook import ( from nanobot.agent.hook import (
AgentHook, AgentHook,
@@ -46,15 +46,14 @@ class FileEditActivityHook(AgentHook):
tool: Any, tool: Any,
params: Any, params: Any,
) -> None: ) -> None:
if self._publish is None or not isinstance(params, dict): if self._publish is None:
return return
typed_params = cast(dict[str, Any], params)
trackers = prepare_file_edit_trackers( trackers = prepare_file_edit_trackers(
call_id=tool_call.id, call_id=tool_call.id,
tool_name=tool_call.name, tool_name=tool_call.name,
tool=tool, tool=tool,
workspace=self._workspace, workspace=self._workspace,
params=typed_params, params=params,
) )
if not trackers: if not trackers:
return return
+17 -6
View File
@@ -1,5 +1,6 @@
from __future__ import annotations from __future__ import annotations
from collections.abc import Iterator, Mapping
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
@@ -19,7 +20,9 @@ class _PatchError(ValueError):
pass pass
def _validate_patch_path(path: str) -> str: def _validate_patch_path(path: object) -> str:
if not isinstance(path, str):
raise _PatchError("path required for edit")
normalized = path.strip() normalized = path.strip()
if not normalized: if not normalized:
raise _PatchError("patch path cannot be empty") raise _PatchError("patch path cannot be empty")
@@ -88,6 +91,17 @@ class ApplyPatchTool(_WritableFsTool):
"Use edit_file only for small exact replacements on a single file." "Use edit_file only for small exact replacements on a single file."
) )
def _file_edit_paths(self, params: Mapping[str, object]) -> Iterator[str]:
edits = params.get("edits")
if params.get("dry_run") is True or not isinstance(edits, list):
return
for edit in cast(list[object], edits):
if isinstance(edit, dict):
try:
yield _validate_patch_path(cast(dict[str, object], edit).get("path"))
except _PatchError:
continue
async def execute( async def execute(
self, self,
edits: list[object] | None = None, edits: list[object] | None = None,
@@ -106,14 +120,11 @@ class ApplyPatchTool(_WritableFsTool):
if not isinstance(edit_value, dict): if not isinstance(edit_value, dict):
raise _PatchError("each edit must be an object") raise _PatchError("each edit must be an object")
edit = cast(dict[str, Any], edit_value) edit = cast(dict[str, Any], edit_value)
raw_path = edit.get("path") path = _validate_patch_path(edit.get("path"))
if not isinstance(raw_path, str):
raise _PatchError("path required for edit")
path = _validate_patch_path(raw_path)
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.file_edit_target(path) source = self._files.edit_target(path)
if action == "add": if action == "add":
new_text = edit.get("new_text") new_text = edit.get("new_text")
+14 -4
View File
@@ -4,6 +4,7 @@ import codecs
import difflib import difflib
import hashlib import hashlib
import mimetypes import mimetypes
from collections.abc import Iterator, Mapping
from copy import deepcopy from copy import deepcopy
from dataclasses import dataclass from dataclasses import dataclass
from pathlib import Path from pathlib import Path
@@ -100,8 +101,17 @@ class _FsTool(Tool):
class _WritableFsTool(_FsTool): class _WritableFsTool(_FsTool):
"""Expose the same write target to execution and edit activity tracking.""" """Expose the same write target to execution and edit activity tracking."""
def file_edit_target(self, path: str) -> WritableFile: def _file_edit_paths(self, params: Mapping[str, object]) -> Iterator[str]:
return self._files.edit_target(path) path = params.get("path")
if isinstance(path, str) and path.strip():
yield path
def file_edit_targets(self, params: Mapping[str, object]) -> Iterator[WritableFile]:
for path in self._file_edit_paths(params):
try:
yield self._files.edit_target(path)
except (OSError, RuntimeError, ValueError):
continue # Execution reports the error; activity must not read this target.
@property @property
def file_edit_workspace(self) -> Path | None: def file_edit_workspace(self) -> Path | None:
@@ -598,7 +608,7 @@ class WriteFileTool(_WritableFsTool):
raise ValueError("Unknown path") raise ValueError("Unknown path")
if content is None: if content is None:
raise ValueError("Unknown content") raise ValueError("Unknown content")
target = self.file_edit_target(path) target = self._files.edit_target(path)
target.write(content, create_parents=True) target.write(content, create_parents=True)
self._file_states.record_write(target.path) self._file_states.record_write(target.path)
return f"Successfully wrote {len(content)} characters to {target.path}" return f"Successfully wrote {len(content)} characters to {target.path}"
@@ -950,7 +960,7 @@ class EditFileTool(_WritableFsTool):
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.")
target = self.file_edit_target(path) target = self._files.edit_target(path)
fp = target.path fp = target.path
file_exists = target.exists() file_exists = target.exists()
if file_exists and old_text == new_text: if file_exists and old_text == new_text:
+8 -33
View File
@@ -1,7 +1,7 @@
from __future__ import annotations from __future__ import annotations
import re import re
from collections.abc import Iterable, Iterator from collections.abc import Iterable, Iterator, Mapping
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
@@ -11,7 +11,6 @@ from rapidfuzz.distance import Indel, Opcode, Opcodes
from nanobot.execution.files import FileSnapshot, WritableFile 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_SNAPSHOT_BYTES = 2 * 1024 * 1024
_MAX_DIFF_LINES = 500 _MAX_DIFF_LINES = 500
_MAX_DIFF_LINE_CHARS = 1200 _MAX_DIFF_LINE_CHARS = 1200
@@ -20,7 +19,9 @@ _DIFF_CONTEXT_LINES = 3
@runtime_checkable @runtime_checkable
class FileEditSource(Protocol): class FileEditSource(Protocol):
def file_edit_target(self, path: str) -> WritableFile: ... """A tool that exposes its authorized mutation targets for activity snapshots."""
def file_edit_targets(self, params: Mapping[str, object]) -> Iterable[WritableFile]: ...
@property @property
def file_edit_workspace(self) -> Path | None: ... def file_edit_workspace(self) -> Path | None: ...
@@ -144,10 +145,6 @@ class FileEditResult(str):
return str, (str(self),) return str, (str(self),)
def is_file_edit_tool(tool_name: str | None) -> bool:
return bool(tool_name) and tool_name in TRACKED_FILE_EDIT_TOOLS
def display_file_edit_path(path: Path, workspace: Path | None) -> str: def display_file_edit_path(path: Path, workspace: Path | None) -> str:
if workspace is not None: if workspace is not None:
try: try:
@@ -302,22 +299,16 @@ def prepare_file_edit_trackers(
*, *,
call_id: str, call_id: str,
tool_name: str, tool_name: str,
tool: Any, tool: object,
workspace: Path | None, workspace: Path | None,
params: dict[str, Any] | None, params: object,
) -> list[FileEditTracker]: ) -> list[FileEditTracker]:
if not isinstance(params, dict) or not is_file_edit_tool(tool_name): if not isinstance(params, dict) or not isinstance(tool, FileEditSource):
return []
if not isinstance(tool, FileEditSource):
return [] return []
display_workspace = tool.file_edit_workspace or workspace display_workspace = tool.file_edit_workspace or workspace
trackers: list[FileEditTracker] = [] trackers: list[FileEditTracker] = []
seen: set[Path] = set() seen: set[Path] = set()
for raw_path in _file_edit_paths(tool_name, params): for target in tool.file_edit_targets(cast(dict[str, object], params)):
try:
target = tool.file_edit_target(raw_path)
except (OSError, RuntimeError, ValueError):
continue
if target.path in seen: if target.path in seen:
continue continue
seen.add(target.path) seen.add(target.path)
@@ -331,22 +322,6 @@ def prepare_file_edit_trackers(
return trackers return trackers
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 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]: def build_file_edit_start_event(tracker: FileEditTracker) -> dict[str, Any]:
return _event_payload( return _event_payload(
tracker, tracker,
+12 -8
View File
@@ -57,13 +57,21 @@ def _attach_webui_runtime_events(loop: AgentLoop, bus: MessageBus) -> None:
class TestToolEventProgress: class TestToolEventProgress:
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_write_file_emits_file_edit_progress(self, tmp_path: Path) -> None: @pytest.mark.parametrize("tool_name", ["write_file", "workspace_write"])
async def test_write_file_emits_file_edit_progress(self, tmp_path: Path, tool_name: str) -> None:
loop = _make_loop(tmp_path) loop = _make_loop(tmp_path)
target = tmp_path / "foo.txt" target = tmp_path / "foo.txt"
target.write_text("old\n", encoding="utf-8") target.write_text("old\n", encoding="utf-8")
class NamedWriteTool(WriteFileTool):
@property
def name(self) -> str:
return tool_name
loop.tools.register(NamedWriteTool(workspace=tmp_path))
tool_call = ToolCallRequest( tool_call = ToolCallRequest(
id="call-write", id="call-write",
name="write_file", name=tool_name,
arguments={"path": "foo.txt", "content": "new\nextra\n"}, arguments={"path": "foo.txt", "content": "new\nextra\n"},
) )
calls = iter([ calls = iter([
@@ -71,11 +79,6 @@ class TestToolEventProgress:
LLMResponse(content="Done", tool_calls=[]), LLMResponse(content="Done", tool_calls=[]),
]) ])
loop.provider.chat_stream_with_retry = AsyncMock(side_effect=lambda *a, **kw: next(calls)) loop.provider.chat_stream_with_retry = AsyncMock(side_effect=lambda *a, **kw: next(calls))
loop.tools.get_definitions = MagicMock(return_value=[])
tool = WriteFileTool(workspace=tmp_path)
loop.tools.prepare_call = MagicMock(
return_value=(tool, {"path": "foo.txt", "content": "new\nextra\n"}, None),
)
file_events: list[dict] = [] file_events: list[dict] = []
async def on_progress( async def on_progress(
@@ -95,11 +98,12 @@ class TestToolEventProgress:
) )
assert result.final_content == "Done" assert result.final_content == "Done"
assert target.read_text(encoding="utf-8") == "new\nextra\n"
assert [event["phase"] for event in file_events] == ["start", "end"] assert [event["phase"] for event in file_events] == ["start", "end"]
assert file_events[0] == { assert file_events[0] == {
"version": 1, "version": 1,
"call_id": "call-write", "call_id": "call-write",
"tool": "write_file", "tool": tool_name,
"path": "foo.txt", "path": "foo.txt",
"absolute_path": (tmp_path / "foo.txt").resolve().as_posix(), "absolute_path": (tmp_path / "foo.txt").resolve().as_posix(),
"phase": "start", "phase": "start",