> For the complete documentation index, see [llms.txt](https://www.opencodebook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.opencodebook.xyz/en/chapter_17_hands-on_labs/17.4_lab4_writing_opencode_plugin.md). Agents can also search and read this documentation through its [MCP server](https://www.opencodebook.xyz/~gitbook/mcp).

# 17.4 Lab 4: Writing an OpenCode Plugin

> **Model**: claude-opus-4-6 (anthropic/claude-opus-4-6) **Generation Date**: 2026-02-18

***

In the first three labs, we built an LLM CLI conversation tool from scratch, added Tool Use capabilities, and constructed an MCP Server. These were all **standalone projects** -- they run outside of OpenCode. In this section, we shift perspective and **go deep inside OpenCode** -- by writing a Plugin that directly extends OpenCode's core capabilities.

In Chapter 13, we analyzed the Plugin system's architecture in detail: the `@opencode-ai/plugin` package defines the type interfaces, `plugin/index.ts` implements the loading mechanism, and oh-my-opencode demonstrates the full power of the Plugin system. Now it is time to implement a Plugin of our own.

## 17.4.1 Objectives

Implement a Plugin named `opencode-plugin-guardian` with the following features:

1. **`chat.message` Hook**: Automatically inject project guidelines (such as code style requirements) every time the user sends a message
2. **`tool.execute.before` Hook**: Log operations before tool execution
3. **`tool.execute.after` Hook**: Log results and elapsed time after tool execution
4. **Custom tool `project_stats`**: Gather basic project information such as file count, lines of code, etc.

Through this lab, you will experience the complete Plugin development workflow firsthand -- from type definitions to Hook implementation, from tool registration to local debugging.

## 17.4.2 Reviewing the Plugin Interface

Before we start coding, let us review the core types defined in `@opencode-ai/plugin` (see Section 13.1 for details):

```typescript
// Core type definitions
type Plugin = (input: PluginInput) => Promise<Hooks>

type PluginInput = {
  client: ReturnType<typeof createOpencodeClient>  // OpenCode SDK client
  project: Project                                   // Current project info
  directory: string                                  // Current working directory
  worktree: string                                   // Project root directory
  serverUrl: URL                                     // OpenCode Server URL
  $: BunShell                                        // Shell execution interface
}
```

The essence of a Plugin is an **async function**: it receives a `PluginInput` context and returns a `Hooks` object. Each field in `Hooks` corresponds to a lifecycle hook, and OpenCode calls them at the appropriate times.

> **Extended Explanation -- What Are Lifecycle Hooks?**
>
> Lifecycle hooks are a software design pattern that allows external code to "mount" custom logic at critical execution points within a framework. Just as React's `useEffect` executes when a component mounts/updates, or Git's `pre-commit` hook executes before a commit, OpenCode's Plugin Hooks are triggered at key points such as message sending and tool execution.
>
> The core idea is **Inversion of Control (IoC)**: you do not need to modify OpenCode's source code -- you simply register callback functions on the prescribed interfaces, and the framework calls your code at the appropriate time.

## 17.4.3 Implementation Steps

### Step 1: Initialize the Project

```bash
# Create the project directory
mkdir opencode-plugin-guardian
cd opencode-plugin-guardian

# Initialize a Bun project
bun init -y

# Install the Plugin type definitions
bun add @opencode-ai/plugin
```

After installation, the project structure looks like this:

```
opencode-plugin-guardian/
├── package.json
├── tsconfig.json
├── node_modules/
└── src/
    └── index.ts        # Plugin entry point (to be created)
```

Edit `package.json` to set the entry file and build configuration:

```json
{
  "name": "opencode-plugin-guardian",
  "version": "0.1.0",
  "main": "src/index.ts",
  "type": "module",
  "dependencies": {
    "@opencode-ai/plugin": "latest"
  }
}
```

### Step 2: Write the Plugin Entry Point

Create `src/index.ts` -- this is the Plugin's core file:

```typescript
import type { Plugin, Hooks } from "@opencode-ai/plugin"
import { tool } from "@opencode-ai/plugin/tool"
import { createProjectStatsTool } from "./tools/project-stats"
import { createLogger } from "./logger"

const GuardianPlugin: Plugin = async (ctx) => {
  // Initialize the logger
  const logger = createLogger(ctx.directory)

  // Read the project guidelines file (if it exists)
  const guidelinesPath = `${ctx.directory}/.guardian/guidelines.md`
  let guidelines = ""
  try {
    const file = Bun.file(guidelinesPath)
    if (await file.exists()) {
      guidelines = await file.text()
    }
  } catch {
    // No guidelines file, skip
  }

  const hooks: Hooks = {
    // ---- 1. Register custom tools ----
    tool: {
      project_stats: createProjectStatsTool(ctx),
    },

    // ---- 2. chat.message Hook: inject project guidelines ----
    "chat.message": async (input, output) => {
      if (!guidelines) return

      // Only inject in the main session to avoid duplicate injection in sub-Agent sessions
      if (!input.agent || input.agent === "build") {
        // Inject the project guidelines as an additional text Part in the message
        output.parts.push({
          type: "text",
          text: [
            "<project-guidelines>",
            guidelines,
            "</project-guidelines>",
          ].join("\n"),
        })
      }
    },

    // ---- 3. tool.execute.before Hook: pre-execution logging ----
    "tool.execute.before": async (input, output) => {
      const timestamp = new Date().toISOString()
      logger.log(
        `[${timestamp}] BEFORE | tool=${input.tool} | session=${input.sessionID} | args=${JSON.stringify(output.args).slice(0, 200)}`
      )
    },

    // ---- 4. tool.execute.after Hook: post-execution logging ----
    "tool.execute.after": async (input, output) => {
      if (!output) return
      const timestamp = new Date().toISOString()
      logger.log(
        `[${timestamp}] AFTER  | tool=${input.tool} | session=${input.sessionID} | title=${output.title} | output_length=${output.output.length}`
      )
    },
  }

  return hooks
}

// Default export -- OpenCode's Plugin loader will discover it automatically
export default GuardianPlugin
```

This code clearly demonstrates the four major capabilities of a Plugin:

| Capability                      | Hook Name             | Trigger Timing                |
| ------------------------------- | --------------------- | ----------------------------- |
| Register custom tools           | `tool`                | During Plugin initialization  |
| Message interception            | `chat.message`        | When the user sends a message |
| Pre-tool-execution interception | `tool.execute.before` | Before any tool executes      |
| Post-tool-execution processing  | `tool.execute.after`  | After any tool executes       |

### Step 3: Implement the Logger Module

Create `src/logger.ts` -- a simple file logger:

```typescript
import * as fs from "fs"
import * as path from "path"

export function createLogger(directory: string) {
  const logDir = path.join(directory, ".guardian")
  const logFile = path.join(logDir, "operations.log")

  // Ensure the log directory exists
  if (!fs.existsSync(logDir)) {
    fs.mkdirSync(logDir, { recursive: true })
  }

  return {
    log(message: string) {
      fs.appendFileSync(logFile, message + "\n")
    },
  }
}
```

### Step 4: Implement the Custom Tool

Create `src/tools/project-stats.ts` -- implementing the `project_stats` tool:

```typescript
import type { PluginInput } from "@opencode-ai/plugin"
import { tool } from "@opencode-ai/plugin/tool"

export function createProjectStatsTool(ctx: PluginInput) {
  return tool({
    description:
      "Gather basic information about the current project, including file count, lines of code, file type distribution, etc. " +
      "Useful for quickly understanding project scale and structure.",

    args: {
      path: tool.schema
        .string()
        .optional()
        .describe("Directory path to analyze; defaults to the project root"),
      extensions: tool.schema
        .string()
        .optional()
        .describe(
          "File extensions to include, comma-separated, e.g., 'ts,tsx,js'. If not specified, all files are counted"
        ),
    },

    async execute(args, context) {
      const targetDir = args.path || ctx.directory
      const extensions = args.extensions
        ? new Set(args.extensions.split(",").map((e) => e.trim()))
        : null

      try {
        // Use ctx.$ (BunShell) to execute the statistics command
        // Get the file list (excluding node_modules, .git, etc.)
        const findResult = await ctx
          .$`find ${targetDir} -type f \
              -not -path "*/node_modules/*" \
              -not -path "*/.git/*" \
              -not -path "*/dist/*" \
              -not -path "*/.opencode/*"`
          .text()

        const allFiles = findResult
          .trim()
          .split("\n")
          .filter((f) => f.length > 0)

        // Filter by extension
        const files = extensions
          ? allFiles.filter((f) => {
              const ext = f.split(".").pop() || ""
              return extensions.has(ext)
            })
          : allFiles

        // Count file type distribution
        const extCounts: Record<string, number> = {}
        for (const file of files) {
          const ext = file.split(".").pop() || "(no extension)"
          extCounts[ext] = (extCounts[ext] || 0) + 1
        }

        // Count lines of code (using wc -l)
        let totalLines = 0
        if (files.length > 0) {
          // Process in batches to avoid argument length limits
          const batchSize = 100
          for (let i = 0; i < files.length; i += batchSize) {
            const batch = files.slice(i, i + batchSize)
            try {
              const wcResult = await ctx
                .$`wc -l ${batch.join(" ")} 2>/dev/null | tail -1`
                .text()
              const match = wcResult.trim().match(/^\s*(\d+)/)
              if (match) {
                totalLines += parseInt(match[1], 10)
              }
            } catch {
              // Some files may be unreadable, skip
            }
          }
        }

        // Build output
        const sortedExts = Object.entries(extCounts)
          .sort((a, b) => b[1] - a[1])
          .slice(0, 15) // Show only the top 15

        const extTable = sortedExts
          .map(([ext, count]) => `  .${ext}: ${count} files`)
          .join("\n")

        return [
          `## Project Statistics: ${targetDir}`,
          "",
          `- **Total files**: ${files.length}`,
          `- **Total lines of code**: ${totalLines.toLocaleString()}`,
          `- **File type distribution** (Top ${sortedExts.length}):`,
          extTable,
        ].join("\n")
      } catch (error) {
        return `Statistics failed: ${error instanceof Error ? error.message : String(error)}`
      }
    },
  })
}
```

Let us examine the key aspects of this tool implementation:

1. **The `tool()` factory function**: Imported from `@opencode-ai/plugin/tool`, it accepts three fields: `description`, `args`, and `execute`. The `args` field uses `tool.schema` (which is essentially Zod) to define the parameter schema, and OpenCode automatically converts the schema into a Tool definition that the LLM can understand.
2. **`ctx.$` (BunShell)**: The Plugin gains Bun's shell execution capability through `PluginInput`. The syntax `ctx.$\`command\`\` is a tagged template literal, similar to executing a command in the terminal.
3. **The `context` parameter**: The second argument of the `execute` function provides context information such as `sessionID`, `messageID`, `agent`, and an `abort` signal, enabling more fine-grained control.

### Step 5: Local Debugging

OpenCode supports loading local Plugins via the `file://` protocol, without needing to publish to npm.

