OpenCode 完全指南:AI 编程助手的配置艺术与生态实践

一、OpenCode 简介

OpenCode 是一个基于 AI 大模型的命令行编程助手,旨在为开发者提供流畅、强大的代码编辑与项目管理体验。

1.1 核心特性一览

特性 说明
多模型支持 支持 75+ AI 服务提供商
灵活配置 六层配置优先级体系
插件系统 TypeScript/JavaScript 插件,20+ 事件钩子
工具生态 文件编辑、代码搜索、Shell 执行等
权限安全 细粒度的权限控制
服务器模式 REST API 暴露,可与 CI/CD 集成
SDK 官方 TypeScript SDK

1.2 与 Claude Code 的区别

维度 OpenCode Claude Code
生态定位 开源开放,支持 75+ 提供商 主要面向 Anthropic 自有模型
配置体系 六层优先级,变量替换 环境变量配置
插件系统 20+ 事件钩子 有限扩展
服务器模式 REST API + OpenAPI
SDK 官方 SDK

二、安装指南

2.1 npm 安装

npm install -g opencode-ai
pnpm add -g opencode-ai
bun add -g opencode-ai

2.2 下载可执行文件

curl -fsSL https://opencode.ai/install | bash

2.3 首次配置

opencode /connect
export OPENAI_API_KEY="sk-..."
export ANTHROPIC_API_KEY="sk-ant-..."

三、配置详解

3.1 配置位置与优先级

优先级 位置 用途
1 https://domain/.well-known/opencode 远程配置
2 ~/.config/opencode/opencode.json 全局配置
3 OPENCODE_CONFIG 环境变量 自定义路径
4 ./opencode.json 项目配置
5 .opencode/ 目录 代理、命令、插件
6 OPENCODE_CONFIG_CONTENT 环境变量 内联配置

配置是合并而非替换,非冲突设置会被保留。

3.2 Provider 配置

Anthropic

{
  "$schema": "https://opencode.ai/config.json",
  "model": "anthropic/claude-sonnet-4-5",
  "small_model": "anthropic/claude-haiku-4-5",
  "provider": {
    "anthropic": {
      "options": {
        "apiKey": "{env:ANTHROPIC_API_KEY}",
        "timeout": 600000,
        "chunkTimeout": 30000,
        "setCacheKey": true
      }
    }
  }
}

Amazon Bedrock

{
  "$schema": "https://opencode.ai/config.json",
  "model": "anthropic.claude-3-5-sonnet-20241022-v2:0",
  "provider": {
    "amazon-bedrock": {
      "options": {
        "region": "us-east-1",
        "profile": "my-aws-profile",
        "endpoint": "https://bedrock-runtime.us-east-1.vpce.amazonaws.com"
      }
    }
  }
}

Ollama(本地模型)

{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "ollama": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "Ollama (local)",
      "options": {
        "baseURL": "http://localhost:11434/v1"
      }
    }
  }
}

LM Studio

{
  "$schema": "https://opencode.ai/config.json",
  "provider": {
    "lmstudio": {
      "npm": "@ai-sdk/openai-compatible",
      "name": "LM Studio (local)",
      "options": {
        "baseURL": "http://localhost:1234/v1"
      }
    }
  }
}

其他 Provider

提供商 Provider ID 备注
GitHub Copilot github-copilot 特殊订阅认证
GitLab Duo gitlab-duo 特殊订阅认证
Groq groq 低延迟
DeepSeek deepseek 国产模型
MiniMax minimax 国产模型
Moonshot moonshot Kimi K2

提供商白名单与黑名单

{
  "$schema": "https://opencode.ai/config.json",
  "enabled_providers": ["anthropic", "openai"],
  "disabled_providers": ["github-copilot"]
}

3.3 服务器配置

{
  "$schema": "https://opencode.ai/config.json",
  "server": {
    "port": 4096,
    "hostname": "0.0.0.0",
    "mdns": true,
    "mdnsDomain": "opencode.local",
    "cors": ["http://localhost:5173"]
  }
}

3.4 工具配置

{
  "$schema": "https://opencode.ai/config.json",
  "tools": {
    "write": false,
    "bash": false
  }
}

3.5 权限配置

{
  "$schema": "https://opencode.ai/config.json",
  "permission": {
    "edit": "ask",
    "bash": "ask"
  }
}

值:allow(直接执行)、ask(询问)、deny(拒绝)

3.6 代理配置

{
  "$schema": "https://opencode.ai/config.json",
  "agent": {
    "code-reviewer": {
      "description": "Reviews code for best practices",
      "model": "anthropic/claude-sonnet-4-5",
      "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.",
      "permission": {
        "edit": "deny",
        "bash": "deny"
      }
    }
  },
  "default_agent": "plan"
}

