diff --git a/src/ai/agents/hooks.py b/src/ai/agents/hooks.py index 049ac0ae..dde85b45 100644 --- a/src/ai/agents/hooks.py +++ b/src/ai/agents/hooks.py @@ -33,7 +33,7 @@ from . import runtime as runtime_ if TYPE_CHECKING: - from collections.abc import AsyncIterator + from collections.abc import AsyncIterator, Callable class HookRegistry: @@ -141,6 +141,15 @@ def __init__( super().__init__(hook.hook_id) self.hook = hook + def __reduce__( + self, + ) -> tuple[ + Callable[..., HookDeferredException], + tuple[messages_.HookPart[Any]], + dict[str, Any], + ]: + return type(self), (self.hook,), self.__dict__ + def _label(target: str | messages_.HookPart[Any]) -> str: """Normalize a hook label or a HookPart down to its label string.""" diff --git a/tests/agents/test_hooks.py b/tests/agents/test_hooks.py index 2f449f36..90ec9448 100644 --- a/tests/agents/test_hooks.py +++ b/tests/agents/test_hooks.py @@ -3,6 +3,8 @@ from __future__ import annotations import asyncio +import copy +import pickle from collections.abc import AsyncGenerator from typing import Any @@ -20,6 +22,22 @@ class Confirmation(pydantic.BaseModel): reason: str = "" +def test_hook_deferred_exception_survives_pickle_and_copy() -> None: + hook: ai.messages.HookPart[Any] = ai.messages.HookPart( + hook_id="approve_tc-1", hook_type="ToolApproval", status="pending" + ) + exc = ai.HookDeferredException(hook) + exc.add_note("keep exception state") + + restored = pickle.loads(pickle.dumps(exc)) + assert restored.hook == hook + assert copy.copy(exc).hook == hook + assert copy.deepcopy(exc).hook == hook + assert restored.args == exc.args == (hook.hook_id,) + assert str(restored) == str(exc) == hook.hook_id + assert restored.__notes__ == ["keep exception state"] + + # -- resolve_hook() with live future (long-running mode) -------------------