create-opencode-plugin

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Creating OpenCode Plugins

开发OpenCode插件

<critical> Re-read this file periodically during plugin development to refresh context and ensure you're following the correct procedure. </critical> <workflow>
<critical> 在插件开发过程中,请定期重新阅读本文档,以刷新上下文并确保遵循正确的开发流程。 </critical> <workflow>

Procedure Overview

流程概述

StepActionRead
1Verify SDK referenceRun extract script
2Validate feasibilityThis file
3Design plugin
references/hooks.md
,
references/hook-patterns.md
,
references/CODING-TS.MD
4Implement
references/tool-helper.md
(if custom tools)
5Add UI feedback
references/toast-notifications.md
,
references/ui-feedback.md
(if needed)
6Test
references/testing.md
7Publish
references/publishing.md
,
references/update-notifications.md
(if npm)

步骤操作内容参考文档
1验证SDK参考文档运行提取脚本
2验证可行性本文档
3设计插件
references/hooks.md
references/hook-patterns.md
references/CODING-TS.MD
4实现插件
references/tool-helper.md
(如果开发自定义工具)
5添加UI反馈
references/toast-notifications.md
references/ui-feedback.md
(如有需要)
6测试插件
references/testing.md
7发布插件
references/publishing.md
references/update-notifications.md
(如果发布到npm)

Step 1: Verify SDK Reference (REQUIRED)

步骤1:验证SDK参考文档(必填)

Before creating any plugin, MUST regenerate the API reference to ensure accuracy:
bash
bun run .opencode/skill/create-opencode-plugin/scripts/extract-plugin-api.ts
This generates:
  • references/hooks.md
    - All available hooks and signatures
  • references/events.md
    - All event types and properties
  • references/tool-helper.md
    - Tool creation patterns

在创建任何插件之前,必须重新生成API参考文档以确保准确性:
bash
bun run .opencode/skill/create-opencode-plugin/scripts/extract-plugin-api.ts
此命令将生成以下文档:
  • references/hooks.md
    - 所有可用钩子及其签名
  • references/events.md
    - 所有事件类型及属性
  • references/tool-helper.md
    - 工具创建模式

Step 2: Validate Feasibility (REQUIRED)

步骤2:验证可行性(必填)

MUST determine if the user's concept is achievable with available hooks.
必须确定用户的需求是否可以通过现有钩子实现。

Feasible as plugins:

可通过插件实现的功能:

  • Intercepting/blocking tool calls
  • Reacting to events (file edits, session completion, etc.)
  • Adding custom tools for the LLM
  • Modifying LLM parameters (temperature, etc.)
  • Custom auth flows for providers
  • Customizing session compaction
  • Displaying status messages (toasts, inline)
  • 拦截/阻止工具调用
  • 响应事件(文件编辑、会话完成等)
  • 为LLM添加自定义工具
  • 修改LLM参数(如temperature等)
  • 为提供程序实现自定义身份验证流程
  • 自定义会话压缩
  • 显示状态消息(提示弹窗、内联消息)

NOT feasible (inform user):

无法通过插件实现的功能(需告知用户):

  • Modifying TUI rendering or layout
  • Adding new built-in tools (requires OC source)
  • Changing core agent behavior/prompts
  • Intercepting assistant responses mid-stream
  • Adding new keybinds or commands
  • Modifying internal file read/write
  • Adding new permission types
If not feasible, MUST inform user clearly. Suggest:
  • OC core changes: contribute to
    packages/opencode
  • MCP tools: use MCP server configuration
  • Simple automation: use shell scripts

  • 修改TUI渲染或布局
  • 添加新的内置工具(需要修改OpenCode核心源码)
  • 更改核心Agent行为/提示词
  • 中途拦截助手响应
  • 添加新的快捷键或命令
  • 修改内部文件读写操作
  • 添加新的权限类型
如果需求无法实现,必须清晰告知用户。可建议:
  • OpenCode核心修改:向
    packages/opencode
    提交贡献
  • MCP工具:使用MCP服务器配置
  • 简单自动化:使用Shell脚本

Step 3: Design Plugin

步骤3:设计插件

READ:
references/hooks.md
for available hooks,
references/hook-patterns.md
for implementation patterns.
READ:
references/CODING-TS.MD
for code architecture principles. MUST follow these design guidelines:
  • Modular structure: Split complex plugins into multiple focused files (types, utilities, hooks, tools)
  • Single purpose: Each function does ONE thing well
  • DRY: Extract common patterns into shared utilities immediately
  • Small files: Keep individual files under 150 lines - split into smaller modules as needed
  • No monoliths: MUST NOT put all plugin code in a single
    index.ts
    file