3.7 命令配置

{
  "$schema": "https://opencode.ai/config.json",
  "command": {
    "test": {
      "template": "Run the full test suite with coverage report.",
      "description": "Run tests with coverage",
      "agent": "build",
      "model": "anthropic/claude-haiku-4-5"
    }
  }
}

3.8 格式化配置

{
  "$schema": "https://opencode.ai/config.json",
  "formatter": {
    "prettier": {
      "disabled": true
    },
    "custom-prettier": {
      "command": ["npx", "prettier", "--write", "$FILE"],
      "environment": {
        "NODE_ENV": "development"
      },
      "extensions": [".js", ".ts", ".jsx", ".tsx"]
    }
  }
}

3.9 TUI 配置

{
  "$schema": "https://opencode.ai/tui.json",
  "scroll_speed": 3,
  "scroll_acceleration": {
    "enabled": true
  },
  "diff_style": "auto",
  "theme": "tokyonight"
}

3.10 其他配置

{
  "$schema": "https://opencode.ai/config.json",
  "compaction": {
    "auto": true,
    "prune": true,
    "reserved": 10000
  },
  "watcher": {
    "ignore": ["node_modules/**", "dist/**", ".git/**"]
  },
  "mcp": {},
  "plugin": ["opencode-helicone-session"],
  "autoupdate": false,
  "snapshot": true,
  "instructions": ["CONTRIBUTING.md", "docs/guidelines.md"]
}

四、规则(Rules)

OpenCode 通过 AGENTS.md 文件提供自定义指令,类似于 Cursor 的 rules。

4.1 初始化规则

运行 /init 命令扫描项目并生成 AGENTS.md 文件。

4.2 规则类型

类型 位置 用途
项目规则 ./AGENTS.md 项目专用规则
全局规则 ~/.config/opencode/AGENTS.md 跨会话通用规则
Claude Code 兼容 ~/.claude/CLAUDE.md 迁移兼容

4.3 Claude Code 兼容性

OpenCode 支持 Claude Code 文件约定:

  • CLAUDE.md(项目目录,若无 AGENTS.md 则使用)
  • ~/.claude/CLAUDE.md(全局,若无 ~/.config/opencode/AGENTS.md 则使用)
  • ~/.claude/skills/(Skills 目录)

禁用选项:

export OPENCODE_DISABLE_CLAUDE_CODE=1        # 禁用所有 .claude 支持
export OPENCODE_DISABLE_CLAUDE_CODE_PROMPT=1 # 仅禁用 ~/.claude/CLAUDE.md
export OPENCODE_DISABLE_CLAUDE_CODE_SKILLS=1 # 仅禁用 .claude/skills

4.4 优先级

  1. 本地文件(从当前目录向上遍历)
  2. 全局文件 ~/.config/opencode/AGENTS.md
  3. Claude Code 文件 ~/.claude/CLAUDE.md

4.5 自定义指令文件

{
  "$schema": "https://opencode.ai/config.json",
  "instructions": ["CONTRIBUTING.md", "docs/guidelines.md", ".cursor/rules/*.md"]
}

支持远程 URL:

{
  "$schema": "https://opencode.ai/config.json",
  "instructions": ["https://raw.githubusercontent.com/my-org/shared-rules/main/style.md"]
}

五、代理(Agents)

代理是专门化的 AI 助手,可配置特定任务和工作流。

5.1 代理类型

类型 说明 使用方式
Primary 主交互代理 Tab 键切换
Subagent 专业子代理 @ 提及调用

5.2 内置代理

代理 类型 说明
Build Primary 默认代理,全工具启用
Plan Primary 规划代理,只读模式
General Subagent 通用代理,多任务并行
Explore Subagent 探索代理,快速搜索
Compaction Primary 系统代理,自动压缩上下文
Title Primary 系统代理,生成标题
Summary Primary 系统代理,创建摘要

5.3 配置代理

JSON 配置

{
  "$schema": "https://opencode.ai/config.json",
  "agent": {
    "code-reviewer": {
      "description": "代码审查",
      "mode": "subagent",
      "model": "anthropic/claude-sonnet-4-5",
      "prompt": "你是代码审查员,关注安全、性能和可维护性。",
      "permission": {
        "edit": "deny",
        "bash": "deny"
      }
    }
  }
}

Markdown 配置

.opencode/agents/~/.config/opencode/agents/ 目录创建:

---
description: 代码质量审查
mode: subagent
model: anthropic/claude-sonnet-4-5
temperature: 0.1
permission:
  edit: deny
  bash: deny
---

你是代码审查模式。专注于:
- 代码质量和最佳实践
- 潜在 bug 和边界情况
- 性能影响
- 安全考虑

5.4 代理选项

