> 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_13_plugin_system/13.3_plugin_loading_mechanism.md). Agents can also search and read this documentation through its [MCP server](https://www.opencodebook.xyz/~gitbook/mcp).

# 13.3 Plugin Loading Mechanism

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

***

No matter how elegantly a Plugin is defined, it remains merely ink on paper if it cannot be correctly loaded and initialized. This section explains how OpenCode discovers, installs, and loads Plugins.

## 13.3.1 Built-in Plugins

OpenCode ships with three built-in authentication Plugins that are loaded via direct `import` statements, bypassing the npm installation process:

```typescript
// plugin/index.ts
import { CodexAuthPlugin } from "./codex"
import { CopilotAuthPlugin } from "./copilot"
import { gitlabAuthPlugin as GitlabAuthPlugin } from "@gitlab/opencode-gitlab-auth"

const INTERNAL_PLUGINS: PluginInstance[] = [
  CodexAuthPlugin,
  CopilotAuthPlugin,
  GitlabAuthPlugin,
]
```

| Plugin              | Function                                                     |
| ------------------- | ------------------------------------------------------------ |
| `CodexAuthPlugin`   | Provides OAuth authentication for OpenAI's Codex API         |
| `CopilotAuthPlugin` | Provides Device Flow OAuth authentication for GitHub Copilot |
| `GitlabAuthPlugin`  | Provides OAuth authentication for GitLab AI                  |

Additionally, there is a built-in npm Plugin (`opencode-anthropic-auth`) that is loaded through the npm installation process.

## 13.3.2 Plugin Loading Flow

The complete Plugin loading flow is implemented in the initialization function of `Instance.state()`:

```typescript
const state = Instance.state(async () => {
  const hooks: Hooks[] = []
  const input: PluginInput = { /* construct context */ }

  // Step 1: Load internal Plugins
  for (const plugin of INTERNAL_PLUGINS) {
    const init = await plugin(input)
    hooks.push(init)
  }

  // Step 2: Load Plugins declared in configuration
  let plugins = config.plugin ?? []
  if (plugins.length) await Config.waitForDependencies()
  if (!Flag.OPENCODE_DISABLE_DEFAULT_PLUGINS) {
    plugins = [...BUILTIN, ...plugins]
  }

  for (let plugin of plugins) {
    // Skip legacy Plugins that are now built-in
    if (plugin.includes("opencode-openai-codex-auth")) continue
    if (plugin.includes("opencode-copilot-auth")) continue

    if (!plugin.startsWith("file://")) {
      // npm package Plugin: install dynamically
      const pkg = /* parse package name */
      const version = /* parse version number */
      plugin = await BunProc.install(pkg, version)
    }

    // Dynamically import the Plugin module
    const mod = await import(plugin)

    // Deduplication (prevent the same function from being initialized
    // as both a named export and a default export)
    const seen = new Set<PluginInstance>()
    for (const [_name, fn] of Object.entries(mod)) {
      if (seen.has(fn)) continue
      seen.add(fn)
      const init = await fn(input)
      hooks.push(init)
    }
  }

  return { hooks, input }
})
```

### npm Package Plugins

When a Plugin string does not start with `file://`, OpenCode treats it as an npm package and installs it dynamically via `BunProc.install()`:

```typescript
// Parse "my-plugin@1.0.0" -> pkg="my-plugin", version="1.0.0"
const lastAtIndex = plugin.lastIndexOf("@")
const pkg = lastAtIndex > 0 ? plugin.substring(0, lastAtIndex) : plugin
const version = lastAtIndex > 0 ? plugin.substring(lastAtIndex + 1) : "latest"

// Install to global cache using Bun
plugin = await BunProc.install(pkg, version)
```

`BunProc.install()` uses `bun install` to install the package into OpenCode's data directory, returns the installed module path, and then loads it dynamically via `import()`.

### Local File Plugins

Plugins prefixed with `file://` are loaded directly from the local filesystem:

```json
{
  "plugin": [
    "file:///path/to/my-plugin.ts"
  ]
}
```

This approach is primarily used for Plugin development and debugging -- developers do not need to publish their Plugin to npm in order to test it.

### Deduplication

A Plugin module may simultaneously export a named export and a default export that point to the same function:

```typescript
export const myPlugin: Plugin = async (ctx) => { /* ... */ }
export default myPlugin  // Same reference as above
```

Without deduplication, `Object.entries(mod)` would return two entries (`myPlugin` and `default`), causing the Plugin to be initialized twice. The `seen` Set avoids this problem through reference comparison (`has(fn)`).

## 13.3.3 Error Handling

Errors during the Plugin loading process are carefully handled to ensure that a single Plugin's failure does not bring down the entire system:

```typescript
plugin = await BunProc.install(pkg, version).catch((err) => {
  if (!builtin) throw err  // Installation failure for non-built-in Plugins is fatal

  // Built-in Plugin installation failure only logs a warning
  log.error("failed to install builtin plugin", { pkg, version, error: message })
  Bus.publish(Session.Event.Error, {
    error: new NamedError.Unknown({
      message: `Failed to install built-in plugin ${pkg}@${version}: ${message}`,
    }).toObject(),
  })
  return ""  // Return empty string; will be skipped later
})
if (!plugin) continue  // Skip Plugins that failed to install
```

For built-in Plugins, an installation failure emits an error event and continues loading other Plugins. For user-configured Plugins, an installation failure throws an error, since the user explicitly declared a dependency on that Plugin.

## 13.3.4 Plugin Initialization

After loading is complete, `Plugin.init()` performs two initialization operations:

```typescript
export async function init() {
  const hooks = await state().then((x) => x.hooks)
  const config = await Config.get()

  // 1. Call each Plugin's config hook
  for (const hook of hooks) {
    await hook.config?.(config)
  }

  // 2. Forward Bus events to Plugin event hooks
  Bus.subscribeAll(async (input) => {
    const hooks = await state().then((x) => x.hooks)
    for (const hook of hooks) {
      hook["event"]?.({ event: input })
    }
  })
}
```

## 13.3.5 Summary

The Plugin loading mechanism supports three sources, listed in loading order:

| Source              | Loading Method                           | Typical Use Case                |
| ------------------- | ---------------------------------------- | ------------------------------- |
| Internal Plugins    | Direct `import`                          | Built-in authentication support |
| npm Package Plugins | `BunProc.install()` + dynamic `import()` | Community ecosystem             |
| Local File Plugins  | Direct `import("file://...")`            | Development and debugging       |

The reliability of the loading process is ensured by the following mechanisms:

1. **Graceful degradation**: The system continues running when a built-in Plugin fails to install.
2. **Deduplication**: Prevents the same Plugin from being initialized twice.
3. **Legacy skipping**: Plugins that have been superseded by built-in replacements are automatically skipped.
4. **Environment toggle**: `OPENCODE_DISABLE_DEFAULT_PLUGINS` can disable built-in Plugins.
