fix(plugin): support optional RPC method schemas and events

This commit is contained in:
Filip Hejmowski 2026-10-29 15:21:03 +01:00
parent d9d3548548
commit 20543c63ea
13 changed files with 547 additions and 51 deletions

View file

@ -18,16 +18,16 @@ export type RpcClient<
EventError = E,
> = {
readonly [Name in keyof D["methods"]]: (
...args: RpcArguments<Rpc.Input<D["methods"][Name]["input"]>, Options>
...args: RpcArguments<Rpc.MethodInput<D["methods"][Name]>, Options>
) => Effect.Effect<
Rpc.Output<D["methods"][Name]["output"]>,
Rpc.MethodError<D["methods"][Name]> | DecodeError<D["methods"][Name]["output"]> | E
Rpc.MethodOutput<D["methods"][Name]>,
Rpc.MethodError<D["methods"][Name]> | DecodeError<Rpc.OutputSchema<D["methods"][Name]>> | E
>
} & {
readonly events: {
readonly subscribe: <Name extends keyof D["events"] & string>(
readonly subscribe: <Name extends Rpc.EventName<D>>(
name: Name,
) => Stream.Stream<Rpc.EventPayload<D, Name>, DecodeError<D["events"][Name]["schema"]> | EventError>
) => Stream.Stream<Rpc.EventPayload<D, Name>, DecodeError<Rpc.EventSchema<D, Name>> | EventError>
}
}
@ -70,9 +70,10 @@ export function make<CallError, EventError>(
// oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion
return Object.assign(methods, {
events: {
subscribe: (name: keyof D["events"] & string) => {
subscribe: (name: Rpc.EventName<D>) => {
const type = RpcRuntime.eventType(definition, name)
if (!Object.hasOwn(definition.events, name)) return Stream.fail(new Error(`Unknown RPC event: ${type}`))
if (!definition.events || !Object.hasOwn(definition.events, name))
return Stream.fail(new Error(`Unknown RPC event: ${type}`))
const schema = definition.events[name]
return subscribe().pipe(
Stream.filter((event): event is RpcEvent => event.type === type),

View file

@ -17,15 +17,15 @@ export type RpcArguments<Input, Options> = unknown extends Input
export type RpcClient<D extends Rpc.PortableDefinition, Options = RpcCallOptions> = {
readonly [Name in keyof D["methods"]]: (
...args: RpcArguments<Rpc.Input<D["methods"][Name]["input"]>, Options>
) => Promise<Rpc.Output<D["methods"][Name]["output"]>>
...args: RpcArguments<Rpc.MethodInput<D["methods"][Name]>, Options>
) => Promise<Rpc.MethodOutput<D["methods"][Name]>>
} & {
readonly events: {
readonly subscribe: <Name extends keyof D["events"] & string>(
readonly subscribe: <Name extends Rpc.EventName<D>>(
name: Name,
options?: Pick<RequestOptions, "signal">,
) => AsyncIterable<RpcEventPayload<D, Name>>
readonly on: <Name extends keyof D["events"] & string>(
readonly on: <Name extends Rpc.EventName<D>>(
name: Name,
handler: (event: RpcEventPayload<D, Name>) => Promise<void> | void,
options?: Pick<RequestOptions, "signal">,
@ -35,15 +35,15 @@ export type RpcClient<D extends Rpc.PortableDefinition, Options = RpcCallOptions
type RpcEventPayloadFor<
D extends Rpc.PortableDefinition,
Name extends keyof D["events"] & string,
Name extends Rpc.EventName<D>,
> = Omit<RpcEvent, "type" | "data"> & {
type: `rpc.${D["id"]}.${Name}`
data: Rpc.EventData<D["events"][Name]["schema"]>
data: Rpc.EventData<Rpc.EventSchema<D, Name>>
}
export type RpcEventPayload<
D extends Rpc.PortableDefinition,
Name extends keyof D["events"] & string = keyof D["events"] & string,
Name extends Rpc.EventName<D> = Rpc.EventName<D>,
> = { [K in Name]: RpcEventPayloadFor<D, K> }[Name]
export interface RpcApi<Options = RpcCallOptions> {
@ -59,7 +59,8 @@ export function makeRpc(
name: string,
options?: Pick<RequestOptions, "signal">,
): AsyncIterable<RpcEventPayload<Rpc.PortableDefinition>> => {
if (!Object.hasOwn(definition.events, name)) throw new Error(`Unknown RPC event: ${definition.id}.${name}`)
if (!definition.events || !Object.hasOwn(definition.events, name))
throw new Error(`Unknown RPC event: ${definition.id}.${name}`)
const type = eventType(definition, name)
return {
[Symbol.asyncIterator]() {

View file

@ -9,7 +9,9 @@ type RpcEvent = Extract<OpenCodeEvent, { type: `rpc.${string}` }>
export function read(schema: Rpc.Method["output"], value: unknown) {
// Standard Schema results have already been parsed by the server.
return Schema.isSchema(schema) ? Schema.decodeUnknownEffect(schema)(value) : Effect.succeed(value)
return schema !== undefined && Schema.isSchema(schema)
? Schema.decodeUnknownEffect(schema)(value)
: Effect.succeed(value)
}
export function readError(method: Rpc.Method, error: unknown): Effect.Effect<never, unknown> {
@ -35,7 +37,7 @@ export function readError(method: Rpc.Method, error: unknown): Effect.Effect<nev
export const event = Effect.fn("Client.Rpc.event")(function* <
D extends Rpc.Definition,
Name extends keyof D["events"] & string,
Name extends Rpc.EventName<D>,
>(
definition: D,
name: Name,
@ -52,7 +54,7 @@ export const event = Effect.fn("Client.Rpc.event")(function* <
} as Rpc.EventPayload<D, Name>
})
export function eventType<const D extends Rpc.Definition, const Name extends keyof D["events"] & string>(
export function eventType<const D extends Rpc.Definition, const Name extends Rpc.EventName<D>>(
definition: D,
name: Name,
): `rpc.${D["id"]}.${Name}` {

View file

@ -1,5 +1,6 @@
import { Effect } from "effect"
import { Effect, Schema } from "effect"
import { OpenCode as EffectOpenCode, type AppApi as EffectApi } from "../src/effect"
import { Rpc } from "@opencode/schema/rpc"
import type { Session } from "@opencode/schema/session"
import type { DiscoverOptions } from "../src/service"
@ -46,6 +47,28 @@ const promiseRemove: Promise<void> = promiseClient.experimental.session.instruct
key: "review-notes",
})
const OneSidedRpc = Rpc.define({
id: "one-sided",
methods: {
status: { output: Schema.toStandardSchemaV1(Schema.Struct({ ok: Schema.Boolean })) },
reset: {},
},
})
const effectRpcStatus: Effect.Effect<{ readonly ok: boolean }, unknown> = effectClient.rpc(OneSidedRpc).status()
const effectRpcReset: Effect.Effect<void, unknown> = effectClient.rpc(OneSidedRpc).reset()
const promiseRpcStatus: Promise<{ readonly ok: boolean }> = promiseClient.rpc(OneSidedRpc).status()
const promiseRpcReset: Promise<void> = promiseClient.rpc(OneSidedRpc).reset()
// @ts-expect-error Input-less RPC methods reject arguments on Effect clients.
effectClient.rpc(OneSidedRpc).status({})
// @ts-expect-error Input-less RPC methods reject arguments on Promise clients.
void promiseClient.rpc(OneSidedRpc).status({})
// @ts-expect-error RPC definitions without events reject subscriptions.
effectClient.rpc(OneSidedRpc).events.subscribe("updated")
// @ts-expect-error RPC definitions without events reject listeners.
promiseClient.rpc(OneSidedRpc).events.on("updated", () => {})
void [
effectSession,
effectList,
@ -54,6 +77,10 @@ void [
promiseList,
promisePut,
promiseRemove,
effectRpcStatus,
effectRpcReset,
promiseRpcStatus,
promiseRpcReset,
exactVersion,
compatibleVersion,
]

View file

@ -57,7 +57,7 @@ const layer = Layer.effect(
const existing = definitions.get(definition)
if (existing) return existing
const events = new Map(
Object.entries(definition.events).map(([name, event]) => [
Object.entries(definition.events ?? {}).map(([name, event]) => [
name,
{ event, definition: eventDefinition(eventType(definition, name)) },
]),
@ -114,7 +114,8 @@ const layer = Layer.effect(
return yield* Effect.fail(failure("rpc.method_not_found", `Unknown RPC method: ${rpcID}.${name}`))
const method = entry.definition.methods[name]
const handler = entry.handlers[name]
const parsed = yield* parse(method.input, input).pipe(
// Omitted input/output schemas mean the method accepts or returns no value.
const parsed = yield* parse(method.input === undefined ? Schema.Undefined : method.input, input).pipe(
Effect.mapError((error) => failure("rpc.invalid_input", errorMessage(error, "Invalid RPC input"))),
)
const result = yield* Effect.suspend(() => {
@ -136,7 +137,7 @@ const layer = Layer.effect(
),
),
)
return yield* encode(method.output, result).pipe(
return yield* encode(method.output === undefined ? Schema.Void : method.output, result).pipe(
Effect.mapError((error) => failure("rpc.invalid_output", errorMessage(error, "Invalid RPC output"))),
)
})
@ -158,7 +159,7 @@ const layer = Layer.effect(
return {
...methods,
events: {
subscribe: <Name extends keyof D["events"] & string>(name: Name) => {
subscribe: <Name extends Rpc.EventName<D>>(name: Name) => {
const registered = events.get(name)
if (!registered) return Stream.fail(new Error(`Unknown RPC event: ${definition.id}.${name}`))
return bus.subscribe(registered.definition).pipe(
@ -185,7 +186,7 @@ const fields = {
const EventData = Schema.Record(Schema.String, Schema.Unknown)
const jsonSchemas = new WeakMap<JsonSchema.JsonSchema, Schema.Codec<unknown>>()
function eventType<const D extends Rpc.Definition, const Name extends keyof D["events"] & string>(
function eventType<const D extends Rpc.Definition, const Name extends Rpc.EventName<D>>(
definition: D,
name: Name,
): `rpc.${D["id"]}.${Name}` {
@ -258,24 +259,27 @@ function errorMessage(error: unknown, fallback: string) {
}
function isStandardSchema(schema: Tool.ValueSchema): schema is Extract<Tool.ValueSchema, StandardSchemaV1> {
return "~standard" in schema
return typeof schema === "object" && schema !== null && "~standard" in schema
}
function read(schema: Tool.ValueSchema, value: unknown): Effect.Effect<unknown, unknown> {
function read(schema: Tool.ValueSchema | undefined, value: unknown): Effect.Effect<unknown, unknown> {
// Standard Schema results were already parsed by the publisher; don't apply transforms twice.
return Schema.isSchema(schema) ? Schema.decodeUnknownEffect(schema)(value) : Effect.succeed(value)
return schema !== undefined && Schema.isSchema(schema)
? Schema.decodeUnknownEffect(schema)(value)
: Effect.succeed(value)
}
const logicalEvent = Effect.fn("Rpc.logicalEvent")(function* <
D extends Rpc.Definition,
Name extends keyof D["events"] & string,
Name extends Rpc.EventName<D>,
>(
definition: D,
name: Name,
payload: Event.Payload,
ref: Location.Ref,
): Effect.fn.Return<Rpc.EventPayload<D, Name>, unknown> {
const event = definition.events[name]
const event = definition.events?.[name]
if (!event) return yield* Effect.fail(new Error(`Unknown RPC event: ${definition.id}.${name}`))
const data = yield* read(event.schema, payload.data)
// SAFETY: The private Bus definition owns the envelope and location.
// oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion

View file

@ -0,0 +1,185 @@
import { expect } from "bun:test"
import { AppNodeBuilder } from "@opencode/core/effect/app-node-builder"
import { Location } from "@opencode/core/location"
import { Rpc } from "@opencode/core/rpc"
import { AbsolutePath } from "@opencode/core/schema"
import { Plugin } from "@opencode/plugin"
import { fromPromise } from "@opencode/plugin/promise/adapter"
import { Effect, Layer, Schema } from "effect"
import { location } from "./fixture/location"
import { testEffect } from "./lib/effect"
import { host } from "./plugin/host"
const it = testEffect(
AppNodeBuilder.build(Rpc.node, [
Location.node.replace(Layer.succeed(Location.Service, location({ directory: AbsolutePath.make("/rpc-project") }))),
]),
)
const EffectOneSided = Rpc.define({
id: "effect-one-sided",
methods: {
status: { output: Schema.Struct({ ok: Schema.Boolean }) },
notify: { input: Schema.Struct({ text: Schema.String }) },
reset: {},
},
})
const PortableOneSided = Rpc.define({
id: "portable-one-sided",
methods: {
status: {
output: {
type: "object",
properties: { ok: { type: "boolean" }, items: { type: "number" } },
required: ["ok", "items"],
additionalProperties: false,
},
},
notify: {
input: {
type: "object",
properties: { text: { type: "string" } },
required: ["text"],
additionalProperties: false,
},
},
reset: {},
},
})
it.effect("calls Effect RPC methods that omit input, output, or events", () =>
Effect.gen(function* () {
const rpc = yield* Rpc.Service
const seen: string[] = []
const receivedInputs: unknown[] = []
const registration = yield* rpc.register(EffectOneSided, {
status: (input) => {
receivedInputs.push(input)
return Effect.succeed({ ok: true })
},
notify: (input) => {
seen.push(input.text)
return Effect.void
},
reset: () => {
seen.length = 0
return Effect.void
},
})
const client = rpc.client(EffectOneSided)
expect(yield* client.status()).toEqual({ ok: true })
expect(receivedInputs).toEqual([undefined])
expect(yield* client.notify({ text: "hello" })).toBeUndefined()
expect(seen).toEqual(["hello"])
expect(yield* client.reset()).toBeUndefined()
expect(seen).toEqual([])
if (false) {
// @ts-expect-error Methods without an input schema reject arguments.
void client.status({ unexpected: true })
// @ts-expect-error Definitions without events reject event emission.
void registration.events.emit("updated", {})
// @ts-expect-error Definitions without events reject event subscriptions.
void client.events.subscribe("updated")
}
}),
)
it.effect("rejects unexpected input on input-less methods and discards stray output on output-less methods", () =>
Effect.gen(function* () {
const rpc = yield* Rpc.Service
yield* rpc.register(EffectOneSided, {
status: () => Effect.succeed({ ok: true }),
// Effect<A> is covariant and assignable to Effect<void>; Schema.Void discards the value so it never leaks.
notify: () => Effect.succeed({ leaked: "internal" }),
reset: () => Effect.void,
})
const badInput = yield* rpc.call("effect-one-sided", "status", { unexpected: 1 }).pipe(Effect.flip)
expect(badInput.type).toBe("rpc.invalid_input")
expect(yield* rpc.call("effect-one-sided", "notify", { text: "hi" })).toBeUndefined()
}),
)
it.effect("maps malformed non-object schemas from untyped JS plugins to rpc.invalid_input instead of throwing", () =>
Effect.gen(function* () {
const rpc = yield* Rpc.Service
const malformed = Rpc.define({
id: "malformed",
methods: {
bad: {
// @ts-expect-error Intentionally pass a non-object schema as an untyped JS plugin would.
input: 123,
output: { type: "object" },
},
},
})
yield* rpc.register(malformed, {
bad: () => Effect.succeed({}),
})
const result = yield* rpc.call("malformed", "bad", {}).pipe(Effect.flip)
expect(result.type).toBe("rpc.invalid_input")
}),
)
it.effect("supports Promise plugins registering and calling JSON Schema RPCs without input, output, or events", () =>
Effect.gen(function* () {
const rpc = yield* Rpc.Service
const pluginHost = host({ rpc: Object.assign(rpc.client, { register: rpc.register }) })
const items: string[] = []
let statusSnapshot: unknown
const TextInput = Schema.Struct({ text: Schema.String })
const plugin = fromPromise(
Plugin.define({
id: "portable-one-sided-plugin",
async setup(ctx) {
const registration = await ctx.rpc.register(PortableOneSided, {
status: async () => ({ ok: true, items: items.length }),
notify: async (input) => {
const payload = Schema.decodeUnknownSync(TextInput)(input)
items.push(payload.text)
},
reset: async () => {
items.length = 0
},
})
const local = ctx.rpc(PortableOneSided)
await local.notify({ text: "first" })
statusSnapshot = await local.status()
await local.reset()
if (false) {
// @ts-expect-error Input-less methods do not accept dummy {} arguments.
await local.status({})
// @ts-expect-error Definitions without events cannot emit events.
await registration.events.emit("updated", {})
// @ts-expect-error Definitions without events cannot subscribe to events.
local.events.on("updated", () => {})
await ctx.rpc.register(PortableOneSided, {
status: async () => ({ ok: true, items: 0 }),
notify: async () => {},
// @ts-expect-error Output-less Promise handlers must return void.
reset: async () => ({ leaked: true }),
})
}
},
}),
)
yield* plugin.effect(pluginHost)
expect(statusSnapshot).toEqual({ ok: true, items: 1 })
expect(items).toEqual([])
expect(yield* rpc.call("portable-one-sided", "status", undefined)).toEqual({ ok: true, items: 0 })
}),
)

View file

@ -10,9 +10,9 @@ export interface RpcCallContext<M extends Rpc.Method> {
export type RpcHandlers<D extends Rpc.Definition> = {
readonly [Name in keyof D["methods"]]: (
input: Rpc.Output<D["methods"][Name]["input"]>,
input: Rpc.HandlerInput<D["methods"][Name]>,
context: RpcCallContext<D["methods"][Name]>,
) => Effect.Effect<Rpc.HandlerOutput<D["methods"][Name]["output"]>, Rpc.HandlerError<D["methods"][Name]>>
) => Effect.Effect<Rpc.MethodHandlerOutput<D["methods"][Name]>, Rpc.HandlerError<D["methods"][Name]>>
}
export interface RpcRegistration<D extends Rpc.Definition> extends Registration {

View file

@ -11,9 +11,9 @@ export interface RpcCallContext<M extends Rpc.Method> {
export type RpcHandlers<D extends Rpc.PortableDefinition> = {
readonly [Name in keyof D["methods"]]: (
input: Rpc.Output<D["methods"][Name]["input"]>,
input: Rpc.HandlerInput<D["methods"][Name]>,
context: RpcCallContext<D["methods"][Name]>,
) => Promise<Rpc.HandlerOutput<D["methods"][Name]["output"]> | Rpc.HandlerError<D["methods"][Name]>>
) => Promise<Rpc.MethodHandlerOutput<D["methods"][Name]> | Rpc.HandlerError<D["methods"][Name]>>
}
export interface RpcRegistration<D extends Rpc.PortableDefinition> extends Registration {

View file

@ -11,16 +11,16 @@ export type ErrorMap = Readonly<Record<string, Tool.ValueSchema>> & {
}
export interface Method {
readonly input: Tool.ValueSchema
readonly output: Tool.ValueSchema
readonly input?: Tool.ValueSchema
readonly output?: Tool.ValueSchema
readonly errors?: ErrorMap
}
export type PortableValueSchema = StandardSchemaV1<unknown, unknown> | JsonSchema.JsonSchema
export interface PortableMethod extends Method {
readonly input: PortableValueSchema
readonly output: PortableValueSchema
readonly input?: PortableValueSchema
readonly output?: PortableValueSchema
readonly errors?: Readonly<Record<string, PortableValueSchema>> & {
readonly [Name in `rpc.${string}`]?: never
}
@ -43,12 +43,12 @@ export type PortableEventDefinition = EventDefinition & { readonly schema: Porta
export interface Definition {
readonly id: string
readonly methods: Readonly<Record<string, Method>> & { readonly events?: never }
readonly events: Readonly<Record<string, EventDefinition>>
readonly events?: Readonly<Record<string, EventDefinition>>
}
export interface PortableDefinition extends Definition {
readonly methods: Readonly<Record<string, PortableMethod>> & { readonly events?: never }
readonly events: Readonly<Record<string, PortableEventDefinition>>
readonly events?: Readonly<Record<string, PortableEventDefinition>>
}
export function define<const D extends Definition>(definition: D) {
@ -74,6 +74,24 @@ export type Output<S extends Tool.ValueSchema> = S extends Schema.Top
// Effect codecs encode handler results; Standard Schema parses them forward.
export type HandlerOutput<S extends Tool.ValueSchema> = S extends Schema.Top ? Output<S> : Input<S>
type PresentProperty<T, K extends PropertyKey> = K extends keyof T ? Exclude<T[K], undefined> : never
export type InputSchema<M extends Method> = Extract<PresentProperty<M, "input">, Tool.ValueSchema>
export type OutputSchema<M extends Method> = Extract<PresentProperty<M, "output">, Tool.ValueSchema>
export type MethodInput<M extends Method> = [InputSchema<M>] extends [never] ? undefined : Input<InputSchema<M>>
export type HandlerInput<M extends Method> = [InputSchema<M>] extends [never] ? undefined : Output<InputSchema<M>>
export type MethodOutput<M extends Method> = [OutputSchema<M>] extends [never] ? void : Output<OutputSchema<M>>
export type MethodHandlerOutput<M extends Method> = [OutputSchema<M>] extends [never]
? void
: HandlerOutput<OutputSchema<M>>
export type Events<D extends Definition> = Extract<
PresentProperty<D, "events">,
Readonly<Record<string, EventDefinition>>
>
export type EventName<D extends Definition> = [Events<D>] extends [never] ? never : keyof Events<D> & string
export type EventSchema<D extends Definition, Name extends EventName<D>> = Events<D>[Name]["schema"]
type MethodErrors<M extends Method> = M extends {
readonly errors: infer Errors extends ErrorMap
}
@ -150,18 +168,18 @@ export type EventData<S extends EventValueSchema> = S extends JsonSchema.JsonSch
// Keep the event name correlated with its payload even when callers use unions.
export type EventInput<D extends Definition> = {
[Name in keyof D["events"] & string]: [name: Name, data: EventInputData<D["events"][Name]["schema"]>]
}[keyof D["events"] & string]
[Name in EventName<D>]: [name: Name, data: EventInputData<EventSchema<D, Name>>]
}[EventName<D>]
type EventPayloadFor<
D extends Definition,
Name extends keyof D["events"] & string,
Name extends EventName<D>,
> = Omit<Event.Payload<Event.EphemeralDefinition>, "type" | "data" | "durable" | "location"> & {
readonly type: `rpc.${D["id"]}.${Name}`
readonly data: EventData<D["events"][Name]["schema"]>
readonly data: EventData<EventSchema<D, Name>>
readonly location: Location.Ref
}
export type EventPayload<D extends Definition, Name extends keyof D["events"] & string = keyof D["events"] & string> = {
export type EventPayload<D extends Definition, Name extends EventName<D> = EventName<D>> = {
readonly [K in Name]: EventPayloadFor<D, K>
}[Name]

View file

@ -0,0 +1,81 @@
import { describe, expect, test } from "bun:test"
import { Schema } from "effect"
import type { Types } from "effect"
import { Rpc } from "../src/rpc.js"
type Assert<T extends true> = T
describe("Rpc.define", () => {
test("accepts methods that omit input, output, or both, and definitions that omit events", () => {
const Dragon = Rpc.define({
id: "dragon",
methods: {
vibrate: {},
status: {
output: Schema.toStandardSchemaV1(Schema.Struct({ ok: Schema.Boolean })),
},
notify: {
input: Schema.toStandardSchemaV1(Schema.Struct({ text: Schema.String })),
},
rawStatus: {
output: { type: "object", properties: { ok: { type: "boolean" } }, required: ["ok"] },
},
},
})
expect(Dragon.id).toBe("dragon")
expect(Object.keys(Dragon.methods)).toEqual(["vibrate", "status", "notify", "rawStatus"])
type Checks = [
Assert<Types.Equals<Rpc.MethodInput<typeof Dragon.methods.vibrate>, undefined>>,
Assert<Types.Equals<Rpc.HandlerInput<typeof Dragon.methods.vibrate>, undefined>>,
Assert<Types.Equals<Rpc.MethodOutput<typeof Dragon.methods.vibrate>, void>>,
Assert<Types.Equals<Rpc.MethodHandlerOutput<typeof Dragon.methods.vibrate>, void>>,
Assert<Types.Equals<Rpc.MethodInput<typeof Dragon.methods.status>, undefined>>,
Assert<Types.Equals<Rpc.HandlerInput<typeof Dragon.methods.status>, undefined>>,
Assert<Types.Equals<Rpc.MethodOutput<typeof Dragon.methods.status>, { readonly ok: boolean }>>,
Assert<Types.Equals<Rpc.MethodHandlerOutput<typeof Dragon.methods.status>, { readonly ok: boolean }>>,
Assert<Types.Equals<Rpc.MethodInput<typeof Dragon.methods.notify>, { readonly text: string }>>,
Assert<Types.Equals<Rpc.HandlerInput<typeof Dragon.methods.notify>, { readonly text: string }>>,
Assert<Types.Equals<Rpc.MethodOutput<typeof Dragon.methods.notify>, void>>,
Assert<Types.Equals<Rpc.MethodHandlerOutput<typeof Dragon.methods.notify>, void>>,
Assert<Types.Equals<Rpc.MethodInput<typeof Dragon.methods.rawStatus>, undefined>>,
Assert<Types.Equals<Rpc.MethodOutput<typeof Dragon.methods.rawStatus>, unknown>>,
Assert<Types.Equals<Rpc.EventName<typeof Dragon>, never>>,
Assert<Types.Equals<Rpc.EventInput<typeof Dragon>, never>>,
]
const checks: Checks = [
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
true,
]
expect(checks).toHaveLength(16)
})
test("still rejects reserved rpc.* error names on methods without input or output", () => {
expect(() =>
Rpc.define({
id: "dragon",
methods: {
vibrate: {
// @ts-expect-error Error names starting with rpc. are reserved.
errors: { "rpc.internal": { type: "object" } },
},
},
}),
).toThrow('RPC error names starting with "rpc." are reserved: rpc.internal')
})
})

View file

@ -0,0 +1,153 @@
import { expect } from "bun:test"
import { OpenCode } from "@opencode/client"
import { SdkPlugins } from "@opencode/core/plugin/sdk"
import { Plugin } from "@opencode/plugin"
import { fromPromise } from "@opencode/plugin/promise/adapter"
import { Rpc } from "@opencode/plugin/rpc"
import { Context, Effect, Layer, Schema } from "effect"
import { HttpClient, HttpClientResponse, HttpEffect, HttpRouter, HttpServer } from "effect/http"
import { tmpdirScoped } from "../../core/test/fixture/tmpdir"
import { it } from "../../core/test/lib/effect"
import { createEmbeddedRoutes } from "../src/routes"
const Vibeguard = Rpc.define({
id: "vibeguard",
methods: {
status: {
output: {
type: "object",
properties: { ok: { type: "boolean" }, count: { type: "number" } },
required: ["ok", "count"],
additionalProperties: false,
},
},
notify: {
input: {
type: "object",
properties: { text: { type: "string" } },
required: ["text"],
additionalProperties: false,
},
},
reset: {},
},
})
it.live("dispatches HTTP and SDK RPC calls for methods without input, output, or events", () =>
Effect.gen(function* () {
const directory = yield* tmpdirScoped()
const context = yield* Layer.build(
createEmbeddedRoutes({
database: { path: ":memory:" },
models: { fetch: false },
config: { directory: directory.path, project: false, content: "{}" },
fs: { filewatcher: false },
}).pipe(Layer.provide(HttpServer.layerServices)),
)
const messages: string[] = []
const sdk = Context.get(context, SdkPlugins.Service)
yield* sdk.register(
fromPromise(
Plugin.define({
id: "vibeguard-plugin",
async setup(ctx) {
await ctx.rpc.register(Vibeguard, {
status: async () => ({ ok: true, count: messages.length }),
notify: async (input) => {
const payload = Schema.decodeUnknownSync(Schema.Struct({ text: Schema.String }))(input)
messages.push(payload.text)
},
reset: async () => {
messages.length = 0
},
})
},
}),
),
)
const webHandler = Context.get(context, HttpRouter.HttpRouter)
.asHttpEffect()
.pipe(HttpEffect.toWebHandlerWith(context))
const post = (method: string, body: unknown) => {
const url = new URL(`/api/rpc/vibeguard/${method}`, "http://opencode.local")
url.searchParams.set("location[directory]", directory.path)
return Effect.promise(async () => {
const response = await webHandler(
new Request(url, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(body),
}),
)
return { status: response.status, json: await response.json() }
})
}
// Exact #59755 HTTP reproduction: `{}` omits `input` on an output-only method.
expect(yield* post("status", {})).toEqual({
status: 200,
json: { output: { ok: true, count: 0 } },
})
// Non-undefined input on an input-less method is rejected as 400 rpc.invalid_input.
const invalidInput = yield* post("status", { input: {} })
expect(invalidInput.status).toBe(400)
expect(invalidInput.json).toMatchObject({ _tag: "RpcError", type: "rpc.invalid_input" })
// Output-less methods omit `output` in the HTTP response body (`{}`).
expect(yield* post("notify", { input: { text: "alpha" } })).toEqual({
status: 200,
json: {},
})
// Promise SDK client calls zero-arg and void methods directly.
const promiseClient = OpenCode.make({
baseUrl: "http://opencode.local",
fetch: Object.assign(
(input: RequestInfo | URL, init?: RequestInit) => webHandler(new Request(input, init)),
{ preconnect: globalThis.fetch.preconnect },
),
})
const promiseRpc = promiseClient.rpc(Vibeguard)
expect(yield* Effect.promise(() => promiseRpc.status(undefined, { location: { directory: directory.path } }))).toEqual({
ok: true,
count: 1,
})
expect(
yield* Effect.promise(() => promiseRpc.notify({ text: "beta" }, { location: { directory: directory.path } })),
).toBeUndefined()
expect(yield* Effect.promise(() => promiseRpc.status())).toEqual({ ok: true, count: 2 })
expect(yield* Effect.promise(() => promiseRpc.reset())).toBeUndefined()
// Effect SDK client calls the same contract directly.
const httpClient = HttpClient.make((request) =>
Effect.promise(async () => {
const body =
request.body._tag === "Uint8Array"
? Buffer.from(request.body.body)
: request.body._tag === "Raw"
? String(request.body.body)
: undefined
const response = await webHandler(
new Request(request.url, {
method: request.method,
headers: request.headers,
body,
}),
)
return HttpClientResponse.fromWeb(request, response)
}),
)
const effectSdk = yield* Effect.promise(() => import("@opencode/client/effect"))
const effectClient = yield* effectSdk.OpenCode.make({
baseUrl: "http://opencode.local",
}).pipe(Effect.provideService(HttpClient.HttpClient, httpClient))
const effectRpc = effectClient.rpc(Vibeguard)
expect(yield* effectRpc.notify({ text: "gamma" })).toBeUndefined()
expect(yield* effectRpc.status()).toEqual({ ok: true, count: 1 })
expect(yield* effectRpc.reset()).toBeUndefined()
expect(yield* effectRpc.status()).toEqual({ ok: true, count: 0 })
}),
)

View file

@ -45,8 +45,7 @@ JSON Schema and Standard Schema are also supported.
### Input and output
Use `input` for the method argument and `output` for its return value. Leave
either one out when there is no value.
Use `input` for the method argument and `output` for its return value.
```ts
search: {
@ -55,6 +54,16 @@ search: {
}
```
Leave either schema out when there is no value. Callers omit the argument when
`input` is absent, and handlers return `Effect.void` when `output` is absent:
```ts
status: {
output: Schema.Struct({ ok: Schema.Boolean }),
},
reset: {},
```
### Errors
Add expected failures to `errors`. Each key becomes the error's `type`.
@ -67,7 +76,8 @@ errors: {
### Events
Add events to the top-level `events` map. Event data must be an object.
Add events to the top-level `events` map, or omit `events` when the RPC only
defines methods. Event data must be an object.
```ts
events: {

View file

@ -69,8 +69,7 @@ and errors. It supports two schema formats:
### Input and output
Each method can define an `input` schema for its argument and an `output` schema
for its return value. Leave either one out if the method does not accept or
return a value.
for its return value.
```ts
search: {
@ -90,6 +89,21 @@ search: {
JSON Schema values are `unknown` in TypeScript, so narrow them before use.
Standard Schema infers the input and output types.
Leave either schema out when the method takes or returns no value. Callers omit
the argument when `input` is absent, and handlers return nothing when `output`
is absent:
```ts
status: {
output: {
type: "object",
properties: { ok: { type: "boolean" } },
required: ["ok"],
},
},
reset: {},
```
### Errors
Add an `errors` map to a method for expected failures. Each key becomes the
@ -110,8 +124,8 @@ Error names beginning with `rpc.` are reserved by OpenCode.
### Events
Add events to the top-level `events` map. Each event has a schema for the data
sent to subscribers.
Add events to the top-level `events` map, or omit `events` when the RPC only
defines methods. Each event has a schema for the data sent to subscribers.
Event data must be an object. Use an empty object schema when there is no data: