---
name: external-coding-agents
description: "Orchestrate external AI coding agents: Claude Code, OpenAI Codex, and OpenCode. Includes installation, auth, print mode, interactive PTY mode, and best-practice delegation recipes."
version: 3.0.0
author: Hermes Agent
license: MIT
platforms: [linux, macos, windows]
metadata:
  hermes:
    tags: [Coding-Agent, Claude, Codex, OpenCode, AI-Agent, Delegation, Terminal, PTY, hermes-agent, spawning]
    related_skills: [hermes-agent]
---

# External Coding Agents

Orchestrate autonomous coding agents from Hermes. Covers Claude Code, OpenAI Codex, and OpenCode — installation, auth, one-shot print mode, interactive multi-turn PTY sessions, and safe delegation recipes.

> **When to use:** User explicitly asks to delegate coding to an external agent, wants long-running implementation, needs parallel autonomous workers, or wants feature/PR development via an agent CLI.

---

## 1. Claude Code

Claude Code is Anthropic's autonomous coding CLI. It can read files, write code, run shell commands, spawn subagents, and manage git workflows. Requires npm + Node.

### Install and Auth

```bash
npm install -g @anthropic-ai/claude-code
claude auth login              # desktop OAuth
claude auth login --console    # API key billing
claude auth login --sso        # Enterprise SSO
claude auth status             # verify
claude doctor                  # health check
```

### Mode 1: Print Mode (preferred)

One-shot, non-interactive, exits when done. No PTY needed.

```bash
# Review diff for bugs
claude -p 'Add error handling to all API calls in src/' --allowedTools 'Read,Edit' --max-turns 10

# Pipe input for analysis
cat src/auth.py | claude -p 'Review this code for bugs' --max-turns 1

# Structured JSON output with cost tracking
claude -p 'Analyze auth.py for security issues' --output-format json --max-turns 5

# Bare mode (CI/scripting) — fastest startup, skips OAuth
claude --bare -p 'Run all tests and report failures' --allowedTools 'Read,Bash' --max-turns 10
```

**Key flags:** `--max-turns N`, `--max-budget-usd N`, `--model sonnet/opus/haiku`, `--effort low/medium/high/max`, `--bare`, `--allowedTools`, `--dangerously-skip-permissions`

**Important:** Print mode skips ALL interactive dialogs, making it ideal for automation.

### Mode 2: Interactive PTY via tmux

For multi-turn iterative work. Requires tmux orchestration.

```bash
# Start tmux session
terminal(command="tmux new-session -d -s claude-work -x 140 -y 40")

# Launch Claude inside it
terminal(command="tmux send-keys -t claude-work 'cd /project && claude --dangerously-skip-permissions \"Refactor auth module to use JWT tokens\"' Enter")

# Handle trust dialog (first visit only) — Enter for "Yes"
terminal(command="sleep 4 && tmux send-keys -t claude-work Enter")

# Handle permissions dialog — Down then Enter for "Yes, I accept"
terminal(command="sleep 3 && tmux send-keys -t claude-work Down && sleep 0.3 && tmux send-keys -t claude-work Enter")

# Monitor progress
terminal(command="sleep 15 && tmux capture-pane -t claude-work -p -S -60")

# Send follow-up
terminal(command="tmux send-keys -t claude-work 'Now add unit tests for the JWT code' Enter")

# Exit
terminal(command="tmux send-keys -t claude-work '/exit' Enter")
terminal(command="tmux kill-session -t claude-work")
```

**Dialogs to handle:**
1. Workspace trust (first visit): default is "Yes" → just press Enter.
2. Permissions bypass dialog: default is "No" → must send Down then Enter.

### Monitoring Interactive Sessions

- `❯` at bottom = waiting for input (done or asking a question)
- `●` lines = actively using tools
- Check context health with `/context` — degrade starts at 70%, use `/compact` above 85%

### Key Pitfalls

- Interactive mode **requires tmux** — `pty=true` alone works but tmux gives `capture-pane` and `send-keys`
- `--dangerously-skip-permissions` dialog defaults to "No, exit" — must navigate DOWN then Enter
- Session resumption requires same directory (`--continue`)
- Background tmux sessions persist — always clean up with `tmux kill-session`
- Context degradation is real above 70% usage — monitor with `/context`

### Cost Tips

- Use `--max-turns` in print mode (prevent runaway loops)
- Use `--max-budget-usd` for cost caps (minimum ~$0.05 for cache creation)
- Use `--bare` for CI to skip plugin/hook overhead
- Use `--model haiku` for simple tasks, `--model opus` for complex multi-step work

### Resources

- Homepage: https://code.claude.com/docs/en/cli-reference
- Print mode JSON output: parse `session_id`, `num_turns`, `total_cost_usd`, `usage`
- Hooks, MCP, custom agents, and CLAUDE.md memory files all supported in interactive mode
- For full details (all flags, hooks, MCP, agents, settings), load the archived `claude-code` skill references.

---

## 2. OpenAI Codex CLI

Codex is OpenAI's autonomous coding agent. Install via npm.

### Install and Auth

```bash
npm install -g @openai/codex
export OPENAI_API_KEY="sk-..."
```

### One-shot (print mode)

```bash
codex --model o4-mini "Add retry logic to API calls and update tests"
```

