OpenCode 是一个开源的 AI 编码助手。它可以在你的终端、桌面应用或 IDE 中运行,读取你的代码库、理解项目结构、编写代码、执行命令。
选择 OpenCode 作为我的 AI 编码助手的原因:
所以这里记录一下 OpenCode 的一些使用笔记。
可以根据自己的系统,选择合适的命令安装。
# curl
$ curl -fsSL https://opencode.ai/install | bash
# npm
$ npm i -g opencode-ai
# bun
$ bun add -g opencode-ai
# brew
$ brew install anomalyco/tap/opencode
# paru
paru -S opencode
除了 CLI 形式,OpenCode 也提供了客户端安装包,可以在这里下载。
安装完成后,通过 opencode 可以在当前目录启动 opencode 的 TUI。
$ opencode
以下大部分命令都是在 opencode TUI 中输入的,除非必要说明。
1、LLM Provider
/connect
输入 /connect 后会弹出配置 LLM Provider 的界面,配置你购买的 Key 即可。
2、LLM
配置 Provider 后,可以选择 AI 模型
/models
选择合适的模型后,就可以愉快的进行 AI Coding 了。
/init #初始化项目,该命令会在项目根目录下创建 AGENTS.md,这个文件是给 opencode 阅读的。会包含一些项目的基础信息,例如使用的编程语言,框架等等。你也可以编辑这个文件增加信息,内容越详细,AI 完成任务越出色。
OpenCode 有两个基础的 agent:Build 和 Plan。通过 <tab> 可以切换 agent。
我的工作流:
通过 @ 符号可以引用某个文件
How is authentication handled in @packages/api/src/auth/index.ts?
TUI 可以输入图片,你可以将图片拖入到输入行中,帮助描述你的问题。
使用场景:
/undo 和 /redo #支持 undo、redo 操作。
/undo
/redo
/share #可以通过 /share 命令将当前会话创建未一个分享链接。
/sessions #可以查看会话历史,继续之前的会话。
打开 opencode 时,可以通过 --continue 参数,继续上次会话。
$ opencode --continue
# or
$ opencode -c
也可以通过 session id 指定打开某个会话
$ opencode --session ses_abc123
opencode.json #opencode 的有三个级别的配置文件。
~/.config/opencode/opencode.json):个人用户配置project/opencode.json): 项目根目录下的配置公司可以先设置一套基础配置作为默认值,开发者个人可以在此基础上根据自己的偏好做覆盖,而具体项目还可以在个人配置之上再做进一步的定制。
{
"$schema": "https://opencode.ai/config.json",
"model": "synthetic/hf:moonshotai/Kimi-K2.5",
"small_model": "synthetic/hf:MiniMaxAI/MiniMax-M2.1"
}
model 是你的主力模型,用来处理主要工作负载;而 small_model 负责一些轻量级任务,比如生成会话标题这类小活。
model ID 的格式 provider/model-id。
opencode 默认允许所有操作(编辑文件,执行命令),可以通过配置文件控制权限:
{
"$schema": "https://opencode.ai/config.json",
"permission": {
"edit": "ask",
"bash": "ask"
}
}
权限可选值:
还可以对 bash 命令做更细粒度的权限配置:
{
"permission": {
"bash": {
"*": "ask",
"git status": "allow",
"git diff": "allow",
"rm -rf *": "deny"
}
}
}
除了 AGENTS.md,还可以指定其他的说明文档。
{
"$schema": "https://opencode.ai/config.json",
"instructions": [
"CONTRIBUTING.md",
"docs/coding-guidelines.md",
".cursor/rules/*.md",
"https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"
]
}
opencode 有三种扩展机制:commands, skills, agents。
Commands are what to do. Skills are how to do it. Agents are who does it.
命令就是预先定义好的一段提示语,你用 / 来触发它。这样你就不用每次都重复输入同样的说明,而是创建一次命令,以后反复调用就行。
commands 存储在 .opencode/commands 目录中,例如创建一个 test command,创建 .opencode/commands/test.md:
---
description: Run tests with coverage
agent: build
---
Run the full test suite with coverage report.
Focus on failing tests and suggest fixes.
command 是一个包含 YAML 头的 markdown 文件。description 用于说明这个 command 是干什么的,agent 指定这个命令将会在哪种模式(agent)下执行,YAML 头下方文字用于指示 AI 工作。
创建完成后,可以在 TUI 输入 /test 执行这个命令。
支持 $ARGUMENTS 和占位符($1,$2)指定参数
例如:
---
description: Create a new component
---
Create a new React component named $ARGUMENTS with TypeScript.
Include proper typing and basic structure.
执行命令:/component Button。
---
description: Review recent changes
---
Recent git commits:
!`git log --oneline -10`
Review these changes and suggest improvements.
---
description: Review this file
---
Review the code in @src/components/Button.tsx.
Check for performance issues.
skills 可以看作是给 AI 的 wiki,指导 AI 怎么做。opencode 会在需要的时候按需加载这些 skills,而不是每次手动执行这些 skills。
哪些东西可以作为 skills:
创建 .opencode/skills/git-release/SKILL.md:
---
name: git-release
description: Create consistent releases and changelogs
---
## What I do
- Draft release notes from merged PRs
- Propose a version bump
- Provide a copy-pasteable `gh release create` command
## When to use me
Use this when preparing a tagged release.
Ask clarifying questions if versioning scheme is unclear.
## Process
1. Run `git log --oneline $(git describe --tags --abbrev=0)..HEAD`
2. Categorise commits (features, fixes, chores)
3. Determine version bump (major/minor/patch)
4. Generate changelog entry
5. Output the release command
/skills 会显示当前可用的 skills,opencode 会在需要的时候自动加载这些 skills。
在配置文件中,可以设置 agent 可以使用的 skills。
{
[...]
"permission": {
"skill": {
"*": "allow",
"internal-*": "deny",
"experimental-*": "ask"
}
}
}
Agents 是可配置的 AI 助手。它们可以拥有不同的 models、permissions、prompts 和 tool。例如 Build Agent 和 Plan Agent。
什么时候使用 Agent:
内置的 agents:
创建 .opencode/agents/reviewer.md:
---
description: Reviews code for quality and security
mode: subagent
temperature: 0.1
tools:
write: false
edit: false
bash: false
---
You are a code reviewer. Focus on:
- Security vulnerabilities
- Performance issues
- Maintainability concerns
- Test coverage gaps
Provide constructive feedback without making changes.
通过 Tab 可以切换 Primary agents。通过输入 @ 可以使用 subagents,例如:
@reviewer Check the authentication module
插件用于挂载在 OpenCode 的 Agent 生命周期上,在特定时机自动执行自定义逻辑。
可以在 .opencode/plugins(项目级)和 ~/.config/opencode/plugins(全局)中添加。还可以在 opencode.json 的 plugin 字段中指定 npm 包,加载插件。
opencode 的插件用 ts 编写,对于前端开发者十分友好。
例如,创建,.opencode/plugins/post-turn-check.ts:
import { promises as fs } from "node:fs";
import type { Plugin } from "@opencode-ai/plugin";
let hasEdited = false;
const cooldownMs = 15_000;
let lastRunAt = 0;
export const PostTurnCheck: Plugin = async ({ client, $ }) => {
return {
"tool.execute.after": async (input) => {
const editTools = [
"write",
"edit",
"replace_content",
"create_text_file",
];
if (editTools.includes(input.tool)) {
hasEdited = true;
}
},
event: async ({ event }) => {
if (event.type !== "session.idle") return;
if (!hasEdited) return;
const now = Date.now();
if (now - lastRunAt < cooldownMs) return;
lastRunAt = now;
hasEdited = false;
// Run Biome and capture output
const outputFile = `/tmp/opencode-check-${Date.now()}.log`;
await $`sh -c ${"pnpm run check > " + outputFile + " 2>&1 || true"}`;
const output = await fs.readFile(outputFile, "utf8").catch(() => "");
const message = `
Post-turn lint check completed.
--- BEGIN BIOME OUTPUT ---
${output || "No issues found."}
--- END BIOME OUTPUT ---
If there are errors, fix them. If something's unclear, ask.
`.trim();
const sessionID = event.properties.sessionID;
if (sessionID) {
await client.session.prompt({
path: { id: sessionID },
body: {
parts: [{ type: "text", text: message }],
},
});
}
},
};
};
同时需要在 .opencode/package.json 中添加 plugin 依赖:
{
[...]
"dependencies": {
"@opencode-ai/plugin": "^1.1.13"
}
}
opencode 在启动时,会自动安装依赖包。
上面的自定义插件作用是:当 Agent 修改完文件后,会自动运行 Biome,并把错误结果返回去,让 Agent 自动修复。
opencode 可以添加 mcp,在 opencode.json 中指定:
{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"firecrawl": {
"type": "local",
"command": ["npx", "-y", "firecrawl-mcp"],
"enabled": true
}
}
}
或者添加一个远程 mcp server:
{
"mcp": {
"my-server": {
"type": "remote",
"url": "https://my-mcp-server.example.com/mcp",
"enabled": true
}
}
}
(完)