本文档基于 OpenCode 官方文档整理,专为终端打造的开源 AI 编码代理(AI Coding Agent)。
要在终端中使用 OpenCode,你需要:
OpenCode 支持多种安装方式,请根据你的操作系统和环境选择最适合的一种。
bashcurl -fsSL [https://opencode.ai/install](https://opencode.ai/install) | bash
如果你已经安装了 Node.js 环境,可以通过以下包管理器全局安装:
bash# 使用 npm
npm install -g opencode-ai
# 使用 Bun
bun install -g opencode-ai
# 使用 pnpm
pnpm install -g opencode-ai
# 使用 Yarn
yarn global add opencode-ai
使用 Homebrew: 推荐使用 OpenCode tap 以获取最新版本:
bashbrew install anomalyco/tap/opencode
使用 Arch Linux:
bashsudo pacman -S opencode # Arch Linux (Stable)
paru -S opencode-bin # Arch Linux (Latest from AUR)
强烈推荐使用 Windows Subsystem for Linux (WSL) 以获得最佳体验、性能和完全兼容性。如果在 Windows 原生环境中安装:
bash# 使用 Chocolatey
choco install opencode
# 使用 Scoop
scoop install opencode
# 使用 NPM
npm install -g opencode-ai
# 使用 Mise
mise use -g github:anomalyco/opencode
# 使用 Docker
docker run -it --rm ghcr.io/anomalyco/opencode
(注:你也可以直接从其 GitHub Releases 页面下载对应的二进制文件。)
通过 OpenCode,你可以配置 API 密钥来使用任意 LLM 提供商。如果你刚开始接触,官方推荐使用 OpenCode Zen(一组经过团队测试验证的精选模型组合)。
opencode,在 TUI 界面中输入:
text/connect
opencode),然后前往 opencode.ai/auth 获取并复制 API 密钥。┌ API key 提示处粘贴密钥并回车。配置好提供商后,将 OpenCode 引入你的实际项目中:
bashcd /path/to/project
bashopencode
OpenCode 会自动分析你的项目,并在项目根目录创建一个text/init
AGENTS.md 文件。💡 提示:建议将
AGENTS.md文件提交到你的 Git 仓库中。这有助于 OpenCode 深入理解你的项目结构和编码规范。
现在你已经准备好使用 OpenCode 来处理项目了,可以直接在对话框中向它提问或下达指令。
你可以让 OpenCode 为你讲解代码库,遇到不熟悉的代码时非常有用。
💡 提示:在对话中输入
@键可以模糊搜索并引入项目中的具体文件。
示例:
textHow is authentication handled in @packages/functions/src/api/index.ts
当你需要添加新功能时,建议先让 AI 制定一个计划。
<TAB> 键切换到“计划模式”(Plan Mode)。在此模式下,它不会进行任何实质性修改,只会给出代码实现建议。右下角会有模式指示器。textWhen a user deletes a note, we'd like to flag it as deleted in the database. Then create a screen that shows all the recently deleted notes.
textTake a look at this image and use it as a reference.
<TAB> 键切换回“构建模式”(Build Mode),然后让它开始修改代码:
textSounds good! Go ahead and make the changes.
对于简单的修改,你可以跳过计划阶段,直接让 OpenCode 实施:
textWe need to add authentication to the /settings route. Take a look at how this is handled in the /notes route in @packages/functions/src/notes.ts and implement the same logic in @packages/functions/src/settings.ts
如果 OpenCode 做的修改不符合预期,你可以轻松回退:
/undo:OpenCode 会还原刚刚所做的文件修改,并将你之前的提示词重新填入输入框,方便你微调后重试。你可以多次运行 /undo 撤销多步操作。/redo:重做被撤销的修改。你可以将与 OpenCode 的精彩对话分享给团队:
/share:这会生成当前对话的网页链接并自动复制到剪贴板。(注意:默认情况下对话是私密的,只有主动执行命令才会被分享)。本文作者:Dryhten
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!