第 7 讲:Agent 类型与 ACP 协议

OpenHands 源码解析 · 第 7 讲

OpenHands 源码解析系列 第 7 讲:Agent 类型与 ACP 协议 基于 OpenHands 源码 · 2026-08-03 一、引言:从单一 Agent 到双轨架构 在 OpenHands 的架构演进中,Agent 从最初的单一 "OpenHands Agent" 逐渐扩展为支持多种智能体类型的双轨架构。第 7 讲我们将深入源码,理解 OpenHands 如何管理两种截然不同的 Agent 类型:原生 OpenHands Agent 和基于 ACP (Agent Client Protocol) 的第三方 Agent,以及它们如何在同一套会话生命周期中协同工作。 二、Agent 类型体系:agent_kind 枚举 OpenHands 使用 agent_kind 字段来区分不同类型的 Agent。这是一个核心路由字段,决定了会话的创建路径、Agent 实例化方式以及事件处理逻辑。 📄 openhands/app_server/app_conversation/app_conversation_models.py (第 125 行) class AppConversationInfo(BaseModel): """Conversation info which does not contain status.""" id: OpenHandsUUID = Field(default_factory=uuid4) # ... agent_kind: str = 'openhands' # ... @computed_field @property def acp_server(self) -> str | None: """Active ACP provider key ('claude-code', 'codex', 'gemini-cli'), else None.""" if self.agent_kind != 'acp': return None return self.tags.get(ACP_SERVER_TAG_KEY) 可以看到, agent_kind 默认值为 'openhands' 。当值变为 'acp' 时,系统通过 acp_server 计算属性从会话标签中提取 ACP 提供商标识(如 claude-code 、 codex 、 gemini-cli )。 📄 openhands/app_server/app_conversation/app_conversation_models.py (第 64-69 行) class AgentType(Enum): """Agent type for conversation.""" DEFAULT = 'default' PLAN = 'plan' 除了 agent_kind ,OpenHands 还有 AgentType 枚举,用于区分 DEFAULT (标准执行模式)和 PLAN (规划模式)两种运行策略。 三、Agent 设置的双变体架构 OpenHands 的核心设计之一是将 Agent 配置抽象为 鉴别联合类型 (Discriminated Union) : OpenHandsAgentSettings 和 ACPAgentSettings 。这两种设置在 AgentSettingsConfig 中作为互斥变体存在。 📄 openhands/app_server/settings/settings_models.py (第 40-48 行) from openhands.sdk.settings import ( ACPAgentSettings, AgentSettingsConfig, ConversationSettings, OpenHandsAgentSettings, apply_agent_settings_diff, default_agent_settings, validate_agent_settings, ) 📄 openhands/app_server/settings/settings_models.py (第 706 行) class Settings(BaseModel): # ... agent_settings…

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