| 1 |
"""Tests for `SessionToolRunner` (the implementation behind |
| 2 |
`client.beta.sessions.events.tool_runner()`). |
| 3 |
|
| 4 |
We use lightweight stand-ins for `AsyncEvents` so each test can script the |
| 5 |
sequence of stream events, list events (for the reconcile pass), and per-call |
| 6 |
send failures. `asyncio.sleep` is left real so `await asyncio.sleep(0)` in |
| 7 |
the fake stream actually yields control to the event loop. |
| 8 |
""" |
| 9 |
|
| 10 |
from __future__ import annotations |
| 11 |
|
| 12 |
import time |
| 13 |
import asyncio |
| 14 |
import threading |
| 15 |
from typing import Any, Optional, cast |
| 16 |
from collections.abc import Callable, Sequence, Awaitable, AsyncIterator |
| 17 |
from typing_extensions import override |
| 18 |
|
| 19 |
import httpx2 |
| 20 |
import pytest |
| 21 |
|
| 22 |
from anthropic import APIStatusError |
| 23 |
from anthropic._compat import PYDANTIC_V1 |
| 24 |
from anthropic.lib.tools import ToolError, BetaBuiltinFunctionTool, _beta_session_runner as session_runner_mod |
| 25 |
from anthropic.types.beta import BetaToolParam |
| 26 |
from anthropic.lib.tools._beta_session_runner import ( |
| 27 |
SessionToolRunner, |
| 28 |
DispatchedToolCall, |
| 29 |
) |
| 30 |
|
| 31 |
|
| 32 |
@pytest.fixture(autouse=True) |
| 33 |
def _intercept_scoped_client(monkeypatch: pytest.MonkeyPatch) -> None: # pyright: ignore[reportUnusedFunction] |
| 34 |
"""Make `_scoped_client` return the parent client unchanged so the runner's |
| 35 |
requests land on the test fakes. |
| 36 |
|
| 37 |
The real `_scoped_client` builds an `AsyncAnthropic` sub-client for |
| 38 |
request scoping; the tests use a `_FakeClient` whose only API surface is |
| 39 |
`.beta.sessions.events`, so the sub-client construction would fail. The |
| 40 |
auth-specific tests further down install their own `_scoped_client` |
| 41 |
override (via the `scoped_calls` fixture) to assert on the args. |
| 42 |
""" |
| 43 |
|
| 44 |
def passthrough(client: Any, _key: str | None) -> Any: |
| 45 |
return client |
| 46 |
|
| 47 |
monkeypatch.setattr(session_runner_mod, "_scoped_client", passthrough) |
| 48 |
|
| 49 |
|
| 50 |
@pytest.fixture() |
| 51 |
def scoped_calls(monkeypatch: pytest.MonkeyPatch) -> list[dict[str, Any]]: |
| 52 |
"""Record every `_scoped_client(client, environment_key)` call; still |
| 53 |
returns the parent client (the autouse fixture's behaviour) so the runner |
| 54 |
keeps using the test fakes.""" |
| 55 |
calls: list[dict[str, Any]] = [] |
| 56 |
|
| 57 |
def fake_factory(client: Any, environment_key: str | None) -> Any: |
| 58 |
calls.append({"environment_key": environment_key}) |
| 59 |
return client |
| 60 |
|
| 61 |
monkeypatch.setattr(session_runner_mod, "_scoped_client", fake_factory) |
| 62 |
return calls |
| 63 |
|
| 64 |
|
| 65 |
class _StubEvent: |
| 66 |
"""Stand-in for the various session event types — only the fields the |
| 67 |
runner reads are populated.""" |
| 68 |
|
| 69 |
def __init__(self, type: str, **kw: Any) -> None: |
| 70 |
self.type = type |
| 71 |
for k, v in kw.items(): |
| 72 |
setattr(self, k, v) |
| 73 |
|
| 74 |
|
| 75 |
def _tool_use( |
| 76 |
id: str, |
| 77 |
name: str, |
| 78 |
input: dict[str, Any], |
| 79 |
*, |
| 80 |
evaluated_permission: str | None = None, |
| 81 |
) -> _StubEvent: |
| 82 |
# `evaluated_permission` is always present on the real (typed) event — |
| 83 |
# `None` unless the server evaluated a permission policy for the call. |
| 84 |
return _StubEvent("agent.tool_use", id=id, name=name, input=input, evaluated_permission=evaluated_permission) |
| 85 |
|
| 86 |
|
| 87 |
def _tool_result(tool_use_id: str) -> _StubEvent: |
| 88 |
return _StubEvent("user.tool_result", tool_use_id=tool_use_id) |
| 89 |
|
| 90 |
|
| 91 |
def _tool_confirmation(tool_use_id: str, result: str) -> _StubEvent: |
| 92 |
"""The user's allow/deny verdict for an ask-gated (`always_ask`) tool call.""" |
| 93 |
return _StubEvent("user.tool_confirmation", id=f"conf_{tool_use_id}", tool_use_id=tool_use_id, result=result) |
| 94 |
|
| 95 |
|
| 96 |
def _custom_tool_use(id: str, name: str, input: dict[str, Any]) -> _StubEvent: |
| 97 |
"""A CUSTOM (user-defined) tool call — the agent emits `agent.custom_tool_use` |
| 98 |
rather than `agent.tool_use` for these.""" |
| 99 |
return _StubEvent("agent.custom_tool_use", id=id, name=name, input=input) |
| 100 |
|
| 101 |
|
| 102 |
def _custom_tool_result(custom_tool_use_id: str) -> _StubEvent: |
| 103 |
return _StubEvent("user.custom_tool_result", custom_tool_use_id=custom_tool_use_id) |
| 104 |
|
| 105 |
|
| 106 |
def _terminated() -> _StubEvent: |
| 107 |
return _StubEvent("session.status_terminated") |
| 108 |
|
| 109 |
|
| 110 |
def _idle_end_turn() -> _StubEvent: |
| 111 |
return _StubEvent("session.status_idle", stop_reason=_StubEvent("end_turn")) |
| 112 |
|
| 113 |
|
| 114 |
def _result_content(item: DispatchedToolCall) -> Any: |
| 115 |
"""The content blocks the runner computed and posted back, as carried in |
| 116 |
`result` (the flat `content` convenience field was removed).""" |
| 117 |
return cast(Any, item.result)["content"] |
| 118 |
|
| 119 |
|
| 120 |
def _result_text(item: DispatchedToolCall) -> str: |
| 121 |
"""Concatenated text of the posted-back result's text blocks.""" |
| 122 |
return "".join(b.get("text", "") for b in _result_content(item) if b.get("type") == "text") |
| 123 |
|
| 124 |
|
| 125 |
def _api_status_error(code: int) -> APIStatusError: |
| 126 |
request = httpx2.Request("POST", "https://api.example/x") |
| 127 |
response = httpx2.Response(status_code=code, request=request, content=b"{}") |
| 128 |
return APIStatusError("boom", response=response, body=None) |
| 129 |
|
| 130 |
|
| 131 |
class _FakeStream: |
| 132 |
"""Stand-in for the AsyncStream returned by `events.stream()`. |
| 133 |
|
| 134 |
Yields scripted events in order; once exhausted, blocks forever (the real |
| 135 |
stream stays open until a network event closes it). If `raise_after` is |
| 136 |
set, raises `raise_with` after producing that many events — used to |
| 137 |
exercise the reconnect-with-backoff path. |
| 138 |
""" |
| 139 |
|
| 140 |
def __init__( |
| 141 |
self, |
| 142 |
events: list[_StubEvent], |
| 143 |
*, |
| 144 |
raise_after: int | None = None, |
| 145 |
raise_with: BaseException | None = None, |
| 146 |
) -> None: |
| 147 |
self._events = events |
| 148 |
self._raise_after = raise_after |
| 149 |
self._raise_with = raise_with |
| 150 |
|
| 151 |
async def __aenter__(self) -> _FakeStream: |
| 152 |
return self |
| 153 |
|
| 154 |
async def __aexit__(self, *exc: object) -> None: |
| 155 |
return None |
| 156 |
|
| 157 |
def __aiter__(self) -> Any: |
| 158 |
return self._gen() |
| 159 |
|
| 160 |
async def _gen(self) -> Any: |
| 161 |
for i, ev in enumerate(self._events): |
| 162 |
yield ev |
| 163 |
# Yield control so the dispatch task can pick up the event we just |
| 164 |
# produced before we run on to the next one. |
| 165 |
await asyncio.sleep(0) |
| 166 |
if self._raise_after is not None and i + 1 == self._raise_after: |
| 167 |
assert self._raise_with is not None |
| 168 |
raise self._raise_with |
| 169 |
# Keep the connection "open" until cancelled. |
| 170 |
await asyncio.Event().wait() |
| 171 |
|
| 172 |
|
| 173 |
class FakeAsyncEvents: |
| 174 |
def __init__( |
| 175 |
self, |
| 176 |
*, |
| 177 |
streams: list[_FakeStream | BaseException] | None = None, |
| 178 |
stream_events: list[_StubEvent] | None = None, |
| 179 |
list_events: list[_StubEvent] | None = None, |
| 180 |
list_events_per_call: list[list[_StubEvent]] | None = None, |
| 181 |
list_raises: BaseException | None = None, |
| 182 |
send_failures: Sequence[BaseException | None] | None = None, |
| 183 |
) -> None: |
| 184 |
if streams is not None: |
| 185 |
self._streams: list[_FakeStream | BaseException] = list(streams) |
| 186 |
elif stream_events is not None: |
| 187 |
self._streams = [_FakeStream(stream_events)] |
| 188 |
else: |
| 189 |
self._streams = [_FakeStream([])] |
| 190 |
self._list_events = list(list_events or []) |
| 191 |
# When set, each `list()` call consumes the next entry (falling back |
| 192 |
# to `list_events` once exhausted) so reconnect tests can script a |
| 193 |
# different history per reconcile pass. |
| 194 |
self._list_events_per_call = [list(evs) for evs in (list_events_per_call or [])] |
| 195 |
self._list_raises = list_raises |
| 196 |
self._send_failures: list[BaseException | None] = list(send_failures or []) |
| 197 |
self.send_calls: list[dict[str, Any]] = [] |
| 198 |
self.stream_calls: int = 0 |
| 199 |
self.stream_headers: list[Any] = [] |
| 200 |
self.list_headers: list[Any] = [] |
| 201 |
|
| 202 |
async def stream(self, _session_id: str, *, extra_headers: Any = None) -> _FakeStream: |
| 203 |
self.stream_calls += 1 |
| 204 |
self.stream_headers.append(extra_headers) |
| 205 |
if not self._streams: |
| 206 |
return _FakeStream([]) # block forever; mirrors a fresh connection |
| 207 |
nxt = self._streams.pop(0) |
| 208 |
if isinstance(nxt, BaseException): |
| 209 |
raise nxt |
| 210 |
return nxt |
| 211 |
|
| 212 |
def list(self, _session_id: str, *, limit: int = 1000, extra_headers: Any = None) -> Any: # noqa: ARG002 |
| 213 |
list_raises = self._list_raises |
| 214 |
self.list_headers.append(extra_headers) |
| 215 |
list_events = self._list_events_per_call.pop(0) if self._list_events_per_call else self._list_events |
| 216 |
|
| 217 |
async def _gen() -> Any: |
| 218 |
for ev in list_events: |
| 219 |
yield ev |
| 220 |
if list_raises is not None: |
| 221 |
raise list_raises |
| 222 |
|
| 223 |
return _gen() |
| 224 |
|
| 225 |
async def send(self, session_id: str, *, events: list[Any], extra_headers: Any = None) -> None: |
| 226 |
idx = len(self.send_calls) |
| 227 |
self.send_calls.append({"session_id": session_id, "events": events, "extra_headers": extra_headers}) |
| 228 |
if idx < len(self._send_failures): |
| 229 |
err = self._send_failures[idx] |
| 230 |
if err is not None: |
| 231 |
raise err |
| 232 |
|
| 233 |
|
| 234 |
class _FakeTool: |
| 235 |
def __init__( |
| 236 |
self, |
| 237 |
name: str, |
| 238 |
fn: Callable[[dict[str, Any]], Awaitable[Any]], |
| 239 |
*, |
| 240 |
close: Callable[[], Any] | None = None, |
| 241 |
) -> None: |
| 242 |
self.name = name |
| 243 |
self._fn = fn |
| 244 |
if close is not None: |
| 245 |
self.close = close |
| 246 |
|
| 247 |
def call(self, input: dict[str, Any]) -> Any: |
| 248 |
return self._fn(input) |
| 249 |
|
| 250 |
|
| 251 |
class _SyncTool(BetaBuiltinFunctionTool): |
| 252 |
"""A real `BetaBuiltinFunctionTool`, unlike `_FakeTool`, so `run_runnable_tool` |
| 253 |
takes its sync-tool branch.""" |
| 254 |
|
| 255 |
def __init__(self, name: str, fn: Callable[[object], str]) -> None: |
| 256 |
self._name = name |
| 257 |
self._fn = fn |
| 258 |
|
| 259 |
@override |
| 260 |
def to_dict(self) -> BetaToolParam: |
| 261 |
return {"name": self._name, "input_schema": {"type": "object"}} |
| 262 |
|
| 263 |
@override |
| 264 |
def call(self, input: object) -> str: |
| 265 |
return self._fn(input) |
| 266 |
|
| 267 |
|
| 268 |
class _FakeClient: |
| 269 |
"""Minimal stand-in for `AsyncAnthropic` — only exposes the resource path |
| 270 |
the runner reads.""" |
| 271 |
|
| 272 |
def __init__(self, events: FakeAsyncEvents) -> None: |
| 273 |
self.beta = type( |
| 274 |
"_Beta", |
| 275 |
(), |
| 276 |
{"sessions": type("_Sessions", (), {"events": events})()}, |
| 277 |
)() |
| 278 |
|
| 279 |
|
| 280 |
async def _run_with_fakes( |
| 281 |
*, |
| 282 |
events: FakeAsyncEvents, |
| 283 |
tools: list[Any], |
| 284 |
max_idle: float | None = None, |
| 285 |
environment_key: str | None = None, |
| 286 |
extra_headers: dict[str, Any] | None = None, |
| 287 |
) -> AsyncIterator[DispatchedToolCall]: |
| 288 |
client = _FakeClient(events) |
| 289 |
runner = SessionToolRunner( |
| 290 |
cast(Any, client), |
| 291 |
"s_1", |
| 292 |
tools=tools, |
| 293 |
max_idle=max_idle, |
| 294 |
environment_key=environment_key, |
| 295 |
extra_headers=extra_headers, |
| 296 |
) |
| 297 |
async for call in runner: |
| 298 |
yield call |
| 299 |
|
| 300 |
|
| 301 |
# ---------- happy-path / basic termination --------------------------------- |
| 302 |
|
| 303 |
|
| 304 |
@pytest.mark.asyncio() |
| 305 |
async def test_yields_completed_tool_call() -> None: |
| 306 |
async def echo(input: dict[str, Any]) -> str: |
| 307 |
return f"got {input.get('x')}" |
| 308 |
|
| 309 |
tool = _FakeTool("echo", echo) |
| 310 |
events = FakeAsyncEvents(stream_events=[_tool_use("tu_1", "echo", {"x": 42}), _terminated()]) |
| 311 |
|
| 312 |
items = [item async for item in _run_with_fakes(events=events, tools=[tool])] |
| 313 |
|
| 314 |
assert len(items) == 1 |
| 315 |
item = items[0] |
| 316 |
assert isinstance(item, DispatchedToolCall) |
| 317 |
assert item.tool_use_id == "tu_1" |
| 318 |
assert item.name == "echo" |
| 319 |
assert item.event.input == {"x": 42} |
| 320 |
assert item.is_error is False |
| 321 |
assert item.posted is True |
| 322 |
assert _result_text(item) == "got 42" |
| 323 |
# The reshaped DispatchedToolCall embeds the originating event and the |
| 324 |
# posted-back result block, alongside the flat convenience fields. |
| 325 |
assert item.event.id == "tu_1" |
| 326 |
assert item.result is not None |
| 327 |
assert item.result["type"] == "user.tool_result" |
| 328 |
assert item.result["tool_use_id"] == "tu_1" |
| 329 |
assert item.result.get("is_error") is False |
| 330 |
|
| 331 |
assert len(events.send_calls) == 1 |
| 332 |
sent = events.send_calls[0]["events"][0] |
| 333 |
assert sent["type"] == "user.tool_result" |
| 334 |
assert sent["tool_use_id"] == "tu_1" |
| 335 |
assert sent["is_error"] is False |
| 336 |
|
| 337 |
|
| 338 |
@pytest.mark.asyncio() |
| 339 |
async def test_yields_error_for_failing_tool() -> None: |
| 340 |
async def boom(_input: dict[str, Any]) -> str: |
| 341 |
raise RuntimeError("nope") |
| 342 |
|
| 343 |
tool = _FakeTool("boom", boom) |
| 344 |
events = FakeAsyncEvents(stream_events=[_tool_use("tu_1", "boom", {}), _terminated()]) |
| 345 |
|
| 346 |
items = [item async for item in _run_with_fakes(events=events, tools=[tool])] |
| 347 |
|
| 348 |
assert len(items) == 1 |
| 349 |
assert items[0].is_error is True |
| 350 |
assert items[0].posted is True |
| 351 |
assert "RuntimeError" in _result_text(items[0]) |
| 352 |
|
| 353 |
|
| 354 |
@pytest.mark.asyncio() |
| 355 |
async def test_unknown_tool_skipped_by_default() -> None: |
| 356 |
"""An unregistered tool name is assumed to belong to the other client |
| 357 |
servicing the session, so it is skipped — not answered in place. The call |
| 358 |
is still yielded (`posted=False` / `is_error=False` / `result=None`) |
| 359 |
and nothing is posted.""" |
| 360 |
events = FakeAsyncEvents(stream_events=[_tool_use("tu_1", "missing", {}), _terminated()]) |
| 361 |
|
| 362 |
items = [item async for item in _run_with_fakes(events=events, tools=[])] |
| 363 |
|
| 364 |
assert len(items) == 1 |
| 365 |
assert items[0].is_error is False |
| 366 |
assert items[0].posted is False |
| 367 |
assert items[0].result is None |
| 368 |
assert events.send_calls == [] |
| 369 |
|
| 370 |
|
| 371 |
@pytest.mark.asyncio() |
| 372 |
async def test_skips_already_answered_events() -> None: |
| 373 |
"""Tool result already in history (via reconcile) should suppress |
| 374 |
re-execution of the same tool_use seen on the live stream.""" |
| 375 |
counter = {"calls": 0} |
| 376 |
|
| 377 |
async def increment(_input: dict[str, Any]) -> str: |
| 378 |
counter["calls"] += 1 |
| 379 |
return "done" |
| 380 |
|
| 381 |
tool = _FakeTool("inc", increment) |
| 382 |
events = FakeAsyncEvents( |
| 383 |
list_events=[_tool_use("tu_1", "inc", {}), _tool_result("tu_1")], |
| 384 |
stream_events=[_tool_use("tu_1", "inc", {}), _terminated()], |
| 385 |
) |
| 386 |
|
| 387 |
items = [item async for item in _run_with_fakes(events=events, tools=[tool])] |
| 388 |
|
| 389 |
assert counter["calls"] == 0 |
| 390 |
assert items == [] |
| 391 |
|
| 392 |
|
| 393 |
# ---------- custom-tool dispatch ------------------------------------------ |
| 394 |
|
| 395 |
|
| 396 |
@pytest.mark.asyncio() |
| 397 |
async def test_yields_completed_custom_tool_call() -> None: |
| 398 |
"""A CUSTOM (user-defined) tool call arrives as `agent.custom_tool_use` and |
| 399 |
must be answered with `user.custom_tool_result` — keyed by |
| 400 |
`custom_tool_use_id` — not `user.tool_result`.""" |
| 401 |
|
| 402 |
async def weather(input: dict[str, Any]) -> str: |
| 403 |
return f"sunny in {input.get('city')}" |
| 404 |
|
| 405 |
tool = _FakeTool("get_weather", weather) |
| 406 |
events = FakeAsyncEvents(stream_events=[_custom_tool_use("ctu_1", "get_weather", {"city": "SF"}), _terminated()]) |
| 407 |
|
| 408 |
items = [item async for item in _run_with_fakes(events=events, tools=[tool])] |
| 409 |
|
| 410 |
assert len(items) == 1 |
| 411 |
item = items[0] |
| 412 |
assert item.tool_use_id == "ctu_1" |
| 413 |
assert item.name == "get_weather" |
| 414 |
assert item.event.input == {"city": "SF"} |
| 415 |
assert item.is_error is False |
| 416 |
assert item.posted is True |
| 417 |
assert _result_text(item) == "sunny in SF" |
| 418 |
# The embedded event is the custom-tool-use event, and the posted-back |
| 419 |
# result is a custom tool result keyed by custom_tool_use_id. |
| 420 |
assert item.event.type == "agent.custom_tool_use" |
| 421 |
result = cast(Any, item.result) |
| 422 |
assert result["type"] == "user.custom_tool_result" |
| 423 |
assert result["custom_tool_use_id"] == "ctu_1" |
| 424 |
assert result.get("is_error") is False |
| 425 |
|
| 426 |
assert len(events.send_calls) == 1 |
| 427 |
sent = events.send_calls[0]["events"][0] |
| 428 |
assert sent["type"] == "user.custom_tool_result" |
| 429 |
assert sent["custom_tool_use_id"] == "ctu_1" |
| 430 |
assert sent["is_error"] is False |
| 431 |
|
| 432 |
|
| 433 |
@pytest.mark.asyncio() |
| 434 |
async def test_dispatches_builtin_and_custom_tools_in_one_stream() -> None: |
| 435 |
"""A single stream carrying both an `agent.tool_use` and an |
| 436 |
`agent.custom_tool_use` dispatches both, each answered with its matching |
| 437 |
result-event type.""" |
| 438 |
|
| 439 |
async def echo(input: dict[str, Any]) -> str: |
| 440 |
return f"echo {input.get('x')}" |
| 441 |
|
| 442 |
async def weather(_input: dict[str, Any]) -> str: |
| 443 |
return "sunny" |
| 444 |
|
| 445 |
events = FakeAsyncEvents( |
| 446 |
stream_events=[ |
| 447 |
_tool_use("tu_1", "echo", {"x": 1}), |
| 448 |
_custom_tool_use("ctu_1", "get_weather", {}), |
| 449 |
_terminated(), |
| 450 |
] |
| 451 |
) |
| 452 |
|
| 453 |
items = [ |
| 454 |
item |
| 455 |
async for item in _run_with_fakes( |
| 456 |
events=events, tools=[_FakeTool("echo", echo), _FakeTool("get_weather", weather)] |
| 457 |
) |
| 458 |
] |
| 459 |
|
| 460 |
by_id = {it.tool_use_id: it for it in items} |
| 461 |
assert set(by_id) == {"tu_1", "ctu_1"} |
| 462 |
builtin_result = by_id["tu_1"].result |
| 463 |
custom_result = by_id["ctu_1"].result |
| 464 |
assert builtin_result is not None and custom_result is not None |
| 465 |
assert by_id["tu_1"].event.type == "agent.tool_use" |
| 466 |
assert builtin_result["type"] == "user.tool_result" |
| 467 |
assert by_id["ctu_1"].event.type == "agent.custom_tool_use" |
| 468 |
assert custom_result["type"] == "user.custom_tool_result" |
| 469 |
# Both result events were posted, each with the matching type. |
| 470 |
posted = {call["events"][0]["type"] for call in events.send_calls} |
| 471 |
assert posted == {"user.tool_result", "user.custom_tool_result"} |
| 472 |
|
| 473 |
|
| 474 |
@pytest.mark.asyncio() |
| 475 |
async def test_skips_already_answered_custom_tool() -> None: |
| 476 |
"""A custom tool whose `user.custom_tool_result` is already in history (via |
| 477 |
reconcile) is not re-executed when the same `agent.custom_tool_use` is then |
| 478 |
seen on the live stream.""" |
| 479 |
counter = {"calls": 0} |
| 480 |
|
| 481 |
async def weather(_input: dict[str, Any]) -> str: |
| 482 |
counter["calls"] += 1 |
| 483 |
return "sunny" |
| 484 |
|
| 485 |
events = FakeAsyncEvents( |
| 486 |
list_events=[_custom_tool_use("ctu_1", "get_weather", {}), _custom_tool_result("ctu_1")], |
| 487 |
stream_events=[_custom_tool_use("ctu_1", "get_weather", {}), _terminated()], |
| 488 |
) |
| 489 |
|
| 490 |
items = [item async for item in _run_with_fakes(events=events, tools=[_FakeTool("get_weather", weather)])] |
| 491 |
|
| 492 |
assert counter["calls"] == 0 |
| 493 |
assert items == [] |
| 494 |
|
| 495 |
|
| 496 |
# ---------- skip unowned tools (split-client partial fulfillment) ----------- |
| 497 |
|
| 498 |
|
| 499 |
@pytest.mark.asyncio() |
| 500 |
async def test_skips_unowned_builtin_and_custom_tools_by_default() -> None: |
| 501 |
"""Default split-client behavior: a tool-call event whose name is not in |
| 502 |
the runner's registry belongs to the other client servicing the session |
| 503 |
(e.g. the customer's app backend handling custom tools). The runner must |
| 504 |
post NO result for it, claim nothing, and leave the `tool_use_id` |
| 505 |
pending — while still yielding the `DispatchedToolCall` so the caller can |
| 506 |
observe the unowned dispatch (`posted=False`, `is_error=False`, |
| 507 |
`result=None`). A registered tool in the same stream still runs, and the |
| 508 |
registry miss must not raise.""" |
| 509 |
ran = {"echo": 0} |
| 510 |
|
| 511 |
async def echo(_input: dict[str, Any]) -> str: |
| 512 |
ran["echo"] += 1 |
| 513 |
return "ok" |
| 514 |
|
| 515 |
events = FakeAsyncEvents( |
| 516 |
stream_events=[ |
| 517 |
_tool_use("evt_99", "not_ours", {}), |
| 518 |
_custom_tool_use("cevt_99", "app_backend_tool", {}), |
| 519 |
_tool_use("tu_ok", "echo", {}), |
| 520 |
_terminated(), |
| 521 |
] |
| 522 |
) |
| 523 |
|
| 524 |
items = [item async for item in _run_with_fakes(events=events, tools=[_FakeTool("echo", echo)])] |
| 525 |
|
| 526 |
by_id = {it.tool_use_id: it for it in items} |
| 527 |
assert set(by_id) == {"evt_99", "cevt_99", "tu_ok"} |
| 528 |
|
| 529 |
builtin = by_id["evt_99"] |
| 530 |
assert builtin.name == "not_ours" |
| 531 |
assert builtin.event.type == "agent.tool_use" |
| 532 |
assert builtin.is_error is False, "a skipped call is not an error" |
| 533 |
assert builtin.posted is False, "nothing was sent for an unowned tool" |
| 534 |
assert builtin.result is None, "no user.tool_result was ever built" |
| 535 |
|
| 536 |
custom = by_id["cevt_99"] |
| 537 |
assert custom.name == "app_backend_tool" |
| 538 |
assert custom.event.type == "agent.custom_tool_use" |
| 539 |
assert custom.is_error is False, "a skipped call is not an error" |
| 540 |
assert custom.posted is False, "nothing was sent for an unowned custom tool" |
| 541 |
assert custom.result is None, "no user.custom_tool_result was ever built" |
| 542 |
|
| 543 |
owned = by_id["tu_ok"] |
| 544 |
assert owned.is_error is False |
| 545 |
assert owned.posted is True |
| 546 |
assert owned.result is not None and owned.result["type"] == "user.tool_result" |
| 547 |
|
| 548 |
assert ran["echo"] == 1, "the registered tool should still have run" |
| 549 |
# Only the owned tool's result reached the session; nothing for the unowned. |
| 550 |
assert len(events.send_calls) == 1 |
| 551 |
assert events.send_calls[0]["events"][0]["tool_use_id"] == "tu_ok" |
| 552 |
|
| 553 |
|
| 554 |
@pytest.mark.asyncio() |
| 555 |
async def test_skipped_unowned_tool_does_not_trip_idle() -> None: |
| 556 |
"""A skipped (unanswered) unowned tool_use stays OUT of the end-turn |
| 557 |
accounting: reconcile sees history ending on an `end_turn` idle but with |
| 558 |
the unowned tool_use still unanswered, so it must NOT arm the idle |
| 559 |
countdown — the runner has not handled that call, its owner still has to. |
| 560 |
|
| 561 |
A correct runner therefore stays alive past `max_idle` (the iterator |
| 562 |
never completes); a buggy one would idle-stop almost immediately. |
| 563 |
""" |
| 564 |
events = FakeAsyncEvents( |
| 565 |
# No live events — the reconcile pass drives the test. History ends on |
| 566 |
# an end_turn idle with the unowned tool_use still unanswered. |
| 567 |
list_events=[_tool_use("evt_pending", "not_ours", {}), _idle_end_turn()], |
| 568 |
stream_events=[], |
| 569 |
) |
| 570 |
seen: list[DispatchedToolCall] = [] |
| 571 |
|
| 572 |
async def drive() -> None: |
| 573 |
async for call in _run_with_fakes(events=events, tools=[], max_idle=0.1): |
| 574 |
seen.append(call) |
| 575 |
|
| 576 |
# If the unowned tool wrongly armed the idle clock the runner would stop |
| 577 |
# ~0.1s in and `drive()` would return; a correct runner blocks until the |
| 578 |
# (never-arriving) owner answers, so `wait_for` must time out instead. |
| 579 |
with pytest.raises((asyncio.TimeoutError, TimeoutError)): |
| 580 |
await asyncio.wait_for(drive(), timeout=1.0) |
| 581 |
|
| 582 |
assert len(seen) >= 1, "reconcile must still surface the unowned call" |
| 583 |
call = seen[0] |
| 584 |
assert call.tool_use_id == "evt_pending" |
| 585 |
assert call.posted is False |
| 586 |
assert call.is_error is False |
| 587 |
assert call.result is None, "no result was built for the skipped call" |
| 588 |
assert events.send_calls == [], "runner must not post a result it does not own" |
| 589 |
|
| 590 |
|
| 591 |
# ---------- confirmation gating (always_ask tools) -------------------------- |
| 592 |
|
| 593 |
|
| 594 |
@pytest.mark.asyncio() |
| 595 |
async def test_ask_tool_blocks_without_confirmation() -> None: |
| 596 |
"""An `agent.tool_use` whose `evaluated_permission` is `ask` (an |
| 597 |
`always_ask` tool) must NOT execute on arrival — it is held until the |
| 598 |
matching `user.tool_confirmation` event. Here none ever arrives, so the |
| 599 |
tool never runs, nothing is posted, and nothing is yielded.""" |
| 600 |
counter = {"calls": 0} |
| 601 |
|
| 602 |
async def gated(_input: dict[str, Any]) -> str: |
| 603 |
counter["calls"] += 1 |
| 604 |
return "ran" |
| 605 |
|
| 606 |
tool = _FakeTool("gated", gated) |
| 607 |
events = FakeAsyncEvents(stream_events=[_tool_use("tu_1", "gated", {}, evaluated_permission="ask"), _terminated()]) |
| 608 |
|
| 609 |
items = [item async for item in _run_with_fakes(events=events, tools=[tool])] |
| 610 |
|
| 611 |
assert counter["calls"] == 0, "an ask-gated tool must not run before its confirmation" |
| 612 |
assert events.send_calls == [], "no result may be posted for an unconfirmed call" |
| 613 |
assert items == [] |
| 614 |
|
| 615 |
|
| 616 |
@pytest.mark.asyncio() |
| 617 |
async def test_ask_tool_executes_after_allow_confirmation() -> None: |
| 618 |
"""An `allow` confirmation releases the held call: the tool runs, the |
| 619 |
result is posted, and the yielded call records `confirmation="allow"`.""" |
| 620 |
counter = {"calls": 0} |
| 621 |
|
| 622 |
async def gated(_input: dict[str, Any]) -> str: |
| 623 |
counter["calls"] += 1 |
| 624 |
return "ran" |
| 625 |
|
| 626 |
tool = _FakeTool("gated", gated) |
| 627 |
events = FakeAsyncEvents( |
| 628 |
stream_events=[ |
| 629 |
_tool_use("tu_1", "gated", {}, evaluated_permission="ask"), |
| 630 |
_tool_confirmation("tu_1", "allow"), |
| 631 |
_terminated(), |
| 632 |
] |
| 633 |
) |
| 634 |
|
| 635 |
items = [item async for item in _run_with_fakes(events=events, tools=[tool])] |
| 636 |
|
| 637 |
assert counter["calls"] == 1 |
| 638 |
assert len(items) == 1 |
| 639 |
call = items[0] |
| 640 |
assert call.confirmation == "allow" |
| 641 |
assert call.posted is True |
| 642 |
assert call.is_error is False |
| 643 |
assert _result_text(call) == "ran" |
| 644 |
assert len(events.send_calls) == 1 |
| 645 |
assert events.send_calls[0]["events"][0]["tool_use_id"] == "tu_1" |
| 646 |
|
| 647 |
|
| 648 |
@pytest.mark.asyncio() |
| 649 |
async def test_ask_tool_denied_never_executes() -> None: |
| 650 |
"""A `deny` confirmation resolves the held call without executing it: |
| 651 |
nothing runs, nothing is posted (the denial itself resolves the call |
| 652 |
server-side), and the call is still yielded for observability with |
| 653 |
`confirmation="deny"` / `posted=False` / `result=None`.""" |
| 654 |
counter = {"calls": 0} |
| 655 |
|
| 656 |
async def gated(_input: dict[str, Any]) -> str: |
| 657 |
counter["calls"] += 1 |
| 658 |
return "ran" |
| 659 |
|
| 660 |
tool = _FakeTool("gated", gated) |
| 661 |
events = FakeAsyncEvents( |
| 662 |
stream_events=[ |
| 663 |
_tool_use("tu_1", "gated", {}, evaluated_permission="ask"), |
| 664 |
_tool_confirmation("tu_1", "deny"), |
| 665 |
_terminated(), |
| 666 |
] |
| 667 |
) |
| 668 |
|
| 669 |
items = [item async for item in _run_with_fakes(events=events, tools=[tool])] |
| 670 |
|
| 671 |
assert counter["calls"] == 0, "a denied tool must never run" |
| 672 |
assert events.send_calls == [], "the denial resolves the call; the runner must post nothing" |
| 673 |
assert len(items) == 1 |
| 674 |
call = items[0] |
| 675 |
assert call.confirmation == "deny" |
| 676 |
assert call.posted is False |
| 677 |
assert call.is_error is False |
| 678 |
assert call.result is None |
| 679 |
|
| 680 |
|
| 681 |
@pytest.mark.asyncio() |
| 682 |
async def test_pre_denied_tool_never_executes() -> None: |
| 683 |
"""A call the server already evaluated to `deny` needs no confirmation — |
| 684 |
it must never execute and nothing may be posted for it.""" |
| 685 |
counter = {"calls": 0} |
| 686 |
|
| 687 |
async def gated(_input: dict[str, Any]) -> str: |
| 688 |
counter["calls"] += 1 |
| 689 |
return "ran" |
| 690 |
|
| 691 |
tool = _FakeTool("gated", gated) |
| 692 |
events = FakeAsyncEvents(stream_events=[_tool_use("tu_1", "gated", {}, evaluated_permission="deny"), _terminated()]) |
| 693 |
|
| 694 |
items = [item async for item in _run_with_fakes(events=events, tools=[tool])] |
| 695 |
|
| 696 |
assert counter["calls"] == 0 |
| 697 |
assert events.send_calls == [] |
| 698 |
assert len(items) == 1 |
| 699 |
assert items[0].confirmation == "deny" |
| 700 |
assert items[0].posted is False |
| 701 |
assert items[0].result is None |
| 702 |
|
| 703 |
|
| 704 |
@pytest.mark.asyncio() |
| 705 |
async def test_confirmation_in_history_releases_ask_call() -> None: |
| 706 |
"""An ask-gated call whose `allow` confirmation is already in history |
| 707 |
(e.g. it was posted while the runner was disconnected) executes on the |
| 708 |
reconcile pass — the verdict is recorded before pending calls are routed.""" |
| 709 |
counter = {"calls": 0} |
| 710 |
|
| 711 |
async def gated(_input: dict[str, Any]) -> str: |
| 712 |
counter["calls"] += 1 |
| 713 |
return "ran" |
| 714 |
|
| 715 |
tool = _FakeTool("gated", gated) |
| 716 |
events = FakeAsyncEvents( |
| 717 |
list_events=[ |
| 718 |
_tool_use("tu_1", "gated", {}, evaluated_permission="ask"), |
| 719 |
_tool_confirmation("tu_1", "allow"), |
| 720 |
], |
| 721 |
stream_events=[_terminated()], |
| 722 |
) |
| 723 |
|
| 724 |
items = [item async for item in _run_with_fakes(events=events, tools=[tool])] |
| 725 |
|
| 726 |
assert counter["calls"] == 1 |
| 727 |
assert len(items) == 1 |
| 728 |
assert items[0].confirmation == "allow" |
| 729 |
assert items[0].posted is True |
| 730 |
|
| 731 |
|
| 732 |
@pytest.mark.asyncio() |
| 733 |
async def test_denied_ask_call_does_not_block_idle_stop() -> None: |
| 734 |
"""A denied call counts as resolved in the reconcile idle accounting: |
| 735 |
history ends on an `end_turn` idle with the denied call unanswered (no |
| 736 |
result event ever exists for it), and the runner must still arm the idle |
| 737 |
countdown and stop on its own rather than wait forever for a result.""" |
| 738 |
events = FakeAsyncEvents( |
| 739 |
list_events=[ |
| 740 |
_tool_use("tu_1", "gated", {}, evaluated_permission="ask"), |
| 741 |
_tool_confirmation("tu_1", "deny"), |
| 742 |
_idle_end_turn(), |
| 743 |
], |
| 744 |
stream_events=[], |
| 745 |
) |
| 746 |
|
| 747 |
items = [item async for item in _run_with_fakes(events=events, tools=[], max_idle=0.05)] |
| 748 |
|
| 749 |
assert len(items) == 1 |
| 750 |
assert items[0].confirmation == "deny" |
| 751 |
assert events.send_calls == [] |
| 752 |
|
| 753 |
|
| 754 |
@pytest.mark.asyncio() |
| 755 |
async def test_held_ask_call_keeps_runner_alive() -> None: |
| 756 |
"""While a call awaits its confirmation the runner must keep running — |
| 757 |
even if history (defensively) ends on an `end_turn` idle — so the |
| 758 |
verdict can still arrive and be acted on.""" |
| 759 |
counter = {"calls": 0} |
| 760 |
|
| 761 |
async def gated(_input: dict[str, Any]) -> str: |
| 762 |
counter["calls"] += 1 |
| 763 |
return "ran" |
| 764 |
|
| 765 |
tool = _FakeTool("gated", gated) |
| 766 |
events = FakeAsyncEvents( |
| 767 |
list_events=[_tool_use("tu_1", "gated", {}, evaluated_permission="ask"), _idle_end_turn()], |
| 768 |
stream_events=[], |
| 769 |
) |
| 770 |
|
| 771 |
async def drive() -> None: |
| 772 |
async for _ in _run_with_fakes(events=events, tools=[tool], max_idle=0.1): |
| 773 |
pass |
| 774 |
|
| 775 |
# A runner that wrongly armed the idle clock would stop ~0.1s in and |
| 776 |
# `drive()` would return; a correct one blocks awaiting the confirmation. |
| 777 |
with pytest.raises((asyncio.TimeoutError, TimeoutError)): |
| 778 |
await asyncio.wait_for(drive(), timeout=1.0) |
| 779 |
|
| 780 |
assert counter["calls"] == 0 |
| 781 |
assert events.send_calls == [] |
| 782 |
|
| 783 |
|
| 784 |
@pytest.mark.asyncio() |
| 785 |
async def test_live_idle_while_call_held_keeps_runner_alive() -> None: |
| 786 |
"""An `end_turn` idle arriving on the LIVE stream while a call is held |
| 787 |
for confirmation must not start the idle countdown — stopping would drop |
| 788 |
the call when its verdict later arrives. (The reconcile-path counterpart |
| 789 |
is `test_held_ask_call_keeps_runner_alive`.)""" |
| 790 |
counter = {"calls": 0} |
| 791 |
|
| 792 |
async def gated(_input: dict[str, Any]) -> str: |
| 793 |
counter["calls"] += 1 |
| 794 |
return "ran" |
| 795 |
|
| 796 |
tool = _FakeTool("gated", gated) |
| 797 |
events = FakeAsyncEvents( |
| 798 |
stream_events=[_tool_use("tu_1", "gated", {}, evaluated_permission="ask"), _idle_end_turn()], |
| 799 |
) |
| 800 |
|
| 801 |
async def drive() -> None: |
| 802 |
async for _ in _run_with_fakes(events=events, tools=[tool], max_idle=0.1): |
| 803 |
pass |
| 804 |
|
| 805 |
# A runner that armed the idle clock would stop ~0.1s in and `drive()` |
| 806 |
# would return; a correct one blocks awaiting the confirmation. |
| 807 |
with pytest.raises((asyncio.TimeoutError, TimeoutError)): |
| 808 |
await asyncio.wait_for(drive(), timeout=1.0) |
| 809 |
|
| 810 |
assert counter["calls"] == 0 |
| 811 |
assert events.send_calls == [] |
| 812 |
|
| 813 |
|
| 814 |
@pytest.mark.asyncio() |
| 815 |
async def test_reconnect_does_not_double_dispatch_held_call(monkeypatch: pytest.MonkeyPatch) -> None: |
| 816 |
"""A call held on the live stream whose `allow` confirmation shows up in |
| 817 |
the reconcile history after a reconnect is dispatched exactly once: the |
| 818 |
routing pass applies the recorded verdict, the history loop must not also |
| 819 |
release the held copy. The first result post fails permanently so a |
| 820 |
duplicate enqueue would visibly re-execute the tool.""" |
| 821 |
monkeypatch.setattr(session_runner_mod, "STREAM_BACKOFF_START", 0.01) |
| 822 |
counter = {"calls": 0} |
| 823 |
|
| 824 |
async def gated(_input: dict[str, Any]) -> str: |
| 825 |
counter["calls"] += 1 |
| 826 |
return "ran" |
| 827 |
|
| 828 |
tool = _FakeTool("gated", gated) |
| 829 |
gated_call = _tool_use("tu_1", "gated", {}, evaluated_permission="ask") |
| 830 |
events = FakeAsyncEvents( |
| 831 |
streams=[ |
| 832 |
# First connection: the gated call arrives live (and is held), then |
| 833 |
# the stream drops with a transient error. |
| 834 |
_FakeStream([gated_call], raise_after=1, raise_with=httpx2.ReadError("dropped")), |
| 835 |
_FakeStream([_terminated()]), |
| 836 |
], |
| 837 |
# The reconcile after the reconnect sees both the held call and its |
| 838 |
# allow verdict; the initial reconcile saw an empty history. |
| 839 |
list_events_per_call=[[], [gated_call, _tool_confirmation("tu_1", "allow")]], |
| 840 |
send_failures=[_api_status_error(400)], |
| 841 |
) |
| 842 |
|
| 843 |
items = [item async for item in _run_with_fakes(events=events, tools=[tool])] |
| 844 |
|
| 845 |
assert counter["calls"] == 1, "the confirmed call must be dispatched exactly once" |
| 846 |
assert len([it for it in items if it.tool_use_id == "tu_1"]) == 1 |
| 847 |
|
| 848 |
|
| 849 |
@pytest.mark.asyncio() |
| 850 |
async def test_reconcile_confirmation_releases_call_held_from_live_stream(monkeypatch: pytest.MonkeyPatch) -> None: |
| 851 |
"""A confirmation that only ever appears in the reconcile history (its |
| 852 |
tool_use event is not in the listed window — it was held from the live |
| 853 |
stream before the disconnect) still releases the held call.""" |
| 854 |
monkeypatch.setattr(session_runner_mod, "STREAM_BACKOFF_START", 0.01) |
| 855 |
counter = {"calls": 0} |
| 856 |
|
| 857 |
async def gated(_input: dict[str, Any]) -> str: |
| 858 |
counter["calls"] += 1 |
| 859 |
return "ran" |
| 860 |
|
| 861 |
tool = _FakeTool("gated", gated) |
| 862 |
events = FakeAsyncEvents( |
| 863 |
streams=[ |
| 864 |
_FakeStream( |
| 865 |
[_tool_use("tu_1", "gated", {}, evaluated_permission="ask")], |
| 866 |
raise_after=1, |
| 867 |
raise_with=httpx2.ReadError("dropped"), |
| 868 |
), |
| 869 |
_FakeStream([_terminated()]), |
| 870 |
], |
| 871 |
list_events_per_call=[[], [_tool_confirmation("tu_1", "allow")]], |
| 872 |
) |
| 873 |
|
| 874 |
items = [item async for item in _run_with_fakes(events=events, tools=[tool])] |
| 875 |
|
| 876 |
assert counter["calls"] == 1 |
| 877 |
assert len(items) == 1 |
| 878 |
assert items[0].confirmation == "allow" |
| 879 |
assert items[0].posted is True |
| 880 |
|
| 881 |
|
| 882 |
@pytest.mark.asyncio() |
| 883 |
async def test_held_ask_call_does_not_block_other_dispatches() -> None: |
| 884 |
"""Holding an ask-gated call must not stall the rest of the queue: an |
| 885 |
ungated call arriving after it executes immediately, and the gated call |
| 886 |
follows once its confirmation lands.""" |
| 887 |
|
| 888 |
async def echo(_input: dict[str, Any]) -> str: |
| 889 |
return "echo" |
| 890 |
|
| 891 |
async def gated(_input: dict[str, Any]) -> str: |
| 892 |
return "gated" |
| 893 |
|
| 894 |
events = FakeAsyncEvents( |
| 895 |
stream_events=[ |
| 896 |
_tool_use("tu_gated", "gated", {}, evaluated_permission="ask"), |
| 897 |
_tool_use("tu_echo", "echo", {}), |
| 898 |
_tool_confirmation("tu_gated", "allow"), |
| 899 |
_terminated(), |
| 900 |
] |
| 901 |
) |
| 902 |
|
| 903 |
items = [ |
| 904 |
item |
| 905 |
async for item in _run_with_fakes(events=events, tools=[_FakeTool("echo", echo), _FakeTool("gated", gated)]) |
| 906 |
] |
| 907 |
|
| 908 |
by_id = {it.tool_use_id: it for it in items} |
| 909 |
assert set(by_id) == {"tu_gated", "tu_echo"} |
| 910 |
assert by_id["tu_echo"].confirmation is None |
| 911 |
assert by_id["tu_echo"].posted is True |
| 912 |
assert by_id["tu_gated"].confirmation == "allow" |
| 913 |
assert by_id["tu_gated"].posted is True |
| 914 |
# The ungated call was not held up behind the gated one: its result was |
| 915 |
# posted first, the gated one only after its confirmation arrived. |
| 916 |
posted_ids = [call["events"][0]["tool_use_id"] for call in events.send_calls] |
| 917 |
assert posted_ids == ["tu_echo", "tu_gated"] |
| 918 |
|
| 919 |
|
| 920 |
@pytest.mark.asyncio() |
| 921 |
async def test_confirmation_for_unknown_id_is_ignored() -> None: |
| 922 |
"""A confirmation for a call this runner has never seen (another client's |
| 923 |
call, or an `agent.mcp_tool_use` it never dispatches) is recorded but |
| 924 |
must not crash or yield anything.""" |
| 925 |
events = FakeAsyncEvents(stream_events=[_tool_confirmation("tu_elsewhere", "allow"), _terminated()]) |
| 926 |
|
| 927 |
items = [item async for item in _run_with_fakes(events=events, tools=[])] |
| 928 |
|
| 929 |
assert items == [] |
| 930 |
assert events.send_calls == [] |
| 931 |
|
| 932 |
|
| 933 |
@pytest.mark.asyncio() |
| 934 |
async def test_unrecognised_verdict_fails_closed() -> None: |
| 935 |
"""The gate is an allow-list: a confirmation whose `result` is a value |
| 936 |
this SDK doesn't recognise (the wire can carry values newer than our |
| 937 |
types) must NOT release the held call — it is resolved as a denial.""" |
| 938 |
counter = {"calls": 0} |
| 939 |
|
| 940 |
async def gated(_input: dict[str, Any]) -> str: |
| 941 |
counter["calls"] += 1 |
| 942 |
return "ran" |
| 943 |
|
| 944 |
tool = _FakeTool("gated", gated) |
| 945 |
events = FakeAsyncEvents( |
| 946 |
stream_events=[ |
| 947 |
_tool_use("tu_1", "gated", {}, evaluated_permission="ask"), |
| 948 |
_tool_confirmation("tu_1", "escalate"), # not "allow"/"deny" |
| 949 |
_terminated(), |
| 950 |
] |
| 951 |
) |
| 952 |
|
| 953 |
items = [item async for item in _run_with_fakes(events=events, tools=[tool])] |
| 954 |
|
| 955 |
assert counter["calls"] == 0, "only an explicit allow may release a gated call" |
| 956 |
assert events.send_calls == [] |
| 957 |
assert len(items) == 1 |
| 958 |
assert items[0].confirmation == "deny" |
| 959 |
assert items[0].result is None |
| 960 |
|
| 961 |
|
| 962 |
@pytest.mark.asyncio() |
| 963 |
async def test_unrecognised_permission_fails_closed() -> None: |
| 964 |
"""An `evaluated_permission` value this SDK doesn't recognise must not |
| 965 |
dispatch unconfirmed — it is held like `ask` and released only by an |
| 966 |
explicit `allow` verdict.""" |
| 967 |
counter = {"calls": 0} |
| 968 |
|
| 969 |
async def gated(_input: dict[str, Any]) -> str: |
| 970 |
counter["calls"] += 1 |
| 971 |
return "ran" |
| 972 |
|
| 973 |
tool = _FakeTool("gated", gated) |
| 974 |
# Without a confirmation the call must never run... |
| 975 |
events = FakeAsyncEvents( |
| 976 |
stream_events=[_tool_use("tu_1", "gated", {}, evaluated_permission="ask_strict"), _terminated()] |
| 977 |
) |
| 978 |
items = [item async for item in _run_with_fakes(events=events, tools=[tool])] |
| 979 |
assert counter["calls"] == 0 |
| 980 |
assert items == [] |
| 981 |
|
| 982 |
# ...while an explicit allow still releases it. |
| 983 |
events = FakeAsyncEvents( |
| 984 |
stream_events=[ |
| 985 |
_tool_use("tu_2", "gated", {}, evaluated_permission="ask_strict"), |
| 986 |
_tool_confirmation("tu_2", "allow"), |
| 987 |
_terminated(), |
| 988 |
] |
| 989 |
) |
| 990 |
items = [item async for item in _run_with_fakes(events=events, tools=[tool])] |
| 991 |
assert counter["calls"] == 1 |
| 992 |
assert len(items) == 1 |
| 993 |
assert items[0].posted is True |
| 994 |
|
| 995 |
|
| 996 |
@pytest.mark.asyncio() |
| 997 |
async def test_pre_denied_tool_ignores_stray_allow_verdict() -> None: |
| 998 |
"""A call the server already evaluated to `deny` must never execute, |
| 999 |
even if an (anomalous) `allow` confirmation exists for its id.""" |
| 1000 |
counter = {"calls": 0} |
| 1001 |
|
| 1002 |
async def gated(_input: dict[str, Any]) -> str: |
| 1003 |
counter["calls"] += 1 |
| 1004 |
return "ran" |
| 1005 |
|
| 1006 |
tool = _FakeTool("gated", gated) |
| 1007 |
events = FakeAsyncEvents( |
| 1008 |
stream_events=[ |
| 1009 |
# Confirmation first so the verdict is already recorded when the |
| 1010 |
# pre-denied call is routed. |
| 1011 |
_tool_confirmation("tu_1", "allow"), |
| 1012 |
_tool_use("tu_1", "gated", {}, evaluated_permission="deny"), |
| 1013 |
_terminated(), |
| 1014 |
] |
| 1015 |
) |
| 1016 |
|
| 1017 |
items = [item async for item in _run_with_fakes(events=events, tools=[tool])] |
| 1018 |
|
| 1019 |
assert counter["calls"] == 0, "a server-denied call must never execute" |
| 1020 |
assert events.send_calls == [] |
| 1021 |
assert len(items) == 1 |
| 1022 |
assert items[0].confirmation == "deny" |
| 1023 |
|
| 1024 |
|
| 1025 |
@pytest.mark.asyncio() |
| 1026 |
async def test_ungated_tool_with_stray_deny_verdict_resolves_as_denied() -> None: |
| 1027 |
"""Mirror of `test_pre_denied_tool_ignores_stray_allow_verdict`: a stray |
| 1028 |
`deny` verdict recorded before an ungated call is routed resolves the |
| 1029 |
call as denied without executing it — any deny signal wins (the gate fails |
| 1030 |
closed).""" |
| 1031 |
counter = {"calls": 0} |
| 1032 |
|
| 1033 |
async def echo(_input: dict[str, Any]) -> str: |
| 1034 |
counter["calls"] += 1 |
| 1035 |
return "ran" |
| 1036 |
|
| 1037 |
tool = _FakeTool("echo", echo) |
| 1038 |
events = FakeAsyncEvents( |
| 1039 |
stream_events=[ |
| 1040 |
# Confirmation first so the stray verdict is already recorded when |
| 1041 |
# the ungated call is routed. |
| 1042 |
_tool_confirmation("tu_1", "deny"), |
| 1043 |
_tool_use("tu_1", "echo", {}), |
| 1044 |
_terminated(), |
| 1045 |
] |
| 1046 |
) |
| 1047 |
|
| 1048 |
items = [item async for item in _run_with_fakes(events=events, tools=[tool])] |
| 1049 |
|
| 1050 |
assert counter["calls"] == 0, "a deny verdict must suppress the call even if it was never gated" |
| 1051 |
assert events.send_calls == [] |
| 1052 |
assert len(items) == 1 |
| 1053 |
assert items[0].confirmation == "deny" |
| 1054 |
assert items[0].posted is False |
| 1055 |
assert items[0].result is None |
| 1056 |
|
| 1057 |
|
| 1058 |
@pytest.mark.asyncio() |
| 1059 |
async def test_deny_after_live_end_turn_resumes_idle_stop() -> None: |
| 1060 |
"""A `deny` that resolves the last held call must let the idle countdown |
| 1061 |
resume: the session already went idle (`end_turn`) while the call was |
| 1062 |
held, the denial produces no further stream events, and the runner must |
| 1063 |
stop on its own instead of waiting forever.""" |
| 1064 |
counter = {"calls": 0} |
| 1065 |
|
| 1066 |
async def gated(_input: dict[str, Any]) -> str: |
| 1067 |
counter["calls"] += 1 |
| 1068 |
return "ran" |
| 1069 |
|
| 1070 |
tool = _FakeTool("gated", gated) |
| 1071 |
events = FakeAsyncEvents( |
| 1072 |
stream_events=[ |
| 1073 |
_tool_use("tu_1", "gated", {}, evaluated_permission="ask"), |
| 1074 |
_idle_end_turn(), |
| 1075 |
_tool_confirmation("tu_1", "deny"), |
| 1076 |
] |
| 1077 |
) |
| 1078 |
|
| 1079 |
async def drive() -> list[DispatchedToolCall]: |
| 1080 |
return [item async for item in _run_with_fakes(events=events, tools=[tool], max_idle=0.05)] |
| 1081 |
|
| 1082 |
# A runner that lost the end_turn while the call was held hangs here (the |
| 1083 |
# stream never produces another event) and `wait_for` would time out. |
| 1084 |
items = await asyncio.wait_for(drive(), timeout=2.0) |
| 1085 |
|
| 1086 |
assert counter["calls"] == 0 |
| 1087 |
assert events.send_calls == [] |
| 1088 |
assert len(items) == 1 |
| 1089 |
assert items[0].confirmation == "deny" |
| 1090 |
|
| 1091 |
|
| 1092 |
@pytest.mark.asyncio() |
| 1093 |
async def test_reconcile_released_call_not_cut_short_by_idle(monkeypatch: pytest.MonkeyPatch) -> None: |
| 1094 |
"""A held call released by the reconcile pass (its allow verdict only shows |
| 1095 |
up in history after a reconnect) is in-flight work: even if that history |
| 1096 |
ends on an `end_turn` idle, the idle countdown must not run while the |
| 1097 |
released tool is still executing. Only once the call is fully dispatched |
| 1098 |
does the deferred countdown start, granting a fresh grace window for the |
| 1099 |
events its posted result will produce.""" |
| 1100 |
monkeypatch.setattr(session_runner_mod, "STREAM_BACKOFF_START", 0.01) |
| 1101 |
max_idle = 0.4 |
| 1102 |
counter = {"calls": 0} |
| 1103 |
|
| 1104 |
async def slow_gated(_input: dict[str, Any]) -> str: |
| 1105 |
counter["calls"] += 1 |
| 1106 |
await asyncio.sleep(0.6) |
| 1107 |
return "ran" |
| 1108 |
|
| 1109 |
tool = _FakeTool("gated", slow_gated) |
| 1110 |
events = FakeAsyncEvents( |
| 1111 |
streams=[ |
| 1112 |
# The gated call arrives live (and is held), then the stream drops. |
| 1113 |
_FakeStream( |
| 1114 |
[_tool_use("tu_1", "gated", {}, evaluated_permission="ask")], |
| 1115 |
raise_after=1, |
| 1116 |
raise_with=httpx2.ReadError("dropped"), |
| 1117 |
), |
| 1118 |
_FakeStream([]), |
| 1119 |
], |
| 1120 |
# The reconcile after the reconnect sees only the verdict and the idle: |
| 1121 |
# the original tool_use event has scrolled out of the listed window. |
| 1122 |
list_events_per_call=[[], [_tool_confirmation("tu_1", "allow"), _idle_end_turn()]], |
| 1123 |
) |
| 1124 |
|
| 1125 |
seen: list[DispatchedToolCall] = [] |
| 1126 |
|
| 1127 |
async def drive() -> None: |
| 1128 |
async for call in _run_with_fakes(events=events, tools=[tool], max_idle=max_idle): |
| 1129 |
seen.append(call) |
| 1130 |
|
| 1131 |
async def run_and_time() -> tuple[float, float]: |
| 1132 |
loop = asyncio.get_running_loop() |
| 1133 |
task = asyncio.ensure_future(drive()) |
| 1134 |
while not events.send_calls: |
| 1135 |
await asyncio.sleep(0.01) |
| 1136 |
posted_at = loop.time() |
| 1137 |
await task |
| 1138 |
return posted_at, loop.time() |
| 1139 |
|
| 1140 |
posted_at, stopped_at = await asyncio.wait_for(run_and_time(), timeout=5.0) |
| 1141 |
|
| 1142 |
assert counter["calls"] == 1 |
| 1143 |
assert len(seen) == 1 |
| 1144 |
assert seen[0].confirmation == "allow" |
| 1145 |
assert seen[0].posted is True |
| 1146 |
# A runner that armed the idle clock during the reconcile has its countdown |
| 1147 |
# already expired by the time the slow tool finishes (0.6s > max_idle) and |
| 1148 |
# stops immediately after posting; the deferred countdown instead starts |
| 1149 |
# only once the call is dispatched, so the runner stays up for roughly a |
| 1150 |
# full grace window after the post. |
| 1151 |
assert stopped_at - posted_at > max_idle * 0.6 |
| 1152 |
|
| 1153 |
|
| 1154 |
@pytest.mark.asyncio() |
| 1155 |
async def test_idle_after_end_turn_ends_iteration() -> None: |
| 1156 |
# The session goes idle with stop_reason end_turn and nothing else happens; |
| 1157 |
# after `max_idle` seconds the runner stops on its own. |
| 1158 |
events = FakeAsyncEvents(stream_events=[_idle_end_turn()]) |
| 1159 |
|
| 1160 |
items = [item async for item in _run_with_fakes(events=events, tools=[], max_idle=0.05)] |
| 1161 |
|
| 1162 |
assert items == [] |
| 1163 |
|
| 1164 |
|
| 1165 |
@pytest.mark.asyncio() |
| 1166 |
async def test_idle_grace_does_not_fire_without_end_turn() -> None: |
| 1167 |
# No end_turn idle is ever seen, so the grace timer never arms — the runner |
| 1168 |
# only stops because the stream delivers a terminated event. |
| 1169 |
async def echo(input: dict[str, Any]) -> str: |
| 1170 |
return f"got {input.get('x')}" |
| 1171 |
|
| 1172 |
events = FakeAsyncEvents(stream_events=[_tool_use("tu_1", "echo", {"x": 1}), _terminated()]) |
| 1173 |
|
| 1174 |
items = [item async for item in _run_with_fakes(events=events, tools=[_FakeTool("echo", echo)], max_idle=0.05)] |
| 1175 |
|
| 1176 |
assert [it.tool_use_id for it in items] == ["tu_1"] |
| 1177 |
|
| 1178 |
|
| 1179 |
@pytest.mark.asyncio() |
| 1180 |
async def test_new_event_resets_idle_grace() -> None: |
| 1181 |
# end_turn arms the grace timer, then a tool_use arrives and resets it; the |
| 1182 |
# tool is dispatched and the runner only stops on the terminated event. |
| 1183 |
async def echo(input: dict[str, Any]) -> str: |
| 1184 |
return f"got {input.get('x')}" |
| 1185 |
|
| 1186 |
events = FakeAsyncEvents(stream_events=[_idle_end_turn(), _tool_use("tu_1", "echo", {"x": 1}), _terminated()]) |
| 1187 |
|
| 1188 |
# Generous grace so the timer can't fire between the scripted events. |
| 1189 |
items = [item async for item in _run_with_fakes(events=events, tools=[_FakeTool("echo", echo)], max_idle=5.0)] |
| 1190 |
|
| 1191 |
assert [it.tool_use_id for it in items] == ["tu_1"] |
| 1192 |
|
| 1193 |
|
| 1194 |
@pytest.mark.asyncio() |
| 1195 |
async def test_terminated_event_ends_iteration() -> None: |
| 1196 |
events = FakeAsyncEvents(stream_events=[_terminated()]) |
| 1197 |
|
| 1198 |
items = [item async for item in _run_with_fakes(events=events, tools=[])] |
| 1199 |
|
| 1200 |
assert items == [] |
| 1201 |
|
| 1202 |
|
| 1203 |
# ---------- tool cleanup -------------------------------------------------- |
| 1204 |
|
| 1205 |
|
| 1206 |
@pytest.mark.asyncio() |
| 1207 |
async def test_runs_tool_close_hook_on_exit() -> None: |
| 1208 |
"""The runner calls each tool's optional `close` cleanup hook when the |
| 1209 |
iteration ends, regardless of cause.""" |
| 1210 |
closed = {"count": 0} |
| 1211 |
|
| 1212 |
def _close() -> None: |
| 1213 |
closed["count"] += 1 |
| 1214 |
|
| 1215 |
async def echo(_input: dict[str, Any]) -> str: |
| 1216 |
return "ok" |
| 1217 |
|
| 1218 |
tool = _FakeTool("echo", echo, close=_close) |
| 1219 |
events = FakeAsyncEvents(stream_events=[_tool_use("tu_1", "echo", {}), _terminated()]) |
| 1220 |
|
| 1221 |
[_ async for _ in _run_with_fakes(events=events, tools=[tool])] |
| 1222 |
|
| 1223 |
assert closed["count"] == 1 |
| 1224 |
|
| 1225 |
|
| 1226 |
@pytest.mark.asyncio() |
| 1227 |
async def test_awaits_async_tool_close_hook() -> None: |
| 1228 |
closed = {"count": 0} |
| 1229 |
|
| 1230 |
async def _aclose() -> None: |
| 1231 |
closed["count"] += 1 |
| 1232 |
|
| 1233 |
async def echo(_input: dict[str, Any]) -> str: |
| 1234 |
return "ok" |
| 1235 |
|
| 1236 |
tool = _FakeTool("echo", echo, close=_aclose) |
| 1237 |
events = FakeAsyncEvents(stream_events=[_terminated()]) |
| 1238 |
|
| 1239 |
[_ async for _ in _run_with_fakes(events=events, tools=[tool])] |
| 1240 |
|
| 1241 |
assert closed["count"] == 1 |
| 1242 |
|
| 1243 |
|
| 1244 |
# ---------- send-result failure surfaces to consumer ----------------------- |
| 1245 |
|
| 1246 |
|
| 1247 |
@pytest.mark.asyncio() |
| 1248 |
async def test_send_retries_past_three_attempts(monkeypatch: pytest.MonkeyPatch) -> None: |
| 1249 |
"""A tool-result send that keeps failing transiently must keep retrying with |
| 1250 |
backoff (not give up after three attempts while an enclosing worker keeps |
| 1251 |
the lease alive) and land once the server recovers.""" |
| 1252 |
monkeypatch.setattr(session_runner_mod, "SEND_BACKOFF_CAP", 0.02) |
| 1253 |
|
| 1254 |
async def echo(_input: dict[str, Any]) -> str: |
| 1255 |
return "result" |
| 1256 |
|
| 1257 |
tool = _FakeTool("echo", echo) |
| 1258 |
events = FakeAsyncEvents( |
| 1259 |
stream_events=[_tool_use("tu_1", "echo", {}), _terminated()], |
| 1260 |
send_failures=[_api_status_error(503)] * 6, |
| 1261 |
) |
| 1262 |
|
| 1263 |
items = [item async for item in _run_with_fakes(events=events, tools=[tool])] |
| 1264 |
|
| 1265 |
assert len(items) == 1 |
| 1266 |
assert items[0].posted is True |
| 1267 |
assert len(events.send_calls) == 7 |
| 1268 |
|
| 1269 |
|
| 1270 |
@pytest.mark.asyncio() |
| 1271 |
async def test_yields_with_posted_false_on_retry_window_exhaust(monkeypatch: pytest.MonkeyPatch) -> None: |
| 1272 |
"""If `events.send` keeps failing for the whole retry window, the consumer |
| 1273 |
should still receive the `DispatchedToolCall` with `posted=False` so |
| 1274 |
they know the tool ran but the session-side agent never saw the result.""" |
| 1275 |
monkeypatch.setattr(session_runner_mod, "SEND_BACKOFF_CAP", 0.05) |
| 1276 |
monkeypatch.setattr(session_runner_mod, "SEND_RETRY_WINDOW", 0.5) |
| 1277 |
|
| 1278 |
async def echo(_input: dict[str, Any]) -> str: |
| 1279 |
return "result" |
| 1280 |
|
| 1281 |
tool = _FakeTool("echo", echo) |
| 1282 |
events = FakeAsyncEvents( |
| 1283 |
stream_events=[_tool_use("tu_1", "echo", {}), _terminated()], |
| 1284 |
send_failures=[_api_status_error(500)] * 100, |
| 1285 |
) |
| 1286 |
|
| 1287 |
start = time.monotonic() |
| 1288 |
items = [item async for item in _run_with_fakes(events=events, tools=[tool])] |
| 1289 |
elapsed = time.monotonic() - start |
| 1290 |
|
| 1291 |
assert len(items) == 1 |
| 1292 |
assert items[0].posted is False |
| 1293 |
# The tool itself succeeded — the failure is just the post-back. |
| 1294 |
assert items[0].is_error is False |
| 1295 |
assert _result_text(items[0]) == "result" |
| 1296 |
assert len(events.send_calls) >= 3 |
| 1297 |
assert 0.5 <= elapsed < 5 |
| 1298 |
|
| 1299 |
|
| 1300 |
@pytest.mark.asyncio() |
| 1301 |
async def test_send_retry_window_update_bounds_send_already_retrying(monkeypatch: pytest.MonkeyPatch) -> None: |
| 1302 |
"""A send retry window that changes while a send is already retrying bounds |
| 1303 |
that send — `EnvironmentWorker` keeps it equal to the lease TTL each |
| 1304 |
heartbeat reports (through `_run_session_tools`).""" |
| 1305 |
monkeypatch.setattr(session_runner_mod, "SEND_BACKOFF_CAP", 0.05) |
| 1306 |
|
| 1307 |
async def echo(_input: dict[str, Any]) -> str: |
| 1308 |
return "result" |
| 1309 |
|
| 1310 |
tool = _FakeTool("echo", echo) |
| 1311 |
events = FakeAsyncEvents( |
| 1312 |
stream_events=[_tool_use("tu_1", "echo", {}), _terminated()], |
| 1313 |
send_failures=[_api_status_error(503)] * 10_000, |
| 1314 |
) |
| 1315 |
lease_ttl: Optional[float] = None |
| 1316 |
|
| 1317 |
async def consume() -> list[DispatchedToolCall]: |
| 1318 |
async with session_runner_mod._run_session_tools( |
| 1319 |
cast(Any, _FakeClient(events)), "s_1", tools=cast(Any, [tool]), send_retry_window=lambda: lease_ttl |
| 1320 |
) as calls: |
| 1321 |
return [item async for item in calls] |
| 1322 |
|
| 1323 |
start = time.monotonic() |
| 1324 |
task = asyncio.ensure_future(consume()) |
| 1325 |
await asyncio.sleep(0.3) |
| 1326 |
assert not task.done() # still retrying under the 300s default |
| 1327 |
lease_ttl = 0.2 # e.g. a heartbeat reported a short lease TTL |
| 1328 |
items = await asyncio.wait_for(task, timeout=5) |
| 1329 |
|
| 1330 |
assert len(items) == 1 |
| 1331 |
assert items[0].posted is False |
| 1332 |
assert time.monotonic() - start < 2 |
| 1333 |
|
| 1334 |
|
| 1335 |
@pytest.mark.asyncio() |
| 1336 |
async def test_yields_with_posted_false_on_permanent_4xx() -> None: |
| 1337 |
"""A permanent 4xx (e.g. 400) on send should short-circuit the retry loop |
| 1338 |
after a single attempt and still yield with posted=False.""" |
| 1339 |
|
| 1340 |
async def echo(_input: dict[str, Any]) -> str: |
| 1341 |
return "result" |
| 1342 |
|
| 1343 |
tool = _FakeTool("echo", echo) |
| 1344 |
events = FakeAsyncEvents( |
| 1345 |
stream_events=[_tool_use("tu_1", "echo", {}), _terminated()], |
| 1346 |
send_failures=[_api_status_error(400)], |
| 1347 |
) |
| 1348 |
|
| 1349 |
items = [item async for item in _run_with_fakes(events=events, tools=[tool])] |
| 1350 |
|
| 1351 |
assert len(items) == 1 |
| 1352 |
assert items[0].posted is False |
| 1353 |
assert len(events.send_calls) == 1 # no retry on permanent 4xx |
| 1354 |
|
| 1355 |
|
| 1356 |
# ---------- tool execution edge cases -------------------------------------- |
| 1357 |
|
| 1358 |
|
| 1359 |
@pytest.mark.asyncio() |
| 1360 |
async def test_tool_timeout(monkeypatch: pytest.MonkeyPatch) -> None: |
| 1361 |
"""Tool that exceeds `TOOL_TIMEOUT` yields with `is_error=True` and a |
| 1362 |
`"timed out"` message — distinct from the generic exception path.""" |
| 1363 |
monkeypatch.setattr(session_runner_mod, "TOOL_TIMEOUT", 0.05) |
| 1364 |
|
| 1365 |
async def slow(_input: dict[str, Any]) -> str: |
| 1366 |
await asyncio.Event().wait() # never resolves |
| 1367 |
return "never" |
| 1368 |
|
| 1369 |
tool = _FakeTool("slow", slow) |
| 1370 |
events = FakeAsyncEvents(stream_events=[_tool_use("tu_1", "slow", {}), _terminated()]) |
| 1371 |
|
| 1372 |
items = [item async for item in _run_with_fakes(events=events, tools=[tool])] |
| 1373 |
|
| 1374 |
assert len(items) == 1 |
| 1375 |
assert items[0].is_error is True |
| 1376 |
assert "timed out" in _result_text(items[0]) |
| 1377 |
|
| 1378 |
|
| 1379 |
@pytest.mark.asyncio() |
| 1380 |
async def test_sync_tool_runs_off_the_event_loop() -> None: |
| 1381 |
"""A sync tool runs on a worker thread: the event loop keeps running while its body blocks.""" |
| 1382 |
loop = asyncio.get_running_loop() |
| 1383 |
release = threading.Event() |
| 1384 |
|
| 1385 |
def blocking(_input: object) -> str: |
| 1386 |
loop.call_soon_threadsafe(release.set) |
| 1387 |
if not release.wait(timeout=2): |
| 1388 |
raise RuntimeError("the event loop did not run while the tool blocked") |
| 1389 |
return "released" |
| 1390 |
|
| 1391 |
events = FakeAsyncEvents(stream_events=[_custom_tool_use("ctu_1", "blocking", {}), _terminated()]) |
| 1392 |
|
| 1393 |
items = [item async for item in _run_with_fakes(events=events, tools=[_SyncTool("blocking", blocking)])] |
| 1394 |
|
| 1395 |
assert len(items) == 1 |
| 1396 |
assert items[0].is_error is False |
| 1397 |
assert _result_text(items[0]) == "released" |
| 1398 |
|
| 1399 |
|
| 1400 |
@pytest.mark.asyncio() |
| 1401 |
async def test_tool_timeout_fires_for_blocking_sync_tool(monkeypatch: pytest.MonkeyPatch) -> None: |
| 1402 |
"""A sync tool that blocks past `TOOL_TIMEOUT` is reported timed out at the |
| 1403 |
deadline; its thread is abandoned rather than awaited.""" |
| 1404 |
monkeypatch.setattr(session_runner_mod, "TOOL_TIMEOUT", 0.05) |
| 1405 |
release = threading.Event() |
| 1406 |
|
| 1407 |
def slow(_input: object) -> str: |
| 1408 |
release.wait(timeout=2) |
| 1409 |
return "late" |
| 1410 |
|
| 1411 |
events = FakeAsyncEvents(stream_events=[_custom_tool_use("ctu_1", "slow", {}), _terminated()]) |
| 1412 |
try: |
| 1413 |
items = [item async for item in _run_with_fakes(events=events, tools=[_SyncTool("slow", slow)])] |
| 1414 |
finally: |
| 1415 |
release.set() |
| 1416 |
|
| 1417 |
assert len(items) == 1 |
| 1418 |
assert items[0].is_error is True |
| 1419 |
assert "timed out" in _result_text(items[0]) |
| 1420 |
assert len(events.send_calls) == 1 |
| 1421 |
|
| 1422 |
|
| 1423 |
def test_tool_timeout_exceeds_bash_default() -> None: |
| 1424 |
"""`TOOL_TIMEOUT` MUST stay strictly greater than the bash tool's own |
| 1425 |
`BASH_DEFAULT_TIMEOUT`. |
| 1426 |
|
| 1427 |
If they were equal the outer per-tool-call `fail_after` could win the |
| 1428 |
race against the bash tool's inner `fail_after`; anyio would then raise a |
| 1429 |
plain parent-scope `Cancelled` (not `TimeoutError`), the bash tool's |
| 1430 |
`except TimeoutError` subprocess cleanup would never run, and the next |
| 1431 |
bash call would read the previous (timed-out) command's stale output. This |
| 1432 |
test pins the invariant so the two constants can't silently converge. |
| 1433 |
""" |
| 1434 |
from anthropic.lib.tools.agent_toolset import BASH_DEFAULT_TIMEOUT |
| 1435 |
|
| 1436 |
assert session_runner_mod.TOOL_TIMEOUT > BASH_DEFAULT_TIMEOUT |
| 1437 |
|
| 1438 |
|
| 1439 |
@pytest.mark.asyncio() |
| 1440 |
async def test_tool_error_preserves_structured_content() -> None: |
| 1441 |
"""`ToolError` raised by the tool preserves its structured content rather |
| 1442 |
than being stringified through `repr(e)`.""" |
| 1443 |
structured = [{"type": "text", "text": "structured error"}] |
| 1444 |
|
| 1445 |
async def boom(_input: dict[str, Any]) -> str: |
| 1446 |
raise ToolError(content=cast(Any, structured)) |
| 1447 |
|
| 1448 |
tool = _FakeTool("boom", boom) |
| 1449 |
events = FakeAsyncEvents(stream_events=[_tool_use("tu_1", "boom", {}), _terminated()]) |
| 1450 |
|
| 1451 |
items = [item async for item in _run_with_fakes(events=events, tools=[tool])] |
| 1452 |
|
| 1453 |
assert len(items) == 1 |
| 1454 |
assert items[0].is_error is True |
| 1455 |
assert _result_content(items[0]) == structured |
| 1456 |
|
| 1457 |
|
| 1458 |
# ---------- stream-loop edge cases ----------------------------------------- |
| 1459 |
|
| 1460 |
|
| 1461 |
@pytest.mark.asyncio() |
| 1462 |
async def test_stream_permanent_4xx_ends_iteration() -> None: |
| 1463 |
"""A permanent 4xx on the stream connect must not loop forever — the |
| 1464 |
iterator should exit cleanly.""" |
| 1465 |
events = FakeAsyncEvents(streams=[_api_status_error(401)]) |
| 1466 |
|
| 1467 |
items = [item async for item in _run_with_fakes(events=events, tools=[])] |
| 1468 |
|
| 1469 |
assert items == [] |
| 1470 |
# Should not have retried after the permanent 4xx. |
| 1471 |
assert events.stream_calls == 1 |
| 1472 |
|
| 1473 |
|
| 1474 |
@pytest.mark.asyncio() |
| 1475 |
async def test_reconcile_list_error_does_not_dispatch_partial() -> None: |
| 1476 |
"""If `events.list` errors mid-pagination, the partial `pending` list |
| 1477 |
should not be enqueued — otherwise we'd risk re-running a tool whose result |
| 1478 |
was on a page we never reached.""" |
| 1479 |
counter = {"calls": 0} |
| 1480 |
|
| 1481 |
async def increment(_input: dict[str, Any]) -> str: |
| 1482 |
counter["calls"] += 1 |
| 1483 |
return "done" |
| 1484 |
|
| 1485 |
tool = _FakeTool("inc", increment) |
| 1486 |
# The list yields a tool_use, then raises before we reach the result. |
| 1487 |
# Without the fix this tool_use would be enqueued and re-executed. |
| 1488 |
events = FakeAsyncEvents( |
| 1489 |
list_events=[_tool_use("tu_1", "inc", {})], |
| 1490 |
list_raises=_api_status_error(500), |
| 1491 |
stream_events=[_terminated()], # no live tool_use either |
| 1492 |
) |
| 1493 |
|
| 1494 |
items = [item async for item in _run_with_fakes(events=events, tools=[tool])] |
| 1495 |
|
| 1496 |
assert items == [] |
| 1497 |
assert counter["calls"] == 0 |
| 1498 |
|
| 1499 |
|
| 1500 |
# ---------- environment-key auth ----------------------------------------- |
| 1501 |
|
| 1502 |
|
| 1503 |
@pytest.mark.asyncio() |
| 1504 |
async def test_environment_key_threads_through_to_scoped_client(scoped_calls: list[dict[str, Any]]) -> None: |
| 1505 |
"""When an environment key is set, the runner asks `_scoped_client` for a |
| 1506 |
Bearer-only sub-client keyed to that environment. The actual header shape |
| 1507 |
(`Authorization: Bearer …`, no `X-Api-Key`, helper-telemetry on defaults) |
| 1508 |
is the responsibility of `_scoped_client` itself — exercised separately in |
| 1509 |
integration tests; here we just verify the runner threaded the right key.""" |
| 1510 |
|
| 1511 |
async def echo(_input: dict[str, Any]) -> str: |
| 1512 |
return "ok" |
| 1513 |
|
| 1514 |
tool = _FakeTool("echo", echo) |
| 1515 |
events = FakeAsyncEvents( |
| 1516 |
list_events=[], |
| 1517 |
stream_events=[_tool_use("tu_1", "echo", {}), _terminated()], |
| 1518 |
) |
| 1519 |
|
| 1520 |
[_ async for _ in _run_with_fakes(events=events, tools=[tool], environment_key="env_key")] |
| 1521 |
|
| 1522 |
assert scoped_calls == [{"environment_key": "env_key"}] |
| 1523 |
|
| 1524 |
|
| 1525 |
@pytest.mark.asyncio() |
| 1526 |
async def test_no_environment_key_threads_none_to_scoped_client(scoped_calls: list[dict[str, Any]]) -> None: |
| 1527 |
"""Without an environment key the runner still asks `_scoped_client` for a |
| 1528 |
request client — passing `None` so the factory returns the parent client |
| 1529 |
unchanged (just with a helper-telemetry header layered on).""" |
| 1530 |
|
| 1531 |
async def echo(_input: dict[str, Any]) -> str: |
| 1532 |
return "ok" |
| 1533 |
|
| 1534 |
tool = _FakeTool("echo", echo) |
| 1535 |
events = FakeAsyncEvents(stream_events=[_tool_use("tu_1", "echo", {}), _terminated()]) |
| 1536 |
|
| 1537 |
[_ async for _ in _run_with_fakes(events=events, tools=[tool])] |
| 1538 |
|
| 1539 |
assert scoped_calls == [{"environment_key": None}] |
| 1540 |
|
| 1541 |
|
| 1542 |
@pytest.mark.asyncio() |
| 1543 |
async def test_session_runner_threads_extra_headers_into_stream_list_and_send() -> None: |
| 1544 |
"""A caller-supplied `extra_headers` is threaded, unchanged, into every |
| 1545 |
per-request call the runner makes: the event `stream`, the history |
| 1546 |
`list`, and each result `send`. |
| 1547 |
|
| 1548 |
The runner does no header munging — it just passes the caller's mapping |
| 1549 |
to each call's `extra_headers=`. Auth is handled by the scoped |
| 1550 |
sub-client the runner builds from `environment_key`, independent of |
| 1551 |
this passthrough.""" |
| 1552 |
|
| 1553 |
async def echo(_input: dict[str, Any]) -> str: |
| 1554 |
return "ok" |
| 1555 |
|
| 1556 |
tool = _FakeTool("echo", echo) |
| 1557 |
events = FakeAsyncEvents( |
| 1558 |
list_events=[], |
| 1559 |
stream_events=[_tool_use("tu_1", "echo", {}), _terminated()], |
| 1560 |
) |
| 1561 |
|
| 1562 |
extras = {"x-trace-id": "abc123"} |
| 1563 |
[ |
| 1564 |
_ |
| 1565 |
async for _ in _run_with_fakes( |
| 1566 |
events=events, |
| 1567 |
tools=[tool], |
| 1568 |
environment_key="env_key", |
| 1569 |
extra_headers=extras, |
| 1570 |
) |
| 1571 |
] |
| 1572 |
|
| 1573 |
assert events.stream_headers[0] == extras |
| 1574 |
assert events.list_headers[0] == extras |
| 1575 |
assert events.send_calls[0]["extra_headers"] == extras |
| 1576 |
|
| 1577 |
|
| 1578 |
@pytest.mark.asyncio() |
| 1579 |
@pytest.mark.skipif(PYDANTIC_V1, reason="tool functions are only supported with pydantic v2") |
| 1580 |
async def test_runs_context_manager_tool_cleanup_on_exit() -> None: |
| 1581 |
"""A tool defined as an `@asynccontextmanager` via `@beta_async_tool` |
| 1582 |
has its `__aexit__` driven by the runner cleanup path, additively to the |
| 1583 |
legacy `close` hook.""" |
| 1584 |
from contextlib import asynccontextmanager |
| 1585 |
|
| 1586 |
from anthropic.types.beta import BetaManagedAgentsAgentToolset20260401BashInput |
| 1587 |
from anthropic.lib.tools._beta_functions import beta_async_tool |
| 1588 |
|
| 1589 |
events_seen: list[str] = [] |
| 1590 |
|
| 1591 |
@asynccontextmanager |
| 1592 |
async def echo_cm() -> AsyncIterator[Callable[..., Awaitable[str]]]: |
| 1593 |
events_seen.append("enter") |
| 1594 |
|
| 1595 |
# `Optional[str]` (not `str | None`) because `@beta_async_tool` |
| 1596 |
# evaluates these annotations at runtime via pydantic, and PEP 604 union |
| 1597 |
# syntax can't be `eval`'d under Python 3.9 — our minimum version. |
| 1598 |
async def echo(command: Optional[str] = None) -> str: |
| 1599 |
return f"echo:{command}" |
| 1600 |
|
| 1601 |
try: |
| 1602 |
yield echo |
| 1603 |
finally: |
| 1604 |
events_seen.append("exit") |
| 1605 |
|
| 1606 |
echo_tool = beta_async_tool(name="echo", input_schema=BetaManagedAgentsAgentToolset20260401BashInput)( |
| 1607 |
cast(Any, echo_cm) |
| 1608 |
) |
| 1609 |
|
| 1610 |
fake_events = FakeAsyncEvents(stream_events=[_tool_use("tu_1", "echo", {"command": "hi"}), _terminated()]) |
| 1611 |
calls = [c async for c in _run_with_fakes(events=fake_events, tools=[echo_tool])] |
| 1612 |
|
| 1613 |
assert [_result_text(c) for c in calls] == ["echo:hi"] |
| 1614 |
# Entered lazily on first dispatch, exited on runner cleanup. |
| 1615 |
assert events_seen == ["enter", "exit"] |
| 1616 |
|
| 1617 |
|
| 1618 |
# ---------- resource-method wrapper --------------------------------------- |
| 1619 |
|
| 1620 |
|
| 1621 |
@pytest.mark.asyncio() |
| 1622 |
async def test_tool_runner_method_returns_session_tool_runner() -> None: |
| 1623 |
from anthropic import AsyncAnthropic |
| 1624 |
|
| 1625 |
client = AsyncAnthropic(api_key="dummy") |
| 1626 |
runner = client.beta.sessions.events.tool_runner("s_1", tools=[]) |
| 1627 |
assert isinstance(runner, SessionToolRunner) |
| 1628 |
assert runner.session_id == "s_1" |
| 1629 |
|
| 1630 |
|
| 1631 |
@pytest.mark.asyncio() |
| 1632 |
async def test_until_done_drives_runner_to_completion() -> None: |
| 1633 |
"""`until_done()` (renamed from `run()` to match `BetaToolRunner` and |
| 1634 |
avoid colliding with `EnvironmentWorker.run`'s forever-loop) drives the |
| 1635 |
runner to the session end, discarding per-call observations.""" |
| 1636 |
calls = {"n": 0} |
| 1637 |
|
| 1638 |
async def echo(_input: dict[str, Any]) -> str: |
| 1639 |
calls["n"] += 1 |
| 1640 |
return "ok" |
| 1641 |
|
| 1642 |
tool = _FakeTool("echo", echo) |
| 1643 |
events = FakeAsyncEvents(stream_events=[_tool_use("tu_1", "echo", {}), _terminated()]) |
| 1644 |
client = _FakeClient(events) |
| 1645 |
runner = SessionToolRunner(cast(Any, client), "s_1", tools=cast(Any, [tool]), max_idle=None) |
| 1646 |
|
| 1647 |
# The old name is gone; the new one exists and returns at session end. |
| 1648 |
assert not hasattr(runner, "run") |
| 1649 |
await runner.until_done() |
| 1650 |
assert calls["n"] == 1 |
| 1651 |
assert len(events.send_calls) == 1 |
| 1652 |
|
| 1653 |
|
| 1654 |
def test_environments_public_reexports() -> None: |
| 1655 |
"""A user can type their own code against the public runner API without |
| 1656 |
reaching into a `_`-private module.""" |
| 1657 |
from anthropic.lib import environments as env_pkg |
| 1658 |
|
| 1659 |
for name in ( |
| 1660 |
"BetaAnyRunnableTool", |
| 1661 |
"DispatchedToolCall", |
| 1662 |
"DispatchedToolUseEvent", |
| 1663 |
"DispatchedToolResultParams", |
| 1664 |
"download_session_skills", |
| 1665 |
"SessionToolRunner", |
| 1666 |
): |
| 1667 |
assert name in env_pkg.__all__, name |
| 1668 |
assert getattr(env_pkg, name) is not None, name |
| 1669 |
|
| 1670 |
# The old `RunnableTool` name was renamed to `BetaAnyRunnableTool`; it |
| 1671 |
# must be fully gone (it had no released consumers). |
| 1672 |
assert "RunnableTool" not in env_pkg.__all__ |
| 1673 |
assert not hasattr(env_pkg, "RunnableTool") |
| 1674 |
|
| 1675 |
|
| 1676 |
# ---------- _to_session_content --------------------------------------------- |
| 1677 |
|
| 1678 |
|
| 1679 |
def _to_session_content(content: Any) -> list[Any]: |
| 1680 |
return cast("list[Any]", session_runner_mod._to_session_content(content)) # pyright: ignore[reportPrivateUsage] |
| 1681 |
|
| 1682 |
|
| 1683 |
def test_to_session_content_text_passthrough() -> None: |
| 1684 |
out = _to_session_content([{"type": "text", "text": "hello"}]) |
| 1685 |
assert out == [{"type": "text", "text": "hello"}] |
| 1686 |
|
| 1687 |
|
| 1688 |
def test_to_session_content_image_passthrough() -> None: |
| 1689 |
block = { |
| 1690 |
"type": "image", |
| 1691 |
"source": {"type": "base64", "media_type": "image/png", "data": "QUJD"}, |
| 1692 |
} |
| 1693 |
out = _to_session_content([block]) |
| 1694 |
assert out == [block], "image blocks should pass through structurally, not be stringified" |
| 1695 |
|
| 1696 |
|
| 1697 |
def test_to_session_content_document_passthrough() -> None: |
| 1698 |
block = { |
| 1699 |
"type": "document", |
| 1700 |
"source": {"type": "url", "url": "https://example.com/doc.pdf"}, |
| 1701 |
"title": "doc", |
| 1702 |
} |
| 1703 |
out = _to_session_content([block]) |
| 1704 |
assert out == [block], "document blocks should pass through structurally, not be stringified" |
| 1705 |
|
| 1706 |
|
| 1707 |
def test_to_session_content_search_result_passthrough() -> None: |
| 1708 |
"""A `search_result` block — valid on the Sessions content union — passes |
| 1709 |
through structurally so the model retains the typed citation metadata.""" |
| 1710 |
block = { |
| 1711 |
"type": "search_result", |
| 1712 |
"source": "https://example.com", |
| 1713 |
"title": "result", |
| 1714 |
"content": [{"type": "text", "text": "hit"}], |
| 1715 |
"citations": {"enabled": True}, |
| 1716 |
} |
| 1717 |
out = _to_session_content([block]) |
| 1718 |
assert out == [block], "search_result blocks should pass through structurally, not be stringified" |
| 1719 |
|
| 1720 |
|
| 1721 |
def test_to_session_content_tool_reference_stringified() -> None: |
| 1722 |
"""`tool_reference` blocks have no Sessions equivalent and must be stringified.""" |
| 1723 |
block = {"type": "tool_reference", "tool_name": "weather"} |
| 1724 |
out = _to_session_content([block]) |
| 1725 |
assert out == [{"type": "text", "text": session_runner_mod.json.dumps(block)}] |