Debian Codegraph @

tests/lib/tools/test_agent_toolset.py

raw
1 from __future__ import annotations
2
3 import os
4 import re
5 import sys
6 import time
7 import base64
8 from typing import Any, cast
9 from pathlib import Path
10 from typing_extensions import Required, get_args, get_origin, get_type_hints
11
12 import anyio
13 import pytest
14
15 from anthropic._compat import PYDANTIC_V1
16 from anthropic.lib.tools import ToolError
17 from anthropic.lib.tools.agent_toolset import (
18 _BINARY_MEDIA_TYPES,
19 DEFAULT_MAX_IMAGE_BASE64_BYTES,
20 BashSession,
21 AgentToolContext,
22 resolve_path,
23 beta_edit_tool,
24 beta_glob_tool,
25 beta_grep_tool,
26 beta_read_tool,
27 beta_write_tool,
28 _reject_read_only,
29 beta_agent_toolset_20260401,
30 )
31 from anthropic.types.beta.beta_base64_pdf_source_param import BetaBase64PDFSourceParam
32 from anthropic.types.beta.beta_base64_image_source_param import BetaBase64ImageSourceParam
33
34 needs_pydantic_v2 = pytest.mark.skipif(PYDANTIC_V1, reason="tool functions are only supported with pydantic v2")
35
36
37 @pytest.mark.parametrize(
38 ("description", "p", "expect_error"),
39 [
40 ("relative path inside workdir resolves", "a/b.txt", False),
41 ("dot-dot that stays inside workdir resolves", "a/../b.txt", False),
42 ("dot-dot that escapes workdir is rejected", "../etc/passwd", True),
43 ("absolute path outside workdir is rejected", "/etc/passwd", True),
44 ],
45 )
46 def test_resolve_path(tmp_path: Path, description: str, p: str, expect_error: bool) -> None:
47 env = AgentToolContext(workdir=str(tmp_path))
48 if expect_error:
49 with pytest.raises(ValueError):
50 resolve_path(env, p)
51 else:
52 assert resolve_path(env, p), description
53
54
55 @pytest.mark.parametrize("value", [True, False])
56 def test_unrestricted_paths_is_rejected_with_guidance(tmp_path: Path, value: bool) -> None:
57 with pytest.raises(TypeError, match="unrestricted_paths is no longer supported.*allowed_roots"):
58 AgentToolContext(workdir=str(tmp_path), unrestricted_paths=value)
59
60
61 def test_resolve_path_absolute_inside_workdir(tmp_path: Path) -> None:
62 """An absolute path that canonicalises inside the workdir is permitted in
63 confined mode — the containment check is what guards the jail, not the
64 absolute/relative spelling. Regression for anthropics/anthropic-sdk-go#368.
65 """
66 env = AgentToolContext(workdir=str(tmp_path))
67 (tmp_path / "a.txt").write_text("x")
68 assert resolve_path(env, str(tmp_path / "a.txt")) == tmp_path / "a.txt"
69 assert resolve_path(env, str(tmp_path)) == tmp_path
70 sub = tmp_path / "sub"
71 sub.mkdir()
72 assert resolve_path(env, str(sub / "b.txt")) == sub / "b.txt"
73 # Still rejected: absolute outside, and absolute-that-symlinks-outside.
74 with pytest.raises(ValueError, match="outside the session's working directory"):
75 resolve_path(env, "/etc/passwd")
76 if sys.platform != "win32":
77 (tmp_path / "out").symlink_to("/etc/passwd")
78 with pytest.raises(ValueError, match="outside the session's working directory"):
79 resolve_path(env, str(tmp_path / "out"))
80
81
82 needs_symlinks = pytest.mark.skipif(sys.platform == "win32", reason="symlink fixtures need a POSIX filesystem")
83
84
85 def _symlink_fixture(tmp_path: Path) -> Path:
86 """Workdir with two symlink cycles, a link that escapes, and a link whose
87 target spells its way through a cycle to the escaping link."""
88 outside = tmp_path / "outside"
89 outside.mkdir()
90 (outside / "secret.txt").write_text("SECRET")
91 work = tmp_path / "work"
92 work.mkdir()
93 (work / "loop_a").symlink_to("loop_b")
94 (work / "loop_b").symlink_to("loop_a")
95 (work / "self").symlink_to("self")
96 (work / "evil_link").symlink_to(outside / "secret.txt")
97 (work / "L").symlink_to("loop_a/../evil_link")
98 return work
99
100
101 _LOOP_INPUTS = ["loop_a", "loop_a/child.txt", "self", "self/x"]
102
103
104 @needs_symlinks
105 @pytest.mark.parametrize("p", _LOOP_INPUTS)
106 def test_resolve_path_rejects_symlink_loop(tmp_path: Path, p: str) -> None:
107 work = _symlink_fixture(tmp_path)
108 env = AgentToolContext(workdir=str(work))
109 started = time.monotonic()
110 with pytest.raises(
111 ValueError, match=rf"^path {re.escape(repr(p))}: too many levels of symbolic links$"
112 ) as exc_info:
113 resolve_path(env, p)
114 assert time.monotonic() - started < 2
115 assert str(tmp_path) not in str(exc_info.value)
116
117
118 @needs_symlinks
119 def test_resolve_path_dotdot_is_lexical_before_symlinks(tmp_path: Path) -> None:
120 """`a/../b` never touches `a`, so a cycle at `a` cannot carry `b`
121 past the containment check on any interpreter."""
122 work = _symlink_fixture(tmp_path)
123 env = AgentToolContext(workdir=str(work))
124 for p in ("loop_a/../evil_link", "self/../evil_link"):
125 with pytest.raises(ValueError, match="outside the session's working directory"):
126 resolve_path(env, p)
127 with pytest.raises(ValueError, match="too many levels of symbolic links|outside the session's working directory"):
128 resolve_path(env, "L")
129 (work / "ok.txt").write_text("ok")
130 assert resolve_path(env, "loop_a/../ok.txt") == work / "ok.txt"
131
132
133 @needs_symlinks
134 def test_resolve_path_rejects_symlink_escape_live_and_dangling(tmp_path: Path) -> None:
135 work = _symlink_fixture(tmp_path)
136 (work / "dangle_out").symlink_to(tmp_path / "outside" / "nope")
137 env = AgentToolContext(workdir=str(work))
138 for p in ("evil_link", "dangle_out"):
139 with pytest.raises(ValueError, match="outside the session's working directory"):
140 resolve_path(env, p)
141
142
143 def test_resolve_path_allowed_roots(tmp_path: Path) -> None:
144 """A path inside an allowed root resolves; one outside the workdir and
145 every allowed root is refused, and the refusal names no internal options."""
146 work = tmp_path / "work"
147 work.mkdir()
148 mount = tmp_path / "mount"
149 mount.mkdir()
150 env = AgentToolContext(workdir=str(work), allowed_roots=[mount])
151 assert resolve_path(env, str(mount / "note.md")) == mount / "note.md"
152 assert resolve_path(env, "inside.txt") == work / "inside.txt"
153 with pytest.raises(ValueError, match="outside the session's working directory and its other permitted directories"):
154 resolve_path(env, str(tmp_path / "elsewhere" / "x"))
155 with pytest.raises(ValueError, match="outside the session's working directory and its other permitted directories"):
156 resolve_path(env, "../elsewhere/x")
157
158
159 def test_resolve_path_symlink_out_of_allowed_root_is_rejected(tmp_path: Path) -> None:
160 """Symlinks are canonicalised before the containment check, so a link
161 inside an allowed root cannot reach outside it."""
162 if sys.platform == "win32":
163 pytest.skip("symlinks need privileges on windows")
164 work = tmp_path / "work"
165 work.mkdir()
166 mount = tmp_path / "mount"
167 mount.mkdir()
168 (mount / "leak").symlink_to("/etc/passwd")
169 env = AgentToolContext(workdir=str(work), allowed_roots=[mount])
170 with pytest.raises(ValueError, match="outside the session's working directory and its other permitted directories"):
171 resolve_path(env, str(mount / "leak"))
172
173
174 def test_resolve_path_segment_aware_sibling(tmp_path: Path) -> None:
175 """A sibling directory sharing a prefix (workdir vs workdir2) must not satisfy the jail."""
176 root = tmp_path / "work"
177 root.mkdir()
178 env = AgentToolContext(workdir=str(root))
179 with pytest.raises(ValueError):
180 resolve_path(env, "../work2/file")
181
182
183 @needs_pydantic_v2
184 def test_agent_toolset_names_and_type(tmp_path: Path) -> None:
185 env = AgentToolContext(workdir=str(tmp_path))
186 names = [t.name for t in beta_agent_toolset_20260401(env)]
187 assert names == ["bash", "read", "write", "edit", "glob", "grep"]
188
189
190 @needs_pydantic_v2
191 async def test_agent_toolset_filter_and_extend(tmp_path: Path) -> None:
192 """The list returned by beta_agent_toolset_20260401 is a plain list that callers can filter or extend."""
193 env = AgentToolContext(workdir=str(tmp_path))
194 subset = [t for t in beta_agent_toolset_20260401(env) if t.name not in ("bash", "grep")]
195 assert [t.name for t in subset] == ["read", "write", "edit", "glob"]
196 extended = [*subset, beta_read_tool(env)]
197 assert extended[-1].name == "read"
198
199
200 @needs_pydantic_v2
201 async def test_read_write_edit_roundtrip(tmp_path: Path) -> None:
202 env = AgentToolContext(workdir=str(tmp_path))
203
204 msg = await beta_write_tool(env).call({"file_path": "f.txt", "content": "hello world"})
205 assert isinstance(msg, str)
206 assert "wrote" in msg
207
208 text = await beta_read_tool(env).call({"file_path": "f.txt"})
209 assert text == "hello world"
210
211 await beta_edit_tool(env).call({"file_path": "f.txt", "old_string": "world", "new_string": "there"})
212 assert (tmp_path / "f.txt").read_text() == "hello there"
213
214
215 @needs_pydantic_v2
216 async def test_read_view_range(tmp_path: Path) -> None:
217 (tmp_path / "f.txt").write_bytes(b"a\nb\nc\nd\n")
218 env = AgentToolContext(workdir=str(tmp_path))
219 out = await beta_read_tool(env).call({"file_path": "f.txt", "view_range": [2, 3]})
220 assert out == "b\nc"
221
222
223 @needs_pydantic_v2
224 @pytest.mark.parametrize(
225 ("view_range", "want"),
226 [
227 ([2, 2], "line2"),
228 ([2, 0], "line2\nline3"),
229 ([10, 12], ""),
230 ([3, 1], ""),
231 ([], "line1\nline2\nline3"),
232 ],
233 )
234 async def test_read_view_range_edges(tmp_path: Path, view_range: list[int], want: str) -> None:
235 (tmp_path / "a.txt").write_bytes(b"line1\nline2\nline3")
236 env = AgentToolContext(workdir=str(tmp_path))
237 assert await beta_read_tool(env).call({"file_path": "a.txt", "view_range": view_range}) == want
238
239
240 @needs_pydantic_v2
241 async def test_read_view_range_wrong_arity_is_rejected(tmp_path: Path) -> None:
242 (tmp_path / "a.txt").write_text("line1\nline2\nline3")
243 env = AgentToolContext(workdir=str(tmp_path))
244 with pytest.raises(ToolError) as exc_info:
245 await beta_read_tool(env).call({"file_path": "a.txt", "view_range": [2]})
246 assert str(exc_info.value) == "read: view_range must be [start_line, end_line]"
247
248
249 @needs_pydantic_v2
250 async def test_read_preserves_crlf_line_endings(tmp_path: Path) -> None:
251 (tmp_path / "crlf.txt").write_bytes(b"line1\r\nline2\r\nline3\r\n")
252 env = AgentToolContext(workdir=str(tmp_path))
253 assert await beta_read_tool(env).call({"file_path": "crlf.txt"}) == "line1\r\nline2\r\nline3\r\n"
254 out = await beta_read_tool(env).call({"file_path": "crlf.txt", "view_range": [1, 2]})
255 assert out == "line1\r\nline2\r"
256
257
258 @needs_pydantic_v2
259 async def test_read_preserves_lone_cr(tmp_path: Path) -> None:
260 (tmp_path / "cr.txt").write_bytes(b"a\rb\rc\r")
261 env = AgentToolContext(workdir=str(tmp_path))
262 assert await beta_read_tool(env).call({"file_path": "cr.txt"}) == "a\rb\rc\r"
263 assert await beta_read_tool(env).call({"file_path": "cr.txt", "view_range": [1, 1]}) == "a\rb\rc\r"
264 assert await beta_read_tool(env).call({"file_path": "cr.txt", "view_range": [2, 2]}) == ""
265
266
267 @needs_pydantic_v2
268 async def test_edit_preserves_crlf_line_endings(tmp_path: Path) -> None:
269 path = tmp_path / "crlf.txt"
270 path.write_bytes(b"line1\r\nline2\r\nline3\r\n")
271 env = AgentToolContext(workdir=str(tmp_path))
272 await beta_edit_tool(env).call({"file_path": "crlf.txt", "old_string": "line2", "new_string": "LINE2"})
273 assert path.read_bytes() == b"line1\r\nLINE2\r\nline3\r\n"
274
275
276 @needs_pydantic_v2
277 async def test_write_preserves_content_bytes(tmp_path: Path) -> None:
278 env = AgentToolContext(workdir=str(tmp_path))
279 await beta_write_tool(env).call({"file_path": "w.txt", "content": "a\r\nb\nc\r"})
280 assert (tmp_path / "w.txt").read_bytes() == b"a\r\nb\nc\r"
281
282
283 @needs_pydantic_v2
284 async def test_read_rejects_oversized_file(tmp_path: Path) -> None:
285 (tmp_path / "big.txt").write_bytes(b"a" * (257 * 1024))
286 env = AgentToolContext(workdir=str(tmp_path))
287 with pytest.raises(ToolError, match="exceeds") as exc_info:
288 await beta_read_tool(env).call({"file_path": "big.txt"})
289 assert "view_range" in str(exc_info.value)
290 assert "bash" not in str(exc_info.value)
291
292
293 @needs_pydantic_v2
294 async def test_read_oversized_file_view_range_wrong_arity_is_rejected(tmp_path: Path) -> None:
295 (tmp_path / "big.txt").write_bytes(b"a" * (257 * 1024))
296 env = AgentToolContext(workdir=str(tmp_path))
297 with pytest.raises(ToolError) as exc_info:
298 await beta_read_tool(env).call({"file_path": "big.txt", "view_range": [2]})
299 assert str(exc_info.value) == "read: view_range must be [start_line, end_line]"
300
301
302 @needs_pydantic_v2
303 @pytest.mark.parametrize(
304 ("view_range", "want"),
305 [
306 ([2, 2], "line2"),
307 ([2, 0], "line2\nline3\n"),
308 ([10, 12], ""),
309 ([3, 1], ""),
310 ],
311 )
312 async def test_read_view_range_streams_file_over_cap(tmp_path: Path, view_range: list[int], want: str) -> None:
313 (tmp_path / "a.txt").write_bytes(b"line1\nline2\nline3\n")
314 env = AgentToolContext(workdir=str(tmp_path), max_file_bytes=16)
315 assert await beta_read_tool(env).call({"file_path": "a.txt", "view_range": view_range}) == want
316
317
318 @needs_pydantic_v2
319 async def test_read_view_range_over_cap_rejects_oversized_slice(tmp_path: Path) -> None:
320 (tmp_path / "a.txt").write_bytes(b"line1\nline2\nline3\n")
321 env = AgentToolContext(workdir=str(tmp_path), max_file_bytes=16)
322 with pytest.raises(ToolError, match="exceeds") as exc_info:
323 await beta_read_tool(env).call({"file_path": "a.txt", "view_range": [1, 3]})
324 assert "Narrow the view_range" in str(exc_info.value)
325 assert "bash" not in str(exc_info.value)
326
327
328 @needs_pydantic_v2
329 async def test_read_view_range_over_cap_single_long_line(tmp_path: Path) -> None:
330 (tmp_path / "a.txt").write_bytes(b"x" * 100 + b"\nok\n")
331 env = AgentToolContext(workdir=str(tmp_path), max_file_bytes=16)
332 with pytest.raises(ToolError, match="cannot return part of a line"):
333 await beta_read_tool(env).call({"file_path": "a.txt", "view_range": [1, 1]})
334 assert await beta_read_tool(env).call({"file_path": "a.txt", "view_range": [2, 2]}) == "ok"
335
336
337 @needs_pydantic_v2
338 async def test_read_view_range_over_cap_preserves_crlf_line_endings(tmp_path: Path) -> None:
339 (tmp_path / "a.txt").write_bytes(b"line1\r\nline2\r\nline3\r\n")
340 env = AgentToolContext(workdir=str(tmp_path), max_file_bytes=16)
341 assert await beta_read_tool(env).call({"file_path": "a.txt", "view_range": [1, 2]}) == "line1\r\nline2\r"
342
343
344 @needs_pydantic_v2
345 async def test_read_view_range_over_cap_preserves_lone_cr(tmp_path: Path) -> None:
346 (tmp_path / "a.txt").write_bytes(b"a\rb\rc\r")
347 env = AgentToolContext(workdir=str(tmp_path), max_file_bytes=4)
348 with pytest.raises(ToolError, match="cannot return part of a line"):
349 await beta_read_tool(env).call({"file_path": "a.txt", "view_range": [1, 1]})
350 assert await beta_read_tool(env).call({"file_path": "a.txt", "view_range": [2, 2]}) == ""
351
352 (tmp_path / "b.txt").write_bytes(b"a\rb\rc\r\n0123456789\n")
353 env = AgentToolContext(workdir=str(tmp_path), max_file_bytes=16)
354 assert await beta_read_tool(env).call({"file_path": "b.txt", "view_range": [1, 1]}) == "a\rb\rc\r"
355 assert await beta_read_tool(env).call({"file_path": "b.txt", "view_range": [3, 3]}) == ""
356
357
358 @needs_pydantic_v2
359 async def test_read_view_range_over_cap_crosses_chunk_boundaries(tmp_path: Path) -> None:
360 rows = [f"row{i:04d}" + "." * 90 for i in range(1, 5001)]
361 (tmp_path / "big.txt").write_bytes("".join(row + "\n" for row in rows).encode())
362 env = AgentToolContext(workdir=str(tmp_path))
363 out = await beta_read_tool(env).call({"file_path": "big.txt", "view_range": [1000, 1002]})
364 assert out == "\n".join(rows[999:1002])
365
366
367 @needs_pydantic_v2
368 async def test_read_rejects_directory(tmp_path: Path) -> None:
369 (tmp_path / "sub").mkdir()
370 env = AgentToolContext(workdir=str(tmp_path))
371 with pytest.raises(ToolError, match="not a regular file"):
372 await beta_read_tool(env).call({"file_path": "sub"})
373
374
375 @needs_pydantic_v2
376 async def test_edit_rejects_oversized_file(tmp_path: Path) -> None:
377 (tmp_path / "big.txt").write_bytes(b"a" * (257 * 1024))
378 env = AgentToolContext(workdir=str(tmp_path))
379 with pytest.raises(ToolError, match="exceeds") as exc_info:
380 await beta_edit_tool(env).call({"file_path": "big.txt", "old_string": "a", "new_string": "b"})
381 assert "bash" not in str(exc_info.value)
382
383
384 @needs_pydantic_v2
385 async def test_edit_rejects_directory(tmp_path: Path) -> None:
386 (tmp_path / "sub").mkdir()
387 env = AgentToolContext(workdir=str(tmp_path))
388 with pytest.raises(ToolError, match="not a regular file"):
389 await beta_edit_tool(env).call({"file_path": "sub", "old_string": "a", "new_string": "b"})
390
391
392 @needs_pydantic_v2
393 async def test_edit_normal_within_limit(tmp_path: Path) -> None:
394 (tmp_path / "f.txt").write_text("hello world")
395 env = AgentToolContext(workdir=str(tmp_path))
396 await beta_edit_tool(env).call({"file_path": "f.txt", "old_string": "world", "new_string": "there"})
397 assert (tmp_path / "f.txt").read_text() == "hello there"
398
399
400 @needs_pydantic_v2
401 async def test_edit_custom_max_bytes_rejects_below_cap(tmp_path: Path) -> None:
402 (tmp_path / "f.txt").write_bytes(b"OLD" + b"\x00" * 2000)
403 env = AgentToolContext(workdir=str(tmp_path), max_file_bytes=1024)
404 with pytest.raises(ToolError, match="exceeds") as exc_info:
405 await beta_edit_tool(env).call({"file_path": "f.txt", "old_string": "OLD", "new_string": "NEW"})
406 assert "bash" not in str(exc_info.value)
407
408
409 @needs_pydantic_v2
410 async def test_edit_custom_max_bytes_allows_above_default(tmp_path: Path) -> None:
411 (tmp_path / "f.txt").write_bytes(b"OLD" + b"\x00" * (257 * 1024))
412 env = AgentToolContext(workdir=str(tmp_path), max_file_bytes=512 * 1024)
413 await beta_edit_tool(env).call({"file_path": "f.txt", "old_string": "OLD", "new_string": "NEW"})
414 assert (tmp_path / "f.txt").read_bytes()[:3] == b"NEW"
415
416
417 @needs_pydantic_v2
418 async def test_edit_uncapped_allows_oversized(tmp_path: Path) -> None:
419 (tmp_path / "f.txt").write_bytes(b"OLD" + b"\x00" * (257 * 1024))
420 env = AgentToolContext(workdir=str(tmp_path), max_file_bytes=None)
421 await beta_edit_tool(env).call({"file_path": "f.txt", "old_string": "OLD", "new_string": "NEW"})
422
423
424 @needs_pydantic_v2
425 async def test_edit_rejects_directory_even_when_uncapped(tmp_path: Path) -> None:
426 (tmp_path / "sub").mkdir()
427 env = AgentToolContext(workdir=str(tmp_path), max_file_bytes=None)
428 with pytest.raises(ToolError, match="not a regular file"):
429 await beta_edit_tool(env).call({"file_path": "sub", "old_string": "a", "new_string": "b"})
430
431
432 @needs_pydantic_v2
433 async def test_read_custom_max_bytes_rejects_below_cap(tmp_path: Path) -> None:
434 (tmp_path / "f.txt").write_bytes(b"a" * 2000)
435 env = AgentToolContext(workdir=str(tmp_path), max_file_bytes=1024)
436 with pytest.raises(ToolError, match="exceeds") as exc_info:
437 await beta_read_tool(env).call({"file_path": "f.txt"})
438 assert "view_range" in str(exc_info.value)
439 assert "bash" not in str(exc_info.value)
440
441
442 @needs_pydantic_v2
443 async def test_read_uncapped_allows_oversized(tmp_path: Path) -> None:
444 (tmp_path / "big.txt").write_bytes(b"a" * (257 * 1024))
445 env = AgentToolContext(workdir=str(tmp_path), max_file_bytes=None)
446 await beta_read_tool(env).call({"file_path": "big.txt"})
447
448
449 @needs_pydantic_v2
450 async def test_read_rejects_directory_even_when_uncapped(tmp_path: Path) -> None:
451 (tmp_path / "sub").mkdir()
452 env = AgentToolContext(workdir=str(tmp_path), max_file_bytes=None)
453 with pytest.raises(ToolError, match="not a regular file"):
454 await beta_read_tool(env).call({"file_path": "sub"})
455
456
457 def _media_type_literal_values(typed_dict: type, key: str) -> set[str]:
458 """Extract the values of a `Required[Literal[...]]` TypedDict field."""
459 hint = get_type_hints(typed_dict, include_extras=True)[key]
460 if get_origin(hint) is Required:
461 (hint,) = get_args(hint)
462 values = get_args(hint)
463 assert values, f"expected a Literal for {typed_dict.__name__}.{key}"
464 return set(values)
465
466
467 def test_binary_media_types_track_generated_api_types() -> None:
468 """Pin the read tool's extension map to the codegen'd media-type literals.
469
470 When a spec change adds or removes a supported image/document media type,
471 this fails to force the extension map (and its size caps) to be revisited.
472 """
473 supported = _media_type_literal_values(BetaBase64ImageSourceParam, "media_type") | _media_type_literal_values(
474 BetaBase64PDFSourceParam, "media_type"
475 )
476 assert set(_BINARY_MEDIA_TYPES.values()) == supported
477
478
479 # Real magic bytes so the round-trip assertion exercises non-UTF-8 data; the
480 # tool itself only sniffs the extension.
481 _JPEG_BYTES = b"\xff\xd8\xff\xe0" + b"\x00" * 32
482 _PNG_BYTES = b"\x89PNG\r\n\x1a\n" + b"\x00" * 32
483 _PDF_BYTES = b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n"
484
485
486 @needs_pydantic_v2
487 @pytest.mark.parametrize(
488 ("filename", "data", "kind", "media_type"),
489 [
490 ("slide.jpg", _JPEG_BYTES, "image", "image/jpeg"),
491 ("slide.JPEG", _JPEG_BYTES, "image", "image/jpeg"),
492 ("chart.png", _PNG_BYTES, "image", "image/png"),
493 ("doc.pdf", _PDF_BYTES, "document", "application/pdf"),
494 ],
495 )
496 async def test_read_binary_returns_content_block(
497 tmp_path: Path, filename: str, data: bytes, kind: str, media_type: str
498 ) -> None:
499 """Images/PDFs come back as base64 content blocks, not UnicodeDecodeError."""
500 (tmp_path / filename).write_bytes(data)
501 env = AgentToolContext(workdir=str(tmp_path))
502 result = await beta_read_tool(env).call({"file_path": filename})
503 assert not isinstance(result, str)
504 (block,) = [cast("dict[str, Any]", b) for b in result]
505 assert block["type"] == kind
506 source = block["source"]
507 assert source["type"] == "base64"
508 assert source["media_type"] == media_type
509 assert base64.standard_b64decode(source["data"]) == data
510
511
512 @needs_pydantic_v2
513 async def test_read_binary_not_subject_to_text_cap(tmp_path: Path) -> None:
514 """An image over the 256 KiB text default still reads (the API media caps govern)."""
515 (tmp_path / "big.png").write_bytes(_PNG_BYTES + b"\x00" * (300 * 1024))
516 env = AgentToolContext(workdir=str(tmp_path))
517 result = await beta_read_tool(env).call({"file_path": "big.png"})
518 assert not isinstance(result, str)
519 (block,) = [cast("dict[str, Any]", b) for b in result]
520 assert block["type"] == "image"
521
522
523 @needs_pydantic_v2
524 async def test_read_binary_honors_explicit_cap(tmp_path: Path) -> None:
525 (tmp_path / "big.png").write_bytes(_PNG_BYTES + b"\x00" * 2048)
526 env = AgentToolContext(workdir=str(tmp_path), max_file_bytes=1024)
527 with pytest.raises(ToolError, match="exceeds"):
528 await beta_read_tool(env).call({"file_path": "big.png"})
529
530
531 @needs_pydantic_v2
532 async def test_read_binary_rejects_over_media_cap(tmp_path: Path) -> None:
533 """An image whose base64 form would exceed the default per-image cap is rejected up front."""
534 raw_cap = (DEFAULT_MAX_IMAGE_BASE64_BYTES // 4) * 3
535 (tmp_path / "huge.png").write_bytes(b"\x00" * (raw_cap + 1))
536 env = AgentToolContext(workdir=str(tmp_path), max_file_bytes=None)
537 with pytest.raises(ToolError, match="exceeds"):
538 await beta_read_tool(env).call({"file_path": "huge.png"})
539
540
541 @needs_pydantic_v2
542 async def test_read_binary_custom_media_caps(tmp_path: Path) -> None:
543 """The media caps are configurable: a small custom cap rejects, a larger/disabled one permits."""
544 (tmp_path / "img.png").write_bytes(_PNG_BYTES + b"\x00" * 2048) # ~2 KiB raw
545 (tmp_path / "doc.pdf").write_bytes(_PDF_BYTES + b"\x00" * 2048)
546
547 # The image cap is on the base64 form (4/3 of raw), so 1 KiB rejects ~2 KiB raw.
548 tight = AgentToolContext(workdir=str(tmp_path), max_image_base64_bytes=1024, max_pdf_bytes=1024)
549 with pytest.raises(ToolError, match="exceeds"):
550 await beta_read_tool(tight).call({"file_path": "img.png"})
551 with pytest.raises(ToolError, match="exceeds"):
552 await beta_read_tool(tight).call({"file_path": "doc.pdf"})
553
554 # A larger cap (or `None` to disable) admits the same files.
555 loose = AgentToolContext(workdir=str(tmp_path), max_image_base64_bytes=1024 * 1024, max_pdf_bytes=None)
556 for name, kind in (("img.png", "image"), ("doc.pdf", "document")):
557 result = await beta_read_tool(loose).call({"file_path": name})
558 assert not isinstance(result, str)
559 (block,) = [cast("dict[str, Any]", b) for b in result]
560 assert block["type"] == kind
561
562
563 @needs_pydantic_v2
564 async def test_read_binary_rejects_view_range(tmp_path: Path) -> None:
565 (tmp_path / "slide.jpg").write_bytes(_JPEG_BYTES)
566 env = AgentToolContext(workdir=str(tmp_path))
567 with pytest.raises(ToolError, match="view_range is not supported"):
568 await beta_read_tool(env).call({"file_path": "slide.jpg", "view_range": [1, 2]})
569
570
571 @needs_pydantic_v2
572 async def test_read_undecodable_binary_raises_tool_error(tmp_path: Path) -> None:
573 """Non-image/PDF binary surfaces a clean ToolError, not a raw UnicodeDecodeError."""
574 (tmp_path / "blob.bin").write_bytes(b"\xff\xfe\x00\x01")
575 env = AgentToolContext(workdir=str(tmp_path))
576 with pytest.raises(ToolError, match="not valid UTF-8"):
577 await beta_read_tool(env).call({"file_path": "blob.bin"})
578
579
580 @needs_pydantic_v2
581 async def test_edit_binary_raises_tool_error(tmp_path: Path) -> None:
582 (tmp_path / "blob.bin").write_bytes(b"\xff\xfe\x00\x01")
583 env = AgentToolContext(workdir=str(tmp_path))
584 with pytest.raises(ToolError, match="not valid UTF-8"):
585 await beta_edit_tool(env).call({"file_path": "blob.bin", "old_string": "a", "new_string": "b"})
586
587
588 @needs_pydantic_v2
589 def test_text_io_is_utf8_under_ascii_locale(tmp_path: Path) -> None:
590 """Text I/O is explicitly UTF-8: an ASCII-locale host (LANG=C) must not
591 mislabel valid UTF-8 as binary. Runs in a subprocess because the locale
592 default is fixed at interpreter startup."""
593 import subprocess
594
595 (tmp_path / "notes.txt").write_bytes("café — naïve\n".encode("utf-8"))
596 script = "\n".join(
597 [
598 "import sys, anyio",
599 "from anthropic.lib.tools.agent_toolset import (",
600 " AgentToolContext, beta_edit_tool, beta_read_tool)",
601 f"ctx = AgentToolContext(workdir={str(tmp_path)!r})",
602 "async def main():",
603 " text = await beta_read_tool(ctx).call({'file_path': 'notes.txt'})",
604 " sys.stdout.buffer.write(text.encode('utf-8'))",
605 " await beta_edit_tool(ctx).call(",
606 " {'file_path': 'notes.txt', 'old_string': 'caf\\u00e9', 'new_string': 'th\\u00e9'})",
607 "anyio.run(main)",
608 ]
609 )
610 proc = subprocess.run(
611 [sys.executable, "-c", script],
612 env={**os.environ, "LC_ALL": "C", "LANG": "C", "PYTHONUTF8": "0", "PYTHONCOERCECLOCALE": "0"},
613 capture_output=True,
614 )
615 assert proc.returncode == 0, proc.stderr.decode("utf-8", errors="replace")
616 assert proc.stdout.decode("utf-8") == "café — naïve\n"
617 assert (tmp_path / "notes.txt").read_text(encoding="utf-8") == "thé — naïve\n"
618
619
620 @pytest.mark.parametrize(
621 ("description", "args", "want_error"),
622 [
623 (
624 "edit fails when old_string is absent from the file",
625 {"file_path": "f.txt", "old_string": "nope", "new_string": "x"},
626 True,
627 ),
628 (
629 "edit fails when old_string is non-unique and replace_all is false",
630 {"file_path": "f.txt", "old_string": "ab", "new_string": "x"},
631 True,
632 ),
633 (
634 "edit succeeds on non-unique old_string when replace_all is true",
635 {"file_path": "f.txt", "old_string": "ab", "new_string": "x", "replace_all": True},
636 False,
637 ),
638 ],
639 )
640 @needs_pydantic_v2
641 async def test_edit_uniqueness(tmp_path: Path, description: str, args: dict[str, object], want_error: bool) -> None:
642 (tmp_path / "f.txt").write_text("ab ab")
643 env = AgentToolContext(workdir=str(tmp_path))
644 tool = beta_edit_tool(env)
645 if want_error:
646 with pytest.raises(ToolError):
647 await tool.call(args)
648 else:
649 assert await tool.call(args), description
650
651
652 @needs_pydantic_v2
653 async def test_glob_mtime_order(tmp_path: Path) -> None:
654 a = tmp_path / "a.txt"
655 b = tmp_path / "b.txt"
656 a.write_text("a")
657 b.write_text("b")
658 os.utime(a, (1, 1))
659 os.utime(b, (2, 2))
660 env = AgentToolContext(workdir=str(tmp_path))
661 res = await beta_glob_tool(env).call({"pattern": "*.txt"})
662 assert isinstance(res, str)
663 lines = res.splitlines()
664 assert lines[0].endswith("b.txt") and lines[1].endswith("a.txt")
665
666
667 @needs_pydantic_v2
668 async def test_glob_with_path(tmp_path: Path) -> None:
669 (tmp_path / "sub").mkdir()
670 (tmp_path / "sub" / "a.txt").write_text("a")
671 (tmp_path / "b.txt").write_text("b")
672 env = AgentToolContext(workdir=str(tmp_path))
673 res = await beta_glob_tool(env).call({"pattern": "*.txt", "path": "sub"})
674 assert isinstance(res, str)
675 assert res.endswith("a.txt")
676 assert "b.txt" not in res
677
678
679 @needs_pydantic_v2
680 async def test_grep_finds_match(tmp_path: Path) -> None:
681 (tmp_path / "x.txt").write_text("foo\nbar\nbaz\n")
682 env = AgentToolContext(workdir=str(tmp_path))
683 res = await beta_grep_tool(env).call({"pattern": "ba.", "path": "."})
684 assert isinstance(res, str)
685 assert "bar" in res and "baz" in res
686
687
688 @needs_pydantic_v2
689 async def test_grep_single_file_path(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
690 """Fallback walker must handle a file path, not just directories."""
691 (tmp_path / "x.txt").write_text("alpha\nbeta\n")
692 env = AgentToolContext(workdir=str(tmp_path))
693 monkeypatch.setattr("shutil.which", lambda _name: None) # type: ignore[arg-type]
694 res = await beta_grep_tool(env).call({"pattern": "beta", "path": "x.txt"})
695 assert isinstance(res, str)
696 assert "beta" in res
697 assert res != "no matches"
698
699
700 @pytest.mark.skipif(sys.platform == "win32", reason="bash session requires /bin/bash")
701 async def test_bash_session_persistence(tmp_path: Path) -> None:
702 s = await BashSession.start(str(tmp_path))
703 try:
704 out, code = await s.exec("export FOO=bar; echo set")
705 assert (out, code) == ("set", 0)
706 out, code = await s.exec("echo $FOO")
707 assert (out, code) == ("bar", 0)
708 finally:
709 await s.close()
710
711
712 @pytest.mark.skipif(sys.platform == "win32", reason="bash session requires /bin/bash")
713 async def test_bash_timeout(tmp_path: Path) -> None:
714 s = await BashSession.start(str(tmp_path))
715 with pytest.raises(TimeoutError):
716 await s.exec("sleep 5", timeout=0.2)
717
718
719 @pytest.mark.skipif(sys.platform == "win32", reason="bash session requires /bin/bash")
720 async def test_bash_sentinel_not_spoofable(tmp_path: Path) -> None:
721 """A command that prints a hardcoded marker can't truncate output or spoof the exit code."""
722 s = await BashSession.start(str(tmp_path))
723 try:
724 out, code = await s.exec("printf '__ANT_CMD_DONE__7\\nafter\\n'; (exit 3)")
725 assert "__ANT_CMD_DONE__7" in out
726 assert "after" in out
727 assert code == 3
728 finally:
729 await s.close()
730
731
732 @pytest.mark.skipif(sys.platform == "win32", reason="bash session requires /bin/bash")
733 async def test_bash_stdin_redirect(tmp_path: Path) -> None:
734 """A stdin-reading command gets immediate EOF instead of hanging until timeout."""
735 s = await BashSession.start(str(tmp_path))
736 try:
737 out, code = await s.exec("cat; echo done", timeout=2.0)
738 assert out == "done"
739 assert code == 0
740 finally:
741 await s.close()
742
743
744 @pytest.mark.skipif(sys.platform == "win32", reason="bash session requires /bin/bash")
745 async def test_bash_session_closed_property(tmp_path: Path) -> None:
746 """`closed` is the inverse of the old `alive` (TS parity) and there is
747 no `alive` attribute any more."""
748 s = await BashSession.start(str(tmp_path))
749 assert s.closed is False
750 assert not hasattr(s, "alive")
751 await s.close()
752 assert s.closed is True
753 # A closed session refuses further commands rather than silently hanging.
754 with pytest.raises(RuntimeError, match="terminated"):
755 await s.exec("echo nope")
756
757
758 @pytest.mark.skipif(sys.platform == "win32", reason="bash session requires /bin/bash")
759 async def test_bash_outer_cancel_closes_subprocess_no_stale_state(tmp_path: Path) -> None:
760 """Regression: a cancellation from an *outer* scope (e.g. the session
761 runner's `TOOL_TIMEOUT`) during a bash exec must tear the subprocess down,
762 so the next call can't read the cancelled command's stale output/sentinel.
763
764 anyio raises an outer-scope cancel as a plain `Cancelled` (not
765 `TimeoutError`), so the `except TimeoutError` cleanup never runs — only
766 the new `except get_cancelled_exc_class()` path saves us here.
767 """
768 s = await BashSession.start(str(tmp_path))
769 try:
770 # The inner per-call timeout is huge; an OUTER scope cancels first,
771 # mid-command, while `sleep` is producing no output.
772 with anyio.move_on_after(0.3):
773 await s.exec("sleep 5; echo STALE_MARKER", timeout=120.0)
774
775 # The outer cancel fired mid-exec. The subprocess must have been closed
776 # (not left alive with `sleep 5; echo STALE_MARKER` still queued).
777 assert s.closed is True
778 # And because it's closed, the next exec refuses outright — it can NOT
779 # hand back the previous command's STALE_MARKER output + old sentinel.
780 with pytest.raises(RuntimeError, match="terminated"):
781 await s.exec("echo NEXT")
782 finally:
783 await s.close()
784
785
786 @needs_pydantic_v2
787 async def test_read_through_symlink_escape_is_rejected(tmp_path: Path) -> None:
788 """resolve_path realpaths, so a symlink that escapes the workdir is caught."""
789 outside = tmp_path / "outside"
790 outside.mkdir()
791 (outside / "secret.txt").write_text("secret")
792 work = tmp_path / "work"
793 work.mkdir()
794 (work / "escape").symlink_to(outside)
795 env = AgentToolContext(workdir=str(work))
796 with pytest.raises(ToolError, match="outside the session's working directory"):
797 await beta_read_tool(env).call({"file_path": "escape/secret.txt"})
798
799
800 @needs_pydantic_v2
801 @needs_symlinks
802 async def test_read_symlink_loop_is_rejected(tmp_path: Path) -> None:
803 work = _symlink_fixture(tmp_path)
804 env = AgentToolContext(workdir=str(work))
805 with pytest.raises(ToolError) as exc_info:
806 await beta_read_tool(env).call({"file_path": "loop_a"})
807 assert str(exc_info.value) == "read: path 'loop_a': too many levels of symbolic links"
808 for p in ("loop_a/../evil_link", "L"):
809 with pytest.raises(ToolError) as exc_info:
810 await beta_read_tool(env).call({"file_path": p})
811 assert "SECRET" not in str(exc_info.value)
812
813
814 @needs_pydantic_v2
815 @needs_symlinks
816 async def test_write_under_symlink_loop_creates_nothing(tmp_path: Path) -> None:
817 work = _symlink_fixture(tmp_path)
818 before = sorted(os.listdir(work))
819 env = AgentToolContext(workdir=str(work))
820 with pytest.raises(ToolError, match="too many levels of symbolic links"):
821 await beta_write_tool(env).call({"file_path": "loop_a/child.txt", "content": "x"})
822 assert sorted(os.listdir(work)) == before
823
824
825 @needs_pydantic_v2
826 @needs_symlinks
827 async def test_write_through_dangling_symlink_inside_workdir(tmp_path: Path) -> None:
828 """A dangling link whose target is inside the workdir is followed: the
829 target and its missing parent directory are created."""
830 env = AgentToolContext(workdir=str(tmp_path))
831 (tmp_path / "d").symlink_to(tmp_path / "newdir" / "f.txt")
832 await beta_write_tool(env).call({"file_path": "d", "content": "via link"})
833 assert (tmp_path / "newdir" / "f.txt").read_text() == "via link"
834
835
836 @needs_pydantic_v2
837 @needs_symlinks
838 async def test_read_follows_symlink_chain_inside_workdir(tmp_path: Path) -> None:
839 (tmp_path / "real.txt").write_text("payload")
840 (tmp_path / "c2").symlink_to("real.txt")
841 (tmp_path / "c1").symlink_to("c2")
842 (tmp_path / "c0").symlink_to("c1")
843 env = AgentToolContext(workdir=str(tmp_path))
844 assert await beta_read_tool(env).call({"file_path": "c0"}) == "payload"
845
846
847 @needs_pydantic_v2
848 async def test_write_creates_deeply_nested_missing_directories(tmp_path: Path) -> None:
849 """Missing path components are not symlink hops, so any depth is allowed."""
850 env = AgentToolContext(workdir=str(tmp_path))
851 rel = "/".join(f"d{i}" for i in range(50)) + "/f.txt"
852 await beta_write_tool(env).call({"file_path": rel, "content": "deep"})
853 assert (tmp_path / rel).read_text() == "deep"
854
855
856 @needs_pydantic_v2
857 async def test_read_under_unreadable_directory_reports_permission_denied(tmp_path: Path) -> None:
858 if os.name != "posix":
859 pytest.skip("chmod semantics only apply on POSIX")
860 if os.geteuid() == 0:
861 pytest.skip("root bypasses POSIX mode bits")
862 noperm = tmp_path / "noperm"
863 noperm.mkdir()
864 noperm.chmod(0)
865 env = AgentToolContext(workdir=str(tmp_path))
866 try:
867 with pytest.raises(ToolError) as exc_info:
868 await beta_read_tool(env).call({"file_path": "noperm/x"})
869 finally:
870 noperm.chmod(0o700)
871 assert str(exc_info.value) == "read: path 'noperm/x': permission denied"
872
873
874 @needs_pydantic_v2
875 async def test_glob_rejects_dotdot_pattern(tmp_path: Path) -> None:
876 """`Path.glob` honours literal `..` segments — the tool must reject a
877 pattern that would walk out of the workdir before it ever runs."""
878 outside = tmp_path / "outside"
879 outside.mkdir()
880 (outside / "secret.txt").write_text("secret")
881 work = tmp_path / "work"
882 work.mkdir()
883 env = AgentToolContext(workdir=str(work))
884 with pytest.raises(ToolError, match=r"\.\."):
885 await beta_glob_tool(env).call({"pattern": "../outside/*.txt"})
886
887
888 @needs_pydantic_v2
889 async def test_glob_post_filters_symlink_escape(tmp_path: Path) -> None:
890 """A symlink traversed mid-pattern must not let a glob result escape the workdir."""
891 outside = tmp_path / "outside"
892 outside.mkdir()
893 (outside / "secret.txt").write_text("secret")
894 work = tmp_path / "work"
895 work.mkdir()
896 (work / "escape").symlink_to(outside)
897 env = AgentToolContext(workdir=str(work))
898 res = await beta_glob_tool(env).call({"pattern": "escape/*.txt"})
899 assert res == "no matches"
900
901
902 @needs_pydantic_v2
903 @needs_symlinks
904 async def test_glob_drops_matches_that_cannot_be_canonicalised(tmp_path: Path) -> None:
905 work = _symlink_fixture(tmp_path)
906 (work / "ok.txt").write_text("ok")
907 env = AgentToolContext(workdir=str(work))
908 res = await beta_glob_tool(env).call({"pattern": "*"})
909 assert isinstance(res, str)
910 assert [Path(line).name for line in res.splitlines()] == ["ok.txt"]
911
912
913 @needs_pydantic_v2
914 async def test_grep_skips_symlinked_files(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
915 """The fallback walker must not read through a symlink that escapes the workdir."""
916 secret = tmp_path / "secret.txt"
917 secret.write_text("TOPSECRET")
918 work = tmp_path / "work"
919 work.mkdir()
920 (work / "leak").symlink_to(secret)
921 (work / "real.txt").write_text("ordinary\n")
922 env = AgentToolContext(workdir=str(work))
923 monkeypatch.setattr("shutil.which", lambda _name: None) # type: ignore[arg-type]
924 res = await beta_grep_tool(env).call({"pattern": "TOPSECRET"})
925 assert res == "no matches"
926
927
928 @needs_pydantic_v2
929 async def test_file_tools_confinement_matrix(tmp_path: Path) -> None:
930 """The full path policy through the real tools: the workdir works, a memory
931 folder mounted outside it works, a read-only memory folder reads but
932 refuses writes, and everywhere else is refused."""
933 work = tmp_path / "work"
934 work.mkdir()
935 mount = tmp_path / "mnt" / "notes"
936 mount.mkdir(parents=True)
937 ro = tmp_path / "mnt" / "facts"
938 ro.mkdir(parents=True)
939 (ro / "facts.md").write_text("immutable")
940 outside = tmp_path / "outside"
941 outside.mkdir()
942 (outside / "secret.txt").write_text("secret")
943
944 env = AgentToolContext(workdir=str(work), allowed_roots=[mount, ro], read_only_roots=[ro.resolve()])
945 read = beta_read_tool(env)
946 write = beta_write_tool(env)
947 edit = beta_edit_tool(env)
948
949 await write.call({"file_path": "w.txt", "content": "in workdir"})
950 assert (work / "w.txt").read_text() == "in workdir"
951
952 await write.call({"file_path": str(mount / "note.md"), "content": "remembered"})
953 assert await read.call({"file_path": str(mount / "note.md")}) == "remembered"
954 await edit.call({"file_path": str(mount / "note.md"), "old_string": "remembered", "new_string": "edited"})
955 assert (mount / "note.md").read_text() == "edited"
956
957 assert await read.call({"file_path": str(ro / "facts.md")}) == "immutable"
958 with pytest.raises(ToolError, match="read-only"):
959 await write.call({"file_path": str(ro / "facts.md"), "content": "x"})
960 assert (ro / "facts.md").read_text() == "immutable"
961
962 with pytest.raises(ToolError, match="outside the session's working directory and its other permitted directories"):
963 await read.call({"file_path": str(outside / "secret.txt")})
964 with pytest.raises(ToolError, match="outside the session's working directory and its other permitted directories"):
965 await write.call({"file_path": str(outside / "new.txt"), "content": "x"})
966 assert not (outside / "new.txt").exists()
967
968
969 @needs_pydantic_v2
970 async def test_glob_and_grep_reach_an_allowed_root(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
971 work = tmp_path / "work"
972 work.mkdir()
973 mount = tmp_path / "mnt" / "notes"
974 mount.mkdir(parents=True)
975 (mount / "note.md").write_text("remembered fact")
976 env = AgentToolContext(workdir=str(work), allowed_roots=[mount])
977
978 res = await beta_glob_tool(env).call({"pattern": "*.md", "path": str(mount)})
979 assert res == str(mount / "note.md")
980
981 monkeypatch.setattr("shutil.which", lambda _name: None) # type: ignore[arg-type]
982 res = await beta_grep_tool(env).call({"pattern": "remembered", "path": str(mount)})
983 assert isinstance(res, str)
984 assert "note.md" in res
985
986
987 def test_a_symlinked_read_only_root_still_refuses_writes(tmp_path: Path) -> None:
988 """allowed_roots entries resolve at check time, so read_only_roots must
989 too — the same symlinked path must not grant access on one side while
990 its write protection misses on the other."""
991 if sys.platform == "win32":
992 pytest.skip("symlinks need privileges on windows")
993 work = tmp_path / "work"
994 work.mkdir()
995 real = tmp_path / "real-store"
996 real.mkdir()
997 link = tmp_path / "link-store"
998 link.symlink_to(real)
999 env = AgentToolContext(workdir=str(work), allowed_roots=[link], read_only_roots=[link])
1000
1001 target = resolve_path(env, str(link / "note.md"))
1002 assert target == real / "note.md"
1003 with pytest.raises(ToolError, match="read-only"):
1004 _reject_read_only(env, target, op="write", file_path=str(link / "note.md"))