日本語
ドキュメント
OpenCode で開発
プラグイン
プラグイン RPC

プラグイン RPC

プラグインのカスタムメソッドやイベントを、他のプラグインやクライアントに公開します。

プラグインはサーバー上で実行されるカスタムメソッドやイベントを公開でき、他のプラグインやクライアントからそれらを呼び出すことができます。

定義

Rpc.define を使用して、RPC のメソッド、エラー、イベントを定義します。

src/rpc.ts
import { Rpc } from "@opencode/plugin/rpc"
 
export const Acme = Rpc.define({
  id: "acme",
  methods: {
    search: {
      input: {
        type: "object",
        properties: { query: { type: "string" } },
        required: ["query"],
        additionalProperties: false,
      },
      output: {
        type: "object",
        properties: { text: { type: "string" } },
        required: ["text"],
        additionalProperties: false,
      },
      errors: {
        not_found: {
          type: "object",
          properties: { query: { type: "string" } },
          required: ["query"],
          additionalProperties: false,
        },
      },
    },
  },
  events: {
    updated: {
      schema: {
        type: "object",
        properties: {
          itemID: { type: "string" },
          text: { type: "string" },
        },
        required: ["itemID", "text"],
        additionalProperties: false,
      },
    },
  },
})

バリデーション

RPC 定義では、メソッド、イベント、エラーの入出力の形状を記述します。以下の 2 つのスキーマ形式に対応しています。

  • JSON Schema(シンプルで追加の依存関係が不要)
  • Standard Schema 準拠の任意のバリデーター
    • Zod
    • Valibot
    • ArkType

入力と出力

各メソッドには、引数用の input スキーマと戻り値用の output スキーマを定義できます。メソッドが値を受け取らない、または返さない場合は、該当するフィールドを省略してください。

search: {
  input: {
    type: "object",
    properties: { query: { type: "string" } },
    required: ["query"],
  },
  output: {
    type: "object",
    properties: { text: { type: "string" } },
    required: ["text"],
  },
}

JSON Schema の値は TypeScript 上では unknown になるため、使用前に型を絞り込んでください。Standard Schema の場合は入力と出力の型が自動的に推論されます。

エラー

想定される失敗についてはメソッドに errors マップを追加します。各キーがエラーの type になり、そのスキーマがエラーの data を定義します。

errors: {
  not_found: {
    type: "object",
    properties: { query: { type: "string" } },
    required: ["query"],
    additionalProperties: false,
  },
}

rpc. で始まるエラー名は OpenCode によって予約されています。

イベント

トップレベルの events マップにイベントを追加します。各イベントには、サブスクライバーへ送信されるデータのスキーマを定義します。

イベントデータはオブジェクトである必要があります。データがない場合は空オブジェクトのスキーマを使用してください。

events: {
  refreshed: {
    schema: { type: "object", additionalProperties: false },
  },
}

スカラー値、配列、null、undefined は有効なイベントデータではありません。

実装

setup 内で実装を登録します。

src/index.ts
import { Plugin } from "@opencode/plugin"
import { Acme } from "./rpc.js"
 
export default Plugin.define({
  id: "acme-plugin",
  async setup(ctx) {
    const registration = await ctx.rpc.register(Acme, {
      search: async (input, context) => {
        const { query } = input as { query: string }
        const text = await findText(query, { signal: context.signal })
        if (!text) return context.error("not_found", "Result not found", { query })
        return { text }
      },
    })
 
    const acme = ctx.rpc(Acme)
    const result = await acme.search({ query: "hello" })
 
    await registration.events.emit("updated", { itemID: "item-1", text: "ready" })
  },
})

RPC を登録した後は、同じプラグイン内からも ctx.rpc(Acme) を通じて呼び出せます。

第 2 引数には、キャンセル用の signal と宣言済みエラー用の context.error(...) が含まれます。エラーは return することも throw することもできます。

1 つのプラグインで複数の RPC を登録できます。登録(registration)を破棄(dispose)すると、その RPC は削除されます。

呼び出し

RPC が登録されると、HTTP 経由または別のプラグインから呼び出せるようになります。

HTTP

OpenCode クライアントを作成し、client.rpc を使って RPC 用のサブクライアントを作成します。

import { OpenCode } from "@opencode/client"
import { Acme } from "opencode-acme-plugin/rpc"
 
const client = OpenCode.make({
  baseUrl: "http://localhost:4096",
})
 
const acme = client.rpc(Acme)
const result = await acme.search({ query: "hello" })

プラグイン

プラグインはすでに OpenCode クライアントを備えています。たとえば、TUI プラグインでは context.client から同じ RPC サブクライアントを作成できます。

src/tui.ts
import { Plugin } from "@opencode/plugin/tui"
import { Acme } from "opencode-acme-plugin/rpc"
 
export default Plugin.define({
  id: "acme-tui",
  async setup(context) {
    const acme = context.client.rpc(Acme)
    const result = await acme.search({ query: "hello" })
    console.log(result)
  },
})

GUI プラグインでは、デスクトップアプリ自身のサーバーに対するクライアントを ctx.client から読み取ります。

src/gui.tsx
import { Command, Plugin } from "@opencode/plugin/gui"
import { Acme } from "opencode-acme-plugin/rpc"
 
export default Plugin.define({
  setup(ctx) {
    ctx.add(Command, {
      id: "search",
      title: "Search Acme",
      run: async () => {
        const result = await ctx.client.rpc(Acme).search({ query: "hello" })
        console.log(result)
      },
    })
  },
})

ctx.client はサーバー再起動後に変更されるため、呼び出す箇所で毎回読み取ってください。サーバーに到達できない間はすべての呼び出しが reject されます。

サブスクライブ

コールバック形式には events.on を使用し、リスナーが不要になったらアンサブスクライブします。

const unsubscribe = acme.events.on("updated", (event) => {
  console.log(event.type, event.location.directory, event.data.text)
})
 
unsubscribe()

非同期イテラブルとして扱う場合は events.subscribe("updated") を使用します。

for await (const event of acme.events.subscribe("updated")) {
  console.log(event.data.text)
}

イベントサブスクリプションはライブ専用のため、切断中のサブスクライバーはイベントを取りこぼします。

  • updated のようなローカル名でサブスクライブします。
  • 受信される型には rpc.acme.updated のようにプレフィックスが付きます。
  • 各イベントには data と location が含まれます。
  • プラグインがアンロードされると、そのサブスクリプションは閉じられます。

外部クライアントはすべてのロケーションからイベントを受信するため、必要に応じて event.location を確認してください。なお、サーバープラグインが設定され稼働している必要があります。