Based on video “Must-Have AI Agent Tool | GitHub 170k Stars Project | OPENCODE” (Rick Hau, 2026-06-05) Video link: https://www.youtube.com/watch?v=__bcJHoTE08 Analysis date: 2026-06-09 Version: OpenCode v0.1.x+ (GitHub 170k+ Stars)


📑 Table of Contents

  • What Is OpenCode
  • Why You “Must Install” It
  • Installation and Launch
  • Interactive Mode (TUI + CLI)
  • Common Commands
  • CLI Commands
  • Model Configuration
  • Configuration Files
  • Custom Agents
  • Custom Commands
  • Agent Skills
  • Custom Tools
  • Permission Control
  • MCP Servers
  • Plugin System
  • GitHub and GitLab Integration
  • Important Notes
  • Comparison with Claude Code / Codex
  • Recommended Workflow
  • Quick Reference Cheat Sheet

1. What Is OpenCode

OpenCode is an open-source AI coding agent that can compete with Claude Code, Codex, and similar tools.

ItemDetails
GitHubhttps://github.com/anomalyco/opencode
Websitehttps://opencode.ai
Documentationhttps://opencode.ai/docs
Stars170,000+
LicenseMIT (fully open-source)
Built WithGo (TUI, based on Bubble Tea) + JavaScript/Bun (HTTP server, based on Hono)
ArchitectureClient-Server (supports Terminal TUI, Desktop App, IDE extensions, HTTP clients)
Core AdvantageModel-Agnostic: supports 75+ model providers, zero vendor lock-in

Essential Difference from Other Tools

ToolCore Strategy
Claude CodeSingle model family (Claude), deep optimization, pursuing speed
CodexOpenAI ecosystem (ChatGPT binding), pursuing integration depth
OpenCodeModel-agnostic + open-source + zero lock-in, pursuing flexibility and privacy

2. Why You “Must Install” It

2.1 Core Advantages

AdvantageDescription
🆓 Completely FreeMIT license, bring your own API key, zero cost for the tool itself
🌐 75+ Model ProvidersAnthropic, OpenAI, Google, DeepSeek, Groq, Ollama (local models)
🔒 Zero Vendor Lock-InSwitch models anytime, immune to price hikes or quality drops
💻 LSP IntegrationOnly AI coding agent with Language Server Protocol support
🤖 Multi-Agent SystemBuild, Plan, General, Explore, Scout - five built-in agents
🔧 Highly CustomizableAgents, Commands, Skills, Tools, MCP all configurable
📱 Multi-Surface SupportTUI (Terminal), Desktop App, VS Code extension, HTTP API
🛡️ Security ControlsGit snapshots + /undo + /redo + fine-grained permission control
🏠 Complete Local PrivacySupport Ollama local models, code never uploaded
🌍 20+ LanguagesIncludes Traditional Chinese (README.zht.md)

2.2 Who Should Use It

  • Developers who don’t want lock-in: Don’t want to be tied to Anthropic or OpenAI
  • Cost-conscious users: Can use cheap models for simple tasks, expensive for complex
  • High privacy requirements: Code cannot be uploaded to cloud → use Ollama local models
  • Multi-language projects: Need different models for different languages
  • Enterprise users: Need fine-grained permission control + MCP integration

3. Installation and Launch

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

3.2 Platform-Specific Methods

PlatformCommand
npmnpm install -g opencode-ai
Bunbun install -g opencode-ai
pnpmpnpm install -g opencode-ai
Yarnyarn global add opencode-ai
Homebrew (macOS/Linux)brew install anomalyco/tap/opencode
Arch Linux (stable)sudo pacman -S opencode
Arch Linux (latest)paru -S opencode-bin
Windows (Chocolatey)choco install opencode
Windows (Scoop)scoop install opencode
Mise (any OS)mise use -g github:anomalyco/opencode
Dockerdocker run -it --rm ghcr.io/anomalyco/opencode
Nixnix run nixpkgs#opencode

3.3 Desktop Applications

PlatformDownload
macOS (Apple Silicon)opencode-desktop-mac-arm64.dmg
macOS (Intel)opencode-desktop-mac-x64.dmg
Windowsopencode-desktop-windows-x64.exe
Linux.deb / .rpm / .AppImage

macOS install: brew install --cask opencode-desktop Windows install: scoop bucket add extras; scoop install extras/opencode-desktop

3.4 Prerequisites

  • Modern terminal emulator: WezTerm, Alacritty, Ghostty, Kitty (any one)
  • LLM API Key: At least one model provider’s API key
  • Git: /undo and /redo features require Git repository

3.5 Launch

# Enter project directory
cd /path/to/project

# Launch TUI
opencode

# Or specify directory
opencode /path/to/project

3.6 First-Time Setup

After launch, run /init. OpenCode will analyze project structure and create AGENTS.md file to help AI understand your codebase.


4. Interactive Mode (TUI + CLI)

4.1 TUI (Terminal User Interface)

┌─────────────────────────────────┐
│  OpenCode TUI                   │
│                                 │
│  💬 Message History             │
│  ─────────────────────          │
│  Q: Explain this function...    │
│  A: This function does...       │
│  ─────────────────────          │
│  > Enter new message...         │
│                                 │
│  [Build]  [Tab to switch]       │
└─────────────────────────────────┘

4.2 File References

Use @ symbol to reference files:

How is authentication handled in @packages/functions/src/api/index.ts?
  • Supports fuzzy search
  • File content automatically loaded into conversation
  • Supports alias references (@docs/README.md)

4.3 Bash Command Injection

Messages starting with ! execute Shell commands directly:

!ls -la
!git status
!npm test

Command output automatically loaded into conversation.

4.4 Two Main Agent Modes

ModeShortcutDescription
BuildTab to switchDefault agent, full tool access
PlanTab to switchRead-only agent, no edits or commands

Recommended workflow:

  1. Use Plan mode to analyze and plan
  2. Use Build mode to execute and build

4.5 Image Support

Drag and drop images directly into terminal. OpenCode will scan images and add to prompt.


5. Common Commands

5.1 Built-in Slash Commands

CommandShortcutFunction
/connectAdd model provider and API key
/initInitialize project, create AGENTS.md
/newCtrl+X NStart new session
/compactCtrl+X CCompress/summarize current session
/undoCtrl+X UUndo last message (requires Git)
/redoCtrl+X RRedo undone message
/shareShare current session (generate link)
/helpShow help
/modelsCtrl+X MList available models
/sessionsCtrl+X LList/switch sessions
/themesCtrl+X TList available themes
/editorCtrl+X EOpen external editor
/exportCtrl+X XExport session as Markdown
/detailsToggle tool execution details
/thinkingToggle model reasoning visibility
/quit / /qCtrl+X QExit OpenCode

5.2 Conversation Mode Switch

  • Tab key: Switch between Build and Plan agents
  • Bottom-right indicator: Shows current agent mode

6. CLI Commands

6.1 Non-Interactive Mode

# Send message directly (without entering TUI)
opencode run "Explain the functionality of src/index.ts"

# Specify directory
opencode run "Help me refactor this code" /path/to/project

6.2 Server Mode

# Start HTTP server
opencode serve

# Start Web interface
opencode web

6.3 Custom Install Path

# Specify install directory
OPENCODE_INSTALL_DIR=/usr/local/bin curl -fsSL https://opencode.ai/install | bash

# XDG standard path
XDG_BIN_DIR=$HOME/.local/bin curl -fsSL https://opencode.ai/install | bash

7. Model Configuration

7.1 Connect Model Providers

/connect

Select provider → Enter API Key → Done.

7.2 Supported Model Providers

ProviderModelsUse Case
AnthropicClaude Sonnet 4.5, Opus 4.6, Haiku 4.5Code generation, reasoning
OpenAIGPT-5.1 Codex, GPT-5 CodexProgramming-specific
GoogleGemini 3.1 ProMultimodal
DeepSeekDeepSeek-V3Cost-effective
GroqVarious open-source modelsHigh-speed inference
OllamaLocal modelsPrivacy-first
LM StudioLocal modelsPrivacy-first

7.3 Model Configuration Format

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

small_model: Used for lightweight tasks (title generation, etc.), automatically uses cheaper model.

  • Officially tested and verified model list
  • Pay-as-you-go
  • Run /connect → Select opencode → Go to opencode.ai/auth

7.5 Different Models for Different Tasks

{
  "agent": {
    "build": {
      "model": "anthropic/claude-sonnet-4-20250514"
    },
    "plan": {
      "model": "anthropic/claude-haiku-4-20250514"
    }
  }
}

8. Configuration Files

8.1 Configuration Priority (Low to High)

PrioritySourceDescription
1Remote configOrganization defaults (.well-known/opencode)
2Global config~/.config/opencode/opencode.json
3Custom configOPENCODE_CONFIG environment variable
4Project configProject root opencode.json
5.opencode directoryagents, commands, plugins
6Inline configOPENCODE_CONFIG_CONTENT environment variable
7Managed configAdministrator configuration (highest priority)

Important: Configuration files are merged, not replaced. Non-conflicting settings from different sources are preserved.

8.2 Global Configuration

// ~/.config/opencode/opencode.json
{
  "$schema": "https://opencode.ai/config.json",
  "model": "anthropic/claude-sonnet-4-5",
  "autoupdate": true,
  "server": {
    "port": 4096
  }
}

8.3 Project Configuration

// Project root opencode.json
{
  "$schema": "https://opencode.ai/config.json",
  "model": "anthropic/claude-sonnet-4-20250514",
  "permission": {
    "edit": "ask",
    "bash": "ask"
  }
}

Safe to commit to Git

8.4 TUI Configuration

// ~/.config/opencode/tui.json
{
  "$schema": "https://opencode.ai/tui.json",
  "scroll_speed": 3,
  "scroll_acceleration": {
    "enabled": true
  },
  "diff_style": "auto",
  "mouse": true,
  "attention": {
    "enabled": true,
    "notifications": true,
    "sound": true,
    "volume": 0.4
  }
}

8.5 Custom Configuration Path

export OPENCODE_CONFIG=/path/to/my/custom-config.json
opencode run "Hello world"

9. Custom Agents

9.1 Built-in Agents

AgentTypeDescription
BuildPrimaryDefault, all tools available, full development permissions
PlanPrimaryRead-only, no edits or commands, perfect for analysis and planning
GeneralSubagentGeneral research, multi-step tasks, can execute in parallel
ExploreSubagentQuick read-only codebase exploration, cannot modify files
ScoutSubagentExternal documentation and dependency research, clones dependency repos to cache

9.2 Hidden System Agents

AgentFunction
CompactionAutomatically compresses long context
TitleAutomatically generates session titles
SummaryAutomatically creates session summaries

9.3 Using Subagents

# Mention with @ in messages
@general help me search for this function
@explore find all authentication-related files
@scout check the source code implementation of this library

