feat: add run-level agent hook lifecycle

This commit is contained in:
chengyongru authored and Xubin Ren committed 2026-06-05 01:09:45 +08:00
1 parent c77ca16d91
commit 2ea226055e
5 files changed
+317 -7

No files matched your search

+37 -1
View File
@@ -12,7 +12,7 @@ from typing import Any, Callable
from loguru import logger
from nanobot.agent.hook import AgentHook, AgentHookContext
from nanobot.agent.hook import AgentHook, AgentHookContext, AgentRunHookContext
from nanobot.agent.tools.registry import ToolRegistry
from nanobot.providers.base import LLMProvider, LLMResponse, ToolCallRequest
from nanobot.utils.file_edit_events import (
@@ -272,6 +272,42 @@ class AgentRunner:
async def run(self, spec: AgentRunSpec) -> AgentRunResult:
hook = spec.hook or AgentHook()
messages = list(spec.initial_messages)
context = AgentRunHookContext(messages=list(messages))
try:
await hook.before_run(context)
result = await self._run_core(spec, hook, messages)
except BaseException as exc:
context.messages = list(messages)
context.stop_reason = "error"
context.error = f"Error: {type(exc).__name__}: {exc}"
context.exception = exc
await hook.on_error(context)
raise
else:
context.messages = list(result.messages)
context.final_content = result.final_content
context.tools_used = list(result.tools_used)
context.usage = dict(result.usage)
context.stop_reason = result.stop_reason
context.error = result.error
context.tool_events = list(result.tool_events)
context.had_injections = result.had_injections
context.exception = None
if context.error is not None:
await hook.on_error(context)
await hook.after_run(context)
return result
finally:
context.messages = list(messages)
await hook.on_finally(context)
async def _run_core(
self,
spec: AgentRunSpec,
hook: AgentHook,
messages: list[dict[str, Any]],
) -> AgentRunResult:
final_content: str | None = None
tools_used: list[str] = []
usage: dict[str, int] = {"prompt_tokens": 0, "completion_tokens": 0}