Contents

OpenCode Installation Guide: From Zero to First Run

OpenCode is a powerful AI-driven programming assistant that supports code generation, refactoring, debugging, and documentation. This article will guide you from scratch through the installation, configuration, and first run of OpenCode, ensuring you can quickly get started and unlock its full potential.

What is OpenCode?

OpenCode is an open-source AI programming assistant that integrates large language model capabilities deeply with code editors, allowing developers to complete complex programming tasks using natural language.

Core Features

  • Multi-Model Support: Free use of GLM-4.7, also supports top models like Claude, GPT-4, Gemini.
  • Terminal Native: Pure command-line interface, lightweight and efficient, no GUI required.
  • Plugin Ecosystem: Supports custom plugins to extend tool capabilities (MCP, Skills).
  • Code Awareness: Automatically understands project structure and provides context-aware suggestions.
  • Multi-Language Support: Python, JavaScript, TypeScript, Go, Rust, and other mainstream languages.

Use Cases

ScenarioExample Task
Code Generation“Create a React component implementing form validation”
Code Refactoring“Convert this code to TypeScript and add type annotations”
Bug Fixing“Why is this function erroring? Help me fix it”
Documentation“Generate full JSDoc comments for this class”
Learning New Tech“Explain how async/await works and give an example”

System Requirements

Before starting installation, ensure your system meets the following requirements:

Minimum Configuration

  • OS: macOS 10.15+, Linux (Ubuntu 20.04+), Windows 10+ (WSL2)
  • Memory: 4GB RAM (8GB+ Recommended)
  • Disk Space: 500MB available
  • Network: Stable internet connection (required for initial model download)

Software Dependencies

Depending on the installation method, you might need:

  • Homebrew Installation: Homebrew on macOS or Linux
  • NPM Installation: Node.js 16+ or Bun runtime
  • Script Installation: Bash shell and curl tool

Installation Method Guide

OpenCode offers multiple installation methods. Choose the one that suits you best:

MethodProsSuitable For
HomebrewAuto dependency management, easy updatesMac Users (Recommended)
NPM/BunGood integration with Node.js projectsFrontend Developers
Curl ScriptOne-click install, fast and simpleLinux Users
GUIStandalone app, no terminal neededNon-technical Users

Homebrew is the most popular package manager on macOS and also supports Linux.

Step 1: Install Homebrew (If not installed)

# Check if installed
brew --version

# If not installed, run the following (takes 5-10 mins)
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

Step 2: Add OpenCode Tap

# Add OpenCode official tap
brew tap anomalyco/tap

# Update Homebrew index
brew update

Step 3: Install OpenCode

brew install opencode

# Verify version after installation
opencode --version

Expected Output:

OpenCode v1.8.2 (Build 20260122)

Step 4: First Configuration

# Start OpenCode
opencode

# First run will automatically download GLM-4.7 model (approx 2GB)
# Welcome screen appears after download

Method B: Install via NPM or Bun

Suitable for developers with an existing Node.js environment.

Check Node.js Version

node --version  # Requires v16.0.0 or higher
npm --version

# Or use bun (faster)
bun --version

If Node.js is not installed, download it from Node.js Official Site.

Global Install OpenCode

# Using npm
npm install -g opencode-ai

# Or using bun (recommended, faster)
bun add -g opencode-ai

Verify Installation

# Check command availability
which opencode
# Example output: /usr/local/bin/opencode

# Check version
opencode --version

Path Issues (If command not found)

# Find npm global installation prefix
npm config get prefix

# Add path to PATH (example for ~/.zshrc)
echo 'export PATH="$(npm config get prefix)/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc

# Re-verify
opencode --version

Method C: Install via Official Script

The simplest one-click installation, suitable for Linux and macOS.

Run Install Script

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

The script will automatically:

  1. Detect OS and architecture
  2. Download corresponding binary
  3. Install to ~/.local/bin/opencode
  4. Configure environment variables

Manually Add to PATH (If needed)

# Check installation location
ls -la ~/.local/bin/opencode

# Add to PATH
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc  # Or ~/.zshrc
source ~/.bashrc

Method D: Download GUI Version

If you prefer not to use the command line, OpenCode provides a standalone desktop application.

Download Steps

  1. Visit https://opencode.ai/download
  2. Select based on OS:
    • macOS: OpenCode-macOS-arm64.dmg (Apple Silicon) or OpenCode-macOS-x64.dmg (Intel)
    • Windows: OpenCode-Setup.exe
    • Linux: OpenCode-linux-x64.AppImage
  3. Download and install following standard procedures

