Kituwa Network · Our other sites
Kituwa Learn Kituwa Learn
Progress
0/7
Module 01 · Open-Source AI Coding Agent

Master OpenCode CLI (v2.4)

Everything you need to run OpenCode like a power user—from first session and MCP toggling to scheduled & event-driven automations, Code Mode, background subagents, and hardened multi-agent workflows.

Verified against v2.4.3 7 Visual Chapters 5 Infographics · 4 TUI Captures No Login · Local Progress
OpenCode v2.4 TUI overview showing MCP servers, automations, Code Mode, and background subagents
Chapter 01 · Foundations

Quickstart, V2 Architecture & Sessions

Install OpenCode v2, understand the shared background service, connect any LLM provider, and control sessions like Git branches.

1. Install & Verify (v2.4+)

OpenCode is MIT-licensed and provider-agnostic. Pick your package manager—the curl installer also exposes an opencode2 alias if you still have a 1.x binary installed.

bash · Install & Upgrade
# macOS / Linux (recommended)
curl -fsSL https://opencode.ai/v2/install | bash

# Homebrew or npm
brew install anomalyco/tap/opencode-v2
npm install -g @opencode/cli

# Verify binary & upgrade later
opencode --version
opencode upgrade --method npm   # specify curl | npm | pnpm | bun | brew if needed
Infographic 01 · OpenCode V2 Shared Service Topology
OpenCode v2.4 shared background service connecting TUI, Desktop, Web, Mobile, and CI clients to LLM providers, Git workspace, and MCP pool
Unlike V1, OpenCode V2 runs one shared background service (opencode serve --service) that owns sessions, permissions, MCP connections, and automations across all your terminals and apps. Use --standalone in CI for an isolated private process.

2. Connect Models (5 Ways to Run)

Free Models $0

Work out of the box without an account (e.g., DeepSeek V4.1 Flash Free, Big Pickle, Nemotron Lightning). Run /models inside the TUI to pick one.

Existing Plans OAuth

Run /connect to link ChatGPT Plus/Pro, GitHub Copilot, or Claude Pro/Max (via Claude Agent).

API Keys & OpenCode Go Multi-Model

Add OpenRouter, Anthropic, OpenAI, Gemini, or OpenCode Go ($10/mo). Keys also auto-load from env vars and project .env.

Local Models Private

Auto-discovers local Ollama, LM Studio, and vLLM endpoints on your machine.

bash · Auth & Model Discovery
opencode auth login                 # Interactive provider setup
opencode auth login -p openrouter   # Jump straight to a provider
opencode models                     # List exact provider/model strings
opencode -m anthropic/claude-sonnet-4-5#high   # Launch with model + reasoning variant

3. Starting, Resuming & Managing Sessions

Every interactive CLI feature has a scripted twin. Launch the TUI in your project root, or fire one-shot prompts with opencode run.

bash · Essential Session Commands
opencode                     # Open interactive TUI in current directory
opencode ~/code/my-app       # Open TUI targeting a specific project folder
opencode -c                  # Continue the most recent session
opencode -s <session-id>     # Resume a specific session ID
opencode run "Explain auth"  # Non-interactive scripted mode (streams to stdout)
opencode service stop        # Stop the shared V2 background daemon
TUI Capture 01 · Interactive Session, Diff Status & Leader Chords
Simulated OpenCode v2.4 TUI showing build agent edits, test execution, right-side session status panel, and prompt bar
Inside the TUI, press Tab to toggle between Build (edits files) and Plan (read-only planning). Use Ctrl+T to cycle model reasoning effort (low/medium/high).
ActionShortcut / CommandWhat It Does
New Session/new or Ctrl+X NStarts a clean session (alias: /clear)
Switch Session/sessions or Ctrl+X LPick & resume any previous session (aliases: /resume, /continue)
Undo / Redo/undo (Ctrl+X U) · /redo (Ctrl+X R)Reverts/restores the last turn AND its Git filesystem snapshot
Fork / Timeline/fork · /timeline (Ctrl+X G)Jump back to any message or branch into a parallel conversation
Compact Context/compact or Ctrl+X CSummarizes older turns into a checkpoint to reclaim context window
Queue Follow-UpCtrl+X EnterQueues your next prompt while the agent is busy (Alt+Enter = newline)
Command PaletteCtrl+PFuzzy-search every command, agent, model, and shortcut
Chapter 02 · Speed & Repeatability