9.4 Subagent Session Navigation

ActionShortcut
Enter sub-sessionCtrl+Down (or +Down)
Switch to next sub-sessionRight
Switch to previous sub-sessionLeft
Return to parent sessionUp

9.5 Custom Agents (JSON Configuration)

{
  "$schema": "https://opencode.ai/config.json",
  "agent": {
    "code-reviewer": {
      "description": "Review code for best practices and potential issues",
      "mode": "subagent",
      "model": "anthropic/claude-sonnet-4-20250514",
      "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.",
      "permission": {
        "edit": "deny",
        "bash": "deny"
      },
      "temperature": 0.1
    }
  }
}

9.6 Custom Agents (Markdown Configuration)

Create file ~/.config/opencode/agents/review.md:

---
description: Reviews code for quality and best practices
mode: subagent
model: anthropic/claude-sonnet-4-20250514
temperature: 0.1
permission:
  edit: deny
  bash: 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.

Filename is agent name (review.md → @review)

9.7 Agent Configuration Options

OptionDescription
descriptionAgent description (required)
modeprimary or subagent
modelOverride default model
temperature0.0-1.0 (0=deterministic, 1=creative)
promptCustom system prompt file path
permissionPermission control
stepsMaximum agent steps (control costs)
disabletrue to disable agent

10. Custom Commands

10.1 Create Commands (Markdown)

Create .opencode/commands/test.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.

Use: /test

10.2 Create Commands (JSON)

{
  "$schema": "https://opencode.ai/config.json",
  "command": {
    "test": {
      "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.",
      "description": "Run tests with coverage",
      "agent": "build",
      "model": "anthropic/claude-3-5-sonnet-20241022"
    }
  }
}

10.3 Command Arguments

Use $ARGUMENTS or $1, $2, $3:

---
description: Create a new component
---

Create a new React component named $ARGUMENTS with TypeScript support.
Include proper typing and basic structure.

Use: /component Button$ARGUMENTS replaced with Button

---
description: Create a new file with content
---

Create a file named $1 in the directory $2
with the following content: $3

Use: /create-file config.json src '{ "key": "value" }'

10.4 Command Embedded Shell Output

Use !command to inject Shell command output:

---
description: Review recent changes
---

Recent git commits:

!`git log --oneline -10`

Review these changes and suggest any improvements.

10.5 Command Embedded Files

Use @filename to reference files:

---
description: Review component
---

Review the component in @src/components/Button.tsx.
Check for performance issues and suggest improvements.

10.6 Command Options

OptionDescription
templatePrompt template (required)
descriptionDescription shown in TUI
agentSpecify execution agent
subtasktrue forces execution as subagent
modelOverride default model

11. Agent Skills

11.1 What Are Skills

Skills are reusable knowledge files (SKILL.md) containing specialized instructions and processes for specific domains.

11.2 Using Skills

skill tool automatically loads SKILL.md file content into conversation

11.3 Skills Storage Location

ScopePath
Global~/.config/opencode/skills/
Project.opencode/skills/

11.4 Creating Skills

Each Skill is a directory containing SKILL.md:

.opencode/skills/
├── my-skill/
│   └── SKILL.md
└── another-skill/
    └── SKILL.md

12. Custom Tools

12.1 What Are Custom Tools

Custom tools allow you to define your own functions for LLM to call and execute arbitrary code.

12.2 Built-in Tools List

ToolDescription
bashExecute Shell commands
editModify existing files
writeCreate new files or overwrite existing files
readRead file contents
grepRegular expression search in file contents
globPattern matching to find files
lspLanguage Server Protocol (go-to-definition, find references, etc.)
apply_patchApply patch files
skillLoad SKILL.md files
todowriteManage to-do lists
webfetchFetch web content
websearchSearch web using Exa AI
questionAsk user questions

12.3 Underlying Technology

  • grep and glob use ripgrep (rg)
  • Default respects .gitignore rules
  • Can use .ignore files to override ignore rules

13. Permission Control

13.1 Permission Levels

LevelDescription
allowAllow all operations, no approval needed
askRequires user approval before execution
denyDisable the tool

13.2 Permission Keys

KeyControlled Tools
readread
editwrite, edit, apply_patch
globglob
grepgrep
listlist
bashbash
tasktask
external_directoryAccess files outside project directory
todowritewritetodo, readtodo
webfetchwebfetch
websearchwebsearch
lsplsp
skillskill
questionquestion
doom_loopRecovery prompt when agent is stuck

13.3 Fine-Grained Control (Glob Patterns)

{
  "permission": {
    "edit": "deny",
    "bash": {
      "*": "ask",
      "git diff": "allow",
      "git log*": "allow",
      "grep *": "allow",
      "rm -rf *": "deny"
    },
    "webfetch": "deny"
  }
}

13.4 Wildcard Control

{
  "permission": {
    "mymcp_*": "ask"
  }
}

13.5 Independent Permissions Per Agent

{
  "permission": {
    "edit": "deny"
  },
  "agent": {
    "build": {
      "permission": {
        "edit": "ask"
      }
    }
  }
}

13.6 Markdown Agent Permissions

---
description: Code review without edits
mode: subagent
permission:
  edit: deny
  bash:
    "*": ask
    "git diff": allow
    "git log*": allow
---

14. MCP Servers

14.1 What Is MCP

MCP (Model Context Protocol) servers allow integration with external tools and services, including database access, API integration, third-party services, etc.

14.2 MCP Configuration

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "jira": {
      "type": "remote",
      "url": "https://jira.example.com/mcp",
      "enabled": true
    }
  }
}

