refactor(tools): separate regular file execution from tool identity
This commit is contained in:
1 parent
8d64e22fbb
commit
c539da9269
6 files changed
+89
-23
No files matched your search
@@ -2,7 +2,6 @@ from __future__ import annotations
|
|||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
from collections.abc import Awaitable, Callable
|
from collections.abc import Awaitable, Callable
|
||||||
from contextlib import nullcontext
|
|
||||||
from dataclasses import dataclass, replace
|
from dataclasses import dataclass, replace
|
||||||
from functools import cache
|
from functools import cache
|
||||||
from typing import Any, cast
|
from typing import Any, cast
|
||||||
@@ -186,10 +185,7 @@ async def _execute_tool_call_inner(
|
|||||||
|
|
||||||
await hook.before_execute_tool(context, tool_call, tool, params)
|
await hook.before_execute_tool(context, tool_call, tool, params)
|
||||||
try:
|
try:
|
||||||
with (
|
with file_read_context(tool_call.id, read_results):
|
||||||
file_read_context(tool_call.id, read_results)
|
|
||||||
if tool_call.name == "read_file" else nullcontext()
|
|
||||||
):
|
|
||||||
if tool is not None:
|
if tool is not None:
|
||||||
result = await tool.execute(**params)
|
result = await tool.execute(**params)
|
||||||
else:
|
else:
|
||||||
|
|||||||
@@ -9,10 +9,10 @@ from dataclasses import dataclass
|
|||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(slots=True)
|
||||||
class _FileReadContext:
|
class _FileReadContext:
|
||||||
call_id: str
|
call_id: str
|
||||||
tool_results: Callable[[], Mapping[str, str]]
|
tool_results: Callable[[], Mapping[str, str]] | None
|
||||||
|
|
||||||
|
|
||||||
_current_file_read: ContextVar[_FileReadContext | None] = ContextVar(
|
_current_file_read: ContextVar[_FileReadContext | None] = ContextVar(
|
||||||
@@ -24,11 +24,15 @@ _current_file_read: ContextVar[_FileReadContext | None] = ContextVar(
|
|||||||
def file_read_context(
|
def file_read_context(
|
||||||
call_id: str, tool_results: Callable[[], Mapping[str, str]],
|
call_id: str, tool_results: Callable[[], Mapping[str, str]],
|
||||||
) -> Generator[None]:
|
) -> Generator[None]:
|
||||||
"""Bind one file read; resolve visible results only when checking a prior read."""
|
"""Bind call-local receipts without indexing results unless a read needs them."""
|
||||||
token = _current_file_read.set(_FileReadContext(call_id, tool_results))
|
context = _FileReadContext(call_id, tool_results)
|
||||||
|
token = _current_file_read.set(context)
|
||||||
try:
|
try:
|
||||||
yield
|
yield
|
||||||
finally:
|
finally:
|
||||||
|
# A tool can spawn a task that inherits this context and outlives the call.
|
||||||
|
# It must not retain the model request or use its read receipts afterward.
|
||||||
|
context.tool_results = None
|
||||||
_current_file_read.reset(token)
|
_current_file_read.reset(token)
|
||||||
|
|
||||||
|
|
||||||
@@ -60,7 +64,7 @@ class FileStates:
|
|||||||
offset=offset,
|
offset=offset,
|
||||||
limit=limit,
|
limit=limit,
|
||||||
content_hash=content_hash,
|
content_hash=content_hash,
|
||||||
call_id=context.call_id if context is not None else None,
|
call_id=context.call_id if context is not None and context.tool_results else None,
|
||||||
result_hash=hashlib.sha256(result.encode("utf-8")).hexdigest(),
|
result_hash=hashlib.sha256(result.encode("utf-8")).hexdigest(),
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -75,7 +79,7 @@ class FileStates:
|
|||||||
p = str(Path(path).resolve())
|
p = str(Path(path).resolve())
|
||||||
entry = self._state.get(p)
|
entry = self._state.get(p)
|
||||||
context = _current_file_read.get()
|
context = _current_file_read.get()
|
||||||
if entry is None or context is None or not entry.call_id:
|
if entry is None or context is None or context.tool_results is None or not entry.call_id:
|
||||||
return None
|
return None
|
||||||
if entry.offset != offset or entry.limit != limit:
|
if entry.offset != offset or entry.limit != limit:
|
||||||
return None
|
return None
|
||||||
|
|||||||
@@ -5,7 +5,6 @@ import difflib
|
|||||||
import hashlib
|
import hashlib
|
||||||
import mimetypes
|
import mimetypes
|
||||||
import os
|
import os
|
||||||
import stat
|
|
||||||
from copy import deepcopy
|
from copy import deepcopy
|
||||||
from dataclasses import dataclass
|
from dataclasses import dataclass
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
@@ -22,6 +21,7 @@ from nanobot.agent.tools.schema import (
|
|||||||
StringSchema,
|
StringSchema,
|
||||||
tool_parameters_schema,
|
tool_parameters_schema,
|
||||||
)
|
)
|
||||||
|
from nanobot.execution.files import NotRegularFileError, open_regular_file
|
||||||
from nanobot.security.workspace_access import current_tool_workspace
|
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
|
||||||
@@ -425,17 +425,9 @@ class ReadFileTool(_FsTool):
|
|||||||
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(fp, offset, limit)
|
||||||
|
|
||||||
# Keep one open file description for detection, hashing, and decoding.
|
with open_regular_file(fp) as (stream, opened_size):
|
||||||
# Nonblocking/no-follow flags also avoid opening a swapped-in FIFO or
|
if opened_size > self._MAX_FILE_SIZE_BYTES:
|
||||||
# final symlink on platforms that support them.
|
return self._file_too_large(opened_size)
|
||||||
flags = os.O_RDONLY | getattr(os, "O_BINARY", 0)
|
|
||||||
flags |= getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_NOFOLLOW", 0)
|
|
||||||
with os.fdopen(os.open(fp, flags), "rb") as stream:
|
|
||||||
opened = os.fstat(stream.fileno())
|
|
||||||
if not stat.S_ISREG(opened.st_mode):
|
|
||||||
return ToolResult.error(f"Error: Not a file: {path}")
|
|
||||||
if opened.st_size > self._MAX_FILE_SIZE_BYTES:
|
|
||||||
return self._file_too_large(opened.st_size)
|
|
||||||
|
|
||||||
check_previous = not force
|
check_previous = not force
|
||||||
while True:
|
while True:
|
||||||
@@ -485,6 +477,8 @@ class ReadFileTool(_FsTool):
|
|||||||
# type while the previous receipt was being checked.
|
# type while the previous receipt was being checked.
|
||||||
stream.seek(0)
|
stream.seek(0)
|
||||||
check_previous = False
|
check_previous = False
|
||||||
|
except NotRegularFileError:
|
||||||
|
return ToolResult.error(f"Error: Not a file: {path}")
|
||||||
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:
|
||||||
|
|||||||
@@ -0,0 +1,29 @@
|
|||||||
|
"""Descriptor-based reads for paths already resolved under workspace policy."""
|
||||||
|
|
||||||
|
import os
|
||||||
|
import stat
|
||||||
|
from collections.abc import Generator
|
||||||
|
from contextlib import contextmanager
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import BinaryIO
|
||||||
|
|
||||||
|
|
||||||
|
class NotRegularFileError(OSError):
|
||||||
|
"""The opened resource is not a regular file."""
|
||||||
|
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def open_regular_file(resolved_path: Path) -> Generator[tuple[BinaryIO, int]]:
|
||||||
|
"""Own one descriptor for the entire read and report its initial size.
|
||||||
|
|
||||||
|
Callers must resolve the path under the current access policy first.
|
||||||
|
Where supported, refuse a swapped-in final symlink and avoid waiting on
|
||||||
|
a swapped-in FIFO. This does not protect ancestor path components.
|
||||||
|
"""
|
||||||
|
flags = os.O_RDONLY | getattr(os, "O_BINARY", 0)
|
||||||
|
flags |= getattr(os, "O_NONBLOCK", 0) | getattr(os, "O_NOFOLLOW", 0)
|
||||||
|
with os.fdopen(os.open(resolved_path, flags), "rb") as stream:
|
||||||
|
opened = os.fstat(stream.fileno())
|
||||||
|
if not stat.S_ISREG(opened.st_mode):
|
||||||
|
raise NotRegularFileError
|
||||||
|
yield stream, opened.st_size
|
||||||
@@ -112,6 +112,11 @@ IMPORT_RULES = (
|
|||||||
ImportRule(
|
ImportRule(
|
||||||
"security-primitives",
|
"security-primitives",
|
||||||
("nanobot.security",),
|
("nanobot.security",),
|
||||||
|
(*_ADAPTERS, "nanobot.agent", "nanobot.execution", "nanobot.session"),
|
||||||
|
),
|
||||||
|
ImportRule(
|
||||||
|
"resource-execution",
|
||||||
|
("nanobot.execution",),
|
||||||
(*_ADAPTERS, "nanobot.agent", "nanobot.session"),
|
(*_ADAPTERS, "nanobot.agent", "nanobot.session"),
|
||||||
),
|
),
|
||||||
ImportRule(
|
ImportRule(
|
||||||
|
|||||||
@@ -121,6 +121,44 @@ async def test_direct_read_without_model_context_never_omits_contents(tmp_path):
|
|||||||
assert "1| alpha" in second
|
assert "1| alpha" in second
|
||||||
|
|
||||||
|
|
||||||
|
async def test_same_file_read_contract_under_two_tool_names(tmp_path):
|
||||||
|
class InspectFileTool(ReadFileTool):
|
||||||
|
@property
|
||||||
|
def name(self) -> str:
|
||||||
|
return "inspect_file"
|
||||||
|
|
||||||
|
workspace = tmp_path / "workspace"
|
||||||
|
workspace.mkdir()
|
||||||
|
(workspace / "data.txt").write_text("alpha\n", encoding="utf-8")
|
||||||
|
(tmp_path / "private.txt").write_text("private contents", encoding="utf-8")
|
||||||
|
states = FileStates()
|
||||||
|
tools = ToolRegistry()
|
||||||
|
for tool_class in (ReadFileTool, InspectFileTool):
|
||||||
|
tools.register(tool_class(workspace=workspace, allowed_dir=workspace, file_states=states))
|
||||||
|
|
||||||
|
async def run(name, call_id, path, messages=None):
|
||||||
|
settled = []
|
||||||
|
await execute_tool_calls(
|
||||||
|
tools, [ToolCallRequest(id=call_id, name=name, arguments={"path": path})],
|
||||||
|
concurrent=False, external_lookup_counts={}, workspace_violation_counts={},
|
||||||
|
hook=AgentHook(), context=AgentHookContext(iteration=0, messages=[]),
|
||||||
|
model_messages=messages, on_settled=AsyncMock(side_effect=settled.extend),
|
||||||
|
)
|
||||||
|
return settled[0].result
|
||||||
|
|
||||||
|
first = await run("inspect_file", "first", "data.txt")
|
||||||
|
assert "1| alpha" in first
|
||||||
|
history = [{"role": "tool", "tool_call_id": "first", "content": first}]
|
||||||
|
for name in ("read_file", "inspect_file"):
|
||||||
|
denied = await run(name, f"{name}-denied", "../private.txt")
|
||||||
|
assert "outside" in denied.lower()
|
||||||
|
assert "private contents" not in denied
|
||||||
|
assert await run(name, f"{name}-repeat", "data.txt", history) == (
|
||||||
|
"[File unchanged since last read: data.txt]"
|
||||||
|
)
|
||||||
|
assert await run("inspect_file", "missing-result", "data.txt") == first
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("operation", ["list_dir", "first_read", "forced_read", "repeat_batch"])
|
@pytest.mark.parametrize("operation", ["list_dir", "first_read", "forced_read", "repeat_batch"])
|
||||||
async def test_only_repeat_reads_scan_model_results_once_per_batch(tmp_path, operation):
|
async def test_only_repeat_reads_scan_model_results_once_per_batch(tmp_path, operation):
|
||||||
tools = _tools(tmp_path)
|
tools = _tools(tmp_path)
|
||||||
|
|||||||
Reference in new issue
Block a user