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
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 / Flag | Purpose |
|---|---|
claude | Start interactive REPL |
claude "prompt" | Start REPL with an initial prompt |
claude -p "prompt" | Non-interactive print mode (execute and exit) |
claude -c | Continue most recent conversation |
claude -r <id> | Resume a specific session by ID |
claude config list|get|set|add|remove | Manage configuration values |
claude mcp list|add|remove | Manage MCP servers |
claude update | Update to latest version |
claude doctor | Diagnose installation issues |
claude login / logout | Authentication management |
--model <name> | Select model for session |
--output-format text|json|stream-json | Control output format |
--max-turns <n> | Cap agentic turns |
--max-budget-usd <n> | Set spending limit |
--allowedTools / --disallowedTools | Whitelist or blacklist specific tools |
--add-dir <path> | Add additional working directories |
--worktree | Git worktree isolation |
--remote | Cloud execution (Max subscribers) |
--agents <json> | Define custom subagents |
--system-prompt / --append-system-prompt | Custom system instructions |
--dangerously-skip-permissions | Bypass all permission prompts |
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
! — execute bash without model tokens. @file — mention files for context. #note — save to CLAUDE.md memory. /cmd — slash commands.
Slash Commands
| Command | Purpose |
|---|---|
/compact [focus] | Compress conversation history with optional focus area |
/clear | Wipe conversation completely |
/config | Open tabbed settings interface |
/context | Visualize token usage breakdown |
/cost | Show spending and usage |
/doctor | Check installation health |
/hooks | Configure pre/post tool hooks |
/init | Generate starter CLAUDE.md from codebase |
/memory | Edit CLAUDE.md memory files |
/model [name] | Switch AI model |
/permissions | View and update tool permissions |
/review | Request code review |
/rewind | Rewind conversation and/or code changes |
/sandbox | Enable sandboxed bash execution |
/status | View account and system status |
/vim | Toggle vim mode |
/agents | Manage custom AI subagents |
/plugin | Browse and manage plugins |
/output-style | Switch response style |
/effort | Set thinking effort (low/med/high/max) |
/theme | Pick color theme |
/terminal-setup | Install Shift+Enter keybinding |
/keybindings | Create 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
| Variable | Purpose |
|---|---|
ANTHROPIC_API_KEY | API authentication |
ANTHROPIC_MODEL | Default model selection |
MAX_THINKING_TOKENS | Extended thinking budget |
CLAUDE_AUTOCOMPACT_PCT_OVERRIDE | Auto-compaction threshold (%) |
CLAUDE_CODE_USE_BEDROCK=1 | Use AWS Bedrock backend |
CLAUDE_CODE_USE_VERTEX=1 | Use Google Vertex backend |
CLAUDE_CODE_SUBAGENT_MODEL | Model for subagent tasks |
CLAUDE_CODE_MAX_OUTPUT_TOKENS | Maximum output token budget |
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC | Disable telemetry/updates/errors |
CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1 | Enable 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).
{
"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
# 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 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
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
| Command | Purpose |
|---|---|
opencode | Start TUI |
opencode run [message] | Non-interactive mode |
opencode serve | Start headless HTTP server |
opencode web | Browser interface |
opencode attach [url] | Attach TUI to running server |
opencode agent create|list | Manage subagents |
opencode auth login|list|logout | Provider authentication |
opencode mcp add|list|auth|debug | Manage MCP servers |
opencode models [provider] | List available models |
opencode session list | Show sessions |
opencode stats | Usage statistics |
opencode export|import | Session import/export |
opencode github install|run | GitHub Action integration |
opencode upgrade | Self-update |
Keybindings
Leader key: Ctrl+X (configurable). All commands start with the leader.
Slash Commands
| Command | Purpose |
|---|---|
/compact | Compress conversation history |
/new | Clear session |
/sessions | Resume a previous session |
/init | Create AGENTS.md from codebase |
/models | Switch model |
/themes | Change visual theme |
/undo / /redo | Revert or reapply file changes (Git-based) |
/editor | Open external editor |
/details | Toggle tool execution details |
/thinking | Toggle reasoning visibility |
/share | Create public session link |
/export | Export session data |
Configuration
{
"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.json → OPENCODE_CONFIG env path → project opencode.json. Reads .claude files by default for compatibility.
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
| Variable | Purpose |
|---|---|
OPENCODE_CONFIG | Custom config file path |
OPENCODE_DISABLE_AUTOUPDATE | Disable auto-update |
OPENCODE_DISABLE_LSP_DOWNLOAD | Skip LSP server downloads |
OPENCODE_DISABLE_AUTOCOMPACT | Disable auto-compaction |
OPENCODE_DISABLE_CLAUDE_CODE | Stop reading .claude files |
OPENCODE_EXPERIMENTAL_LSP_TOOL | Enable goToDefinition, findReferences |
OPENCODE_ENABLE_EXA | Enable web search |
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
npm install -g @openai/codex # npm brew install --cask codex # macOS # Auth: ChatGPT OAuth (recommended) or OPENAI_API_KEY
CLI Commands
| Command | Purpose |
|---|---|
codex | Start interactive TUI |
codex exec | Non-interactive mode for CI |
codex resume | Resume previous session |
codex fork | Branch from previous session |
codex apply | Apply Codex Cloud diffs locally |
codex cloud | Browse/execute cloud tasks |
codex mcp | Manage MCP servers |
codex features | Toggle feature flags |
codex login / logout | Authentication |
codex completion | Shell 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
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
Slash Commands
| Command | Purpose |
|---|---|
/model | Switch model |
/permissions | View/update permissions |
/clear | Clear conversation |
/compact | Compress context |
/copy | Copy last response |
/status | System status |
/review | Code review |
/fork | Fork session |
/plan | Enter plan mode |
/init | Create AGENTS.md |
/agent | Manage agents |
/skills | Browse skills |
/debug | Debug mode |
/terminals | Manage 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
Read-only analysis
Ctrl+G in editor
5-10 min subtask
Run tests
Git checkpoint
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
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
# 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
# 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
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
| Scope | Claude Code | OpenCode | Codex CLI |
|---|---|---|---|
| Global | ~/.claude/CLAUDE.md | ~/.config/opencode/AGENTS.md | ~/.codex/instructions.md |
| Project | CLAUDE.md | AGENTS.md (reads CLAUDE.md) | AGENTS.md |
| Subdirectory | Child CLAUDE.md files | — | — |
| Extra rules | .claude/rules/*.md | instructions 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.
| Aspect | Claude Code | OpenCode | Codex CLI |
|---|---|---|---|
| License | Proprietary | MIT | Apache-2.0 |
| Language | TypeScript | TypeScript + Go/Zig | Rust |
| Models | Anthropic only | 75+ providers | OpenAI + Ollama/OpenRouter |
| Local models | No | Full support | Via Ollama |
| Context window | 200K (1M beta) | Provider-dependent | ~192K |
| Sandbox | Hooks-based | Shell environment | OS-level (Seatbelt / Landlock) |
| TUI quality | Simple REPL | Full TUI + themes | Full TUI |
| Desktop app | Cowork (limited) | macOS / Win / Linux | macOS |
| LSP built-in | ripgrep search | 30+ LSP servers | No |
| MCP support | Full (stdio / HTTP) | Full (stdio / HTTP, OAuth) | Experimental (stdio) |
| Instruction file | CLAUDE.md | AGENTS.md (reads CLAUDE.md) | AGENTS.md |
| Undo mechanism | Checkpoint snapshots | Git-based /undo /redo | Session fork |
| Config format | JSON | JSON / JSONC | TOML |
| GitHub stars | ~71.5K | ~104K | ~60K |
| Session sharing | No | Public links | Cloud tasks |
| Best for | Deep analysis, complex refactoring | Provider flexibility, local models | Autonomous tasks, CI/CD |
Quick Reference Cheat Sheet
Side-by-side commands for common actions across all three agents.
| Action | Claude Code | OpenCode | Codex CLI |
|---|---|---|---|
| Start interactive | claude | opencode | codex |
| Non-interactive run | claude -p "msg" | opencode run "msg" | codex exec "msg" |
| Continue session | claude -c | /sessions | codex resume |
| Plan mode | Shift+Tab → Plan | Tab → 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 changes | Esc Esc (rewind) | /undo (Git-based) | codex fork |
| External editor | Ctrl+G | /editor or ⟨leader⟩e | Ctrl+G |
| File reference | @filename | @filename | @filename |
| Shell command | !command | !command | !command |
| New line | Shift+Enter | Shift+Return | Shift+Enter |
| Cancel | Esc | Esc | Esc |
| Exit | Ctrl+D | Ctrl+D | Ctrl+C |
| Init instructions | /init → CLAUDE.md | /init → AGENTS.md | /init → AGENTS.md |
| MCP servers | claude mcp add | opencode mcp add | codex mcp |
| Headless / CI | claude -p --max-turns 5 | opencode serve | codex exec |
| Config location | ~/.claude/settings.json | ~/.config/opencode/opencode.json | ~/.codex/config.toml |
| Config format | JSON | JSON / JSONC | TOML |
| Project config | .claude/settings.json | opencode.json | .codex/config.toml |
| Update | claude update | opencode upgrade | npm update -g @openai/codex |
| Diagnostics | claude doctor | opencode stats | /debug |
| Worktree isolation | --worktree | Manual git worktree | Manual git worktree |
| GitHub Action | anthropics/claude-code-action | opencode github install | openai/codex-action |