OpenCode AI:终端原生 AI 代码编辑器 - Openclaw Skills

作者:互联网

2026-03-26

AI教程

什么是 OpenCode AI?

OpenCode AI 是一款专为终端环境设计的 AI 原生代码编辑器。它作为图形化 IDE(如 Cursor)的 CLI 或 TUI 等效工具,允许开发人员在不离开命令行的情况下进行复杂的重构、功能实现和代码库探索。作为 Openclaw Skills 中的特色工具,它为偏好高效键盘驱动工作流的开发人员提供了无缝集成。

OpenCode AI 支持包括 GPT-4o、Claude Sonnet 和 Gemini 在内的多种 AI 模型,并提供专门用于规划和构建的代理。这确保了每次代码更改前都经过逻辑架构审查,使其成为专业软件开发的可靠解决方案。

下载入口:https://github.com/openclaw/skills/tree/main/skills/csuwl/opencode

安装与下载

1. ClawHub CLI

从源直接安装技能的最快方式。

npx clawhub@latest install opencode

2. 手动安装

将技能文件夹复制到以下位置之一

全局模式 ~/.openclaw/skills/ 工作区 /skills/

优先级:工作区 > 本地 > 内置

3. 提示词安装

将此提示词复制到 OpenClaw 即可自动安装。

请帮我使用 Clawhub 安装 opencode。如果尚未安装 Clawhub,请先安装(npm i -g clawhub)。

OpenCode AI 应用场景

  • 使用 AI 上下文跨多个文件执行复杂的重构。
  • 自动执行 GitHub PR 审查并通过 CLI 实施建议的修复。
  • 管理长时运行的代码会话,在终端重启后仍保留上下文。
  • 使用 AI 驱动的探索模式探索并记录不熟悉的代码库。
  • 使用 JSON 输出模式将 AI 辅助编程集成到 CI/CD 流水线中。
OpenCode AI 工作原理
  1. 用户通过在项目目录中运行 opencode 命令来初始化会话。
  2. 开发人员选择特定的 AI 代理,例如通过斜杠命令界面使用 plan 来规划架构更改。
  3. 审查计划后,用户切换到 build 代理来执行代码生成和文件修改。
  4. OpenCode AI 与本地文件系统交互以应用编辑、运行测试或分析代码结构。
  5. 上下文通过持久会话 ID 维护,允许随着时间的推移进行迭代改进。

OpenCode AI 配置指南

要开始使用 Openclaw Skills 库中的此技能,请确保您的 PATH 包含系统实用程序。使用以下命令配置您的环境:

# 确保 sysctl 可访问
export PATH="/usr/sbin:/usr/bin:/sbin:/bin:$PATH"

# 永久添加到 shell 配置中
echo 'export PATH="/usr/sbin:/usr/bin:/sbin:/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc

# 验证安装
opencode --version

OpenCode AI 数据架构与分类体系

OpenCode AI 通过结构化的会话和模型管理系统来组织其操作:

数据组件 描述
会话 (Sessions) 存储在本地的基于 JSON 的持久历史记录,可通过唯一 ID 进行状态恢复。
代理 (Agents) 专门的逻辑模式:plan(设计)、build(代码)、explore(分析)和 general(帮助)。
MCP 服务器 模型上下文协议 (MCP) 服务器的配置,通过外部工具扩展代理能力。
元数据 (Metadata) 使用指标,包括 Token 计数、成本跟踪和模型推理努力程度。
name: opencode
description: "OpenCode AI - AI-driven code editor/IDE (CLI/TUI version of Cursor/Windsurf). Use when: (1) AI-assisted coding tasks, (2) Code refactoring with AI, (3) GitHub PR review/fixes, (4) Multi-file edits requiring context, (5) Running AI agents on codebases. NOT for: simple one-line edits (use edit tool), reading files (use read tool)."
metadata:
  {
    "openclaw": { "emoji": "??", "requires": { "bins": ["opencode"] } },
  }

OpenCode AI - AI Code Editor

OpenCode is an AI-native code editor that runs in your terminal. Think of it as Cursor or Windsurf, but as a CLI/TUI tool.

Version: 1.2.10 (Homebrew) Platform: macOS Darwin x64

Prerequisites

CRITICAL: OpenCode requires sysctl to detect system architecture. Ensure /usr/sbin is in your PATH:

export PATH="/usr/sbin:/usr/bin:/sbin:/bin:$PATH"

