外掛

透過自定義外掛擴充 OpenCode。涵蓋外掛 API、事件鉤子、自定義工具、環境變數注入以及發布到 npm 分發的完整指南。

本頁內文若連結到尚未提供繁體版本的頁面(例如 /ecosystem/plugins/、/news/),會開啟英文原頁;導覽與頁尾標有 EN 的項目即為這類頁面。

外掛允許你透過掛鉤各種事件並自定義行為來擴充 OpenCode。你可以建立外掛來新增新功能、與外部服務整合,或修改 OpenCode 的預設行為。

有關示例,請參閱社群建立的外掛。


使用外掛

有兩種載入外掛的方式。


從本機檔案

將 JavaScript 或 TypeScript 檔案放到外掛目錄中。

  • .opencode/plugins/ - 專案級外掛
  • ~/.config/opencode/plugins/ - 全域性外掛

這些目錄中的檔案會在啟動時自動載入。


從 npm

在設定檔案中指定 npm 包。

{
  "$schema": "https://opencode.ai/config.json",
  "plugin": ["opencode-helicone-session", "opencode-wakatime", "@my-org/custom-plugin"]
}

普通包和帶 scope 的 npm 包都受支援。

在 ecosystem 中瀏覽可用的外掛。


外掛的安裝方式

npm 外掛在啟動時由 Bun 自動安裝。包及其依賴會快取在 ~/.cache/opencode/node_modules/ 中。

本機外掛直接從外掛目錄載入。要使用外部包,你必須在設定目錄中建立一個 package.json(見 Dependencies),或者將外掛發布到 npm 並將其新增到你的設定中。


載入順序

外掛會從所有來源載入,所有 hooks 按順序執行。載入順序為:

  1. 全域性設定(~/.config/opencode/opencode.json)
  2. 專案設定(opencode.json)
  3. 全域性外掛目錄(~/.config/opencode/plugins/)
  4. 專案外掛目錄(.opencode/plugins/)

同名同版本的重複 npm 包只會載入一次。但是,名稱相似的本機外掛和 npm 外掛會作為獨立的兩個外掛載入。


建立一個外掛

外掛是一個 JavaScript/TypeScript 模組,匯出一個或多個外掛函式。 每個函式接收一個上下文物件並返回一個 hooks 物件。


依賴項

本機外掛和自定義工具可以使用外部 npm 包。在你的設定目錄中新增一個 package.json,並在其中宣告你需要的依賴。

{
  "dependencies": {
    "shescape": "^2.1.0"
  }
}

OpenCode 會在啟動時執行 bun install 來安裝這些依賴。之後你的外掛和工具就可以匯入它們了。

import { escape } from "shescape"

export const MyPlugin = async (ctx) => {
  return {
    "tool.execute.before": async (input, output) => {
      if (input.tool === "bash") {
        output.args.command = escape(output.args.command)
      }
    },
  }
}

基本結構

export const MyPlugin = async ({ project, client, $, directory, worktree }) => {
  console.log("Plugin initialized!")

  return {
    // Hook implementations go here
  }
}

外掛函式會接收:

  • project:當前專案的資訊。
  • directory:當前工作目錄。
  • worktree:git worktree 路徑。
  • client:一個 opencode SDK 客戶端,用於與 AI 互動。
  • $:Bun 的 shell API,用於執行命令。

TypeScript support

對於 TypeScript 外掛,你可以從外掛包中匯入型別:

import type { Plugin } from "@opencode-ai/plugin"

export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => {
  return {
    // Type-safe hook implementations
  }
}

Events

外掛可以訂閱事件,訂閱方式見下方 Examples 章節。下面是可用事件的列表。

Command Events

  • command.executed

File Events

  • file.edited
  • file.watcher.updated

Installation Events

  • installation.updated

LSP Events

  • lsp.client.diagnostics
  • lsp.updated

Message Events

  • message.part.removed
  • message.part.updated
  • message.removed
  • message.updated

Permission Events

  • permission.asked
  • permission.replied

Server Events

  • server.connected

Session Events

  • session.created
  • session.compacted
  • session.deleted
  • session.diff
  • session.error
  • session.idle
  • session.status
  • session.updated

Todo Events

  • todo.updated

Shell Events

  • shell.env

Tool Events

  • tool.execute.after
  • tool.execute.before

TUI Events

  • tui.prompt.append
  • tui.command.execute
  • tui.toast.show

Examples

下面是一些你可以用來擴充 opencode 的外掛示例。


傳送通知

在某些事件發生時傳送通知:

export const NotificationPlugin = async ({ project, client, $, directory, worktree }) => {
  return {
    event: async ({ event }) => {
      // Send notification on session completion
      if (event.type === "session.idle") {
        await $`osascript -e 'display notification "Session completed!" with title "opencode"'`
      }
    },
  }
}

我們使用 osascript 在 macOS 上執行 AppleScript。這裡我們用它來傳送通知。


.env protection

阻止 opencode 讀取 .env 檔案:

export const EnvProtection = async ({ project, client, $, directory, worktree }) => {
  return {
    "tool.execute.before": async (input, output) => {
      if (input.tool === "read" && output.args.filePath.includes(".env")) {
        throw new Error("Do not read .env files")
      }
    },
  }
}

注入環境變數

向所有 shell 執行個體(AI 工具與使用者終端)注入環境變數:

export const InjectEnvPlugin = async () => {
  return {
    "shell.env": async (input, output) => {
      output.env.MY_API_KEY = "secret"
      output.env.PROJECT_ROOT = input.cwd
    },
  }
}

自定義工具

外掛也可以向 opencode 新增自定義工具:

import { type Plugin, tool } from "@opencode-ai/plugin"

export const CustomToolsPlugin: Plugin = async (ctx) => {
  return {
    tool: {
      mytool: tool({
        description: "This is a custom tool",
        args: {
          foo: tool.schema.string(),
        },
        async execute(args, context) {
          const { directory, worktree } = context
          return `Hello ${args.foo} from ${directory} (worktree: ${worktree})`
        },
      }),
    },
  }
}

tool 輔助函式用於建立一個可被 opencode 呼叫的自定義工具。它接受一個 Zod schema 函式,並返回包含以下內容的工具定義:

  • description:工具的功能描述
  • args:工具引數的 Zod schema
  • execute:工具被呼叫時執行的函式

你的自定義工具會與內建工具一起在 opencode 中可用。


Logging

使用 client.app.log() 而不是 console.log 來進行結構化日誌記錄:

export const MyPlugin = async ({ client }) => {
  await client.app.log({
    body: {
      service: "my-plugin",
      level: "info",
      message: "Plugin initialized",
      extra: { foo: "bar" },
    },
  })
}

日誌級別:debug、info、warn、error。詳見 SDK 文件。


壓縮鉤子

自定義在 session 被壓縮(compact)時包含的上下文:

import type { Plugin } from "@opencode-ai/plugin"

export const CompactionPlugin: Plugin = async (ctx) => {
  return {
    "experimental.session.compacting": async (input, output) => {
      // Inject additional context into the compaction prompt
      output.context.push(`
## Custom Context

Include any state that should persist across compaction:
- Current task status
- Important decisions made
- Files being actively worked on
`)
    },
  }
}

experimental.session.compacting hook 會在 LLM 生成延續摘要之前觸發。使用它可以注入預設壓縮 prompt 可能會遺漏的特定領域上下文。

你也可以透過設定 output.prompt 來完全替換壓縮 prompt:

import type { Plugin } from "@opencode-ai/plugin"

export const CustomCompactionPlugin: Plugin = async (ctx) => {
  return {
    "experimental.session.compacting": async (input, output) => {
      // Replace the entire compaction prompt
      output.prompt = `
You are generating a continuation prompt for a multi-agent swarm session.

Summarize:
1. The current task and its status
2. Which files are being modified and by whom
3. Any blockers or dependencies between agents
4. The next steps to complete the work

Format as a structured prompt that a new agent can use to resume work.
`
    },
  }
}

當設定了 output.prompt 時,它會完全替換預設的壓縮 prompt。在這種情況下,output.context 陣列會被忽略。