From 20543c63ea0bf0b40324ddc54d07cebb80196fcf Mon Sep 17 00:00:00 2001 From: Filip Hejmowski Date: Thu, 29 Oct 2026 15:21:03 +0100 Subject: [PATCH] fix(plugin): support optional RPC method schemas and events --- packages/client/src/effect/rpc.ts | 15 +- packages/client/src/promise/rpc.ts | 17 +- packages/client/src/rpc-runtime.ts | 8 +- packages/client/test/api.types.ts | 29 ++- packages/core/src/rpc.ts | 24 ++- .../core/test/rpc-optional-schemas.test.ts | 185 ++++++++++++++++++ packages/plugin/src/effect/rpc.ts | 4 +- packages/plugin/src/promise/rpc.ts | 4 +- packages/schema/src/rpc.ts | 40 ++-- packages/schema/test/rpc.test.ts | 81 ++++++++ .../server/test/rpc-optional-schemas.test.ts | 153 +++++++++++++++ .../docs/content/build/plugins/effect/rpc.mdx | 16 +- .../src/docs/content/build/plugins/rpc.mdx | 22 ++- 13 files changed, 547 insertions(+), 51 deletions(-) create mode 100644 packages/core/test/rpc-optional-schemas.test.ts create mode 100644 packages/schema/test/rpc.test.ts create mode 100644 packages/server/test/rpc-optional-schemas.test.ts diff --git a/packages/client/src/effect/rpc.ts b/packages/client/src/effect/rpc.ts index 623ec549e1c..bac1b357060 100644 --- a/packages/client/src/effect/rpc.ts +++ b/packages/client/src/effect/rpc.ts @@ -18,16 +18,16 @@ export type RpcClient< EventError = E, > = { readonly [Name in keyof D["methods"]]: ( - ...args: RpcArguments, Options> + ...args: RpcArguments, Options> ) => Effect.Effect< - Rpc.Output, - Rpc.MethodError | DecodeError | E + Rpc.MethodOutput, + Rpc.MethodError | DecodeError> | E > } & { readonly events: { - readonly subscribe: ( + readonly subscribe: >( name: Name, - ) => Stream.Stream, DecodeError | EventError> + ) => Stream.Stream, DecodeError> | EventError> } } @@ -70,9 +70,10 @@ export function make( // 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) => { 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), diff --git a/packages/client/src/promise/rpc.ts b/packages/client/src/promise/rpc.ts index e7c502e1cc8..e048a96ee75 100644 --- a/packages/client/src/promise/rpc.ts +++ b/packages/client/src/promise/rpc.ts @@ -17,15 +17,15 @@ export type RpcArguments = unknown extends Input export type RpcClient = { readonly [Name in keyof D["methods"]]: ( - ...args: RpcArguments, Options> - ) => Promise> + ...args: RpcArguments, Options> + ) => Promise> } & { readonly events: { - readonly subscribe: ( + readonly subscribe: >( name: Name, options?: Pick, ) => AsyncIterable> - readonly on: ( + readonly on: >( name: Name, handler: (event: RpcEventPayload) => Promise | void, options?: Pick, @@ -35,15 +35,15 @@ export type RpcClient, > = Omit & { type: `rpc.${D["id"]}.${Name}` - data: Rpc.EventData + data: Rpc.EventData> } export type RpcEventPayload< D extends Rpc.PortableDefinition, - Name extends keyof D["events"] & string = keyof D["events"] & string, + Name extends Rpc.EventName = Rpc.EventName, > = { [K in Name]: RpcEventPayloadFor }[Name] export interface RpcApi { @@ -59,7 +59,8 @@ export function makeRpc( name: string, options?: Pick, ): AsyncIterable> => { - 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]() { diff --git a/packages/client/src/rpc-runtime.ts b/packages/client/src/rpc-runtime.ts index 2267db8ee0a..0df6a0115ee 100644 --- a/packages/client/src/rpc-runtime.ts +++ b/packages/client/src/rpc-runtime.ts @@ -9,7 +9,9 @@ type RpcEvent = Extract 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 { @@ -35,7 +37,7 @@ export function readError(method: Rpc.Method, error: unknown): Effect.Effect, >( definition: D, name: Name, @@ -52,7 +54,7 @@ export const event = Effect.fn("Client.Rpc.event")(function* < } as Rpc.EventPayload }) -export function eventType( +export function eventType>( definition: D, name: Name, ): `rpc.${D["id"]}.${Name}` { diff --git a/packages/client/test/api.types.ts b/packages/client/test/api.types.ts index 93aad966fe0..2dd673af915 100644 --- a/packages/client/test/api.types.ts +++ b/packages/client/test/api.types.ts @@ -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 = 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 = effectClient.rpc(OneSidedRpc).reset() +const promiseRpcStatus: Promise<{ readonly ok: boolean }> = promiseClient.rpc(OneSidedRpc).status() +const promiseRpcReset: Promise = 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, ] diff --git a/packages/core/src/rpc.ts b/packages/core/src/rpc.ts index 134fe06b37e..42dc29c1e7d 100644 --- a/packages/core/src/rpc.ts +++ b/packages/core/src/rpc.ts @@ -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: Name) => { + subscribe: >(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>() -function eventType( +function eventType>( 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 { - return "~standard" in schema + return typeof schema === "object" && schema !== null && "~standard" in schema } -function read(schema: Tool.ValueSchema, value: unknown): Effect.Effect { +function read(schema: Tool.ValueSchema | undefined, value: unknown): Effect.Effect { // 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, >( definition: D, name: Name, payload: Event.Payload, ref: Location.Ref, ): Effect.fn.Return, 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 diff --git a/packages/core/test/rpc-optional-schemas.test.ts b/packages/core/test/rpc-optional-schemas.test.ts new file mode 100644 index 00000000000..3933b191d2f --- /dev/null +++ b/packages/core/test/rpc-optional-schemas.test.ts @@ -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 is covariant and assignable to Effect; 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 }) + }), +) diff --git a/packages/plugin/src/effect/rpc.ts b/packages/plugin/src/effect/rpc.ts index f4109c3e85d..548c94f6625 100644 --- a/packages/plugin/src/effect/rpc.ts +++ b/packages/plugin/src/effect/rpc.ts @@ -10,9 +10,9 @@ export interface RpcCallContext { export type RpcHandlers = { readonly [Name in keyof D["methods"]]: ( - input: Rpc.Output, + input: Rpc.HandlerInput, context: RpcCallContext, - ) => Effect.Effect, Rpc.HandlerError> + ) => Effect.Effect, Rpc.HandlerError> } export interface RpcRegistration extends Registration { diff --git a/packages/plugin/src/promise/rpc.ts b/packages/plugin/src/promise/rpc.ts index 45d3f984ad0..928d40d283a 100644 --- a/packages/plugin/src/promise/rpc.ts +++ b/packages/plugin/src/promise/rpc.ts @@ -11,9 +11,9 @@ export interface RpcCallContext { export type RpcHandlers = { readonly [Name in keyof D["methods"]]: ( - input: Rpc.Output, + input: Rpc.HandlerInput, context: RpcCallContext, - ) => Promise | Rpc.HandlerError> + ) => Promise | Rpc.HandlerError> } export interface RpcRegistration extends Registration { diff --git a/packages/schema/src/rpc.ts b/packages/schema/src/rpc.ts index 2fed79a2cc5..bf894372077 100644 --- a/packages/schema/src/rpc.ts +++ b/packages/schema/src/rpc.ts @@ -11,16 +11,16 @@ export type ErrorMap = Readonly> & { } 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 | JsonSchema.JsonSchema export interface PortableMethod extends Method { - readonly input: PortableValueSchema - readonly output: PortableValueSchema + readonly input?: PortableValueSchema + readonly output?: PortableValueSchema readonly errors?: Readonly> & { 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> & { readonly events?: never } - readonly events: Readonly> + readonly events?: Readonly> } export interface PortableDefinition extends Definition { readonly methods: Readonly> & { readonly events?: never } - readonly events: Readonly> + readonly events?: Readonly> } export function define(definition: D) { @@ -74,6 +74,24 @@ export type Output = S extends Schema.Top // Effect codecs encode handler results; Standard Schema parses them forward. export type HandlerOutput = S extends Schema.Top ? Output : Input +type PresentProperty = K extends keyof T ? Exclude : never +export type InputSchema = Extract, Tool.ValueSchema> +export type OutputSchema = Extract, Tool.ValueSchema> + +export type MethodInput = [InputSchema] extends [never] ? undefined : Input> +export type HandlerInput = [InputSchema] extends [never] ? undefined : Output> +export type MethodOutput = [OutputSchema] extends [never] ? void : Output> +export type MethodHandlerOutput = [OutputSchema] extends [never] + ? void + : HandlerOutput> + +export type Events = Extract< + PresentProperty, + Readonly> +> +export type EventName = [Events] extends [never] ? never : keyof Events & string +export type EventSchema> = Events[Name]["schema"] + type MethodErrors = M extends { readonly errors: infer Errors extends ErrorMap } @@ -150,18 +168,18 @@ export type EventData = S extends JsonSchema.JsonSch // Keep the event name correlated with its payload even when callers use unions. export type EventInput = { - [Name in keyof D["events"] & string]: [name: Name, data: EventInputData] -}[keyof D["events"] & string] + [Name in EventName]: [name: Name, data: EventInputData>] +}[EventName] type EventPayloadFor< D extends Definition, - Name extends keyof D["events"] & string, + Name extends EventName, > = Omit, "type" | "data" | "durable" | "location"> & { readonly type: `rpc.${D["id"]}.${Name}` - readonly data: EventData + readonly data: EventData> readonly location: Location.Ref } -export type EventPayload = { +export type EventPayload = EventName> = { readonly [K in Name]: EventPayloadFor }[Name] diff --git a/packages/schema/test/rpc.test.ts b/packages/schema/test/rpc.test.ts new file mode 100644 index 00000000000..58c170a18d0 --- /dev/null +++ b/packages/schema/test/rpc.test.ts @@ -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 + +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, undefined>>, + Assert, undefined>>, + Assert, void>>, + Assert, void>>, + Assert, undefined>>, + Assert, undefined>>, + Assert, { readonly ok: boolean }>>, + Assert, { readonly ok: boolean }>>, + Assert, { readonly text: string }>>, + Assert, { readonly text: string }>>, + Assert, void>>, + Assert, void>>, + Assert, undefined>>, + Assert, unknown>>, + Assert, never>>, + Assert, 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') + }) +}) diff --git a/packages/server/test/rpc-optional-schemas.test.ts b/packages/server/test/rpc-optional-schemas.test.ts new file mode 100644 index 00000000000..041693e242b --- /dev/null +++ b/packages/server/test/rpc-optional-schemas.test.ts @@ -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 }) + }), +) diff --git a/services/www/src/docs/content/build/plugins/effect/rpc.mdx b/services/www/src/docs/content/build/plugins/effect/rpc.mdx index ddadb478c6f..650908e229c 100644 --- a/services/www/src/docs/content/build/plugins/effect/rpc.mdx +++ b/services/www/src/docs/content/build/plugins/effect/rpc.mdx @@ -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: { diff --git a/services/www/src/docs/content/build/plugins/rpc.mdx b/services/www/src/docs/content/build/plugins/rpc.mdx index 557508151b9..b5afb19374f 100644 --- a/services/www/src/docs/content/build/plugins/rpc.mdx +++ b/services/www/src/docs/content/build/plugins/rpc.mdx @@ -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: