|
| 1 | +"""Bounded tools over application-selected decoded UTF-8 documents.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import asyncio |
| 6 | +import hashlib |
| 7 | +import os |
| 8 | +import stat |
| 9 | +import tempfile |
| 10 | +from collections.abc import Callable, Mapping, Sequence |
| 11 | +from contextlib import suppress |
| 12 | +from dataclasses import dataclass |
| 13 | +from pathlib import Path |
| 14 | +from typing import TypeVar |
| 15 | + |
| 16 | +from typing_extensions import TypedDict |
| 17 | + |
| 18 | +from agents import ToolOutput, function_tool |
| 19 | + |
| 20 | +PAGE_CHARS = 4096 |
| 21 | +MAX_FILE_BYTES = 16 * 1024 * 1024 |
| 22 | +T = TypeVar("T") |
| 23 | + |
| 24 | + |
| 25 | +class RevisionConflict(ValueError): |
| 26 | + """The caller must read again before continuing or editing.""" |
| 27 | + |
| 28 | + |
| 29 | +class DocumentPage(TypedDict): |
| 30 | + document: str |
| 31 | + revision: str |
| 32 | + offset: int |
| 33 | + text: str |
| 34 | + next_offset: int | None |
| 35 | + |
| 36 | + |
| 37 | +class SearchMatch(TypedDict): |
| 38 | + offset: int |
| 39 | + text: str |
| 40 | + |
| 41 | + |
| 42 | +class SearchPage(TypedDict): |
| 43 | + document: str |
| 44 | + revision: str |
| 45 | + matches: list[SearchMatch] |
| 46 | + next_offset: int | None |
| 47 | + |
| 48 | + |
| 49 | +class SavedDocument(TypedDict): |
| 50 | + document: str |
| 51 | + revision: str |
| 52 | + status: str |
| 53 | + |
| 54 | + |
| 55 | +@dataclass(frozen=True) |
| 56 | +class _Document: |
| 57 | + path: Path |
| 58 | + text: str |
| 59 | + mode: int |
| 60 | + revision: str |
| 61 | + |
| 62 | + |
| 63 | +class SelectedDocuments: |
| 64 | + """The application chooses aliases, paths, and permission to write. |
| 65 | +
|
| 66 | + Supply decoded text, including text extracted from a PDF. Keep the root |
| 67 | + and its parent directories under application control. External writers |
| 68 | + must share an application lock with this owner. |
| 69 | + """ |
| 70 | + |
| 71 | + def __init__( |
| 72 | + self, |
| 73 | + *, |
| 74 | + root: Path, |
| 75 | + selected: Mapping[str, str], |
| 76 | + writable: Sequence[str] = (), |
| 77 | + ) -> None: |
| 78 | + self._root = root.resolve(strict=True) |
| 79 | + self._selected = dict(selected) |
| 80 | + self._writable = frozenset(writable) |
| 81 | + if not self._writable.issubset(self._selected): |
| 82 | + raise ValueError("Writable documents must be selected by the application") |
| 83 | + self._lock = asyncio.Lock() |
| 84 | + |
| 85 | + async def _exclusive(self, operation: Callable[[], T]) -> T: |
| 86 | + async with self._lock: |
| 87 | + worker = asyncio.create_task(asyncio.to_thread(operation)) |
| 88 | + try: |
| 89 | + return await asyncio.shield(worker) |
| 90 | + except asyncio.CancelledError: |
| 91 | + # Join file work before releasing ownership, even after repeated cancellation. |
| 92 | + while not worker.done(): |
| 93 | + with suppress(asyncio.CancelledError): |
| 94 | + await asyncio.wait((worker,)) |
| 95 | + worker.exception() |
| 96 | + raise |
| 97 | + |
| 98 | + def _load(self, alias: str) -> _Document: |
| 99 | + if alias not in self._selected: |
| 100 | + raise ValueError("The application did not select this document") |
| 101 | + path = Path(os.path.abspath(self._root / self._selected[alias])) |
| 102 | + if ( |
| 103 | + path == self._root |
| 104 | + or not path.is_relative_to(self._root) |
| 105 | + or path.resolve(strict=True) != path |
| 106 | + ): |
| 107 | + raise ValueError("Selected document must remain at its selected path") |
| 108 | + flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_NONBLOCK", 0) |
| 109 | + with os.fdopen(os.open(path, flags), "rb") as file: |
| 110 | + details = os.fstat(file.fileno()) |
| 111 | + if not stat.S_ISREG(details.st_mode) or details.st_size > MAX_FILE_BYTES: |
| 112 | + raise ValueError("Select a regular text file of at most 16 MiB") |
| 113 | + content = file.read(MAX_FILE_BYTES + 1) |
| 114 | + if len(content) > MAX_FILE_BYTES: |
| 115 | + raise ValueError("Selected document grew beyond 16 MiB") |
| 116 | + return _Document( |
| 117 | + path, |
| 118 | + content.decode("utf-8"), |
| 119 | + stat.S_IMODE(details.st_mode), |
| 120 | + hashlib.sha256(content).hexdigest(), |
| 121 | + ) |
| 122 | + |
| 123 | + async def read(self, alias: str, offset: int = 0, revision: str | None = None) -> DocumentPage: |
| 124 | + if isinstance(offset, bool) or not isinstance(offset, int) or offset < 0: |
| 125 | + raise ValueError("Offset must be a nonnegative integer") |
| 126 | + |
| 127 | + def read_page() -> DocumentPage: |
| 128 | + document = self._load(alias) |
| 129 | + if revision is not None and revision != document.revision: |
| 130 | + raise RevisionConflict("Stale revision; restart the read") |
| 131 | + end = offset + PAGE_CHARS |
| 132 | + return { |
| 133 | + "document": alias, |
| 134 | + "revision": document.revision, |
| 135 | + "offset": offset, |
| 136 | + "text": document.text[offset:end], |
| 137 | + "next_offset": end if end < len(document.text) else None, |
| 138 | + } |
| 139 | + |
| 140 | + return await self._exclusive(read_page) |
| 141 | + |
| 142 | + async def search( |
| 143 | + self, alias: str, query: str, offset: int = 0, revision: str | None = None |
| 144 | + ) -> SearchPage: |
| 145 | + if not 1 <= len(query) <= 256: |
| 146 | + raise ValueError("Search text must contain 1 to 256 code points") |
| 147 | + page = await self.read(alias, offset, revision) |
| 148 | + matches: list[SearchMatch] = [] |
| 149 | + cursor = 0 |
| 150 | + while cursor <= len(page["text"]) - len(query) and len(matches) < 16: |
| 151 | + found = page["text"].find(query, cursor) |
| 152 | + if found < 0: |
| 153 | + break |
| 154 | + matches.append({"offset": offset + found, "text": page["text"][found : found + 128]}) |
| 155 | + cursor = found + len(query) |
| 156 | + next_offset = ( |
| 157 | + offset + cursor |
| 158 | + if len(matches) == 16 |
| 159 | + else None |
| 160 | + if page["next_offset"] is None |
| 161 | + else offset + len(page["text"]) - len(query) + 1 |
| 162 | + ) |
| 163 | + return { |
| 164 | + "document": alias, |
| 165 | + "revision": page["revision"], |
| 166 | + "matches": matches, |
| 167 | + "next_offset": next_offset, |
| 168 | + } |
| 169 | + |
| 170 | + async def revise( |
| 171 | + self, alias: str, revision: str, old_text: str, new_text: str |
| 172 | + ) -> SavedDocument: |
| 173 | + if alias not in self._writable: |
| 174 | + raise ValueError("The application did not select this document for writing") |
| 175 | + if not old_text or len(old_text) > PAGE_CHARS or len(new_text) > PAGE_CHARS: |
| 176 | + raise ValueError("Select one nonempty edit of at most one page") |
| 177 | + |
| 178 | + def save() -> SavedDocument: |
| 179 | + before = self._load(alias) |
| 180 | + if before.revision != revision: |
| 181 | + raise RevisionConflict("Stale revision; read before editing") |
| 182 | + first = before.text.find(old_text) |
| 183 | + if first < 0 or before.text.find(old_text, first + 1) >= 0: |
| 184 | + raise ValueError("Edit text must occur exactly once") |
| 185 | + after = before.text[:first] + new_text + before.text[first + len(old_text) :] |
| 186 | + content = after.encode("utf-8") |
| 187 | + if len(content) > MAX_FILE_BYTES: |
| 188 | + raise ValueError("Edited document exceeds 16 MiB") |
| 189 | + descriptor, name = tempfile.mkstemp(prefix=".agents-document-", dir=before.path.parent) |
| 190 | + temporary = Path(name) |
| 191 | + try: |
| 192 | + with os.fdopen(descriptor, "wb") as file: |
| 193 | + file.write(content) |
| 194 | + file.flush() |
| 195 | + os.fsync(file.fileno()) |
| 196 | + os.chmod(temporary, before.mode) |
| 197 | + if self._load(alias).revision != before.revision: |
| 198 | + raise RevisionConflict("Document changed before the write") |
| 199 | + os.replace(temporary, before.path) |
| 200 | + saved = self._load(alias) |
| 201 | + if saved.text != after: |
| 202 | + raise OSError("Artifact verification failed") |
| 203 | + return { |
| 204 | + "document": alias, |
| 205 | + "revision": saved.revision, |
| 206 | + "status": "saved and reopened", |
| 207 | + } |
| 208 | + finally: |
| 209 | + temporary.unlink(missing_ok=True) |
| 210 | + |
| 211 | + return await self._exclusive(save) |
| 212 | + |
| 213 | + def tools(self): |
| 214 | + """Expose aliases and bounded operations through ordinary function tools.""" |
| 215 | + |
| 216 | + @function_tool |
| 217 | + async def read_document( |
| 218 | + document: str, offset: int, revision: str | None |
| 219 | + ) -> DocumentPage | ToolOutput: |
| 220 | + """Read a selected page; continue with its next_offset and revision.""" |
| 221 | + try: |
| 222 | + return await self.read(document, offset, revision) |
| 223 | + except RevisionConflict: |
| 224 | + return _revision_retry() |
| 225 | + |
| 226 | + @function_tool |
| 227 | + async def search_document( |
| 228 | + document: str, query: str, offset: int, revision: str | None |
| 229 | + ) -> SearchPage | ToolOutput: |
| 230 | + """Search one selected page; follow next_offset until it is null.""" |
| 231 | + try: |
| 232 | + return await self.search(document, query, offset, revision) |
| 233 | + except RevisionConflict: |
| 234 | + return _revision_retry() |
| 235 | + |
| 236 | + @function_tool |
| 237 | + async def revise_document( |
| 238 | + document: str, revision: str, old_text: str, new_text: str |
| 239 | + ) -> SavedDocument | ToolOutput: |
| 240 | + """Replace unique text in a writable document using its current revision.""" |
| 241 | + try: |
| 242 | + return await self.revise(document, revision, old_text, new_text) |
| 243 | + except RevisionConflict: |
| 244 | + return _revision_retry() |
| 245 | + |
| 246 | + return [read_document, search_document, revise_document] |
| 247 | + |
| 248 | + |
| 249 | +def _revision_retry() -> ToolOutput: |
| 250 | + return ToolOutput.error( |
| 251 | + "The document changed. Restart read_document at offset 0 with revision null, " |
| 252 | + "then use the returned revision for later reads or edits." |
| 253 | + ) |
0 commit comments