# CLI Claude Code

> Claude Code CLI executor for Anthropic-backed reasoning, edits, reviews, and structured cross-AI handoff.

- Skill: `michelkerkmeester/cli-claude-code` (Agent Skill, multi-file: 109 files)
- Install (CLI): `npx get-skill add michelkerkmeester/cli-claude-code`
- Raw SKILL.md: https://api.skillmd.com/api/skills/michelkerkmeester/cli-claude-code/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Coding & Dev Tools
- Author: MichelKerkmeester (https://skillmd.com/u/michelkerkmeester)
- Updated: 2026-11-15
- Page: https://skillmd.com/skills/michelkerkmeester/cli-claude-code

---


# Claude Code CLI Orchestrator - Cross-AI Task Delegation

> **CRITICAL — SELF-INVOCATION PROHIBITED**
>
> This skill dispatches to the Anthropic CLI binary (`claude`). If the agent currently reading this skill is itself running inside Claude Code (detection signals listed in [`ROUTER.md`](./ROUTER.md)), the skill MUST refuse to load and return the documented error message instead of generating any `claude` invocation.
>
> A running CLI skill never dispatches itself. The cli-X skills are for **cross-AI delegation only** — never self-invocation.

Orchestrate Anthropic's Claude Code CLI from external AI assistants (OpenCode, Copilot, etc.) for tasks that benefit from deep extended thinking, surgical code editing, structured output with JSON schema validation, agent delegation, or persistent memory context.

**Core Principle**: The calling AI stays the conductor. Delegate to Claude Code for what it does best — deep reasoning, precise code editing, and structured analysis. Validate and integrate the output.

---

## 1. WHEN TO USE

### Activation Triggers

- **Deep Reasoning** — extended-thinking architectural decisions, multi-dimensional trade-off analysis, step-by-step algorithm design, root-cause analysis of subtle bugs.
- **Code Editing** — surgical diff-based edits, pattern-preserving refactors, and multi-file coordinated changes.
- **Structured Output** — `--json-schema`-validated output, machine-readable analysis, guaranteed-structure data extraction, pipeline integration.
- **Code Review** — second-AI security audits, extended-thinking architecture review, cross-AI validation, pre-merge quality gates.
- **Agent-Delegated Tasks** — specialized `.claude/agents/*.md` matches, `--permission-mode plan` read-only exploration, `@ai-council` planning, session continuity (`--continue`, `--resume`).
- **Background Processing** — long-running offloaded analysis, parallel generation/docs, batch processing with `--max-budget-usd` cost control.

### When NOT to Use

- **You ARE Claude Code already.** If your runtime is Claude Code (detection signal: `$CLAUDECODE` env var set, `claude` in process ancestry, or `~/.claude/state/<id>/lock` present), this skill refuses to load. Self-invocation creates a circular dispatch loop and burns tokens for no value. The cli-X family is exclusively for cross-AI delegation.
  - **Run the work natively instead.** Dispatch a subagent with the Agent tool. Its `model` parameter picks the model, and it takes no effort setting.
  - **Effort comes from the session.** A subagent runs at the session's effort level unless its agent definition sets `effort` (`low`, `medium`, `high`, `xhigh` or `max`), so a definition is needed only for a level different from the session's, such as `~/.claude/agents/opus-xhigh.md`. A new or edited definition loads within seconds, with no restart.
  - **Source:** the `effort` row of the frontmatter table at [code.claude.com/docs/en/sub-agents](https://code.claude.com/docs/en/sub-agents); where this summary and that page differ, the page wins.
- Simple, quick tasks where CLI overhead is not worth it.
- Tasks requiring interactive terminal UI (use `claude` directly instead).
- Context already loaded and understood by the calling AI.
- Tasks where Claude Code CLI is not installed.
- Real-time web search (Claude Code has no `--search` flag — use OpenCode).

---

## 2. SMART ROUTING

The `cli-external-orchestration` hub routes an Anthropic dispatch here: the prompt names Claude Code, the Claude CLI, extended thinking or a deep-reasoning handoff, and the hub's `cli-claude-code` mode signal selects this packet.
A session already running inside Claude Code never routes here; the self-invocation guard refuses it.
The hub [`ROUTER.md`](../ROUTER.md) names the two leaves a dispatch starts from.
Inside this packet the `ALWAYS` tier loads first: `references/cli-reference.md` for the flags, models and permission modes, and `assets/prompt-quality-card.md` for the fast-path prompt framework.
Intent-mapped references load after those, one set per intent.
Read [`ROUTER.md`](./ROUTER.md) before selecting skill-local resources; open only the matched files.

---

## 3. HOW IT WORKS

### Execution Ownership

This packet owns user-facing routing, the `command -v claude` availability probe, prompt construction and the self-invocation guard.
For research and review lineages, the shared deep-loop runtime at `../../system-deep-loop/runtime/scripts/fanout-run.cjs` owns process construction and execution, using executor kind `cli-claude-code`.
That runner accepts only the `research` and `review` loop types, so a single build or doc dispatch uses the child dispatch envelope in [providers-and-models.md](./references/providers-and-models.md) §5.
Do not add a packet-local wrapper, spawn path or command builder. Direct `claude -p` snippets below are operator reference and manual-testing examples.

### Prerequisites

```bash
# Verify installation
command -v claude || echo "Not installed. Run: npm install -g @anthropic-ai/claude-code"

# Self-invocation guard
[ -n "$CLAUDECODE" ] && echo "ERROR: Already inside a Claude Code session — do not self-invoke"

# Authentication — OAuth (Claude subscription), no API key
claude auth login        # interactive OAuth (browser flow)
# claude setup-token     # non-interactive OAuth token for CI/CD
```

**Authentication**: cli-claude-code authenticates through the Claude subscription OAuth only — `claude auth login` (interactive browser flow) or `claude setup-token` (a non-interactive OAuth token for CI/CD). It does not use an `ANTHROPIC_API_KEY`.

### Provider Auth Pre-Flight (Claude Subscription OAuth)

**MANDATORY before any first dispatch in a session.** cli-claude-code authenticates through the Claude subscription OAuth only. If neither `claude auth login` nor a `claude setup-token` session is configured on this machine, a dispatch fails with `401 Unauthorized` mid-round-trip. Run this check once per session, cache the result, and re-run it only if a dispatch fails with an auth error.

```bash
# One-shot pre-flight: capture OAuth status for routing
CLAUDE_AUTH=$(claude auth status 2>&1)
echo "$CLAUDE_AUTH" | grep -qi "authenticated\|logged in\|oauth\|setup-token" && CLAUDE_OAUTH_OK=1 || CLAUDE_OAUTH_OK=0
```

**Decision tree** (apply in order — first match wins):

| State | CLAUDE_OAUTH_OK | Action |
|-------|-----------------|--------|
| OAuth ready | 1 | Proceed with `claude -p "<prompt>" --model claude-sonnet-5-5 --output-format text` |
| Not authenticated | 0 | **ASK user** to run `claude auth login` — surface the command, do NOT dispatch. Never substitute an API key or a different model. |

**User prompt template — not authenticated:**

```
Claude Code is not authenticated on this machine. cli-claude-code uses Claude subscription OAuth only.
Run one, then confirm — the skill will retry the original dispatch:
  - `claude auth login`     (interactive browser OAuth flow)
  - `claude setup-token`    (non-interactive OAuth token for CI/CD)
```

**Error-recovery contract.** If a dispatch returns an auth error after pre-flight passed (OAuth expired or revoked), invalidate the cache, re-run `claude auth login`, and re-check before retrying. Never substitute a model the user didn't approve.

### Default Invocation (Skill Default)

**Default model + flags + agent**: `claude-sonnet-5-5` · `--output-format text` · no `--agent` (general-purpose). For deep-reasoning work, override with `--model claude-opus-5-5 --effort high`.

> **Fan-out fallback:** a deep-loop lineage that pins no model runs **Opus**. The family is named here on purpose, without a version or an effort tier, so this line does not go stale when the family ships a point release; the runner resolves the current id. A drift test keeps the two in the same family.

```bash
claude -p "<prompt>" \
  --model claude-sonnet-5-5 \
  --output-format text \
  2>&1
```

**User override** (honor explicit user phrasing verbatim):

| User says | Resolve to |
|-----------|------------|
| (nothing specified) | `--model claude-sonnet-5-5 --output-format text` |
| "Use Opus extended thinking" | `--model claude-opus-5-5 --effort high` |
| A named effort ("at xhigh", "max effort") | Append `--effort <level>`: `low`, `medium`, `high`, `xhigh` or `max` |
| "JSON schema output" | Append `--json-schema '<schema>' --output-format json` |
| "Cost-capped" | Append `--max-budget-usd 1.00` |
| "Plan mode" | Append `--permission-mode plan` (read-only) |

### Model Selection

`claude-sonnet-5-5` is the skill default. Use `claude-opus-5-5` for deep reasoning and complex architecture, paired with `--effort high`.
Use `claude-haiku-5-5` for fast, lightweight work when the caller asks, or `claude-fable-5-1` for the Fable family.
Claude Code 2.1.293 has no Fable 5.5 and rejects `claude-fable-5-5`.
Every roster model takes all five `--effort` levels: `low`, `medium`, `high`, `xhigh` and `max`.
Full roster, roles, defaults and when to use each effort → [references/providers-and-models.md](references/providers-and-models.md).

### Claude Code Agent Delegation

Route to a specialized `.claude/agents/*.md` agent with `--agent <name>` when the task matches a specialization. Full roster and invocation patterns: [agent-delegation.md](./references/agent-delegation.md).

| Task Type | Agent |
|-----------|-------|
| Codebase exploration | `context` (add `--permission-mode plan`) |
| Systematic debugging | `debug` |
| Code implementation | `code` (orchestrator-only) |
| Multi-agent coordination | `orchestrate` (add `--permission-mode plan`) |
| Single-iteration research | `deep-research` (command-owned) |
| Single-iteration review | `deep-review` (command-owned) |
| Code review / audit | `review` (add `--permission-mode plan`) |
| Multi-strategy planning | `ai-council` (add `--permission-mode plan`) |
| Documentation generation | `markdown` |
| Prompt packages | `prompt-improver` (command-owned) |
| Design values and measurement | `design` |

### Dispatch-Critical Gotchas

The full flag glossary, unique capabilities (`--json-schema`, `--max-budget-usd`, extended thinking, session `--continue`/`--resume`), essential command examples, and troubleshooting table are in the ALWAYS-loaded [cli-reference.md](./references/cli-reference.md) (§4–§13). Four gotchas that must be honored at routing time:

- **Non-interactive requires `-p` (print) mode** — `claude -p "prompt" --output-format text 2>&1`. `--output-format` defaults to `text`; use `json` (adds role/content/cost metadata) or `stream-json` only when a pipeline needs it. Capture stderr with `2>&1`.
- **`--permission-mode plan` is read-only** — use it for review/analysis/exploration (no file writes). `bypassPermissions` auto-approves all writes and **requires explicit user approval**; the default mode already allows writes.
- **No `--search` flag** — Claude Code has no live web browsing. Route web research to cli-opencode.
- **Check `$CLAUDECODE` before dispatch** — a set value means the caller is already inside Claude Code; do not dispatch the CLI, route to a native subagent instead.

---

## 4. RULES

### ✅ ALWAYS

1. Verify Claude Code CLI is installed before first invocation (`command -v claude`); check `$CLAUDECODE` for nesting.
2. Use `--permission-mode plan` for review/analysis/exploration (no file writes); `--output-format text` unless JSON is specifically needed.
3. Validate output before applying — correctness, completeness, alignment, syntax checks if code generated.
4. Capture stderr (`2>&1`) to catch errors and warnings.
5. Specify `--model` explicitly: default `claude-sonnet-5-5` unless task needs Opus (deep reasoning). Use Haiku only when explicitly requested or after adoption.
6. Route to the appropriate `--agent <name>` when the task matches a specialization (see Section 3 routing table).
7. **Pass the spec folder to the delegated agent** in the prompt: if the calling AI has an active Gate-3 spec folder, include `Spec folder: <path> (pre-approved, skip Gate 3)`. If none, ASK the user before delegating — the delegated agent cannot answer Gate 3 interactively.
8. **Prompt construction & model-craft (cli-* family precedence).** Compose every dispatch prompt via the 2-tier rule canonical in `../../sk-prompt/assets/cli-prompt-quality-card.md`:
   1. **Fast path (default).** Build from the local `assets/prompt-quality-card.md`, which delegates the framework table + CLEAR check to the canonical card.
   2. **Deep path (escalation).** Dispatch `@prompt-improver` via the Task tool (never load full `sk-prompt` inline) when any canonical **Tier 2** trigger applies — the trigger list lives in `../../sk-prompt/assets/cli-prompt-quality-card.md` under "Tier 2 — Deep path"; do not re-enumerate it here.

   Tag the framework in the Bash invocation comment and use the returned `ENHANCED_PROMPT`. Apply the CLEAR 5-question check from the canonical card via the local delegating card.
9. **Code Standards Loading (surface-aware contract)** — For code review or code generation, tell the dispatched session to:
   - Load `sk-code`.
   - Let `sk-code` emit a surface tag matching the detected stack from markers and target files.
   - Load the selected surface resources and run its verification commands.
   - Load `sk-code`'s code-review mode only for formal findings-first review output.
   - If the surface cannot be determined confidently, ask for the runtime surface and verification command set.
   - NEVER hardcode obsolete sibling code skills in dispatch prompts.
10. **Design Standards Loading (measured-reference contract)** — For design or UI work, tell the dispatched session to:
   - Load `sk-design-md-generator`.
   - Extract a measured Style Reference DESIGN.md from the live source before building UI. Include named color tokens, type scale, components, and Quick-Start CSS/Tailwind.
   - Build against those measured tokens, then run the extraction's validate step to confirm hex/section fidelity.
   - If there is no live source to measure, ask for the reference URL or exact tokens to build against.
   - NEVER treat `mcp-figma` or `sk-design-md-generator` as a taste, visual-direction, or critique authority. The extraction measures real CSS; it does not judge design.
11. **Pass the design reference manifest to the dispatched session.** When dispatching design or UI work:
   - Inline a `DESIGN_DISPATCH_MANIFEST v1` block in the prompt. The child cannot resolve skill paths, so the manifest travels in the payload, not by reference.
   - Include `styleReferenceExtracted` true, the live `source` that was measured, the measured design tokens / type scale / components the child must build against, `loadedFiles`, and `proofDemandBack`.
   - If you cannot assemble the manifest — no Style Reference extracted or no live source to measure — ASK before launching the child. Do not start a silent design dispatch.
   - The child returns the demanded proof; the parent reconciles it on the return path.
12. **Single-dispatch discipline (operator-gated, session-scoped).** By default, launch ONE cli-* dispatch at a time across the cli-* family (`cli-opencode`, `cli-claude-code`).
   - Wait for the dispatched agent's work to return and verify outputs exist. Then SIGKILL the dispatcher process and any orphan children (`pkill -9 -f "claude -p"` for this skill, plus `gtimeout` / `positional_scoring_fallback:app` cleanup).
   - Launch the next dispatch (this skill or a sibling) only after the prior one is dead and RSS has dropped.
   - In a deep-flow session (deep-review / deep-research), the operator authorizes the whole multi-iteration session at start. Iterations chain back-to-back with kill-between as the safety mechanism, not a per-iteration operator confirmation prompt.
   - Exception: when the operator explicitly authorizes N parallel dispatches, run N concurrently and still SIGKILL each as its work returns.
13. **Set `AI_SESSION_CHILD=1` in the dispatched child's env and state the exemption in the prompt.** The variable makes the waiver true; it does not make it observable.
   - The reader being waived is a model, and a model cannot see an environment variable. A child given only the variable still stops to ask the documentation-scope question, writes nothing, and exits with code zero.
   - Copy the preamble from [`shared/references/child-dispatch-preamble.md`](../shared/references/child-dispatch-preamble.md) to the top of every non-interactive prompt.
   - A session may use the per-session worktree wrapper (`.skilled/bin/worktree-session.sh`). A dispatched `claude -p` run is an orchestrated sub-session, not a new top-level session, so it must SHARE the parent's worktree rather than allocate its own.
   - The wrapper checks `AI_SESSION_CHILD` (plus a `git --git-common-dir` structural backstop) and exec's in place when set. Pattern: `AI_SESSION_CHILD=1 claude -p ...`. This is harmless when the wrapper is not in use.
   - See `.skilled/bin/README.md` → "Worktree session isolation".
   - Prepend `SYSTEM_SPEC_GATE_ENFORCE=0` next to it so a dispatched child never inherits an enforced spec-gate from the parent shell. This is belt-and-suspenders alongside the wrapper's own neutralization and the core's complete `AI_SESSION_CHILD` classify/enforce no-op. Pattern: `SYSTEM_SPEC_GATE_ENFORCE=0 AI_SESSION_CHILD=1 claude -p ...`.
14. **Agent-persona injection (attach identity, not just the task).** Every dispatch composes `{resolved agent persona + task prompt}`, never a bare task.
   - Resolve the persona from the ACTIVE runtime's agent directory per AGENTS.md §9 (`.claude/agents/<name>.md`, `.skilled/agents/<name>.md`, etc. — never hardcode one runtime).
   - Map each subtask to the RIGHT agent (`code`→code, `review`→review, `design`→design, research→`deep-research`, docs→`markdown`), not one default.
   - Claude Code has a native persona flag. Pass `claude -p --agent <name>`; the CLI resolves `.claude/agents/<name>.md` on the print path, which satisfies the rule.
   - On bare `claude -p` without `--agent`, INLINE the persona block into the payload using the in-payload pattern from `DESIGN_DISPATCH_MANIFEST` (Rule 11). The child cannot resolve agent paths by reference.
   - A persona-less dispatch runs the leaf as a generic assistant. It silently drops the agent's tool-scope, verification gates, and output contract.
   - Canonical contract: `../../sk-prompt/assets/cli-prompt-quality-card.md` "Persona Injection". Native precedent: `orchestrate.md` "Agent Loading Protocol".
   - Declare rare exceptions (native surface used, focused summary for a small-context model, pure-mechanical command) at the dispatch site.

### ⛔ NEVER

1. Use `--permission-mode bypassPermissions` without explicit user approval (auto-approves all writes/tool calls).
2. Trust output blindly for security-sensitive code (review for XSS, injection, hardcoded secrets, eval), or send sensitive data (API keys, passwords, credentials) in prompts — Claude Code transmits to Anthropic's API.
3. Hammer the API with rapid sequential calls — respect rate limits; use `--max-budget-usd` for cost control.
4. Use Claude Code for tasks where context is already loaded — direct action by the calling AI is faster.

### ⚠️ ESCALATE IF

1. Claude Code CLI is not installed and user has not acknowledged (provide `npm install -g @anthropic-ai/claude-code`).
2. Rate limits or budget caps are persistently hit (suggest increasing `--max-budget-usd` or checking quota).
3. Output conflicts with existing code patterns (present both perspectives; user decides).
4. Task requires `--permission-mode bypassPermissions` (describe risks; get explicit user approval).

### Memory Handback Protocol

When the calling AI needs to preserve session context from a Claude Code CLI delegation, run the canonical procedure:
- Extract the `MEMORY_HANDBACK` section and build structured JSON.
- Scrub secrets, then invoke `generate-context.js` via `--stdin`/`--json`/temp-file.

The continuity writer is the last step; nothing is handed to an index.
Full procedure and caveats: [`system-spec-kit/references/cli/memory-handback.md`](../../system-spec-kit/references/cli/memory-handback.md).

Claude-Code-specific Memory Epilogue template: see [assets/prompt-templates.md](./assets/prompt-templates.md) §13.

Example invocation:
```bash
printf '%s' "$JSON_PAYLOAD" | node .skilled/skills/system-spec-kit/runtime/cli/dist/continuity/generate-context.js --stdin [spec-folder]
```

---

## 5. REFERENCES

### Core References

- [cli-reference.md](./references/cli-reference.md) - Complete CLI flags, commands, models, authentication, and configuration
- [providers-and-models.md](./references/providers-and-models.md) - Anthropic model ids, the default pin and the `--effort` mapping
- [integration-patterns.md](./references/integration-patterns.md) - Cross-AI orchestration patterns (reversed: external AI conducts, Claude Code executes)
- [claude-tools.md](./references/claude-tools.md) - Unique capabilities and comparison with OpenCode
- [agent-delegation.md](./references/agent-delegation.md) - 11 agent roster, routing table, and invocation patterns

### Templates and Assets

- [prompt-quality-card.md](./assets/prompt-quality-card.md) - Fast-path prompt discipline, the framework table and CLEAR check
- [prompt-templates.md](./assets/prompt-templates.md) - Copy-paste ready prompt templates for common tasks

### Shared (cli-* family)
- [shared-smart-router.md](../../system-spec-kit/references/cli/shared-smart-router.md) - Helper-function bodies for the smart router.
- [memory-handback.md](../../system-spec-kit/references/cli/memory-handback.md) - Canonical 7-step Memory Handback procedure.

### External
- [Claude Code GitHub](https://github.com/anthropics/claude-code) - Official repository
- [Claude](https://claude.ai) - Claude subscription OAuth account (auth for cli-claude-code)
- [Claude Code Documentation](https://docs.anthropic.com/en/docs/claude-code) - Official docs

### Reference Loading Notes

- Load only references needed for current intent.
- The [`ROUTER.md`](./ROUTER.md) router is the single routing authority.
- `cli-reference.md` is ALWAYS loaded as baseline.

---

## 6. SUCCESS CRITERIA

### Task Completion

- Claude Code CLI invoked with correct flags, model, and permission mode.
- Output captured, validated, and integrated appropriately.
- No security vulnerabilities introduced from generated code.
- Rate limits and budget caps handled gracefully.
- Appropriate agent routed for specialized tasks.
- Permission mode matched to task type (plan for review, default for generation).

### Skill Quality

- All 8 numbered H2 sections present with `---` separators.
- Smart routing covers all intent signals with UNKNOWN_FALLBACK.
- Reference files provide deep-dive content without duplication.

---

## 7. INTEGRATION POINTS

### Framework Integration

This skill operates within the behavioral framework defined in [AGENTS.md](../../../../AGENTS.md).

Key integrations:
- **Gate 2**: Skill routing via `skill_advisor.py`
- **Tool Routing**: Per AGENTS.md Section 5 decision tree
- **Continuity**: Context preserved by `/speckit:save`, which writes through `generate-context.js`

**Tool roles**: Bash dispatches the CLI; Read/Glob/Grep validate output.

---

## 8. REFERENCES AND RELATED RESOURCES

The router discovers reference, asset, and script docs dynamically. The hub [`ROUTER.md`](../ROUTER.md) names the two leaves a Claude Code dispatch starts from, and the `ALWAYS` tier in [`ROUTER.md`](./ROUTER.md) names the baseline. Load task-specific resources from `references/`, templates from `assets/`, and automation from `scripts/` when present.

Related skills: `cli-codex` for sandboxed OpenAI perspective, `cli-opencode` for full OpenCode runtime dispatch, `sk-code` for code-quality contracts, `mcp-code-mode` for external MCP work, and `system-spec-kit` for packet handback.