14.3 Remote MCP

Organizations can provide default MCP servers via .well-known/opencode endpoint, users can enable as needed.

14.4 Use Cases

  • Database queries
  • Jira / GitHub integration
  • Third-party API calls
  • Internal tool integration

15. Plugin System

OpenCode supports plugin extensions. Plugins stored in .opencode/ directory:

.opencode/
├── agents/     # Custom agents
├── commands/   # Custom commands
├── skills/     # Custom skills
└── plugins/    # Plugins

16. GitHub and GitLab Integration

16.1 Git Safety Net

  • Automatic snapshots: Creates Git snapshot before each change
  • /undo: Undo all changes from last message
  • /redo: Redo undone changes
  • /share: Generate session share link

16.2 Session Sharing

/share

Creates share link for current conversation, copies to clipboard.

Example: https://opencode.ai/s/4XP1fce5

16.3 Git Worktrees

OpenCode supports Git Worktrees as isolation strategy, letting AI work on independent branches without affecting main branch.


17. Important Notes

17.1 ⚠️ Critical Reminders

ItemDescription
Version cleanupRemove versions before 0.1.x before installing
Git dependency/undo and /redo require project to be Git repository
API Key securityKeep API keys safe, don’t commit to public repositories
Model selectionChoose appropriate model based on task complexity, balance cost and quality
Permission settingsProduction environment recommends bash: "ask" to prevent accidental command execution
Context managementUse /compact to compress context for long conversations to save tokens
Naming conflictsIf creating OpenCode-related projects, name must include note that it’s unofficial

17.2 Cost Optimization Suggestions

StrategyDescription
Tiered modelsUse cheap models (Haiku) for simple tasks, expensive models (Sonnet/Opus) for complex tasks
small_modelConfigure small_model for lightweight tasks like title generation
temperatureLower temperature to reduce unnecessary diverse output
steps limitSet maximum steps to control costs
Local modelsUse Ollama for non-critical tasks, completely free

18. Comparison with Claude Code / Codex

FeatureOpenCodeClaude CodeCodex
Model Support75+ providersClaude onlyOpenAI only
LicenseMIT (open-source)ProprietaryProprietary
Local ModelsYes (Ollama)NoNo
CostFree (BYO API key)SubscriptionSubscription
Vendor Lock-InNoneFullFull
LSP SupportYesNoNo
Custom AgentsYesLimitedLimited
Custom CommandsYesNoNo
MCP IntegrationYesNoNo
Git Integration/undo, /redo, snapshotsBasicBasic

  1. Start with Plan mode - Analyze codebase, understand structure
  2. Use @file references - Point AI to specific files
  3. Leverage subagents - Use @explore for codebase exploration, @general for research
  4. Create custom commands - Automate repetitive tasks
  5. Set appropriate permissions - Balance safety and efficiency
  6. Use /compact regularly - Prevent context overflow in long sessions
  7. Commit frequently - Use /undo when needed to revert changes

20. Quick Reference Cheat Sheet

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

# Launch
cd /path/to/project && opencode

# First-time setup
/init

# Connect provider
/connect

# Essential commands
/new          # New session
/compact      # Compress context
/undo         # Undo last change
/models       # List models
/share        # Share session

# Agent modes (Tab to switch)
Build         # Full access
Plan          # Read-only

# File references
@filename     # Reference file

# Bash commands
!command      # Execute shell command

# Subagents
@explore      # Codebase exploration
@general      # General research
@scout        # External docs research

Have you tried OpenCode yet? What model provider do you prefer for AI coding?


中文版

基於影片「不得不裝的 AI 代理工具|GitHub 萬星項目|OPENCODE」(Rick Hau, 2026-06-05)影片連結:https://www.youtube.com/watch?v=__bcJHoTE08分析時間:2026-06-09版本:OpenCode v0.1.x+(GitHub 17 萬+ Stars)


📑 目錄

  • OpenCode 是什麼- 為什麼「不得不裝」- 安裝與啟動- 交互模式(TUI + CLI)- 常用命令- CLI 命令- 模型配置- 配置文件- 自定義智能體(Agents)- 自定義命令(Custom Commands)- Agent Skills- Custom Tools- 權限控制(Permissions)- MCP 服務器- 插件系統- GitHub 與 GitLab 集成- 注意事項- 與 Claude Code / Codex 比較- 推薦工作流程- 快速參考速查表

1. OpenCode 是什麼

OpenCode 是一個開源的 AI 編程代理工具(AI Coding Agent),可以與 Claude Code、Codex 等並駕齊驅。

項目詳情
GitHubhttps://github.com/anomalyco/opencode
官網https://opencode.ai
文檔https://opencode.ai/docs
Stars17 萬+
授權MIT(完全開源)
開發語言Go(TUI,基於 Bubble Tea)+ JavaScript/Bun(HTTP 服務器,基於 Hono)
架構Client-Server(支持終端 TUI、桌面應用、IDE 擴展、HTTP 客戶端)
核心賣點模型無關(Model-Agnostic):支持 75+ 模型提供商,零供應商鎖定

與其他工具的本質區別

工具核心策略
Claude Code單一模型家族(Claude),深度優化,追求速度
CodexOpenAI 生態系(ChatGPT 綁定),追求集成深度
OpenCode模型無關 + 開源 + 零鎖定,追求靈活性與隱私

2. 為什麼「不得不裝」

2.1 核心優勢

