15.7 Plugin Interface 实现

模型: claude-opus-4-6 (anthropic/claude-opus-4-6) 生成日期: 2026-02-17


plugin/ 目录是 oh-my-opencode 的接口层——它将内部的 Agent、工具、Hook 等能力"翻译"成 OpenCode Plugin 接口。本节分析每个接口实现。

15.7.1 plugin/chat-params.ts:Anthropic Effort 等级注入

chat.params Hook 在 LLM 请求发出之前修改请求参数。oh-my-opencode 用它来注入 Anthropic 的 effort 等级:

// oh-my-opencode/src/plugin/chat-params.ts
export function createChatParamsHandler(args: {
  anthropicEffort: { "chat.params"?: (input, output) => Promise<void> } | null
}): (input, output) => Promise<void> {
  return async (input, output) => {
    const normalizedInput = buildChatParamsInput(input)
    if (!normalizedInput) return
    if (!isChatParamsOutput(output)) return

    // 委托给 anthropicEffort Hook
    await args.anthropicEffort?.["chat.params"]?.(normalizedInput, output)
  }
}

ChatParamsOutput 的结构允许修改 temperature、topP、topK 以及任意的 provider-specific options:

15.7.2 plugin/chat-message.ts:消息预处理

chat.message Hook 在用户消息发送给 LLM 之前进行预处理,是 oh-my-opencode 最复杂的接口实现之一:

这个 Handler 执行了一系列有序的操作:

  1. Session-Agent 映射记录:记录哪个会话使用了哪个 Agent,供后续 Hook 查询

  2. 首消息变体注入:对会话的第一条消息应用 Agent 变体(variant),实现模型行为的微调

  3. 上下文注入:将 AGENTS.md、README.md、规则文件的内容注入到消息中

  4. 关键词检测:扫描用户消息中的关键词(如 "ultrawork"),触发相应的自动化流程

  5. Start Work Hook:如果检测到工作启动命令,触发 start-work 流程

15.7.3 plugin/messages-transform.ts:消息列表变换

experimental.chat.messages.transform 是一个实验性接口,允许在整个消息列表发送给 LLM 之前对其进行变换。oh-my-opencode 用它实现 thinking block 验证和消息格式规范化等功能。

15.7.4 plugin/event.ts:事件处理

event Handler 是 oh-my-opencode 的事件分发中心,将 OpenCode 的事件路由到各个 Hook:

15.7.5 plugin/tool-execute-before.ts:工具执行前拦截

tool.execute.before Hook 在工具执行之前被调用,可以修改工具的输入参数或完全取消执行:

oh-my-opencode 用它实现:

  • Hashline Read 增强:在 Read 工具执行前添加标记,使输出包含行号哈希

  • 写入保护:检查是否正在写入已存在的文件,发出警告

  • Claude Code Hook 兼容:触发 Claude Code 格式的 PreToolUse Hook

15.7.6 plugin/tool-execute-after.ts:工具执行后处理

tool.execute.after Hook 在工具执行完成后被调用,可以修改工具的输出或触发副作用:

oh-my-opencode 用它实现:

  • 工具输出截断:防止过长的输出消耗过多 Token

  • 编辑错误恢复:检测 Edit 工具的错误并注入恢复指令

  • 先发制人压缩:检查 Token 使用率并触发压缩

  • 上下文窗口监控:发出上下文使用率警告

  • 注释检查:检测 AI 生成代码中的过多注释

15.7.7 plugin/session-agent-resolver.ts:Session-Agent 映射

Session Agent Resolver 从会话的消息历史中推断当前使用的 Agent:

这个函数在多个场景中被使用——例如后台任务完成时,需要知道父会话使用的是哪个 Agent,以便将通知发送给正确的 Agent。

15.7.8 plugin/available-categories.ts:Category 定义

createAvailableCategories() 从配置中构建可用的 Category 列表,供 task 工具的 category 参数使用。

15.7.9 plugin/tool-registry.ts:工具注册表

createToolRegistry() 是工具注册的核心。它将所有自定义工具汇总、应用禁用列表过滤、并返回最终的工具表:

本节小结

oh-my-opencode 的 Plugin Interface 层通过 9 个专门的 Handler 函数,将内部的 53 个 Hook、15 个工具和 11 个 Agent 的能力映射到 OpenCode 的 Plugin 接口上。每个 Handler 都是一个轻薄的适配层——它的主要工作是规范化输入输出、分发事件到内部 Hook、以及处理边界情况。

这种设计使得 oh-my-opencode 的内部架构完全不依赖于 OpenCode 的 Plugin 接口设计——即使 OpenCode 的 Plugin 接口发生变化,只需要修改这些 Handler 函数,而不需要改动内部的 Agent、Hook 或工具逻辑。

Last updated