Edit the `opencode.json` in your project (or `~/.config/opencode/opencode.json`):

```json
{
  "plugin": [
    "file:///absolute/path/to/opencode-plugin-guardian"
  ]
}
```

Then start OpenCode:

```bash
opencode
```

You should see the Plugin being loaded in the startup log. Try the following operations to verify:

1. **Verify the `chat.message` Hook**: Create a `.guardian/guidelines.md` file in your project with some code standards, then send a message -- observe whether the AI follows your guidelines.
2. **Verify tool registration**: Ask the AI to use the `project_stats` tool in conversation, for example by typing "Show me the code statistics for the current project."
3. **Verify the logging Hooks**: Check the `.guardian/operations.log` file -- you should see a record for each tool invocation.

The log file output will look something like this:

```
[2026-02-18T10:30:15.123Z] BEFORE | tool=read | session=ses_abc123 | args={"file_path":"/src/index.ts"}
[2026-02-18T10:30:15.456Z] AFTER  | tool=read | session=ses_abc123 | title=Read(/src/index.ts) | output_length=2340
[2026-02-18T10:30:18.789Z] BEFORE | tool=project_stats | session=ses_abc123 | args={"extensions":"ts,tsx"}
[2026-02-18T10:30:19.234Z] AFTER  | tool=project_stats | session=ses_abc123 | title= | output_length=456
```

