Debian Codegraph @

src/anthropic/lib/tools/_beta_session_runner.py

raw
1 """The sessions-side tool runner — the managed-agents counterpart to
2 `client.beta.messages.tool_runner`.
3
4 `SessionToolRunner` attaches to a managed-agents session's event stream,
5 reconciles against the events-list endpoint, dispatches every `agent.tool_use`
6 *and* `agent.custom_tool_use` event against a local tool registry, posts the
7 matching result event back (`user.tool_result` / `user.custom_tool_result`),
8 and yields one `DispatchedToolCall` per completed call. A call the
9 server gated behind user confirmation (`evaluated_permission` `ask`, e.g.
10 an `always_ask` tool) is held until its `user.tool_confirmation` event
11 arrives — executed on `allow`, never executed on `deny`. It also stops
12 itself once the session has been idle (`stop_reason` `end_turn`) for
13 `max_idle` seconds. It does **not** touch the work-item lease — wrap it in
14 `anthropic.lib.environments.EnvironmentWorker` if you need heartbeating /
15 force-stop.
16 """
17
18 from __future__ import annotations
19
20 import json
21 import math
22 import time
23 import logging
24 import itertools
25 import contextlib
26 from typing import TYPE_CHECKING, Union, Literal, cast
27 from dataclasses import dataclass
28 from collections.abc import Callable, Sequence, AsyncIterator
29
30 import anyio
31
32 from .._retry import TRANSIENT_ERRORS, jitter, backoff, is_fatal_status_error
33 from ..._types import Headers
34 from ._tool_dispatch import tool_registry, run_runnable_tool, tool_error_content
35 from .._scoped_client import _copy_client_with_bearer_auth
36 from ._beta_functions import (
37 ToolError,
38 BetaRunnableTool,
39 BetaAsyncRunnableTool,
40 BetaFunctionToolResultType,
41 aclose_runnable_tool,
42 )
43 from .._stainless_helpers import helper_header
44 from ...types.beta.sessions import (
45 BetaManagedAgentsAgentToolUseEvent,
46 BetaManagedAgentsAgentCustomToolUseEvent,
47 BetaManagedAgentsUserToolConfirmationEvent,
48 )
49 from ...types.beta.sessions.beta_managed_agents_user_tool_result_event_params import (
50 Content as _SessionContent,
51 BetaManagedAgentsUserToolResultEventParams,
52 )
53 from ...types.beta.sessions.beta_managed_agents_user_custom_tool_result_event_params import (
54 BetaManagedAgentsUserCustomToolResultEventParams,
55 )
56
57 if TYPE_CHECKING:
58 from ..._client import AsyncAnthropic
59 from ...resources.beta.sessions.events import AsyncEvents
60
61 __all__ = [
62 "SessionToolRunner",
63 "DispatchedToolCall",
64 "DispatchedToolUseEvent",
65 "DispatchedToolResultParams",
66 "BetaAnyRunnableTool",
67 "MANAGED_AGENTS_BETA",
68 "DEFAULT_MAX_IDLE",
69 # Re-exported for `anthropic.lib.environments._worker`, which drives the
70 # runner as an async context manager inside its own task group.
71 "_run_session_tools",
72 ]
73
74 # Either sync or async runnable tool — the union the session-side runners
75 # accept. `Beta`-prefixed for consistency with the released
76 # `BetaRunnableTool` (sync) / `BetaAsyncRunnableTool` (async) members it
77 # unions; those two are unchanged.
78 BetaAnyRunnableTool = Union[BetaRunnableTool, BetaAsyncRunnableTool]
79
80 # The two tool-call event kinds the runner dispatches against the local tool
81 # registry, and the matching result-event params it posts back for each:
82 #
83 # agent.tool_use -> user.tool_result (builtin agent_toolset tools)
84 # agent.custom_tool_use -> user.custom_tool_result (custom, user-defined tools)
85 #
86 # `agent.mcp_tool_use` is intentionally absent — MCP tools run server-side and
87 # the runner never sees a result to post for them.
88 DispatchedToolUseEvent = Union[BetaManagedAgentsAgentToolUseEvent, BetaManagedAgentsAgentCustomToolUseEvent]
89 DispatchedToolResultParams = Union[
90 BetaManagedAgentsUserToolResultEventParams,
91 BetaManagedAgentsUserCustomToolResultEventParams,
92 ]
93
94 # A dispatch-queue item: the tool-call event paired with the confirmation
95 # verdict that released it — `"allow"` for an ask-gated call the user
96 # approved, `None` for a call that needed no confirmation. (Denied calls
97 # never reach the queue.) Threading the verdict with the event keeps the
98 # yielded `DispatchedToolCall.confirmation` tied to the verdict that actually
99 # released the call rather than whatever `_confirmations` holds by the time
100 # the tool finishes.
101 _WorkItem = tuple[DispatchedToolUseEvent, Union[Literal["allow"], None]]
102
103 # anthropic-beta gating Sessions access to self-hosted environments. The Sessions
104 # resource auto-injects this header on its own requests; this constant is kept
105 # for the work-item `stop` call the worker issues against the Work resource.
106 MANAGED_AGENTS_BETA = "managed-agents-2026-04-01"
107
108 STREAM_BACKOFF_START = 0.5
109 STREAM_BACKOFF_CAP = 10.0
110 # Outer per-tool-call timeout. This MUST stay strictly greater than the bash
111 # tool's own `agent_toolset.BASH_DEFAULT_TIMEOUT` (120s). The bash tool wraps
112 # its read in its own `anyio.fail_after(BASH_DEFAULT_TIMEOUT)` and, on
113 # `TimeoutError`, tears down the subprocess. If this outer deadline equalled
114 # the inner one, the *outer* fail_after could win the race; anyio then raises
115 # the parent scope's cancel as a plain `Cancelled` (NOT `TimeoutError`), so
116 # the bash tool's `except TimeoutError` cleanup never runs and its subprocess
117 # is left alive with the timed-out command still queued — the next bash call
118 # then reads stale output. The 30s margin gives the inner fail_after room to
119 # fire and clean up before this one. (BashSession also now closes on any
120 # outer-scope cancel as a belt-and-braces backstop, but these two timeouts must
121 # still never be equal.) Invariant covered by
122 # tests/lib/tools/test_session_runner.py::test_tool_timeout_exceeds_bash_default.
123 TOOL_TIMEOUT = 150.0
124 # Cap, in seconds, on the exponential backoff (1s, 2s, 4s, …) between
125 # tool-result send retries.
126 SEND_BACKOFF_CAP = 30.0
127 # How long, in seconds, a transiently failing tool-result send keeps retrying
128 # when the runner is used on its own: the server's default work-item lease TTL.
129 # `EnvironmentWorker` overrides it with the live TTL from each lease heartbeat
130 # (through `_run_session_tools`), so a send is only abandoned once the lease
131 # can no longer be ours.
132 SEND_RETRY_WINDOW = 300.0
133 # Grace period, in seconds, that the runner keeps running after the session goes
134 # idle with stop_reason `end_turn` before it stops; any new event in that
135 # window resets it. `max_idle=None` disables it (run until the session ends).
136 DEFAULT_MAX_IDLE = 60.0
137
138 log = logging.getLogger(__name__)
139
140
141 class _IdleClock:
142 """Tracks how long the session has been idle after an `end_turn` stop.
143
144 `end_turn_at` is the monotonic timestamp of the most recent
145 `session.status_idle` event with `stop_reason.type == "end_turn"` for
146 which no newer event has since arrived; `None` whenever the session is not
147 in that state. `SessionToolRunner._idle_watchdog` stops the runner
148 once it has been set for `max_idle` seconds.
149
150 Confirmation-gated calls pause the clock while they are unresolved:
151 `hold` / `release` count them — from the moment a call is held
152 awaiting its verdict until it is denied or, when allowed, until the dispatch
153 loop has finished with it — and an `arm` landing while any are
154 outstanding is deferred rather than applied. The last `release`
155 applies a still-pending deferral so the runner can time out once nothing
156 gated remains in flight.
157
158 The clock is event-driven, not polled: every armed-state change signals the
159 `wake` event so the watchdog wakes immediately instead of waiting out
160 a poll interval. The watchdog captures `wake` *before* it reads
161 `end_turn_at`, so a change landing between the read and the wait still
162 wakes it.
163 """
164
165 __slots__ = ("end_turn_at", "wake", "_holds", "_arm_deferred")
166
167 def __init__(self) -> None:
168 self.end_turn_at: float | None = None
169 self.wake = anyio.Event()
170 self._holds = 0
171 self._arm_deferred = False
172
173 def _signal(self) -> None:
174 # Wake any current waiter and arm a fresh event for the next wait.
175 self.wake.set()
176 self.wake = anyio.Event()
177
178 def note_event(self, ev: object) -> None:
179 """Arm the clock on an `end_turn` idle, disarm it on anything else.
180
181 `user.tool_confirmation` events are neutral: they signal neither agent
182 activity nor an idle, and their effect on the clock flows through
183 `hold` / `release` instead — disarming here would discard
184 the deferred arm the verdict is about to settle.
185 """
186 ev_type = getattr(ev, "type", None)
187 if ev_type == "user.tool_confirmation":
188 return
189 if ev_type == "session.status_idle" and getattr(getattr(ev, "stop_reason", None), "type", None) == "end_turn":
190 self.arm()
191 else:
192 self.disarm()
193
194 def arm(self) -> None:
195 """(Re)start the idle countdown from now and wake the watchdog.
196
197 Deferred while any gated call is held or in flight — stopping then
198 would drop the held call when its verdict later arrives, or cut the
199 runner off before a released call's result can drive the next turn.
200 """
201 if self._holds:
202 self._arm_deferred = True
203 return
204 self.end_turn_at = time.monotonic()
205 self._signal()
206
207 def disarm(self) -> None:
208 """Cancel the idle countdown; only signals on an actual transition."""
209 self._arm_deferred = False
210 if self.end_turn_at is not None:
211 self.end_turn_at = None
212 self._signal()
213
214 def hold(self) -> None:
215 """Pause the countdown while a gated call is held or in flight."""
216 self._holds += 1
217 if self.end_turn_at is not None:
218 # Defensive: a hold taken while armed converts the running
219 # countdown into a deferred one.
220 self._arm_deferred = True
221 self.end_turn_at = None
222 self._signal()
223
224 def release(self) -> None:
225 """Drop one hold; the last release applies any deferred arm.
226
227 Once nothing gated is held or in flight, a deferred `end_turn`
228 countdown starts now (with a fresh grace window) so the runner can
229 still time out — any newer event disarms it again as usual.
230 """
231 self._holds -= 1
232 if self._holds == 0 and self._arm_deferred:
233 self.arm()
234
235
236 @dataclass(frozen=True)
237 class DispatchedToolCall:
238 """One tool call observed by `SessionToolRunner`.
239
240 Covers both tool-call event kinds — a builtin `agent.tool_use` and a
241 custom `agent.custom_tool_use`. The originating event is in `event`
242 (with its input) and the posted-back result in `result`; `name` and
243 `tool_use_id` are flat conveniences mirroring `event`.
244 """
245
246 event: DispatchedToolUseEvent
247 """The full `agent.tool_use` / `agent.custom_tool_use` event the agent
248 emitted. The tool input is `event.input`."""
249
250 result: DispatchedToolResultParams | None
251 """The result event the runner computed and attempted to post back to the
252 session — `user.tool_result` for an `agent.tool_use` call,
253 `user.custom_tool_result` for an `agent.custom_tool_use` call. The
254 computed content is `result["content"]`.
255
256 `None` when the runner deliberately posted nothing: the tool name is not
257 one this runner owns, so the `tool_use_id` was left pending for its
258 owner, or the call was denied and never executed (see `confirmation`).
259 `posted` is `False` in either case."""
260
261 tool_use_id: str
262 """Convenience: the id of the originating tool-call event — the same value
263 as `event.id` for both event kinds."""
264
265 name: str
266 """Convenience: the tool name — the same value as `event.name`."""
267
268 is_error: bool
269 """Convenience: whether the result is an error — the same value as
270 `result["is_error"]`. Always `False` for a skipped unowned call (the
271 runner reaches no verdict on a tool it does not own; `result` is
272 `None`) and for a denied call (nothing ran, so there is no error to
273 report; see `confirmation`)."""
274
275 posted: bool = True
276 """`True` if the result event made it to the session. `False` if all
277 retries were exhausted or the server returned a permanent 4xx — in which
278 case the session-side agent will *not* see this result and the consumer may
279 want to surface that or retry at a higher level — and also `False`, with
280 `result` left `None`, when the tool name is not one this runner owns and
281 it deliberately posted nothing, leaving the `tool_use_id` pending for its
282 owner (the split-client partial-fulfillment behavior), or when the call was
283 denied and never executed (see `confirmation`)."""
284
285 confirmation: Literal["allow", "deny"] | None = None
286 """The confirmation verdict that gated this call, if any.
287
288 `"allow"` — the call required user confirmation (the server evaluated its
289 permission to `ask`, e.g. under an `always_ask` policy) and the matching
290 `user.tool_confirmation` event approved it before the tool ran.
291 `"deny"` — the user denied it, or the server itself evaluated the
292 permission to `deny`; the tool was never executed and nothing was posted
293 (`result=None`, `posted=False`, `is_error=False`).
294 `None` — the call needed no confirmation."""
295
296
297 def _scoped_client(client: AsyncAnthropic, environment_key: str | None) -> AsyncAnthropic:
298 """Build the runner's request client.
299
300 With an environment key, defer to `_copy_client_with_bearer_auth`
301 for a Bearer-only sub-client. Without one, layer the helper-telemetry
302 header onto the caller's client via `with_options` (parent is not
303 mutated).
304 """
305 if environment_key is not None:
306 return _copy_client_with_bearer_auth(client, auth_token=environment_key, helper="session-tool-runner")
307 return client.with_options(default_headers=helper_header("session-tool-runner"))
308
309
310 def _to_session_content(content: BetaFunctionToolResultType) -> list[_SessionContent]:
311 """Bridge Messages-API tool-result content to the narrower Sessions-API content union.
312
313 The two APIs share text/image/document/search_result block shapes but use
314 distinct nominal TypedDicts; ToolReference blocks have no Sessions equivalent
315 so they are stringified.
316 """
317 if isinstance(content, str):
318 return [{"type": "text", "text": content or "(no output)"}]
319 out: list[_SessionContent] = []
320 for block in content:
321 kind = block.get("type")
322 if kind == "text":
323 text = cast("str", block.get("text") or "(no output)")
324 out.append({"type": "text", "text": text})
325 elif kind in ("image", "document", "search_result"):
326 out.append(cast("_SessionContent", block))
327 else:
328 out.append({"type": "text", "text": json.dumps(block)})
329 return out or [{"type": "text", "text": "(no output)"}]
330
331
332 def _build_result_event(
333 ev: DispatchedToolUseEvent,
334 content: BetaFunctionToolResultType,
335 is_error: bool,
336 ) -> DispatchedToolResultParams:
337 """Build the result-event params matching `ev`'s tool-call kind.
338
339 A custom tool call (`agent.custom_tool_use`) is answered with a
340 `user.custom_tool_result` keyed by `custom_tool_use_id`; a builtin tool
341 call (`agent.tool_use`) with a `user.tool_result` keyed by
342 `tool_use_id`. Both use the codegen'd event-params TypedDicts.
343 """
344 session_content = _to_session_content(content)
345 if ev.type == "agent.custom_tool_use":
346 custom_result: BetaManagedAgentsUserCustomToolResultEventParams = {
347 "type": "user.custom_tool_result",
348 "custom_tool_use_id": ev.id,
349 "is_error": is_error,
350 "content": session_content,
351 }
352 return custom_result
353 builtin_result: BetaManagedAgentsUserToolResultEventParams = {
354 "type": "user.tool_result",
355 "tool_use_id": ev.id,
356 "is_error": is_error,
357 "content": session_content,
358 }
359 return builtin_result
360
361
362 class SessionToolRunner:
363 """Attach to a managed-agents session and dispatch its tool calls locally.
364
365 The sessions-side counterpart to `client.beta.messages.tool_runner`: an
366 async iterable that, for each `agent.tool_use` or `agent.custom_tool_use`
367 event the agent emits, executes the matching tool from `tools`, posts the
368 matching result event back (`user.tool_result` for a builtin tool call,
369 `user.custom_tool_result` for a custom one), and yields one
370 `DispatchedToolCall`. Internally drives event-stream reconnect (with
371 capped backoff) and result posting via an `anyio` task group, so it works
372 under both `asyncio` and `trio`.
373
374 Iteration ends when the session terminates (`session.status_terminated` /
375 `session.deleted`), when the consumer breaks out of the loop, or — once
376 the session has gone idle with `stop_reason` `end_turn` — when
377 `max_idle` seconds elapse with no new event (any new event resets the
378 countdown; it re-arms on the next `end_turn` idle). `max_idle=None`
379 disables that last condition. On exit it runs each tool's optional cleanup:
380 the `close` hook and, for tools defined as an (async) context manager, its
381 `__exit__` / `__aexit__`. It does **not** touch the work-item lease —
382 wrap it in an
383 `anthropic.lib.environments.EnvironmentWorker` for heartbeating /
384 force-stop.
385
386 Tool calls run one at a time and each is bounded by `TOOL_TIMEOUT`,
387 after which the runner posts an `is_error` "timed out" result. Async
388 tools are awaited on the event loop, so keep them non-blocking. Sync tools
389 (`@beta_tool`, `anthropic.lib.tools.BetaBuiltinFunctionTool`)
390 run on a worker thread so they cannot stall the loop, and should use
391 `anyio.from_thread.run` if they need to call async code. A timed-out
392 sync tool's thread is not joined, so its body may still be running during
393 later calls and the exit-time cleanup.
394
395 Pass `environment_key` to authenticate the event stream / list / send
396 calls with the self-hosted environment key (bearered, with the client's
397 default `x-api-key` dropped); leave it unset to use the client's own
398 credentials. `anthropic.lib.environments.EnvironmentWorker` may
399 pass a per-item sessions token here instead when the claimed work item
400 carried one — any Bearer credential the session endpoints accept works.
401
402 A self-hosted session is commonly serviced by **two** clients at once: this
403 runner inside the customer's sandbox (registered with the file/shell sandbox
404 tools) and the customer's app backend (handling the agent's `custom`
405 function tools). The Sessions API has a partial-fulfillment contract: when a
406 session pauses on `requires_action` the pending tool-call ids can mix both
407 kinds, and each client must post results **only** for the ids it owns and
408 leave the rest pending for the other client. A tool-call event whose name is
409 not in `tools` is therefore assumed to belong to the other client: the
410 runner posts no result for it, does not mark it answered, and leaves the
411 `tool_use_id` pending — but still yields a `DispatchedToolCall`
412 (`posted=False`, `is_error=False`, `result=None`) so the caller can
413 observe the unowned dispatch.
414
415 Tool calls the server gated behind user confirmation are **not** executed
416 on arrival: an `agent.tool_use` event whose `evaluated_permission` is
417 `ask` (e.g. a tool configured with the `always_ask` permission policy)
418 is held until the matching `user.tool_confirmation` event arrives. An
419 `allow` verdict releases the call to execute as normal; a `deny`
420 verdict — or a call the server already evaluated to `deny` — is never
421 executed and nothing is posted for it (the denial itself resolves the call
422 server-side), but it is still yielded (`confirmation="deny"`,
423 `posted=False`, `result=None`) so the caller can observe it.
424
425 Usage:
426
427 ```py
428 from anthropic.lib.tools.agent_toolset import AgentToolContext, beta_agent_toolset_20260401
429
430 async with AgentToolContext(workdir="/workspace") as env:
431 async for call in client.beta.sessions.events.tool_runner(
432 work.data.id,
433 tools=[*beta_agent_toolset_20260401(env), my_tool],
434 ):
435 print(f"{call.name} -> {'error' if call.is_error else 'ok'}")
436 ```
437 """
438
439 def __init__(
440 self,
441 client: AsyncAnthropic,
442 session_id: str,
443 *,
444 tools: Sequence[BetaAnyRunnableTool],
445 max_idle: float | None = DEFAULT_MAX_IDLE,
446 environment_key: str | None = None,
447 extra_headers: Headers | None = None,
448 ) -> None:
449 self.session_id = session_id
450 self.tools: Sequence[BetaAnyRunnableTool] = tools
451 self.max_idle = max_idle
452 # All event stream / list / send requests are issued via this scoped
453 # sub-client: Bearer-only when an environment key is set, otherwise the
454 # caller's own client with the helper-telemetry header layered on.
455 self._scoped = _scoped_client(client, environment_key)
456 # Per-request passthrough headers: threaded into every event stream /
457 # list / send via that call's `extra_headers=` (make_request_options)
458 # — never assigned onto the client, so client state is not mutated.
459 # Auth and `x-stainless-helper` come from the scoped sub-client and
460 # the parent client's `default_headers` propagate via its
461 # `client.copy()`; per the SDK's standard `extra_headers`
462 # precedence a caller header overrides the scoped client's same-named
463 # default for that request (`x-stainless-helper` is the exception —
464 # a caller value appends to the runner's tag rather than replacing it),
465 # so this is for caller passthrough (trace ids etc.), not auth.
466 self.extra_headers = extra_headers
467 # Override for SEND_RETRY_WINDOW, re-read before every send retry;
468 # `_run_session_tools` installs EnvironmentWorker's live lease TTL.
469 self._send_retry_window: Callable[[], float | None] = lambda: None
470
471 async def __aiter__(self) -> AsyncIterator[DispatchedToolCall]:
472 async with self._run() as calls:
473 async for call in calls:
474 yield call
475
476 async def until_done(self) -> None:
477 """Drive the runner to completion, discarding the per-call observations.
478
479 Named to match `BetaToolRunner.until_done` (and to avoid colliding
480 with `EnvironmentWorker.run`, which is a forever-loop): it returns
481 once the session ends / goes idle, rather than running until cancelled.
482 """
483 async for _ in self:
484 pass
485
486 @contextlib.asynccontextmanager
487 async def _run(self) -> AsyncIterator[AsyncIterator[DispatchedToolCall]]:
488 """Drive the session tool loop, yielding an iterator of
489 `DispatchedToolCall`. `__aiter__` (and the module-level
490 `_run_session_tools` shim used by `EnvironmentWorker`) wrap this.
491
492 Per-run state lives on `self` as private attributes so the loops below
493 — `_stream_loop`, `_dispatch_loop`, `_reconcile`,
494 `_idle_watchdog`, `_stop_watcher` — can mutate it as methods
495 rather than threading a shared state object through free functions.
496 """
497 self._events: AsyncEvents = self._scoped.beta.sessions.events
498 log.info("session tool runner starting session_id=%s", self.session_id)
499 self._tools_by_name: dict[str, BetaAnyRunnableTool] = tool_registry(self.tools)
500 # `_seen` dedups tool-call events across the stream and the reconcile
501 # pass (by event id); `_answered` holds the ids whose result post has
502 # actually landed, so a failed post is retried on the next reconcile.
503 self._seen: set[str] = set()
504 self._answered: set[str] = set()
505 # Confirmation gating (`always_ask` tools): `_confirmations` records
506 # every `user.tool_confirmation` verdict by `tool_use_id`;
507 # `_awaiting_confirmation` holds the tool-call events whose
508 # `evaluated_permission` is `ask` and whose verdict has not arrived
509 # yet — they are released to the dispatch loop (or resolved as denied)
510 # by `_note_confirmation` / the next reconcile pass. Like `_seen`
511 # and `_answered`, `_confirmations` is per-session O(tool calls):
512 # recorded verdicts persist for the life of the run.
513 self._confirmations: dict[str, Literal["allow", "deny"]] = {}
514 self._awaiting_confirmation: dict[str, DispatchedToolUseEvent] = {}
515 self._stop = anyio.Event()
516 self._idle_clock = _IdleClock()
517
518 self._send_work, self._recv_work = anyio.create_memory_object_stream[_WorkItem](
519 max_buffer_size=100,
520 )
521 self._send_results, self._recv_results = anyio.create_memory_object_stream[DispatchedToolCall](
522 max_buffer_size=math.inf,
523 )
524
525 async def iterator() -> AsyncIterator[DispatchedToolCall]:
526 # `_recv_results` is explicitly closed in the outer `finally` to
527 # keep cleanup deterministic regardless of whether the consumer
528 # iterated at all (e.g. `async with runner._run(): pass`).
529 async for call in self._recv_results:
530 yield call
531
532 try:
533 # The outer `CancelScope` absorbs the task-group cancellation we
534 # trigger in the `finally` below, so it doesn't surface to the
535 # consumer as `Cancelled`.
536 with anyio.CancelScope():
537 async with anyio.create_task_group() as tg:
538 # The stop watcher closes `_send_work` when `_stop` is
539 # set so the dispatch loop's `receive()` raises
540 # EndOfStream and the loop exits cleanly without us having
541 # to inject a sentinel or race two awaitables.
542 tg.start_soon(self._stop_watcher)
543 tg.start_soon(self._stream_loop)
544 tg.start_soon(self._dispatch_loop)
545 if self.max_idle is not None:
546 tg.start_soon(self._idle_watchdog)
547 try:
548 yield iterator()
549 finally:
550 # Signal every loop to exit. Most exit voluntarily on
551 # `_stop`; cancelling the task group's scope wakes
552 # anything still blocked on an unrelated await (e.g. an
553 # uncancellable test fake). anyio absorbs the resulting
554 # cancel via the outer `CancelScope`.
555 self._stop.set()
556 tg.cancel_scope.cancel()
557 finally:
558 # Explicitly close every stream so anyio doesn't warn on GC.
559 # `aclose` is idempotent, so it's fine if the producer already
560 # closed its end during normal shutdown.
561 with anyio.CancelScope(shield=True):
562 for stream in (self._recv_results, self._send_results, self._recv_work, self._send_work):
563 try:
564 await stream.aclose()
565 except Exception:
566 pass
567 # Run each tool's optional cleanup (`close` hook and, for
568 # context-manager tools, `__exit__` / `__aexit__`). Shielded so
569 # the hooks survive the surrounding cancellation.
570 with anyio.CancelScope(shield=True):
571 for tool in self.tools:
572 await aclose_runnable_tool(tool)
573
574 async def _reconcile(self) -> None:
575 """Read full history and enqueue every tool-call event still unanswered.
576
577 Two-pass: read the whole history before emitting so a tool-call whose
578 result appears later in the same history is not re-dispatched. Pairs
579 `agent.tool_use` with `user.tool_result` and `agent.custom_tool_use`
580 with `user.custom_tool_result` when computing which calls are answered.
581 """
582 pending: list[DispatchedToolUseEvent] = []
583 last_was_end_turn = False
584 list_failed = False
585 try:
586 async for ev in self._events.list(self.session_id, limit=1000, extra_headers=self.extra_headers):
587 if ev.type == "agent.tool_use" or ev.type == "agent.custom_tool_use":
588 # Mark the event seen so the live stream doesn't re-enqueue it, but
589 # decide whether it still needs executing from `_answered`, not
590 # `_seen`: a call whose result post failed is seen-but-unanswered
591 # and must be retried on the next reconcile pass rather than dropped.
592 self._seen.add(ev.id)
593 pending.append(ev)
594 elif ev.type == "user.tool_result":
595 self._answered.add(ev.tool_use_id)
596 elif ev.type == "user.custom_tool_result":
597 self._answered.add(ev.custom_tool_use_id)
598 elif ev.type == "user.tool_confirmation":
599 # Record the verdict only, before the pending pass below, so
600 # a tool call whose confirmation appears later in the same
601 # history is routed with its verdict already known. Releasing
602 # a held call here as well would enqueue it a second time
603 # when the routing pass reaches its tool_use event. Calls
604 # already answered are never re-routed, so skip re-recording
605 # their verdict on every reconcile.
606 if ev.tool_use_id not in self._answered:
607 self._confirmations[ev.tool_use_id] = ev.result
608 last_was_end_turn = (
609 ev.type == "session.status_idle"
610 and getattr(getattr(ev, "stop_reason", None), "type", None) == "end_turn"
611 )
612 except Exception as e:
613 # Pagination may have failed partway through; the `_answered` set
614 # could be incomplete, so dispatching `pending` now would risk
615 # re-running a tool whose result was on a page we never reached.
616 # The next reconnect will retry the reconcile. Leave `_idle_clock`
617 # untouched since the history we read may be incomplete.
618 log.warning("reconcile list failed; skipping pending enqueue error=%s", e)
619 list_failed = True
620 if list_failed:
621 # Roll back the ids we added to `_seen` so the live stream can
622 # re-process them rather than silently dedup what we never finished
623 # reading.
624 for ev in pending:
625 self._seen.discard(ev.id)
626 return
627 unanswered = [ev for ev in pending if ev.id not in self._answered]
628 # Disarm before routing: enqueuing below can block on a full work
629 # buffer while the clock may still be armed from before the reconnect.
630 self._idle_clock.disarm()
631 for ev in unanswered:
632 await self._route_tool_event(ev)
633 # A held call's verdict is normally applied by the routing pass above;
634 # if its tool_use event fell outside the listed window the pass never
635 # saw it, so apply the verdict to the held copy here.
636 for held in [ev for ev in self._awaiting_confirmation.values() if ev.id in self._confirmations]:
637 await self._apply_verdict(held, self._confirmations[held.id])
638 # Routing resolves denied calls in place (marking them answered) and
639 # holds ask-gated calls for their `user.tool_confirmation`. If the
640 # most recent event in history is an `end_turn` idle and no tool work
641 # is outstanding, the session is done — arm the idle clock so the
642 # watchdog counts down even if that `end_turn` arrived during a
643 # disconnect. Gated calls don't count as outstanding here whether still
644 # held or just released to the dispatch queue: the clock holds them
645 # (`_IdleClock.hold`), so this `arm` is deferred until they resolve.
646 outstanding = [
647 ev for ev in unanswered if ev.id not in self._answered and ev.id not in self._awaiting_confirmation
648 ]
649 if last_was_end_turn and not outstanding:
650 self._idle_clock.arm()
651
652 async def _stream_loop(self) -> None:
653 backoff = STREAM_BACKOFF_START
654 while not self._stop.is_set():
655 try:
656 # Open the stream *before* reconciling: with the stream already
657 # attached, an event emitted in the gap between the list call
658 # and the attach is delivered live instead of lost. `_seen`
659 # dedups any overlap between the history and the live stream.
660 async with await self._events.stream(self.session_id, extra_headers=self.extra_headers) as stream:
661 await self._reconcile()
662 async for ev in stream:
663 backoff = STREAM_BACKOFF_START
664 # Arm/disarm the idle clock: an `end_turn` idle starts
665 # the grace countdown, any other event cancels it. The
666 # clock itself defers the countdown while gated calls
667 # are held or in flight (see `_IdleClock.hold`).
668 self._idle_clock.note_event(ev)
669 if ev.type == "agent.tool_use" or ev.type == "agent.custom_tool_use":
670 if ev.id not in self._seen:
671 self._seen.add(ev.id)
672 await self._route_tool_event(ev)
673 elif ev.type == "user.tool_result":
674 self._answered.add(ev.tool_use_id)
675 elif ev.type == "user.custom_tool_result":
676 self._answered.add(ev.custom_tool_use_id)
677 elif ev.type == "user.tool_confirmation":
678 await self._note_confirmation(ev)
679 elif ev.type in ("session.status_terminated", "session.deleted"):
680 log.info("session terminated")
681 self._stop.set()
682 return
683 except TRANSIENT_ERRORS as e:
684 if self._stop.is_set():
685 return
686 if is_fatal_status_error(e):
687 # No amount of backoff will fix a 401/403; bail out so the
688 # consumer sees the runner exit instead of looping silently.
689 log.error("stream failed permanently error=%s", e)
690 self._stop.set()
691 return
692 log.warning("stream disconnected, reconnecting backoff=%.1fs error=%s", backoff, e)
693 with anyio.move_on_after(backoff):
694 await self._stop.wait()
695 backoff = min(backoff * 2, STREAM_BACKOFF_CAP)
696
697 async def _route_tool_event(self, ev: DispatchedToolUseEvent) -> None:
698 """Enqueue `ev` for dispatch, honoring its evaluated permission.
699
700 A builtin call the server gated behind user confirmation
701 (`evaluated_permission == "ask"`, e.g. the `always_ask` policy) is
702 held until the matching `user.tool_confirmation` event arrives
703 instead of executing immediately. The gate fails closed: only an
704 explicit `allow` verdict releases a gated call, a call the server
705 already evaluated to `deny` is never executed regardless of any
706 verdict, a stray `deny` verdict recorded for a call that never needed
707 confirmation also resolves it as denied (any deny signal wins), and —
708 because the wire can carry values newer than this SDK's types — an
709 unrecognised permission is held like `ask` and an unrecognised
710 verdict is treated as a denial, never dispatched.
711 """
712 # `getattr` rather than an event-type check: today only
713 # `agent.tool_use` carries `evaluated_permission`, but if the field
714 # ever lands on `agent.custom_tool_use` the gate must keep failing
715 # closed rather than dispatch a gated call by event type.
716 permission = getattr(ev, "evaluated_permission", None)
717 verdict = self._confirmations.get(ev.id)
718 if permission == "deny":
719 # Server already denied the call: never execute it, even if a
720 # (stray) allow verdict exists for the id.
721 await self._resolve_denied(ev)
722 return
723 if verdict is None:
724 if permission is None or permission == "allow":
725 await self._send_work.send((ev, None))
726 elif ev.id not in self._awaiting_confirmation:
727 # "ask" — or a permission value this SDK doesn't recognise,
728 # which must not dispatch unconfirmed — waits for the user's
729 # verdict. (Already-held: a reconcile after a reconnect
730 # re-routes the call; keep the existing hold.)
731 log.info(
732 "tool %r requires user confirmation; holding tool_use_id=%s until user.tool_confirmation",
733 ev.name,
734 ev.id,
735 )
736 self._awaiting_confirmation[ev.id] = ev
737 self._idle_clock.hold()
738 return
739 await self._apply_verdict(ev, verdict)
740
741 async def _note_confirmation(self, ev: BetaManagedAgentsUserToolConfirmationEvent) -> None:
742 """Record an allow/deny verdict and release the held call it gates, if any."""
743 self._confirmations[ev.tool_use_id] = ev.result
744 held = self._awaiting_confirmation.get(ev.tool_use_id)
745 if held is None:
746 # Nothing held: the verdict gates a call this runner has not seen
747 # yet (or one it never gates, e.g. an `agent.mcp_tool_use`).
748 # Keeping it in `_confirmations` lets a later route of that call
749 # resolve instantly.
750 return
751 await self._apply_verdict(held, ev.result)
752
753 async def _apply_verdict(self, ev: DispatchedToolUseEvent, verdict: Literal["allow", "deny"]) -> None:
754 """Dispatch or resolve a gated call according to the user's verdict.
755
756 The idle-clock hold accounting lives here: a denial drops the held
757 call's hold, while an allow keeps one hold on the call (taking it now
758 if the verdict was already known when the call was routed, so it was
759 never held) until the dispatch loop has finished with it — the
760 countdown must not run over gated work that is still in flight.
761 """
762 was_held = self._awaiting_confirmation.pop(ev.id, None) is not None
763 if verdict == "allow":
764 log.info("tool call confirmed tool=%s tool_use_id=%s", ev.name, ev.id)
765 if not was_held:
766 self._idle_clock.hold()
767 await self._send_work.send((ev, "allow"))
768 else:
769 # "deny" — or a verdict value this SDK doesn't recognise, which
770 # must not release the call (the gate fails closed).
771 if was_held:
772 self._idle_clock.release()
773 await self._resolve_denied(ev)
774
775 async def _resolve_denied(self, ev: DispatchedToolUseEvent) -> None:
776 """Resolve a denied call without executing it.
777
778 The denial itself resolves the call server-side — no result event will
779 ever be posted for it — so mark it answered to keep reconcile from
780 re-surfacing it and the idle accounting from waiting on it, then yield
781 the observability call (nothing ran, nothing was posted).
782 """
783 self._answered.add(ev.id)
784 log.info("tool call denied; not executing tool=%s tool_use_id=%s", ev.name, ev.id)
785 await self._surface_call(
786 DispatchedToolCall(
787 event=ev,
788 result=None,
789 tool_use_id=ev.id,
790 name=ev.name,
791 is_error=False,
792 posted=False,
793 confirmation="deny",
794 )
795 )
796
797 async def _surface_call(self, call: DispatchedToolCall) -> None:
798 """Yield `call` to the consumer, tolerating a consumer that left early.
799
800 `BrokenResourceError` — the consumer broke out of the iterator;
801 `ClosedResourceError` — the dispatch loop already closed the send
802 side (possible for the deny path, which runs from the stream loop and
803 can outlive the dispatch loop). Either way the underlying work already
804 happened; only the observability event is lost.
805 """
806 try:
807 await self._send_results.send(call)
808 except (anyio.BrokenResourceError, anyio.ClosedResourceError):
809 pass
810
811 async def _dispatch_loop(self) -> None:
812 try:
813 while True:
814 try:
815 ev, confirmation = await self._recv_work.receive()
816 except anyio.EndOfStream:
817 # Producer side closed — usually because `_stop` was set
818 # (the idle watchdog or stream loop signalled it).
819 return
820 try:
821 if ev.id not in self._answered:
822 # Shielded execute so consumer-side cancellation can't
823 # interrupt an in-flight tool. The result will still be
824 # posted and the DispatchedToolCall enqueued before the
825 # cancel propagates.
826 with anyio.CancelScope(shield=True):
827 await self._execute(ev, confirmation)
828 finally:
829 if confirmation == "allow":
830 # The user-approved call is fully disposed of (executed,
831 # or moot because it was answered elsewhere); drop the
832 # idle-clock hold `_apply_verdict` kept on it.
833 self._idle_clock.release()
834 finally:
835 # Closing the results stream signals the iterator that no more
836 # results will arrive. Wrapped in a shield because we're often in a
837 # cancellation path on the way out.
838 with anyio.CancelScope(shield=True):
839 await self._send_results.aclose()
840
841 async def _execute(self, ev: DispatchedToolUseEvent, confirmation: Literal["allow"] | None) -> None:
842 """Run `ev`'s tool, post its result, and surface the dispatched call.
843
844 `confirmation` is the verdict that released the call onto the work
845 queue — `"allow"` for an ask-gated call the user approved, `None`
846 for a call that needed no confirmation. (Denied calls never reach this
847 method; `_resolve_denied` surfaces them.)
848 """
849 log.info("executing tool tool=%s tool_use_id=%s", ev.name, ev.id)
850 tool = self._tools_by_name.get(ev.name)
851 tool_result: DispatchedToolResultParams | None
852 if tool is None:
853 # Skip unowned (split-client partial fulfillment): a name this
854 # runner is not registered for belongs to the other client
855 # servicing this session (typically the customer's app backend
856 # handling custom tools). Post NO result, do not mark it answered,
857 # and leave the tool_use_id pending for its owner — claiming it
858 # would corrupt the conversation (the model would read "not
859 # implemented" as the tool output while the real result from the
860 # other client arrives afterwards). Still yield the call so the
861 # caller can observe the unowned dispatch; nothing was sent, so
862 # `posted` and `is_error` stay False and `result` is None.
863 # The id stays unanswered, so reconcile keeps it out of the
864 # idle/end-turn accounting and re-surfaces it after a reconnect
865 # until its owner answers it.
866 log.info(
867 "tool %r not owned by this runner; leaving tool_use_id=%s pending for its owner",
868 ev.name,
869 ev.id,
870 )
871 tool_result = None
872 is_error = False
873 sent = False
874 else:
875 content: BetaFunctionToolResultType
876 is_error = False
877 input_ = dict(ev.input)
878 try:
879 with anyio.fail_after(TOOL_TIMEOUT):
880 content = await run_runnable_tool(tool, input_)
881 except TimeoutError:
882 content = f"tool {ev.name!r} timed out"
883 is_error = True
884 except ToolError as e:
885 content = tool_error_content(e)
886 is_error = True
887 except Exception as e:
888 log.exception("tool %s raised", ev.name)
889 content = tool_error_content(e)
890 is_error = True
891 tool_result = _build_result_event(ev, content, is_error)
892 sent = await self._send_result(tool_result, ev.id)
893 await self._surface_call(
894 DispatchedToolCall(
895 event=ev,
896 result=tool_result,
897 tool_use_id=ev.id,
898 name=ev.name,
899 is_error=is_error,
900 posted=sent,
901 confirmation=confirmation,
902 )
903 )
904
905 async def _send_result(self, tool_result: DispatchedToolResultParams, tool_use_id: str) -> bool:
906 """Post `tool_result` back to the session, retrying transient failures
907 with jittered exponential backoff until the send retry window elapses.
908
909 `tool_use_id` is the originating tool-call event id — passed
910 explicitly because the result params key it differently
911 (`tool_use_id` vs `custom_tool_use_id`) depending on the kind.
912 """
913 start = time.monotonic()
914 last_err: Exception | None = None
915 attempt = 0
916 for attempt in itertools.count(1):
917 try:
918 await self._events.send(
919 self.session_id,
920 events=[tool_result],
921 extra_headers=self.extra_headers,
922 )
923 self._answered.add(tool_use_id)
924 return True
925 except TRANSIENT_ERRORS as e:
926 last_err = e
927 if is_fatal_status_error(e):
928 break
929 remaining = (self._send_retry_window() or SEND_RETRY_WINDOW) - (time.monotonic() - start)
930 if remaining <= 0:
931 break
932 delay = backoff(attempt - 1, cap=SEND_BACKOFF_CAP)
933 wait = min(jitter(delay / 2, delay), remaining)
934 log.warning(
935 "tool result send failed; retrying tool_use_id=%s attempt=%d backoff=%.1fs error=%s",
936 tool_use_id,
937 attempt,
938 wait,
939 e,
940 )
941 await anyio.sleep(wait)
942 log.error("failed to send tool result tool_use_id=%s attempts=%d error=%s", tool_use_id, attempt, last_err)
943 return False
944
945 async def _idle_watchdog(self) -> None:
946 """Stop the runner once the session has been idle (`end_turn`) for
947 `max_idle` seconds with no new events.
948
949 Event-driven: it blocks on the idle clock's wake event rather than
950 polling. Capturing `clock.wake` *before* reading `clock.end_turn_at`
951 closes the race where the clock changes between the read and the wait.
952 """
953 max_idle = self.max_idle
954 assert max_idle is not None
955 clock = self._idle_clock
956 while not self._stop.is_set():
957 wake = clock.wake
958 at = clock.end_turn_at
959 if at is None:
960 # Not armed: block until the clock arms (or the runner stops).
961 await _wait_first(wake, self._stop)
962 continue
963 remaining = max_idle - (time.monotonic() - at)
964 if remaining <= 0:
965 log.info("session idle after end_turn for %.0fs; stopping", max_idle)
966 self._stop.set()
967 return
968 # Armed: wait out the remaining grace, waking early if the clock
969 # changes (disarmed, or re-armed with a fresh timestamp) or the
970 # runner stops. Either way, loop back and re-evaluate.
971 with anyio.move_on_after(remaining):
972 await _wait_first(wake, self._stop)
973
974 async def _stop_watcher(self) -> None:
975 """When `_stop` is set, close the work stream so `_dispatch_loop` exits."""
976 await self._stop.wait()
977 await self._send_work.aclose()
978
979
980 async def _wait_first(*events: anyio.Event) -> None:
981 """Return as soon as any of `events` is set."""
982 async with anyio.create_task_group() as tg:
983
984 async def _waiter(ev: anyio.Event) -> None:
985 await ev.wait()
986 tg.cancel_scope.cancel()
987
988 for ev in events:
989 tg.start_soon(_waiter, ev)
990
991
992 @contextlib.asynccontextmanager
993 async def _run_session_tools(
994 client: AsyncAnthropic,
995 session_id: str,
996 *,
997 tools: Sequence[BetaAnyRunnableTool],
998 max_idle: float | None = DEFAULT_MAX_IDLE,
999 environment_key: str | None = None,
1000 extra_headers: Headers | None = None,
1001 send_retry_window: Callable[[], float | None] | None = None,
1002 ) -> AsyncIterator[AsyncIterator[DispatchedToolCall]]:
1003 """Internal: drive a `SessionToolRunner` as an async context manager.
1004
1005 Kept as a thin module-level shim because
1006 `anthropic.lib.environments.EnvironmentWorker` enters the runner
1007 inside its own task group and wants the context-manager shape for
1008 deterministic cleanup, and feeds it the work-item lease TTL as the
1009 tool-result send retry window via `send_retry_window` (re-read before
1010 every retry; `None` until the first heartbeat means the default). New
1011 code should iterate `SessionToolRunner` directly.
1012 """
1013 runner = SessionToolRunner(
1014 client,
1015 session_id,
1016 tools=tools,
1017 max_idle=max_idle,
1018 environment_key=environment_key,
1019 extra_headers=extra_headers,
1020 )
1021 if send_retry_window is not None:
1022 runner._send_retry_window = send_retry_window # noqa: SLF001
1023 async with runner._run() as calls: # noqa: SLF001
1024 yield calls