The Definitive Guide — 2026

Terminal Coding Agents

Complete commands, shortcuts, configs, and workflow patterns for Claude Code, OpenCode, and Codex CLI — everything you need to master agentic development.

71.5K★Claude Code
104K★OpenCode
60K★Codex CLI
75+Providers
Claude Code

Claude Code Reference

Anthropic's proprietary CLI agent. Interactive REPL with deep context reasoning, file editing, shell execution, web search, and git workflows in a single agentic loop.

Installation

bash
npm install -g @anthropic-ai/claude-code
claude                   # Start interactive REPL
claude "fix linting errors"  # Start with prompt
claude login             # Authenticate

CLI Commands & Flags

Command / FlagPurpose
claudeStart interactive REPL
claude "prompt"Start REPL with an initial prompt
claude -p "prompt"Non-interactive print mode (execute and exit)
claude -cContinue most recent conversation
claude -r <id>Resume a specific session by ID
claude config list|get|set|add|removeManage configuration values
claude mcp list|add|removeManage MCP servers
claude updateUpdate to latest version
claude doctorDiagnose installation issues
claude login / logoutAuthentication management
--model <name>Select model for session
--output-format text|json|stream-jsonControl output format
--max-turns <n>Cap agentic turns
--max-budget-usd <n>Set spending limit
--allowedTools / --disallowedToolsWhitelist or blacklist specific tools
--add-dir <path>Add additional working directories
--worktreeGit worktree isolation
--remoteCloud execution (Max subscribers)
--agents <json>Define custom subagents
--system-prompt / --append-system-promptCustom system instructions
--dangerously-skip-permissionsBypass all permission prompts
Pipe Input

Pipe works naturally: cat src/utils.ts | claude -p "Find bugs". Combine with --output-format json for structured responses with cost/token metadata.

Keyboard Shortcuts

EnterSend message
Shift+EnterNew line
EscCancel / clear input
Esc EscRewind menu (undo changes)
Ctrl+CCancel operation
Ctrl+C Ctrl+CForce exit
Ctrl+DGraceful exit
Shift+TabCycle permission modes
Ctrl+GOpen external editor
Ctrl+VPaste image
Ctrl+TToggle task list
Ctrl+OToggle verbose output
Cmd+P / Alt+PModel picker
Alt+MCycle input modes
Ctrl+AStart of line
Ctrl+EEnd of line
Ctrl+WDelete word
Ctrl+UClear line
Input Prefixes

! — execute bash without model tokens. @file — mention files for context. #note — save to CLAUDE.md memory. /cmd — slash commands.

Slash Commands

CommandPurpose
/compact [focus]Compress conversation history with optional focus area
/clearWipe conversation completely
/configOpen tabbed settings interface
/contextVisualize token usage breakdown
/costShow spending and usage
/doctorCheck installation health
/hooksConfigure pre/post tool hooks
/initGenerate starter CLAUDE.md from codebase
/memoryEdit CLAUDE.md memory files
/model [name]Switch AI model
/permissionsView and update tool permissions
/reviewRequest code review
/rewindRewind conversation and/or code changes
/sandboxEnable sandboxed bash execution
/statusView account and system status
/vimToggle vim mode
/agentsManage custom AI subagents
/pluginBrowse and manage plugins
/output-styleSwitch response style
/effortSet thinking effort (low/med/high/max)
/themePick color theme
/terminal-setupInstall Shift+Enter keybinding
/keybindingsCreate keybindings.json for customization

Configuration Hierarchy

1. Enterprise Managed

/etc/claude-code/managed-settings.json — Cannot be overridden. Sets org-wide policy, model restrictions, MCP allowlists.

2. Project Local

.claude/settings.local.json — Personal, git-ignored. Your local overrides for a specific repo.

3. Project Shared

.claude/settings.json — Version-controlled. Team conventions, shared permissions, hooks.

4. User Global

~/.claude/settings.json — Your personal defaults across all projects.

Key Environment Variables