## 17.4.4 Understanding the Plugin Loading Mechanism

Let us cross-reference the source code to see how OpenCode loads our Plugin. Recall the analysis from Section 13.3 -- the loading flow in `packages/opencode/src/plugin/index.ts`:

```typescript
// Simplified loading flow
for (let plugin of plugins) {
  if (!plugin.startsWith("file://")) {
    // npm package mode: parse name@version, install via BunProc.install()
    const pkg = parsePackageName(plugin)
    plugin = await BunProc.install(pkg.name, pkg.version)
  }

  // Import the module
  const mod = await import(plugin)

  // Iterate over all exports to find Plugin functions and initialize them
  for (const [_name, fn] of Object.entries(mod)) {
    const init = await fn(input)  // Call the Plugin function
    hooks.push(init)               // Collect the returned Hooks
  }
}
```

Key points:

1. **The `file://` prefix** determines whether it is a local file or an npm package. Local files are `import`ed directly, while npm packages are first installed to `~/.cache/opencode/node_modules/` before being imported.
2. OpenCode iterates over **all exports** of the module (`Object.entries(mod)`), finds those that are functions, and calls them. This means a single module can export multiple Plugin functions.
3. **When a Hook is triggered**, all Hooks returned by Plugins are called in a chain according to registration order -- the first-registered Plugin executes first. This is similar to a middleware pipeline.