If missing, OpenCode will fail with:

Executable not found in $PATH: "sysctl"

Add this to ~/.zshrc permanently:

echo 'export PATH="/usr/sbin:/usr/bin:/sbin:/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc

When to Use OpenCode

? Use for:

  • Complex refactoring across multiple files
  • AI-assisted feature implementation
  • GitHub PR review and automated fixes
  • Exploring and understanding unfamiliar codebases
  • Running multi-step coding tasks with context
  • Session-based coding (continue previous work)

? Don't use for:

  • Simple one-line edits (use edit tool)
  • Reading file contents (use read tool)
  • Non-coding tasks

Core Operations (TUI Slash Commands)

When running OpenCode in TUI mode (opencode), you can use these slash commands to control the AI workflow:

/sessions - Session Management

/sessions
  • Opens session selector
  • Choose to continue an existing session
  • Create a new session (with user approval)
  • Recommended: Select existing session for current project

/agents - Agent (Mode) Control

/agents

Available agents:

  • plan - Planning mode (analyze and design)
  • build - Build mode (implement and code)
  • explore - Exploration mode (understand codebase)
  • general - General assistance

Best Practice: Always select plan first, then switch to build after approval.

/models - Model Selection

/models
  • Opens model selector
  • Filter by provider (OpenAI, Anthropic, Google, Z.AI, etc.)
  • Select preferred model for the task
  • If authentication required, follow the login link provided

Agent Workflow

Plan Agent Behavior

  • Ask OpenCode to analyze the task
  • Request a clear step-by-step plan
  • Allow OpenCode to ask clarification questions
  • Review the plan carefully
  • If plan is incomplete, ask for revision
  • Do not allow code generation in Plan mode

Build Agent Behavior

  • Switch to Build using /agents
  • Ask OpenCode to implement the approved plan
  • If OpenCode asks questions, switch back to Plan
  • Answer and confirm the plan, then switch back to Build

Plan → Build Loop

  1. Select plan agent with /agents
  2. Describe the task
  3. Review and approve the plan
  4. Switch to build agent with /agents
  5. Implement the plan
  6. Repeat until satisfied

Key Rules:

  • Never skip Plan
  • Never answer questions in Build mode (switch to Plan first)
  • Always show slash commands explicitly in output

Other Useful Commands

  • /title - Change session title
  • /summary - Generate session summary
  • /compaction - Compact conversation history

Core Commands

1. Quick Tasks (One-Shot)

# Run a single AI command on a project
opencode run "Add input validation to the login form"

# With specific directory
opencode run --dir ~/path/to/project "Refactor this code to use async/await"

# With specific model
opencode run -m openai/gpt-4o "Optimize the database queries"

# Attach files for context
opencode run -f src/auth.js -f src/database.js "Fix the authentication bug"

# Continue last session
opencode run --continue

# Continue specific session
opencode run --session abc123 --fork

2. Interactive TUI Mode

# Start TUI in current directory
opencode

# Start TUI in specific project
opencode ~/path/to/project

# Start with specific model
opencode -m anthropic/claude-sonnet-4

3. Authentication

# List configured providers
opencode auth list

# Login to a provider (e.g., OpenCode, OpenAI, Anthropic)
opencode auth login [url]

# Logout
opencode auth logout

4. Model Management

# List all available models
opencode models

# List models for specific provider
opencode models openai

# List with cost metadata
opencode models --verbose

# Refresh model cache
opencode models --refresh

5. Session Management

# List all sessions
opencode session list

# Delete a session
opencode session delete 

# Export session data
opencode export [sessionID]

# Import session from file
opencode import 

6. GitHub Integration

# Fetch and checkout a PR, then run OpenCode
opencode pr 123

# Manage GitHub agent
opencode github --help

7. MCP Servers (Model Context Protocol)

# List MCP servers
opencode mcp list

# Add an MCP server
opencode mcp add

# Authenticate with OAuth MCP server
opencode mcp auth [name]

# Debug OAuth connection
opencode mcp debug 

8. Agent Management

# List all agents
opencode agent list

# Create a new agent
opencode agent create

9. Server Mode

# Start headless server
opencode serve

# Start server and open web interface
opencode web

# Start ACP (Agent Client Protocol) server
opencode acp

10. Statistics

# Show token usage and costs
opencode stats

Key Options (Global)

