OpenCode Plugin SDK - Research Findings
Compiled from official docs, source code analysis, ecosystem plugins, and GitHub issues.
Overview
Plugins are JavaScript/TypeScript modules that hook into OpenCode events, add custom tools, and modify behavior. They run within the OpenCode process and have access to a rich context API.
Plugin Location
- Global:
~/.config/opencode/plugins/or~/.config/opencode/plugin/ - Project:
.opencode/plugins/or.opencode/plugin/
Both locations work. Load order:
- Global config (
~/.config/opencode/opencode.json) - Project config (
opencode.json) - Global plugin directory
- Project plugin directory
Basic Structure
import type { Plugin } from "@opencode-ai/plugin";
export const MyPlugin: Plugin = async (
{ client, project, directory, worktree, $ },
) => {
console.log("Plugin initialized!");
return {
// Hooks go here
};
};
Context Parameters
| Parameter | Type | Description |
|---|---|---|
client |
SDK Client | OpenCode SDK for AI/session interactions |
project |
Project | Current project info { id, worktree } |
directory |
string | Current working directory |
worktree |
string | Git worktree root |
$ |
Bun Shell | Bun's shell API for commands |
serverUrl |
URL | Server URL (internal) |
Available Hooks
Event Hook (General)
event: (async ({ event }) => {
console.log("Event:", event.type);
});
Session Events:
session.created- New session startedsession.updated- Session updatedsession.deleted- Session deletedsession.error- Session error occurredsession.idle- Session became idlesession.status- Session status changedsession.compacted- Session was compactedsession.diff- Session diff occurred
Message Events:
message.updated- Message updatedmessage.removed- Message removedmessage.part.updated- Message part updatedmessage.part.removed- Message part removed
Tool Events:
tool.execute.before- Before tool executiontool.execute.after- After tool execution
File Events:
file.edited- File editedfile.watcher.updated- File watcher updated
Permission Events:
permission.asked- Permission requestedpermission.replied- Permission answered
Other Events:
command.executed- Command executedinstallation.updated- Installation updatedlsp.client.diagnostics- LSP diagnosticslsp.updated- LSP updatedserver.connected- Server connectedtodo.updated- Todo updatedtui.prompt.append- Prompt appendedtui.command.execute- Command executedtui.toast.show- Toast shownshell.env- Shell environment
Tool Execution Hooks
"tool.execute.before": async (input, output) => {
// input: { tool, args, sessionID, callID }
// output: { args } - can modify args
if (input.tool === "bash" && output.args.command.includes("rm -rf")) {
throw new Error("Dangerous command blocked")
}
}
"tool.execute.after": async (input, output) => {
// input: { tool, args, sessionID, callID }
// output: { title, output, metadata }
console.log(`Tool ${input.tool} completed:`, output.output)
}
Chat/Message Hooks
"chat.message": async (input, output) => {
// input: { message, parts }
// output: { message } - can modify
}
"chat.params": async (input, output) => {
// Modify LLM params before sending
output.temperature = 0.7
output.topP = 0.9
}
Experimental Hooks
"experimental.chat.system.transform": async (input, output) => {
// Inject into system prompt
output.system.push(`<custom-context>...</custom-context>`)
}
"experimental.session.compacting": async (input, output) => {
// Customize compaction context
output.context.push(`## State\nTask progress: 75%`)
// Or replace entirely:
// output.prompt = "Custom prompt..."
}
Permission Hook
"permission.ask": async (perm, output) => {
// output: { status: 'allow' | 'deny' }
if (perm.type === "read_file" && perm.path.includes(".env")) {
output.status = "deny"
}
}
Configuration Hook
config: (async (config) => {
// Modify config before it's applied
config.model = "anthropic/claude-3-5-sonnet";
});
Custom Tools
import { type Plugin, tool } from "@opencode-ai/plugin";
export const MyPlugin: Plugin = async (ctx) => {
return {
tool: {
myTool: tool({
description: "Does something useful",
args: {
input: tool.schema.string().describe("Input text"),
count: tool.schema.number().optional().describe("Count"),
},
async execute(args, context) {
// context: { sessionID, messageID, agent, directory, worktree, abort }
return `Processed: ${args.input}`;
},
}),
},
};
};
Tool Schema (Zod)
tool.schema is Zod. All Zod types are available:
tool.schema.string(),.number(),.boolean(),.array(),.object().describe(),.optional(),.default(),.min(),.max()
SDK Client Capabilities
const { client } = await createOpencode();
// or from plugin context
await client.session.prompt({
path: { id: sessionId },
body: { parts: [{ type: "text", text: "Hello" }] },
});
Key SDK Methods
| Method | Description |
|---|---|
client.session.create() |
Create new session |
client.session.get() |
Get session by ID |
client.session.list() |
List sessions |
client.session.prompt() |
Send prompt to session |
client.session.abort() |
Abort session |
client.session.messages() |
Get session messages |
client.app.agents() |
List available agents |
client.app.log() |
Write log entry |
client.event.subscribe() |
Subscribe to events (SSE) |
client.file.read() |
Read file |
client.find.text() |
Search text |
client.tui.showToast() |
Show toast |
✅ Message Injection (WORKS!)
Updated: This DOES work via noReply: true
You CAN inject AI-visible messages into sessions:
// Inject context without triggering AI response
await client.session.prompt({
path: { id: sessionId },
body: {
noReply: true, // ← Injects message, no AI response
parts: [{
type: "text",
text: "Context: Previous step completed with findings..."
}],
},
})
This is perfect for multi-agent orchestration - inject context from previous steps before prompting agent.
✅ Structured Output (BUILT-IN!)
The SDK supports native JSON schema validation with automatic retries:
const result = await client.session.prompt({
path: { id: sessionId },
body: {
parts: [{ type: "text", text: "Research the codebase and extract data" }],
format: {
type: "json_schema",
schema: {
type: "object",
properties: {
findings: { type: "string", description: "Research findings" },
files: { type: "array", items: { type: "string" } },
},
required: ["findings", "files"],
},
retryCount: 2, // Auto-retry on validation failure
},
},
})
// Already validated! No manual parsing needed
const output = result.data.info.structured_output
// output.findings: string
// output.files: string[]
Benefits:
- LLM is instructed to generate valid JSON matching schema
- Automatic validation and retries
- No manual parsing or Zod validation needed at runtime
- Type-safe output
For Chef Plugin: Convert Zod schemas to JSON Schema using zodToJsonSchema library, then pass to SDK.
Additional SDK Methods (Updated)
File Operations:
client.find.files({ query: { query, type, directory, limit } })- Find files by patternclient.file.status({ query? })- Get file status
TUI Control:
client.tui.appendPrompt({ body: { text } })- Append to promptclient.tui.submitPrompt()- Submit current promptclient.tui.clearPrompt()- Clear promptclient.tui.executeCommand({ body })- Execute command
Project/Config:
client.project.list()- List all projectsclient.project.current()- Get current projectclient.path.get()- Get current pathclient.config.get()- Get config infoclient.config.providers()- List providers and models
Session Management:
client.session.children({ path })- List child sessionsclient.session.update({ path, body })- Update session propertiesclient.session.init({ path, body })- Initialize session with app analysisclient.session.share({ path })/unshare({ path })- Share sessionsclient.session.summarize({ path, body })- Summarize sessionclient.session.command({ path, body })- Send commandclient.session.shell({ path, body })- Run shell commandclient.session.revert({ path, body })/unrevert({ path })- Revert messages
Auth & Global:
client.auth.set({ path, body })- Set authentication credentialsclient.global.health()- Health check
Critical Limitations
1. Event Handlers Are Fire-and-Forget
The event hook does NOT wait for async operations:
// From source: plugin/index.ts L138
hook["event"]?.({ event: input }); // return value dropped
Workaround: Use session.stopping (being added per issue #16626) or external processes.
2. No Message Injection ✅ WORKS NOW
You cannot inject AI-visible messages from plugins. Issue #17412 tracks this.
UPDATED: Message injection WORKS via noReply: true parameter in session.prompt().
3. No Session Continuation
session.idle fires AFTER the agent loop breaks. Cannot keep agent running.
4. Subagent Hooks Don't Work
tool.execute.before/after don't intercept subagent (task tool) calls. Security issue #5894.
5. No Native Agent Spawning ✅ WORKS NOW
Plugins cannot spawn agents or sessions programmatically in a blocking way.
UPDATED: Plugins CAN create sessions and prompt agents using the SDK client.
Storage Patterns
Plugins have no built-in state persistence. Options:
1. File-Based
import { $ } from "@opencode-ai/plugin";
import { readFileSync, writeFileSync } from "fs";
const stateFile = join(directory, ".opencode/chef/state.json");
function loadState() {
try {
return JSON.parse(readFileSync(stateFile, "utf-8"));
} catch {
return { pipelines: [] };
}
}
function saveState(state) {
writeFileSync(stateFile, JSON.stringify(state, null, 2));
}
2. SQLite with bun:sqlite
import { Database } from "bun:sqlite";
const db = new Database(join(directory, ".opencode/chef/chef.db"));
db.run("CREATE TABLE IF NOT EXISTS pipeline (...)");
Note: Need package.json in config dir for external deps.
Package Dependencies
Add package.json to config directory:
{
"dependencies": {
"bun:sqlite": "latest",
"zod": "^3.0.0",
"zod-to-json-schema": "^3.22.0"
}
}
OpenCode runs bun install at startup.
Open Source Plugin Examples
Community Plugins (from ecosystem)
| Plugin | Description |
|---|---|
opencode-workspace |
Bundled orchestration harness (16 components) |
opencode-background-agents |
Claude Code-style background agents |
@openspoon/subtask2 |
Orchestration system with granular flow control |
opencode-rules |
Rule file injection into prompts |
opencode-skillful |
Lazy-load prompts on demand |
opencode-supermemory |
Persistent memory across sessions |
micode |
Structured Brainstorm → Plan → Implement |
Key Pattern from opencode-workspace
Uses a bundle approach with:
- Multiple plugins (reactive features)
- Multiple agents (planner, coder, reviewer)
- Multiple skills (protocol enforcement)
- MCP servers (external tools)
NOT a centralized kernel - distributed coordination.
Related GitHub Issues
| Issue | Status | Description |
|---|---|---|
| #16626 | Open | session.stopping hook to allow re-entering agent loop |
| #17412 | Closed | noReply) |
| #16879 | Closed | Await plugin event handlers on session.idle |
| #12472 | Open | Native Claude Code hooks compatibility |
| #5894 | Open | Bug: Plugin hooks don't intercept subagents |
| #18007 | PR | Add session.start lifecycle hook |
Security Considerations
- Subagent bypass:
tool.execute.beforedoesn't fire for subagents - Permission system bypass: Subagents can bypass permission checks
- No isolation: Plugin code runs in same process
References
- Official Plugin Docs
- Custom Tools Docs
- SDK Docs
- Plugin Source
- Plugin Package
- Ecosystem
- opencode-workspace
Last updated: 2026-03-23