macOS Installation

# Open DMG file
open OpenCode-macOS-arm64.dmg

# Drag OpenCode to Applications folder
# On first open, right-click and select "Open" to bypass security prompt

Windows Installation

  1. Double click OpenCode-Setup.exe
  2. Follow the setup wizard
  3. Start OpenCode from Start Menu after installation

Verify Installation and First Run

Regardless of the installation method, you should perform the following verifications.

Basic Verification

# 1. Check version
opencode --version

# 2. View help info
opencode --help

# 3. Check config directory
ls -la ~/.config/opencode

First Launch

# Start OpenCode
opencode

# If run for the first time, you will see a welcome screen:

Expected Output:

┌──────────────────────────────────────┐
│  Welcome to OpenCode v1.8.2          │
│  Type /help to see available commands│
└──────────────────────────────────────┘

Using model: glm-4.7 (free, no API key required)

>

Test Basic Functionality

# Enter at OpenCode prompt
> Hello, can you help me write a function to reverse a string?

# You should get a reply and code similar to:

Expected Reply:

function reverseString(str) {
  return str.split('').reverse().join('');
}

// Usage:
console.log(reverseString("hello"));  // "olleh"

Verify Free Model

# Check currently used model
> /models

# Output should include glm-4.7

If everything is normal, congratulations on successfully installing OpenCode!

Configuration and Personalization

Configuration File Location

OpenCode configuration file is located at:

  • macOS/Linux: ~/.config/opencode/opencode.json
  • Windows: %APPDATA%\opencode\opencode.json

Basic Config Example

{
  "defaultModel": "glm-4.7",
  "theme": "dark",
  "autoSave": true,
  "maxTokens": 2048,
  "temperature": 0.7
}

Configuring Multiple Models

If you have other API Keys (like OpenAI, Anthropic), you can add them:

{
  "models": [
    {
      "name": "glm-4.7",
      "provider": "default",
      "free": true
    },
    {
      "name": "claude-3-5-sonnet-20241022",
      "provider": "anthropic",
      "apiKey": "YOUR_ANTHROPIC_KEY"
    }
  ],
  "defaultModel": "glm-4.7"
}

Switching Models

# Switch model in OpenCode
> /model set claude-3-5-sonnet-20241022

# View all available models
> /models

Practical Example: A Complete Workflow

Let’s demonstrate a full OpenCode workflow with a real example.

Scenario: Create a Node.js HTTP Server

# 1. Create project directory
mkdir my-server
cd my-server

# 2. Start OpenCode in project directory
opencode

# 3. Start conversation
> Create a simple Node.js HTTP server that:
> 1. Listens on port 3000
> 2. Has a /health endpoint returning JSON status
> 3. Has a /api/users endpoint with mock user data
> 4. Includes error handling
>
> Please write the code and save it to server.js

OpenCode will:

  1. Generate complete code
  2. Automatically create server.js file
  3. Add necessary error handling and comments

Generated Code (Example):

const http = require('http');

const PORT = 3000;

// Mock user data
const users = [
  { id: 1, name: 'Alice', email: '[email protected]' },
  { id: 2, name: 'Bob', email: '[email protected]' }
];

const server = http.createServer((req, res) => {
  // Health check endpoint
  if (req.url === '/health' && req.method === 'GET') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ status: 'OK', timestamp: new Date().toISOString() }));
    return;
  }

  // Users API endpoint
  if (req.url === '/api/users' && req.method === 'GET') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify({ data: users }));
    return;
  }

  // 404 for other routes
  res.writeHead(404, { 'Content-Type': 'application/json' });
  res.end(JSON.stringify({ error: 'Not Found' }));
});

server.listen(PORT, () => {
  console.log(`Server running at http://localhost:${PORT}/`);
});

// Error handling
server.on('error', (err) => {
  console.error('Server error:', err);
  process.exit(1);
});

Run and Test

# 4. Exit OpenCode (Ctrl+D or /exit)
> /exit

# 5. Run server
node server.js

# 6. Test in another terminal
curl http://localhost:3000/health
curl http://localhost:3000/api/users

Troubleshooting

Issue 1: command not found: opencode

Symptom: Command not found when running opencode.

Possible Causes:

  1. Improper installation
  2. Executable not in PATH

Solution:

# 1. Confirm installation success
which opencode

