RPC de plugins de Effect
Los plugins de Effect pueden exponer métodos y eventos que devuelven Effects y Streams tipados.
Usa Rpc.define con Effect Schema para definir el RPC.
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 valida los valores e infiere sus tipos de TypeScript.
input: Schema.Struct({ query: Schema.String })También se admiten JSON Schema y Standard Schema.
Usa input para el argumento del método y output para su valor de retorno. Ambos son
obligatorios. Si el método no recibe o no devuelve datos, usa Schema.Struct({}) para el valor que falte.
Pasa {} en la llamada o devuelve {}, según corresponda.
search: {
input: Schema.Struct({ query: Schema.String }),
output: Schema.Struct({ text: Schema.String }),
}Agrega los fallos esperados a errors. Cada clave se convierte en el type del error.
errors: {
not_found: Schema.Struct({ query: Schema.String }),
}Agrega eventos al mapa events de nivel superior. Los datos del evento deben ser un objeto.
El mapa es obligatorio. Si el RPC no tiene eventos, usa events: {}.
events: {
updated: {
schema: Schema.Struct({ itemID: Schema.String, text: Schema.String }),
},
}Registra la implementación desde el Effect del plugin:
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),
})El mapa de errores define el tipo de error del Effect de cada método. Usa
context.error(...) para crear un error declarado.
Una vez registrado el RPC, se puede llamar por HTTP o desde otro plugin.
Crea el cliente de Effect y luego crea el subcliente RPC:
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)))Otro plugin de Effect puede crear un subcliente local desde su contexto:
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)Los eventos RPC se reciben mediante Streams. Suscríbete por nombre de evento y ejecuta el Stream en una fibra asociada al ámbito:
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,
)Las suscripciones solo reciben eventos en directo y se cierran cuando dejas de consumir el Stream.