## 17.4.5 Advanced: Adding an Event Hook

In addition to `chat.message` and `tool.execute.*`, Plugins can also listen to OpenCode's event system. Let us add session event monitoring to the Guardian Plugin:

```typescript
// Add an event Hook to the hooks object
event: async (input) => {
  const { event } = input

  // Listen for session creation events
  if (event.type === "session.created") {
    logger.log(`[SESSION] New session created: ${JSON.stringify(event.properties)}`)
  }

  // Listen for session error events
  if (event.type === "session.error") {
    logger.log(`[ERROR] Session error: ${JSON.stringify(event.properties)}`)
  }
},
```

The `event` Hook receives all events published by OpenCode's event bus (Chapter 11). You can distinguish event types via the `event.type` field, and `event.properties` contains the event's detailed data.

## 17.4.6 Advanced: Adding the experimental.chat.system.transform Hook

This experimental Hook allows you to modify the System Prompt sent to the LLM. For example, you can inject different behavioral instructions based on the current time:

```typescript
"experimental.chat.system.transform": async (input, output) => {
  const hour = new Date().getHours()

  if (hour >= 22 || hour < 6) {
    // Night mode: remind the AI to be more cautious
    output.system.push(
      "It is currently late at night. The user may be fatigued. Please ask for " +
      "extra confirmation before performing dangerous operations (such as deleting files " +
      "or modifying critical configurations). Keep responses concise and avoid lengthy explanations."
    )
  }
},
```

`output.system` is a string array that will ultimately be concatenated into the LLM's System Prompt. You can `push` new instruction paragraphs into it.

## 17.4.7 Publishing to npm

Once Plugin development is complete, you can publish it to npm so that other OpenCode users can use it:

```bash
# Make sure the name in package.json is globally unique
# Log in to npm
npm login

# Publish
npm publish
```

After publishing, users simply need to add the package name in `opencode.json`:

```json
{
  "plugin": ["opencode-plugin-guardian@0.1.0"]
}
```

OpenCode will automatically install and load it via `BunProc.install()`.

## 17.4.8 Key Takeaways

Through this lab, we mastered the following core concepts:

| Concept               | Corresponding Source Location           | Description                                            |
| --------------------- | --------------------------------------- | ------------------------------------------------------ |
| Plugin type interface | `packages/plugin/src/index.ts`          | `Plugin`, `PluginInput`, `Hooks` type definitions      |
| Tool definition API   | `packages/plugin/src/tool.ts`           | `tool()` function and Zod schema parameter definitions |
| Hook lifecycle        | `packages/opencode/src/plugin/index.ts` | Chained Hook invocation via the `trigger()` method     |
| Local loading         | `packages/opencode/src/plugin/index.ts` | `file://` protocol handling logic                      |
| npm loading           | `packages/opencode/src/bun/index.ts`    | `BunProc.install()` dynamic installation mechanism     |
| Message model         | `packages/plugin/src/index.ts`          | `output.parts` structure in `chat.message`             |

**Core principles of Plugin development**:

1. **Minimal intrusion**: Plugins extend behavior through Hooks rather than modifying OpenCode's core code.
2. **Fault tolerance first**: Errors in Hooks should never cause OpenCode to crash. Always wrap potentially failing operations in try-catch.
3. **Context awareness**: Obtain current project information through `PluginInput` rather than hardcoding paths. Use `ctx.directory` instead of `process.cwd()`.
4. **Inject on demand**: Do not inject large amounts of content into every message -- this wastes tokens. Inject selectively based on conditions such as `input.agent`.

In the next lab, we will go even further -- mimicking the core architecture of oh-my-opencode to implement a multi-Agent orchestration system.
