feat: add run-level agent hook lifecycle

This commit is contained in:
chengyongru
2026-06-05 01:09:45 +08:00
committed by Xubin Ren
parent c77ca16d91
commit 2ea226055e
5 changed files with 317 additions and 7 deletions
+39
View File
@@ -28,6 +28,21 @@ class AgentHookContext:
error: str | None = None
@dataclass(slots=True)
class AgentRunHookContext:
"""Run-level state snapshot exposed to runner hooks."""
messages: list[dict[str, Any]]
final_content: str | None = None
tools_used: list[str] = field(default_factory=list)
usage: dict[str, int] = field(default_factory=dict)
stop_reason: str | None = None
error: str | None = None
tool_events: list[dict[str, str]] = field(default_factory=list)
had_injections: bool = False
exception: BaseException | None = None
class AgentHook:
"""Minimal lifecycle surface for shared runner customization."""
@@ -37,6 +52,18 @@ class AgentHook:
def wants_streaming(self) -> bool:
return False
async def before_run(self, context: AgentRunHookContext) -> None:
pass
async def after_run(self, context: AgentRunHookContext) -> None:
pass
async def on_error(self, context: AgentRunHookContext) -> None:
pass
async def on_finally(self, context: AgentRunHookContext) -> None:
pass
async def before_iteration(self, context: AgentHookContext) -> None:
pass
@@ -98,6 +125,18 @@ class CompositeHook(AgentHook):
async def before_iteration(self, context: AgentHookContext) -> None:
await self._for_each_hook_safe("before_iteration", context)
async def before_run(self, context: AgentRunHookContext) -> None:
await self._for_each_hook_safe("before_run", context)
async def after_run(self, context: AgentRunHookContext) -> None:
await self._for_each_hook_safe("after_run", context)
async def on_error(self, context: AgentRunHookContext) -> None:
await self._for_each_hook_safe("on_error", context)
async def on_finally(self, context: AgentRunHookContext) -> None:
await self._for_each_hook_safe("on_finally", context)
async def on_stream(self, context: AgentHookContext, delta: str) -> None:
await self._for_each_hook_safe("on_stream", context, delta)