# Effect 外掛 RPC

Effect 外掛可以公開傳回具型別 Effect 與 Stream 的方法與事件。

## 定義

使用 `Rpc.define` 搭配 Effect Schema 定義 RPC。

```ts title="src/rpc.ts"
import { Rpc } from "@opencode/plugin/rpc"
import { Schema } from "effect"

export const Acme = Rpc.define({
  id: "acme",
  methods: {
    search: {
      input: Schema.Struct({ query: Schema.String }),
      output: Schema.Struct({ text: Schema.String }),
      errors: {
        not_found: Schema.Struct({ query: Schema.String }),
      },
    },
  },
  events: {
    updated: {
      schema: Schema.Struct({ itemID: Schema.String, text: Schema.String }),
    },
  },
})
```

### 驗證

Effect Schema 會驗證值並推斷其 TypeScript 型別。

```ts
input: Schema.Struct({ query: Schema.String })
```

也支援 JSON Schema 與 Standard Schema。

### 輸入與輸出

方法引數使用 `input`，回傳值使用 `output`，兩者都必填。若方法不接收引數或不回傳值，請在對應欄位使用 `Schema.Struct({})`。沒有引數時傳入 `{}`，沒有回傳值時則回傳 `{}`。

```ts
search: {
  input: Schema.Struct({ query: Schema.String }),
  output: Schema.Struct({ text: Schema.String }),
}
```

### 錯誤

將預期的失敗加入 `errors`。每個鍵會成為錯誤的 `type`。

```ts
errors: {
  not_found: Schema.Struct({ query: Schema.String }),
}
```

### 事件

將事件加入頂層 `events` 對照表。事件資料必須是物件。這個對照表是必填的；若 RPC 沒有事件，請使用 `events: {}`。

```ts
events: {
  updated: {
    schema: Schema.Struct({ itemID: Schema.String, text: Schema.String }),
  },
}
```

## 實作

從外掛的 Effect 註冊實作：

```ts title="src/index.ts"
import { Plugin } from "@opencode/plugin/effect"
import { Effect } from "effect"
import { Acme } from "./rpc.js"

export default Plugin.define({
  id: "acme-effect-plugin",
  effect: (ctx) =>
    Effect.gen(function* () {
      const registration = yield* ctx.rpc.register(Acme, {
        search: ({ query }, context) =>
          findText(query).pipe(
            Effect.flatMap((text) =>
              text
                ? Effect.succeed({ text })
                : Effect.fail(context.error("not_found", "Result not found", { query })),
            ),
          ),
      })

      const acme = ctx.rpc(Acme)
      const result = yield* acme.search({ query: "hello" })

      yield* registration.events.emit("updated", { itemID: "item-1", text: result.text })
    }).pipe(Effect.orDie),
})
```

錯誤對照表會成為每個方法 Effect 的錯誤型別。使用
`context.error(...)` 建立宣告的錯誤。

## 呼叫

RPC 註冊後，即可透過 HTTP 或從另一個外掛呼叫。

### HTTP

建立 Effect 用戶端，然後建立 RPC 子用戶端：

```ts
import { OpenCode } from "@opencode/client/effect"
import { Effect } from "effect"
import { FetchHttpClient } from "effect/http"
import { Acme } from "opencode-acme-plugin/rpc"

const program = Effect.gen(function* () {
  const client = yield* OpenCode.make({ baseUrl: "http://localhost:4096" })
  const acme = client.rpc(Acme)
  return yield* acme.search({ query: "hello" })
})

const result = await Effect.runPromise(program.pipe(Effect.provide(FetchHttpClient.layer)))
```

### 外掛

另一個 Effect 外掛可以從其上下文建立本機子用戶端：

```ts
import { Effect } from "effect"

effect: (ctx) =>
  Effect.gen(function* () {
    const acme = ctx.rpc(Acme)
    const result = yield* acme.search({ query: "hello" })
    yield* Effect.logInfo(result.text)
  }).pipe(Effect.orDie)
```

### 訂閱

RPC 事件以 Stream 提供。依事件名稱訂閱，並在由 Scope 管理的 fiber 中執行 Stream：

{/* prettier-ignore */}
```ts
import { Effect, Stream } from "effect"

const acme = ctx.rpc(Acme)

yield* acme.events.subscribe("updated").pipe(
  Stream.runForEach((event) => Effect.logInfo(event.data.text)),
  Effect.forkScoped,
)
```

訂閱只接收即時事件，停止取用 Stream 時便會關閉。