跳到主要內容
文件
移轉外掛設定

從 V1 移轉外掛

外掛設定可以自動標準化,但外掛實作程式碼必須移植。V1 外掛函式 會傳回一個包含工具與掛鉤的物件。V2 外掛會預設匯出含有 id 與 setup(ctx) 的定義; setup 會透過上下文註冊掛鉤、轉換、工具與訂閱。

將 plugin 重新命名為 plugins。以物件取代套件與選項的元組:

JSONC
// 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 檔案會略過,並在日誌中留下警告。 移動外掛時,請將支援模組保留在外掛旁。本機外掛與套件外掛使用相同的實作 API。

變更套件匯入、以 Plugin.define 取代匯出的外掛函式,並將初始化移入 setup。

V1
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
  }
}
V2
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 為範圍,ID 也會在狀態 與診斷中識別外掛。已發布的外掛應相依於與其目標 OpenCode 版本相容的 @opencode/plugin 版本。

V2 上下文既是 OpenCode 用戶端,也是外掛 API。大多數操作會依功能領域分組,而不是 放在獨立的 client 屬性上。

V1V2
directoryctx.location.directory
projectctx.location.project
client依功能領域分組的方法,例如 ctx.session、ctx.permission 和 ctx.agent
外掛選項引數ctx.options
傳回的 dispose() 掛鉤setup 傳回的清理函式
傳回的 event 掛鉤ctx.event.subscribe()
傳回的設定、模型或工具變更網域的 transform(...)
Bun 的 shell 輔助函式 $匯入並管理外掛使用的處理程序 API

ctx.location 描述此外掛執行個體載入的位置。它不是外掛可能觀察到的每個工作階段或事件的 位置。當這項區別很重要時,請讀取工作階段或事件資料。

外掛上下文提供的網域不只表中所列,還包括指令、整合、MCP 伺服器、引用、技能、儲存、VCS、worktree 與網路搜尋。請參閱完整外掛上下文。

較早版本的外掛透過 ctx.catalog 發布供應商與模型。現在 OpenCode 分別透過 ctx.provider 和 ctx.model 提供這兩個網域,因此呼叫 ctx.catalog.transform 的外掛將無法載入。

舊版目錄 API目前的對應用法
ctx.catalog.transform(draft => …)ctx.provider.transform(editor => …) 和 ctx.model.transform(editor => …)
draft.provider.update(id, fn)ctx.provider 的 editor.update(id, fn)
draft.model.update(providerID, modelID, fn)ctx.model 的 editor.update(providerID, modelID, fn)
ctx.catalog.reload()ctx.provider.reload() 和 ctx.model.reload()
TypeScript
await ctx.provider.transform((editor) => {
  editor.update("acme", (provider) => {
    provider.headers = { ...provider.headers, "x-company": "engineering" }
  })
  editor.models.update("acme", "reasoner", (model) => {
    model.name = "Acme Reasoner"
  })
})

完整的編輯器 API 請參閱供應商和模型。

V1 以字串鍵傳回掛鉤。V2 會在擁有該操作的網域上註冊每個掛鉤。回呼會收到一個 可變事件,而不是分開的 input 與 output 物件。

V1
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"
  },
})
V2
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
eventctx.event.subscribe()
disposesetup 傳回的清理函式
config受影響網域上的轉換
tool 對照表ctx.tool.transform(...)
authctx.integration.transform(...) 與整合 API
providerctx.provider.transform(...) 與 ctx.model.transform(...)
chat.messagectx.session.hook("prompt", ...)
chat.paramsctx.session.hook("context", ...)
chat.headersctx.session.hook("model.request", ...) 或 "http.request"
permission.askctx.permission.hook("evaluate", ...)
command.execute.before依意圖使用指令轉換或提示詞掛鉤
tool.execute.beforectx.tool.hook("execute.before", ...)
tool.execute.afterctx.tool.hook("execute.after", ...)
shell.envctx.shell.hook("create.before", ...)
tool.definitionctx.tool.transform(...)
experimental.chat.system.transformctx.session.hook("context", ...) 並編輯 event.system
experimental.chat.messages.transformctx.session.hook("context", ...) 並編輯 event.messages
experimental.session.compactingctx.session.hook("compaction", ...)

這些是移轉時可採用的對應項目,不一定能直接改名。特別是 V2 的 prompt 掛鉤會在提示詞正式收錄至持久儲存前執行, 而 context 會緊接在 agent 送出模型請求前執行。若轉換必須套用至 每種模型請求,請分別註冊 context、compaction、 generate 與 title。

並非每個實驗性 V1 掛鉤都有對應的直接 V2 掛鉤。請對照 V2 的工作階段、供應商、模型與事件 API,重新評估使用 experimental.compaction.autocontinue、experimental.provider.small_model 或 experimental.text.complete 的外掛,而不是保留內部的生命週期假設。

command.execute.before 也沒有一對一的全域掛鉤。當外掛擁有該指令時,請以 ctx.command.transform 註冊指令。若真正的意圖是修改指令與其他 提示詞來源提交的提示詞,請使用提示詞掛鉤。

V2 將提示詞收錄、模型可見的上下文、語意層的模型選項及原生 HTTP 分開處理。請選擇能滿足外掛需求且範圍最小的層級。

V1
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.")
  },
})
V2
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 編輯器註冊工具定義。工具 schema 使用 JSON Schema,執行則傳回結構化內容。

V1
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}!`
      },
    }),
  },
})
V2
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}!` }
        },
      })
    })
  },
})

轉換是可重播的狀態編輯。請讓回呼保持同步、輕量,且不含一次性的副作用。請在 註冊前載入外部資料、在回呼中捕捉它,並在資料變更時呼叫該網域的 reload() 方法。後續外掛轉換會看到先前的變更,並可更新、取代或移除它們。

相同的轉換模式可取代 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。 驗證方法屬於整合;供應商轉換會提供來源定義與供應商設定, 而模型轉換會對完整的現用供應商模型集合套用限制與覆寫。

TypeScript
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 回呼會變成對公開伺服器事件串流的非同步訂閱。請從 setup 傳回的清理函式予以中止。

V2
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()
  },
})

計時器、子處理程序、通訊端與外掛擁有的其他資源,請使用清理函式。掛鉤與轉換 註冊會以外掛為範圍,並自動清理。

從 ctx.options 讀取選項。當狀態屬於外掛時,請使用 ctx.storage,而不要自行建立全域檔案;其 JSON 值具持久性,並以外掛為範圍。

TypeScript
const strict = ctx.options.strict === true
await ctx.storage.set("settings", { strict })
const settings = await ctx.storage.get("settings")

套件可以暫時從同一個預設匯出公開兩種實作。V1 會呼叫 server(),V2 則呼叫 setup()。API 仍各自獨立;此形式不會自動轉譯掛鉤。

src/index.ts
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 實作。

對每個外掛:

  1. 確認其 ID 與來源出現在作用中的外掛清單中。
  2. 實際操作每個已註冊的掛鉤、轉換、工具、指令與事件訂閱。
  3. 透過重新載入或移除外掛,驗證清理。
  4. 以乾淨的專案測試外掛選項與持久狀態。
  5. 對於已發布的套件,請測試已安裝的套件,而不只是工作區連結的複本。

完整 Promise API 請參閱伺服器,Effect 進入點請參閱 Effect 外掛, 自訂方法與事件請參閱外掛 RPC,終端機介面請參閱 TUI 外掛。