第 10 讲:Webhook 与事件回调机制

OpenHands 源码解析 · 第 10 讲

OpenHands 源码解析系列 第 10 讲:Webhook 与事件回调机制 基于 OpenHands 源码 · 2026-08-06 一、Webhook 在 OpenHands 中的角色 OpenHands 的 agent-server(负责运行 AI Agent 的沙箱内服务)与 app-server(面向用户的管理服务)是两个独立进程。它们之间如何通信?答案是 Webhook + 事件回调 。 当沙箱中的 Agent 执行对话时,会通过 HTTP POST 向 app-server 的 /webhooks/ 端点推送两类通知: 🔹 对话生命周期事件 — 对话开始、暂停、恢复、删除 🔹 事件流事件 — 消息、状态变更、统计信息、错误 与此同时,app-server 内部还有一个 事件回调系统(Event Callback System) ,用于在特定事件发生时自动执行处理器(如自动为对话生成标题)。 📦 核心源码位置 openhands/app_server/event_callback/ 共 9 个文件,包含路由、服务抽象层、SQL 实现、回调处理器等 二、Webhook 路由架构 2.1 路由注册 Webhook 路由挂载在 /webhooks 前缀下,通过 v1_router 统一注册: 📄 openhands/app_server/v1_router.py (第 6-34 行) from openhands.app_server.event_callback import ( webhook_router, ) ... router.include_router(webhook_router.router) 2.2 两个核心端点 📄 webhook_router.py (第 84 行) router = APIRouter(prefix='/webhooks', tags=['Webhooks']) 端点 1: POST /webhooks/conversations — 对话生命周期通知 📄 webhook_router.py (第 362-480 行) @router.post('/conversations') async def on_conversation_update( conversation_info: ConversationInfo, sandbox_record: SandboxRecord = Depends(valid_sandbox), app_conversation_info_service: AppConversationInfoService = ..., ) -> Success: """Webhook callback for when a conversation starts, pauses, resumes, or deletes. The ``ConversationInfo.agent`` field is an ``AgentBase`` discriminated union so both OpenHands (``Agent``) and ACP (``ACPAgent``) payloads are accepted on this single endpoint. """ 端点 2: POST /webhooks/events/{conversation_id} — 事件流通知 📄 webhook_router.py (第 535-626 行) @router.post('/events/{conversation_id}') async def on_event( background_tasks: BackgroundTasks, events: list[Event], conversation_id: UUID, app_conversation_info: AppConversationInfo = Depends(valid_conversation), app_conversation_info_service: AppConversationInfoService = ..., event_service: EventService = ev…

阅读全文:OpenHands 源码解析 第 10 讲