Flags:
- `-q` / `--quiet` — non-interactive, returns when done
- `-a` / `--approval-mode` — `suggest` (read-only), `auto-edit` (writes allowed), `full-auto` (full auto)
- `-t` / `--model` — `o4-mini`, `gpt-4o`
- `-i` / `--image` — attach screenshots for visual context
- `--workdir` — run inside a specific directory

### Multi-turn (interactive)

```bash
codex                                  # launches interactive REPL
codex "Implement OAuth refresh flow"   # starts with a prompt
```

### Features

- `--approval-mode full-auto` for headless CI/automation (requires `OPENAI_API_KEY`)
- Built-in git awareness: auto-commits with descriptive messages
- Image inputs for UI/frontend work (`-i screenshot.png`)
- Sandbox security: runs commands in isolated containers by default
- `--notify` for desktop notifications on completion

### Pitfalls

- Quiet mode exits after the first prompt/response — for iterative tasks, use interactive mode
- Full-auto requires API key (not OAuth) and trusts the sandbox
- Git auto-commit can surprise you — review the commit before pushing
- Sandbox containers may lack your project's custom dependencies

---

## 3. OpenCode

OpenCode is a provider-agnostic, open-source AI coding agent with a TUI and CLI.

### Install and Auth

```bash
npm i -g opencode-ai@latest
# or brew install anomalyco/tap/opencode

opencode auth login
opencode auth list    # verify at least one provider
```

### One-shot: `opencode run`

```bash
opencode run 'Add retry logic to API calls and update tests'
opencode run 'Review this config for security issues' -f config.yaml -f .env.example
opencode run 'Debug why tests fail in CI' --thinking
opencode run 'Refactor auth module' --model openrouter/anthropic/claude-sonnet-4
```

Flags: `--continue` / `-c`, `--session <id>`, `--agent <name>`, `--model provider/model`, `--format json`, `--file <path>`, `--thinking`, `--variant <level>`, `--title <name>`

### Multi-turn (interactive)

```bash
terminal(command="opencode", workdir="~/project", background=true, pty=true)
# Returns session_id

# Send prompts
process(action="submit", session_id="<id>", data="Implement OAuth refresh flow and add tests")

# Monitor
process(action="poll", session_id="<id>")
process(action="log", session_id="<id>")

# Exit with Ctrl+C (NOT /exit)
process(action="write", session_id="<id>", data="\x03")
# Or: process(action="kill", session_id="<id>")
```

### Key Pitfalls

- `pty=true` is required for the TUI; `opencode run` does NOT need pty
- `/exit` is NOT a valid command — it opens an agent selector. Use `Ctrl+C` (`\x03`) or `kill`
- PATH mismatch can select the wrong binary/model config — verify with `which -a opencode`
- Enter may need to be pressed TWICE to submit in the TUI
- Avoid sharing one working directory across parallel OpenCode sessions

---

## Cross-Tool Comparison

| Dimension | Claude Code | Codex CLI | OpenCode |
|-----------|-------------|-----------|----------|
| Vendor | Anthropic | OpenAI | Open-source (provider-agnostic) |
| Auth | OAuth / API key | API key only | Multiple providers |
| One-shot mode | `-p` (print) | `-q` (quiet) | `run` |
| Auto-approve all | `--dangerously-skip-permissions` | `--approval-mode full-auto` | Interactive only |
| Image inputs | Yes (Ctrl+V) | Yes (`-i`) | Limited |
| Git auto-commit | Manual | Automatic | Manual |
| Sandbox | No | Yes (containerized) | No |
| Cost tracking | JSON output with USD | Estimate in output | `opencode stats` |
| Session resumption | `--continue`, `--resume` | N/A | `-c`, `--session` |

---

## When to Use Which

| Scenario | Recommended | Why |
|----------|-------------|-----|
| Quick one-shot fix, low risk | Claude Code `-p` or Codex `-q` | Fast, deterministic exit |
| Long multi-turn refactor | Claude Code tmux | Best interactive experience |
| Budget-sensitive / simple tasks | Claude Code `--model haiku` or OpenCode | Cheaper models |
| CI/automation pipeline | Claude Code `--bare` or Codex `--approval-mode full-auto` | No auth prompts |
| Multi-provider / don't want vendor lock-in | OpenCode | Supports OpenRouter, etc. |
| Image-heavy frontend work | Codex `-i` | Strong vision support |
| Complex reasoning, multi-step architecture | Claude Code `--model opus` | Deepest reasoning |

---

## General Safety Rules

1. **Prefer one-shot mode** for bounded tasks — cleaner, no dialog handling, structured output
2. **Use tmux for multi-turn interactive work** — the only reliable way to orchestrate TUIs
3. **Always set `workdir`** — keep the agent focused on the right project directory
4. **Set `--max-turns`** in print mode — prevents infinite loops and runaway costs
5. **Monitor tmux sessions** — `tmux capture-pane` to check progress
6. **Look for the `❯` prompt** — indicates the agent is waiting for input (done or asking)
7. **Clean up tmux sessions** — kill them when done to avoid resource leaks
8. **Report results to user** — summarize what the agent did and what changed
9. **Don't kill slow sessions blindly** — the agent may be doing multi-step work
10. **Use `--allowedTools`** to restrict capabilities to what the task actually needs

---

## Resources

- For exhaustive Claude Code flags, slash commands, keyboard shortcuts, hooks, MCP, and agents: load the archived `claude-code` skill references.
- For Codex sandbox details and advanced flags: load the archived `codex` skill.
- For OpenCode session management and stats: load the archived `opencode` skill.