Built-In & Custom Slash Commands

Master every built-in / command, then turn repeatable prompts + live shell output into instant one-word slash workflows.

1. Built-In Slash Command Reference

CommandKeybind / AliasPurpose
/init—Scans your repo and creates/updates AGENTS.md via guided questions
/new/clear · Ctrl+X NStarts a brand-new session
/sessions/resume · Ctrl+X LLists and switches between saved sessions
/compact/summarize · Ctrl+X CCompacts conversation history into a token-saving checkpoint
/undo / /redoCtrl+X U · Ctrl+X RRolls back or replays last prompt + file changes (requires Git/snapshots)
/diff—Opens interactive diff viewer for modified files
/modelsCtrl+X MSwitches active provider/model for the current session
/connect—Interactive wizard to add a provider API key or OAuth login
/agents—Switches active primary agent (build, plan, or custom)
/mcps—Live manager to connect, disconnect, or authenticate MCP servers
/automation—Opens scheduled & event-driven automations manager (v2.4+)
/thinking—Shows or hides reasoning blocks (use Ctrl+T to change effort)
/details—Toggles verbose tool execution inputs/outputs
/editorCtrl+X EComposes a long prompt inside your $EDITOR (vim, nano, code)
/exportCtrl+X XExports current session transcript to Markdown in $EDITOR
/themesCtrl+X TSwitches TUI color theme
/help / /exit/quit, /q · Ctrl+X QDisplays shortcuts dialog or exits the TUI cleanly

2. Custom Slash Commands (Markdown & Shell Interpolation)

Drop any .md file into .opencode/commands/ (project) or ~/.config/opencode/commands/ (global). Subfolders become namespaced commands—for example, commands/team/review.md becomes /team/review. Edits hot-reload automatically.

TUI Capture 02 · Custom /review-diff Command with !`shell` Interpolation
Side by side view of .opencode/commands/review-diff.md definition and live TUI execution injecting git diff output
Wrap shell commands in !`...` to execute them before the prompt is sent and inject stdout directly into the prompt. Bind a safer agent: plan and stronger model in frontmatter.
Argument Placeholders
  • $ARGUMENTS — full raw string typed after the command
  • $1, $2, … — positional args (quotes group spaces, e.g. /check src/auth "missing tests")
  • If no placeholder is present, extra text is appended after a blank line.
Security Note on !`...` Important

Shell interpolations run in your shell before the agent's permission flow evaluates the turn. Never pass untrusted user input into a !`...` block, and only install command files from sources you trust.

.opencode/commands/check.md · Positional Arguments + JSON Alternative
---
description: Inspect a specific path with a custom audit focus
agent: plan
model: anthropic/claude-sonnet-4-5#high
---
Inspect `$1`. Focus strictly on: $2.
Git status context:
!`git status -s`

# Usage in TUI:
# /check src/payments "idempotency and race conditions"
Chapter 03 · External Tools

MCP Servers: Install, Load & Unload

Connect GitHub, browsers, docs indexes, databases, or your own scripts via Model Context Protocol—without bloating your context window.

Infographic 02 · MCP Server Lifecycle & V2 Schema Rules
Four-step MCP server lifecycle showing Install, Verify, Live TUI Toggle via /mcps, and Permanent Unload with disabled true plus five V2 schema rules
OpenCode V2 pools MCP connections inside the shared service. Every MCP exposes Tools (callable functions), Resources (readable docs), and Prompts (auto-surfaced as /server:prompt slash commands).

1. Installing MCP Servers (CLI One-Liners)

Use opencode mcp add to avoid hand-editing paths. Omit --global to register in the current project's opencode.jsonc; add --global to save in ~/.config/opencode/opencode.jsonc.

bash · Install Remote (HTTP/OAuth) & Local (stdio) MCPs
# 1. Add a remote HTTP / OAuth MCP server (e.g. Context7 or Sentry)
opencode mcp add context7 --url https://mcp.context7.com/mcp --global
opencode mcp add sentry   --url https://mcp.sentry.dev/mcp

# 2. Authenticate OAuth servers (PKCE flow; tokens stored OUTSIDE your repo config!)
opencode mcp auth sentry
opencode mcp logout sentry

# 3. Add a local stdio MCP server with env vars (note the -- separator)
opencode mcp add playwright --global -- bunx @playwright/mcp
opencode mcp add repolens --env REPOLENS_ROOT="$PWD" -- "$PWD/.venv/bin/python" "$PWD/src/server.py"