必读
references/hooks.md
查看可用钩子,
references/hook-patterns.md
查看实现模式。
必读
references/CODING-TS.MD
查看代码架构原则。必须遵循以下设计准则:
  • 模块化结构:将复杂插件拆分为多个专注的文件(类型定义、工具函数、钩子实现、工具定义)
  • 单一职责:每个函数仅做好一件事
  • DRY原则:立即将通用模式提取为共享工具函数
  • 小文件:单个文件代码量控制在150行以内 - 随着复杂度增加,拆分为更小的模块
  • 避免单体化:禁止将所有插件代码放入单个
    index.ts
    文件

Plugin Locations

插件存放位置

ScopePathUse Case
Project
.opencode/plugin/<name>/index.ts
Team-shared, repo-specific
Global
~/.config/opencode/plugin/<name>/index.ts
Personal, all projects
作用范围路径使用场景
项目级
.opencode/plugin/<name>/index.ts
团队共享、特定仓库使用
全局级
~/.config/opencode/plugin/<name>/index.ts
个人使用、所有项目通用

Basic Structure

基础结构

typescript
import type { Plugin } from "@opencode-ai/plugin"

export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => {
  // Setup code runs once on load

  return {
    // Hook implementations - see references/hook-patterns.md
  }
}
typescript
import type { Plugin } from "@opencode-ai/plugin"

export const MyPlugin: Plugin = async ({ project, client, $, directory, worktree }) => {
  // 初始化代码仅在加载时运行一次

  return {
    // 钩子实现 - 参考references/hook-patterns.md
  }
}

Context Parameters

上下文参数

ParameterTypeDescription
project
Project
Current project info (id, worktree, name)
client
SDK ClientOpenCode API client
$
BunShell
Bun shell for commands
directory
string
Current working directory
worktree
string
Git worktree path

参数名类型描述
project
Project
当前项目信息(ID、工作树、名称)
client
SDK客户端OpenCode API客户端
$
BunShell
用于执行命令的Bun Shell
directory
string
当前工作目录
worktree
string
Git工作树路径

Step 4: Implement

步骤4:实现插件

READ:
references/hook-patterns.md
for hook implementation examples.
READ:
references/tool-helper.md
if adding custom tools (Zod schemas).
READ:
references/events.md
if using event hook (event types/properties).
READ:
references/examples.md
for complete plugin examples.
ALWAYS READ:
references/CODING-TS.MD
and follow modular design principles.
必读
references/hook-patterns.md
查看钩子实现示例。
必读:如果添加自定义工具,请查看
references/tool-helper.md
(Zod架构)。
必读:如果使用事件钩子,请查看
references/events.md
(事件类型/属性)。
必读
references/examples.md
查看完整插件示例。
始终必读
references/CODING-TS.MD
并遵循模块化设计原则。

Plugin Structure (Non-Monolithic)

插件结构(非单体化)

For complex plugins, MUST use a modular directory structure:
.opencode/plugin/my-plugin/
├── index.ts          # Entry point, exports Plugin
├── types.ts          # TypeScript types/interfaces
├── utils.ts          # Shared utilities
├── hooks/            # Hook implementations
│   ├── event.ts
│   └── tool-execute.ts
└── tools/            # Custom tool definitions
    └── my-tool.ts
Example modular index.ts:
typescript
import type { Plugin } from "@opencode-ai/plugin"
import { eventHooks } from "./hooks/event"
import { toolHooks } from "./hooks/tool-execute"
import { customTools } from "./tools"

export const MyPlugin: Plugin = async ({ project, client }) => {
  return {
    ...eventHooks({ client }),
    ...toolHooks({ client }),
    tool: customTools,
  }
}
Keep each file under 150 lines. Split as complexity grows.
对于复杂插件,必须使用模块化目录结构:
.opencode/plugin/my-plugin/
├── index.ts          # 入口文件,导出Plugin
├── types.ts          # TypeScript类型/接口定义
├── utils.ts          # 共享工具函数
├── hooks/            # 钩子实现
│   ├── event.ts
│   └── tool-execute.ts
└── tools/            # 自定义工具定义
    └── my-tool.ts
模块化index.ts示例
typescript
import type { Plugin } from "@opencode-ai/plugin"
import { eventHooks } from "./hooks/event"
import { toolHooks } from "./hooks/tool-execute"
import { customTools } from "./tools"

export const MyPlugin: Plugin = async ({ project, client }) => {
  return {
    ...eventHooks({ client }),
    ...toolHooks({ client }),
    tool: customTools,
  }
}
保持每个文件代码量在150行以内。随着复杂度增加,及时拆分模块。

