在日常开发中,总有一些操作需要反复执行——运行测试、检查代码覆盖率、审查最近提交、生成某种固定格式的组件。每次都要手动输入相同的 Prompt,不仅效率低下,还容易遗漏关键细节。
OpenCode 提供了自定义命令(Custom Commands)功能,允许你将常用的 Prompt 模板封装成一个 / 开头的快捷命令。只需在对话中输入 /test,就能跑完整测试;输入 /review,就能审查代码变更;输入 /component Button,就能生成指定组件。这篇文章将带你从零开始,掌握 OpenCode 自定义命令的全部玩法。
自定义命令本质上是一个预设的 Prompt 模板,当你在 OpenCode TUI 中输入 /命令名 时,OpenCode 会将模板内容发送给 LLM 执行。你可以在模板中定义固定指令、注入参数、嵌入 Shell 输出,甚至可以指定使用哪个 Agent 和模型来执行。
OpenCode 本身内置了一些命令(如 /init、/undo、/redo、/share、/help),自定义命令是对这些内置命令的补充——你甚至可以覆盖同名内置命令。
在项目根目录创建 .opencode/commands/ 目录,然后新建 .md 文件作为命令定义:
--- description: Run tests with coverage agent: build model: anthropic/claude-sonnet-4-20250514 --- Run the full test suite with coverage report and show any failures. Focus on the failing tests and suggest fixes.
文件名为 test.md,保存后即可在 TUI 中使用 /test 触发。
Markdown 文件的文件名自动成为命令名,Frontmatter 定义命令的元数据,正文内容就是发送给 LLM 的 Prompt 模板。
除了项目级的 .opencode/commands/,你还可以把命令放在全局目录 ~/.config/opencode/commands/ 下,这样所有项目都能共用。
在 opencode.jsonc 中直接定义命令:
{
"$schema": "https://opencode.ai/config.json",
"command": {
"test": {
"template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.",
"description": "Run tests with coverage",
"agent": "build",
"model": "anthropic/claude-sonnet-4-20250514"
}
}
}
两种方式效果完全一样,选择哪种取决于你的偏好——Markdown 文件方式更适合独立维护和团队共享,JSON 方式更适合集中管理少量命令。
自定义命令支持五个配置选项,下面逐一说明。
命令的核心——发送给 LLM 的 Prompt 内容。支持多行文本,换行符会保留。
--- description: Check types --- Run TypeScript type checking across the entire project. Report any type errors found, grouped by file. For each error, show the file path and line number.
命令的简短说明,在 TUI 中通过 / 键浏览命令列表时会显示。不指定则无描述信息。
指定执行该命令的 Agent。例如你有一个专门做代码审查的 review agent:
{
"command": {
"review": {
"template": "Review the following code...",
"agent": "review"
}
}
}
不指定则使用当前对话的 Agent。
设为 true 时,命令会强制以子 Agent(Subagent)的方式执行,不污染主会话的上下文。
{
"command": {
"analyze": {
"template": "Analyze the project structure...",
"subtask": true
}
}
}
即使 Agent 配置 mode 为 primary,设置 subtask: true 后也会强制以子 Agent 模式运行。对于大型分析任务,这是一个非常实用的选项。
覆盖默认模型,为特定命令指定专用模型。比如日常开发用便宜的模型,但代码审查用最强的:
{
"command": {
"review": {
"template": "Review the following code changes...",
"model": "anthropic/claude-sonnet-4-20250514"
}
}
}
自定义命令的 Prompt 模板支持三种特殊的占位符和语法,这让命令的灵活度大幅提升。
最常用的动态能力是在命令后附加参数,用 $ARGUMENTS 获取全部参数,或用 $1、$2、$3 获取位置参数。
使用 $ARGUMENTS:
--- description: Create a new React component --- Create a new React component named $ARGUMENTS with TypeScript support. Include proper typing, basic structure, and a default export.
使用时输入 /component Button,$ARGUMENTS 会被替换为 Button。
使用位置参数:
--- description: Create a new file with content --- Create a file named $1 in the directory $2 with the following content: $3
使用时输入 /create-file config.json src '{ "key": "value" }',OpenCode 会分别替换三个位置参数。
你可以混合使用 $ARGUMENTS 和位置参数,但要注意参数中如果包含空格,需要用引号包裹。
command在 Prompt 模板中使用 !command`` 语法,可以将 Shell 命令的输出直接注入 Prompt。这对于需要实时信息作为上下文的命令非常实用。
--- description: Analyze test coverage --- Here are the current test results: !`npm test` Based on these results, suggest improvements to increase coverage. Identify the files with the lowest coverage.
--- description: Review recent changes --- Recent git commits: !`git log --oneline -15` Git diff summary: !`git diff --stat HEAD~5` Review these changes and suggest any improvements. Check for: - Potential bugs - Missing tests - Code style issues
Shell 命令在项目根目录执行,输出会完整地成为 Prompt 的一部分。这个特性的强大之处在于,你不需要手动复制粘贴运行结果,命令会自动携带最新的上下文信息。
使用 @文件路径 可以在命令中直接引用项目文件的内容:
--- description: Review and refactor the component --- Review the component in @src/components/DataTable.tsx. Check for: 1. Performance issues (unnecessary re-renders, missing memoization) 2. Accessibility problems 3. Type safety concerns 4. Code duplication Suggest concrete fixes for each issue found.
文件引用会将该文件的完整内容注入 Prompt。如果你引用了多个文件,它们的内容都会被自动加载。
你还可以把文件引用和 Shell 注入结合使用:
--- description: Compare implementation with tests --- Implementation: @src/utils/formatters.ts Test file: !`find src -name "formatters.test.*" -type f | head -1` Compare the implementation with the test coverage. Are there any edge cases not covered by the tests?
下面给出几个真实开发场景中的命令配置。
适用于 Laravel 项目,根据表名自动生成 Model、Controller、Migration:
---
description: Generate a complete CRUD module for Laravel
agent: build
---
Generate a complete CRUD module for a `$ARGUMENTS` entity in this Laravel project.
Create the following files:
1. Migration: database/migrations/*_create_$ARGUMENTS_table.php
2. Model: app/Models/$ARGUMENTS.php (with proper fillable, casts, relations)
3. Controller: app/Http/Controllers/$ARGUMENTS_Controller.php (RESTful, with validation)
4. Form Request: app/Http/Requests/Store${ARGUMENTS}Request.php and Update${ARGUMENTS}Request.php
5. API Routes in routes/api.php
Follow the existing code style. Use dependency injection and type hints.
使用时:
/crud products
利用 Shell 注入自动获取待审查的变更:
--- description: Review staged changes before commit agent: plan --- Review the following staged changes before they are committed: Changed files: !`git diff --cached --name-only` Full diff: !`git diff --cached` Review checklist: 1. Are there any obvious bugs or logic errors? 2. Is error handling adequate? 3. Are there any security concerns (SQL injection, XSS, etc.)? 4. Is the code style consistent with the project? 5. Are there any missing edge cases? 6. Could anything be simplified or optimized? Provide a summary of findings with severity levels (high/medium/low).
自动检查过期的依赖并分析更新风险:
--- description: Check outdated dependencies and analyze update risks subtask: true --- Here are the outdated npm packages: !`npm outdated --json` Dependency graph: @package.json For each outdated package: 1. Check the latest version's breaking changes 2. Assess the risk level (high/medium/low) 3. Suggest whether to update now, plan for later, or skip Prioritize security-related updates.
--- description: Find and catalog technical debt in the codebase subtask: true --- Scan the codebase for common technical debt patterns: !`rg -n "TODO|FIXME|HACK|XXX|OPTIMIZE" --type-add 'all:*' -t all` For each finding, categorize it as: - **Bug risk**: Logic that might cause issues - **Performance**: Code that could be optimized - **Maintenance**: Code that's hard to understand or change - **Dependency**: Outdated patterns or libraries Create a prioritized backlog of the top 10 items to address.
自定义命令可以放在四个层级,后加载的会覆盖先加载的同名命令:
内置于二进制文件中的命令
用户全局配置目录:~/.config/opencode/commands/*.md(所有项目共享)
项目根目录:<project-root>/.opencode/commands/*.md(项目级)
当前工作目录:./.opencode/commands/*.md(更精细的控制)
在团队开发中,建议将通用的开发流程命令(如测试、代码审查)放在项目根目录的 .opencode/commands/ 中,提交到 Git 仓库。个人偏好的命令则放在全局 ~/.config/opencode/commands/ 中。
OpenCode 的自定义命令功能将重复性的 Prompt 工作封装为可复用的快捷入口,是提升日常开发效率的利器。三个核心能力值得反复使用:
配合 Agent 指定和子任务模式,你甚至可以打造一套完整的自动化开发流水线——从代码审查到测试分析,从模块生成到依赖管理,全部用 / 一个命令触发。开始整理你的常用工作流,把它们封装成命令吧。