한국어
문서
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 정의는 메서드, 이벤트 및 오류의 입력과 출력 형태를 기술합니다. 두 가지 스키마 형식을 지원합니다.

  • 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으로 추론되므로 사용 전에 타입을 좁혀야(narrow) 합니다. 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)를 통해 호출할 수 있습니다.

두 번째 인수에는 취소를 위한 signal과 선언된 오류를 생성하기 위한 context.error(...)가 포함됩니다. 오류는 반환(return)하거나 throw할 수 있습니다.

하나의 플러그인이 둘 이상의 RPC를 등록할 수 있습니다. 등록을 해제(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)
}

이벤트 구독은 실시간 전용(live only)이므로 연결이 끊긴 구독자는 이벤트를 놓치게 됩니다.

  • updated와 같은 로컬 이름으로 구독합니다.
  • 수신되는 타입에는 rpc.acme.updated처럼 접두사가 붙습니다.
  • 각 이벤트에는 data와 location이 포함됩니다.
  • 플러그인이 언로드되면 해당 구독이 닫힙니다.

외부 클라이언트는 모든 위치의 이벤트를 수신하므로 필요에 따라 event.location을 확인하세요. 서버 플러그인이 설정되어 실행 중이어야 합니다.