Objective: Use this skill to prevent host crashes, unhandled promise rejections, and race conditions in OpenCode plugins by enforcing export discipline, defensive event handling, and session abort safety.
OpenCode Plugin Development
Complete, field-tested guide for developing plugins for OpenCode (v1.18+) AI coding agent.
**Every rule, signature, and pattern below was verified against a production
plugin that went through 5 versions and 3 distinct crash classes.** The "Hard-won
rules" sections are non-negotiable —
violating them silently breaks the host.
Extension Types — When to Use What
| Extension Type | Best For | Example |
|----------------|----------|---------|
| Plugin (Hooks) | Event-driven automation, custom tools, recovery logic | Auto-resume stalled sessions, enforce agent selection |
| Tools | AI-triggered actions inside a plugin | task_complete, commit, custom search |
| MCP Servers | External service integrations | Databases, GitHub, filesystem, remote APIs |
| Skills | Knowledge/prompt templates (this file is one) | Framework patterns, project conventions |
| Commands | Interactive slash shortcuts | /hello, /deploy |
| Providers | Custom LLM backends | Alternative API gateways, self-hosted models |
The Plugin Contract (v1.18+) — Read This First
A plugin is an async function (input, Options) => Promise<Hooks>. It is NOT an object with name/version/tools fields — that shape is outdated and the host ignores it.
Type definition (from `@opencode-ai/plugin/dist/index.d.ts`)
export type Plugin = (input: PluginInput, options?: PluginOptions) => Promise<Hooks>
export interface Hooks {
dispose?: () => Promise<void>
event?: (input: { event: Event }) => Promise<void>
config?: (input: Config) => Promise<void>
tool?: { [key: string]: ToolDefinition }
auth?: AuthHook
provider?: ProviderHook
"chat.message"?: (input: ChatMessageInput) => Promise<void>
"tool.execute.before"?: (input: ToolExecInput) => Promise<void>
"tool.execute.after"?: (input: ToolExecInput) => Promise<void>
"command.execute.before"?: (input: CommandExecInput) => Promise<void>
"command.execute.after"?: (input: CommandExecInput) => Promise<void>
}
Correct minimal plugin
import type { Plugin } from "@opencode-ai/plugin"
import { tool } from "@opencode-ai/plugin"
export const MyPlugin: Plugin = async (ctx, options) => {
return {
event: async ({ event }) => {
// handle events
},
config: async () => {
// one-time init
},
tool: {
my_tool: tool({
description: "Does something useful",
args: {},
execute: async (_args, ctx) => "ok",
}),
},
}
}
export default MyPlugin
⚠️
confighook signature:(input: Config) => Promise<void>. It receives a Config object — you may ignore it but the parameter exists.
🚨 Hard-Won Rules (violate these and the host crashes)
These rules were discovered through real production crashes. Each one has a regression test in the reference plugin.
Rule 1 — Only export Plugin-shaped values from the entry module
Do only export Plugin-shaped values from the entry module because OpenCode's loader calls every export as a Plugin, and non-Plugin exports crash the host.
OpenCode's plugin loader iterates every module export via Object.values(module) and treats each as a Plugin entrypoint:
// Inside opencode's plugin loader (deobfuscated):
for (let N of Object.values(pluginModule)) {
if (typeof N !== "function") throw TypeError("Plugin export is not a function")
const hooks = await N(ctx, options) // called as a Plugin!
pluginArray.push(hooks)
}
// later:
for (let N of pluginArray) {
await N.config?.(config) // crashes if N is null
}
If any export returns null → the host crashes with null is not an object (evaluating 'N.config'), surfaced in the TUI as Unexpected server error. Check server logs for details.
✅ Correct
// src/index.ts — ONLY Plugin exports
export const MyPlugin: Plugin = async (ctx, options) => { ... }
export default MyPlugin
🚫 Wrong — crashes the host
// src/index.ts
export function getLastAssistantError(messages) { ... return null } // called as Plugin, returns null, host crashes
export function backoffMs(attempt) { return 42 } // called as Plugin, returns number, host crashes
export const MyPlugin: Plugin = async (ctx, options) => { ... }
export default MyPlugin
Solution — split utilities into a separate file
// src/index.ts — bundle entry, only Plugin exports
export const MyPlugin: Plugin = async (ctx, options) => { ... }
export default MyPlugin
// src/test-utils.ts — NOT the bundle entry; tests import from here
export function getLastAssistantError(messages) { ... }
export function backoffMs(attempt, base, max) { ... }
Tests import utilities from ./test-utils; the bundled dist/index.js only exposes the Plugin. Verify with:
bun -e 'const m = await import("./dist/index.js"); console.log(Object.keys(m))'
# MUST print only: [ "MyPlugin", "default" ]
Rule 2 — Never let an async handler throw unhandled
The event hook is called fire-and-forget by the host. If handleEvent() rejects, it becomes an unhandled promise rejection → bun process exits → OpenCode disappears from the TUI.
✅ Correct
return {
event: async ({ event }) => {
handleEvent(event).catch((e) => {
console.error("[my-plugin] handleEvent error:", e)
})
},
}
Same rule applies to setInterval(async () => { ... }) bodies — wrap in a safe() boundary:
async function safe<T>(fn: () => Promise<T>, label: string): Promise<T | undefined> {
try { return await fn() }
catch (e) {
const msg = e instanceof Error ? e.message : String(e)
console.error(`[my-plugin] ${label}: ${msg}`)
return undefined
}
}
setInterval(() => {
safe(doPeriodicWork, "periodic timer").catch(() => {})
}, 5000)
Rule 3 — Validate event payloads defensively
OpenCode event payloads are not guaranteed to match the documented shape. Real-world crashes found:
todo.updatedevents arrive withproperties.todosas{}(object) orundefined, not an arraysession.statusproperties.statusis always{ type: "idle" | "busy" | "retry" }— never a bare string- Session IDs (
sessionID) may be missing on some events
✅ Correct — `Array.isArray` before `.map()`/`.filter()`
case "todo.updated": {
const rawTodos = (event.properties as any)?.todos
const todos: Array<Record<string, unknown>> = Array.isArray(rawTodos) ? rawTodos : []
w.todos = todos.map((t) => ({ ... })) // safe
break
}
Rule 4 — `log()` must never rethrow
If the OpenCode log API itself throws (network/server error), your log() helper's catch block must not propagate. Otherwise an error inside an error handler escapes:
async function log(level: "info" | "warn" | "error", msg: string) {
try {
await ctx.client.app.log({ body: { service: "my-plugin", level, message: msg } })
} catch (e) {
console.error("[my-plugin] log() failed:", e instanceof Error ? e.message : e)
// do NOT rethrow
}
}
Rule 5 — Validate `sid` before every SDK call
Session IDs from events may be empty, undefined, or malformed. The SDK throws Expected 'id' to be a string if you pass garbage:
if (typeof sid !== "string" || !sid.startsWith("ses_")) return
await ctx.client.session.prompt({ path: { id: sid }, body: { ... } })
Rule 6 — ESC/abort race: set `pluginAbortInFlight` before calling `session.abort()`
The session.status event with "interrupted" can arrive BEFORE session.error with MessageAbortedError. If you abort during this window, check the flag before treating it as user-cancel:
// In ensureWatch
w.pluginAbortInFlight = false
w.pluginAbortAt = 0
// Before aborting
w.pluginAbortInFlight = true
w.pluginAbortAt = Date.now()
try {
await ctx.client.session.abort({ path: { id: sid } })
} finally {
w.pluginAbortInFlight = false
w.pluginAbortAt = 0
}
// In session.error handler
case "session.error": {
if (props?.error?.name === "MessageAbortedError") {
if (w.pluginAbortInFlight && Date.now() - w.pluginAbortAt < 1000) {
// Plugin-initiated abort, not user ESC
} else {
w.userCancelled = true
}
}
break
}