第 19 讲:Agent 核心系统——多 Agent 编排、Runner 循环与权限治理

OpenCode 源码解析 · 第 19 讲

OpenCode 源码解析 第 19 讲:Agent 核心系统——多 Agent 编排、Runner 循环与权限治理 基于 dev 分支源码 · 2026-07-26 一、Agent:从"一个 Agent"到"多 Agent 编排" 前十八讲覆盖了 OpenCode 从 CLI 到 Session 处理器的完整链路。这一讲深入 Agent 核心系统 ——OpenCode 的真正"大脑"。V2 架构不再使用单一 Agent 处理所有任务,而是设计了 多 Agent 编排体系 :每个 Agent 有独立的角色、System Prompt、权限规则和模型配置。Agent 系统横跨 8 个核心文件、约 1,500+ 行代码 ,是整个 V2 架构的控制中枢。 📦 本讲核心文件 agent.ts (111 行)— Agent 注册与选择 plugin/agent.ts (206 行)— 内建 Agent 定义 session/runner/llm.ts (427 行)— Agent 执行循环 session/runner/model.ts (218 行)— 模型解析引擎 system-context/index.ts (321 行)— 动态系统上下文 question.ts (153 行)— 用户交互系统 二、AgentV2:Agent 注册中心与服务接口 agent.ts 定义了 Agent 的注册、查询和选择机制。Agent 不再是硬编码的配置项,而是通过 State.Transformable 模式管理的动态注册表。 1. Agent Info Schema 📄 config/agent.ts (第 13-25 行) class Info extends Schema.Class<Info>("ConfigV2.Agent")({ model: Schema.String.pipe(Schema.optional), // 绑定的模型 variant: Schema.String.pipe(Schema.optional), // 模型变体 request: ConfigProvider.Request.pipe(Schema.optional), system: Schema.String.pipe(Schema.optional), // System Prompt description: Schema.String.pipe(Schema.optional), mode: Schema.Literals(["subagent", "primary", "all"]), hidden: Schema.Boolean.pipe(Schema.optional), // 是否对用户可见 color: Color.pipe(Schema.optional), steps: PositiveInt.pipe(Schema.optional), // 最大步数限制 disabled: Schema.Boolean.pipe(Schema.optional), permissions: Permission.Ruleset.pipe(Schema.optional), // 权限规则集 }) Schema 设计要点: 每个 Agent 拥有独立的 model/variant 绑定,独立的 System Prompt,以及最重要的——独立的 权限规则集(Permission Ruleset) 。mode 字段区分了 primary(用户可直接选择的主 Agent)、subagent(只能被其他 Agent 调用的子 Agent)和 all(两者皆可)。 2. Agent 选择逻辑 📄 agent.ts (第 67-101 行) // Selection 是 Runner 实际使用的 Agent 视图 interface Selection { readonly id: ID readonly info: Info | undefined } // 选择逻辑:排除 subagent 和 hidden const selectable = (agent: Info | undefined) => agent && agent.mode !== "sub…

阅读全文:OpenCode 源码解析 第 19 讲