# 4. Verify connection health & diagnose auth/HTTP issues
opencode mcp list
opencode mcp debug sentry

2. V2 Manual Configuration (opencode.jsonc)

V2 Breaking Changes vs V1 & Cursor: Entries MUST live under mcp.servers (not top-level mcp or mcpServers). Use command as a single array, environment (not env), disabled: true (not enabled: false), and "oauth": false when using a Bearer PAT instead of OAuth.
opencode.jsonc · Complete V2 MCP Example
{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "timeout": { "startup": 45000 },
    "servers": {
      "github": {
        "type": "remote",
        "url": "https://api.githubcopilot.com/mcp/",
        "oauth": false,
        "headers": {
          "Authorization": "Bearer {env:GITHUB_PAT}",
          "X-MCP-Toolsets": "repos,pull_requests,issues"
        }
      },
      "playwright": {
        "type": "local",
        "command": ["bunx", "@playwright/mcp"],
        "environment": { "PLAYWRIGHT_HEADLESS": "true" },
        "disabled": true   // Configured, but unloaded until you need it
      }
    }
  }
}

3. Loading & Unloading MCPs (Runtime vs Permanent)

Every connected MCP registers its tool metadata. Keep your sessions lean using three unload tiers:

Live Session Toggle Instant

Type /mcps inside the TUI to connect, disconnect, or re-authenticate any server on the fly. Does not modify your config file.

Permanent Unload Config

Set "disabled": true on a server inside opencode.jsonc. It stays configured for later but won't start automatically.

Per-Agent Gating Best Practice

Deny heavy MCP tools globally in permissions and allow them only on a dedicated agent (e.g., browser-qa) so coding turns stay fast.

TUI Capture 03 · /mcps Live Connect, Disconnect & OAuth Panel
OpenCode TUI /mcps modal showing connected context7 and github servers and disabled playwright server
Tip: For huge servers like GitHub MCP, also pass server-side filters (X-MCP-Toolsets) so only the tools you actually use are registered.
Chapter 04 · Autonomous Workflows (New in v2.4)

Automations: Scheduled, Event-Driven & Slash Triggers

Let OpenCode wake itself on timers, cron schedules, or real-time MCP push events—or trigger instant workflows via /automation and slash commands.

Infographic 03 · OpenCode v2.4 Automations Engine
Flowchart of OpenCode Automations showing 4 triggers (timer, interval, cron, MCP event), 3 actions (prompt, Code Mode script, shell command), and 3 destinations (current session, existing session, new subagent)
Shipped in v2.4.0 and expanded with a cross-server Desktop sidebar in v2.4.3: any combination of Trigger + Action + Destination runs on the shared background service.

1. How to Create & Manage Automations

You don't need to memorize complex YAML—just describe what you want in natural language (the agent invokes its built-in automation_* tools) or type /automation to open the TUI manager.

TUI Capture 04 · /automation Management Dashboard
OpenCode v2.4.3 /automation panel showing nightly-tests cron shell job, pr-triage MCP event job, and paused dep-digest interval job
Pause, resume, inspect exit codes, or delete jobs inside /automation (TUI) or the Automations sidebar in OpenCode Desktop (v2.4.3).
Shell Action Approval Model Safety

A fixed shell command asks for your permission once at creation time. Every subsequent run executes automatically and logs its exit code and stdout—audit the command carefully before approving.

MCP Push Events (Beta) Event-Driven

Follows the MCP push-delivery spec with argument validation, heartbeats, and automatic reconnects. Oversized payloads are safely skipped without killing the automation loop.

2. Practical Automation Recipes (Copy & Paste into TUI)

OpenCode TUI Prompts · Cron, Interval, MCP Event & Kill Switch
# Recipe A — Nightly Test Suite (Cron + Fixed Shell + Isolated Subagent)
Create a cron automation at "0 2 * * *" that runs the shell command
"npm test" in a fresh subagent. Only summarize failures into a report.

# Recipe B — Real-Time PR Triage (MCP Push Event + Code Mode Script)
Create an automation triggered by the github MCP pull_request event.
Use a Code Mode script to inspect changed files and flag missing migrations
in a dedicated new subagent.

# Recipe C — One-Off Follow-Up Reminder (Timer + Prompt)
In 45 minutes, check `kubectl get pods -n learn` in this session and alert me
if any pod restarted.

