repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by bugabinga

opencode/plugins/chef/PLUGIN_SDK.md

Raw

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

Both locations work. Load order:

  1. Global config (~/.config/opencode/opencode.json)
  2. Project config (opencode.json)
  3. Global plugin directory
  4. 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:

Message Events:

Tool Events:

File Events:

Permission Events:

Other Events:

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:


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:

For Chef Plugin: Convert Zod schemas to JSON Schema using zodToJsonSchema library, then pass to SDK.

Additional SDK Methods (Updated)

File Operations:

TUI Control:

Project/Config:

Session Management:

Auth & Global:


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:

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 Plugin hooks should inject AI-visible messages (Resolved via 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

  1. Subagent bypass: tool.execute.before doesn't fire for subagents
  2. Permission system bypass: Subagents can bypass permission checks
  3. No isolation: Plugin code runs in same process

References


Last updated: 2026-03-23

Markdown source
File outline
# 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:

1. Global config (`~/.config/opencode/opencode.json`)
2. Project config (`opencode.json`)
3. Global plugin directory
4. Project plugin directory

---

## Basic Structure

```typescript
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)

```typescript
event: (async ({ event }) => {
  console.log("Event:", event.type);
});
```

**Session Events:**

- `session.created` - New session started
- `session.updated` - Session updated
- `session.deleted` - Session deleted
- `session.error` - Session error occurred
- `session.idle` - Session became idle
- `session.status` - Session status changed
- `session.compacted` - Session was compacted
- `session.diff` - Session diff occurred

**Message Events:**

- `message.updated` - Message updated
- `message.removed` - Message removed
- `message.part.updated` - Message part updated
- `message.part.removed` - Message part removed

**Tool Events:**

- `tool.execute.before` - Before tool execution
- `tool.execute.after` - After tool execution

**File Events:**

- `file.edited` - File edited
- `file.watcher.updated` - File watcher updated

**Permission Events:**

- `permission.asked` - Permission requested
- `permission.replied` - Permission answered

**Other Events:**

- `command.executed` - Command executed
- `installation.updated` - Installation updated
- `lsp.client.diagnostics` - LSP diagnostics
- `lsp.updated` - LSP updated
- `server.connected` - Server connected
- `todo.updated` - Todo updated
- `tui.prompt.append` - Prompt appended
- `tui.command.execute` - Command executed
- `tui.toast.show` - Toast shown
- `shell.env` - Shell environment

### Tool Execution Hooks

```typescript
"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

```typescript
"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

```typescript
"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

```typescript
"permission.ask": async (perm, output) => {
  // output: { status: 'allow' | 'deny' }
  if (perm.type === "read_file" && perm.path.includes(".env")) {
    output.status = "deny"
  }
}
```

### Configuration Hook

```typescript
config: (async (config) => {
  // Modify config before it's applied
  config.model = "anthropic/claude-3-5-sonnet";
});
```

---

## Custom Tools

```typescript
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

```typescript
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:

```typescript
// 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:

```typescript
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 pattern
- `client.file.status({ query? })` - Get file status

**TUI Control:**
- `client.tui.appendPrompt({ body: { text } })` - Append to prompt
- `client.tui.submitPrompt()` - Submit current prompt
- `client.tui.clearPrompt()` - Clear prompt
- `client.tui.executeCommand({ body })` - Execute command

**Project/Config:**
- `client.project.list()` - List all projects
- `client.project.current()` - Get current project
- `client.path.get()` - Get current path
- `client.config.get()` - Get config info
- `client.config.providers()` - List providers and models

**Session Management:**
- `client.session.children({ path })` - List child sessions
- `client.session.update({ path, body })` - Update session properties
- `client.session.init({ path, body })` - Initialize session with app analysis
- `client.session.share({ path })` / `unshare({ path })` - Share sessions
- `client.session.summarize({ path, body })` - Summarize session
- `client.session.command({ path, body })` - Send command
- `client.session.shell({ path, body })` - Run shell command
- `client.session.revert({ path, body })` / `unrevert({ path })` - Revert messages

**Auth & Global:**
- `client.auth.set({ path, body })` - Set authentication credentials
- `client.global.health()` - Health check

---

## Critical Limitations

### 1. Event Handlers Are Fire-and-Forget

The `event` hook does NOT wait for async operations:

```typescript
// 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

```typescript
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

```typescript
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:

```json
{
  "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 | ~~Plugin hooks should inject AI-visible messages~~ (Resolved via `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

1. **Subagent bypass**: `tool.execute.before` doesn't fire for subagents
2. **Permission system bypass**: Subagents can bypass permission checks
3. **No isolation**: Plugin code runs in same process

---

## References

- [Official Plugin Docs](https://opencode.ai/docs/plugins/)
- [Custom Tools Docs](https://opencode.ai/docs/custom-tools/)
- [SDK Docs](https://opencode.ai/docs/sdk/)
- [Plugin Source](https://github.com/anomalyco/opencode/blob/dev/packages/opencode/src/plugin/index.ts)
- [Plugin Package](https://github.com/anomalyco/opencode/blob/dev/packages/plugin/src/index.ts)
- [Ecosystem](https://opencode.ai/docs/ecosystem)
- [opencode-workspace](https://github.com/kdcokenny/opencode-workspace)

---

_Last updated: 2026-03-23_