VariablePurpose
ANTHROPIC_API_KEYAPI authentication
ANTHROPIC_MODELDefault model selection
MAX_THINKING_TOKENSExtended thinking budget
CLAUDE_AUTOCOMPACT_PCT_OVERRIDEAuto-compaction threshold (%)
CLAUDE_CODE_USE_BEDROCK=1Use AWS Bedrock backend
CLAUDE_CODE_USE_VERTEX=1Use Google Vertex backend
CLAUDE_CODE_SUBAGENT_MODELModel for subagent tasks
CLAUDE_CODE_MAX_OUTPUT_TOKENSMaximum output token budget
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFICDisable telemetry/updates/errors
CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1Enable agent-to-agent communication

Permissions & Hooks

Four permission modes toggle with Shift+Tab: Default (prompts first use), AcceptEdits (auto file edits, prompt commands), Plan (read-only), BypassPermissions (auto all).

json — settings.json hooks example
{
  "hooks": {
    "PostToolUse": [{
      "matcher": "Edit|Write",
      "hooks": [{
        "type": "command",
        "command": "npx prettier --write $FILE_PATH"
      }]
    }],
    "PreToolUse": [{
      "matcher": "Bash",
      "hooks": [{
        "type": "command",
        "command": "echo 'Bash about to run: $TOOL_INPUT'"
      }]
    }]
  }
}

Hook events: PreToolUse (exit 2 blocks), PostToolUse, UserPromptSubmit, Notification, Stop, SubagentStop, SessionStart/End, PreCompact. Pattern rules: Bash(npm run *), Read(./.env*), WebFetch(domain:example.com), mcp__github__get_issue.

MCP Server Integration

bash
# Add stdio server (default transport)
claude mcp add github npx -y @modelcontextprotocol/server-github

# Add HTTP/SSE server
claude mcp add my-api --transport http https://api.example.com/mcp

# Scopes: local (default, ~/.claude.json), project (.mcp.json), user
claude mcp add --scope project db-server npx db-mcp
OpenCode

OpenCode Reference

Open-source (MIT) terminal agent by Anomaly. Client/server architecture with TypeScript+Bun backend and Go+Zig TUI. Supports 75+ model providers, 30+ LSP servers, MCP, and desktop apps.

Installation

bash
curl -fsSL https://opencode.ai/install | bash    # Install script
brew install anomalyco/tap/opencode                # macOS / Linux
npm i -g opencode-ai@latest                        # npm
scoop install opencode                             # Windows
opencode auth login                                # Configure API keys
opencode                                           # Start TUI

CLI Commands

CommandPurpose
opencodeStart TUI
opencode run [message]Non-interactive mode
opencode serveStart headless HTTP server
opencode webBrowser interface
opencode attach [url]Attach TUI to running server
opencode agent create|listManage subagents
opencode auth login|list|logoutProvider authentication
opencode mcp add|list|auth|debugManage MCP servers
opencode models [provider]List available models
opencode session listShow sessions
opencode statsUsage statistics
opencode export|importSession import/export
opencode github install|runGitHub Action integration
opencode upgradeSelf-update

Keybindings

Leader key: Ctrl+X (configurable). All commands start with the leader.

⟨leader⟩ nNew session
⟨leader⟩ lSession list
⟨leader⟩ cCompact context
⟨leader⟩ mModel list
⟨leader⟩ aAgent list
⟨leader⟩ eExternal editor
⟨leader⟩ tTheme picker
⟨leader⟩ uUndo (Git-based)
⟨leader⟩ rRedo
⟨leader⟩ bToggle sidebar
⟨leader⟩ sStatus
TabCycle Build / Plan agents
F2Cycle recent models
Ctrl+TCycle model variants
Ctrl+PCommand palette
Shift+ReturnNew line

Slash Commands

CommandPurpose
/compactCompress conversation history
/newClear session
/sessionsResume a previous session
/initCreate AGENTS.md from codebase
/modelsSwitch model
/themesChange visual theme
/undo / /redoRevert or reapply file changes (Git-based)
/editorOpen external editor
/detailsToggle tool execution details
/thinkingToggle reasoning visibility
/shareCreate public session link
/exportExport session data

Configuration