優勢說明
🆓完全免費MIT 授權,自己帶 API Key 即可,工具本身零費用
🌐75+ 模型提供商Anthropic、OpenAI、Google、DeepSeek、Groq、Ollama(本地模型)
🔒零供應商鎖定隨時切換模型,不怕任何一家漲價或降質
💻LSP 集成業界唯一支持 Language Server Protocol 的 AI 編程代理
🤖多代理系統Build、Plan、General、Explore、Scout 五大內建代理
🔧高度可定制Agents、Commands、Skills、Tools、MCP 全部可自定義
📱多表面支持TUI(終端)、Desktop App、VS Code 擴展、HTTP API
🛡️安全控制Git 快照 + /undo + /redo + 精細權限控制
🏠完全本地隱私支持 Ollama 本地模型,代碼不上傳
🌍20+ 語言包含繁體中文(README.zht.md)

2.2 適合誰用

  • ✅不想被鎖定的開發者:不想只綁定 Anthropic 或 OpenAI- ✅成本敏感者:可以用便宜的模型做簡單任務,貴的模型做複雜任務- ✅隱私要求高:代碼不能上傳到雲端 → 用 Ollama 本地模型- ✅多語言項目:需要不同模型處理不同語言- ✅企業用戶:需要精細權限控制 + MCP 集成

3. 安裝與啟動

3.1 一鍵安裝(推薦)

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

3.2 各平台安裝方法

平台命令
npmnpm install -g opencode-ai
Bunbun install -g opencode-ai
pnpmpnpm install -g opencode-ai
Yarnyarn global add opencode-ai
Homebrew(macOS/Linux)brew install anomalyco/tap/opencode
Arch Linux(穩定)sudo pacman -S opencode
Arch Linux(最新)paru -S opencode-bin
Windows(Chocolatey)choco install opencode
Windows(Scoop)scoop install opencode
Mise(任意 OS)mise use -g github:anomalyco/opencode
Dockerdocker run -it –rm ghcr.io/anomalyco/opencode
Nixnix run nixpkgs#opencode

3.3 桌面應用

平台下載
macOS(Apple Silicon)opencode-desktop-mac-arm64.dmg
macOS(Intel)opencode-desktop-mac-x64.dmg
Windowsopencode-desktop-windows-x64.exe
Linux.deb / .rpm / .AppImage

macOS 安裝:brew install –cask opencode-desktopWindows 安裝:scoop bucket add extras; scoop install extras/opencode-desktop

3.4 前置要求

  • 現代終端模擬器:WezTerm、Alacritty、Ghostty、Kitty(任一)- LLM API Key:至少一個模型提供商的 API Key- Git:/undo 和 /redo 功能需要 Git 倉庫

3.5 啟動

# 進入項目目錄
cd /path/to/project

# 啟動 TUI
opencode

# 或指定目錄
opencode /path/to/project

3.6 首次配置

啟動後運行/init,OpenCode 會分析項目結構並創建AGENTS.md文件,幫助 AI 理解你的代碼庫。


4. 交互模式(TUI + CLI)

4.1 TUI(終端用戶界面)

┌─────────────────────────────────┐
│  OpenCode TUI                   │
│                                 │
│  💬 消息歷史                     │
│  ─────────────────────          │
│  Q: 幫我解釋這個函數...          │
│  A: 這個函數的作用是...          │
│  ─────────────────────          │
│  > 輸入新消息...                │
│                                 │
│  [Build]  [Tab 切換代理]         │
└─────────────────────────────────┘

4.2 文件引用

使用@符號引用文件:

How is authentication handled in @packages/functions/src/api/index.ts?
  • 支持模糊搜索- 文件內容自動載入對話- 支持別名引用(@docs/README.md)

4.3 Bash 命令注入

消息以!開頭直接執行 Shell 命令:

!ls -la
!git status
!npm test

命令輸出自動載入對話。

4.4 兩種主要代理模式

模式快捷鍵說明
BuildTab 切換默認代理,完整工具訪問權限
PlanTab 切換只讀代理,禁止編輯和執行命令

工作流程建議:1. 用Plan模式分析和規劃2. 用Build模式執行和構建

4.5 圖像支持

直接拖放圖片到終端,OpenCode 會掃描圖片並加入提示詞。


5. 常用命令

5.1 內建斜線命令

命令快捷鍵功能
/connect添加模型提供商和 API Key
/init初始化項目,創建 AGENTS.md
/newCtrl+X N開始新會話
/compactCtrl+X C壓縮/總結當前會話
/undoCtrl+X U撤銷上次消息(需要 Git)
/redoCtrl+X R重做已撤銷的消息
/share分享當前會話(生成鏈接)
/help顯示幫助
/modelsCtrl+X M列出可用模型
/sessionsCtrl+X L列出/切換會話
/themesCtrl+X T列出可用主題
/editorCtrl+X E打開外部編輯器
/exportCtrl+X X導出會話為 Markdown
/details切換工具執行詳情顯示
/thinking切換模型推理過程可見性
/quit//qCtrl+X Q退出 OpenCode

5.2 對話模式切換

  • Tab 鍵:在 Build 和 Plan 代理間切換- 右下角指示器:顯示當前代理模式

6. CLI 命令

6.1 非交互模式

# 直接發送消息(不進入 TUI)
opencode run "幫我解釋 src/index.ts 的功能"

# 指定目錄
opencode run "幫我重構這段代碼" /path/to/project

6.2 服務器模式

# 啟動 HTTP 服務器
opencode serve

# 啟動 Web 界面
opencode web

