# 從 V1 移轉外掛

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

<Callout type="warning">
  V1 外掛實作無法在 V2 中執行。只移動檔案或重新命名其設定項目並不足夠。
</Callout>

## 移轉外掛設定

將 `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`。

```ts title="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
  }
}
```

```ts title="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` 屬性上。

| V1 | V2 |
| --- | --- |
| `directory` | `ctx.location.directory` |
| `project` | `ctx.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 與網路搜尋。請參閱[完整外掛上下文](/zht/docs/build/plugins/server#api)。

### 移轉目錄網域

較早版本的外掛透過 `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()` |

```ts
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 請參閱[供應商](/zht/docs/build/plugins/server#providers)和[模型](/zht/docs/build/plugins/server#models)。

## 在 `setup` 中註冊掛鉤

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

```ts title="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"
  },
})
```

```ts title="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 |
| --- | --- |
| `event` | `ctx.event.subscribe()` |
| `dispose` | `setup` 傳回的清理函式 |
| `config` | 受影響網域上的轉換 |
| `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` | 依意圖使用指令轉換或提示詞掛鉤 |
| `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` 會緊接在 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 分開處理。請選擇能滿足外掛需求且範圍最小的層級。

```ts title="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.")
  },
})
```

```ts title="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，執行則傳回結構化內容。

```ts title="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}!`
      },
    }),
  },
})
```

```ts title="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`。
驗證方法屬於整合；供應商轉換會提供來源定義與供應商設定，
而模型轉換會對完整的現用供應商模型集合套用限制與覆寫。

```ts
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`
傳回的清理函式予以中止。

```ts title="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 值具持久性，並以外掛為範圍。

```ts
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 仍各自獨立；此形式不會自動轉譯掛鉤。

```ts title="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 請參閱[伺服器](/zht/docs/build/plugins/server)，Effect 進入點請參閱 [Effect 外掛](/zht/docs/build/plugins/effect)，
自訂方法與事件請參閱[外掛 RPC](/zht/docs/build/plugins/rpc)，終端機介面請參閱 [TUI 外掛](/zht/docs/build/plugins/cli)。