# Manage or Disable Globally:
/automation                       # View, pause, resume, delete in TUI
# In opencode.jsonc to switch automations completely off:
{ "automations": false }
Automations vs Slash Commands: Use Custom Slash Commands (/deploy-check) when you want on-demand one-word triggers with !`shell` context. Use Automations (/automation) when OpenCode should wake itself on a clock or an external MCP event while you do something else.
Chapter 05 · Power Features

Code Mode, Background Subagents & Git Worktrees

Slash latency with sandboxed JavaScript tool composition, run parallel agents asynchronously, and isolate overlapping edits with Git worktrees.

Infographic 04 · Code Mode & Concurrent Subagent Execution
Comparison of traditional one-by-one LLM tool loop versus OpenCode Code Mode single JS script, alongside parent session delegating to concurrent background subagents and Git worktrees
Code Mode (@opencode/codemode) is enabled by default for MCP servers. Since v2.3.0, subagents also execute asynchronously in the background by default.

1. Code Mode: Why 1 Script Beats 10 Tool Calls

Normally, chaining 6 MCP queries takes 6 full LLM round-trips and dumps giant JSON blobs into your context window. OpenCode V2 exposes connected MCP servers and OpenAPI specs as callable functions inside a restricted JS interpreter via the execute tool. The agent writes one small script, filters and joins results locally, and returns only the clean answer.

JavaScript · What OpenCode Executes Under the Hood in Code Mode
// Single LLM turn instead of 12 sequential tool calls:
const issues = await github.listIssues({ state: "open", labels: "bug" });
const recent = issues.filter(i => i.comments === 0).slice(0, 5);
const details = await Promise.all(recent.map(i => github.getIssue({ number: i.number })));
return details.map(d => ({ number: d.number, title: d.title, author: d.user.login }));

2. Built-In & Custom Agents (Background by Default)

Type @explore ... or ask your primary agent to delegate. Subagents launch in a child session with fresh context, return immediately so you can keep working, and notify the parent when idle (waiting automatically if their own background shells are still running).

Built-In AgentModeRole & Default Safety
buildprimaryDefault coding agent. Full tool access; asks before reading .env or external paths.
planprimaryArchitecture & planning. File edits denied (except plan files); explores safely before coding.
generalsubagentMulti-step research & implementation in a child session (cannot spawn nested subagents).
exploresubagentFast read-only codebase & web search (read, glob, grep, webfetch, websearch).
.opencode/agents/reviewer.md · Custom Read-Only Security Reviewer
---
description: Audits PRs and diffs for security flaws and missing tests
mode: subagent
model: anthropic/claude-sonnet-4-5#high
permissions:
  - action: edit
    resource: "*"
    effect: deny
  - action: shell
    resource: "git *"
    effect: allow
---
Review code strictly for auth bypasses, injection vectors, secret leaks, and untested edge cases.
Never modify files; output concrete line-referenced findings.

# Invoke anytime in TUI:
# @reviewer audit the new webhook handler in src/billing/

3. Git Worktrees: Safe Parallel Coding

Independent sessions share the same filesystem unless isolated. OpenCode V2 integrates directly with Git worktrees so parallel agents never step on each other's edits.

bash & TUI · Isolated Worktree Sessions
# Launch a scripted task inside a fresh Git worktree automatically
opencode run -w "Refactor billing webhooks and run full test suite"

# Or inside the TUI, ask OpenCode (it knows its own V2 API!):
> Create a new git worktree for feat/oauth-pkce and move this session into it.
Chapter 06 · Governance & Reusability

Skills, Rules (AGENTS.md) & V2 Permissions

Separate soft behavioral instructions from hard permission guardrails, and package deep playbooks as zero-bloat Skills.

