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 pathlib import Path
from typing import Any, cast
from typing import Any
from nanobot.agent.hook import (
AgentHook,
@@ -46,15 +46,14 @@ class FileEditActivityHook(AgentHook):
tool: Any,
params: Any,
) -> None:
if self._publish is None or not isinstance(params, dict):
if self._publish is None:
return
typed_params = cast(dict[str, Any], params)
trackers = prepare_file_edit_trackers(
call_id=tool_call.id,
tool_name=tool_call.name,
tool=tool,
workspace=self._workspace,
params=typed_params,
params=params,
)
if not trackers:
return
+17 -6
View File
@@ -1,5 +1,6 @@
from __future__ import annotations
from collections.abc import Iterator, Mapping
from typing import Any, cast
from nanobot.agent.tools.base import ToolResult, tool_parameters
@@ -19,7 +20,9 @@ class _PatchError(ValueError):
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()
if not normalized:
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."
)
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(
self,
edits: list[object] | None = None,
@@ -106,14 +120,11 @@ class ApplyPatchTool(_WritableFsTool):
if not isinstance(edit_value, dict):
raise _PatchError("each edit must be an object")
edit = cast(dict[str, Any], edit_value)
raw_path = edit.get("path")
if not isinstance(raw_path, str):
raise _PatchError("path required for edit")
path = _validate_patch_path(raw_path)
path = _validate_patch_path(edit.get("path"))
action = edit.get("action")
if not isinstance(action, str):
raise _PatchError(f"action required for edit: {path}")
source = self.file_edit_target(path)
source = self._files.edit_target(path)
if action == "add":
new_text = edit.get("new_text")
+14 -4
View File
@@ -4,6 +4,7 @@ import codecs
import difflib
import hashlib
import mimetypes
from collections.abc import Iterator, Mapping
from copy import deepcopy
from dataclasses import dataclass
from pathlib import Path
@@ -100,8 +101,17 @@ class _FsTool(Tool):
class _WritableFsTool(_FsTool):
"""Expose the same write target to execution and edit activity tracking."""
def file_edit_target(self, path: str) -> WritableFile:
return self._files.edit_target(path)
def _file_edit_paths(self, params: Mapping[str, object]) -> Iterator[str]:
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
def file_edit_workspace(self) -> Path | None:
@@ -598,7 +608,7 @@ class WriteFileTool(_WritableFsTool):
raise ValueError("Unknown path")
if content is None:
raise ValueError("Unknown content")
target = self.file_edit_target(path)
target = self._files.edit_target(path)
target.write(content, create_parents=True)
self._file_states.record_write(target.path)
return f"Successfully wrote {len(content)} characters to {target.path}"
@@ -950,7 +960,7 @@ class EditFileTool(_WritableFsTool):
if expected_replacements is not None and expected_replacements < 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
file_exists = target.exists()
if file_exists and old_text == new_text:
+8 -33
View File
@@ -1,7 +1,7 @@
from __future__ import annotations
import re
from collections.abc import Iterable, Iterator
from collections.abc import Iterable, Iterator, Mapping
from dataclasses import dataclass
from itertools import groupby, islice
from pathlib import Path
@@ -11,7 +11,6 @@ from rapidfuzz.distance import Indel, Opcode, Opcodes
from nanobot.execution.files import FileSnapshot, WritableFile
TRACKED_FILE_EDIT_TOOLS = frozenset({"write_file", "edit_file", "apply_patch"})
_MAX_SNAPSHOT_BYTES = 2 * 1024 * 1024
_MAX_DIFF_LINES = 500
_MAX_DIFF_LINE_CHARS = 1200
@@ -20,7 +19,9 @@ _DIFF_CONTEXT_LINES = 3
@runtime_checkable
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
def file_edit_workspace(self) -> Path | None: ...
@@ -144,10 +145,6 @@ class FileEditResult(str):
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:
if workspace is not None:
try:
@@ -302,22 +299,16 @@ def prepare_file_edit_trackers(
*,
call_id: str,
tool_name: str,
tool: Any,
tool: object,
workspace: Path | None,
params: dict[str, Any] | None,
params: object,
) -> list[FileEditTracker]:
if not isinstance(params, dict) or not is_file_edit_tool(tool_name):
return []
if not isinstance(tool, FileEditSource):
if not isinstance(params, dict) or not isinstance(tool, FileEditSource):
return []
display_workspace = tool.file_edit_workspace or workspace
trackers: list[FileEditTracker] = []
seen: set[Path] = set()
for raw_path in _file_edit_paths(tool_name, params):
try:
target = tool.file_edit_target(raw_path)
except (OSError, RuntimeError, ValueError):
continue
for target in tool.file_edit_targets(cast(dict[str, object], params)):
if target.path in seen:
continue
seen.add(target.path)
@@ -331,22 +322,6 @@ def prepare_file_edit_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]:
return _event_payload(
tracker,
+12 -8
View File
@@ -57,13 +57,21 @@ def _attach_webui_runtime_events(loop: AgentLoop, bus: MessageBus) -> None:
class TestToolEventProgress:
@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)
target = tmp_path / "foo.txt"
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(
id="call-write",
name="write_file",
name=tool_name,
arguments={"path": "foo.txt", "content": "new\nextra\n"},
)
calls = iter([
@@ -71,11 +79,6 @@ class TestToolEventProgress:
LLMResponse(content="Done", tool_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] = []
async def on_progress(
@@ -95,11 +98,12 @@ class TestToolEventProgress:
)
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 file_events[0] == {
"version": 1,
"call_id": "call-write",
"tool": "write_file",
"tool": tool_name,
"path": "foo.txt",
"absolute_path": (tmp_path / "foo.txt").resolve().as_posix(),
"phase": "start",