选项 类型 说明
description string 代理描述(必需)
mode string primary/subagent/all
model string 模型 ID
temperature number 0.0-1.0,创意度
top_p number 0.0-1.0,响应多样性
max_steps number 最大迭代次数
hidden boolean 隐藏 @ 自动完成
permission object 权限配置
prompt string 系统提示或文件路径
color string UI 颜色(#hex 或主题色)

5.5 创建代理

opencode agent create

六、命令(Commands)

自定义命令让你在 TUI 中执行预设提示。

6.1 JSON 配置

{
  "$schema": "https://opencode.ai/config.json",
  "command": {
    "test": {
      "template": "运行完整的测试套件...",
      "description": "运行测试",
      "agent": "build"
    }
  }
}

6.2 Markdown 配置

.opencode/commands/ 创建 Markdown 文件:

---
description: 运行测试
agent: build
model: anthropic/claude-sonnet-4-5
---

运行完整的测试套件并展示覆盖率报告。

6.3 命令选项

选项 类型 说明
template string 发送给 LLM 的提示(必需)
description string TUI 中显示的描述
agent string 指定执行的代理
model string 覆盖默认模型
subtask boolean 强制触发子代理

6.4 参数传递

使用 $ARGUMENTS$1, $2 等:

---
description: 创建组件
---

创建名为 $ARGUMENTS 的 React 组件。

6.5 内置命令

  • /init - 初始化项目
  • /undo - 撤销
  • /redo - 重做
  • /share - 分享会话
  • /help - 帮助

七、主题(Themes)

7.1 设置主题

tui.json 中设置 UI 主题:

{
  "$schema": "https://opencode.ai/tui.json",
  "theme": "tokyonight"
}

7.2 可用主题

  • tokyonight(默认)
  • catppuccin
  • dracula
  • github-dark
  • nord
  • one-dark
  • solarized-dark
  • solarized-light
  • gruvbox

八、快捷键(Keybinds)

8.1 自定义快捷键

{
  "$schema": "https://opencode.ai/tui.json",
  "keybinds": {
    "toggle_sidebar": "ctrl+b",
    "new_session": "ctrl+n"
  }
}

8.2 常用快捷键

功能 默认快捷键
切换侧边栏 ctrl+b
新建会话 ctrl+n
提交 ctrl+enter
中断 ctrl+c
切换代理 tab
进入子会话 +Down
返回父会话 Up
切换到下一个子会话 Right
切换到上一个子会话 Left

九、MCP 服务器

OpenCode 支持 Model Context Protocol (MCP),可添加外部工具和服务。

9.1 启用 MCP

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "server-name": {
      "enabled": true
    }
  }
}

9.2 本地 MCP 服务器

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "my-local-server": {
      "type": "local",
      "command": ["npx", "-y", "@modelcontextprotocol/server-everything"],
      "enabled": true,
      "environment": {
        "MY_ENV_VAR": "value"
      }
    }
  }
}
选项 类型 必需 说明
type string 必须为 “local”
command array 启动命令和参数
environment object 环境变量
enabled boolean 默认 true
timeout number 超时(毫秒),默认 5000

9.3 远程 MCP 服务器

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "my-remote": {
      "type": "remote",
      "url": "https://mcp.example.com",
      "enabled": true,
      "headers": {
        "Authorization": "Bearer {env:API_KEY}"
      }
    }
  }
}

9.4 OAuth 认证

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "server": {
      "type": "remote",
      "url": "https://mcp.example.com/mcp",
      "oauth": {
        "clientId": "{env:MCP_CLIENT_ID}",
        "clientSecret": "{env:MCP_CLIENT_SECRET}",
        "scope": "tools:read tools:execute"
      }
    }
  }
}

CLI 管理:

opencode mcp auth <server>   # 认证
opencode mcp list           # 列出服务器
opencode mcp logout <server> # 登出

9.5 MCP 管理

全局启用/禁用

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "my-server": {
      "type": "local",
      "command": ["npx", "-y", "server"]
    }
  },
  "tools": {
    "my-server": false
  }
}

按 Agent 启用

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "my-server": {
      "type": "local",
      "command": ["npx", "-y", "server"]
    }
  },
  "tools": {
    "my-server*": false
  },
  "agent": {
    "my-agent": {
      "tools": {
        "my-server*": true
      }
    }
  }
}

9.6 常用 MCP 服务器

Sentry

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "sentry": {
      "type": "remote",
      "url": "https://mcp.sentry.dev/mcp",
      "oauth": {}
    }
  }
}
opencode mcp auth sentry

Context7(文档搜索)

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "context7": {
      "type": "remote",
      "url": "https://mcp.context7.com/mcp",
      "headers": {
        "CONTEXT7_API_KEY": "{env:CONTEXT7_API_KEY}"
      }
    }
  }
}

