跳到主要内容

OpenCode 学习

https://opencode.ai/docs/

OpenCode 是一个开源 AI 编程助手. 提供 terminal-based interface, desktop app, IDE 扩展三种使用方式.

Intro

  1. npm 安装
npm install -g opencode-ai --registry https://registry.npmjs.org
  1. /init 会为项目初始化 OpenCode. 在项目根目录生成 AGENTS.md

  2. tab 键可以切换 Agent

  • plan 只读模式,只做分析和规划, 不会修改代码
  • build 默认, 全权限,可以读写文件,执行命令
  1. undo 可以撤销修改. /redo 重新执行这些修改.

  2. /share 将对话内容分享给团队成员.

Config

OpenCode 配置支持 jsonjsonc 格式.(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.jsonbaseURL 来设置代理服务

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 终端用户界面

  1. opencode 启动终端用户界面
  • opencode /path/to/project 指定工作目录启动
  1. 通过 @ 来引用文件, 文件内容会自动添加到对话中.

  2. 通过 ! 来运行 Shell 命令, 如 !ls -la, 结果会输出到对话中.

  3. 通过 / 来执行快速操作, 如 /connect, /models, /help

  4. /compact 压缩当前会话. 别名: /summarize

  5. /details 切换工具执行详情. 这个目前使用没有效果, 不知道是什么问题. // TODO

  6. /editor 打开外部编辑器.

  7. /exit , /quit, /q 退出

  8. /export 导出会话

  9. /help, 快捷键 ctrp + p

  10. /init 创建和跟新 AGENTS.md

  11. /models

  12. /clear, /new 开启一个新会话

  13. /redo , /undo

  14. /sessions, /resume, /continue 列出并切换会话

  15. /share 分享会话, /unshare 取消分享

CLI

  1. opencode [projet] 启动 opencode 的 TUI
  • opencode -c 继续上次会话
  1. opencode agent [command]
  • opencode agent create 创建一个带有自定义系统提示和工具配置的全新智能体。
  • opencode agent list 列出所有 Agent
  1. opencode attach

  2. opencode auth [command]

  • opencode auth login
  • opencode auth list
  • opencode auth ls
  • opencode auth logout
  1. opencode github [command]
  • opencode github install Install the GitHub agent
  • opencode github run
    • --event
    • --token GitHub 令牌
  1. opencode mcp [command]
  • opencode mcp add
  • opencode mcp list
  • opencode mcp auth [name]
  • opencode mcp auth list
  • opencode mcp auth ls
  • opencode mcp logout [name]
  • opencode mcp debug <name>
  1. opencode modles [provider]
  • --refresh
  • --verbose
  1. opencode run [messages..] 直接传入提示词, 即可在非交互模式下运行 opencode
  • opencode run 输出1+1的结果
  1. opencode serve 启动无界面的 OpenCode 服务器以通过 API 访问

    • --port
    • --hostname
    • --mdns
    • --cros
  2. opencode session [command] 列出 Opencode 的所有会话

  • opencode session list
    • -n 显示最近 n 个会话
    • --format 格式化输出(table or json)
  1. opencode stats 统计信息

    • --days
    • --tools
    • --models
    • --project
  2. opencode export [sessionID]

  3. opencode import <file> 导入会话数据

  • opencode import session.json
  • opencode import https://opncd.ai/s/abc123
  1. opencode web
  2. opencode acp
  3. opencode uninstall
  4. opencode 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 install
    • git status
  • edit 通过精确字符串替换来修改现有文件.
  • write 创建新文件和覆盖现有文件 -read 读代码库内容
  • grep 使用正则表达式搜索文件内容
  • glob 通过模式匹配查找文件。
  • list
  • lsp
  • patch
  • skill 加载一个技能(一个 SKILL.md 文件),并在对话中返回其内容。
  • todowrite
  • todoread
  • webfetch

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 内置了 planbuild 2 个 primary agents
  • subagents 子代理是主代理可调用的专业助手,用于执行特定任务。您也可以通过@提及的方式在消息中手动调用它们。
    • opencode 内置了 GeneralExplore 2 个 subagents.
      • General 用于研究复杂问题, 搜索代码以及执行多步骤任务.
      • Explore 一个专为探索代码库而设计的快速智能体。当你需要按模式快速查找文件、搜索代码中的关键词,或回答关于代码库的问题时,请使用它

primary agents 之间的切换使用 tab

subagents 的调用使用 @ 符号, 如 @general help me search for this function

有 2 中方法可以自定义 agent

  1. .opencode.json 中定义

    "build": {
    "mode": "primary",
    "model": "anthropic/claude-sonnet-4-20250514",
    "prompt": "{file:./prompts/build.txt}",
    "tools": {
    "write": true,
    "edit": true,
    "bash": true
    }
    },
  2. 通过 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.
  • description Agent 的描述信息, 必填
  • temperature 数值越低,回答越专注且可预测;数值越高,则创造性与多样性越强。 (在 0.0~1.0 之间取值)
  • maxSteps 最大迭代次数. (希望控制成本的用户可以为 agents 设置一个上限.) 如果未设置,会一直迭代直到用户手动终止或 agent 任务可以返回为止.
  • disable 是否禁用
  • prompt 提示词
  • model 需要使用 provider/model-id 格式
  • tools
  • permission, 可选项有 ask, allow, deny
  • mode 设置 agent 的类型, 是 primary agents 还是 subagents
  • hide @ 提示中隐藏此 agent
  • permission.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 的 prompt
    • description 描述
    • 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}`
    },
    })