# Coding Agent

> Use when delegating a coding task to a CLI coding agent (Claude Code, Codex, Gemini, OpenCode, Pi) — investigations, multi-step refactors, parallel issue work, PR reviews. Direct mode for quick (<5 min) tasks; pair with long-running-task for background execution >5 min.

- Skill: `colindmurray/coding-agent` (Agent Skill)
- Install (CLI): `npx skillmds@latest add colindmurray/coding-agent`
- Raw SKILL.md: https://api.skillmd.com/api/skills/colindmurray/coding-agent/raw
- Safety review: pending (external: skill-scanner PASS, skillspector FAIL)
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: AI & ML
- Author: colindmurray (https://skillmd.com/u/colindmurray)
- Updated: 2026-09-22
- Page: https://skillmd.com/skills/colindmurray/coding-agent

---


# Coding Agent

Launch coding agents headlessly (`-p` / `exec`) for programmatic control. For tasks expected to run >5 min, route through `long-running-task` for manifests, watchdogs, and channel-aware notifications.

## Use Cases

Coding agents are powerful general-purpose assistants that excel at:

- **Investigation**: Exploring large codebases to understand architecture, find bugs, trace data flows
- **Analysis**: Deep-diving into complex systems, identifying patterns, root cause analysis
- **Documentation**: Writing specs, creating detailed action plans, generating comprehensive comments
- **Multi-step workflows**: Tasks requiring iteration, exploration, and decision-making

---

## Launching Coding Agents

### Background mode (tasks >5 min)

Use `execute_long_running_task` with `--type coding-agent`. This handles manifests,
NDJSON streaming, watchdogs, notifications, and monitoring automatically.

**Read:** `~/.openclaw/skills/long-running-task/SKILL.md` for templates.

```bash
~/.openclaw/skills/long-running-task/bin/execute_long_running_task \
  --mode heartbeat \
  --type coding-agent \
  --agent claude \
  --command "<PROMPT>" \
  --workdir "<WORKDIR>" \
  --summary "<DESCRIPTION>" \
  --session-id "<SESSION_ID>" \
  --channel <CHANNEL> \
  --target "<TARGET_ID>" \
  --permission-mode bypassPermissions  # default; use acceptEdits for sandboxed/read-edit-only
```

### Direct mode (quick tasks <5 min)

Run the agent directly and wait for the response:

```bash
# Full access (default — can run tests, installs, builds, git operations)
claude -p --dangerously-skip-permissions "<PROMPT>"
gemini -y -p "<PROMPT>"
codex -s danger-full-access --dangerously-bypass-approvals-and-sandbox exec "<PROMPT>"

# Sandboxed (only when explicitly requested — can read/edit files, no bash)
claude -p --permission-mode acceptEdits "<PROMPT>"
gemini --approval-mode auto_edit -p "<PROMPT>"
```

No manifest needed — you're blocking and will see the result immediately.

### Checking on background agents

```bash
~/.openclaw/skills/long-running-task/bin/check_task --task-id <TASK_ID>
~/.openclaw/skills/long-running-task/bin/check_task --all
```

---

## Progress Updates (Responsibility Split)

### Scripts auto-handle:
- **Task started** — notification sent within ~1 second of launch
- **Task completed** — notification sent immediately on exit with summary, duration, last output
- **Task failed** — notification sent immediately with exit code, error context
- **Task died** (OOM/crash) — notification sent within ~2 minutes by PID monitor

### AI must handle:
- **Retry decisions** — NEVER retry silently. ALWAYS notify the user before retrying.
- **Milestone updates** — Significant progress points during long tasks
- **Result interpretation** — What the task output means, what to do next

---

## Memory Safety

Coding agents use significant RAM (~1-2GB each). The task launcher **automatically blocks** new coding agents when system memory is below 1.5GB, preventing cascading OOM kills.

- Override with `--force` if you're certain there's enough headroom
- Adjust threshold: `export OPENCLAW_MIN_MEMORY_MB=2048`
- Check current usage: `check_task --all --json` (shows per-task RSS + system memory)
- On low-memory systems, run agents sequentially

---

## Supported Agents

### Claude Code

| Mode | Command | Use when |
|------|---------|----------|
| One-shot | `claude -p "prompt"` | Quick queries, no file changes |
| Full auto (recommended) | `claude -p --dangerously-skip-permissions "prompt"` | Default for headless agents: tests, installs, builds, git, system changes |
| Auto-edit (sandboxed) | `claude -p --permission-mode acceptEdits "prompt"` | Restricted: file read/edit only, no bash. Use only when explicitly requested |

### Codex CLI

| Mode | Command | Use when |
|------|---------|----------|
| Full auto (recommended) | `codex --full-auto exec "prompt"` | Safe default: sandboxed to workspace, auto-approves |
| Read-only | `codex -s read-only exec "prompt"` | Investigation only, no writes |
| Full access | `codex -s danger-full-access --dangerously-bypass-approvals-and-sandbox exec "prompt"` | System-wide changes, installs |

**Note:** Codex requires a git repository. Use `mktemp -d && git init` for scratch work.

### Gemini CLI

| Mode | Command | Use when |
|------|---------|----------|
| One-shot | `gemini -p "prompt"` | Quick queries, prompts for approval |
| Auto-edit (recommended) | `gemini --approval-mode auto_edit -p "prompt"` | Code-only tasks: auto-approves edits, blocks shell |
| Full auto | `gemini -y -p "prompt"` | Tasks needing shell commands |

### Pi Coding Agent

| Mode | Command | Use when |
|------|---------|----------|
| Restricted tools | `pi --tools read,edit -p "prompt"` | Safe: file access only, no bash |
| Full access (default) | `pi -p "prompt"` | Pi runs unrestricted by default |
| Custom provider | `pi --provider openai --model gpt-4o-mini -p "prompt"` | Use alternative models |

**Note:** Pi has no built-in permission system. For sandboxing, restrict tools with `--tools` or run in a container.

### OpenCode

| Mode | Command | Use when |
|------|---------|----------|
| Non-interactive | `opencode run "prompt"` | Auto-approves all permissions in non-interactive mode |
| YOLO mode | `opencode --dangerously-skip-permissions` | Skip all permission prompts in TUI mode |

**Note:** OpenCode uses config-based permissions (`bash: "deny"` / `"allow"` / `"ask"`) for fine-grained control.

---

## Configuration

Configure agent preferences and billing in `~/.openclaw/coding-agents.json`. The installer creates this interactively, or create it manually from the inline example below.

### Config Format

```json
{
  "agents": {
    "claude": { "enabled": true, "billing": "subscription" },
    "codex": { "enabled": true, "billing": "api_key" },
    "gemini": { "enabled": false, "billing": "api_key" }
  },
  "preference_order": ["claude", "codex"],
  "default_agent": "claude"
}
```

### Fields

| Field | Description |
|-------|-------------|
| `agents.<name>.enabled` | Whether this agent is available for use |
| `agents.<name>.billing` | `api_key` (default) or `subscription` — controls how the agent authenticates |
| `preference_order` | Ordered list of agents to try (primary, backup, third choice) |
| `default_agent` | Which agent to use when none is specified |

### Billing Modes

- **`api_key`** (default) — Uses the standard API key environment variable (e.g., `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`)
- **`subscription`** — For agents that support OAuth/subscription billing. Currently only affects Claude: unsets `ANTHROPIC_API_KEY` so Claude Code falls back to OAuth subscription billing. Other agents ignore this setting for now.

The billing mode can also be overridden per-invocation with `OPENCLAW_UNSET_ANTHROPIC_KEY=true|false`.

### Environment Variables

| Variable | Default | Description |
|----------|---------|-------------|
| `OPENCLAW_CODING_AGENTS_FILE` | `~/.openclaw/coding-agents.json` | Path to the coding agent config |
| `OPENCLAW_UNSET_ANTHROPIC_KEY` | (unset) | Override Claude billing: `true` forces subscription, `false` forces API key |

---

## Headless vs Interactive Modes

Coding agents have **two execution modes** — pick by context, not by reflex:

| Mode | When | Examples |
|------|------|----------|
| **Headless** (no PTY) | Programmatic invocation, scripts, background tasks, `execute_long_running_task` | `claude -p`, `codex exec`, `gemini -p`, `opencode run` |
| **Interactive** (PTY required) | Live REPL-style sessions, TUI mode | `claude` (no `-p`), `codex` (no `exec`), `gemini`, `opencode` |

Headless mode reads from stdin/argv, writes plain (or JSON) to stdout, and exits cleanly — no terminal needed. **Allocating a PTY for headless invocations is unnecessary and can break stream-json output parsing.**

If you are using OpenClaw's bash tool and explicitly want an interactive session, pass `pty:true`. For headless invocations from any shell or runner, omit the PTY.

---

## Parallel Issue Fixing with git worktrees

```bash
# 1. Create worktrees for each issue
git worktree add -b fix/issue-78 /tmp/issue-78 main
git worktree add -b fix/issue-99 /tmp/issue-99 main

# 2. Launch agents in each
execute_long_running_task --mode heartbeat --type coding-agent --agent claude \
  --command "Fix issue #78: <description>. Commit and push." \
  --workdir /tmp/issue-78 --summary "Fix issue #78"

execute_long_running_task --mode heartbeat --type coding-agent --agent claude \
  --command "Fix issue #99: <description>. Commit and push." \
  --workdir /tmp/issue-99 --summary "Fix issue #99"

# 3. Monitor
check_task --all

# 4. Cleanup after merge
git worktree remove /tmp/issue-78
git worktree remove /tmp/issue-99
```

---

## PR Review

```bash
# Clone to temp for safe review (never review in your main working directory)
REVIEW_DIR=$(mktemp -d)
git clone <repo-url> $REVIEW_DIR
cd $REVIEW_DIR && gh pr checkout 42
codex review --base origin/main

# Or use git worktree
git worktree add /tmp/pr-42-review pr-42-branch
( cd /tmp/pr-42-review && codex review --base main )
```

---

## tmux Orchestration (Alternative)

For advanced multi-agent control with live attach/detach, use tmux instead of background mode.

| Use Case | Recommended |
|----------|-------------|
| Quick one-shot tasks | direct headless invocation (`claude -p`, `codex exec`) |
| Long-running with monitoring | `execute_long_running_task --mode heartbeat` |
| Multiple parallel agents | **tmux** |
| Session persistence | **tmux** |

```bash
SOCKET="${TMPDIR:-/tmp}/coding-agents.sock"

# Create sessions for parallel work
tmux -S "$SOCKET" new-session -d -s agent-1 -c /tmp/worktree-1
tmux -S "$SOCKET" new-session -d -s agent-2 -c /tmp/worktree-2

# Launch agents
tmux -S "$SOCKET" send-keys -t agent-1 "codex exec 'Fix issue #1'" Enter
tmux -S "$SOCKET" send-keys -t agent-2 "claude 'Fix issue #2'" Enter

# Monitor
tmux -S "$SOCKET" capture-pane -p -t agent-1 -S -100
```

---

## Sandboxing & Permission Modes

By default, agents launched via `execute_long_running_task` run with **full permissions** (`--permission-mode bypassPermissions`). This ensures agents can complete end-to-end workflows including tests, git operations, and builds without getting blocked by sandbox restrictions.

### Permission modes

`execute_long_running_task` normalizes permission handling across agents via `--permission-mode`:

| `--permission-mode` | Claude Code | Codex CLI | Gemini CLI |
|---------------------|-------------|-----------|------------|
| `bypassPermissions` (default) | `--dangerously-skip-permissions` | `-s danger-full-access --dangerously-bypass-approvals-and-sandbox` | `-y` (yolo) |
| `acceptEdits` | `--permission-mode acceptEdits` | `--full-auto` | `--approval-mode auto_edit` |

### When to use each mode

**Use `bypassPermissions` (default) for:**
- Most tasks — this is the default and recommended mode
- Running tests (`npm test`, `pytest`, `cargo test`)
- Installing dependencies (`npm install`, `pip install`)
- Building projects (`make`, `cargo build`)
- Git operations (commit, push, branch management, PR creation)
- Any end-to-end workflow (implement → test → commit → push → PR)

**Use `acceptEdits` only when explicitly requested for:**
- Restricted sandboxed execution (file read/edit only, no bash)
- Security-sensitive environments where bash access must be blocked
- When the user specifically asks for sandboxed/restricted mode

### Worktrees for isolation

Use git worktrees to isolate agents from each other and from your main working directory:

```bash
# Each agent gets its own worktree — no conflicts
git worktree add -b fix/issue-1 /tmp/issue-1 main
execute_long_running_task --type coding-agent --agent claude \
  --command "Fix issue #1" --workdir /tmp/issue-1 \
  --permission-mode bypassPermissions  # needs bash for tests
```

### Overriding per-task

```bash
# Default: full access (bypassPermissions)
execute_long_running_task --type coding-agent --agent claude --command "..."

# Explicit sandboxed mode when requested
execute_long_running_task --type coding-agent --agent claude --command "..." \
  --permission-mode acceptEdits
```

---

## Best Practices

1. **Use headless mode for programmatic invocations** — `-p` / `exec`. Reserve PTY for live interactive sessions only.
2. **Use `--workdir`** — keeps agent focused on the target project, prevents reading unrelated files
3. **Default to `bypassPermissions`** — only use `acceptEdits` when the user explicitly requests sandboxed/restricted execution
4. **Use worktrees for parallel agents** — prevents file conflicts between concurrent agents
5. **Never review PRs in your main working directory** — use temp dirs or worktrees
6. **Use `check_task` to monitor background agents** — the manifest system provides richer analysis than raw logs
7. **Let `execute_long_running_task` handle flags** — don't assemble `--dangerously-skip-permissions`, `--output-format stream-json`, etc. manually
8. **Pass `--target` / `--channel` / `--session-id` from `SESSION_CONTEXT.md`** — so completion notifications route back to the chat that launched the task

---

## Worktree Cleanup After PR Merge

When a coding agent merges a PR, clean up the worktree:

```
1. Delete the remote branch: git push origin --delete <branch-name>
2. Remove the local worktree: git worktree remove <worktree-path>
```

The heartbeat cleanup script also removes worktrees for merged PRs after 30 minutes as a safety net.

