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
|
||||
from collections.abc import Awaitable, Callable
|
||||
from contextlib import nullcontext
|
||||
from dataclasses import dataclass, replace
|
||||
from functools import cache
|
||||
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)
|
||||
try:
|
||||
with (
|
||||
file_read_context(tool_call.id, read_results)
|
||||
if tool_call.name == "read_file" else nullcontext()
|
||||
):
|
||||
with file_read_context(tool_call.id, read_results):
|
||||
if tool is not None:
|
||||
result = await tool.execute(**params)
|
||||
else:
|
||||
|
||||
@@ -9,10 +9,10 @@ from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@dataclass(slots=True)
|
||||
class _FileReadContext:
|
||||
call_id: str
|
||||
tool_results: Callable[[], Mapping[str, str]]
|
||||
tool_results: Callable[[], Mapping[str, str]] | None
|
||||
|
||||
|
||||
_current_file_read: ContextVar[_FileReadContext | None] = ContextVar(
|
||||
@@ -24,11 +24,15 @@ _current_file_read: ContextVar[_FileReadContext | None] = ContextVar(
|
||||
def file_read_context(
|
||||
call_id: str, tool_results: Callable[[], Mapping[str, str]],
|
||||
) -> Generator[None]:
|
||||
"""Bind one file read; resolve visible results only when checking a prior read."""
|
||||
token = _current_file_read.set(_FileReadContext(call_id, tool_results))
|
||||
"""Bind call-local receipts without indexing results unless a read needs them."""
|
||||
context = _FileReadContext(call_id, tool_results)
|
||||
token = _current_file_read.set(context)
|
||||
try:
|
||||
yield
|
||||
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)
|
||||
|
||||
|
||||
@@ -60,7 +64,7 @@ class FileStates:
|
||||
offset=offset,
|
||||
limit=limit,
|
||||
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(),
|
||||
)
|
||||
|
||||
@@ -75,7 +79,7 @@ class FileStates:
|
||||
p = str(Path(path).resolve())
|
||||
entry = self._state.get(p)
|
||||
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
|
||||
if entry.offset != offset or entry.limit != limit:
|
||||
return None
|
||||
|
||||
@@ -5,7 +5,6 @@ import difflib
|
||||
import hashlib
|
||||
import mimetypes
|
||||
import os
|
||||
import stat
|
||||
from copy import deepcopy
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
@@ -22,6 +21,7 @@ from nanobot.agent.tools.schema import (
|
||||
StringSchema,
|
||||
tool_parameters_schema,
|
||||
)
|
||||
from nanobot.execution.files import NotRegularFileError, open_regular_file
|
||||
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.helpers import build_image_content_blocks, detect_image_mime
|
||||
@@ -425,17 +425,9 @@ class ReadFileTool(_FsTool):
|
||||
if fp.suffix.lower() in {".docx", ".xlsx", ".pptx"}:
|
||||
return self._read_office_doc(fp, offset, limit)
|
||||
|
||||
# Keep one open file description for detection, hashing, and decoding.
|
||||
# Nonblocking/no-follow flags also avoid opening a swapped-in FIFO or
|
||||
# final symlink on platforms that support them.
|
||||
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)
|
||||
with open_regular_file(fp) as (stream, opened_size):
|
||||
if opened_size > self._MAX_FILE_SIZE_BYTES:
|
||||
return self._file_too_large(opened_size)
|
||||
|
||||
check_previous = not force
|
||||
while True:
|
||||
@@ -485,6 +477,8 @@ class ReadFileTool(_FsTool):
|
||||
# type while the previous receipt was being checked.
|
||||
stream.seek(0)
|
||||
check_previous = False
|
||||
except NotRegularFileError:
|
||||
return ToolResult.error(f"Error: Not a file: {path}")
|
||||
except PermissionError as e:
|
||||
return ToolResult.error(f"Error: {e}")
|
||||
except Exception as e:
|
||||
|
||||
Reference in new issue
Block a user