6.3 自定義安裝路徑

# 指定安裝目錄
OPENCODE_INSTALL_DIR=/usr/local/bin curl -fsSL https://opencode.ai/install | bash

# XDG 標準路徑
XDG_BIN_DIR=$HOME/.local/bin curl -fsSL https://opencode.ai/install | bash

7. 模型配置

7.1 連接模型提供商

/connect

選擇提供商 → 輸入 API Key → 完成。

7.2 支持的主要模型提供商

提供商模型用途
AnthropicClaude Sonnet 4.5, Opus 4.6, Haiku 4.5代碼生成、推理
OpenAIGPT-5.1 Codex, GPT-5 Codex編程專用
GoogleGemini 3.1 Pro多模態
DeepSeekDeepSeek-V3性價比高
Groq各種開源模型高速推理
Ollama本地模型隱私優先
LM Studio本地模型隱私優先

7.3 模型配置格式

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

small_model:用於輕量任務(標題生成等),自動使用更便宜的模型。

7.4 OpenCode Zen(推薦新手)

  • 官方測試驗證的模型列表- 按需付費- 運行/connect→ 選擇opencode→ 前往 opencode.ai/auth

7.5 不同任務用不同模型

{
  "agent": {
    "build": {
      "model": "anthropic/claude-sonnet-4-20250514"
    },
    "plan": {
      "model": "anthropic/claude-haiku-4-20250514"
    }
  }
}

8. 配置文件

8.1 配置優先級(從低到高)

優先級來源說明
1Remote config組織默認值(.well-known/opencode)
2Global config~/.config/opencode/opencode.json
3Custom configOPENCODE_CONFIG環境變數
4Project config項目根目錄opencode.json
5.opencode 目錄agents、commands、plugins
6Inline configOPENCODE_CONFIG_CONTENT環境變數
7Managed config管理員配置(最高優先級)

重要:配置文件是合併的,不是替換。不同來源的非衝突設置都會保留。

8.2 全局配置

// ~/.config/opencode/opencode.json
{
  "$schema": "https://opencode.ai/config.json",
  "model": "anthropic/claude-sonnet-4-5",
  "autoupdate": true,
  "server": {
    "port": 4096
  }
}

8.3 項目配置

// 項目根目錄 opencode.json
{
  "$schema": "https://opencode.ai/config.json",
  "model": "anthropic/claude-sonnet-4-20250514",
  "permission": {
    "edit": "ask",
    "bash": "ask"
  }
}

✅可以安全提交到 Git

8.4 TUI 配置

// ~/.config/opencode/tui.json
{
  "$schema": "https://opencode.ai/tui.json",
  "scroll_speed": 3,
  "scroll_acceleration": {
    "enabled": true
  },
  "diff_style": "auto",
  "mouse": true,
  "attention": {
    "enabled": true,
    "notifications": true,
    "sound": true,
    "volume": 0.4
  }
}

8.5 自定義配置路徑

export OPENCODE_CONFIG=/path/to/my/custom-config.json
opencode run "Hello world"

9. 自定義智能體(Agents)

9.1 內建代理

代理類型說明
Build主代理默認,所有工具可用,完整開發權限
Plan主代理只讀,禁止編輯和執行命令,適合分析和規劃
General子代理通用研究,多步任務,可並行執行
Explore子代理快速只讀代碼庫探索,不可修改文件
Scout子代理外部文檔和依賴研究,克隆依賴倉庫到緩存

9.2 隱藏系統代理

代理功能
Compaction自動壓縮長上下文
Title自動生成會話標題
Summary自動創建會話摘要

9.3 使用子代理

# 在消息中 @ 提及
@general help me search for this function
@explore 幫我找出所有與認證相關的文件
@scout 幫我查看這個庫的源代碼實現

9.4 子代理會話導航

操作快捷鍵
進入子會話Ctrl+Down(或+Down)
切換到下一個子會話Right
切換到上一個子會話Left
返回父會話Up

9.5 自定義代理(JSON 配置)

{
  "$schema": "https://opencode.ai/config.json",
  "agent": {
    "code-reviewer": {
      "description": "Review code for best practices and potential issues",
      "mode": "subagent",
      "model": "anthropic/claude-sonnet-4-20250514",
      "prompt": "You are a code reviewer. Focus on security, performance, and maintainability.",
      "permission": {
        "edit": "deny",
        "bash": "deny"
      },
      "temperature": 0.1
    }
  }
}

9.6 自定義代理(Markdown 配置)

創建文件~/.config/opencode/agents/review.md:

---
description: Reviews code for quality and best practices
mode: subagent
model: anthropic/claude-sonnet-4-20250514
temperature: 0.1
permission:
  edit: deny
  bash: 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.

文件名即代理名稱(review.md →@review)

9.7 代理配置選項

選項說明
description代理描述(必填)
modeprimary或subagent
model覆蓋默認模型
temperature0.0-1.0(0=確定性,1=創造性)
prompt自定義系統提示詞文件路徑
permission權限控制
steps最大代理步驟數(控制成本)
disabletrue禁用代理

10. 自定義命令(Custom Commands)

10.1 創建命令(Markdown)

創建.opencode/commands/test.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.

使用:/test

10.2 創建命令(JSON)

{
  "$schema": "https://opencode.ai/config.json",
  "command": {
    "test": {
      "template": "Run the full test suite with coverage report and show any failures.\nFocus on the failing tests and suggest fixes.",
      "description": "Run tests with coverage",
      "agent": "build",
      "model": "anthropic/claude-3-5-sonnet-20241022"
    }
  }
}