jsonc — opencode.json
{
  "model": "claude-sonnet-4-20250514",
  "small_model": "claude-haiku-4-5-20251001",
  "default_agent": "build",
  "permission": { "edit": "auto", "bash": "ask" },
  "formatter": "prettier --write",
  "lsp": {
    "typescript": { "enabled": true },
    "python": { "enabled": true }
  },
  "mcp": {
    "github": {
      "type": "local",
      "command": ["npx", "@modelcontextprotocol/server-github"],
      "env": { "GITHUB_TOKEN": "{env:GITHUB_TOKEN}" }
    }
  }
}

Config precedence: remote .well-known/opencode → global ~/.config/opencode/opencode.jsonOPENCODE_CONFIG env path → project opencode.json. Reads .claude files by default for compatibility.

LSP Integration

30+ built-in LSP servers auto-detect: TypeScript, Python/Pyright, Go/gopls, Rust/rust-analyzer, Java/jdtls, C/clangd, and more. Enable experimental LSP tools with OPENCODE_EXPERIMENTAL_LSP_TOOL=true.

Key Environment Variables

VariablePurpose
OPENCODE_CONFIGCustom config file path
OPENCODE_DISABLE_AUTOUPDATEDisable auto-update
OPENCODE_DISABLE_LSP_DOWNLOADSkip LSP server downloads
OPENCODE_DISABLE_AUTOCOMPACTDisable auto-compaction
OPENCODE_DISABLE_CLAUDE_CODEStop reading .claude files
OPENCODE_EXPERIMENTAL_LSP_TOOLEnable goToDefinition, findReferences
OPENCODE_ENABLE_EXAEnable web search
Codex CLI

Codex CLI Reference

OpenAI's open-source (Apache-2.0) terminal agent. Rewritten in Rust with OS-level sandboxing via Seatbelt (macOS) and Landlock (Linux). Sandbox-first design for autonomous execution.

Installation

bash
npm install -g @openai/codex      # npm
brew install --cask codex          # macOS
# Auth: ChatGPT OAuth (recommended) or OPENAI_API_KEY

CLI Commands

CommandPurpose
codexStart interactive TUI
codex execNon-interactive mode for CI
codex resumeResume previous session
codex forkBranch from previous session
codex applyApply Codex Cloud diffs locally
codex cloudBrowse/execute cloud tasks
codex mcpManage MCP servers
codex featuresToggle feature flags
codex login / logoutAuthentication
codex completionShell completion scripts

Approval Modes & Sandbox

Suggest untrusted

Every action requires explicit y approval. Safest for untrusted repos and unfamiliar codebases.

Auto-edit on-request

File edits happen automatically; shell commands still prompt. Best balance for active development.

Full-auto never

Everything executes without confirmation. Requires sandbox restrictions. --full-auto flag combines with workspace-write sandbox.

Sandbox: read-only

Cannot change anything on disk. Pure analysis and suggestion mode.

Sandbox: workspace-write

Write within CWD + /tmp only. Network blocked. .git/ and .codex/ remain read-only.

Sandbox: danger-full-access

No restrictions. Use with extreme caution. The --yolo flag bypasses both approvals AND sandbox.

Configuration

toml — ~/.codex/config.toml
model = "gpt-5.4"
model_reasoning_effort = "high"       # low | medium | high | xhigh
approval_policy = "on-request"       # untrusted | on-request | never
sandbox_mode = "workspace-write"    # read-only | workspace-write | danger-full-access
web_search = "cached"              # cached | live | disabled
personality = "pragmatic"          # friendly | pragmatic | none

# Named profiles loaded with codex -p ci
[profiles.ci]
approval_policy = "never"
sandbox_mode = "workspace-write"

# Custom providers
[model_providers.openrouter]
base_url = "https://openrouter.ai/api/v1"
wire_api = "responses"

Config precedence: CLI args → active profile → project .codex/config.toml → user ~/.codex/config.toml → defaults.

Keyboard Shortcuts

EnterSend message
TabQueue follow-up
Shift+EnterNew line
EscCancel request
Ctrl+CCancel / exit
Ctrl+GExternal editor
Ctrl+LClear screen
@Fuzzy file search
/Slash command popup
$Invoke skills
!Shell command prefix

Slash Commands