Grep by Vercel(GitHub 代码搜索)

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "gh_grep": {
      "type": "remote",
      "url": "https://mcp.grep.app"
    }
  }
}

9.7 注意事项

  • MCP 服务器会增加上下文 token 使用量
  • 建议按需启用,避免耗尽上下文
  • GitHub MCP 等大型服务器可能占用大量 token

十、自定义工具

10.1 创建自定义工具

{
  "$schema": "https://opencode.ai/config.json",
  "tools": {
    "my-tool": {
      "description": "My custom tool",
      "args": {
        "input": { "type": "string", "description": "Input text" }
      },
      "execute": async ({ input }) => {
        return `Processed: ${input}`
      }
    }
  }
}

10.2 工具配置选项

选项 类型 必需 说明
description string 工具描述
args object 参数定义(JSON Schema)
execute function 执行函数

10.3 参数类型

  • string - 字符串
  • number - 数字
  • boolean - 布尔值
  • array - 数组
  • object - 对象

10.4 示例

// 带可选参数的查询工具
"query-db": {
  "description": "查询数据库",
  "args": {
    "sql": { "type": "string", "description": "SQL 查询语句" },
    "limit": { "type": "number", "description": "返回条数", "default": 10 }
  },
  "execute": async ({ sql, limit = 10 }) => {
    return { rows: [], count: 0 }
  }
}

十一、基础使用

11.1 启动会话

opencode
opencode /path/to/project
opencode --model anthropic/claude-sonnet-4-5
opencode serve

11.2 常用命令

  • /connect - 配置 Provider
  • /models - 选择模型
  • /share - 分享会话
  • /compact - 压缩上下文

11.3 会话管理

opencode sessions list
opencode sessions switch <session-id>

十二、工具系统

12.1 内置工具

工具 功能 权限
bash 执行命令 bash
read 读文件 read
edit 编辑文件 edit
write 写文件 edit
glob 查找文件 glob
grep 搜索内容 grep
list 列出目录 list
lsp 代码智能 lsp
patch 应用补丁 edit
skill 加载技能 skill
todowrite 创建待办 todowrite
todoread 读取待办 todoread
webfetch 获取网页 webfetch
websearch 网络搜索 websearch
question 向用户提问

12.2 示例

read("src/app.tsx")
edit({ file: "a.txt", oldText: "a", newText: "b" })
bash({ command: "npm run build" })

十三、插件开发

13.1 创建插件

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

export const MyPlugin: Plugin = async ({ project, client, $ }) => {
  return {
    "session.idle": async () => {
      console.log("会话空闲")
    }
  }
}
{ "plugin": [".opencode/plugins/my-plugin"] }

13.2 事件钩子

  • session.created/deleted/updated/error/idle/compacted
  • tool.execute.before/after
  • permission.asked/replied
  • file.edited/watcher.updated
  • tui.prompt.append/command.execute/toast.show

13.3 实用示例

// 通知插件
export const Notify: Plugin = async ({ $ }) => ({
  "session.idle": async () => { await $`notify-send done` }
})

// .env 保护
export const EnvProtect: Plugin = async () => ({
  "tool.execute.before": async (input) => {
    if (input.tool === "read" && input.args.file?.includes(".env")) {
      throw new Error("禁止读取 .env")
    }
  }
})

十四、SDK 与生态

14.1 JavaScript SDK

npm install @opencode-ai/sdk
import { createOpencode } from "@opencode-ai/sdk"

const { client } = await createOpencode({
  config: {
    model: "anthropic/claude-sonnet-4-5",
    provider: {
      anthropic: {
        options: { apiKey: process.env.ANTHROPIC_API_KEY }
      }
    }
  }
})

await client.session.prompt({
  path: { id: sessionId },
  body: { parts: [{ type: "text", text: "hello" }] }
})

14.2 社区插件

  • opencode-helicone-session - 会话跟踪
  • opencode-gitlab-plugin - GitLab 集成

14.3 社区项目

  • opencode.nvim - Neovim
  • kimaki - Discord

十五、常见问题

Q1: 切换模型

opencode --model anthropic/claude-sonnet-4-5

Q2: 安全建议

  • 使用环境变量存储 API Key
  • {env:VAR} 引用
  • .env 默认拒绝读取

Q3: 禁用更新

{ "autoupdate": false }

Q4: 禁止 bash

{ "permission": { "bash": "deny" } }

十六、总结

OpenCode 核心优势:

  • 75+ Provider 支持
  • 六层配置优先级
  • 20+ 插件事件钩子
  • TypeScript SDK
  • 细粒度权限控制

祝你编程愉快!


本站由 时空 使用 Stellar 搭建。