Option Description
-m, --model Model to use (format: provider/model)
-c, --continue Continue last session
-s, --session Continue specific session
--fork Fork session when continuing
--agent Use specific agent
--dir Directory to run in
--format Output format: default or json
--thinking Show thinking blocks
--variant Model reasoning effort (high, max, minimal)

Common Patterns

Pattern 1: Refactor Code

opencode run "Refactor this function to be more readable and add error handling"

Pattern 2: Add Features

opencode run "Add a new API endpoint for user registration with email verification"

Pattern 3: Fix Bugs

opencode run -f error.log -f src/auth.js "Fix the authentication bug described in the error log"

Pattern 4: Review Code

opencode run "Review this code for security vulnerabilities and suggest improvements"

Pattern 5: GitHub PR Workflow

# Auto-fix a PR
opencode pr 123

Pattern 6: Continue Previous Work

# Continue last session
opencode run --continue

# Fork and continue (keeps original intact)
opencode run --continue --fork

Session-Based Work

OpenCode maintains sessions that preserve context across runs:

# Start a new session
opencode run "Implement user authentication"

# Continue it later
opencode run --continue

# Or continue a specific session
opencode run --session session-abc123

Session Lifecycle

  1. Create: Run opencode run "prompt" or opencode
  2. Continue: Use --continue or --session
  3. Fork: Use --fork to branch from a session
  4. Export: Save session data as JSON
  5. Delete: Remove old sessions

Model Selection

Format

provider/model

Examples:

  • openai/gpt-4o
  • anthropic/claude-sonnet-4
  • opencode/gpt-4o
  • google/gemini-2.5-pro

List Available Models

# All models
opencode models

# Provider-specific
opencode models openai
opencode models anthropic

Model Variants (Reasoning Effort)

Some models support reasoning effort levels:

opencode run --variant high "Solve this complex algorithm problem"
opencode run --variant max "Architect a distributed system"
opencode run --variant minimal "Quick code review"

JSON Mode (For Automation)

Use --format json for machine-readable output:

opencode run --format json "Refactor this code" | jq .

Useful for:

  • CI/CD integration
  • Scripting
  • Parsing results programmatically

Web Interface

For a GUI experience:

# Start server + open browser
opencode web

# Custom port
opencode web --port 8080

# Custom hostname
opencode web --hostname 0.0.0.0

Troubleshooting

"sysctl not found" Error

Problem: OpenCode can't find sysctl command Solution:

export PATH="/usr/sbin:/usr/bin:/sbin:/bin:$PATH"

Add to ~/.zshrc to make permanent.

"Failed to change directory" Error

Problem: OpenCode treats arguments as directory paths Solution: Use flags like --version, --help, or run explicitly:

# Wrong
opencode version

# Right
opencode --version

OpenCode hangs or freezes

Problem: Interactive TUI waiting for input Solution: Press Ctrl+C to exit, or use run mode for non-interactive tasks.

Permission issues

Problem: Can't write to files Solution: Ensure file/directory permissions allow your user to write:

chmod +w ./path/to/file

Integration with OpenClaw

Use via exec tool

# For simple tasks
bash command:"opencode run 'Add error handling'"

# For longer tasks (background)
bash background:true command:"opencode run 'Refactor entire codebase'"

Check current sessions

bash command:"opencode session list"

View stats

bash command:"opencode stats"

Tips & Best Practices

  1. Be specific: Clear prompts produce better results
  2. Use files: Attach relevant files with -f for context
  3. Iterate: Use --continue to build on previous work
  4. Fork experiments: Use --fork to try variations safely
  5. Choose models wisely: Different models excel at different tasks
  6. Monitor costs: Use opencode stats to track token usage
  7. Leverage sessions: Sessions maintain context across interactions

Comparison to Other Tools

Feature OpenCode Cursor Windsurf Claude Code
Interface CLI/TUI GUI GUI CLI
Terminal-native ? ? ? ?
Session management ? ? ? ?
GitHub PR integration ? ? ? ?
Model support Multi Multi Multi Anthropic
MCP support ? ? ? ?

Choose OpenCode when:

  • You prefer terminal workflows
  • Need CI/CD integration
  • Want headless/server mode
  • Require MCP protocol support

Documentation & Resources

  • Version: opencode --version
  • Help: opencode --help or opencode --help
  • Models: opencode models --verbose
  • Sessions: opencode session list

Last updated: 2026-02-25