OpenCode 学习
OpenCode 是一个开源 AI 编程助手. 提供 terminal-based interface, desktop app, IDE 扩展三种使用方式.
Intro
- npm 安装
npm install -g opencode-ai --registry https://registry.npmjs.org
-
/init会为项目初始化 OpenCode. 在项目根目录生成AGENTS.md -
tab键可以切换 Agent
plan只读模式,只做分析和规划, 不会修改代码build默认, 全权限,可以读写文件,执 行命令
-
undo可以撤销修改./redo重新执行这些修改. -
/share将对话内容分享给团队成员.
Config
OpenCode 配置支持 json 和 jsonc 格式.(jsonc 格式支持注释)
文件的优先级(从低到高)
- 远程配置
.well-known/open - 全局配置
~/.config/opencode/.opencode.json - 自定义配置
OPENCODE_CONFIG环境变量指定.opencode.json的路径, 如:export OPENCODE_CONFIG=/path/to/my/custom-config.json - 项目专属配置 项目根目录
.opencode.json - 代理, 命令, 插件
.opencode目录 - 运行时覆盖,
OPENCODE_CONFIG_CONTENT环境变量OPENCODE_CONFIG_DIR自定义.opencode配置目录
Provider
/connect 选择供应商
/models 查看模型
可以通过设置 .opencode.json 的 baseURL 来设置代理服务
Nerwork
export HTTPS_PROXY=https://proxy.example.com:8080
export HTTP_PROXY=http://proxy.example.com:8080
export NO_PROXY=localhost,127.0.0.1
TUI
termial user interface 终端用户界面
opencode启动终端用户界面
opencode /path/to/project指定工作目录启动
-
通过
@来引用文件, 文件内容会自动添加到对话中. -
通过
!来运行Shell命令, 如!ls -la, 结果会输出到对话中. -
通过
/来执行快速操作, 如/connect,/models,/help等 -
/compact压缩当前会话. 别名:/summarize -
/details切换工具执行详情. 这个目前使用没有效果, 不知道是什么问题. // TODO -
/editor打开外部编辑器. -
/exit,/quit,/q退出 -
/export导出会话 -
/help, 快捷键ctrp + p -
/init创建和跟新AGENTS.md -
/models -
/clear,/new开启一个新会话 -
/redo,/undo -
/sessions,/resume,/continue列出并切换会话 -
/share分享会话,/unshare取消分享
CLI
opencode [projet]启动 opencode 的 TUI
opencode -c继续上次会话
opencode agent [command]
opencode agent create创建一个带有自定义系统提示和工具配置的全新智能体。opencode agent list列出所有 Agent
-
opencode attach -
opencode auth [command]
opencode auth loginopencode auth listopencode auth lsopencode auth logout
opencode github [command]
opencode github installInstall the GitHub agentopencode github run--event--tokenGitHub 令牌
opencode mcp [command]
opencode mcp addopencode mcp listopencode mcp auth [name]opencode mcp auth listopencode mcp auth lsopencode mcp logout [name]opencode mcp debug <name>
opencode modles [provider]
--refresh--verbose
opencode run [messages..]直接传入提示词, 即可在非交互模式下运行 opencode
opencode run 输出1+1的结果
-
opencode serve启动无界面的 OpenCode 服务器以通过 API 访问--port--hostname--mdns--cros
-
opencode session [command]列出 Opencode 的所有会话
opencode session list-n显示最近 n 个会话--format格式化输出(table or json)
-
opencode stats统计信息--days--tools--models--project
-
opencode export [sessionID] -
opencode import <file>导入会话数据
opencode import session.jsonopencode import https://opncd.ai/s/abc123
opencode webopencode acpopencode uninstallopencode upgrade升级
GitHub
Use OpenCode in GitHub issues and pull-requests.
Features
- triage issue
- fix and implement
- secure
tools
opencode 内置一组 tools, 你可以通过 custom tools or MCP servers 进行扩展.
默认情况下所有 tools 都是启用的无需任何权限即可运行. 通过 permissions 来调整权限.
built-in tools
bash在项目环境中执行 Shell 命令npm installgit status
edit通过精确字符串替换来修改现有文件.write创建新文件和覆盖现有文件 -read读代码库内容grep使用正则表达式搜索文件内容glob通过模式匹配查找文件。listlsppatchskill加载一个技能(一个 SKILL.md 文件),并在对话中返回其内容。todowritetodoreadwebfetch
Rules
可以通过创建一个 AGENTS.md 文件来为 opencode 提供自定义指令.
/init 会扫描当前项目的所有内容, 并生成一个 AGENTS.md 文件.
自定义指令可以通过编辑 .opencode.json 来实现.
{
"$schema": "https://opencode.ai/config.json",
"instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]
}
CONTRIBUTING.md, docs/guidelines.md, .cursor/rules/\*.md 会与 AGENTS.md 文件进行合并.
在 AGENTS.md 中添加明确指令的优势
- 创建模块化, 可复用的规则文件. Create modular, reusable rule files
- 通过符号链接或 git 子模块跨项目共享规则. Share rules across projects via symlinks or git submodules
- 保持 AGENTS.md 简洁明了,同时引用详细指南. Keep AGENTS.md concise while referencing detailed guidelines
- 确保 opencode 仅在特定任务需要时加载文件. Ensure opencode loads files only when needed for the specific task
Agents
智能体是专为特定任务和工作流定制的 AI 助手,支持通过自定义提示词、模型和工具访问权限来打造专属工具。 Agents are specialized AI assistants that can be configured for specific tasks and workflows. They allow you to create focused tools with custom prompts, models, and tool access.
OpenCode 有 2 中 agents
primary agents这些助手负责处理您的主要对话,并能访问所有已配置的工具。- opencode 内置了
plan和build2 个 primary agents
- opencode 内置了
subagents子代理是主代理可调用的专业助手,用于执行特定任务。您也可以通过@提及的方式在消息中手动调用它们。- opencode 内置了
General和Explore2 个 subagents.General用于研究复杂问题, 搜索代码以及执行多步骤任务.Explore一个专为探索代码库而设计的快速智能体。当你需要按模式快速查找文件、搜索代码中的关键词,或回答关于代码库的问题时,请使用它
- opencode 内置了
primary agents 之间的切换使用 tab 键
subagents 的调用使用 @ 符号, 如 @general help me search for this function
有 2 中方法可以自定义 agent
-
在
.opencode.json中定义"build": {
"mode": "primary",
"model": "anthropic/claude-sonnet-4-20250514",
"prompt": "{file:./prompts/build.txt}",
"tools": {
"write": true,
"edit": true,
"bash": true
}
}, -
通过 markdown 文件定义, 需要放在
.opencode/agent/文件夹下面---
description: Reviews code for quality and best practices
mode: subagent
model: anthropic/claude-sonnet-4-20250514
temperature: 0.1
tools:
write: false
edit: false
bash: false
permission:
edit: deny
bash:
"*": ask
"git diff": allow
"git log*": allow
"git push": ask
webfetch: deny
---
You are in code review mode. Focus on:
- Code quality and best practices
- Potential bugs and edge cases
- Performance implications
- Security considerations
Provide constructive feedback without making direct changes.
descriptionAgent 的描述信息, 必填temperature数值越低,回答越专注且可预测;数值越高,则创造性与多样性越强。 (在 0.0~1.0 之间取值)maxSteps最大迭代次数. ( 希望控制成本的用户可以为 agents 设置一个上限.) 如果未设置,会一直迭代直到用户手动终止或 agent 任务可以返回为止.disable是否禁用prompt提示词model需要使用provider/model-id格式toolspermission, 可选项有ask,allow,denymode设置 agent 的类型, 是 primary agents 还是 subagentshide@提示中隐藏此 agentpermission.task控制代理可调用的子代理任务工具。采用通配符模式实现灵活匹配。- Additional, opencode 允许添加一些其他选项作为模型传输传递给 provider
OpenCode 提供了 2 个可能有用的智能体 https://opencode.ai/docs/agents/#examples
Models
/models 选择模型
在 .opencode.json 通过 model 字段设置默认 model
Variants
许多模型都支持多种配置变体.
Built-in variants
- Anthropic
- high
- max
- OpenAI
- none
- minial
- low
- medium
- high
- xhigh
- Google
- low
- high
Themes
使用内置主题即可
Keybinds
opencode 的 leader key 默认是 ctrl + x 需要先按 leader key 在按快捷键.
https://opencode.ai/docs/keybinds/#desktop-prompt-shortcuts
Commands
为重复性任务创建自定义命令, 如 init, undo, redo, share, help 等
opencode 有 2 种方法自定义 command
-
.opencode.json的 command 字段 -
opencode/command文件夹下的 md 文件---
description: Run tests with coverage
agent: build
model: anthropic/claude-3-5-sonnet-20241022
---
Run the full test suite with coverage report and show any failures.
Focus on the failing tests and suggest fixes. -
通过
/来执行 command -
通过
$ARGUMENTS来传参. 多个参数时使用$1,$2,$3... -
在 prompt 中通过 !`shell` (shell 命令使用反引号包裹起来)来注入 shell 执行结果
- !`git log --oneline -10`
-
在 prompt 中通过
@来引用文件@src/components/Button.tsx
-
Options
template发送给 LLM 的 promptdescription描述agent使用那个 agent 来执行subtask子任务, 触发 subagent 调用model
Formatters
opencode 会在文件被写入或编辑后, 自动使用格式化工具格式化代码
Permissions
opencode 可以控制哪些操作需要经过审批才能运行.
MCP servers
Model Context Protocol 模型上下文协议
当使用一个 MCP servers 时,它会增加上下文内容. 如果使用很多的 MCP servers 会使上下文迅速积累, 因此 慎重选择要使用的 MCP.
Agent Skills
Custom Tools
tools: 可供 LLM 在 opencode 中调用的工具(函数)
-
放在
opencode/tool/文件夹下, tool 名就是文件名 -
structure, 最简单的方法是使用
tool()辅助函数, 他提供了类型安全和额验证功能.
import { tool } from "@opencode-ai/plugin"
export default tool({
description: "Query the project database",
args: {
query: tool.schema.string().describe("SQL query to execute"),
},
async execute(args) {
// Your database logic here
return `Executed query: ${args.query}`
},
})
-
可以在一个文件中导出多个 tool, tool 名为
<filename>_<exportname> -
Context , tool 可以通过 execute 方法的第二个参数来获取当前会话的上下文信息.
import { tool } from "@opencode-ai/plugin"
export default tool({
description: "Get project information",
args: {},
async execute(args, context) {
// Access context information
const { agent, sessionID, messageID } = context
return `Agent: ${agent}, Session: ${sessionID}, Message: ${messageID}`
},
})