10.3 命令參數

使用$ARGUMENTS或$1,$2,$3:

---
description: Create a new component
---

Create a new React component named $ARGUMENTS with TypeScript support.
Include proper typing and basic structure.

使用:/component Button→$ARGUMENTS替換為Button

---
description: Create a new file with content
---

Create a file named $1 in the directory $2
with the following content: $3

使用:/create-file config.json src ‘{ “key”: “value” }’

10.4 命令嵌入 Shell 輸出

使用!command注入 Shell 命令輸出:

---
description: Review recent changes
---

Recent git commits:

!`git log --oneline -10`

Review these changes and suggest any improvements.

10.5 命令嵌入文件

使用@filename引用文件:

---
description: Review component
---

Review the component in @src/components/Button.tsx.
Check for performance issues and suggest improvements.

10.6 命令選項

選項說明
template提示詞模板(必填)
descriptionTUI 中顯示的描述
agent指定執行代理
subtasktrue強制作為子代理執行
model覆蓋默認模型

11. Agent Skills

11.1 什麼是 Skills

Skills 是可重用的知識文件(SKILL.md),包含特定領域的專業指令和流程。

11.2 使用 Skills

skill tool 自動加載 SKILL.md 文件內容到對話中

11.3 Skills 存放位置

範圍路徑
全局~/.config/opencode/skills/
項目.opencode/skills/

11.4 創建 Skill

每個 Skill 是一個目錄,包含SKILL.md:

.opencode/skills/
├── my-skill/
│   └── SKILL.md
└── another-skill/
    └── SKILL.md

12. Custom Tools

12.1 什麼是 Custom Tools

自定義工具允許你定義自己的函數,讓 LLM 調用執行任意代碼。

12.2 內建工具列表

工具說明
bash執行 Shell 命令
edit修改現有文件
write創建新文件或覆蓋現有文件
read讀取文件內容
grep正則表達式搜索文件內容
glob模式匹配查找文件
lsp語言服務器協議(定義跳轉、引用查找等)
apply_patch應用補丁文件
skill加載 SKILL.md 文件
todowrite管理待辦列表
webfetch獲取網頁內容
websearch使用 Exa AI 搜索網路
question向用戶提問

12.3 底層技術

  • grep和glob使用ripgrep(rg)- 默認遵守.gitignore規則- 可使用.ignore文件覆蓋忽略規則

13. 權限控制(Permissions)

13.1 權限級別

級別說明
allow允許所有操作,無需批准
ask執行前需要用戶批准
deny禁用該工具

13.2 權限鍵

控制的工具
readread
editwrite, edit, apply_patch
globglob
grepgrep
listlist
bashbash
tasktask
external_directory訪問項目目錄外的文件
todowritewritetodo, readtodo
webfetchwebfetch
websearchwebsearch
lsplsp
skillskill
questionquestion
doom_loop代理卡住時的恢復提示

13.3 精細控制(Glob 模式)

{
  "permission": {
    "edit": "deny",
    "bash": {
      "*": "ask",
      "git diff": "allow",
      "git log*": "allow",
      "grep *": "allow",
      "rm -rf *": "deny"
    },
    "webfetch": "deny"
  }
}

13.4 通配符控制

{
  "permission": {
    "mymcp_*": "ask"
  }
}

13.5 每個代理獨立權限

{
  "permission": {
    "edit": "deny"
  },
  "agent": {
    "build": {
      "permission": {
        "edit": "ask"
      }
    }
  }
}

13.6 Markdown 代理權限

---
description: Code review without edits
mode: subagent
permission:
  edit: deny
  bash:
    "*": ask
    "git diff": allow
    "git log*": allow
---

14. MCP 服務器

14.1 什麼是 MCP

MCP(Model Context Protocol)服務器允許集成外部工具和服務,包括數據庫訪問、API 集成、第三方服務等。

14.2 MCP 配置

{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "jira": {
      "type": "remote",
      "url": "https://jira.example.com/mcp",
      "enabled": true
    }
  }
}

14.3 遠程 MCP

組織可以通過.well-known/opencode端點提供默認 MCP 服務器,用戶可以按需啟用。

14.4 使用場景

  • 數據庫查詢- Jira / GitHub 集成- 第三方 API 調用- 內部工具集成

15. 插件系統

OpenCode 支持插件擴展功能。插件存放在.opencode/目錄下:

.opencode/
├── agents/     # 自定義代理
├── commands/   # 自定義命令
├── skills/     # 自定義技能
└── plugins/    # 插件

16. GitHub 與 GitLab 集成

16.1 Git 安全網

  • 自動快照:每次更改前自動創建 Git 快照- /undo:撤銷上次消息的所有更改- /redo:重做已撤銷的更改- /share:生成會話分享鏈接

16.2 會話分享

/share

創建當前對話的分享鏈接,複製到剪貼板。

示例:https://opencode.ai/s/4XP1fce5

16.3 Git Worktrees

OpenCode 支持 Git Worktrees 作為隔離策略,讓 AI 在獨立分支工作而不影響主分支。


17. 注意事項

17.1 ⚠️ 重要提醒

項目說明
版本清理安裝前移除 0.1.x 之前的舊版本
Git 依賴/undo 和 /redo 需要項目是 Git 倉庫
API Key 安全妥善保管 API Key,不要提交到公共倉庫
模型選擇根據任務複雜度選擇合適的模型,平衡成本和質量
權限設置生產環境建議設置bash: “ask"防止意外命令執行
上下文管理長對話使用/compact壓縮上下文以節省 token
命名衝突如果創建與 OpenCode 相關的項目,名稱中必須包含註釋說明非官方