Common Mistakes

常见错误

MistakeFix
Using
client.registerTool()
Use
tool: { name: tool({...}) }
Wrong event property namesCheck
references/events.md
Sync event handlerMUST use
async
Not throwing to block
throw new Error()
in
tool.execute.before
Forgetting TypeScript types
import type { Plugin } from "@opencode-ai/plugin"

错误内容修复方案
使用
client.registerTool()
改用
tool: { name: tool({...}) }
事件属性名称错误查看
references/events.md
确认
使用同步事件处理器必须使用
async
异步函数
未通过抛出错误实现拦截
tool.execute.before
中使用
throw new Error()
抛出错误
忘记添加TypeScript类型定义导入
import type { Plugin } from "@opencode-ai/plugin"

Step 5: Add UI Feedback (Optional)

步骤5:添加UI反馈(可选)

Only if plugin needs user-visible notifications:
READ:
references/toast-notifications.md
for transient alerts (brief popups)
READ:
references/ui-feedback.md
for persistent inline status messages
Choose based on:
NeedUse
Brief alerts, warningsToast
Detailed stats, multi-lineInline message
Config validation errorsToast
Session completion noticeToast or inline

仅当插件需要向用户显示通知时执行此步骤:
必读
references/toast-notifications.md
查看临时提示弹窗(短暂弹出)的实现
必读
references/ui-feedback.md
查看持久化内联状态消息的实现
根据需求选择合适的方式:
需求推荐使用方式
简短提醒、警告提示弹窗(Toast)
详细统计、多行消息内联消息
配置验证错误提示弹窗(Toast)
会话完成通知提示弹窗或内联消息

Step 6: Test

步骤6:测试插件

READ:
references/testing.md
for full testing procedure.
必读
references/testing.md
查看完整测试流程。

Quick Test Steps

快速测试步骤

  1. Create test folder with
    opencode.json
    :
    jsonc
    {
      "plugin": ["file:///path/to/your/plugin/index.ts"],
    }
  2. Verify plugin loads:
    bash
    cd /path/to/test-folder
    opencode run hi
  3. Test interactively:
    bash
    opencode
  4. SHOULD recommend specific tests based on hook type used.

  1. 创建测试文件夹并添加
    opencode.json
    文件:
    jsonc
    {
      "plugin": ["file:///path/to/your/plugin/index.ts"],
    }
  2. 验证插件是否加载成功:
    bash
    cd /path/to/test-folder
    opencode run hi
  3. 交互式测试:
    bash
    opencode
  4. 应根据使用的钩子类型推荐特定的测试方法。

Step 7: Publish (Optional)

步骤7:发布插件(可选)

READ:
references/publishing.md
for npm publishing.
READ:
references/update-notifications.md
for version update toasts (for users with pinned versions).
</workflow>
<reference_summary>
必读
references/publishing.md
查看npm发布流程。
必读
references/update-notifications.md
查看版本更新提示弹窗的实现(针对固定版本的用户)。
</workflow>
<reference_summary>

Reference Files Summary

参考文档汇总

FilePurposeWhen to Read
hooks.md
Hook signatures (auto-generated)Step 3-4
events.md
Event types (auto-generated)Step 4 (if using events)
tool-helper.md
Zod tool schemas (auto-generated)Step 4 (if custom tools)
hook-patterns.md
Hook implementation examplesStep 3-4
CODING-TS.MD
Code architecture principlesStep 3 (Design)
examples.md
Complete plugin examplesStep 4
toast-notifications.md
Toast popup APIStep 5 (if toasts needed)
ui-feedback.md
Inline message APIStep 5 (if inline needed)
testing.md
Testing procedureStep 6
publishing.md
npm publishingStep 7
update-notifications.md
Version toast patternStep 7 (for npm plugins)
</reference_summary>
文档名称用途阅读时机
hooks.md
钩子签名(自动生成)步骤3-4
events.md
事件类型(自动生成)步骤4(如果使用事件)
tool-helper.md
Zod工具架构(自动生成)步骤4(如果开发自定义工具)
hook-patterns.md
钩子实现示例步骤3-4
CODING-TS.MD
代码架构原则步骤3(设计阶段)
examples.md
完整插件示例步骤4
toast-notifications.md
提示弹窗API步骤5(如果需要弹窗)
ui-feedback.md
内联消息API步骤5(如果需要内联消息)
testing.md
测试流程步骤6
publishing.md
npm发布流程步骤7
update-notifications.md
版本提示弹窗模式步骤7(针对npm插件)
</reference_summary>