Infographic 05 · Config Merge Hierarchy & Last-Rule-Wins Permissions
Config layer stack from defaults to global, repo root, and local .opencode overrides alongside ordered V2 permissions showing last matching rule wins
Rule of thumb: put how the agent should think in AGENTS.md, put what it is allowed to do in opencode.jsonc, and put terminal preferences in ~/.config/opencode/cli.json (replaces V1's tui.json).

1. Ordered V2 Permissions Array

In V2, permissions are an ordered list of { action, resource, effect } rules where the last matching rule wins. Put broad wildcards first and targeted exceptions below. Actions include shell, edit (covers write/edit/patch), read, glob, grep, subagent, skill, webfetch, websearch, and external_directory.

~/.config/opencode/opencode.jsonc · Verify with `opencode debug config`
{
  "$schema": "https://opencode.ai/config.json",
  "default_agent": "build",
  "permissions": [
    { "action": "read",     "resource": "**/.env*",    "effect": "ask"   },
    { "action": "shell",    "resource": "rm -rf *",    "effect": "deny"  },
    { "action": "shell",    "resource": "git push *",  "effect": "ask"   },
    { "action": "skill",    "resource": "*",           "effect": "allow" },
    { "action": "skill",    "resource": "internal-*",  "effect": "deny"  }
  ]
}

2. Skills: Progressive Disclosure Playbooks

Unlike AGENTS.md (always loaded into every prompt), Skills only advertise their tiny id, name, and description. OpenCode loads the full Markdown body + up to 10 supporting file paths only when relevant—or when you type /skill-id directly in the TUI!

Discovery Precedence (Low → High)
  • Built-in skills
  • .claude/skills & .agents/skills (global & project compat)
  • ~/.config/opencode/skills (global)
  • .opencode/skills (project root down to cwd)
  • Explicit skills local paths or HTTP catalogs in opencode.jsonc
Useful Skill Frontmatter Flags
  • description — required if you want the model to auto-discover it
  • slash: false — hide from the TUI / catalog
  • metadata.opencode/autoinvoke: false — manual /id only
.opencode/skills/git-release/SKILL.md · Directory Skill with Scripts
---
name: Git Release
description: Prepare release notes, semver bumps, and GitHub releases
metadata:
  opencode/slash: "true"
---
## Workflow
1. Read `references/release-policy.md`.
2. Summarize merged commits since the previous tag.
3. Propose the semver bump and wait for explicit user approval.
4. Run `scripts/changelog.ts` only after approval.
Chapter 07 · Production & Extensibility

V2 Plugins, Headless Server & Production Ops

Extend OpenCode with hot-reloading V2 plugins, run headless servers over Tailscale, audit costs, and grab ready-to-paste production configs.

1. V2 Plugins (Hot-Reloading & Auto-Updating)

V2 plugins use Plugin.define and can bundle server, TUI, and desktop targets inside one npm package. Version ranges like name@latest automatically check for updates on startup and every 24 hours (v2.4.0+).

bash · Install Popular V2 Plugins
# Context-aware LLM reviewer for "ask" permissions while you're away
opencode plugin add opencode-auto-permissions

# Deep web crawling & search plugins (in addition to built-in Exa websearch)
opencode plugin add opencode-tavily
opencode plugin add opencode-firecrawl

2. Headless Server, Web Pairing, Stats & Portability

Remote TUI & Web Client-Server

Run opencode serve --port 4096 with OPENCODE_SERVER_PASSWORD, attach from anywhere via opencode attach, or print a one-time web link with opencode pair.

Cost & Model Stats Auditing

Run opencode stats --models to see exact token usage and dollar spend broken down by model across sessions.

Safe Export / Import Redacted

opencode export redacts sensitive .env secrets automatically so transcripts can be shared or imported cleanly.

Built-In Media & SDK v2.4

Built-in websearch, webfetch, generate_image, async generate_video, Desktop Browser, plus @opencode/client & @opencode/sdk.

3. Interactive Copy-Ready Recipe Builder

Click a scenario to inspect and copy production-tested V2 commands and JSONC configs:

opencode.jsonc (Remote MCP with PAT)
{
  "$schema": "https://opencode.ai/config.json",
  "mcp": {
    "servers": {
      "github": {
        "type": "remote",
        "url": "https://api.githubcopilot.com/mcp/",
        "oauth": false,
        "headers": {
          "Authorization": "Bearer {env:GITHUB_PAT}",
          "X-MCP-Toolsets": "repos,pull_requests,issues"
        }
      }
    }
  }
}

4. V1 → V2 Quick Migration Checklist

AreaV1 BehaviorV2.4 Current Behavior
Terminal Settingstui.jsonMoved to single global ~/.config/opencode/cli.json
MCP Configmcp.<name> + enabledmcp.servers.<name> + disabled: true
PluginsV1 plugin hooksBreaking rewrite using Plugin.define (install via opencode plugin add)
LSP & FormattersBuilt-in LSP diagnosticsConfig keys preserved for compatibility, but V2 does not spawn LSPs—run lint/typecheck via shell
PermissionsMap style (permission)Ordered array under permissions (last matching rule wins)