CommandPurpose
/modelSwitch model
/permissionsView/update permissions
/clearClear conversation
/compactCompress context
/copyCopy last response
/statusSystem status
/reviewCode review
/forkFork session
/planEnter plan mode
/initCreate AGENTS.md
/agentManage agents
/skillsBrowse skills
/debugDebug mode
/terminalsManage terminals

Agentic Workflow Patterns

Battle-tested development cycles, prompting strategies, and integration patterns that work across all terminal coding agents.

The Plan → Act → Verify Loop

📋 Plan
Read-only analysis
✍️ Edit plan
Ctrl+G in editor
⚡ Execute
5-10 min subtask
🧪 Test
Run tests
📦 Commit
Git checkpoint
🔄 Repeat

Plan Mode

Use plan mode for any task >3 files. Shift+Tab (Claude Code), Tab to Plan (OpenCode), /plan (Codex). Agent proposes approach without modifying anything.

Atomic Execution

Break features into 5-10 minute subtasks. Execute one at a time, each ending with tests + commit. Series of precise subtasks >> one vague mega-task.

Test-Driven Agents

TDD is ideal for agents because tests provide binary success metrics. Agents achieve ~94% SWE-Bench with human-written tests vs ~70% when generating their own.

Context Management

The #1 Failure Mode

Context degradation causes most agentic coding failures. Monitor with /context every 5-10 exchanges. Manually /compact at 50-70% utilization — don't wait for auto-compaction at ~95%. Start fresh sessions for distinct tasks. Avoid screenshots and verbose output that consume tokens rapidly.

Cost Optimization

Use cheaper models for subagent tasks (Haiku for research, Sonnet for coding). Disable unused MCP servers. Prefer CLI tools over MCP (more context-efficient). Average daily cost: ~$6/dev, 90% under $12.

Recovery Patterns

When stuck in loops: reset rather than persist. Double-Esc or /rewind (Claude), /undo (OpenCode), fresh session (Codex). Cross-model validation: write with one model, review with another.

Git Integration

bash — Parallel agents with worktrees
# Claude Code — built-in worktree flag
claude --worktree feature-auth

# Manual worktrees (works with any agent)
git worktree add ../feature-auth -b feature-auth
cd ../feature-auth && opencode

# GitHub Actions (Claude Code)
# uses: anthropics/claude-code-action@v1

# GitHub Actions (Codex CLI)
# uses: openai/codex-action@v1

Start from a clean git state. Commit after every coherent change — treat commits as save points. Always require human review before merging agent PRs.

Design Your Codebase for Agents

Flat & Semantic

Flat directory structures with semantic names. Minimal packages with clear boundaries. No barrel file re-exports that confuse navigation.

Strong Types

Discriminated unions, explicit types everywhere. Functions over classes, plain SQL over ORMs, explicit over implicit. "Dumb" code agents can reason about.

Fast Tooling

Fast compilation, fast tests. Crashes are tolerable but hangs are catastrophic for agent loops. Go's incremental test caching >> Python's slow startup.

Deterministic Formatters

Run formatters via hooks, not agent prompts. Agents shouldn't waste tokens on whitespace. Use PostToolUse hooks with Prettier/Black/gofmt.

Instruction Files

CLAUDE.md, AGENTS.md, and similar files are the highest-leverage configuration point. They define what the agent knows about your project before you even type a prompt.

Structure: WHAT → WHY → HOW

markdown — CLAUDE.md (or AGENTS.md) template
# Project Name

## Stack
TypeScript, React 19, Next.js 15 (App Router), Prisma, PostgreSQL.
Monorepo with pnpm workspaces: packages/ui, apps/web, apps/api.

## Build & Test
- pnpm dev          — start dev server (port 3000)
- pnpm test         — run vitest (unit + integration)
- pnpm test:e2e     — playwright e2e tests
- pnpm lint         — eslint + prettier check
- pnpm typecheck    — tsc --noEmit

## Code Conventions
- Use named exports, never default exports
- All API routes return { data, error } envelope
- State management via Zustand, NOT Redux
- Prefer server components; use "use client" sparingly
- Error boundaries at route segment level

## Architecture Decisions
- Auth: NextAuth v5 with database sessions (NOT JWT)
- Files organized by feature, not by type
- Database migrations via prisma migrate dev

