From 219d29eb7bfb4a24efdfb0810d6d04b8052c117f Mon Sep 17 00:00:00 2001 From: Andrey Buzin Date: Mon, 16 Nov 2026 13:24:10 -0800 Subject: [PATCH] Explain hook calls without an active runtime Calling hook or yield_from outside a running loop exposed the repr of a ContextVar. Raise LookupError with a sentence that explains where the call belongs, without changing the exception type. Cover both callers and the runtime getter. Also describe hook metadata as part of the emitted HookPart rather than an obsolete checkpoint. --- src/ai/agents/hooks.py | 4 ++-- src/ai/agents/runtime.py | 8 +++++++- tests/agents/test_hooks.py | 7 +++++++ tests/agents/test_runtime.py | 21 +++++++++++++++++++++ 4 files changed, 37 insertions(+), 3 deletions(-) diff --git a/src/ai/agents/hooks.py b/src/ai/agents/hooks.py index 049ac0ae..bd24dd66 100644 --- a/src/ai/agents/hooks.py +++ b/src/ai/agents/hooks.py @@ -162,8 +162,8 @@ async def hook[T: pydantic.BaseModel]( whose ``hook_id`` supplies it. payload: Pydantic model class — the resolution data must validate against this type. The return value is a validated instance. - metadata: Arbitrary metadata surfaced in the deferred signal message - and checkpoint. Useful for UI rendering (e.g. which tool needs + metadata: Arbitrary metadata included in the HookPart emitted in + hook events. Useful for UI rendering (e.g. which tool needs approval, what arguments it received). tool_call_id: The tool call this hook suspends, if any. Stamped onto the emitted :class:`~ai.messages.HookPart` so consumers diff --git a/src/ai/agents/runtime.py b/src/ai/agents/runtime.py index 5cfb8211..98ba0710 100644 --- a/src/ai/agents/runtime.py +++ b/src/ai/agents/runtime.py @@ -46,7 +46,13 @@ async def signal_done(self) -> None: def get_runtime() -> Runtime: """Return the active Runtime. Raises LookupError outside of run().""" - return _runtime.get() + try: + return _runtime.get() + except LookupError: + raise LookupError( + "No active agent runtime: call this inside the agent loop or a " + "tool during agent.run()." + ) from None def run( diff --git a/tests/agents/test_hooks.py b/tests/agents/test_hooks.py index 2f449f36..eff13278 100644 --- a/tests/agents/test_hooks.py +++ b/tests/agents/test_hooks.py @@ -331,6 +331,13 @@ async def loop( assert hooks[0].metadata == {"tool": "rm -rf", "path": "/"} +async def test_hook_outside_run_has_a_clear_error() -> None: + with pytest.raises( + LookupError, match=r"^No active agent runtime: .*agent\.run\(\)\.$" + ): + await ai.hook("outside_run", payload=Confirmation) + + # -- telemetry spans -------------------------------------------------------- diff --git a/tests/agents/test_runtime.py b/tests/agents/test_runtime.py index 09439b3c..5f60f596 100644 --- a/tests/agents/test_runtime.py +++ b/tests/agents/test_runtime.py @@ -6,6 +6,8 @@ import contextlib from collections.abc import AsyncGenerator +import pytest + import ai from ai.agents import runtime from ai.types import events, messages @@ -36,6 +38,25 @@ async def concat(a: str, b: str) -> str: # -- runtime.run ------------------------------------------------------------ +def test_get_runtime_outside_run_has_a_clear_error() -> None: + with pytest.raises( + LookupError, match=r"^No active agent runtime: .*agent\.run\(\)\.$" + ) as exc_info: + runtime.get_runtime() + assert type(exc_info.value) is LookupError + assert exc_info.value.__suppress_context__ + + +async def test_yield_from_outside_run_has_a_clear_error() -> None: + async def source() -> AsyncGenerator[events.AgentEvent]: + yield events.TextDelta(chunk="unused") + + with pytest.raises( + LookupError, match=r"^No active agent runtime: .*agent\.run\(\)\.$" + ): + await ai.yield_from(source(), aggregator=ai.agents.MessageAggregator) + + async def test_run_source_lockstep() -> None: """run() only advances its source when the consumer asks for an event.""" advanced: list[int] = []