从 V1 迁移插件
将 V1 插件的工具与钩子迁移至 V2 插件 API。
插件配置可以自动规范化,但插件实现代码必须手工迁移。V1 插件函数返回一个包含工具和钩子的对象;而 V2 插件默认导出一个带有 id 和 setup(ctx) 的定义,在 setup 中通过上下文注册钩子、转换器(transform)、工具与事件订阅。
警告: V1 插件实现无法在 V2 中直接运行。仅移动文件或重命名配置项并不足以完成迁移。
迁移插件配置
将 plugin 重命名为 plugins,并将“包名 + 选项”的二元组替换为对象格式:
// V1
{
"plugin": [
"opencode-example-plugin",
["./plugin/local.ts", { "enabled": true }]
]
}
// V2
{
"plugins": [
"opencode-example-plugin",
{
"package": "./plugin/local",
"options": { "enabled": true }
}
]
}V2 会同时扫描 .opencode/plugin/ 和 .opencode/plugins/ 目录来发现本地插件,建议将 V2 插件文件放在 .opencode/plugins/ 下。配置中的本地路径必须指向目录:以上述示例为例,应将迁移后的实现移至 ./plugin/local/index.ts;若配置为 ./plugin/local.ts 单文件,OpenCode 会跳过加载并在日志中输出警告。移动时请将其依赖的辅助模块一并迁入该目录。本地插件与 npm 包插件使用完全一致的实现 API。
替换插件入口
更新依赖导入路径,将导出的插件函数替换为 Plugin.define,并将初始化逻辑移入 setup:
import type { Plugin } from "@opencode-ai/plugin"
export const ExamplePlugin: Plugin = async ({ directory, project, client }) => {
await client.app.log({
body: { service: "example", level: "info", message: `Loaded for ${project.id}` },
})
return {
// V1 tools and hooks
}
}import { Plugin } from "@opencode/plugin"
export default Plugin.define({
id: "example",
async setup(ctx) {
await ctx.storage.set("last-project", ctx.location.project.id)
console.log(`Loaded for ${ctx.location.directory}`)
},
})每个 V2 插件都必须声明稳定的 id。插件持久化存储按该 ID 隔离,它也用于在状态与诊断信息中标识插件。已发布的插件应依赖与目标 OpenCode 版本兼容的 @opencode/plugin。
迁移上下文对象
V2 的上下文对象既是 OpenCode 客户端,也是插件 API。大多数操作按领域分组,不再挂载在单独的 client 属性下。
| V1 | V2 |
|---|---|
directory | ctx.location.directory |
project | ctx.location.project |
client | 领域方法,如 ctx.session、ctx.permission、ctx.agent |
| 插件 options 参数 | ctx.options |
返回的 dispose() 钩子 | setup 返回的清理函数 |
返回的 event 钩子 | ctx.event.subscribe() |
| 返回的配置、模型或工具修改 | 对应领域的 transform(...) |
$ Bun shell 辅助工具 | 自行导入并管理插件所需的进程 API |
ctx.location 表示当前插件实例被加载的位置,而不一定是插件后续观察到的每个会话或事件所在的位置。当这种区分重要时,请直接读取会话或事件对象上的位置信息。
上下文还暴露了许多上表未列出的领域,包括目录(catalogs)、命令、集成、MCP 服务器、引用、技能、存储、VCS、worktrees 和网页搜索。详见完整插件上下文。
在 setup 中注册钩子
V1 通过字符串键返回钩子;V2 则在拥有该操作的领域上注册钩子,且回调接收单个可变事件对象,而非分离的 input 与 output 对象。
import type { Plugin } from "@opencode-ai/plugin"
export const GuardPlugin: Plugin = async () => ({
"tool.execute.before": async (input, output) => {
if (input.tool === "read" && output.args.filePath.includes(".env")) {
throw new Error("Do not read .env files")
}
},
"shell.env": async (_input, output) => {
output.env.COMPANY_ENV = "development"
},
})import { Plugin } from "@opencode/plugin"
export default Plugin.define({
id: "company.guard",
async setup(ctx) {
await ctx.tool.hook("execute.before", (event) => {
const input = event.input as { filePath?: string }
if (event.tool === "read" && input.filePath?.includes(".env")) {
throw new Error("Do not read .env files")
}
})
await ctx.shell.hook("create.before", (event) => {
event.env.COMPANY_ENV = "development"
})
},
})注册项会在插件整个生命周期内保持生效,并在插件卸载时自动释放。只有当插件需要提前通过 registration.dispose() 移除某个特定钩子或转换器时,才需要保留返回的注册句柄。
请参考下表查找每个 V1 钩子最接近的 V2 API:
| V1 钩子 | V2 API |
|---|---|
event | ctx.event.subscribe() |
dispose | setup 返回的清理函数 |
config | 对应受影响领域的 transforms |
tool 映射表 | ctx.tool.transform(...) |
auth | ctx.integration.transform(...) 及集成 API |
provider | ctx.provider.transform(...) 与 ctx.model.transform(...) |
chat.message | ctx.session.hook("prompt", ...) |
chat.params | ctx.session.hook("context", ...) |
chat.headers | ctx.session.hook("model.request", ...) 或 "http.request" |
permission.ask | ctx.permission.hook("evaluate", ...) |
command.execute.before | 视意图选择命令 transform 或 prompt 钩子 |
tool.execute.before | ctx.tool.hook("execute.before", ...) |
tool.execute.after | ctx.tool.hook("execute.after", ...) |
shell.env | ctx.shell.hook("create.before", ...) |
tool.definition | ctx.tool.transform(...) |
experimental.chat.system.transform | ctx.session.hook("context", ...) 并修改 event.system |
experimental.chat.messages.transform | ctx.session.hook("context", ...) 并修改 event.messages |
experimental.session.compacting | ctx.session.hook("compaction", ...) |
上表给出的是迁移目标,并不总是简单的一对一改名。特别是 V2 的 prompt 钩子运行在持久化提示词准入之前,而 context 钩子运行在代理模型请求发出前夕。如果你的转换逻辑需要覆盖所有类型的模型请求,请分别注册 context、compaction、generate 与 title。
并非每个 V1 实验性钩子都有直接对应的 V2 钩子。使用了 experimental.compaction.autocontinue、experimental.provider.small_model 或 experimental.text.complete 的插件,应结合 V2 的会话、提供商、模型与事件 API 重新评估设计,而不是照搬旧版内部生命周期假设。
command.execute.before 同样没有一对一的全局钩子。如果插件本身拥有该命令,请使用 ctx.command.transform 注册;如果真实目的是拦截并修改由命令或其他来源提交的提示词,请使用 prompt 钩子。
迁移请求钩子
V2 将提示词准入、模型可见上下文、语义化模型选项和底层原生 HTTP 拆分为独立层次,请只挂接满足需求的最窄一层。
import type { Plugin } from "@opencode-ai/plugin"
export const RequestPlugin: Plugin = async () => ({
"chat.params": async (_input, output) => {
output.temperature = 0.2
output.maxOutputTokens = 8_000
},
"chat.headers": async (_input, output) => {
output.headers["x-plugin"] = "review"
},
"experimental.chat.system.transform": async (_input, output) => {
output.system.push("Focus on correctness.")
},
})import { Plugin } from "@opencode/plugin"
export default Plugin.define({
id: "review-request",
async setup(ctx) {
await ctx.session.hook("context", (event) => {
event.system.push({ type: "text", text: "Focus on correctness." })
event.options.temperature = 0.2
event.options.maxTokens = 8_000
})
await ctx.session.hook("model.request", (event) => {
event.headers["x-plugin"] = "review"
})
},
})语义化的提供商参数应写在 event.options 中;模型请求头与原始请求配置使用 model.request;仅在插件确实需要干预厂商原生 HTTP 报文交互时,才使用 http.request 或 http.response。针对特定提供商的钩子可将 { providerID: "..." } 作为 ctx.session.hook 的第三个参数传入。
迁移自定义工具
V1 使用旧版 tool() 辅助函数返回 tool 映射表;V2 则通过同步的 ctx.tool.transform 编辑器注册工具定义。工具输入参数采用 JSON Schema,执行函数返回结构化内容。
import { tool } from "@opencode-ai/plugin"
export const ToolsPlugin = async () => ({
tool: {
greeting: tool({
description: "Create a greeting",
args: { name: tool.schema.string() },
async execute(args) {
return `Hello ${args.name}!`
},
}),
},
})import { Plugin } from "@opencode/plugin"
export default Plugin.define({
id: "greeting",
async setup(ctx) {
await ctx.tool.transform((editor) => {
editor.add({
name: "greeting",
description: "Create a greeting",
input: {
type: "object",
properties: { name: { type: "string" } },
required: ["name"],
additionalProperties: false,
},
async execute(input) {
return { content: `Hello ${(input as { name: string }).name}!` }
},
})
})
},
})Transform 是可重放的状态编辑操作,其回调必须保持同步、轻量且不包含一次性副作用。应在注册前先加载外部数据并在回调中捕获它,当外部数据变化时调用对应领域的 reload() 方法。后执行的插件 transform 可以看到先前插件的变更,并对其进行更新、替换或移除。
同样的 transform 模式也替代了 V1 的 config 和 provider 钩子,但 V2 不再暴露单一的可变全局配置对象。请向各自所属的领域注册修改:ctx.agent、ctx.provider、ctx.model、ctx.command、ctx.integration、ctx.mcp、ctx.reference、ctx.skill、ctx.tool、ctx.vcs、ctx.websearch 或 ctx.worktree。认证方式归属于集成(integrations);提供商 transform 用于贡献源定义与提供商配置;模型 transform 则对全部活跃提供商的完整模型集合应用过滤限制与覆写。
await ctx.provider.transform((editor) => {
editor.update("anthropic", (provider) => {
provider.headers = { ...provider.headers, "x-company": "engineering" }
})
})
await ctx.model.transform((editor) => {
editor.list("anthropic").forEach((model) => {
if (!model.capabilities.tools) editor.remove(model.providerID, model.id)
})
})迁移事件与清理逻辑
V1 的 event 回调在 V2 中变为对公开服务器事件流的异步订阅,并在 setup 返回的清理函数中中止该订阅:
import { Plugin } from "@opencode/plugin"
export default Plugin.define({
id: "notifications",
setup(ctx) {
const controller = new AbortController()
void (async () => {
for await (const event of ctx.event.subscribe({ signal: controller.signal })) {
if (event.type === "session.idle") console.log("Session completed")
}
})()
return () => controller.abort()
},
})请使用清理函数释放插件自行创建的定时器、子进程、套接字等资源。钩子和 transform 的注册与插件生命周期绑定,会自动清理。
迁移配置选项与持久化状态
通过 ctx.options 读取插件选项。当状态归属于插件自身时,请使用 ctx.storage,而不要自行创建全局文件;其 JSON 数据持久化存储并按插件自动隔离:
const strict = ctx.options.strict === true
await ctx.storage.set("settings", { strict })
const settings = await ctx.storage.get("settings")在同一个包中同时支持 V1 与 V2
插件包可以在过渡期内通过同一个默认导出同时暴露两套实现:V1 会调用 server(),V2 会调用 setup()。两套 API 相互独立,此结构不会自动转换钩子:
import { Plugin } from "@opencode/plugin"
export default {
...Plugin.define({
id: "example",
async setup(ctx) {
await ctx.tool.hook("execute.before", () => {
console.log("A tool is about to run")
})
},
}),
async server() {
return {
"tool.execute.before": async () => {
console.log("A tool is about to run")
},
}
},
}OpenCode 1.18.29 及更高版本支持 V1 对象入口格式。如果你需要兼容更早的 V1 版本,请使用独立的包版本或入口点,并在你声明支持的最低版本上进行实测。过渡期结束后请移除 V1 实现。
验证迁移后的插件
对每个迁移完成的插件,请逐项检查:
- 确认其 ID 与来源已出现在活跃插件列表中。
- 触发并验证所有注册的钩子、transform、工具、命令与事件订阅。
- 通过重载或移除插件来验证清理逻辑是否生效。
- 在全新项目中测试插件选项与持久化状态。
- 若为已发布的 npm 包,务必测试真实安装后的包,而非仅测试工作区软链接副本。
完整 Promise API 请参阅服务端插件,Effect 入口请参阅 Effect 插件,自定义方法与事件请参阅插件 RPC,终端界面扩展请参阅 TUI 插件。