docs: improve plugin guide readability (#46342)

This commit is contained in:
Dax
2026-08-31 11:48:04 -04:00
committed by GitHub
Unverified
parent d609752891
commit 6a38cacc1d
7 changed files with 249 additions and 149 deletions
+3
View File
@@ -16,6 +16,9 @@
- Put the relevant example immediately after the text that introduces it, following `content/build/plugins/cli.mdx` as the reference pattern.
- Split long explanations with meaningful headings and examples rather than accumulating caveats in one paragraph.
- Lead with the common task and working example; place edge cases and supporting details afterward.
- Do not stack several prose paragraphs without a visual break. After introducing a concept, use an example, list, table, or task-oriented subheading before covering the next concern.
- Use bullets or tables for independent rules, options, and constraints. Do not hide reference material in narrative paragraphs.
- Organize workflow documentation in the order readers perform it, with a working example at each major step.
## Validation
@@ -104,7 +104,7 @@ RPC error wrapper; reserved `rpc.*` types identify framework failures.
RPC events are typed Streams, not callback-style `on` listeners. They receive the
RPC's events from all locations, each with required `location` and a normal
prefixed type such as `rpc.acme.updated`. This differs from server-plugin handles,
which are fixed to their own location. See [plugin RPC](/build/plugins#rpc) for
which are fixed to their own location. See [plugin RPC](/build/plugins/rpc) for
definitions, schemas, registration, and live subscription semantics.
## Local background service
@@ -133,7 +133,7 @@ and end that listener. Native and typed subscriptions receive the same normal
do not replay missed events.
The server plugin must be configured and implement the RPC; importing a
definition does not register it. See [plugin RPC](/build/plugins#rpc) for the
definition does not register it. See [plugin RPC](/build/plugins/rpc) for the
definition and registration API. Any HTTP client can also invoke the generic
`POST /api/rpc/{rpcID}/{method}` route with `{ "input": ... }` and receive
`{ "output": ... }`. Omitted input/output fields represent no value.
@@ -633,7 +633,7 @@ interface Context {
### RPC
Use the same execution-neutral [`Rpc.define` builder](/build/plugins#rpc).
Use the same execution-neutral [`Rpc.define` builder](/build/plugins/rpc).
Effect clients and plugins accept Effect Schema, Standard Schema, or plain JSON
Schema. Promise consumers accept only the portable Standard and JSON formats.
@@ -1010,16 +1010,23 @@ interface EventContext {
## Hooks
Hooks intercept live operations. Multiple plugins can register the same hook; OpenCode runs them in plugin order so
later hooks see earlier changes.
Hooks intercept live operations. Register a hook on its domain and dispose the
returned registration when it is no longer needed.
```ts
const registration = await ctx.session.hook("context", () => {})
await registration.dispose()
```
Multiple plugins can register the same hook. OpenCode runs them in plugin order,
so later hooks see changes made by earlier hooks.
### Sessions
Session hooks intercept prompt admission, model calls, native HTTP, and retries.
#### Prompt admission
Intercept incoming user prompts before attachment and skill resolution and durable inbox admission:
```ts
@@ -1032,20 +1039,35 @@ await ctx.session.hook("prompt", (event) => {
})
```
The hook receives an owned, mutable draft with `text`, `files`, agent mentions (`agents`), and selected `skills`, plus
`metadata` and `delivery` (`"steer"` by default, or `"queue"`). Files and skills added by hooks use the normal resolution
and validation path. If you rewrite text, update or remove attachment `mention` offsets that no longer match it. Agent
mentions do not switch the session's active agent. Session and message IDs are readonly and cannot redirect admission.
The hook receives an owned, mutable draft:
Hooks run in registration order after the session's location plugins are ready. Edits become the canonical persisted user
input; unlike `context`, `prompt` does not run on each model call. Commands that submit through `session.prompt` also run
this hook. Synthetic messages, shell messages, and compaction/move controls do not. Prompt hooks cannot be scoped by model
provider because admission is separate from model resolution. Use an unscoped registration.
- `prompt` contains `text`, `files`, agent mentions in `agents`, and selected `skills`.
- `metadata` contains application-defined admission metadata.
- `delivery` is `"steer"` by default and can be changed to `"queue"`.
- Session and message IDs are readonly; a hook cannot redirect admission.
Retries of an ID already pending or delivered return the original admission without rerunning hooks or resolving the
retried payload. Concurrent submissions can run hooks more than once before either admission commits, but only the first
successful admission wins. Keep hooks retry-safe; they are not an exactly-once side-effect boundary. A failed or interrupted
preparation admits no prompt. This hook transforms input and does not expose a typed rejection API.
Files and skills added by a hook follow the normal resolution and validation
path. When rewriting text, update or remove attachment `mention` offsets that no
longer match. Agent mentions do not switch the session's active agent.
Prompt hooks run under these conditions:
- Hooks run in registration order after the session's location plugins are ready.
- Commands that submit through `session.prompt` run the hook.
- Synthetic messages, shell messages, compaction controls, and move controls do not.
- The hook runs once during admission, not before every model call.
- Provider scoping is unavailable because model resolution happens after admission.
Edits become the canonical persisted user input. If preparation fails or is
interrupted, OpenCode does not admit the prompt.
Keep prompt hooks retry-safe. They are not an exactly-once side-effect boundary:
- Retrying an ID already pending or delivered returns the original admission without rerunning hooks.
- Concurrent submissions can run hooks more than once, but only the first successful admission wins.
- Prompt hooks transform input and do not expose a typed rejection API.
#### Model context
Modify assembled system instructions, messages, tools, generation settings, or provider options immediately before model
dispatch.
@@ -1059,15 +1081,20 @@ await ctx.session.hook("context", (event) => {
})
```
`generation` and `providerOptions` start as empty request-override objects for each context hook invocation, not resolved
model settings. Hooks run in registration order and see earlier hooks' overrides. During compilation, request overrides
take precedence over model defaults, which take precedence over route defaults. Provider option records merge recursively;
arrays and scalar values replace earlier values. Deleting an override or setting it to `undefined` falls back to defaults;
it does not remove a configured default. This precedence applies to semantic generation and provider options; explicit raw
HTTP body overlays are applied after protocol lowering and can override the resulting fields.
Context changes affect only the outgoing model call, not persisted history or
configuration. The hook runs again for subsequent calls such as tool-driven
continuations, but not for title or compaction requests.
These changes affect only the outgoing model call, not persisted session history or configuration. Context hooks also run
for subsequent calls such as tool-driven continuations, but do not run for title or compaction requests.
Request overrides follow these rules:
- `generation` and `providerOptions` start empty for each model call; they do not contain resolved model settings.
- Hooks run in registration order and see overrides made by earlier hooks.
- Request overrides take precedence over model defaults, which take precedence over route defaults.
- Provider option objects merge recursively; arrays and scalar values replace earlier values.
- Deleting an override or setting it to `undefined` falls back to configured defaults rather than removing them.
- Raw HTTP body overlays apply after protocol lowering and can override the resulting fields.
#### Provider options
Provider options use the selected protocol's semantic option names, not raw HTTP body fields. Scope provider-specific
settings to the matching provider. For example, OpenAI Responses uses `reasoningEffort`:
@@ -1082,8 +1109,12 @@ await ctx.session.hook(
)
```
`maxTokens` is the semantic output-token limit. Generation settings are supported only where the selected protocol and
model support them; for example, Gemini supports `topK`, while OpenAI Responses does not expose it.
Generation options depend on the selected protocol and model:
- `maxTokens` is the semantic output-token limit.
- Gemini supports `topK`; OpenAI Responses does not expose it.
#### Model request
Modify model request settings and optionally scope the hook to one provider.
@@ -1097,6 +1128,8 @@ await ctx.session.hook(
)
```
#### Native HTTP
Modify native provider requests or responses. Their bodies are one-shot streams; clone or replace a body before reading
it.
@@ -1113,6 +1146,8 @@ await ctx.session.hook("http.response", (event) => {
})
```
#### Retry policy
Override the retry decision for a provider failure or replace its delay in milliseconds. The hook runs after OpenCode
classifies the failure and proposes its policy, but before any retry is scheduled. It does not expose how OpenCode
internally performs the next attempt.
@@ -1131,13 +1166,18 @@ await ctx.session.hook("retry", (event) => {
})
```
The initial `decision` is OpenCode's policy, so hooks may make a normally terminal provider failure retryable or veto a
proposed retry. Multiple hooks run in registration order and later hooks see the current decision. The built-in maximum
attempt count remains a hard limit. `attempt` is the physical attempt being proposed; the initial request is attempt `1`,
so the first retry is attempt `2`. Invalid delays (`NaN`, infinity, or negative values) fall back to the computed delay.
Context-overflow recovery remains separate because it compacts the conversation instead of retrying the same request.
Retry hooks can change OpenCode's initial `decision` by making a terminal failure
retryable or vetoing a proposed retry.
#### Reference
Retry decisions follow these rules:
- Multiple hooks run in registration order, and later hooks see the current decision.
- The built-in maximum attempt count remains a hard limit.
- `attempt` is the physical attempt under consideration. The initial request is `1`, so the first retry is `2`.
- Invalid delays such as `NaN`, infinity, or negative values fall back to the computed delay.
- Context-overflow recovery is separate because it compacts the conversation instead of retrying the same request.
#### Session reference
```ts
import type { SessionPrompt } from "@opencode-ai/plugin/promise/session"
@@ -1193,9 +1233,8 @@ interface SessionHookContext {
### Permissions
Review permission decisions after configured rules are evaluated and before an action runs or a permission prompt is
published. Hooks run for `allow` and `ask` decisions. An explicit configured `deny` is final and does not invoke the
hook.
Review permission decisions after configured rules are evaluated and before an
action runs or a permission prompt is published.
```ts
await ctx.permission.hook("evaluate", async (event) => {
@@ -1213,8 +1252,12 @@ await ctx.permission.hook("evaluate", async (event) => {
})
```
The hook may set `effect` to `allow`, `ask`, or `deny`. When set, `message` is included in an escalated permission
request or used as the denial reason.
Permission hooks follow these rules:
- Hooks run for `allow` and `ask` decisions.
- An explicit configured `deny` is final and does not invoke the hook.
- A hook may change `effect` to `allow`, `ask`, or `deny`.
- `message` appears in an escalated permission request or becomes the denial reason.
#### Reference
@@ -1293,115 +1336,6 @@ interface ToolHookContext {
}
```
## RPC
Expose typed methods and custom events through a shared RPC definition. Keep
the contract in a browser-safe module, separate from plugin setup and server code.
`Rpc.define` is synchronous and independent of Promise or Effect execution.
```ts title="src/rpc.ts"
import { Rpc } from "@opencode-ai/plugin/rpc"
import { z } from "zod"
export const Acme = Rpc.define({
id: "acme",
methods: {
search: {
input: z.object({ query: z.string() }),
output: z.object({ text: z.string() }),
errors: {
not_found: z.object({ query: z.string() }),
},
},
},
events: {
updated: {
schema: z.object({ itemID: z.string(), text: z.string() }),
},
},
})
```
Promise plugin contracts accept Standard Schema such as Zod or plain JSON Schema.
Standard Schema infers types; plain JSON Schema uses `unknown` while still
validating at runtime. Effect Schema is supported only by the Effect plugin and
client APIs. Use Standard or JSON Schema when both API styles consume a contract.
Every method declares `input` and `output` and may declare an `errors` map.
Error keys become literal error `type` values, while each schema validates and
transforms that error's `data`. Names starting with `rpc.` are reserved for
framework failures. Schemas own parsing, transformations, and Effect encoding.
RPC does not add a second generic JSON validation pass.
Custom event schemas must produce JSON objects. Scalars, arrays, `null`, and
`undefined` are not valid event data. Plain JSON Schema event definitions are
checked at emission even though they do not infer a TypeScript payload type.
Plain JSON Schema is interpreted as Draft 2020-12 and delegated directly to
Effect's JSON Schema importer and decoder. Use Standard Schema when another
dialect or parser is required.
Use `{}` for an empty event payload; only omitted method input/output represents
no value.
Register the implementation inside `setup`:
```ts title="src/index.ts"
import { Plugin } from "@opencode-ai/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 ({ query }, context) => {
const text = await findText(query, { signal: context.signal })
if (!text) return context.error("not_found", "Result not found", { query })
return { text }
},
})
await registration.events.emit("updated", { itemID: "item-1", text: "ready" })
},
})
```
Promise handlers receive a general second context argument with `signal` and a
typed `error(type, message, data)` constructor. They may return or throw the
constructed error; both reject callers with `{ type, message, data? }`. RPC IDs
are independent of plugin IDs. One plugin can implement several RPCs, and later registrations override earlier ones
at the same location. Disposal or unload removes only that registration and
reveals the previous implementation. In-flight calls retain their original handler.
Other server plugins can obtain a handle without implementing the RPC:
```ts
const acme = ctx.rpc(Acme)
const result = await acme.search({ query: "hello" })
const unsubscribe = acme.events.on("updated", (event) => {
console.log(event.type, event.location.directory, event.data.text)
})
```
Handles are immediate; each call finds the current registration. Server-plugin
handles call and subscribe within their own location and cannot override it.
`events.subscribe("updated")` returns an async iterable; `events.on` is a
callback convenience returning unsubscribe. Plugin unload closes its subscriptions.
Event keys are local names. Subscribers see normal prefixed types such as
`rpc.acme.updated`, with `id`, `created`, direct `data`, required `location`, and optional
`metadata`. Events publish through the normal ephemeral Bus path.
Subscriptions remain live-only: there is no plugin log/replay API yet, and events
while disconnected are missed. The method name `events` is reserved for the
subclient's event API.
External [clients](/build/client#plugin-rpc) use `client.rpc(Acme)` and receive
that RPC's events across all locations. The native `/api/event` stream and
typed subclients observe the same direct `rpc.<rpcID>.<event>` envelope.
Neither importing the contract nor constructing a handle loads the server implementation.
Configure the plugin on the server separately.
## Publish
A package plugin uses the same default export as a local plugin. A minimal
@@ -1422,8 +1356,9 @@ manifest is:
}
```
The `./rpc` export is optional; include it when publishing a shared RPC contract
for other plugins and clients to import without loading your implementation.
The `./rpc` export is optional; include it when publishing a shared
[RPC contract](/build/plugins/rpc) for other plugins and clients to import
without loading your implementation.
Use versions compatible with the OpenCode release you target and test the
installed package, not only a workspace-linked copy. Because the plugin API is
@@ -0,0 +1,161 @@
---
title: "RPC"
---
Expose typed methods and custom events through a shared RPC definition. Start by
putting the contract in a browser-safe module, separate from plugin setup and
server code.
## Define the contract
Use `Rpc.define` to declare the RPC ID, methods, errors, and events. The builder
is synchronous and independent of Promise or Effect execution.
```ts title="src/rpc.ts"
import { Rpc } from "@opencode-ai/plugin/rpc"
import { z } from "zod"
export const Acme = Rpc.define({
id: "acme",
methods: {
search: {
input: z.object({ query: z.string() }),
output: z.object({ text: z.string() }),
errors: {
not_found: z.object({ query: z.string() }),
},
},
},
events: {
updated: {
schema: z.object({ itemID: z.string(), text: z.string() }),
},
},
})
```
## Choose schemas
Use Standard Schema, such as Zod, when Promise and Effect consumers share the
contract. It validates at runtime and infers TypeScript types.
Other schema formats have narrower tradeoffs:
- Plain JSON Schema validates at runtime, but its inferred TypeScript value is `unknown`.
- Plain JSON Schema uses Draft 2020-12 through Effect's JSON Schema importer and decoder.
- Use Standard Schema when you need another JSON Schema dialect or parser.
- Effect Schema is supported only by Effect plugins and clients.
Every method declares `input` and `output`. Omit either to represent no value.
An empty event payload is an object instead:
```ts
events: {
refreshed: { schema: z.object({}) },
}
```
Event schemas must produce JSON objects. Scalars, arrays, `null`, and `undefined`
are invalid event data. Plain JSON Schema events are checked when emitted even
though their payload type remains `unknown`.
## Declare errors
Add an `errors` map to a method for expected failures. Each key becomes the
literal error `type`, and its schema validates and transforms the error `data`.
```ts
errors: {
not_found: z.object({ query: z.string() }),
}
```
Names beginning with `rpc.` are reserved for framework failures. Contract schemas
own parsing, transformations, and Effect encoding; RPC does not perform another
generic JSON validation pass.
## Register the implementation
Register the implementation inside `setup`:
```ts title="src/index.ts"
import { Plugin } from "@opencode-ai/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 ({ query }, context) => {
const text = await findText(query, { signal: context.signal })
if (!text) return context.error("not_found", "Result not found", { query })
return { text }
},
})
await registration.events.emit("updated", { itemID: "item-1", text: "ready" })
},
})
```
Promise handlers receive `signal` and a typed `error(type, message, data)`
constructor in their second argument. Return or throw a constructed error to
reject callers with `{ type, message, data? }`.
Registration follows these rules:
- RPC IDs are independent of plugin IDs, and one plugin can implement several RPCs.
- A later registration overrides an earlier registration at the same location.
- Disposal or plugin unload removes only that registration and reveals the previous one.
- In-flight calls retain the handler with which they started.
## Call from another plugin
Other server plugins can obtain a handle without implementing the RPC:
```ts
const acme = ctx.rpc(Acme)
const result = await acme.search({ query: "hello" })
```
The handle is available immediately, and each call finds the current registration.
Calls stay within the server plugin's location and cannot override it.
## Subscribe to events
Use `events.on` for a callback and unsubscribe when the listener is no longer
needed:
```ts
const unsubscribe = acme.events.on("updated", (event) => {
console.log(event.type, event.location.directory, event.data.text)
})
unsubscribe()
```
For an async iterable, use `events.subscribe("updated")`:
```ts
for await (const event of acme.events.subscribe("updated")) {
console.log(event.data.text)
}
```
Event subscriptions have these semantics:
- Event keys use local names such as `updated` when subscribing.
- Delivered types are prefixed, such as `rpc.acme.updated`.
- Each event includes `id`, `created`, direct `data`, required `location`, and optional `metadata`.
- Events use the normal ephemeral Bus path and are live-only; disconnected subscribers miss events.
- Plugin unload closes its subscriptions. There is no plugin event log or replay API yet.
- The method name `events` is reserved for the subclient event API.
## Connect external clients
External [clients](/build/client#plugin-rpc) use `client.rpc(Acme)` and receive
that RPC's events across all locations. The native `/api/event` stream and
typed subclients observe the same direct `rpc.<rpcID>.<event>` envelope.
Importing the contract or constructing a handle does not load its server
implementation. Configure the plugin on the server separately.
+1
View File
@@ -94,6 +94,7 @@ export const docsSections: DocsSection[] = [
title: "Plugins",
items: [
{ title: "Overview", slug: "build/plugins" },
{ title: "RPC", slug: "build/plugins/rpc" },
{ title: "Effect", slug: "build/plugins/effect" },
{ title: "CLI", slug: "build/plugins/cli" },
],