日本語
ドキュメント
OpenCode で開発
プラグイン
V1 からの移行

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 のようなファイルを指定すると、ログに警告が出力されてスキップされます。移動時は補助モジュールもプラグインの近くに配置してください。ローカルプラグインとパッケージプラグインは同じ実装 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 ごとにスコープされ、ステータスや診断情報でもプラグインの識別に使用されます。公開プラグインは、対象とする OpenCode リリースと互換性のあるバージョンの @opencode/plugin に依存してください。

コンテキストの移行

V2 のコンテキストは、OpenCode クライアントとプラグイン API の両方の役割を兼ね備えています。ほとんどの操作は独立した client プロパティではなく、ドメインごとにグループ化されています。

V1V2
directoryctx.location.directory
projectctx.location.project
clientctx.session、ctx.permission、ctx.agent などのドメインメソッド
プラグインの options 引数ctx.options
返却される dispose() フックsetup が返すクリーンアップ関数
返却される event フックctx.event.subscribe()
返却される config / model / tool の変更各ドメインの transform(...)
$ Bun シェルヘルパープラグインが使用するプロセス API をインポートして管理

ctx.location はこのプラグインインスタンスが読み込まれたロケーションを表します。プラグインが観測するすべてのセッションやイベントのロケーションとは限りません。その区別が重要な場合は、セッションやイベントのデータから読み取ってください。

コンテキストはこの表に記載したもの以外にも、カタログ、コマンド、インテグレーション、MCP サーバー、リファレンス、スキル、ストレージ、VCS、ワークツリー、Web 検索など多くのドメインを公開しています。詳細は完全なプラグインコンテキストを参照してください。

setup でのフック登録

V1 では文字列キーでフックを返していました。V2 では各フックをその操作を所有するドメインに登録します。コールバックは別々の input と output オブジェクトではなく、1 つのミュータブルなイベントを受け取ります。

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)はプラグインのライフタイムの間有効であり、アンロード時に自動的に破棄されます。返却される登録オブジェクトを保持する必要があるのは、registration.dispose() でその特定のフックや変換を早期に解除したい場合のみです。

以下の表で、各 V1 フックに最も近い V2 API を確認してください。

V1 フックV2 API
eventctx.event.subscribe()
disposesetup が返すクリーンアップ関数
config対象ドメインでの transform
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目的に応じてコマンドの transform または prompt フック
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 フックは永続的なプロンプト受理(admission)の前に実行されるのに対し、context はエージェントのモデルリクエスト直前に実行されます。あらゆるモデルリクエスト種別に変換を適用する必要がある場合は、context、compaction、generate、title を個別に登録してください。

すべての実験的 V1 フックに対応する直接の V2 フックがあるわけではありません。experimental.compaction.autocontinue、experimental.provider.small_model、experimental.text.complete を使用しているプラグインは、内部ライフサイクルの前提をそのまま引き継ぐのではなく、V2 のセッション、プロバイダー、モデル、イベントの各 API に照らして再設計してください。

command.execute.before にも 1 対 1 で対応するグローバルフックはありません。プラグインがそのコマンドを所有している場合は ctx.command.transform でコマンドを登録してください。コマンドやその他のプロンプトソースから送信されるプロンプトを変更することが本来の目的であれば、prompt フックを使用してください。

リクエストフックの移行

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 を使用してください。プロバイダー固有のフックでは、ctx.session.hook の第 3 引数に { providerID: "..." } を渡せます。

カスタムツールの移行

V1 では旧 tool() ヘルパーで構築した tool マップを返していました。V2 では同期的な ctx.tool.transform エディターを通じてツール定義を登録します。ツールスキーマには 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}!` }
        },
      })
    })
  },
})

変換(transform)は再実行可能な状態編集です。コールバックは同期的かつ軽量に保ち、一度限りの副作用を含めないでください。外部データは登録前に読み込んでコールバック内にキャプチャし、そのデータが変化したときにドメインの 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)に登録してください。認証方式はインテグレーションに属します。プロバイダー変換はソース定義とプロバイダー設定を提供し、モデル変換はアクティブなプロバイダーのモデルコレクション全体に制限やオーバーライドを適用します。

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 値が永続化され、プラグイン単位にスコープされます。

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

1 つのパッケージで V1 と V2 の両方をサポートする

1 つのデフォルトエクスポートから両方の実装を一時的に公開できます。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")
      },
    }
  },
}

V1 のオブジェクト形式エントリーポイントは OpenCode 1.18.29 以降でサポートされています。それより古い V1 リリースをサポートする場合は、別のパッケージバージョンまたはエントリーポイントを使用し、サポート対象とする最古のリリースでテストしてください。サポート期間が終了したら V1 実装を削除してください。

移植したプラグインの検証

各プラグインについて以下を確認してください。

  1. ID とソースがアクティブなプラグイン一覧に表示されることを確認します。
  2. 登録したすべてのフック、変換、ツール、コマンド、イベントサブスクリプションを実際に動作させます。
  3. プラグインを再読み込みまたは削除して、クリーンアップが正しく行われることを検証します。
  4. クリーンなプロジェクトでプラグインオプションと永続状態をテストします。
  5. 公開パッケージの場合は、ワークスペースリンクされたコピーだけでなくインストール済みパッケージでもテストします。

完全な Promise API についてはサーバー、Effect エントリーポイントについては Effect プラグイン、カスタムメソッドとイベントについてはプラグイン RPC、ターミナル UI については TUI プラグインを参照してください。