# 2. If not found, check install location
# Homebrew usually: /opt/homebrew/bin/opencode
# NPM usually: $(npm config get prefix)/bin/opencode

# 3. Manually add to PATH
echo 'export PATH="/opt/homebrew/bin:$PATH"' >> ~/.zshrc
source ~/.zshrc

# 4. Re-verify
opencode --version

Issue 2: Model Download Failed

Symptom: Stuck at “Downloading model…” on first launch.

Possible Causes:

  • Unstable network connection
  • Firewall blocking download
  • Insufficient disk space

Solution:

# 1. Check network
ping -c 3 opencode.ai

# 2. Check disk space
df -h

# 3. Download model manually
opencode --download-model glm-4.7

# 4. Use mirror (if available)
export OPENCODE_MIRROR=https://mirror.opencode.cn
opencode

Issue 3: Permission Error after NPM Install

Symptom: npm install -g opencode-ai reports EACCES error.

Solution:

# Plan A: Change npm global directory permissions
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.zshrc
source ~/.zshrc

# Re-install
npm install -g opencode-ai

# Plan B: Use npx (no global install needed)
npx opencode-ai

Issue 4: macOS “Cannot verify developer”

Symptom: macOS blocks GUI version on first open.

Solution:

# 1. Right click OpenCode app
# 2. Select "Open" instead of double click
# 3. Click "Open" in the dialog

# Or via command line:
sudo xattr -r -d com.apple.quarantine /Applications/OpenCode.app

Issue 5: Windows Antivirus False Positive

Symptom: Windows Defender or other AV blocks execution.

Solution:

  1. Open Windows Security
  2. Click “Virus & threat protection”
  3. Select “Manage settings”
  4. Add OpenCode to exclusions

Issue 6: Unresponsive after Start

Symptom: No output in terminal after running opencode.

Debugging:

# 1. Start in debug mode
opencode --debug

# 2. Check logs
cat ~/.config/opencode/logs/latest.log

# 3. Check config file
cat ~/.config/opencode/opencode.json

# 4. Reset config
mv ~/.config/opencode ~/.config/opencode.backup
opencode

Next Steps: Diving Deeper into OpenCode

After successful installation, you might want to learn about:

Claude Ecosystem

Official Resources

FAQ

Q1: Is OpenCode free?

A: Yes, OpenCode itself is open-source and free. It uses the GLM-4.7 free model by default without an API Key. If you want to use advanced models like Claude or GPT-4, you need your own API keys (paid per provider).

Q2: Difference from GitHub Copilot?

A: Main differences:

FeatureOpenCodeGitHub Copilot
CostFree + Optional Paid Models$10/month Subs
Model SelectionMulti-model SupportFixed Model
Running ModeCLI + GUIVS Code Plugin
CustomizationHigh (Plugins)Low

Q3: How to update OpenCode?

A: Depending on installation method:

# Homebrew
brew upgrade opencode

# NPM
npm update -g opencode-ai

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

# GUI: Check for updates within app

Q4: Which languages are supported?

A: OpenCode supports all major languages, including but not limited to:

  • Web: JavaScript, TypeScript, HTML, CSS, React, Vue
  • Backend: Python, Java, Go, Rust, PHP, Ruby
  • Mobile: Swift, Kotlin, Dart
  • Data: SQL, R, Julia

Q5: Can I use it in company projects?

A: Yes, but note:

  • OpenCode is open-source (check license)
  • Your code is not sent to OpenCode servers
  • If using third-party APIs (like OpenAI), verify their ToS
  • Check your company’s code security policies

Q6: How to uninstall OpenCode?

A:

# Homebrew
brew uninstall opencode

# NPM
npm uninstall -g opencode-ai

# Manual Delete
rm -rf ~/.local/bin/opencode
rm -rf ~/.config/opencode

# GUI: Follow system standard uninstall process

Summary

OpenCode is a powerful and flexible AI programming assistant beneficial for both beginners and veterans. Through this guide, you should have successfully installed and grasped the basics of OpenCode.

Key Takeaways:

  • ✅ Choose your installation method (Homebrew/NPM/Script)
  • ✅ Verify installation (opencode --version)
  • ✅ First run auto-downloads free model
  • ✅ Supports multiple models (Free + Paid)
  • ✅ Consult troubleshooting for issues
  • ✅ Explore config and plugin capabilities

Remember: OpenCode is your assistant, not a replacement. Use it to boost efficiency, but don’t rely on it completely. Keep learning!

Start your AI coding journey now!