17.2 成本優化建議

策略說明
分層模型簡單任務用便宜模型(Haiku),複雜任務用貴模型(Sonnet/Opus)
small_model配置 small_model 用於標題生成等輕量任務
temperature降低 temperature 減少不必要的多樣性輸出
steps 限制設置最大步驟數控制成本
本地模型使用 Ollama 完全免費

17.3 安全最佳實踐

實踐配置
禁止危險命令“bash”: { “rm -rf *”: “deny” }
編輯需批准“edit”: “ask”
外部目錄禁止“external_directory”: “deny”
Web 訪問控制“webfetch”: “deny"或"ask”

18. 與 Claude Code / Codex 比較

18.1 架構對比

維度Claude CodeCodexOpenCode
運行時本地終端 / 雲端 VM本地 CLI/應用/IDE(+ 雲端)本地 Client-Server
語言TypeScript/Node.jsRust(CLI)Go(TUI)+ Bun/JS(服務器)
模型鎖定僅 Claude僅 GPT-Codex75+ 提供商 + 本地
LSP 集成✅(獨有功能)
代理協調Teams 2-16 個代理多任務並行子代理
開源部分(CLI Apache 2.0)✅ MIT

18.2 基準測試

測試Claude CodeCodexOpenCode
SWE-bench ProOpus 4.6: 57.5%GPT-5-Codex: 57.0%取決於使用的模型
Terminal-Bench 2.0Sonnet 4.6: 53.0%GPT-5 Codex: 53.0%取決於使用的模型
速度(相同模型)基準相近慢 78%,但更徹底

18.3 價格對比

工具最便宜中等高端
OpenCode$0(Ollama 本地)API 費用$200/月(Black)
Claude Code$20/月(Pro)$100/月(Max 5x)$200/月(Max 20x)
Codex$0(免費/Go)$20/月(Plus)$200/月(Pro)

18.4 選擇建議

需求推薦
模型靈活性 + 零鎖定OpenCode
本地隱私OpenCode + Ollama
開源代碼可 forkOpenCode
LSP 智能代碼分析OpenCode
最快上手 + 最簡單Codex(ChatGPT 自帶)
最高代碼質量Claude Code
GitHub PR 自動創建Codex

19. 推薦工作流程

19.1 日常開發流程

1. cd /path/to/project
2. opencode                              # 啟動 TUI
3. /init                                  # 初始化項目(首次)
4. Tab → Plan                             # 切換到規劃模式
5. "幫我分析一下當前項目的架構..."          # 分析
6. Tab → Build                            # 切換到構建模式
7. "幫我添加這個功能..."                    # 執行
8. /undo                                  # 如果不滿意,撤銷
9. 調整提示詞,重試                         # 迭代
10. /share                                # 分享給團隊

19.2 代碼審查流程

1. @explore 幫我找出所有與認證相關的文件    # 快速探索
2. @code-reviewer 檢查這段代碼的質量        # 使用自定義代理
3. @general 幫我搜索這個庫的最佳實踐        # 外部研究

19.3 成本優化配置

{
  "$schema": "https://opencode.ai/config.json",
  "model": "anthropic/claude-sonnet-4-20250514",
  "small_model": "anthropic/claude-haiku-4-20250514",
  "agent": {
    "build": {
      "model": "anthropic/claude-sonnet-4-20250514",
      "temperature": 0.3
    },
    "plan": {
      "model": "anthropic/claude-haiku-4-20250514",
      "temperature": 0.1,
      "steps": 10
    },
    "code-reviewer": {
      "mode": "subagent",
      "model": "anthropic/claude-sonnet-4-20250514",
      "permission": { "edit": "deny" }
    }
  }
}

20. 快速參考速查表

20.1 安裝

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

20.2 啟動

cd /path/to/project && opencode

20.3 常用快捷鍵

快捷鍵功能
Tab切換代理(Build ↔ Plan)
Ctrl+X前導鍵(Leader Key)
Ctrl+X N新會話
Ctrl+X U撤銷
Ctrl+X R重做
Ctrl+X C壓縮會話
Ctrl+X M列出模型
Ctrl+X T列出主題
Ctrl+X L列出會話
Ctrl+X P命令面板

20.4 常用命令

命令說明
/connect添加 API Key
/init初始化項目
/new新會話
/undo撤銷
/redo重做
/compact壓縮上下文
/share分享會話

20.5 文件引用格式

@文件路徑        → 引用文件
!shell 命令      → 執行 Shell 命令
$ARGUMENTS       → 命令參數
$1, $2, $3       → 定位參數

20.6 關鍵資源

資源連結
GitHubhttps://github.com/anomalyco/opencode
官網https://opencode.ai
文檔https://opencode.ai/docs
Discordhttps://discord.gg/opencode
X.comhttps://x.com/opencode
安裝指南https://opencode.ai/docs#install
配置指南https://opencode.ai/docs/config
代理文檔https://opencode.ai/docs/agents
命令文檔https://opencode.ai/docs/commands
工具文檔https://opencode.ai/docs/tools
TUI 文檔https://opencode.ai/docs/tui
影片教程https://www.youtube.com/watch?v=__bcJHoTE08

本文檔基於 Rick Hau 的 OpenCode 教學影片(2026-06-05)及官方文檔編制。分析時間:2026-06-09 08:52 HK版本:v1.0