Debian Codegraph @

src/anthropic/lib/tools/agent_toolset.py

raw
1 """Reference implementations of the `agent_toolset_20260401` tools — `bash`,
2 `read`, `write`, `edit`, `glob`, `grep` — plus the workdir/skills
3 `AgentToolContext`.
4
5 This sits next to the other `lib/tools` helpers (the Messages tool runner, the
6 memory tool, …). Importing it pulls in `subprocess` etc., so it is kept out of
7 `anthropic.lib.tools.__init__` — depend on it explicitly
8 (`from anthropic.lib.tools.agent_toolset import beta_agent_toolset_20260401`).
9
10 The result of `beta_agent_toolset_20260401` is a plain
11 `list[BetaAsyncFunctionTool]` — *async* function tools, so it is for the
12 **async** runners only: `client.beta.sessions.events.tool_runner(...)` (the
13 `SessionToolRunner`, always async) for a managed-agents session, or — via the
14 `anthropic.lib.environments.EnvironmentWorker` — the self-hosted
15 environment worker. The sync `Anthropic` `messages.tool_runner` accepts
16 `BetaRunnableTool`, which excludes the async function tools this returns, so
17 it cannot consume this toolset.
18
19 Warning: `bash` is **stateful**: it owns a persistent `/bin/bash` subprocess that
20 is only torn down by its `close` cleanup hook. Only `SessionToolRunner`
21 (and the `EnvironmentWorker` built on it) invoke that hook. The Messages
22 `client.beta.messages.tool_runner(...)` does **not** call `close`, so
23 handing this toolset to the Messages tool runner leaks the bash subprocess
24 (one orphaned shell per run). Run stateful tools under
25 `client.beta.sessions.events.tool_runner(...)` / the environment worker,
26 or drop `bash` from the toolset before using the Messages tool runner.
27
28 Trust model: the file tools confine to `workdir` plus any `allowed_roots`
29 (symlink-aware) and are safe without a sandbox; `bash` is unrestricted and
30 should run inside one. See `AgentToolContext`.
31 """
32
33 from __future__ import annotations
34
35 import os
36 import re
37 import uuid
38 import errno
39 import base64
40 import shutil
41 import logging
42 import subprocess
43 from stat import S_ISLNK, S_ISREG
44 from typing import TYPE_CHECKING, Any, List, Optional, NamedTuple, cast
45 from pathlib import Path, PurePosixPath
46 from functools import partial
47 from itertools import islice
48 from contextlib import asynccontextmanager
49 from dataclasses import field, dataclass
50 from collections.abc import Mapping, Callable, Iterable, Iterator, Awaitable, AsyncIterator
51
52 import anyio
53 import anyio.abc
54 from anyio.to_thread import run_sync
55
56 from ._files import read_line_range, read_text_exact, write_text_exact
57 from ._skills import _within, download_session_skills
58 from ..._types import NotGiven, not_given
59 from ..._utils import is_given
60 from ...types.beta import (
61 BetaManagedAgentsAgentToolset20260401BashInput,
62 BetaManagedAgentsAgentToolset20260401EditInput,
63 BetaManagedAgentsAgentToolset20260401GlobInput,
64 BetaManagedAgentsAgentToolset20260401GrepInput,
65 BetaManagedAgentsAgentToolset20260401ReadInput,
66 BetaManagedAgentsAgentToolset20260401WriteInput,
67 )
68 from ._deprecations import reject_unrestricted_paths
69 from ._beta_functions import (
70 ToolError,
71 BetaContent,
72 BetaAsyncFunctionTool,
73 BetaFunctionToolResultType,
74 beta_async_tool,
75 )
76
77 if TYPE_CHECKING:
78 from ..._client import AsyncAnthropic
79 from ...types.beta import BetaManagedAgentsSession
80
81 __all__ = [
82 "AgentToolContext",
83 "BashSession",
84 "BashResult",
85 "resolve_path",
86 "beta_agent_toolset_20260401",
87 "beta_bash_tool",
88 "beta_read_tool",
89 "beta_write_tool",
90 "beta_edit_tool",
91 "beta_glob_tool",
92 "beta_grep_tool",
93 ]
94
95 BASH_OUTPUT_LIMIT = 100 * 1024
96 BASH_DEFAULT_TIMEOUT = 120.0
97 DEFAULT_MAX_FILE_BYTES = 256 * 1024
98 # Default image/PDF caps for the binary `read` path (overridable on
99 # `AgentToolContext`, same shape as `max_file_bytes`). The API
100 # enforces a per-image limit on the *encoded* (base64) form and a total
101 # request-size limit that the raw-PDF cap stays under after the ~4/3 base64
102 # inflation; an oversized block would be rejected at request time, so reject
103 # it here with a clear error instead. The spec doesn't publish these limits, so
104 # they can't be codegen'd; if the API raises them, the only cost of these going
105 # stale is rejecting a file early that the API would now accept — bump them
106 # here (or override them on the context) when that happens.
107 DEFAULT_MAX_IMAGE_BASE64_BYTES = 5 * 1024 * 1024
108 DEFAULT_MAX_PDF_BYTES = 20 * 1024 * 1024
109 READ_IMAGE_MAX_BASE64_BYTES = DEFAULT_MAX_IMAGE_BASE64_BYTES # For backwards compat only.
110 READ_PDF_MAX_BYTES = DEFAULT_MAX_PDF_BYTES # For backwards compat only.
111 # Extension → media type for files `read` returns as base64 content blocks
112 # rather than text. The supported media types ARE codegen'd
113 # (`BetaBase64ImageSourceParam` / `BetaBase64PDFSourceParam`); a test pins
114 # this map's values to those literals, so a spec change that adds or removes a
115 # media type fails CI until the map is updated. Not user-configurable (yet).
116 _BINARY_MEDIA_TYPES = {
117 ".png": "image/png",
118 ".jpg": "image/jpeg",
119 ".jpeg": "image/jpeg",
120 ".gif": "image/gif",
121 ".webp": "image/webp",
122 ".pdf": "application/pdf",
123 }
124 GREP_OUTPUT_LIMIT = 100 * 1024
125 GREP_MAX_LINE_LENGTH = 2000
126 GLOB_RESULT_LIMIT = 200
127 WALK_MAX_ENTRIES = 50_000
128 _ANSI = re.compile(r"\x1b\[[0-9;?]*[ -/]*[@-~]")
129
130
131 def _resolve_max_bytes(configured: int | None | NotGiven, default: int = DEFAULT_MAX_FILE_BYTES) -> int | None:
132 """Resolve a configured cap to an effective size limit.
133
134 `not_given` selects `default`; `None` disables the size check
135 (uncapped); a positive int is the cap. Governs only the size guard — callers
136 still reject non-regular files.
137 """
138 return configured if is_given(configured) else default
139
140
141 log = logging.getLogger("anthropic.lib.tools.agent_toolset")
142
143
144 def _default_bash_env() -> dict[str, str]:
145 """The environment for the bash subprocess, with the runner's own
146 credentials scrubbed.
147
148 The bash tool runs model-issued commands, so it must never inherit the
149 runner's `ANTHROPIC_*` variables (API key, environment key, per-work
150 session tokens): a prompt-injected `echo $ANTHROPIC_API_KEY` would
151 otherwise land the credential straight in the session transcript. Passing
152 an explicit `env` to `AgentToolContext` does NOT add to this
153 default — it FULLY REPLACES it. The provided mapping becomes the entire
154 bash environment verbatim; nothing here is merged in, so callers who want
155 the scrubbed process environment plus extras must build that mapping
156 themselves.
157 """
158 return {k: v for k, v in os.environ.items() if not k.startswith("ANTHROPIC_")}
159
160
161 def _fs_reason(e: OSError) -> str:
162 """Map a filesystem `OSError` to a consistent, runtime-independent phrase.
163
164 The raw `OSError` string is platform-specific (`[Errno 2] ENOENT: ...`)
165 and can embed a host path; normalise the common cases so the model sees the
166 same wording everywhere and never the runner's absolute paths.
167 """
168 if isinstance(e, FileNotFoundError):
169 return "no such file or directory"
170 if isinstance(e, NotADirectoryError):
171 return "not a directory"
172 if isinstance(e, IsADirectoryError):
173 return "is a directory"
174 if isinstance(e, PermissionError):
175 return "permission denied"
176 if isinstance(e, FileExistsError):
177 return "file already exists"
178 if e.errno == errno.ELOOP:
179 return "too many levels of symbolic links"
180 return (e.strerror or "i/o error").lower()
181
182
183 def _fs_error(op: str, file_path: str, e: OSError) -> ToolError:
184 return ToolError(f"{op}: {file_path}: {_fs_reason(e)}")
185
186
187 def _empty_skill_dirs() -> list[Path]:
188 return []
189
190
191 @dataclass
192 class AgentToolContext:
193 """Workdir + path-policy for the agent toolset.
194
195 Trust model — two tiers:
196
197 - The file tools (`beta_read_tool`, `beta_write_tool`,
198 `beta_edit_tool`, `beta_glob_tool`, `beta_grep_tool`)
199 resolve paths against `workdir` and reject anything outside `workdir`
200 and `allowed_roots`. `resolve_path` follows every symlink
201 (including the leaf, even a dangling one) before the check and returns
202 that canonical path for the operation, so a symlink inside the workdir
203 that points outside it can neither pass the check nor be followed
204 afterwards — a real boundary, consistent with the memory tool, so the
205 file tools are safe to use without a sandbox.
206 - `beta_bash_tool` runs an unrestricted `/bin/bash` regardless of
207 the path policy. Confinement for it must come from the OS layer
208 (e.g. a self-hosted environment runner).
209
210 Attributes:
211 workdir: Base directory for resolving relative tool paths. Defaults to
212 `os.getcwd` captured when the context is constructed (TS
213 parity: `process.cwd()` at construction), so a `chdir` between
214 constructing this context and the first tool call does not move
215 where paths resolve. Pass an explicit path to override.
216 unrestricted_paths: Deprecated and no longer accepted. The file tools
217 are always confined to `workdir` plus `allowed_roots`, which is
218 neither of the two behaviors this flag used to select, so passing
219 either value raises `TypeError` explaining what to do
220 instead. The parameter itself will be removed in a future release.
221 allowed_roots: Directories outside `workdir` that the file tools may
222 also reach. The environment worker sets this to the session's
223 memory-store folders, so memories mounted outside the working
224 directory stay readable and writable. Does **not** constrain
225 `beta_bash_tool`.
226 env: Optional environment for the bash subprocess. When unset, the bash
227 tool inherits the process environment with the runner's
228 `ANTHROPIC_*` credentials scrubbed. When provided, it FULLY
229 REPLACES that default environment — the mapping is used verbatim
230 and is NOT merged with or added to the scrubbed process
231 environment. To keep the defaults plus extra vars, build the
232 combined mapping yourself before passing it.
233 max_file_bytes: Size cap for a whole-file `read` and for `edit`,
234 which both load the whole file into memory. A `read` with
235 `view_range` on a larger file streams it and applies the cap to
236 the selected lines instead. `not_given` (default) uses the
237 built-in 256 KiB cap; a positive int sets a custom cap; `None`
238 disables the cap entirely. Disabling it reintroduces the OOM risk on
239 a model-controlled path, so pass `None` only when the sandbox can
240 absorb arbitrarily large files. The non-regular-file (FIFO/device)
241 guard always applies regardless of this value. Image/PDF files,
242 which `read` returns as base64 content blocks, are not subject to
243 the 256 KiB default (`max_image_base64_bytes` /
244 `max_pdf_bytes` govern instead), but an explicit positive cap
245 binds them too.
246 max_image_base64_bytes: Cap on the *base64-encoded* size of an image
247 `read` returns as a content block. `not_given` (default)
248 uses the built-in 5 MiB cap — a memory bound plus the API's
249 per-image limit; a positive int overrides it; `None` disables it
250 (only `max_file_bytes` / the API's own limit then apply).
251 max_pdf_bytes: Cap on the raw size of a PDF `read` returns as a
252 document block. `not_given` (default) uses the built-in 20 MiB
253 cap; a positive int overrides it; `None` disables it.
254 """
255
256 # `default_factory` (not a literal "." ) so the cwd is snapshotted at
257 # *construction* time, not resolved lazily at first use — a chdir in
258 # between must not change where tools resolve paths (TS parity).
259 workdir: str | os.PathLike[str] = field(default_factory=os.getcwd)
260 unrestricted_paths: bool | NotGiven = not_given
261 allowed_roots: list[Path] = field(default_factory=list[Path])
262 # When `client` and `session` are both set, entering the context
263 # manager downloads each of the session agent's skills into
264 # `{workdir}/skills/<name>/` before any tool runs.
265 client: AsyncAnthropic | None = None
266 # The already-fetched session. A session's resources cannot change while it
267 # runs, so the caller fetches it once and shares that snapshot with the
268 # memory-store download; the two can then never disagree about them.
269 session: BetaManagedAgentsSession | None = None
270 # Deprecated: `setup_skills` fetches the session itself when given only
271 # an id, one extra round trip per context. Prefer `session`. Kept for
272 # callers written before `session` existed; ignored when `session` is
273 # set.
274 session_id: str | None = None
275 env: Optional[Mapping[str, str]] = None
276 max_file_bytes: int | None | NotGiven = not_given
277 max_image_base64_bytes: int | None | NotGiven = not_given
278 max_pdf_bytes: int | None | NotGiven = not_given
279 # Resolved directories the write and edit tools refuse to modify. The
280 # worker sets this to the roots of read-only memory stores so the agent
281 # sees the error at write time instead of the change silently never
282 # syncing; the mechanism is generic to any directory.
283 read_only_roots: list[Path] = field(default_factory=list[Path])
284 _bash: BashSession | None = field(default=None, init=False, repr=False)
285 # Skill directories downloaded by `setup_skills`; removed again on
286 # `__aexit__` so a context doesn't leave downloaded skills behind.
287 _skill_dirs: list[Path] = field(default_factory=_empty_skill_dirs, init=False, repr=False)
288
289 def __post_init__(self) -> None:
290 reject_unrestricted_paths(self.unrestricted_paths)
291
292 async def bash(self) -> BashSession:
293 if self._bash is None:
294 self._bash = await BashSession.start(self.workdir, env=self.env)
295 return self._bash
296
297 async def close(self) -> None:
298 if self._bash is not None:
299 await self._bash.close()
300 self._bash = None
301
302 async def setup_skills(self) -> None:
303 """Download the session agent's skills into `{workdir}/skills/<name>/`.
304
305 No-op unless `client` is set together with `session` (or
306 the deprecated `session_id`). The download + safe archive
307 extraction lives in `anthropic.lib.tools._skills`.
308 """
309 if self.client is None or (self.session is None and self.session_id is None):
310 return
311 self._skill_dirs = await download_session_skills(
312 self.client, session=self.session, session_id=self.session_id, workdir=self.workdir
313 )
314
315 async def _cleanup_skills(self) -> None:
316 """Remove the skill directories `setup_skills` downloaded.
317
318 Only the directories this context created are removed — a pre-existing
319 `{workdir}/skills` tree is left untouched.
320 """
321 for skill_dir in self._skill_dirs:
322 try:
323 # `shutil.rmtree` is blocking; keep it off the event loop.
324 await run_sync(partial(shutil.rmtree, skill_dir, ignore_errors=True))
325 except Exception as e:
326 log.warning("failed to remove downloaded skill dir %s: %s", skill_dir, e)
327 self._skill_dirs = []
328
329 async def __aenter__(self) -> AgentToolContext:
330 await self.setup_skills()
331 return self
332
333 async def __aexit__(self, *exc: object) -> None:
334 try:
335 await self.close()
336 finally:
337 await self._cleanup_skills()
338
339
340 _MAX_SYMLINK_HOPS = 40
341 _MISSING_ERRNOS = (errno.ENOENT, errno.ENOTDIR)
342
343
344 def _symlink_loop_error() -> OSError:
345 return OSError(errno.ELOOP, os.strerror(errno.ELOOP))
346
347
348 def _canonicalize(path: Path) -> Path:
349 """Return `path` with `.`/`..` collapsed lexically and every symlink
350 followed, or raise `OSError` — the same outcome on every supported Python,
351 and never a partly resolved path.
352
353 Trailing components that do not exist yet are kept as spelled, so a new
354 file under new directories still canonicalises; a dangling symlink met on
355 the way is read and followed by hand, and more than `_MAX_SYMLINK_HOPS`
356 such hops count as a loop. Non-strict `Path.resolve()` is avoided because
357 its symlink-loop handling differs between CPython versions.
358 """
359 prefix = Path(os.path.normpath(str(path)))
360 missing_tail: list[str] = []
361 hops = 0
362 while True:
363 try:
364 return prefix.resolve(strict=True).joinpath(*reversed(missing_tail))
365 except RuntimeError:
366 # CPython < 3.13 reports a symlink loop from `resolve(strict=True)` this way.
367 raise _symlink_loop_error() from None
368 except OSError as e:
369 if e.errno not in _MISSING_ERRNOS:
370 raise
371 unresolved = e
372 try:
373 is_symlink = S_ISLNK(os.lstat(prefix).st_mode)
374 except OSError as e:
375 if e.errno not in _MISSING_ERRNOS or prefix.parent == prefix:
376 raise
377 missing_tail.append(prefix.name)
378 prefix = prefix.parent
379 continue
380 if not is_symlink:
381 raise unresolved
382 hops += 1
383 if hops > _MAX_SYMLINK_HOPS:
384 raise _symlink_loop_error()
385 prefix = Path(os.path.normpath(os.path.join(prefix.parent, os.readlink(prefix))))
386
387
388 def resolve_path(ctx: AgentToolContext, p: str) -> Path:
389 """Resolve `p` against the workdir; reject results outside the permitted roots.
390
391 The permitted roots are `workdir` plus each entry of `allowed_roots`.
392 Absolute and relative inputs go through the same canonicalise-then-contain
393 check — an absolute path that lands inside a permitted root is accepted,
394 only paths that resolve *outside* all of them are rejected. `.` and `..`
395 components are collapsed lexically first; then every symlink (including the
396 leaf, even a dangling one) is followed before the containment check, so a
397 symlink under the workdir that targets `/etc` is rejected — and the
398 resolved path is what the tool then operates on, so it can't be followed
399 afterwards either. A symlink loop or an unreadable component rejects the
400 path outright rather than falling back to an unresolved path. See the trust
401 model on `AgentToolContext`.
402 """
403 candidate = Path(p)
404 root = Path(ctx.workdir).resolve()
405 try:
406 full = _canonicalize(candidate if candidate.is_absolute() else root / candidate)
407 except OSError as e:
408 raise ValueError(f"path {p!r}: {_fs_reason(e)}") from e
409 if _within(full, root) or any(_within(full, Path(r).resolve()) for r in ctx.allowed_roots):
410 return full
411 if ctx.allowed_roots:
412 raise ValueError(f"path {p!r} is outside the session's working directory and its other permitted directories")
413 raise ValueError(f"path {p!r} is outside the session's working directory")
414
415
416 def _reject_read_only(ctx: AgentToolContext, target: Path, *, op: str, file_path: str) -> None:
417 """Raise `ToolError` when `target` falls under a read-only root.
418
419 Roots resolve at check time, exactly like `allowed_roots` in
420 `resolve_path` — a symlinked entry must not grant access on one
421 side while its write protection misses on the other.
422 """
423 for root in ctx.read_only_roots:
424 if _within(target, Path(root).resolve()):
425 raise ToolError(f"{op}: {file_path} is inside read-only directory {root}")
426
427
428 class BashResult(NamedTuple):
429 """Result of `BashSession.exec` — the captured output and exit code.
430
431 A `NamedTuple` so it unpacks positionally (`out, code = await s.exec(...)`)
432 and reads by name (`result.output` / `result.exit_code`) interchangeably.
433 """
434
435 output: str
436 """The command's combined stdout + stderr (ANSI escapes stripped, possibly
437 truncated to the last `BASH_OUTPUT_LIMIT` bytes)."""
438
439 exit_code: int
440 """The command's exit status. `-1` when the exit code could not be parsed
441 from the shell sentinel (e.g. truncated output)."""
442
443
444 class BashSession:
445 """A persistent `/bin/bash` process; cwd, env and jobs survive across calls.
446
447 Warning: `BashSession` is **stateful and not safe to share concurrently**.
448 Interleaved `exec` calls would race for the same stdin/stdout
449 pipes (mixed input, output read by the wrong caller, and corrupted
450 sentinel detection). Each `AgentToolContext` creates its own
451 session, so the safe pattern is *one context per session* — never a
452 single `AgentToolContext` (or hand-constructed `BashSession`) shared
453 across multiple sessions running on different self-hosted environments.
454 Holding the shared instance behind a per-call lock would serialize all
455 bash work and is almost certainly not what you want.
456 """
457
458 def __init__(self, proc: anyio.abc.Process) -> None:
459 """Use `BashSession.start` to construct — `__init__` takes an
460 already-spawned process and is intended for internal use."""
461 self._proc = proc
462
463 @classmethod
464 async def start(cls, workdir: str | os.PathLike[str], *, env: Optional[Mapping[str, str]] = None) -> BashSession:
465 base = dict(env) if env is not None else _default_bash_env()
466 proc = await anyio.open_process(
467 ["/bin/bash", "--noprofile", "--norc"],
468 cwd=workdir,
469 env={**base, "PS1": "", "PS2": "", "TERM": "dumb"},
470 stdin=subprocess.PIPE,
471 stdout=subprocess.PIPE,
472 stderr=subprocess.STDOUT,
473 )
474 return cls(proc)
475
476 @property
477 def closed(self) -> bool:
478 """Whether the underlying bash process has exited / been torn down.
479
480 Inverse of "alive". Named `closed` (not `alive`) to match the TS
481 `BashSession.closed` boolean — porting code between the two SDKs
482 should not have to flip the sense of this check.
483 """
484 return self._proc.returncode is not None
485
486 async def exec(self, cmd: str, timeout: float = BASH_DEFAULT_TIMEOUT) -> BashResult:
487 if self.closed:
488 raise RuntimeError("bash session terminated; restart required")
489 assert self._proc.stdin is not None and self._proc.stdout is not None
490 stdin = self._proc.stdin
491 stdout = self._proc.stdout
492 # Per-call nonce so a command that prints a fixed marker can't spoof the
493 # exit-code framing. The `''` split keeps the literal out of what we
494 # write to stdin — only the shell's printf reassembles it.
495 sentinel = f"__ANT_CMD_{uuid.uuid4().hex}_DONE__"
496 sentinel_split = f"{sentinel[:8]}''{sentinel[8:]}"
497 # </dev/null: a stdin-reading command (`cat`, `read`) gets EOF instead
498 # of blocking on the shared pipe until the timeout.
499 wrapped = f"{{ {cmd}\n}} </dev/null 2>&1; printf '\\n{sentinel_split}%d\\n' $?\n"
500 await stdin.send(wrapped.encode())
501
502 buf = bytearray()
503 truncated = False
504 marker = sentinel.encode()
505
506 async def read_until_sentinel() -> None:
507 nonlocal truncated
508 while True:
509 try:
510 chunk = await stdout.receive(4096)
511 except anyio.EndOfStream:
512 return
513 if not chunk:
514 return
515 buf.extend(chunk)
516 if len(buf) > BASH_OUTPUT_LIMIT:
517 # Keep only the tail so the sentinel remains detectable and
518 # the buffer cannot grow without bound.
519 del buf[: len(buf) - BASH_OUTPUT_LIMIT]
520 truncated = True
521 if marker in buf:
522 return
523
524 try:
525 with anyio.fail_after(timeout):
526 await read_until_sentinel()
527 except TimeoutError as e:
528 # This call's own deadline fired. Tear down the subprocess so the
529 # timed-out command can't bleed into the next call. Shielded so the
530 # teardown still completes if an outer scope is also cancelling.
531 with anyio.CancelScope(shield=True):
532 await self.close()
533 raise TimeoutError(f"bash command timed out after {timeout}s") from e
534 except anyio.get_cancelled_exc_class():
535 # A cancellation from *any outer scope* (e.g. the session runner's
536 # `TOOL_TIMEOUT` fail_after winning a race, or a worker-wide
537 # shutdown) unwinds this call without ever raising `TimeoutError`,
538 # so the branch above never runs. Without closing here the
539 # subprocess would be left alive with the in-flight command still
540 # queued, and the NEXT exec() would read this command's stale
541 # output + old sentinel — silent cross-call corruption. Close it
542 # (shielded, since we're already cancelled) and re-raise the
543 # cancellation; never swallow it.
544 with anyio.CancelScope(shield=True):
545 await self.close()
546 raise
547
548 text = _ANSI.sub("", buf.decode(errors="replace"))
549 idx = text.rfind(sentinel)
550 if idx < 0:
551 return BashResult(text.strip(), -1)
552 out = text[:idx].rstrip("\n")
553 tail = text[idx + len(sentinel) :].strip()
554 try:
555 code = int(tail.splitlines()[0]) if tail else -1
556 except ValueError:
557 code = -1
558 if truncated:
559 out = "[output truncated]\n" + out
560 return BashResult(out, code)
561
562 async def close(self) -> None:
563 if self._proc.stdin is not None:
564 with anyio.CancelScope(shield=True):
565 try:
566 await self._proc.stdin.aclose()
567 except Exception:
568 pass
569 if self._proc.returncode is None:
570 self._proc.kill()
571 with anyio.move_on_after(2):
572 await self._proc.wait()
573 with anyio.CancelScope(shield=True):
574 try:
575 await self._proc.aclose()
576 except Exception:
577 pass
578
579
580 def beta_bash_tool(ctx: AgentToolContext) -> BetaAsyncFunctionTool[Any]:
581 @asynccontextmanager
582 async def bash_tool() -> AsyncIterator[Callable[..., Awaitable[str]]]:
583 """Run a command in a persistent bash shell."""
584 # The bash tool owns its own persistent shell for the lifetime of the
585 # tool run. Defining it as an async context manager lets the tool runner
586 # drive this cleanup on exit, so the bash tool no longer needs
587 # AgentToolContext purely for that lifecycle — it only reads the workdir
588 # and subprocess env off `ctx`.
589 session: BashSession | None = None
590
591 async def _session() -> BashSession:
592 nonlocal session
593 if session is None:
594 session = await BashSession.start(ctx.workdir, env=ctx.env)
595 return session
596
597 # `Optional[...]` (not `| None`) because `@beta_async_tool`
598 # evaluates these annotations at runtime via pydantic, and PEP 604 union
599 # syntax can't be `eval`'d under Python 3.9 — our minimum version.
600 async def bash(
601 command: Optional[str] = None, restart: Optional[bool] = None, timeout_ms: Optional[int] = None
602 ) -> str:
603 nonlocal session
604 if restart:
605 if session is not None:
606 await session.close()
607 session = None
608 await _session()
609 return "bash session restarted"
610 if not command:
611 raise ToolError("bash: command is required")
612 timeout = timeout_ms / 1000.0 if timeout_ms else BASH_DEFAULT_TIMEOUT
613 try:
614 s = await _session()
615 out, code = await s.exec(command, timeout=timeout)
616 except (RuntimeError, TimeoutError) as e:
617 raise ToolError(f"bash: {e}") from e
618 if code != 0:
619 raise ToolError(out)
620 return out
621
622 try:
623 yield bash
624 finally:
625 if session is not None:
626 await session.close()
627
628 # `@beta_async_tool` detects the async context manager, enters it lazily
629 # on first call to obtain the `bash` callable, and drives its `__aexit__`
630 # on the tool-runner cleanup path. The `cast` is only to satisfy the
631 # decorator's "async function" overload — the runtime object is the
632 # context-manager factory the decorator expects.
633 return beta_async_tool(
634 name="bash",
635 input_schema=BetaManagedAgentsAgentToolset20260401BashInput,
636 )(cast(Any, bash_tool))
637
638
639 def _read_binary_block(target: Path, file_path: str, size: int, media_type: str, ctx: AgentToolContext) -> BetaContent:
640 """Read an image/PDF as a base64 `image`/`document` content block.
641
642 The text cap does not apply here — its 256 KiB default would reject most
643 real images. Instead the media caps (`max_image_base64_bytes` /
644 `max_pdf_bytes`, defaulting to the API's own limits) govern, checked
645 against the stat size before opening (same OOM rationale as the text path)
646 and tightened by an *explicitly* configured `max_file_bytes` — an
647 explicit cap is a memory bound and binds every read.
648 """
649 # The image cap is on the encoded form: n raw bytes -> 4*ceil(n/3) base64.
650 if media_type == "application/pdf":
651 limit = _resolve_max_bytes(ctx.max_pdf_bytes, DEFAULT_MAX_PDF_BYTES)
652 else:
653 b64_cap = _resolve_max_bytes(ctx.max_image_base64_bytes, DEFAULT_MAX_IMAGE_BASE64_BYTES)
654 limit = (b64_cap // 4) * 3 if b64_cap is not None else None
655 if is_given(ctx.max_file_bytes) and ctx.max_file_bytes is not None:
656 limit = ctx.max_file_bytes if limit is None else min(limit, ctx.max_file_bytes)
657 if limit is not None and size > limit:
658 raise ToolError(f"read: {file_path} is {size} bytes, exceeds {limit}-byte limit for image/PDF files.")
659 data = base64.standard_b64encode(target.read_bytes()).decode("ascii")
660 if media_type == "application/pdf":
661 return {"type": "document", "source": {"type": "base64", "media_type": "application/pdf", "data": data}}
662 return {
663 "type": "image",
664 "source": {"type": "base64", "media_type": cast(Any, media_type), "data": data},
665 }
666
667
668 def beta_read_tool(ctx: AgentToolContext) -> BetaAsyncFunctionTool[Any]:
669 @beta_async_tool(name="read", input_schema=BetaManagedAgentsAgentToolset20260401ReadInput)
670 async def read(file_path: str, view_range: Optional[List[int]] = None) -> BetaFunctionToolResultType:
671 """Read a file rooted at the working directory."""
672 try:
673 target = resolve_path(ctx, file_path)
674 except ValueError as e:
675 raise ToolError(f"read: {e}") from e
676 if view_range and len(view_range) != 2:
677 raise ToolError("read: view_range must be [start_line, end_line]")
678 try:
679 # stat() before any open(): the size cap stops a multi-GB file from
680 # OOM'ing the runner, and is_file() rejects FIFOs/devices/dirs
681 # without opening them (open() on an unconnected FIFO blocks).
682 st = target.stat()
683 if not S_ISREG(st.st_mode):
684 raise ToolError(f"read: {file_path}: not a regular file")
685 media_type = _BINARY_MEDIA_TYPES.get(target.suffix.lower())
686 if media_type is not None:
687 # Images/PDFs come back as content blocks (hosted-toolset
688 # parity) — read_text() on them raises UnicodeDecodeError.
689 if view_range:
690 raise ToolError("read: view_range is not supported for image/PDF files")
691 return [_read_binary_block(target, file_path, st.st_size, media_type, ctx)]
692 limit = _resolve_max_bytes(ctx.max_file_bytes)
693 if limit is not None and st.st_size > limit:
694 if not view_range:
695 raise ToolError(
696 f"read: {file_path} is {st.st_size} bytes, exceeds {limit}-byte limit. "
697 "Use the view_range parameter to read specific line ranges, e.g. view_range: [1, 500]."
698 )
699 return await run_sync(partial(read_line_range, target, file_path, view_range[0], view_range[1], limit))
700 # Explicit UTF-8: the locale default varies by host (ASCII under
701 # LANG=C), which would mislabel valid UTF-8 as binary below.
702 text = read_text_exact(target)
703 except ToolError:
704 raise
705 except UnicodeDecodeError as e:
706 raise ToolError(
707 f"read: {file_path}: not valid UTF-8 text (binary files are only supported for image/PDF extensions)"
708 ) from e
709 except OSError as e:
710 raise _fs_error("read", file_path, e) from e
711 if not view_range:
712 return text
713 start_line, end_line = view_range
714 lines = text.split("\n")
715 start = max(0, start_line - 1)
716 end = end_line if end_line > 0 else len(lines)
717 return "\n".join(lines[start:end])
718
719 return read
720
721
722 def beta_write_tool(ctx: AgentToolContext) -> BetaAsyncFunctionTool[Any]:
723 @beta_async_tool(name="write", input_schema=BetaManagedAgentsAgentToolset20260401WriteInput)
724 async def write(file_path: str, content: str) -> str:
725 """Write a file, creating parent directories as needed."""
726 try:
727 target = resolve_path(ctx, file_path)
728 except ValueError as e:
729 raise ToolError(f"write: {e}") from e
730 _reject_read_only(ctx, target, op="write", file_path=file_path)
731 try:
732 target.parent.mkdir(parents=True, exist_ok=True)
733 write_text_exact(target, content)
734 except OSError as e:
735 raise _fs_error("write", file_path, e) from e
736 return f"wrote {len(content)} bytes to {file_path}"
737
738 return write
739
740
741 def beta_edit_tool(ctx: AgentToolContext) -> BetaAsyncFunctionTool[Any]:
742 @beta_async_tool(name="edit", input_schema=BetaManagedAgentsAgentToolset20260401EditInput)
743 async def edit(file_path: str, old_string: str, new_string: str, replace_all: Optional[bool] = None) -> str:
744 """Replace text in a file by exact string match."""
745 try:
746 target = resolve_path(ctx, file_path)
747 except ValueError as e:
748 raise ToolError(f"edit: {e}") from e
749 _reject_read_only(ctx, target, op="edit", file_path=file_path)
750 try:
751 # stat() before any open(): the size cap stops a multi-GB file from
752 # OOM'ing the runner, and is_file() rejects FIFOs/devices/dirs
753 # without opening them (open() on an unconnected FIFO blocks). Same
754 # guard as the read tool — edit reads the whole file too.
755 st = target.stat()
756 if not S_ISREG(st.st_mode):
757 raise ToolError(f"edit: {file_path}: not a regular file")
758 limit = _resolve_max_bytes(ctx.max_file_bytes)
759 if limit is not None and st.st_size > limit:
760 raise ToolError(
761 f"edit: {file_path} is {st.st_size} bytes, exceeds {limit}-byte limit. "
762 "The edit tool loads the whole file and cannot modify a file this large."
763 )
764 text = read_text_exact(target)
765 except ToolError:
766 raise
767 except UnicodeDecodeError as e:
768 raise ToolError(f"edit: {file_path}: not valid UTF-8 text (cannot edit binary files)") from e
769 except OSError as e:
770 raise _fs_error("edit", file_path, e) from e
771 count = text.count(old_string)
772 if count == 0:
773 raise ToolError(f"edit: old_string not found in {file_path}")
774 if not replace_all and count > 1:
775 raise ToolError(f"edit: old_string appears {count} times in {file_path} (must be unique)")
776 updated = text.replace(old_string, new_string) if replace_all else text.replace(old_string, new_string, 1)
777 try:
778 write_text_exact(target, updated)
779 except OSError as e:
780 raise _fs_error("edit", file_path, e) from e
781 return f"edited {file_path} ({count if replace_all else 1} replacement(s))"
782
783 return edit
784
785
786 def _mtime_or_zero(p: Path) -> float:
787 try:
788 return p.stat().st_mtime
789 except OSError:
790 return 0.0
791
792
793 def _confined(matches: Iterable[Path], root: Path) -> Iterator[Path]:
794 """Yield the matches whose canonical path is inside `root`; a match that
795 cannot be canonicalised (symlink loop, unreadable) is dropped, not raised."""
796 for match in matches:
797 try:
798 canonical = _canonicalize(match)
799 except OSError:
800 continue
801 if _within(canonical, root):
802 yield match
803
804
805 def beta_glob_tool(ctx: AgentToolContext) -> BetaAsyncFunctionTool[Any]:
806 @beta_async_tool(name="glob", input_schema=BetaManagedAgentsAgentToolset20260401GlobInput)
807 async def glob(pattern: str, path: Optional[str] = None) -> str:
808 """List files matching a glob pattern, newest first."""
809 if Path(pattern).is_absolute():
810 raise ToolError("glob: absolute pattern not permitted; pass a relative pattern (and optionally path)")
811 # `Path.glob` honours literal `..` segments, so a pattern like
812 # `../../etc/*` would escape the workdir before resolve_path() is
813 # ever consulted — reject it up front.
814 if ".." in PurePosixPath(pattern).parts:
815 raise ToolError("glob: '..' is not permitted in the pattern")
816 if path:
817 try:
818 root = resolve_path(ctx, path)
819 except ValueError as e:
820 raise ToolError(f"glob: {e}") from e
821 else:
822 root = Path(ctx.workdir).resolve()
823 try:
824 # islice caps the materialised match list so a pattern that matches
825 # an enormous tree can't OOM the runner.
826 matches = list(islice(root.glob(pattern), WALK_MAX_ENTRIES))
827 except (ValueError, OSError) as e:
828 raise ToolError(f"glob: {e}") from e
829 # Post-filter: a symlink traversed mid-pattern (glob follows symlinks
830 # for non-`**` segments) must not let a result escape the search root.
831 matches = list(_confined(matches, root))
832 if not matches:
833 return "no matches"
834 matches.sort(key=_mtime_or_zero, reverse=True)
835 return "\n".join(str(m) for m in matches[:GLOB_RESULT_LIMIT])
836
837 return glob
838
839
840 def beta_grep_tool(ctx: AgentToolContext) -> BetaAsyncFunctionTool[Any]:
841 @beta_async_tool(name="grep", input_schema=BetaManagedAgentsAgentToolset20260401GrepInput)
842 async def grep(pattern: str, path: Optional[str] = None) -> str:
843 """Search file contents for a regular expression."""
844 try:
845 search = resolve_path(ctx, path) if path else Path(ctx.workdir).resolve()
846 except ValueError as e:
847 raise ToolError(f"grep: {e}") from e
848
849 if rg := shutil.which("rg"):
850 # `check=False` because ripgrep exits 1 on "no matches", which
851 # isn't an error for us — we surface it as a friendly string.
852 result = await anyio.run_process(
853 [rg, "-n", "--no-heading", "-e", pattern, "--", str(search)],
854 check=False,
855 )
856 if result.returncode == 1:
857 return "no matches"
858 if result.returncode != 0:
859 raise ToolError(f"grep: rg failed: {result.stderr.decode(errors='replace')}")
860 out = result.stdout.decode(errors="replace")
861 if len(out) > GREP_OUTPUT_LIMIT:
862 out = out[:GREP_OUTPUT_LIMIT] + f"\n[output truncated at {GREP_OUTPUT_LIMIT} bytes]"
863 return out
864
865 try:
866 rx = re.compile(pattern)
867 except re.error as e:
868 raise ToolError(f"grep: invalid regex: {e}") from e
869 return _walk_grep(rx, search)
870
871 return grep
872
873
874 def _walk_grep(rx: re.Pattern[str], search: Path) -> str:
875 hits: list[str] = []
876 budget = GREP_OUTPUT_LIMIT
877
878 def push(line: str) -> bool:
879 nonlocal budget
880 budget -= len(line) + 1
881 if budget < 0:
882 hits.append(f"[output truncated at {GREP_OUTPUT_LIMIT} bytes]")
883 return False
884 hits.append(line)
885 return True
886
887 def scan(full: Path) -> bool:
888 try:
889 with full.open("rb") as f:
890 if b"\x00" in f.read(512):
891 return True
892 f.seek(0)
893 for i, raw in enumerate(f, 1):
894 # Cap line length: `pattern` is model-supplied and Python's
895 # `re` backtracks, so a pathological pattern against a very
896 # long line is a ReDoS.
897 if len(raw) > GREP_MAX_LINE_LENGTH:
898 continue
899 line = raw.decode(errors="replace").rstrip("\r\n")
900 if rx.search(line) and not push(f"{full}:{i}:{line}"):
901 return False
902 except OSError:
903 pass
904 return True
905
906 if search.is_file():
907 scan(search)
908 else:
909 seen = 0
910 for dirpath, dirnames, filenames in os.walk(search):
911 # Never descend into a symlinked directory: a symlink in the workdir
912 # pointing at `/` would otherwise let grep walk straight out of it.
913 dirnames[:] = [
914 d for d in dirnames if d not in (".git", "node_modules") and not (Path(dirpath) / d).is_symlink()
915 ]
916 for name in filenames:
917 full = Path(dirpath) / name
918 # Likewise skip symlinked files — a symlink to /etc/shadow must
919 # not be read through just because it lives inside the workdir.
920 if full.is_symlink():
921 continue
922 seen += 1
923 if seen > WALK_MAX_ENTRIES or not scan(full):
924 return "\n".join(hits) if hits else "no matches"
925 return "\n".join(hits) if hits else "no matches"
926
927
928 def beta_agent_toolset_20260401(ctx: AgentToolContext) -> list[BetaAsyncFunctionTool[Any]]:
929 """Return the `agent_toolset_20260401` implementations bound to `ctx`.
930
931 The result is a plain list of `anthropic.lib.tools.BetaAsyncFunctionTool`
932 instances — *async* function tools, so it is for the **async** runners only:
933 the `AsyncAnthropic` `client.beta.messages.tool_runner` and
934 `client.beta.sessions.events.tool_runner` (always async). The sync
935 `Anthropic` `messages.tool_runner` takes `BetaRunnableTool`, which
936 excludes the async function tools this returns. Filter or extend it before
937 passing it on:
938
939 ```py
940 tools = [*beta_agent_toolset_20260401(ctx), my_custom_tool]
941 tools = [t for t in beta_agent_toolset_20260401(ctx) if t.name != "grep"]
942 ```
943 """
944 return [
945 beta_bash_tool(ctx),
946 beta_read_tool(ctx),
947 beta_write_tool(ctx),
948 beta_edit_tool(ctx),
949 beta_glob_tool(ctx),
950 beta_grep_tool(ctx),
951 ]