## Reference Docs
- API schema: see docs/api-spec.md (read when working on API routes)
- Component library: see packages/ui/README.md (read when creating UI)
- Deployment: see docs/deploy.md (read when touching infra)

Critical Best Practices

The 150-200 Instruction Limit

Research shows frontier LLMs follow ~150-200 instructions consistently. Performance degrades uniformly as count increases — not just newer instructions, but ALL of them. Claude Code's system prompt already uses ~50. Keep your file under 60-200 lines.

✅ DO

Include only universally applicable content. Use progressive disclosure — separate reference docs with descriptions of when to read them. Craft every line carefully. Prefer pointers over embedded code.

❌ DON'T

Don't use as a linter (use hooks). Don't auto-generate blindly with /init. Don't embed code snippets that become stale. Don't provide negative-only constraints without alternatives. Don't stuff hotfixes for edge cases.

File Locations by Tool

ScopeClaude CodeOpenCodeCodex CLI
Global~/.claude/CLAUDE.md~/.config/opencode/AGENTS.md~/.codex/instructions.md
ProjectCLAUDE.mdAGENTS.md (reads CLAUDE.md)AGENTS.md
SubdirectoryChild CLAUDE.md files
Extra rules.claude/rules/*.mdinstructions in config
Custom commands.claude/commands/*.md
Skills.claude/skills/*/SKILL.md

Head-to-Head Comparison

How Claude Code, OpenCode, and Codex CLI differ across key dimensions.

AspectClaude CodeOpenCodeCodex CLI
LicenseProprietaryMITApache-2.0
LanguageTypeScriptTypeScript + Go/ZigRust
ModelsAnthropic only75+ providersOpenAI + Ollama/OpenRouter
Local modelsNoFull supportVia Ollama
Context window200K (1M beta)Provider-dependent~192K
SandboxHooks-basedShell environmentOS-level (Seatbelt / Landlock)
TUI qualitySimple REPLFull TUI + themesFull TUI
Desktop appCowork (limited)macOS / Win / LinuxmacOS
LSP built-inripgrep search30+ LSP serversNo
MCP supportFull (stdio / HTTP)Full (stdio / HTTP, OAuth)Experimental (stdio)
Instruction fileCLAUDE.mdAGENTS.md (reads CLAUDE.md)AGENTS.md
Undo mechanismCheckpoint snapshotsGit-based /undo /redoSession fork
Config formatJSONJSON / JSONCTOML
GitHub stars~71.5K~104K~60K
Session sharingNoPublic linksCloud tasks
Best forDeep analysis, complex refactoringProvider flexibility, local modelsAutonomous tasks, CI/CD

Quick Reference Cheat Sheet

Side-by-side commands for common actions across all three agents.

ActionClaude CodeOpenCodeCodex CLI
Start interactiveclaudeopencodecodex
Non-interactive runclaude -p "msg"opencode run "msg"codex exec "msg"
Continue sessionclaude -c/sessionscodex resume
Plan modeShift+Tab → PlanTab → Plan agent/plan
Switch model/model or Cmd+P/models or F2/model
Compact context/compact/compact or ⟨leader⟩c/compact
Clear session/clear/new/clear
Code review/review/review
Undo changesEsc Esc (rewind)/undo (Git-based)codex fork
External editorCtrl+G/editor or ⟨leader⟩eCtrl+G
File reference@filename@filename@filename
Shell command!command!command!command
New lineShift+EnterShift+ReturnShift+Enter
CancelEscEscEsc
ExitCtrl+DCtrl+DCtrl+C
Init instructions/init → CLAUDE.md/init → AGENTS.md/init → AGENTS.md
MCP serversclaude mcp addopencode mcp addcodex mcp
Headless / CIclaude -p --max-turns 5opencode servecodex exec
Config location~/.claude/settings.json~/.config/opencode/opencode.json~/.codex/config.toml
Config formatJSONJSON / JSONCTOML
Project config.claude/settings.jsonopencode.json.codex/config.toml
Updateclaude updateopencode upgradenpm update -g @openai/codex
Diagnosticsclaude doctoropencode stats/debug
Worktree isolation--worktreeManual git worktreeManual git worktree
GitHub Actionanthropics/claude-code-actionopencode github installopenai/codex-action