开发一个 opencode 插件
深入最后更新: 2026年10月21日
opencode 插件是挂载到 agent 事件、定制行为的 JavaScript/TypeScript 模块——可以加工具、改写工具调用、注入上下文、响应会话事件。官方文档的生态页已经收录了一批插件,这篇讲怎么加入。
插件放在哪
两种加载路径:
- 本地文件——
~/.config/opencode/plugins/(全局)或.opencode/plugins/(项目),直接加载。 - npm 包——写进
opencode.json的plugin数组,启动时由 Bun 自动安装,缓存在~/.cache/opencode/node_modules/:
{ "plugin": ["opencode-copilot-plugin", "@my-org/custom-plugin"] }
模块结构
插件导出一个或多个插件函数。每个函数接收上下文对象,返回 hooks 对象:
export const MyPlugin = async ({ project, client, $, directory, worktree }) => {
console.log("Plugin initialized!")
return {
// hook 实现
}
}
上下文提供:
project——当前项目信息directory——当前工作目录worktree——git worktree 路径client——opencode SDK 客户端$——Bun 的 shell API,用于执行命令
hooks 与事件
hook 包含工具拦截点,比如 tool.execute.before——在 shell 命令执行前做清洗:
import { escape } from "shescape"
export const Escape = async (ctx) => ({
"tool.execute.before": async (input, output) => {
if (input.tool === "shell") output.args.command = escape(output.args.command)
},
})
event hook 可订阅生命周期事件——command.executed、file.edited、file.watcher.updated、installation.updated、会话/权限事件等(完整列表见插件文档;较新的事件还包括 lsp.*、message.*、tui.* 和 tool.execute.after)。
依赖与 TypeScript
本地插件可用 npm 包:在配置目录放一个 package.json(.opencode/package.json),opencode 启动时会执行 bun install。
类型从官方包导入:
import type { Plugin } from "@opencode-ai/plugin"
export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => ({
// 类型安全的 hooks
})
发布
- 最小插件就是一个导出
Plugin函数的.ts/.js文件,无需脚手架;骨架可参考生态页上已发布的小插件。 - 以
opencode-*(或 scope 名)发到 npm,用户在plugin配置数组里引用即可,无需手动安装。 - 可研读的实例:生态页上的
opencode-pty、opencode-dynamic-context-pruning、opencode-supermemory。